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): probe the Codex sandbox before starting a billed scan (#1084)
stanleys123371d2e24464
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 053fefeb6..384e5b3f0 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@@ -1124,6 +1124,7 @@ async function testWorkerRuntimeSettings() {"GIT_SSH_COMMAND","GIT_CONFIG_GLOBAL","CODEX_CLI_PATH",+ "CODEX_HOME","CODEX_SECURITY_CONFIG_PATH","CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH","OPENAI_API_KEY",@@ -1152,17 +1153,22 @@ async function testWorkerRuntimeSettings() {};Object.assign(process.env, gitEnvironment);const configPath = path.join(fixture.root, "active scan config.toml");+ const codexHome = path.join(fixture.root, "scan home");const promptPath = path.join(fixture.root, "prompt.md");+ await mkdir(codexHome);await writeFile(configPath, configuration);await writeFile(promptPath, "synthetic worker configuration fixture");process.env.CODEX_CLI_PATH = process.execPath;+ process.env.CODEX_HOME = codexHome;process.env.CODEX_SECURITY_CONFIG_PATH = configPath;process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH = path.join(fixture.root,"deep settings.toml",);- childProcess.spawn = (command, args, options) =>- originalSpawn(+ const launches = [];+ childProcess.spawn = (command, args, options) => {+ launches.push({ command, args, environment: options.env });+ return originalSpawn(command,command === process.execPath ||command === path.toNamespacedPath(process.execPath)@@ -1170,6 +1176,7 @@ async function testWorkerRuntimeSettings() {: args,options,);+ };syncBuiltinESMExports();const executor = new CodexSdkWorkerExecutor({model: "gpt-6-sol",@@ -1186,6 +1193,7 @@ async function testWorkerRuntimeSettings() {// A running coordinator retains its settings if the source file changes.for (const kind of ["discovery", "dedup"]) {for (const resumeThreadId of [undefined, "fixture-resumed-thread"]) {+ launches.length = 0;await executor.run({kind,promptPath,@@ -1203,6 +1211,37 @@ async function testWorkerRuntimeSettings() {},signal: new AbortController().signal,});+ const workerLaunches = launches.filter(+ ({ args }) => args[0] === "exec",+ );+ assert.equal(workerLaunches.length, 1);+ const workerLaunch = workerLaunches[0];+ assert.equal(+ workerLaunch.command,+ process.platform === "win32"+ ? path.toNamespacedPath(process.execPath)+ : process.execPath,+ );+ assert.equal(+ workerLaunch.environment.CODEX_CLI_PATH,+ process.execPath,+ );+ assert.equal(+ workerLaunch.environment.CODEX_HOME,+ await realpath(codexHome),+ );+ assert.equal(+ workerLaunch.environment.CODEX_SECURITY_CONFIG_PATH,+ configPath,+ );+ assert.equal(+ workerLaunch.environment.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,+ process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,+ );+ assert.equal(+ workerPermissionProfileOverride(workerLaunch.args),+ 'permissions.codex_security_deep_scan_worker={extends=":read-only",filesystem={":root"="read","/repo/.env"="deny","/repo/**/.secret"="deny","/repo/**/*.pem"="deny",glob_scan_max_depth=3},network={enabled=false}}',+ );const invocation = JSON.parse(await readFile(fixture.markerPath, "utf8"),);diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex e6177f78b..2d97f8a30 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -187,6 +187,7 @@ import {prepareScanArtifactRestorer,prepareOutputDir,preparePersistentOutputRoot,+ probeCodexSandbox,requireModelSafeOutputDir,requireOutputOutsideRepositories,requireOutputOutsideRepository,@@ -454,6 +455,7 @@ interface ClientDependencies {prepareScanArtifactRestorer?: typeof prepareScanArtifactRestorer;repositoryRevision?: typeof repositoryRevision;resolveCodexCommand?: () => CodexCommand;+ probeCodexSandbox?: typeof probeCodexSandbox;runWorkbench?: typeof runWorkbench;matchFindings?: typeof matchScanFindingsInternal;}@@ -3494,8 +3496,14 @@ export class CodexSecurity {await writeCodexConfig(join(codexHome, "config.toml"), codexConfig);const configPath = join(bootstrapWorkspace, "config-preflight.toml");throwIfAborted(signal);+ const codexCommand = this.#codexCommand();+ await (this.#dependencies.probeCodexSandbox ?? probeCodexSandbox)(+ codexCommand,+ { ...withoutCodexHome(processEnvironment), CODEX_HOME: codexHome },+ signal,+ );const plugin = await bootstrapPlugin(codexHome, pluginRoot, {- codexCommand: this.#codexCommand(),+ codexCommand,environment: withoutCodexHome(processEnvironment),signal,});diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.tsindex 2b59b192d..0c160db3a 100644--- a/sdk/typescript/src/errors.ts+++ b/sdk/typescript/src/errors.ts@@ -58,6 +58,7 @@ export class ConfigurationError extends CodexSecurityError {}export class AuthenticationRequiredError extends CodexSecurityError {}export class PluginBootstrapError extends CodexSecurityError {}export class PluginPythonUnavailableError extends PluginBootstrapError {}+export class SandboxUnavailableError extends CodexSecurityError {}export class InvalidTargetError extends CodexSecurityError {}export class OutputDirectoryError extends CodexSecurityError {}export class OutputDirectoryNotEmptyError extends OutputDirectoryError {diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 2460e6135..13a01255e 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -93,6 +93,7 @@ export {OutputInsideProtectedRootError,PluginBootstrapError,PluginPythonUnavailableError,+ SandboxUnavailableError,ScanCostLimitExceededError,ScanInterruptedError,} from "./errors.js";diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 1400f5396..f7850203a 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -57,6 +57,7 @@ import {PluginBootstrapError,PluginPythonUnavailableError,type ProtectedScanPathKind,+ SandboxUnavailableError,errorMessage,} from "./errors.js";import type { JsonObject } from "./config.js";@@ -87,6 +88,7 @@ const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;const MAX_PROCESS_ID = 2_147_483_647;const MAX_WINDOWS_CREDENTIAL_ACL_STDERR = 64 * 1024;+const SANDBOX_PROBE_TIMEOUT_MILLISECONDS = 10_000;const PLUGIN_HELPER_SECRET_ENVIRONMENT_VARIABLES = new Set(["OPENAI_API_KEY","CODEX_API_KEY",@@ -2777,6 +2779,39 @@ export async function runCodexCommand(return await completion;}+export async function probeCodexSandbox(+ command: CodexCommand,+ environment: ProcessEnvironment,+ signal?: AbortSignal,+): Promise<void> {+ // This preflight covers the Unix sandbox backends.+ if (process.platform === "win32") return;+ // Reuse the resolved Codex executable instead of looking up a probe on PATH.+ const args = ["sandbox", "--", command.command, "--version"];+ const timeout = AbortSignal.timeout(SANDBOX_PROBE_TIMEOUT_MILLISECONDS);+ let detail: string;+ try {+ const result = await runCodexCommand(+ command,+ args,+ environment,+ undefined,+ signal === undefined ? timeout : AbortSignal.any([signal, timeout]),+ );+ if (result.success) return;+ detail =+ result.stderr.trim() ||+ result.stdout.trim() ||+ `Codex exited with status ${result.exitCode}.`;+ } catch (error) {+ signal?.throwIfAborted();+ detail = processErrorDetail(error);+ }+ throw new SandboxUnavailableError(+ `Codex could not run a command in its sandbox; reproduce with '${command.command} ${args.join(" ")}'. On Linux this usually means unprivileged user namespaces are restricted (kernel.apparmor_restrict_unprivileged_userns=1 on Ubuntu 24.04 and later), which Bubblewrap needs; inside the container image, use the AppArmor profile and Compose override from the SDK README. Codex reported: ${detail}`,+ );+}+async function runPluginCommand(command: CodexCommand,args: readonly string[],diff --git a/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts b/sdk/typescript/tests-ts/api-attribution-concurrency.test.tsindex d523e4a36..8bcbeb9d6 100644--- a/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts+++ b/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts@@ -62,6 +62,7 @@ describe("delegated scan attribution", () => {OPENAI_API_KEY: `synthetic-${surface}-key`,},resolvePluginPython: async () => "/managed/python",+ probeCodexSandbox: async () => {},prepareOutputDir: async () => scanDirectory,repositoryRevision: async () => "deadbeef",runWorkbench: async (diff --git a/sdk/typescript/tests-ts/sandbox-probe.test.ts b/sdk/typescript/tests-ts/sandbox-probe.test.tsnew file mode 100644index 000000000..62877012a--- /dev/null+++ b/sdk/typescript/tests-ts/sandbox-probe.test.ts@@ -0,0 +1,191 @@+import {+ chmod,+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, test } from "bun:test";+import { SandboxUnavailableError } from "../src/index.js";+import { probeCodexSandbox } from "../src/runtime.js";+import { TestClient } from "./support/api-client.js";++const SANDBOX_DENIAL =+ "bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted";++const temporaryDirectories: string[] = [];++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((path) => rm(path, { recursive: true, force: true })),+ );+});++async function temporaryDirectory(): Promise<string> {+ const path = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-sandbox-")),+ );+ temporaryDirectories.push(path);+ return path;+}++async function syntheticPlugin(root: string): Promise<string> {+ const path = join(root, "plugin");+ await mkdir(join(path, ".codex-plugin"), { recursive: true });+ await writeFile(+ join(path, ".codex-plugin", "plugin.json"),+ JSON.stringify({ name: "codex-security", version: "1.2.3" }),+ );+ return path;+}++async function syntheticCodex(root: string, exitCode: number): Promise<string> {+ const command = join(root, "codex");+ await writeFile(+ command,+ [+ "#!/bin/sh",+ 'printf \'%s\\n\' "$@" >> "$0.args"',+ 'printf \'%s\\n\' "$PATH" "$CODEX_HOME" "$PROBE_SETTING" > "$0.environment"',+ 'if [ "$1" != sandbox ]; then exit 0; fi',+ `if [ ${exitCode} -ne 0 ]; then echo "${SANDBOX_DENIAL}" >&2; fi`,+ `exit ${exitCode}`,+ "",+ ].join("\n"),+ );+ await chmod(command, 0o700);+ return command;+}++describe("Codex sandbox probe", () => {+ test.skipIf(process.platform === "win32")(+ "reports what the sandbox said and how to reproduce it",+ async () => {+ const root = await temporaryDirectory();+ const command = await syntheticCodex(root, 1);+ const failure = await probeCodexSandbox({ command }, {}).then(+ () => null,+ (error: Error) => error,+ );+ expect(failure).toBeInstanceOf(SandboxUnavailableError);+ expect(failure?.message).toContain(SANDBOX_DENIAL);+ expect(failure?.message).toContain(+ `${command} sandbox -- ${command} --version`,+ );+ },+ );++ test.skipIf(process.platform === "win32")(+ "uses the resolved executable and preserves the scan environment",+ async () => {+ const root = await temporaryDirectory();+ const commandDirectory = join(root, "installed tools");+ await mkdir(commandDirectory);+ const command = await syntheticCodex(commandDirectory, 0);+ const environment = {+ PATH: join(root, "repository", "bin"),+ CODEX_HOME: join(root, "codex-home"),+ PROBE_SETTING: "scan-specific-setting",+ };+ await expect(+ probeCodexSandbox({ command }, environment),+ ).resolves.toBeUndefined();+ expect(await readFile(`${command}.args`, "utf8")).toBe(+ ["sandbox", "--", command, "--version", ""].join("\n"),+ );+ expect(await readFile(`${command}.environment`, "utf8")).toBe(+ [+ environment.PATH,+ environment.CODEX_HOME,+ environment.PROBE_SETTING,+ "",+ ].join("\n"),+ );+ },+ );++ test.skipIf(process.platform === "win32")(+ "preserves cancellation before the probe starts",+ async () => {+ const root = await temporaryDirectory();+ const reason = new Error("scan canceled");+ const signal = AbortSignal.abort(reason);+ await expect(+ probeCodexSandbox(+ { command: await syntheticCodex(root, 0) },+ {},+ signal,+ ),+ ).rejects.toBe(reason);+ },+ );++ test.skipIf(process.platform === "win32")(+ "reports an executable that cannot be started",+ async () => {+ const root = await temporaryDirectory();+ await expect(+ probeCodexSandbox({ command: join(root, "missing-codex") }, {}),+ ).rejects.toMatchObject({+ name: SandboxUnavailableError.name,+ message: expect.stringContaining("ENOENT"),+ });+ },+ );++ test.skipIf(process.platform !== "win32")(+ "does not probe on Windows",+ async () => {+ const root = await temporaryDirectory();+ await expect(+ probeCodexSandbox({ command: join(root, "missing-codex.exe") }, {}),+ ).resolves.toBeUndefined();+ },+ );++ test.skipIf(process.platform === "win32")(+ "stops a scan before it starts a billed Codex thread",+ async () => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const state = join(root, "state");+ const scanDir = join(root, "scan");+ await mkdir(repository, { mode: 0o700 });+ await mkdir(state, { mode: 0o700 });+ await mkdir(scanDir, { mode: 0o700 });+ await writeFile(join(repository, "app.py"), "print('synthetic')\n");+ const command = await syntheticCodex(root, 1);+ const client = new TestClient(+ { pluginPath: await syntheticPlugin(root) },+ {+ environment: {+ OPENAI_API_KEY: "synthetic-key",+ CODEX_SECURITY_STATE_DIR: state,+ },+ resolveCodexCommand: () => ({ command }),+ probeCodexSandbox,+ resolvePluginPython: async () => "/managed/python",+ prepareOutputDir: async () => scanDir,+ repositoryRevision: async () => "deadbeef",+ },+ );+ try {+ await expect(client.run(repository)).rejects.toMatchObject({+ name: SandboxUnavailableError.name,+ message: expect.stringContaining(SANDBOX_DENIAL),+ });+ expect(await readFile(`${command}.args`, "utf8")).toBe(+ ["sandbox", "--", command, "--version", ""].join("\n"),+ );+ } finally {+ await client.close();+ }+ },+ );+});diff --git a/sdk/typescript/tests-ts/support/api-client.ts b/sdk/typescript/tests-ts/support/api-client.tsindex 2195e73ae..e31f429ca 100644--- a/sdk/typescript/tests-ts/support/api-client.ts+++ b/sdk/typescript/tests-ts/support/api-client.ts@@ -68,6 +68,7 @@ export class TestClient extends CodexSecurity {throw new Error("Unexpected Codex invocation in test");},environment: {},+ probeCodexSandbox: async () => {},prepareScanArtifactRestorer: async () => ({restore: async () => {},}),