Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(sdk): resolve document links against selected sources (#2430)

Michael D'Angelobbf65774a326
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index dd3599c3b..0e5943841 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -548,7 +548,9 @@ Use the separate `suggest-owners` command for explicit owner-only jobs.
Repeat `--knowledge-base PATH` for context: UTF-8 text files (including JSON and
SARIF), PDF, DOCX, or directories. Directory traversal skips other binary files;
explicit unsupported binary files are rejected. Bulk scans share this context
-with every repository.
+with every repository. Select external documents directly. Links in a checkout
+must stay inside it. For bulk scans with bare or separate Git storage, use
+canonical paths for shared documents and prompt files.
Use `--output-dir DIR` to choose where a scan saves its results. The directory
must be empty and outside the scanned directory and enclosing Git worktree.
@@ -1908,7 +1910,9 @@ request. It sends the config name without findings or account identifiers.
If the request fails, times out, or returns an invalid rubric, the built-in
rubric is used. An explicit `--rubric` (SDK `rubricPath`) skips the lookup and
uses your policy for every review. Rubrics and repeatable `--knowledge-base`
-context accept text, PDF, DOCX, and directories.
+context accept text, PDF, DOCX, and directories. Select external documents directly.
+Links in the artifact directory or a saved checkout must stay inside their source.
+When `--scan` cannot verify the saved checkout, use the document's canonical path.
Each finding is classified three times by default. `--runs N` accepts
an integer from 1 through 10; SDK options use `classificationRuns` with the same
@@ -2555,6 +2559,7 @@ Context inputs are optional and can be combined:
- Repeat `--knowledge-base PATH` to add files or directories. It uses the scan
document loader: UTF-8 text (including JSON and YAML), PDF, and DOCX. Directories
are searched recursively; binary files, symlinks, and Git metadata are skipped.
+ When validating from a Git checkout, select external documents directly.
Inline and file context are included in the prompt. Knowledge-base documents are
prepared in a temporary directory for Codex to read during the assessment, then
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 8f8ab763d..9536d3cec 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -1024,16 +1024,18 @@ export class CodexSecurity {
try {
throwIfAborted(signal);
const finding = standaloneFindingForPrompt(options.finding);
- const snapshot = options.knowledgeBasePaths?.length
- ? (options.knowledgeBaseSnapshot ??
- (await readKnowledgeBaseSnapshot(options.knowledgeBasePaths, signal)))
- : undefined;
+ let repository = options.repositoryPath;
+ let snapshot: KnowledgeBaseSnapshot | undefined;
let protectedRoots: string[] | undefined;
- if (snapshot !== undefined) {
- const repository = await normalizeRepository(
- resolveRepositoryPath(options.repositoryPath),
- signal,
- );
+ if (options.knowledgeBasePaths?.length) {
+ repository = await normalizeRepository(repository, signal);
+ snapshot =
+ options.knowledgeBaseSnapshot ??
+ (await readKnowledgeBaseSnapshot(
+ options.knowledgeBasePaths,
+ signal,
+ repository,
+ ));
protectedRoots = [
(await enclosingGitWorktreeRoot(repository, signal)) ?? repository,
...(await knowledgeBaseProtectedRoots(snapshot, signal)),
@@ -1042,7 +1044,7 @@ export class CodexSecurity {
// Cached validation may already own this output. Regeneration below still
// requires an empty directory through prepareOutputDir.
const inputs = await this.#prepareLocalInputs(
- options.repositoryPath,
+ repository,
options,
signal,
protectedRoots,
@@ -1754,6 +1756,8 @@ export class CodexSecurity {
const knowledgeBase = await prepareKnowledgeBase(
options.knowledgeBaseSnapshot ?? options.knowledgeBasePaths,
options.signal,
+ undefined,
+ inputs.repository,
);
await knowledgeBase.cleanup();
}
@@ -1960,6 +1964,7 @@ export class CodexSecurity {
options.knowledgeBasePaths,
signal,
outputDir,
+ inputs.repository,
);
}
notifyObserver(options, "onOutputDirReady")(outputDir);
@@ -2368,6 +2373,7 @@ export class CodexSecurity {
(await readKnowledgeBaseSnapshot(
options.knowledgeBasePaths,
signal,
+ repo,
)),
};
knowledgeBase = await prepareKnowledgeBase(
@@ -5431,6 +5437,8 @@ export class CodexSecurity {
const knowledgeBase = await prepareKnowledgeBase(
options.knowledgeBaseSnapshot ?? options.knowledgeBasePaths,
signal,
+ undefined,
+ local.repository,
);
await knowledgeBase.cleanup();
}
diff --git a/sdk/typescript/src/classify-scan-severity.ts b/sdk/typescript/src/classify-scan-severity.ts
index ac4d90d18..d7caee6b0 100644
--- a/sdk/typescript/src/classify-scan-severity.ts
+++ b/sdk/typescript/src/classify-scan-severity.ts
@@ -10,6 +10,7 @@ import {
import { loadContractWithScanDirectory } from "./contract.js";
import { CodexSecurityError } from "./errors.js";
import type { Finding } from "./models.js";
+import type { DocumentRoots } from "./prompt-files.js";
import { bundledPluginRoot } from "./runtime.js";
import { savedScanWorkbench } from "./saved-scan-bootstrap.js";
import {
@@ -17,6 +18,7 @@ import {
type SavedScanDependencies,
} from "./saved-scan.js";
import { SeverityStore } from "./severity-store.js";
+import { documentSourceRoot, nullIfMissingPath } from "./targets.js";
const CLASSIFICATION_FILE = "severity-classification.json";
export interface ScanSeverityClassification extends SeverityClassification {
@@ -69,11 +71,22 @@ export async function classifyScanSeverityInternal(
) {
throw new CodexSecurityError("Saved scan does not match expectedScanId.");
}
+ const target = scan["targetPath"];
+ // The workbench enables remediation only for the recorded checkout and revision.
+ const sourceRoot =
+ scan["remediationAvailable"] === true &&
+ typeof target === "string" &&
+ (options.rubricPath !== undefined || options.knowledgeBasePaths?.length)
+ ? await documentSourceRoot(target, options.signal).catch(
+ nullIfMissingPath,
+ )
+ : null;
return classifyScanDirectorySeverityInternal(
scan.scanDir,
{ ...options, expectedScanId: scan.scanId },
surface,
bootstrap?.protectedRoots,
+ sourceRoot === null ? null : [sourceRoot],
);
}
@@ -91,6 +104,7 @@ export async function classifyScanDirectorySeverityInternal(
options: ClassifyScanSeverityOptions = {},
surface: "sdk" | "cli" = "sdk",
protectedRoots: readonly string[] = [],
+ sourceRoots: DocumentRoots = [],
): Promise<ScanSeverityClassification> {
const { contract, scanDirectory } = await loadContractWithScanDirectory(
requestedDirectory,
@@ -120,6 +134,7 @@ export async function classifyScanDirectorySeverityInternal(
findings.map(({ findingId }) => findingId),
options.reprocess ?? false,
),
+ sourceRoots && [scanDirectory, ...sourceRoots],
)),
scanId: contract.manifest.scan.id,
};
diff --git a/sdk/typescript/src/classify-severity.ts b/sdk/typescript/src/classify-severity.ts
index 08cfc903b..a7de3ebc4 100644
--- a/sdk/typescript/src/classify-severity.ts
+++ b/sdk/typescript/src/classify-severity.ts
@@ -7,7 +7,8 @@ import { findingEntry } from "./value.js";
import { z } from "zod";
import { CodexSecurityError } from "./errors.js";
import { workflowDigest } from "./finding-workflow.js";
-import { readKnowledgeBaseDocuments } from "./knowledge-base.js";
+import { readKnowledgeBaseSnapshot } from "./knowledge-base.js";
+import type { DocumentRoots } from "./prompt-files.js";
import type { Finding } from "./models.js";
import {
runReadOnlyCodex,
@@ -123,6 +124,7 @@ export async function classifySeverityInternal(
options: ClassifySeverityOptions = {},
surface: "sdk" | "cli" = "sdk",
checkpoint?: SeverityClassificationCheckpoint,
+ roots?: DocumentRoots,
): Promise<SeverityClassification> {
options.signal?.throwIfAborted();
const classificationRuns = reviewRunsOption.parse(options.classificationRuns);
@@ -141,10 +143,10 @@ export async function classifySeverityInternal(
defaultRubric = await getDefaultSeverityRubric(options);
rubric = [defaultRubric.markdown];
} else {
- rubric = await readDocuments([options.rubricPath], options.signal);
+ rubric = await readDocuments([options.rubricPath], options.signal, roots);
}
const knowledge = options.knowledgeBasePaths?.length
- ? await readDocuments(options.knowledgeBasePaths, options.signal)
+ ? await readDocuments(options.knowledgeBasePaths, options.signal, roots)
: null;
const rubricCheckpointSha256 = workflowDigest(rubric);
const metadata = {
@@ -221,8 +223,12 @@ export async function classifySeverityInternal(
async function readDocuments(
paths: readonly string[],
signal?: AbortSignal,
+ roots?: DocumentRoots,
): Promise<string[]> {
- const contents = await readKnowledgeBaseDocuments(paths, signal);
+ const { documents } = await readKnowledgeBaseSnapshot(paths, signal, roots);
+ const contents = Object.keys(documents)
+ .sort()
+ .map((name) => documents[name]!);
if (contents.every((text) => !text.trim())) {
throw new CodexSecurityError("Classification documents must not be empty.");
}
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index f8d12b39a..374cf1aec 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -7083,11 +7083,21 @@ export async function main(
if (options.records)
throw new CodexSecurityError("Use validate --records alone.");
if (options.knowledgeBase.length > 0) {
- knowledgeBase = await prepareKnowledgeBase(
- options.knowledgeBase.map((path) =>
- resolveCliPath(dependencies.currentDirectory(), path),
- ),
+ const directory = dependencies.currentDirectory();
+ const checkout = await gitMarkerRoot(
+ directory,
+ undefined,
+ "nearest",
+ );
+ const paths = options.knowledgeBase.map((path) =>
+ resolveCliPath(directory, path),
+ );
+ const snapshot = await readKnowledgeBaseSnapshot(
+ paths,
+ undefined,
+ checkout ? [checkout] : [],
);
+ knowledgeBase = await prepareKnowledgeBase(snapshot);
}
exitCode = await runSkill(
"validation",
@@ -11909,6 +11919,7 @@ async function executeScan(
options.knowledgeBaseSnapshot = await readKnowledgeBaseSnapshot(
options.knowledgeBasePaths,
preparationAbortController.signal,
+ resolve(directory, expandHome(repository)),
);
}
if (arguments_.rerunInputIdentity !== undefined) {
diff --git a/sdk/typescript/src/knowledge-base.ts b/sdk/typescript/src/knowledge-base.ts
index a0ce4508e..386ac6a4f 100644
--- a/sdk/typescript/src/knowledge-base.ts
+++ b/sdk/typescript/src/knowledge-base.ts
@@ -15,8 +15,10 @@ import { basename, extname, join, resolve } from "node:path";
import { unzipSync } from "fflate";
import { SaxesParser } from "saxes";
import { ConfigurationError, errorMessage } from "./errors.js";
+import { checkDocumentPath, type DocumentRootSource } from "./prompt-files.js";
import { expandHome } from "./runtime.js";
import {
+ documentSourceRoot,
gitMarkerRoot,
isGitMetadataDirectory,
nullIfMissingFile,
@@ -61,11 +63,11 @@ export async function knowledgeBaseProtectedRoots(
export async function readKnowledgeBaseSnapshot(
paths: readonly string[],
signal?: AbortSignal,
+ roots: string | DocumentRootSource = [],
): Promise<KnowledgeBaseSnapshot> {
try {
const sources = new Set<string>();
const documents = new Set<string>();
-
for (const requested of paths) {
signal?.throwIfAborted();
if (!requested.trim())
@@ -84,6 +86,11 @@ export async function readKnowledgeBaseSnapshot(
}
const source = await realpath(path);
+ if (path !== source) {
+ if (typeof roots === "string")
+ roots = [await documentSourceRoot(roots, signal)];
+ await checkDocumentPath(path, source, roots, signal);
+ }
const selected = metadata.isDirectory()
? (await discover(source, signal)).sort()
: [source];
@@ -146,12 +153,13 @@ export async function prepareKnowledgeBase(
input: readonly string[] | KnowledgeBaseSnapshot,
signal?: AbortSignal,
directory?: string,
+ repository?: string,
): Promise<PreparedKnowledgeBase> {
try {
const snapshot =
"documents" in input
? input
- : await readKnowledgeBaseSnapshot(input, signal);
+ : await readKnowledgeBaseSnapshot(input, signal, repository);
const protectedRoots = await knowledgeBaseProtectedRoots(snapshot, signal);
const path = await mkdtemp(
join(await realpath(directory ?? tmpdir()), "codex-security-knowledge-"),
@@ -181,17 +189,6 @@ export async function prepareKnowledgeBase(
}
}
-/** @internal Read the same extracted document text used by scans. */
-export async function readKnowledgeBaseDocuments(
- paths: readonly string[],
- signal?: AbortSignal,
-): Promise<string[]> {
- const { documents } = await readKnowledgeBaseSnapshot(paths, signal);
- return Object.keys(documents)
- .sort()
- .map((name) => documents[name]!);
-}
-
async function discover(
directory: string,
signal?: AbortSignal,
diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.ts
index e46d745a2..14efbf940 100644
--- a/sdk/typescript/src/multiscan.ts
+++ b/sdk/typescript/src/multiscan.ts
@@ -45,7 +45,7 @@ import {
readKnowledgeBaseSnapshot,
type KnowledgeBaseSnapshot,
} from "./knowledge-base.js";
-import { resolveScanPrompts } from "./prompt-files.js";
+import { type DocumentRoots, resolveScanPrompts } from "./prompt-files.js";
import {
canonicalConfigPath,
createWindowsOutputDirectory,
@@ -56,6 +56,8 @@ import {
} from "./runtime.js";
import {
DiffTarget,
+ gitOutput,
+ nullIfMissingPath,
UNSUPPORTED_GIT_ENVIRONMENT,
resolveTargetPath,
type ScanMode,
@@ -196,28 +198,11 @@ export async function runMultiscan(
"Bulk scans do not support diff or working-tree scopes because their checkouts are clean, shallow snapshots. Use repository or path scopes instead.",
);
}
- const repositories: string[] = [];
- if (
- [
- [options.scanPrompt, options.scanPromptFile],
- [options.validationPrompt, options.validationPromptFile],
- [options.postScanPrompt, options.postScanPromptFile],
- ].some(([inline, file]) => inline === undefined && file !== undefined)
- ) {
- for (const repository of new Set(tasks.map((task) => task.repository))) {
- if (!isAbsolute(repository)) continue;
- try {
- repositories.push(await realpath(repository));
- } catch (error) {
- // Missing sources retain the campaign's per-repository failure behavior.
- const code = (error as NodeJS.ErrnoException).code;
- if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
- }
- }
- }
- // Shared inputs use actual local CSV sources as directory-link boundaries,
- // not the invocation directory, and are read once before any scan starts.
- const prompts = await resolveScanPrompts(options, repositories);
+ // Direct input paths need no source discovery. Prompts and knowledge share the result.
+ let pendingRoots: Promise<DocumentRoots> | undefined;
+ const documentRoots = () =>
+ (pendingRoots ??= bulkDocumentRoots(tasks, options.signal));
+ const prompts = await resolveScanPrompts(options, documentRoots);
const resolvedOptions: MultiscanOptions = {
...options,
...prompts,
@@ -267,6 +252,7 @@ export async function runMultiscan(
tasks,
output,
resumePluginRoot,
+ documentRoots,
);
return (await realpath(requestedOutput).catch(() => undefined)) === output
? { ...result, resultsPath: join(requestedOutput, "results.jsonl") }
@@ -281,25 +267,68 @@ export async function runMultiscan(
}
}
+async function bulkDocumentRoots(
+ tasks: readonly MultiscanTask[],
+ signal?: AbortSignal,
+): Promise<DocumentRoots> {
+ const roots: string[] = [];
+ for (const repository of new Set(tasks.map((task) => task.repository))) {
+ if (!isAbsolute(repository)) continue;
+ const source = await realpath(repository).catch(nullIfMissingPath);
+ if (source === null) {
+ // Git also accepts an omitted .git suffix; wholly missing rows fail at checkout.
+ if (await lstat(repository + ".git").catch(nullIfMissingPath))
+ return null;
+ continue;
+ }
+ // Only an ordinary worktree and its own .git directory share one boundary.
+ const marker = await lstat(join(source, ".git")).catch(nullIfMissingPath);
+ if (!marker?.isDirectory()) return null;
+ const layout = await gitOutput(
+ source,
+ [
+ "rev-parse",
+ "--path-format=relative",
+ "--show-toplevel",
+ "--git-common-dir",
+ ],
+ signal,
+ undefined,
+ source,
+ "utf8",
+ process.cwd(),
+ ).catch(() => null);
+ signal?.throwIfAborted();
+ if (layout !== "./\n.git" && layout !== "./\r\n.git") return null;
+ roots.push(source);
+ }
+ return roots;
+}
+
async function runCampaign(
options: MultiscanOptions,
tasks: MultiscanTask[],
output: string,
resumePluginRoot: () => Promise<string>,
+ documentRoots: () => Promise<DocumentRoots>,
): Promise<MultiscanResult> {
const ledger = join(output, "results.jsonl");
await ensureOutputDirectory(join(output, "checkouts"));
await ensureOutputDirectory(join(output, "artifacts"));
const knowledgeByMode: MultiscanKnowledge = {};
const sharedKnowledge = options.knowledgeBasePaths?.length
- ? readKnowledgeBaseSnapshot(options.knowledgeBasePaths, options.signal)
+ ? readKnowledgeBaseSnapshot(
+ options.knowledgeBasePaths,
+ options.signal,
+ documentRoots,
+ )
: undefined;
for (const mode of new Set(tasks.map((task) => task.mode))) {
try {
const paths = options.scanOptionsByMode?.[mode]?.knowledgeBasePaths;
const snapshot = await (sharedKnowledge ??
(paths?.length
- ? readKnowledgeBaseSnapshot(paths, options.signal)
+ ? readKnowledgeBaseSnapshot(paths, options.signal, documentRoots)
: undefined));
if (snapshot !== undefined) knowledgeByMode[mode] = { snapshot };
} catch (error) {
diff --git a/sdk/typescript/src/prompt-files.ts b/sdk/typescript/src/prompt-files.ts
index e232d3c27..ef8e1c65e 100644
--- a/sdk/typescript/src/prompt-files.ts
+++ b/sdk/typescript/src/prompt-files.ts
@@ -1,15 +1,23 @@
import { constants, type BigIntStats } from "node:fs";
-import { lstat, open, realpath } from "node:fs/promises";
-import { basename, dirname, join, relative } from "node:path";
-import { CodexSecurityError } from "./errors.js";
+import { lstat, open, readlink, realpath } from "node:fs/promises";
import {
- resolveInputPath,
- resolveParentTraversal,
- validateDirectoryLinks,
-} from "./runtime.js";
-import { relativePathIsOutside as isOutsidePath } from "./targets.js";
+ basename,
+ dirname,
+ format,
+ isAbsolute,
+ join,
+ parse,
+ sep,
+} from "node:path";
+import { CodexSecurityError } from "./errors.js";
+import { resolveInputPath, resolveParentTraversal } from "./runtime.js";
+import { isWithin } from "./trusted-executable.js";
import type { ScanPromptSettings } from "./scan-settings.js";
+/** Canonical source directories, or null when a checkout cannot be verified. */
+export type DocumentRoots = readonly string[] | null;
+export type DocumentRootSource = DocumentRoots | (() => Promise<DocumentRoots>);
+
type ResolvedScanPrompts = Pick<
ScanPromptSettings,
"scanPrompt" | "validationPrompt" | "postScanPrompt"
@@ -22,7 +30,7 @@ type ResolvedScanPrompts = Pick<
/** Resolve selected files once; an inline SDK prompt overrides its file. */
export async function resolveScanPrompts(
options: ScanPromptSettings,
- repository: string | readonly string[],
+ repository: string | DocumentRootSource,
directory = process.cwd(),
): Promise<ResolvedScanPrompts> {
const read = async (inline: string | undefined, file: string | undefined) =>
@@ -62,36 +70,71 @@ export async function resolveScanPrompts(
};
}
+/** A selected source cannot use a directory link to supply a document outside it. */
+export async function checkDocumentPath(
+ path: string,
+ canonical: string,
+ source: DocumentRootSource,
+ signal?: AbortSignal,
+): Promise<void> {
+ if (path === canonical) return;
+ const roots = typeof source === "function" ? await source() : source;
+ const outside = roots?.filter((root) => !isWithin(root, canonical));
+ if (outside?.length === 0) return;
+
+ const directories = new Set([dirname(path)]);
+ for (const directory of directories) {
+ const parsed = parse(directory);
+ if (!parsed.base) continue;
+ directories.add(parsed.dir);
+ signal?.throwIfAborted();
+ // A trailing slash would make lstat follow the link. Keep any raw "..".
+ const entry = format(parsed);
+ if (!(await lstat(entry)).isSymbolicLink()) continue;
+ if (!outside) {
+ throw new CodexSecurityError(
+ "Select the document by its canonical path when the source checkout is unknown.",
+ );
+ }
+ const owner = await realpath(await resolveParentTraversal(parsed.dir));
+ if (outside.some((root) => isWithin(root, owner))) {
+ throw new CodexSecurityError(
+ `Input files must not follow repository directory links outside the selected repository: ${entry}`,
+ );
+ }
+ // An external alias can point through a directory link inside a checkout.
+ const target = await readlink(entry);
+ directories.add(isAbsolute(target) ? target : `${owner}${sep}${target}`);
+ }
+}
+
export async function readRegularInputFile(
path: string,
- repository: string | readonly string[],
+ repository: string | DocumentRootSource,
metadata?: Pick<BigIntStats, "isFile" | "dev" | "ino">,
): Promise<string> {
const selected = metadata ?? (await lstat(path, { bigint: true }));
if (!selected.isFile()) {
throw new CodexSecurityError("Input files must be regular files.");
}
- const canonicalParent = await realpath(
- await resolveParentTraversal(dirname(path)),
+ const canonical = join(
+ await realpath(await resolveParentTraversal(dirname(path))),
+ basename(path),
+ );
+ const roots = typeof repository === "string" ? [repository] : repository;
+ await checkDocumentPath(
+ path,
+ canonical,
+ Array.isArray(roots)
+ ? await Promise.all(
+ roots.map(async (root: string) =>
+ realpath(await resolveParentTraversal(root)),
+ ),
+ )
+ : roots,
);
- const repositories =
- typeof repository === "string" ? [repository] : repository;
- for (const repository of repositories) {
- const canonicalRepository = await realpath(
- await resolveParentTraversal(repository),
- );
- if (isOutsidePath(relative(canonicalRepository, canonicalParent))) {
- await validateDirectoryLinks(path, (link) => {
- if (!isOutsidePath(relative(canonicalRepository, link))) {
- throw new CodexSecurityError(
- "Input files must not follow repository directory links outside the selected repository.",
- );
- }
- });
- }
- }
const file = await open(
- join(canonicalParent, basename(path)),
+ canonical,
constants.O_RDONLY |
(constants.O_NOFOLLOW ?? 0) |
(constants.O_NONBLOCK ?? 0),
diff --git a/sdk/typescript/src/targets.ts b/sdk/typescript/src/targets.ts
index 4dcd59e2f..a4b58cc7b 100644
--- a/sdk/typescript/src/targets.ts
+++ b/sdk/typescript/src/targets.ts
@@ -975,6 +975,17 @@ export async function gitOutput(
);
}
+/** Bound repository-supplied document links to the selected checkout or directory. */
+export async function documentSourceRoot(
+ repository: string,
+ signal?: AbortSignal,
+): Promise<string> {
+ return (
+ (await gitMarkerRoot(repository, signal, "nearest")) ??
+ (await realpath(repository))
+ );
+}
+
export async function gitMarkerRoot(
repository: string,
signal: AbortSignal | undefined,
diff --git a/sdk/typescript/tests-ts/api-validation-guidance.test.ts b/sdk/typescript/tests-ts/api-validation-guidance.test.ts
index be4c8df4e..36d74c8bd 100644
--- a/sdk/typescript/tests-ts/api-validation-guidance.test.ts
+++ b/sdk/typescript/tests-ts/api-validation-guidance.test.ts
@@ -7,6 +7,7 @@ import {
rename,
rm,
stat,
+ symlink,
writeFile,
} from "node:fs/promises";
import * as fsPromises from "node:fs/promises";
@@ -32,6 +33,47 @@ describe("CodexSecurity finding validation", () => {
temporaryDirectory,
} = createValidationFixtures();
+ for (const sourceOwned of [false, true]) {
+ test(`validates knowledge directory links against the traversed repository (source-owned=${sourceOwned})`, async () => {
+ const fixture = await validationClient();
+ await using client = fixture.client;
+ const spelling = join(fixture.root, "spelling");
+ const child = join(fixture.root, "child");
+ const documents = join(fixture.root, "documents");
+ await Promise.all([mkdir(spelling), mkdir(child), mkdir(documents)]);
+ await symlink(child, join(spelling, "jump"), "junction");
+ const lexical = join(spelling, "repository");
+ if (sourceOwned || process.platform === "win32") {
+ await mkdir(lexical);
+ execFileSync("git", ["init", "--quiet", lexical]);
+ }
+ const repository =
+ process.platform === "win32" ? lexical : fixture.options.repositoryPath;
+ const alias = join(sourceOwned ? repository : spelling, "knowledge");
+ await symlink(documents, alias, "junction");
+ await writeFile(
+ join(documents, "policy.md"),
+ "Synthetic operator guidance.",
+ );
+ const result = client.validate({
+ ...fixture.options,
+ repositoryPath: `${spelling}/jump/../repository`,
+ knowledgeBasePaths: [join(alias, "policy.md")],
+ });
+ if (sourceOwned) {
+ await expect(result).rejects.toThrow(
+ "repository directory links outside the selected repository",
+ );
+ expect(fixture.captured.thread).toBeUndefined();
+ } else {
+ await expect(result).resolves.toMatchObject(assessment);
+ expect(fixture.captured.codex?.env?.["CODEX_SECURITY_REPOSITORY"]).toBe(
+ await fsPromises.realpath(repository),
+ );
+ }
+ });
+ }
+
test("invalidates cached validation when inline instructions change", async () => {
let modelCalls = 0;
let instructions = "Original standalone validation instructions.";
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index cac359e6a..13f1971e6 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -921,6 +921,12 @@ describe("CodexSecurity orchestration", () => {
"Knowledge base directory contains no supported documents",
],
];
+ const redirected = join(repository, "documents");
+ await symlink(root, redirected, "junction");
+ invalidDocuments.push([
+ join(redirected, "context.json"),
+ "repository directory links",
+ ]);
if (process.platform !== "win32") {
const linkedDocument = join(root, "linked.md");
await symlink(knowledgeBase, linkedDocument);
diff --git a/sdk/typescript/tests-ts/classify-scan-severity.test.ts b/sdk/typescript/tests-ts/classify-scan-severity.test.ts
index a04fb4cec..fc5178cef 100644
--- a/sdk/typescript/tests-ts/classify-scan-severity.test.ts
+++ b/sdk/typescript/tests-ts/classify-scan-severity.test.ts
@@ -5,6 +5,8 @@ import {
chmod,
mkdir,
readFile,
+ realpath,
+ rename,
rm,
symlink,
writeFile,
@@ -186,6 +188,39 @@ test("classifies and reads a saved scan with an embedded NUL in its ID without P
).toEqual(classification);
});
+test("saved scan artifacts cannot redirect knowledge-base reads", async () => {
+ const { scanDirectory, root, environment, rubricPath } = await fixture();
+ const alias = join(scanDirectory, "documents");
+ await symlink(root, alias, "junction");
+ await expect(
+ classifyScanDirectorySeverity(scanDirectory, {
+ environment,
+ findingIds: [],
+ rubricPath,
+ knowledgeBasePaths: [join(alias, "policy.md")],
+ }),
+ ).rejects.toThrow(/symbolic link|directory link/i);
+});
+
+test("classifying a saved scan ID checks document links in its source directory", async () => {
+ const { environment, repository, root, scanId } = await savedFixture();
+ await symlink(root, join(repository, "documents"), "junction");
+ const classify = (directory: string) =>
+ classifyScanSeverityInternal(scanId, {
+ environment,
+ findingIds: [],
+ rubricPath: join(directory, "documents", "policy.md"),
+ });
+ await expect(classify(repository)).rejects.toThrow(
+ /symbolic link|directory link/i,
+ );
+ const moved = join(root, "moved");
+ await rename(repository, moved);
+ await expect(classify(moved)).rejects.toThrow("canonical path");
+ await mkdir(repository);
+ await expect(classify(moved)).rejects.toThrow("canonical path");
+});
+
test("severity helpers skip Node executables in the caller's enclosing checkout", async () => {
const { root, environment, scanDirectory } = await fixture();
const repository = join(root, "repository");
@@ -304,6 +339,7 @@ test.each(["id", "prefix", "latest", "missing target"])(
{
environment,
expectedScanId: f.scanId,
+ rubricPath: await realpath(f.rubricPath),
codex: recordingClassifier().codex,
},
{
diff --git a/sdk/typescript/tests-ts/cli-project-config.test.ts b/sdk/typescript/tests-ts/cli-project-config.test.ts
index 943aabba4..076b9ad0a 100644
--- a/sdk/typescript/tests-ts/cli-project-config.test.ts
+++ b/sdk/typescript/tests-ts/cli-project-config.test.ts
@@ -321,6 +321,26 @@ test.each([undefined, "standard", "daybreak_red"] as const)(
},
);
+test("validation rejects knowledge selected through a checkout link", async () => {
+ const input = await fixture({});
+ git(input.repository, "init", "--quiet");
+ const link = join(input.repository, "documents");
+ await symlink(input.configDirectory, link, "junction");
+ for (const command of [
+ ["scan", "--validate"],
+ ["validate", "candidate"],
+ ]) {
+ const stderr = captureCli(main, "stderr");
+ expect(
+ await stderr.run(
+ [...command, "--knowledge-base", join(link, "scan.json")],
+ dependencies({ currentDirectory: input.repository }),
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain("repository directory links");
+ }
+});
+
test("a missing operator-selected environment file fails without falling back", async () => {
const input = await fixture({});
const onConfig = mock();
@@ -422,6 +442,7 @@ test.each(["instructions_file", "validation_file"] as const)(
scan: { [file]: "../repository/linked/prompt.md" },
output: { directory: "../batch-results" },
});
+ git(input.repository, "init", "--quiet");
const external = join(input.root, "external");
await mkdir(external);
await writeFile(join(external, "prompt.md"), "Synthetic external data.");
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index 485ea9503..ab5b76e5f 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -1737,9 +1737,12 @@ describe("CLI workbench", () => {
test("reruns canonical recipes with exact config, policy, plugin, and lineage", async () => {
const onConfig = mock<(config: CodexSecurityConfig) => void>();
const onTurn = mock<(repository: string, options: ScanOptions) => void>();
- const knowledgeRoot = await temporaryDirectory("rerun-knowledge-");
+ const root = await temporaryDirectory("rerun-recipe-");
try {
- const knowledgeBasePath = join(knowledgeRoot, "security.md");
+ const repository = join(root, "repository");
+ await mkdir(join(repository, "src"), { recursive: true });
+ await mkdir(join(repository, "packages", "core"), { recursive: true });
+ const knowledgeBasePath = join(root, "security.md");
await writeFile(knowledgeBasePath, "Synthetic architecture context.\n");
const savedConfig = {
approval_policy: "on-request",
@@ -1758,7 +1761,7 @@ describe("CLI workbench", () => {
onWorkbench: () => ({
scanId: "scan-original",
recipe: {
- repository: "/original/repository",
+ repository,
target: { kind: "paths", paths: ["src", "packages/core"] },
mode: "deep",
pluginVersion: "1.2.3",
@@ -1778,7 +1781,7 @@ describe("CLI workbench", () => {
),
).toBe(0);
expect(onConfig.mock.lastCall?.[0]?.codexOverrides).toEqual(savedConfig);
- expect(onTurn.mock.lastCall?.[0]).toBe("/original/repository");
+ expect(onTurn.mock.lastCall?.[0]).toBe(repository);
expect(onTurn.mock.lastCall?.[1]).toMatchObject({
target: ["src", "packages/core"],
mode: "deep",
@@ -1793,7 +1796,7 @@ describe("CLI workbench", () => {
maxTimeHours: 1.5,
});
} finally {
- await rm(knowledgeRoot, { recursive: true, force: true });
+ await rm(root, { recursive: true, force: true });
}
const references: Array<[JsonObject, ReturnType<typeof DiffTarget.refs>]> =
diff --git a/sdk/typescript/tests-ts/knowledge-base.test.ts b/sdk/typescript/tests-ts/knowledge-base.test.ts
index 77d763301..59422e7e7 100644
--- a/sdk/typescript/tests-ts/knowledge-base.test.ts
+++ b/sdk/typescript/tests-ts/knowledge-base.test.ts
@@ -1048,6 +1048,32 @@ describe("scan knowledge bases", () => {
);
});
+ test("checks each directory link on the way to an external document", async () => {
+ const repository = await temporaryDirectory();
+ const external = await temporaryDirectory();
+ await writeFile(join(external, "guide.md"), "External policy.");
+ const escape = join(repository, "outside");
+ const viaRepository = join(external, "via-repository");
+ const operatorAlias = join(external, "current");
+ await symlink(external, escape, "junction");
+ await symlink(escape, viaRepository, "junction");
+ await symlink(external, operatorAlias, "junction");
+ const read = (directory: string, checkout: string) =>
+ readKnowledgeBaseSnapshot(
+ [join(directory, "guide.md")],
+ undefined,
+ checkout,
+ );
+ await expect(read(viaRepository, repository)).rejects.toThrow(
+ "repository directory links",
+ );
+ for (const checkout of [repository, external]) {
+ expect(
+ Object.values((await read(operatorAlias, checkout)).documents),
+ ).toEqual(["External policy."]);
+ }
+ });
+
testPosix("rejects unreadable source documents", async () => {
const root = await temporaryDirectory();
const source = join(root, "scope.md");
diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.ts
index f290c4dce..cb354c6f0 100644
--- a/sdk/typescript/tests-ts/multiscan.test.ts
+++ b/sdk/typescript/tests-ts/multiscan.test.ts
@@ -154,6 +154,56 @@ second,${source.path},${source.revision}
]);
});
+ test("checks linked bulk documents against the selected Git layout", async () => {
+ const { paths, source } = await repositoryFixture("source");
+ const settings = options(paths, client(completeRun), { maxAttempts: 1 });
+ const direct = join(await filesystem.realpath(paths.root), "policy.md");
+ await writeFile(direct, "External document.");
+ const docs = join(source.path, "docs");
+ await filesystem.symlink(paths.root, docs, "junction");
+ const linked = join(docs, "policy.md");
+
+ const { resultsPath } = await runMultiscan({
+ ...settings,
+ knowledgeBasePaths: [linked],
+ });
+ expect(await results(resultsPath)).toMatchObject([
+ {
+ status: "failed",
+ error: expect.stringContaining("repository directory links"),
+ },
+ ]);
+
+ const requireCanonical = async (repository: string) => {
+ await writeFile(
+ paths.input,
+ `id,repository,revision\nrow,${repository},${source.revision}\n`,
+ );
+ await expect(
+ runMultiscan({ ...settings, scanPromptFile: linked }),
+ ).rejects.toThrow("canonical path");
+ };
+
+ const gitfile = join(source.path, "target.ref");
+ await writeFile(
+ gitfile,
+ `gitdir: ${git(source.path, "rev-parse", "--absolute-git-dir")}\n`,
+ );
+ await requireCanonical(gitfile);
+ const directRun = await runMultiscan({
+ ...settings,
+ outputDir: join(paths.root, "direct-run"),
+ knowledgeBasePaths: [direct],
+ });
+ expect(directRun.completed).toBe(1);
+
+ const archive = join(paths.root, "archive");
+ git(paths.root, "clone", "--bare", source.path, archive + ".git");
+ await requireCanonical(archive);
+ git(source.path, "config", "core.worktree", paths.root);
+ await requireCanonical(source.path);
+ });
+
test.each([DiffTarget.refs({ base: "HEAD~1" }), DiffTarget.workingTree()])(
"rejects unsupported bulk diff scopes before preparing a campaign: %j",
async (target) => {