Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: contain Linux Code Animation workers with bubblewrap (#9420)

[._.]/ Adam Eivy5843ab8845b9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 16093dfe9d..0847029a16 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -843,10 +843,39 @@ jobs:
- name: Run the Node compatibility contract
run: npm run test:fast --prefix server -- ../scripts/checkNodeVersion.test.js ../scripts/node-version-drift.test.js
+ linux-containment:
+ name: Linux worker containment
+ needs: impact
+ if: needs.impact.outputs.server_mode != 'skip'
+ # 22.04 allows unprivileged user namespaces without changing the runner's
+ # AppArmor policy. Restricted hosts must remain fail-closed in the product.
+ runs-on: ubuntu-22.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: 24.x
+ cache: npm
+ cache-dependency-path: server/package-lock.json
+ - name: Install the containment prerequisite
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y bubblewrap
+ - name: Install test dependencies
+ run: npm ci --ignore-scripts --prefix server
+ - name: Exercise real namespaces, seccomp, limits and cancellation
+ env:
+ PORTOS_REQUIRE_LINUX_CONTAINMENT: '1'
+ run: npm test --prefix server -- --run lib/codeAnimationContainment.test.js routes/codeAnimationExecution.test.js services/codeAnimation/containedWorker.test.js
+
+
gate:
name: CI Gate
if: always()
- needs: [impact, server, client, lint, database, windows-server, node-minimum]
+ needs: [impact, server, client, lint, database, windows-server, node-minimum, linux-containment]
runs-on: ubuntu-latest
timeout-minutes: 10
# READ, not write: the reporter only lists this run's jobs, to name the one
@@ -885,6 +914,7 @@ jobs:
CI_GATE_RESULT_DATABASE: ${{ needs.database.result }}
CI_GATE_RESULT_WINDOWS_SERVER: ${{ needs.windows-server.result }}
CI_GATE_RESULT_NODE_MINIMUM: ${{ needs.node-minimum.result }}
+ CI_GATE_RESULT_LINUX_CONTAINMENT: ${{ needs.linux-containment.result }}
run: node scripts/ci-gate-report.js
full-gate:
diff --git a/docs/CODE_ANIMATION_PACKAGES.md b/docs/CODE_ANIMATION_PACKAGES.md
index 1b1c7d4774..28e5b4fd18 100644
--- a/docs/CODE_ANIMATION_PACKAGES.md
+++ b/docs/CODE_ANIMATION_PACKAGES.md
@@ -106,7 +106,7 @@ research access belong to the authoring route, never to execution.
| Platform | Mechanism | Status |
|---|---|---|
| macOS | Seatbelt kernel sandbox (`/usr/bin/sandbox-exec`, deny-by-default profile) | Supported; proven on demand by the containment check |
-| Linux | None implemented (bubblewrap/user namespaces are the candidate) | Refused |
+| Linux x64 / arm64 | bubblewrap namespaces and seccomp | Requires executable `/usr/bin/bwrap`, permitted unprivileged user namespaces and seccomp; proven on demand |
| Windows | None implemented | Refused |
Each run gets a fresh UUID workspace under `data/code-animation-workspaces/`
@@ -133,6 +133,25 @@ memory (watchdog), open descriptors, no core dumps. Output that is not a
regular, singly-linked file (a symlink or hard link the worker made) fails the
run and is never handed to the caller.
+On Linux, bubblewrap starts from an empty filesystem, mounts only system/tool
+code and staged input read-only, and maps the three writable directories under
+`/workspace`. The synthetic root is read-only too, so it cannot become
+unmetered scratch space. PID, network, IPC, UTS and user namespaces isolate the
+worker; all capabilities are dropped. A seccomp filter denies process creation,
+network sockets and namespace changes while permitting native threads. The
+filter rejects unknown ABIs and makes `clone3` fall back to the older, flag-
+checked `clone` syscall. Cancellation kills the wrapper's process group;
+bubblewrap's parent-death handling tears down its PID namespace. Memory
+accounting includes the wrapper's descendants, not just the wrapper itself.
+
+A capability probe runs trusted system code to verify namespaces before any
+package is staged. Missing bubblewrap, unsupported architecture, restricted
+user namespaces (including Ubuntu AppArmor restrictions), or failure of the
+adversarial check keeps execution refused. PortOS never installs bubblewrap,
+changes host policy or falls back to an uncontained worker automatically.
+The dedicated Linux CI job requires a functioning real mechanism: unavailable
+bubblewrap fails that job instead of silently skipping its boundary tests.
+
Installed tools are operator-owned machine-local settings
(`codeAnimationExecution` in `data/settings.json`). Packages cannot name an
executable, install command or mount. A tool must be an existing absolute
diff --git a/server/lib/README.md b/server/lib/README.md
index 8b5b2ec645..3f047a69e3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -27,7 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `appDeployFlags.js` | Shared allowlist of flags PortOS may forward to a managed app's `deploy.sh`, consumed by socket validation and deployment orchestration without reversing the lib/services dependency. |
| `apiContractSchemas.js` | Canonical Zod request contracts for externally callable APIs plus `zodToOpenApiSchema` (plain JSON Schema — the 3.0.3 conversion happens at the OpenAPI document boundary, not here); runtime routes and OpenAPI use the same schema objects. |
-| `codeAnimationContainment.js` | Code Animation production worker containment contract: per-platform enforced mechanism (macOS Seatbelt, otherwise refusal), deny-by-default Seatbelt profile, from-scratch worker environment, operator tool-root rules, tool configuration and worker limit schemas. Pure; the runner is `services/codeAnimation/containedWorker.js`. |
+| `codeAnimationContainment.js` | Code Animation production worker containment contract: per-platform enforced mechanism (macOS Seatbelt or Linux bubblewrap, otherwise refusal), deny-by-default profiles and a process-denying Linux seccomp filter, from-scratch worker environment, operator tool-root rules, tool configuration and worker limit schemas. Pure; the runner is `services/codeAnimation/containedWorker.js`. |
| `codeAnimationPackage.js` | Versioned data-only Code Animation package schema, byte/path/reference integrity limits, SHA-256 revision binding, `createCodeAnimationPackage` and `summarizeCodeAnimationPackage`; validation never executes or stages code. |
| `socketEventContracts.js` | Payload contracts for modeled Socket.IO events, reusing live Zod validation for inbound events and documenting public outbound snapshots. |
| `socketEventInventory.js` | Cached source-derived Socket.IO event inventory: event names and directions only, with no checked-in manifest or positional source metadata. |
diff --git a/server/lib/codeAnimationContainment.js b/server/lib/codeAnimationContainment.js
index 2a99255a58..ed4f42b613 100644
--- a/server/lib/codeAnimationContainment.js
+++ b/server/lib/codeAnimationContainment.js
@@ -4,9 +4,8 @@
* A job directory is not a boundary. Generated or imported package code runs
* only under an enforced OS mechanism; when none is available execution is
* refused, never downgraded to an uncontained spawn. The supported mechanism
- * on this release is the macOS Seatbelt kernel sandbox (`sandbox-exec`), the
- * same one the private security assessment harness uses. Linux and Windows
- * report no mechanism and refuse.
+ * is macOS Seatbelt or Linux bubblewrap with a process-denying seccomp
+ * filter. Windows and hosts missing the prerequisites refuse.
*
* Pure: no filesystem, process or settings access.
*/
@@ -14,6 +13,7 @@ import { basename, dirname, isAbsolute, join, normalize, parse } from 'node:path
import { z } from 'zod';
export const CODE_ANIMATION_SEATBELT = '/usr/bin/sandbox-exec';
+export const CODE_ANIMATION_BUBBLEWRAP = '/usr/bin/bwrap';
/** Upper bounds a caller may request; defaults suit one preview render. */
export const codeAnimationWorkerLimitsSchema = z.object({
@@ -40,12 +40,17 @@ export const codeAnimationExecutionToolsSchema = z.object({
* The enforced mechanism for `platform`, or a refusal reason. `seatbeltAvailable`
* is whether `/usr/bin/sandbox-exec` is executable on this host.
*/
-export function codeAnimationContainmentMechanism(platform, seatbeltAvailable) {
+export function codeAnimationContainmentMechanism(platform, seatbeltAvailable, bubblewrap = null) {
if (platform === 'darwin') {
return seatbeltAvailable
? { id: 'macos-seatbelt', supported: true, reason: null }
: { id: null, supported: false, reason: 'macOS Seatbelt (/usr/bin/sandbox-exec) is unavailable on this host.' };
}
+ if (platform === 'linux') {
+ return bubblewrap?.supported
+ ? { id: 'linux-bubblewrap', supported: true, reason: null }
+ : { id: null, supported: false, reason: bubblewrap?.reason || 'Linux containment unavailable: bubblewrap and unrestricted user namespaces are required.' };
+ }
return {
id: null, supported: false,
reason: `No enforced worker containment is implemented for ${platform}. Production code execution is refused; package import/export and the browser preview sandbox remain available.`,
@@ -138,3 +143,70 @@ export function codeAnimationWorkerEnv(workspace) {
PORTOS_WORKER_OUTPUT: join(workspace, 'output'),
};
}
+
+/**
+ * Classic BPF seccomp program, using Linux UAPI syscall/audit constants.
+ * Native threads remain possible; fork/vfork and non-thread clone are denied.
+ * clone3 returns ENOSYS so libc can fall back to the inspectable clone flags.
+ * Unknown ABIs (including x32) fail closed instead of bypassing syscall checks.
+ * Applied by bwrap after its supervisor/namespace setup, before tool exec.
+ */
+export function codeAnimationSeccompFilter(arch) {
+ const abi = {
+ x64: { audit: 0xc000003e, clone: 56, denied: [57, 58, 41, 272, 308] },
+ arm64: { audit: 0xc00000b7, clone: 220, denied: [198, 97, 268] },
+ }[arch];
+ if (!abi) throw new Error('Linux worker seccomp supports only x64 and arm64.');
+ const ALLOW = 0x7fff0000, KILL = 0x80000000, EPERM = 0x00050001, ENOSYS = 0x00050026;
+ const instructions = [
+ [0x20, 0, 0, 4], // seccomp_data.arch
+ [0x15, 1, 0, abi.audit],
+ [0x06, 0, 0, KILL],
+ [0x20, 0, 0, 0], // seccomp_data.nr
+ [0x35, 0, 1, 0x40000000], // x32/invalid syscall range
+ [0x06, 0, 0, KILL],
+ [0x15, 0, 1, 435], // clone3
+ [0x06, 0, 0, ENOSYS],
+ ...abi.denied.flatMap((nr) => [[0x15, 0, 1, nr], [0x06, 0, 0, EPERM]]),
+ [0x15, 1, 0, abi.clone],
+ [0x06, 0, 0, ALLOW],
+ [0x20, 0, 0, 16], // clone flags, args[0] low word
+ [0x45, 0, 1, 0x7e020000], // namespace creation flags
+ [0x06, 0, 0, EPERM],
+ [0x45, 1, 0, 0x00010000], // CLONE_THREAD
+ [0x06, 0, 0, EPERM],
+ [0x06, 0, 0, ALLOW],
+ ];
+ const bytes = Buffer.alloc(instructions.length * 8);
+ instructions.forEach(([code, jt, jf, k], index) => {
+ bytes.writeUInt16LE(code, index * 8);
+ bytes[index * 8 + 2] = jt;
+ bytes[index * 8 + 3] = jf;
+ bytes.writeUInt32LE(k, index * 8 + 4);
+ });
+ return bytes;
+}
+
+/** Empty filesystem with only installed code, staged inputs and owned writes. */
+export function codeAnimationBubblewrapArgs({ executable, toolRoots, workspace, sandboxWorkspace = '/workspace', argv = [] }) {
+ const args = [
+ '--unshare-all', '--unshare-user', '--die-with-parent', '--new-session',
+ '--cap-drop', 'ALL', '--clearenv', '--seccomp', '3', '--info-fd', '4',
+ '--proc', '/proc', '--remount-ro', '/proc',
+ ];
+ // Never bind the host root, /etc, /run, /tmp or the user's home.
+ for (const root of new Set(['/usr/lib', '/usr/lib64', '/usr/share', '/lib', '/lib64', ...toolRoots])) {
+ args.push('--ro-bind-try', root, root);
+ }
+ for (const device of ['null', 'zero', 'random', 'urandom']) {
+ args.push('--dev-bind', `/dev/${device}`, `/dev/${device}`);
+ }
+ args.push('--ro-bind', join(workspace, 'input'), join(sandboxWorkspace, 'input'));
+ for (const name of ['output', 'tmp', 'home']) {
+ args.push('--bind', join(workspace, name), join(sandboxWorkspace, name));
+ }
+ for (const [key, value] of Object.entries(codeAnimationWorkerEnv(sandboxWorkspace))) args.push('--setenv', key, value);
+ // The synthetic root/ancestor directories must not become unmetered scratch.
+ args.push('--remount-ro', '/', '--chdir', join(sandboxWorkspace, 'tmp'), '--', executable, ...argv);
+ return args;
+}
diff --git a/server/lib/codeAnimationContainment.test.js b/server/lib/codeAnimationContainment.test.js
new file mode 100644
index 0000000000..ec9be6fd2c
--- /dev/null
+++ b/server/lib/codeAnimationContainment.test.js
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import { codeAnimationBubblewrapArgs, codeAnimationSeccompFilter } from './codeAnimationContainment.js';
+
+// Interpret the small classic-BPF instruction set this security filter uses.
+// This catches ABI bypasses and jump/offset mistakes even on non-Linux hosts.
+const verdict = (filter, { arch, nr, flags = 0 }) => {
+ const data = new Map([[0, nr], [4, arch], [16, flags]]);
+ let accumulator = 0;
+ for (let pc = 0; pc < filter.length / 8; pc += 1) {
+ const offset = pc * 8;
+ const code = filter.readUInt16LE(offset);
+ const value = filter.readUInt32LE(offset + 4);
+ if (code === 0x20) accumulator = data.get(value) ?? 0;
+ else if (code === 0x06) return value;
+ else {
+ const match = code === 0x15 ? accumulator === value
+ : code === 0x35 ? accumulator >= value
+ : (accumulator & value) !== 0;
+ pc += filter[offset + (match ? 2 : 3)];
+ }
+ }
+ throw new Error('Filter did not return a verdict');
+};
+
+describe('Linux worker containment policy', () => {
+ it.each([
+ ['x64', 0xc000003e, 56, [57, 58, 41, 272, 308]],
+ ['arm64', 0xc00000b7, 220, [198, 97, 268]],
+ ])('denies process creation, sockets and namespace escape on %s while preserving threads', (name, arch, clone, denied) => {
+ const filter = codeAnimationSeccompFilter(name);
+ const run = (nr, flags = 0) => verdict(filter, { arch, nr, flags });
+ for (const nr of denied) expect(run(nr)).toBe(0x00050001);
+ expect(run(clone, 17)).toBe(0x00050001); // SIGCHLD: ordinary process
+ expect(run(clone, 0x00010000)).toBe(0x7fff0000); // native thread
+ expect(run(clone, 0x10010000)).toBe(0x00050001); // thread + new user namespace
+ expect(run(435)).toBe(0x00050026); // clone3 must fall back to clone
+ expect(run(0x40000000)).toBe(0x80000000); // x32
+ expect(verdict(filter, { arch: 0x40000003, nr: 2 })).toBe(0x80000000); // i386 fork
+ expect(run(1)).toBe(0x7fff0000);
+ });
+
+ it('refuses unknown architectures and never grants the host root or ambient writable scratch', () => {
+ expect(() => codeAnimationSeccompFilter('riscv64')).toThrow(/x64 and arm64/);
+ const args = codeAnimationBubblewrapArgs({
+ executable: '/opt/example/bin/tool',
+ toolRoots: ['/opt/example/lib', '/opt/example/bin'],
+ workspace: '/tmp/example-worker',
+ argv: ['/workspace/input/scene.py'],
+ });
+ const grants = [];
+ for (let index = 0; index < args.length; index += 1) {
+ if (['--bind', '--ro-bind', '--ro-bind-try', '--dev-bind'].includes(args[index])) {
+ grants.push(args.slice(index, index + 3));
+ }
+ }
+ expect(grants.filter(([kind]) => kind === '--bind')).toEqual(
+ ['output', 'tmp', 'home'].map((name) => ['--bind', '/tmp/example-worker/' + name, '/workspace/' + name]),
+ );
+ expect(grants.some(([, source]) => ['/', '/etc', '/run', '/home', '/tmp'].includes(source))).toBe(false);
+ expect(args).toContain('--clearenv');
+ expect(args).toContain('--unshare-all');
+ expect(args).toContain('--seccomp');
+ expect(args.slice(-7)).toEqual(['--remount-ro', '/', '--chdir', '/workspace/tmp', '--', '/opt/example/bin/tool', '/workspace/input/scene.py']);
+ });
+});
diff --git a/server/routes/codeAnimationExecution.test.js b/server/routes/codeAnimationExecution.test.js
index 442e6e7df8..a93f25fc2a 100644
--- a/server/routes/codeAnimationExecution.test.js
+++ b/server/routes/codeAnimationExecution.test.js
@@ -1,13 +1,12 @@
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
-import { existsSync } from 'node:fs';
import { chmod, mkdir, mkdtemp, readdir, realpath, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
-import { CODE_ANIMATION_SEATBELT } from '../lib/codeAnimationContainment.js';
+import { currentContainmentMechanism } from '../services/codeAnimation/containedWorker.js';
const { settings } = vi.hoisted(() => ({ settings: { current: {} } }));
vi.mock('../lib/paths.js', async (importOriginal) =>
@@ -26,7 +25,11 @@ const app = express();
app.use(express.json());
app.use('/api/code-animation/execution', router);
app.use(errorMiddleware);
-const seatbelt = process.platform === 'darwin' && existsSync(CODE_ANIMATION_SEATBELT);
+const mechanism = await currentContainmentMechanism();
+const supported = mechanism.supported;
+if (process.env.PORTOS_REQUIRE_LINUX_CONTAINMENT === '1' && mechanism.id !== 'linux-bubblewrap') {
+ throw new Error(`Real Linux containment is required by this test job: ${mechanism.reason}`);
+}
const scratch = [];
afterAll(async () => {
cleanupTempDataRoots();
@@ -49,8 +52,8 @@ describe('Code Animation execution capability', () => {
expect(body.probe).toBeNull();
expect(body.lanes.blender.ready).toBe(false);
expect(body.lanes.browser.mechanism).toBe('chromium-cdp-sandbox');
- expect(body.mechanism.supported).toBe(seatbelt);
- if (!seatbelt) expect(body.mechanism.reason).toMatch(/refused|unavailable/);
+ expect(body.mechanism.supported).toBe(supported);
+ if (!supported) expect(body.mechanism.reason).toMatch(/refused|unavailable/);
});
it('accepts only an operator tool that cannot expose PortOS data, and stores its realpath', async () => {
@@ -74,7 +77,7 @@ describe('Code Animation execution capability', () => {
expect(settings.current.codeAnimationExecution).toEqual({ blender: { executable: null } });
});
- it.skipIf(seatbelt)('refuses the containment check where no enforced mechanism exists', async () => {
+ it.skipIf(supported)('refuses the containment check where no enforced mechanism exists', async () => {
const { body } = await request(app).post('/api/code-animation/execution/probe');
expect(body.probe).toMatchObject({ passed: false, mechanism: null, checks: [] });
expect(body.probe.refused).toMatch(/refused|unavailable/);
@@ -83,7 +86,7 @@ describe('Code Animation execution capability', () => {
// Actual mechanism evidence: synthetic hostile packages run through the real
// Seatbelt worker, and each boundary/limit is observed failing for them.
- it.skipIf(!seatbelt)('proves the macOS Seatbelt boundary and limits, and keeps a tool that cannot start contained refused', async () => {
+ it.skipIf(!supported)('proves the host containment boundary and limits, and keeps a tool that cannot start contained refused', async () => {
const dir = await mkdtemp(join(tmpdir(), 'portos-tool-'));
scratch.push(dir);
// A script tool needs /bin/sh, which the worker profile does not grant.
@@ -91,7 +94,7 @@ describe('Code Animation execution capability', () => {
const { status, body } = await request(app).post('/api/code-animation/execution/probe');
expect(status).toBe(200);
- expect(body.probe.mechanism).toBe('macos-seatbelt');
+ expect(body.probe.mechanism).toBe(mechanism.id);
expect(Object.fromEntries(body.probe.checks.map((check) => [check.id, check.passed]))).toEqual({
'worker-runs': true, 'read-outside': true, 'list-data': true, 'list-home': true, 'write-outside': true,
'write-input': true, 'spawn-process': true, 'file-size': true, credentials: true, 'host-api': true, network: true,
diff --git a/server/services/codeAnimation/containedWorker.js b/server/services/codeAnimation/containedWorker.js
index feafec8489..2e7f6993d0 100644
--- a/server/services/codeAnimation/containedWorker.js
+++ b/server/services/codeAnimation/containedWorker.js
@@ -6,7 +6,7 @@
* what the worker left behind. No uncontained fallback exists.
*/
import { constants } from 'node:fs';
-import { access, lstat, mkdir, open, readdir, realpath, rm } from 'node:fs/promises';
+import { access, lstat, mkdir, open, readFile, readdir, realpath, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { promisify } from 'node:util';
@@ -14,7 +14,8 @@ import { ServerError } from '../../lib/errorHandler.js';
import { execFile, spawn } from '../../lib/childProcess.js';
import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
import {
- CODE_ANIMATION_SEATBELT, codeAnimationContainmentMechanism, codeAnimationSeatbeltProfile,
+ CODE_ANIMATION_SEATBELT, CODE_ANIMATION_BUBBLEWRAP, codeAnimationContainmentMechanism, codeAnimationSeatbeltProfile,
+ codeAnimationBubblewrapArgs, codeAnimationSeccompFilter,
codeAnimationToolRoots, codeAnimationWorkerEnv, codeAnimationWorkerLimitsSchema,
} from '../../lib/codeAnimationContainment.js';
@@ -27,9 +28,32 @@ const swept = new Set();
const canExecute = (path) => access(path, constants.X_OK).then(() => true, () => false);
-/** The enforced mechanism for this host, probing only that the sandbox binary is executable. */
-export async function currentContainmentMechanism(seatbeltPath = CODE_ANIMATION_SEATBELT) {
- return codeAnimationContainmentMechanism(process.platform, process.platform === 'darwin' && await canExecute(seatbeltPath));
+/**
+ * Probe namespaces with trusted system code only. A binary's presence does not
+ * prove that kernel/user-namespace or AppArmor policy allows containment.
+ */
+export async function currentContainmentMechanism(seatbeltPath = CODE_ANIMATION_SEATBELT, bubblewrapPath = CODE_ANIMATION_BUBBLEWRAP) {
+ if (process.platform !== 'linux') {
+ return codeAnimationContainmentMechanism(process.platform, process.platform === 'darwin' && await canExecute(seatbeltPath));
+ }
+ if (!['x64', 'arm64'].includes(process.arch)) {
+ return codeAnimationContainmentMechanism('linux', false, { reason: 'Linux containment unavailable: seccomp requires x64 or arm64.' });
+ }
+ if (!(await canExecute(bubblewrapPath))) {
+ return codeAnimationContainmentMechanism('linux', false, { reason: 'Linux containment unavailable: install bubblewrap (/usr/bin/bwrap).' });
+ }
+ if (!(await canExecute('/bin/bash'))) {
+ return codeAnimationContainmentMechanism('linux', false, { reason: 'Linux containment unavailable: /bin/bash is required for consistent resource-limit units.' });
+ }
+ const supported = await execFileAsync(bubblewrapPath, [
+ '--unshare-all', '--unshare-user', '--die-with-parent', '--new-session', '--cap-drop', 'ALL',
+ '--clearenv', '--ro-bind', '/usr', '/usr', '--ro-bind-try', '/lib', '/lib', '--ro-bind-try', '/lib64', '/lib64',
+ '--', '/usr/bin/true',
+ ], { cwd: '/', env: {}, timeout: 5000, maxBuffer: 4096 }).then(() => true, () => false);
+ return codeAnimationContainmentMechanism('linux', false, {
+ supported,
+ reason: 'Linux containment unavailable: bubblewrap could not create namespaces. Check unprivileged user namespaces and the host AppArmor policy.',
+ });
}
// A crash leaves its workspace behind; nothing else may own a UUID entry here.
@@ -88,14 +112,29 @@ async function measure(dirs, { maxFiles }) {
}
async function residentBytes(pid) {
+ if (process.platform === 'linux') {
+ // bwrap supervises a separate PID namespace; its own RSS is not the tool's.
+ // Walk host-visible descendants, including the namespace init and worker.
+ const readProc = (path) => readFile(path, 'utf8').catch((error) => {
+ if (error.code === 'ENOENT' || error.code === 'ESRCH') return '';
+ throw error;
+ });
+ const [status, children] = await Promise.all([
+ readProc(`/proc/${pid}/status`), readProc(`/proc/${pid}/task/${pid}/children`),
+ ]);
+ const own = Number(status.match(/^VmRSS:\s+(\d+)/m)?.[1] || 0) * 1024;
+ const descendants = await Promise.all(children.trim().split(/\s+/).filter(Boolean).map((child) => residentBytes(Number(child))));
+ return own + descendants.reduce((sum, bytes) => sum + bytes, 0);
+ }
const { stdout } = await execFileAsync('/bin/ps', ['-o', 'rss=', '-p', String(pid)]).catch(() => ({ stdout: '' }));
const kib = Number.parseInt(stdout.trim(), 10);
return Number.isFinite(kib) ? kib * 1024 : 0;
}
-function groupAlive(pgid) {
- try { process.kill(-pgid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
+function processAlive(pid) {
+ try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
}
+const groupAlive = (pgid) => processAlive(-pgid);
const tail = () => {
let text = '';
@@ -111,9 +150,9 @@ const tail = () => {
*/
export async function runContainedWorker({
tool, files = [], entrypoint = null, limits: requested = {}, signal, workspaceRoot,
- onOutput, tickMs = 1000, seatbeltPath = CODE_ANIMATION_SEATBELT,
+ onOutput, tickMs = 1000, seatbeltPath = CODE_ANIMATION_SEATBELT, bubblewrapPath = CODE_ANIMATION_BUBBLEWRAP,
}) {
- const mechanism = await currentContainmentMechanism(seatbeltPath);
+ const mechanism = await currentContainmentMechanism(seatbeltPath, bubblewrapPath);
if (!mechanism.supported) {
throw new ServerError(`Contained execution refused: ${mechanism.reason}`, { status: 503, code: 'CODE_ANIMATION_CONTAINMENT_UNAVAILABLE' });
}
@@ -135,15 +174,29 @@ export async function runContainedWorker({
for (const name of ['input', 'output', 'tmp', 'home']) await mkdir(join(workspace, name), { mode: 0o700 });
await stage(join(workspace, 'input'), files);
const writable = ['output', 'tmp', 'home'].map((name) => join(workspace, name));
- const profile = codeAnimationSeatbeltProfile({ executable, toolRoots: codeAnimationToolRoots(executable), workspace });
- const argv = tool.argv(entrypoint === null ? null : join(workspace, 'input', entrypoint), workspace);
- // RLIMIT_FSIZE caps any single file (macOS sh counts 1 KiB blocks), no core
- // dumps, bounded descriptors. `exec` keeps one pid: sh → sandbox-exec → tool.
- const child = spawn('/bin/sh', ['-c', 'ulimit -c 0 && ulimit -n "$1" && ulimit -f "$2" && shift 2 && exec "$@"',
+ const linux = mechanism.id === 'linux-bubblewrap';
+ const sandboxWorkspace = linux ? '/workspace' : workspace;
+ const argv = tool.argv(entrypoint === null ? null : join(sandboxWorkspace, 'input', entrypoint), sandboxWorkspace);
+ const config = { executable, toolRoots: codeAnimationToolRoots(executable), workspace, sandboxWorkspace, argv };
+ const wrapper = linux
+ ? [bubblewrapPath, ...codeAnimationBubblewrapArgs(config)]
+ : [seatbeltPath, '-p', codeAnimationSeatbeltProfile(config), executable, ...argv];
+ // Explicit bash on Linux avoids /bin/sh's distro-dependent ulimit units.
+ // Both this bash invocation and macOS sh count KiB; limits survive exec.
+ const child = spawn(linux ? '/bin/bash' : '/bin/sh', ['-c', 'ulimit -c 0 && ulimit -n "$1" && ulimit -f "$2" && shift 2 && exec "$@"',
'portos-contained-worker', String(limits.openFiles), String(Math.max(1, Math.floor(limits.diskBytes / 1024))),
- seatbeltPath, '-p', profile, executable, ...argv], {
- cwd: join(workspace, 'tmp'), env: withSpawnCwdEnv(codeAnimationWorkerEnv(workspace), join(workspace, 'tmp')), detached: true, stdio: ['ignore', 'pipe', 'pipe'],
+ ...wrapper], {
+ cwd: join(workspace, 'tmp'), env: withSpawnCwdEnv(codeAnimationWorkerEnv(workspace), join(workspace, 'tmp')),
+ detached: true, stdio: linux ? ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'],
});
+ const namespaceInfo = tail();
+ if (linux) {
+ child.stdio[4].on('data', namespaceInfo.push);
+ // bwrap consumes/closes fd 3 before tool exec. A refused setup can close
+ // the pipe early; that is reported through the worker's nonzero exit.
+ child.stdio[3].on('error', () => {});
+ child.stdio[3].end(codeAnimationSeccompFilter(process.arch));
+ }
const stdout = tail();
const stderr = tail();
child.stdout.on('data', stdout.push);
@@ -178,13 +231,19 @@ export async function runContainedWorker({
clearTimeout(timer);
clearInterval(watchdog);
signal?.removeEventListener('abort', onAbort);
- // The worker cannot fork, but the group is still verified empty, and any
+ // The worker cannot fork; bwrap also owns its PID namespace and uses
+ // die-with-parent. The outer group is still verified empty, and any
// straggler is killed before the run is reported.
- let processGroupClear = !groupAlive(child.pid);
+ // --new-session moves the namespace child out of the outer process group.
+ // bwrap's info fd names that host PID before allowing it to run; verify it
+ // too, so an empty launcher group cannot masquerade as completed teardown.
+ const namespacePid = linux ? Number(namespaceInfo.get().match(/"child-pid":\s*(\d+)/)?.[1]) : null;
+ const cleared = () => !groupAlive(child.pid) && (!namespacePid || !processAlive(namespacePid));
+ let processGroupClear = cleared();
for (let attempt = 0; !processGroupClear && attempt < 20; attempt += 1) {
try { process.kill(-child.pid, 'SIGKILL'); } catch { /* gone */ }
await new Promise((resolve) => setTimeout(resolve, 50));
- processGroupClear = !groupAlive(child.pid);
+ processGroupClear = cleared();
}
if (exit.signal === 'SIGXFSZ') terminated ??= 'file-size';
const usage = await measure(writable, limits);
@@ -195,6 +254,7 @@ export async function runContainedWorker({
if (terminated) { status = 'terminated'; reason = terminated; }
else if (exit.error || exit.code !== 0) { status = 'failed'; reason = exit.error ? 'spawn' : 'exit'; }
else if (usage.invalid.length) { status = 'failed'; reason = 'output-invalid'; }
+ else if (!processGroupClear || (linux && !namespacePid)) { status = 'failed'; reason = 'containment-status'; }
const result = {
status, reason, mechanism: mechanism.id, exitCode: exit.code, signal: exit.signal,
processGroupClear, durationMs: Date.now() - started, limits,
diff --git a/server/services/codeAnimation/containedWorker.test.js b/server/services/codeAnimation/containedWorker.test.js
index cbd08ce9e3..ed4d180e80 100644
--- a/server/services/codeAnimation/containedWorker.test.js
+++ b/server/services/codeAnimation/containedWorker.test.js
@@ -1,15 +1,17 @@
import { afterAll, describe, expect, it } from 'vitest';
-import { existsSync } from 'node:fs';
import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { CODE_ANIMATION_SEATBELT } from '../../lib/codeAnimationContainment.js';
-import { runContainedWorker } from './containedWorker.js';
+import { currentContainmentMechanism, runContainedWorker } from './containedWorker.js';
// Real-mechanism suite: these run only where the enforced sandbox exists. The
// adversarial boundary and limit checks run end to end through the probe route
// (routes/codeAnimationExecution.test.js); this file pins the worker lifecycle.
-const seatbelt = process.platform === 'darwin' && existsSync(CODE_ANIMATION_SEATBELT);
+const mechanism = await currentContainmentMechanism();
+const supported = mechanism.supported;
+if (process.env.PORTOS_REQUIRE_LINUX_CONTAINMENT === '1' && mechanism.id !== 'linux-bubblewrap') {
+ throw new Error(`Real Linux containment is required by this test job: ${mechanism.reason}`);
+}
const roots = [];
const workspaceRoot = async () => {
const root = await mkdtemp(join(tmpdir(), 'portos-contained-worker-'));
@@ -20,18 +22,45 @@ const node = (extra = []) => ({ executable: process.execPath, argv: (entry) => [
afterAll(async () => { await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); });
describe('contained worker refusal', () => {
+ it.skipIf(process.platform !== 'linux')('refuses a present wrapper that cannot create namespaces before staging', async () => {
+ const root = await workspaceRoot();
+ await expect(runContainedWorker({
+ tool: node(), workspaceRoot: root, bubblewrapPath: '/usr/bin/false',
+ })).rejects.toMatchObject({ code: 'CODE_ANIMATION_CONTAINMENT_UNAVAILABLE', message: expect.stringContaining('user namespaces') });
+ expect(await readdir(root)).toEqual([]);
+ });
+
+
it('refuses with no enforced mechanism and creates no workspace', async () => {
const root = await workspaceRoot();
await expect(runContainedWorker({
tool: node(), workspaceRoot: root, entrypoint: 'main.cjs',
files: [{ path: 'main.cjs', content: 'require("fs").writeFileSync("/tmp/never", "x")' }],
seatbeltPath: join(root, 'missing-sandbox-exec'),
+ bubblewrapPath: join(root, 'missing-bwrap'),
})).rejects.toMatchObject({ status: 503, code: 'CODE_ANIMATION_CONTAINMENT_UNAVAILABLE' });
expect(await readdir(root)).toEqual([]);
});
});
-describe.skipIf(!seatbelt)('contained worker lifecycle under macOS Seatbelt', () => {
+describe.skipIf(!supported)('contained worker lifecycle under the real host sandbox', () => {
+ it('allows native worker threads to complete without granting subprocess creation', async () => {
+ const root = await workspaceRoot();
+ const result = await runContainedWorker({
+ tool: node(), workspaceRoot: root, entrypoint: 'main.cjs',
+ files: [{ path: 'main.cjs', content: `
+const { Worker } = require('worker_threads');
+const worker = new Worker('require("worker_threads").parentPort.postMessage("thread complete")', { eval: true });
+worker.on('message', (value) => console.log(value));
+worker.on('error', () => process.exit(1));
+` }],
+ });
+ expect(result).toMatchObject({ status: 'completed', processGroupClear: true });
+ expect(result.stdout).toContain('thread complete');
+ expect(await readdir(root)).toEqual([]);
+ });
+
+
it('stages input read-only, collects regular output files, then removes the workspace', async () => {
const root = await workspaceRoot();
let collected = null;
@@ -43,7 +72,7 @@ describe.skipIf(!seatbelt)('contained worker lifecycle under macOS Seatbelt', ()
],
onOutput: async (dir, outputs) => { collected = { outputs, body: await readFile(join(dir, 'frames/0001.txt'), 'utf8') }; },
});
- expect(result).toMatchObject({ status: 'completed', mechanism: 'macos-seatbelt', exitCode: 0, processGroupClear: true });
+ expect(result).toMatchObject({ status: 'completed', mechanism: mechanism.id, exitCode: 0, processGroupClear: true });
expect(result.stdout).toContain('rendered');
expect(collected).toEqual({ outputs: [{ path: 'frames/0001.txt', bytes: 5 }], body: 'frame' });
expect(await readdir(root)).toEqual([]);
diff --git a/server/services/codeAnimation/execution.js b/server/services/codeAnimation/execution.js
index 75190f41fa..5031fe9375 100644
--- a/server/services/codeAnimation/execution.js
+++ b/server/services/codeAnimation/execution.js
@@ -152,7 +152,9 @@ const LIMIT_SCRIPTS = {
// sandbox, environment and limits, running synthetic hostile scripts.
const probeTool = (extra = []) => ({ executable: process.execPath, argv: (entry) => [entry, ...extra] });
-const denied = (result, code = 'EPERM') => result && result.allowed === false && result.code === code;
+// Seatbelt denies access; a bubblewrap filesystem instead hides unmounted
+// paths (ENOENT) and exposes read-only binds (EROFS).
+const denied = (result) => result && result.allowed === false && ['EPERM', 'EACCES', 'ENOENT', 'EROFS'].includes(result.code);
async function probeBoundary(workspaceRoot) {
const scratch = await mkdtemp(join(tmpdir(), 'portos-containment-canary-'));
@@ -181,7 +183,7 @@ async function probeBoundary(workspaceRoot) {
{ id: 'list-home', passed: denied(report.listHome), detail: 'The home directory could not be listed.' },
{ id: 'write-outside', passed: denied(report.writeOutside), detail: 'Nothing could be written outside the workspace.' },
{ id: 'write-input', passed: denied(report.writeInput), detail: 'Staged input is read-only.' },
- { id: 'spawn-process', passed: denied(report.spawnProcess), detail: 'No shell, installer or other process could be started.' },
+ { id: 'spawn-process', passed: report.spawnProcess?.allowed === false && report.spawnProcess.code === 'EPERM', detail: 'No shell, installer or other process could be started.' },
{ id: 'file-size', passed: report.oversizedFile?.allowed === false, detail: 'A single file larger than the disk limit could not be written.' },
{ id: 'credentials', passed: Array.isArray(report.envKeys) && inherited.length === 0, detail: inherited.length ? `Unexpected inherited variables: ${inherited.length}.` : 'The environment contained only the worker’s own paths; no PortOS token or credential was inherited.' },
{ id: 'host-api', passed: denied(report.loopback) && connections === 0, detail: 'Loopback (where PortOS and local services listen) was unreachable.' },