Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(runtime): keep Windows bootstrap workspaces out of TEMP (#1803)

Michael D'Angeloc5c503ca1be4
diff --git a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts
index 66668d75a..1d1bacc8e 100644
--- a/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts
+++ b/plugins/codex-security/mcp-app/tests/support/fake-codex-source.ts
@@ -14,8 +14,9 @@ const preflightProfile = process.env.FAKE_CODEX_PREFLIGHT_PROFILE ? JSON.parse(p
const preflightAllowed = ${JSON.stringify(preflightAllowed)};
const accountResult = ${JSON.stringify(accountResult)};
const preflightMarkerPath = process.env.FAKE_CODEX_PREFLIGHT_MARKER ?? ${JSON.stringify(preflightMarkerPath)};
+const temporaryEnvironment = Object.fromEntries(['TEMP', 'TMP'].map(name => [name, process.env[name]]));
if (process.argv.includes('app-server')) {
- const preflight = { argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env.LD_LIBRARY_PATH, cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, 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]])), requests: [] };
+ const preflight = { argv: process.argv.slice(2), configPath: process.env.CODEX_SECURITY_CONFIG_PATH, stateDirectory: process.env.CODEX_SECURITY_STATE_DIR, temporaryEnvironment, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env.LD_LIBRARY_PATH, cwd: process.cwd(), codexHome: process.env.CODEX_HOME, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, providerHeader: process.env.SYNTHETIC_HEADER_VALUE, 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]])), requests: [] };
writeFileSync(preflightMarkerPath, JSON.stringify(preflight));
${jsonLineInputSource(` if (message.method === 'initialized') continue;
if (message.method === 'config/read' || message.method === 'permissionProfile/list') {
@@ -72,7 +73,7 @@ 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')]));
const deepConfig = process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH ? readFileSync(process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH, 'utf8') : undefined;
-writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, 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, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, 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 } : {}) }));
+writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ ...(scopeInput === undefined ? {} : { scopeInput }), argv: process.argv.slice(2), stdin, cwd: process.cwd(), knowledgePath, knowledgeDocuments, deepConfig, codexHome: process.env.CODEX_HOME, temporaryEnvironment, 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, mcpNodePath: process.env.CODEX_MCP_NODE_PATH, 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); }
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.ts
index 6e806112d..e81ada2b1 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
@@ -1399,6 +1399,8 @@ async function testWorkerRuntimeSettings() {
"LD_LIBRARY_PATH",
"DYLD_LIBRARY_PATH",
"DYLD_FALLBACK_LIBRARY_PATH",
+ "TEMP",
+ "TMP",
].map((name) => [name, process.env[name]] as const);
const originalSpawn = childProcess.spawn;
try {
@@ -1409,6 +1411,9 @@ async function testWorkerRuntimeSettings() {
delete process.env.SYNTHETIC_HEADER_VALUE;
delete process.env.CODEX_SQLITE_HOME;
for (const [configuration, expected] of cases) {
+ for (const [name, value] of saved) {
+ if (name === "TEMP" || name === "TMP") restoreEnv(name, value);
+ }
const fixture = await fakeCodexFixture(
deniedWorkerPermissionProfile,
true,
@@ -1471,6 +1476,15 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
const providerHeaders = settings.map((_, index) =>
index === 0 ? undefined : ` synthetic-header-${index}\t`,
);
+ const temporaryEnvironments = settings.map((_, index) => ({
+ TEMP: path.join(fixture.root, `temp-${index}`),
+ TMP: path.join(fixture.root, `tmp-${index}`),
+ }));
+ await Promise.all(
+ temporaryEnvironments.flatMap((environment) =>
+ Object.values(environment).map((directory) => mkdir(directory)),
+ ),
+ );
const workerConfigurations = Array.from(
{ length: settings.length },
(_, index) => {
@@ -1630,6 +1644,9 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
fixture.root,
`native-state-${index}`,
),
+ ...(index === 1
+ ? { TMP: temporaryEnvironments[index].TEMP }
+ : {}),
},
authentication:
index === 0
@@ -1876,6 +1893,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
executors.map((executor, index) => {
// Snapshot each scan environment independently.
process.env.CODEX_MCP_NODE_PATH = nodePaths[index];
+ Object.assign(process.env, temporaryEnvironments[index]);
process.env.CODEX_SECURITY_STATE_DIR = path.join(
fixture.root,
`state-${index}`,
@@ -2023,6 +2041,22 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
workerConfigurations[index].knowledgeDocuments,
);
assert.equal(invocation.codexHome, await realpath(codexHome));
+ assert.deepEqual(invocation.temporaryEnvironment, {
+ ...temporaryEnvironments[index],
+ ...(index === 1
+ ? { TMP: temporaryEnvironments[index].TEMP }
+ : {}),
+ });
+ for (const name of ["TEMP", "TMP"] as const) {
+ assert.equal(
+ process.env[name],
+ temporaryEnvironments.at(-1)![name],
+ );
+ }
+ assert.equal(
+ invocation.deepConfigPath,
+ workerConfigurations[index].workerConfigPath,
+ );
assert.equal(
invocation.runtimeEnvironment.CODEX_SECURITY_STATE_DIR,
path.join(fixture.root, `state-${index}`),
@@ -2281,6 +2315,18 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
selectedProvider,
"worker preflight must use the same scan environment",
);
+ const index = workerConfigurations.indexOf(selectedProvider);
+ assert.equal(preflight.codexHome, await realpath(codexHome));
+ assert.equal(
+ preflight.stateDirectory,
+ path.join(fixture.root, `state-${index}`),
+ );
+ assert.deepEqual(preflight.temporaryEnvironment, {
+ ...temporaryEnvironments[index],
+ ...(index === 1
+ ? { TMP: temporaryEnvironments[index].TEMP }
+ : {}),
+ });
assert.equal(
launch.environment!.CODEX_SECURITY_STATE_DIR,
path.join(
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 6c467292d..f37c9bbaa 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -905,9 +905,12 @@ Preserve existing state, then choose a private `CODEX_SECURITY_STATE_DIR` outsid
the rejected ancestor and the repository, with a full ancestor chain that passes
the same checks. If the volume root is rejected, another directory on that
volume cannot resolve it; use a separately provisioned volume with trusted
-ancestry. Temporary bootstrap homes also need trusted ancestry: set `TEMP` and
-`TMP` to a private directory on that volume before launching the CLI. Do not
-change the system volume's owner or ACL to make a scan run. If no suitable
+ancestry. On Windows, local runtime bootstrap directories are created beside
+`codex-home` in the state directory and removed when the SDK client closes.
+They use the same trusted ancestry checks, so sandbox write permissions on
+`TEMP` do not prevent runtime preparation. `TEMP`, `TMP`, and scan output
+locations are unchanged. Do not change the system volume's owner or ACL to
+make a scan run. If no suitable
location is available, this layout cannot provision credentials safely under
the current checks. Sign in again if needed; a new state directory has separate
scan history and does not migrate credentials or reports from the old state
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index f0f9c9ce0..e8868227c 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -4315,7 +4315,9 @@ export class CodexSecurity {
try {
throwIfAborted(signal);
bootstrapWorkspace = await createIsolatedHome(
- temporaryRoot,
+ // Windows sandboxes can grant replacement rights on TEMP. Keep private
+ // staging beside the validated home, outside it so ZIP plugins are readable.
+ process.platform === "win32" ? dirname(codexHome) : temporaryRoot,
validateLocation,
);
await requirePrivateCredentialHome(
diff --git a/sdk/typescript/tests-ts/api-runtime-storage.test.ts b/sdk/typescript/tests-ts/api-runtime-storage.test.ts
index 173f19fd7..6e3e8470c 100644
--- a/sdk/typescript/tests-ts/api-runtime-storage.test.ts
+++ b/sdk/typescript/tests-ts/api-runtime-storage.test.ts
@@ -1,8 +1,19 @@
import { codexFactory } from "./support/api-events.js";
-import { mkdir, readFile, readdir, stat } from "node:fs/promises";
+import {
+ lstat,
+ mkdir,
+ readFile,
+ readdir,
+ realpath,
+ stat,
+ writeFile,
+} from "node:fs/promises";
import { existsSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import * as os from "node:os";
import { basename, dirname, join } from "node:path";
import { afterEach, expect, spyOn, test } from "bun:test";
+import { strToU8, zipSync } from "fflate";
import * as runtime from "../src/runtime.js";
import { TestClient } from "./support/api-client.js";
import { parse as parseToml } from "smol-toml";
@@ -12,9 +23,21 @@ import { PLUGIN_ROOT } from "./plugin-root.js";
const { temporaryDirectory, cleanup } = createApiTestFixtures();
afterEach(cleanup);
-test.each([false, true])(
- "protects provider snapshots across runtime reuse (ACL failure: %j)",
- async (failAcl) => {
+function stubPluginInstall() {
+ return spyOn(runtime, "bootstrapPlugin").mockImplementation(
+ async (_home, pluginRoot) => ({
+ ...(await runtime.pluginMetadata(pluginRoot)),
+ pluginRoot,
+ installedRoot: pluginRoot,
+ marketplaceRoot: pluginRoot,
+ marketplaceName: "codex-security-sdk",
+ }),
+ );
+}
+
+test.each(["ready", "denied", "canceled"])(
+ "protects provider snapshots across runtime reuse (preparation: %s)",
+ async (preparation) => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
const scan = join(root, "scan");
@@ -25,6 +48,8 @@ test.each([false, true])(
let workerFile: string | undefined;
let launched = false;
let operation: "deep" | "standard" | "validation" = "deep";
+ const controller = new AbortController();
+ const install = stubPluginInstall();
const guard = spyOn(
runtime,
"requirePrivateCredentialHome",
@@ -36,7 +61,13 @@ test.each([false, true])(
secureWindowsHome: async (directory) => {
expect(await readdir(directory)).toEqual([]);
protectedDirectory = directory;
- if (failAcl) throw new Error("synthetic ACL denial");
+ expect(dirname(directory)).toBe(
+ process.platform === "win32"
+ ? join(root, "state")
+ : await realpath(os.tmpdir()),
+ );
+ if (preparation === "denied") throw new Error("synthetic ACL denial");
+ if (preparation === "canceled") controller.abort();
},
});
});
@@ -121,12 +152,23 @@ test.each([false, true])(
},
);
try {
- await expect(client.run(repository, { mode: "deep" })).rejects.toThrow(
- failAcl ? "synthetic ACL denial" : "synthetic scan reached",
+ await expect(
+ client.run(repository, {
+ mode: "deep",
+ signal: controller.signal,
+ }),
+ ).rejects.toThrow(
+ preparation === "denied"
+ ? "synthetic ACL denial"
+ : preparation === "canceled"
+ ? "interrupted during preparation"
+ : "synthetic scan reached",
);
expect(protectedDirectory).toBeDefined();
- expect(launched).toBe(!failAcl);
- if (!failAcl) {
+ expect(launched).toBe(preparation === "ready");
+ if (preparation !== "ready") {
+ expect(existsSync(protectedDirectory!)).toBe(false);
+ } else {
operation = "standard";
await expect(client.run(repository)).rejects.toThrow(
"synthetic scan reached",
@@ -142,6 +184,7 @@ test.each([false, true])(
}
} finally {
guard.mockRestore();
+ install.mockRestore();
await client.close();
}
expect(existsSync(protectedDirectory!)).toBe(false);
@@ -150,3 +193,181 @@ test.each([false, true])(
}
},
);
+
+test.each(["directory", "zip"])(
+ "isolates and reuses runtime workspaces outside sandbox-writable Windows TEMP (%s plugin)",
+ async (source) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const temporary = join(root, "temporary");
+ const state = join(root, "state");
+ await mkdir(repository);
+ await mkdir(temporary, { mode: 0o700 });
+ const pluginFiles = {
+ ".codex-plugin/plugin.json": strToU8(
+ JSON.stringify({ name: "codex-security", version: "1.2.3" }),
+ ),
+ "skills/security-scan/SKILL.md": strToU8("# Synthetic scan workflow\n"),
+ };
+ const pluginPath = join(root, source === "zip" ? "plugin.zip" : "plugin");
+ if (source === "zip") {
+ await writeFile(pluginPath, zipSync(pluginFiles));
+ } else {
+ for (const [name, contents] of Object.entries(pluginFiles)) {
+ await mkdir(dirname(join(pluginPath, name)), { recursive: true });
+ await writeFile(join(pluginPath, name), contents);
+ }
+ }
+ const snapshotAcl = () => {
+ const system = join(process.env["SystemRoot"]!, "System32");
+ const result = spawnSync(
+ join(system, "WindowsPowerShell", "v1.0", "powershell.exe"),
+ [
+ "-NoLogo",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "(Get-Acl -LiteralPath $env:CODEX_SECURITY_TEST_TEMP).Sddl",
+ ],
+ {
+ encoding: "utf8",
+ env: {
+ ...Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([name]) => name.toUpperCase() !== "PSMODULEPATH",
+ ),
+ ),
+ CODEX_SECURITY_TEST_TEMP: temporary,
+ PSModulePath: join(system, "WindowsPowerShell", "v1.0", "Modules"),
+ },
+ windowsHide: true,
+ },
+ );
+ expect(result.status, result.stderr).toBe(0);
+ return result.stdout.trim();
+ };
+ let temporaryAcl: string | undefined;
+ if (process.platform === "win32") {
+ const grant = spawnSync(
+ join(process.env["SystemRoot"]!, "System32", "icacls.exe"),
+ [temporary, "/grant", "*S-1-1-0:(OI)(CI)(M,DC)"],
+ { encoding: "utf8", windowsHide: true },
+ );
+ expect(grant.status, grant.stderr).toBe(0);
+ temporaryAcl = snapshotAcl();
+ const rejected = await runtime.createIsolatedHome(temporary);
+ await expect(
+ runtime.requirePrivateCredentialHome(await lstat(rejected), rejected),
+ ).rejects.toThrow("allows another identity to replace");
+ }
+ const processTemporary = {
+ TEMP: process.env["TEMP"],
+ TMP: process.env["TMP"],
+ };
+ const temporaryRoot = spyOn(os, "tmpdir").mockReturnValue(temporary);
+ const install = stubPluginInstall();
+ const workspaces = new Map<number, string>();
+ const clients: TestClient[] = [];
+ const createClient = (index: number, stateDirectory = state) => {
+ const client = new TestClient(
+ {
+ pluginPath,
+ codexOverrides: {
+ model_provider: "synthetic",
+ model_providers: {
+ synthetic: {
+ name: "Synthetic",
+ base_url: "https://provider.example.test/v1",
+ wire_api: "responses",
+ auth: { command: "synthetic-auth" },
+ },
+ },
+ },
+ },
+ {
+ environment: {
+ CODEX_HOME: join(root, "ambient"),
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ TEMP: temporary,
+ TMP: temporary,
+ },
+ resolvePluginPython: async () => "/managed/python",
+ repositoryRevision: async () => "deadbeef",
+ createCodex: (options) => {
+ const environment = options.env!;
+ expect(environment["TEMP"]).toBe(temporary);
+ expect(environment["TMP"]).toBe(temporary);
+ expect(environment["CODEX_HOME"]).toBe(
+ join(stateDirectory, "codex-home"),
+ );
+ expect(environment["CODEX_SECURITY_STATE_DIR"]).toBe(
+ stateDirectory,
+ );
+ const workspace = dirname(
+ environment["CODEX_SECURITY_CONFIG_PATH"]!,
+ );
+ expect(dirname(workspace)).toBe(
+ process.platform === "win32" ? stateDirectory : temporary,
+ );
+ const previous = workspaces.get(index);
+ if (previous !== undefined) expect(workspace).toBe(previous);
+ workspaces.set(index, workspace);
+ expect(environment["CODEX_SECURITY_PLUGIN_ROOT"]).toBe(
+ source === "zip"
+ ? join(workspace, "extracted-plugin")
+ : pluginPath,
+ );
+ const codex = codexFactory(async function () {
+ throw new Error("synthetic scan reached");
+ })();
+ return {
+ startThread: (threadOptions) => {
+ expect(threadOptions.workingDirectory).toBe(
+ join(root, `scan-${index}`),
+ );
+ return codex.startThread();
+ },
+ };
+ },
+ },
+ );
+ clients.push(client);
+ return client;
+ };
+ const run = (client: TestClient, index: number) =>
+ client.run(repository, { outputDir: join(root, `scan-${index}`) });
+ try {
+ const first = createClient(0);
+ const second = createClient(1);
+ await Promise.all([
+ expect(run(first, 0)).rejects.toThrow("synthetic scan reached"),
+ expect(run(second, 1)).rejects.toThrow("synthetic scan reached"),
+ ]);
+ expect(workspaces.size).toBe(2);
+ expect(workspaces.get(0)).not.toBe(workspaces.get(1));
+ await first.close();
+ expect(existsSync(workspaces.get(0)!)).toBe(false);
+ expect(existsSync(workspaces.get(1)!)).toBe(true);
+ await expect(run(second, 1)).rejects.toThrow("synthetic scan reached");
+ if (process.platform === "win32") {
+ const rejected = createClient(2, join(temporary, "untrusted-state"));
+ await expect(run(rejected, 2)).rejects.toThrow(
+ "allows another identity to replace",
+ );
+ expect(workspaces.has(2)).toBe(false);
+ expect(snapshotAcl()).toBe(temporaryAcl!);
+ }
+ expect({ TEMP: process.env["TEMP"], TMP: process.env["TMP"] }).toEqual(
+ processTemporary,
+ );
+ } finally {
+ temporaryRoot.mockRestore();
+ install.mockRestore();
+ await Promise.all(clients.map((client) => client.close()));
+ }
+ for (const workspace of workspaces.values()) {
+ expect(existsSync(workspace)).toBe(false);
+ }
+ },
+ 60_000,
+);