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(cli): preserve repository protections in artifact exports (#1668)

Michael D'Angelo9263e0633244
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 9f4221f85..03c91bbfa 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -566,16 +566,18 @@ policy locations and reporting instructions, headless use, and saved artifacts.
### Exports and CI
-Export saved findings or a threat model without starting another analysis:
+Export a completed scan's findings to a SARIF file:
```bash
-cs export --scan SCAN_ID --export-format sarif --output results.sarif
-cs export --scan SCAN_ID --artifact threat-model --output threatmodel.md
+cs export /path/to/scan-results --output results.sarif
```
-The SDK provides `exportArtifact()` for the same offline operations. See
-[exports and CI](docs/cli.md#exports-and-ci) for details. For repository or pull
-request scans in GitHub Actions, use the
+Replace `/path/to/scan-results` with the results directory printed by `scan`.
+Export reads saved results, so you don't need to rerun the scan or sign in.
+
+See [exports and CI](docs/cli.md#exports-and-ci) for source fingerprints, other
+formats, threat models, and the `exportArtifact()` SDK method. For repository or
+pull request scans in GitHub Actions, use the
[GitHub Action guide](https://github.com/openai/codex-security/blob/main/github-action/README.md).
Separate examples cover
[GitHub Actions with Bedrock](https://github.com/openai/codex-security/blob/main/examples/github-actions/README.md)
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 26a43ed65..d436e6ee2 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -364,11 +364,15 @@ SARIF), PDF, DOCX, or directories. Directory traversal skips other binary files;
explicit unsupported binary files are rejected. Bulk scans share this context
with every repository.
-Output directories must be empty and outside the scanned directory and enclosing
-Git worktree. On macOS/Linux, existing directories must be private (`chmod 700`).
+Use `--output-dir DIR` to choose where a scan saves its results. The directory
+must be empty and outside the scanned directory and enclosing Git worktree. On
+macOS/Linux, existing directories must be private (`chmod 700`).
`--archive-existing` moves earlier output to
`<output-dir>.previous-<timestamp>-<id>`; `--dry-run` previews the move.
-SARIF, when produced, is saved at `<scan-dir>/exports/results.sarif`.
+
+Scans also attempt to write SARIF to `<scan-dir>/exports/results.sarif`. If that
+optional export fails, the scan can still complete. Use the
+[export command](#export-findings) to write or retry SARIF from the saved results.
Completed scans exit with `0` by default. Configure `--fail-on-severity high`
to return `1` for high or critical findings. Scope exclusions, skipped files, and follow-up notes
@@ -1491,31 +1495,80 @@ Progress callback failures do not stop matching.
## Exports and CI
-`export` reads saved results without Codex or credentials. It defaults to the
-current repository's latest completed scan. Choose either a positional result
-directory or `--scan ID`. Findings require sealed results and support
-`--export-format csv|json|sarif` (default SARIF). `--source-root PATH` adds SARIF
-source-line fingerprints.
+Export saved findings and threat models without rerunning a scan or signing in.
+
+### Export findings
+
+To save a completed scan's findings as SARIF, run:
+
+```bash
+codex-security export /path/to/scan-results --output results.sarif
+```
+
+Replace `/path/to/scan-results` with the results directory printed by `scan`.
+The command writes `results.sarif` in the current directory. The output directory
+must already exist.
+
+SARIF is the default format, and `./results.sarif` is the default output path.
+Use `--export-format json` or `--export-format csv` to choose another format.
+To select a saved scan by its ID and export JSON, run:
```bash
codex-security export --scan SCAN_ID --export-format json --output findings.json
-codex-security export --artifact threat-model --output docs/threatmodel.md
-codex-security export /path/to/policy-results --artifact threat-model --output -
```
-Threat-model exports use Markdown and default to `./threatmodel.md`. Standard,
-Deep, Diff, and policy workflows retain models when available; component/bulk
-runs save one per child. Explicit results may expose a model before completion
-or after later failure. Missing models return an error rather than generating
-or substituting one. Historical models in sealed scans need a matching manifest
-digest.
+Replace `SCAN_ID` with the ID printed by `scan`. If you omit both the results
+directory and `--scan`, `export` uses the current repository's latest completed
+scan.
+
+JSON preserves the saved findings. CSV marks them open, omits local triage state,
+and retains distinct occurrence IDs. It escapes spreadsheet-formula prefixes and
+leading apostrophes; import removes the escape. Use JSON to recover ambiguous
+apostrophes from older CSV exports.
+
+For SARIF, `--source-root` adds source-line fingerprints that help tools match
+findings across scans. Before changing the scanned files or applying patches,
+run the export from the scanned repository's root:
+
+```bash
+codex-security export /path/to/scan-results --source-root . --output results.sarif
+```
+
+The `.` selects the current directory as the source root. Its source files must
+be unchanged since the scan. `--source-root` is supported only for SARIF.
+
+If export fails, it exits with `2`. Fix the reported error and rerun the export;
+the saved scan remains available, so you don't need to run another scan.
+
+### Export a threat model
+
+To save a scan's threat model as Markdown, run:
+
+```bash
+codex-security export --scan SCAN_ID --artifact threat-model --output threatmodel.md
+```
+
+Threat-model exports default to `./threatmodel.md`. Standard, Deep, Diff, and
+policy workflows retain models when available; component/bulk runs save one per
+child. With an explicit results directory, you can export a saved threat model
+even if the workflow has not completed or later failed. Missing models return
+an error rather than generating or substituting one. Historical models in sealed
+scans need a matching manifest digest.
+
+To print a policy workflow's saved threat model, pass its results directory and
+`--output -`:
+
+```bash
+codex-security export /path/to/policy-results --artifact threat-model --output -
+```
`--output -` emits only artifact content, with diagnostics on stderr. Markdown
and CSV stdout cannot combine with JSON command output. Exporting into a checkout
does not make the model scan input; pass it with `--knowledge-base`.
-`ScanResult.threatModel` and `threatModelPath` expose the retained model and
-document, or null. Export still works if the document could not be written.
+### Export with the SDK
+
+Use `exportArtifact()` to export saved results from TypeScript:
```ts
import { exportArtifact } from "@openai/codex-security";
@@ -1532,12 +1585,12 @@ Use `artifact: "findings"` with `format: "csv" | "json" | "sarif"` for findings.
`output: "-"` streams stdout and returns null path/provenance. `pythonPath`
selects an interpreter; `signal` cancels.
-JSON preserves sealed findings. CSV marks them open, omits local triage state,
-and retains distinct occurrence IDs. It escapes spreadsheet-formula prefixes and
-leading apostrophes; import removes the escape. Use JSON to recover ambiguous
-apostrophes from older CSV exports.
+`ScanResult.threatModel` and `threatModelPath` expose the retained model and
+document, or null. Export still works if the document could not be written.
-For CI, place output outside the checkout and set a severity threshold:
+### Use exports in CI
+
+Save each scan's results outside the checkout and set a severity threshold:
```bash
SCAN_ROOT="$(mktemp -d)"
@@ -1553,6 +1606,21 @@ codex-security scan . --diff origin/main \
| `2` | Invalid input, runtime error, target change, or required-output failure. |
| `130` / `143` | Interrupt / termination. |
+If the scan exits with `2`, `130`, or `143`, skip export and upload. After a scan
+exits with `0` or `1`, use these steps:
+
+1. Export from that run's results directory. Using the explicit directory keeps
+ concurrent scans from changing which results are selected:
+
+ ```bash
+ codex-security export "$SCAN_ROOT/results" --source-root . \
+ --output "$SCAN_ROOT/results.sarif"
+ ```
+
+2. If export succeeds, upload the SARIF file.
+3. If the scan exited with `1`, keep the CI job failed so the severity threshold
+ remains enforced.
+
JSON scans have no interactive controls. `validate`, `login`, and `logout` reject
`--json`. Use `validate --output-schema FILE` for a schema-checked JSON assessment.
For GitHub Actions setup, see the
diff --git a/sdk/typescript/src/artifact-export.ts b/sdk/typescript/src/artifact-export.ts
index 3925b33ea..4b9faecd2 100644
--- a/sdk/typescript/src/artifact-export.ts
+++ b/sdk/typescript/src/artifact-export.ts
@@ -1,13 +1,16 @@
import { workbenchArgs } from "./workbench-arguments.js";
import { spawn } from "node:child_process";
+import { realpath as callbackRealpath } from "node:fs";
import { lstat, realpath } from "node:fs/promises";
import { basename, dirname, join, relative, resolve } from "node:path";
import { Writable as NodeWritable } from "node:stream";
import { pipeline } from "node:stream/promises";
+import { promisify } from "node:util";
import type { JsonObject } from "./config.js";
import { CodexSecurityError } from "./errors.js";
import { relativePathIsOutside as isOutsidePath } from "./targets.js";
import {
+ type PluginPythonOptions,
bundledPluginRoot,
codexSecurityStateDirectory,
expandHome,
@@ -16,6 +19,9 @@ import {
runWorkbench,
} from "./runtime.js";
+// Bun's promise-based realpath can return drive-relative Windows roots.
+const nativeRealpath = promisify(callbackRealpath.native);
+
export type ArtifactOutput = Pick<NodeJS.WriteStream, "write">;
export const ARTIFACT_EXPORT_FILENAMES = {
@@ -61,7 +67,7 @@ export interface ArtifactExportResult {
interface HelperOptions {
pythonPath?: string;
- protectedRoot?: string;
+ protectedRoot?: PluginPythonOptions["protectedRoot"];
pluginRoot?: string;
signal?: AbortSignal;
output?: ArtifactOutput;
@@ -204,6 +210,10 @@ export async function runArtifactExport(
],
{
pythonPath: arguments_.pythonPath,
+ protectedRoot:
+ arguments_.sourceRoot === undefined
+ ? undefined
+ : [process.cwd(), arguments_.sourceRoot],
signal: arguments_.signal,
failureMessage:
artifact === "findings"
@@ -257,45 +267,52 @@ export async function resolveArtifactExportOutput(
basename(arguments_.output),
);
if (arguments_.output !== "-") {
- const outputFromCurrent = relative(currentDirectory, arguments_.output);
- if (outputFromCurrent !== "" && !isOutsidePath(outputFromCurrent)) {
- let existingParent: string | undefined;
- for (
- let directory = dirname(arguments_.output);
- relative(currentDirectory, directory) !== "";
- directory = dirname(directory)
- ) {
- const metadata = await lstat(directory).catch(
- (error: NodeJS.ErrnoException) => {
- if (error.code === "ENOENT") return undefined;
- throw error;
- },
+ const canonicalCurrent = await realpath(currentDirectory).catch(
+ () => currentDirectory,
+ );
+ let traversedSymlink = false;
+ let expectedOutput: string | undefined;
+ for (
+ let directory = dirname(arguments_.output);
+ ;
+ directory = dirname(directory)
+ ) {
+ const metadata = await lstat(directory).catch(
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return undefined;
+ throw error;
+ },
+ );
+ const canonicalDirectory =
+ relative(currentDirectory, directory) === ""
+ ? canonicalCurrent
+ : metadata === undefined
+ ? undefined
+ : await nativeRealpath(directory);
+ if (canonicalDirectory !== undefined) {
+ expectedOutput ??= resolve(
+ canonicalDirectory,
+ relative(directory, arguments_.output),
);
- if (metadata?.isSymbolicLink()) {
+ if (
+ !isOutsidePath(relative(canonicalCurrent, canonicalDirectory)) &&
+ (traversedSymlink ||
+ isOutsidePath(relative(canonicalCurrent, outputPath)) ||
+ relative(expectedOutput, outputPath) !== "")
+ ) {
throw new CodexSecurityError(
"The export output path cannot traverse a repository symlink.",
);
}
- if (metadata !== undefined) existingParent ??= directory;
}
- const canonicalCurrent = await realpath(currentDirectory).catch(
- () => currentDirectory,
- );
- const expectedOutput =
- existingParent === undefined
- ? resolve(canonicalCurrent, outputFromCurrent)
- : resolve(
- await realpath(existingParent),
- relative(existingParent, arguments_.output),
- );
+ // An external alias may select the repository, but links below it are
+ // repository-owned. Check ancestors before counting the current link.
+ traversedSymlink ||= metadata?.isSymbolicLink() ?? false;
if (
- isOutsidePath(relative(canonicalCurrent, outputPath)) ||
- relative(expectedOutput, outputPath) !== ""
- ) {
- throw new CodexSecurityError(
- "The export output path cannot traverse a repository symlink.",
- );
- }
+ relative(currentDirectory, directory) === "" ||
+ dirname(directory) === directory
+ )
+ break;
}
}
return { ...arguments_, scanDir: canonicalScan, output: outputPath };
@@ -332,6 +349,10 @@ export async function exportArtifact(
): Promise<ArtifactExportResult> {
const artifact = options.artifact ?? "findings";
const format = resolveArtifactFormat(artifact, options.format);
+ const sourceRoot =
+ options.sourceRoot === undefined
+ ? undefined
+ : resolve(expandHome(options.sourceRoot));
const environment = {
...exportEnvironment(),
CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
@@ -343,6 +364,8 @@ export async function exportArtifact(
const python = await resolvePluginPython({
configuredPath: options.pythonPath,
environment,
+ protectedRoot:
+ sourceRoot === undefined ? undefined : [process.cwd(), sourceRoot],
signal: options.signal,
});
const pluginRoot = await bundledPluginRoot();
@@ -373,9 +396,7 @@ export async function exportArtifact(
pythonPath: options.pythonPath,
signal: options.signal,
includeMetadata: artifact === "threat-model" && options.output !== "-",
- ...(options.sourceRoot === undefined
- ? {}
- : { sourceRoot: resolve(expandHome(options.sourceRoot)) }),
+ ...(sourceRoot === undefined ? {} : { sourceRoot }),
},
process.cwd(),
);
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index d1aa7dc83..87551e692 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -230,6 +230,7 @@ import {
sameFile,
setCodexSecurityCredentialLogout,
type CodexCommand,
+ type PluginPythonOptions,
} from "./runtime.js";
import {
comparisonFindingGroups,
@@ -1192,6 +1193,7 @@ interface CliDependencies {
input?: string,
signal?: AbortSignal,
pythonPath?: string,
+ protectedRoot?: PluginPythonOptions["protectedRoot"],
): Promise<JsonObject>;
matchFindings: typeof matchScanFindings;
checkForUpdate(signal: AbortSignal): Promise<UpdateNotice | undefined>;
@@ -1276,7 +1278,7 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
return options?.trim === false ? stdout : stdout.trim();
},
exportFindings: runArtifactExport,
- runWorkbench: async (args, input, signal, pythonPath) => {
+ runWorkbench: async (args, input, signal, pythonPath, protectedRoot) => {
const environment = {
...exportEnvironment(),
CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
@@ -1286,6 +1288,7 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
python: await resolvePluginPython({
configuredPath: pythonPath,
environment,
+ protectedRoot,
signal,
}),
pluginRoot: await bundledPluginRoot(),
@@ -1847,10 +1850,17 @@ export async function main(
select: (value: JsonObject) => JsonObject | Promise<JsonObject> = (value) =>
value,
pythonPath?: string,
+ protectedRoot?: PluginPythonOptions["protectedRoot"],
): Promise<JsonObject> => {
try {
return await select(
- await dependencies.runWorkbench(args, undefined, undefined, pythonPath),
+ await dependencies.runWorkbench(
+ args,
+ undefined,
+ undefined,
+ pythonPath,
+ protectedRoot,
+ ),
);
} catch (error) {
errorOutput.write(`codex-security: ${diagnosticLines(error)}\n`);
@@ -1862,6 +1872,7 @@ export async function main(
count = 1,
status: "complete" | "any" = "complete",
pythonPath?: string,
+ protectedRoot?: PluginPythonOptions["protectedRoot"],
): Promise<SavedScan[] | undefined> => {
const result = await history(
workbenchArgs("list-scans", {
@@ -1881,6 +1892,7 @@ export async function main(
return value;
},
pythonPath,
+ protectedRoot,
);
return result?.["scans"] as SavedScan[] | undefined;
};
@@ -4861,11 +4873,21 @@ export async function main(
options.artifact,
options.exportFormat,
);
+ const sourceRoot =
+ options.sourceRoot === undefined
+ ? undefined
+ : resolveCliPath(currentDirectory, options.sourceRoot);
+ const protectedRoot =
+ sourceRoot === undefined
+ ? undefined
+ : [currentDirectory, sourceRoot];
let scanDir = args.scanDir;
if (scanDir === undefined) {
const scanId =
options.scan ??
- (await latestScans(1, "complete", options.python))?.[0]?.scanId;
+ (
+ await latestScans(1, "complete", options.python, protectedRoot)
+ )?.[0]?.scanId;
if (scanId === undefined) return;
scanDir = await resolveSavedArtifactDirectory(
scanId,
@@ -4877,6 +4899,7 @@ export async function main(
undefined,
undefined,
options.python,
+ protectedRoot,
),
);
}
@@ -4891,10 +4914,7 @@ export async function main(
currentDirectory,
options.output ?? EXPORT_DEFAULT_OUTPUTS[format],
),
- sourceRoot:
- options.sourceRoot === undefined
- ? undefined
- : resolveCliPath(currentDirectory, options.sourceRoot),
+ sourceRoot,
pythonPath: options.python,
};
try {
diff --git a/sdk/typescript/tests-ts/artifact-export.test.ts b/sdk/typescript/tests-ts/artifact-export.test.ts
index 554cad104..cd3f44a6b 100644
--- a/sdk/typescript/tests-ts/artifact-export.test.ts
+++ b/sdk/typescript/tests-ts/artifact-export.test.ts
@@ -14,8 +14,9 @@ import {
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
-import { basename, dirname, join } from "node:path";
+import { basename, delimiter, dirname, join } from "node:path";
import { PassThrough } from "node:stream";
+import { fileURLToPath } from "node:url";
import { describe, expect, spyOn, test } from "bun:test";
import { exportArtifact } from "../src/index.js";
import {
@@ -37,6 +38,115 @@ const caseInsensitiveVolume = await stat(join(caseProbe, "REPORTS")).then(
await rm(caseProbe, { recursive: true, force: true });
describe("offline artifact export", () => {
+ test.skipIf(process.platform === "win32").each([
+ ["artifact helper", "PATH"],
+ ["artifact helper", "PYTHON"],
+ ["artifact helper", "configured"],
+ ["SDK scan ID", "PYTHON"],
+ ["SDK scan ID", "configured"],
+ ["CLI scan ID", "PYTHON"],
+ ["CLI scan ID", "configured"],
+ ["CLI latest", "PYTHON"],
+ ["CLI latest", "configured"],
+ ] as const)(
+ "%s does not execute Python in input directories when selected via %s",
+ async (entrypoint, selection) => {
+ const root = await mkdtemp(
+ join(tmpdir(), "codex-security-export-python-"),
+ );
+ const caller = join(root, "caller");
+ const protectCaller =
+ entrypoint === "artifact helper" && selection !== "PATH";
+ const repository = protectCaller
+ ? join(caller, "src")
+ : join(root, "repository");
+ const scanDir = join(root, "scan");
+ const executable = join(
+ protectCaller ? join(caller, "tools") : repository,
+ "python3",
+ );
+ try {
+ await mkdir(caller);
+ await mkdir(repository);
+ await mkdir(dirname(executable), { recursive: true });
+ await cp(join(PLUGIN_ROOT, "examples", "completed-scan"), scanDir, {
+ recursive: true,
+ });
+ await writeFile(
+ executable,
+ '#!/bin/sh\nprintf probed > "$0.probed"\nprintf "codex-security-python-ok\\n"\n',
+ { mode: 0o700 },
+ );
+ const child = childProcess.spawnSync(
+ process.execPath,
+ [
+ "-e",
+ `
+ const { exportArtifact, runArtifactExport } = await import(process.argv[1]);
+ const options = {
+ scanDir: process.argv[2],
+ sourceRoot: process.argv[3],
+ pythonPath: process.argv[4] || undefined,
+ format: "sarif",
+ output: "-",
+ };
+ const entrypoint = process.argv[5];
+ if (entrypoint === "artifact helper") {
+ process.stdout.write(await runArtifactExport(options));
+ } else if (entrypoint === "SDK scan ID") {
+ await exportArtifact({ ...options, source: { scanId: "synthetic-scan" } });
+ } else {
+ const { main } = await import(process.argv[6]);
+ process.exitCode = await main([
+ "export",
+ ...(entrypoint === "CLI scan ID" ? ["--scan", "synthetic-scan"] : []),
+ "--source-root", options.sourceRoot,
+ "--output", "-",
+ ...(options.pythonPath ? ["--python", options.pythonPath] : []),
+ ]);
+ }
+ `,
+ fileURLToPath(
+ new URL("../src/artifact-export.ts", import.meta.url),
+ ),
+ scanDir,
+ repository,
+ selection === "configured" ? executable : "",
+ entrypoint,
+ fileURLToPath(new URL("../src/cli.ts", import.meta.url)),
+ ],
+ {
+ cwd: caller,
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ PATH: [
+ dirname(executable),
+ dirname(PYTHON),
+ process.env["PATH"],
+ ].join(delimiter),
+ PYTHON: selection === "PYTHON" ? executable : "",
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ XDG_CACHE_HOME: join(root, "cache"),
+ },
+ },
+ );
+ expect(await stat(`${executable}.probed`).catch(() => null)).toBeNull();
+ if (selection === "PATH") {
+ expect(child.status, child.stderr).toBe(0);
+ expect(JSON.parse(child.stdout).version).toBe("2.1.0");
+ } else {
+ expect(child.status).not.toBe(0);
+ expect(child.stderr).toContain(
+ "interpreter is unavailable or unusable",
+ );
+ }
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
test("exports with Python from the selected managed-runtime cache", async () => {
const root = await mkdtemp(join(tmpdir(), "codex-security-export-cache-"));
const environment = {
@@ -175,6 +285,37 @@ describe("offline artifact export", () => {
}
});
+ test.each(["external", "scan-local"])(
+ "resolves %s exports outside the current directory",
+ async (destination) => {
+ const root = await mkdtemp(
+ join(tmpdir(), "codex-security-external-output-"),
+ );
+ const scanDir = join(root, "scan");
+ try {
+ await mkdir(scanDir);
+ const output =
+ destination === "scan-local"
+ ? join(scanDir, "exports", "findings.json")
+ : join(root, "findings.json");
+ expect(
+ (
+ await resolveArtifactExportOutput(
+ { scanDir, output, format: "json" },
+ process.cwd(),
+ )
+ ).output,
+ ).toBe(
+ destination === "scan-local"
+ ? join(await realpath(scanDir), "exports", "findings.json")
+ : join(await realpath(root), "findings.json"),
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
test.skipIf(!caseInsensitiveVolume)(
"accepts an export parent accessed through a case alias",
async () => {
@@ -277,6 +418,74 @@ describe("offline artifact export", () => {
}
});
+ test.each(["repository", "descendant"])(
+ "checks repository-owned symlinks below an external alias into a %s",
+ async (destination) => {
+ const root = await mkdtemp(
+ join(tmpdir(), "codex-security-output-alias-"),
+ );
+ const repository = join(root, "repository");
+ const source =
+ destination === "repository" ? repository : join(repository, "src");
+ const alias = join(root, "alias");
+ const outside = join(root, "outside");
+ try {
+ await mkdir(source, { recursive: true });
+ await mkdir(outside);
+ await symlink(source, alias, "junction");
+ const options = {
+ scanDir: join(root, "scan"),
+ format: "sarif" as const,
+ output: join(alias, "results.sarif"),
+ };
+ expect(
+ (await resolveArtifactExportOutput(options, repository)).output,
+ ).toBe(join(await realpath(source), "results.sarif"));
+ for (const linkTarget of [outside, source]) {
+ const reports = join(source, "reports");
+ await symlink(linkTarget, reports, "junction");
+ await expect(
+ resolveArtifactExportOutput(
+ { ...options, output: join(alias, "reports", "results.sarif") },
+ repository,
+ ),
+ ).rejects.toThrow("cannot traverse a repository symlink");
+ await rm(reports, { recursive: true, force: true });
+ }
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
+ test("preserves trusted output aliases outside the repository", async () => {
+ const root = await mkdtemp(
+ join(tmpdir(), "codex-security-trusted-output-"),
+ );
+ const repository = join(root, "repository");
+ const reports = join(root, "reports");
+ const alias = join(root, "alias");
+ try {
+ await mkdir(repository);
+ await mkdir(reports);
+ await symlink(reports, alias, "junction");
+ expect(
+ (
+ await resolveArtifactExportOutput(
+ {
+ scanDir: join(root, "scan"),
+ format: "sarif",
+ output: join(alias, "results.sarif"),
+ },
+ repository,
+ )
+ ).output,
+ ).toBe(join(await realpath(reports), "results.sarif"));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
test("only exposes a document matching the current canonical model", async () => {
const root = await mkdtemp(join(tmpdir(), "codex-security-current-model-"));
const modelPath = join(root, "threatmodel.md");