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(windows): stage the bundled plugin for scan sandbox reads (#2494)
Michael D'Angelo7b6c058dc55a
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.tsindex e5acb8fb9..07df96f20 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts@@ -180,6 +180,8 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {}childEnv[name] = value;}+ if (parentSandbox.pluginReadRoot !== undefined)+ childEnv.CODEX_SECURITY_PLUGIN_ROOT = parentSandbox.pluginReadRoot;if (deepConfigFile !== undefined) {const config = this.modelSettings.deepScanConfig!;// The saved run owns these limits, including after a coordinator restart.@@ -605,10 +607,11 @@ function workerPermissionProfile(const literalDenies = sandbox.literalFilesystemDenies ?? [];const filesystem = new Map<string, string | Record<string, string>>([[":root", "read"],- ...[...sandbox.filesystemDenies, ...literalDenies].map(- (key): [string, string] => [key, "deny"],- ),]);+ if (sandbox.pluginReadRoot !== undefined)+ filesystem.set(sandbox.pluginReadRoot, { ".": "read" });+ for (const path of [...sandbox.filesystemDenies, ...literalDenies])+ filesystem.set(path, "deny");const pointDenies = literalDenies.filter((path) => /[*?[\]]/u.test(path));// Bubblewrap cannot mount a second mask inside a directory it already hid.if (diff --git a/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts b/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.tsindex 46bf5fc9f..21e30a2c7 100644--- a/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts+++ b/plugins/codex-security/mcp-app/src/deep-scan/parent-sandbox.ts@@ -1,5 +1,5 @@import { asRecord as record, isNonEmptyString } from "../record.js";-import { isAbsolute } from "node:path";+import { isAbsolute, relative, toNamespacedPath } from "node:path";import { isDeepStrictEqual } from "node:util";import { DeepScanNonRetryableError } from "./errors.js";@@ -8,18 +8,22 @@ export const CODEX_SANDBOX_STATE_META_CAPABILITY = "codex/sandbox-state-meta";export type DeepWorkerParentSandbox = {/*** Validated glob keys copied into the worker's stricter root-read- * profile. Grants are intentionally not transported because Deep Scan- * workers never inherit parent write access.+ * profile. Workers never inherit parent write access.*/readonly filesystemDenies: readonly string[];/** Preserve literal paths separately from glob patterns. */readonly literalFilesystemDenies?: readonly string[];+ /** Windows needs the parent's named read root for the selected plugin. */+ readonly pluginReadRoot?: string;readonly globScanMaxDepth?: number;};/** Resolve the effective host policy, never a model-supplied scan argument. */export function resolveDeepWorkerParentSandbox(extra: unknown,+ pluginRoot = process.platform === "win32"+ ? process.env.CODEX_SECURITY_PLUGIN_ROOT+ : undefined,): DeepWorkerParentSandbox {const state = trustedSandboxState(extra);@@ -52,6 +56,7 @@ export function resolveDeepWorkerParentSandbox(let hasRootRead = false;const filesystemDenies: string[] = [];const literalFilesystemDenies: string[] = [];+ let pluginReadRoot: string | undefined;for (const value of filesystem.entries) {const entry = record(value);if (!entry || !isKnownFilesystemAccess(entry.access)) {@@ -98,6 +103,14 @@ export function resolveDeepWorkerParentSandbox();}literalFilesystemDenies.push(path.path);+ } else if (+ entry.access === "read" &&+ pluginRoot !== undefined &&+ isAbsolute(path.path) &&+ relative(toNamespacedPath(path.path), toNamespacedPath(pluginRoot)) ===+ ""+ ) {+ pluginReadRoot = path.path;}} else if (path.type === "glob_pattern") {if (!isNonEmptyString(path.pattern)) {@@ -136,6 +149,7 @@ export function resolveDeepWorkerParentSandbox(return {filesystemDenies,+ ...(pluginReadRoot === undefined ? {} : { pluginReadRoot }),...(literalFilesystemDenies.length ? { literalFilesystemDenies } : {}),...(globScanMaxDepth !== undefined ? { globScanMaxDepth } : {}),};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 d164fef4e..ee1e5351e 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@@ -1646,7 +1646,12 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,`scan-${index}`,);const receiptRoot = path.parse(workerUsageDirectory).root;+ const pluginReadRoot =+ index === 0+ ? path.join(fixture.root, `plugin-${index}`)+ : undefined;const parentSandbox = {+ pluginReadRoot,filesystemDenies: [...trustedParentSandboxWithDenials.filesystemDenies,...(nestedReceipts ? [] : [workerUsageDirectory]),@@ -1715,6 +1720,9 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,...deniedWorkerPermissionProfile,filesystem: {...deniedWorkerPermissionProfile.filesystem,+ ...(pluginReadRoot === undefined+ ? {}+ : { [pluginReadRoot]: { ".": "read" } }),[deepPath]: { ".": "deny" },[codexHome]: { ".": "deny" },...(!nestedReceipts || process.platform !== "linux"@@ -2157,7 +2165,8 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,);assert.equal(workerLaunch.environment!.CODEX_SECURITY_PLUGIN_ROOT,- path.join(fixture.root, "ambient-plugin"),+ workerConfigurations[index].parentSandbox.pluginReadRoot ??+ path.join(fixture.root, "ambient-plugin"),);assert.equal(workerLaunch.environment!.CODEX_SECURITY_CONFIG_PATH,diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_parent_sandbox.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_parent_sandbox.tsindex 2af8faaec..59fa601b4 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_parent_sandbox.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_parent_sandbox.ts@@ -17,6 +17,26 @@ const pinnedReadOnly = {network: "restricted",};+const stagedPlugin = path.resolve("bundled plugin [fixture]");+assert.deepEqual(+ resolveDeepWorkerParentSandbox(+ restricted([+ rootRead,+ { path: { type: "path", path: stagedPlugin }, access: "read" },+ {+ path: { type: "path", path: path.dirname(stagedPlugin) },+ access: "write",+ },+ {+ path: { type: "path", path: path.resolve("other-plugin") },+ access: "read",+ },+ ]),+ stagedPlugin,+ ),+ { filesystemDenies: [], pluginReadRoot: stagedPlugin },+);+assert.equal(CODEX_SANDBOX_STATE_META_CAPABILITY, "codex/sandbox-state-meta");assert.deepEqual(resolveDeepWorkerParentSandbox(extra(pinnedReadOnly)), {filesystemDenies: [],diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex d4f7b6336..3caf02628 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -262,6 +262,7 @@ import {codexSecurityHasStoredFileCredentials,codexSecurityStateDirectory,codexExecutableReadPaths,+ copyPluginTree,createIsolatedHome,logoutCredentialHome,executablePathForSpawn,@@ -2187,6 +2188,7 @@ export class CodexSecurity {let notifiedLimit: number | undefined;let scanDir = "";let targetPathsFile: string | null = null;+ let stagedPluginRoot: string | undefined;let knowledgeBase: PreparedKnowledgeBase | null = null;let costTracker: ScanCostTracker | null = null;let scanProgressTracker: ScanProgressTracker | null = null;@@ -2464,8 +2466,9 @@ export class CodexSecurity {}checkOpen();- const shellPluginRoot = runtime.plugin.pluginRoot;- const canonicalShellPluginRoot = await realpath(shellPluginRoot);+ const canonicalShellPluginRoot = await realpath(+ runtime.plugin.pluginRoot,+ );const pluginRelativeToHome = relative(runtimeHome,canonicalShellPluginRoot,@@ -2480,6 +2483,24 @@ export class CodexSecurity {`Shell-visible plugin root must be outside CODEX_HOME: ${canonicalShellPluginRoot}`,);}+ // Windows grants directory reads to its sandbox account through inheritable+ // ACLs. Keep those grants on a disposable copy of the SDK's shipped plugin.+ if (+ process.platform === "win32" &&+ this.config.pluginPath === undefined &&+ runtime.bootstrapWorkspace !== undefined &&+ this.#dependencies.hostedScan === undefined+ ) {+ stagedPluginRoot = await mkdtemp(+ join(runtime.bootstrapWorkspace, "bundled-plugin-"),+ );+ await copyPluginTree(+ canonicalShellPluginRoot,+ stagedPluginRoot,+ signal,+ );+ }+ const shellPluginRoot = stagedPluginRoot ?? runtime.plugin.pluginRoot;const skillName = skillNameFor(normalized, mode);// Native no-turn resume retains saved permissions; exec refreshes them.// Keep the parent for its ChatGPT advisory and configured Node launcher.@@ -3330,7 +3351,7 @@ export class CodexSecurity {const { codex, environment, codexOptions } =await this.#createSessionCodex(session,- { command: "scan", mode },+ { command: "scan", mode, pluginReadRoot: stagedPluginRoot },runtimePaths,options.auth,git,@@ -3469,6 +3490,8 @@ export class CodexSecurity {codexOptions,preflightCommand:await this.#providerPreflightCommand(effectiveConfig),+ // Host imports must use the stable install URL. The engine receives+ // the scan's shell-visible plugin through codexOptions.env.pluginRoot: runtime.plugin.pluginRoot,repository: repo,scanDir,@@ -4141,6 +4164,9 @@ export class CodexSecurity {for (const cleanup of await Promise.allSettled([knowledgeBase?.cleanup(),removeTargetPathsFile(targetPathsFile),+ stagedPluginRoot === undefined+ ? undefined+ : cleanupSdkDirectory(stagedPluginRoot),savedProviderProfile?.cleanup(),])) {if (cleanup.status === "rejected") {@@ -4480,7 +4506,15 @@ export class CodexSecurity {async #createSessionCodex(session: PreparedSession,- { command, mode }: { command: string; mode?: ScanMode },+ {+ command,+ mode,+ pluginReadRoot,+ }: {+ command: string;+ mode?: ScanMode;+ pluginReadRoot?: string;+ },runtimePaths: Record<string, string>,auth: ScanAuthMode = "auto",git?: InspectedExecutable,@@ -4641,13 +4675,20 @@ export class CodexSecurity {}const sdkCodexConfig = structuredCodexConfig(config ?? sessionConfig);// This snapshot outlives a Deep Scan when the client reuses its runtime.- if (runtime.deepScanConfigPath !== undefined) {+ if (+ runtime.deepScanConfigPath !== undefined ||+ pluginReadRoot !== undefined+ ) {configOverrides = [`permissions.${SCAN_PERMISSION_PROFILE}.filesystem=${inlineToml({":root": "read",":workspace_roots": "write",+ ...(pluginReadRoot === undefined+ ? {}+ : { [pluginReadRoot]: { ".": "read" } }),[runtimeHome]: { ".": "deny" },- ...(runtime.deepScanConfigDirectory === undefined+ ...(runtime.deepScanConfigPath !== undefined &&+ runtime.deepScanConfigDirectory === undefined? { [runtime.deepScanConfigPath]: { ".": "deny" } }: {}),})}`,diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 08339ffe8..5b4a8b2f8 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -3697,7 +3697,7 @@ async function validatePluginRoot(root: string): Promise<string> {return await realpath(root);}-async function copyPluginTree(+export async function copyPluginTree(source: string,destination: string,signal?: AbortSignal,diff --git a/sdk/typescript/tests-ts/api-direct-deep-scan.test.ts b/sdk/typescript/tests-ts/api-direct-deep-scan.test.tsindex 8778aa026..05b3895ac 100644--- a/sdk/typescript/tests-ts/api-direct-deep-scan.test.ts+++ b/sdk/typescript/tests-ts/api-direct-deep-scan.test.ts@@ -3,9 +3,10 @@ import { hash } from "node:crypto";import { execFile } from "node:child_process";import { promisify } from "node:util";import { fileURLToPath } from "node:url";-import { delimiter, join } from "node:path";+import { delimiter, dirname, join } from "node:path";import { afterEach, expect, mock, test } from "bun:test";-import { copyCompletedScan } from "./plugin-root.js";+import { parse as parseToml } from "smol-toml";+import { copyCompletedScan, PLUGIN_ROOT } from "./plugin-root.js";import { TestClient, mockWorkbench } from "./support/api-client.js";import {completedEvents,@@ -26,6 +27,8 @@ test.each([undefined, "Summarize the completed scan."])(const repository = join(root, "repository");const codexHome = join(root, "codex-home");const scanDir = join(root, "scan");+ const bootstrapWorkspace = join(root, "bootstrap");+ await mkdir(bootstrapWorkspace);await mkdir(repository);await mkdir(codexHome);await mkdir(scanDir, { mode: 0o700 });@@ -50,6 +53,10 @@ test.each([undefined, "Summarize the completed scan."])({ codexOverrides: { model: "gpt-5.6-sol" } },{...scanRuntimeDependencies(codexHome, scanDir),+ prepareRuntime: async () => ({+ ...preparedRuntime(codexHome),+ bootstrapWorkspace,+ }),canRunDirectDeepScan: () => true,environment: {CODEX_SECURITY_STATE_DIR: join(root, "state"),@@ -61,6 +68,27 @@ test.each([undefined, "Summarize the completed scan."])(}),runDeepScan: async function* (options) {expect(options.scanId).toBe("scan_example_001");+ expect(options.pluginRoot).toBe(PLUGIN_ROOT);+ const shellPlugin =+ options.codexOptions.env!["CODEX_SECURITY_PLUGIN_ROOT"]!;+ if (process.platform === "win32") {+ expect(dirname(shellPlugin)).toBe(bootstrapWorkspace);+ const skill = join("skills", "security-scan", "SKILL.md");+ expect(await readFile(join(shellPlugin, skill))).toEqual(+ await readFile(join(options.pluginRoot, skill)),+ );+ const override = options.codexOptions.configOverrides!.find(+ (entry) =>+ entry.startsWith("permissions.codex_security_scan.filesystem="),+ )!;+ expect(parseToml(override)).toMatchObject({+ permissions: {+ codex_security_scan: {+ filesystem: { [shellPlugin]: { ".": "read" } },+ },+ },+ });+ } else expect(shellPlugin).toBe(PLUGIN_ROOT);expect(options.codexOptions.env).toMatchObject({CODEX_SECURITY_SCAN_ID: options.scanId,CODEX_SECURITY_SCAN_DIR: scanDir,diff --git a/sdk/typescript/tests-ts/api-runtime-storage.test.ts b/sdk/typescript/tests-ts/api-runtime-storage.test.tsindex ec9be3090..2550fb983 100644--- a/sdk/typescript/tests-ts/api-runtime-storage.test.ts+++ b/sdk/typescript/tests-ts/api-runtime-storage.test.ts@@ -46,6 +46,7 @@ test.each(["ready", "denied", "canceled"])(const original = runtime.requirePrivateCredentialHome;let protectedDirectory: string | undefined;let workerFile: string | undefined;+ const stagedPlugins: string[] = [];let launched = false;let operation: "deep" | "standard" | "validation" = "deep";const controller = new AbortController();@@ -73,7 +74,6 @@ test.each(["ready", "denied", "canceled"])(});const client = new TestClient({- pluginPath: PLUGIN_ROOT,codexOverrides: {model_provider: "synthetic.provider",model_providers: {@@ -130,14 +130,22 @@ test.each(["ready", "denied", "canceled"])(value.startsWith("permissions.codex_security_scan.filesystem="),)!,)["permissions"] as Record<string, Record<string, unknown>>;- expect(- (- filesystem["codex_security_scan"]!["filesystem"] as Record<- string,- unknown- >- )[dirname(profileFile)],- ).toEqual({ ".": "deny" });+ const roots = filesystem["codex_security_scan"]![+ "filesystem"+ ] as Record<string, unknown>;+ expect(roots[dirname(profileFile)]).toEqual({ ".": "deny" });+ if (process.platform === "win32" && operation !== "validation") {+ const staged = options.env!["CODEX_SECURITY_PLUGIN_ROOT"]!;+ expect(dirname(staged)).toBe(protectedDirectory!);+ expect(roots[staged]).toEqual({ ".": "read" });+ expect(roots[protectedDirectory!]).toBeUndefined();+ expect(roots[await realpath(PLUGIN_ROOT)]).toBeUndefined();+ const skill = join("skills", "security-scan", "SKILL.md");+ expect(await readFile(join(staged, skill))).toEqual(+ await readFile(join(PLUGIN_ROOT, skill)),+ );+ stagedPlugins.push(staged);+ }if (process.platform !== "win32") {expect((await stat(profileFile)).mode & 0o777).toBe(0o600);expect((await stat(file)).mode & 0o777).toBe(0o600);@@ -173,6 +181,9 @@ test.each(["ready", "denied", "canceled"])(await expect(client.run(repository)).rejects.toThrow("synthetic scan reached",);+ expect(existsSync(protectedDirectory!)).toBe(true);+ for (const staged of stagedPlugins)+ expect(existsSync(staged)).toBe(false);operation = "validation";await expect(client.validate({diff --git a/sdk/typescript/tests-ts/direct-deep-scan.test.ts b/sdk/typescript/tests-ts/direct-deep-scan.test.tsindex cdd89077e..906d98cbf 100644--- a/sdk/typescript/tests-ts/direct-deep-scan.test.ts+++ b/sdk/typescript/tests-ts/direct-deep-scan.test.ts@@ -53,7 +53,7 @@ export async function prepareCliDeepScanSession(options) {await writeFile(join(pluginRoot, "mcp", "server.mjs"),`-import { writeFileSync } from 'node:fs';+import { readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';import { createInterface } from 'node:readline';const lines = createInterface({input: process.stdin});@@ -62,6 +62,8 @@ writeFileSync(process.env.SYNTHETIC_RECEIPT, JSON.stringify({request, ipc: !!process.send, argv: process.argv.slice(2), key: process.env.CODEX_API_KEY,execPath: process.execPath, bun: process.versions.bun,awsProfile: process.env.AWS_PROFILE, snapshot: process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,+ skill: process.env.CODEX_SECURITY_PLUGIN_ROOT === undefined ? undefined+ : readFileSync(join(process.env.CODEX_SECURITY_PLUGIN_ROOT, 'skills', 'security-scan', 'SKILL.md'), 'utf8'),}));if (request.diagnosticsVersion === 1 && process.env.SYNTHETIC_OLD_ENGINE !== '1') {process.send({ event: 'discovery_worker_replaced', scanId: request.scanId, reason: 'tool error' });@@ -92,12 +94,17 @@ test("isolates direct engine credentials and runtime snapshots across concurrentconst scanDir = join(root, name);const receipt = join(root, `${name}.json`);await mkdir(scanDir);+ const staged = join(root, `staged plugin ${name}`);+ const skills = join(staged, "skills", "security-scan");+ await mkdir(skills, { recursive: true });+ await writeFile(join(skills, "SKILL.md"), `synthetic skill ${name}`);const environment = {PATH: process.versions["bun"] ? process.env["PATH"]! : "",CODEX_HOME: join(root, "codex-home"),SYNTHETIC_RECEIPT: receipt,SYNTHETIC_THREAD_ID: `thread-${name}`,CODEX_SECURITY_SCAN_DIR: scanDir,+ CODEX_SECURITY_PLUGIN_ROOT: staged,CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: join(scanDir,"private-snapshot.toml",@@ -131,6 +138,7 @@ test("isolates direct engine credentials and runtime snapshots across concurrentassert.partialDeepStrictEqual(saved, {key: `synthetic-key-${name}`,awsProfile: `profile-${name}`,+ skill: `synthetic skill ${name}`,snapshot: environment.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,request: {scanId: `scan-${name}`,diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.tsindex d404a1bba..c1a873b50 100644--- a/sdk/typescript/tests-ts/scan-resume.test.ts+++ b/sdk/typescript/tests-ts/scan-resume.test.ts@@ -17,7 +17,7 @@ import {stat,writeFile,} from "node:fs/promises";-import { join } from "node:path";+import { dirname, join } from "node:path";import { afterEach, expect, spyOn, test } from "bun:test";import { parse as parseToml } from "smol-toml";import { main } from "../src/cli.js";@@ -395,6 +395,8 @@ test("CLI resumes through native execution with current permissions and preservesha256: hash("sha256", markdown),};const f = await interruptedScan("deep", false, { severityRubric });+ const bootstrapWorkspace = join(f.root, "resumed-bootstrap");+ await mkdir(bootstrapWorkspace);Object.assign(f.environment, {CODEX_SECURITY_ENABLE_REMOTE_SEVERITY_RUBRIC: "1",});@@ -458,6 +460,7 @@ test("CLI resumes through native execution with current permissions and preserveenvironment: f.environment,prepareRuntime: async () => ({...preparedRuntime(f.codexHome),+ bootstrapWorkspace,deepScanConfigDirectory: join(f.codexHome, "worker-config"),deepScanConfigPath: join(f.codexHome,@@ -500,6 +503,11 @@ test("CLI resumes through native execution with current permissions and preservepermissions.permissions.codex_security_scan.filesystem;expect(filesystem[f.codexHome]).toEqual({ ".": "deny" });expect(filesystem[originalHome]).toBeUndefined();+ if (process.platform === "win32") {+ const currentPlugin = options.env!["CODEX_SECURITY_PLUGIN_ROOT"]!;+ expect(dirname(currentPlugin)).toBe(bootstrapWorkspace);+ expect(filesystem[currentPlugin]).toEqual({ ".": "read" });+ }expect(options.env).toMatchObject({CODEX_SECURITY_SCAN_ID: f.scanId,CODEX_SECURITY_SCAN_DIR: f.scanDir,