import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { expect, test } from 'bun:test'; const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); const auditScript = fileURLToPath(new URL('../audit-secrets.ts', import.meta.url)); function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record { const env: Record = {}; for (const [key, value] of Object.entries(baseEnv)) { if (value !== undefined && !key.startsWith('GIT_')) { env[key] = value; } } return env; } function decodeRun(result: ReturnType) { return { exitCode: result.exitCode, stdout: new TextDecoder().decode(result.stdout), stderr: new TextDecoder().decode(result.stderr), }; } function runAuditSecrets( cwd: string, baseEnv: NodeJS.ProcessEnv = process.env, fixtureEnv: Record = {} ) { return decodeRun( Bun.spawnSync([process.execPath, auditScript], { cwd, env: { ...isolatedGitEnv(baseEnv), ...fixtureEnv }, stdout: 'pipe', stderr: 'pipe', }) ); } // Stop Git discovery at the fixture directory so a TMPDIR inside a checkout cannot // make Git find the parent repository and audit an unrelated (or empty) file list. function ceilingAt(dir: string): Record { return { GIT_CEILING_DIRECTORIES: dirname(realpathSync(dir)) }; } /** A throwaway Git repo whose index tracks one file containing a non-placeholder credential URL. */ 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`; 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); expect(result.exitCode, result.stderr).toBe(0); expect(result.stderr).toBe(''); expect(result.stdout).toContain('Secret audit passed'); }); test('audit:secrets fails closed when git metadata is unavailable', () => { const tempDir = mkdtempSync(join(tmpdir(), 'audit-secrets-no-git-')); try { const result = runAuditSecrets(tempDir, process.env, ceilingAt(tempDir)); 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(tempDir, { recursive: true, force: true }); } }); test('audit:secrets fails closed in a non-repo directory nested inside another checkout', () => { const outerRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-outer-repo-')); try { createLeakingRepo(outerRepo); const nestedDir = join(outerRepo, 'tmp', 'audit-secrets-no-git'); mkdirSync(nestedDir, { recursive: true }); const result = runAuditSecrets(nestedDir, process.env, ceilingAt(nestedDir)); 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(outerRepo, { recursive: true, force: true }); } }); test('real-repository audit ignores inherited GIT_DIR, GIT_WORK_TREE and GIT_INDEX_FILE', () => { const callerRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-polluted-env-')); try { const { gitDir, indexFile } = createLeakingRepo(callerRepo); const pollutedEnv: NodeJS.ProcessEnv = { ...process.env, GIT_DIR: gitDir, GIT_WORK_TREE: callerRepo, GIT_INDEX_FILE: indexFile, }; // Sensitivity check: unstripped, these variables really do redirect the audit to the // leaking fixture repo, so a pass below proves the stripping is what protects it. const redirected = decodeRun( Bun.spawnSync([process.execPath, auditScript], { cwd: callerRepo, env: pollutedEnv as Record, stdout: 'pipe', stderr: 'pipe', }) ); expect(redirected.exitCode).toBe(1); expect(redirected.stderr).toContain('leaked.ts:1'); const indexBefore = readFileSync(indexFile); const result = runAuditSecrets(repoRoot, pollutedEnv); expect(result.exitCode, result.stderr).toBe(0); expect(result.stderr).toBe(''); expect(result.stdout).toContain('Secret audit passed'); expect(readFileSync(indexFile)).toEqual(indexBefore); } finally { rmSync(callerRepo, { recursive: true, force: true }); } }); test('audit:secrets never echoes the leaked credential when reporting a finding', () => { const leakingRepo = mkdtempSync(join(tmpdir(), 'audit-secrets-leak-')); try { createLeakingRepo(leakingRepo); const result = runAuditSecrets(leakingRepo, 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-pass'); expect(result.stdout + result.stderr).not.toContain('repo-fixture-user'); } finally { 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'); });