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(cli): preserve authentication when resuming scans (#875)
mldangelo-oai8b247a9feccb
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjsindex b47ec19ff..76112891d 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_executor.mjs@@ -680,7 +680,6 @@ async function testOpenAiCredentialsReachWorker() {{ openai: " synthetic-openai-key ", codex: " ", expected: "synthetic-openai-key" },{ openai: "synthetic-openai-key", codex: "synthetic-selected-key", expected: "synthetic-selected-key" },{ codex: "synthetic-selected-key", expected: "synthetic-selected-key" },- { openai: "synthetic-openai-key", resumeThreadId: "fixture-resume", expected: "synthetic-openai-key" },{ openai: "synthetic-openai-key", accountResult: { account: { type: "apiKey" }, requiresOpenaiAuth: true } },{ openai: "synthetic-openai-key", accountResult: { account: { type: "chatgpt" }, requiresOpenaiAuth: true } },{ openai: "synthetic-provider-key", accountResult: { account: null, requiresOpenaiAuth: false } },@@ -708,20 +707,28 @@ async function testOpenAiCredentialsReachWorker() {syncBuiltinESMExports();const promptPath = path.join(fixture.root, "prompt.md");await writeFile(promptPath, "CAPTURE_SYNTHETIC_OPENAI_AUTH\n");- await new CodexSdkWorkerExecutor({ parentSandbox: trustedParentSandbox }).run({- kind: "discovery",- promptPath,- workingDirectory: fixture.root,- subagents: 0,- resumeThreadId: entry.resumeThreadId,- signal: new AbortController().signal- });- const invocation = JSON.parse(await readFile(fixture.markerPath, "utf8"));- assert.equal(invocation.openaiAuthentication.CODEX_API_KEY, entry.expected);- assert.equal(invocation.openaiAuthentication.OPENAI_API_KEY, entry.openai);- assert.equal(process.env.CODEX_API_KEY, entry.codex);- assert.equal(process.env.OPENAI_API_KEY, entry.openai);- assert.equal(invocation.argv.some((arg) => arg.includes("synthetic-")), false);+ const executor = new CodexSdkWorkerExecutor({ parentSandbox: trustedParentSandbox });+ for (const kind of ["discovery", "dedup"]) {+ for (const resumeThreadId of [undefined, "fixture-resume"]) {+ await executor.run({+ kind,+ promptPath,+ workingDirectory: fixture.root,+ subagents: 0,+ resumeThreadId,+ signal: new AbortController().signal+ });+ const preflight = JSON.parse(await readFile(fixture.preflightMarkerPath, "utf8"));+ const invocation = JSON.parse(await readFile(fixture.markerPath, "utf8"));+ assert.equal(preflight.codexHome, fixture.root);+ assert.equal(invocation.codexHome, fixture.root);+ assert.equal(invocation.openaiAuthentication.CODEX_API_KEY, entry.expected);+ assert.equal(invocation.openaiAuthentication.OPENAI_API_KEY, entry.openai);+ assert.equal(process.env.CODEX_API_KEY, entry.codex);+ assert.equal(process.env.OPENAI_API_KEY, entry.openai);+ assert.equal(invocation.argv.some((arg) => arg.includes("synthetic-")), false);+ }+ }} finally {childProcess.spawn = originalSpawn;syncBuiltinESMExports();diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 96f7d900a..e3ab1b51c 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -1456,8 +1456,10 @@ The checkout's identity, revision, and contents must match the saved target.Completed, failed, and canceled scans cannot resume; `scans rerun` starts a new scan.Resume uses the saved configuration and instructions with the installed plugin.-New scans save the explicit safety identifier and post-scan prompt contents.-Single-scan resume restores them even if the prompt file changes or disappears.+New scans save the selected authentication mode, explicit safety identifier, and+post-scan prompt contents. Resume restores the authentication choice without+saving credentials. Single-scan resume restores the prompt even if its original+file changes or disappears.Older records that did not save these values cannot reconstruct them. Bulkrecovery still requires matching campaign inputs and options; it uses the suppliedpost-scan prompt when the scan has no saved prompt.diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.tsindex 71cedfa4e..a70986bb2 100644--- a/sdk/typescript/tests-ts/scan-resume.test.ts+++ b/sdk/typescript/tests-ts/scan-resume.test.ts@@ -729,95 +729,117 @@ test.each([},);-test("CLI saves launch settings before execution without depending on the prompt file", async () => {- const root = await temporaryDirectory();- const repository = join(root, "repository");- const codexHome = join(root, "state", "codex-home");- await mkdir(repository);- await mkdir(codexHome, { recursive: true });- await writeFile(join(repository, "source.py"), "# synthetic source\n");- const promptFile = join(root, "post-scan.md");- const postScanPrompt = "Keep these original post-scan instructions.\n";- await writeFile(promptFile, postScanPrompt);- const python = Bun.which("python3") ?? Bun.which("python");- if (python === null) throw new Error("Python is required for this test.");- const environment = {- PATH: process.env["PATH"],- SystemRoot: process.env["SystemRoot"],- TEMP: process.env["TEMP"],- TMP: process.env["TMP"],- CODEX_HOME: codexHome,- CODEX_SECURITY_STATE_DIR: join(root, "state"),- OPENAI_API_KEY: "synthetic-launch-key",- };- const command = (args: readonly string[], input?: string) =>- runWorkbench({ python, pluginRoot: PLUGIN_ROOT, environment }, args, input);- const stdout = capture();- const stderr = capture();- const code = await main(- [- "scan",- repository,- "--mode",- "deep",- "--output-dir",- join(root, "scan"),- "--safety-identifier",- "synthetic-original-user",- "--post-scan-prompt-file",+test.each(["chatgpt", "api-key"] as const)(+ "CLI saves %s authentication and launch settings before execution",+ async (auth) => {+ const safetyIdentifier =+ auth === "chatgpt" ? undefined : "synthetic-original-user";+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const codexHome = join(root, "state", "codex-home");+ await mkdir(repository);+ await mkdir(codexHome, { recursive: true });+ await writeFile(join(repository, "source.py"), "# synthetic source\n");+ const promptFile = join(root, "post-scan.md");+ const postScanPrompt = "Keep these original post-scan instructions.\n";+ await writeFile(promptFile, postScanPrompt);+ const python = Bun.which("python3") ?? Bun.which("python");+ if (python === null) throw new Error("Python is required for this test.");+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ TEMP: process.env["TEMP"],+ TMP: process.env["TMP"],+ CODEX_HOME: codexHome,+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ OPENAI_API_KEY: "synthetic-launch-key",+ };+ const command = (args: readonly string[], input?: string) =>+ runWorkbench(+ { python, pluginRoot: PLUGIN_ROOT, environment },+ args,+ input,+ );+ const stdout = capture();+ const stderr = capture();+ const code = await main(+ [+ "scan",+ repository,+ "--mode",+ "deep",+ "--output-dir",+ join(root, "scan"),+ "--auth",+ auth,+ ...(safetyIdentifier === undefined+ ? []+ : ["--safety-identifier", safetyIdentifier]),+ "--post-scan-prompt-file",+ promptFile,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ {+ ...dependencies({ environment, currentDirectory: root }),+ runWorkbench: command,+ createSecurity: (config) =>+ new TestClient(config, {+ environment,+ prepareRuntime: async () => preparedRuntime(codexHome),+ resolvePluginPython: async () => python,+ runWorkbench,+ createCodex: () => {+ throw new Error("Synthetic stop after registration");+ },+ }),+ },+ );+ expect(code).toBe(2);+ expect(stderr.text()).toContain("Synthetic stop after registration");+ await writeFile(promptFile,- "--json",- ],- stdout.stream,- stderr.stream,- {- ...dependencies({ environment, currentDirectory: root }),- runWorkbench: command,- createSecurity: (config) =>- new TestClient(config, {- environment,- prepareRuntime: async () => preparedRuntime(codexHome),- resolvePluginPython: async () => python,- runWorkbench,- createCodex: () => {- throw new Error("Synthetic stop after registration");- },- }),- },- );- expect(code).toBe(2);- expect(stderr.text()).toContain("Synthetic stop after registration");- await writeFile(- promptFile,- "Changed instructions that must not replace the saved text.",- );- await rm(promptFile);- const scans = (await command(["list-scans", "--repository", repository]))[- "scans"- ] as Array<{ scanId: string }>;- expect(scans).toHaveLength(1);- const saved = await command([- "get-scan-recipe",- "--scan-id",- scans[0]!.scanId,- ]);- expect(saved["recipe"]).toMatchObject({- safetyIdentifier: "synthetic-original-user",- postScanPrompt,- });- expect(JSON.stringify(saved)).not.toContain("synthetic-launch-key");- expect(JSON.stringify(saved)).not.toContain(promptFile);-});+ "Changed instructions that must not replace the saved text.",+ );+ await rm(promptFile);+ const scans = (await command(["list-scans", "--repository", repository]))[+ "scans"+ ] as Array<{ scanId: string }>;+ expect(scans).toHaveLength(1);+ const saved = await command([+ "get-scan-recipe",+ "--scan-id",+ scans[0]!.scanId,+ ]);+ expect(saved["recipe"]).toMatchObject({+ auth,+ ...(safetyIdentifier === undefined ? {} : { safetyIdentifier }),+ postScanPrompt,+ });+ expect(JSON.stringify(saved)).not.toContain("synthetic-launch-key");+ expect(JSON.stringify(saved)).not.toContain(promptFile);+ },+);-test.each([false, true])(- "resume restores saved launch settings (bulk: %p)",- async (bulk) => {+test.each([+ ["chatgpt", false],+ ["api-key", false],+ [undefined, false],+ ["chatgpt", true],+ ["api-key", true],+ [undefined, true],+] as const)(+ "resume restores saved launch settings with %s auth (bulk: %p)",+ async (auth, bulk) => {const settings = {- auth: "api-key" as const,- safetyIdentifier: "synthetic-original-user",+ auth,+ safetyIdentifier:+ auth === "chatgpt" ? undefined : "synthetic-original-user",postScanPrompt: "Run these exact saved post-scan instructions.\n",};const f = await interruptedScan("deep", bulk, settings, true);+ f.environment.OPENAI_API_KEY = "synthetic-resume-key";const ambientHome = join(f.root, "ambient-codex-home");f.environment.CODEX_HOME = ambientHome;const ambientDeepConfig = join(@@ -846,7 +868,11 @@ test.each([false, true])(expect(options.env?.["CODEX_SAFETY_IDENTIFIER"]).toBe(settings.safetyIdentifier,);- expect(options.apiKey).toBe("synthetic-resume-key");+ expect(options.apiKey).toBe(+ auth === "chatgpt" ? undefined : "synthetic-resume-key",+ );+ expect(options.env?.["OPENAI_API_KEY"]).toBeUndefined();+ expect(options.env?.["CODEX_API_KEY"]).toBeUndefined();return {startThread() {throw new Error("Resume must use the original session.");@@ -881,6 +907,7 @@ test.each([false, true])(expect(code, stderr.text()).toBe(2);expect(prompts, stderr.text()).toHaveLength(2);expect(prompts[1]).toBe(settings.postScanPrompt);+ expect(f.environment.OPENAI_API_KEY).toBe("synthetic-resume-key");expect((await f.command(["get-scan", "--scan-id", f.scanId]))["scan"],).toMatchObject({