diff --git a/scripts/audit-secrets.ts b/scripts/audit-secrets.ts index ff757830..7a2312ad 100644 --- a/scripts/audit-secrets.ts +++ b/scripts/audit-secrets.ts @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; // Explicit private local-development exceptions, not a general permission to track secrets. const localDevelopmentEnvironmentFiles = new Set(['.env', 'apps/stock/web-app/.env']); @@ -109,15 +110,40 @@ export function unexpectedTrackedEnvironmentFiles(paths: readonly string[]): str }); } +/** Resolve the top-level Git repository root for the given working directory. */ +export function resolveRepoRoot(cwd: string = process.cwd()): string { + const result = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], { + cwd, + stdout: 'pipe', + stderr: 'pipe', + }); + const repoRoot = new TextDecoder().decode(result.stdout).replace(/\r?\n$/, ''); + if (result.exitCode !== 0 || !repoRoot) { + throw new Error('Cannot inspect tracked files for the secret audit'); + } + return repoRoot; +} + +/** List all tracked repository paths relative to the top-level Git repository root. */ +export function listTrackedFiles(repoRoot: string): string[] { + const result = Bun.spawnSync(['git', 'ls-files', '-z', '--full-name'], { + cwd: repoRoot, + stdout: 'pipe', + stderr: 'pipe', + }); + if (result.exitCode !== 0) { + throw new Error('Cannot inspect tracked files for the secret audit'); + } + return new TextDecoder().decode(result.stdout).split('\0').filter(Boolean); +} + if (import.meta.main) { - const result = Bun.spawnSync(['git', 'ls-files', '-z']); - if (result.exitCode !== 0) throw new Error('Cannot inspect tracked files for the secret audit'); - const trackedPaths = new TextDecoder() - .decode(result.stdout) - .split('\0') - .filter(Boolean); + const repoRoot = resolveRepoRoot(); + const trackedPaths = listTrackedFiles(repoRoot); const envFiles = unexpectedTrackedEnvironmentFiles(trackedPaths); - const credentialHits = scanTrackedFilesForHttpCredentials(trackedPaths); + const credentialHits = scanTrackedFilesForHttpCredentials(trackedPaths, path => + defaultReadFile(join(repoRoot, path)) + ); if (envFiles.length) { process.stderr.write(`Unexpected tracked environment files: ${envFiles.join(', ')}\n`); diff --git a/scripts/test/audit-secrets-repo.test.ts b/scripts/test/audit-secrets-repo.test.ts index d8282b56..cbcd3297 100644 --- a/scripts/test/audit-secrets-repo.test.ts +++ b/scripts/test/audit-secrets-repo.test.ts @@ -47,15 +47,32 @@ function ceilingAt(dir: string): Record { } /** A throwaway Git repo whose index tracks one file containing a non-placeholder credential URL. */ -function createLeakingRepo(root: string): { gitDir: string; indexFile: string } { +function createLeakingRepo( + root: string, + relativePath = 'leaked.ts' +): { gitDir: string; indexFile: string } { const env = isolatedGitEnv(); expect(Bun.spawnSync(['git', 'init', '-q'], { cwd: root, env }).exitCode).toBe(0); const leakedUrl = `${'https'}://repo-fixture-user:repo-fixture-pass@proxy.vendor.io`; - writeFileSync(join(root, 'leaked.ts'), `export const url = "${leakedUrl}";\n`, 'utf8'); - expect(Bun.spawnSync(['git', 'add', 'leaked.ts'], { cwd: root, env }).exitCode).toBe(0); + const targetPath = join(root, relativePath); + mkdirSync(dirname(targetPath), { recursive: true }); + writeFileSync(targetPath, `export const url = "${leakedUrl}";\n`, 'utf8'); + expect(Bun.spawnSync(['git', 'add', relativePath], { cwd: root, env }).exitCode).toBe(0); return { gitDir: join(root, '.git'), indexFile: join(root, '.git', 'index') }; } +/** A throwaway Git repo tracking the specified files with benign contents. */ +function createFixtureRepo(root: string, files: Record): void { + const env = isolatedGitEnv(); + expect(Bun.spawnSync(['git', 'init', '-q'], { cwd: root, env }).exitCode).toBe(0); + for (const [relativePath, content] of Object.entries(files)) { + const targetPath = join(root, relativePath); + mkdirSync(dirname(targetPath), { recursive: true }); + writeFileSync(targetPath, content, 'utf8'); + expect(Bun.spawnSync(['git', 'add', '-f', relativePath], { cwd: root, env }).exitCode).toBe(0); + } +} + test('audit:secrets passes on the real repository', () => { const result = runAuditSecrets(repoRoot); @@ -150,3 +167,119 @@ test('audit:secrets never echoes the leaked credential when reporting a finding' rmSync(leakingRepo, { recursive: true, force: true }); } }); + +test('audit:secrets audits full repo from a nested empty subdirectory', () => { + const leakingRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-subdir-empty-')); + + try { + createLeakingRepo(leakingRepo); + const emptySubdir = join(leakingRepo, 'sub', 'empty'); + mkdirSync(emptySubdir, { recursive: true }); + + const result = runAuditSecrets(emptySubdir, process.env, ceilingAt(leakingRepo)); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Embedded HTTP(S) credentials found: leaked.ts:1'); + expect(result.stdout).not.toContain('Secret audit passed'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-user'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-pass'); + } finally { + rmSync(leakingRepo, { recursive: true, force: true }); + } +}); + +test('audit:secrets audits full repo from a sibling subdirectory', () => { + const leakingRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-subdir-sibling-')); + + try { + createLeakingRepo(leakingRepo, 'pkg-a/leaked.ts'); + const siblingDir = join(leakingRepo, 'pkg-b'); + mkdirSync(siblingDir, { recursive: true }); + + const result = runAuditSecrets(siblingDir, process.env, ceilingAt(leakingRepo)); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Embedded HTTP(S) credentials found: pkg-a/leaked.ts:1'); + expect(result.stdout).not.toContain('Secret audit passed'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-user'); + expect(result.stdout + result.stderr).not.toContain('repo-fixture-pass'); + } finally { + rmSync(leakingRepo, { recursive: true, force: true }); + } +}); + +test('audit:secrets catches unexpected tracked .env from subdirectories without false root exemption', () => { + const repo = mkdtempSync(join(tmpdir(), 'audit-secrets-subdir-env-')); + + try { + createFixtureRepo(repo, { + 'apps/stock/web-api/.env': 'API_KEY=dummy\n', + }); + const emptySubdir = join(repo, 'empty'); + mkdirSync(emptySubdir, { recursive: true }); + + const fromEmpty = runAuditSecrets(emptySubdir, process.env, ceilingAt(repo)); + expect(fromEmpty.exitCode).toBe(1); + expect(fromEmpty.stderr).toContain( + 'Unexpected tracked environment files: apps/stock/web-api/.env' + ); + expect(fromEmpty.stdout).not.toContain('Secret audit passed'); + + const fromWebApi = runAuditSecrets( + join(repo, 'apps', 'stock', 'web-api'), + process.env, + ceilingAt(repo) + ); + expect(fromWebApi.exitCode).toBe(1); + expect(fromWebApi.stderr).toContain( + 'Unexpected tracked environment files: apps/stock/web-api/.env' + ); + expect(fromWebApi.stdout).not.toContain('Secret audit passed'); + } finally { + rmSync(repo, { recursive: true, force: true }); + } +}); + +test('audit:secrets preserves documented .env exception when run from a subdirectory', () => { + const repo = mkdtempSync(join(tmpdir(), 'audit-secrets-subdir-allowed-env-')); + + try { + createFixtureRepo(repo, { + 'apps/stock/web-app/.env': 'PUBLIC_URL=http://localhost:3000\n', + }); + const scriptsDir = join(repo, 'scripts'); + mkdirSync(scriptsDir, { recursive: true }); + + const result = runAuditSecrets(scriptsDir, process.env, ceilingAt(repo)); + + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toBe(''); + expect(result.stdout).toContain('Secret audit passed'); + } finally { + rmSync(repo, { recursive: true, force: true }); + } +}); + +test('audit:secrets fails closed when run inside a repository .git directory', () => { + const repo = mkdtempSync(join(tmpdir(), 'audit-secrets-gitdir-')); + + try { + const { gitDir } = createLeakingRepo(repo); + + const result = runAuditSecrets(gitDir, process.env, ceilingAt(repo)); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain('Cannot inspect tracked files for the secret audit'); + expect(result.stdout).not.toContain('Secret audit passed'); + } finally { + rmSync(repo, { recursive: true, force: true }); + } +}); + +test('audit:secrets passes on the real repository when run from scripts subdirectory', () => { + const result = runAuditSecrets(join(repoRoot, 'scripts')); + + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toBe(''); + expect(result.stdout).toContain('Secret audit passed'); +});