OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(scopes): preserve literal component and CSV paths (#1814)
Michael D'Angelo56ff6b691347
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex ae6279dd2..75b0ca7e4 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -656,7 +656,9 @@ codex-security scan-components . \--output-dir /path/outside/project/results```-Plans use repository-relative paths:+Plans use literal repository-relative paths, so `~/src` selects a directory+named `~` inside the repository rather than expanding the home directory.+Existing absolute paths inside the repository are also accepted.```json{@@ -689,7 +691,8 @@ or API-key auth. SDK-selected command providers retain their authentication.From TypeScript, use `runComponentScans({ repository, outputDir, components })`.Use `auto: true`, `planOnly: true`, and `scanOptions.auth` for the corresponding-planning and authentication choices.+planning and authentication choices. Custom `createSecurity` clients receive+absolute targets; saved plans and component receipts retain relative paths.### Set investigation time@@ -1061,6 +1064,8 @@ codex-security bulk-scan repositories.csv \```Bulk scans use clean shallow checkouts and support repository/path scopes.+CSV scopes are literal paths relative to each checkout, including names such+as `~/src`.Configured diff or working-tree scopes are rejected unless every affected rowoverrides them with a path scope. `--output-dir` requires CSV input.diff --git a/sdk/typescript/src/component-plan.ts b/sdk/typescript/src/component-plan.tsindex cd6c8bfaa..c0d91bb14 100644--- a/sdk/typescript/src/component-plan.ts+++ b/sdk/typescript/src/component-plan.ts@@ -1,6 +1,6 @@import { lstat, readdir } from "node:fs/promises";import { tmpdir } from "node:os";-import { join, posix } from "node:path";+import { isAbsolute, join, posix, resolve } from "node:path";import { z } from "zod";import type { CodexSecuritySurface, ScanAuthMode } from "./api.js";import {@@ -53,8 +53,15 @@ export async function normalizeComponentPlan(signal?: AbortSignal,): Promise<ComponentPlan> {const plan = componentPlanSchema.parse(value);+ repository = await normalizeRepository(repository, signal);for (const component of plan.components) {- const target = await normalizeTarget(repository, component.paths, signal);+ const target = await normalizeTarget(+ repository,+ component.paths.map((path) =>+ isAbsolute(path) ? path : resolve(repository, path),+ ),+ signal,+ );component.paths = [...target.paths];}return plan;diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.tsindex 9c3e4fe2b..774a71fe3 100644--- a/sdk/typescript/src/component-scan.ts+++ b/sdk/typescript/src/component-scan.ts@@ -1,7 +1,7 @@import { notify } from "./value.js";import { writeFile } from "node:fs/promises";import { tmpdir } from "node:os";-import { basename, join, relative, sep } from "node:path";+import { basename, join, relative, resolve, sep } from "node:path";import {CodexSecurity,DEFAULT_DEPENDENCIES,@@ -230,7 +230,7 @@ export async function runComponentScans(...options.scanOptions,...observers,mode: options.scanOptions?.mode ?? "standard",- target: receipt.paths,+ target: receipt.paths.map((path) => resolve(repository, path)),outputDir: receipt.outputDir,signal: options.signal,});diff --git a/sdk/typescript/src/multiscan.ts b/sdk/typescript/src/multiscan.tsindex c4f76c555..a9f8610b5 100644--- a/sdk/typescript/src/multiscan.ts+++ b/sdk/typescript/src/multiscan.ts@@ -553,7 +553,9 @@ async function runCampaign(result = await security.run(checkout, {...scanSettings,knowledgeBaseSnapshot: knowledge?.snapshot,- ...(task.scope === undefined ? {} : { target: [task.scope] }),+ ...(task.scope === undefined+ ? {}+ : { target: [resolve(checkout, task.scope)] }),...(options.knowledgeBasePaths?.length? { knowledgeBasePaths: options.knowledgeBasePaths }: {}),diff --git a/sdk/typescript/tests-ts/cli-project-config.test.ts b/sdk/typescript/tests-ts/cli-project-config.test.tsindex aef66479a..62414a57b 100644--- a/sdk/typescript/tests-ts/cli-project-config.test.ts+++ b/sdk/typescript/tests-ts/cli-project-config.test.ts@@ -545,7 +545,9 @@ test("bulk scans apply config and linked operator prompts, preserve CSV scope ov});expect(selected.find((options) => options.mode === "standard")).toMatchObject({- target: ["lib"],+ target: [+ join(input.root, "batch-results", "checkouts", "standard", "lib"),+ ],auth: "api-key",maxCostUsd: 3,failureSeverity: "high",@@ -637,7 +639,7 @@ test.each(["standard", "deep"] as const)(const selected = onTurn.mock.lastCall?.[1];expect(selected).toMatchObject({mode,- target: ["lib"],+ target: [join(input.repository, "lib")],scanPrompt: "Review synthetic boundaries.",failureSeverity: "high",maxCostUsd: 7,diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.tsindex 080d96a7b..d854d4f4a 100644--- a/sdk/typescript/tests-ts/component-scan.test.ts+++ b/sdk/typescript/tests-ts/component-scan.test.ts@@ -126,14 +126,23 @@ function finding(} as Finding;}+function scope(repository: string, options: ScanOptions): string {+ return String(+ (options.target as string[]).map((path) =>+ relative(repository, path).split(sep).join("/"),+ ),+ );+}+async function completed(+ repository: string,options: ScanOptions,- findings = [finding(String(options.target))],+ findings = [finding(scope(repository, options))],coverage?: "complete" | "partial",threatModelPath: string | null = null,) {const original = fakeResult([], coverage);- const scanId = String(options.target);+ const scanId = scope(repository, options);original.manifest.scan.id = scanId;original.findings.scanId = scanId;original.findings.findings = findings;@@ -164,7 +173,8 @@ function client(run: (repository: string,options: ScanOptions,- ) => Promise<ScanResult> = async (_repository, options) => completed(options),+ ) => Promise<ScanResult> = async (repository, options) =>+ completed(repository, options),close = async () => {},) {return () => ({@@ -299,18 +309,19 @@ test("links independently scoped saved models including a failed component", asytry {summary = await scan(paths, {components: components.slice(0, 2),- createSecurity: client(async (_repository, options) => {+ createSecurity: client(async (repository, options) => {await mkdir(options.outputDir!, { recursive: true });- const failed = String(options.target).includes("web");+ const failed = scope(repository, options).includes("web");await writeFile(join(options.outputDir!,failed ? "THREAT_MODEL.md" : "threatmodel.md",),- `# Model\n\nScope: ${String(options.target)}\n`,+ `# Model\n\nScope: ${scope(repository, options)}\n`,);if (failed) throw new Error("Synthetic component failure");return completed(+ repository,options,[],"complete",@@ -401,12 +412,13 @@ test("bounds standard scans, continues after failure, and preserves partial resuscanPrompt: "Check access controls",maxCostUsd: 3,});- if (String(options.target) === "apps/api")+ if (scope(repository, options) === "apps/api")throw new Error("Authorization: Bearer SYNTHETIC_SECRET_123");return await completed(+ repository,options,undefined,- String(options.target) === "apps/web" ? "partial" : "complete",+ scope(repository, options) === "apps/web" ? "partial" : "complete",);} finally {active--;@@ -415,7 +427,9 @@ test("bounds standard scans, continues after failure, and preserves partial resu});expect([peak, close.mock.calls.length]).toEqual([2, 2]);expect(seen.map(({ target }) => target)).toEqual(- components.map(({ paths }) => paths),+ components.map(({ paths: scopes }) =>+ scopes.map((scope) => join(paths.repository, scope)),+ ),);expect(summary).toMatchObject({total: 3,@@ -473,9 +487,9 @@ test("forwards scan events with their component identity without letting observeonProgress(receipt) {receipt.paths[0] = "changed-by-observer";},- createSecurity: client(async (_repository, options) => {+ createSecurity: client(async (repository, options) => {expect(planned).toBe(true);- const target = String(options.target);+ const target = scope(repository, options);options.onProgress?.({phase: "discovery",filesCompleted: 1,@@ -509,7 +523,7 @@ test("forwards scan events with their component identity without letting observestarted: 1,});options.onWarning?.("synthetic warning");- return completed(options);+ return completed(repository, options);}),});expect(summary).toMatchObject({@@ -569,7 +583,7 @@ test.each([environment:presentation === "ci" ? { CI: "true" } : { NO_COLOR: "1" },}),- createSecurity: client(async (_repository, options) => {+ createSecurity: client(async (repository, options) => {expect(typeof options.onProgress).toBe("function");options.onProgress?.({phase: "validation",@@ -592,7 +606,7 @@ test.each([outputTokens: 20,estimatedUsd: 0.00123,});- return completed(options);+ return completed(repository, options);}),},);@@ -683,8 +697,8 @@ test("CLI restores the dashboard and reports saved partial results on cancellati],{...dependencies({ currentDirectory: paths.root, signals }),- createSecurity: client(async (_repository, options) => {- const result = await completed(options);+ createSecurity: client(async (repository, options) => {+ const result = await completed(repository, options);signals.emit("SIGINT");return result;}),@@ -724,8 +738,8 @@ test("merges confirmed root causes with complete evidence and the highest severiconst summary = await scan(paths, {config,onDeduplicationStarted,- createSecurity: client(async (_repository, options) =>- completed(options, batches[batch++]),+ createSecurity: client(async (repository, options) =>+ completed(repository, options, batches[batch++]),),matchFindings: matcher((input, options) => {inputs.push(input);@@ -776,8 +790,10 @@ test("keeps uncertain findings separate even when their fingerprints match", asyconst paths = await fixture();const summary = await scan(paths, {components: components.slice(0, 2),- createSecurity: client(async (_repository, options) =>- completed(options, [finding(String(options.target), "high", "same")]),+ createSecurity: client(async (repository, options) =>+ completed(repository, options, [+ finding(scope(repository, options), "high", "same"),+ ]),),matchFindings: matcher(({ before, after }) => ({matches: [],@@ -857,10 +873,11 @@ test.each([0, 1])(const paths = await fixture();const matchFindings = mock(rejecting("unexpected model call"));const summary = await scan(paths, {- createSecurity: client(async (_repository, options) =>+ createSecurity: client(async (repository, options) =>completed(+ repository,options,- populated && String(options.target) === "apps/web"+ populated && scope(repository, options) === "apps/web"? [finding("one")]: [],),@@ -885,9 +902,9 @@ test.each(["scan", "matching"])(await expect(scan(paths, {signal: controller.signal,- createSecurity: client(async (_repository, options) => {+ createSecurity: client(async (repository, options) => {runs++;- const result = await completed(options);+ const result = await completed(repository, options);if (phase === "scan") controller.abort();return result;}),@@ -941,6 +958,54 @@ test("rejects escaped component paths and output inside the enclosing worktree",).rejects.toThrow();});+test("keeps literal component paths through planning and execution", async () => {+ const name = "keeps literal component paths through planning and execution";+ if (runTestInSubprocess(import.meta.path, name)) return;+ const paths = await fixture();+ const home = join(paths.repository, "home");+ const os = { ...(await import("node:os")) };+ mock.module("node:os", () => ({ ...os, homedir: () => home }));+ const literals = ["~/src", "$HOME/src", "%HOME%/src", "space name"];+ for (const path of ["home/src", ...literals]) {+ await mkdir(join(paths.repository, path), { recursive: true });+ await writeFile(join(paths.repository, path, "app.ts"), "export {};\n");+ }+ const proposed = {+ components: literals.map((path) => ({ name: path, paths: [path] })),+ };+ const plan = await normalizeComponentPlan(paths.repository, proposed);+ expect(plan).toEqual(proposed);+ expect(await normalizeComponentPlan(paths.repository, plan)).toEqual(plan);+ expect(+ await normalizeComponentPlan(paths.repository, {+ components: [{ name: "Aliases", paths: ["./~/src", "~/src"] }],+ }),+ ).toEqual({ components: [{ name: "Aliases", paths: ["~/src"] }] });+ expect(await normalizeTarget(paths.repository, ["~/src"])).toMatchObject({+ paths: ["home/src"],+ });+ execFileSync("git", ["-C", paths.repository, "init", "-q"]);+ const automatic = await planComponents(paths.repository, {+ codex: fakeCodex(() => ({ components: [proposed.components[0]] })),+ });+ expect(automatic.components[0]).toEqual(proposed.components[0]);+ const observed: (readonly string[])[] = [];+ const summary = await scan(paths, {+ components: plan.components,+ createSecurity: client(async (repository, options) => {+ const target = await normalizeTarget(repository, options.target!);+ observed.push(target.paths);+ expect(options.target).toEqual(+ target.paths.map((path) => join(repository, path)),+ );+ return await completed(repository, options, []);+ }),+ });+ expect(summary).toMatchObject({ completed: literals.length, failed: 0 });+ expect(observed).toEqual(literals.map((path) => [path]));+ expect(await json(summary.planPath)).toEqual(proposed);+});+test("component inventory uses the shared Git runner without fsmonitor callbacks", async () => {const paths = await fixture();execFileSync("git", ["-C", paths.repository, "init", "-q"]);@@ -1626,10 +1691,10 @@ test.each(["auto", "chatgpt", "api-key"] as const)(planned = true;return { components: components.slice(0, 2) };},- createSecurity: client(async (_repository, options) => {+ createSecurity: client(async (repository, options) => {expect(options.auth).toBe(auth);expect(options.cyberAccessProgram).toBe("daybreak_blue");- return completed(options);+ return completed(repository, options);}),matchFindings: async (_input, options) => {expect(options?.auth).toBe(auth);@@ -1862,8 +1927,8 @@ test("CLI forwards scan settings and accepts legacy scope notes", async () => {const createSecurity = mock((_value: unknown) => {return client(run)();});- const run = mock(async (_repository: string, options: ScanOptions) => {- return completed(options, [], "partial");+ const run = mock(async (repository: string, options: ScanOptions) => {+ return completed(repository, options, [], "partial");});const result = await cli(paths,@@ -1887,7 +1952,7 @@ test("CLI forwards scan settings and accepts legacy scope notes", async () => {codexOverrides: { model: "gpt-5.6-terra", model_reasoning_effort: "high" },});expect(run.mock.lastCall?.[1]).toMatchObject({- target: ["apps/api"],+ target: [join(paths.repository, "apps/api")],mode: "standard",maxCostUsd: 2,});diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.tsindex 65e51a2d3..d0171a8cf 100644--- a/sdk/typescript/tests-ts/multiscan.test.ts+++ b/sdk/typescript/tests-ts/multiscan.test.ts@@ -34,7 +34,7 @@ import { ScanCostLimitExceededError } from "../src/errors.js";import type { ScanResult } from "../src/result.js";import { buildGitHubCredentialArgs, runMultiscan } from "../src/multiscan.js";import { resolveTrustedExecutable } from "../src/trusted-executable.js";-import { DiffTarget } from "../src/targets.js";+import { DiffTarget, normalizeTarget } from "../src/targets.js";import { prepareOutputDir } from "../src/runtime.js";import { workflowDigest } from "../src/finding-workflow.js";import { TestClient, mockWorkbench } from "./support/api-client.js";@@ -56,6 +56,60 @@ const testPosix = process.platform === "win32" ? test.skip : test;afterEach(cleanup);+test("keeps literal CSV scopes at the checked out repository", async () => {+ const name = "keeps literal CSV scopes at the checked out repository";+ if (runTestInSubprocess(import.meta.path, name)) return;+ const { paths, source } = await repositoryFixture("literal-scopes");+ const os = { ...(await import("node:os")) };+ mock.module("node:os", () => ({ ...os, homedir: () => source.path }));+ const literals = ["~/src", "$HOME/src", "%HOME%/src", "space name"];+ for (const path of literals) {+ await mkdir(join(source.path, path), { recursive: true });+ await writeFile(join(source.path, path, "app.ts"), "export {};\n");+ }+ git(source.path, "add", ".");+ git(+ source.path,+ "-c",+ "user.name=Multiscan Test",+ "-c",+ "[email protected]",+ "commit",+ "-qm",+ "literal scopes",+ );+ const revision = git(source.path, "rev-parse", "HEAD");+ await writeFile(+ paths.input,+ [+ "id,repository,revision,scope",+ ...literals.map(+ (scope, index) => `scope-${index},${source.path},${revision},${scope}`,+ ),+ `configured,${source.path},${revision},`,+ ].join("\n"),+ );+ const observed: string[] = [];+ const summary = await runMultiscan(+ options(+ paths,+ client(async (repository, scanOptions = {}) => {+ const target = await normalizeTarget(repository, scanOptions.target!);+ observed.push(...target.paths);+ expect(scanOptions.target).toEqual(+ target.paths[0] === "src"+ ? ["src"]+ : target.paths.map((path) => join(repository, path)),+ );+ return await completedScan(scanOptions.outputDir!);+ }),+ { scanOptionsByMode: { standard: { target: ["src"] } } },+ ),+ );+ expect(summary).toMatchObject({ completed: literals.length + 1, failed: 0 });+ expect(observed.sort()).toEqual([...literals, "src"].sort());+});+async function fixture() {const root = await temporaryDirectory();return {@@ -1319,8 +1373,8 @@ describe("multiscan", () => {const summary = await runMultiscan(options(paths,- client(async (_repository, scanOptions = {}) => {- expect(scanOptions.target).toEqual(["src"]);+ client(async (repository, scanOptions = {}) => {+ expect(scanOptions.target).toEqual([join(repository, "src")]);expect(scanOptions.mode).toBe("deep");expect(scanOptions.scanPrompt).toBe("Review boundaries.\n\nFocus on authentication, authorization.",@@ -1952,7 +2006,7 @@ describe("multiscan", () => {expect(await readFile(join(path, "src", "app.ts"), "utf8")).toContain('name = "payments"',);- expect(scanOptions.target).toEqual(["src"]);+ expect(scanOptions.target).toEqual([join(path, "src")]);expect(scanOptions.mode).toBe("deep");expect(scanOptions.outputDir).toBe(join(paths.output, "artifacts", "payments", "attempt-1"),