mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-29 19:25:31 +00:00
feat(sandbox): add Tier 1 container execution
This commit is contained in:
17 files changed
+1118
-82
No files matched your search
@@ -0,0 +1,148 @@
|
||||
name: Sandbox Tier 1 acceptance
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.github/workflows/sandbox-tier1.yml'
|
||||
- 'images/sandbox/**'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
- 'schemas/sandbox-*.schema.json'
|
||||
- 'scripts/sandbox/**'
|
||||
- 'tests/fixtures/sandbox/podman-install.yaml'
|
||||
- 'tests/sandbox/**'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: sandbox-tier1-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
podman:
|
||||
name: Podman ${{ matrix.distro }} (${{ matrix.arch }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 25
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- distro: ubuntu
|
||||
arch: x86_64
|
||||
runner: ubuntu-latest
|
||||
image: localhost/ecc-sandbox:ubuntu-lts
|
||||
acceptance: true
|
||||
- distro: debian
|
||||
arch: x86_64
|
||||
runner: ubuntu-latest
|
||||
image: localhost/ecc-sandbox:debian-stable
|
||||
acceptance: false
|
||||
- distro: fedora
|
||||
arch: x86_64
|
||||
runner: ubuntu-latest
|
||||
image: localhost/ecc-sandbox:fedora-latest
|
||||
acceptance: false
|
||||
- distro: ubuntu
|
||||
arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
image: localhost/ecc-sandbox:ubuntu-lts
|
||||
acceptance: false
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: Install validation dependencies and Podman
|
||||
shell: bash
|
||||
run: |
|
||||
npm ci --ignore-scripts
|
||||
sudo apt-get update
|
||||
sudo apt-get install --yes podman
|
||||
podman info
|
||||
|
||||
- name: Build pinned snapshot
|
||||
run: >-
|
||||
podman build
|
||||
--file images/sandbox/Containerfile.${{ matrix.distro }}
|
||||
--tag ${{ matrix.image }}
|
||||
images/sandbox
|
||||
|
||||
- name: Execute snapshot smoke test
|
||||
run: >-
|
||||
podman run --rm --user 1000:1000
|
||||
${{ matrix.image }}
|
||||
bash -lc 'node --version && npm --version && test "$(id -u)" = 1000'
|
||||
|
||||
- name: Run adapter contract tests
|
||||
if: matrix.acceptance
|
||||
run: node tests/sandbox/podman.test.js
|
||||
|
||||
- name: Run two real clean-user installs
|
||||
if: matrix.acceptance
|
||||
shell: bash
|
||||
env:
|
||||
ECC_SANDBOX_IMAGE: ${{ matrix.image }}
|
||||
run: |
|
||||
scripts/sandbox/ecc-sandbox probe \
|
||||
--refresh \
|
||||
--cache "$RUNNER_TEMP/ecc-sandbox-capabilities.json" \
|
||||
> "$RUNNER_TEMP/ecc-sandbox-probe.json"
|
||||
scripts/sandbox/ecc-sandbox run \
|
||||
tests/fixtures/sandbox/podman-install.yaml \
|
||||
--capabilities "$RUNNER_TEMP/ecc-sandbox-capabilities.json" \
|
||||
> "$RUNNER_TEMP/ecc-sandbox-tier1-first.json"
|
||||
scripts/sandbox/ecc-sandbox run \
|
||||
tests/fixtures/sandbox/podman-install.yaml \
|
||||
--capabilities "$RUNNER_TEMP/ecc-sandbox-capabilities.json" \
|
||||
> "$RUNNER_TEMP/ecc-sandbox-tier1-second.json"
|
||||
node - "$RUNNER_TEMP/ecc-sandbox-tier1-first.json" "$RUNNER_TEMP/ecc-sandbox-tier1-second.json" <<'NODE'
|
||||
const fs = require('fs');
|
||||
const { validateReport } = require('./scripts/sandbox/contracts');
|
||||
const reports = process.argv.slice(2).map(reportPath => (
|
||||
validateReport(JSON.parse(fs.readFileSync(reportPath, 'utf8')))
|
||||
));
|
||||
for (const report of reports) {
|
||||
if (report.backend !== 'podman' || report.execution_mode !== 'real' || report.result !== 'pass') {
|
||||
throw new Error('Tier 1 acceptance did not produce a real passing Podman report');
|
||||
}
|
||||
if (report.install_diff.method !== 'podman-layer' || !report.install_diff.complete || report.install_diff.files_added.length === 0) {
|
||||
throw new Error('Tier 1 acceptance is missing Podman layer evidence');
|
||||
}
|
||||
if (!report.notes.some(note => note.startsWith('image_id=sha256:'))) {
|
||||
throw new Error('Tier 1 acceptance did not record the inspected snapshot ID');
|
||||
}
|
||||
if (!report.install_diff.path_changes.some(filePath => filePath.endsWith('/cowsay'))) {
|
||||
throw new Error('Tier 1 acceptance did not report the installed cowsay executable');
|
||||
}
|
||||
}
|
||||
const startNote = reports[1].notes.find(note => note.startsWith('container_start_ms='));
|
||||
if (!startNote || Number(startNote.split('=')[1]) >= 1000) {
|
||||
throw new Error(`Reused snapshot start was not sub-second: ${startNote || '<missing>'}`);
|
||||
}
|
||||
NODE
|
||||
if [ -n "$(podman ps --all --quiet --filter name=ecc-sandbox-)" ]; then
|
||||
echo 'Tier 1 acceptance leaked an ECC sandbox container' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Upload normalized reports
|
||||
if: matrix.acceptance
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: sandbox-tier1-podman
|
||||
path: |
|
||||
${{ runner.temp }}/ecc-sandbox-probe.json
|
||||
${{ runner.temp }}/ecc-sandbox-tier1-first.json
|
||||
${{ runner.temp }}/ecc-sandbox-tier1-second.json
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
@@ -120,11 +120,29 @@ uses these decisions to preserve its stated safety and fidelity goals:
|
||||
private temporary scripts that SRT may read but the sandbox may not write,
|
||||
so neither repository shim lookup nor an outer `cmd.exe` parses untrusted
|
||||
manifest text before isolation starts.
|
||||
20. Tier 1 mounts the invocation directory read-only at `/workspace/source`
|
||||
and gives the test an otherwise disposable container filesystem rooted at
|
||||
`/workspace`. Reports record both the requested image reference and its
|
||||
inspected content ID so a mutable local tag cannot hide the snapshot that
|
||||
actually ran.
|
||||
21. Every Podman run verifies rootless mode immediately before image creation,
|
||||
drops all Linux capabilities, bounds processes/CPU/memory, and keeps the
|
||||
source mount read-only. First-party tests retain passwordless `sudo` only
|
||||
inside that rootless user namespace so package installers behave normally;
|
||||
untrusted Podman fallback additionally enables `no-new-privileges` and is
|
||||
explicitly reported as degraded from the preferred Microsandbox backend.
|
||||
22. Layer-diff reports include directory entries and cap every normalized list
|
||||
at 1,000 paths. Executable and top-level home dotfile classifications include
|
||||
deleted paths; `services_registered` includes only added/changed services,
|
||||
while removed services remain explicit in `files_deleted`. Malformed or
|
||||
truncated install evidence makes an `install-diff` run an error, never a
|
||||
passing partial report.
|
||||
|
||||
The plan explicitly delegates uncovered decisions to the free, lightweight,
|
||||
harness-agnostic option. Items 1, 2, 5, 8, 9, 15, 16, 17, 18, and 19 resolve
|
||||
internal contract contradictions or a missing clean-machine, write-scope, or
|
||||
evidence-integrity need and are therefore treated as that delegated authority.
|
||||
Items 20-22 record the corresponding Tier 1 containment and evidence choices.
|
||||
They are surfaced here before code and in the user handoff rather than hidden
|
||||
in implementation. Every matching code departure from a written routing rule
|
||||
must include a `DECISION:` comment referring to the applicable item above.
|
||||
@@ -0,0 +1,31 @@
|
||||
ARG BASE_IMAGE=debian:stable-slim@sha256:0d97731c59efdde181e19c4a5ec22d16e9eefcb73175598b9b7bae712c7214eb
|
||||
ARG NODE_IMAGE=node:22-bookworm-slim@sha256:6c74791e557ce11fc957704f6d4fe134a7bc8d6f5ca4403205b2966bd488f6b3
|
||||
|
||||
FROM ${NODE_IMAGE} AS node-runtime
|
||||
FROM ${BASE_IMAGE}
|
||||
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \
|
||||
bash ca-certificates curl git libatomic1 sudo \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& existing_group="$(getent group 1000 | cut -d: -f1 || true)" \
|
||||
&& if [ -n "${existing_group}" ] && [ "${existing_group}" != ecc ]; then groupmod --new-name ecc "${existing_group}"; elif [ -z "${existing_group}" ]; then groupadd --gid 1000 ecc; fi \
|
||||
&& existing_user="$(getent passwd 1000 | cut -d: -f1 || true)" \
|
||||
&& if [ -n "${existing_user}" ] && [ "${existing_user}" != ecc ]; then usermod --login ecc --home /home/ecc --move-home "${existing_user}"; elif [ -z "${existing_user}" ]; then useradd --uid 1000 --gid 1000 --create-home --shell /bin/bash ecc; fi \
|
||||
&& printf 'ecc ALL=(ALL) NOPASSWD: ALL\n' > /etc/sudoers.d/ecc \
|
||||
&& chmod 0440 /etc/sudoers.d/ecc
|
||||
|
||||
COPY --from=node-runtime /usr/local/ /usr/local/
|
||||
|
||||
RUN mkdir -p /workspace /home/ecc/.local \
|
||||
&& chown -R 1000:1000 /workspace /home/ecc
|
||||
|
||||
ENV HOME=/home/ecc
|
||||
ENV NPM_CONFIG_PREFIX=/home/ecc/.local
|
||||
ENV PATH=/home/ecc/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
|
||||
WORKDIR /workspace
|
||||
USER 1000:1000
|
||||
CMD ["sleep", "infinity"]
|
||||
|
||||
LABEL org.opencontainers.image.title="ECC sandbox Debian stable snapshot"
|
||||
@@ -0,0 +1,34 @@
|
||||
ARG BASE_IMAGE=fedora:latest@sha256:6c75d5bf57cb0fa5aa4b92c6a83c86c791644496d9ac230de7711f5b8ec3b898
|
||||
ARG NODE_IMAGE=node:22-bookworm-slim@sha256:6c74791e557ce11fc957704f6d4fe134a7bc8d6f5ca4403205b2966bd488f6b3
|
||||
|
||||
FROM ${NODE_IMAGE} AS node-runtime
|
||||
FROM ${BASE_IMAGE}
|
||||
|
||||
RUN dnf install --assumeyes \
|
||||
bash ca-certificates curl findutils git libatomic shadow-utils sudo \
|
||||
&& dnf clean all \
|
||||
&& existing_group="$(getent group 1000 | cut -d: -f1 || true)" \
|
||||
&& if [ -n "${existing_group}" ] && [ "${existing_group}" != ecc ]; then groupmod --new-name ecc "${existing_group}"; elif [ -z "${existing_group}" ]; then groupadd --gid 1000 ecc; fi \
|
||||
&& existing_user="$(getent passwd 1000 | cut -d: -f1 || true)" \
|
||||
&& if [ -n "${existing_user}" ] && [ "${existing_user}" != ecc ]; then usermod --login ecc --home /home/ecc --move-home "${existing_user}"; elif [ -z "${existing_user}" ]; then useradd --uid 1000 --gid 1000 --create-home --shell /bin/bash ecc; fi \
|
||||
&& printf 'ecc ALL=(ALL) NOPASSWD: ALL\n' > /etc/sudoers.d/ecc \
|
||||
&& chmod 0440 /etc/sudoers.d/ecc
|
||||
|
||||
COPY --from=node-runtime /usr/local/bin/node /usr/local/bin/node
|
||||
COPY --from=node-runtime /usr/local/lib/node_modules/ /usr/local/lib/node_modules/
|
||||
|
||||
RUN mkdir -p /workspace /home/ecc/.local \
|
||||
&& ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
|
||||
&& ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \
|
||||
&& ln -s ../lib/node_modules/corepack/dist/corepack.js /usr/local/bin/corepack \
|
||||
&& chown -R 1000:1000 /workspace /home/ecc
|
||||
|
||||
ENV HOME=/home/ecc
|
||||
ENV NPM_CONFIG_PREFIX=/home/ecc/.local
|
||||
ENV PATH=/home/ecc/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
|
||||
WORKDIR /workspace
|
||||
USER 1000:1000
|
||||
CMD ["sleep", "infinity"]
|
||||
|
||||
LABEL org.opencontainers.image.title="ECC sandbox Fedora latest snapshot"
|
||||
@@ -0,0 +1,31 @@
|
||||
ARG BASE_IMAGE=ubuntu:24.04@sha256:561618e2c15bf2397621dd04f96926663a3b5616c189cf7e38db7e82f5c538ea
|
||||
ARG NODE_IMAGE=node:22-bookworm-slim@sha256:6c74791e557ce11fc957704f6d4fe134a7bc8d6f5ca4403205b2966bd488f6b3
|
||||
|
||||
FROM ${NODE_IMAGE} AS node-runtime
|
||||
FROM ${BASE_IMAGE}
|
||||
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends \
|
||||
bash ca-certificates curl git libatomic1 sudo \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& existing_group="$(getent group 1000 | cut -d: -f1 || true)" \
|
||||
&& if [ -n "${existing_group}" ] && [ "${existing_group}" != ecc ]; then groupmod --new-name ecc "${existing_group}"; elif [ -z "${existing_group}" ]; then groupadd --gid 1000 ecc; fi \
|
||||
&& existing_user="$(getent passwd 1000 | cut -d: -f1 || true)" \
|
||||
&& if [ -n "${existing_user}" ] && [ "${existing_user}" != ecc ]; then usermod --login ecc --home /home/ecc --move-home "${existing_user}"; elif [ -z "${existing_user}" ]; then useradd --uid 1000 --gid 1000 --create-home --shell /bin/bash ecc; fi \
|
||||
&& printf 'ecc ALL=(ALL) NOPASSWD: ALL\n' > /etc/sudoers.d/ecc \
|
||||
&& chmod 0440 /etc/sudoers.d/ecc
|
||||
|
||||
COPY --from=node-runtime /usr/local/ /usr/local/
|
||||
|
||||
RUN mkdir -p /workspace /home/ecc/.local \
|
||||
&& chown -R 1000:1000 /workspace /home/ecc
|
||||
|
||||
ENV HOME=/home/ecc
|
||||
ENV NPM_CONFIG_PREFIX=/home/ecc/.local
|
||||
ENV PATH=/home/ecc/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
|
||||
WORKDIR /workspace
|
||||
USER 1000:1000
|
||||
CMD ["sleep", "infinity"]
|
||||
|
||||
LABEL org.opencontainers.image.title="ECC sandbox Ubuntu LTS snapshot"
|
||||
+2
-1
@@ -81,6 +81,7 @@
|
||||
"docs/zh-CN/",
|
||||
"docs/zh-TW/",
|
||||
"hooks/",
|
||||
"images/sandbox/",
|
||||
"install.ps1",
|
||||
"install.sh",
|
||||
"manifests/",
|
||||
@@ -466,7 +467,7 @@
|
||||
"security:ioc-scan": "node scripts/ci/scan-supply-chain-iocs.js",
|
||||
"security:advisory-sources": "node scripts/ci/supply-chain-advisory-sources.js",
|
||||
"test:plugin-setup-platform": "node docker/plugin-setup/run-platform-tests.js",
|
||||
"test:sandbox": "node tests/sandbox/contracts-router.test.js && node tests/sandbox/probe.test.js && node tests/sandbox/report-srt.test.js",
|
||||
"test:sandbox": "node tests/sandbox/contracts-router.test.js && node tests/sandbox/probe.test.js && node tests/sandbox/report-srt.test.js && node tests/sandbox/podman.test.js",
|
||||
"claw": "node scripts/claw.js",
|
||||
"orchestrate:status": "node scripts/orchestration-status.js",
|
||||
"orchestrate:worker": "bash scripts/orchestrate-codex-worker.sh",
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
"dotfiles_touched"
|
||||
],
|
||||
"properties": {
|
||||
"method": { "enum": ["podman-layer", "scan", "none"] },
|
||||
"method": { "enum": ["podman-layer", "docker-layer", "scan", "none"] },
|
||||
"complete": { "type": "boolean" },
|
||||
"files_added": { "$ref": "#/definitions/stringArray" },
|
||||
"files_changed": { "$ref": "#/definitions/stringArray" },
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
const {
|
||||
buildSingleReport,
|
||||
emptyInstallDiff,
|
||||
normalizeStep,
|
||||
tailOutput,
|
||||
} = require('../report');
|
||||
|
||||
const DEFAULT_IMAGE = 'localhost/ecc-sandbox:ubuntu-lts';
|
||||
const MAX_EXEC_BUFFER = 1024 * 1024;
|
||||
const MAX_DIFF_BUFFER = 16 * 1024 * 1024;
|
||||
const MAX_DIFF_ITEMS = 1_000;
|
||||
const CLEANUP_TIMEOUT_MS = 30_000;
|
||||
|
||||
function defaultRunner(executable, argv, options = {}) {
|
||||
return spawnSync(executable, argv, {
|
||||
...options,
|
||||
encoding: 'utf8',
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
maxBuffer: options.maxBuffer || MAX_EXEC_BUFFER,
|
||||
});
|
||||
}
|
||||
|
||||
function succeeded(result) {
|
||||
return !result.error && result.status === 0;
|
||||
}
|
||||
|
||||
function firstLine(value) {
|
||||
return String(value || '').trim().split(/\r?\n/, 1)[0] || null;
|
||||
}
|
||||
|
||||
function resultDetail(result) {
|
||||
return tailOutput([result.stderr, result.stdout, result.error?.message]
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
.trim(), 50, 4_000);
|
||||
}
|
||||
|
||||
function hasOpenNetwork(manifest) {
|
||||
return manifest.needs.capabilities.includes('network:*');
|
||||
}
|
||||
|
||||
function buildCreateArgs(manifest, options) {
|
||||
// DECISION: conventions items 20-21 keep the host source read-only and
|
||||
// reserve in-container sudo for first-party work inside a rootless runtime.
|
||||
const args = [
|
||||
'create',
|
||||
'--name', options.containerName,
|
||||
'--cap-drop', 'ALL',
|
||||
'--pids-limit', '256',
|
||||
'--cpus', String(manifest.resources.cpu),
|
||||
'--memory', manifest.resources.memory.toLowerCase(),
|
||||
'--tmpfs', '/tmp:rw,nosuid,nodev,exec,size=256m',
|
||||
'--volume', `${path.resolve(options.cwd)}:/workspace/source:ro`,
|
||||
'--workdir', '/workspace',
|
||||
'--user', '1000:1000',
|
||||
'--hostname', 'ecc-sandbox',
|
||||
];
|
||||
if (manifest.needs.trust === 'untrusted') {
|
||||
args.push('--security-opt', 'no-new-privileges');
|
||||
}
|
||||
if (!hasOpenNetwork(manifest)) args.push('--network', 'none');
|
||||
args.push(options.image, 'sleep', 'infinity');
|
||||
return args;
|
||||
}
|
||||
|
||||
function uniqueSorted(values) {
|
||||
return [...new Set(values)].sort();
|
||||
}
|
||||
|
||||
function bounded(values) {
|
||||
const sorted = uniqueSorted(values);
|
||||
return { values: sorted.slice(0, MAX_DIFF_ITEMS), truncated: sorted.length > MAX_DIFF_ITEMS };
|
||||
}
|
||||
|
||||
function parseContainerDiff(output, method = 'podman-layer') {
|
||||
const changes = { A: [], C: [], D: [] };
|
||||
let malformed = false;
|
||||
for (const line of String(output || '').split(/\r?\n/)) {
|
||||
if (!line.trim()) continue;
|
||||
const match = line.match(/^([ACD])\s+(.+)$/);
|
||||
if (!match || !match[2].startsWith('/') || match[2].length > 4_096) {
|
||||
malformed = true;
|
||||
continue;
|
||||
}
|
||||
changes[match[1]].push(match[2]);
|
||||
}
|
||||
|
||||
const added = bounded(changes.A);
|
||||
const changed = bounded(changes.C);
|
||||
const deleted = bounded(changes.D);
|
||||
const touched = uniqueSorted([...changes.A, ...changes.C, ...changes.D]);
|
||||
const present = uniqueSorted([...changes.A, ...changes.C]);
|
||||
const pathChanges = bounded(touched.filter(filePath => (
|
||||
/^\/(?:usr\/)?(?:local\/)?bin\//.test(filePath)
|
||||
|| /^\/home\/[^/]+\/\.local\/bin\//.test(filePath)
|
||||
)));
|
||||
const services = bounded(present.filter(filePath => (
|
||||
/\/(?:systemd\/system|init\.d|rc\.d)\//.test(filePath)
|
||||
)));
|
||||
const dotfiles = bounded(touched.flatMap(filePath => {
|
||||
const match = filePath.match(/^(\/(?:home\/[^/]+|root)\/\.[^/]+)(?:\/|$)/);
|
||||
return match ? [match[1]] : [];
|
||||
}));
|
||||
const truncated = [added, changed, deleted, pathChanges, services, dotfiles]
|
||||
.some(entry => entry.truncated);
|
||||
|
||||
return {
|
||||
diff: {
|
||||
method,
|
||||
complete: !malformed && !truncated,
|
||||
files_added: added.values,
|
||||
files_changed: changed.values,
|
||||
files_deleted: deleted.values,
|
||||
path_changes: pathChanges.values,
|
||||
services_registered: services.values,
|
||||
dotfiles_touched: dotfiles.values,
|
||||
},
|
||||
malformed,
|
||||
truncated,
|
||||
};
|
||||
}
|
||||
|
||||
function imageCheckArgs(runtime, image) {
|
||||
return ['image', 'inspect', '--format', '{{.Id}}', image];
|
||||
}
|
||||
|
||||
function podmanInfoIsRootless(result) {
|
||||
if (!succeeded(result)) return false;
|
||||
try {
|
||||
return JSON.parse(result.stdout)?.host?.security?.rootless === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function missingContainer(result) {
|
||||
return /(?:no such container|container .* not found|does not exist)/i.test(resultDetail(result));
|
||||
}
|
||||
|
||||
function imageBuildFix(runtime) {
|
||||
const imageRoot = path.resolve(__dirname, '..', '..', '..', 'images', 'sandbox');
|
||||
return `${runtime} build --file "${path.join(imageRoot, 'Containerfile.ubuntu')}" --tag ${DEFAULT_IMAGE} "${imageRoot}"`;
|
||||
}
|
||||
|
||||
function executeContainer(manifest, options = {}) {
|
||||
const runtime = options.runtime || 'podman';
|
||||
if (!['podman', 'docker'].includes(runtime)) {
|
||||
throw new Error(`Unsupported Tier 1 runtime: ${runtime}`);
|
||||
}
|
||||
const cwd = path.resolve(options.cwd || process.cwd());
|
||||
const image = options.image || DEFAULT_IMAGE;
|
||||
const containerName = options.containerName
|
||||
|| `ecc-sandbox-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
|
||||
const run = options.run || defaultRunner;
|
||||
const clock = options.clock || (() => Date.now());
|
||||
const startedMs = clock();
|
||||
const started = new Date(startedMs).toISOString();
|
||||
const deadline = startedMs + (manifest.resources.timeout * 1000);
|
||||
const steps = [];
|
||||
const assertions = [];
|
||||
const notes = [...(options.notes || [])];
|
||||
let installDiff = emptyInstallDiff();
|
||||
let createAttempted = false;
|
||||
let created = false;
|
||||
let executionError = false;
|
||||
let cleanupSucceeded = false;
|
||||
let unsafeToDiff = false;
|
||||
|
||||
const invoke = (argv, maxBuffer = MAX_EXEC_BUFFER, timeout) => run(runtime, argv, {
|
||||
cwd,
|
||||
timeout: timeout || Math.max(1, deadline - clock()),
|
||||
maxBuffer,
|
||||
});
|
||||
|
||||
let runtimeReady = true;
|
||||
if (runtime === 'podman') {
|
||||
const info = invoke(['info', '--format', 'json']);
|
||||
runtimeReady = podmanInfoIsRootless(info);
|
||||
if (!runtimeReady) {
|
||||
executionError = true;
|
||||
notes.push(
|
||||
"Podman is not confirmed rootless — run as an unprivileged user and verify: podman info --format '{{.Host.Security.Rootless}}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const imageResult = runtimeReady
|
||||
? invoke(imageCheckArgs(runtime, image))
|
||||
: { status: null, stdout: '', stderr: '', error: null };
|
||||
const imageId = firstLine(imageResult.stdout);
|
||||
if (runtimeReady && (!succeeded(imageResult) || !imageId)) {
|
||||
executionError = true;
|
||||
notes.push(
|
||||
`${runtime} image ${image} is unavailable — build the pinned snapshot: ${imageBuildFix(runtime)}`
|
||||
);
|
||||
const detail = resultDetail(imageResult);
|
||||
if (detail) notes.push(`${runtime} image check: ${detail}`);
|
||||
} else if (runtimeReady) {
|
||||
notes.push(`image_ref=${image}`);
|
||||
notes.push(`image_id=${imageId}`);
|
||||
createAttempted = true;
|
||||
const createResult = invoke(buildCreateArgs(manifest, {
|
||||
containerName,
|
||||
cwd,
|
||||
// Use the inspected immutable ID, not the mutable reference, so the
|
||||
// evidence and executed snapshot cannot diverge through a retag race.
|
||||
image: imageId,
|
||||
}));
|
||||
if (!succeeded(createResult)) {
|
||||
executionError = true;
|
||||
notes.push(`${runtime} create failed: ${resultDetail(createResult) || 'unknown error'}`);
|
||||
} else {
|
||||
created = true;
|
||||
const startMs = clock();
|
||||
const startResult = invoke(['start', containerName]);
|
||||
const containerStartMs = Math.max(0, clock() - startMs);
|
||||
notes.push(`container_start_ms=${containerStartMs}`);
|
||||
if (!succeeded(startResult)) {
|
||||
executionError = true;
|
||||
notes.push(`${runtime} start failed: ${resultDetail(startResult) || 'unknown error'}`);
|
||||
} else {
|
||||
const execute = (command, assertion) => {
|
||||
const execution = invoke([
|
||||
'exec',
|
||||
containerName,
|
||||
'/bin/bash',
|
||||
'-lc',
|
||||
command,
|
||||
]);
|
||||
const step = normalizeStep(command, execution);
|
||||
steps.push(step);
|
||||
if (assertion) assertions.push({ cmd: command, pass: step.exit === 0 });
|
||||
if (execution.error || execution.status === null) {
|
||||
executionError = true;
|
||||
const stop = invoke(
|
||||
['stop', '--time', '0', containerName],
|
||||
MAX_EXEC_BUFFER,
|
||||
CLEANUP_TIMEOUT_MS
|
||||
);
|
||||
if (succeeded(stop)) {
|
||||
notes.push(`${runtime} stopped the container after an indeterminate or timed-out exec`);
|
||||
} else {
|
||||
unsafeToDiff = true;
|
||||
notes.push(`${runtime} could not stop the container after exec failure; diff skipped before forced cleanup`);
|
||||
}
|
||||
}
|
||||
return step.exit === 0;
|
||||
};
|
||||
|
||||
let setupPassed = true;
|
||||
for (const command of manifest.steps.setup) {
|
||||
if (!execute(command, false)) {
|
||||
setupPassed = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (setupPassed) {
|
||||
for (const command of manifest.steps.assert) {
|
||||
if (!execute(command, true)) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (manifest.report === 'install-diff' && !unsafeToDiff) {
|
||||
const diffResult = invoke(
|
||||
['diff', containerName],
|
||||
MAX_DIFF_BUFFER,
|
||||
CLEANUP_TIMEOUT_MS
|
||||
);
|
||||
if (succeeded(diffResult)) {
|
||||
const parsed = parseContainerDiff(diffResult.stdout, `${runtime}-layer`);
|
||||
installDiff = parsed.diff;
|
||||
notes.push(`${runtime} diff reports changed filesystem paths, including directories`);
|
||||
if (parsed.malformed) notes.push(`${runtime} diff contained malformed lines; evidence is incomplete`);
|
||||
if (parsed.truncated) notes.push(`install diff exceeded ${MAX_DIFF_ITEMS} entries; evidence is truncated`);
|
||||
if (!parsed.diff.complete) executionError = true;
|
||||
} else {
|
||||
executionError = true;
|
||||
notes.push(`${runtime} diff failed: ${resultDetail(diffResult) || 'unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (createAttempted) {
|
||||
const cleanup = invoke(
|
||||
['rm', '--force', containerName],
|
||||
MAX_EXEC_BUFFER,
|
||||
CLEANUP_TIMEOUT_MS
|
||||
);
|
||||
cleanupSucceeded = succeeded(cleanup) || (!created && missingContainer(cleanup));
|
||||
if (!cleanupSucceeded) {
|
||||
executionError = true;
|
||||
notes.push(
|
||||
`${runtime} cleanup failed for ${containerName} — remove it manually: ${runtime} rm --force ${containerName}`
|
||||
);
|
||||
}
|
||||
}
|
||||
if (options.mock) notes.push(`Mock ${runtime} execution: no container was created`);
|
||||
|
||||
const report = buildSingleReport({
|
||||
manifest: options.manifestPath,
|
||||
backend: runtime,
|
||||
tier: 1,
|
||||
os: 'linux',
|
||||
arch: options.arch,
|
||||
executionMode: options.mock ? 'mock' : 'real',
|
||||
started,
|
||||
durationMs: clock() - startedMs,
|
||||
steps,
|
||||
assertions,
|
||||
installDiff,
|
||||
executionError,
|
||||
notes,
|
||||
});
|
||||
return {
|
||||
report,
|
||||
exitCode: report.result === 'pass' ? 0 : (report.result === 'fail' ? 1 : 2),
|
||||
cleanup: { attempted: createAttempted, pass: cleanupSucceeded, container: containerName },
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_IMAGE,
|
||||
CLEANUP_TIMEOUT_MS,
|
||||
MAX_DIFF_BUFFER,
|
||||
MAX_DIFF_ITEMS,
|
||||
buildCreateArgs,
|
||||
defaultRunner,
|
||||
executeContainer,
|
||||
hasOpenNetwork,
|
||||
imageBuildFix,
|
||||
parseContainerDiff,
|
||||
podmanInfoIsRootless,
|
||||
};
|
||||
@@ -4,8 +4,8 @@ const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
const { readBoundedRegularFile } = require('../contracts');
|
||||
const { buildSingleReport, normalizeStep } = require('../report');
|
||||
const { loadMockScenario, mockRunner, validateMockScenario } = require('../mock');
|
||||
|
||||
const SRT_DENIAL_EXIT_CODE = 77;
|
||||
const MAX_EXEC_BUFFER = 1024 * 1024;
|
||||
@@ -123,66 +123,6 @@ function hasInstallerSignature(command) {
|
||||
return INSTALLER_PATTERN.test(command);
|
||||
}
|
||||
|
||||
function validateMockScenario(value) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error('SRT mock scenario must be an object');
|
||||
}
|
||||
const keys = Object.keys(value);
|
||||
if (keys.length !== 1 || keys[0] !== 'results') {
|
||||
throw new Error('SRT mock scenario permits only a results array');
|
||||
}
|
||||
if (!Array.isArray(value.results) || value.results.length < 1 || value.results.length > 1000) {
|
||||
throw new Error('SRT mock results must contain 1-1000 entries');
|
||||
}
|
||||
return value.results.map((entry, index) => {
|
||||
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
||||
throw new Error(`SRT mock result ${index} must be an object`);
|
||||
}
|
||||
const allowed = new Set(['status', 'stdout', 'stderr', 'error']);
|
||||
const unknown = Object.keys(entry).filter(key => !allowed.has(key));
|
||||
if (unknown.length > 0) {
|
||||
throw new Error(`SRT mock result ${index} has unknown key: ${unknown[0]}`);
|
||||
}
|
||||
if (!Number.isInteger(entry.status) && entry.status !== null) {
|
||||
throw new Error(`SRT mock result ${index} status must be an integer or null`);
|
||||
}
|
||||
for (const field of ['stdout', 'stderr', 'error']) {
|
||||
if (entry[field] !== undefined && typeof entry[field] !== 'string') {
|
||||
throw new Error(`SRT mock result ${index} ${field} must be a string`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: entry.status,
|
||||
stdout: entry.stdout || '',
|
||||
stderr: entry.stderr || '',
|
||||
error: entry.error ? new Error(entry.error) : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function loadMockScenario(filePath) {
|
||||
return validateMockScenario(JSON.parse(
|
||||
readBoundedRegularFile(filePath, 'SRT mock scenario')
|
||||
));
|
||||
}
|
||||
|
||||
function mockRunner(results) {
|
||||
let index = 0;
|
||||
return () => {
|
||||
if (index >= results.length) {
|
||||
return {
|
||||
status: null,
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
error: new Error('SRT mock scenario ran out of results'),
|
||||
};
|
||||
}
|
||||
const result = results[index];
|
||||
index += 1;
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
function executeSrt(manifest, options) {
|
||||
const cwd = path.resolve(options.cwd || process.cwd());
|
||||
const platform = options.platform || process.platform;
|
||||
|
||||
+20
-11
@@ -16,11 +16,9 @@ const {
|
||||
readCapabilityCache,
|
||||
writeCapabilityCache,
|
||||
} = require('./probe');
|
||||
const {
|
||||
executeSrt,
|
||||
loadMockScenario,
|
||||
mockRunner,
|
||||
} = require('./backends/srt');
|
||||
const { executeSrt } = require('./backends/srt');
|
||||
const { executeContainer } = require('./backends/podman');
|
||||
const { loadMockScenario, mockRunner } = require('./mock');
|
||||
|
||||
const COMMANDS = ['probe', 'run', 'report'];
|
||||
|
||||
@@ -165,25 +163,36 @@ function runExecution(options) {
|
||||
throw new Error('Multiple-route execution is unavailable until the aggregate execution phase');
|
||||
}
|
||||
const route = resolved.decision.routes[0];
|
||||
if (route.backend !== 'srt') {
|
||||
if (!['srt', 'podman', 'docker'].includes(route.backend)) {
|
||||
throw new Error(`${route.backend} execution is unavailable until its adapter phase`);
|
||||
}
|
||||
|
||||
let run;
|
||||
let mock = false;
|
||||
if (options.mockPath) {
|
||||
run = mockRunner(loadMockScenario(path.resolve(options.mockPath)));
|
||||
run = mockRunner(loadMockScenario(path.resolve(options.mockPath), route.backend));
|
||||
mock = true;
|
||||
}
|
||||
return executeSrt(resolved.manifest, {
|
||||
const executionOptions = {
|
||||
arch: route.arch,
|
||||
cwd: process.cwd(),
|
||||
enableWeakerNestedSandbox: process.env.ECC_SANDBOX_ALLOW_NESTED_SRT === '1',
|
||||
manifestPath: resolved.manifestPath,
|
||||
mock,
|
||||
os: route.os,
|
||||
platform: process.platform,
|
||||
notes: route.notes,
|
||||
run,
|
||||
};
|
||||
if (route.backend === 'srt') {
|
||||
return executeSrt(resolved.manifest, {
|
||||
...executionOptions,
|
||||
enableWeakerNestedSandbox: process.env.ECC_SANDBOX_ALLOW_NESTED_SRT === '1',
|
||||
os: route.os,
|
||||
platform: process.platform,
|
||||
});
|
||||
}
|
||||
return executeContainer(resolved.manifest, {
|
||||
...executionOptions,
|
||||
image: process.env.ECC_SANDBOX_IMAGE,
|
||||
runtime: route.backend,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
|
||||
const { readBoundedRegularFile } = require('./contracts');
|
||||
|
||||
function validateMockScenario(value, adapter = 'sandbox') {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new Error(`${adapter} mock scenario must be an object`);
|
||||
}
|
||||
const keys = Object.keys(value);
|
||||
if (keys.length !== 1 || keys[0] !== 'results') {
|
||||
throw new Error(`${adapter} mock scenario permits only a results array`);
|
||||
}
|
||||
if (!Array.isArray(value.results) || value.results.length < 1 || value.results.length > 1000) {
|
||||
throw new Error(`${adapter} mock results must contain 1-1000 entries`);
|
||||
}
|
||||
return value.results.map((entry, index) => {
|
||||
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
||||
throw new Error(`${adapter} mock result ${index} must be an object`);
|
||||
}
|
||||
const allowed = new Set(['status', 'stdout', 'stderr', 'error']);
|
||||
const unknown = Object.keys(entry).filter(key => !allowed.has(key));
|
||||
if (unknown.length > 0) {
|
||||
throw new Error(`${adapter} mock result ${index} has unknown key: ${unknown[0]}`);
|
||||
}
|
||||
if (!Number.isInteger(entry.status) && entry.status !== null) {
|
||||
throw new Error(`${adapter} mock result ${index} status must be an integer or null`);
|
||||
}
|
||||
for (const field of ['stdout', 'stderr', 'error']) {
|
||||
if (entry[field] !== undefined && typeof entry[field] !== 'string') {
|
||||
throw new Error(`${adapter} mock result ${index} ${field} must be a string`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: entry.status,
|
||||
stdout: entry.stdout || '',
|
||||
stderr: entry.stderr || '',
|
||||
error: entry.error ? new Error(entry.error) : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function loadMockScenario(filePath, adapter) {
|
||||
return validateMockScenario(
|
||||
JSON.parse(readBoundedRegularFile(filePath, `${adapter} mock scenario`)),
|
||||
adapter
|
||||
);
|
||||
}
|
||||
|
||||
function mockRunner(results) {
|
||||
let index = 0;
|
||||
return () => {
|
||||
if (index >= results.length) {
|
||||
return {
|
||||
status: null,
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
error: new Error('Sandbox mock scenario ran out of results'),
|
||||
};
|
||||
}
|
||||
const result = results[index];
|
||||
index += 1;
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { loadMockScenario, mockRunner, validateMockScenario };
|
||||
@@ -106,13 +106,30 @@ function detectPodman(run, platform, architecture) {
|
||||
|
||||
if (platform === 'linux') {
|
||||
const info = run('podman', ['info', '--format', 'json']);
|
||||
const ready = succeeded(info);
|
||||
let rootless = false;
|
||||
if (succeeded(info)) {
|
||||
try {
|
||||
const parsed = JSON.parse(info.stdout);
|
||||
rootless = parsed?.host?.security?.rootless === true;
|
||||
} catch {
|
||||
rootless = false;
|
||||
}
|
||||
}
|
||||
const ready = succeeded(info) && rootless;
|
||||
return backend(ready, {
|
||||
version,
|
||||
state: ready ? 'ready' : 'not-configured',
|
||||
state: ready ? 'ready' : (succeeded(info) ? 'unavailable' : 'not-configured'),
|
||||
targets: ready ? [{ os: 'linux', arch: architecture }] : [],
|
||||
reason: ready ? 'rootless Podman is ready' : 'podman is installed but not usable by this user',
|
||||
fix: ready ? undefined : 'Configure rootless Podman: podman system migrate',
|
||||
reason: ready
|
||||
? 'rootless Podman is ready'
|
||||
: (succeeded(info)
|
||||
? 'Podman is running as root; ECC requires rootless isolation'
|
||||
: 'podman is installed but not usable by this user'),
|
||||
fix: ready
|
||||
? undefined
|
||||
: (succeeded(info)
|
||||
? "Run Podman as an unprivileged user; verify: podman info --format '{{.Host.Security.Rootless}}'"
|
||||
: 'Configure rootless Podman: podman system migrate'),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -130,6 +147,26 @@ function detectPodman(run, platform, architecture) {
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
if (running) {
|
||||
const info = run('podman', ['info', '--format', 'json']);
|
||||
let rootless = false;
|
||||
if (succeeded(info)) {
|
||||
try {
|
||||
rootless = JSON.parse(info.stdout)?.host?.security?.rootless === true;
|
||||
} catch {
|
||||
rootless = false;
|
||||
}
|
||||
}
|
||||
if (!rootless) {
|
||||
return backend(false, {
|
||||
version,
|
||||
state: 'unavailable',
|
||||
targets: [],
|
||||
reason: 'Podman machine is rootful or its rootless state cannot be verified',
|
||||
fix: 'Use a rootless Podman machine: podman machine set --rootful=false && podman machine stop && podman machine start',
|
||||
});
|
||||
}
|
||||
}
|
||||
return backend(running, {
|
||||
version,
|
||||
state: running ? 'ready' : 'stopped',
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
name: install-cowsay-clean-user
|
||||
needs:
|
||||
os: [linux]
|
||||
capabilities:
|
||||
- pkg-install
|
||||
- network:*
|
||||
trust: first-party
|
||||
native: false
|
||||
resources:
|
||||
cpu: 2
|
||||
memory: 512MB
|
||||
timeout: 120
|
||||
steps:
|
||||
setup:
|
||||
- npm install --global cowsay@1.6.0 --ignore-scripts
|
||||
assert:
|
||||
- command -v cowsay
|
||||
- cowsay ECC | grep -q ECC
|
||||
report: install-diff
|
||||
@@ -0,0 +1,326 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
const { validateManifest, validateReport } = require('../../scripts/sandbox/contracts');
|
||||
const { defaultHost } = require('../../scripts/sandbox/router');
|
||||
const {
|
||||
DEFAULT_IMAGE,
|
||||
buildCreateArgs,
|
||||
executeContainer,
|
||||
parseContainerDiff,
|
||||
} = require('../../scripts/sandbox/backends/podman');
|
||||
|
||||
const repoRoot = path.join(__dirname, '..', '..');
|
||||
const cliPath = path.join(repoRoot, 'scripts', 'sandbox', 'ecc-sandbox');
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
passed += 1;
|
||||
} catch (error) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${error.stack || error.message}`);
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
function manifest(overrides = {}) {
|
||||
return validateManifest({
|
||||
name: 'podman-test',
|
||||
needs: {
|
||||
os: ['linux'],
|
||||
capabilities: overrides.capabilities || ['pkg-install', 'network:*'],
|
||||
trust: overrides.trust || 'first-party',
|
||||
native: false,
|
||||
},
|
||||
resources: { cpu: 2, memory: '512MB', timeout: 30 },
|
||||
steps: {
|
||||
setup: overrides.setup || ['npm install --global cowsay@1.6.0 --ignore-scripts'],
|
||||
assert: overrides.assert || ['command -v cowsay'],
|
||||
},
|
||||
report: overrides.report || 'install-diff',
|
||||
});
|
||||
}
|
||||
|
||||
function result(status, stdout = '', stderr = '', error = null) {
|
||||
return { status, stdout, stderr, error };
|
||||
}
|
||||
|
||||
function sequenceRunner(results, calls) {
|
||||
let index = 0;
|
||||
return (executable, argv, options) => {
|
||||
calls.push({ executable, argv, options });
|
||||
const value = results[index];
|
||||
index += 1;
|
||||
return value || result(null, '', '', new Error('mock sequence exhausted'));
|
||||
};
|
||||
}
|
||||
|
||||
function runDirect(results, extras = {}) {
|
||||
const calls = [];
|
||||
let tick = 0;
|
||||
const runtime = extras.runtime || 'podman';
|
||||
const runtimeResults = runtime === 'podman'
|
||||
? [result(0, '{"host":{"security":{"rootless":true}}}\n'), ...results]
|
||||
: results;
|
||||
const outcome = executeContainer(extras.manifest || manifest(), {
|
||||
arch: 'arm64',
|
||||
clock: () => 1_700_000_000_000 + (tick++ * 5),
|
||||
containerName: 'ecc-sandbox-test',
|
||||
cwd: repoRoot,
|
||||
manifestPath: path.join(repoRoot, 'sandbox.yaml'),
|
||||
mock: true,
|
||||
notes: extras.notes,
|
||||
run: sequenceRunner(runtimeResults, calls),
|
||||
runtime,
|
||||
});
|
||||
return { outcome, calls };
|
||||
}
|
||||
|
||||
console.log('\n=== ECC sandbox Podman adapter tests ===\n');
|
||||
|
||||
test('ships three digest-pinned non-root Linux snapshot definitions', () => {
|
||||
for (const distro of ['ubuntu', 'debian', 'fedora']) {
|
||||
const source = fs.readFileSync(
|
||||
path.join(repoRoot, 'images', 'sandbox', `Containerfile.${distro}`),
|
||||
'utf8'
|
||||
);
|
||||
assert.match(source, /^ARG BASE_IMAGE=[^\n]+@sha256:[a-f0-9]{64}$/m);
|
||||
assert.match(source, /^ARG NODE_IMAGE=[^\n]+@sha256:[a-f0-9]{64}$/m);
|
||||
assert.match(source, /^USER 1000:1000$/m);
|
||||
}
|
||||
});
|
||||
|
||||
test('builds a bounded rootless create command with network off by default', () => {
|
||||
const args = buildCreateArgs(manifest({ capabilities: ['pkg-install'] }), {
|
||||
containerName: 'ecc-sandbox-test',
|
||||
cwd: repoRoot,
|
||||
image: DEFAULT_IMAGE,
|
||||
});
|
||||
assert.deepStrictEqual(args.slice(0, 3), ['create', '--name', 'ecc-sandbox-test']);
|
||||
assert.ok(args.includes('--cap-drop'));
|
||||
assert.ok(args.includes('ALL'));
|
||||
assert.strictEqual(args.includes('no-new-privileges'), false);
|
||||
assert.ok(args.includes('--network'));
|
||||
assert.ok(args.includes('none'));
|
||||
assert.ok(args.includes(`${repoRoot}:/workspace/source:ro`));
|
||||
assert.deepStrictEqual(args.slice(-3), [DEFAULT_IMAGE, 'sleep', 'infinity']);
|
||||
|
||||
const untrusted = buildCreateArgs(manifest({
|
||||
capabilities: ['pkg-install'], trust: 'untrusted',
|
||||
}), {
|
||||
containerName: 'ecc-sandbox-test', cwd: repoRoot, image: DEFAULT_IMAGE,
|
||||
});
|
||||
assert.ok(untrusted.includes('no-new-privileges'));
|
||||
|
||||
const open = buildCreateArgs(manifest(), {
|
||||
containerName: 'ecc-sandbox-test', cwd: repoRoot, image: DEFAULT_IMAGE,
|
||||
});
|
||||
assert.strictEqual(open.includes('--network'), false);
|
||||
});
|
||||
|
||||
test('normalizes Podman diff paths into install evidence', () => {
|
||||
const parsed = parseContainerDiff([
|
||||
'A /home/ecc/.local/bin/cowsay',
|
||||
'A /home/ecc/.local/lib/node_modules/cowsay/index.js',
|
||||
'C /home/ecc/.npm/_logs/install.log',
|
||||
'A /etc/systemd/system/demo.service',
|
||||
'D /home/ecc/.local/bin/old-tool',
|
||||
'D /home/ecc/.config/old-tool/config.json',
|
||||
'',
|
||||
].join('\n'));
|
||||
assert.strictEqual(parsed.diff.method, 'podman-layer');
|
||||
assert.strictEqual(parsed.diff.complete, true);
|
||||
assert.ok(parsed.diff.files_added.includes('/home/ecc/.local/bin/cowsay'));
|
||||
assert.ok(parsed.diff.files_deleted.includes('/home/ecc/.local/bin/old-tool'));
|
||||
assert.deepStrictEqual(parsed.diff.path_changes, [
|
||||
'/home/ecc/.local/bin/cowsay',
|
||||
'/home/ecc/.local/bin/old-tool',
|
||||
]);
|
||||
assert.deepStrictEqual(parsed.diff.services_registered, ['/etc/systemd/system/demo.service']);
|
||||
assert.ok(parsed.diff.dotfiles_touched.includes('/home/ecc/.npm'));
|
||||
assert.ok(parsed.diff.dotfiles_touched.includes('/home/ecc/.config'));
|
||||
});
|
||||
|
||||
test('executes create-start-steps-diff-remove and emits a valid report', () => {
|
||||
const { outcome, calls } = runDirect([
|
||||
result(0, 'sha256:mock-image\n'),
|
||||
result(0, 'container-id\n'),
|
||||
result(0),
|
||||
result(0, 'installed\n'),
|
||||
result(0, '/home/ecc/.local/bin/cowsay\n'),
|
||||
result(0, 'A /home/ecc/.local/bin/cowsay\nA /home/ecc/.npm/_logs/install.log\n'),
|
||||
result(0),
|
||||
], { notes: ['microsandbox unavailable; using documented degraded Podman isolation'] });
|
||||
assert.strictEqual(validateReport(outcome.report), outcome.report);
|
||||
assert.strictEqual(outcome.exitCode, 0);
|
||||
assert.strictEqual(outcome.report.result, 'pass');
|
||||
assert.strictEqual(outcome.report.execution_mode, 'mock');
|
||||
assert.deepStrictEqual(calls.map(call => call.argv[0]), [
|
||||
'info', 'image', 'create', 'start', 'exec', 'exec', 'diff', 'rm',
|
||||
]);
|
||||
assert.ok(outcome.report.install_diff.files_added.includes('/home/ecc/.local/bin/cowsay'));
|
||||
assert.strictEqual(outcome.cleanup.pass, true);
|
||||
assert.match(outcome.report.notes.join('\n'), /container_start_ms=/);
|
||||
assert.ok(outcome.report.notes.includes('image_id=sha256:mock-image'));
|
||||
const createCall = calls.find(call => call.argv[0] === 'create');
|
||||
assert.deepStrictEqual(createCall.argv.slice(-3), ['sha256:mock-image', 'sleep', 'infinity']);
|
||||
});
|
||||
|
||||
test('still captures diff and removes the container after a failed step', () => {
|
||||
const { outcome, calls } = runDirect([
|
||||
result(0, 'sha256:mock-image\n'), result(0), result(0),
|
||||
result(1, '', 'installer failed'),
|
||||
result(0, 'C /home/ecc/.npm/_logs/failure.log\n'),
|
||||
result(0),
|
||||
]);
|
||||
assert.strictEqual(outcome.report.result, 'fail');
|
||||
assert.deepStrictEqual(calls.map(call => call.argv[0]), [
|
||||
'info', 'image', 'create', 'start', 'exec', 'diff', 'rm',
|
||||
]);
|
||||
assert.strictEqual(outcome.cleanup.pass, true);
|
||||
});
|
||||
|
||||
test('cleanup failure upgrades the report to error with a recovery command', () => {
|
||||
const { outcome } = runDirect([
|
||||
result(0, 'sha256:mock-image\n'), result(0), result(0), result(0), result(0), result(0, ''),
|
||||
result(1, '', 'container busy'),
|
||||
]);
|
||||
assert.strictEqual(outcome.report.result, 'error');
|
||||
assert.strictEqual(outcome.exitCode, 2);
|
||||
assert.match(outcome.report.notes.join('\n'), /podman rm --force ecc-sandbox-test/);
|
||||
});
|
||||
|
||||
test('attempts cleanup even when create reports failure', () => {
|
||||
const { outcome, calls } = runDirect([
|
||||
result(0, 'sha256:mock-image\n'),
|
||||
result(1, '', 'create failed after allocating state'),
|
||||
result(1, '', 'no such container'),
|
||||
]);
|
||||
assert.strictEqual(outcome.report.result, 'error');
|
||||
assert.strictEqual(outcome.cleanup.attempted, true);
|
||||
assert.strictEqual(outcome.cleanup.pass, true);
|
||||
assert.deepStrictEqual(calls.map(call => call.argv[0]), ['info', 'image', 'create', 'rm']);
|
||||
});
|
||||
|
||||
test('stops an indeterminate exec before collecting diff evidence', () => {
|
||||
const { outcome, calls } = runDirect([
|
||||
result(0, 'sha256:mock-image\n'), result(0), result(0),
|
||||
result(null, '', '', new Error('ETIMEDOUT')),
|
||||
result(0),
|
||||
result(0, 'C /home/ecc/.npm/_logs/timeout.log\n'),
|
||||
result(0),
|
||||
]);
|
||||
assert.strictEqual(outcome.report.result, 'error');
|
||||
assert.deepStrictEqual(calls.map(call => call.argv[0]), [
|
||||
'info', 'image', 'create', 'start', 'exec', 'stop', 'diff', 'rm',
|
||||
]);
|
||||
assert.match(outcome.report.notes.join('\n'), /stopped the container/);
|
||||
});
|
||||
|
||||
test('incomplete diff evidence upgrades an otherwise passing run to error', () => {
|
||||
const oversized = '/tmp/' + 'x'.repeat(4_100);
|
||||
const { outcome } = runDirect([
|
||||
result(0, 'sha256:mock-image\n'), result(0), result(0),
|
||||
result(0), result(0), result(0, `A ${oversized}\n`), result(0),
|
||||
]);
|
||||
assert.strictEqual(outcome.report.result, 'error');
|
||||
assert.strictEqual(outcome.report.install_diff.complete, false);
|
||||
assert.match(outcome.report.notes.join('\n'), /evidence is incomplete/);
|
||||
});
|
||||
|
||||
test('bounds runtime diagnostics so error reports remain schema-valid', () => {
|
||||
const { outcome } = runDirect([
|
||||
result(0, 'sha256:mock-image\n'),
|
||||
result(1, '', 'failure '.repeat(2_000)),
|
||||
result(1, '', 'no such container'),
|
||||
]);
|
||||
assert.strictEqual(validateReport(outcome.report), outcome.report);
|
||||
assert.ok(outcome.report.notes.every(note => note.length <= 4_096));
|
||||
});
|
||||
|
||||
test('missing snapshot returns a schema-valid actionable error report', () => {
|
||||
const { outcome, calls } = runDirect([result(1, '', 'image not known')]);
|
||||
assert.strictEqual(outcome.report.result, 'error');
|
||||
assert.strictEqual(outcome.cleanup.attempted, false);
|
||||
assert.strictEqual(calls.length, 2);
|
||||
assert.match(outcome.report.notes.join('\n'), /podman build --file/);
|
||||
});
|
||||
|
||||
test('refuses execution when Podman is not confirmed rootless', () => {
|
||||
const calls = [];
|
||||
const outcome = executeContainer(manifest(), {
|
||||
arch: 'x86_64',
|
||||
containerName: 'ecc-sandbox-rootful-test',
|
||||
cwd: repoRoot,
|
||||
manifestPath: path.join(repoRoot, 'sandbox.yaml'),
|
||||
mock: true,
|
||||
run: sequenceRunner([result(0, '{"host":{"security":{"rootless":false}}}')], calls),
|
||||
runtime: 'podman',
|
||||
});
|
||||
assert.strictEqual(outcome.report.result, 'error');
|
||||
assert.deepStrictEqual(calls.map(call => call.argv[0]), ['info']);
|
||||
assert.match(outcome.report.notes.join('\n'), /not confirmed rootless/);
|
||||
});
|
||||
|
||||
test('CLI mock mode routes to Podman and emits only normalized JSON', () => {
|
||||
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-podman-cli-'));
|
||||
try {
|
||||
const host = defaultHost();
|
||||
const manifestPath = path.join(tempRoot, 'sandbox.yaml');
|
||||
const capabilitiesPath = path.join(tempRoot, 'capabilities.json');
|
||||
const mockPath = path.join(tempRoot, 'mock.json');
|
||||
fs.writeFileSync(manifestPath, [
|
||||
'name: cli-podman-test',
|
||||
'needs:',
|
||||
' os: [linux]',
|
||||
' capabilities: [pkg-install]',
|
||||
' trust: first-party',
|
||||
' native: false',
|
||||
'resources:',
|
||||
' cpu: 1',
|
||||
' memory: 256MB',
|
||||
' timeout: 30',
|
||||
'steps:',
|
||||
' setup: ["printf setup"]',
|
||||
' assert: ["printf assert"]',
|
||||
'report: install-diff',
|
||||
'',
|
||||
].join('\n'));
|
||||
fs.writeFileSync(capabilitiesPath, JSON.stringify({
|
||||
schema_version: 1,
|
||||
host,
|
||||
backends: { podman: { available: true, targets: [{ os: 'linux', arch: host.arch }] } },
|
||||
}));
|
||||
fs.writeFileSync(mockPath, JSON.stringify({ results: [
|
||||
{ status: 0, stdout: '{"host":{"security":{"rootless":true}}}\n' },
|
||||
{ status: 0, stdout: 'sha256:mock-image\n' }, { status: 0 }, { status: 0 },
|
||||
{ status: 0, stdout: 'setup' }, { status: 0, stdout: 'assert' },
|
||||
{ status: 0, stdout: 'A /home/ecc/.local/bin/demo\n' }, { status: 0 },
|
||||
] }));
|
||||
const cli = spawnSync(process.execPath, [
|
||||
cliPath, 'run', manifestPath,
|
||||
'--capabilities', capabilitiesPath,
|
||||
'--mock', mockPath,
|
||||
], { cwd: repoRoot, encoding: 'utf8', shell: false, timeout: 30_000 });
|
||||
assert.strictEqual(cli.status, 0, cli.stderr || cli.stdout);
|
||||
assert.strictEqual(cli.stderr, '');
|
||||
const report = validateReport(JSON.parse(cli.stdout));
|
||||
assert.strictEqual(report.backend, 'podman');
|
||||
assert.strictEqual(report.execution_mode, 'mock');
|
||||
assert.ok(report.install_diff.path_changes.includes('/home/ecc/.local/bin/demo'));
|
||||
} finally {
|
||||
fs.rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
if (failed > 0) process.exitCode = 1;
|
||||
@@ -55,7 +55,11 @@ function fakeRunner(platform, installed = {}) {
|
||||
return result(0, JSON.stringify([{ Running: Boolean(installed.podmanRunning) }]));
|
||||
}
|
||||
if (executable === 'podman' && argv[0] === 'info') {
|
||||
return installed.podmanRunning ? result(0, '{}') : result(1, '', 'not ready');
|
||||
return installed.podmanRunning
|
||||
? result(0, JSON.stringify({
|
||||
host: { security: { rootless: installed.podmanRootless !== false } },
|
||||
}))
|
||||
: result(1, '', 'not ready');
|
||||
}
|
||||
if (executable === 'docker' && argv[0] === 'info') {
|
||||
return installed.docker ? result(0, '"27.0"') : missing(executable);
|
||||
@@ -154,6 +158,19 @@ test('disables weaker nested SRT on a Linux container', () => {
|
||||
assert.strictEqual(capabilities.backends.microsandbox.available, true);
|
||||
});
|
||||
|
||||
test('rejects rootful Podman on Linux', () => {
|
||||
const capabilities = probeCapabilities(commonOptions('linux', 'x64', {
|
||||
virtualization: true,
|
||||
podman: true,
|
||||
podmanRunning: true,
|
||||
podmanRootless: false,
|
||||
}));
|
||||
assert.strictEqual(capabilities.backends.podman.available, false);
|
||||
assert.strictEqual(capabilities.backends.podman.state, 'unavailable');
|
||||
assert.match(capabilities.backends.podman.reason, /requires rootless/);
|
||||
assert.match(capabilities.backends.podman.fix, /unprivileged user/);
|
||||
});
|
||||
|
||||
test('enables weaker nested SRT only through an explicit opt-in', () => {
|
||||
const capabilities = probeCapabilities(commonOptions('linux', 'x64', {
|
||||
virtualization: true,
|
||||
@@ -255,6 +272,18 @@ test('starts an existing stopped Podman machine without reinitializing it', () =
|
||||
assert.strictEqual(capabilities.backends.podman.fix, 'Start Podman: podman machine start');
|
||||
});
|
||||
|
||||
test('rejects a rootful Podman machine', () => {
|
||||
const capabilities = probeCapabilities(commonOptions('darwin', 'arm64', {
|
||||
virtualization: true,
|
||||
podman: true,
|
||||
podmanRunning: true,
|
||||
podmanRootless: false,
|
||||
}));
|
||||
assert.strictEqual(capabilities.backends.podman.available, false);
|
||||
assert.match(capabilities.backends.podman.reason, /rootful/);
|
||||
assert.match(capabilities.backends.podman.fix, /rootful=false/);
|
||||
});
|
||||
|
||||
test('writes and reads a private schema-valid capability cache', () => {
|
||||
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-probe-cache-'));
|
||||
try {
|
||||
|
||||
@@ -21,8 +21,8 @@ const {
|
||||
isSrtDenial,
|
||||
resolveWindowsSrtShim,
|
||||
sanitizeEnvironment,
|
||||
validateMockScenario,
|
||||
} = require('../../scripts/sandbox/backends/srt');
|
||||
const { validateMockScenario } = require('../../scripts/sandbox/mock');
|
||||
|
||||
const repoRoot = path.join(__dirname, '..', '..');
|
||||
const cliPath = path.join(repoRoot, 'scripts', 'sandbox', 'ecc-sandbox');
|
||||
@@ -277,10 +277,10 @@ test('reports runner startup and timeout errors as error, not policy denial', ()
|
||||
|
||||
test('rejects loose mock scenarios at the public boundary', () => {
|
||||
assert.throws(
|
||||
() => validateMockScenario({ results: [{ status: 0, surprise: true }] }),
|
||||
() => validateMockScenario({ results: [{ status: 0, surprise: true }] }, 'srt'),
|
||||
/unknown key/
|
||||
);
|
||||
assert.throws(() => validateMockScenario({ results: [] }), /1-1000/);
|
||||
assert.throws(() => validateMockScenario({ results: [] }, 'srt'), /1-1000/);
|
||||
});
|
||||
|
||||
test('CLI mock mode emits only a schema-valid SRT report', () => {
|
||||
|
||||
@@ -42,6 +42,7 @@ function buildExpectedPublishPaths(repoRoot) {
|
||||
|
||||
const extraPaths = [
|
||||
"manifests",
|
||||
"images/sandbox",
|
||||
"scripts/ecc.js",
|
||||
"scripts/feedback.js",
|
||||
"scripts/catalog.js",
|
||||
@@ -179,6 +180,11 @@ function main() {
|
||||
"scripts/sandbox/report.js",
|
||||
"scripts/sandbox/router.js",
|
||||
"scripts/sandbox/backends/srt.js",
|
||||
"scripts/sandbox/backends/podman.js",
|
||||
"scripts/sandbox/mock.js",
|
||||
"images/sandbox/Containerfile.ubuntu",
|
||||
"images/sandbox/Containerfile.debian",
|
||||
"images/sandbox/Containerfile.fedora",
|
||||
"scripts/work-items.js",
|
||||
"scripts/platform-audit.js",
|
||||
"scripts/sync-ecc-to-codex.sh",
|
||||
|
||||
Reference in new issue
Block a user