From af5cacafa9af18234d7ed9bd0adad2ab338b4813 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sun, 22 Nov 2026 03:19:14 -0800 Subject: [PATCH] /cso keeps going when a .env-style file cannot be read, and reports it as unread (#4688) /cso's `start` no longer aborts when a tracked secret-like file (`.env.example` and the like) cannot be read because of a sandbox deny rule or file permissions; the file is listed as unread and the run's source coverage reads partial. Why: with Claude Code's sandbox and a `Read(**/.env*)` deny rule, /cso could not run at all on any repo tracking such a file. Nothing to do after merge. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=testing --- .../fix-cso-unreadable-secret-files.md | 1 + lib/cso/snapshot.ts | 63 +++++++++- test/cso-unreadable-secret-file.test.ts | 111 ++++++++++++++++++ 3 files changed, 172 insertions(+), 3 deletions(-) create mode 100644 changelog.d/fix-cso-unreadable-secret-files.md create mode 100644 test/cso-unreadable-secret-file.test.ts diff --git a/changelog.d/fix-cso-unreadable-secret-files.md b/changelog.d/fix-cso-unreadable-secret-files.md new file mode 100644 index 000000000..a720c2ac4 --- /dev/null +++ b/changelog.d/fix-cso-unreadable-secret-files.md @@ -0,0 +1 @@ +**/cso no longer aborts when a tracked secret-like file such as `.env.example` cannot be read.** A Claude Code sandbox rule like `Read(**/.env*)`, or a file with no read permission, made `start` fail with a generic `INVALID_SCHEMA` error. The file is now listed as unread, the source coverage reads partial, and the audit continues. Other files /cso already leaves out of the audit (dependencies, tool state and agent configuration) are handled the same way when unreadable; any other unreadable file still stops the run. Reported by @kado-ta (#4395). diff --git a/lib/cso/snapshot.ts b/lib/cso/snapshot.ts index 5724679bd..236674558 100644 --- a/lib/cso/snapshot.ts +++ b/lib/cso/snapshot.ts @@ -455,6 +455,16 @@ export function assertOpenedFileContained(root: string, full: string, fd: number ) throw new CsoError('SNAPSHOT_RACE', 'Opened source identity changed during containment validation'); } +/** A permission error (a sandbox deny rule, a mode-000 file): the capture may withhold an excluded path instead (#4395). */ +const DENIED = new Set(['EACCES', 'EPERM']); +class UnreadableSource extends CsoError { + constructor( + path: string, + public errno: string, + ) { + super('UNSAFE_PATH', `Source could not be opened as a regular file: ${path}`); + } +} function readStableWith( root: string, path: string, @@ -478,6 +488,7 @@ function readStableWith( const code = (error as NodeJS.ErrnoException).code; if (['ELOOP', 'ENOENT', 'ENOTDIR', 'ENXIO'].includes(code ?? '')) throw new CsoError('SNAPSHOT_RACE', `Source changed before it could be opened: ${path}`); + if (DENIED.has(code ?? '')) throw new UnreadableSource(path, code!); throw new CsoError('UNSAFE_PATH', `Source could not be opened as a regular file: ${path}`); } try { @@ -662,8 +673,15 @@ async function rejectSpecialFiles( const path = relativePath(prefix ? `${prefix}/${item.name}` : item.name); if (noReadPath(path) || ignoredDirectory(path)) continue; admission.count(++visited); - const full = join(at, item.name), + const full = join(at, item.name); + let stat: fs.Stats; + try { stat = fs.lstatSync(full); + } catch (error: any) { + // Never opened: the capture withholds an unreadable excluded path. + if (DENIED.has(error?.code) && exclusion(path)) continue; + throw error; + } if (stat.isDirectory()) { if (leadsIntoScope(path)) walk(full, path); continue; @@ -740,8 +758,24 @@ export async function capture( sensitiveEvidence: any[] = [], boundaries = new Map(), links = new Map(), - absentPaths = new Set(); + absentPaths = new Set(), + lstatDenied = new Set(); let total = 0; + // An excluded secret-like path that cannot be read is already kept out of + // snapshot/; record it as an unread input (a coverage gap) instead of + // aborting. Every other unreadable path still fails the capture. + const withholdUnreadable = (path: string, source: fs.Stats | undefined, errno: string) => { + if (!source) lstatDenied.add(path); + entries.push({ + path, + pathId: snapshotPathId(repo, path), + originalHash: 'not-read', + bytes: source?.size ?? 0, + mode: (source?.mode ?? 0) & 0o777, + transformation: `withheld: ${exclusion(path)} file is unreadable (${errno}); its payload was not assessed`, + }); + guard(); + }; guard(); const objectFormat = (await git(repo, ['rev-parse', '--show-object-format'], home)).trim(); guard(); @@ -800,6 +834,10 @@ export async function capture( absentPaths.add(path); continue; } + if (DENIED.has(error?.code) && exclusion(path)) { + withholdUnreadable(path, undefined, error.code); + continue; + } throw error; } const size = source.size; @@ -875,7 +913,15 @@ export async function capture( continue; } if (total + size > SOURCE_LIMIT) throw sourceCapError(); - const { data, mode } = readStable(repo, path, SOURCE_LIMIT); + let read: { data: Buffer; mode: number }; + try { + read = readStable(repo, path, SOURCE_LIMIT); + } catch (error) { + if (!(error instanceof UnreadableSource && exclusion(path))) throw error; + withholdUnreadable(path, source, error.errno); + continue; + } + const { data, mode } = read; total += data.length; guard(); if (total > SOURCE_LIMIT) throw sourceCapError(); @@ -985,6 +1031,17 @@ export async function capture( guard(); continue; } + if (lstatDenied.has(e.path)) { + try { + fs.lstatSync(containedFile(repo, e.path)); + } catch (error: any) { + if (DENIED.has(error?.code)) { + guard(); + continue; + } + } + throw new CsoError('SNAPSHOT_RACE', `${message}: ${e.path}`); + } const current = fs.lstatSync(containedFile(repo, e.path)), compared = gitHashes.get(e.path); if ( diff --git a/test/cso-unreadable-secret-file.test.ts b/test/cso-unreadable-secret-file.test.ts new file mode 100644 index 000000000..b774b730b --- /dev/null +++ b/test/cso-unreadable-secret-file.test.ts @@ -0,0 +1,111 @@ +import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { capture } from '../lib/cso/snapshot'; +import { CsoError } from '../lib/cso/contracts'; +import { newRun } from '../lib/cso/state'; + +// An unreadable secret-like file (a Claude Code sandbox deny rule such as Read(**/.env*), or a chmod 000 file) is +// already kept out of snapshot/, so start reports it as an unread input instead of aborting the whole audit (#4395). +const roots: string[] = []; +const tmp = () => { const p = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-unreadable-')); roots.push(p); return p; }; +afterEach(() => { for (const p of roots.splice(0)) { try { fs.chmodSync(path.join(p, '.env.example'), 0o600); } catch {} try { fs.chmodSync(path.join(p, 'app.ts'), 0o600); } catch {} fs.rmSync(p, { recursive: true, force: true }); } }); +let originalState: string | undefined, state = ''; +beforeAll(() => { originalState = process.env.GSTACK_HOME; state = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-unreadable-state-')); process.env.GSTACK_HOME = state; }); +afterAll(() => { if (originalState === undefined) delete process.env.GSTACK_HOME; else process.env.GSTACK_HOME = originalState; fs.rmSync(state, { recursive: true, force: true }); }); +function git(repo: string, ...args: string[]) { + const r = spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8', env: { ...process.env, HOME: repo, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }, timeout: 30_000 }); + if (r.status) throw new Error(r.stderr); +} +function repo() { + const p = tmp(); + git(p, 'init', '-q'); + git(p, 'config', 'user.email', 'fixture@example.test'); + git(p, 'config', 'user.name', 'Fixture'); + fs.writeFileSync(path.join(p, '.env.example'), 'FOO=bar\n'); + fs.writeFileSync(path.join(p, 'app.ts'), 'export const x = 1;\n'); + git(p, 'add', '.'); + git(p, 'commit', '-qm', 'base'); + return p; +} +const permissionsBind = process.platform !== 'win32' && process.getuid?.() !== 0; + +describe('cso snapshot with an unreadable secret-like file (#4395)', () => { + // Value: protects=a tracked .env.example that cannot be opened becomes an unread, withheld input and the capture + // continues; fails_when=open's EACCES aborts start with UNSAFE_PATH; why_new=no capture case had an unreadable + // file; seam=none + test.skipIf(!permissionsBind)('a file that cannot be opened is withheld as unread and the capture continues', async () => { + const p = repo(); + fs.chmodSync(path.join(p, '.env.example'), 0o000); + const run = newRun(p), m = await capture(p, run.dir); + const entry = m.entries.find(e => e.path === '.env.example')!; + expect(entry.originalHash).toBe('not-read'); + expect(entry.executionHash).toBeUndefined(); + expect(entry.transformation).toMatch(/^withheld: .*unreadable \(EACCES\)/); + expect(fs.existsSync(path.join(run.dir, 'readable', '.env.example'))).toBe(false); + expect(m.entries.find(e => e.path === 'app.ts')?.executionHash).toBeDefined(); + }); + + // Value: protects=the sandbox case, where even lstat is denied (EPERM), is withheld the same way; fails_when=the raw + // EPERM escapes and start reports a generic INVALID_SCHEMA; why_new=the case above denies only open; + // seam=fs.lstatSync on that one path + test('a file whose lstat is denied is withheld as unread and the capture continues', async () => { + const p = repo(), denied = path.join(p, '.env.example'), real = fs.lstatSync; + const spy = spyOn(fs, 'lstatSync').mockImplementation(((file: any, ...args: any[]) => { + if (String(file) === denied) throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); + return (real as any)(file, ...args); + }) as any); + try { + const m = await capture(p, newRun(p).dir); + const entry = m.entries.find(e => e.path === '.env.example')!; + expect([entry.originalHash, entry.bytes]).toEqual(['not-read', 0]); + expect(entry.transformation).toMatch(/^withheld: .*unreadable \(EPERM\)/); + } finally { spy.mockRestore(); } + }); + + // Value: protects=an unreadable ordinary source file still stops the capture, so the exemption covers only paths + // already excluded as secrets; fails_when=any unreadable file is silently withheld; why_new=the exemption is new; seam=none + test.skipIf(!permissionsBind)('an unreadable ordinary source file still refuses', async () => { + const p = repo(); + fs.chmodSync(path.join(p, 'app.ts'), 0o000); + const error = await capture(p, newRun(p).dir).then(() => null, e => e); + expect(error).toBeInstanceOf(CsoError); + expect((error as CsoError).code).toBe('UNSAFE_PATH'); + }); + + // Value: protects=an ordinary source file whose lstat is denied still stops the capture; fails_when=the lstat catch + // drops its exclusion check and silently withholds app.ts; why_new=the lstat exemption is new; seam=fs.lstatSync on that one path + test('an ordinary source file whose lstat is denied still refuses', async () => { + const p = repo(), denied = path.join(p, 'app.ts'), real = fs.lstatSync; + const spy = spyOn(fs, 'lstatSync').mockImplementation(((file: any, ...args: any[]) => { + if (String(file) === denied) throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); + return (real as any)(file, ...args); + }) as any); + try { + const error = await capture(p, newRun(p).dir).then(() => null, e => e); + expect((error as NodeJS.ErrnoException | null)?.code).toBe('EPERM'); + } finally { spy.mockRestore(); } + }); + + // Value: protects=a withheld lstat-denied path that becomes readable before the end of capture is a race, not a pass; + // fails_when=the end-of-capture re-check accepts a path it can now stat; why_new=the re-check is new; + // seam=fs.lstatSync on that one path, denied on every call but the last (counted from a fully denied capture) + test('an lstat-denied secret that becomes readable before the end of capture is a SNAPSHOT_RACE', async () => { + const p = repo(), denied = path.join(p, '.env.example'), real = fs.lstatSync; + let calls = 0, allow = Infinity; + const spy = spyOn(fs, 'lstatSync').mockImplementation(((file: any, ...args: any[]) => { + if (String(file) === denied && ++calls < allow) throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); + return (real as any)(file, ...args); + }) as any); + try { + await capture(p, newRun(p).dir); + allow = calls; + calls = 0; + const error = await capture(p, newRun(p).dir).then(() => null, e => e); + expect(error).toBeInstanceOf(CsoError); + expect((error as CsoError).code).toBe('SNAPSHOT_RACE'); + } finally { spy.mockRestore(); } + }); +});