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(runtime): preserve worker settings and executable selection (#1501)
mldangelo-oaiab2df5b31817
diff --git a/evals/secret-discovery/test_runtime.mts b/evals/secret-discovery/test_runtime.mtsindex c5c67c44b..4a0cf5dca 100644--- a/evals/secret-discovery/test_runtime.mts+++ b/evals/secret-discovery/test_runtime.mts@@ -197,10 +197,11 @@ test("the SDK launches long Windows paths with the native namespace prefix", asy});test("the SDK executable override preserves bundled tools at the child boundary", async (t) => {- const directory = await mkdtemp(join(tmpdir(), "eval-tools-test-"));+ const directory = await temporaryDirectory("eval-tools-test-", true);t.after(() => rm(directory, { recursive: true, force: true }));const executable = join(directory, "bin", "codex");const tools = join(directory, "codex-path");+ await mkdir(dirname(executable));await mkdir(tools);const inherited = {Path: [tools, join(directory, "other tools"), tools].join(delimiter),diff --git a/plugins/codex-security/.mcp.json b/plugins/codex-security/.mcp.jsonindex 9e901b69b..21303cf73 100644--- a/plugins/codex-security/.mcp.json+++ b/plugins/codex-security/.mcp.json@@ -35,6 +35,7 @@"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","PYTHON","PYTHONUTF8",+ "CODEX_SECURITY_PYTHON_COMMAND","CODEX_SECURITY_GIT","CODEX_SECURITY_KNOWLEDGE_BASE","CODEX_SECURITY_CONFIG_PATH",diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex c6a061161..b69638298 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -14,6 +14,7 @@ import {isAbsolute,join,resolve,+ sep,win32,} from "node:path";import {@@ -723,7 +724,7 @@ function resolveFromSearchPath(originalCwd: string,): string | undefined {for (const directory of searchPath?.split(delimiter) ?? []) {- const candidate = join(resolve(originalCwd, directory), executableName);+ const candidate = `${absoluteCodexPath(directory, process.platform, originalCwd)}${sep}${executableName}`;if (isExecutableFile(candidate)) return candidate;}return undefined;@@ -830,7 +831,9 @@ function absoluteCodexPath(if (isAbsolute(value) || (platform === "win32" && win32.isAbsolute(value))) {return value;}- return resolve(originalCwd, value);+ return platform === "win32"+ ? resolve(originalCwd, value)+ : `${originalCwd}${sep}${value}`;}function isNativeWindowsRootRelativePath(value: string): boolean {diff --git a/plugins/codex-security/mcp-app/src/python_command.ts b/plugins/codex-security/mcp-app/src/python_command.tsindex 9d44e05d8..24a6027aa 100644--- a/plugins/codex-security/mcp-app/src/python_command.ts+++ b/plugins/codex-security/mcp-app/src/python_command.ts@@ -22,6 +22,12 @@ const MISSING_PYTHON_HELPER_MESSAGE =export async function resolvePythonCommand(options: ResolvePythonCommandOptions = {},): Promise<string> {+ if (+ options.configuredPython === undefined &&+ process.env.CODEX_SECURITY_PYTHON_COMMAND+ ) {+ return process.env.CODEX_SECURITY_PYTHON_COMMAND;+ }const configuredPython = options.configuredPython ?? process.env.PYTHON;if (configuredPython?.trim()) {return configuredPython.trim();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 9a1221ad6..8e274f341 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@@ -32,6 +32,16 @@ import type {import { testDeepScanContextSnapshots } from "./deep_scan_context_snapshot_cases.ts";const executorSource = new URL("../src/deep-scan/executor.ts", import.meta.url);+const { bundledCodexSdkEnvironment } = await importModule({+ entryPoints: [+ fileURLToPath(+ new URL(+ "../../../../sdk/typescript/src/codex-sdk-environment.ts",+ import.meta.url,+ ),+ ),+ ],+});const {CodexSdkWorkerExecutor,@@ -56,7 +66,7 @@ export * from "./errors.js";`,},});-const temporaryDirectories = createTemporaryDirectories();+const temporaryDirectories = createTemporaryDirectories(true);const previousMarker = process.env.FAKE_CODEX_MARKER;const trustedParentSandbox = Object.freeze({filesystemDenies: [],@@ -809,6 +819,13 @@ async function testPreflightBindsExecutableAndHomeBeforeChangingCwd() {await mkdir(nonExecutableDirectory);await mkdir(path.join(directoryShadow, "codex"), { recursive: true });await mkdir(binaryDirectory);+ const bundledTools = path.join(fixture.root, "codex-path");+ await mkdir(bundledTools);+ await writeFile(+ path.join(bundledTools, "rg"),+ "#!/bin/sh\nprintf 'synthetic bundled search\\n'\n",+ { mode: 0o755 },+ );await mkdir(homeTargetChild, { recursive: true });await mkdir(codexHome, { recursive: true });assert.notEqual(workingDirectory, originalCwd);@@ -817,8 +834,16 @@ async function testPreflightBindsExecutableAndHomeBeforeChangingCwd() {path.join(nonExecutableDirectory, "codex"),"not executable\n",);- await copyFile(fixture.executablePath, codexPath);- await chmod(codexPath, 0o755);+ // A shell wrapper lets the OS select this file before Node loads the fixture.+ const shellArguments = [process.execPath, fixture.executablePath]+ .map((value) => `'${value.replaceAll("'", `'"'"'`)}'`)+ .join(" ");+ await writeFile(codexPath, `#!/bin/sh\nexec ${shellArguments} "$@"\n`, {+ mode: 0o755,+ });+ await mkdir(path.join(binaryDirectory, "child"));+ const executableLink = path.join(fixture.root, "executable-link");+ await symlink(path.join(binaryDirectory, "child"), executableLink, "dir");await symlink(homeTargetChild, homeLink, "dir");const relativeHome = `${path.relative(originalCwd, homeLink)}/../home`;const expectedHome = await realpath(relativeHome);@@ -837,36 +862,92 @@ async function testPreflightBindsExecutableAndHomeBeforeChangingCwd() {path.dirname(process.execPath),].join(path.delimiter);try {- for (const [configured, expectedExecutable] of [+ const defaultSearchPath = process.env.PATH;+ for (const [configured, expectedExecutable, searchPath] of [[path.relative(originalCwd, fixture.executablePath),fixture.executablePath,],[undefined, codexPath],+ [`${binaryDirectory}/./codex`, codexPath],["codex", codexPath],+ [`${executableLink}/../codex`, codexPath],+ [`${path.relative(originalCwd, executableLink)}/../codex`, codexPath],+ ...[+ `${executableLink}/..`,+ `${path.relative(originalCwd, executableLink)}/..`,+ ].flatMap(+ (entry) =>+ [+ [+ undefined,+ codexPath,+ `${entry}${path.delimiter}${path.dirname(process.execPath)}`,+ ],+ [+ "codex",+ codexPath,+ `${entry}${path.delimiter}${path.dirname(process.execPath)}`,+ ],+ ] as const,+ ),] as const) {+ process.env.PATH = searchPath ?? defaultSearchPath;if (configured === undefined) delete process.env.CODEX_CLI_PATH;else process.env.CODEX_CLI_PATH = configured;- assert.equal(resolveCodexPath(), expectedExecutable);- const result = await runWorker(promptPath, workingDirectory);+ const hasBundledTools = expectedExecutable === codexPath;+ if (hasBundledTools) {+ process.env.PATH = bundledCodexSdkEnvironment(resolveCodexPath(), {+ PATH: process.env.PATH,+ }).PATH;+ }+ await writeFile(+ promptPath,+ hasBundledTools+ ? "CAPTURE_SYNTHETIC_RG"+ : "fixture bound worker executable and home",+ );+ assert.equal(+ await realpath(resolveCodexPath()),+ await realpath(expectedExecutable),+ );+ for (const kind of ["discovery", "dedup"] as const)+ for (const resumeThreadId of [undefined, "resumed-thread"]) {+ const result = await runWorker(promptPath, workingDirectory, {+ kind,+ resumeThreadId,+ });- assert.equal(result.threadId, "fixture-thread-id");- const preflight = await readJson(fixture.preflightMarkerPath);- const invocation = await readJson(fixture.markerPath);- assert.equal(preflight.cwd, await realpath(workingDirectory));- assert.equal(invocation.cwd, originalCwd);- assert.equal(preflight.codexHome, expectedHome);- assert.equal(invocation.codexHome, expectedHome);- assert.equal(process.env.CODEX_HOME, relativeHome);- assert.deepEqual(preflight.requests, [- { method: "config/read", cwd: workingDirectory },- { method: "permissionProfile/list", cwd: workingDirectory },- ]);- assert.deepEqual(invocation.argv.slice(0, 2), [- "exec",- "--experimental-json",- ]);- assertFlagPair(invocation.argv, "--cd", workingDirectory);+ assert.equal(result.threadId, resumeThreadId ?? "fixture-thread-id");+ const preflight = await readJson(fixture.preflightMarkerPath);+ const invocation = await readJson(fixture.markerPath);+ assert.equal(preflight.cwd, await realpath(workingDirectory));+ assert.equal(invocation.cwd, originalCwd);+ assert.equal(preflight.codexHome, expectedHome);+ assert.equal(invocation.codexHome, expectedHome);+ if (hasBundledTools) {+ assert.equal(+ invocation.runtimeEnvironment.PATH.split(path.delimiter)[0],+ bundledTools,+ );+ assert.equal(invocation.bundledTool, "synthetic bundled search");+ assert.equal(+ preflight.gitEnvironment.PATH,+ invocation.runtimeEnvironment.PATH,+ );+ }+ assert.equal(process.env.CODEX_HOME, relativeHome);+ assert.deepEqual(preflight.requests, [+ { method: "config/read", cwd: workingDirectory },+ { method: "permissionProfile/list", cwd: workingDirectory },+ ]);+ assert.deepEqual(invocation.argv.slice(0, 2), [+ "exec",+ "--experimental-json",+ ]);+ assertFlagPair(invocation.argv, "--cd", workingDirectory);+ assertReadOnlyWorkerPolicy(invocation.argv);+ }}} finally {restoreEnv("CODEX_CLI_PATH", previousCodexPath);@@ -1038,6 +1119,8 @@ async function testOpenAiCredentialsReachWorker() {? "": process.env.LD_LIBRARY_PATH + path.delimiter) +path.join(fixture.root, "libraries"),+ DYLD_LIBRARY_PATH: path.join(fixture.root, "dylibs"),+ DYLD_FALLBACK_LIBRARY_PATH: path.join(fixture.root, "fallback-libraries"),CODEX_SECURITY_STATE_DIR: path.join(fixture.root, "state"),RUNNER_TRACKING_ID: "synthetic-worker-job",};@@ -1256,6 +1339,7 @@ async function testWorkerRuntimeSettings() {];const saved = ["PYTHON",+ "CODEX_SECURITY_PYTHON_COMMAND","PATH","CODEX_SECURITY_GIT","GIT_SSH_COMMAND",@@ -1272,9 +1356,13 @@ async function testWorkerRuntimeSettings() {"SYNTHETIC_HEADER_VALUE","CODEX_SQLITE_HOME","XDG_CACHE_HOME",+ "LD_LIBRARY_PATH",+ "DYLD_LIBRARY_PATH",+ "DYLD_FALLBACK_LIBRARY_PATH",].map((name) => [name, process.env[name]] as const);const originalSpawn = childProcess.spawn;try {+ process.env.CODEX_SECURITY_PYTHON_COMMAND = "stale-ambient-python";delete process.env.OPENAI_API_KEY;delete process.env.CODEX_API_KEY;delete process.env.SYNTHETIC_GATEWAY_KEY;@@ -1412,6 +1500,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,index === 0? undefined: {+ goals: index % 2 === 0,shell_tool: index % 2 === 0,unified_exec: false,view_image: index % 2 !== 0,@@ -1499,6 +1588,15 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,autoCompactTokenLimit:index === 0 ? undefined : 24_000 * (index + 1),windowsSandbox,+ shellPolicy:+ index === 0+ ? undefined+ : {+ inherit: index % 2 === 0 ? "core" : "none",+ include_only: ["PATH", "SYNTHETIC_INCLUDED"],+ exclude: ["SYNTHETIC_EXCLUDED"],+ set: { SYNTHETIC_SHELL_MARKER: `scan-${index}` },+ },webSearch,features,telemetry,@@ -1572,6 +1670,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,native_profile: entry.nativeProfile,environment: entry.environment,windows: { sandbox: entry.windowsSandbox },+ shell_environment_policy: entry.shellPolicy,features: entry.features,}),},@@ -1646,7 +1745,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,pluginRoot: path.join(fixture.root, `plugin-${index}`),repoRoot: fixture.root,scanId: `fixture-scan-${modelSettings.model ?? "inherited"}`,- pythonCommand: helperPython,+ pythonCommand: `${helperPython}-${index} `,},}),);@@ -1665,6 +1764,16 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,fixture.root,`cache-${index} `,);+ for (const name of [+ "LD_LIBRARY_PATH",+ "DYLD_LIBRARY_PATH",+ "DYLD_FALLBACK_LIBRARY_PATH",+ ]) {+ process.env[name] = path.join(+ fixture.root,+ `libraries-${index}`,+ );+ }restoreEnv("CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",workerConfigurations[index].workerConfigPath,@@ -1746,6 +1855,20 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,workerConfigurations[index].knowledgePath,);const invocation = await readJson(workerLaunch.markerPath);+ for (const name of [+ "LD_LIBRARY_PATH",+ "DYLD_LIBRARY_PATH",+ "DYLD_FALLBACK_LIBRARY_PATH",+ ]) {+ assert.equal(+ workerLaunch.environment![name],+ path.join(fixture.root, `libraries-${index}`),+ );+ assert.equal(+ invocation.runtimeEnvironment[name],+ workerLaunch.environment![name],+ );+ }assert.equal(invocation.knowledgePath,workerConfigurations[index].knowledgePath,@@ -1873,8 +1996,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,}assert.equal(invocation.python, python);assertConfigOverrides(invocation.argv, {- "mcp_servers.cs_artifacts.env.CODEX_SECURITY_PYTHON_COMMAND":- helperPython,+ "mcp_servers.cs_artifacts.env.CODEX_SECURITY_PYTHON_COMMAND": `${helperPython}-${index} `,"mcp_servers.cs_artifacts.args.0": path.join(fixture.root,`plugin-${index}`,@@ -1891,6 +2013,20 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,invocation.deepConfigPath,workerConfigurations[index].workerConfigPath,);+ assert.deepEqual(+ JSON.parse(+ JSON.stringify(+ parseToml(+ invocation.argv+ .filter((arg: string) =>+ arg.startsWith("shell_environment_policy="),+ )+ .join("\n"),+ ),+ ),+ ).shell_environment_policy,+ workerConfigurations[index].shellPolicy,+ );const workerFeatures = parseToml(invocation.argv.filter((arg: string) => /^features[.=]/.test(arg))@@ -2013,7 +2149,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,),writeFile(entry.deepPath,- '[worker_runtime.features]\nshell_tool = true\nunified_exec = true\nview_image = true\n[worker_runtime]\nopenai_base_url = "https://changed-snapshot.example.test/v1"\nweb_search = "live"\nmodel_provider = "changed"\nnative_profile = "changed"\nmodel_instructions_file = "changed-instructions.md"\nmodel_verbosity = "changed"\nmodel_context_window = 999000\nmodel_auto_compact_token_limit = 888000\n[worker_runtime.windows]\nsandbox = "changed"\n[worker_runtime.environment]\nSYNTHETIC_GATEWAY_KEY = "changed"\nSYNTHETIC_HEADER_VALUE = "changed"\n[worker_runtime.analytics]\nenabled = false\n[worker_runtime.responses_api_metadata]\ncustom_tag = "changed"\n',+ '[worker_runtime.features]\nshell_tool = true\nunified_exec = true\nview_image = true\n[worker_runtime]\nopenai_base_url = "https://changed-snapshot.example.test/v1"\nweb_search = "live"\nmodel_provider = "changed"\nnative_profile = "changed"\nmodel_instructions_file = "changed-instructions.md"\nmodel_verbosity = "changed"\nmodel_context_window = 999000\nmodel_auto_compact_token_limit = 888000\n[worker_runtime.shell_environment_policy]\ninherit = "all"\n[worker_runtime.shell_environment_policy.set]\nSYNTHETIC_SHELL_MARKER = "changed"\n[worker_runtime.windows]\nsandbox = "changed"\n[worker_runtime.environment]\nSYNTHETIC_GATEWAY_KEY = "changed"\nSYNTHETIC_HEADER_VALUE = "changed"\n[worker_runtime.analytics]\nenabled = false\n[worker_runtime.responses_api_metadata]\ncustom_tag = "changed"\n',),]),),@@ -2940,13 +3076,15 @@ const profileIndex = process.argv.indexOf('--profile');const profileContents = profileIndex === -1 ? undefined : readFileSync(join(process.env.CODEX_HOME, process.argv[profileIndex + 1] + '.config.toml'), 'utf8');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;-const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'LD_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]]));+const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'LD_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]]));+const toolProbe = stdin.includes('CAPTURE_SYNTHETIC_RG') ? spawnSync('rg', ['--version'], { encoding: 'utf8' }) : undefined;+if (toolProbe && toolProbe.status !== 0) throw toolProbe.error ?? new Error(toolProbe.stderr);const pythonProbe = stdin.includes('CAPTURE_SYNTHETIC_PYTHON') ? spawnSync(process.env.PYTHON, ['-I', '-c', 'import json,os,sys; print(json.dumps([sys.prefix,os.environ.get("LD_LIBRARY_PATH")]))'], { encoding: 'utf8' }) : undefined;if (pythonProbe && pythonProbe.status !== 0) throw new Error(pythonProbe.stderr || String(pythonProbe.error));const pythonRuntime = pythonProbe ? JSON.parse(pythonProbe.stdout) : undefined;const knowledgePath = stdin.includes('synthetic worker configuration fixture') ? process.env.CODEX_SECURITY_KNOWLEDGE_BASE : undefined;const knowledgeDocuments = knowledgePath === undefined ? undefined : Object.fromEntries(readdirSync(knowledgePath).map(name => [name, readFileSync(join(knowledgePath, name), 'utf8')]));-writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, codexHome: process.env.CODEX_HOME, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(stdin.includes('COMPLETE_THEN_HANG') ? { pid: process.pid } : {}), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));+writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, codexHome: process.env.CODEX_HOME, cacheDirectory: process.env.XDG_CACHE_HOME, gitEnvironment: Object.fromEntries(['PATH', 'CODEX_SECURITY_GIT', 'GIT_SSH_COMMAND', 'GIT_CONFIG_GLOBAL'].map(name => [name, process.env[name]])), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, deepConfigPath: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, python: process.env.PYTHON, bundledTool: toolProbe?.stdout.trim(), pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(profileContents === undefined ? {} : { profileContents }), ...(stdin.includes('COMPLETE_THEN_HANG') ? { pid: process.pid } : {}), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => { if (!stdin.includes('IGNORE_TERMINATION')) 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_stdio_lifecycle.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.tsindex 313a95dd8..8ab8fbaed 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts@@ -14,6 +14,7 @@ import {readFile,realpath,rm,+ symlink,writeFile,} from "node:fs/promises";import path from "node:path";@@ -57,7 +58,7 @@ async function testDeepScanStdioLifecycle() {"fake-codex-signal-checkpoint-control.txt",);const fakeCodexPath = path.join(fixtureRoot, "fake-codex.mjs");- const pythonWrapperPath = path.join(fixtureRoot, "python-wrapper.mjs");+ const pythonWrapperPath = path.join(fixtureRoot, "python-wrapper ");const cancelFailureControlPath = path.join(fixtureRoot,"fail-next-cancel-scan",@@ -126,7 +127,8 @@ profile = "selected"model_reasoning_summary = "none"`,);- await writePythonWrapper(pythonWrapperPath);+ await writePythonWrapper(`${pythonWrapperPath}.mjs`);+ await symlink(`${pythonWrapperPath}.mjs`, pythonWrapperPath);await buildServer(serverBundlePath, { target: "node20" });const environment = {@@ -140,6 +142,7 @@ model_reasoning_summary = "none"CODEX_SECURITY_SCAN_ROOT: path.join(fixtureRoot, "scans"),CODEX_SECURITY_STATE_DIR: stateDir,PYTHON: pythonWrapperPath,+ CODEX_SECURITY_PYTHON_COMMAND: pythonWrapperPath,REAL_PYTHON: process.env.PYTHON?.trim() || "python3",FAKE_WORKBENCH_CANCEL_FAILURE_CONTROL: cancelFailureControlPath,FAKE_WORKBENCH_CANCEL_LOG: cancelLogPath,diff --git a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.tsindex 8384b770c..ffa0b9b47 100644--- a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts+++ b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts@@ -84,6 +84,7 @@ assert.deepEqual("AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","PYTHON","PYTHONUTF8",+ "CODEX_SECURITY_PYTHON_COMMAND","CODEX_SECURITY_GIT","CODEX_SECURITY_KNOWLEDGE_BASE","CODEX_SECURITY_CONFIG_PATH",diff --git a/plugins/codex-security/mcp-app/tests/test_python_command.ts b/plugins/codex-security/mcp-app/tests/test_python_command.tsindex c0bbead90..b0ddc0fc2 100644--- a/plugins/codex-security/mcp-app/tests/test_python_command.ts+++ b/plugins/codex-security/mcp-app/tests/test_python_command.ts@@ -1,5 +1,12 @@import assert from "node:assert/strict";-import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import {+ chmod,+ mkdir,+ mkdtemp,+ rm,+ symlink,+ writeFile,+} from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import {@@ -131,6 +138,8 @@ assert.equal(overrideProbeCount, 0);const executableFixtureRoot = await mkdtemp(path.join(tmpdir(), "codex-security-python-command-"),);+const previousPython = process.env.PYTHON;+const previousResolvedPython = process.env.CODEX_SECURITY_PYTHON_COMMAND;try {const directoryCandidate = path.join(executableFixtureRoot, "directory");const fileCandidate = path.join(executableFixtureRoot, "python3");@@ -140,6 +149,19 @@ try {await isUsablePythonExecutable(directoryCandidate, "linux"),false,);+ const resolvedPython =+ process.platform === "win32" ? process.execPath : `${fileCandidate} `;+ if (process.platform !== "win32")+ await symlink(process.execPath, resolvedPython);+ process.env.PYTHON = ` ${fileCandidate} `;+ process.env.CODEX_SECURITY_PYTHON_COMMAND = resolvedPython;+ assert.equal(await resolvePythonCommand(), resolvedPython);+ assert.equal(+ await resolvePythonCommand({ configuredPython: " /custom/python " }),+ "/custom/python",+ );+ delete process.env.CODEX_SECURITY_PYTHON_COMMAND;+ assert.equal(await resolvePythonCommand(), fileCandidate);if (process.platform !== "win32") {assert.equal(await isUsablePythonExecutable(fileCandidate, "linux"), false);await chmod(fileCandidate, 0o755);@@ -148,6 +170,11 @@ try {}assert.equal(await isUsablePythonExecutable(fileCandidate, "win32"), true);} finally {+ if (previousPython === undefined) delete process.env.PYTHON;+ else process.env.PYTHON = previousPython;+ if (previousResolvedPython === undefined)+ delete process.env.CODEX_SECURITY_PYTHON_COMMAND;+ else process.env.CODEX_SECURITY_PYTHON_COMMAND = previousResolvedPython;await rm(executableFixtureRoot, { force: true, recursive: true });}diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex a7ec0414b..e13affa1c 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -4778,9 +4778,11 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {}return result;};- const result = executionConfig(config);- // Keep effective execution settings even when preflight filters the profile name.const resolved = resolveCodexProfile(config);+ const result = executionConfig(+ safeProfileName(config["profile"]) ? config : resolved,+ );+ // Keep effective execution settings even when preflight filters the profile name.for (const key of ["model_reasoning_summary", "service_tier"]) {const value = resolved[key];if (safeString(value)) result[key] = value;@@ -4949,6 +4951,7 @@ function selectedWorkerRuntimeConfig("model_context_window","model_instructions_file","model_verbosity",+ "shell_environment_policy","web_search","windows",]diff --git a/sdk/typescript/src/artifact-export.ts b/sdk/typescript/src/artifact-export.tsindex cb4b828b2..fb0b97919 100644--- a/sdk/typescript/src/artifact-export.ts+++ b/sdk/typescript/src/artifact-export.ts@@ -451,6 +451,7 @@ export function exportEnvironment("TEMP","TMPDIR","PYTHON",+ "XDG_CACHE_HOME","LANG","LC_ALL","LC_CTYPE",diff --git a/sdk/typescript/src/codex-sdk-environment.ts b/sdk/typescript/src/codex-sdk-environment.tsindex 75d0dc778..d57316a7b 100644--- a/sdk/typescript/src/codex-sdk-environment.ts+++ b/sdk/typescript/src/codex-sdk-environment.ts@@ -1,4 +1,4 @@-import { statSync } from "node:fs";+import { realpathSync, statSync } from "node:fs";import { delimiter, dirname, join } from "node:path";export function bundledCodexSdkEnvironment(@@ -6,8 +6,12 @@ export function bundledCodexSdkEnvironment(environment: Record<string, string>,): Record<string, string> {// An SDK executable override disables its bundled-tool PATH setup.- const toolsDirectory = join(dirname(dirname(command)), "codex-path");+ let toolsDirectory: string;try {+ toolsDirectory = join(+ dirname(realpathSync.native(dirname(command))),+ "codex-path",+ );if (!statSync(toolsDirectory).isDirectory()) return environment;} catch {return environment;diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 776bfaac1..9987621d6 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -36,6 +36,7 @@ import {basename,dirname,extname,+ isAbsolute,join,relative,resolve,@@ -2791,12 +2792,21 @@ export function resolveCodexCommand(): CodexCommand {const configured = environmentValue(environment, "CODEX_CLI_PATH");const expanded =- configured === undefined ? undefined : expandHome(configured, environment);+ configured === undefined+ ? undefined+ : expandExecutableHome(configured, environment);if (expanded &&(process.platform !== "win32" || /\.(?:exe|com)$/iu.test(expanded))) {- return { command: resolve(expanded) };+ return {+ command:+ process.platform === "win32"+ ? resolve(expanded)+ : isAbsolute(expanded)+ ? expanded+ : `${process.cwd()}${sep}${expanded}`,+ };}const platform = process.platform === "android" ? "linux" : process.platform;@@ -3248,6 +3258,7 @@ export function pluginExecutionEnvironment(return {...pythonUtf8Environment(environment),PYTHON: python,+ CODEX_SECURITY_PYTHON_COMMAND: python,CODEX_CLI_PATH: resolveCodexCommand(environment).command,};}@@ -3558,7 +3569,7 @@ async function usablePython(): Promise<string | null> {const command = await resolveTrustedExecutable(isPythonPathCandidate(candidate)- ? expandHome(candidate, environment)+ ? expandExecutableHome(candidate, environment): candidate,environment,protectedRoot,@@ -3614,6 +3625,17 @@ export function sameFile(left: string, right: string): Promise<boolean> {);}+function expandExecutableHome(+ value: string,+ environment: ProcessEnvironment,+): string {+ const path = value.startsWith("~\\") ? value.replaceAll("\\", "/") : value;+ // Expand only the home prefix; joining the suffix would collapse symlink/.. paths.+ return path.startsWith("~/")+ ? `${expandHome("~", environment)}${sep}${path.slice(2)}`+ : expandHome(path, environment);+}+export function expandHome(value: string,environment: ProcessEnvironment = process.env,diff --git a/sdk/typescript/src/trusted-executable.ts b/sdk/typescript/src/trusted-executable.tsindex b517b0734..8850515fa 100644--- a/sdk/typescript/src/trusted-executable.ts+++ b/sdk/typescript/src/trusted-executable.ts@@ -92,7 +92,10 @@ export async function inspectTrustedExecutable(const candidates = pathLike? extensions.map((extension) => ({entry: null,- path: resolve(`${candidate}${extension.suffix}`),+ path:+ process.platform === "win32"+ ? resolve(`${candidate}${extension.suffix}`)+ : candidate,runnable: extension.runnable,})): entries.flatMap((entry) =>diff --git a/sdk/typescript/tests-ts/api-provider-isolation.test.ts b/sdk/typescript/tests-ts/api-provider-isolation.test.tsindex 778e2c1d3..61823a72e 100644--- a/sdk/typescript/tests-ts/api-provider-isolation.test.ts+++ b/sdk/typescript/tests-ts/api-provider-isolation.test.ts@@ -232,6 +232,10 @@ test.each([unified_exec: false,view_image: index === 0,};+ const shellPolicy = {+ inherit: "none",+ set: { SYNTHETIC_WORKER_VALUE: `shell-value-${index}` },+ };const providerEnvironment = {SYNTHETIC_CUSTOM_API_KEY: ` synthetic-key-${index} `,SYNTHETIC_CUSTOM_HEADER: ` synthetic-header-${index} `,@@ -244,6 +248,8 @@ test.each([codexOverrides: {model_provider: "openrouter",web_search: selection === "root" ? webSearch : "live",+ shell_environment_policy:+ selection === "root" ? shellPolicy : { inherit: "all" },features: selection === "root" ? featureOverrides : {},...(selection === "profile only"? {}@@ -271,6 +277,7 @@ test.each([selected: {features: featureOverrides,web_search: webSearch,+ shell_environment_policy: shellPolicy,...(selection === "null profile"? {model_provider: null,@@ -338,6 +345,7 @@ test.each([);expect(preflight).not.toContain("synthetic-key-");expect(preflight).not.toContain("synthetic-header-");+ expect(preflight).not.toContain("shell-value-");const workerSnapshotPath =environment["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!;const workerSnapshot = parseToml(@@ -345,10 +353,14 @@ test.each([);expect(workerSnapshot["worker_runtime"]).toMatchObject({environment: providerEnvironment,+ shell_environment_policy: shellPolicy,features: featureOverrides,web_search: webSearch,});expect(options.config!["web_search"]).toBe(webSearch);+ expect(options.config!["shell_environment_policy"]).toEqual(+ shellPolicy,+ );expect(options.config!["features"]).toMatchObject(featureOverrides,);@@ -374,6 +386,9 @@ test.each([featureOverrides,);expect(settings.config["web_search"]).toBe(webSearch);+ expect(settings.config["shell_environment_policy"]).toEqual(+ shellPolicy,+ );expect(settings.config["model_provider"]).toBe("openrouter");expect(settings.nativeProfile).toBeDefined();expect(settings.nativeProfile).toBe(options.nativeProfile);@@ -721,7 +736,7 @@ const legacyScanCases: Array<],),[- "deep with a filtered profile and readable snapshot",+ "deep with a resolved profile and readable snapshot","deep",{profile: "selected.profile",@@ -730,8 +745,6 @@ const legacyScanCases: Array<{capability: true,inherited: "synthetic.system",- reads: true,- rejects: true,},],];diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 0b6f410e1..636fb9a59 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -1837,6 +1837,8 @@ describe("CodexSecurity orchestration", () => {windows: { sandbox: "elevated" },profiles: {"cloud.production": {+ model: "synthetic-profile-model",+ model_reasoning_effort: "high",model_reasoning_summary: "concise",service_tier: "fast",model_instructions_file: "profile-instructions.md",@@ -1861,6 +1863,11 @@ describe("CodexSecurity orchestration", () => {};const clients = await Promise.all(scenarios.map(async ([overrides, expected, expectedTier], index) => {+ const expectedModel = {+ model:+ index === 3 ? "synthetic-profile-model" : "openai.gpt-5.6-luna",+ model_reasoning_effort: index === 3 ? "high" : "xhigh",+ };const scanDir = join(root, `scan-${index}`);await mkdir(scanDir, { mode: 0o700 });const instructionsFile =@@ -1892,6 +1899,7 @@ describe("CodexSecurity orchestration", () => {id: null,async runStreamed() {expect(threadOptions.workingDirectory).toBe(scanDir);+ expect(options.config).toMatchObject(expectedModel);if (++started === scenarios.length) allStarted.resolve();await allStarted.promise;const mcpEnvironment = Object.fromEntries(@@ -1966,8 +1974,8 @@ describe("CodexSecurity orchestration", () => {await readFile(configPath!, "utf8"),) as JsonObject;expect(resolveCodexProfile(config)).toMatchObject({+ ...expectedModel,model_reasoning_summary: expected,- model_reasoning_effort: "xhigh",model_provider: "amazon-bedrock",});expect(config["service_tier"]).toBe(expectedTier);@@ -6741,6 +6749,7 @@ describe("CodexSecurity orchestration", () => {const bundledTools = join(dirname(dirname(executable)), "codex-path");const inheritedTools = join(root, "operator-tools");await mkdir(bundledTools, { recursive: true });+ await mkdir(dirname(executable));await mkdir(inheritedTools);const originalPlatform = Object.getOwnPropertyDescriptor(process,diff --git a/sdk/typescript/tests-ts/artifact-export.test.ts b/sdk/typescript/tests-ts/artifact-export.test.tsindex 0d8be39ba..554cad104 100644--- a/sdk/typescript/tests-ts/artifact-export.test.ts+++ b/sdk/typescript/tests-ts/artifact-export.test.ts@@ -14,7 +14,7 @@ import {writeFile,} from "node:fs/promises";import { tmpdir } from "node:os";-import { basename, join } from "node:path";+import { basename, dirname, join } from "node:path";import { PassThrough } from "node:stream";import { describe, expect, spyOn, test } from "bun:test";import { exportArtifact } from "../src/index.js";@@ -37,6 +37,60 @@ const caseInsensitiveVolume = await stat(join(caseProbe, "REPORTS")).then(await rm(caseProbe, { recursive: true, force: true });describe("offline artifact export", () => {+ test("exports with Python from the selected managed-runtime cache", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-export-cache-"));+ const environment = {+ XDG_CACHE_HOME: join(root, "cache"),+ HOME: root,+ USERPROFILE: root,+ PATH: "",+ PYTHON: undefined,+ };+ const previous = Object.keys(environment).map(+ (key) => [key, process.env[key]] as const,+ );+ try {+ const dependencies = join(+ environment.XDG_CACHE_HOME,+ "codex-runtimes",+ "codex-primary-runtime",+ "dependencies",+ );+ await mkdir(dependencies, { recursive: true });+ await symlink(+ process.platform === "win32"+ ? dirname(PYTHON)+ : dirname(dirname(PYTHON)),+ join(dependencies, "python"),+ "junction",+ );+ await writeFile(+ join(root, "THREAT_MODEL.md"),+ "# Synthetic saved model\n",+ );+ Object.assign(process.env, environment);+ delete process.env["PYTHON"];+ const result = await runArtifactHelper(+ [+ "--scan-dir",+ root,+ "--export-artifact",+ "threat-model",+ "--export-format",+ "md",+ ],+ { pluginRoot: PLUGIN_ROOT },+ );+ expect(result.stdout).toBe("# Synthetic saved model\n");+ } finally {+ for (const [key, value] of previous) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ await rm(root, { recursive: true, force: true });+ }+ });+test.each([0, 1])("preserves split UTF-8 diagnostics at exit %i",async (exitCode) => {diff --git a/sdk/typescript/tests-ts/cli-export.test.ts b/sdk/typescript/tests-ts/cli-export.test.tsindex 05877fbd7..1c9d815e0 100644--- a/sdk/typescript/tests-ts/cli-export.test.ts+++ b/sdk/typescript/tests-ts/cli-export.test.ts@@ -54,6 +54,10 @@ describe("CLI", () => {exportEnvironment({Path: "C:\\Python;C:\\Windows\\System32",PYTHON: "/managed/python",+ XDG_CACHE_HOME: "/managed/cache",+ LD_LIBRARY_PATH: "/managed/libraries",+ DYLD_LIBRARY_PATH: "/managed/dylibs",+ DYLD_FALLBACK_LIBRARY_PATH: "/managed/fallback-libraries",TMPDIR: "/tmp",OPENAI_API_KEY: "openai-secret",CODEX_API_KEY: "codex-secret",@@ -63,6 +67,7 @@ describe("CLI", () => {).toEqual({Path: "C:\\Python;C:\\Windows\\System32",PYTHON: "/managed/python",+ XDG_CACHE_HOME: "/managed/cache",PYTHONUTF8: "1",TMPDIR: "/tmp",});diff --git a/sdk/typescript/tests-ts/provider-profile.test.ts b/sdk/typescript/tests-ts/provider-profile.test.tsindex c1aa902a1..8129d36cd 100644--- a/sdk/typescript/tests-ts/provider-profile.test.ts+++ b/sdk/typescript/tests-ts/provider-profile.test.ts@@ -1,13 +1,14 @@import { existsSync } from "node:fs";import {chmod,+ copyFile,mkdir,readFile,readdir,stat,writeFile,} from "node:fs/promises";-import { join } from "node:path";+import { join, sep } from "node:path";import { pathToFileURL } from "node:url";import { afterEach, expect, test } from "bun:test";import type { CodexOptions } from "@openai/codex-sdk";@@ -287,6 +288,69 @@ test("native profile turns omit optional null fields and retain array errors", a);});+test("native profile launches retain bundled tools through executable path aliases", async () => {+ const root = await temporaryDirectory();+ const bin = join(root, "vendor", "bin");+ const tools = join(root, "vendor", "codex-path");+ const executable = process.platform === "win32" ? "codex.exe" : "codex";+ const tool = process.platform === "win32" ? "rg.exe" : "rg";+ await mkdir(bin, { recursive: true });+ await mkdir(tools);+ const node = Bun.which("node")!;+ await copyFile(node, join(bin, executable));+ await copyFile(node, join(tools, tool));+ const script = join(root, "profile tools.mjs");+ await writeFile(+ script,+ `import { spawnSync } from "node:child_process";+import { basename } from "node:path";+if (basename(process.execPath).startsWith("rg")) {+ console.log("synthetic bundled search");+ process.exit(0);+}+for await (const chunk of process.stdin) {}+const result = spawnSync("rg", [], { encoding: "utf8" });+if (result.error || result.status !== 0) throw result.error ?? new Error(result.stderr);+console.log(JSON.stringify({ type: "thread.started", thread_id: "synthetic-thread" }));+console.log(JSON.stringify({ type: "item.completed", item: {+ type: "agent_message", id: "answer", text: JSON.stringify({+ path: process.env.PATH, configured: process.env.CODEX_CLI_PATH,+ search: result.stdout.trim(), resumed: process.argv.includes("resume"),+ }),+} }));+console.log(JSON.stringify({ type: "turn.completed", usage: { input_tokens: 1, output_tokens: 1 } }));+process.exit(0);`,+ );+ const configured = `${bin}${sep}.${sep}${executable}`;+ const environment = {+ ...(process.env["SystemRoot"] === undefined+ ? {}+ : { SystemRoot: process.env["SystemRoot"] }),+ PATH: "",+ CODEX_HOME: root,+ CODEX_CLI_PATH: configured,+ NODE_OPTIONS: `--import=${pathToFileURL(script).href}`,+ };+ const original = { ...environment };+ const client = await createProfileCodex(+ { env: environment },+ "synthetic-profile",+ );+ for (const resumed of [false, true]) {+ const thread = resumed+ ? client.resumeThread("synthetic-thread")+ : client.startThread();+ const result = await thread.run("synthetic prompt");+ expect(JSON.parse(result.finalResponse)).toEqual({+ path: tools,+ configured,+ search: "synthetic bundled search",+ resumed,+ });+ }+ expect(environment).toEqual(original);+});+test("private profiles retain providers for native required and inherited selection", async () => {const home = await temporaryDirectory();const definitions = {diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex 12e824ae1..c9e34415e 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -3,6 +3,7 @@ import { scanRegistrationArguments } from "./support/workbench-command.js";import { createApiTestFixtures } from "./support/temporary-directories.js";import { parseJsonLines, jsonLines } from "./support/json.js";import { execFile, spawnSync } from "node:child_process";+import { Codex } from "@openai/codex-sdk";import * as childProcess from "node:child_process";import { EventEmitter, once } from "node:events";import { existsSync, renameSync, symlinkSync } from "node:fs";@@ -2798,6 +2799,64 @@ ${directNode ? "}" : ""});});+ testPosix(+ "launches the configured executable through symlink parent components",+ async () => {+ const root = await temporaryDirectory();+ const release = join(root, "release with spaces");+ const childDirectory = join(root, "worker");+ await mkdir(join(release, "child"), { recursive: true });+ await mkdir(childDirectory);+ await symlink(join(release, "child"), join(root, "linked"), "dir");+ const executable = join(release, "codex");+ const script = (id: string) =>+ `#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' '${JSON.stringify({ type: "thread.started", thread_id: id })}' '${JSON.stringify({ type: "turn.completed", usage: { input_tokens: 1, cached_input_tokens: 0, output_tokens: 1 } })}'\n`;+ await writeFile(executable, script("intended"), { mode: 0o755 });+ for (const siblingPresent of [true, false]) {+ if (siblingPresent)+ await writeFile(join(root, "codex"), script("wrong executable"), {+ mode: 0o755,+ });+ else await rm(join(root, "codex"));+ for (const configured of [+ executable,+ `${root}/linked/../codex`,+ `${relative(process.cwd(), root)}/linked/../codex`,+ "~/linked/../codex",+ "~\\linked\\..\\codex",+ ]) {+ const environment = {+ PATH: process.env["PATH"],+ HOME: root,+ CODEX_CLI_PATH: configured,+ };+ const command = resolveCodexCommand(environment);+ const codex = new Codex({+ codexPathOverride: command.command,+ env: { PATH: process.env["PATH"] ?? "" },+ });+ const thread = codex.startThread({+ workingDirectory: childDirectory,+ skipGitRepoCheck: true,+ });+ await thread.run("Synthetic executable selection");+ expect(thread.id).toBe("intended");+ const worker = spawnSync(+ pluginExecutionEnvironment("/synthetic/python", environment)[+ "CODEX_CLI_PATH"+ ]!,+ [],+ { cwd: childDirectory, input: "synthetic", encoding: "utf8" },+ );+ expect(worker.status, worker.stderr).toBe(0);+ expect(JSON.parse(worker.stdout.split("\n")[0]!).thread_id).toBe(+ "intended",+ );+ }+ }+ },+ );+test("uses an explicit Codex executable override", () => {const executable = process.platform === "win32" ? "codex.exe" : "codex";const configured = join(tmpdir(), "custom codex", executable);@@ -2808,9 +2867,6 @@ ${directNode ? "}" : ""}expect(resolveCodexCommand({ CODEX_CLI_PATH: " " })).toEqual(resolveCodexCommand({}),);- expect(- resolveCodexCommand({ CODEX_CLI_PATH: `./bin/${executable}` }),- ).toEqual({ command: join(process.cwd(), "bin", executable) });expect(resolveCodexCommand({ CODEX_CLI_PATH: `~/bin/${executable}` }),).toEqual({@@ -2980,6 +3036,9 @@ ${directNode ? "}" : ""}resolveCodexCommand().command,);expect(workerEnvironment["PYTHONUTF8"]).toBe("1");+ expect(workerEnvironment["CODEX_SECURITY_PYTHON_COMMAND"]).toBe(+ process.execPath,+ );const globalCodex = spawnSync("codex", ["--version"], {encoding: "utf8",env: workerEnvironment,@@ -3005,12 +3064,14 @@ ${directNode ? "}" : ""}expect(pluginExecutionEnvironment("/managed/python", {CODEX_CLI_PATH: ` ${configured} `,+ CODEX_SECURITY_PYTHON_COMMAND: "stale-ambient-python",PATH: "",}),).toEqual({CODEX_CLI_PATH: configured,PATH: "",PYTHON: "/managed/python",+ CODEX_SECURITY_PYTHON_COMMAND: "/managed/python",PYTHONUTF8: "1",});expect(@@ -6450,6 +6511,7 @@ describe("runtime directories and plugin Python boundary", () => {expect(pluginExecutionEnvironment(managed, { TEST: "1" })).toEqual({TEST: "1",PYTHON: managed,+ CODEX_SECURITY_PYTHON_COMMAND: managed,PYTHONUTF8: "1",CODEX_CLI_PATH: resolveCodexCommand().command,});diff --git a/sdk/typescript/tests-ts/scan-recipe.test.ts b/sdk/typescript/tests-ts/scan-recipe.test.tsindex 4caf3191a..41ff9c2fe 100644--- a/sdk/typescript/tests-ts/scan-recipe.test.ts+++ b/sdk/typescript/tests-ts/scan-recipe.test.ts@@ -5,18 +5,30 @@ import { join } from "node:path";import { afterEach, expect, test } from "bun:test";import { main } from "../src/cli.js";import { runWorkbench } from "../src/runtime.js";+import { resolveCodexProfile } from "../src/config.js";import { dependencies } from "./cli-fixtures.js";import { TestClient } from "./support/api-client.js";import { preparedRuntime } from "./support/api-events.js";import { createApiTestFixtures } from "./support/temporary-directories.js";-import { throwing } from "./support/errors.js";const { temporaryDirectory, cleanup } = createApiTestFixtures();afterEach(cleanup);-test.each(["standard", "deep"])(- "%s scans save large post-scan prompts before starting Codex",- async (mode) => {+test.each(+ ["standard", "deep"].flatMap((mode) =>+ ["review", "review.v2", "review mode", "分析"].map(+ (profile) => [mode, profile] as const,+ ),+ ),+)(+ "%s scans save prompts and replay the selected %s profile",+ async (mode, profile) => {+ const selected = {+ model: "synthetic-selected-model",+ model_reasoning_effort: "high",+ model_provider: "amazon-bedrock",+ features: { goals: false },+ };const root = await temporaryDirectory();const repository = join(root, "repository");const codexHome = join(root, "state", "codex-home");@@ -38,6 +50,8 @@ test.each(["standard", "deep"])(CODEX_HOME: codexHome,CODEX_SECURITY_STATE_DIR: join(root, "state"),OPENAI_API_KEY: "synthetic-launch-key",+ AWS_BEARER_TOKEN_BEDROCK: "synthetic-bedrock-key",+ AWS_REGION: "us-east-2",};const command = workbenchCommand(python, () => environment);const { stderr, runCli } = createCliTest(main);@@ -58,13 +72,31 @@ test.each(["standard", "deep"])(...dependencies({ environment, currentDirectory: root }),runWorkbench: command,createSecurity: (config) =>- new TestClient(config, {- environment,- prepareRuntime: async () => preparedRuntime(codexHome),- resolvePluginPython: async () => python,- runWorkbench,- createCodex: throwing("Synthetic stop after registration"),- }),+ new TestClient(+ {+ ...config,+ codexOverrides: {+ model: "synthetic-root-model",+ model_reasoning_effort: "low",+ model_provider: "openai",+ profile,+ profiles: { [profile]: selected },+ },+ },+ {+ environment,+ prepareRuntime: async () => ({+ ...preparedRuntime(codexHome),+ deepScanConfigPath: join(root, "deep.toml"),+ }),+ resolvePluginPython: async () => python,+ runWorkbench,+ createCodex: ({ config }) => {+ expect(config).toMatchObject(selected);+ throw new Error("Synthetic stop after registration");+ },+ },+ ),},);expect(code).toBe(2);@@ -82,5 +114,20 @@ test.each(["standard", "deep"])(expect(saved["recipe"]).toMatchObject({ mode, postScanPrompt });expect(JSON.stringify(saved)).not.toContain(promptFile);expect(JSON.stringify(saved)).not.toContain("synthetic-launch-key");+ expect(JSON.stringify(saved)).not.toContain("synthetic-bedrock-key");+ expect(+ await runCli(["scans", "rerun", scans[0]!.scanId, "--json"], {+ ...dependencies({+ environment,+ currentDirectory: root,+ onConfig: ({ codexOverrides }) => {+ expect(resolveCodexProfile(codexOverrides!)).toMatchObject(+ selected,+ );+ },+ }),+ runWorkbench: command,+ }),+ ).toBe(0);},);diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.tsindex 85e6dea44..b033d52df 100644--- a/sdk/typescript/tests-ts/scan-resume.test.ts+++ b/sdk/typescript/tests-ts/scan-resume.test.ts@@ -18,7 +18,8 @@ import { join } from "node:path";import { afterEach, expect, test } from "bun:test";import { parse as parseToml } from "smol-toml";import { main } from "../src/cli.js";-import type { ScanOptions } from "../src/api.js";+import { scanPreflightCodexConfig, type ScanOptions } from "../src/api.js";+import type { JsonObject } from "../src/config.js";import { runWorkbench } from "../src/runtime.js";import { readKnowledgeBaseSnapshot } from "../src/knowledge-base.js";import { workflowDigest } from "../src/finding-workflow.js";@@ -43,7 +44,7 @@ async function interruptedScan(| "auth"| "knowledgeBasePaths"| "cyberAccessProgram"- > = {},+ > & { config?: JsonObject } = {},resolvedDeep = false,modelProvider?: string,) {@@ -912,7 +913,24 @@ test.each([] as const)("resume restores saved launch settings with %s auth (bulk: %p)",async (auth, bulk) => {+ const profile =+ auth === "chatgpt"+ ? "review.v2"+ : auth === "api-key"+ ? "review mode"+ : "分析";+ const selected = {+ model: `synthetic-${auth ?? "auto"}-model`,+ model_reasoning_effort: "high",+ features: { goals: false },+ };const settings = {+ config: scanPreflightCodexConfig({+ model: "synthetic-root-model",+ model_reasoning_effort: "low",+ profile,+ profiles: { [profile]: selected },+ }),auth,cyberAccessProgram: "daybreak_blue" as const,safetyIdentifier:@@ -938,6 +956,7 @@ test.each([? ["bulk-scan", f.input, "--output-dir", f.root, "--recover", "--json"]: ["scans", "resume", f.scanId, "--json"],resumeDependencies(f, (options) => {+ expect(options.config).toMatchObject(selected);expect(options.env?.["CODEX_SAFETY_IDENTIFIER"]).toBe(settings.safetyIdentifier,);diff --git a/sdk/typescript/tests-ts/trusted-executable.test.ts b/sdk/typescript/tests-ts/trusted-executable.test.tsindex d06f154a4..e31f70623 100644--- a/sdk/typescript/tests-ts/trusted-executable.test.ts+++ b/sdk/typescript/tests-ts/trusted-executable.test.ts@@ -1,12 +1,13 @@import { spawnSync } from "node:child_process";import { chmod, mkdir, realpath, symlink, writeFile } from "node:fs/promises";import { basename, delimiter, dirname, join, relative } from "node:path";-import { fileURLToPath } from "node:url";+import { fileURLToPath, pathToFileURL } from "node:url";import { afterEach, describe, expect, test } from "bun:test";import {inspectTrustedExecutable,resolveTrustedExecutable,} from "../src/trusted-executable.js";+import { PYTHON } from "./support/security-policy.js";import { createApiTestFixtures } from "./support/temporary-directories.js";const { temporaryDirectory, cleanup } = createApiTestFixtures(@@ -226,6 +227,102 @@ describe("trusted executable resolution", () => {},);+ test.skipIf(process.platform === "win32")(+ "Node preserves explicit Python launcher identity through parent traversal",+ async () => {+ const root = await temporaryDirectory();+ const trusted = join(root, "trusted tools");+ const lexical = join(root, "lexical");+ const repository = join(root, "repository");+ const marker = join(root, "selected.txt");+ await Promise.all([+ mkdir(join(trusted, "child"), { recursive: true }),+ mkdir(lexical),+ mkdir(repository),+ ]);+ await symlink(join(trusted, "child"), join(lexical, "linked"), "dir");+ const quote = (value: string) => `'${value.replaceAll("'", `'"'"'`)}'`;+ for (const [directory, identity] of [+ [trusted, "intended"],+ [lexical, "wrong executable"],+ ]) {+ await writeFile(+ join(directory!, "python"),+ `#!/bin/sh\nprintf '%s' ${quote(identity!)} > ${quote(marker)}\nexec ${quote(Bun.which(PYTHON) ?? PYTHON)} "$@"\n`,+ { mode: 0o755 },+ );+ }+ const candidate = `${lexical}/linked/../python`;+ const runtimePath = join(root, "runtime.mjs");+ const build = spawnSync(+ process.execPath,+ [+ "build",+ fileURLToPath(new URL("../src/runtime.ts", import.meta.url)),+ "--target=node",+ "--format=esm",+ "--outfile",+ runtimePath,+ ],+ { encoding: "utf8" },+ );+ expect(build.status, build.stderr).toBe(0);+ const result = spawnSync(+ "node",+ [+ "--experimental-strip-types",+ "--input-type=module",+ "-e",+ `+ import { readFile, rm, chmod } from "node:fs/promises";+ import { spawnSync } from "node:child_process";+ import assert from "node:assert/strict";+ const { resolveTrustedExecutable } = await import(process.argv[1]);+ const { resolvePluginPython } = await import(process.argv[3]);+ const [candidates, repository, trusted, sibling, marker] = JSON.parse(process.argv[2]);+ for (const candidate of candidates) {+ const resolved = await resolveTrustedExecutable(candidate, { PATH: "" }, repository);+ assert.ok(resolved);+ const child = spawnSync(resolved.executable, ["-I", "-c", "import sys; assert sys.version_info >= (3, 10); print('real-python-ok')"], { env: resolved.environment, encoding: "utf8" });+ assert.equal(child.status, 0, child.stderr);+ assert.equal(child.stdout.trim(), "real-python-ok");+ assert.equal(await readFile(marker, "utf8"), "intended");+ assert.equal(resolved.executable, trusted + "/python");+ for (const candidate of ["~/linked/../python", "~\\\\linked\\\\..\\\\python"]) for (const source of ["configuredPath", "PYTHON"]) {+ const selected = await resolvePluginPython({+ environment: { HOME: sibling.slice(0, -"/python".length), PATH: "", ...(source === "PYTHON" ? { PYTHON: candidate } : {}) },+ ...(source === "configuredPath" ? { configuredPath: candidate } : {}),+ protectedRoot: repository,+ });+ assert.equal(selected, trusted + "/python");+ assert.equal(await readFile(marker, "utf8"), "intended");+ }+ await rm(sibling, { force: true });+ }+ assert.equal(await resolveTrustedExecutable(candidates[0], { PATH: "" }, trusted), null);+ await chmod(trusted + "/python", 0o600);+ assert.equal(await resolveTrustedExecutable(candidates[0], { PATH: "" }, repository), null);+ `,+ new URL("../src/trusted-executable.ts", import.meta.url).href,+ JSON.stringify([+ [+ candidate,+ relative(process.cwd(), lexical) + "/linked/../python",+ candidate,+ ],+ repository,+ trusted,+ join(lexical, "python"),+ marker,+ ]),+ pathToFileURL(runtimePath).href,+ ],+ { encoding: "utf8" },+ );+ expect(result.status, result.stderr).toBe(0);+ },+ );+test("selects runnable Windows executables ahead of extensionless and batch files", async () => {const root = await temporaryDirectory();const repository = join(root, "repository");