Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/cso-sandbox-state-root.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **`/cso` now starts inside a Codex `workspace-write` sandbox (CHE-10265).** There `~/.gstack` is read-only, so the helper failed with `PERSISTENCE_FAILED (EROFS)`. When the default state root cannot be written (EROFS, EACCES or EPERM) and no `GSTACK_STATE_ROOT`, `GSTACK_HOME`, `GSTACK_STATE_DIR` or `CLAUDE_PLUGIN_DATA` is set, the helper retries once under `/tmp/gstack-cso-<uid>` (sticky `/tmp`, per-uid, mode 0700, owned by the current user). Every ancestor and owner check still runs there: a group- or world-writable ancestor, or a directory pre-created by another user, is still rejected with `UNSAFE_PATH`, and an unsafe default root is never retried. An explicit state-root variable is never replaced. Runs made in the sandbox live in the `/tmp` root and are not visible outside it. Not offered on Windows.
96 changes: 86 additions & 10 deletions lib/cso/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { randomBytes } from 'node:crypto';
import { atomicWriteSync } from '../fs-atomic';
import {
CsoError,
type ErrorCode,
RunReportV3,
canonical,
completeness,
Expand All @@ -12,7 +13,7 @@ import {
sha256,
} from './contracts';
import { redact, sanitizeForJson, sanitizeHelperForJson } from './process';
import { resolveStateRoot } from '../state-root';
import { resolveStateRoot, STATE_ROOT_VARS } from '../state-root';
import { PROCESS_IDENTITY, identityStartedAtMs, processIdentitySource } from './process-identity';
const MAX_STATE_FILE = 1024 * 1024;

Expand Down Expand Up @@ -682,6 +683,17 @@ export function discardAtomicNoReplaceTemp(
}
}

/** A CSO filesystem fault that keeps its errno, so `privateRoot` can tell a read-only root from an unsafe one. */
class StateFault extends CsoError {
constructor(
code: ErrorCode,
message: string,
readonly errno?: string,
) {
super(code, message);
}
}

export function stateRoot(env: Record<string, string | undefined> = process.env): string {
// The shared chain (lib/state-root.ts), made absolute. Security artifacts are intentionally outside every sync allowlist.
return resolve(resolveStateRoot(env));
Expand Down Expand Up @@ -717,9 +729,10 @@ function ensureDirectory(path: string, hardenExistingLeaf: boolean): string {
created = true;
} catch (error: any) {
if (error?.code !== 'EEXIST')
throw new CsoError(
throw new StateFault(
'PERSISTENCE_FAILED',
`Private state directory could not be created (${error?.code ?? 'unknown error'}); set GSTACK_HOME to a writable directory`,
error?.code,
);
}
if (cursor === p) leafCreated = created;
Expand All @@ -735,23 +748,86 @@ function ensureDirectory(path: string, hardenExistingLeaf: boolean): string {
const s = fs.statSync(p);
if (process.getuid && s.uid !== process.getuid())
throw new CsoError('UNSAFE_PATH', 'Private directory must be owned by the current user');
if (hardenExistingLeaf || leafCreated) fs.chmodSync(p, 0o700);
if (hardenExistingLeaf || leafCreated) {
try {
fs.chmodSync(p, 0o700);
} catch (error: any) {
throw new StateFault(
'PERSISTENCE_FAILED',
`Private state directory could not be secured (${error?.code ?? 'unknown error'}); set GSTACK_HOME to a writable directory`,
error?.code,
);
}
}
return p;
}
/** The supplied leaf is CSO-owned. Existing ancestors are validated, never mutated. */
export function secureDirectory(path: string): string {
return ensureDirectory(path, true);
}
export function privateRoot(): string {
const container = ensureDirectory(stateRoot(), false);
return secureDirectory(join(container, 'security', 'cso'));
/** Env vars that name the state root on purpose. An explicit choice is never replaced by the sandbox fallback. */
const EXPLICIT_ROOT_VARS = [...STATE_ROOT_VARS, 'CLAUDE_PLUGIN_DATA'] as const;
const READ_ONLY_ERRNOS = new Set(['EROFS', 'EACCES', 'EPERM']);
/**
* Private state root for a sandbox whose default `$HOME/.gstack` is read-only (a Codex `workspace-write`
* sandbox mounts it read-only but leaves `/tmp` writable). `/tmp` is sticky, so the writable-ancestor guard
* accepts it; the leaf is per-uid and must be owned by the current user, so a directory another user
* pre-creates there is rejected (UNSAFE_PATH) instead of used. Never offered on Windows.
*/
export function sandboxStateRoot(base = '/tmp'): string | null {
const uid = process.getuid?.();
if (process.platform === 'win32' || uid === undefined) return null;
return join(base, `gstack-cso-${uid}`);
}
function hasExplicitRoot(env: Record<string, string | undefined>): boolean {
return EXPLICIT_ROOT_VARS.some((name) => Boolean(env[name]));
}
function privateRootAt(container: string): string {
const root = secureDirectory(join(ensureDirectory(container, false), 'security', 'cso'));
// A directory that already exists on a read-only mount passes every check above and only fails at the first write.
try {
fs.accessSync(root, fs.constants.W_OK);
} catch (error: any) {
throw new StateFault(
'PERSISTENCE_FAILED',
`Private state directory is not writable (${error?.code ?? 'unknown error'}); set GSTACK_HOME to a writable directory`,
error?.code,
);
}
return root;
}
/**
* The CSO private directory. When the default root cannot be written (EROFS/EACCES/EPERM) and no state-root
* variable was set, retry once under `sandboxStateRoot()`. Every ancestor and ownership check still runs
* there, and an unsafe ancestor (UNSAFE_PATH) is never retried.
*/
export function privateRoot(
env: Record<string, string | undefined> = process.env,
fallbackBase?: string,
): string {
try {
return privateRootAt(stateRoot(env));
} catch (error) {
const fallback = sandboxStateRoot(fallbackBase);
if (
!(error instanceof StateFault) ||
error.code !== 'PERSISTENCE_FAILED' ||
!READ_ONLY_ERRNOS.has(error.errno ?? '') ||
hasExplicitRoot(env) ||
!fallback
)
throw error;
return privateRootAt(fallback);
}
}
export function assertStateOutside(repo: string): void {
const source = fs.realpathSync(repo),
candidate = resolve(stateRoot(), 'security', 'cso');
const relation = relative(source, candidate);
if (relation === '' || (!relation.startsWith(`..${sep}`) && relation !== '..' && !isAbsolute(relation)))
throw new CsoError('UNSAFE_PATH', 'CSO private state must be outside the audited repository');
fallback = sandboxStateRoot();
for (const root of fallback ? [stateRoot(), fallback] : [stateRoot()]) {
const relation = relative(source, resolve(root, 'security', 'cso'));
if (relation === '' || (!relation.startsWith(`..${sep}`) && relation !== '..' && !isAbsolute(relation)))
throw new CsoError('UNSAFE_PATH', 'CSO private state must be outside the audited repository');
}
}
export function repoId(repo: string): string {
return sha256(fs.realpathSync(repo)).slice(0, 24);
Expand Down
136 changes: 136 additions & 0 deletions test/cso-sandbox-state-root.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { spawnSync } from 'node:child_process';
import { CsoError } from '../lib/cso/contracts';
import { privateRoot, sandboxStateRoot } from '../lib/cso/state';

// CHE-10265: inside a Codex workspace-write sandbox ~/.gstack is read-only, so the default state root cannot be
// created. The core retries once under a private per-uid directory in /tmp; the ancestor guard stays on.
const posix = process.platform !== 'win32' && process.getuid?.() !== 0;
const uid = process.getuid?.();
const made: string[] = [];
const scratch = (): string => {
const dir = fs.mkdtempSync(path.join('/tmp', 'cso-sbx-'));
made.push(dir);
return dir;
};
/** A HOME whose ~/.gstack exists but cannot be written, as in the sandbox. */
const readOnlyHome = (): string => {
const home = scratch();
fs.mkdirSync(path.join(home, '.gstack'), { mode: 0o555 });
fs.chmodSync(path.join(home, '.gstack'), 0o555);
return home;
};
const failure = (fn: () => unknown): CsoError => {
try {
fn();
} catch (error) {
return error as CsoError;
}
throw new Error('expected a CsoError');
};
afterEach(() => {
for (const dir of made.splice(0)) {
try {
for (const sub of fs.readdirSync(dir)) fs.chmodSync(path.join(dir, sub), 0o700);
} catch {}
fs.rmSync(dir, { recursive: true, force: true });
}
});

describe('sandbox fallback state root', () => {
test.skipIf(!posix)('names a per-uid directory under the base', () => {
expect(sandboxStateRoot('/base')).toBe(`/base/gstack-cso-${uid}`);
});

test.skipIf(!posix)('a read-only default root falls back to a private 0700 directory', () => {
const home = readOnlyHome();
const base = scratch();
const root = privateRoot({ HOME: home }, base);
expect(root).toBe(path.join(base, `gstack-cso-${uid}`, 'security', 'cso'));
expect(fs.statSync(root).mode & 0o777).toBe(0o700);
expect(fs.statSync(root).uid).toBe(uid!);
expect(privateRoot({ HOME: home }, base)).toBe(root);
});

test.skipIf(!posix)('a writable default root is used and the fallback is not created', () => {
const home = scratch();
const base = scratch();
expect(privateRoot({ HOME: home }, base)).toBe(path.join(home, '.gstack', 'security', 'cso'));
expect(fs.readdirSync(base)).toEqual([]);
});

test.skipIf(!posix)('an explicit GSTACK_HOME that is not writable is reported, never replaced', () => {
const home = readOnlyHome();
const base = scratch();
for (const name of ['GSTACK_STATE_ROOT', 'GSTACK_HOME', 'GSTACK_STATE_DIR'])
expect(failure(() => privateRoot({ HOME: home, [name]: path.join(home, '.gstack') }, base))).toMatchObject({
code: 'PERSISTENCE_FAILED',
});
expect(fs.readdirSync(base)).toEqual([]);
});

test.skipIf(!posix)('a group- or world-writable ancestor of the fallback is still rejected', () => {
const home = readOnlyHome();
const base = scratch();
fs.chmodSync(base, 0o777);
expect(failure(() => privateRoot({ HOME: home }, base))).toMatchObject({
code: 'UNSAFE_PATH',
message: 'Private state has a group- or world-writable ancestor',
});
});

test.skipIf(!posix)('a group-writable pre-existing fallback leaf is still rejected', () => {
const home = readOnlyHome();
const base = scratch();
const leaf = path.join(base, `gstack-cso-${uid}`);
fs.mkdirSync(leaf);
fs.chmodSync(leaf, 0o770);
expect(failure(() => privateRoot({ HOME: home }, base))).toMatchObject({ code: 'UNSAFE_PATH' });
});

test.skipIf(!posix)('an unsafe default ancestor is rejected, not retried in the fallback', () => {
const home = scratch();
fs.mkdirSync(path.join(home, '.gstack'), { mode: 0o700 });
fs.chmodSync(path.join(home, '.gstack'), 0o777);
const base = scratch();
expect(failure(() => privateRoot({ HOME: home }, base))).toMatchObject({ code: 'UNSAFE_PATH' });
expect(fs.readdirSync(base)).toEqual([]);
});
});

const bwrap = '/usr/bin/bwrap';
describe('fallback inside a read-only user namespace', () => {
// Same shape as the Codex sandbox: everything read-only, a fresh sticky /tmp, HOME/.gstack read-only.
test.skipIf(!posix || process.platform !== 'linux' || !fs.existsSync(bwrap) || !fs.existsSync('/var/tmp'))(
'the default /tmp fallback succeeds under bwrap --unshare-user --ro-bind',
() => {
const work = fs.mkdtempSync(path.join('/var/tmp', 'cso-sbx-ns-'));
made.push(work);
try {
fs.mkdirSync(path.join(work, 'home'), { mode: 0o700 });
// The real sandbox case: the state directories already exist, on a read-only mount.
fs.mkdirSync(path.join(work, 'home', '.gstack'), { mode: 0o700 });
fs.mkdirSync(path.join(work, 'home', '.gstack', 'security'), { mode: 0o700 });
fs.mkdirSync(path.join(work, 'home', '.gstack', 'security', 'cso'), { mode: 0o700 });
const file = path.join(work, 'probe.ts');
fs.writeFileSync(
file,
`import { privateRoot } from ${JSON.stringify(path.resolve(import.meta.dir, '../lib/cso/state.ts'))};
console.log(privateRoot({ HOME: ${JSON.stringify(path.join(work, 'home'))} }));`,
);
const r = spawnSync(
bwrap,
['--unshare-user', '--ro-bind', '/', '/', '--proc', '/proc', '--dev', '/dev', '--perms', '1777', '--tmpfs', '/tmp', process.execPath, file],
{ encoding: 'utf8', timeout: 60_000 },
);
expect(r.stderr).not.toContain('UNSAFE_PATH');
expect(r.stdout.trim()).toMatch(/^\/tmp\/gstack-cso-\d+\/security\/cso$/);
expect(r.status).toBe(0);
} finally {
fs.rmSync(work, { recursive: true, force: true });
}
},
);
});
Loading