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
[codex-security] Resolve bundled Codex for nested deep scans (#288)
Kyle Brown07585bf86e56
diff --git a/sdk/typescript/scripts/smoke-package.mjs b/sdk/typescript/scripts/smoke-package.mjsindex 3e0d3702b..0cd6b1160 100644--- a/sdk/typescript/scripts/smoke-package.mjs+++ b/sdk/typescript/scripts/smoke-package.mjs@@ -1,6 +1,7 @@import assert from "node:assert/strict";import { spawnSync } from "node:child_process";import {+ mkdir,mkdtemp,readFile,readdir,@@ -9,8 +10,16 @@ import {writeFile,} from "node:fs/promises";import { tmpdir } from "node:os";-import { basename, dirname, join, relative, resolve, sep } from "node:path";-import { fileURLToPath } from "node:url";+import {+ basename,+ dirname,+ isAbsolute,+ join,+ relative,+ resolve,+ sep,+} from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";import { packageSmokeTimeouts } from "./package-smoke-timeouts.mjs";const PACKAGE_SMOKE_TIMEOUT_MS = packageSmokeTimeouts().commandTimeoutMs;@@ -59,10 +68,11 @@ async function resolveArchive() {function run(command,args,- { cwd, capture = false, windowsVerbatimArguments = false } = {},+ { cwd, env, capture = false, windowsVerbatimArguments = false } = {},) {const result = spawnSync(command, args, {cwd,+ env,encoding: "utf8",stdio: capture ? "pipe" : "inherit",timeout: PACKAGE_SMOKE_TIMEOUT_MS,@@ -146,6 +156,115 @@ async function pluginFiles(directory) {return files.sort();}+async function smokeNestedDeepScanWorker(installedRoot, consumer) {+ const sdk = await import(+ pathToFileURL(join(installedRoot, "dist", "index.js")).href+ );+ const codexCommand = sdk.resolveCodexCommand();+ assert.equal(+ isAbsolute(codexCommand.command),+ true,+ "The bundled Codex executable must resolve to an absolute path.",+ );++ const workerHome = join(consumer, "nested-worker-home");+ await mkdir(workerHome, { recursive: true, mode: 0o700 });+ const parentEnvironment = sdk.pluginExecutionEnvironment(process.execPath, {+ PATH: "",+ HOME: workerHome,+ USERPROFILE: workerHome,+ CODEX_HOME: workerHome,+ ...(process.env.SystemRoot === undefined+ ? {}+ : { SystemRoot: process.env.SystemRoot }),+ ...(process.env.WINDIR === undefined ? {} : { WINDIR: process.env.WINDIR }),+ });+ const mcpConfiguration = JSON.parse(+ await readFile(join(installedRoot, "_bundled_plugin", ".mcp.json"), "utf8"),+ );+ const inherited = new Set([+ "PATH",+ "HOME",+ "USERPROFILE",+ "SystemRoot",+ "WINDIR",+ ...mcpConfiguration.mcpServers["codex-security"].env_vars,+ ]);+ const workerEnvironment = Object.fromEntries(+ Object.entries(parentEnvironment).filter(+ ([name, value]) => value !== undefined && inherited.has(name),+ ),+ );+ assert.equal(+ workerEnvironment.CODEX_CLI_PATH,+ codexCommand.command,+ "The installed plugin must propagate the bundled Codex path into nested workers.",+ );++ const globalCodex = spawnSync("codex", ["--version"], {+ cwd: consumer,+ encoding: "utf8",+ env: workerEnvironment,+ windowsHide: true,+ });+ assert.equal(+ globalCodex.error?.code,+ "ENOENT",+ "Nested-worker smoke must not depend on a globally installed codex executable.",+ );+ const codexVersion = run(codexCommand.command, ["--version"], {+ cwd: consumer,+ env: workerEnvironment,+ capture: true,+ });+ assert.match(codexVersion, /^codex-cli\s+\d/u);++ const workerSdkBridge = join(consumer, "nested-worker-sdk.mjs");+ await writeFile(+ workerSdkBridge,+ 'export { Codex } from "@openai/codex-sdk";\n',+ );+ const { Codex } = await import(pathToFileURL(workerSdkBridge).href);+ const controller = new AbortController();+ const timeout = setTimeout(+ () => controller.abort(new Error("The nested Codex worker did not start.")),+ 15_000,+ );+ let started = false;+ try {+ const codex = new Codex({+ codexPathOverride: workerEnvironment.CODEX_CLI_PATH,+ env: workerEnvironment,+ baseUrl: "http://127.0.0.1:1/v1",+ apiKey: "synthetic-codex-security-package-smoke",+ });+ const { events } = await codex+ .startThread({+ workingDirectory: workerHome,+ skipGitRepoCheck: true,+ sandboxMode: "read-only",+ })+ .runStreamed("Validate packaged nested worker startup.", {+ signal: controller.signal,+ });+ for await (const event of events) {+ if (event.type === "thread.started") {+ started = true;+ controller.abort();+ break;+ }+ }+ } finally {+ clearTimeout(timeout);+ controller.abort();+ }+ assert.equal(+ started,+ true,+ "The installed package must launch an actual nested Codex worker without codex on PATH.",+ );+}+const archive = await resolveArchive();assert.equal((await stat(archive)).isFile(),@@ -279,9 +398,16 @@ try {const help = runInstalledCli("--help");assert.match(help, /Usage: codex-security\b/u);+ await smokeNestedDeepScanWorker(installedRoot, consumer);+console.log(- `Validated installed ${packageManifest.name}@${packageManifest.version}: public import, CLI, and ${expectedPluginFiles.length} bundled plugin files.`,+ `Validated installed ${packageManifest.name}@${packageManifest.version}: public import, CLI, ${expectedPluginFiles.length} bundled plugin files, bundled Codex version, and a nested worker without global codex.`,);} finally {- await rm(consumer, { recursive: true, force: true });+ await rm(consumer, {+ recursive: true,+ force: true,+ maxRetries: 10,+ retryDelay: 100,+ });}diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex a530f8899..bf6c96e0e 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -2092,11 +2092,19 @@ async function codexSecurityPluginRegistration(export function resolveCodexCommand(): CodexCommand {const { packageName, targetTriple } = codexPlatformPackage();- const require = createRequire(import.meta.url);- const codexPackageJson = require.resolve("@openai/codex/package.json");- const packageJson = createRequire(codexPackageJson).resolve(- `${packageName}/package.json`,- );+ let packageJson: string;+ try {+ const require = createRequire(import.meta.url);+ const codexPackageJson = require.resolve("@openai/codex/package.json");+ packageJson = createRequire(codexPackageJson).resolve(+ `${packageName}/package.json`,+ );+ } catch (error) {+ throw new PluginBootstrapError(+ `The bundled Codex executable could not be resolved from ${packageName}. Reinstall @openai/codex with optional dependencies enabled, or set CODEX_CLI_PATH to an installed Codex executable.`,+ { cause: error },+ );+ }const command = join(dirname(packageJson),"vendor",@@ -2106,7 +2114,7 @@ export function resolveCodexCommand(): CodexCommand {);if (!existsSync(command)) {throw new PluginBootstrapError(- `The ${packageName} package does not contain the Codex executable for ${targetTriple}.`,+ `The ${packageName} package does not contain the Codex executable for ${targetTriple}. Reinstall @openai/codex with optional dependencies enabled, or set CODEX_CLI_PATH to an installed Codex executable.`,);}return { command, prefixArgs: [] };@@ -2405,7 +2413,12 @@ export function pluginExecutionEnvironment(python: string,environment: ProcessEnvironment = process.env,): ProcessEnvironment {- return { ...environment, PYTHON: python };+ return {+ ...environment,+ PYTHON: python,+ CODEX_CLI_PATH:+ environment["CODEX_CLI_PATH"]?.trim() || resolveCodexCommand().command,+ };}export async function cleanupSdkDirectory(path: string): Promise<void> {diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.tsindex cafe1f7ac..00f6e96ff 100644--- a/sdk/typescript/tests-ts/runtime.test.ts+++ b/sdk/typescript/tests-ts/runtime.test.ts@@ -1487,6 +1487,67 @@ describe("plugin runtime preparation", () => {);});+ test("launches the bundled Codex through the Deep Scan MCP environment without a global executable", async () => {+ const configuration = JSON.parse(+ await readFile(join(PLUGIN_ROOT, ".mcp.json"), "utf8"),+ ) as {+ mcpServers: Record<string, { env_vars: string[] }>;+ };+ const parentEnvironment = pluginExecutionEnvironment(process.execPath, {+ PATH: "",+ ...(process.env["SystemRoot"] === undefined+ ? {}+ : { SystemRoot: process.env["SystemRoot"] }),+ });+ const allowed = new Set(+ configuration.mcpServers["codex-security"]!.env_vars,+ );+ const workerEnvironment = Object.fromEntries(+ Object.entries(parentEnvironment).filter(+ ([name, value]) =>+ value !== undefined &&+ (name === "PATH" || name === "SystemRoot" || allowed.has(name)),+ ),+ ) as Record<string, string>;++ expect(workerEnvironment["CODEX_CLI_PATH"]).toBe(+ resolveCodexCommand().command,+ );+ const globalCodex = spawnSync("codex", ["--version"], {+ encoding: "utf8",+ env: workerEnvironment,+ });+ expect(globalCodex.error).toMatchObject({ code: "ENOENT" });++ const nestedCodex = spawnSync(+ workerEnvironment["CODEX_CLI_PATH"]!,+ ["--version"],+ { encoding: "utf8", env: workerEnvironment },+ );+ expect(nestedCodex.status).toBe(0);+ expect(nestedCodex.stdout).toMatch(/^codex-cli\s+\d/u);+ });++ test("preserves an explicit Codex executable override for nested workers", () => {+ const configured = join(tmpdir(), "custom codex", "codex");++ expect(+ pluginExecutionEnvironment("/managed/python", {+ CODEX_CLI_PATH: ` ${configured} `,+ PATH: "",+ }),+ ).toEqual({+ CODEX_CLI_PATH: configured,+ PATH: "",+ PYTHON: "/managed/python",+ });+ expect(+ pluginExecutionEnvironment("/managed/python", {+ CODEX_CLI_PATH: " ",+ })["CODEX_CLI_PATH"],+ ).toBe(resolveCodexCommand().command);+ });+test("selects the native Windows Codex executable package", () => {expect(codexPlatformPackage("win32", "x64")).toEqual({packageName: "@openai/codex-win32-x64",@@ -4000,6 +4061,7 @@ describe("runtime directories and plugin Python boundary", () => {expect(pluginExecutionEnvironment(managed, { TEST: "1" })).toEqual({TEST: "1",PYTHON: managed,+ CODEX_CLI_PATH: resolveCodexCommand().command,});await expect(resolvePluginPython({