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

fix: block host Unix sockets and extra writable roots in autofixer repairs (#12487)

[._.]/ Adam Eivy475d13832ae9
diff --git a/autofixer/sandbox.js b/autofixer/sandbox.js
index 8495980b7c..a7fdce99f4 100644
--- a/autofixer/sandbox.js
+++ b/autofixer/sandbox.js
@@ -41,6 +41,7 @@ import {
} from '../server/lib/codeAnimationContainment.js';
import {
autofixVerifyBubblewrapArgs, autofixVerifyEnv, autofixVerifyProtectedPaths, autofixVerifySeatbeltProfile,
+ autofixVerifySeccompFilter,
} from '../server/lib/autofixVerifyContainment.js';
// ---------------------------------------------------------------------------
@@ -472,6 +473,9 @@ export async function probeVerifyContainment() {
return codeAnimationContainmentMechanism('darwin', await canExecute(CODE_ANIMATION_SEATBELT));
}
if (process.platform !== 'linux') return codeAnimationContainmentMechanism(process.platform, false);
+ if (!['x64', 'arm64'].includes(process.arch)) {
+ return codeAnimationContainmentMechanism('linux', false, { reason: 'the verify seccomp filter requires x64 or arm64' });
+ }
if (!(await canExecute(CODE_ANIMATION_BUBBLEWRAP))) {
return codeAnimationContainmentMechanism('linux', false, { reason: 'install bubblewrap (/usr/bin/bwrap) to verify autofixes' });
}
@@ -487,13 +491,15 @@ export async function probeVerifyContainment() {
// Run a contained command as its own process group so a timeout reaches every
// process the test runner started, not just the sandbox launcher.
-function runGroup(file, args, { cwd, env, timeoutMs }) {
+function runGroup(file, args, { cwd, env, timeoutMs, seccomp = null }) {
return new Promise((resolve) => {
let output = '';
let settled = false;
let child;
try {
- child = spawn(file, args, { cwd, env, detached: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ child = spawn(file, args, {
+ cwd, env, detached: true, windowsHide: true, stdio: seccomp ? ['ignore', 'pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'],
+ });
} catch (err) {
resolve({ ok: false, code: -1, output: `[verify] ${err.message}` });
return;
@@ -506,6 +512,12 @@ function runGroup(file, args, { cwd, env, timeoutMs }) {
killGroup();
done({ ok: false, code: -1, output: `${output}\n[verify] timed out after ${timeoutMs}ms` });
}, timeoutMs);
+ if (seccomp) {
+ // bwrap reads the filter from fd 3; a refused setup can close it early,
+ // which surfaces as bwrap's nonzero exit.
+ child.stdio[3].on('error', () => {});
+ child.stdio[3].end(seccomp);
+ }
child.stdout?.on('data', (d) => { output += d.toString(); });
child.stderr?.on('data', (d) => { output += d.toString(); });
child.on('error', (err) => done({ ok: false, code: -1, output: `${output}\n[verify] ${err.message}` }));
@@ -519,7 +531,7 @@ function runGroup(file, args, { cwd, env, timeoutMs }) {
* command string is trusted config, but the files it executes (tests, npm
* lifecycle scripts) were just written by an agent driven by untrusted logs,
* so it runs only under OS containment (`autofixVerifyContainment.js`): no
- * network, writes confined to the worktree and a private scratch dir, no reads
+ * network or host Unix sockets, writes confined to the worktree and a private scratch dir, no reads
* of the PortOS data directory or host credential stores, and an environment
* built from nothing — no provider key or PortOS token. Without an enforced
* mechanism the verify is refused, which blocks promotion.
@@ -550,9 +562,11 @@ export async function runVerifyCommand(command, cwd, { dataDir = null, timeoutMs
const env = autofixVerifyEnv({ scratch, path: process.env.PATH });
const shell = ['/bin/sh', '-c', command];
let launch;
+ let seccomp = null;
if (mechanism.id === 'macos-seatbelt') {
launch = [CODE_ANIMATION_SEATBELT, ['-p', autofixVerifySeatbeltProfile({ worktree, scratch, protectedPaths }), ...shell]];
} else {
+ seccomp = autofixVerifySeccompFilter(process.arch);
const present = await Promise.all(protectedPaths.map(async (path) => [path, await stat(path).catch(() => null)]));
const bwrapArgs = autofixVerifyBubblewrapArgs({
worktree, scratch, env,
@@ -561,7 +575,7 @@ export async function runVerifyCommand(command, cwd, { dataDir = null, timeoutMs
});
launch = [CODE_ANIMATION_BUBBLEWRAP, [...bwrapArgs, ...shell]];
}
- const result = await runGroup(launch[0], launch[1], { cwd: worktree, env, timeoutMs });
+ const result = await runGroup(launch[0], launch[1], { cwd: worktree, env, timeoutMs, seccomp });
return { ...result, contained: true, mechanism: mechanism.id };
} finally {
await rm(scratchDir, { recursive: true, force: true }).catch(() => {});
diff --git a/autofixer/sandbox.test.js b/autofixer/sandbox.test.js
index 61620a68f6..e3994ebd87 100644
--- a/autofixer/sandbox.test.js
+++ b/autofixer/sandbox.test.js
@@ -169,8 +169,8 @@ describe('buildFixPrompt — untrusted log fencing', () => {
});
describe('pickRepairProvider — only an enforced restricted mode runs a repair', () => {
- const claude = { id: 'claude-code', type: 'cli', command: 'claude', args: ['--print', '--dangerously-skip-permissions', '--allowedTools', 'Bash'] };
- const codex = { id: 'codex', type: 'cli', command: 'codex', args: ['--dangerously-bypass-approvals-and-sandbox', '--sandbox', 'danger-full-access'] };
+ const claude = { id: 'claude-code', type: 'cli', command: 'claude', args: ['--print', '--dangerously-skip-permissions', '--allowedTools', 'Bash', '--add-dir', '/example/live'] };
+ const codex = { id: 'codex', type: 'cli', command: 'codex', args: ['--dangerously-bypass-approvals-and-sandbox', '--sandbox', 'danger-full-access', '--add-dir', '/example/live', '-C', '/example/live'] };
const gemini = { id: 'gemini-cli', type: 'cli', command: 'gemini', args: ['--yolo'] };
const agy = { id: 'antigravity-cli', type: 'cli', command: 'agy', args: ['--print', '--dangerously-skip-permissions'] };
// The argv the runner actually spawns: buildCliArgs over the restricted clone.
@@ -193,6 +193,7 @@ describe('pickRepairProvider — only an enforced restricted mode runs a repair'
const argv = spawnedArgv(picked);
expect(argv).not.toContain('--dangerously-skip-permissions');
expect(argv).not.toContain('--allowedTools');
+ expect(argv).not.toContain('/example/live');
expect(argv.join(' ')).toContain('--permission-mode acceptEdits');
expect(argv.join(' ')).toContain('--setting-sources user');
expect(argv.join(' ')).toContain('--disallowedTools Bash WebFetch WebSearch');
@@ -206,7 +207,8 @@ describe('pickRepairProvider — only an enforced restricted mode runs a repair'
expect(argv[0]).toBe('exec');
expect(argv).not.toContain('--dangerously-bypass-approvals-and-sandbox');
expect(argv).not.toContain('danger-full-access');
- expect(argv.join(' ')).toContain('--sandbox workspace-write -c sandbox_workspace_write.network_access=false');
+ expect(argv).not.toContain('/example/live');
+ expect(argv.join(' ')).toContain('--sandbox workspace-write -c sandbox_workspace_write.network_access=false -c sandbox_workspace_write.writable_roots=[]');
expect(argv.at(-1)).toBe('-');
});
});
diff --git a/autofixer/sandbox.verify.test.js b/autofixer/sandbox.verify.test.js
index 7332c0855d..db59891043 100644
--- a/autofixer/sandbox.verify.test.js
+++ b/autofixer/sandbox.verify.test.js
@@ -15,9 +15,13 @@ describe.skipIf(!mechanism.supported)(`runVerifyCommand under ${mechanism.id ||
let outside;
let server;
let port;
+ let unixServer;
+ let socketPath;
beforeAll(async () => {
- root = await mkdtemp(join(tmpdir(), 'autofix-verify-real-'));
+ // Linux hides /tmp and /run behind tmpfs; /var/tmp keeps the socket below
+ // reachable through the read-only root, so the seccomp filter is what's tested.
+ root = await mkdtemp(join(process.platform === 'linux' ? '/var/tmp' : tmpdir(), 'autofix-verify-real-'));
dataDir = join(root, 'data');
worktree = join(dataDir, 'autofixer', 'worktrees', 'example');
outside = join(root, 'outside');
@@ -27,11 +31,16 @@ describe.skipIf(!mechanism.supported)(`runVerifyCommand under ${mechanism.id ||
server = createServer((socket) => socket.end('reached'));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
port = server.address().port;
+ // A host pathname socket (Docker, a database) outside every writable root.
+ socketPath = join(outside, 's.sock');
+ unixServer = createServer((socket) => socket.end('reached'));
+ await new Promise((resolve) => unixServer.listen(socketPath, resolve));
});
afterAll(async () => {
vi.unstubAllEnvs();
await new Promise((resolve) => server.close(resolve));
+ await new Promise((resolve) => unixServer.close(resolve));
await rm(root, { recursive: true, force: true });
});
@@ -53,6 +62,8 @@ describe.skipIf(!mechanism.supported)(`runVerifyCommand under ${mechanism.id ||
expect(result.output).not.toMatch(new RegExp(`^HOME=${process.env.HOME}$`, 'm'));
});
+ const connectProbe = (target) => `${JSON.stringify(process.execPath)} -e "require('net').connect(${target}).on('data', (d) => { console.log(String(d)); process.exit(0); }).on('error', () => process.exit(3))"`;
+
it('cannot write outside the worktree, read the PortOS data directory, or reach loopback', async () => {
const write = await verify(`echo x > ${JSON.stringify(join(outside, 'escaped'))}`);
expect(write.ok).toBe(false);
@@ -62,8 +73,14 @@ describe.skipIf(!mechanism.supported)(`runVerifyCommand under ${mechanism.id ||
expect(read.ok).toBe(false);
expect(read.output).not.toContain('example-provider-key');
- const net = await verify(`${JSON.stringify(process.execPath)} -e "require('net').connect(${port}, '127.0.0.1').on('data', (d) => { console.log(String(d)); process.exit(0); }).on('error', () => process.exit(3))"`);
+ const net = await verify(connectProbe(`${port}, '127.0.0.1'`));
expect(net.ok).toBe(false);
expect(net.output).not.toContain('reached');
});
+
+ it('cannot connect to a host pathname Unix socket', async () => {
+ const unix = await verify(connectProbe(`'${socketPath}'`));
+ expect(unix.ok).toBe(false);
+ expect(unix.output).not.toContain('reached');
+ });
});
diff --git a/server/lib/autofixVerifyContainment.js b/server/lib/autofixVerifyContainment.js
index f58ae3df68..ac0f581d44 100644
--- a/server/lib/autofixVerifyContainment.js
+++ b/server/lib/autofixVerifyContainment.js
@@ -7,7 +7,9 @@
* (`codeAnimationContainment.js`) cannot host it; this profile keeps the same
* mechanisms (macOS Seatbelt, Linux bubblewrap, refusal elsewhere) with these
* bounds instead:
- * - no network, including loopback and Unix sockets (PortOS's API);
+ * - no network, including loopback and pathname Unix sockets (PortOS's API,
+ * a Docker or database socket): Seatbelt denies them, and on Linux a
+ * network namespace plus a seccomp filter refusing AF_UNIX sockets;
* - writes only to the worktree and a private scratch home/tmp;
* - no reads of the PortOS data directory (providers, settings, keys) or the
* host user's credential stores; the rest of the host stays readable so
@@ -19,7 +21,7 @@
* Pure: no filesystem, process or settings access. Paths must be realpaths.
*/
import { join, posix } from 'node:path';
-import { seatbeltPathLiteral } from './codeAnimationContainment.js';
+import { encodeSeccompProgram, seatbeltPathLiteral } from './codeAnimationContainment.js';
/** Host-user credential stores, relative to the real home directory. */
export const AUTOFIX_VERIFY_PROTECTED_HOME_PATHS = Object.freeze([
@@ -72,14 +74,40 @@ ${denied ? `(deny file-read* ${denied})\n` : ''}(allow file-read* (subpath ${lit
}
/**
- * bubblewrap argv up to the command. `protectedDirs` / `protectedFiles` must
+ * Linux seccomp program for the verify command: `socket(AF_UNIX, …)` fails
+ * with EPERM, so a host pathname socket visible through the read-only root
+ * cannot be connected to. `socketpair` (child-process stdio) stays allowed.
+ * Unknown ABIs (including x32) are killed rather than bypassing the check.
+ */
+export function autofixVerifySeccompFilter(arch) {
+ const abi = { x64: { audit: 0xc000003e, socket: 41 }, arm64: { audit: 0xc00000b7, socket: 198 } }[arch];
+ if (!abi) throw new Error('Autofix verify seccomp supports only x64 and arm64.');
+ const ALLOW = 0x7fff0000, KILL = 0x80000000, EPERM = 0x00050001, AF_UNIX = 1;
+ return encodeSeccompProgram([
+ [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, 3, abi.socket],
+ [0x20, 0, 0, 16], // socket domain, args[0] low word
+ [0x15, 0, 1, AF_UNIX],
+ [0x06, 0, 0, EPERM],
+ [0x06, 0, 0, ALLOW],
+ ]);
+}
+
+/**
+ * bubblewrap argv up to the command; the caller writes
+ * `autofixVerifySeccompFilter` to fd 3. `protectedDirs` / `protectedFiles` must
* exist (bwrap mounts over them): directories become empty tmpfs, files
* become /dev/null. The worktree and scratch are bound writable last.
*/
export function autofixVerifyBubblewrapArgs({ worktree, scratch, env, protectedDirs = [], protectedFiles = [] }) {
const args = [
- '--unshare-all', '--die-with-parent', '--new-session', '--cap-drop', 'ALL', '--clearenv',
- '--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp',
+ '--unshare-all', '--die-with-parent', '--new-session', '--cap-drop', 'ALL', '--clearenv', '--seccomp', '3',
+ '--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp', '--tmpfs', '/run',
];
for (const dir of protectedDirs) args.push('--tmpfs', dir);
for (const file of protectedFiles) args.push('--ro-bind', '/dev/null', file);
diff --git a/server/lib/codeAnimationContainment.js b/server/lib/codeAnimationContainment.js
index ede98a4b52..92d1c20d3e 100644
--- a/server/lib/codeAnimationContainment.js
+++ b/server/lib/codeAnimationContainment.js
@@ -185,6 +185,11 @@ export function codeAnimationSeccompFilter(arch) {
[0x06, 0, 0, EPERM],
[0x06, 0, 0, ALLOW],
];
+ return encodeSeccompProgram(instructions);
+}
+
+/** Encode classic BPF `[code, jt, jf, k]` instructions as a `struct sock_filter` array. */
+export function encodeSeccompProgram(instructions) {
const bytes = Buffer.alloc(instructions.length * 8);
instructions.forEach(([code, jt, jf, k], index) => {
bytes.writeUInt16LE(code, index * 8);
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index cc4da40712..cbdd492c2f 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -727,9 +727,10 @@ export function buildEffortArgs(effort, provider, existingArgs = [], model = nul
// edit rather than a four-builder grep.
export const CODEX_UPDATE_CHECK_KEY = 'check_for_update_on_startup';
export const CODEX_AGENT_THREADS_KEY = 'agents.max_concurrent_threads_per_session';
-// Forced off for autofixer repairs (#12487) so a user config cannot open the
-// workspace-write sandbox to the network.
+// Forced off/empty for autofixer repairs (#12487) so a user config cannot open
+// the workspace-write sandbox to the network or to writes outside the cwd.
export const CODEX_WORKSPACE_NETWORK_KEY = 'sandbox_workspace_write.network_access';
+export const CODEX_WORKSPACE_WRITABLE_ROOTS_KEY = 'sandbox_workspace_write.writable_roots';
/**
* Give a Codex swarm enough session threads for its root orchestrator plus
@@ -810,6 +811,7 @@ export const PORTOS_CLI_CONFIG_KEYS = Object.freeze([
CODEX_EFFORT_KEY,
CODEX_UPDATE_CHECK_KEY,
CODEX_WORKSPACE_NETWORK_KEY,
+ CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,
]);
/**
diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.js
index 278dd7d1fc..c477fabe1d 100644
--- a/server/lib/providerModels.test.js
+++ b/server/lib/providerModels.test.js
@@ -43,6 +43,7 @@ import {
PORTOS_CLI_CONFIG_KEYS,
CODEX_AGENT_THREADS_KEY,
CODEX_WORKSPACE_NETWORK_KEY,
+ CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,
isPortosSuppliedConfigKey,
hasCodexUpdateCheckConfig,
buildCodexStartupArgs,
@@ -750,6 +751,7 @@ describe('providerModels', () => {
CODEX_EFFORT_KEY,
CODEX_UPDATE_CHECK_KEY,
CODEX_WORKSPACE_NETWORK_KEY,
+ CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,
].sort());
// Guard against a third emitter appearing without a row: both builders
// that produce `-c` are asserted to use a listed key.
diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.js
index 4e3e411784..773d06835c 100644
--- a/server/lib/providerVendors.js
+++ b/server/lib/providerVendors.js
@@ -80,6 +80,7 @@ import {
OPENCODE_BUILD_AGENT,
applyLeanClaudeArgs,
CODEX_WORKSPACE_NETWORK_KEY,
+ CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,
} from './providerModels.js';
import {
isCodexCommand,
@@ -1152,9 +1153,12 @@ const CLAUDE_REPAIR_ARGS = [
'--setting-sources', 'user',
'--disallowedTools', 'Bash', 'WebFetch', 'WebSearch',
];
-// Codex's OS sandbox: writes confined to the working directory, network off
-// even when the user's config.toml enables it for workspace-write.
-const CODEX_REPAIR_ARGS = ['--sandbox', 'workspace-write', '-c', `${CODEX_WORKSPACE_NETWORK_KEY}=false`];
+// Codex's OS sandbox: writes confined to the working directory, with network
+// and extra writable roots forced off even when the user's config.toml sets them.
+const CODEX_REPAIR_ARGS = [
+ '--sandbox', 'workspace-write',
+ '-c', `${CODEX_WORKSPACE_NETWORK_KEY}=false`, '-c', `${CODEX_WORKSPACE_WRITABLE_ROOTS_KEY}=[]`,
+];
/**
* Saved provider argv for a file-editing repair driven by untrusted input
@@ -1172,13 +1176,14 @@ export function restrictedRepairArgs(provider) {
const saved = stripApprovalBypassArgs(Array.isArray(provider.args) ? provider.args : []).args;
if (isClaudeCommand(command)) {
const cleared = dropOptions(
- dropOptions(saved, ['--allowedTools', '--allowed-tools', '--disallowedTools', '--disallowed-tools', '--mcp-config'], { variadic: true }),
+ dropOptions(saved, ['--allowedTools', '--allowed-tools', '--disallowedTools', '--disallowed-tools', '--mcp-config', '--add-dir'], { variadic: true }),
['--permission-mode', '--setting-sources'],
).filter((arg) => arg !== '--strict-mcp-config');
return { mode: 'claude-disallowed-tools', args: [...cleared, ...CLAUDE_REPAIR_ARGS] };
}
if (isCodexCommand(command)) {
- const cleared = dropOptions(saved, ['--sandbox', '-s']);
+ // --add-dir widens the writable roots; --cd moves the workspace root itself.
+ const cleared = dropOptions(saved, ['--sandbox', '-s', '--add-dir', '--cd', '-C']);
// Options must follow the subcommand; the builder appends `exec` only when absent.
const withExec = cleared.includes('exec') ? cleared : ['exec', ...cleared];
return { mode: 'codex-workspace-write', args: [...withExec, ...CODEX_REPAIR_ARGS] };