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(paths)!: preserve physical parent traversal (#1709)

Michael D'Angelo4aa9acc5ce45
diff --git a/plugins/codex-security/mcp-app/tests/support/temporary-directories.ts b/plugins/codex-security/mcp-app/tests/support/temporary-directories.ts
index 63711e67a..b12f78f36 100644
--- a/plugins/codex-security/mcp-app/tests/support/temporary-directories.ts
+++ b/plugins/codex-security/mcp-app/tests/support/temporary-directories.ts
@@ -5,7 +5,7 @@ import { join } from "node:path";
export function createTemporaryDirectories(
canonicalize = false,
removeDirectory = (root: string) =>
- rm(root, { recursive: true, force: true }),
+ rm(root, { recursive: true, force: true, maxRetries: 10 }),
) {
const roots: string[] = [];
return {
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index ae0887337..57409bb69 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1402,6 +1402,12 @@ require a new output directory. Version 1 manifests also require a new directory
because their original knowledge inputs and direct overrides cannot be verified.
Worker and retry counts can change when resuming.
+On POSIX, local repository paths retain `..` components in the campaign manifest
+so distinct symlink traversals remain distinct sources. Older campaigns may have
+recorded a normalized absolute path instead. Use that recorded path to resume the
+previously selected source; it can differ from the physical target selected by
+the original traversal. Use a new output directory to scan the corrected target.
+
### Recovering failed or interrupted bulk scans
Use the original CSV, output directory, and options:
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 6a0b231e2..bc6bbab97 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -293,6 +293,7 @@ import {
resolvePluginPath,
resolvePluginSource,
resolvePluginPython,
+ resolveScanOutputPath,
runWorkbench,
setCodexSecurityCredentialLogout,
type CodexCommand,
@@ -886,10 +887,14 @@ export class CodexSecurity {
);
const artifactRoots: string[] = [];
if (options.outputDir !== undefined) {
- await workflow.protectArtifacts(options.outputDir);
- artifactRoots.push(
- await canonicalConfigPath(expandHome(options.outputDir)),
+ options.outputDir = await resolveScanOutputPath(
+ options.outputDir,
+ (path) => requireOutputOutsideRepositories(local.protectedRoots, path),
);
+ const canonicalOutput = await canonicalConfigPath(options.outputDir);
+ requireOutputOutsideRepositories(local.protectedRoots, canonicalOutput);
+ await workflow.protectArtifacts(options.outputDir);
+ artifactRoots.push(canonicalOutput);
}
const state = await workflow.bind({
repositoryPath: local.repository,
@@ -900,10 +905,6 @@ export class CodexSecurity {
...local.prompts,
target: options.target ?? "repository",
mode: options.mode ?? DEFAULT_SCAN_MODE,
- outputDir:
- options.outputDir === undefined
- ? undefined
- : resolve(expandHome(options.outputDir)),
workflowId: undefined,
severityRubric: undefined,
rubricPath: undefined,
@@ -6549,13 +6550,16 @@ async function prepareScanOutputDir(
protectedRoots: readonly string[],
allowExistingOutput = false,
): Promise<string | null> {
+ const validateLocation = (path: string) =>
+ requireOutputOutsideRepositories(protectedRoots, path);
const output = await validateOutputDir(
options.outputDir,
allowExistingOutput ||
options.resumeScanId !== undefined ||
options.archiveExisting,
+ validateLocation,
);
- if (output !== null) requireOutputOutsideRepositories(protectedRoots, output);
+ if (output !== null) validateLocation(output);
return output;
}
diff --git a/sdk/typescript/src/artifact-export.ts b/sdk/typescript/src/artifact-export.ts
index b0543bab0..49d3311ee 100644
--- a/sdk/typescript/src/artifact-export.ts
+++ b/sdk/typescript/src/artifact-export.ts
@@ -15,6 +15,8 @@ import {
bundledPluginRoot,
codexSecurityStateDirectory,
expandHome,
+ resolveInputPath,
+ resolveParentTraversal,
pythonUtf8Environment,
resolvePluginPython,
runWorkbench,
@@ -89,6 +91,27 @@ interface HelperOptions {
failureMessage?: string;
}
+export async function artifactSourceProtectionRoots(
+ sourceRoot: string | undefined,
+ directory = process.cwd(),
+): Promise<string[] | undefined> {
+ return (await resolveArtifactSource(sourceRoot, directory))?.protectedRoots;
+}
+
+async function resolveArtifactSource(
+ sourceRoot: string | undefined,
+ directory = process.cwd(),
+) {
+ if (sourceRoot === undefined) return;
+ const path = await resolveParentTraversal(sourceRoot);
+ return {
+ path,
+ protectedRoots: [
+ ...new Set([directory, resolve(directory, sourceRoot), path]),
+ ],
+ };
+}
+
export function resolveArtifactFormat(
artifact: ExportArtifactKind,
format?: ExportFormat,
@@ -220,6 +243,7 @@ export async function runArtifactExport(
): Promise<string | undefined> {
const artifact = arguments_.artifact ?? "findings";
resolveArtifactFormat(artifact, arguments_.format, arguments_.avitTemplate);
+ const source = await resolveArtifactSource(arguments_.sourceRoot);
const result = await runArtifactHelper(
[
"--scan-dir",
@@ -233,17 +257,12 @@ export async function runArtifactExport(
...(arguments_.output === "-"
? []
: ["--export-output", arguments_.output]),
- ...(arguments_.sourceRoot === undefined
- ? []
- : ["--source-root", arguments_.sourceRoot]),
+ ...(source === undefined ? [] : ["--source-root", source.path]),
...(arguments_.includeMetadata ? ["--export-metadata"] : []),
],
{
pythonPath: arguments_.pythonPath,
- protectedRoot:
- arguments_.sourceRoot === undefined
- ? undefined
- : [process.cwd(), arguments_.sourceRoot],
+ protectedRoot: source?.protectedRoots,
signal: arguments_.signal,
failureMessage:
artifact === "findings"
@@ -265,10 +284,11 @@ export async function resolveArtifactExportOutput(
arguments_: ArtifactExportArguments,
currentDirectory: string,
): Promise<ArtifactExportArguments> {
- const canonicalScan = await realpath(arguments_.scanDir).catch(
- () => arguments_.scanDir,
- );
- const scanRelativeOutput = relative(arguments_.scanDir, arguments_.output);
+ const scanDir = await resolveParentTraversal(arguments_.scanDir, {
+ allowMissing: true,
+ });
+ const canonicalScan = await realpath(scanDir).catch(() => scanDir);
+ const scanRelativeOutput = relative(scanDir, arguments_.output);
const scanLocalOutput = join(
"exports",
ARTIFACT_EXPORT_FILENAMES[arguments_.format],
@@ -394,20 +414,19 @@ export async function exportArtifact(
const sourceRoot =
options.sourceRoot === undefined
? undefined
- : resolve(expandHome(options.sourceRoot));
+ : resolveInputPath(options.sourceRoot);
const environment = {
...exportEnvironment(),
CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
};
let directory: string;
if (options.source.directory !== undefined) {
- directory = resolve(expandHome(options.source.directory));
+ directory = resolveInputPath(options.source.directory);
} else {
const python = await resolvePluginPython({
configuredPath: options.pythonPath,
environment,
- protectedRoot:
- sourceRoot === undefined ? undefined : [process.cwd(), sourceRoot],
+ protectedRoot: await artifactSourceProtectionRoots(sourceRoot),
signal: options.signal,
});
const pluginRoot = await bundledPluginRoot();
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 2048c4573..eda7efad8 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -52,6 +52,7 @@ import {
parse,
relative,
resolve,
+ sep,
win32,
} from "node:path";
import { cwd } from "node:process";
@@ -81,6 +82,7 @@ import {
ARTIFACT_EXPORT_FILENAMES,
exportEnvironment,
resolveArtifactFormat,
+ artifactSourceProtectionRoots,
resolveArtifactExportOutput,
resolveSavedArtifactDirectory,
runArtifactExport,
@@ -136,7 +138,7 @@ import {
import { prepareLocalExternalImport } from "./external-findings-import.js";
import { validateInspectorProjectMapping } from "./inspector-findings.js";
import {
- listLocalExternalFindings,
+ readLocalExternalFindings,
type StoredExternalFinding,
} from "./external-findings-local.js";
import type { collectSonarIssues } from "./sonar-collector.js";
@@ -313,12 +315,15 @@ import {
canonicalizeModelSafePath,
codexSecurityCredentialAllowsAmbientImport,
codexSecurityCredentialHome,
+ canonicalConfigPath,
codexSecurityHasStoredFileCredentials,
codexSecurityStateDirectory,
logoutCredentialHome,
executablePathForSpawn,
environmentWithGit,
expandHome,
+ resolveInputPath,
+ resolveParentTraversal,
prepareCodexSecurityCredentialHome,
resolveCodexCommand,
resolvePluginPython,
@@ -393,6 +398,7 @@ import {
import {
abortable,
DiffTarget,
+ resolveRepositoryPath,
enclosingGitWorktreeRoots,
gitMarkerRoot,
normalizeRepository,
@@ -1466,7 +1472,7 @@ interface CliDependencies {
externalPublicationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "confirm">;
collectSonarIssues?: typeof collectSonarIssues;
prepareLocalExternalImport?: typeof prepareLocalExternalImport;
- listLocalExternalFindings?: typeof listLocalExternalFindings;
+ readLocalExternalFindings?: typeof readLocalExternalFindings;
checkScanPublication?: typeof checkScanPublication;
publishScan?: typeof publishScan;
deduplicateScan?: typeof deduplicateScanInternal;
@@ -2833,32 +2839,46 @@ export async function main(
}),
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, format }) {
- const requestedRepository = resolveCliPath(
- dependencies.currentDirectory(),
+ const requestedPath = resolveInputPath(
args.repository ?? ".",
+ dependencies.currentDirectory(),
);
- const repository = await realpath(requestedRepository).catch(
- () => requestedRepository,
+ const storedPath = await resolveParentTraversal(requestedPath).catch(
+ () => undefined,
);
+ const canonicalPath =
+ storedPath === undefined
+ ? undefined
+ : await realpath(storedPath).catch(() => undefined);
+ const requestedRepository =
+ canonicalPath === undefined
+ ? (storedPath ?? requestedPath)
+ : requestedPath;
return await history(
["list-repositories", "--status", "scanned"],
async (value): Promise<JsonObject> => {
const repositories = value["repositories"] as JsonObject[];
- let target = repositories.find(
- (entry) => entry["targetPath"] === requestedRepository,
- );
- const canonicalTarget = repositories.find(
- (entry) => entry["targetPath"] === repository,
- );
- if (
- target === undefined &&
- canonicalTarget !== undefined &&
- (await sameFile(
- canonicalTarget["targetPath"] as string,
- requestedRepository,
- ))
- ) {
- target = canonicalTarget;
+ let target =
+ repositories.find(
+ (entry) => entry["targetPath"] === requestedRepository,
+ ) ??
+ repositories.find((entry) => entry["targetPath"] === storedPath);
+ if (target === undefined && storedPath !== undefined) {
+ const canonical =
+ canonicalPath ??
+ (await canonicalConfigPath(storedPath, {
+ verifyIdentity: true,
+ }).catch(() => undefined));
+ const saved = repositories.find(
+ (entry) => entry["targetPath"] === canonical,
+ );
+ if (
+ saved !== undefined &&
+ (canonicalPath === undefined ||
+ (await sameFile(canonicalPath, requestedRepository)))
+ ) {
+ target = saved;
+ }
}
if (target === undefined) {
for (const entry of repositories) {
@@ -2901,12 +2921,13 @@ export async function main(
const controller = new AbortController();
const removeSignals = listenForAbort(dependencies, controller);
try {
- const repository = resolveCliPath(
- dependencies.currentDirectory(),
+ const repository = resolveInputPath(
args.repository ?? ".",
+ dependencies.currentDirectory(),
);
- const findings = await (
- dependencies.listLocalExternalFindings ?? listLocalExternalFindings
+ controller.signal.throwIfAborted();
+ const result = await (
+ dependencies.readLocalExternalFindings ?? readLocalExternalFindings
)(
{ repository },
{
@@ -2916,11 +2937,11 @@ export async function main(
);
if (useInteractiveHistory(format))
renderedOutput = renderImportedFindings(
- repository,
- findings,
+ result.repository,
+ result.findings,
output.columns || 96,
);
- return { repository, findings };
+ return result;
} catch (error) {
if (controller.signal.aborted) {
exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;
@@ -2972,11 +2993,14 @@ export async function main(
? await canonicalizeModelSafePath(
resolveCliPath(directory, options.scanRoot),
)
- : resolveCliPath(directory, options.scanRoot);
+ : await resolveParentTraversal(
+ resolveInputPath(options.scanRoot, directory),
+ { allowMissing: true },
+ );
const repository =
scanRoot !== undefined && args.repository === undefined
? undefined
- : resolveCliPath(directory, args.repository ?? directory);
+ : resolveInputPath(args.repository ?? directory, directory);
return presentHistory(
await history(
workbenchArgs("list-scans", {
@@ -3604,29 +3628,33 @@ export async function main(
options.csv === undefined
? undefined
: resolveCliPath(currentDirectory, options.csv);
- const directories = [
- ...new Set(
- [
- ...(args.scanDir === undefined ? [] : [args.scanDir]),
- ...options.scanDir,
- ].map((directory) => resolveCliPath(currentDirectory, directory)),
- ),
+ const directoryInputs = [
+ ...(args.scanDir === undefined ? [] : [args.scanDir]),
+ ...options.scanDir,
];
- if (directories.length > 1 && options.to !== "cloud") {
- throw new CodexSecurityError(
- "Multiple scan directories are only supported with --to cloud.",
- );
- }
- if (options.scan.length > 0 && directories.length > 0) {
+ const uniqueDirectories = (paths: string[]) => {
+ const directories = [...new Set(paths)];
+ if (directories.length > 1 && options.to !== "cloud") {
+ throw new CodexSecurityError(
+ "Multiple scan directories are only supported with --to cloud.",
+ );
+ }
+ return directories;
+ };
+ // Reject conflicting selectors before reading their path components.
+ uniqueDirectories(
+ directoryInputs.map((value) =>
+ resolveCliPath(currentDirectory, value),
+ ),
+ );
+ if (options.scan.length > 0 && directoryInputs.length > 0) {
throw new CodexSecurityError(
"Use --scan or scan directory inputs, not both.",
);
}
if (
csvPath !== undefined &&
- (args.scanDir !== undefined ||
- options.scan.length > 0 ||
- options.scanDir.length > 0)
+ (directoryInputs.length > 0 || options.scan.length > 0)
) {
throw new CodexSecurityError(
"Use --csv or scan directory and ID inputs, not both.",
@@ -3698,6 +3726,16 @@ export async function main(
runWorkbench: (args, input) =>
dependencies.runWorkbench(args, input, controller.signal),
};
+ const directories = uniqueDirectories(
+ await Promise.all(
+ directoryInputs.map((value) =>
+ resolveParentTraversal(
+ resolveInputPath(value, currentDirectory),
+ { allowMissing: true },
+ ),
+ ),
+ ),
+ );
const selectedScans: { scanDir: string; scanId?: string }[] =
directories.map((scanDir) => ({ scanDir }));
for (const requestedId of new Set(options.scan)) {
@@ -4251,10 +4289,10 @@ export async function main(
inspectorProjectMap = new Map([[inspectorProjectArn, url]]);
}
const directory = dependencies.currentDirectory();
- const report = resolveCliPath(directory, args.file);
+ const report = resolveInputPath(args.file, directory);
const repository =
options.to === "local"
- ? resolveCliPath(directory, options.repository)
+ ? resolveInputPath(options.repository, directory)
: options.repository;
const publicationOptions = {
...readerOptions,
@@ -4281,7 +4319,7 @@ export async function main(
` ${diagnosticValue(finding.source_finding_id)} [${finding.evidence.severity}] ${diagnosticValue(finding.evidence.title)}\n`,
);
writeDiagnostic(
- `Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`,
+ `Evidence file: ${diagnosticValue(report)}\nImported evidence remains not assessed by Codex.\nUse --dry-run --format json to inspect all normalized findings and complete evidence before storing them.\n`,
);
};
const disposition = externalImportDisposition(preview);
@@ -4333,7 +4371,7 @@ export async function main(
);
showExclusions(preview.excluded);
writeDiagnostic(
- `Evidence file: ${diagnosticValue(resolveCliPath(dependencies.currentDirectory(), args.file))}\nImported evidence remains not assessed by Codex.\n`,
+ `Evidence file: ${diagnosticValue(report)}\nImported evidence remains not assessed by Codex.\n`,
);
const severities = new Map<string, number>();
for (const finding of preview.findings)
@@ -4460,12 +4498,20 @@ export async function main(
const controller = new AbortController();
const removeSignals = listenForAbort(dependencies, controller);
try {
+ const input = resolveInputPath(
+ args.scanDir,
+ dependencies.currentDirectory(),
+ );
+ const destination = publicationDestination(
+ options,
+ dependencies.environment,
+ );
+ const directory = await resolveParentTraversal(input, {
+ allowMissing: true,
+ });
const result = await (
dependencies.checkScanPublication ?? checkScanPublication
- )(resolveCliPath(dependencies.currentDirectory(), args.scanDir), {
- ...publicationDestination(options, dependencies.environment),
- signal: controller.signal,
- });
+ )(directory, { ...destination, signal: controller.signal });
controller.signal.throwIfAborted();
return { ...result };
} catch (error) {
@@ -5222,7 +5268,7 @@ export async function main(
const outcome = await withTerminalErrorsHandled(errorOutput, () =>
runPolicyCommand(
{
- repository: resolveCliPath(directory, args.repository ?? "."),
+ repository: resolveInputPath(args.repository ?? ".", directory),
config: {
pluginPath: options.pluginPath,
pythonPath: options.python,
@@ -5684,8 +5730,13 @@ export async function main(
async run({ args, options }) {
try {
const cwd = dependencies.currentDirectory();
- const repository = resolveCliPath(cwd, args.repository ?? ".");
const environment = dependencies.environment;
+ const requested = resolveInputPath(
+ args.repository ?? ".",
+ cwd,
+ environment,
+ );
+ const repository = await resolveParentTraversal(requested);
const git = await trustedGitCommand(
repository,
true,
@@ -5694,7 +5745,7 @@ export async function main(
repository,
environment,
undefined,
- cwd,
+ { cwd, requestedPaths: [resolve(requested)] },
),
);
const hook = execFileSync(
@@ -5802,9 +5853,9 @@ export async function main(
const removeSignals = listenForAbort(dependencies, controller);
try {
const directory = dependencies.currentDirectory();
- const repository = resolveCliPath(
- directory,
+ const repository = resolveInputPath(
options.sourceRoot ?? ".",
+ directory,
);
const findings = await parseImportedFindings(
await readRegularInputFile(
@@ -6276,7 +6327,10 @@ export async function main(
signalHandlers(dependencies, "add", onInterrupt, onTerminate);
try {
const directory = dependencies.currentDirectory();
- const repository = resolveCliPath(directory, args.repository ?? ".");
+ const repository = resolveInputPath(
+ args.repository ?? ".",
+ directory,
+ );
const project = await selectedProjectConfig(
options.config,
dependencies,
@@ -6575,7 +6629,7 @@ export async function main(
"--output-dir is required with a repository CSV.",
);
}
- inputPath = resolveCliPath(currentDirectory, args.input);
+ inputPath = resolveInputPath(args.input, currentDirectory);
outputDir = settings.outputDir;
}
const scanOptionsByMode =
@@ -6816,11 +6870,11 @@ export async function main(
const sourceRoot =
options.sourceRoot === undefined
? undefined
- : resolveCliPath(currentDirectory, options.sourceRoot);
- const protectedRoot =
- sourceRoot === undefined
- ? undefined
- : [currentDirectory, sourceRoot];
+ : resolveInputPath(options.sourceRoot, currentDirectory);
+ const protectedRoot = await artifactSourceProtectionRoots(
+ sourceRoot,
+ currentDirectory,
+ );
let scanDir = args.scanDir;
if (scanDir === undefined) {
let scanId = options.scan;
@@ -6854,7 +6908,7 @@ export async function main(
: resolveCliPath(currentDirectory, destination);
const prepared = await resolveArtifactExportOutput(
{
- scanDir: resolveCliPath(currentDirectory, scanDir),
+ scanDir: resolveInputPath(scanDir, currentDirectory),
artifact: options.artifact,
format,
output: outputPath,
@@ -8670,7 +8724,7 @@ async function prepareScanArgumentsFromRecipe(
? DiffTarget.workingTree({ base: reference ?? "HEAD" })
: "repository",
knowledgeBasePaths: knowledgeBasePaths.map((path) =>
- resolveCliPath(directory, path),
+ resolveInputPath(path, directory),
),
...prompts,
safetyIdentifier,
@@ -11130,16 +11184,19 @@ async function executeScan(
deepScanOptions(arguments_);
const directory = dependencies.currentDirectory();
repository = arguments_.repository ?? directory;
- if (arguments_.validate) {
+ const repositoryPath = arguments_.validate
+ ? resolveInputPath(repository, directory)
+ : resolveRepositoryPath(repository, directory);
+ if (arguments_.validate || repositoryPath.split(sep).includes("..")) {
repository = await normalizeRepository(
- resolve(directory, expandHome(repository)),
+ repositoryPath,
preparationAbortController.signal,
);
}
const target = arguments_.target;
const prompts = await resolveScanPrompts(
arguments_,
- resolve(directory, repository),
+ resolveRepositoryPath(repository, directory),
directory,
);
const config: CodexSecurityConfig = {
@@ -11771,7 +11828,10 @@ async function executeScan(
result = await security.run(repository, options);
runningMockScan = false;
scanDir = result.scanDir;
- repository = resolve(dependencies.currentDirectory(), repository);
+ repository = resolveRepositoryPath(
+ repository,
+ dependencies.currentDirectory(),
+ );
if (arguments_.validate) {
const scanId = result.manifest.scan.id;
const checkTarget = async () => {
diff --git a/sdk/typescript/src/external-findings-import.ts b/sdk/typescript/src/external-findings-import.ts
index 4b923dc58..6c11150a2 100644
--- a/sdk/typescript/src/external-findings-import.ts
+++ b/sdk/typescript/src/external-findings-import.ts
@@ -1,3 +1,5 @@
+import { stat } from "node:fs/promises";
+import { InvalidTargetError } from "./errors.js";
import {
cloudRepositoryUrlKey,
repositoryUrlKey,
@@ -17,6 +19,7 @@ import {
snapshotImportOptions,
snapshotSourceRepositories,
} from "./external-findings.js";
+import { resolveInputPath } from "./runtime.js";
import { abortable } from "./targets.js";
export interface LocalExternalImportOptions
@@ -35,6 +38,15 @@ export async function prepareLocalExternalImport(
const readerSources = distinctSourceRepositories(
snapshotSourceRepositories(dependencies.sourceRepositories),
);
+ const requested = resolveInputPath(
+ settings.repository,
+ process.cwd(),
+ dependencies.environment,
+ );
+ const selected = await abortable(
+ () => stat(requested, { bigint: true }).catch(() => null),
+ dependencies.signal,
+ );
const parsed = await abortable(
() => readExternalFindings(path, settings, "local", readerSources),
dependencies.signal,
@@ -75,11 +87,24 @@ export async function prepareLocalExternalImport(
];
}
const { environment, runWorkbench, signal } = dependencies;
- return prepareLocalImport(
+ const prepared = await prepareLocalImport(
parsed.findings,
normalizedOptions,
{ environment, runWorkbench, signal },
readerSources,
sourceRepositories,
);
+ const destination = await abortable(
+ () => stat(prepared.preview.repository, { bigint: true }),
+ dependencies.signal,
+ );
+ if (
+ !selected ||
+ selected.dev !== destination.dev ||
+ selected.ino !== destination.ino
+ )
+ throw new InvalidTargetError(
+ `Repository path changed while reading external findings: ${requested}`,
+ );
+ return prepared;
}
diff --git a/sdk/typescript/src/external-findings-local.ts b/sdk/typescript/src/external-findings-local.ts
index 4a1d462f5..f7f47846a 100644
--- a/sdk/typescript/src/external-findings-local.ts
+++ b/sdk/typescript/src/external-findings-local.ts
@@ -1,3 +1,4 @@
+import { resolve } from "node:path";
import {
semgrepLegacyRepositoryWitnesses,
semgrepPlatformFindingBinding,
@@ -90,7 +91,8 @@ import {
bundledPluginRoot,
canonicalConfigPath,
canonicalizeModelSafePath,
- expandHome,
+ resolveInputPath,
+ resolveParentTraversal,
requireOutputOutsideRepositories,
runWorkbench,
workbenchEnvironment,
@@ -671,16 +673,36 @@ async function localContext(
const environment = workbenchEnvironment(
dependencies.environment ?? process.env,
);
- const path = expandHome(selectedRepository, environment);
+ const requested = resolveInputPath(
+ selectedRepository,
+ process.cwd(),
+ environment,
+ );
+ const path = await abortable(
+ () => resolveParentTraversal(requested),
+ dependencies.signal,
+ );
const repository =
mode === "read"
? await abortable(() => canonicalConfigPath(path), dependencies.signal)
: await normalizeRepository(path, dependencies.signal);
+ const lexicalPath = resolve(requested);
+ const lexicalRepository =
+ lexicalPath === resolve(path)
+ ? repository
+ : await abortable(
+ () => canonicalConfigPath(lexicalPath),
+ dependencies.signal,
+ );
const protectedRoot = [
...new Set([
repository,
+ ...(mode === "read" ? [lexicalRepository] : []),
...(await abortable(
- () => commandGitProtectionRoots(path, environment, dependencies.signal),
+ () =>
+ commandGitProtectionRoots(path, environment, dependencies.signal, {
+ requestedPaths: [lexicalPath, lexicalRepository],
+ }),
dependencies.signal,
)),
]),
@@ -695,6 +717,7 @@ async function localContext(
);
return {
repository,
+ selectedPath: path,
options: {
pluginRoot: await abortable(
() => bundledPluginRoot(),
@@ -1438,9 +1461,16 @@ export async function listLocalExternalFindings(
selection: { repository: string; id?: string },
dependencies: LocalExternalImportDependencies = {},
): Promise<StoredExternalFinding[]> {
+ return (await readLocalExternalFindings(selection, dependencies)).findings;
+}
+
+export async function readLocalExternalFindings(
+ selection: { repository: string; id?: string },
+ dependencies: LocalExternalImportDependencies,
+) {
dependencies.signal?.throwIfAborted();
if (selection.id !== undefined) requireIdentity(selection.id, "Finding id");
- const { repository, options } = await localContext(
+ const { repository, selectedPath, options } = await localContext(
selection.repository,
dependencies,
"read",
@@ -1453,5 +1483,8 @@ export async function listLocalExternalFindings(
JSON.stringify({ repository, id: selection.id }),
);
}, dependencies.signal);
- return result["findings"] as unknown as StoredExternalFinding[];
+ return {
+ repository: selectedPath,
+ findings: result["findings"] as unknown as StoredExternalFinding[],
+ };
}
diff --git a/sdk/typescript/src/local-git-metadata.ts b/sdk/typescript/src/local-git-metadata.ts
index 41b4b3889..206c7485e 100644
--- a/sdk/typescript/src/local-git-metadata.ts
+++ b/sdk/typescript/src/local-git-metadata.ts
@@ -134,6 +134,7 @@ export async function localGitProtectionRoots(
repository: string,
environment: NodeJS.ProcessEnv,
signal?: AbortSignal,
+ requestedPaths: readonly string[] = [],
): Promise<string[]> {
const roots = new Set(
await abortable(() => gitProtectionRoots(repository, signal), signal),
@@ -142,7 +143,11 @@ export async function localGitProtectionRoots(
directory: await abortable(() => canonicalConfigPath(repository), signal),
environment,
};
- const paths = new Set([resolve(repository), context.directory]);
+ const paths = new Set([
+ resolve(repository),
+ context.directory,
+ ...requestedPaths,
+ ]);
for (const path of paths) {
for (const root of await bareMetadataRoots(path, signal)) {
roots.add(root);
@@ -191,9 +196,20 @@ export async function commandGitProtectionRoots(
repository: string,
environment: NodeJS.ProcessEnv,
signal?: AbortSignal,
- cwd = process.cwd(),
+ {
+ cwd = process.cwd(),
+ requestedPaths,
+ }: {
+ cwd?: string;
+ requestedPaths?: readonly string[];
+ } = {},
): Promise<string[]> {
- const roots = await localGitProtectionRoots(repository, environment, signal);
+ const roots = await localGitProtectionRoots(
+ repository,
+ environment,
+ signal,
+ requestedPaths,
+ );
if (signal?.aborted) throw abortReason(signal);
if (cwd !== repository)
roots.push(...(await localGitProtectionRoots(cwd, environment, signal)));
diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.ts
index 31aa94e28..86128bd1a 100644
--- a/sdk/typescript/src/multiscan.ts
+++ b/sdk/typescript/src/multiscan.ts
@@ -56,6 +56,7 @@ import {
import {
DiffTarget,
UNSUPPORTED_GIT_ENVIRONMENT,
+ resolveTargetPath,
type ScanMode,
} from "./targets.js";
import {
@@ -173,7 +174,7 @@ export async function runMultiscan(
}
const tasks = parseInventory(
await readFile(options.inputPath, "utf8"),
- dirname(resolve(options.inputPath)),
+ dirname(resolveTargetPath(options.inputPath)),
options.mode,
);
for (const mode of new Set(tasks.map((task) => task.mode))) {
@@ -1312,9 +1313,10 @@ function parseInventory(
) {
throw new Error("Multiscan scope must stay inside its repository.");
}
+ const repository = normalizeRepository(get("repository"), directory);
return {
id,
- repository: normalizeRepository(get("repository"), directory),
+ repository,
revision,
mode: mode as ScanMode,
...(scope ? { scope } : {}),
@@ -1331,7 +1333,7 @@ function normalizeRepository(repository: string, directory: string): string {
}
if (/^[^@\s/:]+@[^:\s/]+:.+$/u.test(repository)) return repository;
if (!repository.includes("://")) {
- const path = resolve(directory, repository);
+ const path = resolveTargetPath(repository, directory);
if (process.platform !== "win32") return path;
try {
return realpathSync.native(path);
diff --git a/sdk/typescript/src/project-config.ts b/sdk/typescript/src/project-config.ts
index c637836c8..7b26b4a72 100644
--- a/sdk/typescript/src/project-config.ts
+++ b/sdk/typescript/src/project-config.ts
@@ -1,5 +1,5 @@
import { isUtf8 } from "node:buffer";
-import { existsSync } from "node:fs";
+import { existsSync, statSync } from "node:fs";
import { readFile, realpath } from "node:fs/promises";
import {
basename,
@@ -19,14 +19,14 @@ import {
} from "./config.js";
import { ConfigurationError, errorMessage } from "./errors.js";
import { DEFAULT_DEEP_SCAN_SETTINGS } from "./deep-scan-defaults.js";
-import { resolveConfigPath, type AbsolutePath } from "./config-path.js";
+import type { AbsolutePath } from "./config-path.js";
import { deepScanOptions, type DeepScanSources } from "./deep-config.js";
import {
projectConfigJsonSchema,
type ProjectConfigInput,
type ProjectScope,
} from "./project-config-schema.js";
-import { expandHomeForLookup } from "./runtime.js";
+import { expandHomeForLookup, resolveInputPath } from "./runtime.js";
import {
DEFAULT_SCAN_AUTH,
DEFAULT_SCAN_MODE,
@@ -264,6 +264,33 @@ function requireProjectConfig(
}
}
+function outputPath(
+ value: string | undefined,
+ directory: string,
+): AbsolutePath | undefined {
+ if (value === undefined) return;
+ const requested = resolveInputPath(value, directory);
+ const parts = requested.split(sep);
+ const parent = parts.lastIndexOf("..");
+ if (parent < 0) return requested;
+ const prefix = parts.slice(0, parent + 1).join(sep);
+ try {
+ // Keep a redirected traversal intact for output validation.
+ const selected = statSync(prefix, { bigint: true, throwIfNoEntry: false });
+ if (selected !== undefined) {
+ const lexical = statSync(resolve(prefix), {
+ bigint: true,
+ throwIfNoEntry: false,
+ });
+ if (selected.dev !== lexical?.dev || selected.ino !== lexical.ino)
+ return requested;
+ }
+ } catch {
+ return requested;
+ }
+ return resolve(requested) as AbsolutePath;
+}
+
export function resolveScanSettings(
project: ProjectConfigSource | undefined,
overrides: Partial<ScanSettings> & { codexOverrides?: JsonObject },
@@ -289,11 +316,9 @@ export function resolveScanSettings(
};
const projectDirectory = project?.directory ?? directory;
const filePath = (value: string | undefined): AbsolutePath | undefined =>
- value === undefined
- ? undefined
- : resolveConfigPath(projectDirectory, value);
+ value === undefined ? undefined : resolveInputPath(value, projectDirectory);
const cliPath = (value: string | undefined): AbsolutePath | undefined =>
- value === undefined ? undefined : resolveConfigPath(directory, value);
+ value === undefined ? undefined : resolveInputPath(value, directory);
const mode =
choose("scan.mode", file?.scan?.mode, overrides.mode) ?? DEFAULT_SCAN_MODE;
@@ -377,10 +402,10 @@ export function resolveScanSettings(
choose(
"scan.knowledge_base",
file?.scan?.knowledge_base?.map((value) =>
- resolveConfigPath(projectDirectory, value),
+ resolveInputPath(value, projectDirectory),
),
overrides.knowledgeBasePaths?.map((value) =>
- resolveConfigPath(directory, value),
+ resolveInputPath(value, directory),
),
) ?? [];
const settings: ResolvedScanSettings = {
@@ -413,8 +438,8 @@ export function resolveScanSettings(
postScanPromptFile: cliPath(overrides.postScanPromptFile),
outputDir: choose(
"output.directory",
- filePath(file?.output?.directory),
- cliPath(overrides.outputDir),
+ outputPath(file?.output?.directory, projectDirectory),
+ outputPath(overrides.outputDir, directory),
),
failureSeverity: choose(
"policy.fail_on_severity",
diff --git a/sdk/typescript/src/prompt-files.ts b/sdk/typescript/src/prompt-files.ts
index 050630bbd..e232d3c27 100644
--- a/sdk/typescript/src/prompt-files.ts
+++ b/sdk/typescript/src/prompt-files.ts
@@ -1,8 +1,12 @@
import { constants, type BigIntStats } from "node:fs";
import { lstat, open, realpath } from "node:fs/promises";
-import { basename, dirname, join, relative, resolve } from "node:path";
+import { basename, dirname, join, relative } from "node:path";
import { CodexSecurityError } from "./errors.js";
-import { expandHome } from "./runtime.js";
+import {
+ resolveInputPath,
+ resolveParentTraversal,
+ validateDirectoryLinks,
+} from "./runtime.js";
import { relativePathIsOutside as isOutsidePath } from "./targets.js";
import type { ScanPromptSettings } from "./scan-settings.js";
@@ -25,7 +29,7 @@ export async function resolveScanPrompts(
inline !== undefined || file === undefined
? inline
: await readRegularInputFile(
- resolve(directory, expandHome(file)),
+ resolveInputPath(file, directory),
repository,
);
const [scanPrompt, validationPrompt, postScanPrompt] = await Promise.all([
@@ -67,24 +71,23 @@ export async function readRegularInputFile(
if (!selected.isFile()) {
throw new CodexSecurityError("Input files must be regular files.");
}
- const canonicalParent = await realpath(dirname(path));
+ const canonicalParent = await realpath(
+ await resolveParentTraversal(dirname(path)),
+ );
const repositories =
typeof repository === "string" ? [repository] : repository;
for (const repository of repositories) {
- const canonicalRepository = await realpath(repository);
+ const canonicalRepository = await realpath(
+ await resolveParentTraversal(repository),
+ );
if (isOutsidePath(relative(canonicalRepository, canonicalParent))) {
- for (let ancestor = dirname(path); ; ancestor = dirname(ancestor)) {
- if (
- !isOutsidePath(
- relative(canonicalRepository, await realpath(ancestor)),
- )
- ) {
+ await validateDirectoryLinks(path, (link) => {
+ if (!isOutsidePath(relative(canonicalRepository, link))) {
throw new CodexSecurityError(
"Input files must not follow repository directory links outside the selected repository.",
);
}
- if (dirname(ancestor) === ancestor) break;
- }
+ });
}
}
const file = await open(
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 03a0d9ca2..36f324d0a 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -12,7 +12,8 @@ import {
PLUGIN_PYTHON_READY,
} from "./plugin-python-probe.js";
import { resolveBundledCodexExecutable } from "./codex-sdk-environment.js";
-import { abortable, gitProtectionRoots } from "./targets.js";
+import { abortable, gitProtectionRoots, resolveTargetPath } from "./targets.js";
+import type { AbsolutePath } from "./config-path.js";
import { isNonEmptyString, notify } from "./value.js";
import {
execFile as execFileCallback,
@@ -45,6 +46,7 @@ import {
open,
readFile,
readdir,
+ readlink,
realpath,
rename,
rm,
@@ -76,6 +78,7 @@ import { fromFdPromise, type ZipFile } from "yauzl";
import { parse } from "smol-toml";
import {
CodexSecurityError,
+ InvalidTargetError,
OutputDirectoryError,
OutputDirectoryNotEmptyError,
OutputInsideProtectedRootError,
@@ -2167,16 +2170,38 @@ export async function bundledPluginRoot(): Promise<string> {
);
}
+export async function resolveScanOutputPath(
+ outputDirectory: string,
+ validateTraversalLink?: (path: string) => void,
+): Promise<string> {
+ try {
+ const requested = resolveInputPath(outputDirectory);
+ const path = await resolveParentTraversal(requested, {
+ allowMissing: true,
+ });
+ requireModelSafeOutputDir(path);
+ if (validateTraversalLink && path !== resolve(requested)) {
+ await validateDirectoryLinks(requested, validateTraversalLink);
+ }
+ return path;
+ } catch (error) {
+ throw outputInspectionError(outputDirectory, error);
+ }
+}
+
export async function validateOutputDir(
outputDirectory?: string,
archiveExisting = false,
+ validateTraversalLink?: (path: string) => void,
): Promise<string | null> {
if (outputDirectory === undefined) {
return null;
}
- const path = resolve(expandHome(outputDirectory));
- requireModelSafeOutputDir(path);
try {
+ const path = await resolveScanOutputPath(
+ outputDirectory,
+ validateTraversalLink,
+ );
const metadata = await lstat(path).catch(nullIfMissingFileError);
if (metadata !== null) {
if (!metadata.isDirectory()) {
@@ -2224,11 +2249,44 @@ export async function validateOutputDir(
`Unable to create scan output directory: ${path}`,
);
} catch (error) {
- if (error instanceof OutputDirectoryError) throw error;
- throw new OutputDirectoryError(
- `Unable to inspect scan output directory: ${outputDirectory}`,
- { cause: error },
- );
+ throw outputInspectionError(outputDirectory, error);
+ }
+}
+
+function outputInspectionError(
+ outputDirectory: string,
+ cause: unknown,
+): OutputDirectoryError {
+ return cause instanceof OutputDirectoryError
+ ? cause
+ : new OutputDirectoryError(
+ `Unable to inspect scan output directory: ${outputDirectory}`,
+ { cause },
+ );
+}
+
+/** Check each traversed directory link at its physical location, including linked targets. */
+export async function validateDirectoryLinks(
+ requested: string,
+ validateLocation: (path: string) => void,
+): Promise<void> {
+ const directories = [dirname(requested)];
+ const visited = new Set<string>();
+ while (directories.length > 0) {
+ let directory = directories.pop()!;
+ while (dirname(directory) !== directory && !visited.has(directory)) {
+ visited.add(directory);
+ if (
+ (await lstat(directory).catch(nullIfMissingFileError))?.isSymbolicLink()
+ ) {
+ const parent = await realpath(
+ await resolveParentTraversal(dirname(directory)),
+ );
+ validateLocation(join(parent, basename(directory)));
+ directories.push(resolveTargetPath(await readlink(directory), parent));
+ }
+ directory = dirname(directory);
+ }
}
}
@@ -2409,12 +2467,18 @@ export async function canonicalizeModelSafePath(
return canonical;
}
-export async function canonicalConfigPath(path: string): Promise<string> {
+export async function canonicalConfigPath(
+ path: string,
+ { verifyIdentity = false }: { verifyIdentity?: boolean } = {},
+): Promise<string> {
let existing = resolve(path);
const missing: string[] = [];
while (true) {
try {
- return join(await realpath(existing), ...missing);
+ const canonical = await realpath(existing);
+ if (verifyIdentity && !(await sameFile(existing, canonical)))
+ throw new InvalidTargetError(`Repository path changed: ${existing}`);
+ return join(canonical, ...missing);
} catch (error) {
const parent = dirname(existing);
if (
@@ -2474,6 +2538,7 @@ async function prepareOutputDirectory(
const path = await validateOutputDir(
outputDirectory,
existingOutput !== "reject",
+ validateLocation,
);
if (path === null) {
requireModelSafeOutputDir(temporaryRoot);
@@ -4552,6 +4617,50 @@ export function sameFile(left: string, right: string): Promise<boolean> {
);
}
+export function resolveInputPath(
+ value: string,
+ directory = process.cwd(),
+ environment: ProcessEnvironment = process.env,
+): AbsolutePath {
+ if (value === "~") value = expandHome("~", environment);
+ else if (value.startsWith("~/") || value.startsWith("~\\")) {
+ const home = expandHome("~", environment);
+ const suffix = value.startsWith("~\\")
+ ? value.slice(2).split("\\").filter(Boolean).join(sep)
+ : value.slice(2);
+ value = home === "" ? suffix : `${home}${sep}${suffix}`;
+ }
+ return resolveTargetPath(value, directory) as AbsolutePath;
+}
+
+/** Resolve through the last parent traversal while retaining aliases in the remaining path. */
+export async function resolveParentTraversal(
+ path: string,
+ { allowMissing = false }: { allowMissing?: boolean } = {},
+): Promise<string> {
+ const parts = path.split(sep);
+ const parent = parts.lastIndexOf("..");
+ if (parent === -1) return path;
+ const prefix = parts.slice(0, parent + 1).join(sep);
+ // A new output directory can be spelled missing/../scan before its parent exists.
+ if (
+ allowMissing &&
+ (await stat(prefix).catch(nullIfMissingFileError)) === null
+ ) {
+ return resolve(path);
+ }
+ // Resolve each directory before moving to its parent. Some runtimes collapse
+ // a literal ".." inside realpath before consulting the filesystem.
+ const before =
+ parts.slice(0, parent).join(sep) || (isAbsolute(path) ? sep : ".");
+ const physical = dirname(
+ await realpath(await resolveParentTraversal(before)),
+ );
+ if (!(await sameFile(prefix, physical)))
+ throw new InvalidTargetError(`Repository path changed: ${prefix}`);
+ return join(physical, ...parts.slice(parent + 1));
+}
+
export function expandHomeForLookup(
value: string,
environment: ProcessEnvironment = process.env,
diff --git a/sdk/typescript/src/targets.ts b/sdk/typescript/src/targets.ts
index 5e6a68fd4..4ce34967a 100644
--- a/sdk/typescript/src/targets.ts
+++ b/sdk/typescript/src/targets.ts
@@ -161,9 +161,28 @@ export async function normalizeRepository(
return canonical;
}
-export function resolveRepositoryPath(repository: string): string {
+export function resolveRepositoryPath(
+ repository: string,
+ directory = process.cwd(),
+): string {
requireUtf8Path("Repository path", repository);
- return resolve(expandHome(repository));
+ return resolveTargetPath(expandHome(repository), directory);
+}
+
+/** Preserve filesystem resolution of symlink/.. paths on POSIX. */
+export function resolveTargetPath(
+ value: string,
+ directory = process.cwd(),
+): string {
+ if (sep === "\\") return resolve(directory, value);
+ const base = isAbsolute(directory)
+ ? directory
+ : `${process.cwd()}/${directory}`;
+ const absolute = isAbsolute(value) ? value : `${base}/${value}`;
+ const parts = absolute
+ .split("/")
+ .filter((part) => part !== "" && part !== ".");
+ return `/${parts.join("/")}`;
}
function requireUtf8Path(
@@ -600,9 +619,7 @@ export async function normalizeTarget(
);
}
requireUtf8Path("Path target", value);
- const candidate = isAbsolute(expandHome(value))
- ? resolve(expandHome(value))
- : resolve(root, expandHome(value));
+ const candidate = resolveTargetPath(expandHome(value), root);
let canonical: string;
try {
// Some runtimes cannot canonicalize special files to filesystem paths.
@@ -1074,7 +1091,10 @@ function expandHome(value: string): string {
if (value.startsWith("~/") || value.startsWith("~\\")) {
const separators =
sep === "/" && value.startsWith("~/") ? /^\/+/ : /^[/\\]+/;
- return resolve(homedir(), value.slice(2).replace(separators, ""));
+ const suffix = value.slice(2).replace(separators, "");
+ const home = homedir();
+ if (process.platform === "win32") return resolve(home, suffix);
+ return home === "" ? resolveTargetPath(suffix) : `${home}${sep}${suffix}`;
}
return value;
}
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 228476342..ca6da9fb3 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -575,6 +575,43 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
+ test.skipIf(process.platform === "win32")(
+ "Node preflight preserves physical repository and scope paths",
+ async () => {
+ const root = await temporaryDirectory();
+ // Bun's realpath collapses parent traversal before resolving symlinks.
+ const source = new URL(
+ "./fixtures/target-paths-node.ts",
+ import.meta.url,
+ );
+ const built = await Bun.build({
+ entrypoints: [fileURLToPath(source)],
+ target: "node",
+ format: "esm",
+ packages: "external",
+ define: {
+ "import.meta.url": JSON.stringify(
+ new URL("../src/api.ts", import.meta.url).href,
+ ),
+ },
+ });
+ expect(built.success).toBe(true);
+ await symlink(
+ fileURLToPath(new URL("../node_modules", import.meta.url)),
+ join(root, "node_modules"),
+ "dir",
+ );
+ const module = join(root, "target-paths.mjs");
+ await writeFile(module, await built.outputs[0]!.text());
+ const exportRoot = await temporaryDirectory();
+ execFileSync(nodeCommand().command, [module, root, exportRoot], {
+ cwd: root,
+ encoding: "utf8",
+ env: { ...process.env, HOME: root, USERPROFILE: root },
+ });
+ },
+ );
+
test("preflights local inputs without initializing runtime or credentials", async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
diff --git a/sdk/typescript/tests-ts/cli-export.test.ts b/sdk/typescript/tests-ts/cli-export.test.ts
index a2604f780..1c0489e7e 100644
--- a/sdk/typescript/tests-ts/cli-export.test.ts
+++ b/sdk/typescript/tests-ts/cli-export.test.ts
@@ -1020,7 +1020,18 @@ describe("CLI", () => {
const scan = join(actual, "scan");
await mkdir(scan, { recursive: true });
await symlink(actual, linked, "dir");
- for (const output of ["-", join(directory, "results.sarif")] as const) {
+ const selected = join(linked, "scan");
+ const scanDirs = [selected];
+ if (process.platform !== "win32") {
+ await mkdir(join(actual, "child"));
+ const entry = join(directory, "entry");
+ await symlink(join(actual, "child"), entry);
+ scanDirs.push(`${entry}/../scan`);
+ }
+ for (const [input, output] of [
+ ...scanDirs.map((input) => [input, "-"] as const),
+ [selected, join(directory, "results.sarif")] as const,
+ ]) {
const deps = dependencies();
let received = "";
deps.exportFindings = async (arguments_) => {
@@ -1028,11 +1039,7 @@ describe("CLI", () => {
return new TextEncoder().encode('{"version":"2.1.0"}\n');
};
expect(
- await runCapturedCli(
- main,
- ["export", join(linked, "scan"), "--output", output],
- deps,
- ),
+ await runCapturedCli(main, ["export", input, "--output", output], deps),
).toBe(0);
expect(received).toBe(await realpath(scan));
}
diff --git a/sdk/typescript/tests-ts/cli-external-imports.test.ts b/sdk/typescript/tests-ts/cli-external-imports.test.ts
index 3f77d8492..c9fb28a4e 100644
--- a/sdk/typescript/tests-ts/cli-external-imports.test.ts
+++ b/sdk/typescript/tests-ts/cli-external-imports.test.ts
@@ -36,15 +36,20 @@ test.each(
test("a legacy disabled setting still allows reading imported findings", async () => {
const cli = createCliTest(main);
- const listLocalExternalFindings = mock(async () => []);
+ const readLocalExternalFindings = mock(
+ async ({ repository }: { repository: string }) => ({
+ repository,
+ findings: [],
+ }),
+ );
const code = await cli.runCli(["findings", "imported", ".", "--json"], {
...dependencies({
environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "0" },
}),
- listLocalExternalFindings,
+ readLocalExternalFindings,
});
expect(code).toBe(0);
- expect(listLocalExternalFindings).toHaveBeenCalledTimes(1);
+ expect(readLocalExternalFindings).toHaveBeenCalledTimes(1);
expect(JSON.parse(cli.stdout.text()).findings).toEqual([]);
});
diff --git a/sdk/typescript/tests-ts/cli-local-import.test.ts b/sdk/typescript/tests-ts/cli-local-import.test.ts
index fd4c05a70..a28f606ab 100644
--- a/sdk/typescript/tests-ts/cli-local-import.test.ts
+++ b/sdk/typescript/tests-ts/cli-local-import.test.ts
@@ -4,13 +4,16 @@ import {
mkdtemp,
readdir,
realpath,
+ rename,
rm,
+ symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join, resolve } from "node:path";
+import { join, resolve, sep } from "node:path";
import { afterEach, expect, test } from "bun:test";
import { main } from "../src/cli.js";
+import { readLocalExternalFindings } from "../src/external-findings-local.js";
import { dependencies, FakeSignals } from "./cli-fixtures.js";
import { createCliTest } from "./support/cli-run.js";
import { opengrepJson } from "./support/opengrep-import-fixtures.js";
@@ -498,30 +501,33 @@ test.each([true, false])(
const fileUrl = hasInstalledVersion
? "https://example.test/project/blob/test-fixture/src/app.ts"
: reference;
- deps.listLocalExternalFindings = async () => [
- {
- repository,
- id: "external-1",
- version: 1,
- provider: "github",
- sourceKey: "example/project",
- sourceFindingId: "42",
- createdAt: "2026-01-01T00:00:00Z",
- updatedAt: "2026-01-01T00:00:00Z",
- assessment: { state: "not_assessed" },
- evidence: {
- title: "Dependency\nissue",
- severity: "high",
- packages: [pkg],
- locations: hasInstalledVersion
- ? [{ path: "src/app.ts", line: 12 }]
- : [],
- url: reference,
- details: { kind: "advisory", file_url: fileUrl },
- source_data: { vendorField: "raw details" },
+ deps.readLocalExternalFindings = async () => ({
+ repository,
+ findings: [
+ {
+ repository,
+ id: "external-1",
+ version: 1,
+ provider: "github",
+ sourceKey: "example/project",
+ sourceFindingId: "42",
+ createdAt: "2026-01-01T00:00:00Z",
+ updatedAt: "2026-01-01T00:00:00Z",
+ assessment: { state: "not_assessed" },
+ evidence: {
+ title: "Dependency\nissue",
+ severity: "high",
+ packages: [pkg],
+ locations: hasInstalledVersion
+ ? [{ path: "src/app.ts", line: 12 }]
+ : [],
+ url: reference,
+ details: { kind: "advisory", file_url: fileUrl },
+ source_data: { vendorField: "raw details" },
+ },
},
- },
- ];
+ ],
+ });
const args = ["findings", "imported"];
const interactive = createCliTest(main, { stdout: true });
expect(await interactive.runCli(args, deps)).toBe(0);
@@ -559,11 +565,11 @@ test.each([true, false])(
test("imported readback resolves its repository argument and supports structured output", async () => {
const deps = dependencies({ currentDirectory: resolve("workspace") });
- deps.listLocalExternalFindings = async ({ repository }, settings) => {
+ deps.readLocalExternalFindings = async ({ repository }, settings) => {
expect(repository).toBe(resolve("workspace", "project"));
expect(settings?.environment).toBe(deps.environment);
expect(settings?.signal?.aborted).toBe(false);
- return [];
+ return { repository: resolve("selected project"), findings: [] };
};
const cli = createCliTest(main);
expect(
@@ -573,11 +579,41 @@ test("imported readback resolves its repository argument and supports structured
),
).toBe(0);
expect(JSON.parse(cli.stdout.text())).toEqual({
- repository: resolve("workspace", "project"),
+ repository: resolve("selected project"),
findings: [],
});
});
+test.skipIf(process.platform === "win32")(
+ "imported readback labels the repository used for an empty query after an alias changes",
+ async () => {
+ const f = await fixture();
+ const other = join(f.root, "other");
+ for (const repo of [f.repository, other])
+ await mkdir(join(repo, "child"), { recursive: true });
+ const entry = join(f.root, "entry");
+ await mkdir(entry);
+ const link = join(entry, "link");
+ const replacement = join(entry, "replacement");
+ await symlink(join(f.repository, "child"), link);
+ await symlink(join(other, "child"), replacement);
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli(["findings", "imported", `${link}${sep}..`, "--json"], {
+ ...f.deps,
+ readLocalExternalFindings: async (selection, settings) => {
+ await rename(replacement, link);
+ return readLocalExternalFindings(selection, settings);
+ },
+ }),
+ ).toBe(0);
+ expect(JSON.parse(cli.stdout.text())).toEqual({
+ repository: other,
+ findings: [],
+ });
+ },
+);
+
for (const format of ["json", "jsonl"] as const) {
test.each(["SIGINT", "SIGTERM"] as const)(
`imported readback reports %s cancellation in ${format} full output`,
@@ -587,7 +623,7 @@ for (const format of ["json", "jsonl"] as const) {
signals,
currentDirectory: resolve("workspace"),
});
- deps.listLocalExternalFindings = async (_selection, settings) => {
+ deps.readLocalExternalFindings = async (_selection, settings) => {
expect(settings?.signal).toBeDefined();
signals.emit(signalName);
settings!.signal!.throwIfAborted();
@@ -611,6 +647,38 @@ for (const format of ["json", "jsonl"] as const) {
);
}
+test("imported readback honors an interruption before resolving the repository", async () => {
+ const signals = new FakeSignals();
+ const deps = dependencies({
+ currentDirectory: resolve("workspace"),
+ signals,
+ });
+ deps.addSignalListener = (signal, listener) => {
+ signals.add(signal, listener);
+ if (signal === "SIGINT") listener();
+ };
+ deps.readLocalExternalFindings = async () => {
+ throw new Error("Interrupted readback reached the workbench");
+ };
+ const cli = createCliTest(main);
+ expect(
+ await cli.runCli(
+ [
+ "findings",
+ "imported",
+ "missing/../repo",
+ "--format",
+ "json",
+ "--full-output",
+ ],
+ deps,
+ ),
+ ).toBe(130);
+ expect(JSON.parse(cli.stdout.text()).error.message).toBe("SIGINT");
+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);
+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
+});
+
test("finding import requires an explicit destination and advertises local repository paths", async () => {
const cli = createCliTest(main);
expect(
diff --git a/sdk/typescript/tests-ts/cli-patch.test.ts b/sdk/typescript/tests-ts/cli-patch.test.ts
index d88922fc6..65f1b35e7 100644
--- a/sdk/typescript/tests-ts/cli-patch.test.ts
+++ b/sdk/typescript/tests-ts/cli-patch.test.ts
@@ -1275,69 +1275,82 @@ describe("scan and patch workflow", () => {
test.each([false, true])(
"patches selected scan findings with analytics.enabled=%p in the scanned repository and returns JSON",
async (analyticsEnabled) => {
- const result = resultWithFindings(["critical", "high", "medium", "low"]);
- const invocations: Array<{
- args: readonly string[];
- directory: string | undefined;
- prompt: string | undefined;
- }> = [];
- const patched: Finding[] = [];
- const outcome = await runWorkflow(
- [
- "scan",
- "../other/repository",
- "--patch",
- "--codex",
- `analytics.enabled=${analyticsEnabled}`,
- "--codex",
- "features.goals=false",
- "--patch-severity",
- "high",
- "--fail-on-severity",
+ const directory = await temporaryDirectory("scan-patch-target-");
+ try {
+ const currentDirectory = join(directory, "current");
+ const repository = join(directory, "other", "repository");
+ await mkdir(currentDirectory);
+ await mkdir(repository, { recursive: true });
+ const result = resultWithFindings([
+ "critical",
"high",
- "--json",
- ],
- {
- result,
- onCodex: (args, output) => {
- invocations.push({
- args,
- directory: output?.appServer?.directory,
- prompt: output?.appServer?.prompt,
- });
- patched.push(...completePatches(args, output));
- return 0;
+ "medium",
+ "low",
+ ]);
+ const invocations: Array<{
+ args: readonly string[];
+ directory: string | undefined;
+ prompt: string | undefined;
+ }> = [];
+ const patched: Finding[] = [];
+ const outcome = await runWorkflow(
+ [
+ "scan",
+ "../other/repository",
+ "--patch",
+ "--codex",
+ `analytics.enabled=${analyticsEnabled}`,
+ "--codex",
+ "features.goals=false",
+ "--patch-severity",
+ "high",
+ "--fail-on-severity",
+ "high",
+ "--json",
+ ],
+ {
+ currentDirectory,
+ result,
+ onCodex: (args, output) => {
+ invocations.push({
+ args,
+ directory: output?.appServer?.directory,
+ prompt: output?.appServer?.prompt,
+ });
+ patched.push(...completePatches(args, output));
+ return 0;
+ },
},
- },
- );
-
- expect(outcome.exitCode).toBe(0);
- expect(patched.map(({ occurrenceId }) => occurrenceId)).toEqual([
- "occ_1",
- "occ_2",
- ]);
- expect(invocations).toHaveLength(2);
- for (const invocation of invocations) {
- expect(invocation.args[0]).toBe("app-server");
- expect(invocation.args).toContain(
- `analytics.enabled=${analyticsEnabled}`,
- );
- expect(invocation.args).not.toContain("features.goals=false");
- expect(invocation.directory).toBe(
- resolve(CURRENT_REPOSITORY, "../other/repository"),
);
- expect(invocation.prompt).toContain("Return exactly one JSON object");
+
+ expect(outcome.exitCode).toBe(0);
+ expect(patched.map(({ occurrenceId }) => occurrenceId)).toEqual([
+ "occ_1",
+ "occ_2",
+ ]);
+ expect(invocations).toHaveLength(2);
+ for (const invocation of invocations) {
+ expect(invocation.args[0]).toBe("app-server");
+ expect(invocation.args).toContain(
+ `analytics.enabled=${analyticsEnabled}`,
+ );
+ expect(invocation.args).not.toContain("features.goals=false");
+ expect(invocation.directory).toBe(repository);
+ expect(invocation.prompt).toContain("Return exactly one JSON object");
+ }
+ expect(JSON.parse(outcome.stdout)).toMatchObject({
+ manifest: result.manifest,
+ findings: result.findings,
+ patchSeverity: "high",
+ patches: [
+ { occurrenceId: "occ_1", status: "verified" },
+ { occurrenceId: "occ_2", status: "verified" },
+ ],
+ });
+ expect(outcome.stderr).toContain("Patching 2 confirmed findings...");
+ } finally {
+ await rm(directory, { recursive: true, force: true });
}
- expect(JSON.parse(outcome.stdout)).toMatchObject({
- manifest: result.manifest,
- findings: result.findings,
- patchSeverity: "high",
- patches: [
- { occurrenceId: "occ_1", status: "verified" },
- { occurrenceId: "occ_2", status: "verified" },
- ],
- });
- expect(outcome.stderr).toContain("Patching 2 confirmed findings...");
},
);
diff --git a/sdk/typescript/tests-ts/cli-scan-prompts.test.ts b/sdk/typescript/tests-ts/cli-scan-prompts.test.ts
index bd6bc956d..3dc5114a0 100644
--- a/sdk/typescript/tests-ts/cli-scan-prompts.test.ts
+++ b/sdk/typescript/tests-ts/cli-scan-prompts.test.ts
@@ -117,10 +117,11 @@ describe("CLI scan prompts", () => {
}
}
- for (const [directory, target] of [
- [repository, "."],
- [physicalRepository, repositoryAlias],
- [repositoryAlias, physicalRepository],
+ for (const [directory, target, input] of [
+ [repository, ".", join("..", "external", "external-prompt.md")],
+ [repository, ".", external],
+ [physicalRepository, repositoryAlias, external],
+ [repositoryAlias, physicalRepository, external],
] as const) {
let selected: unknown;
expect(
@@ -129,7 +130,7 @@ describe("CLI scan prompts", () => {
[
"scan",
target,
- ...promptFlags.flatMap((flag) => [flag, external]),
+ ...promptFlags.flatMap((flag) => [flag, input]),
"--json",
],
dependencies({
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index d18f488c3..8b168d732 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -55,12 +55,16 @@ describe("CLI workbench", () => {
fs.stat(replacementPath, { bigint: true }),
]);
expect(actual.ino).not.toBe(replacement.ino);
- for (const includeMatchingAlias of [false, true]) {
+ for (const [suffix, includeMatchingAlias] of [
+ ["", false],
+ ["", true],
+ ["removed", false],
+ ] as const) {
const calls: Array<readonly string[]> = [];
const stdout = captureCli(main, "stdout");
expect(
await stdout.run(
- ["findings", "list", alias, "--json"],
+ ["findings", "list", join(alias, suffix), "--json"],
dependencies({
onWorkbench: (args): JsonObject => {
calls.push(args);
@@ -69,7 +73,7 @@ describe("CLI workbench", () => {
repositories: [
{
targetId: "unrelated",
- targetPath: replacementPath,
+ targetPath: join(replacementPath, suffix),
},
...(includeMatchingAlias
? [{ targetId: "selected", targetPath: savedAlias }]
@@ -99,12 +103,74 @@ describe("CLI workbench", () => {
: []),
]);
expect(JSON.parse(stdout.text())).toEqual({
- repository: alias,
+ repository: join(alias, suffix),
findings: includeMatchingAlias ? [{ title: "selected finding" }] : [],
});
}
},
);
+ test("findings list resolves parent paths after the checkout is removed", async () => {
+ await using temp = await scopedTemporaryDirectory(
+ "finding-removed-checkout-",
+ );
+ const root = temp.path;
+ const repository = join(root, "repository");
+ const directory = join(root, "tools");
+ await mkdir(repository);
+ await mkdir(directory);
+ await rm(repository, { recursive: true });
+ const requests: [string, string][] = [
+ [repository, repository],
+ ["../repository", repository],
+ ];
+ if (process.platform !== "win32") {
+ const moved = join(root, "moved");
+ await mkdir(join(moved, "child"), { recursive: true });
+ await symlink(join(moved, "child"), join(directory, "link"));
+ await symlink(root, join(moved, "archive"));
+ requests.push([
+ "link/../archive/repository",
+ join(moved, "archive", "repository"),
+ ]);
+ }
+ for (const [requested, displayed] of requests) {
+ const calls: Array<readonly string[]> = [];
+ const stdout = captureCli(main, "stdout");
+ expect(
+ await stdout.run(
+ ["findings", "list", requested, "--json"],
+ dependencies({
+ currentDirectory: directory,
+ onWorkbench: (args): JsonObject => {
+ calls.push(args);
+ return args[0] === "list-repositories"
+ ? {
+ repositories: [
+ { targetId: "saved", targetPath: repository },
+ ],
+ }
+ : {
+ findings: [{ title: "Saved finding" }],
+ nextOffset: null,
+ };
+ },
+ }),
+ ),
+ ).toBe(0);
+ expect(calls[1]).toEqual([
+ "list-global-findings",
+ "--target-id",
+ "saved",
+ "--status",
+ "open",
+ ]);
+ expect(JSON.parse(stdout.text())).toEqual({
+ repository: displayed,
+ findings: [{ title: "Saved finding" }],
+ });
+ }
+ });
+
test("findings list matches directory identity when realpath preserves alias spelling", async () => {
const root = await temporaryDirectory("finding-repository-identity-");
const originalRealpath = fs.realpath;
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index 828c55431..cad4cb5ab 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -1173,7 +1173,13 @@ describe("CLI", () => {
{ mode: 0o700 },
);
}
- for (const selected of [component, join(alias, "component")]) {
+ const selections = [component, join(alias, "component")];
+ if (process.platform !== "win32") {
+ const componentLink = join(caller, "component-link");
+ await symlink(component, componentLink);
+ selections.push(componentLink + "/..");
+ }
+ for (const selected of selections) {
const { stdout, stderr, runCli } = createCliTest(main);
const status = await runCli(
["install-hook", selected, "--json"],
@@ -1600,6 +1606,50 @@ describe("CLI", () => {
}
});
+ test.skipIf(process.platform === "win32").each(["present", "missing"])(
+ "reads the physical bulk scan CSV through a symlink parent with the lexical CSV %s",
+ async (lexicalCsv) => {
+ const root = await temporaryDirectory("codex-security-cli-csv-link-");
+ const currentDirectory = join(root, "entry");
+ const physical = join(root, "physical");
+ const output = join(root, "results");
+ try {
+ await mkdir(currentDirectory);
+ await mkdir(join(physical, "child"), { recursive: true });
+ await multiscanInventory(physical);
+ if (lexicalCsv === "present")
+ await multiscanInventory(currentDirectory);
+ await symlink(join(physical, "child"), join(currentDirectory, "link"));
+ const { stdout, stderr, runCli } = createCliTest(main);
+ expect(
+ await runCli(
+ [
+ "bulk-scan",
+ "link/../repositories.csv",
+ "--output-dir",
+ output,
+ "--json",
+ ],
+ dependencies({ currentDirectory }),
+ ),
+ stderr.text(),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text())).toMatchObject({
+ total: 1,
+ completed: 1,
+ failed: 0,
+ });
+ expect(
+ parseJsonLines(await readFile(join(output, "results.jsonl"), "utf8")),
+ ).toMatchObject([
+ { repository: join(physical, "repository"), status: "completed" },
+ ]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
test("expands home-relative bulk scan paths", async () => {
const root = await temporaryDirectory("codex-security-cli-home-");
const home = join(root, "home");
@@ -2890,12 +2940,15 @@ describe("CLI", () => {
] as const)(
"shows the resolved directory name in the scan title for %p",
async (repository, name) => {
+ await using temp = await scopedTemporaryDirectory("scan-title-");
+ const currentDirectory = join(temp.path, "workspace", "repository");
+ await mkdir(join(currentDirectory, "child"), { recursive: true });
const { stderr, runCli } = createCliTest(main, { stderr: true });
expect(
await runCli(
["scan", ...(repository === undefined ? [] : [repository])],
dependencies({
- currentDirectory: resolve("/workspace/repository"),
+ currentDirectory,
environment: { NO_COLOR: "1" },
}),
),
diff --git a/sdk/typescript/tests-ts/external-findings-import.test.ts b/sdk/typescript/tests-ts/external-findings-import.test.ts
index ab1fcc6af..98a97aa5c 100644
--- a/sdk/typescript/tests-ts/external-findings-import.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-import.test.ts
@@ -1,8 +1,9 @@
import { spawnSync } from "node:child_process";
import { gzipSync } from "node:zlib";
-import { access, writeFile } from "node:fs/promises";
+import { access, symlink, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
-import { expect, test } from "bun:test";
+import { expect, mock, test } from "bun:test";
+import { runTestInSubprocess } from "./support/test-subprocess.js";
import { prepareLocalExternalImport } from "../src/external-findings-import.js";
import { listLocalExternalFindings } from "../src/external-findings-local.js";
import { readVendorFindings } from "../src/wiz-findings.js";
@@ -98,6 +99,47 @@ test("cancels preparation while the source file read is pending", async () => {
await expect(access(fixture.stateDirectory)).rejects.toThrow();
});
+const rotatedRepository =
+ "rejects a repository link that changes after the scanner findings are read";
+test(rotatedRepository, async () => {
+ if (runTestInSubprocess(import.meta.filename, rotatedRepository)) return;
+ await using fixture = await localFindingsFixture();
+ const link = join(fixture.root, "selected");
+ const other = join(fixture.root, "other");
+ const linkType = process.platform === "win32" ? "junction" : "dir";
+ fixture.git("init", "--quiet", other);
+ await symlink(fixture.repository, link, linkType);
+ const file = join(link, "wiz.json");
+ const record = {
+ id: "first-checkout",
+ name: "CVE-2026-0001",
+ detailedName: "example-package",
+ vulnerableAsset: { id: "source-branch", type: "REPOSITORY_BRANCH" },
+ };
+ await writeFile(file, JSON.stringify([record]));
+
+ const reader = { ...(await import("../src/external-findings-read.js")) };
+ mock.module("../src/external-findings-read.js", () => ({
+ ...reader,
+ async readExternalFindings(
+ ...args: Parameters<typeof reader.readExternalFindings>
+ ) {
+ const parsed = await reader.readExternalFindings(...args);
+ await unlink(link);
+ await symlink(other, link, linkType);
+ return parsed;
+ },
+ }));
+ await expect(
+ prepareLocalExternalImport(
+ file,
+ { repository: link, provider: "wiz", sourceKey: "example/main" },
+ { environment: fixture.environment },
+ ),
+ ).rejects.toThrow("Repository path changed while reading external findings");
+ await expect(access(fixture.stateDirectory)).rejects.toThrow();
+});
+
const wizSource = {
provider: "wiz",
sourceKey: "example-project/main",
diff --git a/sdk/typescript/tests-ts/external-findings-local.test.ts b/sdk/typescript/tests-ts/external-findings-local.test.ts
index f863af24f..6dafad4b2 100644
--- a/sdk/typescript/tests-ts/external-findings-local.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-local.test.ts
@@ -8,7 +8,7 @@ import {
symlink,
writeFile,
} from "node:fs/promises";
-import { delimiter, join } from "node:path";
+import { delimiter, join, sep } from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, test } from "bun:test";
import type { ExternalFindings } from "../src/external-findings.js";
@@ -958,6 +958,32 @@ describe("local normalized scanner findings", () => {
expect(existsSync(join(repository, "state"))).toBe(false);
});
+ test("protects imported findings readback through parent traversal", async () => {
+ const { root, repository, environment } = await fixture();
+ const owner = join(root, "owner");
+ await mkdir(owner);
+ await mkdir(join(repository, "child"));
+ const linkType = process.platform === "win32" ? "junction" : "dir";
+ const link = join(owner, "link");
+ await symlink(join(repository, "child"), link, linkType);
+ const direct = join(owner, "direct");
+ await symlink(repository, direct, linkType);
+ const state = join(owner, "state");
+ const dependencies = {
+ environment: { ...environment, CODEX_SECURITY_STATE_DIR: state },
+ };
+ await expect(
+ listLocalExternalFindings(
+ { repository: `${link}${sep}..` },
+ dependencies,
+ ),
+ ).rejects.toThrow("must be outside the protected scan root");
+ expect(existsSync(state)).toBe(false);
+ expect(
+ await listLocalExternalFindings({ repository: direct }, dependencies),
+ ).toEqual([]);
+ });
+
test.each(["bare", "linked", "ordinary"] as const)(
"protects selected %s roots through nested paths and aliases",
async (kind) => {
@@ -978,11 +1004,21 @@ describe("local normalized scanner findings", () => {
await symlink(repository, join(owner, "to-selected"), linkType);
const alias = join(root, "owner-alias");
await symlink(owner, alias, linkType);
+ const nestedAlias = join(root, "nested-alias");
+ await symlink(join(owner, "nested"), nestedAlias, linkType);
+ await mkdir(join(repository, "child"));
+ await mkdir(join(repository, "selected"));
+ await symlink(
+ join(repository, "child"),
+ join(owner, "nested", "link"),
+ linkType,
+ );
const selections = [
owner,
nested,
join(owner, "to-selected"),
join(alias, "to-selected"),
+ `${join(nestedAlias, "link")}${sep}..${sep}selected`,
];
if (kind === "bare") {
const inner = join(owner, "inner-worktree");
diff --git a/sdk/typescript/tests-ts/external-findings-publish.test.ts b/sdk/typescript/tests-ts/external-findings-publish.test.ts
index 122bb21d8..30822d3b0 100644
--- a/sdk/typescript/tests-ts/external-findings-publish.test.ts
+++ b/sdk/typescript/tests-ts/external-findings-publish.test.ts
@@ -40,7 +40,7 @@ import {
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
+import { basename, dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { gzipSync } from "node:zlib";
@@ -4466,6 +4466,36 @@ test("request and pagination metadata retain Cloud byte limits and distinct iden
).toThrow("4096 UTF-8");
});
+test("Cloud previews the findings file selected through a directory link and parent", async () => {
+ const f = await fixture();
+ const directory = join(f.root, "physical", "child");
+ await mkdir(directory, { recursive: true });
+ await fs.symlink(
+ directory,
+ join(f.root, "link"),
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ const name = basename(f.file);
+ await writeFile(
+ join(f.root, "physical", name),
+ JSON.stringify([normalized("other")]),
+ );
+ const input = `link/../${name}`;
+ const [expected] = JSON.parse(await readFile(`${f.root}/${input}`, "utf8"));
+ const cli = createCliTest(main);
+ const args = [...f.command];
+ args[2] = input;
+ expect(
+ await cli.runCli([...args, "--dry-run"], {
+ ...f.cliDeps,
+ currentDirectory: () => f.root,
+ }),
+ ).toBe(0);
+ expect(JSON.parse(cli.stdout.text()).findings).toMatchObject([
+ { source_finding_id: expected.source_finding_id },
+ ]);
+});
+
const inspectorOptions = {
...options,
provider: "inspector" as const,
diff --git a/sdk/typescript/tests-ts/fixtures/target-paths-node.ts b/sdk/typescript/tests-ts/fixtures/target-paths-node.ts
new file mode 100644
index 000000000..20226efb8
--- /dev/null
+++ b/sdk/typescript/tests-ts/fixtures/target-paths-node.ts
@@ -0,0 +1,655 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import {
+ mkdir,
+ open,
+ readFile,
+ readdir,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import { homedir } from "node:os";
+import { join, relative } from "node:path";
+import { TestClient } from "../support/api-client.js";
+import type { JsonObject } from "../../src/config.js";
+import { main } from "../../src/cli.js";
+import { runComponentScans } from "../../src/component-scan.js";
+import { runWorkbench } from "../../src/runtime.js";
+import { runArtifactExport } from "../../src/artifact-export.js";
+import { prepareNormalizedLocalImport } from "../../src/external-findings-local.js";
+import { dependencies, fakeResult } from "../cli-fixtures.js";
+import { createCliTest } from "../support/cli-run.js";
+import { copyCompletedScan } from "../plugin-root.js";
+
+const root = process.argv[2]!;
+const entry = join(root, "entry");
+const repository = join(root, "physical", "repository");
+const sibling = join(entry, "repository");
+await mkdir(join(sibling, "scope"), { recursive: true, mode: 0o700 });
+await writeFile(join(sibling, "app.ts"), "export const sibling = true;\n");
+await mkdir(join(root, "physical", "child"), { recursive: true, mode: 0o700 });
+await mkdir(join(repository, "components", "child"), {
+ recursive: true,
+ mode: 0o700,
+});
+await writeFile(join(repository, "components", "app.ts"), "export {};\n");
+await writeFile(join(repository, "app.ts"), "export const sibling = true;\n");
+await symlink(join(root, "physical", "child"), join(entry, "link"));
+await symlink(
+ join(repository, "components", "child"),
+ join(repository, "scope"),
+);
+const requestedRepository = `${entry}/link/../repository`;
+const localClient = () =>
+ new TestClient(
+ {},
+ {
+ environment: {},
+ prepareRuntime: async () => {
+ throw new Error("Runtime must not initialize");
+ },
+ },
+ );
+const client = localClient();
+try {
+ for (const mode of ["standard", "deep"] as const) {
+ for (const requested of [
+ requestedRepository,
+ relative(process.cwd(), entry) + "/link/../repository",
+ "~/entry/link/../repository",
+ "~//entry/link/../repository",
+ ]) {
+ const result = await client.preflight(requested, {
+ target: ["scope/../app.ts"],
+ mode,
+ outputDir: join(root, `output-${mode}`),
+ });
+ assert.equal(result.repository, await realpath(repository));
+ assert.deepEqual(result.target, {
+ kind: "paths",
+ paths: ["components/app.ts"],
+ });
+ }
+ await rm(sibling, { recursive: true, force: true });
+ await rm(join(repository, "app.ts"), { force: true });
+ }
+ for (const command of ["scan", "policy"]) {
+ const { runCli, stdout, stderr } = createCliTest(main);
+ assert.equal(
+ await runCli([command, requestedRepository, "--dry-run", "--json"], {
+ ...dependencies({ currentDirectory: root }),
+ createSecurity: localClient,
+ createPolicySecurity: localClient,
+ }),
+ 0,
+ stderr.text(),
+ );
+ assert.equal(
+ JSON.parse(stdout.text()).repository,
+ await realpath(repository),
+ );
+ }
+ const otherHome = join(root, "other-home");
+ await mkdir(otherHome, { mode: 0o700 });
+ for (const home of [root, undefined, ""]) {
+ const profile = home === undefined ? root : otherHome;
+ process.env["USERPROFILE"] = profile;
+ if (home === undefined) delete process.env["HOME"];
+ else process.env["HOME"] = home;
+ try {
+ {
+ const home = homedir();
+ const requested = `~/${relative(home === "" ? root : home, entry)}/link/../repository`;
+ assert.equal(
+ (await client.preflight(requested)).repository,
+ await realpath(repository),
+ );
+ assert.deepEqual(
+ (
+ await client.preflight(repository, {
+ target: [`${requested}/scope/../app.ts`],
+ })
+ ).target,
+ { kind: "paths", paths: ["components/app.ts"] },
+ );
+ if (home === "") {
+ await writeFile(
+ join(root, "app.ts"),
+ "export const caller = true;\n",
+ );
+ await writeFile(
+ join(repository, "app.ts"),
+ "export const caller = false;\n",
+ );
+ await assert.rejects(
+ client.preflight(repository, { target: ["~/app.ts"] }),
+ /outside the repository/,
+ );
+ }
+ }
+ if (home === undefined) {
+ for (const requested of [
+ "~/physical/repository",
+ "~\\physical\\repository",
+ ]) {
+ const validated = createCliTest(main);
+ let selected;
+ assert.equal(
+ await validated.runCli(
+ ["scan", requested, "--validate", "--json"],
+ dependencies({
+ currentDirectory: root,
+ onTurn: (path) => {
+ selected = path;
+ },
+ }),
+ ),
+ 0,
+ validated.stderr.text(),
+ );
+ assert.equal(selected, repository);
+ }
+ }
+ const cliEntry = relative(home || profile, entry);
+ const windowsEntry = cliEntry.replaceAll("/", "\\");
+ for (const requested of [
+ `~/${cliEntry}/link/../repository`,
+ `~\\${windowsEntry}\\link\\..\\repository`,
+ `~\\\\${windowsEntry}\\link\\..\\repository`,
+ ]) {
+ const fallback = createCliTest(main);
+ assert.equal(
+ await fallback.runCli(["policy", requested, "--dry-run", "--json"], {
+ ...dependencies({ currentDirectory: root }),
+ createPolicySecurity: localClient,
+ }),
+ 0,
+ fallback.stderr.text(),
+ );
+ assert.equal(
+ JSON.parse(fallback.stdout.text()).repository,
+ await realpath(repository),
+ );
+ }
+ } finally {
+ process.env["HOME"] = root;
+ process.env["USERPROFILE"] = root;
+ }
+ }
+ const planned = createCliTest(main);
+ assert.equal(
+ await planned.runCli(
+ [
+ "scan-components",
+ requestedRepository,
+ "--component",
+ "components",
+ "--plan-only",
+ "--output-dir",
+ join(root, "component-plan"),
+ "--json",
+ ],
+ dependencies({ currentDirectory: root }),
+ ),
+ 0,
+ planned.stderr.text(),
+ );
+ const backslashRepository = join(root, "physical\\repository");
+ await mkdir(backslashRepository, { mode: 0o700 });
+ assert.equal(
+ (await client.preflight("~\\physical\\repository")).repository,
+ await realpath(backslashRepository),
+ );
+ for (const [requested, expected] of [
+ [requestedRepository, repository],
+ ["~\\physical\\repository", backslashRepository],
+ ] as const) {
+ let editorOpened = false;
+ const interactive = createCliTest(main, { stderr: true });
+ assert.equal(
+ await interactive.runCli(["scan", requested], {
+ ...dependencies({
+ currentDirectory: root,
+ result: fakeResult(["high"]),
+ }),
+ confirmPatchReview: async () => true,
+ patchEditor: async (selected) => {
+ assert.equal(selected, await realpath(expected));
+ editorOpened = true;
+ return null;
+ },
+ }),
+ 0,
+ interactive.stderr.text(),
+ );
+ assert.equal(editorOpened, true);
+ }
+ for (const patchReview of [false, true]) {
+ const link = join(entry, "temporary-link");
+ await symlink(join(root, "physical", "child"), link);
+ const lifecycle = createCliTest(main, { stderr: patchReview });
+ let editorOpened = false;
+ assert.equal(
+ await lifecycle.runCli(
+ ["scan", `${link}/../repository`, ...(patchReview ? [] : ["--json"])],
+ {
+ ...dependencies({ currentDirectory: root }),
+ createSecurity: () => ({
+ preflight: client.preflight.bind(client),
+ validate: client.validate.bind(client),
+ run: async (selected, options) => {
+ assert.equal(
+ (await client.preflight(selected, options)).repository,
+ await realpath(repository),
+ );
+ await rm(link);
+ return fakeResult(["high"]);
+ },
+ close: async () => {},
+ }),
+ confirmPatchReview: async () => true,
+ patchEditor: async (selected) => {
+ assert.equal(selected, await realpath(repository));
+ editorOpened = true;
+ return null;
+ },
+ },
+ ),
+ 0,
+ lifecycle.stderr.text(),
+ );
+ assert.equal(editorOpened, patchReview);
+ if (!patchReview)
+ assert.equal(
+ JSON.parse(lifecycle.stdout.text()).manifest.scan.status,
+ "completed",
+ );
+ }
+ await mkdir(sibling, { mode: 0o700 });
+ const savedAlias = join(root, "owner", "alias");
+ async function checkHistory(
+ expectedTarget: string | undefined,
+ requested = requestedRepository,
+ ) {
+ const history = createCliTest(main);
+ let selectedTarget: string | undefined;
+ assert.equal(
+ await history.runCli(
+ ["findings", "list", requested, "--json"],
+ dependencies({
+ currentDirectory: root,
+ onWorkbench: (args): JsonObject => {
+ if (args[0] === "list-repositories") {
+ return {
+ repositories: [
+ { targetId: "sibling", targetPath: sibling },
+ { targetId: "physical", targetPath: repository },
+ { targetId: "saved-alias", targetPath: savedAlias },
+ ],
+ };
+ }
+ selectedTarget = args[2];
+ return {
+ findings: [{ title: `${selectedTarget} finding` }],
+ nextOffset: null,
+ };
+ },
+ }),
+ ),
+ 0,
+ history.stderr.text(),
+ );
+ assert.equal(selectedTarget, expectedTarget);
+ assert.deepEqual(
+ JSON.parse(history.stdout.text()).findings,
+ expectedTarget === undefined
+ ? []
+ : [{ title: `${expectedTarget} finding` }],
+ );
+ }
+ await checkHistory("physical");
+ const publication = createCliTest(main);
+ const published: string[] = [];
+ assert.equal(
+ await publication.runCli(
+ [
+ "publish",
+ "scan",
+ requestedRepository,
+ "--scan-dir",
+ repository,
+ "--to",
+ "cloud",
+ "--dry-run",
+ ],
+ {
+ ...dependencies({ currentDirectory: root }),
+ publishScanToCloud: async (directory) => {
+ published.push(directory);
+ return { scanId: "scan-1", findingIds: [], findingCount: 0 };
+ },
+ },
+ ),
+ 0,
+ publication.stderr.text(),
+ );
+ assert.deepEqual(published, [await realpath(repository)]);
+ const sourceOptions = dependencies({
+ currentDirectory: root,
+ environment: { CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1" },
+ });
+ sourceOptions.readLocalExternalFindings = async ({
+ repository: selected,
+ }) => {
+ assert.equal(await realpath(selected), repository);
+ return { repository, findings: [] };
+ };
+ sourceOptions.exportFindings = async ({ sourceRoot }) => {
+ assert.equal(await realpath(sourceRoot!), repository);
+ return "";
+ };
+ await writeFile(join(root, "vendor.json"), "[]");
+ await writeFile(join(repository, "vendor.json"), "[]");
+ await writeFile(join(sibling, "vendor.json"), "invalid sibling report");
+ const publish = (selected: string, file = "vendor.json") => [
+ "publish",
+ "findings",
+ file,
+ "--to",
+ "local",
+ "--repository",
+ selected,
+ "--provider",
+ "wiz",
+ "--source-key",
+ "fixture",
+ "--dry-run",
+ "--json",
+ ];
+ for (const command of [
+ ["findings", "imported", requestedRepository, "--json"],
+ publish(requestedRepository, `${requestedRepository}/vendor.json`),
+ ["export", "scan", "--output", "-", "--source-root", requestedRepository],
+ ]) {
+ const cli = createCliTest(main);
+ assert.equal(
+ await cli.runCli(command, sourceOptions),
+ 0,
+ cli.stderr.text(),
+ );
+ if (command[0] !== "export")
+ assert.equal(JSON.parse(cli.stdout.text()).repository, repository);
+ }
+ const outputDir = `${requestedRepository}/output`;
+ await assert.rejects(client.preflight(requestedRepository, { outputDir }), {
+ name: "OutputInsideProtectedRootError",
+ });
+ const output = createCliTest(main);
+ assert.equal(
+ await output.runCli(
+ [
+ "scan",
+ requestedRepository,
+ "--dry-run",
+ "--output-dir",
+ outputDir,
+ "--json",
+ ],
+ {
+ ...dependencies({ currentDirectory: root }),
+ createSecurity: localClient,
+ },
+ ),
+ 2,
+ );
+ assert.match(output.stderr.text(), /outside the scanned directory/);
+ const owner = join(root, "owner");
+ await mkdir(join(owner, "tools"), { recursive: true, mode: 0o700 });
+ execFileSync("git", ["init", "--quiet", owner]);
+ execFileSync("git", ["init", "--quiet", repository]);
+ await symlink(repository, savedAlias);
+ const selected = join(repository, "components");
+ const physical = join(root, "physical");
+ const saved = join(physical, "saved-output");
+ await mkdir(saved, { mode: 0o700 });
+ await writeFile(join(saved, "prior-marker"), "existing output");
+ await symlink(join(physical, "child"), join(repository, "build"));
+ await symlink(join(repository, "build"), join(owner, "linked-build"));
+ await symlink(selected, join(owner, "selected"));
+ const outside = {
+ name: "OutputInsideProtectedRootError",
+ protectedRoot: await realpath(repository),
+ };
+ const workflowOutput = join(physical, "workflow-output");
+ const writer = new TestClient(
+ {},
+ {
+ environment: {
+ PATH: process.env["PATH"],
+ HOME: root,
+ CODEX_SECURITY_STATE_DIR: join(workflowOutput, "state"),
+ },
+ runWorkbench,
+ },
+ );
+ try {
+ for (const outputDir of [
+ `${repository}/build/../saved-output`,
+ `${owner}/alias/build/../saved-output`,
+ `${owner}/linked-build/../saved-output`,
+ ]) {
+ await assert.rejects(
+ writer.run(selected, { mock: true, outputDir, archiveExisting: true }),
+ outside,
+ );
+ }
+ assert.deepEqual(await readdir(saved), ["prior-marker"]);
+ assert.equal(
+ await readFile(join(saved, "prior-marker"), "utf8"),
+ "existing output",
+ );
+ for (const outputDir of [
+ join(selected, "scan-output"),
+ join(owner, "selected", "scan-output"),
+ ]) {
+ await assert.rejects(
+ writer.run(selected, { mock: true, outputDir, workflowId: "guard" }),
+ outside,
+ );
+ }
+ for (const outputDir of [
+ workflowOutput,
+ `${entry}/link/../workflow-output`,
+ ]) {
+ await assert.rejects(
+ writer.run(selected, { mock: true, outputDir, workflowId: "guard" }),
+ /Workflow state must be outside the sealed scan artifacts/,
+ );
+ }
+ assert.equal(
+ existsSync(join(workflowOutput, "state", "workbench.sqlite3")),
+ false,
+ );
+ } finally {
+ await writer.close();
+ }
+ const plan = (outputDir: string) =>
+ runComponentScans({
+ repository: selected,
+ outputDir,
+ components: [{ name: "Source", paths: ["."] }],
+ planOnly: true,
+ });
+ await assert.rejects(plan(`${owner}/selected/../build/new-plan`), outside);
+ for (const [outputDir, name] of [
+ [`${entry}/link/../operator-plan`, "operator-plan"],
+ [`${repository}/../plain-plan`, "plain-plan"],
+ ] as const) {
+ const result = await plan(outputDir);
+ assert.equal(result.planPath, join(physical, name, "components.json"));
+ assert.equal(
+ JSON.parse(await readFile(result.planPath, "utf8")).components[0].name,
+ "Source",
+ );
+ }
+ await checkHistory("saved-alias", savedAlias);
+ await checkHistory("saved-alias", "owner/tools/../alias");
+ const requestedAlias = `${owner}/tools/../alias`;
+ const alias = createCliTest(main);
+ assert.equal(
+ await alias.runCli(
+ publish(requestedAlias),
+ dependencies({
+ currentDirectory: root,
+ environment: {
+ ...process.env,
+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",
+ CODEX_SECURITY_STATE_DIR: join(owner, "state"),
+ },
+ }),
+ ),
+ 2,
+ );
+ assert.match(alias.stderr.text(), /outside the protected scan root/);
+ const exportRoot = process.argv[3]!;
+ const source = join(exportRoot, "source");
+ const physicalSource = join(exportRoot, "physical");
+ await mkdir(source);
+ await mkdir(join(physicalSource, "child"), { recursive: true });
+ await symlink(join(physicalSource, "child"), join(source, "link"));
+ const traversedSource = `${source}/link/..`;
+ const scan = await copyCompletedScan(exportRoot);
+ if (process.platform === "linux" && existsSync("/proc/self/fd")) {
+ await mkdir(join(physicalSource, "src"));
+ await writeFile(
+ join(physicalSource, "src", "extract.py"),
+ "\n".repeat(40) + "extract(member)\n",
+ );
+ await using directory = await open(join(physicalSource, "child"));
+ const sarif = await runArtifactExport({
+ scanDir: scan,
+ sourceRoot: `/proc/self/fd/${directory.fd}/..`,
+ format: "sarif",
+ output: "-",
+ });
+ const [finding] = JSON.parse(sarif!).runs[0].results;
+ assert.equal(
+ finding.partialFingerprints.primaryLocationLineHash,
+ "68da6fe4396c35f9:1",
+ );
+ }
+ for (const [sourceRoot, directory] of [
+ [requestedAlias, owner],
+ [traversedSource, source],
+ [traversedSource, physicalSource],
+ [traversedSource, exportRoot],
+ ] as const) {
+ const python = join(directory, "fixture-python");
+ await writeFile(
+ python,
+ '#!/bin/sh\necho run >> "$0-ran"\nexec python3 "$@"\n',
+ { mode: 0o755 },
+ );
+ const exported = createCliTest(main);
+ const code = await exported.runCli(
+ [
+ "export",
+ scan,
+ "--output",
+ "-",
+ "--source-root",
+ sourceRoot,
+ "--python",
+ python,
+ ],
+ {
+ ...dependencies({ currentDirectory: root }),
+ exportFindings: runArtifactExport,
+ },
+ );
+ if (directory === exportRoot) {
+ assert.equal(code, 0, exported.stderr.text());
+ assert.equal(JSON.parse(exported.stdout.text()).version, "2.1.0");
+ assert.equal(await readFile(`${python}-ran`, "utf8"), "run\nrun\n");
+ } else {
+ assert.equal(code, 2);
+ assert.match(
+ exported.stderr.text(),
+ /configured plugin Python interpreter is unavailable/,
+ );
+ await assert.rejects(realpath(`${python}-ran`), { code: "ENOENT" });
+ }
+ }
+ await assert.rejects(
+ prepareNormalizedLocalImport(
+ { read: 0, findings: [], excluded: [] },
+ {
+ repository: `${requestedRepository}/components`,
+ provider: "wiz",
+ sourceKey: "fixture",
+ },
+ {
+ environment: {
+ ...process.env,
+ CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS: "1",
+ CODEX_SECURITY_STATE_DIR: join(repository, "state"),
+ },
+ },
+ ),
+ /outside the protected scan root/,
+ );
+ const prompt = createCliTest(main);
+ await writeFile(join(repository, "prompt.md"), "physical");
+ await writeFile(join(sibling, "prompt.md"), "sibling");
+ let selectedPrompt: string | undefined;
+ assert.equal(
+ await prompt.runCli(
+ [
+ "scan",
+ requestedRepository,
+ "--scan-prompt-file",
+ `${requestedRepository}/prompt.md`,
+ "--json",
+ ],
+ dependencies({
+ currentDirectory: root,
+ onTurn: (_, options) => {
+ selectedPrompt = options.scanPrompt;
+ },
+ }),
+ ),
+ 0,
+ prompt.stderr.text(),
+ );
+ assert.equal(selectedPrompt, "physical");
+ await mkdir(join(entry, "missing"), { mode: 0o700 });
+ await assert.rejects(
+ client.preflight(`${entry}/link/../missing`),
+ /Repository is not a directory/,
+ );
+ await mkdir(join(root, "outside", "child"), { recursive: true, mode: 0o700 });
+ await writeFile(join(root, "outside", "app.ts"), "export {};\n");
+ await writeFile(join(repository, "app.ts"), "export {};\n");
+ await symlink(join(root, "outside", "child"), join(repository, "outside"));
+ await assert.rejects(
+ client.preflight(requestedRepository, {
+ scanPromptFile: `${requestedRepository}/outside/../app.ts`,
+ }),
+ /directory links outside the selected repository/,
+ );
+ await assert.rejects(
+ client.preflight(repository, { target: ["outside/../app.ts"] }),
+ /outside the repository/,
+ );
+ await rm(repository, { recursive: true });
+ await checkHistory("physical");
+ await rm(join(root, "physical", "child"), { recursive: true });
+ await checkHistory(undefined);
+ await rm(join(entry, "link"));
+ await checkHistory(undefined);
+} finally {
+ await client.close();
+}
diff --git a/sdk/typescript/tests-ts/knowledge-base.test.ts b/sdk/typescript/tests-ts/knowledge-base.test.ts
index 00f891890..77d763301 100644
--- a/sdk/typescript/tests-ts/knowledge-base.test.ts
+++ b/sdk/typescript/tests-ts/knowledge-base.test.ts
@@ -1012,6 +1012,25 @@ describe("scan knowledge bases", () => {
);
});
+ testPosix(
+ "a directory link before a parent traversal cannot select outside documents",
+ async () => {
+ const repository = await temporaryDirectory();
+ const outside = await temporaryDirectory();
+ await mkdir(join(outside, "child"));
+ await symlink(join(outside, "child"), join(repository, "context"));
+ await writeFile(join(outside, "guide.md"), "External data");
+ const requested = `${repository}/context/../guide.md`;
+ await expect(prepareKnowledgeBase([requested])).rejects.toThrow();
+ await writeFile(join(repository, "guide.md"), "Repository guide");
+ const prepared = await prepareKnowledgeBase([requested]);
+ temporaryDirectories.track(prepared.path);
+ expect(await extractedDocuments(prepared.path)).toEqual([
+ "Repository guide",
+ ]);
+ },
+ );
+
testPosix("does not follow symbolic links", async () => {
const root = await temporaryDirectory();
const source = join(root, "scope.md");
diff --git a/sdk/typescript/tests-ts/mock-scan.test.ts b/sdk/typescript/tests-ts/mock-scan.test.ts
index ed0cf13e7..e82c170bd 100644
--- a/sdk/typescript/tests-ts/mock-scan.test.ts
+++ b/sdk/typescript/tests-ts/mock-scan.test.ts
@@ -6,6 +6,7 @@ import {
readFile,
readdir,
realpath,
+ symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -275,6 +276,43 @@ test("mock scans preserve output protection and archive existing completed resul
}
});
+test.skipIf(process.platform === "win32")(
+ "durable mock scans resume only from the same physical output directory",
+ async () => {
+ const { root, repository, client } = await fixture();
+ const linkedOutput = (id: string) => `${join(root, `${id}-link`)}/../scan`;
+ const run = async (
+ workflowId: string,
+ outputDir = linkedOutput(workflowId),
+ ) => {
+ const { manifest, scanDir } = await client.run(repository, {
+ mock: true,
+ workflowId,
+ outputDir,
+ });
+ return { scanId: manifest.scan.id, scanDir };
+ };
+ try {
+ for (const id of ["first", "second"]) {
+ const child = join(root, id, "child");
+ await mkdir(child, { recursive: true, mode: 0o700 });
+ await symlink(child, join(root, `${id}-link`));
+ }
+ const first = await run("first");
+ const second = await run("second");
+ expect(first.scanDir).toBe(join(root, "first", "scan"));
+ expect(second.scanDir).toBe(join(root, "second", "scan"));
+ await expect(run("first", linkedOutput("second"))).rejects.toThrow(
+ "already bound to a different",
+ );
+ expect(await run("first", first.scanDir)).toEqual(first);
+ expect(await run("second", second.scanDir)).toEqual(second);
+ } finally {
+ await client.close();
+ }
+ },
+);
+
test("mock scan CLI forwards the flag and never offers authentication or patching", async () => {
const stdout = capture();
const stderr = capture(true);
diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.ts
index 9c8ffc142..5e42caba6 100644
--- a/sdk/typescript/tests-ts/multiscan.test.ts
+++ b/sdk/typescript/tests-ts/multiscan.test.ts
@@ -7,10 +7,11 @@ import {
readdir,
rename,
rm,
+ symlink,
writeFile,
} from "node:fs/promises";
import * as filesystem from "node:fs/promises";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { afterEach, describe, expect, spyOn, test, mock } from "bun:test";
import { main } from "../src/cli.js";
import { ScanCostLimitExceededError } from "../src/errors.js";
@@ -26,6 +27,7 @@ import {
type SecurityClient,
type MultiscanOptions,
createMultiscanFixtures,
+ git,
repository,
completedScan,
customPlugin,
@@ -39,6 +41,8 @@ const { fixture, repositoryFixture, cleanup } = createMultiscanFixtures();
afterEach(cleanup);
+const testPosix = test.skipIf(process.platform === "win32");
+
describe("multiscan", () => {
test("prepares shared prompt files once while missing sources remain row failures", async () => {
const paths = await fixture();
@@ -98,6 +102,205 @@ describe("multiscan", () => {
},
);
+ testPosix.each(["repository", "inventory"])(
+ "clones the physical repository through a %s symlink parent traversal",
+ async (selection) => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "physical/repository");
+ await repository(paths.root, "entry/repository");
+ await mkdir(join(paths.root, "physical", "child"));
+ await symlink(
+ join(paths.root, "physical", "child"),
+ join(paths.root, "entry", "link"),
+ );
+ const input =
+ selection === "inventory"
+ ? `${paths.root}/entry/link/../repositories.csv`
+ : paths.input;
+ await writeFile(
+ selection === "inventory"
+ ? join(paths.root, "physical", "repositories.csv")
+ : input,
+ `id,repository,revision\nphysical,${selection === "inventory" ? "repository" : "entry/link/../repository"},${source.revision}\n`,
+ );
+ let scanned = false;
+ const summary = await runMultiscan(
+ options(
+ { ...paths, input },
+ client(async (checkout, scanOptions = {}) => {
+ expect(
+ await readFile(join(checkout, "src", "app.ts"), "utf8"),
+ ).toBe(await readFile(join(source.path, "src", "app.ts"), "utf8"));
+ scanned = true;
+ return completedScan(scanOptions.outputDir!);
+ }),
+ ),
+ );
+ expect(summary).toMatchObject({ total: 1, completed: 1, failed: 0 });
+ expect(scanned).toBe(true);
+ },
+ );
+
+ testPosix.each([
+ ["repository", "../source"],
+ ["repository ancestor", "../source/src/.."],
+ ["terminal alias", "../alias"],
+ ["ancestor alias", "../alias/src/.."],
+ ])(
+ "resumes the recorded %s source without changing traversal spelling",
+ async (selection, relativePath) => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "source");
+ const alias = join(paths.root, "alias");
+ await symlink(source.path, alias);
+ const input = join(paths.root, "inventory", "repositories.csv");
+ await mkdir(dirname(input));
+ const original = selection.startsWith("repository") ? source.path : alias;
+ const inventory = (path: string) =>
+ `id,repository,revision\nresume,${path},${source.revision}\n`;
+ await writeFile(input, inventory(original));
+ const security = client(mock(completeRun));
+ const settings = options({ ...paths, input }, security);
+ expect(await runMultiscan(settings)).toMatchObject({
+ completed: 1,
+ failed: 0,
+ });
+ const manifestPath = join(paths.output, "manifest.json");
+ const manifest = await readFile(manifestPath, "utf8");
+ expect(JSON.parse(manifest).tasks[0].repository).toBe(original);
+
+ await writeFile(input, inventory(relativePath));
+ await expect(runMultiscan(settings)).rejects.toThrow(
+ "Multiscan manifest does not match existing output directory.",
+ );
+ expect(await readFile(manifestPath, "utf8")).toBe(manifest);
+ await writeFile(input, inventory(original));
+ expect(await runMultiscan(settings)).toMatchObject({
+ completed: 1,
+ failed: 0,
+ skipped: 1,
+ });
+ await rm(source.path, { recursive: true });
+ expect(await runMultiscan(settings)).toMatchObject({
+ completed: 1,
+ failed: 0,
+ skipped: 1,
+ });
+ expect(await readFile(manifestPath, "utf8")).toBe(manifest);
+ expect(security.run).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ testPosix.each([
+ ["traversal", "entry/first/../repository", "entry/second/../repository"],
+ ["recorded path", "entry/repository", "entry/first/../repository"],
+ ])(
+ "rejects changing a %s source at the same revision",
+ async (_selection, original, changed) => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "first/repository");
+ await mkdir(join(paths.root, "first", "child"));
+ await mkdir(join(paths.root, "second", "child"), { recursive: true });
+ await mkdir(join(paths.root, "entry"));
+ for (const destination of ["second/repository", "entry/repository"]) {
+ git(paths.root, "clone", "--quiet", "--", source.path, destination);
+ expect(git(join(paths.root, destination), "rev-parse", "HEAD")).toBe(
+ source.revision,
+ );
+ }
+ for (const name of ["first", "second"]) {
+ await symlink(
+ join(paths.root, name, "child"),
+ join(paths.root, "entry", name),
+ );
+ }
+ const inventory = (path: string) =>
+ `id,repository,revision\nresume,${path},${source.revision}\n`;
+ await writeFile(paths.input, inventory(original));
+ const security = client(mock(completeRun));
+ const settings = options(paths, security);
+ expect(await runMultiscan(settings)).toMatchObject({
+ completed: 1,
+ failed: 0,
+ });
+ const manifestPath = join(paths.output, "manifest.json");
+ const manifest = await readFile(manifestPath, "utf8");
+ await writeFile(paths.input, inventory(changed));
+ await expect(runMultiscan(settings)).rejects.toThrow(
+ "Multiscan manifest does not match existing output directory.",
+ );
+ expect(await readFile(manifestPath, "utf8")).toBe(manifest);
+ expect(security.run).toHaveBeenCalledTimes(1);
+
+ await rm(
+ original === "entry/repository"
+ ? join(paths.root, "entry", "repository")
+ : source.path,
+ { recursive: true },
+ );
+ expect(
+ await runMultiscan({
+ ...settings,
+ outputDir: join(paths.root, "new-results"),
+ }),
+ ).toMatchObject({ completed: 1, failed: 0, skipped: 0 });
+ expect(security.run).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ testPosix.each(["link", "target"])(
+ "resumes a completed campaign after its traversal %s disappears",
+ async (removed) => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "physical/repository");
+ const target = join(paths.root, "physical", "child");
+ const link = join(paths.root, "entry", "link");
+ await mkdir(target);
+ await mkdir(dirname(link));
+ await symlink(target, link);
+ await writeFile(
+ paths.input,
+ `id,repository,revision\nresume,entry/link/../repository,${source.revision}\n`,
+ );
+ const security = client(mock(completeRun));
+ const settings = options(paths, security);
+ expect(await runMultiscan(settings)).toMatchObject({
+ completed: 1,
+ failed: 0,
+ });
+ const manifestPath = join(paths.output, "manifest.json");
+ const manifest = await readFile(manifestPath, "utf8");
+ await rm(removed === "link" ? link : target, { recursive: true });
+ expect(await runMultiscan(settings)).toMatchObject({
+ completed: 1,
+ failed: 0,
+ skipped: 1,
+ });
+ expect(await readFile(manifestPath, "utf8")).toBe(manifest);
+ expect(security.run).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ testPosix.each(["missing", "file", "file-link"])(
+ "does not collapse a %s parent component into another repository",
+ async (component) => {
+ const paths = await fixture();
+ const source = await repository(paths.root, "entry/repository");
+ const file = join(paths.root, "entry", "file");
+ await writeFile(file, "Synthetic file.\n");
+ await symlink(file, join(paths.root, "entry", "file-link"));
+ await writeFile(
+ paths.input,
+ `id,repository,revision\ninvalid,entry/${component}/../repository,${source.revision}\n`,
+ );
+ const security = client(mock(completeRun));
+ expect(
+ await runMultiscan(options(paths, security, { maxAttempts: 1 })),
+ ).toMatchObject({ completed: 0, failed: 1 });
+ expect(security.run).not.toHaveBeenCalled();
+ },
+ );
+
test("parses quoted CSV fields, embedded delimiters, and Windows line endings", async () => {
const paths = await fixture();
const source = await repository(paths.root, "comma, quoted");
diff --git a/sdk/typescript/tests-ts/sdk-scan-prompts.test.ts b/sdk/typescript/tests-ts/sdk-scan-prompts.test.ts
index d66b032f4..eed40d0b3 100644
--- a/sdk/typescript/tests-ts/sdk-scan-prompts.test.ts
+++ b/sdk/typescript/tests-ts/sdk-scan-prompts.test.ts
@@ -34,7 +34,8 @@ test("rerun recognizes unchanged context after the workbench serializes its reci
await mkdir(scanDir, { mode: 0o700 });
await writeFile(join(repository, "source.ts"), "// synthetic source\n");
const document = join(root, "architecture.md");
- await writeFile(document, "Original architecture.");
+ const selectedDocument = join(root, "architecture.md");
+ await writeFile(selectedDocument, "Original architecture.");
const scanInputs = scanInputIdentity(
undefined,
await readKnowledgeBaseSnapshot([document]),
@@ -165,19 +166,39 @@ test("rerun identifies changed instructions and captures current knowledge for t
const root = await temporaryDirectory();
const repository = join(root, "repository");
await mkdir(repository);
- const document = join(root, "architecture.md");
- const prompt = join(root, "instructions.md");
- await writeFile(document, "Original architecture.");
+ let context = root;
+ if (process.platform !== "win32") {
+ const physical = join(root, "physical");
+ await mkdir(join(physical, "child"), { recursive: true });
+ const link = join(root, "context");
+ await symlink(join(physical, "child"), link);
+ context = `${link}/..`;
+ await writeFile(`${context}/architecture.md`, "Outside architecture.");
+ await writeFile(join(root, "instructions.md"), "Other instructions.");
+ }
+ const document = `${context}/architecture.md`;
+ const prompt = `${context}/instructions.md`;
+ const selectedDocument = join(root, "architecture.md");
+ await writeFile(selectedDocument, "Original architecture.");
const scanInputs = scanInputIdentity(
"Original instructions.",
await readKnowledgeBaseSnapshot([document]),
);
- await writeFile(document, "Current architecture.");
+ await writeFile(selectedDocument, "Current architecture.");
await writeFile(prompt, "Current instructions.");
let selected: unknown;
const stderr = captureCli(main, "stderr");
const code = await stderr.run(
- ["scans", "rerun", "saved", "--scan-prompt-file", prompt, "--json"],
+ [
+ "scans",
+ "rerun",
+ "saved",
+ "--scan-prompt-file",
+ prompt,
+ "--validation-prompt-file",
+ prompt,
+ "--json",
+ ],
dependencies({
currentDirectory: repository,
onWorkbench: async () => ({
@@ -201,6 +222,7 @@ test("rerun identifies changed instructions and captures current knowledge for t
expect(selected).toMatchObject({
parentScanId: "saved",
scanPrompt: "Current instructions.",
+ validationPrompt: "Current instructions.",
knowledgeBaseSnapshot: {
documents: { "0-architecture.md.txt": "Current architecture." },
},