diff --git a/TODOS.md b/TODOS.md index 1303e4af3..37e01d81a 100644 --- a/TODOS.md +++ b/TODOS.md @@ -189,12 +189,12 @@ Left open by the iPad and route-drop release, each with its reason. Left open by v1.91.42.0, which lifted the snapshot file-count ceiling. -- **Tracked symlinks refuse the whole /cso run** — `capture()` fails closed on +- **Tracked symlinks refuse the whole /cso run** — `capture()` failed closed on any tracked symlink ("Symlink or special source file"). 5 of 8 mid-size OSS - repos measured for v1.91.42.0 stop there (django, rails, terraform, grafana, - vscode; 1-10 symlinks each, mostly test fixtures). Recording them as unread - exclusions in the manifest, like dependency trees, is a security design call - for Garry. **Effort:** M. **Priority:** P1. + repos measured for v1.91.42.0 stopped there (django, rails, terraform, grafana, + vscode; 1-10 symlinks each, mostly test fixtures). Decided on 2026-11-20 by + GStack Minder in #4567: /cso records each link by its target string, or notes that the target was withheld when it matches a secret pattern and never + dereferences it. **Effort:** M. **Priority:** P1. - **64 MiB aggregate source cap (#2993)** — files over 1 MiB are withheld from the audit but still read and counted. Stream-hash them without counting toward the cap, report them as unread coverage, and add an admission estimate diff --git a/changelog.d/cso-audits-repos-with-symlinks.md b/changelog.d/cso-audits-repos-with-symlinks.md new file mode 100644 index 000000000..49cc2f3c4 --- /dev/null +++ b/changelog.d/cso-audits-repos-with-symlinks.md @@ -0,0 +1,4 @@ +--- +important: blocker +--- +**`/cso` now audits repositories that track symlinks.** One symlink anywhere in the checkout, even `CLAUDE.md -> AGENTS.md` or gstack's own `connect-chrome`, used to stop `gstack-cso start` with `UNSAFE_PATH`. Each tracked or nonignored symlink is now listed in the report with its target string, or notes that the target was withheld when it matches a secret pattern and is never followed, so a link to `/etc/passwd`, one that escapes through `..`, a loop or a dangling link is reported and never read. FIFOs, sockets and devices are still refused, and `--paths` now limits that check to the audited directories, so a FIFO outside them no longer blocks the run. Thanks to @nathanshox for the report and first fix (#4540). diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 71583b5e8..98f21c42e 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -1636,7 +1636,12 @@ or too large. Each message names the cap that applied: - **64 MiB source cap.** The full size of every such file outside dependency and VCS directories counts, including files over 1 MiB whose contents are withheld from the audit. -- **Symlinks.** A tracked symlink anywhere in the repository stops the run. +- **Special files.** A nonignored FIFO, socket or device inside the audit + scope (the whole repository, or the `--paths` directories) stops the run. + Symlinks do not: since the first release after v1.102.0.0 (#4540), each + tracked or nonignored symlink is listed in the report with its target string, or notes that the target was withheld when it matches a secret pattern + and is never followed, so a link to `/etc/passwd` or out through `..` is + reported, not read. **Fix.** No setting raises these caps. For the 64 MiB source cap, rerun with `--paths` set to the comma-separated repo-relative directories you want audited @@ -1648,7 +1653,8 @@ With `--diff`, every changed path outside dependency directories must be inside `--paths`, or the run is refused. Do not audit a hand-trimmed copy: /cso would treat it as the whole repository and report nothing as skipped. `--paths` does not lower the manifest cap or the 100,000-entry limit, because every skipped path still has a -manifest entry (about 50,000 files fit). Symlinks must be removed. Add your +manifest entry (about 50,000 files fit). Remove or ignore a FIFO, socket or +device, or narrow `--paths` past it. Add your file count or size to [#2993](https://github.com/garrytan/gstack/issues/2993). diff --git a/lib/cso/snapshot.ts b/lib/cso/snapshot.ts index 7899dc0fd..81b1cad43 100644 --- a/lib/cso/snapshot.ts +++ b/lib/cso/snapshot.ts @@ -1,6 +1,6 @@ import * as fs from 'node:fs'; import { createHash } from 'node:crypto'; -import { dirname, isAbsolute, join, resolve, relative, sep } from 'node:path'; +import { dirname, isAbsolute, join, posix, resolve, relative, sep } from 'node:path'; import { CsoError, SnapshotManifest, @@ -77,6 +77,28 @@ export function historyMarker(note: string): string { /** Transformation recorded for a repository boundary Git listed as one entry: an untracked nested repository or a registered submodule gitlink. */ export const NESTED_REPOSITORY = 'excluded: nested Git repository; Git listed it as a single boundary entry and never descends into it, so its own source and history are not audited with this repository'; +/** + * Transformation recorded for a symlink. Git tracks only its target string, so + * that string is the whole input: it is reported verbatim and the link is never + * followed. Where it points is classified lexically, without touching the + * filesystem, so the classification cannot be raced or redirected. A target + * that matches any secret pattern, as a whole or in any path segment (the + * redactor misses key=value after a slash, and per-segment checks miss a URL), + * fails closed: it is withheld and no path derived from it is shown. + */ +export function symlinkTransformation(path: string, target: string): string { + const unix = target.replace(/\\/g, '/'), + secret = redact(target) !== target || unix.split('/').some((part) => redact(part) !== part), + normalized = posix.normalize(posix.join(posix.dirname(relativePath(path)), unix)), + where = /^(?:[A-Za-z]:)?[\\/]/.test(target) + ? 'an absolute path, never resolved' + : normalized === '..' || normalized.startsWith('../') + ? 'a relative path that escapes the repository, never resolved' + : secret + ? 'a relative path inside the repository' + : `resolves lexically to ${normalized === '.' ? 'the repository root' : JSON.stringify(normalized)} inside the repository`; + return `excluded: symlink to ${secret ? 'a target withheld because it matches a secret pattern' : JSON.stringify(target)} (${where}); the link is recorded by its target string and never followed, and a target inside the repository is audited only under its own path`; +} export function inAuditPaths(path: string, prefixes: readonly string[]): boolean { return prefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`)); } @@ -324,6 +346,39 @@ function directoryIdentities(root: string, path: string): DirectoryIdentity[] { } return identities; } +type LinkIdentity = { dev: number; ino: number; mode: number; target: Buffer }; +/** Read a source symlink's own target string under identity checks; the link itself is never followed. */ +function readLinkStable(root: string, path: string): LinkIdentity { + const ancestors = directoryIdentities(root, path), + full = join(root, relativePath(path)), + changed = () => new CsoError('SNAPSHOT_RACE', `Source symlink changed while reading: ${path}`), + stat = () => { + try { + return fs.lstatSync(full); + } catch { + throw changed(); + } + }, + named = stat(); + if (!named.isSymbolicLink()) throw changed(); + let target: Buffer; + try { + target = fs.readlinkSync(full, { encoding: 'buffer' }); + } catch { + throw changed(); + } + const current = stat(); + if ( + !current.isSymbolicLink() || + current.dev !== named.dev || + current.ino !== named.ino || + current.mode !== named.mode || + current.size !== named.size + ) + throw changed(); + assertDirectoryIdentities(ancestors, path); + return { dev: named.dev, ino: named.ino, mode: named.mode & 0o777, target }; +} function assertDirectoryIdentities(identities: DirectoryIdentity[], path: string): void { for (const expected of identities) { let current: fs.Stats; @@ -542,10 +597,15 @@ async function rejectSpecialFiles( repo: string, home: string, admission: ReturnType, + auditPaths?: readonly string[], ): Promise { - // Git intentionally omits untracked FIFOs and devices from ls-files. Walk - // pathnames without opening payloads, then ask Git which special names are - // ignored so a nonignored FIFO cannot silently disappear from the snapshot. + // Git intentionally omits untracked FIFOs, sockets and devices from + // ls-files. Walk pathnames without opening payloads, then ask Git which + // special names are ignored so a nonignored FIFO cannot silently disappear + // from the snapshot. Symlinks are not special here: Git lists every tracked + // or nonignored one, and capture records it by its target string without + // following it. With --paths, only the audit scope and the directories + // leading to it are walked, since nothing outside it is captured. admission.time(); const ignoredRaw = await git( repo, @@ -570,6 +630,9 @@ async function rejectSpecialFiles( candidate = candidate.slice(0, slash); } }; + const inScope = (path: string) => !auditPaths || inAuditPaths(path, auditPaths), + leadsIntoScope = (path: string) => + inScope(path) || auditPaths!.some((prefix) => prefix.startsWith(`${path}/`)); const special: string[] = []; let visited = 0; const walk = (at: string, prefix = '') => { @@ -584,10 +647,10 @@ async function rejectSpecialFiles( const full = join(at, item.name), stat = fs.lstatSync(full); if (stat.isDirectory()) { - walk(full, path); + if (leadsIntoScope(path)) walk(full, path); continue; } - if (!stat.isFile()) special.push(path); + if (!stat.isFile() && !stat.isSymbolicLink() && inScope(path)) special.push(path); } } finally { directory.closeSync(); @@ -658,6 +721,7 @@ export async function capture( gitModes = new Map(), sensitiveEvidence: any[] = [], boundaries = new Map(), + links = new Map(), absentPaths = new Set(); let total = 0; guard(); @@ -673,7 +737,7 @@ export async function capture( if (unmatched !== undefined) throw new CsoError('INVALID_ARGUMENT', `--paths entry matches no source file: ${unmatched}`); const outsideAudit = (path: string) => auditPaths !== undefined && !inAuditPaths(path, auditPaths); - await rejectSpecialFiles(repo, home, admission); + await rejectSpecialFiles(repo, home, admission, auditPaths); guard(); const manifest: SnapshotManifest = { version: 3, @@ -716,6 +780,33 @@ export async function capture( throw error; } const size = source.size; + // Git stores a symlink as its target string, so that string is the + // whole source. Record it and never follow the link, whatever it + // points at: a file, a directory, a device, /etc, a loop or nothing. + if (source.isSymbolicLink()) { + const link = readLinkStable(repo, path), + dependency = noReadPath(path); + links.set(path, link); + gitModes.set(path, '120000'); + gitHashes.set( + path, + createHash(objectFormat).update(`blob ${link.target.length}\0`).update(link.target).digest('hex'), + ); + entries.push({ + path, + pathId: snapshotPathId(repo, path), + originalHash: dependency || outsideAudit(path) ? 'not-read' : sha256(link.target), + bytes: link.target.length, + mode: link.mode, + transformation: dependency + ? `excluded: ${exclusion(path) ?? 'host dependency input'}` + : outsideAudit(path) + ? OUTSIDE_AUDIT_PATHS + : symlinkTransformation(path, link.target.toString()), + }); + guard(); + continue; + } // A directory in Git's inventory is a repository boundary, not source: // an untracked nested repository (listed with a trailing slash) or a // registered submodule's gitlink. Git reports it as one entry and never @@ -841,6 +932,19 @@ export async function capture( const assertEntriesStable = (message: string) => { for (const e of entries) { guard(); + const link = links.get(e.path); + if (link) { + const current = readLinkStable(repo, e.path); + if ( + current.dev !== link.dev || + current.ino !== link.ino || + current.mode !== link.mode || + !current.target.equals(link.target) + ) + throw new CsoError('SNAPSHOT_RACE', `${message}: ${e.path}`); + guard(); + continue; + } if (e.originalHash === 'not-read') { const boundary = boundaries.get(e.path); if (boundary) { @@ -1032,7 +1136,7 @@ export async function capture( // Finish with a complete source check. Nothing below this block reads the // audited repository, so a late nonignored file or restored deletion cannot // fall between the final inventory and manifest publication. - await rejectSpecialFiles(repo, home, admission); + await rejectSpecialFiles(repo, home, admission, auditPaths); guard(); assertEntriesStable('Source changed before snapshot persistence'); if (canonical(list) !== canonical(await paths(repo, home, headCommit, admission))) diff --git a/test/cso-ordinary-repos.test.ts b/test/cso-ordinary-repos.test.ts index 2153f854c..b674dce3d 100644 --- a/test/cso-ordinary-repos.test.ts +++ b/test/cso-ordinary-repos.test.ts @@ -1,13 +1,15 @@ // Regressions for /cso on ordinary user repositories: an untracked nested Git // repository (#3255 bug 1), a patch history over the 1 MiB bound (#3255 bug 2), -// and a Docker socket that realpath refuses to open (#3248). +// a Docker socket that realpath refuses to open (#3248), and tracked symlinks, +// which are recorded by their target string and never followed (#4540). import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test'; import * as fs from 'node:fs'; import * as net from 'node:net'; import * as os from 'node:os'; import * as path from 'node:path'; import { spawnSync } from 'node:child_process'; -import { NESTED_REPOSITORY, capture, historyMarker } from '../lib/cso/snapshot'; +import { createHash } from 'node:crypto'; +import { NESTED_REPOSITORY, OUTSIDE_AUDIT_PATHS, capture, historyMarker, symlinkTransformation } from '../lib/cso/snapshot'; import { newRun, readJson } from '../lib/cso/state'; import { MAX_OUTPUT } from '../lib/cso/contracts'; import { dockerEndpoint } from '../lib/cso/docker'; @@ -97,18 +99,25 @@ describe('CSO start on a repository with an untracked nested repository (#3255 b expect(fs.existsSync(path.join(dir, 'readable', 'inner'))).toBe(false); }); - test('negative control: an untracked symlink to a directory is still refused, not treated as a boundary', () => { + test.skipIf(process.platform === 'win32')('negative control: an untracked symlink to a directory is recorded as a link, never treated as a boundary or followed (#4540)', () => { const root = tmp(), repo = init(path.join(root, 'repo')), outside = path.join(root, 'outside'); commit(repo, { 'README.md': 'outer\n' }, 'outer'); nestedRepository(repo, 'inner', { 'f.txt': 'x\n' }); fs.mkdirSync(outside); - fs.writeFileSync(path.join(outside, 'host.txt'), 'host\n'); + fs.writeFileSync(path.join(outside, 'host.txt'), `TOKEN=${CREDENTIAL_CANARY}\n`); fs.symlinkSync(outside, path.join(repo, 'escape')); const started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); - expect(started.status).not.toBe(0); - expect(JSON.parse(started.stderr).error).toMatchObject({ code: 'UNSAFE_PATH', message: expect.stringContaining('escape') }); + expect(started.stderr).toBe(''); + expect(started.status).toBe(0); + const run = JSON.parse(started.stdout), + dir = path.join(state, 'security', 'cso', run.repoId, run.runId), + snapshot = readJson(path.join(dir, 'report.json')).coverage.find((item: any) => item.domain === 'snapshot-inputs'); + expect(snapshot.exclusions.sort()).toEqual([`escape: ${symlinkTransformation('escape', outside)}`, `inner: ${NESTED_REPOSITORY}`]); + expect(snapshot.gaps).toEqual([]); + for (const file of runFiles(dir)) expect(fs.readFileSync(file, 'utf8')).not.toContain(CREDENTIAL_CANARY); + expect(fs.existsSync(path.join(dir, 'snapshot', 'escape'))).toBe(false); }); test('negative control: a nested repository swapped for another directory during capture fails as a snapshot race', async () => { @@ -152,6 +161,161 @@ describe('CSO start on a repository with an untracked nested repository (#3255 b }); }); +describe.skipIf(process.platform === 'win32')('CSO on a repository that tracks symlinks (#4540)', () => { + const OUTSIDE_CANARY = ['outside', 'payload', 'never', 'read'].join('-'); + const LINKS: Record = { + 'CLAUDE.md': 'README.md', + handbook: 'docs', + 'web/guide.md': '../docs/guide.md', + 'host-users': '/etc/passwd', + 'null-device': '/dev/null', + escape: '../outside.txt', + 'docs/deep-escape': '../../outside.txt', + 'loop-a': 'loop-b', + 'loop-b': 'loop-a', + dangling: 'missing.txt', + }; + function linkedRepo(): { root: string; repo: string } { + const root = tmp(), + repo = init(path.join(root, 'repo')); + fs.writeFileSync(path.join(root, 'outside.txt'), `${OUTSIDE_CANARY}\n`); + fs.mkdirSync(path.join(repo, 'docs')); + fs.mkdirSync(path.join(repo, 'web')); + commit(repo, { 'README.md': 'readme\n', 'docs/guide.md': 'guide\n', 'web/app.ts': 'export {};\n' }, 'base'); + for (const [name, target] of Object.entries(LINKS)) fs.symlinkSync(target, path.join(repo, name)); + git(repo, 'add', '-A'); + git(repo, 'commit', '-qm', 'links'); + return { root, repo }; + } + + test('start audits the repository and reports every tracked link by its target string', () => { + const { repo } = linkedRepo(); + const started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); + expect(started.stderr).toBe(''); + expect(started.status).toBe(0); + const run = JSON.parse(started.stdout), + dir = path.join(state, 'security', 'cso', run.repoId, run.runId), + report = readJson(path.join(dir, 'report.json')), + snapshot = report.coverage.find((item: any) => item.domain === 'snapshot-inputs'); + expect(snapshot.exclusions.sort()).toEqual( + Object.entries(LINKS) + .map(([name, target]) => `${name}: ${symlinkTransformation(name, target)}`) + .sort(), + ); + expect(snapshot.gaps).toEqual([]); + expect(symlinkTransformation('host-users', '/etc/passwd')).toContain('"/etc/passwd"'); + expect(symlinkTransformation('escape', '../outside.txt')).toContain('escapes the repository'); + expect(symlinkTransformation('handbook', 'docs')).toContain('"docs" inside the repository'); + const retained = runFiles(path.join(dir, 'snapshot')).map((file) => path.relative(path.join(dir, 'snapshot'), file)).sort(); + expect(retained).toEqual(['README.md', 'docs/guide.md', 'web/app.ts']); + for (const file of runFiles(dir)) { + const body = fs.readFileSync(file, 'utf8'); + expect(body).not.toContain(OUTSIDE_CANARY); + expect(body).not.toContain('root:x:0:0'); + } + }); + + test('capture never opens, stats or resolves a link: only lstat and readlink touch it', async () => { + const { repo } = linkedRepo(), + linkPaths = Object.keys(LINKS).map((name) => path.join(repo, name)), + touched: string[] = [], + spies = (['statSync', 'realpathSync', 'openSync', 'readFileSync', 'opendirSync', 'existsSync', 'accessSync', 'readdirSync'] as const).map((name) => { + const original = (fs as any)[name]; + return spyOn(fs, name as any).mockImplementation(((...args: any[]) => { + if (typeof args[0] === 'string' || args[0] instanceof URL || Buffer.isBuffer(args[0])) touched.push(path.resolve(String(args[0]))); + return original(...args); + }) as any); + }); + let manifest: Awaited>; + try { + manifest = await capture(repo, newRun(repo).dir); + } finally { + for (const spy of spies) spy.mockRestore(); + } + expect(touched).toContain(path.join(repo, 'README.md')); + expect(touched.filter((item) => linkPaths.some((link) => item === link || item.startsWith(`${link}${path.sep}`)))).toEqual([]); + for (const [name, target] of Object.entries(LINKS)) { + const entry = manifest.entries.find((item) => item.path === name); + expect(entry).toMatchObject({ + originalHash: createHash('sha256').update(target).digest('hex'), + bytes: Buffer.byteLength(target), + transformation: symlinkTransformation(name, target), + }); + expect(entry?.executionHash).toBeUndefined(); + } + }); + + test('a comparison base sees a retargeted link as changed and an unchanged link as unchanged', async () => { + const { repo } = linkedRepo(), + base = git(repo, 'rev-parse', 'HEAD').trim(); + fs.unlinkSync(path.join(repo, 'handbook')); + fs.symlinkSync('web', path.join(repo, 'handbook')); + commit(repo, { 'web/app.ts': 'export const changed = 1;\n' }, 'change'); + const manifest = await capture(repo, newRun(repo).dir, base); + expect(manifest.changedPaths).toEqual(['handbook', 'web/app.ts']); + }); + + test('negative controls: an untracked FIFO or socket is still refused', async () => { + const { repo } = linkedRepo(), + fifo = path.join(repo, 'request.pipe'); + expect(spawnSync('/usr/bin/mkfifo', [fifo], { timeout: 10_000 }).status).toBe(0); + await expect(capture(repo, newRun(repo).dir)).rejects.toMatchObject({ code: 'UNSAFE_PATH', message: 'Symlink or special source file: request.pipe' }); + fs.unlinkSync(fifo); + const server = net.createServer(), + socket = path.join(repo, 'web', 'app.sock'); + await new Promise((done) => server.listen(socket, done)); + try { + await expect(capture(repo, newRun(repo).dir)).rejects.toMatchObject({ code: 'UNSAFE_PATH', message: 'Symlink or special source file: web/app.sock' }); + } finally { + await new Promise((done) => server.close(() => done())); + } + }); + + test('--paths narrows the special-file walk: a FIFO outside the scope no longer blocks, one inside still does', async () => { + const { repo } = linkedRepo(); + expect(spawnSync('/usr/bin/mkfifo', [path.join(repo, 'request.pipe')], { timeout: 10_000 }).status).toBe(0); + const manifest = await capture(repo, newRun(repo).dir, undefined, undefined, {}, ['web']); + expect(manifest.entries.find((item) => item.path === 'web/guide.md')?.transformation).toBe(symlinkTransformation('web/guide.md', '../docs/guide.md')); + expect(manifest.entries.find((item) => item.path === 'host-users')?.transformation).toBe(OUTSIDE_AUDIT_PATHS); + expect(spawnSync('/usr/bin/mkfifo', [path.join(repo, 'web', 'request.pipe')], { timeout: 10_000 }).status).toBe(0); + await expect(capture(repo, newRun(repo).dir, undefined, undefined, {}, ['web'])).rejects.toMatchObject({ code: 'UNSAFE_PATH', message: 'Symlink or special source file: web/request.pipe' }); + }); + + test('negative control: a link retargeted during capture fails as a snapshot race', async () => { + const { repo } = linkedRepo(), + link = path.join(repo, 'handbook'), + original = fs.readlinkSync; + let hits = 0; + const counting = spyOn(fs, 'readlinkSync').mockImplementation(((candidate: any, options?: any) => { + if (path.resolve(String(candidate)) === link) hits++; + return original(candidate, options); + }) as typeof fs.readlinkSync); + try { + await capture(repo, newRun(repo).dir); + } finally { + counting.mockRestore(); + } + expect(hits).toBeGreaterThan(1); + const last = hits; + hits = 0; + let swapped = false; + const swapping = spyOn(fs, 'readlinkSync').mockImplementation(((candidate: any, options?: any) => { + if (path.resolve(String(candidate)) === link && ++hits === last) { + fs.unlinkSync(link); + fs.symlinkSync('/etc', link); + swapped = true; + } + return original(candidate, options); + }) as typeof fs.readlinkSync); + try { + await expect(capture(repo, newRun(repo).dir)).rejects.toMatchObject({ code: 'SNAPSHOT_RACE', message: expect.stringContaining('handbook') }); + } finally { + swapping.mockRestore(); + } + expect(swapped).toBe(true); + }); +}); + describe('CSO history capture over the 1 MiB bound (#3255 bug 2)', () => { test('keeps the newest whole commits that fit, marks the truncation, and still redacts', async () => { const repo = init(path.join(tmp(), 'repo')); @@ -297,3 +461,60 @@ describe.skipIf(process.platform === 'win32' || !dockerInstalled)('CSO Docker en await expect(admit('tcp://127.0.0.1:2375')).rejects.toMatchObject({ code: 'ISOLATION_FAILED' }); }); }); + +test('a symlink transformation never carries an unredacted secret or raw control text from its target (#4540)', () => { + const inside = symlinkTransformation('cfg/link', `keys/${CREDENTIAL_CANARY}`), + crafted = symlinkTransformation('cfg/link', 'a\nexcluded: fake sentence'); + expect(inside).not.toContain(CREDENTIAL_CANARY); + expect(inside).toContain('inside the repository'); + expect(crafted).not.toContain('\n'); + expect(crafted).toContain('"cfg/a\\nexcluded: fake sentence" inside the repository'); +}); + +test.skipIf(process.platform === 'win32')('negative controls: nested and deeply nested links carrying password, api_key and token values never leak them into the report or manifest (#4540)', () => { + const repo = init(path.join(tmp(), 'repo')), + keys = [['pass', 'word'].join(''), ['api', 'key'].join('_'), ['to', 'ken'].join('')], + values = keys.map((key) => `${key}=${['Xk9', 'qPz7Lm2Rt8Vw4Ny6', key.length].join('')}`), + secrets = values.map((value) => value.split('=')[1]), + links: [string, string][] = []; + fs.mkdirSync(path.join(repo, 'cfg', 'a', 'b', 'c', 'd'), { recursive: true }); + commit(repo, { 'README.md': 'readme\n' }, 'base'); + for (const dir of ['cfg', 'cfg/a/b/c/d']) + keys.forEach((key, index) => { + links.push([`${dir}/${key}-link`, values[index]], [`${dir}/${key}-up`, `../${values[index]}`]); + }); + for (const [name, target] of links) { + fs.symlinkSync(target, path.join(repo, name)); + const text = symlinkTransformation(name, target); + for (const secret of secrets) expect(text).not.toContain(secret); + } + git(repo, 'add', '-A'); + git(repo, 'commit', '-qm', 'links'); + const started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); + expect(started.stderr).toBe(''); + expect(started.status).toBe(0); + const run = JSON.parse(started.stdout), + dir = path.join(state, 'security', 'cso', run.repoId, run.runId), + snapshot = readJson(path.join(dir, 'report.json')).coverage.find((item: any) => item.domain === 'snapshot-inputs'); + expect(snapshot.exclusions).toHaveLength(links.length); + for (const file of ['report.json', 'snapshot.json']) { + const body = fs.readFileSync(path.join(dir, file), 'utf8'); + for (const secret of secrets) expect(body).not.toContain(secret); + } +}); + +test('fail closed: a link target that matches a secret pattern, whole or per segment, is withheld with its resolved path (#4540)', () => { + const value = ['Xk9', 'qPz7Lm2Rt8Vw4Ny6'].join(''), + halves = [['c3Hd6Ty8Qp2Z', 'x7Lm4Nb9'].join(''), ['Vw1Rk5Js0Gh3', 'Fd8Ks2Pq'].join('')], + cases: [string, string, string[]][] = [ + ['cfg/db', ['postgres://alice:', value, '@localhost/db'].join(''), [value]], + ['cfg/aws', [['AWS', 'SECRET', 'ACCESS', 'KEY'].join('_'), '=', halves[0], '/', halves[1]].join(''), halves], + ['cfg/a/b/up', ['../', ['pass', 'word'].join(''), '=', value].join(''), [value]], + ]; + for (const [name, target, secrets] of cases) { + const text = symlinkTransformation(name, target); + for (const secret of secrets) expect(text).not.toContain(secret); + expect(text).toContain('a target withheld because it matches a secret pattern'); + expect(text).not.toContain('resolves lexically'); + } +}); diff --git a/test/cso-snapshot-state.test.ts b/test/cso-snapshot-state.test.ts index 3357e8b54..43d31abc4 100644 --- a/test/cso-snapshot-state.test.ts +++ b/test/cso-snapshot-state.test.ts @@ -1,6 +1,6 @@ import { afterAll, afterEach, 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 { spawn, spawnSync } from 'node:child_process'; -import { assertSnapshot, capture, NESTED_REPOSITORY } from '../lib/cso/snapshot';import { CsoError, snapshotPathHandle } from '../lib/cso/contracts';import { runProcess, sanitizeForJson, sanitizeHelperForJson } from '../lib/cso/process';import { discardAtomicNoReplaceTemp, finalizeReplayTemporary,reclaimDeadAttemptScratch, loadReport, newRun, privateRoot, readJson, recoverAtomicNoReplaceJson, retention, saveReport, secureDirectory, stateRoot, withLock, writeHelperJson, writeJson } from '../lib/cso/state'; +import { assertSnapshot, capture, NESTED_REPOSITORY, symlinkTransformation } from '../lib/cso/snapshot';import { CsoError, snapshotPathHandle } from '../lib/cso/contracts';import { runProcess, sanitizeForJson, sanitizeHelperForJson } from '../lib/cso/process';import { discardAtomicNoReplaceTemp, finalizeReplayTemporary,reclaimDeadAttemptScratch, loadReport, newRun, privateRoot, readJson, recoverAtomicNoReplaceJson, retention, saveReport, secureDirectory, stateRoot, withLock, writeHelperJson, writeJson } from '../lib/cso/state'; const roots:string[]=[];const tmp=()=>{const p=fs.mkdtempSync(path.join(os.tmpdir(),'cso-snapshot-'));roots.push(p);return p;};afterEach(()=>{for(const p of roots.splice(0))fs.rmSync(p,{recursive:true,force:true});}); const originalState=process.env.GSTACK_HOME,state=fs.mkdtempSync(path.join(os.tmpdir(),'cso-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('/usr/bin/git',['-C',repo,...args],{encoding:'utf8',env:{PATH:'/usr/bin:/bin',HOME:repo},timeout:30_000});if(r.status)throw new Error(r.stderr);return r.stdout;} @@ -25,8 +25,8 @@ describe('CSO dirty snapshot boundary',()=>{ test('admits source membership and time before an unbounded startup walk',async()=>{const p=repo();fs.writeFileSync(path.join(p,'second.txt'),'second\n');const tooMany=newRun(p);await expect(capture(p,tooMany.dir,undefined,undefined,{maxEntries:1})).rejects.toMatchObject({code:'MISSING_INPUT'});expect(fs.existsSync(path.join(tooMany.dir,'snapshot'))).toBe(false);const expired=newRun(p);await expect(capture(p,expired.dir,undefined,undefined,{deadlineMs:Date.now()-1})).rejects.toMatchObject({code:'DEADLINE'});expect(fs.existsSync(path.join(expired.dir,'snapshot'))).toBe(false);}); test('includes chmod-only changes in diff scope',async()=>{const p=repo();fs.chmodSync(path.join(p,'tracked.txt'),0o755);const manifest=await capture(p,newRun(p).dir,'HEAD');expect(manifest.changedPaths).toContain('tracked.txt');}); test('does not invoke configured clean filters, hooks, fsmonitor, or PATH shims',async()=>{const p=repo(),marker=path.join(p,'marker');fs.writeFileSync(path.join(p,'.gitattributes'),'*.txt filter=hostile\n');git(p,'config','filter.hostile.clean',`/bin/sh -c 'touch ${marker}; cat'`);git(p,'config','core.fsmonitor',`/bin/sh -c 'touch ${marker}'`);const fake=path.join(p,'bin');fs.mkdirSync(fake);fs.writeFileSync(path.join(fake,'git'),`#!/bin/sh\ntouch '${marker}'\nexit 99\n`,{mode:0o755});const old=process.env.PATH;process.env.PATH=`${fake}:${old}`;try{await capture(p,newRun(p).dir,'HEAD');}finally{process.env.PATH=old;}expect(fs.existsSync(marker)).toBe(false);}); - test('rejects symlinks and hard links as execution inputs',async()=>{const p=repo();fs.symlinkSync('/etc/passwd',path.join(p,'escape'));expect(capture(p,newRun(p).dir)).rejects.toThrow();fs.unlinkSync(path.join(p,'escape'));fs.linkSync(path.join(p,'tracked.txt'),path.join(p,'hard'));expect(capture(p,newRun(p).dir)).rejects.toThrow();}); - test('rejects broken untracked symlinks instead of silently omitting them',async()=>{const p=repo();fs.symlinkSync('missing-target',path.join(p,'broken'));expect(capture(p,newRun(p).dir)).rejects.toThrow('Symlink');}); + test('never makes a symlink an execution input, and rejects hard links (#4540)',async()=>{const p=repo();fs.symlinkSync('/etc/passwd',path.join(p,'escape'));const run=newRun(p).dir,manifest=await capture(p,run),link=manifest.entries.find(e=>e.path==='escape');expect(link?.executionHash).toBeUndefined();expect(link?.transformation).toBe(symlinkTransformation('escape','/etc/passwd'));expect(fs.existsSync(path.join(run,'snapshot','escape'))).toBe(false);expect(fs.existsSync(path.join(run,'readable','escape'))).toBe(false);fs.unlinkSync(path.join(p,'escape'));fs.linkSync(path.join(p,'tracked.txt'),path.join(p,'hard'));await expect(capture(p,newRun(p).dir)).rejects.toThrow();}); + test('records broken untracked symlinks instead of silently omitting them (#4540)',async()=>{const p=repo();fs.symlinkSync('missing-target',path.join(p,'broken'));const manifest=await capture(p,newRun(p).dir);expect(manifest.entries.find(e=>e.path==='broken')).toMatchObject({transformation:symlinkTransformation('broken','missing-target')});}); for(const earlierSensitive of [false,true])test(earlierSensitive?'keeps credential evidence bound to .env when an earlier file is also sensitive':'redacts secrets and excludes credentials from execution while retaining safe evidence',async()=>{ const p=repo(); if(earlierSensitive)fs.writeFileSync(path.join(p,'.earlier.txt'),'Source: /home/fixture/project/source.ts\n');