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

test: reuse SDK API runtime and repository fixtures (#1446)

mldangelo-oai47f9f850fb40
diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.ts
index e3b15c51a..1c845abae 100644
--- a/sdk/typescript/tests-ts/api-credentials.test.ts
+++ b/sdk/typescript/tests-ts/api-credentials.test.ts
@@ -139,35 +139,27 @@ describe("CodexSecurity orchestration", () => {
repositoryRevision: async () => "deadbeef",
createCodex: (options) => {
captured = options;
- return {
- startThread: () => ({
- id: null,
- async runStreamed() {
- if (!profile) {
- const preflightConfig = parseToml(
- await readFile(
- options.env!["CODEX_SECURITY_CONFIG_PATH"]!,
- "utf8",
- ),
- );
- expect(preflightConfig["model_provider"]).toBe(
- "synthetic.provider",
- );
- expect(preflightConfig["model_providers"]).toBeUndefined();
- if (process.platform !== "win32") {
- expect(
- (
- await stat(
- options.env!["CODEX_SECURITY_CONFIG_PATH"]!,
- )
- ).mode & 0o777,
- ).toBe(0o600);
- }
- }
- throw new Error("synthetic command-auth scan started");
- },
- }),
- };
+ return codexFactory(async function runStreamed() {
+ if (!profile) {
+ const preflightConfig = parseToml(
+ await readFile(
+ options.env!["CODEX_SECURITY_CONFIG_PATH"]!,
+ "utf8",
+ ),
+ );
+ expect(preflightConfig["model_provider"]).toBe(
+ "synthetic.provider",
+ );
+ expect(preflightConfig["model_providers"]).toBeUndefined();
+ if (process.platform !== "win32") {
+ expect(
+ (await stat(options.env!["CODEX_SECURITY_CONFIG_PATH"]!))
+ .mode & 0o777,
+ ).toBe(0o600);
+ }
+ }
+ throw new Error("synthetic command-auth scan started");
+ })();
},
},
);
@@ -296,140 +288,136 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => interpreter!,
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- createCodex: (options: CodexOptions) => ({
- startThread: () => ({
- id: null,
- async runStreamed(input: string) {
- const configPath = options.env?.["CODEX_SECURITY_CONFIG_PATH"];
- const codexHome = options.env?.["CODEX_HOME"];
- expect(typeof configPath).toBe("string");
- expect(typeof codexHome).toBe("string");
- capturedConfigPath = configPath;
- capturedCodexHome = codexHome;
- expect(configPath!.startsWith(`${codexHome!}/`)).toBe(false);
- expect(
- parseToml(
- await readFile(join(codexHome!, "config.toml"), "utf8"),
- ),
- ).toMatchObject({
- approval_policy: "never",
- permissions: {
- codex_security_scan: {
- filesystem: {
- ":root": "read",
- ":workspace_roots": "write",
- [join(
- ambientHome,
- "state",
- "plugins",
- "codex-security",
- "codex-home",
- )]: { ".": "deny" },
- },
+ createCodex: (options: CodexOptions) =>
+ codexFactory(async function runStreamed(input: string) {
+ const configPath = options.env?.["CODEX_SECURITY_CONFIG_PATH"];
+ const codexHome = options.env?.["CODEX_HOME"];
+ expect(typeof configPath).toBe("string");
+ expect(typeof codexHome).toBe("string");
+ capturedConfigPath = configPath;
+ capturedCodexHome = codexHome;
+ expect(configPath!.startsWith(`${codexHome!}/`)).toBe(false);
+ expect(
+ parseToml(
+ await readFile(join(codexHome!, "config.toml"), "utf8"),
+ ),
+ ).toMatchObject({
+ approval_policy: "never",
+ permissions: {
+ codex_security_scan: {
+ filesystem: {
+ ":root": "read",
+ ":workspace_roots": "write",
+ [join(
+ ambientHome,
+ "state",
+ "plugins",
+ "codex-security",
+ "codex-home",
+ )]: { ".": "deny" },
},
},
- });
- const codexConfig = await readFile(
- join(codexHome!, "config.toml"),
- "utf8",
- );
- expect(options.env?.["CODEX_SECURITY_SURFACE"]).toBe("sdk");
- expect(codexConfig).not.toContain("model_reasoning_summary");
- expect(codexConfig).not.toContain("show_raw_agent_reasoning");
- expect(options.config).not.toHaveProperty("projects");
- expect(options.config).not.toHaveProperty("permissions");
- expect(options.config).toMatchObject({
- default_permissions: "codex_security_scan",
- allow_login_shell: false,
- model_reasoning_summary: "detailed",
- show_raw_agent_reasoning: true,
- windows: { sandbox: "elevated" },
- mcp_servers: {
- private: {
- command: "echo",
- env: { PRIVATE_TOKEN: "RUNTIME_MCP_SECRET" },
- },
- },
- shell_environment_policy: {
- set: { PRIVATE_TOKEN: "RUNTIME_SHELL_SECRET" },
- },
- responses_api_metadata: {
- request_trace: "preserve-configured-metadata",
- codex_security_surface: "sdk",
- },
- });
- if (process.platform !== "win32") {
- expect((await stat(configPath!)).mode & 0o777).toBe(0o600);
- }
- const serialized = await readFile(configPath!, "utf8");
- expect(serialized).not.toContain("RUNTIME_MCP_SECRET");
- expect(serialized).not.toContain("RUNTIME_SHELL_SECRET");
- expect(serialized).not.toContain("mcp_servers");
- expect(serialized).not.toContain("shell_environment_policy");
- expect(parseToml(serialized)).toMatchObject({
- projects: {
- [repository]: { trust_level: "trusted" },
+ },
+ });
+ const codexConfig = await readFile(
+ join(codexHome!, "config.toml"),
+ "utf8",
+ );
+ expect(options.env?.["CODEX_SECURITY_SURFACE"]).toBe("sdk");
+ expect(codexConfig).not.toContain("model_reasoning_summary");
+ expect(codexConfig).not.toContain("show_raw_agent_reasoning");
+ expect(options.config).not.toHaveProperty("projects");
+ expect(options.config).not.toHaveProperty("permissions");
+ expect(options.config).toMatchObject({
+ default_permissions: "codex_security_scan",
+ allow_login_shell: false,
+ model_reasoning_summary: "detailed",
+ show_raw_agent_reasoning: true,
+ windows: { sandbox: "elevated" },
+ mcp_servers: {
+ private: {
+ command: "echo",
+ env: { PRIVATE_TOKEN: "RUNTIME_MCP_SECRET" },
},
- });
- expect(input).toContain(
- `--config ${shellEnvironmentReference("CODEX_SECURITY_CONFIG_PATH")}`,
- );
- expect(input).toContain("--effective-config");
- const shellEnvironment = options.env as Record<string, string>;
- const helper = execFileSync(
- interpreter!,
- [
- join(PLUGIN_ROOT, "scripts", "config_preflight.py"),
- "--skill",
- "security-scan",
- "--config",
- shellEnvironment["CODEX_SECURITY_CONFIG_PATH"]!,
- "--cwd",
- repository,
- "--multi-agent-runtime-owner",
- "native",
- "--multi-agent-runtime-version",
- "v2",
- "--multi-agent-session-cap",
- "12",
- "--multi-agent-runtime-provenance",
- "tool-surface",
- "--runtime-check",
- "delegation_available=true",
- "--runtime-check",
- "goal_tools_available=true",
- "--effective-config",
- "features.goals=true",
- ],
- {
- env: {
- PATH: process.env["PATH"],
- CODEX_HOME: join(root, "denied"),
- },
- encoding: "utf8",
+ },
+ shell_environment_policy: {
+ set: { PRIVATE_TOKEN: "RUNTIME_SHELL_SECRET" },
+ },
+ responses_api_metadata: {
+ request_trace: "preserve-configured-metadata",
+ codex_security_surface: "sdk",
+ },
+ });
+ if (process.platform !== "win32") {
+ expect((await stat(configPath!)).mode & 0o777).toBe(0o600);
+ }
+ const serialized = await readFile(configPath!, "utf8");
+ expect(serialized).not.toContain("RUNTIME_MCP_SECRET");
+ expect(serialized).not.toContain("RUNTIME_SHELL_SECRET");
+ expect(serialized).not.toContain("mcp_servers");
+ expect(serialized).not.toContain("shell_environment_policy");
+ expect(parseToml(serialized)).toMatchObject({
+ projects: {
+ [repository]: { trust_level: "trusted" },
+ },
+ });
+ expect(input).toContain(
+ `--config ${shellEnvironmentReference("CODEX_SECURITY_CONFIG_PATH")}`,
+ );
+ expect(input).toContain("--effective-config");
+ const shellEnvironment = options.env as Record<string, string>;
+ const helper = execFileSync(
+ interpreter!,
+ [
+ join(PLUGIN_ROOT, "scripts", "config_preflight.py"),
+ "--skill",
+ "security-scan",
+ "--config",
+ shellEnvironment["CODEX_SECURITY_CONFIG_PATH"]!,
+ "--cwd",
+ repository,
+ "--multi-agent-runtime-owner",
+ "native",
+ "--multi-agent-runtime-version",
+ "v2",
+ "--multi-agent-session-cap",
+ "12",
+ "--multi-agent-runtime-provenance",
+ "tool-surface",
+ "--runtime-check",
+ "delegation_available=true",
+ "--runtime-check",
+ "goal_tools_available=true",
+ "--effective-config",
+ "features.goals=true",
+ ],
+ {
+ env: {
+ PATH: process.env["PATH"],
+ CODEX_HOME: join(root, "denied"),
},
- );
- const preflight = JSON.parse(helper) as Record<string, unknown>;
- expect(preflight["status"]).toBe("ready");
- expect(preflight["config_resolution"]).toBe("manual-layers");
- expect(preflight["config_paths"]).toEqual([configPath]);
- await copyCompletedScan(root);
- const manifestPath = join(scanDir, "scan-manifest.json");
- const manifest = JSON.parse(
- await readFile(manifestPath, "utf8"),
- ) as { scan: { producer: { version: string } } };
- const pluginManifest = JSON.parse(
- await readFile(
- join(PLUGIN_ROOT, ".codex-plugin", "plugin.json"),
- "utf8",
- ),
- ) as { version: string };
- manifest.scan.producer.version = pluginManifest.version;
- await writeFile(manifestPath, JSON.stringify(manifest));
- return { events: completedEvents() };
- },
- }),
- }),
+ encoding: "utf8",
+ },
+ );
+ const preflight = JSON.parse(helper) as Record<string, unknown>;
+ expect(preflight["status"]).toBe("ready");
+ expect(preflight["config_resolution"]).toBe("manual-layers");
+ expect(preflight["config_paths"]).toEqual([configPath]);
+ await copyCompletedScan(root);
+ const manifestPath = join(scanDir, "scan-manifest.json");
+ const manifest = JSON.parse(
+ await readFile(manifestPath, "utf8"),
+ ) as { scan: { producer: { version: string } } };
+ const pluginManifest = JSON.parse(
+ await readFile(
+ join(PLUGIN_ROOT, ".codex-plugin", "plugin.json"),
+ "utf8",
+ ),
+ ) as { version: string };
+ manifest.scan.producer.version = pluginManifest.version;
+ await writeFile(manifestPath, JSON.stringify(manifest));
+ return { events: completedEvents() };
+ })(),
},
);
diff --git a/sdk/typescript/tests-ts/api-provider-isolation.test.ts b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
index c622465ac..778e2c1d3 100644
--- a/sdk/typescript/tests-ts/api-provider-isolation.test.ts
+++ b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
@@ -1,3 +1,4 @@
+import { codexFactory } from "./support/api-events.js";
import { afterEach, expect, spyOn, test } from "bun:test";
import { build } from "esbuild";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
@@ -306,117 +307,108 @@ test.each([
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scan,
repositoryRevision: async () => "deadbeef",
- createCodex: (options) => ({
- startThread: () => ({
- id: null,
- async runStreamed() {
- const environment = options.env!;
- snapshots[index] =
- environment["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!;
- const permission = parseToml(
- options.configOverrides!.find((value) =>
- value.startsWith(
- "permissions.codex_security_scan.filesystem=",
- ),
- )!,
- )["permissions"] as Record<string, Record<string, unknown>>;
- filesystems[index] = permission["codex_security_scan"]![
- "filesystem"
- ] as Record<string, unknown>;
- ready[index]!.resolve();
- await ready[1]!.promise;
- expect(snapshots[0]).not.toBe(snapshots[1]);
- for (const snapshot of snapshots) {
- expect(dirname(dirname(snapshot))).toBe(sharedHome);
- for (const filesystem of filesystems) {
- // The same denied home protects both concurrent snapshots.
- expect(filesystem[sharedHome]).toEqual({ ".": "deny" });
- }
- }
- const preflight = await readFile(
- environment["CODEX_SECURITY_CONFIG_PATH"]!,
- "utf8",
- );
- expect(preflight).not.toContain("synthetic-key-");
- expect(preflight).not.toContain("synthetic-header-");
- const workerSnapshotPath =
- environment["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!;
- const workerSnapshot = parseToml(
- await readFile(workerSnapshotPath, "utf8"),
- );
- expect(workerSnapshot["worker_runtime"]).toMatchObject({
- environment: providerEnvironment,
- features: featureOverrides,
- web_search: webSearch,
- });
- expect(options.config!["web_search"]).toBe(webSearch);
- expect(options.config!["features"]).toMatchObject(
- featureOverrides,
- );
- expect(
- (workerSnapshot["worker_runtime"] as JsonObject)[
- "environment"
- ],
- ).toEqual(providerEnvironment);
- if (process.platform !== "win32") {
- expect(
- (await stat(workerSnapshotPath)).mode & 0o777,
- ).toBe(0o600);
- }
- expect(
- JSON.stringify({
- config: options.config,
- overrides: options.configOverrides,
- }),
- ).not.toContain("synthetic-key-");
- const settings = await workerRuntimeSettings(environment);
- expect(settings.environment).toEqual(providerEnvironment);
- expect(settings.config["features"]).toMatchObject(
- featureOverrides,
- );
- expect(settings.config["web_search"]).toBe(webSearch);
- expect(settings.config["model_provider"]).toBe(
- "openrouter",
- );
- expect(settings.nativeProfile).toBeDefined();
- expect(settings.nativeProfile).toBe(options.nativeProfile);
- expect(
- (workerSnapshot["worker_runtime"] as JsonObject)[
- "native_profile"
- ],
- ).toBe(settings.nativeProfile);
- // Read A's private profile after B updates the shared home.
- // Native profile loading is covered by the inheritance tests.
- const nativeConfig = parseToml(
- await readFile(
- join(
- sharedHome,
- `${settings.nativeProfile}.config.toml`,
- ),
- "utf8",
+ createCodex: (options) =>
+ codexFactory(async function runStreamed() {
+ const environment = options.env!;
+ snapshots[index] =
+ environment["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!;
+ const permission = parseToml(
+ options.configOverrides!.find((value) =>
+ value.startsWith(
+ "permissions.codex_security_scan.filesystem=",
),
+ )!,
+ )["permissions"] as Record<string, Record<string, unknown>>;
+ filesystems[index] = permission["codex_security_scan"]![
+ "filesystem"
+ ] as Record<string, unknown>;
+ ready[index]!.resolve();
+ await ready[1]!.promise;
+ expect(snapshots[0]).not.toBe(snapshots[1]);
+ for (const snapshot of snapshots) {
+ expect(dirname(dirname(snapshot))).toBe(sharedHome);
+ for (const filesystem of filesystems) {
+ // The same denied home protects both concurrent snapshots.
+ expect(filesystem[sharedHome]).toEqual({ ".": "deny" });
+ }
+ }
+ const preflight = await readFile(
+ environment["CODEX_SECURITY_CONFIG_PATH"]!,
+ "utf8",
+ );
+ expect(preflight).not.toContain("synthetic-key-");
+ expect(preflight).not.toContain("synthetic-header-");
+ const workerSnapshotPath =
+ environment["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!;
+ const workerSnapshot = parseToml(
+ await readFile(workerSnapshotPath, "utf8"),
+ );
+ expect(workerSnapshot["worker_runtime"]).toMatchObject({
+ environment: providerEnvironment,
+ features: featureOverrides,
+ web_search: webSearch,
+ });
+ expect(options.config!["web_search"]).toBe(webSearch);
+ expect(options.config!["features"]).toMatchObject(
+ featureOverrides,
+ );
+ expect(
+ (workerSnapshot["worker_runtime"] as JsonObject)[
+ "environment"
+ ],
+ ).toEqual(providerEnvironment);
+ if (process.platform !== "win32") {
+ expect((await stat(workerSnapshotPath)).mode & 0o777).toBe(
+ 0o600,
);
- const actual = (
- nativeConfig["model_providers"] as JsonObject
- )["openrouter"] as JsonObject;
- expect(actual).toMatchObject(provider);
- expect(actual["http_headers"] ?? {}).toEqual(
- provider.http_headers ?? {},
- );
- expect(environment["SYNTHETIC_CUSTOM_API_KEY"]).toBe(
- providerEnvironment.SYNTHETIC_CUSTOM_API_KEY,
- );
- const saved = await readFile(
- join(sharedHome, "config.toml"),
+ }
+ expect(
+ JSON.stringify({
+ config: options.config,
+ overrides: options.configOverrides,
+ }),
+ ).not.toContain("synthetic-key-");
+ const settings = await workerRuntimeSettings(environment);
+ expect(settings.environment).toEqual(providerEnvironment);
+ expect(settings.config["features"]).toMatchObject(
+ featureOverrides,
+ );
+ expect(settings.config["web_search"]).toBe(webSearch);
+ expect(settings.config["model_provider"]).toBe("openrouter");
+ expect(settings.nativeProfile).toBeDefined();
+ expect(settings.nativeProfile).toBe(options.nativeProfile);
+ expect(
+ (workerSnapshot["worker_runtime"] as JsonObject)[
+ "native_profile"
+ ],
+ ).toBe(settings.nativeProfile);
+ // Read A's private profile after B updates the shared home.
+ // Native profile loading is covered by the inheritance tests.
+ const nativeConfig = parseToml(
+ await readFile(
+ join(sharedHome, `${settings.nativeProfile}.config.toml`),
"utf8",
- );
- expect(saved).not.toContain("model_providers");
- expect(saved).not.toContain("synthetic-key-");
- expect(saved).not.toContain("synthetic-header-");
- throw new Error("synthetic provider configuration checked");
- },
- }),
- }),
+ ),
+ );
+ const actual = (
+ nativeConfig["model_providers"] as JsonObject
+ )["openrouter"] as JsonObject;
+ expect(actual).toMatchObject(provider);
+ expect(actual["http_headers"] ?? {}).toEqual(
+ provider.http_headers ?? {},
+ );
+ expect(environment["SYNTHETIC_CUSTOM_API_KEY"]).toBe(
+ providerEnvironment.SYNTHETIC_CUSTOM_API_KEY,
+ );
+ const saved = await readFile(
+ join(sharedHome, "config.toml"),
+ "utf8",
+ );
+ expect(saved).not.toContain("model_providers");
+ expect(saved).not.toContain("synthetic-key-");
+ expect(saved).not.toContain("synthetic-header-");
+ throw new Error("synthetic provider configuration checked");
+ })(),
},
),
);
@@ -817,58 +809,52 @@ test.each(legacyScanCases)(
repositoryRevision: async () => "deadbeef",
createCodex: (options) => {
launched = true;
- return {
- startThread: () => ({
- id: null,
- async runStreamed() {
- const config = parseToml(
- await readFile(
- options.env!["CODEX_SECURITY_CONFIG_PATH"]!,
- "utf8",
- ),
- );
- expect(
- resolveCodexProfile(config as JsonObject)["model_provider"],
- ).toBe(resolveCodexProfile(overrides)["model_provider"]);
- const endpoint =
- resolveCodexProfile(overrides)["openai_base_url"];
- expect(endpoint).toBe(options.config?.["openai_base_url"]);
- expect(config).not.toHaveProperty("openai_base_url");
- if (mode === "deep" && endpoint !== undefined) {
- const worker = parseToml(
- await readFile(
- options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!,
- "utf8",
- ),
- );
- expect(
- (worker["worker_runtime"] as JsonObject)["openai_base_url"],
- ).toBe(endpoint);
- }
- if (native.capability === 2 || native.capability === 3) {
- const worker = parseToml(
- await readFile(
- options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!,
- "utf8",
- ),
- );
- expect(
- (worker["worker_runtime"] as JsonObject)["model_provider"],
- ).toBe("openai");
- }
- expect(
- existsSync(
- join(
- options.env!["CODEX_HOME"]!,
- ".codex-security-preflight",
- ".codex-security-scan.lock",
- ),
- ),
- ).toBe(false);
- throw new Error("synthetic compatible scan started");
- },
- }),
- };
+ return codexFactory(async function runStreamed() {
+ const config = parseToml(
+ await readFile(
+ options.env!["CODEX_SECURITY_CONFIG_PATH"]!,
+ "utf8",
+ ),
+ );
+ expect(
+ resolveCodexProfile(config as JsonObject)["model_provider"],
+ ).toBe(resolveCodexProfile(overrides)["model_provider"]);
+ const endpoint = resolveCodexProfile(overrides)["openai_base_url"];
+ expect(endpoint).toBe(options.config?.["openai_base_url"]);
+ expect(config).not.toHaveProperty("openai_base_url");
+ if (mode === "deep" && endpoint !== undefined) {
+ const worker = parseToml(
+ await readFile(
+ options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!,
+ "utf8",
+ ),
+ );
+ expect(
+ (worker["worker_runtime"] as JsonObject)["openai_base_url"],
+ ).toBe(endpoint);
+ }
+ if (native.capability === 2 || native.capability === 3) {
+ const worker = parseToml(
+ await readFile(
+ options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]!,
+ "utf8",
+ ),
+ );
+ expect(
+ (worker["worker_runtime"] as JsonObject)["model_provider"],
+ ).toBe("openai");
+ }
+ expect(
+ existsSync(
+ join(
+ options.env!["CODEX_HOME"]!,
+ ".codex-security-preflight",
+ ".codex-security-scan.lock",
+ ),
+ ),
+ ).toBe(false);
+ throw new Error("synthetic compatible scan started");
+ })();
},
},
);
@@ -1026,74 +1012,68 @@ test.each([
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scan,
repositoryRevision: async () => "deadbeef",
- createCodex: (options) => ({
- startThread: () => ({
- id: null,
- async runStreamed() {
- expect(options.apiKey).toBe(
- external ? undefined : "synthetic-account-key",
- );
- const status = await nativeRequest(
- {
- ...options.env!,
- ...(options.apiKey === undefined
- ? {}
- : { CODEX_API_KEY: options.apiKey }),
- },
- repository,
- [],
- // Tool enumeration starts the real MCP child without a model turn.
- "mcpServerStatus/list",
- { serverName: "codex-security", detail: "toolsAndAuthOnly" },
- );
- expect(status.data).toHaveLength(1);
- expect(status.data[0].name).toBe("codex-security");
- expect(status.data[0].toolsError).toBeNull();
- expect(status.data[0].tools).toHaveProperty(
- "synthetic_environment",
- );
- expect(JSON.parse(await readFile(report, "utf8"))).toEqual({
- inherited: {
- SYNTHETIC_CUSTOM_API_KEY: null,
- SYNTHETIC_CUSTOM_HEADER: null,
- SYNTHETIC_REQUIRED_KEY: null,
- SYNTHETIC_UNUSED_KEY: null,
- },
- recovered: {
- ...providerEnvironment,
- ...(process.platform === "win32"
- ? { [headerKey]: " synthetic-child-header " }
- : {}),
- ...(external
- ? { [providerKey]: "synthetic-custom-key" }
- : {}),
- ...(providerKey === "CODEX_API_KEY"
- ? { CODEX_API_KEY: "synthetic-account-key" }
- : {}),
- },
- });
- for (const text of [
- await readFile(
- options.env!["CODEX_SECURITY_CONFIG_PATH"]!,
- "utf8",
- ),
- await readFile(
- join(options.env!["CODEX_HOME"]!, "config.toml"),
- "utf8",
- ),
- JSON.stringify({
- config: options.config,
- overrides: options.configOverrides,
- }),
- ]) {
- for (const marker of Object.values(providerEnvironment)) {
- expect(text).not.toContain(marker);
- }
+ createCodex: (options) =>
+ codexFactory(async function runStreamed() {
+ expect(options.apiKey).toBe(
+ external ? undefined : "synthetic-account-key",
+ );
+ const status = await nativeRequest(
+ {
+ ...options.env!,
+ ...(options.apiKey === undefined
+ ? {}
+ : { CODEX_API_KEY: options.apiKey }),
+ },
+ repository,
+ [],
+ // Tool enumeration starts the real MCP child without a model turn.
+ "mcpServerStatus/list",
+ { serverName: "codex-security", detail: "toolsAndAuthOnly" },
+ );
+ expect(status.data).toHaveLength(1);
+ expect(status.data[0].name).toBe("codex-security");
+ expect(status.data[0].toolsError).toBeNull();
+ expect(status.data[0].tools).toHaveProperty(
+ "synthetic_environment",
+ );
+ expect(JSON.parse(await readFile(report, "utf8"))).toEqual({
+ inherited: {
+ SYNTHETIC_CUSTOM_API_KEY: null,
+ SYNTHETIC_CUSTOM_HEADER: null,
+ SYNTHETIC_REQUIRED_KEY: null,
+ SYNTHETIC_UNUSED_KEY: null,
+ },
+ recovered: {
+ ...providerEnvironment,
+ ...(process.platform === "win32"
+ ? { [headerKey]: " synthetic-child-header " }
+ : {}),
+ ...(external ? { [providerKey]: "synthetic-custom-key" } : {}),
+ ...(providerKey === "CODEX_API_KEY"
+ ? { CODEX_API_KEY: "synthetic-account-key" }
+ : {}),
+ },
+ });
+ for (const text of [
+ await readFile(
+ options.env!["CODEX_SECURITY_CONFIG_PATH"]!,
+ "utf8",
+ ),
+ await readFile(
+ join(options.env!["CODEX_HOME"]!, "config.toml"),
+ "utf8",
+ ),
+ JSON.stringify({
+ config: options.config,
+ overrides: options.configOverrides,
+ }),
+ ]) {
+ for (const marker of Object.values(providerEnvironment)) {
+ expect(text).not.toContain(marker);
}
- throw new Error("synthetic native plugin environment checked");
- },
- }),
- }),
+ }
+ throw new Error("synthetic native plugin environment checked");
+ })(),
},
);
try {
diff --git a/sdk/typescript/tests-ts/api-runtime-storage.test.ts b/sdk/typescript/tests-ts/api-runtime-storage.test.ts
index fc266efb7..173f19fd7 100644
--- a/sdk/typescript/tests-ts/api-runtime-storage.test.ts
+++ b/sdk/typescript/tests-ts/api-runtime-storage.test.ts
@@ -1,3 +1,4 @@
+import { codexFactory } from "./support/api-events.js";
import { mkdir, readFile, readdir, stat } from "node:fs/promises";
import { existsSync } from "node:fs";
import { basename, dirname, join } from "node:path";
@@ -62,68 +63,61 @@ test.each([false, true])(
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scan,
repositoryRevision: async () => "deadbeef",
- createCodex: (options) => ({
- startThread: () => ({
- id: null,
- async runStreamed() {
- launched = true;
- const file = join(protectedDirectory!, "config-preflight.toml");
- expect(options.env!["CODEX_SECURITY_CONFIG_PATH"]).toBe(
- operation === "validation" ? undefined : file,
+ createCodex: (options) =>
+ codexFactory(async function runStreamed() {
+ launched = true;
+ const file = join(protectedDirectory!, "config-preflight.toml");
+ expect(options.env!["CODEX_SECURITY_CONFIG_PATH"]).toBe(
+ operation === "validation" ? undefined : file,
+ );
+ expect(dirname(file)).toBe(protectedDirectory!);
+ expect(await readFile(file, "utf8")).not.toContain(
+ "synthetic-client-secret",
+ );
+ workerFile ??= options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"];
+ expect(options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]).toBe(
+ operation === "deep" ? workerFile : undefined,
+ );
+ expect(dirname(dirname(workerFile!))).toBe(
+ options.env!["CODEX_HOME"]!,
+ );
+ expect(await readFile(workerFile!, "utf8")).not.toContain(
+ "synthetic-client-secret",
+ );
+ const profileFile = join(
+ options.env!["CODEX_HOME"]!,
+ `${options.nativeProfile}.config.toml`,
+ );
+ expect(await readFile(profileFile, "utf8")).toContain(
+ "synthetic-client-secret",
+ );
+ expect(JSON.stringify(options)).not.toContain(
+ "synthetic-client-secret",
+ );
+ const filesystem = parseToml(
+ options.configOverrides!.find((value) =>
+ 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" });
+ if (process.platform !== "win32") {
+ expect((await stat(profileFile)).mode & 0o777).toBe(0o600);
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
+ expect((await stat(dirname(file))).mode & 0o777).toBe(0o700);
+ expect((await stat(workerFile!)).mode & 0o777).toBe(0o600);
+ expect((await stat(dirname(workerFile!))).mode & 0o777).toBe(
+ 0o700,
);
- expect(dirname(file)).toBe(protectedDirectory!);
- expect(await readFile(file, "utf8")).not.toContain(
- "synthetic-client-secret",
- );
- workerFile ??=
- options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"];
- expect(options.env!["CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH"]).toBe(
- operation === "deep" ? workerFile : undefined,
- );
- expect(dirname(dirname(workerFile!))).toBe(
- options.env!["CODEX_HOME"]!,
- );
- expect(await readFile(workerFile!, "utf8")).not.toContain(
- "synthetic-client-secret",
- );
- const profileFile = join(
- options.env!["CODEX_HOME"]!,
- `${options.nativeProfile}.config.toml`,
- );
- expect(await readFile(profileFile, "utf8")).toContain(
- "synthetic-client-secret",
- );
- expect(JSON.stringify(options)).not.toContain(
- "synthetic-client-secret",
- );
- const filesystem = parseToml(
- options.configOverrides!.find((value) =>
- 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" });
- if (process.platform !== "win32") {
- expect((await stat(profileFile)).mode & 0o777).toBe(0o600);
- expect((await stat(file)).mode & 0o777).toBe(0o600);
- expect((await stat(dirname(file))).mode & 0o777).toBe(0o700);
- expect((await stat(workerFile!)).mode & 0o777).toBe(0o600);
- expect((await stat(dirname(workerFile!))).mode & 0o777).toBe(
- 0o700,
- );
- }
- throw new Error("synthetic scan reached");
- },
- }),
- }),
+ }
+ throw new Error("synthetic scan reached");
+ })(),
},
);
try {
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 1c4e3b67d..b996c9ae3 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -112,11 +112,16 @@ function localClient(
};
}
-async function runtimeDirectories() {
+async function repositoryDirectories() {
const root = await temporaryDirectory();
const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
await mkdir(repository);
+ return { root, repository };
+}
+
+async function runtimeDirectories() {
+ const { root, repository } = await repositoryDirectories();
+ const codexHome = join(root, "codex-home");
await mkdir(codexHome);
return { root, repository, codexHome };
}
@@ -437,11 +442,8 @@ describe("CodexSecurity finding validation", () => {
events: (signal: AbortSignal) => AsyncGenerator<ThreadEvent> = () =>
validationEvents(),
) {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome } = await runtimeDirectories();
const stateDirectory = join(root, "state");
- await Promise.all([mkdir(repository), mkdir(codexHome)]);
const captured: {
codex?: CodexOptions;
thread?: ThreadOptions;
@@ -892,10 +894,7 @@ describe("CodexSecurity orchestration", () => {
] as const)(
"preserves strict approvals from %s in scan threads and saved recipes",
async (_source, codexOverrides) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- await Promise.all([mkdir(repository), mkdir(codexHome)]);
+ const { root, repository, codexHome } = await runtimeDirectories();
let threadOptions: Record<string, unknown> | undefined;
let recipe: Record<string, unknown> | undefined;
const client = new TestClient(
@@ -1027,9 +1026,7 @@ describe("CodexSecurity orchestration", () => {
});
test("reports configured model and reasoning during local-only preflight", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const { client, prepareRuntime } = localClient(
{
codexOverrides: {
@@ -1049,9 +1046,7 @@ describe("CodexSecurity orchestration", () => {
});
test("reports selected profile model and reasoning during local-only preflight", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const { client, prepareRuntime } = localClient({
codexOverrides: {
profile: "review",
@@ -1078,9 +1073,7 @@ describe("CodexSecurity orchestration", () => {
});
test("validates cost limits and pricing before starting a scan", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const { client, prepareRuntime } = localClient();
await expect(
@@ -1123,9 +1116,7 @@ describe("CodexSecurity orchestration", () => {
});
test("validates deep scan settings before initializing the runtime", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const { client, prepareRuntime } = localClient();
await expect(
@@ -1235,9 +1226,7 @@ describe("CodexSecurity orchestration", () => {
});
test("rejects unusable model settings during local-only preflight", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const invalidSettings: JsonObject[] = [
{ model: "" },
@@ -1255,9 +1244,7 @@ describe("CodexSecurity orchestration", () => {
});
test("reports selected credentials without checking them during preflight", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
for (const [environment, expected] of [
[
@@ -1283,9 +1270,7 @@ describe("CodexSecurity orchestration", () => {
});
test("honors explicit authentication selection without initializing the runtime", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const { client, prepareRuntime } = localClient(
{},
{
@@ -1331,9 +1316,7 @@ describe("CodexSecurity orchestration", () => {
] as const)(
"rejects unsupported %s before runtime initialization",
async (field, value, message) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const { client, prepareRuntime } = localClient(
{},
field === "auth" ? { OPENAI_API_KEY: "synthetic-openai-key" } : {},
@@ -1350,9 +1333,7 @@ describe("CodexSecurity orchestration", () => {
);
test("rejects explicit API-key authentication without a configured key before runtime initialization", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const { client, prepareRuntime } = localClient(
{},
{ OPENAI_API_KEY: " " },
@@ -1424,9 +1405,7 @@ describe("CodexSecurity orchestration", () => {
test.each(EXTERNAL_PROVIDER_CASES)(
"requires the %s API key instead of accepting another provider's credentials",
async (name, provider, apiKey, model, providerConfig) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const prepareRuntime = mock(rejecting("runtime must not start"));
const client = new TestClient(
{
@@ -1480,10 +1459,8 @@ describe("CodexSecurity orchestration", () => {
},
{
environment,
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: unauthenticatedRuntime(codexHome, () => environment),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
resolveCodexCommand: () =>
fail(`${provider} must not sign in to OpenAI`),
createCodex,
@@ -1547,10 +1524,8 @@ describe("CodexSecurity orchestration", () => {
},
{
environment,
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: unauthenticatedRuntime(codexHome, () => environment),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
resolveCodexCommand: () =>
fail("Amazon Bedrock must not sign in to OpenAI"),
createCodex,
@@ -1634,10 +1609,8 @@ describe("CodexSecurity orchestration", () => {
},
{
environment,
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: unauthenticatedRuntime(codexHome, () => environment),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
runWorkbench: async (
_options: unknown,
args: readonly string[],
@@ -2049,9 +2022,7 @@ describe("CodexSecurity orchestration", () => {
});
test("does not accept Bedrock credentials for an OpenAI scan", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
const client = TestClient.withDependencies({
environment: {
AWS_BEARER_TOKEN_BEDROCK: "synthetic-bedrock-bearer",
@@ -2625,9 +2596,7 @@ describe("CodexSecurity orchestration", () => {
});
test("rejects overlapping scan output before runtime initialization", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { root, repository } = await repositoryDirectories();
await writeFile(join(repository, "preserved.txt"), "preserved\n");
const { client, prepareRuntime } = localClient();
@@ -2664,9 +2633,7 @@ describe("CodexSecurity orchestration", () => {
});
test("rejects scan output paths that can inject model context", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { root, repository } = await repositoryDirectories();
const { client, prepareRuntime } = localClient();
for (const separator of ["\n", "\u0085", "\u2028", "\u2029"]) {
@@ -2757,9 +2724,7 @@ describe("CodexSecurity orchestration", () => {
});
test("rejects unsupported Git repository overrides before runtime initialization", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { root, repository } = await repositoryDirectories();
for (const name of [
"GIT_DIR",
"GIT_WORK_TREE",
@@ -2783,9 +2748,7 @@ describe("CodexSecurity orchestration", () => {
});
test("scrubs Git overrides from direct target normalization", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { root, repository } = await repositoryDirectories();
execFileSync("git", ["init", "-q", repository]);
await writeFile(join(repository, "tracked.txt"), "tracked\n");
execFileSync("git", ["-C", repository, "add", "."]);
@@ -2914,6 +2877,7 @@ describe("CodexSecurity orchestration", () => {
{ codexOverrides: { model: "replay-model" } },
{
environment: { PATH: dirname(git!), OPENAI_API_KEY: "" },
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: async () => ({
...preparedRuntime(codexHome, root),
environment: {
@@ -2924,9 +2888,6 @@ describe("CodexSecurity orchestration", () => {
AWS_SECRET_ACCESS_KEY: "must-not-reach-shell",
},
}),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
runWorkbench: async (
workbenchOptions: Parameters<typeof runWorkbench>[0],
args: readonly string[],
@@ -3181,6 +3142,7 @@ describe("CodexSecurity orchestration", () => {
let recipe: Record<string, unknown> | undefined;
const client = TestClient.withDependencies({
environment: { CODEX_HOME: ambientHome },
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: async () => {
await writeFile(
join(ambientHome, "codex-security", "config.toml"),
@@ -3188,9 +3150,6 @@ describe("CodexSecurity orchestration", () => {
);
return preparedRuntime(codexHome);
},
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
runWorkbench: async (
_options: unknown,
args: readonly string[],
@@ -3259,10 +3218,8 @@ describe("CodexSecurity orchestration", () => {
const environment = { CODEX_CLI_PATH: process.execPath };
const client = TestClient.withDependencies({
environment,
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: runtimePreparer(codexHome, () => ({ environment })),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
resolveCodexCommand: () => ({ command: process.execPath }),
runWorkbench: async (
_options: unknown,
@@ -3983,13 +3940,7 @@ describe("CodexSecurity orchestration", () => {
test.each(["none", "sync", "async"] as const)(
"observes workers before scan completion with %s observer errors",
async (failure) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- const scanDir = join(root, "scan");
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const observed = Promise.withResolvers<void>();
const workers: ScanWorkerEvent[] = [];
const errors: ScanObserverName[] = [];
@@ -3997,10 +3948,7 @@ describe("CodexSecurity orchestration", () => {
{},
{
environment: {},
- prepareRuntime: async () => preparedRuntime(codexHome),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
+ ...scanRuntimeDependencies(codexHome, scanDir),
createCodex: () => ({
startThread: () => ({
id: "thread-1",
@@ -4152,18 +4100,13 @@ describe("CodexSecurity orchestration", () => {
});
test("rejects a missing scan skill before registering a scan", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const pluginRoot = join(root, "plugin-without-skills");
- const scanDir = join(root, "scan");
- await mkdir(repository);
- await mkdir(codexHome);
await mkdir(pluginRoot);
- await mkdir(scanDir, { mode: 0o700 });
const runtime = preparedRuntime(codexHome);
const commands: string[] = [];
const client = TestClient.withDependencies({
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: async () => ({
...runtime,
plugin: {
@@ -4173,9 +4116,6 @@ describe("CodexSecurity orchestration", () => {
installedRoot: pluginRoot,
},
}),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
runWorkbench: async (
_options: unknown,
args: readonly string[],
@@ -4203,14 +4143,8 @@ describe("CodexSecurity orchestration", () => {
] as const)(
"uses the registered scan ID in %s",
async (_scenario, mode, withFeedback) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- const scanDir = join(root, "scan");
+ const { repository, codexHome, scanDir } = await scanDirectories();
const scanId = "123e4567-e89b-12d3-a456-426614174000";
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
let prompt = "";
const client = TestClient.withDependencies({
...scanRuntimeDependencies(codexHome, scanDir),
@@ -4950,13 +4884,8 @@ describe("CodexSecurity orchestration", () => {
test.each(["cancel", "close", "restore failure"])(
"preserves completed artifacts when a follow-up ends with %s",
async (scenario) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- const scanDir = join(root, "scan");
- await Promise.all([mkdir(repository), mkdir(codexHome)]);
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const controller = new AbortController();
- await mkdir(scanDir, { mode: 0o700 });
let originalFindings: string;
let turns = 0;
let closing: Promise<void> | undefined;
@@ -5007,11 +4936,9 @@ describe("CodexSecurity orchestration", () => {
);
test("raises a live budget twice without restarting or resetting accumulated usage", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome } = await runtimeDirectories();
const scanDir = join(root, "scan");
- await Promise.all([mkdir(repository), mkdir(codexHome), mkdir(scanDir)]);
+ await mkdir(scanDir);
const approvals = new Map<number, () => void>();
const firstApproval = new Promise<void>((resolve) =>
approvals.set(0.008, resolve),
@@ -5108,11 +5035,9 @@ describe("CodexSecurity orchestration", () => {
] as const)(
"keeps the original budget enforceable when an increase is %s",
async (scenario) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome } = await runtimeDirectories();
const scanDir = join(root, "scan");
- await Promise.all([mkdir(repository), mkdir(codexHome), mkdir(scanDir)]);
+ await mkdir(scanDir);
const requestStarted = Promise.withResolvers<void>();
const nextCost = Promise.withResolvers<void>();
const lateAnswer = Promise.withResolvers<number>();
@@ -5317,15 +5242,7 @@ describe("CodexSecurity orchestration", () => {
test.each(["partial", "invalid", "unavailable"] as const)(
"recovers exhausted deep-scan budget when completion is %s",
async (completion) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- const scanDir = join(root, "scan");
- await Promise.all([
- mkdir(repository),
- mkdir(codexHome),
- mkdir(scanDir, { mode: 0o700 }),
- ]);
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const commands: Array<readonly string[]> = [];
const warnings: string[] = [];
const runStreamed = mock(
@@ -5525,6 +5442,7 @@ describe("CodexSecurity orchestration", () => {
let prompt = "";
let recipe: unknown;
const client = TestClient.withDependencies({
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: runtimePreparer(codexHome, () => ({
environment: {
PATH: [knowledgeBaseBin, trustedBin, dirname(trustedGit)].join(
@@ -5533,9 +5451,6 @@ describe("CodexSecurity orchestration", () => {
GIT_SSH_COMMAND: "synthetic-ssh --fixture",
},
})),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
runWorkbench: async (
workbenchOptions: Parameters<typeof runWorkbench>[0],
args: readonly string[],
@@ -5601,14 +5516,8 @@ describe("CodexSecurity orchestration", () => {
);
test("cleans up knowledge-base documents when a scan fails", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- const scanDir = join(root, "scan");
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const knowledgeBase = join(root, "scope.md");
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
await writeFile(knowledgeBase, "Authorization boundaries are in scope.\n");
let knowledgeDirectory = "";
let prompt = "";
@@ -5639,14 +5548,8 @@ describe("CodexSecurity orchestration", () => {
});
test("marks a started scan failed without masking its original error", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const stateDirectory = join(root, "state");
- const scanDir = join(root, "scan");
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
const python = Bun.which("python3") ?? Bun.which("python");
expect(python).not.toBeNull();
const environment = {
@@ -5700,14 +5603,8 @@ describe("CodexSecurity orchestration", () => {
});
test("preserves original failures in saved scan history", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const stateDirectory = join(root, "state");
- const scanDir = join(root, "scan");
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
const python = Bun.which("python3") ?? Bun.which("python");
expect(python).not.toBeNull();
const environment = {
@@ -5767,12 +5664,8 @@ describe("CodexSecurity orchestration", () => {
});
test("retains default scan output under persistent plugin state", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome } = await runtimeDirectories();
const stateDirectory = join(root, "state");
- await mkdir(repository);
- await mkdir(codexHome);
const client = TestClient.withDependencies({
environment: { CODEX_SECURITY_STATE_DIR: stateDirectory },
prepareRuntime: async () => preparedRuntime(codexHome),
@@ -6184,6 +6077,7 @@ describe("CodexSecurity orchestration", () => {
await mkdir(scanDir, { mode: 0o700 });
const createCodex = mock(throwing("Codex should not start"));
const client = TestClient.withDependencies({
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: runtimePreparer(codexHome, () => ({
plugin: {
...preparedRuntime(codexHome).plugin,
@@ -6191,9 +6085,6 @@ describe("CodexSecurity orchestration", () => {
installedRoot: pluginRoot,
},
})),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex,
});
@@ -6718,9 +6609,7 @@ describe("CodexSecurity orchestration", () => {
});
test("rejects committed diffs when checkout bytes can differ from head", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { repository } = await repositoryDirectories();
await writeFile(
join(repository, "tracked.ts"),
"export const value = 'base';\n",
@@ -6885,10 +6774,7 @@ describe("CodexSecurity orchestration", () => {
test.each(["native", "shim"])(
"uses one spawnable Codex executable for scans and nested workers (%s)",
async (kind) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- const scanDir = join(root, "scan");
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const searchPath = join(root, "custom search path");
await mkdir(searchPath);
const executable = join(
@@ -6903,9 +6789,6 @@ describe("CodexSecurity orchestration", () => {
process.platform === "win32" && kind === "shim"
? resolveCodexCommand({}).command
: executable;
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
const createCodex = mock(completedCodex(root));
const client = TestClient.withDependencies({
environment: {
@@ -6913,6 +6796,7 @@ describe("CodexSecurity orchestration", () => {
CODEX_CLI_PATH: ` ${executable} `,
PATH: searchPath,
},
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: runtimePreparer(codexHome, () => ({
environment: {
CODEX_HOME: codexHome,
@@ -6920,9 +6804,6 @@ describe("CodexSecurity orchestration", () => {
PATH: searchPath,
},
})),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex,
});
@@ -6958,10 +6839,7 @@ describe("CodexSecurity orchestration", () => {
"non-directory tools",
"blank override",
])("preserves default SDK bundled tools for %s", async (scenario) => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- const scanDir = join(root, "scan");
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const executable = join(
root,
"vendor",
@@ -6987,10 +6865,7 @@ describe("CodexSecurity orchestration", () => {
].join(delimiter),
};
await Promise.all([
- mkdir(repository),
- mkdir(codexHome),
mkdir(otherTools),
- mkdir(scanDir, { mode: 0o700 }),
mkdir(dirname(executable), { recursive: true }),
]);
await writeFile(executable, "synthetic executable; never launched\n");
@@ -7012,12 +6887,10 @@ describe("CodexSecurity orchestration", () => {
const createCodex = mock(completedCodex(root));
const client = TestClient.withDependencies({
environment: callerEnvironment,
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: runtimePreparer(codexHome, () => ({
environment: runtimeEnvironment,
})),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex,
});
try {
@@ -7088,15 +6961,9 @@ describe("CodexSecurity orchestration", () => {
});
test("passes environment API keys transiently without native login or keyring persistence", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const fakeCodex = join(root, "codex.mjs");
const nativeLoginMarker = join(root, "native-api-key-login");
- const scanDir = join(root, "scan");
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
await writeFile(
fakeCodex,
`
@@ -7191,14 +7058,12 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
const client = TestClient.withDependencies({
environment: { CODEX_SECURITY_STATE_DIR: join(root, "state") },
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: unauthenticatedRuntime(codexHome, () => ({
CODEX_HOME: codexHome,
...fakeCommand.environment,
})),
resolveCodexCommand: () => fakeCommand.command,
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex: () => fail("managed keyring scan reached"),
});
@@ -7283,10 +7148,8 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
CODEX_HOME: ambientHome,
OPENAI_API_KEY: "synthetic-openai-key",
},
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: unauthenticatedRuntime(codexHome),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex: (options: CodexOptions) => {
selectedApiKeys.push(options.apiKey);
codexEnvironments.push(options.env);
@@ -7353,14 +7216,12 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
CODEX_HOME: ambientHome,
OPENAI_API_KEY: "synthetic-key",
},
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: unauthenticatedRuntime(codexHome, () => ({
CODEX_HOME: codexHome,
...fake.environment,
})),
resolveCodexCommand: () => fake.command,
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex,
},
);
@@ -7439,10 +7300,8 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
const selectedKeys: Array<string | undefined> = [];
const client = TestClient.withDependencies({
environment,
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: unauthenticatedRuntime(codexHome),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex: (options: CodexOptions) => {
selectedKeys.push(options.apiKey);
throw new Error("scan reached");
@@ -7518,13 +7377,11 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
const prepared =
Promise.withResolvers<ReturnType<typeof preparedRuntime>>();
const client = TestClient.withDependencies({
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: async () => {
started.resolve();
return await prepared.promise;
},
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex: completedCodex(root),
});
const controller = new AbortController();
@@ -7540,12 +7397,8 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
});
test("waits for in-flight turn setup before close removes the runtime", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
+ const { root, repository, codexHome } = await runtimeDirectories();
const scanDir = await copyCompletedScan(root);
- await mkdir(repository);
- await mkdir(codexHome);
const started = Promise.withResolvers<void>();
const blocked = Promise.withResolvers<void>();
const createCodex = mock(throwing("turn continued after close"));
@@ -7599,14 +7452,8 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
});
test("closes a real Codex subprocess cleanly after a streamed terminal failure", async () => {
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- const codexHome = join(root, "codex-home");
- const scanDir = join(root, "scan");
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
const preload = join(root, "fake-codex.mjs");
- await mkdir(repository);
- await mkdir(codexHome);
- await mkdir(scanDir, { mode: 0o700 });
await writeFile(
preload,
[
@@ -7618,12 +7465,10 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
);
const nodeExecutable = nodeCommand().command;
const client = TestClient.withDependencies({
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: runtimePreparer(codexHome, () => ({
environment: { CODEX_HOME: codexHome },
})),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex: (options: CodexOptions) =>
new Codex({
...options,
@@ -7802,9 +7647,7 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
) {
return;
}
- const root = await temporaryDirectory();
- const repository = join(root, "repository");
- await mkdir(repository);
+ const { root, repository } = await repositoryDirectories();
const originalRm = fsPromises.rm;
const attempted: string[] = [];
mockFs(() => ({
@@ -7915,15 +7758,13 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
CODEX_SECURITY_STATE_DIR: join(root, "state"),
OPENAI_API_KEY: "ambient-key",
},
+ ...scanRuntimeDependencies(codexHome, scanDir),
prepareRuntime: unauthenticatedRuntime(codexHome, () => ({
...process.env,
CODEX_HOME: codexHome,
OPENAI_API_KEY: "ambient-key",
CODEX_API_KEY: "secondary-ambient-key",
})),
- resolvePluginPython: async () => "/managed/python",
- prepareOutputDir: async () => scanDir,
- repositoryRevision: async () => "deadbeef",
createCodex,
});
try {