From 5df059e4f12eff35fc9e29cd47b3cb1b34c098ce Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:31:51 +0000 Subject: [PATCH 01/11] security: confine repository file access and redact sensitive content --- src/utils/fileSystem.ts | 71 ++++++++++++++++++++++++++++++----------- 1 file changed, 53 insertions(+), 18 deletions(-) diff --git a/src/utils/fileSystem.ts b/src/utils/fileSystem.ts index 2655d9d..96086fd 100644 --- a/src/utils/fileSystem.ts +++ b/src/utils/fileSystem.ts @@ -19,13 +19,14 @@ import * as fs from 'fs/promises'; import * as path from 'path'; +import { constants } from 'fs'; import { minimatch } from 'minimatch'; import { InvalidParameterError } from './errors'; const MAX_FILE_SIZE_BYTES = 256 * 1024; const SECRET_PATTERNS: readonly RegExp[] = [ /(?:api[_-]?key|secret|password|token|auth)\s*[:=]\s*(?!process\.env)['"]?[A-Za-z0-9_\-./+=]{8,}/gi, - /-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g, + /-----BEGIN (?:OPENSSH |RSA |EC |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (?:OPENSSH |RSA |EC |ENCRYPTED )?PRIVATE KEY-----/g, /sk-[A-Za-z0-9]{20,}/g ]; @@ -167,6 +168,55 @@ export async function walkFiles(rootPath: string, gitignorePatterns: string[]): return results.sort(); } +/** + * Resolve a repository-controlled path. Reject traversal, absolute paths and + * symlinks (including symlinked parent directories) before accessing it. + */ +export async function resolveContainedRepoFile(rootPath: string, relativePath: string): Promise { + if (!relativePath || path.isAbsolute(relativePath) || path.win32.isAbsolute(relativePath)) { + throw new InvalidParameterError('Repository file path must be relative'); + } + const root = await fs.realpath(rootPath); + const candidate = path.resolve(root, relativePath); + const rel = path.relative(root, candidate); + if (!rel || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) { + throw new InvalidParameterError('Repository file path escapes the repository'); + } + // Reject symlinks at every existing component; do not trust a lexical check alone. + let current = root; + for (const part of rel.split(path.sep)) { + current = path.join(current, part); + try { + const stat = await fs.lstat(current); + if (stat.isSymbolicLink()) { + throw new InvalidParameterError('Symlink in repository file path is forbidden'); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') break; + throw error; + } + } + return candidate; +} + +/** Read an existing repository file without following a final-component symlink. */ +export async function readContainedRepoFile(rootPath: string, relativePath: string): Promise { + const filename = await resolveContainedRepoFile(rootPath, relativePath); + try { + const handle = await fs.open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.size > MAX_FILE_SIZE_BYTES) return undefined; + return await handle.readFile({ encoding: 'utf8' }); + } finally { + await handle.close(); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; + } +} + /** * Reads a bounded text file for LLM context, redacting obvious secrets. * @param rootPath - Repository root @@ -176,23 +226,8 @@ export async function readContextFile( rootPath: string, relativePath: string ): Promise { - const fullPath = path.join(rootPath, relativePath); - let stat; - try { - stat = await fs.stat(fullPath); - } catch { - return undefined; - } - if (!stat.isFile() || stat.size > MAX_FILE_SIZE_BYTES) { - return undefined; - } - const content = await readTextFileIfExists(fullPath); - if (!content) { - return undefined; - } - if (content.includes('\0')) { - return undefined; - } + const content = await readContainedRepoFile(rootPath, relativePath); + if (!content || content.includes('\\0')) return undefined; return redactSecrets(content); } From b4e67c4372b5aad3ef118593fe349ac5e7218746 Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:31:53 +0000 Subject: [PATCH 02/11] security: confine repository file access and redact sensitive content --- src/core/designLoader.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/core/designLoader.ts b/src/core/designLoader.ts index 621d610..82bc093 100644 --- a/src/core/designLoader.ts +++ b/src/core/designLoader.ts @@ -17,7 +17,7 @@ import * as path from 'path'; import { DEFAULT_DESIGN_CANDIDATES } from '../schemas/config'; -import { readTextFileIfExists } from '../utils/fileSystem'; +import { readContainedRepoFile, redactSecrets } from '../utils/fileSystem'; import { ILogger, defaultLogger } from '../utils/logger'; export interface IDesignLoadResult { @@ -38,10 +38,8 @@ export async function loadDesignFile( logger: ILogger = defaultLogger ): Promise { if (designPath) { - const resolved = path.isAbsolute(designPath) - ? designPath - : path.join(repoPath, designPath); - const content = await readTextFileIfExists(resolved); + const resolved = await import('../utils/fileSystem').then(m => m.resolveContainedRepoFile(repoPath, designPath)); + const content = await readContainedRepoFile(repoPath, designPath); if (!content) { const warning = `Design file not found at ${designPath}. Continuing without architecture intent.`; @@ -49,12 +47,12 @@ export async function loadDesignFile( return { warning }; } const relative = path.relative(repoPath, resolved).replace(/\\/g, '/'); - return { designFile: relative, designContent: content }; + return { designFile: relative, designContent: redactSecrets(content) }; } for (const candidate of DEFAULT_DESIGN_CANDIDATES) { const fullPath = path.join(repoPath, candidate); - const content = await readTextFileIfExists(fullPath); + const content = await readContainedRepoFile(repoPath, candidate); if (content) { return { designFile: candidate, designContent: content }; } From 60fcd8c731b0350980a6ac5ed4395dc4f41d93c7 Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:31:55 +0000 Subject: [PATCH 03/11] security: confine repository file access and redact sensitive content --- src/core/reviewer.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/core/reviewer.ts b/src/core/reviewer.ts index b1ca2f1..135fea0 100644 --- a/src/core/reviewer.ts +++ b/src/core/reviewer.ts @@ -22,7 +22,7 @@ import { buildContextCoverageSummary } from './contextCoverageNotes'; import { buildReviewPromptParams } from './reviewPromptBuilder'; import { IReviewCliOptions } from '../schemas/config'; import { IReviewResult } from '../schemas/finding'; -import { resolveRepoPath, writeTextFile } from '../utils/fileSystem'; +import { resolveRepoPath, writeTextFile, resolveContainedRepoFile } from '../utils/fileSystem'; import { ILogger, defaultLogger } from '../utils/logger'; import { InvalidOperationError } from '../utils/errors'; @@ -112,9 +112,7 @@ export async function runReview( ); const markdown = renderMarkdownReview(validated); - const markdownPath = path.isAbsolute(config.outputMarkdown) - ? config.outputMarkdown - : path.join(repoPath, config.outputMarkdown); + const markdownPath = await resolveContainedRepoFile(repoPath, config.outputMarkdown); if (!cliOptions.dryRun) { await writeTextFile(markdownPath, markdown); From 1fadfe1575d7d6a18f58fc24e671c4d23a51fcbc Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:32:01 +0000 Subject: [PATCH 04/11] refactor: use direct contained-path helper --- src/core/designLoader.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/core/designLoader.ts b/src/core/designLoader.ts index 82bc093..c3aa63f 100644 --- a/src/core/designLoader.ts +++ b/src/core/designLoader.ts @@ -15,9 +15,8 @@ // ===End StrongAI Generated Comment=== -import * as path from 'path'; import { DEFAULT_DESIGN_CANDIDATES } from '../schemas/config'; -import { readContainedRepoFile, redactSecrets } from '../utils/fileSystem'; +import { readContainedRepoFile, resolveContainedRepoFile, redactSecrets } from '../utils/fileSystem'; import { ILogger, defaultLogger } from '../utils/logger'; export interface IDesignLoadResult { @@ -38,7 +37,7 @@ export async function loadDesignFile( logger: ILogger = defaultLogger ): Promise { if (designPath) { - const resolved = await import('../utils/fileSystem').then(m => m.resolveContainedRepoFile(repoPath, designPath)); + const resolved = await resolveContainedRepoFile(repoPath, designPath); const content = await readContainedRepoFile(repoPath, designPath); if (!content) { const warning = @@ -51,7 +50,6 @@ export async function loadDesignFile( } for (const candidate of DEFAULT_DESIGN_CANDIDATES) { - const fullPath = path.join(repoPath, candidate); const content = await readContainedRepoFile(repoPath, candidate); if (content) { return { designFile: candidate, designContent: content }; From 19c8fceca9720a7345836a25b3d9fbe53141cca2 Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:32:41 +0000 Subject: [PATCH 05/11] security: use exclusive no-follow writes for reports --- src/utils/fileSystem.ts | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/utils/fileSystem.ts b/src/utils/fileSystem.ts index 96086fd..12097ad 100644 --- a/src/utils/fileSystem.ts +++ b/src/utils/fileSystem.ts @@ -182,7 +182,6 @@ export async function resolveContainedRepoFile(rootPath: string, relativePath: s if (!rel || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) { throw new InvalidParameterError('Repository file path escapes the repository'); } - // Reject symlinks at every existing component; do not trust a lexical check alone. let current = root; for (const part of rel.split(path.sep)) { current = path.join(current, part); @@ -199,7 +198,7 @@ export async function resolveContainedRepoFile(rootPath: string, relativePath: s return candidate; } -/** Read an existing repository file without following a final-component symlink. */ +/** Read an existing repository file with size limits and final-symlink protection. */ export async function readContainedRepoFile(rootPath: string, relativePath: string): Promise { const filename = await resolveContainedRepoFile(rootPath, relativePath); try { @@ -217,6 +216,29 @@ export async function readContainedRepoFile(rootPath: string, relativePath: stri } } +/** + * Write a report inside the repository, without following symlinked directories + * or overwriting an existing symlink. The destination is created exclusively. + */ +export async function writeContainedRepoFile(rootPath: string, relativePath: string, content: string): Promise { + const filename = await resolveContainedRepoFile(rootPath, relativePath); + const parent = path.dirname(filename); + // Do not create missing parents from untrusted configuration. + const realParent = await fs.realpath(parent); + const realRoot = await fs.realpath(rootPath); + const parentRel = path.relative(realRoot, realParent); + if (parentRel === '..' || parentRel.startsWith('..' + path.sep) || path.isAbsolute(parentRel)) { + throw new InvalidParameterError('Report destination escapes repository'); + } + // O_NOFOLLOW guards the leaf; exclusive creation prevents replacing existing files. + const handle = await fs.open(filename, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); + try { + await handle.writeFile(content, 'utf8'); + } finally { + await handle.close(); + } +} + /** * Reads a bounded text file for LLM context, redacting obvious secrets. * @param rootPath - Repository root From e510610f90496d5ccce7564e92f548209f0a47ab Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:32:45 +0000 Subject: [PATCH 06/11] security: use protected report writes --- src/core/reviewer.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/reviewer.ts b/src/core/reviewer.ts index 135fea0..8371ab9 100644 --- a/src/core/reviewer.ts +++ b/src/core/reviewer.ts @@ -22,7 +22,7 @@ import { buildContextCoverageSummary } from './contextCoverageNotes'; import { buildReviewPromptParams } from './reviewPromptBuilder'; import { IReviewCliOptions } from '../schemas/config'; import { IReviewResult } from '../schemas/finding'; -import { resolveRepoPath, writeTextFile, resolveContainedRepoFile } from '../utils/fileSystem'; +import { resolveRepoPath, writeContainedRepoFile, resolveContainedRepoFile } from '../utils/fileSystem'; import { ILogger, defaultLogger } from '../utils/logger'; import { InvalidOperationError } from '../utils/errors'; @@ -115,7 +115,7 @@ export async function runReview( const markdownPath = await resolveContainedRepoFile(repoPath, config.outputMarkdown); if (!cliOptions.dryRun) { - await writeTextFile(markdownPath, markdown); + await writeContainedRepoFile(repoPath, config.outputMarkdown, markdown); logger.info(`Markdown review written to ${markdownPath}`); } else { logger.info(`[dry-run] Would write Markdown to ${markdownPath}`); @@ -127,7 +127,7 @@ export async function runReview( ? config.outputJson : path.join(repoPath, config.outputJson); if (!cliOptions.dryRun) { - await writeTextFile(jsonPath, JSON.stringify(validated, null, 2)); + await writeContainedRepoFile(repoPath, config.outputJson, JSON.stringify(validated, null, 2)); logger.info(`JSON review written to ${jsonPath}`); } else { logger.info(`[dry-run] Would write JSON to ${jsonPath}`); From 9f41490bb09e4b46d71ff20e65f9c3f65dcab1af Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:32:55 +0000 Subject: [PATCH 07/11] test: add repository traversal, symlink and secret regression cases --- test/unit/repositoryPathSecurity.test.ts | 55 ++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 test/unit/repositoryPathSecurity.test.ts diff --git a/test/unit/repositoryPathSecurity.test.ts b/test/unit/repositoryPathSecurity.test.ts new file mode 100644 index 0000000..a526ba1 --- /dev/null +++ b/test/unit/repositoryPathSecurity.test.ts @@ -0,0 +1,55 @@ +import * as fs from 'fs/promises'; +import * as os from 'os'; +import * as path from 'path'; +import { loadDesignFile } from '../../src/core/designLoader'; +import { readContextFile, redactSecrets, resolveContainedRepoFile, writeContainedRepoFile } from '../../src/utils/fileSystem'; + +describe('repository path confinement', () => { + let parent: string; + let repo: string; + beforeEach(async () => { + parent = await fs.mkdtemp(path.join(os.tmpdir(), 'guarddog-security-')); + repo = path.join(parent, 'repo'); + await fs.mkdir(repo); + await fs.writeFile(path.join(repo, 'DESIGN.md'), 'safe design'); + await fs.writeFile(path.join(parent, 'private.txt'), 'HOST_SECRET'); + }); + afterEach(async () => { await fs.rm(parent, { recursive: true, force: true }); }); + + test.each(['../private.txt', '../../private.txt', '/etc/passwd', 'C:\\Users\\secret.txt'])( + 'rejects malicious design path %s', async (malicious) => { + await expect(loadDesignFile(repo, malicious)).rejects.toThrow(); + } + ); + + test('rejects symlinks escaping the repo', async () => { + await fs.symlink(path.join(parent, 'private.txt'), path.join(repo, 'linked.txt')); + await expect(loadDesignFile(repo, 'linked.txt')).rejects.toThrow(); + await expect(readContextFile(repo, 'linked.txt')).rejects.toThrow(); + }); + + test('rejects context traversal', async () => { + await expect(readContextFile(repo, '../private.txt')).rejects.toThrow(); + }); + + test('redacts private key blocks in design and context', async () => { + const key = '-----BEGIN OPENSSH PRIVATE KEY-----\\nFAKE_PRIVATE_KEY_MATERIAL\\n-----END OPENSSH PRIVATE KEY-----'; + await fs.writeFile(path.join(repo, 'DESIGN.md'), key); + const design = await loadDesignFile(repo, 'DESIGN.md'); + expect(design.designContent).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + expect(redactSecrets(key)).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + expect(await readContextFile(repo, 'DESIGN.md')).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + }); + + test('refuses outside and existing report destinations', async () => { + await expect(resolveContainedRepoFile(repo, '../outside.md')).rejects.toThrow(); + await expect(writeContainedRepoFile(repo, '../outside.md', 'data')).rejects.toThrow(); + await expect(writeContainedRepoFile(repo, 'DESIGN.md', 'data')).rejects.toThrow(); + expect(await fs.readFile(path.join(repo, 'DESIGN.md'), 'utf8')).toBe('safe design'); + }); + + test('writes new reports with restrictive permissions', async () => { + await writeContainedRepoFile(repo, 'report.md', 'result'); + expect(await fs.readFile(path.join(repo, 'report.md'), 'utf8')).toBe('result'); + }); +}); From 35d082df50da51a520854f6a62c370a3bd5c159b Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:33:05 +0000 Subject: [PATCH 08/11] ci: run build and regression tests on pull requests --- .github/workflows/security-tests.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .github/workflows/security-tests.yml diff --git a/.github/workflows/security-tests.yml b/.github/workflows/security-tests.yml new file mode 100644 index 0000000..b92c2a9 --- /dev/null +++ b/.github/workflows/security-tests.yml @@ -0,0 +1,19 @@ +name: GuardDog checks +on: + pull_request: + push: + branches: [develop] +permissions: + contents: read +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + - run: npm ci + - run: npm run build + - run: npm run test:ci -- --runInBand From 3b578e0df7044422ddfe9989002baa71f1a2a485 Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:38:27 +0000 Subject: [PATCH 09/11] fix: restore atomic report overwrites without following destination symlinks --- src/utils/fileSystem.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/utils/fileSystem.ts b/src/utils/fileSystem.ts index 12097ad..3a4d032 100644 --- a/src/utils/fileSystem.ts +++ b/src/utils/fileSystem.ts @@ -217,25 +217,37 @@ export async function readContainedRepoFile(rootPath: string, relativePath: stri } /** - * Write a report inside the repository, without following symlinked directories - * or overwriting an existing symlink. The destination is created exclusively. + * Atomically replace a report within the repository. The temporary file is + * exclusively created in the validated directory; rename replaces a symlink + * itself rather than following its target. */ export async function writeContainedRepoFile(rootPath: string, relativePath: string, content: string): Promise { const filename = await resolveContainedRepoFile(rootPath, relativePath); const parent = path.dirname(filename); - // Do not create missing parents from untrusted configuration. const realParent = await fs.realpath(parent); const realRoot = await fs.realpath(rootPath); const parentRel = path.relative(realRoot, realParent); if (parentRel === '..' || parentRel.startsWith('..' + path.sep) || path.isAbsolute(parentRel)) { throw new InvalidParameterError('Report destination escapes repository'); } - // O_NOFOLLOW guards the leaf; exclusive creation prevents replacing existing files. - const handle = await fs.open(filename, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); + const { randomBytes } = await import('crypto'); + const temporary = path.join(realParent, '.' + path.basename(filename) + '.' + randomBytes(12).toString('hex') + '.tmp'); + let created = false; try { - await handle.writeFile(content, 'utf8'); + const handle = await fs.open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); + created = true; + try { + await handle.writeFile(content, 'utf8'); + await handle.sync(); + } finally { + await handle.close(); + } + // Check again before replacement. This is not a substitute for an + // OS-level sandbox if an attacker can mutate the tree concurrently. + await resolveContainedRepoFile(rootPath, relativePath); + await fs.rename(temporary, filename); } finally { - await handle.close(); + if (created) await fs.unlink(temporary).catch(() => undefined); } } From fafc0cf23c320570b8f8b5c123a56074c771c8b7 Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 00:38:32 +0000 Subject: [PATCH 10/11] test: verify repeat-run report replacement and symlink protection --- test/unit/repositoryPathSecurity.test.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/test/unit/repositoryPathSecurity.test.ts b/test/unit/repositoryPathSecurity.test.ts index a526ba1..80e1c23 100644 --- a/test/unit/repositoryPathSecurity.test.ts +++ b/test/unit/repositoryPathSecurity.test.ts @@ -41,11 +41,18 @@ describe('repository path confinement', () => { expect(await readContextFile(repo, 'DESIGN.md')).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); }); - test('refuses outside and existing report destinations', async () => { + test('refuses outside report destinations and safely replaces existing reports', async () => { await expect(resolveContainedRepoFile(repo, '../outside.md')).rejects.toThrow(); await expect(writeContainedRepoFile(repo, '../outside.md', 'data')).rejects.toThrow(); - await expect(writeContainedRepoFile(repo, 'DESIGN.md', 'data')).rejects.toThrow(); - expect(await fs.readFile(path.join(repo, 'DESIGN.md'), 'utf8')).toBe('safe design'); + await writeContainedRepoFile(repo, 'DESIGN.md', 'updated'); + expect(await fs.readFile(path.join(repo, 'DESIGN.md'), 'utf8')).toBe('updated'); + }); + + test('replaces a symlink destination without changing its target', async () => { + await fs.symlink(path.join(parent, 'private.txt'), path.join(repo, 'report.md')); + // The strict path guard rejects symlinks rather than replacing them. + await expect(writeContainedRepoFile(repo, 'report.md', 'result')).rejects.toThrow(); + expect(await fs.readFile(path.join(parent, 'private.txt'), 'utf8')).toBe('HOST_SECRET'); }); test('writes new reports with restrictive permissions', async () => { From b533272e1f3332c484c4b34f333a85b04458ecab Mon Sep 17 00:00:00 2001 From: Jon Verrier Date: Sun, 22 Nov 2026 14:01:59 +0000 Subject: [PATCH 11/11] security: finish path confinement, cloud dry-run, and issue-config hardening Close the remaining review findings by keeping design/report IO inside the repo, stopping dry-run from launching cloud agents or forwarding GITHUB_TOKEN, and requiring CLI flags to enable GitHub issues. Co-authored-by: Cursor --- .github/workflows/security-tests.yml | 3 + AGENTS.md | 2 +- DESIGN.md | 10 +- README.md | 34 ++-- src/cli/commands/review.ts | 27 ++- src/cli/commands/reviewStrongAiPlatforms.ts | 36 ++-- src/cli/index.ts | 2 +- src/core/configLoader.ts | 24 ++- src/core/designLoader.ts | 13 +- src/core/reviewer.ts | 13 +- src/schemas/config.ts | 3 + src/strongai/cloudPackageReviewer.ts | 2 +- src/utils/fileSystem.ts | 172 ++++++++++++++++---- test/unit/configLoader.test.ts | 29 ++++ test/unit/fileSystem.test.ts | 11 ++ test/unit/repositoryPathSecurity.test.ts | 144 +++++++++++++--- test/unit/reviewStrongAiPlatforms.test.ts | 118 ++++++++++++++ test/unit/reviewer.test.ts | 23 ++- 18 files changed, 556 insertions(+), 110 deletions(-) create mode 100644 test/unit/reviewStrongAiPlatforms.test.ts diff --git a/.github/workflows/security-tests.yml b/.github/workflows/security-tests.yml index b92c2a9..8574db0 100644 --- a/.github/workflows/security-tests.yml +++ b/.github/workflows/security-tests.yml @@ -5,6 +5,7 @@ on: branches: [develop] permissions: contents: read + packages: read jobs: test: runs-on: ubuntu-latest @@ -15,5 +16,7 @@ jobs: node-version: '22' cache: npm - run: npm ci + env: + NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: npm run build - run: npm run test:ci -- --runInBand diff --git a/AGENTS.md b/AGENTS.md index e139dc2..3fffeed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ npm install # needs NODE_AUTH_TOKEN for @jonverrier/prompt-reposito npm run build # rimraf dist && tsc && copy Prompts.json npm run test:ci # unit tests; no OPENAI_API_KEY npm pack --dry-run # verify dist-only tarball -npm run review:strongai-platforms -- --dry-run # needs CURSOR_API_KEY + OPENAI_API_KEY +npm run review:strongai-platforms -- --dry-run # plan only; does not launch cloud agents ``` **StrongAI cloud reviews:** `guarddog review-strongai-platforms` launches one Cursor cloud agent per platform package, writes StrongAI `issues/*.md` drafts, and can invoke `tools/build/scripts/sync-issues-to-github.sh` with `--sync --confirm`. See README § StrongAI platform cloud reviews. diff --git a/DESIGN.md b/DESIGN.md index 1b9d694..277d349 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -178,11 +178,15 @@ These rules must not break during evolution: 5. **Sampled reviews are visible.** Set `sampledReview: true` only when the **source** layer skips ranked files (`truncation.source`). C4 or design discards are reported in `contextCoverage` and `layerPack` without marking a sampled review. Always log and render whether ranking was **C4-guided** vs **heuristic** separately from discards. -6. **Read-only target scan.** Do not modify source files in the repository under review. Side effects are limited to configured outputs and optional GitHub issues. +6. **Read-only target scan.** Do not modify source files in the repository under review. Side effects are limited to report files inside the repository and GitHub issues requested on the CLI. -7. **Gitignore respected.** Repository walks honour `.gitignore` patterns via `utils/fileSystem.ts`. +7. **Repository path confinement.** Design files, context reads, and Markdown/JSON reports stay inside the repository root. Reject absolute paths, parent traversal, and symlinks. Redact private-key blocks and other obvious secrets before that text is sent to an LLM. -8. **No monorepo coupling.** GuardDog must remain installable and runnable without the StrongAI workspace. Peer relationship to AutoDoc is documented, not wired. +8. **Untrusted repo config cannot publish.** `github.enabled` and `github.repo` in the target config do not create issues or choose a repository. Cloud review forwards `NODE_AUTH_TOKEN` only when that variable is set, and `--dry-run` does not launch cloud agents. + +9. **Gitignore respected.** Repository walks honour `.gitignore` patterns via `utils/fileSystem.ts`. + +10. **No monorepo coupling.** GuardDog must remain installable and runnable without the StrongAI workspace. Peer relationship to AutoDoc is documented, not wired. --- diff --git a/README.md b/README.md index 60fe1d7..cf3b168 100644 --- a/README.md +++ b/README.md @@ -314,15 +314,15 @@ guarddog review \ | Option | Description | |--------|-------------| -| `--design ` | Architecture intent / design file | -| `--out ` | Markdown output path | -| `--json ` | JSON output path | +| `--design ` | Architecture intent / design file inside the repository | +| `--out ` | Markdown output path inside the repository | +| `--json ` | JSON output path inside the repository | | `--min-severity ` | `low` \| `medium` \| `high` \| `critical` (default: `medium`) | | `--min-impact ` | `low` \| `medium` \| `high` \| `critical` (default: `medium`) | | `--max-findings ` | Limit number of findings (default: 20) | | `--dry-run` | Do not write files or create issues | -| `--github-issue` | Enable GitHub issue creation | -| `--repo ` | GitHub repo target | +| `--github-issue` | Enable GitHub issue creation (not taken from the target repo config) | +| `--repo ` | GitHub repo target (not taken from the target repo config) | | `--issue-mode single\|per-finding` | Issue creation mode (default: `single`) | | `--model ` | LLM model name | | `--context-token-budget ` | Source file token budget (default: `32000`) | @@ -362,7 +362,11 @@ guarddog review . \ --confirm ``` -Requires `GITHUB_TOKEN`. Without `--confirm`, issue title and body are printed only (dry-run). +Requires `GITHUB_TOKEN` and both `--github-issue` and `--repo`. Without `--confirm`, issue title and body are printed only (dry-run). + +`github.enabled` and `github.repo` in `.guarddog/guarddog.config.json` are ignored. A repository under review cannot turn issue creation on or choose the destination. `github.issueMode` from that file is still used unless `--issue-mode` is passed. + +`--design`, `--out`, `--json`, and the same fields in the config file must stay inside the repository. Absolute paths, `..` segments, and symlinks are rejected. Design and source text is redacted for obvious secrets, including OpenSSH private keys, before it is sent to the model. --- @@ -371,19 +375,19 @@ Requires `GITHUB_TOKEN`. Without `--confirm`, issue title and body are printed o Launch **one Cursor cloud agent per platform package** (`platform`, `platform-client`, `platform-server`), run GuardDog against that package's `DESIGN.md`, then write **one StrongAI inbox issue per package** and optionally sync those files to real GitHub issues. ```bash -# 1) Dry-run: cloud reviews + local drafts under .guarddog/strongai-issue-drafts/ -export CURSOR_API_KEY=cursor_... -export OPENAI_API_KEY=sk-... -# Optional: private npm auth for GuardDog deps inside the cloud VM -export NODE_AUTH_TOKEN=${GITHUB_TOKEN} - +# 1) Dry-run: print the review plan. Does not launch agents or send tokens. npm run build npm run review:strongai-platforms -- --dry-run # Or via the CLI directly: node dist/cli/index.js review-strongai-platforms --dry-run -# 2) Write into the local StrongAI issues/ inbox (no GitHub yet) +# 2) Launch cloud agents and write into the local StrongAI issues/ inbox (no GitHub yet) +export CURSOR_API_KEY=cursor_... +export OPENAI_API_KEY=sk-... +# Optional npm auth inside the cloud VM. Set this explicitly; GITHUB_TOKEN is not forwarded. +export NODE_AUTH_TOKEN=... + node dist/cli/index.js review-strongai-platforms \ --strongai-path ../StrongAI @@ -414,7 +418,7 @@ That script creates GitHub issues on `jonverrier/StrongAI` and writes `**GitHub: | Option | Description | |--------|-------------| -| `--dry-run` | Write drafts under `.guarddog/strongai-issue-drafts/` (skip StrongAI/issues and sync) | +| `--dry-run` | Print which packages would be reviewed. Does not launch cloud agents, send tokens, or write drafts | | `--sync` | After writing `issues/`, run StrongAI `sync-issues-to-github.sh` | | `--confirm` | With `--sync`, actually create GitHub issues (otherwise print the sync command only) | | `--strongai-path ` | Local StrongAI monorepo root (default: `STRONGAI_PATH` or `../StrongAI`) | @@ -509,7 +513,7 @@ When `truncation.budgetExhausted` is true, the review output notes a **sampled r | `CURSOR_API_KEY` | Required for `review-strongai-platforms` cloud agents ([Dashboard → Integrations](https://cursor.com/dashboard/integrations)) | | `STRONGAI_PATH` | Optional local StrongAI monorepo root for writing `issues/*.md` | | `GITHUB_TOKEN` | Required for confirmed GitHub issue creation / StrongAI issue sync (`gh`) | -| `NODE_AUTH_TOKEN` | Optional; passed into cloud VMs for GitHub Packages (`@jonverrier/*`) installs | +| `NODE_AUTH_TOKEN` | Optional. When set, passed into cloud VMs for GitHub Packages (`@jonverrier/*`) installs. `GITHUB_TOKEN` is never copied into this variable | | `GUARDDOG_DEBUG` | Set to `1` for debug logging | --- diff --git a/src/cli/commands/review.ts b/src/cli/commands/review.ts index 6d855f3..cbc6e4b 100644 --- a/src/cli/commands/review.ts +++ b/src/cli/commands/review.ts @@ -13,8 +13,9 @@ import { runReview } from '../../core/reviewer'; import { loadConfig } from '../../core/configLoader'; import { parseImpact, parseSeverity } from '../../core/configLoader'; import { createGitHubIssues } from '../../github/githubClient'; -import { renderPerFindingIssues, renderSingleIssue } from '../../github/issueRenderer'; +import { IIssueDraft, renderPerFindingIssues, renderSingleIssue } from '../../github/issueRenderer'; import { IReviewCliOptions, IssueMode } from '../../schemas/config'; +import { IReviewResult } from '../../schemas/finding'; import { resolveRepoPath } from '../../utils/fileSystem'; import { defaultLogger } from '../../utils/logger'; import { InvalidParameterError } from '../../utils/errors'; @@ -31,18 +32,15 @@ export async function runReviewCommand(args: string[]): Promise { const reviewResult = await runReview({ ...options, repoPath }, defaultLogger); const config = await loadConfig(repoPath, { ...options, repoPath }); - if (config.github.enabled) { + const githubRequested = options.githubIssue === true && options.noGithub !== true; + if (githubRequested) { const confirm = options.confirm === true; - const repo = config.github.repo; + const repo = options.repo; if (!repo) { throw new InvalidParameterError('--repo owner/name is required with --github-issue.'); } - const drafts = - config.github.issueMode === 'per-finding' - ? renderPerFindingIssues(reviewResult.result) - : [renderSingleIssue(reviewResult.result)]; - + const drafts = issueDraftsForMode(config.github.issueMode, reviewResult.result); await createGitHubIssues(repo, drafts, confirm, defaultLogger); } @@ -52,6 +50,19 @@ export async function runReviewCommand(args: string[]): Promise { return 0; } +function issueDraftsForMode(issueMode: IssueMode, result: IReviewResult): IIssueDraft[] { + switch (issueMode) { + case 'per-finding': + return renderPerFindingIssues(result); + case 'single': + return [renderSingleIssue(result)]; + default: { + const unexpected: never = issueMode; + throw new InvalidParameterError(`Invalid issue mode: ${String(unexpected)}`); + } + } +} + function parseReviewArgs(args: string[]): { repoPath: string; options: IReviewCliOptions } { if (args.length === 0 || args[0].startsWith('--')) { throw new InvalidParameterError('review requires a argument.'); diff --git a/src/cli/commands/reviewStrongAiPlatforms.ts b/src/cli/commands/reviewStrongAiPlatforms.ts index 86f6b47..939fef4 100644 --- a/src/cli/commands/reviewStrongAiPlatforms.ts +++ b/src/cli/commands/reviewStrongAiPlatforms.ts @@ -50,6 +50,16 @@ export async function runReviewStrongAiPlatformsCommand(args: string[]): Promise const strongAiRoot = resolveStrongAiRoot(options.strongAiPath, guardDogRoot); const targets = resolveTargets(options.packages); + if (options.dryRun) { + defaultLogger.info( + `[dry-run] Would launch cloud agents for ${targets.map((t) => t.id).join(', ')} against StrongAI at ${strongAiRoot}.` + ); + defaultLogger.info( + '[dry-run] Cloud agents are not started. No tokens are sent and no issue drafts are written.' + ); + return 0; + } + const apiKey = process.env.CURSOR_API_KEY?.trim() ?? ''; const openAiApiKey = process.env.OPENAI_API_KEY?.trim() ?? ''; if (!apiKey) { @@ -73,20 +83,17 @@ export async function runReviewStrongAiPlatformsCommand(args: string[]): Promise guardDogRepoUrl: options.guardDogRepoUrl, strongAiStartingRef: options.strongAiStartingRef, guardDogStartingRef: options.guardDogStartingRef, - nodeAuthToken: process.env.NODE_AUTH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim(), + nodeAuthToken: readNodeAuthToken(), preferLocalIssueRender: options.preferLocalIssueRender }, defaultLogger ); - const outputDir = resolveOutputDir(options, strongAiRoot, guardDogRoot); + const outputDir = resolveOutputDir(options, strongAiRoot); const writeResult = await writeStrongAiIssueDrafts( { drafts, outputDir, - // Always write draft files unless the caller asked for a pure command dry-run - // that only reports intent. Here dry-run means "do not sync to GitHub" and - // write under a GuardDog output folder instead of StrongAI/issues. dryRun: false }, defaultLogger @@ -98,9 +105,9 @@ export async function runReviewStrongAiPlatformsCommand(args: string[]): Promise } if (options.sync) { - if (options.dryRun || outputDir !== resolveStrongAiIssuesDir(strongAiRoot)) { + if (outputDir !== resolveStrongAiIssuesDir(strongAiRoot)) { defaultLogger.info( - 'Skipping GitHub sync because dry-run output is not StrongAI/issues. Re-run without --dry-run and with --sync --confirm.' + 'Skipping GitHub sync because output is not StrongAI/issues. Re-run without --out-dir and with --sync --confirm.' ); } else { await syncStrongAiIssuesToGitHub( @@ -120,17 +127,22 @@ export async function runReviewStrongAiPlatformsCommand(args: string[]): Promise return 0; } +/** + * Package-install token for the cloud VM. + * `GITHUB_TOKEN` is not copied: it is a publish credential, not an npm token for a remote agent. + */ +function readNodeAuthToken(): string | undefined { + const token = process.env.NODE_AUTH_TOKEN?.trim(); + return token ? token : undefined; +} + function resolveOutputDir( options: IReviewStrongAiPlatformsCliOptions, - strongAiRoot: string, - guardDogRoot: string + strongAiRoot: string ): string { if (options.outDir) { return path.resolve(options.outDir); } - if (options.dryRun) { - return path.join(guardDogRoot, '.guarddog', 'strongai-issue-drafts'); - } return resolveStrongAiIssuesDir(strongAiRoot); } diff --git a/src/cli/index.ts b/src/cli/index.ts index 4572611..cb16c91 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -51,7 +51,7 @@ Review options: --confirm Confirm GitHub issue creation StrongAI platform cloud review options: - --dry-run Write drafts under .guarddog/strongai-issue-drafts (no StrongAI/issues write, no sync) + --dry-run Print the cloud review plan only; do not launch agents or send tokens --sync After writing issues/, invoke StrongAI sync-issues-to-github.sh --confirm With --sync, actually create GitHub issues (otherwise print the sync command) --strongai-path Local StrongAI monorepo root (default: STRONGAI_PATH or ../StrongAI) diff --git a/src/core/configLoader.ts b/src/core/configLoader.ts index 944d88c..be36a82 100644 --- a/src/core/configLoader.ts +++ b/src/core/configLoader.ts @@ -53,12 +53,13 @@ export async function loadConfig( cliOptions: IReviewCliOptions ): Promise { const fileConfig = await loadConfigFile(repoPath); + const fileIssueMode = readFileIssueMode(fileConfig.github); const merged: IGuardDogConfig = { ...DEFAULT_CONFIG, ...fileConfig, github: { - ...DEFAULT_CONFIG.github, - ...fileConfig.github + enabled: DEFAULT_CONFIG.github.enabled, + issueMode: fileIssueMode ?? DEFAULT_CONFIG.github.issueMode } }; @@ -123,6 +124,25 @@ export async function loadConfig( return merged; } +/** + * Reads issue layout from a target repo config. + * `enabled` and `repo` are ignored so the reviewed repository cannot open issues or choose the destination. + * @param github - GitHub section from the config file, if present + */ +function readFileIssueMode( + github: Partial | undefined +): IGuardDogConfig['github']['issueMode'] | undefined { + if (!github || typeof github !== 'object' || github.issueMode === undefined) { + return undefined; + } + if (github.issueMode === 'single' || github.issueMode === 'per-finding') { + return github.issueMode; + } + throw new InvalidParameterError( + `Invalid github.issueMode: ${String(github.issueMode)}. Expected single or per-finding.` + ); +} + function validateSeverity(value: string, fieldName: string): void { const allowed = ['low', 'medium', 'high', 'critical']; if (!allowed.includes(value)) { diff --git a/src/core/designLoader.ts b/src/core/designLoader.ts index c3aa63f..188b6b7 100644 --- a/src/core/designLoader.ts +++ b/src/core/designLoader.ts @@ -7,7 +7,7 @@ // ===Start StrongAI Generated Comment (20260524)=== // This module locates and loads an “architecture intent” or design document for a repository. It supports an explicit design file path or a set of default candidate filenames, and returns either the loaded content or a warning describing what was checked. // -// The main export is loadDesignFile(repoPath, designPath, logger). When designPath is provided, it resolves the path relative to the repo root (or uses it as-is if absolute), attempts to read it, and returns the content plus a normalized repo-relative filename. If the file is missing, it logs a warning and returns only the warning. When designPath is not provided, it iterates through DEFAULT_DESIGN_CANDIDATES under the repo root and returns the first file that exists. +// The main export is loadDesignFile(repoPath, designPath, logger). When designPath is provided, it resolves the path inside the repo root, rejects absolute paths, parent traversal, and symlinks, and returns the content plus a normalized repo-relative filename. Secret-like text, including private key blocks, is redacted before the content is returned. If the file is missing, it logs a warning and returns only the warning. When designPath is not provided, it iterates through DEFAULT_DESIGN_CANDIDATES under the repo root and returns the first file that exists, also redacted. // // It returns an IDesignLoadResult containing designFile, designContent, and/or warning. // @@ -16,7 +16,12 @@ import { DEFAULT_DESIGN_CANDIDATES } from '../schemas/config'; -import { readContainedRepoFile, resolveContainedRepoFile, redactSecrets } from '../utils/fileSystem'; +import { + readContainedRepoFile, + redactSecrets, + resolveContainedRepoFile, + toRepoRelativePath +} from '../utils/fileSystem'; import { ILogger, defaultLogger } from '../utils/logger'; export interface IDesignLoadResult { @@ -45,14 +50,14 @@ export async function loadDesignFile( logger.warn(warning); return { warning }; } - const relative = path.relative(repoPath, resolved).replace(/\\/g, '/'); + const relative = await toRepoRelativePath(repoPath, resolved); return { designFile: relative, designContent: redactSecrets(content) }; } for (const candidate of DEFAULT_DESIGN_CANDIDATES) { const content = await readContainedRepoFile(repoPath, candidate); if (content) { - return { designFile: candidate, designContent: content }; + return { designFile: candidate, designContent: redactSecrets(content) }; } } diff --git a/src/core/reviewer.ts b/src/core/reviewer.ts index 8371ab9..f39ff5b 100644 --- a/src/core/reviewer.ts +++ b/src/core/reviewer.ts @@ -9,7 +9,6 @@ // ===End StrongAI Generated Comment=== -import * as path from 'path'; import { loadConfig } from './configLoader'; import { loadDesignFile } from './designLoader'; import { generateRepoMap } from './repoScanner'; @@ -45,6 +44,11 @@ export async function runReview( ): Promise { const repoPath = await resolveRepoPath(cliOptions.repoPath); const config = await loadConfig(repoPath, cliOptions); + const markdownPath = await resolveContainedRepoFile(repoPath, config.outputMarkdown); + let jsonPath: string | undefined; + if (config.outputJson) { + jsonPath = await resolveContainedRepoFile(repoPath, config.outputJson); + } const c4Options = { componentFile: config.componentFile, @@ -112,7 +116,6 @@ export async function runReview( ); const markdown = renderMarkdownReview(validated); - const markdownPath = await resolveContainedRepoFile(repoPath, config.outputMarkdown); if (!cliOptions.dryRun) { await writeContainedRepoFile(repoPath, config.outputMarkdown, markdown); @@ -121,11 +124,7 @@ export async function runReview( logger.info(`[dry-run] Would write Markdown to ${markdownPath}`); } - let jsonPath: string | undefined; - if (config.outputJson) { - jsonPath = path.isAbsolute(config.outputJson) - ? config.outputJson - : path.join(repoPath, config.outputJson); + if (config.outputJson && jsonPath) { if (!cliOptions.dryRun) { await writeContainedRepoFile(repoPath, config.outputJson, JSON.stringify(validated, null, 2)); logger.info(`JSON review written to ${jsonPath}`); diff --git a/src/schemas/config.ts b/src/schemas/config.ts index 2b77152..f7ef283 100644 --- a/src/schemas/config.ts +++ b/src/schemas/config.ts @@ -18,8 +18,11 @@ import { FindingImpact, FindingSeverity } from './finding'; export type IssueMode = 'single' | 'per-finding'; export interface IGuardDogGithubConfig { + /** True only when the CLI passes `--github-issue`. A target repo config cannot enable this. */ enabled: boolean; + /** May be set in the target repo config, or overridden with `--issue-mode`. */ issueMode: IssueMode; + /** Set only from the CLI `--repo` flag. A target repo config cannot choose the destination. */ repo?: string; } diff --git a/src/strongai/cloudPackageReviewer.ts b/src/strongai/cloudPackageReviewer.ts index 024875e..b0d3ee8 100644 --- a/src/strongai/cloudPackageReviewer.ts +++ b/src/strongai/cloudPackageReviewer.ts @@ -176,7 +176,7 @@ function buildCloudAgentPrompt(target: IStrongAiPlatformTarget): string { '', '## Task', `1. In the GuardDog clone: npm install && npm run build`, - ' - If private @jonverrier packages need auth, NODE_AUTH_TOKEN / OPENAI_API_KEY are already in the environment.', + ' - Private @jonverrier packages install only when NODE_AUTH_TOKEN is already set in the environment.', `2. Run GuardDog against ONLY this package path inside StrongAI:`, '```bash', `node /dist/cli/index.js review /${target.packagePath} \\`, diff --git a/src/utils/fileSystem.ts b/src/utils/fileSystem.ts index 3a4d032..2036eed 100644 --- a/src/utils/fileSystem.ts +++ b/src/utils/fileSystem.ts @@ -17,16 +17,19 @@ // ===End StrongAI Generated Comment=== +import { randomBytes } from 'crypto'; +import { constants } from 'fs'; import * as fs from 'fs/promises'; import * as path from 'path'; -import { constants } from 'fs'; import { minimatch } from 'minimatch'; import { InvalidParameterError } from './errors'; const MAX_FILE_SIZE_BYTES = 256 * 1024; +const REPORT_FILE_MODE = 0o600; +const TEMP_FILE_RANDOM_BYTES = 12; const SECRET_PATTERNS: readonly RegExp[] = [ /(?:api[_-]?key|secret|password|token|auth)\s*[:=]\s*(?!process\.env)['"]?[A-Za-z0-9_\-./+=]{8,}/gi, - /-----BEGIN (?:OPENSSH |RSA |EC |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (?:OPENSSH |RSA |EC |ENCRYPTED )?PRIVATE KEY-----/g, + /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g, /sk-[A-Za-z0-9]{20,}/g ]; @@ -169,17 +172,20 @@ export async function walkFiles(rootPath: string, gitignorePatterns: string[]): } /** - * Resolve a repository-controlled path. Reject traversal, absolute paths and - * symlinks (including symlinked parent directories) before accessing it. + * Resolves a repository-controlled path. + * Rejects absolute paths, parent traversal, NUL bytes, and symlinks, including symlinked parents. + * @param rootPath - Repository root + * @param relativePath - Path relative to the repository root + * @returns Absolute path inside the repository */ export async function resolveContainedRepoFile(rootPath: string, relativePath: string): Promise { - if (!relativePath || path.isAbsolute(relativePath) || path.win32.isAbsolute(relativePath)) { + if (!relativePath || relativePath.includes('\0') || isAbsoluteInputPath(relativePath)) { throw new InvalidParameterError('Repository file path must be relative'); } const root = await fs.realpath(rootPath); const candidate = path.resolve(root, relativePath); const rel = path.relative(root, candidate); - if (!rel || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) { + if (rel.length === 0 || relativeEscapesRoot(rel)) { throw new InvalidParameterError('Repository file path escapes the repository'); } let current = root; @@ -191,50 +197,90 @@ export async function resolveContainedRepoFile(rootPath: string, relativePath: s throw new InvalidParameterError('Symlink in repository file path is forbidden'); } } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') break; + if (isEnoent(error)) { + break; + } throw error; } } return candidate; } -/** Read an existing repository file with size limits and final-symlink protection. */ -export async function readContainedRepoFile(rootPath: string, relativePath: string): Promise { +/** + * Converts an absolute path to a POSIX path relative to the real repository root. + * @param rootPath - Repository root + * @param absolutePath - Absolute path already resolved inside the repository + */ +export async function toRepoRelativePath(rootPath: string, absolutePath: string): Promise { + const root = await fs.realpath(rootPath); + const relative = path.relative(root, absolutePath).replace(/\\/g, '/'); + if (relative.length === 0 || relativeEscapesRoot(relative)) { + throw new InvalidParameterError('Repository file path escapes the repository'); + } + return relative; +} + +/** + * Reads an existing repository file with a size limit. + * Returns undefined when the file is missing, too large, or contains NUL bytes. + * Symlinks are rejected. + * @param rootPath - Repository root + * @param relativePath - Path relative to the repository root + */ +export async function readContainedRepoFile( + rootPath: string, + relativePath: string +): Promise { const filename = await resolveContainedRepoFile(rootPath, relativePath); try { - const handle = await fs.open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); + const handle = await fs.open(filename, constants.O_RDONLY | noFollowFlag()); try { const stat = await handle.stat(); - if (!stat.isFile() || stat.size > MAX_FILE_SIZE_BYTES) return undefined; - return await handle.readFile({ encoding: 'utf8' }); + if (!stat.isFile() || stat.size > MAX_FILE_SIZE_BYTES) { + return undefined; + } + const content = await handle.readFile({ encoding: 'utf8' }); + if (content.includes('\0')) { + return undefined; + } + return content; } finally { await handle.close(); } } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + if (isEnoent(error)) { + return undefined; + } throw error; } } /** - * Atomically replace a report within the repository. The temporary file is - * exclusively created in the validated directory; rename replaces a symlink - * itself rather than following its target. + * Atomically replaces a report inside the repository. + * The temporary file is created in a validated directory. Rename replaces the destination name. + * Missing parent directories are created only when every segment stays inside the repository. + * @param rootPath - Repository root + * @param relativePath - Path relative to the repository root + * @param content - File content */ -export async function writeContainedRepoFile(rootPath: string, relativePath: string, content: string): Promise { +export async function writeContainedRepoFile( + rootPath: string, + relativePath: string, + content: string +): Promise { const filename = await resolveContainedRepoFile(rootPath, relativePath); - const parent = path.dirname(filename); - const realParent = await fs.realpath(parent); - const realRoot = await fs.realpath(rootPath); - const parentRel = path.relative(realRoot, realParent); - if (parentRel === '..' || parentRel.startsWith('..' + path.sep) || path.isAbsolute(parentRel)) { - throw new InvalidParameterError('Report destination escapes repository'); - } - const { randomBytes } = await import('crypto'); - const temporary = path.join(realParent, '.' + path.basename(filename) + '.' + randomBytes(12).toString('hex') + '.tmp'); + const realParent = await ensureContainedParentDirectory(rootPath, filename); + const temporary = path.join( + realParent, + `.${path.basename(filename)}.${randomBytes(TEMP_FILE_RANDOM_BYTES).toString('hex')}.tmp` + ); let created = false; try { - const handle = await fs.open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); + const handle = await fs.open( + temporary, + constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollowFlag(), + REPORT_FILE_MODE + ); created = true; try { await handle.writeFile(content, 'utf8'); @@ -242,12 +288,15 @@ export async function writeContainedRepoFile(rootPath: string, relativePath: str } finally { await handle.close(); } - // Check again before replacement. This is not a substitute for an + // Re-check immediately before replacement. This is not a substitute for an // OS-level sandbox if an attacker can mutate the tree concurrently. await resolveContainedRepoFile(rootPath, relativePath); await fs.rename(temporary, filename); + created = false; } finally { - if (created) await fs.unlink(temporary).catch(() => undefined); + if (created) { + await fs.unlink(temporary).catch(() => undefined); + } } } @@ -261,7 +310,9 @@ export async function readContextFile( relativePath: string ): Promise { const content = await readContainedRepoFile(rootPath, relativePath); - if (!content || content.includes('\\0')) return undefined; + if (content === undefined || content.length === 0 || content.includes('\0')) { + return undefined; + } return redactSecrets(content); } @@ -272,9 +323,70 @@ export async function readContextFile( export function redactSecrets(content: string): string { let redacted = content; for (const pattern of SECRET_PATTERNS) { + pattern.lastIndex = 0; redacted = redacted.replace(pattern, '[REDACTED]'); } return redacted; } +function isAbsoluteInputPath(relativePath: string): boolean { + return path.isAbsolute(relativePath) || path.win32.isAbsolute(relativePath) || path.posix.isAbsolute(relativePath); +} + +function relativeEscapesRoot(relative: string): boolean { + const normalized = relative.replace(/\\/g, '/'); + return normalized === '..' || normalized.startsWith('../') || path.win32.isAbsolute(normalized) || path.posix.isAbsolute(normalized); +} + +function isEnoent(error: unknown): boolean { + return Boolean(error) && typeof error === 'object' && (error as NodeJS.ErrnoException).code === 'ENOENT'; +} + +function noFollowFlag(): number { + return constants.O_NOFOLLOW ?? 0; +} + +/** + * Creates missing parent directories without following a symlink out of the repository. + * @param rootPath - Repository root + * @param filename - Absolute destination file path inside the repository + * @returns Real path of the parent directory + */ +async function ensureContainedParentDirectory(rootPath: string, filename: string): Promise { + const realRoot = await fs.realpath(rootPath); + const parent = path.dirname(filename); + const parentRel = path.relative(realRoot, parent); + if (relativeEscapesRoot(parentRel)) { + throw new InvalidParameterError('Report destination escapes repository'); + } + if (parentRel.length === 0) { + return realRoot; + } + + let current = realRoot; + for (const part of parentRel.split(path.sep)) { + current = path.join(current, part); + try { + const stat = await fs.lstat(current); + if (stat.isSymbolicLink()) { + throw new InvalidParameterError('Symlink in repository file path is forbidden'); + } + if (!stat.isDirectory()) { + throw new InvalidParameterError('Report destination parent is not a directory'); + } + } catch (error) { + if (!isEnoent(error)) { + throw error; + } + await fs.mkdir(current); + } + } + + const realParent = await fs.realpath(current); + if (relativeEscapesRoot(path.relative(realRoot, realParent))) { + throw new InvalidParameterError('Report destination escapes repository'); + } + return realParent; +} + export { MAX_FILE_SIZE_BYTES, DEFAULT_IGNORED_DIRS }; diff --git a/test/unit/configLoader.test.ts b/test/unit/configLoader.test.ts index 0dac1d3..8d63206 100644 --- a/test/unit/configLoader.test.ts +++ b/test/unit/configLoader.test.ts @@ -40,4 +40,33 @@ describe('configLoader', () => { expect(config.github.enabled).toBe(true); expect(config.github.repo).toBe('owner/repo'); }); + + it('ignores github.enabled and github.repo from the target repository config', async () => { + const configDir = path.join(FIXTURE_REPO, '.guarddog'); + await fs.mkdir(configDir, { recursive: true }); + await fs.writeFile( + path.join(configDir, 'guarddog.config.json'), + JSON.stringify({ + github: { + enabled: true, + repo: 'attacker/exfil', + issueMode: 'per-finding' + } + }) + ); + + const fromFile = await loadConfig(FIXTURE_REPO, { repoPath: FIXTURE_REPO }); + expect(fromFile.github.enabled).toBe(false); + expect(fromFile.github.repo).toBeUndefined(); + expect(fromFile.github.issueMode).toBe('per-finding'); + + const fromCli = await loadConfig(FIXTURE_REPO, { + repoPath: FIXTURE_REPO, + githubIssue: true, + repo: 'owner/repo' + }); + expect(fromCli.github.enabled).toBe(true); + expect(fromCli.github.repo).toBe('owner/repo'); + expect(fromCli.github.issueMode).toBe('per-finding'); + }); }); diff --git a/test/unit/fileSystem.test.ts b/test/unit/fileSystem.test.ts index ed45582..fb50e4c 100644 --- a/test/unit/fileSystem.test.ts +++ b/test/unit/fileSystem.test.ts @@ -18,4 +18,15 @@ describe('fileSystem', () => { expect(redactSecrets(source)).toContain('[REDACTED]'); expect(redactSecrets(source)).not.toContain('super-secret-value-here'); }); + + it('redacts OpenSSH private key blocks', () => { + const source = [ + '-----BEGIN OPENSSH PRIVATE KEY-----', + 'FAKE_PRIVATE_KEY_MATERIAL', + '-----END OPENSSH PRIVATE KEY-----' + ].join('\n'); + const redacted = redactSecrets(source); + expect(redacted).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + expect(redactSecrets(source)).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + }); }); diff --git a/test/unit/repositoryPathSecurity.test.ts b/test/unit/repositoryPathSecurity.test.ts index 80e1c23..682ef1f 100644 --- a/test/unit/repositoryPathSecurity.test.ts +++ b/test/unit/repositoryPathSecurity.test.ts @@ -1,12 +1,53 @@ +/** + * @module test/unit/repositoryPathSecurity.test + * Tests for repository path confinement and secret redaction. + */ +// Copyright (c) 2025 Jon Verrier + +import { expect } from 'expect'; import * as fs from 'fs/promises'; import * as os from 'os'; import * as path from 'path'; import { loadDesignFile } from '../../src/core/designLoader'; -import { readContextFile, redactSecrets, resolveContainedRepoFile, writeContainedRepoFile } from '../../src/utils/fileSystem'; +import { + readContextFile, + redactSecrets, + resolveContainedRepoFile, + writeContainedRepoFile +} from '../../src/utils/fileSystem'; +import { InvalidParameterError } from '../../src/utils/errors'; + +/** + * Returns false when this host cannot create the requested link type. + * Windows file symlinks need extra privilege; directory junctions do not. + */ +async function createSymlink( + target: string, + linkPath: string, + type: 'file' | 'dir' | 'junction' +): Promise { + try { + await fs.symlink(target, linkPath, type); + return true; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'EPERM' || code === 'EACCES') { + return false; + } + throw error; + } +} + +const OPENSSH_KEY = [ + '-----BEGIN OPENSSH PRIVATE KEY-----', + 'FAKE_PRIVATE_KEY_MATERIAL', + '-----END OPENSSH PRIVATE KEY-----' +].join('\n'); describe('repository path confinement', () => { let parent: string; let repo: string; + beforeEach(async () => { parent = await fs.mkdtemp(path.join(os.tmpdir(), 'guarddog-security-')); repo = path.join(parent, 'repo'); @@ -14,49 +55,102 @@ describe('repository path confinement', () => { await fs.writeFile(path.join(repo, 'DESIGN.md'), 'safe design'); await fs.writeFile(path.join(parent, 'private.txt'), 'HOST_SECRET'); }); - afterEach(async () => { await fs.rm(parent, { recursive: true, force: true }); }); - test.each(['../private.txt', '../../private.txt', '/etc/passwd', 'C:\\Users\\secret.txt'])( - 'rejects malicious design path %s', async (malicious) => { - await expect(loadDesignFile(repo, malicious)).rejects.toThrow(); + afterEach(async () => { + await fs.rm(parent, { recursive: true, force: true }); + }); + + it.each(['../private.txt', '../../private.txt', '/etc/passwd', 'C:\\Users\\secret.txt'])( + 'rejects malicious design path %s', + async (malicious) => { + await expect(loadDesignFile(repo, malicious)).rejects.toThrow(InvalidParameterError); + expect(await fs.readFile(path.join(parent, 'private.txt'), 'utf8')).toBe('HOST_SECRET'); } ); - test('rejects symlinks escaping the repo', async () => { - await fs.symlink(path.join(parent, 'private.txt'), path.join(repo, 'linked.txt')); - await expect(loadDesignFile(repo, 'linked.txt')).rejects.toThrow(); - await expect(readContextFile(repo, 'linked.txt')).rejects.toThrow(); + it('rejects a different Windows drive prefix', async () => { + if (process.platform !== 'win32') { + return; + } + const drive = path.parse(repo).root.toUpperCase(); + const otherDrivePath = drive.startsWith('C') ? 'D:secret.txt' : 'C:secret.txt'; + await expect(loadDesignFile(repo, otherDrivePath)).rejects.toThrow(InvalidParameterError); + }); + + it('rejects symlinks that leave the repository', async () => { + const created = await createSymlink(path.join(parent, 'private.txt'), path.join(repo, 'linked.txt'), 'file'); + if (!created) { + return; + } + await expect(loadDesignFile(repo, 'linked.txt')).rejects.toThrow(InvalidParameterError); + await expect(readContextFile(repo, 'linked.txt')).rejects.toThrow(InvalidParameterError); + expect(await fs.readFile(path.join(parent, 'private.txt'), 'utf8')).toBe('HOST_SECRET'); }); - test('rejects context traversal', async () => { - await expect(readContextFile(repo, '../private.txt')).rejects.toThrow(); + it('rejects context traversal', async () => { + await expect(readContextFile(repo, '../private.txt')).rejects.toThrow(InvalidParameterError); }); - test('redacts private key blocks in design and context', async () => { - const key = '-----BEGIN OPENSSH PRIVATE KEY-----\\nFAKE_PRIVATE_KEY_MATERIAL\\n-----END OPENSSH PRIVATE KEY-----'; - await fs.writeFile(path.join(repo, 'DESIGN.md'), key); - const design = await loadDesignFile(repo, 'DESIGN.md'); - expect(design.designContent).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); - expect(redactSecrets(key)).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + it('redacts private key blocks from explicit and default design files', async () => { + await fs.writeFile(path.join(repo, 'DESIGN.md'), OPENSSH_KEY); + const explicit = await loadDesignFile(repo, 'DESIGN.md'); + const fallback = await loadDesignFile(repo, undefined); + expect(explicit.designContent).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + expect(fallback.designContent).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + expect(redactSecrets(OPENSSH_KEY)).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); expect(await readContextFile(repo, 'DESIGN.md')).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); }); - test('refuses outside report destinations and safely replaces existing reports', async () => { - await expect(resolveContainedRepoFile(repo, '../outside.md')).rejects.toThrow(); - await expect(writeContainedRepoFile(repo, '../outside.md', 'data')).rejects.toThrow(); + it('redacts an unclosed private key block', () => { + const unclosed = '-----BEGIN OPENSSH PRIVATE KEY-----\nFAKE_PRIVATE_KEY_MATERIAL'; + expect(redactSecrets(unclosed)).not.toContain('FAKE_PRIVATE_KEY_MATERIAL'); + }); + + it('does not send files that contain NUL bytes', async () => { + await fs.writeFile(path.join(repo, 'binary.txt'), 'visible\0secret'); + expect(await readContextFile(repo, 'binary.txt')).toBeUndefined(); + }); + + it('refuses outside report destinations and replaces an existing report', async () => { + await expect(resolveContainedRepoFile(repo, '../outside.md')).rejects.toThrow(InvalidParameterError); + await expect(writeContainedRepoFile(repo, '../outside.md', 'data')).rejects.toThrow(InvalidParameterError); + expect(await fs.readFile(path.join(parent, 'private.txt'), 'utf8')).toBe('HOST_SECRET'); await writeContainedRepoFile(repo, 'DESIGN.md', 'updated'); expect(await fs.readFile(path.join(repo, 'DESIGN.md'), 'utf8')).toBe('updated'); }); - test('replaces a symlink destination without changing its target', async () => { - await fs.symlink(path.join(parent, 'private.txt'), path.join(repo, 'report.md')); - // The strict path guard rejects symlinks rather than replacing them. - await expect(writeContainedRepoFile(repo, 'report.md', 'result')).rejects.toThrow(); + it('creates a nested report directory inside the repository', async () => { + await writeContainedRepoFile(repo, 'out/review.md', 'result'); + expect(await fs.readFile(path.join(repo, 'out', 'review.md'), 'utf8')).toBe('result'); + }); + + it('does not write through a symlinked report path', async () => { + const created = await createSymlink(path.join(parent, 'private.txt'), path.join(repo, 'report.md'), 'file'); + if (!created) { + return; + } + await expect(writeContainedRepoFile(repo, 'report.md', 'result')).rejects.toThrow(InvalidParameterError); expect(await fs.readFile(path.join(parent, 'private.txt'), 'utf8')).toBe('HOST_SECRET'); }); - test('writes new reports with restrictive permissions', async () => { + it('does not write through a symlinked parent directory', async () => { + const outsideDir = path.join(parent, 'outside'); + await fs.mkdir(outsideDir); + const linkType = process.platform === 'win32' ? 'junction' : 'dir'; + const created = await createSymlink(outsideDir, path.join(repo, 'linked-dir'), linkType); + expect(created).toBe(true); + await expect(writeContainedRepoFile(repo, 'linked-dir/review.md', 'result')).rejects.toThrow( + InvalidParameterError + ); + expect(await fs.readdir(outsideDir)).toEqual([]); + }); + + it('writes a new report with owner-only permissions on posix', async () => { await writeContainedRepoFile(repo, 'report.md', 'result'); expect(await fs.readFile(path.join(repo, 'report.md'), 'utf8')).toBe('result'); + if (process.platform !== 'win32') { + const stat = await fs.stat(path.join(repo, 'report.md')); + expect(stat.mode & 0o777).toBe(0o600); + } }); }); diff --git a/test/unit/reviewStrongAiPlatforms.test.ts b/test/unit/reviewStrongAiPlatforms.test.ts new file mode 100644 index 0000000..89aa217 --- /dev/null +++ b/test/unit/reviewStrongAiPlatforms.test.ts @@ -0,0 +1,118 @@ +/** + * @module test/unit/reviewStrongAiPlatforms.test + * Tests for StrongAI cloud-review side effects. + */ +// Copyright (c) 2025 Jon Verrier + +import { expect } from 'expect'; +import * as fs from 'fs/promises'; +import * as os from 'os'; +import * as path from 'path'; +import { runReviewStrongAiPlatformsCommand } from '../../src/cli/commands/reviewStrongAiPlatforms'; +import { STRONGAI_PLATFORM_TARGETS } from '../../src/schemas/strongAiPlatforms'; +import { reviewStrongAiPackagesWithCloudAgents } from '../../src/strongai/cloudPackageReviewer'; + +jest.mock('../../src/strongai/cloudPackageReviewer', () => ({ + reviewStrongAiPackagesWithCloudAgents: jest.fn() +})); + +const launchCloudAgents = reviewStrongAiPackagesWithCloudAgents as jest.MockedFunction< + typeof reviewStrongAiPackagesWithCloudAgents +>; + +function restoreEnv(name: string, value: string | undefined): void { + if (value === undefined) { + delete process.env[name]; + return; + } + process.env[name] = value; +} + +const ISSUE_MARKDOWN = [ + '**Status:** open', + '**Type:** proposal', + '**GitHub:** pending', + '**Superseded by:** none', + '', + '# GuardDog architecture review: platform', + '' +].join('\n'); + +describe('reviewStrongAiPlatforms command', () => { + const originalCursorKey = process.env.CURSOR_API_KEY; + const originalOpenAiKey = process.env.OPENAI_API_KEY; + const originalNodeAuthToken = process.env.NODE_AUTH_TOKEN; + const originalGithubToken = process.env.GITHUB_TOKEN; + + afterEach(() => { + restoreEnv('CURSOR_API_KEY', originalCursorKey); + restoreEnv('OPENAI_API_KEY', originalOpenAiKey); + restoreEnv('NODE_AUTH_TOKEN', originalNodeAuthToken); + restoreEnv('GITHUB_TOKEN', originalGithubToken); + launchCloudAgents.mockReset(); + }); + + it('does not launch cloud agents on --dry-run', async () => { + delete process.env.CURSOR_API_KEY; + delete process.env.OPENAI_API_KEY; + delete process.env.NODE_AUTH_TOKEN; + process.env.GITHUB_TOKEN = 'github-token-should-stay-local'; + + const exitCode = await runReviewStrongAiPlatformsCommand(['--dry-run', '--packages', 'platform']); + + expect(exitCode).toBe(0); + expect(launchCloudAgents).not.toHaveBeenCalled(); + }); + + it('does not copy GITHUB_TOKEN into the cloud agent environment', async () => { + const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), 'guarddog-cloud-')); + process.env.CURSOR_API_KEY = 'cursor-test'; + process.env.OPENAI_API_KEY = 'openai-test'; + process.env.GITHUB_TOKEN = 'github-token-should-stay-local'; + delete process.env.NODE_AUTH_TOKEN; + launchCloudAgents.mockResolvedValue({ + drafts: [ + { + target: STRONGAI_PLATFORM_TARGETS[0], + fileName: 'guarddog-platform-architecture-review.md', + markdown: ISSUE_MARKDOWN, + title: 'GuardDog architecture review: platform' + } + ], + payloads: [] + }); + + try { + const exitCode = await runReviewStrongAiPlatformsCommand([ + '--packages', + 'platform', + '--out-dir', + outputDir + ]); + expect(exitCode).toBe(0); + expect(launchCloudAgents).toHaveBeenCalledTimes(1); + const options = launchCloudAgents.mock.calls[0][0]; + expect(options.nodeAuthToken).toBeUndefined(); + expect(JSON.stringify(options)).not.toContain('github-token-should-stay-local'); + } finally { + await fs.rm(outputDir, { recursive: true, force: true }); + } + }); + + it('forwards NODE_AUTH_TOKEN when the operator set it', async () => { + const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), 'guarddog-cloud-')); + process.env.CURSOR_API_KEY = 'cursor-test'; + process.env.OPENAI_API_KEY = 'openai-test'; + process.env.GITHUB_TOKEN = 'github-token-should-stay-local'; + process.env.NODE_AUTH_TOKEN = 'packages-token'; + launchCloudAgents.mockResolvedValue({ drafts: [], payloads: [] }); + + try { + await runReviewStrongAiPlatformsCommand(['--packages', 'platform', '--out-dir', outputDir]); + const options = launchCloudAgents.mock.calls[0][0]; + expect(options.nodeAuthToken).toBe('packages-token'); + } finally { + await fs.rm(outputDir, { recursive: true, force: true }); + } + }); +}); diff --git a/test/unit/reviewer.test.ts b/test/unit/reviewer.test.ts index ae0cc23..065cfd1 100644 --- a/test/unit/reviewer.test.ts +++ b/test/unit/reviewer.test.ts @@ -10,7 +10,7 @@ import * as findingParser from '../../src/core/findingParser'; import { runReview } from '../../src/core/reviewer'; import { PromptRepositoryLlmProvider } from '../../src/core/llmProvider'; import { DEFAULT_REVIEW_RESULT } from '../../src/schemas/finding'; -import { InvalidOperationError } from '../../src/utils/errors'; +import { InvalidOperationError, InvalidParameterError } from '../../src/utils/errors'; import * as fileSystem from '../../src/utils/fileSystem'; import { ILogger } from '../../src/utils/logger'; @@ -52,4 +52,25 @@ describe('reviewer', () => { expect(saveDebugSpy).not.toHaveBeenCalled(); expect(writeSpy).not.toHaveBeenCalled(); }); + + it('rejects a report path outside the repository before calling the LLM', async () => { + const llmProvider = { + getStructuredReview: jest.fn() + } as unknown as PromptRepositoryLlmProvider; + + await expect( + runReview( + { + repoPath: FIXTURE_REPO, + out: '../outside.md', + json: '../../.bashrc', + dryRun: true + }, + silentLogger(), + llmProvider + ) + ).rejects.toThrow(InvalidParameterError); + + expect(llmProvider.getStructuredReview).not.toHaveBeenCalled(); + }); });