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(plugin): authenticate deep workers with OpenAI API keys (#870)
mldangelo-oai00afa60adc3f
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex 2d1753ebe..a6579f74a 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -52,25 +52,31 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {const configOverrides = workerPermissionProfileConfigOverrides(workerProfile);const originalCwd = process.cwd();const childEnv = await snapshotWorkerEnvironment();+ const openAiApiKey = environmentVariable(childEnv, "OPENAI_API_KEY", process.platform)?.trim();+ const codexApiKey = environmentVariable(childEnv, "CODEX_API_KEY", process.platform)?.trim();const codexPath = resolveCodexPath(childEnv,process.platform,process.arch,originalCwd);- await preflightDeepScanWorkerPermissionProfile({+ const { useOpenAiApiKey } = await preflightDeepScanWorkerPermissionProfile({codexPath,cwd: request.workingDirectory,profileId: DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID,configOverrides,expectedProfile: workerProfile,env: childEnv,+ allowOpenAiApiKeyFallback: Boolean(openAiApiKey && !codexApiKey),signal: request.signal});const prompt = await fs.readFile(request.promptPath, "utf8");const codex = new Codex({codexPathOverride: executablePathForSpawn(codexPath),env: childEnv,+ // Codex exec reads CODEX_API_KEY; the SDK maps apiKey to that variable.+ // Keep native credentials unless the worker has no configured account.+ ...(useOpenAiApiKey ? { apiKey: openAiApiKey } : {}),config: {// The CLI can add effort levels before the pinned SDK widens ThreadOptions....(this.modelSettings.reasoningEffortdiff --git a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.tsindex 0e23712cf..c5299478b 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts@@ -23,6 +23,8 @@ export interface DeepScanPermissionProfilePreflightOptions {* Omit it to retain Node's default child-process environment inheritance.*/readonly env?: Readonly<Record<string, string>>;+ /** Check native authentication before using an otherwise ignored OPENAI_API_KEY. */+ readonly allowOpenAiApiKeyFallback?: boolean;/** The injected profile before app-server expands omitted options to null. */readonly expectedProfile: Readonly<Record<string, unknown>>;readonly signal: AbortSignal;@@ -52,7 +54,7 @@ type PendingRequest = {*/export async function preflightDeepScanWorkerPermissionProfile(options: DeepScanPermissionProfilePreflightOptions-): Promise<void> {+): Promise<{ useOpenAiApiKey: boolean }> {validateOptions(options);if (options.signal.aborted) throw abortError(options.signal.reason);@@ -69,6 +71,18 @@ export async function preflightDeepScanWorkerPermissionProfile(? undefined: await client.readConfigRequirementsForClassification();verifyPreflightResult(options, configResponse, catalogEntry, requirementsResponse);+ if (+ !options.allowOpenAiApiKeyFallback+ || record(configResponse.config)?.forced_login_method === "chatgpt"+ ) {+ return { useOpenAiApiKey: false };+ }+ // Reuse Codex's selected credential store and provider, including keyring+ // and command-backed providers, instead of interpreting auth.json here.+ const account = await client.request("account/read", { refreshToken: false });+ return {+ useOpenAiApiKey: account.requiresOpenaiAuth === true && account.account === null+ };} finally {await client.close();}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 b703cd2bb..f24348d6f 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@@ -72,6 +72,7 @@ const deniedWorkerPermissionProfile = {};try {+ await testOpenAiCredentialsReachWorker();if (process.platform !== "win32") {await testMissingParentSandboxFailsBeforeWorkerLaunch();await testDisallowedWorkerProfileFailsBeforeWorkerLaunch();@@ -671,6 +672,63 @@ async function testSdkInvocationAndThreadCapture() {}}+async function testOpenAiCredentialsReachWorker() {+ const noAccount = { account: null, requiresOpenaiAuth: true };+ const cases = [+ { openai: "synthetic-openai-key", expected: "synthetic-openai-key" },+ { 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 } },+ {},+ { openai: " " }+ ];+ for (const entry of cases) {+ const fixture = await fakeCodexFixture(emptyWorkerPermissionProfile, true, entry.accountResult ?? noAccount);+ const previousEnvironment = Object.fromEntries(+ ["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_CLI_PATH", "CODEX_HOME"].map((name) => [name, process.env[name]])+ );+ const originalSpawn = childProcess.spawn;+ try {+ restoreEnv("OPENAI_API_KEY", entry.openai);+ restoreEnv("CODEX_API_KEY", entry.codex);+ process.env.CODEX_CLI_PATH = process.execPath;+ process.env.CODEX_HOME = fixture.root;+ childProcess.spawn = (command, args, options) => originalSpawn(+ command,+ command === process.execPath || command === path.toNamespacedPath(process.execPath)+ ? [fixture.executablePath, ...args]+ : args,+ options+ );+ 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);+ } finally {+ childProcess.spawn = originalSpawn;+ syncBuiltinESMExports();+ for (const [name, value] of Object.entries(previousEnvironment)) restoreEnv(name, value);+ }+ }+}+async function testBedrockCredentialsReachWorker() {const fixture = await fakeCodexFixture();const mcpConfig = JSON.parse(@@ -1332,7 +1390,8 @@ async function testRuntimePermissionProfileFallbackStopsAndDiscards() {async function fakeCodexFixture(preflightProfile = emptyWorkerPermissionProfile,- preflightAllowed = true+ preflightAllowed = true,+ accountResult = { account: { type: "apiKey" }, requiresOpenaiAuth: true }) {const root = await mkdtemp(path.join(tmpdir(), "codex-security-sdk-executor-"));temporaryRoots.push(root);@@ -1344,6 +1403,7 @@ async function fakeCodexFixture('import { writeFileSync } from "node:fs";',`const preflightProfile = ${JSON.stringify(preflightProfile)};`,`const preflightAllowed = ${JSON.stringify(preflightAllowed)};`,+ `const accountResult = ${JSON.stringify(accountResult)};`,`const preflightMarkerPath = ${JSON.stringify(preflightMarkerPath)};`,"if (process.argv.includes('app-server')) {"," const preflight = { cwd: process.cwd(), codexHome: process.env.CODEX_HOME, requests: [] };",@@ -1371,6 +1431,8 @@ async function fakeCodexFixture(" result = { config: { default_permissions: 'codex_security_deep_scan_worker', permissions: { codex_security_deep_scan_worker: preflightProfile } }, origins: {}, layers: null };"," } else if (message.method === 'permissionProfile/list') {"," result = { data: [{ id: 'codex_security_deep_scan_worker', description: null, allowed: preflightAllowed }], nextCursor: null };",+ " } else if (message.method === 'account/read') {",+ " result = accountResult;"," } else if (message.method === 'configRequirements/read') {"," result = { requirements: { allowedPermissionProfiles: { existing_profile: true } } };"," } else {",@@ -1384,8 +1446,9 @@ async function fakeCodexFixture("} else {","let stdin = '';","for await (const chunk of process.stdin) stdin += chunk;",+ "const openaiAuthentication = stdin.includes('CAPTURE_SYNTHETIC_OPENAI_AUTH') ? { OPENAI_API_KEY: process.env.OPENAI_API_KEY, CODEX_API_KEY: process.env.CODEX_API_KEY } : undefined;","const bedrockAuthentication = stdin.includes('CAPTURE_SYNTHETIC_BEDROCK_AUTH') ? Object.fromEntries(JSON.parse(process.env.FAKE_CODEX_BEDROCK_ENV_KEYS).map((name) => [name, process.env[name]])) : undefined;",- "writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ argv: process.argv.slice(2), stdin, cwd: process.cwd(), codexHome: process.env.CODEX_HOME, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(stdin.includes('COMPLETE_THEN_HANG') ? { pid: process.pid } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));",+ "writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ argv: process.argv.slice(2), stdin, cwd: process.cwd(), codexHome: process.env.CODEX_HOME, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(stdin.includes('COMPLETE_THEN_HANG') ? { pid: process.pid } : {}), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));","if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => setTimeout(() => process.exit(0), 100));","if (stdin.includes('THREAD_START_CONFIG_ERROR')) { console.error('Error: thread/start: thread/start failed: agents.max_threads cannot be set when features.multi_agent_v2 is enabled (code -32600)'); process.exit(1); }","if (stdin.includes('CONFIG_ERROR')) { console.error('failed to load configuration: invalid value'); process.exit(2); }",diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjsindex 03fe8a821..36060566a 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.mjs@@ -39,6 +39,7 @@ const rawOverrides = [await testAllowedProfileAndRawArgv();await testPreflightStartsInWorkerCwd();await testProvidedEnvForwardedWithoutMutation();+await testOpenAiApiKeyFallbackPreservesNativeAuthentication();await testSequentialPaginatedResponsesAcrossChunks();await testMalformedStreamFailsClosed();await testRepeatedCatalogCursorFailsClosed();@@ -124,6 +125,39 @@ async function testProvidedEnvForwardedWithoutMutation() {});}+async function testOpenAiApiKeyFallbackPreservesNativeAuthentication() {+ for (const { account, requiresOpenaiAuth, forcedLoginMethod, expected } of [+ { account: null, requiresOpenaiAuth: true, expected: true },+ { account: { type: "apiKey" }, requiresOpenaiAuth: true, expected: false },+ { account: { type: "chatgpt", email: "[email protected]", planType: "pro" }, requiresOpenaiAuth: true, expected: false },+ { account: null, requiresOpenaiAuth: false, expected: false },+ { account: null, requiresOpenaiAuth: true, forcedLoginMethod: "chatgpt", expected: false }+ ]) {+ const configResult = configReadResult(expectedProfile);+ if (forcedLoginMethod) configResult.config.forced_login_method = forcedLoginMethod;+ await withFakeCodex({+ configResult,+ catalogResults: [catalogResult(true)],+ accountResult: { account, requiresOpenaiAuth }+ }, async ({ codexPath, cwd, callsPath }) => {+ const result = await preflightDeepScanWorkerPermissionProfile({+ codexPath,+ cwd,+ profileId,+ configOverrides: rawOverrides,+ expectedProfile,+ allowOpenAiApiKeyFallback: true,+ signal: new AbortController().signal+ });+ assert.equal(result.useOpenAiApiKey, expected);+ const calls = await readJsonLines(callsPath);+ const accountCalls = calls.filter((call) => call.method === "account/read");+ assert.equal(accountCalls.length, forcedLoginMethod === "chatgpt" ? 0 : 1);+ if (accountCalls.length) assert.deepEqual(accountCalls[0].params, { refreshToken: false });+ });+ }+}+async function testPreflightStartsInWorkerCwd() {await withFakeCodex({configResult: configReadResult(expectedProfile),@@ -600,6 +634,10 @@ function handle(message) {send(message.id, scenario.catalogResults?.[catalogIndex++] ?? { data: [], nextCursor: null });return;}+ if (message.method === "account/read") {+ send(message.id, scenario.accountResult);+ return;+ }if (message.method === "configRequirements/read") {send(message.id, scenario.requirementsResult ?? { requirements: null });return;diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.mjs b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.mjsindex 0dd9ff270..63ddf58b5 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.mjs+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.mjs@@ -82,6 +82,8 @@ async function testDeepScanStdioLifecycle() {const environment = {...process.env,+ OPENAI_API_KEY: "synthetic-stdio-key",+ CODEX_API_KEY: "",CODEX_CLI_PATH: fakeCodexPath,CODEX_HOME: codexHome,CODEX_SECURITY_SCAN_ROOT: scanRoot,@@ -151,6 +153,7 @@ async function testDeepScanStdioLifecycle() {const scanId = await waitForScanId({ server });await waitForDeepScanWorker({ environment, scanId, threadId });const [startedWorker] = await waitForJsonLines(startLogPath, 1);+ assert.equal(startedWorker.hasExpectedApiKey, true);const workerContext = discoveryPromptContext(startedWorker.stdin);assert.match(startedWorker.stdin, /record_codex_security_scan_draft/);const startedState = await getDeepScan({ environment, scanId, threadId });@@ -639,7 +642,7 @@ function startServer(serverPath, env) {return responses.get(id);},async stop() {- if (child.exitCode !== null) return;+ if (child.exitCode !== null || child.signalCode !== null) return;child.stdin.end();const exited = new Promise((resolve) => child.once("exit", resolve));const graceful = await Promise.race([exited.then(() => true), delay(2_000).then(() => false)]);@@ -777,6 +780,8 @@ async function writeFakeCodex(executablePath) {" result = { config: { default_permissions: 'codex_security_deep_scan_worker', permissions: { codex_security_deep_scan_worker: { extends: ':read-only', filesystem: { ':root': 'read' }, network: { enabled: false } } } }, origins: {}, layers: null };"," } else if (message.method === 'permissionProfile/list') {"," result = { data: [{ id: 'codex_security_deep_scan_worker', description: null, allowed: true }], nextCursor: null };",+ " } else if (message.method === 'account/read') {",+ " result = { account: null, requiresOpenaiAuth: true };"," } else {"," process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } }) + '\\n');"," continue;",@@ -790,7 +795,7 @@ async function writeFakeCodex(executablePath) {"for await (const chunk of process.stdin) stdin += chunk;","const context = JSON.parse(stdin.match(/```json\\n([\\s\\S]*?)\\n```/u)[1]);","const root = process.argv[process.argv.indexOf('--cd') + 1];",- "appendFileSync(process.env.FAKE_CODEX_START_LOG, JSON.stringify({ pid: process.pid, argv: process.argv.slice(2), stdin }) + '\\n');",+ "appendFileSync(process.env.FAKE_CODEX_START_LOG, JSON.stringify({ pid: process.pid, argv: process.argv.slice(2), stdin, hasExpectedApiKey: process.env.CODEX_API_KEY === 'synthetic-stdio-key' }) + '\\n');","console.log(JSON.stringify({ type: 'thread.started', thread_id: `stdio-fixture-${process.pid}` }));","if (existsSync(process.env.FAKE_CODEX_RESTART_CONTROL)) {"," const phase = readFileSync(process.env.FAKE_CODEX_RESTART_CONTROL, 'utf8');",diff --git a/plugins/codex-security/references/config-preflight.md b/plugins/codex-security/references/config-preflight.mdindex 28545afac..c1d5dde3b 100644--- a/plugins/codex-security/references/config-preflight.md+++ b/plugins/codex-security/references/config-preflight.md@@ -62,6 +62,8 @@ Some remediation patches have `kind = "host_setting"`. Present those as host-levDeep Security Scan uses MCP-owned SDK sessions rather than the parent thread's worker pool. Its preflight does not require a particular parent delegation runtime, ownership, capacity, or depth. Discovery workers inherit the scan's model and use the reserved `codex_security_deep_scan_worker` permission profile with the parent's supported filesystem denials. The selected Codex executable must support permission-profile configuration and allowance checks. If that command fails to start or exits early, report its path and the tool's diagnostic; do not infer that its version is unsupported. If the tool identifies a missing API, ask the user to update the Codex installation at the reported path: the desktop app for an app-bundled executable, or the selected CLI otherwise. If Codex policy rejects the profile, report the tool's administrator guidance. Do not remove deny rules or select a broader sandbox to work around the error.+Deep Scan workers use the selected Codex home's credentials and provider configuration. An existing `CODEX_API_KEY` remains selected. When the worker has no Codex account and its provider requires OpenAI authentication, it can use `OPENAI_API_KEY` through the SDK's API-key option. This does not replace a stored account, custom-provider authentication, or a forced ChatGPT login. The key must be present in the process that launched the plugin; setting it later in a separate shell does not update a running plugin.+Do not warn merely because a user's value differs from the profile's suggested patch. Warn or block only when the evaluated capability requirement is unmet.If a blocking runtime capability is `unknown`, establish it from the current tool surface and rerun the helper with an explicit `--runtime-check`. An unknown `warn` or `suggest` capability does not block a `ready` scan; continue on the documented degraded path without claiming that capability is available.diff --git a/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts b/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.tsindex ddcda61fe..a94bbb8c4 100644--- a/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts+++ b/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts@@ -22,7 +22,7 @@ type WorkerExecutorConstructor = new (settings: {async function bundledWorkerExecutor(events: (signal: AbortSignal) => AsyncGenerator<WorkerEvent>,- preflight = async () => {},+ preflight = async () => ({ useOpenAiApiKey: false }),): Promise<WorkerExecutorConstructor> {const runtime = await loadBundledRuntime();const source = /var CodexSdkWorkerExecutor = class \{[\s\S]*?\n\};/u.exec(@@ -54,6 +54,7 @@ async function bundledWorkerExecutor("workerPermissionProfile","workerPermissionProfileConfigOverrides","snapshotWorkerEnvironment",+ "environmentVariable","preflightDeepScanWorkerPermissionProfile","DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID","deepScanPermissionProfileFallbackError",@@ -69,6 +70,7 @@ async function bundledWorkerExecutor(() => ({}),() => [],async () => ({}),+ () => undefined,preflight,"codex_security_deep_scan_worker",() => undefined,