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(sdk): propagate component scan environment to scan clients (#1550)
12d1aaeba94f6d
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.tsindex dbfba3ebc..02c8074f5 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.ts@@ -1374,6 +1374,7 @@ async function testWorkerRuntimeSettings() {"CODEX_CLI_PATH","CODEX_MCP_NODE_PATH","CODEX_HOME",+ "CODEX_SECURITY_STATE_DIR","CODEX_SECURITY_CONFIG_PATH","CODEX_SECURITY_PLUGIN_ROOT","CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",@@ -1861,6 +1862,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,executors.map((executor, index) => {// Each concurrent launch snapshots its own scan environment.process.env.CODEX_MCP_NODE_PATH = nodePaths[index];+ process.env.CODEX_SECURITY_STATE_DIR = path.join(+ fixture.root,+ `state-${index}`,+ );process.env.CODEX_SECURITY_CONFIG_PATH =workerConfigurations[index].path;process.env.CODEX_SECURITY_KNOWLEDGE_BASE =@@ -1995,6 +2000,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,workerConfigurations[index].knowledgeDocuments,);assert.equal(invocation.codexHome, await realpath(codexHome));+ assert.equal(+ invocation.runtimeEnvironment.CODEX_SECURITY_STATE_DIR,+ path.join(fixture.root, `state-${index}`),+ );assert.equal(invocation.providerKey, providerKeys[index]);assert.equal(invocation.mcpNodePath, nodePaths[index]);assert.equal(process.env.CODEX_MCP_NODE_PATH, nodePaths.at(-1));@@ -2234,6 +2243,13 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,selectedProvider,"worker preflight must use the same scan environment",);+ assert.equal(+ launch.environment!.CODEX_SECURITY_STATE_DIR,+ path.join(+ fixture.root,+ `state-${workerConfigurations.indexOf(selectedProvider)}`,+ ),+ );assert.equal(preflight.providerKey,selectedProvider.environment?.SYNTHETIC_GATEWAY_KEY,diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex eeaddaceb..76dc8a513 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -637,7 +637,8 @@ interface ClientDependencies {canRunDirectDeepScan?: () => boolean;}-const DEFAULT_DEPENDENCIES: ClientDependencies = {+/** @internal */+export const DEFAULT_DEPENDENCIES: ClientDependencies = {createCodex: ({ nativeProfile, ...options }) =>nativeProfile === undefined? new Codex(options)diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.tsindex 2ed84ea0e..9c3e4fe2b 100644--- a/sdk/typescript/src/component-scan.ts+++ b/sdk/typescript/src/component-scan.ts@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";import { basename, join, relative, sep } from "node:path";import {CodexSecurity,+ DEFAULT_DEPENDENCIES,scanAuthentication,selectedScanEnvironment,type CodexSecuritySurface,@@ -193,9 +194,14 @@ export async function runComponentScans(const security = (options.createSecurity ??((config) =>- new CodexSecurity(config, undefined, {- surface: options.surface ?? "sdk",- }))+ new CodexSecurity(+ config,+ {+ ...DEFAULT_DEPENDENCIES,+ environment: options.environment ?? process.env,+ },+ { surface: options.surface ?? "sdk" },+ )))(options.config ?? {});try {while (!options.signal?.aborted) {diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.tsindex 8f1bcfc40..080d96a7b 100644--- a/sdk/typescript/tests-ts/component-scan.test.ts+++ b/sdk/typescript/tests-ts/component-scan.test.ts@@ -18,6 +18,7 @@ import {import { delimiter, dirname, join, relative, sep } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { afterEach, expect, spyOn, test, mock } from "bun:test";+import { parse as parseToml } from "smol-toml";import type { ScanOptions } from "../src/api.js";import { writeThreatModel } from "../src/artifact-export.js";import { main } from "../src/cli.js";@@ -54,6 +55,8 @@ import { createApiTestFixtures } from "./support/temporary-directories.js";import { readJson } from "./support/json.js";import { runTestInSubprocess } from "./support/test-subprocess.js";import { rejecting, throwing } from "./support/errors.js";+import { mockWorkbench } from "./support/api-client.js";+import { preparedRuntime } from "./support/api-events.js";const { temporaryDirectory, cleanup } =createApiTestFixtures("component-scan-");@@ -1674,6 +1677,167 @@ test.each([},);+test("default scan clients use the component scan environment", async () => {+ const paths = await fixture();+ const summary = await scan(paths, {+ components: components.slice(0, 1),+ createSecurity: undefined,+ environment: { ...process.env, GIT_DIR: join(paths.root, "synthetic.git") },+ });+ expect(summary.failed).toBe(1);+ expect(await json(summary.summaryPath!)).toMatchObject({+ components: [+ expect.objectContaining({+ error: "GIT_DIR is not supported for Codex Security scans.",+ }),+ ],+ });+});++test.each([+ ["standard", "api-key"],+ ["deep", "api-key"],+ ["standard", "chatgpt"],+ ["deep", "chatgpt"],+] as const)(+ "isolates concurrent default %s component scans with %s authentication at the Codex child boundary",+ async (mode, auth) => {+ const name = `isolates concurrent default ${mode} component scans with ${auth} authentication at the Codex child boundary`;+ if (runTestInSubprocess(import.meta.path, name)) return;+ const originalEnvironment = { ...process.env };+ const node = nodeCommand().command;+ const ready = Promise.withResolvers<void>();+ let arrivals = 0;+ const resolveCommand = runtime.resolveCodexCommand;+ const spies = [+ spyOn(runtime, "resolveCodexCommand").mockImplementation(+ (environment) => {+ if (environment?.["CODEX_CLI_PATH"] !== node)+ throw new Error(+ "Component scan environment did not reach the runtime.",+ );+ return resolveCommand(environment);+ },+ ),+ spyOn(runtime, "bootstrapPlugin").mockImplementation(async () => {+ if (++arrivals === 2) ready.resolve();+ await ready.promise;+ return preparedRuntime("unused").plugin;+ }),+ spyOn(runtime, "probeCodexSandbox").mockImplementation(async () => {}),+ spyOn(runtime, "resolvePluginPython").mockResolvedValue(+ "/managed/python",+ ),+ spyOn(runtime, "prepareScanArtifactRestorer").mockResolvedValue({+ restore: async () => {},+ }),+ spyOn(runtime, "runWorkbench").mockImplementation(+ async (_options, args, input) => mockWorkbench(args, input),+ ),+ ];+ try {+ const outcomes = await Promise.allSettled(+ ["first", "second"].map(async (value) => {+ const paths = await fixture();+ const preload = join(paths.root, "codex.mjs");+ const receipt = join(paths.root, "child.json");+ const environment = {+ ...Object.fromEntries(+ Object.entries(process.env).filter(([key]) =>+ /^(path|systemroot|comspec|temp|tmp|tmpdir)$/iu.test(key),+ ),+ ),+ OPENAI_API_KEY: `synthetic-${value}-key`,+ CODEX_HOME: join(paths.root, "ambient-home"),+ CODEX_SECURITY_STATE_DIR: join(paths.root, "state"),+ CODEX_CLI_PATH: node,+ NODE_OPTIONS: `--import=${pathToFileURL(preload).href}`,+ SYNTHETIC_COMPONENT: value,+ };+ const original = { ...environment };+ const storedAuthentication = {+ auth_mode: "chatgpt",+ synthetic_identity: value,+ };+ await mkdir(environment.CODEX_HOME, { mode: 0o700 });+ await writeFile(+ join(environment.CODEX_HOME, "auth.json"),+ JSON.stringify(storedAuthentication),+ );+ await writeFile(+ preload,+ [+ 'import { cpSync, existsSync, readFileSync, writeFileSync } from "node:fs";',+ 'import { join } from "node:path";',+ 'import { createHash } from "node:crypto";',+ "for await (const chunk of process.stdin) {}",+ `const scan = process.env.CODEX_SECURITY_SCAN_DIR; cpSync(${JSON.stringify(join(PLUGIN_ROOT, "examples", "completed-scan"))}, scan, { recursive: true });`,+ 'writeFileSync(join(scan, "report.md"), "# Synthetic scan\\n");',+ 'const coveragePath = join(scan, "coverage.json"); const coverage = JSON.parse(readFileSync(coveragePath, "utf8")); coverage.mode = "scoped_path";',+ 'const bytes = JSON.stringify(coverage); writeFileSync(coveragePath, bytes); const manifestPath = join(scan, "scan-manifest.json"); const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));',+ 'manifest.scan.artifacts.find(artifact => artifact.path === "coverage.json").sha256 = createHash("sha256").update(bytes).digest("hex"); writeFileSync(manifestPath, JSON.stringify(manifest));',+ 'const authPath = join(process.env.CODEX_HOME, "auth.json");',+ `writeFileSync(${JSON.stringify(receipt)}, JSON.stringify({ executable: process.execPath, home: process.env.CODEX_HOME, state: process.env.CODEX_SECURITY_STATE_DIR, key: process.env.CODEX_API_KEY ?? null, auth: existsSync(authPath) ? JSON.parse(readFileSync(authPath, "utf8")) : null, value: process.env.SYNTHETIC_COMPONENT, python: process.env.PYTHON, workerConfig: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH ? readFileSync(process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, "utf8") : null }));`,+ 'console.log(JSON.stringify({ type: "thread.started", thread_id: "synthetic-thread" }));',+ 'console.log(JSON.stringify({ type: "item.completed", item: { type: "agent_message", text: "scan complete" } }));',+ 'console.log(JSON.stringify({ type: "turn.completed", usage: null }));',+ "process.exit(0);",+ ].join("\n"),+ );+ const summary = await scan(paths, {+ components: [{ name: "Source", paths: ["."] }],+ createSecurity: undefined,+ environment,+ config: {+ pluginPath: PLUGIN_ROOT,+ codexOverrides: {+ shell_environment_policy: {+ set: { SYNTHETIC_COMPONENT: `worker-${value}` },+ },+ },+ },+ scanOptions: { auth, mode },+ }).finally(ready.resolve);+ expect(+ summary,+ JSON.stringify(await json(summary.summaryPath!)),+ ).toMatchObject({ completed: 1, failed: 0 });+ const child = await json(receipt);+ expect(await realpath(child.executable)).toBe(await realpath(node));+ expect(child).toMatchObject({+ home: join(environment.CODEX_SECURITY_STATE_DIR, "codex-home"),+ state: environment.CODEX_SECURITY_STATE_DIR,+ key: auth === "api-key" ? environment.OPENAI_API_KEY : null,+ auth: auth === "chatgpt" ? storedAuthentication : null,+ value,+ python: "/managed/python",+ });+ if (mode === "deep") {+ expect(parseToml(child.workerConfig)).toMatchObject({+ worker_runtime: {+ shell_environment_policy: {+ set: { SYNTHETIC_COMPONENT: `worker-${value}` },+ },+ },+ });+ } else expect(child.workerConfig).toBeNull();+ expect(environment).toEqual(original);+ expect(await json(join(environment.CODEX_HOME, "auth.json"))).toEqual(+ storedAuthentication,+ );+ }),+ );+ for (const outcome of outcomes)+ if (outcome.status === "rejected") throw outcome.reason;+ expect(arrivals).toBe(2);+ expect(Bun.deepEquals(process.env, originalEnvironment)).toBe(true);+ } finally {+ ready.resolve();+ for (const spy of spies) spy.mockRestore();+ }+ },+);+test("CLI requires an explicitly selected API key before automatic planning", async () => {const paths = await fixture();const planComponentsMock = mock(resolving({ components }));