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: preserve per-scan runtime and worker settings (#1281)

mldangelo-oai0e57e1297597
diff --git a/evals/secret-discovery/test_runtime.mts b/evals/secret-discovery/test_runtime.mts
index 79b07b7d9..c5c67c44b 100644
--- a/evals/secret-discovery/test_runtime.mts
+++ b/evals/secret-discovery/test_runtime.mts
@@ -427,6 +427,7 @@ test(
const exec = await readJson(join(directory, "exec.json"));
assert.equal(preflight.cwd, prepared.repo);
assert.equal(exec.effectiveCwd, prepared.repo);
+ assert.equal(exec.config.model_provider, undefined);
assert.deepEqual(preflight.config, exec.config);
assert.deepEqual(exec.config.features, {
memories: false,
diff --git a/plugins/codex-security/.codex-plugin/plugin.json b/plugins/codex-security/.codex-plugin/plugin.json
index 056258dc9..9d333b0ed 100644
--- a/plugins/codex-security/.codex-plugin/plugin.json
+++ b/plugins/codex-security/.codex-plugin/plugin.json
@@ -18,6 +18,9 @@
"skills": "./skills/",
"apps": "./.app.json",
"mcpServers": "./.mcp.json",
+ "codexSecurity": {
+ "workerProviderSnapshot": 4
+ },
"interface": {
"displayName": "Codex Security",
"shortDescription": "Security scanning for your codebase",
diff --git a/plugins/codex-security/.mcp.json b/plugins/codex-security/.mcp.json
index d7c52e082..9e901b69b 100644
--- a/plugins/codex-security/.mcp.json
+++ b/plugins/codex-security/.mcp.json
@@ -39,6 +39,7 @@
"CODEX_SECURITY_KNOWLEDGE_BASE",
"CODEX_SECURITY_CONFIG_PATH",
"CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
+ "CODEX_SECURITY_PLUGIN_ROOT",
"CODEX_SECURITY_SCAN_ROOT",
"CODEX_SECURITY_STATE_DIR",
"CODEX_SECURITY_SURFACE",
diff --git a/plugins/codex-security/mcp-app/scripts/build_mcp_app.mjs b/plugins/codex-security/mcp-app/scripts/build_mcp_app.mjs
index aa1372c60..c0ad12f22 100644
--- a/plugins/codex-security/mcp-app/scripts/build_mcp_app.mjs
+++ b/plugins/codex-security/mcp-app/scripts/build_mcp_app.mjs
@@ -63,6 +63,14 @@ export async function buildMcpApp({ output, native = "universal" }) {
await copyFile(join(nativeRoot, path), destination);
}
await writeRuntime("helpers", "helpers-main.ts");
+ await build({
+ bundle: true,
+ entryPoints: [join(root, "src/deep-scan/permission-profile-preflight.ts")],
+ format: "esm",
+ outfile: join(mcpDir, "permission-profile-preflight.mjs"),
+ platform: "node",
+ target: "node20",
+ });
async function writeRuntime(name, entryPoint) {
const bundle = join(mcpDir, name + ".bundle.cjs");
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts
index bba032573..7efaaaf31 100644
--- a/plugins/codex-security/mcp-app/server.ts
+++ b/plugins/codex-security/mcp-app/server.ts
@@ -44,7 +44,8 @@ const execFileAsync = promisify(execFile);
const CONFIGURED_SCAN_ROOT = process.env.CODEX_SECURITY_SCAN_ROOT?.trim();
const CONFIGURED_WORKBENCH_STATE_DIR =
process.env.CODEX_SECURITY_STATE_DIR?.trim();
-const PLUGIN_ROOT = resolve(__dirname, "..");
+const PLUGIN_ROOT =
+ process.env.CODEX_SECURITY_PLUGIN_ROOT || resolve(__dirname, "..");
const USER_INPUT_WAIT_TIMEOUT_MS = 14 * 60 * 1000;
const WORKBENCH_COMMANDS_WITHOUT_DATABASE = new Set([
"resolve-scan-root",
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
index 2aa48eeec..abcde7f96 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
@@ -7,6 +7,7 @@ import {
statSync,
} from "node:fs";
import { createRequire } from "node:module";
+import { homedir } from "node:os";
import {
delimiter,
dirname,
@@ -15,8 +16,17 @@ import {
resolve,
win32,
} from "node:path";
-import { Codex, type CyberAccessProgram } from "@openai/codex-sdk";
+import {
+ Codex,
+ type CyberAccessProgram,
+ type ThreadEvent,
+} from "@openai/codex-sdk";
import { parse as parseToml } from "smol-toml";
+import {
+ createCodexProfileClient,
+ preflightProviderDefinitions,
+ profileConfigOverrides,
+} from "../../../scripts/codex_profile.mjs";
import { executablePathForSpawn } from "./executable-path.js";
import {
classifyCodexWorkerError,
@@ -52,13 +62,11 @@ export interface CodexSdkWorkerArtifactContext {
}
interface CodexSdkWorkerRuntimeSettings {
- reasoningSummary?: string;
- serviceTier?: string;
+ environment?: Record<string, string>;
+ config: Record<string, unknown>;
+ preflightProviderOverrides?: string[];
+ nativeProfile?: string;
cyberAccessProgram?: CyberAccessProgram;
- features?: {
- api_key_cyber_access_programs?: boolean;
- api_key_model_discovery?: boolean;
- };
}
export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
@@ -77,13 +85,42 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
);
}
const workerProfile = workerPermissionProfile(parentSandbox);
- const configOverrides =
- workerPermissionProfileConfigOverrides(workerProfile);
const originalCwd = process.cwd();
const childEnv = await snapshotWorkerEnvironment();
// Snapshot the SDK's per-scan config once for this coordinator, including resumes.
const runtimeSettings = await (this.runtimeSettings ??=
workerRuntimeSettings(childEnv));
+ for (const [name, value] of Object.entries(
+ runtimeSettings.environment ?? {},
+ )) {
+ if (process.platform === "win32") {
+ for (const key of Object.keys(childEnv)) {
+ if (key.toUpperCase() === name.toUpperCase()) delete childEnv[key];
+ }
+ }
+ childEnv[name] = value;
+ }
+ // Keep one native configuration for the policy check and the worker turn.
+ // Worker-owned tool and permission settings take precedence over inheritance.
+ const configOverrides = profileConfigOverrides({
+ ...runtimeSettings.config,
+ ...(this.modelSettings.reasoningEffort
+ ? { model_reasoning_effort: this.modelSettings.reasoningEffort }
+ : {}),
+ mcp_servers: {
+ // A disabled server still needs a valid transport during native resolution.
+ "codex-security": { command: "node", enabled: false },
+ ...this.compactArtifactServer(request),
+ },
+ ...workerSubagentConfig(
+ request.subagents,
+ runtimeSettings.config.features,
+ ),
+ approval_policy: "never",
+ default_permissions: DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID,
+ [`permissions.${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}`]:
+ workerProfile,
+ });
const openAiApiKey = environmentVariable(
childEnv,
"OPENAI_API_KEY",
@@ -105,47 +142,34 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
codexPath,
cwd: request.workingDirectory,
configOverrides,
+ providerConfigOverrides: runtimeSettings.preflightProviderOverrides,
expectedProfile: workerProfile,
env: childEnv,
allowOpenAiApiKeyFallback: Boolean(openAiApiKey && !codexApiKey),
signal: request.signal,
});
const prompt = await fs.readFile(request.promptPath, "utf8");
- const codex = new Codex({
+ const codexOptions = {
codexPathOverride: executablePathForSpawn(codexPath),
env: childEnv,
// Codex exec reads CODEX_API_KEY; the SDK maps apiKey to that variable.
// Keep native credentials unless the worker has no configured account.
...(useOpenAiApiKey ? { apiKey: openAiApiKey } : {}),
- config: {
- ...(runtimeSettings.reasoningSummary === undefined
- ? {}
- : { model_reasoning_summary: runtimeSettings.reasoningSummary }),
- ...(runtimeSettings.serviceTier === undefined
- ? {}
- : { service_tier: runtimeSettings.serviceTier }),
- // The CLI can add effort levels before the pinned SDK widens ThreadOptions.
- ...(this.modelSettings.reasoningEffort
- ? { model_reasoning_effort: this.modelSettings.reasoningEffort }
- : {}),
- mcp_servers: {
- // Discovery workers use the bundled skills and artifacts, not the parent workbench MCP.
- // A disabled server still needs a valid transport while Codex resolves plugin configuration.
- "codex-security": { command: "node", enabled: false },
- ...this.compactArtifactServer(request),
- },
- ...workerSubagentConfig(request.subagents, runtimeSettings.features),
- },
- // Structured SDK config cannot preserve literal filesystem keys such as
- // ":root" or "/repo/.env"; raw overrides keep this inline TOML intact.
+ // Raw overrides preserve literal filesystem and MCP keys.
configOverrides,
- });
+ };
+ const codex =
+ runtimeSettings.nativeProfile === undefined
+ ? new Codex(codexOptions)
+ : createCodexProfileClient<ThreadEvent>({
+ ...codexOptions,
+ profileName: runtimeSettings.nativeProfile,
+ });
const threadOptions = {
...(this.modelSettings.model
? { model: this.modelSettings.model }
: {}),
threadSource: "security_scan",
- approvalPolicy: "never",
skipGitRepoCheck: true,
workingDirectory: request.workingDirectory,
} as const;
@@ -290,17 +314,14 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
}
}
-function workerSubagentConfig(
- subagents: number,
- inheritedFeatures: CodexSdkWorkerRuntimeSettings["features"],
-) {
+function workerSubagentConfig(subagents: number, inheritedFeatures: unknown) {
return {
// V1 counts children; V2 counts the root plus its children. Keeping its
// feature disabled lets the model choose either runtime without rejecting
// inherited agents.max_threads configuration.
...(subagents > 0 ? { agents: { max_threads: subagents } } : {}),
features: {
- ...inheritedFeatures,
+ ...(isRecord(inheritedFeatures) ? inheritedFeatures : {}),
multi_agent_v2: {
enabled: false,
max_concurrent_threads_per_session: subagents + 1,
@@ -316,10 +337,7 @@ function workerSubagentConfig(
};
}
-type TomlValue = string | number | boolean | TomlObject;
-type TomlObject = { [key: string]: TomlValue };
-
-function workerPermissionProfile(sandbox: DeepWorkerParentSandbox): TomlObject {
+function workerPermissionProfile(sandbox: DeepWorkerParentSandbox) {
return {
extends: ":read-only",
// Object.fromEntries preserves literal keys such as "__proto__" without
@@ -327,6 +345,10 @@ function workerPermissionProfile(sandbox: DeepWorkerParentSandbox): TomlObject {
filesystem: Object.fromEntries([
[":root", "read"],
...Array.from(sandbox.filesystemDenies, (key) => [key, "deny"]),
+ ...Array.from(sandbox.literalFilesystemDenies ?? [], (key) => [
+ key,
+ { ".": "deny" },
+ ]),
...(sandbox.globScanMaxDepth === undefined
? []
: [["glob_scan_max_depth", sandbox.globScanMaxDepth]]),
@@ -335,30 +357,6 @@ function workerPermissionProfile(sandbox: DeepWorkerParentSandbox): TomlObject {
};
}
-function workerPermissionProfileConfigOverrides(profile: TomlObject): string[] {
- return [
- `default_permissions=${tomlString(DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID)}`,
- `permissions.${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}=${tomlInlineValue(profile)}`,
- ];
-}
-
-function tomlInlineValue(value: TomlValue): string {
- if (typeof value === "string") return tomlString(value);
- if (typeof value === "number") return String(value);
- if (typeof value === "boolean") return value ? "true" : "false";
- return `{${Object.entries(value)
- .map(([key, entry]) => `${tomlKey(key)}=${tomlInlineValue(entry)}`)
- .join(",")}}`;
-}
-
-function tomlKey(value: string): string {
- return /^[A-Za-z0-9_-]+$/.test(value) ? value : tomlString(value);
-}
-
-function tomlString(value: string): string {
- return JSON.stringify(value).replace(/\u007f/g, "\\u007f");
-}
-
/**
* Convert SDK item failures into bounded classifications without retaining the
* command, output, or paths carried by the event. Those fields can contain
@@ -479,42 +477,93 @@ async function workerRuntimeSettings(
"CODEX_SECURITY_CONFIG_PATH",
process.platform,
);
- if (!configPath) return {};
+ if (!configPath) return { config: {} };
const config = parseToml(await fs.readFile(configPath, "utf8"));
const profiles = config.profiles;
const profile =
typeof config.profile === "string" && isRecord(profiles)
? profiles[config.profile]
: undefined;
- const summary =
- isRecord(profile) && profile.model_reasoning_summary !== undefined
- ? profile.model_reasoning_summary
- : config.model_reasoning_summary;
- const serviceTier =
- isRecord(profile) && profile.service_tier !== undefined
- ? profile.service_tier
- : config.service_tier;
- const settings: CodexSdkWorkerRuntimeSettings = {
- ...(typeof summary === "string" ? { reasoningSummary: summary } : {}),
- ...(typeof serviceTier === "string" ? { serviceTier } : {}),
- };
+ const selected = { ...config, ...(isRecord(profile) ? profile : {}) };
+ const inherited = Object.fromEntries(
+ ["model_reasoning_summary", "service_tier"].map((key) => [
+ key,
+ selected[key],
+ ]),
+ );
+ const settings: CodexSdkWorkerRuntimeSettings = { config: inherited };
+ const workerConfigPath = environmentVariable(
+ environment,
+ "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
+ process.platform,
+ );
+ const snapshot = workerConfigPath
+ ? parseToml(await fs.readFile(workerConfigPath, "utf8")).worker_runtime
+ : undefined;
+ const {
+ environment: workerEnvironment,
+ native_profile: nativeProfile,
+ model_providers: legacyProviders,
+ ...workerConfig
+ } = isRecord(snapshot) ? snapshot : {};
+ if (isRecord(workerEnvironment)) {
+ settings.environment = workerEnvironment as Record<string, string>;
+ }
+ if (typeof nativeProfile === "string") {
+ // Match Codex's plain profile-v2 names before constructing a private file path.
+ if (nativeProfile.length === 0 || /[^A-Za-z0-9_-]/.test(nativeProfile)) {
+ throw new DeepScanNonRetryableError(
+ `invalid --profile value ${JSON.stringify(nativeProfile)}; pass a plain name such as "work"`,
+ );
+ }
+ settings.nativeProfile = nativeProfile;
+ const codexHome =
+ environmentVariable(environment, "CODEX_HOME", process.platform) ||
+ join(homedir(), ".codex");
+ const nativeProfileConfig = parseToml(
+ await fs.readFile(
+ join(codexHome, `${nativeProfile}.config.toml`),
+ "utf8",
+ ),
+ );
+ if (isRecord(nativeProfileConfig.model_providers)) {
+ const providers = preflightProviderDefinitions(
+ nativeProfileConfig.model_providers,
+ );
+ if (Object.keys(providers).length > 0) {
+ settings.preflightProviderOverrides = profileConfigOverrides({
+ model_providers: providers,
+ });
+ }
+ }
+ }
+ if (
+ settings.nativeProfile === undefined &&
+ isRecord(legacyProviders) &&
+ Object.keys(legacyProviders).length > 0
+ ) {
+ throw new DeepScanNonRetryableError(
+ "This Deep Scan provider snapshot needs private native profile support. Update the SDK and bundled plugin together.",
+ );
+ }
const security = config.codex_security;
if (isRecord(security) && typeof security.cyber_access_program === "string") {
settings.cyberAccessProgram =
security.cyber_access_program as CyberAccessProgram;
}
- const features = config.features;
- if (isRecord(features)) {
- for (const name of [
- "api_key_cyber_access_programs",
- "api_key_model_discovery",
- ] as const) {
- const value = features[name];
- if (typeof value === "boolean") {
- (settings.features ??= {})[name] = value;
- }
- }
- }
+ const features = isRecord(config.features) ? config.features : {};
+ settings.config = {
+ ...inherited,
+ ...workerConfig,
+ features: {
+ ...Object.fromEntries(
+ ["api_key_cyber_access_programs", "api_key_model_discovery"].map(
+ (key) => [key, features[key]],
+ ),
+ ),
+ ...(isRecord(workerConfig.features) ? workerConfig.features : {}),
+ },
+ };
return settings;
}
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.ts
index 9d1e9b6ec..19f5cb94a 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,6 +1,5 @@
import { asRecord as record, isNonEmptyString } from "../record.js";
import { isAbsolute } from "node:path";
-import { fileURLToPath } from "node:url";
import { isDeepStrictEqual } from "node:util";
import { DeepScanNonRetryableError } from "./errors.js";
@@ -13,6 +12,8 @@ export type DeepWorkerParentSandbox = {
* workers never inherit parent write access.
*/
readonly filesystemDenies: readonly string[];
+ /** Literal paths with glob characters retain native point-deny semantics. */
+ readonly literalFilesystemDenies?: readonly string[];
readonly globScanMaxDepth?: number;
};
@@ -21,7 +22,6 @@ export function resolveDeepWorkerParentSandbox(
extra: unknown,
): DeepWorkerParentSandbox {
const state = trustedSandboxState(extra);
- validateSandboxCwd(state.sandboxCwd);
const profile = record(state.permissionProfile);
if (!profile || profile.type !== "managed") {
@@ -30,12 +30,6 @@ export function resolveDeepWorkerParentSandbox(
);
}
- if (profile.network !== "enabled" && profile.network !== "restricted") {
- throw unsupportedParentSandbox(
- "the parent network permission is missing or invalid",
- );
- }
-
const filesystem = record(profile.file_system);
if (!filesystem) {
throw unsupportedParentSandbox(
@@ -57,6 +51,7 @@ export function resolveDeepWorkerParentSandbox(
let hasRootRead = false;
const filesystemDenies: string[] = [];
+ const literalFilesystemDenies: string[] = [];
for (const value of filesystem.entries) {
const entry = record(value);
if (!entry || !isKnownFilesystemAccess(entry.access)) {
@@ -102,12 +97,10 @@ export function resolveDeepWorkerParentSandbox(
"a parent filesystem denial path cannot be preserved",
);
}
- if (hasGlobMetacharacters(path.path)) {
- throw unsupportedParentSandbox(
- "a parent filesystem denial path with glob characters cannot be preserved",
- );
- }
- filesystemDenies.push(path.path);
+ (hasGlobMetacharacters(path.path)
+ ? literalFilesystemDenies
+ : filesystemDenies
+ ).push(path.path);
}
} else if (path.type === "glob_pattern") {
if (!isNonEmptyString(path.pattern)) {
@@ -138,6 +131,12 @@ export function resolveDeepWorkerParentSandbox(
}
}
+ if (literalFilesystemDenies.some((path) => filesystemDenies.includes(path))) {
+ throw unsupportedParentSandbox(
+ "literal path and glob denials with the same key cannot be preserved",
+ );
+ }
+
if (!hasRootRead) {
throw unsupportedParentSandbox(
"the parent restricts readable paths beyond the supported read-only worker sandbox",
@@ -146,6 +145,7 @@ export function resolveDeepWorkerParentSandbox(
return {
filesystemDenies,
+ ...(literalFilesystemDenies.length ? { literalFilesystemDenies } : {}),
...(globScanMaxDepth !== undefined ? { globScanMaxDepth } : {}),
};
}
@@ -177,29 +177,6 @@ function trustedSandboxState(extra: unknown): Record<string, unknown> {
return state;
}
-function validateSandboxCwd(value: unknown): void {
- if (value === undefined) return;
- if (typeof value !== "string" || value.trim().length === 0) {
- throw unsupportedParentSandbox(
- "the parent sandbox working directory is invalid",
- );
- }
- if (value.startsWith("file:")) {
- try {
- if (isAbsolute(fileURLToPath(value))) return;
- } catch {
- throw unsupportedParentSandbox(
- "the parent sandbox working directory is invalid",
- );
- }
- }
- if (!isAbsolute(value)) {
- throw unsupportedParentSandbox(
- "the parent sandbox working directory is invalid",
- );
- }
-}
-
function resolveGlobScanMaxDepth(
filesystem: Record<string, unknown>,
): number | undefined {
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
index 64babd9cf..fccf08af0 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/permission-profile-preflight.ts
@@ -1,11 +1,12 @@
import type { JsonObject as JsonRecord } from "../types.js";
-import { asRecord as record, isNonEmptyString } from "../record.js";
+import { asRecord as record } from "../record.js";
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { createInterface, type Interface } from "node:readline";
import { isDeepStrictEqual } from "node:util";
import { version as MCP_APP_VERSION } from "../../package.json";
import { DeepScanNonRetryableError } from "./errors.js";
import { executablePathForSpawn } from "./executable-path.js";
+import { isPermissionProfileFallbackWarning } from "../../../scripts/codex_profile.mjs";
/** The stable profile id selected by the worker's raw config overrides. */
export const DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID =
@@ -16,8 +17,10 @@ export interface DeepScanPermissionProfilePreflightOptions {
readonly codexPath: string;
/** The worker cwd used for app-server startup and cwd-scoped config RPCs. */
readonly cwd: string;
- /** Raw `-c` values passed to both this preflight and the SDK worker. */
+ /** Worker overrides, including the effective provider selection. */
readonly configOverrides: readonly string[];
+ /** Provider metadata needed for managed selection; credentials stay in private profiles. */
+ readonly providerConfigOverrides?: readonly string[];
/**
* Exact environment snapshot shared with the SDK worker. The caller resolves
* relative CODEX_HOME values before changing the preflight subprocess cwd.
@@ -29,6 +32,8 @@ export interface DeepScanPermissionProfilePreflightOptions {
/** The injected profile before app-server expands omitted options to null. */
readonly expectedProfile: Readonly<Record<string, unknown>>;
readonly signal: AbortSignal;
+ /** Internal SDK helper context changes the wrapper-owned subject label. */
+ readonly context?: "helper";
}
type PendingRequest = {
@@ -38,9 +43,32 @@ type PendingRequest = {
readonly reject: (error: Error) => void;
};
+type RuntimeConfigReadOptions = Pick<
+ DeepScanPermissionProfilePreflightOptions,
+ "codexPath" | "cwd" | "configOverrides" | "env" | "signal" | "context"
+> & {
+ readonly commandArgs?: readonly string[];
+ readonly providerConfigOverrides?: readonly string[];
+};
+
+/** Read native effective settings, including managed provider requirements, without a turn. */
+export async function readDeepScanRuntimeConfig(
+ options: RuntimeConfigReadOptions,
+): Promise<JsonRecord> {
+ return withPreflightClient(options, async (client) => {
+ const response = await client.request("config/read", {
+ cwd: options.cwd,
+ includeLayers: false,
+ });
+ const config = record(response.config);
+ if (!config) throw malformedPreflightError(options.context);
+ return config;
+ });
+}
+
/**
* Verify the worker profile with the same executable, effective worker cwd,
- * Codex home, and raw overrides that the real worker will use. App-server must
+ * Codex home, and permission overrides that the real worker will use. App-server must
* start in the worker cwd because startup config also selects authentication
* and cloud-managed requirements; cwd-scoped RPCs alone do not replace that
* startup context. This must finish before starting a turn: startup warnings
@@ -54,12 +82,7 @@ type PendingRequest = {
export async function preflightDeepScanWorkerPermissionProfile(
options: DeepScanPermissionProfilePreflightOptions,
): Promise<{ useOpenAiApiKey: boolean }> {
- validateOptions(options);
- if (options.signal.aborted) throw abortError(options.signal.reason);
-
- const client = new AppServerPreflightClient(options);
- try {
- await client.initialize();
+ return withPreflightClient(options, async (client) => {
const configResponse = await client.request("config/read", {
cwd: options.cwd,
includeLayers: false,
@@ -68,7 +91,8 @@ export async function preflightDeepScanWorkerPermissionProfile(
const matchingEntries = catalog.filter(
(entry) => entry.id === DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID,
);
- if (matchingEntries.length !== 1) throw malformedPreflightError();
+ if (matchingEntries.length !== 1)
+ throw malformedPreflightError(options.context);
const catalogEntry = matchingEntries[0];
const requirementsResponse =
catalogEntry.allowed === true
@@ -86,8 +110,8 @@ export async function preflightDeepScanWorkerPermissionProfile(
) {
return { useOpenAiApiKey: false };
}
- // Reuse Codex's selected credential store and provider, including keyring
- // and command-backed providers, instead of interpreting auth.json here.
+ // Reuse Codex's selected credential store, including keyring, instead of
+ // interpreting auth.json here. Custom provider auth is loaded privately by exec.
const account = await client.request("account/read", {
refreshToken: false,
});
@@ -95,6 +119,29 @@ export async function preflightDeepScanWorkerPermissionProfile(
useOpenAiApiKey:
account.requiresOpenaiAuth === true && account.account === null,
};
+ });
+}
+
+async function withPreflightClient<T>(
+ options: RuntimeConfigReadOptions,
+ operation: (client: AppServerPreflightClient) => Promise<T>,
+): Promise<T> {
+ if (options.signal.aborted) throw abortError(options.signal.reason);
+ const client = new AppServerPreflightClient(options);
+ try {
+ await client.initialize();
+ return await operation(client);
+ } catch (error) {
+ await client.close();
+ const stderr = client.stderrText;
+ if (error instanceof Error && stderr)
+ Object.defineProperty(error, "message", {
+ value: error.message + "\n" + stderr,
+ writable: true,
+ configurable: true,
+ enumerable: false,
+ });
+ throw error;
} finally {
await client.close();
}
@@ -106,24 +153,28 @@ class AppServerPreflightClient {
private readonly stdoutLines: Interface;
private pending: PendingRequest | undefined;
private nextId = 1;
+ private readonly stderr: Buffer[] = [];
private terminalError: Error | undefined;
private closed = false;
private childClosed = false;
private readonly removeAbortListener: () => void;
- constructor(
- private readonly options: DeepScanPermissionProfilePreflightOptions,
- ) {
- const args: string[] = [];
+ constructor(private readonly options: RuntimeConfigReadOptions) {
+ const args: string[] = [...(options.commandArgs ?? [])];
for (const override of options.configOverrides) {
args.push("--config", override);
}
+ // App-server loads credential-free metadata; exec reads private provider profiles.
+ for (const override of options.providerConfigOverrides ?? []) {
+ args.push("--config", override);
+ }
args.push("app-server", "--stdio");
this.child = spawn(executablePathForSpawn(options.codexPath), args, {
cwd: options.cwd,
...(options.env === undefined ? {} : { env: options.env }),
stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
});
this.childClose = new Promise((resolve) => {
this.child.once("close", () => {
@@ -131,25 +182,37 @@ class AppServerPreflightClient {
resolve();
});
});
- // stderr can contain paths or repository contents. Drain it so the child
- // cannot block, but never retain or surface it in Deep Scan errors.
- this.child.stderr.resume();
+ this.child.stderr.on("data", (chunk) => this.stderr.push(chunk));
this.stdoutLines = createInterface({
input: this.child.stdout,
crlfDelay: Infinity,
});
this.stdoutLines.on("line", (line) => this.consumeStdoutLine(line));
- const onStdioError = () => {
- this.fail(codexExecutableStdioError(options.codexPath));
+ const onStdioError = (error: Error) => {
+ const failure = codexExecutableStdioError(
+ options.codexPath,
+ options.context,
+ );
+ failure.message += "\n" + error.message;
+ this.fail(failure);
};
this.stdoutLines.on("error", onStdioError);
this.child.stdin.on("error", onStdioError);
this.child.on("error", (error) => {
- this.fail(codexExecutableStartError(options.codexPath, error));
+ this.fail(
+ codexExecutableStartError(options.codexPath, error, options.context),
+ );
});
- this.child.on("exit", (code, signal) => {
+ this.child.on("close", (code, signal) => {
if (!this.closed) {
- this.fail(codexExecutableExitError(options.codexPath, code, signal));
+ this.fail(
+ codexExecutableExitError(
+ options.codexPath,
+ code,
+ signal,
+ options.context,
+ ),
+ );
}
});
@@ -162,6 +225,10 @@ class AppServerPreflightClient {
options.signal.removeEventListener("abort", onAbort);
}
+ get stderrText(): string {
+ return Buffer.concat(this.stderr).toString("utf8");
+ }
+
async initialize(): Promise<void> {
await this.request("initialize", {
clientInfo: {
@@ -186,22 +253,17 @@ class AppServerPreflightClient {
...(cursor === undefined ? {} : { cursor }),
});
const data = result.data;
- if (!Array.isArray(data)) throw malformedPreflightError();
+ if (!Array.isArray(data))
+ throw malformedPreflightError(this.options.context);
for (const value of data) {
const entry = record(value);
// Catalog ids are opaque. Only our requested profile id is fixed and
// non-empty; unrelated valid ids may be empty or otherwise unusual.
if (!entry || typeof entry.id !== "string") {
- throw malformedPreflightError();
- }
- if (typeof entry.allowed !== "boolean") throw malformedPreflightError();
- if (
- entry.description !== null &&
- entry.description !== undefined &&
- typeof entry.description !== "string"
- ) {
- throw malformedPreflightError();
+ throw malformedPreflightError(this.options.context);
}
+ if (typeof entry.allowed !== "boolean")
+ throw malformedPreflightError(this.options.context);
entries.push(entry);
}
@@ -212,7 +274,7 @@ class AppServerPreflightClient {
nextCursor.length === 0 ||
seenCursors.has(nextCursor)
) {
- throw malformedPreflightError();
+ throw malformedPreflightError(this.options.context);
}
seenCursors.add(nextCursor);
cursor = nextCursor;
@@ -254,7 +316,8 @@ class AppServerPreflightClient {
this.closed = true;
this.removeAbortListener();
this.pending?.reject(
- this.terminalError ?? codexExecutableStdioError(this.options.codexPath),
+ this.terminalError ??
+ codexExecutableStdioError(this.options.codexPath, this.options.context),
);
this.pending = undefined;
this.stopChild();
@@ -264,11 +327,20 @@ class AppServerPreflightClient {
private write(message: JsonRecord): void {
if (!this.child.stdin.writable) {
- this.fail(codexExecutableStdioError(this.options.codexPath));
+ this.fail(
+ codexExecutableStdioError(this.options.codexPath, this.options.context),
+ );
return;
}
this.child.stdin.write(`${JSON.stringify(message)}\n`, (error) => {
- if (error) this.fail(codexExecutableStdioError(this.options.codexPath));
+ if (error) {
+ const failure = codexExecutableStdioError(
+ this.options.codexPath,
+ this.options.context,
+ );
+ failure.message += "\n" + error.message;
+ this.fail(failure);
+ }
});
}
@@ -278,12 +350,12 @@ class AppServerPreflightClient {
try {
value = JSON.parse(line);
} catch {
- this.fail(malformedPreflightError());
+ this.fail(malformedPreflightError(this.options.context));
return;
}
const message = record(value);
if (!message) {
- this.fail(malformedPreflightError());
+ this.fail(malformedPreflightError(this.options.context));
return;
}
const id = message.id;
@@ -294,7 +366,7 @@ class AppServerPreflightClient {
}
const pending = this.pending;
if (!pending || pending.id !== id) {
- this.fail(malformedPreflightError());
+ this.fail(malformedPreflightError(this.options.context));
return;
}
this.pending = undefined;
@@ -304,13 +376,14 @@ class AppServerPreflightClient {
this.options.codexPath,
pending.method,
message.error,
+ this.options.context,
),
);
return;
}
const result = record(message.result);
if (!result) {
- pending.reject(malformedPreflightError());
+ pending.reject(malformedPreflightError(this.options.context));
return;
}
pending.resolve(result);
@@ -340,8 +413,8 @@ function verifyPreflightResult(
): void {
if (catalogEntry.allowed !== true) {
throw existingAllowlistExcludesProfile(requirementsResponse)
- ? disallowedProfileAllowlistError()
- : managedPolicyRejectedError();
+ ? disallowedProfileAllowlistError(options.context)
+ : managedPolicyRejectedError(options.context);
}
const config = record(configResponse.config);
@@ -355,16 +428,16 @@ function verifyPreflightResult(
!actualProfile ||
typeof config.default_permissions !== "string"
)
- throw malformedPreflightError();
+ throw malformedPreflightError(options.context);
if (config.default_permissions !== DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID) {
- throw profileNotSelectedError();
+ throw profileNotSelectedError(options.context);
}
const expectedProfile = comparableProfile(options.expectedProfile);
const actualWithoutDescription = comparableProfile(actualProfile);
if (!isDeepStrictEqual(actualWithoutDescription, expectedProfile)) {
- throw profileCollisionError();
+ throw profileCollisionError(options.context);
}
}
@@ -390,18 +463,14 @@ function existingAllowlistExcludesProfile(
/**
* `config/read` serializes omitted TOML options as null. Drop only those null
* placeholders; every unexpected non-null field still participates in the
- * strict comparison. A display description is intentionally not security
- * relevant, but it must remain a string when present.
+ * strict comparison. A display description does not affect permissions.
*/
function comparableProfile(
value: Readonly<Record<string, unknown>>,
): JsonRecord {
- const normalized = stripNullObjectFields(value) as JsonRecord;
- const description = normalized.description;
- if (description !== undefined && typeof description !== "string") {
- throw malformedPreflightError();
- }
- const { description: _description, ...rest } = normalized;
+ const { description: _description, ...rest } = stripNullObjectFields(
+ value,
+ ) as JsonRecord;
return rest;
}
@@ -421,61 +490,52 @@ function stripNullObjectFields(value: unknown): unknown {
);
}
-function validateOptions(
- options: DeepScanPermissionProfilePreflightOptions,
-): void {
- if (
- !isNonEmptyString(options.codexPath) ||
- !isNonEmptyString(options.cwd) ||
- !Array.isArray(options.configOverrides) ||
- options.configOverrides.some((value) => !isNonEmptyString(value)) ||
- !record(options.expectedProfile) ||
- !options.signal ||
- typeof options.signal.addEventListener !== "function"
- ) {
- throw malformedPreflightError();
- }
- comparableProfile(options.expectedProfile);
-}
-
// Verified permission incompatibilities explicitly stop the scan. A failed
// transport attempt alone does not establish that the scan cannot proceed.
-function disallowedProfileAllowlistError(): DeepScanNonRetryableError {
+function disallowedProfileAllowlistError(
+ context?: "helper",
+): DeepScanNonRetryableError {
return new DeepScanNonRetryableError(
- `Deep Scan cannot safely start a read-only worker because organization policy does not allow the required \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile. Ask your Codex administrator to define this read-only stub in a normal config layer:\n\n[permissions.${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}]\nextends = ":read-only"\n\nand add this entry to your existing allowlist in requirements.toml:\n\n[allowed_permission_profiles]\n${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID} = true\n\nDeep Scan did not run.`,
+ `${subject(context)} cannot safely start a read-only worker because organization policy does not allow the required \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile. Ask your Codex administrator to define this read-only stub in a normal config layer:\n\n[permissions.${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}]\nextends = ":read-only"\n\nand add this entry to your existing allowlist in requirements.toml:\n\n[allowed_permission_profiles]\n${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID} = true\n\n${subject(context)} did not run.`,
);
}
-function managedPolicyRejectedError(): DeepScanNonRetryableError {
+function managedPolicyRejectedError(
+ context?: "helper",
+): DeepScanNonRetryableError {
return new DeepScanNonRetryableError(
- `Deep Scan cannot safely start a read-only worker because managed Codex policy rejected the required \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile. Ask your Codex administrator to review the managed permission, sandbox, and filesystem requirements. Deep Scan did not run.`,
+ `${subject(context)} cannot safely start a read-only worker because managed Codex policy rejected the required \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile. Ask your Codex administrator to review the managed permission, sandbox, and filesystem requirements. ${subject(context)} did not run.`,
);
}
-function profileNotSelectedError(): DeepScanNonRetryableError {
+function profileNotSelectedError(
+ context?: "helper",
+): DeepScanNonRetryableError {
return new DeepScanNonRetryableError(
- `Deep Scan cannot safely start a read-only worker because Codex did not select the required \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile. Ask your Codex administrator to allow that profile for Deep Scan. Deep Scan did not run.`,
+ `${subject(context)} cannot safely start a read-only worker because Codex did not select the required \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile. Ask your Codex administrator to allow that profile for ${subject(context)}. ${subject(context)} did not run.`,
);
}
-function profileCollisionError(): DeepScanNonRetryableError {
+function profileCollisionError(context?: "helper"): DeepScanNonRetryableError {
return new DeepScanNonRetryableError(
- `Deep Scan cannot safely start a read-only worker because existing Codex configuration changes the reserved \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile. Ask your Codex administrator to keep the normal-config \`[permissions.${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}]\` stub limited to \`extends = ":read-only"\`; Deep Scan supplies its deny rules at runtime. Deep Scan did not run.`,
+ `${subject(context)} cannot safely start a read-only worker because existing Codex configuration changes the reserved \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile. Ask your Codex administrator to keep the normal-config \`[permissions.${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}]\` stub limited to \`extends = ":read-only"\`; ${subject(context)} supplies its deny rules at runtime. ${subject(context)} did not run.`,
);
}
-function malformedPreflightError(): Error {
+function malformedPreflightError(context?: "helper"): Error {
return new Error(
- "Deep Scan cannot safely verify its read-only worker permission profile with this Codex configuration. Deep Scan did not run.",
+ `${subject(context)} cannot safely verify its read-only worker permission profile with this Codex configuration. ${subject(context)} did not run.`,
);
}
function unsupportedCodexApiError(
codexPath: string,
api: string,
+ context?: "helper",
): DeepScanNonRetryableError {
return new DeepScanNonRetryableError(
- "Deep Scan cannot safely verify its read-only worker permission profile because " +
+ subject(context) +
+ " cannot safely verify its read-only worker permission profile because " +
"the selected Codex executable " +
JSON.stringify(codexPath) +
" does not support the required " +
@@ -483,7 +543,9 @@ function unsupportedCodexApiError(
" API. " +
"Update the Codex installation at that path " +
"(the desktop app if it is bundled, otherwise the selected CLI) and retry." +
- " Deep Scan did not run.",
+ " " +
+ subject(context) +
+ " did not run.",
);
}
@@ -491,25 +553,39 @@ function jsonRpcPreflightError(
codexPath: string,
method: string,
value: unknown,
+ context?: "helper",
): Error {
const error = record(value);
const code =
typeof error?.code === "number" && Number.isFinite(error.code)
? error.code
: undefined;
- if (code === -32601) return unsupportedCodexApiError(codexPath, method);
+ if (code === -32601) {
+ const failure = unsupportedCodexApiError(codexPath, method, context);
+ if (typeof error?.message === "string")
+ failure.message += "\n" + error.message;
+ return failure;
+ }
return new Error(
- "Deep Scan cannot safely verify its read-only worker permission profile because " +
+ subject(context) +
+ " cannot safely verify its read-only worker permission profile because " +
"the selected Codex executable " +
JSON.stringify(codexPath) +
" returned an error for " +
JSON.stringify(method) +
(code === undefined ? "" : " (JSON-RPC code " + code + ")") +
- ". Check the Codex configuration and retry. Deep Scan did not run.",
+ ". Check the Codex configuration and retry. " +
+ subject(context) +
+ " did not run." +
+ (typeof error?.message === "string" ? "\n" + error.message : ""),
);
}
-function codexExecutableStartError(codexPath: string, error: Error): Error {
+function codexExecutableStartError(
+ codexPath: string,
+ error: Error,
+ context?: "helper",
+): Error {
const value = "code" in error ? error.code : undefined;
const code =
typeof value === "string" && /^[A-Z0-9_]+$/u.test(value)
@@ -517,7 +593,13 @@ function codexExecutableStartError(codexPath: string, error: Error): Error {
: undefined;
const codeDetail = code === undefined ? "" : " (" + code + ")";
return new Error(
- codexExecutableFailureMessage(codexPath, "could not start" + codeDetail),
+ codexExecutableFailureMessage(
+ codexPath,
+ "could not start" + codeDetail,
+ context,
+ ) +
+ "\n" +
+ error.message,
{ cause: error },
);
}
@@ -526,6 +608,7 @@ function codexExecutableExitError(
codexPath: string,
code: number | null,
signal: NodeJS.Signals | null,
+ context?: "helper",
): Error {
const detail =
code !== null
@@ -535,14 +618,18 @@ function codexExecutableExitError(
? "was terminated before permission-profile verification completed by signal " +
signal
: "exited before permission-profile verification completed";
- return new Error(codexExecutableFailureMessage(codexPath, detail));
+ return new Error(codexExecutableFailureMessage(codexPath, detail, context));
}
-function codexExecutableStdioError(codexPath: string): Error {
+function codexExecutableStdioError(
+ codexPath: string,
+ context?: "helper",
+): Error {
return new Error(
codexExecutableFailureMessage(
codexPath,
"could not exchange app-server JSON-RPC over stdio",
+ context,
),
);
}
@@ -550,16 +637,20 @@ function codexExecutableStdioError(codexPath: string): Error {
function codexExecutableFailureMessage(
codexPath: string,
detail: string,
+ context?: "helper",
): string {
return (
- "Deep Scan cannot safely verify its read-only worker permission profile because " +
+ subject(context) +
+ " cannot safely verify its read-only worker permission profile because " +
"the selected Codex executable " +
JSON.stringify(codexPath) +
" " +
detail +
". " +
"Check that the named executable runs with --version, and check CODEX_CLI_PATH/PATH, then retry." +
- " Deep Scan did not run."
+ " " +
+ subject(context) +
+ " did not run."
);
}
@@ -573,19 +664,22 @@ export function deepScanPermissionProfileFallbackError(
message: unknown,
): DeepScanNonRetryableError | undefined {
if (typeof message !== "string") return undefined;
- const prefix =
- "Configured value for `permission_profile` is disallowed by requirements; " +
- `falling back from \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` to required value \``;
- const warning = message.trim();
- // The destination is an opaque quoted profile id. It can be empty and can
- // itself contain backticks or newlines, so only anchor the known source
- // prefix and the warning's terminal backtick-period.
- if (!warning.startsWith(prefix) || !warning.endsWith("`.")) return undefined;
+ if (
+ !isPermissionProfileFallbackWarning(
+ message,
+ DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID,
+ )
+ )
+ return undefined;
return new DeepScanNonRetryableError(
- `Deep Scan stopped a worker because organization policy rejected the required \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile after the turn started. The worker was stopped and its results were discarded. Ask your Codex administrator to define this read-only stub in a normal config layer:\n\n[permissions.${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}]\nextends = ":read-only"\n\nand add this entry to your existing allowlist in requirements.toml:\n\n[allowed_permission_profiles]\n${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID} = true`,
+ `Deep Scan stopped a worker because organization policy rejected the required \`${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}\` permission profile after the turn started. The worker was stopped and its results were discarded. Ask your Codex administrator to define this read-only stub in a normal config layer:\n\n[permissions.${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID}]\nextends = ":read-only"\n\nand add this entry to your existing allowlist in requirements.toml:\n\n[allowed_permission_profiles]\n${DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID} = true\n${message}`,
);
}
+function subject(context?: "helper"): string {
+ return context === "helper" ? "Read-only Codex helper" : "Deep Scan";
+}
+
function isAbortError(error: unknown): boolean {
return error instanceof Error && error.name === "AbortError";
}
diff --git a/plugins/codex-security/mcp-app/src/python_command.ts b/plugins/codex-security/mcp-app/src/python_command.ts
index 76bba7fec..9d44e05d8 100644
--- a/plugins/codex-security/mcp-app/src/python_command.ts
+++ b/plugins/codex-security/mcp-app/src/python_command.ts
@@ -5,6 +5,7 @@ import path from "node:path";
type PythonPlatform = NodeJS.Platform;
interface ResolvePythonCommandOptions {
+ cacheDirectory?: string;
configuredPython?: string;
homeDirectory?: string;
isUsableExecutable?: (candidate: string) => Promise<boolean>;
@@ -28,9 +29,11 @@ export async function resolvePythonCommand(
const platform = options.platform ?? process.platform;
const pathImplementation = platform === "win32" ? path.win32 : path.posix;
+ const cacheDirectory =
+ (options.cacheDirectory ?? process.env.XDG_CACHE_HOME) ||
+ pathImplementation.join(options.homeDirectory ?? homedir(), ".cache");
const bundledPythonRoot = pathImplementation.join(
- options.homeDirectory ?? homedir(),
- ".cache",
+ cacheDirectory,
"codex-runtimes",
"codex-primary-runtime",
"dependencies",
diff --git a/plugins/codex-security/mcp-app/tests/test_codex_profile.ts b/plugins/codex-security/mcp-app/tests/test_codex_profile.ts
new file mode 100644
index 000000000..10167a3da
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/test_codex_profile.ts
@@ -0,0 +1,485 @@
+import assert from "node:assert/strict";
+import childProcess, { type SpawnOptions } from "node:child_process";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { syncBuiltinESMExports } from "node:module";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { mock, test } from "node:test";
+import { pathToFileURL } from "node:url";
+import type { ThreadEvent } from "@openai/codex-sdk";
+import { parse as parseToml } from "smol-toml";
+import {
+ createCodexProfileClient,
+ preflightProviderDefinitions,
+ profileConfigOverrides,
+} from "../../scripts/codex_profile.mjs";
+
+test("native startup provider metadata preserves identity and auth without private configuration", () => {
+ const providers = {
+ "custom.provider": {
+ name: "Synthetic managed provider",
+ wire_api: "responses",
+ requires_openai_auth: false,
+ base_url: "https://synthetic-provider.example.test/v1",
+ http_headers: { Authorization: "synthetic-private-header" },
+ env_http_headers: { Authorization: "SYNTHETIC_PRIVATE_ENV" },
+ env_key: "SYNTHETIC_PRIVATE_KEY",
+ experimental_bearer_token: "synthetic-private-token",
+ auth: { env: { SYNTHETIC_PRIVATE_SECRET: "synthetic-secret-value" } },
+ },
+ "account-provider": {
+ name: "Synthetic account provider",
+ requires_openai_auth: true,
+ },
+ "default-auth-provider": {
+ name: "Synthetic default auth provider",
+ wire_api: "responses",
+ },
+ "amazon-bedrock": { aws: { region: "us-east-1" } },
+ };
+ const before = structuredClone(providers);
+ assert.deepEqual(preflightProviderDefinitions(providers), {
+ "custom.provider": {
+ name: "Synthetic managed provider",
+ wire_api: "responses",
+ requires_openai_auth: false,
+ },
+ "account-provider": {
+ name: "Synthetic account provider",
+ requires_openai_auth: true,
+ },
+ "default-auth-provider": {
+ name: "Synthetic default auth provider",
+ wire_api: "responses",
+ },
+ "amazon-bedrock": {},
+ });
+ assert.deepEqual(providers, before);
+});
+
+test("native overrides preserve literal paths, prototype keys, and TOML control escapes", () => {
+ const profile = {
+ extends: ":read-only",
+ filesystem: Object.fromEntries([
+ ["/synthetic/.env\u007f", { ".": "deny" }],
+ [String.raw`C:\Users\synthetic\credentials`, { ".": "deny" }],
+ ["__proto__", "deny"],
+ ]),
+ network: { enabled: false },
+ };
+ const overrides = profileConfigOverrides({
+ "permissions.synthetic_worker": profile,
+ model_instructions_file: "/synthetic/instructions\u007f.md",
+ }).join("\n");
+ assert.equal(overrides.includes("\u007f"), false);
+ assert.deepEqual(JSON.parse(JSON.stringify(parseToml(overrides))), {
+ permissions: { synthetic_worker: profile },
+ model_instructions_file: "/synthetic/instructions\u007f.md",
+ });
+});
+
+async function fixture(mode = "success") {
+ const directory = await mkdtemp(path.join(tmpdir(), "codex-profile-test-"));
+ const script = path.join(directory, "native-fixture.mjs");
+ const marker = path.join(directory, "marker.json");
+ await writeFile(
+ script,
+ String.raw`
+ import { readFile, writeFile } from "node:fs/promises";
+ let input = "";
+ for await (const chunk of process.stdin) input += chunk;
+ const args = process.argv.slice(1);
+ const schemaPath = args[args.indexOf("--output-schema") + 1];
+ await writeFile(process.env.PROFILE_TEST_MARKER, JSON.stringify({
+ args, input, pid: process.pid,
+ schemaPath: args.includes("--output-schema") ? schemaPath : null,
+ schema: args.includes("--output-schema") ? JSON.parse(await readFile(schemaPath, "utf8")) : null,
+ environment: {
+ CODEX_HOME: process.env.CODEX_HOME,
+ CODEX_API_KEY: process.env.CODEX_API_KEY,
+ CODEX_INTERNAL_ORIGINATOR_OVERRIDE: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE,
+ PROFILE_CLIENT_SHOULD_NOT_LEAK: process.env.PROFILE_CLIENT_SHOULD_NOT_LEAK,
+ },
+ }));
+ const emit = (event) => process.stdout.write(JSON.stringify(event) + "\n");
+ if (process.env.PROFILE_TEST_MODE === "error") {
+ process.stderr.write("synthetic token=fixture-secret: upstream diagnostic\n");
+ process.exit(3);
+ }
+ if (process.env.PROFILE_TEST_MODE === "malformed") {
+ process.stdout.write("synthetic malformed token=fixture-secret\n");
+ process.exit(0);
+ }
+ emit({ type: "thread.started", thread_id: args.includes("resume") ? args[args.indexOf("resume") + 1] : "fixture-thread", native_field: "preserved" });
+ if (process.env.PROFILE_TEST_MODE === "turn_failed") {
+ emit({ type: "turn.failed", error: { message: "synthetic token=fixture-secret: upstream turn failure" } });
+ process.exit(0);
+ } else if (process.env.PROFILE_TEST_MODE === "wait") {
+ setInterval(() => {}, 1000);
+ await new Promise(() => {});
+ } else if (process.env.PROFILE_TEST_MODE.startsWith("fallback_")) {
+ emit({ type: "item.completed", item: { type: "agent_message", id: "discarded-item", text: "discarded synthetic response" } });
+ const message = "Configured value for \u0060permission_profile\u0060 is disallowed by requirements; falling back from \u0060synthetic_read_only\u0060 to required value \u0060:workspace\u0060.";
+ emit(process.env.PROFILE_TEST_MODE === "fallback_item"
+ ? { type: "item.completed", item: { type: "error", message } }
+ : { type: "error", message });
+ setInterval(() => {}, 1000);
+ await new Promise(() => {});
+ } else {
+ emit({ type: "item.completed", item: { type: "agent_message", id: "fixture-item", text: "synthetic token=fixture-secret" } });
+ const completion = { type: "turn.completed" };
+ if (process.env.PROFILE_TEST_MODE === "null_usage") completion.usage = null;
+ else if (process.env.PROFILE_TEST_MODE !== "missing_usage") completion.usage = { input_tokens: 2, cached_input_tokens: 1, output_tokens: 3, reasoning_output_tokens: 0, ...(args.includes("resume") ? { cache_write_input_tokens: 9 } : {}) };
+ emit(completion);
+ process.exit(0);
+ }
+ `,
+ );
+ const options = {
+ codexPathOverride: process.execPath,
+ profileName: "scan_fixture_1",
+ apiKey: "synthetic-api-key",
+ env: {
+ ...Object.fromEntries(
+ Object.entries(process.env).filter(([key]) =>
+ [
+ "PATH",
+ "Path",
+ "SystemRoot",
+ "WINDIR",
+ "HOME",
+ "USERPROFILE",
+ "TEMP",
+ "TMP",
+ ].includes(key),
+ ),
+ ),
+ NODE_OPTIONS: `--import=${pathToFileURL(script).href}`,
+ PROFILE_TEST_MARKER: marker,
+ PROFILE_TEST_MODE: mode,
+ CODEX_HOME: path.join(directory, "credential home"),
+ CODEX_API_KEY: "replaced-synthetic-key",
+ },
+ };
+ return {
+ directory,
+ options,
+ record: async () => JSON.parse(await readFile(marker, "utf8")),
+ cleanup: () => rm(directory, { recursive: true, force: true }),
+ };
+}
+
+test("native profile turns preserve settings, JSON events, schema cleanup, and resume identity", async () => {
+ const f = await fixture();
+ const previousEnvironment = process.env.PROFILE_CLIENT_SHOULD_NOT_LEAK;
+ process.env.PROFILE_CLIENT_SHOULD_NOT_LEAK = "synthetic-parent-only-value";
+ try {
+ const client = createCodexProfileClient<ThreadEvent>({
+ ...f.options,
+ baseUrl: "https://provider.example.test/v1",
+ config: {
+ features: { plugins: true },
+ empty: {},
+ values: [1, { "dotted.key": "value" }],
+ },
+ configOverrides: ["features.plugins=false"],
+ });
+ const thread = client.startThread({
+ model: "fixture-model",
+ threadSource: "sdk",
+ sandboxMode: "read-only",
+ workingDirectory: path.join(f.directory, "scan workspace"),
+ additionalDirectories: [path.join(f.directory, "extra workspace")],
+ skipGitRepoCheck: true,
+ modelReasoningEffort: "medium",
+ networkAccessEnabled: false,
+ webSearchMode: "cached",
+ approvalPolicy: "never",
+ });
+ const schema = {
+ type: "object",
+ properties: { answer: { type: "string" } },
+ };
+ const { events } = await thread.runStreamed("first synthetic prompt", {
+ outputSchema: schema,
+ cyberAccessProgram: "standard",
+ });
+ const received = [];
+ for await (const event of events) received.push(event);
+ assert.deepEqual(received[0], {
+ type: "thread.started",
+ thread_id: "fixture-thread",
+ native_field: "preserved",
+ });
+ assert.equal(thread.id, "fixture-thread");
+ assert.deepEqual(received.at(-1), {
+ type: "turn.completed",
+ usage: {
+ input_tokens: 2,
+ cached_input_tokens: 1,
+ cache_write_input_tokens: 0,
+ output_tokens: 3,
+ reasoning_output_tokens: 0,
+ },
+ });
+ const first = await f.record();
+ assert.equal(path.basename(first.args[0]), "exec");
+ assert.deepEqual(first.args.slice(1), [
+ "--experimental-json",
+ "--profile",
+ "scan_fixture_1",
+ "--config",
+ "features={plugins = true}",
+ "--config",
+ "empty={}",
+ "--config",
+ 'values=[1, {"dotted.key" = "value"}]',
+ "--config",
+ "features.plugins=false",
+ "--config",
+ 'openai_base_url="https://provider.example.test/v1"',
+ "--model",
+ "fixture-model",
+ "--thread-source",
+ "sdk",
+ "--sandbox",
+ "read-only",
+ "--cd",
+ path.join(f.directory, "scan workspace"),
+ "--add-dir",
+ path.join(f.directory, "extra workspace"),
+ "--skip-git-repo-check",
+ "--output-schema",
+ first.schemaPath,
+ "--cyber-access-program",
+ "standard",
+ "--config",
+ 'model_reasoning_effort="medium"',
+ "--config",
+ "sandbox_workspace_write.network_access=false",
+ "--config",
+ 'web_search="cached"',
+ "--config",
+ 'approval_policy="never"',
+ ]);
+ assert.equal(first.input, "first synthetic prompt");
+ assert.deepEqual(first.schema, schema);
+ assert.deepEqual(first.environment, {
+ CODEX_HOME: f.options.env.CODEX_HOME,
+ CODEX_API_KEY: "synthetic-api-key",
+ CODEX_INTERNAL_ORIGINATOR_OVERRIDE: "codex_sdk_ts",
+ });
+ assert.ok(!first.args.join(" ").includes("synthetic-api-key"));
+ await assert.rejects(readFile(first.schemaPath), { code: "ENOENT" });
+ const result = await thread.run("second synthetic prompt");
+ assert.equal(result.finalResponse, "synthetic token=fixture-secret");
+ assert.equal(result.items.length, 1);
+ assert.equal(result.usage?.cache_write_input_tokens, 9);
+ const second = await f.record();
+ assert.ok(!second.args.includes("--thread-source"));
+ assert.deepEqual(second.args.slice(-2), ["resume", "fixture-thread"]);
+ const resumed = client.resumeThread("existing-fixture", {
+ webSearchEnabled: false,
+ });
+ await resumed.run("resumed synthetic prompt");
+ const third = await f.record();
+ assert.deepEqual(third.args.slice(-4), [
+ "--config",
+ 'web_search="disabled"',
+ "resume",
+ "existing-fixture",
+ ]);
+ assert.equal(resumed.id, "existing-fixture");
+ } finally {
+ if (previousEnvironment === undefined)
+ delete process.env.PROFILE_CLIENT_SHOULD_NOT_LEAK;
+ else process.env.PROFILE_CLIENT_SHOULD_NOT_LEAK = previousEnvironment;
+ await f.cleanup();
+ }
+});
+
+test("native profile children hide Windows console windows", async () => {
+ const f = await fixture();
+ const originalSpawn = childProcess.spawn;
+ let launched = false;
+ childProcess.spawn = ((
+ command: string,
+ args: readonly string[],
+ options: SpawnOptions,
+ ) => {
+ launched = true;
+ assert.equal(options?.windowsHide, true);
+ return originalSpawn(command, args, options);
+ }) as typeof childProcess.spawn;
+ syncBuiltinESMExports();
+ try {
+ await createCodexProfileClient(f.options)
+ .startThread()
+ .run("synthetic prompt");
+ assert.equal(launched, true);
+ } finally {
+ childProcess.spawn = originalSpawn;
+ syncBuiltinESMExports();
+ await f.cleanup();
+ }
+});
+
+for (const mode of ["null_usage", "missing_usage"]) {
+ for (const resumed of [false, true]) {
+ for (const streamed of [false, true]) {
+ test(`native profile ${resumed ? "resumed" : "fresh"} ${streamed ? "streamed" : "collected"} turns preserve ${mode}`, async () => {
+ const f = await fixture(mode);
+ try {
+ const client = createCodexProfileClient(f.options);
+ const thread = resumed
+ ? client.resumeThread("existing-fixture")
+ : client.startThread();
+ const turnOptions = { outputSchema: { type: "object" } };
+ if (streamed) {
+ const { events } = await thread.runStreamed(
+ "synthetic prompt",
+ turnOptions,
+ );
+ const received = [];
+ for await (const event of events) received.push(event);
+ assert.equal(received.length, 3);
+ assert.deepEqual(received.at(-1), {
+ type: "turn.completed",
+ ...(mode === "null_usage" ? { usage: null } : {}),
+ });
+ } else {
+ const result = await thread.run("synthetic prompt", turnOptions);
+ assert.equal(
+ result.finalResponse,
+ "synthetic token=fixture-secret",
+ );
+ assert.equal(result.items.length, 1);
+ assert.equal(
+ result.usage,
+ mode === "null_usage" ? null : undefined,
+ );
+ }
+ assert.equal(
+ thread.id,
+ resumed ? "existing-fixture" : "fixture-thread",
+ );
+ const record = await f.record();
+ assert.equal(record.args.includes("resume"), resumed);
+ await assert.rejects(readFile(record.schemaPath), { code: "ENOENT" });
+ } finally {
+ await f.cleanup();
+ }
+ });
+ }
+ }
+}
+
+test("native profile failures preserve upstream diagnostics and remove schema files", async () => {
+ for (const mode of ["error", "malformed", "turn_failed"]) {
+ const f = await fixture(mode);
+ try {
+ const thread = createCodexProfileClient(f.options).startThread();
+ await assert.rejects(
+ thread.run("synthetic prompt", { outputSchema: { type: "object" } }),
+ mode === "error"
+ ? /code 3: synthetic token=fixture-secret: upstream diagnostic/
+ : mode === "malformed"
+ ? /Failed to parse item: synthetic malformed token=fixture-secret/
+ : /synthetic token=fixture-secret: upstream turn failure/,
+ );
+ const record = await f.record();
+ await assert.rejects(readFile(record.schemaPath), { code: "ENOENT" });
+ } finally {
+ await f.cleanup();
+ }
+ }
+});
+
+function captureChildClose() {
+ let closed: Promise<void> | undefined;
+ const originalSpawn = childProcess.spawn;
+ const spawnSpy = mock.method(
+ childProcess,
+ "spawn",
+ (command: string, args: readonly string[], options: SpawnOptions) => {
+ const child = originalSpawn(command, args, options);
+ closed = new Promise((resolve) => child.once("close", () => resolve()));
+ return child;
+ },
+ );
+ syncBuiltinESMExports();
+ return {
+ wait: () => {
+ assert.ok(closed);
+ return closed;
+ },
+ restore: () => {
+ spawnSpy.mock.restore();
+ syncBuiltinESMExports();
+ },
+ };
+}
+
+test("native profile abort and abandoned streams close the actual child", async () => {
+ for (const abort of [true, false]) {
+ const f = await fixture("wait");
+ const childClose = captureChildClose();
+ try {
+ const controller = new AbortController();
+ const thread = createCodexProfileClient(f.options).startThread();
+ const { events } = await thread.runStreamed("synthetic prompt", {
+ signal: controller.signal,
+ });
+ assert.equal((await events.next()).value.type, "thread.started");
+ const record = await f.record();
+ if (abort) {
+ controller.abort();
+ await assert.rejects(events.next(), { name: "AbortError" });
+ } else {
+ await events.return(undefined);
+ }
+ await childClose.wait();
+ assert.throws(() => process.kill(record.pid, 0), { code: "ESRCH" });
+ } finally {
+ childClose.restore();
+ await f.cleanup();
+ }
+ }
+});
+
+test("a late native permission fallback discards the turn and closes the actual child", async () => {
+ for (const mode of ["fallback_item", "fallback_event"]) {
+ const f = await fixture(mode);
+ const childClose = captureChildClose();
+ try {
+ const thread = createCodexProfileClient({
+ ...f.options,
+ requestedPermissionProfile: "synthetic_read_only",
+ }).startThread();
+ await assert.rejects(
+ thread.run("synthetic prompt", { outputSchema: { type: "object" } }),
+ /results were discarded[\s\S]*falling back from `synthetic_read_only` to required value `:workspace`\./,
+ );
+ const record = await f.record();
+ await childClose.wait();
+ assert.throws(() => process.kill(record.pid, 0), { code: "ESRCH" });
+ await assert.rejects(readFile(record.schemaPath), { code: "ENOENT" });
+ } finally {
+ childClose.restore();
+ await f.cleanup();
+ }
+ }
+});
+
+test("native profile launch failures do not hang the stream", async () => {
+ const f = await fixture();
+ try {
+ const thread = createCodexProfileClient({
+ ...f.options,
+ codexPathOverride: path.join(f.directory, "missing-native"),
+ }).startThread();
+ await assert.rejects(thread.run("synthetic prompt"), { code: "ENOENT" });
+ } finally {
+ await f.cleanup();
+ }
+});
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 e2b5d74bd..c58b8ba70 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
@@ -2,6 +2,7 @@ import { readJson, writeJson } from "./support/json.ts";
import { assertFlagPair } from "./assertions.ts";
import { createTemporaryDirectories } from "./support/temporary-directories.ts";
import { mock } from "node:test";
+import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import assert from "node:assert/strict";
import childProcess, {
spawnSync,
@@ -18,7 +19,7 @@ import {
utimes,
writeFile,
} from "node:fs/promises";
-import { syncBuiltinESMExports } from "node:module";
+import { createRequire, syncBuiltinESMExports } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { importModule } from "./import-module.ts";
@@ -91,7 +92,9 @@ try {
testCodeModeFrameDiagnosticBoundaries();
await testOpenAiCredentialsReachWorker();
await testWorkerRuntimeSettings();
+ await testUnsupportedProviderSnapshotFailsBeforeLaunch();
await testWorkerCyberAccessSettings();
+ await testCompletedWorkerSettlesWithoutWaitingForProcessExit();
if (process.platform !== "win32") {
await testMissingParentSandboxFailsBeforeWorkerLaunch();
await testDisallowedWorkerProfileFailsBeforeWorkerLaunch();
@@ -108,7 +111,6 @@ try {
await testOwnedArtifactToolFailureDiagnosticIsSanitized();
await testCodeModeFrameDiagnosticSurvivesSuccessfulTurn();
await testStreamTerminationWithoutTerminalEventFails();
- await testCompletedWorkerSettlesWithoutWaitingForProcessExit();
await testAbortPropagation();
await testUnstructuredConfigurationFailureRemainsRetryable();
await testUnstructuredThreadStartFailureRemainsRetryable();
@@ -903,9 +905,19 @@ async function testSdkInvocationAndThreadCapture() {
"mcp_servers.codex-security.enabled": false,
});
assertReadOnlyWorkerPolicy(invocation.argv);
- assert.equal(
- workerPermissionProfileOverride(invocation.argv),
- 'permissions.codex_security_deep_scan_worker={extends=":read-only",filesystem={":root"="read","/repo/.env"="deny","/repo/**/.secret"="deny","/repo/**/*.pem"="deny",glob_scan_max_depth=3},network={enabled=false}}',
+ assert.deepEqual(
+ JSON.parse(
+ JSON.stringify(
+ parseToml(workerPermissionProfileOverride(invocation.argv))
+ .permissions,
+ ),
+ ),
+ { codex_security_deep_scan_worker: deniedWorkerPermissionProfile },
+ );
+ const preflight = await readJson(fixture.preflightMarkerPath);
+ assert.deepEqual(
+ nativeConfigOverrides(preflight.argv),
+ nativeConfigOverrides(invocation.argv),
);
assertWorkerSubagentPolicy(invocation.argv, 3);
assertFlagPair(invocation.argv, "--cd", workingDirectory);
@@ -934,7 +946,22 @@ async function testOpenAiCredentialsReachWorker() {
);
assert.equal(created.status, 0, created.stderr);
}
- const cases = [
+ const sdkRequire = createRequire(import.meta.resolve("@openai/codex-sdk"));
+ const nativeLauncher = path.join(
+ path.dirname(sdkRequire.resolve("@openai/codex/package.json")),
+ "bin",
+ "codex.js",
+ );
+ const cases: {
+ openai?: string;
+ codex?: string;
+ expected?: string;
+ accountResult?: {
+ account: { type: string } | null;
+ requiresOpenaiAuth: boolean;
+ };
+ nativeProvider?: string;
+ }[] = [
{ openai: "synthetic-openai-key", expected: "synthetic-openai-key" },
{
openai: " synthetic-openai-key ",
@@ -959,6 +986,15 @@ async function testOpenAiCredentialsReachWorker() {
openai: "synthetic-provider-key",
accountResult: { account: null, requiresOpenaiAuth: false },
},
+ {
+ openai: "synthetic-openai-key",
+ nativeProvider: "synthetic.gateway",
+ },
+ {
+ openai: "synthetic-openai-key",
+ nativeProvider: "openai",
+ expected: "synthetic-openai-key",
+ },
{},
{ openai: " " },
];
@@ -1003,19 +1039,60 @@ async function testOpenAiCredentialsReachWorker() {
process.env.CODEX_CLI_PATH = process.execPath;
process.env.CODEX_HOME = fixture.root;
Object.assign(process.env, runtimeEnvironment);
+ if (entry.nativeProvider !== undefined) {
+ await writeFile(
+ path.join(fixture.root, "config.toml"),
+ `model_provider = ${JSON.stringify(entry.nativeProvider)}
+cli_auth_credentials_store = "file"
+[features]
+plugins = false
+api_key_model_discovery = false
+[model_providers."synthetic.gateway"]
+name = "Synthetic gateway"
+wire_api = "responses"
+base_url = "https://provider.example.test/v1"
+requires_openai_auth = false
+env_key = "CODEX_API_KEY"
+`,
+ );
+ }
+ let nativePreflight:
+ | {
+ codexHome: string | undefined;
+ argv: readonly string[];
+ runnerTrackingId: string | undefined;
+ libraryPath: string | undefined;
+ }
+ | undefined;
childProcess.spawn = ((
command: string,
args: readonly string[],
options: SpawnOptions,
- ) =>
- originalSpawn(
- command,
+ ) => {
+ const nodeExecutable =
command === process.execPath ||
- command === path.toNamespacedPath(process.execPath)
- ? [fixture.executablePath, ...args]
- : args,
+ command === path.toNamespacedPath(process.execPath);
+ // Keep real account/config selection, while the existing fake exec
+ // observes credentials without starting a model turn.
+ if (
+ nodeExecutable &&
+ entry.nativeProvider !== undefined &&
+ args.includes("app-server")
+ ) {
+ nativePreflight = {
+ codexHome: options.env?.CODEX_HOME,
+ runnerTrackingId: options.env?.RUNNER_TRACKING_ID,
+ libraryPath: options.env?.LD_LIBRARY_PATH,
+ argv: args,
+ };
+ return originalSpawn(command, [nativeLauncher, ...args], options);
+ }
+ return originalSpawn(
+ command,
+ nodeExecutable ? [fixture.executablePath, ...args] : args,
options,
- )) as typeof childProcess.spawn;
+ );
+ }) as typeof childProcess.spawn;
syncBuiltinESMExports();
const promptPath = path.join(fixture.root, "prompt.md");
await writeFile(
@@ -1030,7 +1107,10 @@ async function testOpenAiCredentialsReachWorker() {
await executor.run(
workerRequest(promptPath, fixture.root, { kind, resumeThreadId }),
);
- const preflight = await readJson(fixture.preflightMarkerPath);
+ const preflight =
+ entry.nativeProvider === undefined
+ ? await readJson(fixture.preflightMarkerPath)
+ : nativePreflight!;
const invocation = await readJson(fixture.markerPath);
assert.equal(preflight.codexHome, fixture.root);
assert.equal(
@@ -1067,6 +1147,10 @@ async function testOpenAiCredentialsReachWorker() {
invocation.argv.some((arg: string) => arg.includes("synthetic-")),
false,
);
+ assert.equal(
+ preflight.argv.some((arg: string) => arg.includes("synthetic-")),
+ false,
+ );
}
}
} finally {
@@ -1077,8 +1161,81 @@ async function testOpenAiCredentialsReachWorker() {
}
}
+async function testUnsupportedProviderSnapshotFailsBeforeLaunch() {
+ const fixture = await fakeCodexFixture();
+ const configPath = path.join(fixture.root, "config.toml");
+ const deepPath = path.join(fixture.root, "deep.toml");
+ const promptPath = path.join(fixture.root, "prompt.md");
+ await writeFile(configPath, "");
+ await writeFile(promptPath, "synthetic provider upgrade fixture");
+ await writeFile(
+ deepPath,
+ stringifyToml({
+ worker_runtime: {
+ model_provider: "synthetic.gateway",
+ model_providers: {
+ "synthetic.gateway": {
+ name: "Synthetic gateway",
+ env_key: "SYNTHETIC_GATEWAY_KEY",
+ },
+ },
+ },
+ }),
+ );
+ const saved = [
+ "CODEX_SECURITY_CONFIG_PATH",
+ "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
+ ].map((name) => [name, process.env[name]] as const);
+ try {
+ process.env.CODEX_SECURITY_CONFIG_PATH = configPath;
+ process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH = deepPath;
+ await assert.rejects(
+ new CodexSdkWorkerExecutor({ parentSandbox: trustedParentSandbox }).run({
+ kind: "discovery",
+ promptPath,
+ workingDirectory: fixture.root,
+ subagents: 0,
+ signal: new AbortController().signal,
+ }),
+ (error: Error) =>
+ error.name === "DeepScanNonRetryableError" &&
+ error.message.includes("Update the SDK and bundled plugin together"),
+ );
+ await assert.rejects(
+ readFile(fixture.preflightMarkerPath),
+ (error: NodeJS.ErrnoException) => error.code === "ENOENT",
+ );
+ for (const nativeProfile of ["../outside", "C:\\outside", "", "scan\n"]) {
+ await writeFile(
+ deepPath,
+ stringifyToml({ worker_runtime: { native_profile: nativeProfile } }),
+ );
+ await assert.rejects(
+ new CodexSdkWorkerExecutor({ parentSandbox: trustedParentSandbox }).run(
+ {
+ kind: "discovery",
+ promptPath,
+ workingDirectory: fixture.root,
+ subagents: 0,
+ signal: new AbortController().signal,
+ },
+ ),
+ (error: Error) =>
+ error.name === "DeepScanNonRetryableError" &&
+ error.message.includes("invalid --profile value"),
+ );
+ }
+ await assert.rejects(
+ readFile(fixture.preflightMarkerPath),
+ (error: NodeJS.ErrnoException) => error.code === "ENOENT",
+ );
+ } finally {
+ for (const [name, value] of saved) restoreEnv(name, value);
+ }
+}
+
async function testWorkerRuntimeSettings() {
- const cases = [
+ const cases: [string, string | undefined][] = [
["", undefined],
['model_reasoning_summary = "none"\n', "none"],
['model_reasoning_summary = "auto"\n', "auto"],
@@ -1100,15 +1257,20 @@ async function testWorkerRuntimeSettings() {
"CODEX_CLI_PATH",
"CODEX_HOME",
"CODEX_SECURITY_CONFIG_PATH",
+ "CODEX_SECURITY_PLUGIN_ROOT",
"CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
"OPENAI_API_KEY",
"CODEX_API_KEY",
"SYNTHETIC_GATEWAY_KEY",
+ "SYNTHETIC_HEADER_VALUE",
+ "XDG_CACHE_HOME",
].map((name) => [name, process.env[name]] as const);
const originalSpawn = childProcess.spawn;
try {
delete process.env.OPENAI_API_KEY;
delete process.env.CODEX_API_KEY;
+ delete process.env.SYNTHETIC_GATEWAY_KEY;
+ delete process.env.SYNTHETIC_HEADER_VALUE;
for (const [configuration, expected] of cases) {
const fixture = await fakeCodexFixture(
deniedWorkerPermissionProfile,
@@ -1130,8 +1292,11 @@ async function testWorkerRuntimeSettings() {
GIT_CONFIG_GLOBAL: path.join(fixture.root, "operator.gitconfig"),
};
Object.assign(process.env, gitEnvironment);
- const configPath = path.join(fixture.root, "active scan config.toml");
- const codexHome = path.join(fixture.root, "scan home");
+ const configPath = path.join(fixture.root, "active [scan] config.toml");
+ const codexHome = path.join(
+ fixture.root,
+ process.platform === "win32" ? "scan [home]" : "scan [home] ",
+ );
const promptPath = path.join(fixture.root, "prompt.md");
await mkdir(codexHome);
await writeFile(
@@ -1145,14 +1310,189 @@ base_url = "https://gateway.example.test/v1"
wire_api = "responses"
env_key = "SYNTHETIC_GATEWAY_KEY"`,
);
- await writeFile(configPath, configuration!);
+ const settings = [
+ { model: "gpt-5.6-sol", reasoningEffort: "xhigh" },
+ { model: "gpt-6-astra", reasoningEffort: "ultra" },
+ { model: "gpt-6.1-sol", reasoningEffort: "max" },
+ { model: "gpt-6-sol", reasoningEffort: "high" },
+ { model: "fixture-future-model", reasoningEffort: "future-effort" },
+ // Omitted settings preserve the model and effort in the Codex home.
+ {},
+ ];
+ const providerKeys = settings.map((_, index) =>
+ index === 0 ? undefined : ` synthetic-gateway-key-${index} `,
+ );
+ const providerHeaders = settings.map((_, index) =>
+ index === 0 ? undefined : ` synthetic-header-${index}\t`,
+ );
+ const workerConfigurations = Array.from(
+ { length: settings.length },
+ (_, index) => {
+ const parsedConfiguration = parseToml(configuration);
+ const profiles = (parsedConfiguration.profiles ?? {}) as Record<
+ string,
+ Record<string, unknown>
+ >;
+ const serviceTier =
+ index === 0 ? undefined : index === 3 ? "flex" : "fast";
+ const instructionsFile =
+ index === 0
+ ? undefined
+ : path.join(fixture.root, `instructions ${index}.md`);
+ const verbosity = [undefined, "low", "medium", "high"][index];
+ const windowsSandbox =
+ index === 0
+ ? undefined
+ : index % 2 === 0
+ ? "unelevated"
+ : "elevated";
+ const webSearch =
+ index === 0 ? undefined : ["disabled", "cached", "live"][index % 3];
+ const features =
+ index === 0
+ ? undefined
+ : {
+ shell_tool: index % 2 === 0,
+ unified_exec: false,
+ view_image: index % 2 !== 0,
+ multi_agent_v2: {
+ enabled: true,
+ max_concurrent_threads_per_session: index + 2,
+ },
+ enable_fanout: true,
+ };
+ const entryPath = `${configPath}.${index}`;
+ const deepPath = `${entryPath}.deep`;
+ const nativeProfile =
+ index === 0 ? undefined : `synthetic-scan-${index}`;
+ const profilePath =
+ nativeProfile === undefined
+ ? undefined
+ : path.join(codexHome, `${nativeProfile}.config.toml`);
+ const parentSandbox = {
+ filesystemDenies: [
+ ...trustedParentSandboxWithDenials.filesystemDenies,
+ ],
+ literalFilesystemDenies: [deepPath, codexHome],
+ globScanMaxDepth: trustedParentSandboxWithDenials.globScanMaxDepth,
+ };
+ const provider = index === 0 ? undefined : "synthetic.gateway";
+ const providerConfig =
+ index === 0
+ ? undefined
+ : {
+ name: `Synthetic gateway ${index}`,
+ base_url: `https://gateway-${index}.example.test/v1`,
+ wire_api: "responses",
+ env_key: "SYNTHETIC_GATEWAY_KEY",
+ env_http_headers: { "X-Synthetic": "SYNTHETIC_HEADER_VALUE" },
+ ...(index === 3 ? {} : { requires_openai_auth: index === 2 }),
+ experimental_bearer_token: `synthetic-bearer-${index}`,
+ auth: {
+ type: "command",
+ command: "synthetic-auth",
+ cwd: path.join(codexHome, `helpers ${index}`),
+ args: [String(index)],
+ env: { CLIENT_SECRET: `synthetic-client-secret-${index}` },
+ },
+ };
+ return {
+ path: entryPath,
+ deepPath,
+ nativeProfile,
+ profilePath,
+ parentSandbox,
+ permissionProfile: {
+ ...deniedWorkerPermissionProfile,
+ filesystem: {
+ ...deniedWorkerPermissionProfile.filesystem,
+ [deepPath]: { ".": "deny" },
+ [codexHome]: { ".": "deny" },
+ },
+ },
+ provider,
+ providerConfig,
+ environment:
+ index === 0
+ ? undefined
+ : {
+ SYNTHETIC_GATEWAY_KEY: providerKeys[index],
+ SYNTHETIC_HEADER_VALUE: providerHeaders[index],
+ },
+ serviceTier,
+ instructionsFile,
+ verbosity,
+ windowsSandbox,
+ webSearch,
+ features,
+ configuration: {
+ ...parsedConfiguration,
+ ...(index === 0
+ ? {}
+ : { service_tier: index === 2 ? "flex" : serviceTier }),
+ ...(index === 2 || index === 3
+ ? {
+ profile: "selected",
+ profiles: {
+ ...profiles,
+ selected: {
+ ...profiles.selected,
+ ...(index === 2 ? { service_tier: serviceTier } : {}),
+ },
+ unselected: { service_tier: "fast" },
+ },
+ }
+ : {}),
+ ...(provider === undefined ? {} : { model_provider: provider }),
+ },
+ };
+ },
+ );
+ await Promise.all(
+ workerConfigurations.map((entry) =>
+ Promise.all([
+ writeFile(entry.path, stringifyToml(entry.configuration)),
+ writeFile(
+ entry.deepPath,
+ stringifyToml({
+ worker_runtime:
+ entry.provider === undefined
+ ? {}
+ : {
+ model_instructions_file: entry.instructionsFile,
+ model_verbosity: entry.verbosity,
+ web_search: entry.webSearch,
+ model_provider: entry.provider,
+ native_profile: entry.nativeProfile,
+ environment: entry.environment,
+ windows: { sandbox: entry.windowsSandbox },
+ features: entry.features,
+ },
+ }),
+ ),
+ ...(entry.profilePath === undefined
+ ? []
+ : [
+ writeFile(
+ entry.profilePath,
+ stringifyToml({
+ model_provider: entry.provider,
+ model_providers: {
+ [entry.provider!]: entry.providerConfig,
+ },
+ }),
+ ),
+ ]),
+ ]),
+ ),
+ );
await writeFile(promptPath, "synthetic worker configuration fixture");
process.env.CODEX_CLI_PATH = process.execPath;
process.env.CODEX_HOME = codexHome;
process.env.CODEX_SECURITY_CONFIG_PATH = configPath;
- process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH = path.join(
+ process.env.CODEX_SECURITY_PLUGIN_ROOT = path.join(
fixture.root,
- "deep settings.toml",
+ "ambient-plugin",
);
const launches: {
command?: string;
@@ -1173,6 +1513,11 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
...options!.env,
FAKE_CODEX_MARKER: markerPath,
FAKE_CODEX_PREFLIGHT_MARKER: markerPath,
+ FAKE_CODEX_PREFLIGHT_PROFILE: JSON.stringify(
+ workerConfigurations.find(
+ (entry) => entry.path === options.env?.CODEX_SECURITY_CONFIG_PATH,
+ )!.permissionProfile,
+ ),
};
launches.push({ command, args, environment, markerPath });
return originalSpawn(
@@ -1185,25 +1530,13 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
);
}) as typeof childProcess.spawn;
syncBuiltinESMExports();
- const settings = [
- { model: "gpt-5.6-sol", reasoningEffort: "xhigh" },
- { model: "gpt-6-astra", reasoningEffort: "ultra" },
- { model: "gpt-6.1-sol", reasoningEffort: "max" },
- { model: "gpt-6-sol", reasoningEffort: "high" },
- { model: "fixture-future-model", reasoningEffort: "future-effort" },
- // Omitted settings preserve the model and effort in the Codex home.
- {},
- ];
- const providerKeys = settings.map((_, index) =>
- index < 2 ? `synthetic-gateway-key-${index}` : undefined,
- );
const executors = settings.map(
- (modelSettings) =>
+ (modelSettings, index) =>
new CodexSdkWorkerExecutor({
...modelSettings,
- parentSandbox: trustedParentSandboxWithDenials,
+ parentSandbox: workerConfigurations[index].parentSandbox,
artifactContext: {
- pluginRoot: fixture.root,
+ pluginRoot: path.join(fixture.root, `plugin-${index}`),
repoRoot: fixture.root,
scanId: `fixture-scan-${modelSettings.model ?? "inherited"}`,
pythonCommand: helperPython,
@@ -1217,11 +1550,14 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
await Promise.all(
executors.map((executor, index) => {
// Each concurrent launch snapshots its own scan environment.
- if (providerKeys[index] === undefined) {
- delete process.env.SYNTHETIC_GATEWAY_KEY;
- } else {
- process.env.SYNTHETIC_GATEWAY_KEY = providerKeys[index];
- }
+ process.env.CODEX_SECURITY_CONFIG_PATH =
+ workerConfigurations[index].path;
+ process.env.XDG_CACHE_HOME = path.join(
+ fixture.root,
+ `cache-${index}`,
+ );
+ process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH =
+ workerConfigurations[index].deepPath;
return executor.run(
workerRequest(promptPath, fixture.root, {
kind,
@@ -1270,28 +1606,50 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
workerLaunch.environment!.CODEX_HOME,
await realpath(codexHome),
);
+ assert.equal(
+ workerLaunch.environment!.CODEX_SECURITY_PLUGIN_ROOT,
+ path.join(fixture.root, "ambient-plugin"),
+ );
assert.equal(
workerLaunch.environment!.CODEX_SECURITY_CONFIG_PATH,
- configPath!,
+ workerConfigurations[index].path,
);
assert.equal(
workerLaunch.environment!.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,
- process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,
+ workerConfigurations[index].deepPath,
);
- assert.equal(
- workerPermissionProfileOverride(workerLaunch.args),
- 'permissions.codex_security_deep_scan_worker={extends=":read-only",filesystem={":root"="read","/repo/.env"="deny","/repo/**/.secret"="deny","/repo/**/*.pem"="deny",glob_scan_max_depth=3},network={enabled=false}}',
+ assert.deepEqual(
+ JSON.parse(
+ JSON.stringify(
+ parseToml(workerPermissionProfileOverride(workerLaunch.args)!)
+ .permissions,
+ ),
+ ),
+ {
+ codex_security_deep_scan_worker:
+ workerConfigurations[index].permissionProfile,
+ },
);
const invocation = await readJson(workerLaunch.markerPath);
+ assert.equal(invocation.codexHome, await realpath(codexHome));
assert.equal(invocation.providerKey, providerKeys[index]);
+ assert.equal(invocation.providerHeader, providerHeaders[index]);
assert.equal(workerLaunch.environment!.CODEX_API_KEY, undefined);
- assert.equal(
- process.env.SYNTHETIC_GATEWAY_KEY,
- providerKeys.at(-1),
- );
+ assert.equal(process.env.SYNTHETIC_GATEWAY_KEY, undefined);
+ assert.equal(process.env.SYNTHETIC_HEADER_VALUE, undefined);
assertConfigOverrides(invocation.argv, {
model_reasoning_summary: expected,
+ service_tier: workerConfigurations[index].serviceTier,
+ model_instructions_file:
+ workerConfigurations[index].instructionsFile,
+ model_verbosity: workerConfigurations[index].verbosity,
+ web_search: workerConfigurations[index].webSearch,
+ "windows.sandbox": workerConfigurations[index].windowsSandbox,
});
+ assert.equal(
+ invocation.cacheDirectory,
+ path.join(fixture.root, `cache-${index}`),
+ );
assert.deepEqual(
invocation.argv.filter((arg: string) =>
arg.startsWith("model_reasoning_effort="),
@@ -1309,7 +1667,58 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
invocation.argv.includes("resume"),
resumeThreadId !== undefined,
);
- assert.equal(invocation.configPath, configPath);
+ assert.equal(
+ invocation.configPath,
+ workerConfigurations[index].path,
+ );
+ const selectedProvider = workerConfigurations[index];
+ if (selectedProvider.provider === undefined) {
+ assert.equal(
+ invocation.argv.some(
+ (arg: string) =>
+ arg.startsWith("model_provider=") ||
+ arg.startsWith("model_providers="),
+ ),
+ false,
+ );
+ } else {
+ assert.ok(
+ invocation.argv.includes(
+ `model_provider=${JSON.stringify(selectedProvider.provider)}`,
+ ),
+ );
+ }
+ if (
+ selectedProvider.provider !== undefined &&
+ selectedProvider.providerConfig
+ ) {
+ assertFlagPair(
+ invocation.argv,
+ "--profile",
+ selectedProvider.nativeProfile!,
+ );
+ assert.deepEqual(
+ JSON.parse(
+ JSON.stringify(
+ parseToml(invocation.profileContents).model_providers,
+ ),
+ ),
+ {
+ [selectedProvider.provider]: selectedProvider.providerConfig,
+ },
+ );
+ }
+ assert.equal(
+ invocation.argv.some(
+ (arg: string) =>
+ arg.startsWith("model_providers=") ||
+ arg.includes("synthetic-gateway-key-") ||
+ arg.includes("synthetic-header-") ||
+ arg.includes("synthetic-bearer-") ||
+ arg.includes("synthetic-client-secret-"),
+ ),
+ false,
+ );
assert.deepEqual(invocation.gitEnvironment, gitEnvironment);
for (const [name, value] of Object.entries(gitEnvironment)) {
assert.equal(process.env[name], value);
@@ -1318,12 +1727,35 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
assertConfigOverrides(invocation.argv, {
"mcp_servers.cs_artifacts.env.CODEX_SECURITY_PYTHON_COMMAND":
helperPython,
+ "mcp_servers.cs_artifacts.args.0": path.join(
+ fixture.root,
+ `plugin-${index}`,
+ "mcp",
+ "server.mjs",
+ ),
+ "mcp_servers.cs_artifacts.env.CODEX_SECURITY_PLUGIN_ROOT":
+ path.join(fixture.root, `plugin-${index}`),
+ "mcp_servers.cs_artifacts.env.CODEX_SECURITY_ARTIFACT_LAYOUT":
+ kind === "dedup" ? "reducer" : "worker",
});
assert.equal(process.env.PYTHON, python);
assert.equal(
invocation.deepConfigPath,
- process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH,
+ workerConfigurations[index].deepPath,
);
+ const workerFeatures = parseToml(
+ invocation.argv
+ .filter((arg: string) => /^features[.=]/.test(arg))
+ .join("\n"),
+ ).features;
+ assert.deepEqual(JSON.parse(JSON.stringify(workerFeatures)), {
+ ...workerConfigurations[index].features,
+ multi_agent_v2: {
+ enabled: false,
+ max_concurrent_threads_per_session: 1,
+ },
+ enable_fanout: false,
+ });
assertReadOnlyWorkerPolicy(invocation.argv);
assertWorkerSubagentPolicy(invocation.argv, 0);
}
@@ -1332,12 +1764,108 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
)) {
const preflight = await readJson(launch.markerPath);
assert.deepEqual(preflight.gitEnvironment, gitEnvironment);
+ const selectedProvider = workerConfigurations.find(
+ (entry) => preflight.configPath === entry.path,
+ );
+ assert.ok(
+ selectedProvider,
+ "worker preflight must use the same scan environment",
+ );
+ assert.equal(
+ preflight.providerKey,
+ selectedProvider.environment?.SYNTHETIC_GATEWAY_KEY,
+ );
assert.equal(
- workerPermissionProfileOverride(launch.args),
- workerPermissionProfileOverride(workerLaunches[0].args),
+ preflight.providerHeader,
+ selectedProvider.environment?.SYNTHETIC_HEADER_VALUE,
+ );
+ assertConfigOverrides(preflight.argv, {
+ model_instructions_file: selectedProvider.instructionsFile,
+ model_verbosity: selectedProvider.verbosity,
+ web_search: selectedProvider.webSearch,
+ "windows.sandbox": selectedProvider.windowsSandbox,
+ });
+ assert.equal(
+ preflight.cacheDirectory,
+ path.join(
+ fixture.root,
+ `cache-${workerConfigurations.indexOf(selectedProvider)}`,
+ ),
+ );
+ assert.deepEqual(
+ preflight.argv.filter((arg: string) =>
+ arg.startsWith("model_provider="),
+ ),
+ selectedProvider.provider === undefined
+ ? []
+ : [
+ `model_provider=${JSON.stringify(selectedProvider.provider)}`,
+ ],
+ );
+ const providerOverrides = preflight.argv.filter((arg: string) =>
+ arg.startsWith("model_providers="),
+ );
+ const provider = selectedProvider.providerConfig;
+ assert.equal(
+ providerOverrides.length,
+ provider === undefined ? 0 : 1,
+ );
+ if (provider !== undefined) {
+ assert.deepEqual(
+ JSON.parse(
+ JSON.stringify(
+ parseToml(providerOverrides[0]).model_providers,
+ ),
+ ),
+ {
+ [selectedProvider.provider!]: {
+ name: provider.name,
+ wire_api: "responses",
+ ...(provider.requires_openai_auth === undefined
+ ? {}
+ : {
+ requires_openai_auth: provider.requires_openai_auth,
+ }),
+ },
+ },
+ );
+ }
+ assert.equal(
+ preflight.argv.some(
+ (arg: string) =>
+ arg.includes("synthetic-gateway-key-") ||
+ arg.includes("synthetic-header-") ||
+ arg.includes("synthetic-bearer-") ||
+ arg.includes("synthetic-client-secret-"),
+ ),
+ false,
+ );
+ const execution = workerLaunches.find(
+ (worker) =>
+ worker.environment!.CODEX_SECURITY_CONFIG_PATH ===
+ selectedProvider.path,
+ )!;
+ assert.deepEqual(
+ nativeConfigOverrides(launch.args).filter(
+ (override) => !override.startsWith("model_providers="),
+ ),
+ nativeConfigOverrides(execution.args),
);
}
- await writeFile(configPath, 'model_reasoning_summary = "detailed"\n');
+ await Promise.all(
+ workerConfigurations.map((entry) =>
+ Promise.all([
+ writeFile(
+ entry.path,
+ 'model_reasoning_summary = "detailed"\nservice_tier = "changed"\nmodel_provider = "changed"\n',
+ ),
+ writeFile(
+ entry.deepPath,
+ '[worker_runtime.features]\nshell_tool = true\nunified_exec = true\nview_image = true\n[worker_runtime]\nweb_search = "live"\nmodel_provider = "changed"\nnative_profile = "changed"\nmodel_instructions_file = "changed-instructions.md"\nmodel_verbosity = "changed"\n[worker_runtime.windows]\nsandbox = "changed"\n[worker_runtime.environment]\nSYNTHETIC_GATEWAY_KEY = "changed"\nSYNTHETIC_HEADER_VALUE = "changed"\n',
+ ),
+ ]),
+ ),
+ );
}
}
}
@@ -1486,19 +2014,12 @@ async function testWorkerCyberAccessSettings() {
} else {
assertFlagPair(invocation.argv, "--cyber-access-program", program);
}
- for (const feature of [
- "api_key_cyber_access_programs",
- "api_key_model_discovery",
- ]) {
- assert.deepEqual(
- invocation.argv.filter((arg: string) =>
- arg.startsWith(`features.${feature}=`),
- ),
- features[feature] === undefined
- ? []
- : [`features.${feature}=${features[feature]}`],
- );
- }
+ assertConfigOverrides(invocation.argv, {
+ "features.api_key_cyber_access_programs":
+ features.api_key_cyber_access_programs,
+ "features.api_key_model_discovery":
+ features.api_key_model_discovery,
+ });
assert.equal(
invocation.openaiAuthentication.CODEX_API_KEY,
"synthetic-worker-api-key",
@@ -1567,11 +2088,9 @@ async function testBedrockCredentialsReachWorker() {
invocation.argv.includes("resume"),
resumeThreadId !== undefined,
);
- assert.ok(
- invocation.argv.some((arg: string) =>
- arg.includes("mcp_servers.codex-security.enabled=false"),
- ),
- );
+ assertConfigOverrides(invocation.argv, {
+ "mcp_servers.codex-security.enabled": false,
+ });
}
}
} finally {
@@ -1853,9 +2372,61 @@ async function testAbortPropagation() {
}
async function testCompletedWorkerSettlesWithoutWaitingForProcessExit() {
+ await completedWorkerSettlesWithoutWaitingForProcessExit();
+ for (const kind of ["discovery", "dedup"] as const) {
+ for (const resumed of [false, true]) {
+ await completedWorkerSettlesWithoutWaitingForProcessExit(kind, resumed);
+ }
+ }
+}
+
+async function completedWorkerSettlesWithoutWaitingForProcessExit(
+ kind?: DeepScanWorkerKind,
+ resumed = false,
+) {
const fixture = await fakeCodexFixture();
- const previousPath = process.env.CODEX_CLI_PATH;
- process.env.CODEX_CLI_PATH = fixture.executablePath;
+ const saved = [
+ "CODEX_CLI_PATH",
+ "CODEX_HOME",
+ "CODEX_SECURITY_CONFIG_PATH",
+ "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
+ ].map((name) => [name, process.env[name]] as const);
+ process.env.CODEX_CLI_PATH = process.execPath;
+ const originalSpawn = childProcess.spawn;
+ childProcess.spawn = ((
+ command: string,
+ args: readonly string[] = [],
+ options: SpawnOptions = {},
+ ) =>
+ originalSpawn(
+ command,
+ command === process.execPath ||
+ command === path.win32.toNamespacedPath(process.execPath)
+ ? [fixture.executablePath, ...args]
+ : args,
+ options,
+ )) as typeof childProcess.spawn;
+ syncBuiltinESMExports();
+ if (kind !== undefined) {
+ const home = path.join(fixture.root, "private profile home");
+ await mkdir(home);
+ const configPath = path.join(fixture.root, "preflight.toml");
+ const workerConfigPath = path.join(home, "deep-scan-config.toml");
+ await writeFile(configPath, "");
+ await writeFile(
+ workerConfigPath,
+ '[worker_runtime]\nnative_profile = "completion_fixture"\n',
+ );
+ await writeFile(
+ path.join(home, "completion_fixture.config.toml"),
+ 'model_provider = "openai"\n',
+ );
+ Object.assign(process.env, {
+ CODEX_HOME: home,
+ CODEX_SECURITY_CONFIG_PATH: configPath,
+ CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: workerConfigPath,
+ });
+ }
const controller = new AbortController();
const unexpectedErrors: unknown[] = [];
const captureUnexpectedError = (error: NodeJS.ErrnoException) =>
@@ -1869,15 +2440,24 @@ async function testCompletedWorkerSettlesWithoutWaitingForProcessExit() {
const promptPath = path.join(fixture.root, "prompt.md");
const workingDirectory = path.join(fixture.root, "artifacts");
await mkdir(workingDirectory);
- await writeFile(promptPath, "COMPLETE_THEN_HANG\n");
+ await writeFile(
+ promptPath,
+ kind === undefined
+ ? "COMPLETE_THEN_HANG\n"
+ : "COMPLETE_THEN_HANG_IGNORE_TERMINATION\n",
+ );
execution = new CodexSdkWorkerExecutor({
parentSandbox: trustedParentSandbox,
}).run({
- kind: "discovery",
+ kind: kind ?? "discovery",
promptPath,
workingDirectory,
subagents: 0,
signal: controller.signal,
+ ...(resumed ? { resumeThreadId: "fixture-resumed-thread-id" } : {}),
+ onThreadStarted: async () => {
+ childPid = (await readJson(fixture.markerPath)).pid;
+ },
});
const result = await Promise.race([
@@ -1892,25 +2472,34 @@ async function testCompletedWorkerSettlesWithoutWaitingForProcessExit() {
}),
]);
clearTimeout(timeout);
- assert.equal(result.threadId, "fixture-thread-id");
- childPid = (await readJson(fixture.markerPath)).pid;
+ assert.equal(
+ result.threadId,
+ resumed ? "fixture-resumed-thread-id" : "fixture-thread-id",
+ );
+ const invocation = await readJson(fixture.markerPath);
+ assert.equal(invocation.argv.includes("--profile"), kind !== undefined);
+ assert.equal(invocation.argv.includes("resume"), resumed);
controller.abort("coordinator immediately canceled its remaining workers");
await new Promise((resolve) => setTimeout(resolve, 250));
assert.deepEqual(unexpectedErrors, []);
- assert.throws(() => process.kill(childPid, 0), { code: "ESRCH" });
+ if (kind === undefined) {
+ assert.throws(() => process.kill(childPid, 0), { code: "ESRCH" });
+ }
} finally {
clearTimeout(timeout);
controller.abort("completed worker fixture cleanup");
- await execution?.catch(() => {});
if (childPid) {
try {
process.kill(childPid, "SIGKILL");
} catch {}
}
+ await execution?.catch(() => {});
process.removeListener("uncaughtException", captureUnexpectedError);
- restoreEnv("CODEX_CLI_PATH", previousPath);
+ childProcess.spawn = originalSpawn;
+ syncBuiltinESMExports();
+ for (const [name, value] of saved) restoreEnv(name, value);
}
}
@@ -2145,14 +2734,15 @@ async function fakeCodexFixture(
await writeFile(
scriptPath,
`#!/usr/bin/env node
-import { writeFileSync } from "node:fs";
+import { readFileSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
-const preflightProfile = ${JSON.stringify(preflightProfile)};
+import { join } from "node:path";
+const preflightProfile = process.env.FAKE_CODEX_PREFLIGHT_PROFILE ? JSON.parse(process.env.FAKE_CODEX_PREFLIGHT_PROFILE) : ${JSON.stringify(preflightProfile)};
const preflightAllowed = ${JSON.stringify(preflightAllowed)};
const accountResult = ${JSON.stringify(accountResult)};
const preflightMarkerPath = process.env.FAKE_CODEX_PREFLIGHT_MARKER ?? ${JSON.stringify(preflightMarkerPath)};
if (process.argv.includes('app-server')) {
- const preflight = { cwd: process.cwd(), codexHome: process.env.CODEX_HOME, runnerTrackingId: process.env.RUNNER_TRACKING_ID, libraryPath: process.env.LD_LIBRARY_PATH, 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, 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));
let buffer = '';
process.stdin.setEncoding('utf8');
@@ -2191,14 +2781,16 @@ if (process.argv.includes('app-server')) {
process.stdin.on('end', () => process.exit(0));
} else {
const stdin = (await process.stdin.toArray()).join('');
+const profileIndex = process.argv.indexOf('--profile');
+const profileContents = profileIndex === -1 ? undefined : readFileSync(join(process.env.CODEX_HOME, process.argv[profileIndex + 1] + '.config.toml'), 'utf8');
const openaiAuthentication = stdin.includes('CAPTURE_SYNTHETIC_OPENAI_AUTH') ? { OPENAI_API_KEY: process.env.OPENAI_API_KEY, CODEX_API_KEY: process.env.CODEX_API_KEY } : undefined;
const bedrockAuthentication = stdin.includes('CAPTURE_SYNTHETIC_BEDROCK_AUTH') ? Object.fromEntries(JSON.parse(process.env.FAKE_CODEX_BEDROCK_ENV_KEYS).map((name) => [name, process.env[name]])) : undefined;
const runtimeEnvironment = Object.fromEntries(['PATH', 'HOME', 'PYTHON', 'PYTHONUTF8', 'LD_LIBRARY_PATH', 'CODEX_SECURITY_STATE_DIR', 'RUNNER_TRACKING_ID'].map(name => [name, process.env[name]]));
const pythonProbe = stdin.includes('CAPTURE_SYNTHETIC_PYTHON') ? spawnSync(process.env.PYTHON, ['-I', '-c', 'import json,os,sys; print(json.dumps([sys.prefix,os.environ.get("LD_LIBRARY_PATH")]))'], { encoding: 'utf8' }) : undefined;
if (pythonProbe && pythonProbe.status !== 0) throw new Error(pythonProbe.stderr || String(pythonProbe.error));
const pythonRuntime = pythonProbe ? JSON.parse(pythonProbe.stdout) : undefined;
-writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ argv: process.argv.slice(2), stdin, cwd: process.cwd(), codexHome: process.env.CODEX_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, pythonPrefix: pythonRuntime?.[0], pythonLibraryPath: pythonRuntime?.[1], runtimeEnvironment, providerKey: process.env.SYNTHETIC_GATEWAY_KEY, originator: process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE, ...(stdin.includes('COMPLETE_THEN_HANG') ? { pid: process.pid } : {}), ...(openaiAuthentication ? { openaiAuthentication } : {}), ...(bedrockAuthentication ? { bedrockAuthentication } : {}) }));
-if (stdin.includes('COMPLETE_THEN_HANG')) process.on('SIGTERM', () => setTimeout(() => process.exit(0), 100));
+writeFileSync(process.env.FAKE_CODEX_MARKER, JSON.stringify({ argv: process.argv.slice(2), stdin, cwd: process.cwd(), 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, 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); }
if (stdin.includes('CONFIG_ERROR')) { console.error('failed to load configuration: invalid value'); process.exit(2); }
if (stdin.includes('MCP_STARTUP_TIMEOUT') || stdin.includes('CATALOG_AUTH_ONLY') || stdin.includes('SYNC_AUTH_ONLY')) {
@@ -2268,9 +2860,11 @@ function assertReadOnlyWorkerPolicy(args: readonly string[]) {
false,
);
const override = workerPermissionProfileOverride(args);
- assert.equal(override.includes('extends=":read-only"'), true);
- assert.equal(override.includes('":root"="read"'), true);
- assert.equal(override.includes("network={enabled=false}"), true);
+ assertConfigOverrides(args, {
+ "permissions.codex_security_deep_scan_worker.extends": ":read-only",
+ "permissions.codex_security_deep_scan_worker.filesystem.:root": "read",
+ "permissions.codex_security_deep_scan_worker.network.enabled": false,
+ });
assert.equal(override.includes('"write"'), false);
}
@@ -2314,19 +2908,34 @@ function restoreEnv(name: string, value: string | undefined) {
else process.env[name] = value;
}
+function nativeConfigOverrides(args: readonly string[]) {
+ return args.flatMap((arg, index) =>
+ arg === "--config" || arg === "-c" ? [args[index + 1]] : [],
+ );
+}
+
function assertConfigOverrides(
args: readonly string[],
values: Record<string, string | number | boolean | undefined>,
) {
+ const overrides = nativeConfigOverrides(args).map((value) =>
+ parseToml(value),
+ );
for (const [key, value] of Object.entries(values)) {
- if (value === undefined) {
- assert.equal(
- args.some((arg) => arg.startsWith(`${key}=`)),
- false,
- );
- } else {
- assert.equal(args.includes(`${key}=${JSON.stringify(value)}`), true);
- }
+ const supplied = overrides.map((config) =>
+ key
+ .split(".")
+ .reduce<unknown>(
+ (current, part) =>
+ (current as Record<string, unknown> | undefined)?.[part],
+ config,
+ ),
+ );
+ assert.deepEqual(
+ supplied.findLast((item) => item !== undefined),
+ value,
+ key,
+ );
}
}
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.ts
index 2ce33a5e3..388c753cb 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
@@ -97,6 +97,38 @@ assert.deepEqual(
},
);
+const literalPaths = ["/repo/*.env", "/repo/?.env", "/repo/[literal]"];
+assert.deepEqual(
+ resolveDeepWorkerParentSandbox(
+ restricted([
+ rootRead,
+ ...literalPaths.map((deniedPath, index) => ({
+ path: {
+ type: index === 0 ? "generated_default_path" : "path",
+ path: deniedPath,
+ },
+ access: index === 0 ? "none" : "deny",
+ })),
+ ]),
+ ),
+ { filesystemDenies: [], literalFilesystemDenies: literalPaths },
+);
+
+const collidingDenies = [
+ { path: { type: "glob_pattern", pattern: "/repo/[ab]" }, access: "deny" },
+ { path: { type: "path", path: "/repo/[ab]" }, access: "none" },
+];
+for (const entries of [collidingDenies, [...collidingDenies].reverse()]) {
+ assert.throws(
+ () => resolveDeepWorkerParentSandbox(restricted([rootRead, ...entries])),
+ (error: Error) =>
+ error.name === "DeepScanNonRetryableError" &&
+ /literal path and glob denials with the same key cannot be preserved/i.test(
+ error.message,
+ ),
+ );
+}
+
assert.throws(
() =>
resolveDeepWorkerParentSandbox(
@@ -168,8 +200,6 @@ for (const invalid of [
extra(null),
extra({ ...pinnedReadOnly, type: "external" }),
extra({ ...pinnedReadOnly, type: "disabled" }),
- extra({ ...pinnedReadOnly, network: "unknown" }),
- extra({ ...pinnedReadOnly, network: { enabled: true } }),
extra({ ...pinnedReadOnly, file_system: null }),
extra({ ...pinnedReadOnly, file_system: { type: "unknown" } }),
restricted("not-an-array"),
@@ -203,13 +233,7 @@ for (const invalid of [
missing_path_behavior: "skip",
},
]),
- ...[
- "",
- "relative/private",
- "/repo/*.env",
- "/repo/?.env",
- "/repo/[literal]",
- ].map((deniedPath) =>
+ ...["", "relative/private"].map((deniedPath) =>
restricted([
rootRead,
{ path: { type: "path", path: deniedPath }, access: "deny" },
@@ -231,8 +255,6 @@ for (const invalid of [
},
]),
restricted([{ path: { type: "path", path: "" }, access: "read" }]),
- extra(pinnedReadOnly, "relative/working-directory"),
- extra(pinnedReadOnly, "file://remote-host/tmp/codex-security-parent"),
{
_meta: extra(pinnedReadOnly)._meta,
requestInfo: extra({ ...pinnedReadOnly, network: "enabled" }),
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts
index 2ca93a845..d6d69f9dc 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_permission_profile_preflight.ts
@@ -33,6 +33,7 @@ const {
DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID: profileId,
deepScanPermissionProfileFallbackError,
preflightDeepScanWorkerPermissionProfile,
+ readDeepScanRuntimeConfig,
} = await importSource(
path.join(
import.meta.dirname,
@@ -73,7 +74,7 @@ await testMalformedAndUnsupportedResponsesFailClosed();
await testEarlyExecutableExitIsNotVersionError();
await testUnexpectedTerminationRemainsRetryable();
await testStdioFailuresRemainRetryable();
-await testUnknownJsonRpcFailuresRemainRetryableAndSafe();
+await testUnknownJsonRpcFailuresPreserveNativeDiagnostics();
await testRuntimeFallbackWarningClassification();
await testSpawnErrorFailsClosed();
await testMissingWorkerDirectoryRemainsRetryable();
@@ -109,13 +110,29 @@ async function testAllowedProfileAndRawArgv() {
],
},
async ({ codexPath, cwd, argvPath, callsPath }) => {
- await preflight(codexPath, cwd);
+ await preflightDeepScanWorkerPermissionProfile({
+ codexPath,
+ cwd,
+ configOverrides: [
+ ...rawOverrides,
+ 'model_provider="synthetic.gateway"',
+ ],
+ providerConfigOverrides: [
+ 'model_providers={"synthetic.gateway"={name="Synthetic gateway",wire_api="responses",requires_openai_auth=false}}',
+ ],
+ expectedProfile,
+ signal: new AbortController().signal,
+ });
assert.deepEqual(await readJson(argvPath), [
"--config",
rawOverrides[0],
"--config",
rawOverrides[1],
+ "--config",
+ 'model_provider="synthetic.gateway"',
+ "--config",
+ 'model_providers={"synthetic.gateway"={name="Synthetic gateway",wire_api="responses",requires_openai_auth=false}}',
"app-server",
"--stdio",
]);
@@ -344,7 +361,7 @@ async function testDisallowedProfileGivesAdminGuidance() {
error.message.includes("existing allowlist") &&
error.message.includes(`${profileId} = true`) &&
error.message.includes("Deep Scan did not run.") &&
- !error.message.includes("SECRET_REPOSITORY_PATH"),
+ error.message.includes("SECRET_REPOSITORY_PATH"),
);
const calls = await readJsonLines(callsPath);
assert.deepEqual(
@@ -582,7 +599,7 @@ async function testStdioFailuresRemainRetryable() {
error.message.includes(
"could not exchange app-server JSON-RPC over stdio",
) &&
- !error.message.includes("SECRET_REPOSITORY_PATH"),
+ error.message.includes("SECRET_REPOSITORY_PATH"),
);
await assertPreflightStopped(children, terminatedPath);
},
@@ -590,7 +607,7 @@ async function testStdioFailuresRemainRetryable() {
}
}
-async function testUnknownJsonRpcFailuresRemainRetryableAndSafe() {
+async function testUnknownJsonRpcFailuresPreserveNativeDiagnostics() {
for (const code of [-32603, -32602, -32000, undefined]) {
await withFakeCodex(
{
@@ -611,7 +628,7 @@ async function testUnknownJsonRpcFailuresRemainRetryableAndSafe() {
(code === undefined
? !error.message.includes("JSON-RPC code")
: error.message.includes(`JSON-RPC code ${code}`)) &&
- !error.message.includes("SECRET_REPOSITORY_PATH") &&
+ error.message.includes("SECRET_REPOSITORY_PATH") &&
!error.message.includes("does not support"),
);
await assertPreflightStopped(children, terminatedPath);
@@ -652,6 +669,7 @@ async function testRuntimeFallbackWarningClassification() {
const warning = `Configured value for \`permission_profile\` is disallowed by requirements; falling back from \`${profileId}\` to required value \`enterprise-default\`.`;
const error = deepScanPermissionProfileFallbackError(warning);
assert.equal(error?.name, "DeepScanNonRetryableError");
+ assert.equal(error?.message.includes(warning), true);
assert.equal(
error?.message.includes(
"worker was stopped and its results were discarded",
@@ -684,29 +702,61 @@ async function testRuntimeFallbackWarningClassification() {
}
async function testAbortKillsPreflightChild() {
- await withFakeCodex(
- {
- hangAt: "config/read",
- },
- async ({ codexPath, cwd, readyPath, terminatedPath, children }) => {
- const controller = new AbortController();
- const running = preflightDeepScanWorkerPermissionProfile({
- codexPath,
- cwd,
- configOverrides: rawOverrides,
- expectedProfile,
- signal: controller.signal,
- });
- await waitForFile(readyPath);
- controller.abort(new DOMException("fixture aborted", "AbortError"));
- await assert.rejects(
- running,
- (error: NodeJS.ErrnoException & { cause?: NodeJS.ErrnoException }) =>
- error?.name === "AbortError",
- );
- await assertPreflightStopped(children, terminatedPath);
- },
- );
+ for (const run of [
+ preflightDeepScanWorkerPermissionProfile,
+ readDeepScanRuntimeConfig,
+ ]) {
+ for (const stderr of ["", "synthetic native abort diagnostic\n"]) {
+ for (const reason of [
+ undefined,
+ new DOMException("fixture aborted", "AbortError"),
+ Object.assign(
+ new Error("fixture caller error", { cause: { fixture: true } }),
+ { code: "SYNTHETIC_CANCELED" },
+ ),
+ ]) {
+ await withFakeCodex(
+ { hangAt: "config/read", stderr },
+ async ({ codexPath, cwd, readyPath, terminatedPath, children }) => {
+ const controller = new AbortController();
+ const running = run({
+ codexPath,
+ cwd,
+ configOverrides: rawOverrides,
+ expectedProfile,
+ signal: controller.signal,
+ });
+ if (stderr) {
+ await new Promise<void>((resolve) => {
+ children[0].stderr!.once("data", () => resolve());
+ });
+ }
+ await waitForFile(readyPath);
+ controller.abort(reason);
+ const aborted = controller.signal.reason;
+ const expected = {
+ message: aborted.message + (stderr ? "\n" + stderr : ""),
+ name: aborted.name,
+ code: aborted.code,
+ cause: aborted.cause,
+ };
+ await assert.rejects(running, (error: Error) => {
+ assert.equal(error, aborted);
+ assert.equal(error.name, expected.name);
+ assert.equal(error.message, expected.message);
+ assert.equal(
+ (error as NodeJS.ErrnoException).code,
+ expected.code,
+ );
+ assert.equal(error.cause, expected.cause);
+ return true;
+ });
+ await assertPreflightStopped(children, terminatedPath);
+ },
+ );
+ }
+ }
+ }
}
async function assertPreflightStopped(
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
index beb79f0d4..1a2a27397 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_stdio_lifecycle.ts
@@ -4,10 +4,12 @@ import { assertNoError, assertFlagPair } from "./assertions.ts";
import { readOnlyParentSandboxState } from "./sandbox-state.ts";
import { temporaryDirectory } from "./support/temporary-directories.ts";
import assert from "node:assert/strict";
+import { parse as parseToml } from "smol-toml";
import { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
import {
chmod,
+ cp,
mkdir,
readFile,
realpath,
@@ -26,7 +28,7 @@ const execFileAsync = promisify(execFile);
const pluginRoot = path.resolve(mcpAppRoot, "..");
const workbenchPath = path.join(pluginRoot, "scripts", "workbench_db.py");
-const parentSandboxState = readOnlyParentSandboxState(pluginRoot);
+let parentSandboxState: unknown = readOnlyParentSandboxState(pluginRoot);
if (process.platform === "win32") {
console.log(
@@ -41,7 +43,8 @@ async function testDeepScanStdioLifecycle() {
const targetPath = path.join(fixtureRoot, "target");
const failedTargetPath = path.join(fixtureRoot, "failed-target");
const stateDir = path.join(fixtureRoot, "state");
- const codexHome = path.join(fixtureRoot, "codex-home");
+ const codexHome = path.join(fixtureRoot, "codex [home]");
+ const installedPluginRoot = path.join(codexHome, "plugins", "installed");
const runtimeConfigPath = path.join(fixtureRoot, "active-config.toml");
const startLogPath = path.join(fixtureRoot, "fake-codex-started.jsonl");
const exitLogPath = path.join(fixtureRoot, "fake-codex-exited.jsonl");
@@ -60,8 +63,12 @@ async function testDeepScanStdioLifecycle() {
"fail-next-cancel-scan",
);
const cancelLogPath = path.join(fixtureRoot, "cancel-scan-calls.jsonl");
+ const workbenchLaunchLogPath = path.join(
+ fixtureRoot,
+ "workbench-launches.jsonl",
+ );
const serverBundlePath = path.join(
- pluginRoot,
+ installedPluginRoot,
"mcp",
`.deep-scan-stdio-test-${randomUUID()}.cjs`,
);
@@ -70,6 +77,32 @@ async function testDeepScanStdioLifecycle() {
await mkdir(targetPath, { recursive: true });
await mkdir(failedTargetPath, { recursive: true });
await mkdir(path.join(codexHome, "codex-security"), { recursive: true });
+ for (const directory of [
+ "scripts",
+ "references",
+ "schemas",
+ ".codex-plugin",
+ ]) {
+ await cp(
+ path.join(pluginRoot, directory),
+ path.join(installedPluginRoot, directory),
+ { recursive: true },
+ );
+ }
+ const parentSandbox = readOnlyParentSandboxState(pluginRoot);
+ parentSandboxState = {
+ ...parentSandbox,
+ permissionProfile: {
+ ...parentSandbox.permissionProfile,
+ file_system: {
+ ...parentSandbox.permissionProfile.file_system,
+ entries: [
+ ...parentSandbox.permissionProfile.file_system.entries,
+ { path: { type: "path", path: codexHome }, access: "deny" },
+ ],
+ },
+ },
+ };
await writeFile(path.join(targetPath, "fixture.py"), "print('fixture')\n");
await writeFile(
path.join(failedTargetPath, "fixture.py"),
@@ -103,16 +136,19 @@ model_reasoning_summary = "none"
CODEX_CLI_PATH: fakeCodexPath,
CODEX_HOME: codexHome,
CODEX_SECURITY_CONFIG_PATH: runtimeConfigPath,
+ CODEX_SECURITY_PLUGIN_ROOT: pluginRoot,
CODEX_SECURITY_SCAN_ROOT: path.join(fixtureRoot, "scans"),
CODEX_SECURITY_STATE_DIR: stateDir,
PYTHON: pythonWrapperPath,
REAL_PYTHON: process.env.PYTHON?.trim() || "python3",
FAKE_WORKBENCH_CANCEL_FAILURE_CONTROL: cancelFailureControlPath,
FAKE_WORKBENCH_CANCEL_LOG: cancelLogPath,
+ FAKE_WORKBENCH_LAUNCH_LOG: workbenchLaunchLogPath,
FAKE_CODEX_EXIT_LOG: exitLogPath,
FAKE_CODEX_RESTART_CONTROL: restartControlPath,
FAKE_CODEX_SIGNAL_CHECKPOINT_CONTROL: signalCheckpointControlPath,
FAKE_CODEX_START_LOG: startLogPath,
+ FAKE_CODEX_DENIED_HOME: codexHome,
};
const server = startServer(serverBundlePath, environment);
@@ -205,7 +241,12 @@ model_reasoning_summary = "none"
(worker: PersistedDeepScanWorker) => worker.kind === "discovery",
)?.artifactDir;
assert.equal(typeof startedArtifactRoot, "string");
+ await writeFile(
+ path.join(installedPluginRoot, "scripts", "workbench_db.py"),
+ 'raise RuntimeError("Installed plugin helpers replaced during another scan")\n',
+ );
assert.equal(workerContext.pluginRoot, pluginRoot);
+ assert.equal(startedWorker.readCoreScanReference, true);
assert.equal(workerContext.targetPath, await realpath(targetPath));
assert.equal(workerContext.scope, ".");
assert.equal(workerContext.scanId, scanId);
@@ -237,14 +278,23 @@ model_reasoning_summary = "none"
startedWorker.argv.includes('model_reasoning_summary="none"'),
true,
);
- assertReadOnlyWorkerInvocation(startedWorker.argv);
- assert.equal(
- startedWorker.argv.includes(
- `mcp_servers.cs_artifacts.env.CODEX_SECURITY_PYTHON_COMMAND=${JSON.stringify(pythonWrapperPath)}`,
- ),
- true,
+ assertReadOnlyWorkerInvocation(startedWorker.argv, codexHome);
+ assertWorkerArtifactEnvironment(
+ startedWorker.argv,
+ pluginRoot,
+ pythonWrapperPath,
);
+ // Another client can replace this shared install while the scan is active.
+ await writeFile(
+ path.join(installedPluginRoot, "scripts", "workbench_db.py"),
+ "raise RuntimeError('synthetic replacement plugin helper')\n",
+ );
+ await rm(path.join(installedPluginRoot, "references"), {
+ recursive: true,
+ });
+ await rm(path.join(installedPluginRoot, "schemas"), { recursive: true });
+
// Discovery progress is admitted once the first complete Standard worker is active.
const discoveryProgress = await server.request(
15,
@@ -470,6 +520,7 @@ model_reasoning_summary = "none"
)?.artifactDir;
assert.equal(typeof failedArtifactRoot, "string");
assert.equal(failedWorkerContext.pluginRoot, pluginRoot);
+ assert.equal(failedWorker.readCoreScanReference, true);
assert.equal(
failedWorkerContext.targetPath,
await realpath(failedTargetPath),
@@ -492,7 +543,7 @@ model_reasoning_summary = "none"
failedWorker.argv.includes('model_reasoning_effort="high"'),
true,
);
- assertReadOnlyWorkerInvocation(failedWorker.argv);
+ assertReadOnlyWorkerInvocation(failedWorker.argv, codexHome);
assert.equal(
activeFailureState.workers.some(
(worker: PersistedDeepScanWorker) => worker.kind === "setup",
@@ -676,6 +727,7 @@ model_reasoning_summary = "none"
"start_codex_security_deep_scan",
{ scanId: resumedScanId, handoffClaimToken },
resumedThreadId,
+ { model: "gpt-5.6-sol", reasoning_effort: "high" },
),
);
let partial;
@@ -757,6 +809,7 @@ model_reasoning_summary = "none"
]);
await writeFile(restartControlPath, "after-restart");
+ const resumedStartIndex = (await readJsonLines(startLogPath)).length;
const restartedServer = startServer(serverBundlePath, environment);
try {
assertNoError(
@@ -776,9 +829,20 @@ model_reasoning_summary = "none"
"start_codex_security_deep_scan",
{ scanId: resumedScanId, handoffClaimToken },
resumedThreadId,
+ { model: "gpt-6.1-sol", reasoning_effort: "max" },
),
);
assertNoError(resumed);
+ const modelRows = await execFileAsync(
+ process.env.PYTHON?.trim() || "python3",
+ [
+ "-c",
+ "import sqlite3,sys,json; c=sqlite3.connect(sys.argv[1]); print(json.dumps(c.execute('SELECT model, reasoning_effort FROM scans WHERE id = ?', (sys.argv[2],)).fetchone()))",
+ path.join(stateDir, "workbench.sqlite3"),
+ resumedScanId,
+ ],
+ );
+ assert.deepEqual(JSON.parse(modelRows.stdout), ["gpt-6.1-sol", "max"]);
const instructions = resumed.result.structuredContent.instructions;
assert.match(
instructions,
@@ -869,16 +933,42 @@ model_reasoning_summary = "none"
"utf8",
);
assert.ok(report.length > 0);
+ const helperLaunches = await readLogLines(workbenchLaunchLogPath);
+ for (const command of ["get-scan", "write-scan-draft", "complete-scan"]) {
+ const launches = helperLaunches.filter(
+ (launch) => launch.args[1] === command,
+ );
+ assert.ok(launches.length > 0);
+ for (const launch of launches) {
+ assert.equal(launch.args[0], workbenchPath);
+ assert.equal(launch.cwd, pluginRoot);
+ }
+ }
const executions = (await readLogLines(startLogPath)).slice(
restartStartIndex,
);
- for (const execution of executions) {
- assert.equal(
+ for (const [index, execution] of executions.entries()) {
+ const afterRestart = index + restartStartIndex >= resumedStartIndex;
+ assertReadOnlyWorkerInvocation(execution.argv, codexHome);
+ assert.equal(execution.readCoreScanReference, true);
+ const context = discoveryPromptContext(execution.stdin);
+ if (context.workerLabel) assert.equal(context.pluginRoot, pluginRoot);
+ assertWorkerArtifactEnvironment(
+ execution.argv,
+ pluginRoot,
+ pythonWrapperPath,
+ );
+ assertFlagPair(
+ execution.argv,
+ "--model",
+ afterRestart ? "gpt-6.1-sol" : "gpt-5.6-sol",
+ );
+ assert.ok(
execution.argv.includes(
- `mcp_servers.cs_artifacts.env.CODEX_SECURITY_PYTHON_COMMAND=${JSON.stringify(pythonWrapperPath)}`,
+ `model_reasoning_effort=${JSON.stringify(afterRestart ? "max" : "high")}`,
),
- true,
);
+
assert.equal(
execution.argv.includes('model_reasoning_summary="none"'),
true,
@@ -902,6 +992,7 @@ model_reasoning_summary = "none"
await server.stop();
await rm(serverBundlePath, { force: true });
await rm(fixtureRoot, { recursive: true, force: true });
+ parentSandboxState = readOnlyParentSandboxState(pluginRoot);
}
}
@@ -931,7 +1022,20 @@ function toolCall(
};
}
-function assertReadOnlyWorkerInvocation(args: string[]) {
+function assertWorkerArtifactEnvironment(
+ args: string[],
+ expectedPluginRoot: string,
+ expectedPython: string,
+) {
+ const override = args.find((value) => value.startsWith("mcp_servers="));
+ assert.ok(override);
+ const env = JSON.parse(JSON.stringify(parseToml(override))).mcp_servers
+ .cs_artifacts.env;
+ assert.equal(env.CODEX_SECURITY_PLUGIN_ROOT, expectedPluginRoot);
+ assert.equal(env.CODEX_SECURITY_PYTHON_COMMAND, expectedPython);
+}
+
+function assertReadOnlyWorkerInvocation(args: string[], deniedHome: string) {
assert.equal(args.includes("--sandbox"), false);
assert.equal(args.includes("--add-dir"), false);
assert.equal(
@@ -955,9 +1059,14 @@ function assertReadOnlyWorkerInvocation(args: string[]) {
const overrides = args.filter((arg) =>
arg.startsWith("permissions.codex_security_deep_scan_worker="),
);
- assert.deepEqual(overrides, [
- 'permissions.codex_security_deep_scan_worker={extends=":read-only",filesystem={":root"="read"},network={enabled=false}}',
- ]);
+ assert.deepEqual(
+ overrides.map((value) => parseToml(value)),
+ [
+ parseToml(
+ `permissions.codex_security_deep_scan_worker={extends=":read-only",filesystem={":root"="read",${JSON.stringify(deniedHome)}={"."="deny"}},network={enabled=false}}`,
+ ),
+ ],
+ );
}
async function waitForScanId({
@@ -1063,7 +1172,7 @@ if (process.argv.includes('app-server')) {
if (message.method === 'initialize') {
result = { userAgent: 'fixture', codexHome: '/fixture', platformFamily: 'unix', platformOs: 'macos' };
} else if (message.method === 'config/read') {
- result = { config: { default_permissions: 'codex_security_deep_scan_worker', permissions: { codex_security_deep_scan_worker: { extends: ':read-only', filesystem: { ':root': 'read' }, network: { enabled: false } } } }, origins: {}, layers: null };
+ result = { config: { default_permissions: 'codex_security_deep_scan_worker', permissions: { codex_security_deep_scan_worker: { extends: ':read-only', filesystem: { ':root': 'read', [process.env.FAKE_CODEX_DENIED_HOME]: { '.': 'deny' } }, network: { enabled: false } } } }, origins: {}, layers: null };
} else if (message.method === 'permissionProfile/list') {
result = { data: [{ id: 'codex_security_deep_scan_worker', description: null, allowed: true }], nextCursor: null };
} else if (message.method === 'account/read') {
@@ -1080,7 +1189,8 @@ if (process.argv.includes('app-server')) {
const stdin = (await process.stdin.toArray()).join('');
const context = JSON.parse(stdin.match(/\`\`\`json\\n([\\s\\S]*?)\\n\`\`\`/u)[1]);
const root = process.argv[process.argv.indexOf('--cd') + 1];
-appendFileSync(process.env.FAKE_CODEX_START_LOG, JSON.stringify({ pid: process.pid, argv: process.argv.slice(2), stdin, hasExpectedApiKey: process.env.CODEX_API_KEY === 'synthetic-stdio-key' }) + '\\n');
+const readCoreScanReference = !context.workerLabel || readFileSync(path.join(context.pluginRoot, 'references', 'core-scan.md'), 'utf8').length > 0;
+appendFileSync(process.env.FAKE_CODEX_START_LOG, JSON.stringify({ pid: process.pid, argv: process.argv.slice(2), stdin, readCoreScanReference, hasExpectedApiKey: process.env.CODEX_API_KEY === 'synthetic-stdio-key' }) + '\\n');
console.log(JSON.stringify({ type: 'thread.started', thread_id: \`stdio-fixture-\${process.pid}\` }));
if (existsSync(process.env.FAKE_CODEX_RESTART_CONTROL)) {
const phase = readFileSync(process.env.FAKE_CODEX_RESTART_CONTROL, 'utf8');
@@ -1124,6 +1234,7 @@ async function writePythonWrapper(executablePath: string) {
import { appendFileSync, existsSync, unlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
const args = process.argv.slice(2);
+appendFileSync(process.env.FAKE_WORKBENCH_LAUNCH_LOG, JSON.stringify({ args, cwd: process.cwd() }) + '\\n');
const control = process.env.FAKE_WORKBENCH_CANCEL_FAILURE_CONTROL;
if (args[1] === 'cancel-scan') {
appendFileSync(process.env.FAKE_WORKBENCH_CANCEL_LOG, JSON.stringify(args) + '\\n');
diff --git a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts
index 40587d588..9f7c55ced 100644
--- a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts
+++ b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts
@@ -87,6 +87,7 @@ assert.deepEqual(
"CODEX_SECURITY_KNOWLEDGE_BASE",
"CODEX_SECURITY_CONFIG_PATH",
"CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH",
+ "CODEX_SECURITY_PLUGIN_ROOT",
"CODEX_SECURITY_SCAN_ROOT",
"CODEX_SECURITY_STATE_DIR",
"CODEX_SECURITY_SURFACE",
diff --git a/plugins/codex-security/mcp-app/tests/test_python_command.ts b/plugins/codex-security/mcp-app/tests/test_python_command.ts
index eba3de41a..c0bbead90 100644
--- a/plugins/codex-security/mcp-app/tests/test_python_command.ts
+++ b/plugins/codex-security/mcp-app/tests/test_python_command.ts
@@ -26,6 +26,7 @@ for (const [candidateIndex, expectedCandidate] of windowsCandidates.entries()) {
const checkedCandidates: string[] = [];
assert.equal(
await resolvePythonCommand({
+ cacheDirectory: "",
configuredPython: "",
homeDirectory: windowsHome,
isUsableExecutable: async (candidate: string) => {
@@ -43,6 +44,7 @@ for (const [candidateIndex, expectedCandidate] of windowsCandidates.entries()) {
}
assert.equal(
await resolvePythonCommand({
+ cacheDirectory: "",
configuredPython: "",
homeDirectory: windowsHome,
isUsableExecutable: async () => false,
@@ -69,6 +71,7 @@ assert.equal(
await resolvePythonCommand({
configuredPython: "",
homeDirectory: unixHome,
+ cacheDirectory: "",
isUsableExecutable: async (candidate: string) => {
checkedUnixCandidates.push(candidate);
return false;
@@ -79,6 +82,39 @@ assert.equal(
);
assert.deepEqual(checkedUnixCandidates, unixCandidates);
+for (const platform of ["darwin", "linux", "win32"] as const) {
+ const pathImplementation = platform === "win32" ? path.win32 : path.posix;
+ const cacheDirectory =
+ platform === "win32" ? "D:\\Custom Cache" : "/custom/cache";
+ const managedPython = pathImplementation.join(
+ cacheDirectory,
+ "codex-runtimes",
+ "codex-primary-runtime",
+ "dependencies",
+ "python",
+ ...(platform === "win32" ? ["python.exe"] : ["bin", "python3"]),
+ );
+ const previousCache = process.env.XDG_CACHE_HOME;
+ process.env.XDG_CACHE_HOME = cacheDirectory;
+ try {
+ for (const configuredCache of [cacheDirectory, undefined]) {
+ assert.equal(
+ await resolvePythonCommand({
+ configuredPython: "",
+ homeDirectory: platform === "win32" ? windowsHome : unixHome,
+ cacheDirectory: configuredCache,
+ platform,
+ isUsableExecutable: async (candidate) => candidate === managedPython,
+ }),
+ managedPython,
+ );
+ }
+ } finally {
+ if (previousCache === undefined) delete process.env.XDG_CACHE_HOME;
+ else process.env.XDG_CACHE_HOME = previousCache;
+ }
+}
+
let overrideProbeCount = 0;
assert.equal(
await resolvePythonCommand({
diff --git a/plugins/codex-security/plugin-files.json b/plugins/codex-security/plugin-files.json
index 49920db1b..8088ad6ab 100644
--- a/plugins/codex-security/plugin-files.json
+++ b/plugins/codex-security/plugin-files.json
@@ -27,6 +27,7 @@
"mcp/native/win32-x64/windows.node",
"mcp/helpers.mjs",
"mcp/helpers.mjs.br.part-000",
+ "mcp/permission-profile-preflight.mjs",
"mcp/server.mjs",
"mcp/server.mjs.br.part-000",
"mcp/server.mjs.br.part-001",
@@ -58,6 +59,7 @@
"schemas/tools/scan-draft.schema.json",
"schemas/tools/worker-threat-model.schema.json",
"scripts/config_preflight.py",
+ "scripts/codex_profile.mjs",
"scripts/deep_scan_config.py",
"scripts/deep_scan_defaults.json",
"scripts/deep_scan_workbench.py",
@@ -78,6 +80,7 @@
"scripts/windows_scan_local_files.py",
"scripts/workbench/__init__.py",
"scripts/workbench/handoff.py",
+ "scripts/workbench/runtime_toml.py",
"scripts/workbench/storage.py",
"scripts/workbench_cli.py",
"scripts/workbench_constants.py",
diff --git a/plugins/codex-security/scripts/codex_profile.d.mts b/plugins/codex-security/scripts/codex_profile.d.mts
new file mode 100644
index 000000000..5bb746293
--- /dev/null
+++ b/plugins/codex-security/scripts/codex_profile.d.mts
@@ -0,0 +1,86 @@
+export function preflightProviderDefinitions(
+ providers: Record<string, unknown>,
+): Record<string, unknown>;
+
+export function isPermissionProfileFallbackWarning(
+ message: unknown,
+ profileId: string,
+): boolean;
+
+export function profileConfigOverrides(
+ config: Record<string, unknown>,
+): string[];
+
+export interface CodexProfileOptions {
+ codexPathOverride: string;
+ profileName: string;
+ requestedPermissionProfile?: string;
+ env?: Record<string, string>;
+ apiKey?: string;
+ baseUrl?: string;
+ config?: Record<string, unknown>;
+ configOverrides?: string[];
+}
+
+export interface ProfileThreadOptions {
+ model?: string;
+ threadSource?: string;
+ sandboxMode?: string;
+ workingDirectory?: string;
+ skipGitRepoCheck?: boolean;
+ modelReasoningEffort?: string;
+ networkAccessEnabled?: boolean;
+ webSearchMode?: string;
+ webSearchEnabled?: boolean;
+ approvalPolicy?: string;
+ additionalDirectories?: string[];
+}
+
+export interface ProfileTurnOptions {
+ cyberAccessProgram?: string;
+ outputSchema?: unknown;
+ signal?: AbortSignal;
+}
+
+type CompletedItem<Event> = Event extends {
+ type: "item.completed";
+ item: infer Item;
+}
+ ? Item
+ : never;
+type CompletedUsage<Event> = Event extends {
+ type: "turn.completed";
+ usage: infer Usage;
+}
+ ? Usage
+ : never;
+
+export interface ProfileThread<Event> {
+ readonly id: string | null;
+ runStreamed(
+ input: string,
+ options?: ProfileTurnOptions,
+ ): Promise<{
+ events: AsyncGenerator<Event>;
+ }>;
+ run(
+ input: string,
+ options?: ProfileTurnOptions,
+ ): Promise<{
+ items: CompletedItem<Event>[];
+ finalResponse: string;
+ usage: CompletedUsage<Event> | null;
+ }>;
+}
+
+export function createCodexProfileClient<
+ Event extends { type: string } = Record<string, unknown> & { type: string },
+>(
+ options: CodexProfileOptions,
+): {
+ startThread(options?: ProfileThreadOptions): ProfileThread<Event>;
+ resumeThread(
+ id: string,
+ options?: ProfileThreadOptions,
+ ): ProfileThread<Event>;
+};
diff --git a/plugins/codex-security/scripts/codex_profile.mjs b/plugins/codex-security/scripts/codex_profile.mjs
new file mode 100644
index 000000000..6ef081633
--- /dev/null
+++ b/plugins/codex-security/scripts/codex_profile.mjs
@@ -0,0 +1,237 @@
+import { spawn } from "node:child_process";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createInterface } from "node:readline";
+
+// Native startup needs provider identity and auth selection, while exec reads
+// the full provider configuration from its private profile file.
+export function preflightProviderDefinitions(providers) {
+ return Object.fromEntries(
+ Object.entries(providers).map(([id, provider]) => [
+ id,
+ Object.fromEntries(
+ ["name", "wire_api", "requires_openai_auth"]
+ .filter((key) => Object.hasOwn(provider, key))
+ .map((key) => [key, provider[key]]),
+ ),
+ ]),
+ );
+}
+
+export function isPermissionProfileFallbackWarning(message, profileId) {
+ if (typeof message !== "string") return false;
+ const prefix =
+ "Configured value for `permission_profile` is disallowed by requirements; " +
+ `falling back from \`${profileId}\` to required value \``;
+ const warning = message.trim();
+ return warning.startsWith(prefix) && warning.endsWith("`.");
+}
+
+export function profileConfigOverrides(config) {
+ return Object.entries(config)
+ .filter(([, value]) => value !== undefined)
+ .map(([key, value]) => `${key}=${toml(value)}`);
+}
+
+// Native profile files keep provider configuration off process arguments while
+// retaining the existing CODEX_HOME credential store.
+export function createCodexProfileClient(options) {
+ return {
+ startThread: (threadOptions = {}) =>
+ new ProfileThread(options, threadOptions),
+ resumeThread: (id, threadOptions = {}) =>
+ new ProfileThread(options, threadOptions, id),
+ };
+}
+
+class ProfileThread {
+ constructor(options, threadOptions, id = null) {
+ this.options = options;
+ this.threadOptions = threadOptions;
+ this.id = id;
+ }
+
+ async runStreamed(input, turnOptions = {}) {
+ return { events: this.events(input, turnOptions) };
+ }
+
+ async run(input, turnOptions = {}) {
+ const items = [];
+ let finalResponse = "";
+ let usage = null;
+ for await (const event of this.events(input, turnOptions)) {
+ if (event.type === "item.completed") {
+ items.push(event.item);
+ if (event.item.type === "agent_message")
+ finalResponse = event.item.text;
+ } else if (event.type === "turn.completed") {
+ usage = event.usage;
+ } else if (event.type === "turn.failed") {
+ throw new Error(event.error.message);
+ }
+ }
+ return { items, finalResponse, usage };
+ }
+
+ async *events(input, turnOptions) {
+ let schemaDirectory;
+ try {
+ let schemaPath;
+ if (turnOptions.outputSchema !== undefined) {
+ const schema = turnOptions.outputSchema;
+ if (
+ schema === null ||
+ typeof schema !== "object" ||
+ Array.isArray(schema)
+ ) {
+ throw new Error("outputSchema must be a plain JSON object");
+ }
+ schemaDirectory = await mkdtemp(join(tmpdir(), "codex-output-schema-"));
+ schemaPath = join(schemaDirectory, "schema.json");
+ await writeFile(schemaPath, JSON.stringify(schema), "utf8");
+ }
+ const args = nativeArguments(
+ this.options,
+ this.threadOptions,
+ this.id,
+ turnOptions,
+ schemaPath,
+ );
+ for await (const line of execute(
+ this.options,
+ args,
+ input,
+ turnOptions.signal,
+ )) {
+ let event;
+ try {
+ event = JSON.parse(line);
+ } catch (cause) {
+ throw new Error(`Failed to parse item: ${line}`, { cause });
+ }
+ const item = event.type === "item.completed" ? event.item : event;
+ if (
+ this.options.requestedPermissionProfile !== undefined &&
+ item.type === "error" &&
+ isPermissionProfileFallbackWarning(
+ item.message,
+ this.options.requestedPermissionProfile,
+ )
+ ) {
+ throw new Error(
+ "Read-only Codex helper stopped because organization policy changed its permission profile. Its results were discarded.\n" +
+ item.message,
+ );
+ }
+ if (event.type === "thread.started") this.id = event.thread_id;
+ if (event.type === "turn.completed" && event.usage != null)
+ event.usage.cache_write_input_tokens ??= 0;
+ yield event;
+ }
+ } finally {
+ if (schemaDirectory) {
+ await rm(schemaDirectory, { recursive: true, force: true }).catch(
+ () => {},
+ );
+ }
+ }
+ }
+}
+
+function nativeArguments(options, thread, id, turn, schemaPath) {
+ const args = [
+ "exec",
+ "--experimental-json",
+ "--profile",
+ options.profileName,
+ ];
+ const config = (key, value) => args.push("--config", `${key}=${toml(value)}`);
+ for (const override of profileConfigOverrides(options.config ?? {}))
+ args.push("--config", override);
+ for (const override of options.configOverrides ?? [])
+ args.push("--config", override);
+ if (options.baseUrl) config("openai_base_url", options.baseUrl);
+ if (thread.model) args.push("--model", thread.model);
+ if (thread.threadSource !== undefined && !id)
+ args.push("--thread-source", thread.threadSource);
+ if (thread.sandboxMode) args.push("--sandbox", thread.sandboxMode);
+ if (thread.workingDirectory) args.push("--cd", thread.workingDirectory);
+ for (const directory of thread.additionalDirectories ?? [])
+ args.push("--add-dir", directory);
+ if (thread.skipGitRepoCheck) args.push("--skip-git-repo-check");
+ if (schemaPath) args.push("--output-schema", schemaPath);
+ if (turn.cyberAccessProgram !== undefined)
+ args.push("--cyber-access-program", turn.cyberAccessProgram);
+ if (thread.modelReasoningEffort)
+ config("model_reasoning_effort", thread.modelReasoningEffort);
+ if (thread.networkAccessEnabled !== undefined)
+ config(
+ "sandbox_workspace_write.network_access",
+ thread.networkAccessEnabled,
+ );
+ if (thread.webSearchMode) config("web_search", thread.webSearchMode);
+ else if (thread.webSearchEnabled !== undefined)
+ config("web_search", thread.webSearchEnabled ? "live" : "disabled");
+ if (thread.approvalPolicy) config("approval_policy", thread.approvalPolicy);
+ if (id) args.push("resume", id);
+ return args;
+}
+
+function toml(value) {
+ if (typeof value === "string" || typeof value === "boolean")
+ return JSON.stringify(value).replace(/\u007f/g, "\\u007f");
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
+ if (Array.isArray(value)) return `[${value.map(toml).join(", ")}]`;
+ if (value !== null && typeof value === "object") {
+ return `{${Object.entries(value)
+ .filter(([, child]) => child !== undefined)
+ .map(
+ ([key, child]) =>
+ `${/^[A-Za-z0-9_-]+$/.test(key) ? key : toml(key)} = ${toml(child)}`,
+ )
+ .join(", ")}}`;
+ }
+ throw new Error("Codex config overrides must contain finite TOML values");
+}
+
+async function* execute(options, args, input, signal) {
+ const env = { ...(options.env ?? process.env) };
+ env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE ||= "codex_sdk_ts";
+ if (options.apiKey) env.CODEX_API_KEY = options.apiKey;
+ const child = spawn(options.codexPathOverride, args, {
+ env,
+ signal,
+ windowsHide: true,
+ });
+ let processError;
+ let inputError;
+ child.on("error", (error) => {
+ processError = error;
+ });
+ child.stdin.on("error", (error) => {
+ inputError = error;
+ });
+ const closed = new Promise((resolve) => {
+ child.once("close", (code, exitSignal) => resolve({ code, exitSignal }));
+ });
+ const stderr = [];
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
+ child.stdin.end(input);
+ try {
+ for await (const line of lines) yield line;
+ const { code, exitSignal } = await closed;
+ if (processError) throw processError;
+ if (code !== 0 || exitSignal) {
+ const detail = exitSignal ? `signal ${exitSignal}` : `code ${code ?? 1}`;
+ throw new Error(
+ `Codex Exec exited with ${detail}: ${Buffer.concat(stderr).toString("utf8")}`,
+ );
+ }
+ if (inputError) throw inputError;
+ } finally {
+ lines.close();
+ if (child.exitCode === null && child.signalCode === null) child.kill();
+ }
+}
diff --git a/plugins/codex-security/scripts/config_preflight.py b/plugins/codex-security/scripts/config_preflight.py
index 0132f7980..9eaaa8209 100644
--- a/plugins/codex-security/scripts/config_preflight.py
+++ b/plugins/codex-security/scripts/config_preflight.py
@@ -12,18 +12,16 @@ from collections.abc import Iterator
from pathlib import Path
from typing import Any
-try:
- import tomllib
-except ModuleNotFoundError: # pragma: no cover - Python 3.10 only
- import tomli as tomllib
-
# Some plugin hosts launch Python with safe-path isolation enabled.
sys.path.insert(0, str(Path(__file__).resolve().parent))
+from workbench.runtime_toml import tomllib
from workbench_constants import positive_int
PLUGIN_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_REGISTRY = PLUGIN_ROOT / "preflight" / "capability-profiles.toml"
-DEFAULT_CODEX_HOME = Path(os.environ.get("CODEX_HOME", "~/.codex")).expanduser()
+DEFAULT_CODEX_HOME = Path(
+ os.environ["CODEX_HOME"] if os.environ.get("CODEX_HOME", "").strip() else "~/.codex"
+).expanduser()
def default_system_config() -> Path:
diff --git a/plugins/codex-security/scripts/deep_scan_config.py b/plugins/codex-security/scripts/deep_scan_config.py
index 5d3ffcd1a..b1f2c7862 100644
--- a/plugins/codex-security/scripts/deep_scan_config.py
+++ b/plugins/codex-security/scripts/deep_scan_config.py
@@ -6,13 +6,12 @@ import argparse
import json
import math
import os
+import sys
from pathlib import Path
from typing import Any
-try:
- import tomllib
-except ModuleNotFoundError: # pragma: no cover - Python 3.10 only
- import tomli as tomllib
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from workbench.runtime_toml import tomllib
DEFAULTS = json.loads(
Path(__file__).with_name("deep_scan_defaults.json").read_text(encoding="utf-8")
@@ -35,7 +34,9 @@ CONFIG_KEYS = {
def codex_home() -> Path:
- return Path(os.environ.get("CODEX_HOME", "~/.codex")).expanduser()
+ return Path(
+ os.environ["CODEX_HOME"] if os.environ.get("CODEX_HOME", "").strip() else "~/.codex"
+ ).expanduser()
def config_path() -> Path:
@@ -106,6 +107,8 @@ def resolve_deep_scan_config(available_parallelism: int) -> dict[str, int | floa
def require_integer(value: object, label: str, *, minimum: int) -> int:
+ if isinstance(value, float) and value.is_integer():
+ value = int(value)
if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
qualifier = (
"a non-negative integer"
diff --git a/plugins/codex-security/scripts/workbench/runtime_toml.py b/plugins/codex-security/scripts/workbench/runtime_toml.py
new file mode 100644
index 000000000..8c8af28b9
--- /dev/null
+++ b/plugins/codex-security/scripts/workbench/runtime_toml.py
@@ -0,0 +1,22 @@
+"""Load TOML using the supported Python runtime."""
+
+import sys
+
+__all__ = ["tomllib"]
+
+if sys.version_info < (3, 10):
+ raise SystemExit(
+ "Codex Security requires Python 3.10 or later. Update the Codex managed runtime "
+ "or set PYTHON to a supported interpreter, then restart Codex."
+ )
+
+try:
+ import tomllib as tomllib
+except ModuleNotFoundError: # Python 3.10
+ try:
+ import tomli as tomllib
+ except ModuleNotFoundError as exc:
+ raise SystemExit(
+ "Codex Security requires tomli with Python 3.10. Install tomli for the selected "
+ "interpreter or set PYTHON to Python 3.11 or later, then restart Codex."
+ ) from exc
diff --git a/plugins/codex-security/scripts/workbench/storage.py b/plugins/codex-security/scripts/workbench/storage.py
index bc5a02aa8..257d4c74d 100644
--- a/plugins/codex-security/scripts/workbench/storage.py
+++ b/plugins/codex-security/scripts/workbench/storage.py
@@ -10,7 +10,9 @@ def state_dir() -> Path:
state_dir = os.environ.get("CODEX_SECURITY_STATE_DIR")
if state_dir:
return Path(state_dir).expanduser().resolve()
- codex_home = Path(os.environ.get("CODEX_HOME", "~/.codex")).expanduser()
+ codex_home = Path(
+ os.environ["CODEX_HOME"] if os.environ.get("CODEX_HOME", "").strip() else "~/.codex"
+ ).expanduser()
return (codex_home / "state" / "plugins" / "codex-security").resolve()
diff --git a/plugins/codex-security/tests/test_runtime_settings.py b/plugins/codex-security/tests/test_runtime_settings.py
new file mode 100644
index 000000000..acdf40c29
--- /dev/null
+++ b/plugins/codex-security/tests/test_runtime_settings.py
@@ -0,0 +1,90 @@
+from __future__ import annotations
+
+import runpy
+import sys
+from pathlib import Path
+
+import pytest
+
+SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
+
+
[email protected]("configured", [None, "", " ", "explicit"])
+def test_config_and_state_share_blank_home_semantics(tmp_path, monkeypatch, configured):
+ home = tmp_path / "user"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ monkeypatch.delenv("CODEX_SECURITY_STATE_DIR", raising=False)
+ monkeypatch.delenv("CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH", raising=False)
+ expected = home / ".codex"
+ if configured is None:
+ monkeypatch.delenv("CODEX_HOME", raising=False)
+ else:
+ if configured == "explicit":
+ configured = str(tmp_path / "selected codex")
+ expected = Path(configured)
+ monkeypatch.setenv("CODEX_HOME", configured)
+ deep = runpy.run_path(str(SCRIPTS / "deep_scan_config.py"))
+ preflight = runpy.run_path(str(SCRIPTS / "config_preflight.py"))
+ storage = runpy.run_path(str(SCRIPTS / "workbench" / "storage.py"))
+ assert deep["config_path"]() == expected / "codex-security" / "config.toml"
+ assert preflight["DEFAULT_CONFIG"] == expected / "config.toml"
+ assert storage["state_dir"]() == expected / "state" / "plugins" / "codex-security"
+
+
+def test_integral_toml_counts_match_sdk_values(tmp_path, monkeypatch):
+ config = tmp_path / "config.toml"
+ config.write_text(
+ "[deep_scan]\nworkers=4.0\nsubagents=2.0\nstop_after_no_new=3.0\n"
+ "stop_after_consecutive_errors=5.0\nmax_discovery_runs=8.0\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH", str(config))
+ deep = runpy.run_path(str(SCRIPTS / "deep_scan_config.py"))
+ values = deep["resolve_deep_scan_config"](8)
+ assert values | {"maxTimeHours": 0} == {
+ "workers": 4,
+ "subagents": 2,
+ "stopAfterNoNew": 3,
+ "stopAfterConsecutiveErrors": 5,
+ "maxDiscoveryRuns": 8,
+ "maxTimeHours": 0,
+ }
+ assert all(type(value) is int for name, value in values.items() if name != "maxTimeHours")
+
+
[email protected]("value", [True, 1.5, float("inf"), float("nan"), "4"])
+def test_count_validation_still_rejects_nonintegers(value):
+ deep = runpy.run_path(str(SCRIPTS / "deep_scan_config.py"))
+ with pytest.raises(SystemExit, match="positive integer"):
+ deep["require_integer"](value, "workers", minimum=1)
+
+
[email protected]("absolute", [False, True])
+def test_config_and_storage_preserve_literal_home_spaces(tmp_path, monkeypatch, absolute):
+ monkeypatch.chdir(tmp_path)
+ home = tmp_path / (" selected home" if sys.platform == "win32" else " selected home ")
+ state = home / "state" / "plugins" / "codex-security"
+ state.mkdir(parents=True)
+ (state / "existing-state.txt").write_text("selected state\n", encoding="utf-8")
+ (home / "codex-security").mkdir()
+ (home / "codex-security" / "config.toml").write_text(
+ "[deep_scan]\nworkers = 7\nmax_time_hours = 0.25\n", encoding="utf-8"
+ )
+ (home / "config.toml").write_text('model = "synthetic"\n', encoding="utf-8")
+ monkeypatch.setenv("CODEX_HOME", str(home) if absolute else home.name)
+ monkeypatch.delenv("CODEX_SECURITY_STATE_DIR", raising=False)
+ monkeypatch.delenv("CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH", raising=False)
+ deep = runpy.run_path(str(SCRIPTS / "deep_scan_config.py"))
+ assert deep["config_path"]().resolve() == home / "codex-security" / "config.toml"
+ settings = deep["resolve_deep_scan_config"](8)
+ assert settings["workers"] == 7
+ assert settings["maxTimeHours"] == 0.25
+ preflight = runpy.run_path(str(SCRIPTS / "config_preflight.py"))
+ assert preflight["DEFAULT_CONFIG"].resolve() == home / "config.toml"
+ assert preflight["DEFAULT_CONFIG"].read_text(encoding="utf-8") == 'model = "synthetic"\n'
+ storage = runpy.run_path(str(SCRIPTS / "workbench" / "storage.py"))
+ selected_state = storage["state_dir"]()
+ assert selected_state == state
+ assert (selected_state / "existing-state.txt").read_text(encoding="utf-8") == "selected state\n"
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 7790cbdd7..8175a553b 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -187,10 +187,26 @@ Constructor options are `codexOverrides`, `pythonPath`, and `pluginPath`.
The bundled runtime and plugin are used by default. `pythonPath` overrides the
`PYTHON` environment variable. To choose a model, set `codexOverrides.model`.
+Deep Scans with non-default provider selection or custom provider definitions
+require a plugin that supports per-scan worker provider snapshots. Older custom plugins
+fail before starting model work with an upgrade message; update the plugin or
+omit `pluginPath` to use the bundled version. Older custom plugins remain usable
+for standard scans and Deep Scans that inherit native provider configuration or
+explicitly select the built-in OpenAI provider without custom provider definitions
+when their workers forward that selection or native configuration selects the
+same effective provider for both the parent and workers. Otherwise, the scan
+stops before model work with the plugin upgrade message.
+When no provider is selected, discovery, reducer, and resumed workers inherit the
+same native configuration as the parent.
+
Scans use an isolated Codex configuration. See
[runtime configuration](docs/cli.md#runtime-configuration-and-worker-limits)
for supported overrides and defaults.
+Windows defaults to `windows.sandbox = "elevated"` to enforce credential read
+denials. Explicit `windows.sandbox` settings remain unchanged; Codex reports
+policies unsupported by the selected backend.
+
### Load a project file
Load shared CLI and SDK settings explicitly:
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index b32a64c38..3de9ef6cd 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -175,6 +175,7 @@ const allowedFiles = new Set([
"project-config",
"project-config-schema",
"prompt-files",
+ "provider-profile",
"scan-modes",
"scan-settings",
"errors",
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index bffb4e049..639143df6 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -32,6 +32,13 @@ import {
import { z } from "incur";
import { readThreatModelPath } from "./artifact-export.js";
import { isRecord } from "./record.js";
+import {
+ createProfileCodex,
+ createProviderProfile,
+ legacyWorkerUsesScanProvider,
+ providerPreflightCommand,
+ type ProviderProfile,
+} from "./provider-profile.js";
import {
CODEX_AUTH_CONFIG_KEYS,
@@ -57,12 +64,12 @@ import {
hasCommandAuth,
mergedCodexConfig,
resolveCodexProfile,
- modelProviderConfigOverride,
resolveCommandAuthConfig,
scanApprovalPolicy,
scanCyberAccessConfig,
scanModelConfiguration,
scanModelProvider,
+ structuredCodexConfig,
type CodexSecurityConfig,
type JsonObject,
type ScanModelConfiguration,
@@ -199,6 +206,7 @@ import {
requireModelSafeOutputDir,
requireOutputOutsideRepositories,
requireOutputOutsideRepository,
+ requirePrivateCredentialHome,
requirePrivatePolicyOutputDirectory,
resolveCodexCommand,
resolvePluginPath,
@@ -253,7 +261,9 @@ interface PreparedRuntime {
codexHome: string;
bootstrapWorkspace?: string;
configPath?: string;
+ deepScanConfigDirectory?: string;
deepScanConfigPath?: string;
+ providerProfile?: ProviderProfile;
plugin: PluginInstall;
environment: Record<string, string>;
credentialsAvailable: boolean;
@@ -453,7 +463,9 @@ interface CodexSecurityRuntimeOptions {
}
interface ClientDependencies {
- createCodex(options: CodexOptions): CodexClientLike;
+ createCodex(
+ options: CodexOptions & { nativeProfile?: string },
+ ): CodexClientLike | Promise<CodexClientLike>;
environment: ProcessEnvironment;
prepareRuntime?: (
config: Readonly<CodexSecurityConfig>,
@@ -471,7 +483,10 @@ interface ClientDependencies {
}
const DEFAULT_DEPENDENCIES: ClientDependencies = {
- createCodex: (options) => new Codex(options),
+ createCodex: ({ nativeProfile, ...options }) =>
+ nativeProfile === undefined
+ ? new Codex(options)
+ : createProfileCodex(options, nativeProfile),
environment: process.env,
};
@@ -697,7 +712,7 @@ export class CodexSecurity {
...(session.sessionConfig["features"] as JsonObject),
plugins: false,
};
- const { codex } = this.#createSessionCodex(
+ const { codex } = await this.#createSessionCodex(
session,
{
CODEX_SECURITY_REPOSITORY: inputs.repository,
@@ -1006,7 +1021,7 @@ export class CodexSecurity {
runtime.plugin.pluginRoot,
...(knowledgeBase === null ? [] : [knowledgeBase.path]),
].filter((path, index, roots) => roots.indexOf(path) === index);
- const { codex } = this.#createSessionCodex(
+ const { codex } = await this.#createSessionCodex(
session,
{
CODEX_SECURITY_REPOSITORY: target.repository,
@@ -1329,14 +1344,6 @@ export class CodexSecurity {
);
}
checkOpen();
- if (deepScanConfiguration !== undefined) {
- await writeDeepScanConfig(
- runtime.deepScanConfigPath ??
- join(runtimeHome, "codex-security", "config.toml"),
- deepScanConfiguration,
- );
- }
- checkOpen();
const scanOutputRoot =
requestedOutput === null &&
this.#dependencies.prepareOutputDir === undefined
@@ -1374,6 +1381,67 @@ export class CodexSecurity {
);
checkOpen();
+ const workerProviderEnvironment = {
+ ...withoutOpenAiApiKeys(
+ selectedScanEnvironment(
+ runtime.environment,
+ options.auth,
+ modelProvider,
+ ),
+ ),
+ ...(session.apiKey === null
+ ? {}
+ : {
+ [session.externalProvider?.env_key ?? "CODEX_API_KEY"]:
+ session.apiKey,
+ }),
+ };
+ if (
+ mode === "deep" &&
+ modelProvider === "openai" &&
+ !(await pluginForwardsWorkerProviderSelection(
+ runtime,
+ preflightConfig,
+ )) &&
+ !(await legacyWorkerUsesScanProvider(
+ this.#codexCommand(),
+ definedEnvironment(workerProviderEnvironment),
+ scanDir,
+ modelProvider,
+ signal,
+ ))
+ ) {
+ throw new CodexSecurityError(
+ "This custom plugin cannot forward the scan's selected provider to Deep Scan workers. Update the custom plugin or use the bundled plugin.",
+ );
+ }
+ const { environment: workerEnvironment, ...workerRuntimeConfig } =
+ selectedWorkerRuntimeConfig(
+ effectiveConfig,
+ modelProvider,
+ scanDir,
+ workerProviderEnvironment,
+ );
+ const workerSnapshot: JsonObject = {
+ ...workerRuntimeConfig,
+ ...(workerEnvironment === undefined
+ ? {}
+ : { environment: workerEnvironment }),
+ };
+ delete workerSnapshot["model_providers"];
+ if (runtime.providerProfile !== undefined) {
+ workerSnapshot["native_profile"] = runtime.providerProfile.name;
+ }
+ if (deepScanConfiguration !== undefined) {
+ await writeDeepScanConfig(
+ runtime.deepScanConfigPath ??
+ join(runtimeHome, "codex-security", "config.toml"),
+ deepScanConfiguration,
+ runtime.deepScanConfigPath === undefined ? undefined : workerSnapshot,
+ );
+ }
+ checkOpen();
+
const shellPluginRoot = runtime.plugin.pluginRoot;
const canonicalShellPluginRoot = await realpath(shellPluginRoot);
const pluginRelativeToHome = relative(
@@ -1400,7 +1468,7 @@ export class CodexSecurity {
);
if (discoveryPrompt !== undefined)
session.sessionConfig = await customValidationConfig(
- session.sessionConfig,
+ resolveCodexProfile(session.sessionConfig),
runtime.plugin.installedRoot,
);
const skillPath = join(shellPluginRoot, "skills", skillName, "SKILL.md");
@@ -1910,7 +1978,7 @@ export class CodexSecurity {
? {}
: { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
};
- const { codex, environment } = this.#createSessionCodex(
+ const { codex, environment } = await this.#createSessionCodex(
session,
runtimePaths,
options.auth,
@@ -2269,6 +2337,9 @@ export class CodexSecurity {
"all",
);
if (previousFindings !== undefined) {
+ const matchingRuntimeConfig = structuredClone(workerRuntimeConfig);
+ const matchingFeatures = matchingRuntimeConfig["features"];
+ if (isRecord(matchingFeatures)) delete matchingFeatures["plugins"];
await matchCompletedScan({
scanId,
repository: repo,
@@ -2290,6 +2361,15 @@ export class CodexSecurity {
},
),
environment,
+ nativeProfile: runtime.providerProfile,
+ config: {
+ codexOverrides: {
+ ...scanPreflightCodexConfig(
+ resolveCodexProfile(session.sessionConfig),
+ ),
+ ...matchingRuntimeConfig,
+ },
+ },
model,
cyberAccessProgram: options.cyberAccessProgram,
signal,
@@ -2490,7 +2570,7 @@ export class CodexSecurity {
const authentication = await this.#authentication();
this.#requireOpen();
const result = await persistApiKey(
- this.#codexCommand(),
+ await this.#providerPreflightCommand(),
authentication.environment,
apiKey,
this.#abortController.signal,
@@ -2516,9 +2596,11 @@ export class CodexSecurity {
async #startLogin(deviceCode: boolean): Promise<CodexLoginHandle> {
const authentication = await this.#authentication();
this.#requireOpen();
+ const command = await this.#providerPreflightCommand();
+ this.#requireOpen();
const handle = this.#trackLoginHandle(
new CodexLoginHandle(
- this.#codexCommand(),
+ command,
deviceCode ? ["login", "--device-auth"] : ["login"],
authentication.environment,
() => this.#recordLogin(authentication.codexHome, "stored_credentials"),
@@ -2549,7 +2631,7 @@ export class CodexSecurity {
authentication.codexHome,
);
return await accountStatus(
- this.#codexCommand(),
+ await this.#providerPreflightCommand(),
authentication.environment,
this.#abortController.signal,
);
@@ -2561,7 +2643,7 @@ export class CodexSecurity {
const authentication = await this.#authentication();
this.#requireOpen();
await codexLogout(
- this.#codexCommand(),
+ await this.#providerPreflightCommand(),
authentication.environment,
this.#abortController.signal,
);
@@ -2593,8 +2675,29 @@ export class CodexSecurity {
);
const runtime = this.#runtime;
this.#runtime = null;
- if (runtime?.bootstrapWorkspace !== undefined) {
- await cleanupSdkDirectory(runtime.bootstrapWorkspace);
+ const cleanupErrors: unknown[] = [];
+ try {
+ await runtime?.providerProfile?.cleanup();
+ } catch (error) {
+ cleanupErrors.push(error);
+ }
+ for (const directory of [
+ runtime?.deepScanConfigDirectory,
+ runtime?.bootstrapWorkspace,
+ ]) {
+ if (directory === undefined) continue;
+ try {
+ await cleanupSdkDirectory(directory);
+ } catch (error) {
+ cleanupErrors.push(error);
+ }
+ }
+ if (cleanupErrors.length === 1) throw cleanupErrors[0];
+ if (cleanupErrors.length > 1) {
+ throw new AggregateError(
+ cleanupErrors,
+ "Codex Security runtime directories could not be cleaned up.",
+ );
}
}
@@ -2650,16 +2753,17 @@ export class CodexSecurity {
}
}
- #createSessionCodex(
+ async #createSessionCodex(
session: PreparedSession,
runtimePaths: Record<string, string>,
auth: ScanAuthMode = "auto",
git?: InspectedExecutable,
config?: JsonObject,
configOverrides: string[] = [],
- ): { codex: CodexClientLike; environment: ProcessEnvironment } {
+ ): Promise<{ codex: CodexClientLike; environment: ProcessEnvironment }> {
const {
runtime,
+ runtimeHome,
python,
modelProvider,
externalProvider,
@@ -2696,43 +2800,57 @@ export class CodexSecurity {
if (session.safetyIdentifier !== undefined) {
environment[SAFETY_IDENTIFIER_ENV] = session.safetyIdentifier;
}
- const sdkCodexConfig = { ...(config ?? sessionConfig) };
- // Projects and permissions already live in generated TOML files; the SDK
- // cannot safely encode their path and selector keys as dotted overrides.
- delete sdkCodexConfig["projects"];
- delete sdkCodexConfig["permissions"];
- if (commandAuth) delete sdkCodexConfig["model_providers"];
+ const sdkCodexConfig = structuredCodexConfig(config ?? sessionConfig);
+ // This snapshot outlives a Deep Scan when the client reuses its runtime.
+ if (runtime.deepScanConfigPath !== undefined) {
+ configOverrides = [
+ `permissions.${SCAN_PERMISSION_PROFILE}.filesystem=${inlineToml({
+ ":root": "read",
+ ":workspace_roots": "write",
+ [runtimeHome]: { ".": "deny" },
+ ...(runtime.deepScanConfigDirectory === undefined
+ ? { [runtime.deepScanConfigPath]: { ".": "deny" } }
+ : {}),
+ })}`,
+ ...configOverrides,
+ ];
+ }
const configuredResponsesMetadata = isRecord(
sdkCodexConfig["responses_api_metadata"],
)
? sdkCodexConfig["responses_api_metadata"]
: {};
+ const configuredCodexPath = environmentValue(
+ this.#dependencies.environment,
+ "CODEX_CLI_PATH",
+ );
let codexPathOverride =
- environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH") ===
- undefined
+ configuredCodexPath === undefined
? undefined
: this.#codexCommand().command;
let sdkEnvironment = definedEnvironment(withoutOpenAiApiKeys(environment));
- if (process.platform === "win32" && codexPathOverride === undefined) {
+ if (
+ process.platform === "win32" &&
+ (configuredCodexPath === undefined ||
+ !/\.(?:exe|com)$/iu.test(configuredCodexPath))
+ ) {
codexPathOverride = environment["CODEX_CLI_PATH"]!;
sdkEnvironment = bundledCodexSdkEnvironment(
codexPathOverride,
sdkEnvironment,
);
}
- const codex = this.#dependencies.createCodex({
+ const codex = await this.#dependencies.createCodex({
...(codexPathOverride === undefined
? {}
: { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
- ...(commandAuth || configOverrides.length > 0
+ ...(runtime.providerProfile === undefined
+ ? {}
+ : { nativeProfile: runtime.providerProfile.name }),
+ ...(configOverrides.length > 0
? {
- configOverrides: [
- ...(commandAuth
- ? modelProviderConfigOverride(sessionConfig)
- : []),
- ...configOverrides,
- ],
+ configOverrides,
}
: {}),
env: sdkEnvironment,
@@ -2767,7 +2885,7 @@ export class CodexSecurity {
>,
signal: AbortSignal,
temporaryRoot?: string,
- keepCredentialLock = false,
+ deepScan = false,
): Promise<PreparedSession> {
let releaseCredentialHome: (() => Promise<void>) | null = null;
const checkOpen = (): void => {
@@ -2795,11 +2913,6 @@ export class CodexSecurity {
authentication.method === "api_key"
? environmentApiKey(this.#dependencies.environment, modelProvider)
: null;
- if (externalProvider !== null && apiKey === null) {
- throw new AuthenticationRequiredError(
- `Set ${externalProvider.env_key} to run a scan through ${externalProvider.name}.`,
- );
- }
const scanEnvironment = selectedScanEnvironment(
commandAuth
? withoutOpenAiApiKeys(this.#dependencies.environment)
@@ -2847,6 +2960,20 @@ export class CodexSecurity {
);
const approvalPolicy = scanApprovalPolicy(effectiveConfig);
const preflightConfig = scanPreflightCodexConfig(effectiveConfig);
+ const providers = resolveCodexProfile(effectiveConfig)["model_providers"];
+ if (
+ deepScan &&
+ ((typeof modelProvider === "string" && modelProvider !== "openai") ||
+ (isRecord(providers) && Object.keys(providers).length > 0)) &&
+ (runtime.deepScanConfigPath === undefined ||
+ !(await pluginSupportsWorkerProviderSnapshot(
+ runtime.plugin.pluginRoot,
+ )))
+ ) {
+ throw new CodexSecurityError(
+ "This custom plugin cannot forward per-scan provider settings to Deep Scan workers. Update the custom plugin or use the bundled plugin.",
+ );
+ }
if (runtime.configPath !== undefined) {
await writeCodexConfig(runtime.configPath, {
...preflightConfig,
@@ -2861,6 +2988,15 @@ export class CodexSecurity {
}
const runtimeHome = await realpath(runtime.codexHome);
requireOutputOutsideRepositories(protectedRoots, runtimeHome, "runtime");
+ await runtime.providerProfile?.cleanup();
+ if (isRecord(providers) && Object.keys(providers).length > 0) {
+ runtime.providerProfile = await createProviderProfile(
+ runtimeHome,
+ effectiveConfig,
+ );
+ } else {
+ delete runtime.providerProfile;
+ }
const sessionConfig = scanRuntimeCodexConfig(
effectiveConfig,
runtimeHome,
@@ -2881,7 +3017,8 @@ export class CodexSecurity {
const ambientHome =
environmentValue(this.#dependencies.environment, "CODEX_HOME") ??
join(homedir(), ".codex");
- runtime.credentialsAvailable = await importAmbientAuth(
+ runtime.credentialsAvailable = await initialCredentialsAvailable(
+ scanEnvironment,
ambientHome,
runtime.codexHome,
);
@@ -2889,7 +3026,7 @@ export class CodexSecurity {
? "stored_credentials"
: null;
}
- if (!keepCredentialLock || runtime.deepScanConfigPath !== undefined) {
+ if (!deepScan || runtime.deepScanConfigPath !== undefined) {
await releaseCredentialHome?.();
releaseCredentialHome = null;
}
@@ -2901,7 +3038,7 @@ export class CodexSecurity {
authentication.method === "stored_credentials"
) {
const status = await accountStatus(
- this.#codexCommand(),
+ await this.#providerPreflightCommand(requestedConfig),
runtime.environment,
signal,
);
@@ -2994,6 +3131,13 @@ export class CodexSecurity {
);
}
+ async #providerPreflightCommand(config?: JsonObject): Promise<CodexCommand> {
+ return await providerPreflightCommand(
+ this.#codexCommand(),
+ config ?? (await mergedCodexConfig(this.config)),
+ );
+ }
+
async #refreshPersistentRuntime(
runtime: PreparedRuntime,
environment: ProcessEnvironment,
@@ -3010,16 +3154,30 @@ export class CodexSecurity {
runtime.codexHome,
runtime.plugin.pluginRoot,
{
- codexCommand: this.#codexCommand(),
+ codexCommand: await this.#providerPreflightCommand(mergedConfig),
environment: withoutCodexHome(environment),
signal,
},
);
- runtime.deepScanConfigPath =
+ runtime.environment = {
+ ...withoutCodexHome(environment),
+ CODEX_HOME: runtime.codexHome,
+ CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(environment),
+ };
+ if (
runtime.bootstrapWorkspace !== undefined &&
(await pluginSupportsIsolatedDeepScanConfig(runtime.plugin.pluginRoot))
- ? join(runtime.bootstrapWorkspace, "deep-scan-config.toml")
- : undefined;
+ ) {
+ runtime.deepScanConfigDirectory ??= await mkdtemp(
+ join(runtime.codexHome, "codex-security-worker-"),
+ );
+ runtime.deepScanConfigPath = join(
+ runtime.deepScanConfigDirectory,
+ "deep-scan-config.toml",
+ );
+ } else {
+ runtime.deepScanConfigPath = undefined;
+ }
}
async #validatePolicyInputs(
@@ -3446,12 +3604,17 @@ export class CodexSecurity {
codexSecurityCredentialHome(processEnvironment),
);
let bootstrapWorkspace: string | undefined;
+ let deepScanConfigDirectory: string | undefined;
try {
throwIfAborted(signal);
bootstrapWorkspace = await createIsolatedHome(
temporaryRoot,
validateLocation,
);
+ await requirePrivateCredentialHome(
+ await lstat(bootstrapWorkspace),
+ bootstrapWorkspace,
+ );
const pluginRoot = await resolvePluginPath(
this.config.pluginPath,
bootstrapWorkspace,
@@ -3470,7 +3633,8 @@ export class CodexSecurity {
await writeCodexConfig(join(codexHome, "config.toml"), codexConfig);
const configPath = join(bootstrapWorkspace, "config-preflight.toml");
throwIfAborted(signal);
- const codexCommand = this.#codexCommand();
+ const codexCommand =
+ await this.#providerPreflightCommand(requestedConfig);
await (this.#dependencies.probeCodexSandbox ?? probeCodexSandbox)(
codexCommand,
{ ...withoutCodexHome(processEnvironment), CODEX_HOME: codexHome },
@@ -3481,11 +3645,15 @@ export class CodexSecurity {
environment: withoutCodexHome(processEnvironment),
signal,
});
- const deepScanConfigPath = (await pluginSupportsIsolatedDeepScanConfig(
- plugin.pluginRoot,
- ))
- ? join(bootstrapWorkspace, "deep-scan-config.toml")
- : undefined;
+ if (await pluginSupportsIsolatedDeepScanConfig(plugin.pluginRoot)) {
+ deepScanConfigDirectory = await mkdtemp(
+ join(codexHome, "codex-security-worker-"),
+ );
+ }
+ const deepScanConfigPath =
+ deepScanConfigDirectory === undefined
+ ? undefined
+ : join(deepScanConfigDirectory, "deep-scan-config.toml");
const credentialsAvailable =
hasCommandAuth(requestedConfig) ||
isExternalModelProvider(modelProvider) ||
@@ -3500,6 +3668,7 @@ export class CodexSecurity {
codexHome,
bootstrapWorkspace,
configPath,
+ deepScanConfigDirectory,
deepScanConfigPath,
plugin,
environment: {
@@ -3511,17 +3680,22 @@ export class CodexSecurity {
credentialsAvailable,
};
} catch (error) {
- if (bootstrapWorkspace !== undefined) {
+ const cleanupErrors: unknown[] = [];
+ for (const directory of [deepScanConfigDirectory, bootstrapWorkspace]) {
+ if (directory === undefined) continue;
try {
- await cleanupSdkDirectory(bootstrapWorkspace);
+ await cleanupSdkDirectory(directory);
} catch (cleanupError) {
- throw new AggregateError(
- [error, cleanupError],
- "Codex Security runtime preparation failed and its isolated runtime could not be cleaned up.",
- { cause: error },
- );
+ cleanupErrors.push(cleanupError);
}
}
+ if (cleanupErrors.length > 0) {
+ throw new AggregateError(
+ [error, ...cleanupErrors],
+ "Codex Security runtime preparation failed and its isolated runtime could not be cleaned up.",
+ { cause: error },
+ );
+ }
throw error;
}
}
@@ -4275,6 +4449,12 @@ export function scanAuthentication(
return { method: "stored_credentials", verified: false };
}
const key = environmentApiKeyEntry(environment, modelProvider);
+ if (key === null && isExternalModelProvider(modelProvider)) {
+ const provider = EXTERNAL_CODEX_PROVIDERS[modelProvider];
+ throw new AuthenticationRequiredError(
+ `Set ${provider.env_key} to run a scan through ${provider.name}.`,
+ );
+ }
if (
auth === "api-key" &&
key === null &&
@@ -4549,7 +4729,7 @@ export function scanRuntimeCodexConfig(
":workspace_roots": "write",
...(protectedCredentialHome === undefined
? {}
- : { [protectedCredentialHome]: "read" }),
+ : { [protectedCredentialHome]: { ".": "deny" } }),
},
},
[POLICY_PERMISSION_PROFILE]: {
@@ -4596,8 +4776,8 @@ function requirePolicyConfigKeys(config: JsonObject): void {
function policyCodexConfig(config: JsonObject): JsonObject {
const resolved = resolveCodexProfile(config);
requirePolicyConfigKeys(resolved);
- // The selected provider is already written as TOML. The SDK cannot quote
- // provider names when it flattens this table into command-line overrides.
+ // The selected provider is passed as raw TOML by createSessionCodex.
+ // Structured SDK overrides cannot quote literal provider names.
delete resolved["model_providers"];
return {
...resolved,
@@ -4627,6 +4807,8 @@ function sharedCredentialCodexConfig(
config: JsonObject,
credentialHome: string,
): JsonObject {
+ // Providers stay in private session profiles. Codex merges provider tables, so
+ // persisting them here would mix credentials from concurrent scans.
const shared: JsonObject = {
approval_policy: scanApprovalPolicy(config),
features: { plugins: true },
@@ -4634,22 +4816,6 @@ function sharedCredentialCodexConfig(
for (const key of CODEX_AUTH_CONFIG_KEYS) {
if (Object.hasOwn(config, key)) shared[key] = structuredClone(config[key]!);
}
- const modelProvider = scanModelProvider(config);
- if (hasCommandAuth(config)) {
- for (const key of ["profile", "profiles"]) {
- if (Object.hasOwn(config, key))
- shared[key] = structuredClone(config[key]!);
- }
- }
- if (typeof modelProvider === "string" && modelProvider.length > 0) {
- shared["model_provider"] = modelProvider;
- const providers = config["model_providers"];
- if (isRecord(providers) && Object.hasOwn(providers, modelProvider)) {
- shared["model_providers"] = {
- [modelProvider]: structuredClone(providers[modelProvider]!),
- };
- }
- }
return scanRuntimeCodexConfig(shared, credentialHome);
}
@@ -4722,7 +4888,7 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {
return result;
};
const result = executionConfig(config);
- // Keep effective worker settings even when preflight filters the profile name.
+ // Keep effective execution settings even when preflight filters the profile name.
const resolved = resolveCodexProfile(config);
for (const key of ["model_reasoning_summary", "service_tier"]) {
const value = resolved[key];
@@ -4799,6 +4965,108 @@ export function scanPreflightCodexConfig(config: JsonObject): JsonObject {
return result;
}
+async function pluginSupportsWorkerProviderSnapshot(
+ pluginRoot: string,
+): Promise<boolean> {
+ const manifest: unknown = JSON.parse(
+ await readFile(join(pluginRoot, ".codex-plugin", "plugin.json"), "utf8"),
+ );
+ return (
+ isRecord(manifest) &&
+ isRecord(manifest["codexSecurity"]) &&
+ manifest["codexSecurity"]["workerProviderSnapshot"] === 4
+ );
+}
+
+async function pluginForwardsWorkerProviderSelection(
+ runtime: PreparedRuntime,
+ preflightConfig: JsonObject,
+): Promise<boolean> {
+ const manifest: unknown = JSON.parse(
+ await readFile(
+ join(runtime.plugin.pluginRoot, ".codex-plugin", "plugin.json"),
+ "utf8",
+ ),
+ );
+ const capability =
+ isRecord(manifest) && isRecord(manifest["codexSecurity"])
+ ? manifest["codexSecurity"]["workerProviderSnapshot"]
+ : undefined;
+ if (capability === true) {
+ return (
+ runtime.configPath !== undefined &&
+ resolveCodexProfile(preflightConfig)["model_provider"] === "openai"
+ );
+ }
+ return (
+ runtime.deepScanConfigPath !== undefined &&
+ (capability === 2 || capability === 3 || capability === 4)
+ );
+}
+
+function selectedWorkerRuntimeConfig(
+ config: JsonObject,
+ selectedProvider: unknown,
+ workingDirectory: string,
+ environment: ProcessEnvironment,
+): JsonObject {
+ const provider =
+ typeof selectedProvider === "string" ? selectedProvider : undefined;
+ const resolved = resolveCodexProfile(config);
+ const providers = resolved["model_providers"];
+ const providerEnvironmentNames = isRecord(providers)
+ ? Object.values(providers)
+ .flatMap((providerConfig) =>
+ isRecord(providerConfig)
+ ? [
+ providerConfig["env_key"],
+ ...(isRecord(providerConfig["env_http_headers"])
+ ? Object.values(providerConfig["env_http_headers"])
+ : []),
+ ]
+ : [],
+ )
+ .filter((name): name is string => typeof name === "string")
+ : [];
+ const providerEnvironment = Object.fromEntries(
+ providerEnvironmentNames.flatMap((name) => {
+ const value =
+ environment[name] ??
+ (process.platform === "win32"
+ ? Object.entries(environment).find(
+ ([key]) => key.toUpperCase() === name.toUpperCase(),
+ )?.[1]
+ : undefined);
+ return value === undefined ? [] : [[name, value]];
+ }),
+ );
+ const instructionsFile = resolved["model_instructions_file"];
+ if (typeof instructionsFile === "string") {
+ resolved["model_instructions_file"] = resolve(
+ workingDirectory,
+ expandHome(instructionsFile, environment),
+ );
+ }
+ return {
+ ...Object.fromEntries(
+ [
+ "features",
+ "model_instructions_file",
+ "model_verbosity",
+ "web_search",
+ "windows",
+ ]
+ .filter((key) => resolved[key] !== undefined)
+ .map((key) => [key, resolved[key]!]),
+ ),
+ ...(provider === undefined ? {} : { model_provider: provider }),
+ ...(Object.keys(providerEnvironment).length === 0
+ ? {}
+ : { environment: providerEnvironment }),
+ ...(isRecord(providers) ? { model_providers: providers } : {}),
+ };
+}
+
async function pluginSupportsIsolatedDeepScanConfig(
pluginRoot: string,
): Promise<boolean> {
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.ts
index 5d745b161..892aa6afc 100644
--- a/sdk/typescript/src/auth.ts
+++ b/sdk/typescript/src/auth.ts
@@ -111,11 +111,15 @@ export class CodexLoginHandle {
) {
void this.#urlReady.promise.catch(() => undefined);
void this.#deviceReady.promise.catch(() => undefined);
- this.#child = spawn(executablePathForSpawn(command.command), [...args], {
- env: environment,
- stdio: ["pipe", "pipe", "pipe"],
- windowsHide: true,
- });
+ this.#child = spawn(
+ executablePathForSpawn(command.command),
+ [...(command.args ?? []), ...args],
+ {
+ env: environment,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ },
+ );
this.#child.stdin.end();
this.#child.stdout.setEncoding("utf8");
this.#child.stderr.setEncoding("utf8");
diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.ts
index ddcc4fa94..ad83457be 100644
--- a/sdk/typescript/src/component-scan.ts
+++ b/sdk/typescript/src/component-scan.ts
@@ -14,6 +14,7 @@ import {
type ComponentPlanningOptions,
} from "./component-plan.js";
import {
+ hasCommandAuth,
mergedCodexConfig,
scanModelProvider,
type CodexSecurityConfig,
@@ -131,10 +132,9 @@ export async function runComponentScans(
let environment = options.environment;
if (auth !== undefined && auth !== "auto") {
const source = environment ?? process.env;
- const provider = scanModelProvider(
- await mergedCodexConfig(options.config ?? {}),
- );
- scanAuthentication(source, auth, provider);
+ const configuration = await mergedCodexConfig(options.config ?? {});
+ const provider = scanModelProvider(configuration);
+ scanAuthentication(source, auth, provider, hasCommandAuth(configuration));
environment = selectedScanEnvironment(source, auth, provider);
}
const repository = await normalizeRepository(
diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.ts
index b842ad883..1b5fb524a 100644
--- a/sdk/typescript/src/config.ts
+++ b/sdk/typescript/src/config.ts
@@ -68,9 +68,9 @@ export const DEFAULT_CODEX_CONFIG: Readonly<JsonObject> = Object.freeze({
max_concurrent_threads_per_session: 9,
}),
}),
- // Named filesystem profiles need an active Windows sandbox backend.
+ // Credential read denials require the elevated Windows sandbox backend.
windows: Object.freeze({
- sandbox: "unelevated",
+ sandbox: "elevated",
}),
});
@@ -119,7 +119,7 @@ export function scanModelProvider(config: Readonly<JsonObject>): unknown {
/** @internal Native Codex validates the auth table, including invalid selections. */
export function hasCommandAuth(config: Readonly<JsonObject>): boolean {
const selected = scanModelProvider(config);
- const providers = config["model_providers"];
+ const providers = resolveCodexProfile(config)["model_providers"];
const provider =
typeof selected === "string" && isObject(providers)
? providers[selected]
@@ -133,8 +133,9 @@ export function resolveCommandAuthConfig(
home: string,
): JsonObject {
const resolved = structuredClone(config);
- const providers = resolved["model_providers"];
+ const providers = resolveCodexProfile(resolved)["model_providers"];
if (isObject(providers)) {
+ (selectedScanProfile(resolved) ?? resolved)["model_providers"] = providers;
for (const provider of Object.values(providers)) {
if (!isObject(provider) || !isObject(provider["auth"])) continue;
const auth = provider["auth"];
@@ -157,8 +158,21 @@ export function modelProviderConfigOverride(config: JsonObject): string[] {
: [`model_providers=${inlineToml(config["model_providers"])}`];
}
+/** @internal Resolve settings; literal-key tables use native file layers. */
+export function structuredCodexConfig(config: JsonObject = {}): JsonObject {
+ const structured = resolveCodexProfile(config);
+ delete structured["projects"];
+ delete structured["permissions"];
+ delete structured["model_providers"];
+ return structured;
+}
+
/** @internal Serialize one Codex CLI override value without flattening its keys. */
export function inlineToml(value: JsonValue): string {
+ if (value === null)
+ throw new ConfigurationError(
+ "Codex TOML overrides cannot contain null values.",
+ );
if (Array.isArray(value)) return `[${value.map(inlineToml).join(",")}]`;
if (isObject(value)) {
return `{${Object.entries(value)
@@ -248,7 +262,10 @@ export async function mergedCodexConfig(
return deepMerge(defaults, overrides);
}
-function normalizeLegacyWindowsSandboxOverride(overrides: JsonObject): void {
+/** @internal Preserve existing native Windows backend selections. */
+export function normalizeLegacyWindowsSandboxOverride(
+ overrides: JsonObject,
+): void {
const features = overrides["features"];
if (!isObject(features)) {
return;
diff --git a/sdk/typescript/src/deduplication/checkpointed-review.ts b/sdk/typescript/src/deduplication/checkpointed-review.ts
index d6cedb27d..cb3396445 100644
--- a/sdk/typescript/src/deduplication/checkpointed-review.ts
+++ b/sdk/typescript/src/deduplication/checkpointed-review.ts
@@ -1,6 +1,6 @@
import type { JsonObject } from "../config.js";
+import { configuredCodexHome } from "../auth.js";
import { readFile } from "node:fs/promises";
-import { homedir } from "node:os";
import { join } from "node:path";
import { CodexSecurityError } from "../errors.js";
import type { FindingSearchScope } from "../finding-retrieval.js";
@@ -8,7 +8,6 @@ import { FindingWorkflow, workflowDigest } from "../finding-workflow.js";
import { CODEX_EXECUTABLE_VERSION } from "../version.js";
import {
codexSecurityCredentialHome,
- expandHome,
resolveCodexCommand,
} from "../runtime.js";
import type { CodexReview, CodexReviewRunner } from "./codex-review.js";
@@ -24,10 +23,7 @@ export async function reviewSettingsDigest(
environment: NodeJS.ProcessEnv,
): Promise<string> {
const homes = new Set([
- expandHome(
- environment["CODEX_HOME"] ?? join(homedir(), ".codex"),
- environment,
- ),
+ configuredCodexHome(environment),
codexSecurityCredentialHome(environment),
]);
return workflowDigest({
diff --git a/sdk/typescript/src/deduplication/codex-review.ts b/sdk/typescript/src/deduplication/codex-review.ts
index 618b85833..9f4eff37f 100644
--- a/sdk/typescript/src/deduplication/codex-review.ts
+++ b/sdk/typescript/src/deduplication/codex-review.ts
@@ -29,9 +29,13 @@ import {
} from "../errors.js";
import { configuredCodexHome, readCodexHomeConfig } from "../auth.js";
import {
+ DEFAULT_CODEX_CONFIG,
hasCommandAuth,
+ inlineToml,
modelProviderConfigOverride,
+ normalizeLegacyWindowsSandboxOverride,
resolveCommandAuthConfig,
+ resolveCodexProfile,
} from "../config.js";
import {
reviewErrorInstructions,
@@ -205,6 +209,8 @@ export class CodexReviewRunner {
].find((value) => value?.trim());
const args = ["app-server", "--stdio", "--disable", "plugins"];
const config = await readCodexHomeConfig(environment, this.signal);
+ const executionConfig = resolveCodexProfile(config);
+ normalizeLegacyWindowsSandboxOverride(executionConfig);
if (hasCommandAuth(config)) {
args.push(
...modelProviderConfigOverride(
@@ -238,7 +244,7 @@ export class CodexReviewRunner {
"--config",
`sqlite_home=${JSON.stringify(directory)}`,
"--config",
- 'windows.sandbox="unelevated"',
+ `windows=${inlineToml(executionConfig["windows"] ?? DEFAULT_CODEX_CONFIG["windows"]!)}`,
);
if (apiKey)
args.push("--config", 'cli_auth_credentials_store="ephemeral"');
diff --git a/sdk/typescript/src/deep-config.ts b/sdk/typescript/src/deep-config.ts
index 5b95ccf49..88d8381e6 100644
--- a/sdk/typescript/src/deep-config.ts
+++ b/sdk/typescript/src/deep-config.ts
@@ -120,6 +120,7 @@ export async function resolveDeepScanConfig(
export async function writeDeepScanConfig(
destination: string,
resolved: ResolvedDeepScanConfig,
+ workerRuntime?: JsonObject,
): Promise<void> {
const [source, target] = await Promise.all([
canonicalConfigPath(resolved.source),
@@ -139,6 +140,7 @@ export async function writeDeepScanConfig(
DEEP_SCAN_SETTINGS.some(([name]) => settings[name] === undefined);
await writeCodexConfig(destination, {
...document,
+ ...(workerRuntime === undefined ? {} : { worker_runtime: workerRuntime }),
deep_scan: {
...(retainAmbientSettings
? (document["deep_scan"] as TomlTable | undefined)
diff --git a/sdk/typescript/src/knowledge-base.ts b/sdk/typescript/src/knowledge-base.ts
index 85361d230..a8eb691a4 100644
--- a/sdk/typescript/src/knowledge-base.ts
+++ b/sdk/typescript/src/knowledge-base.ts
@@ -6,12 +6,14 @@ import {
readdir,
realpath,
rm,
+ stat,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, extname, join, resolve } from "node:path";
import { unzipSync } from "fflate";
import { expandHome } from "./runtime.js";
+import { isGitMetadataDirectory, nullIfMissingFile } from "./targets.js";
const DOCUMENT_EXTENSIONS = new Set([
".md",
@@ -124,8 +126,26 @@ async function discover(
signal?.throwIfAborted();
for (const entry of entries) {
signal?.throwIfAborted();
- if (entry.name.toLowerCase() === ".git") continue;
+ if (
+ (process.platform === "win32" ? entry.name.toLowerCase() : entry.name) ===
+ ".git"
+ )
+ continue;
const path = join(directory, entry.name);
+ if (entry.name.toLowerCase() === ".git") {
+ const marker = await stat(join(directory, ".git"), {
+ bigint: true,
+ }).catch(nullIfMissingFile);
+ if (marker !== null) {
+ const candidate = await lstat(path, { bigint: true });
+ if (candidate.dev === marker.dev && candidate.ino === marker.ino) {
+ continue;
+ }
+ }
+ if (entry.isDirectory() && (await isGitMetadataDirectory(path, signal))) {
+ continue;
+ }
+ }
if (entry.isDirectory()) {
for (const document of await discover(path, signal)) {
documents.push(document);
diff --git a/sdk/typescript/src/provider-profile.ts b/sdk/typescript/src/provider-profile.ts
new file mode 100644
index 000000000..22e9e9117
--- /dev/null
+++ b/sdk/typescript/src/provider-profile.ts
@@ -0,0 +1,234 @@
+import { randomUUID } from "node:crypto";
+import { lstat, mkdir, rm } from "node:fs/promises";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import type { Codex, CodexOptions } from "@openai/codex-sdk";
+import { configuredCodexHome } from "./auth.js";
+import {
+ resolveCodexProfile,
+ modelProviderConfigOverride,
+ inlineToml,
+ writeCodexConfig,
+ type JsonObject,
+} from "./config.js";
+import { isRecord } from "./record.js";
+import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";
+import {
+ bundledPluginRoot,
+ acquireCodexSecurityCredentialHomeLock,
+ executablePathForSpawn,
+ requirePrivateCredentialHome,
+ resolveCodexCommand,
+ type CodexCommand,
+} from "./runtime.js";
+
+export interface ProviderProfile {
+ name: string;
+ path: string;
+ cleanup(): Promise<void>;
+}
+
+/** Native no-turn commands need provider metadata when managed policy selects it. */
+export async function providerPreflightCommand(
+ command: CodexCommand,
+ config: JsonObject,
+): Promise<CodexCommand> {
+ const resolved = resolveCodexProfile(config);
+ const overrides: string[] = [];
+ const providers = resolved["model_providers"];
+ if (isRecord(providers) && Object.keys(providers).length > 0) {
+ const client = await nativeProfileClient();
+ const definitions = client.preflightProviderDefinitions(
+ providers,
+ ) as JsonObject;
+ overrides.push(
+ ...modelProviderConfigOverride({ model_providers: definitions }),
+ );
+ }
+ if (resolved["model_provider"] !== undefined)
+ overrides.push(`model_provider=${inlineToml(resolved["model_provider"])}`);
+ if (overrides.length === 0) return command;
+ return {
+ ...command,
+ args: [
+ ...(command.args ?? []),
+ ...overrides.flatMap((value) => ["-c", value]),
+ ],
+ };
+}
+
+/** Provider definitions use a native file layer, never process arguments. */
+export async function createProviderProfile(
+ codexHome: string,
+ config: JsonObject,
+ options: Parameters<typeof requirePrivateCredentialHome>[2] = {},
+): Promise<ProviderProfile> {
+ const providers = resolveCodexProfile(config)["model_providers"];
+ const name = `codex_security_${randomUUID()}`;
+ const path = join(codexHome, `${name}.config.toml`);
+ if ((options.platform ?? process.platform) === "win32") {
+ await mkdir(codexHome, { recursive: true, mode: 0o700 });
+ await requirePrivateCredentialHome(
+ await lstat(codexHome),
+ codexHome,
+ options,
+ );
+ }
+ await writeCodexConfig(path, {
+ model_providers: isRecord(providers) ? providers : {},
+ });
+ return { name, path, cleanup: () => rm(path, { force: true }) };
+}
+
+/** The pinned SDK lacks the native CLI's private profile-file option. */
+export async function createProfileCodex(
+ options: CodexOptions,
+ profileName: string,
+ requestedPermissionProfile?: string,
+): Promise<Codex> {
+ const command =
+ options.codexPathOverride ?? resolveCodexCommand(options.env).command;
+ const client = await nativeProfileClient();
+ return client.createCodexProfileClient({
+ ...options,
+ codexPathOverride: executablePathForSpawn(command),
+ profileName,
+ requestedPermissionProfile,
+ ...(options.env === undefined
+ ? {}
+ : { env: bundledCodexSdkEnvironment(command, options.env) }),
+ }) as Codex;
+}
+
+/** Verify the effective helper policy before starting exec with a private profile. */
+export async function preflightReadOnlyProfileCodex(
+ options: CodexOptions,
+ expectedProfile: JsonObject,
+ providerConfig: JsonObject,
+ cwd: string,
+ signal?: AbortSignal,
+): Promise<{ permissionProfileId: string; configOverrides: string[] }> {
+ const preflight = await nativePermissionPreflight();
+ const permissionProfileId =
+ preflight.DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID as string;
+ const configOverrides = [
+ ...(options.configOverrides ?? []),
+ `default_permissions=${JSON.stringify(permissionProfileId)}`,
+ `permissions.${permissionProfileId}=${inlineToml(expectedProfile)}`,
+ ];
+ const command =
+ options.codexPathOverride ?? resolveCodexCommand(options.env).command;
+ const client = await nativeProfileClient();
+ const providers = resolveCodexProfile(providerConfig)["model_providers"];
+ const definitions = isRecord(providers)
+ ? (client.preflightProviderDefinitions(providers) as JsonObject)
+ : {};
+ const env =
+ options.env === undefined
+ ? undefined
+ : bundledCodexSdkEnvironment(command, options.env);
+ await withCodexPreflightLock(env, signal, async () => {
+ await preflight.preflightDeepScanWorkerPermissionProfile({
+ codexPath: executablePathForSpawn(command),
+ cwd,
+ configOverrides: [
+ ...client.profileConfigOverrides(options.config ?? {}),
+ ...configOverrides,
+ ],
+ providerConfigOverrides: modelProviderConfigOverride({
+ model_providers: definitions,
+ }),
+ ...(env === undefined
+ ? {}
+ : {
+ env: {
+ ...env,
+ ...(options.apiKey === undefined
+ ? {}
+ : { CODEX_API_KEY: options.apiKey }),
+ },
+ }),
+ expectedProfile,
+ signal: signal ?? new AbortController().signal,
+ context: "helper",
+ });
+ });
+ return { permissionProfileId, configOverrides };
+}
+
+/** Older workers must inherit the same effective provider as the parent scan. */
+export async function legacyWorkerUsesScanProvider(
+ command: CodexCommand,
+ environment: Record<string, string>,
+ cwd: string,
+ modelProvider: string,
+ signal?: AbortSignal,
+): Promise<boolean> {
+ const preflight = await nativePermissionPreflight();
+ const env = bundledCodexSdkEnvironment(command.command, environment);
+ return await withCodexPreflightLock(env, signal, async () => {
+ const options = {
+ codexPath: executablePathForSpawn(command.command),
+ commandArgs: command.args,
+ cwd,
+ env,
+ signal: signal ?? new AbortController().signal,
+ context: "helper",
+ };
+ const worker = await preflight.readDeepScanRuntimeConfig({
+ ...options,
+ configOverrides: [],
+ });
+ const parent = await preflight.readDeepScanRuntimeConfig({
+ ...options,
+ configOverrides: [`model_provider=${JSON.stringify(modelProvider)}`],
+ });
+ return (
+ (worker.model_provider ?? "openai") ===
+ (parent.model_provider ?? "openai")
+ );
+ });
+}
+
+async function withCodexPreflightLock<T>(
+ env: Record<string, string> | undefined,
+ signal: AbortSignal | undefined,
+ operation: () => Promise<T>,
+): Promise<T> {
+ // App-server treats concurrent cold-home SQLite initialization as fatal.
+ // Keep the lock in a private child so a readable native home stays readable.
+ const lockDirectory = join(
+ configuredCodexHome(env ?? process.env),
+ ".codex-security-preflight",
+ );
+ await mkdir(lockDirectory, { recursive: true, mode: 0o700 });
+ const release = await acquireCodexSecurityCredentialHomeLock(
+ lockDirectory,
+ signal,
+ );
+ try {
+ return await operation();
+ } finally {
+ await release();
+ }
+}
+
+async function nativePermissionPreflight() {
+ return await import(
+ pathToFileURL(
+ join(
+ await bundledPluginRoot(),
+ "mcp",
+ "permission-profile-preflight.mjs",
+ ),
+ ).href
+ );
+}
+
+async function nativeProfileClient() {
+ return await import(
+ pathToFileURL(
+ join(await bundledPluginRoot(), "scripts", "codex_profile.mjs"),
+ ).href
+ );
+}
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 7f25e4660..514553f04 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -38,6 +38,7 @@ import {
join,
relative,
resolve,
+ sep,
win32,
} from "node:path";
import { fileURLToPath } from "node:url";
@@ -156,6 +157,7 @@ export interface PluginInstall {
export interface CodexCommand {
command: string;
+ args?: readonly string[];
}
interface CodexCommandResult {
@@ -2365,6 +2367,13 @@ export async function createMarketplace(
const marketplace = join(codexHome, "sdk-marketplace");
const pluginDestination = join(marketplace, "plugins", PLUGIN_NAME);
await copyPluginTree(root, pluginDestination, signal);
+ const projection = await legacyPluginProjection(pluginDestination, signal);
+ for (const [path, file] of projection?.files ?? []) {
+ const destination = join(pluginDestination, path);
+ await mkdir(dirname(destination), { recursive: true });
+ await writeFile(destination, file.contents, { mode: file.mode, signal });
+ if (file.mode !== undefined) await chmod(destination, file.mode);
+ }
await writeMarketplaceManifest(marketplace, signal);
return marketplace;
}
@@ -2403,6 +2412,108 @@ async function writeMarketplaceManifest(
}
}
+type LegacyPluginProjection = {
+ root: string;
+ files: Map<string, { contents: Buffer; mode?: number }>;
+};
+
+async function legacyPluginProjection(
+ root: string,
+ signal?: AbortSignal,
+): Promise<LegacyPluginProjection | undefined> {
+ const path = join(root, ".mcp.json");
+ // Keep the source link checks ahead of any configuration read.
+ if (!(await lstat(path).catch(nullIfMissingFileError))?.isFile()) return;
+ const configuration: unknown = JSON.parse(
+ await readFile(path, { encoding: "utf8", signal }),
+ );
+ const servers = isRecord(configuration)
+ ? configuration["mcpServers"]
+ : undefined;
+ const server = isRecord(servers) ? servers[PLUGIN_NAME] : undefined;
+ if (
+ !isRecord(server) ||
+ (server["command"] !== "./scripts/launch_codex_security_mcp" &&
+ server["command"] !== "./scripts/launch_codex_security_mcp.cmd" &&
+ !isLegacyNodeMcpServer(server))
+ ) {
+ return;
+ }
+ const environment = server["env_vars"];
+ if (environment !== undefined && !Array.isArray(environment)) return;
+ const directNode = isLegacyNodeMcpServer(server);
+ if (
+ !Array.isArray(environment) ||
+ !environment.includes("CODEX_SECURITY_PLUGIN_ROOT")
+ ) {
+ server["env_vars"] = [
+ ...(Array.isArray(environment) ? environment : []),
+ "CODEX_SECURITY_PLUGIN_ROOT",
+ ];
+ }
+ const files: LegacyPluginProjection["files"] = new Map();
+ if (directNode) {
+ const args = [...(server["args"] as string[])];
+ args[args.findIndex(isLegacyNodeMcpEntry)] =
+ "./mcp/codex_security_sdk_bridge.mjs";
+ server["args"] = args;
+ files.set("mcp/codex_security_sdk_bridge.mjs", {
+ contents: Buffer.from(
+ 'import { runMain } from "node:module";\n' +
+ 'import { dirname, join } from "node:path";\n' +
+ 'import { fileURLToPath } from "node:url";\n' +
+ "const root = process.env.CODEX_SECURITY_PLUGIN_ROOT;\n" +
+ 'process.argv[1] = root ? join(root, "mcp", "server.mjs") : join(dirname(fileURLToPath(import.meta.url)), "server.mjs");\n' +
+ "runMain(process.argv[1]);\n",
+ ),
+ mode: 0o644,
+ });
+ } else {
+ server["command"] =
+ server["command"] === "./scripts/launch_codex_security_mcp.cmd"
+ ? "./scripts/launch_codex_security_mcp_sdk.cmd"
+ : "./scripts/launch_codex_security_mcp_sdk";
+ files.set("scripts/launch_codex_security_mcp_sdk", {
+ contents: Buffer.from(
+ "#!/bin/sh\n" +
+ 'if [ -n "${CODEX_SECURITY_PLUGIN_ROOT:-}" ]; then\n' +
+ ' exec "$CODEX_SECURITY_PLUGIN_ROOT/scripts/launch_codex_security_mcp" "$@"\n' +
+ "fi\n" +
+ 'exec "$(dirname "$0")/launch_codex_security_mcp" "$@"\n',
+ ),
+ mode: 0o755,
+ });
+ files.set("scripts/launch_codex_security_mcp_sdk.cmd", {
+ contents: Buffer.from(
+ "@echo off\r\nsetlocal DisableDelayedExpansion\r\n" +
+ "if not defined CODEX_SECURITY_PLUGIN_ROOT goto codex_security_sdk_original\r\n" +
+ '"%CODEX_SECURITY_PLUGIN_ROOT%\\scripts\\launch_codex_security_mcp.cmd" %*\r\n' +
+ "exit /b\r\n:codex_security_sdk_original\r\n" +
+ '"%~dp0launch_codex_security_mcp.cmd" %*\r\n',
+ ),
+ mode: 0o755,
+ });
+ }
+ files.set(".mcp.json", {
+ contents: Buffer.from(`${JSON.stringify(configuration, null, 2)}\n`),
+ });
+ return { root, files };
+}
+
+function isLegacyNodeMcpEntry(argument: unknown): boolean {
+ return argument === "./mcp/server.mjs" || argument === "mcp/server.mjs";
+}
+
+function isLegacyNodeMcpServer(server: Record<string, unknown>): boolean {
+ const command = server["command"];
+ return (
+ typeof command === "string" &&
+ ["node", "node.exe"].includes(basename(command).toLowerCase()) &&
+ Array.isArray(server["args"]) &&
+ server["args"].some(isLegacyNodeMcpEntry)
+ );
+}
+
export function resolveCodexCommand(
environment: ProcessEnvironment = process.env,
): CodexCommand {
@@ -2476,6 +2587,7 @@ export async function bootstrapPlugin(
): Promise<PluginInstall> {
const root = await realpath(pluginRoot);
const { name, version } = await pluginMetadata(root);
+ const projection = await legacyPluginProjection(root, options.signal);
const marketplace = join(codexHome, "sdk-marketplace");
throwIfSignalAborted(options.signal);
const command =
@@ -2501,7 +2613,13 @@ export async function bootstrapPlugin(
const stagedRoot = join(marketplace, "plugins", PLUGIN_NAME);
const stagedMatches =
staged?.version === version &&
- (await pluginContentsMatch(root, stagedRoot, options.signal));
+ (await pluginContentsMatch(
+ root,
+ stagedRoot,
+ options.signal,
+ false,
+ projection,
+ ));
if (!stagedMatches) {
if (existing !== null) {
@@ -2574,6 +2692,7 @@ export async function bootstrapPlugin(
previous["installedPath"],
options.signal,
true,
+ projection,
))
) {
return {
@@ -2637,6 +2756,7 @@ async function pluginContentsMatch(
destination: string,
signal?: AbortSignal,
allowExtraFiles = false,
+ projection?: LegacyPluginProjection,
): Promise<boolean> {
throwIfSignalAborted(signal);
@@ -2653,19 +2773,23 @@ async function pluginContentsMatch(
if (destinationMetadata === null) return false;
if (sourceMetadata.isFile() && destinationMetadata.isFile()) {
+ const projected = projection?.files.get(
+ relative(projection.root, source).split(sep).join("/"),
+ );
if (
- sourceMetadata.size !== destinationMetadata.size ||
- (sourceMetadata.mode & 0o111) !== (destinationMetadata.mode & 0o111)
+ (projected === undefined &&
+ sourceMetadata.size !== destinationMetadata.size) ||
+ ((projected?.mode === undefined || process.platform !== "win32") &&
+ ((projected?.mode ?? sourceMetadata.mode) & 0o111) !==
+ (destinationMetadata.mode & 0o111))
) {
return false;
}
-
const [sourceBytes, destinationBytes] = await Promise.all([
readFile(source, { signal }),
readFile(destination, { signal }),
]);
-
- return sourceBytes.equals(destinationBytes);
+ return (projected?.contents ?? sourceBytes).equals(destinationBytes);
}
if (!sourceMetadata.isDirectory() || !destinationMetadata.isDirectory()) {
@@ -2673,13 +2797,32 @@ async function pluginContentsMatch(
}
const entries = await readdir(source);
-
+ const projectedDirectory =
+ projection === undefined
+ ? undefined
+ : relative(projection.root, source).split(sep).join("/") || ".";
+ const generated = [...(projection?.files ?? [])].filter(
+ ([path]) =>
+ dirname(path) === projectedDirectory && !entries.includes(basename(path)),
+ );
if (
!allowExtraFiles &&
- entries.length !== (await readdir(destination)).length
+ entries.length + generated.length !== (await readdir(destination)).length
) {
return false;
}
+ for (const [path, file] of generated) {
+ const generatedPath = join(destination, basename(path));
+ const metadata = await lstat(generatedPath).catch(nullIfMissingFileError);
+ if (
+ !metadata?.isFile() ||
+ (process.platform !== "win32" &&
+ (metadata.mode & 0o111) !== ((file.mode ?? 0o644) & 0o111)) ||
+ !file.contents.equals(await readFile(generatedPath, { signal }))
+ ) {
+ return false;
+ }
+ }
for (const entry of entries) {
if (
@@ -2688,6 +2831,7 @@ async function pluginContentsMatch(
join(destination, entry),
signal,
allowExtraFiles,
+ projection,
))
) {
return false;
@@ -2752,8 +2896,10 @@ export async function resolvePluginPython(
}
const home = options.homeDirectory ?? homedir();
+ const cacheDirectory =
+ environmentValue(environment, "XDG_CACHE_HOME") || join(home, ".cache");
const managedRoots = options.managedRuntimeRoots ?? [
- join(home, ".cache", "codex-runtimes", "codex-primary-runtime"),
+ join(cacheDirectory, "codex-runtimes", "codex-primary-runtime"),
];
const relativeCandidates =
process.platform === "win32"
@@ -2859,12 +3005,16 @@ export async function runCodexCommand(
input?: string | Uint8Array,
signal?: AbortSignal,
): Promise<CodexCommandResult> {
- const child = spawn(executablePathForSpawn(command.command), [...args], {
- env: environment,
- stdio: ["pipe", "pipe", "pipe"],
- windowsHide: true,
- signal,
- });
+ const child = spawn(
+ executablePathForSpawn(command.command),
+ [...(command.args ?? []), ...args],
+ {
+ env: environment,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ signal,
+ },
+ );
let stdout = "";
let stderr = "";
let processError: Error | undefined;
diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.ts
index ed938b16a..2f19d9457 100644
--- a/sdk/typescript/src/scan-comparison.ts
+++ b/sdk/typescript/src/scan-comparison.ts
@@ -1,6 +1,7 @@
import { existsSync } from "node:fs";
+import { isRecord } from "./record.js";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import {
Codex,
type CodexOptions,
@@ -19,19 +20,27 @@ import {
withoutOpenAiApiKeys,
} from "./auth.js";
import {
+ DEFAULT_CODEX_CONFIG,
deepMerge,
hasCommandAuth,
mergedCodexConfig,
- modelProviderConfigOverride,
+ normalizeLegacyWindowsSandboxOverride,
resolveCodexProfile,
resolveCommandAuthConfig,
scanCyberAccessConfig,
scanModelConfiguration,
scanModelProvider,
+ structuredCodexConfig,
type CodexSecurityConfig,
type JsonObject,
} from "./config.js";
import { CodexSecurityError, ConfigurationError } from "./errors.js";
+import {
+ createProfileCodex,
+ createProviderProfile,
+ preflightReadOnlyProfileCodex,
+ providerPreflightCommand,
+} from "./provider-profile.js";
import {
compactFinding,
findingCatalogue,
@@ -141,6 +150,8 @@ export interface ReadOnlyCodexOptions {
/** @internal Cyber access program already selected by the calling scan. */
cyberAccessProgram?: CyberAccessProgram;
config?: CodexSecurityConfig;
+ /** @internal Private native profile owned by the calling scan. */
+ nativeProfile?: { name: string; path: string };
/** @internal */
codex?: ReadOnlyCodex;
environment?: NodeJS.ProcessEnv;
@@ -159,8 +170,10 @@ export interface ScanComparisonOptions extends ReadOnlyCodexOptions {
interface CompletedScanMatchingOptions extends Pick<
ScanComparisonOptions,
- "environment" | "model" | "signal"
+ "config" | "environment" | "model" | "signal"
> {
+ /** @internal Private native profile owned by the calling scan. */
+ nativeProfile?: ReadOnlyCodexOptions["nativeProfile"];
/** @internal Cyber access program already selected by the calling scan. */
cyberAccessProgram?: CyberAccessProgram;
scanId: string;
@@ -302,7 +315,7 @@ export async function matchScanFindingsInternal(
}
}
}
- const thread = await startReadOnlyCodexThread(options, {
+ const { thread, cleanup } = await startReadOnlyCodexThread(options, {
...runtimeOptions,
threadSource: CODEX_SECURITY_THREAD_SOURCES.scanComparison,
});
@@ -338,182 +351,191 @@ export async function matchScanFindingsInternal(
};
let prompt = comparisonPrompt(pages[0]!, 0, pages.length);
progress("catalogue", 1);
- for (;;) {
- options.signal?.throwIfAborted();
- const turn = await thread.run(prompt, turnOptions);
- let response: unknown;
- try {
- response = JSON.parse(turn.finalResponse);
- } catch (error) {
- throw new CodexSecurityError("Scan comparison returned invalid JSON.", {
- cause: error,
- });
- }
- const parsed = matchingTurnSchema.safeParse(response);
- if (!parsed.success) {
- throw new CodexSecurityError(
- "Scan comparison returned an invalid match result.",
- );
- }
- const { request: modelRequest, ...result } = parsed.data;
- let request = modelRequest;
- if (request == null) {
- const unseenPage = remainingPages.values().next().value;
- if (unseenPage !== undefined) {
- request = { kind: "catalogue", page: unseenPage };
- } else {
- validateComparison(
- initialCatalogue,
- result,
- options.allowHistoricalUncertainty ?? false,
- );
- // Omitted descriptions need evidence even for a no-match decision.
- request = requiredEvidenceRequest(
- result.matches,
- omittedEvidence,
- requestedEvidence,
- );
+ try {
+ for (;;) {
+ options.signal?.throwIfAborted();
+ const turn = await thread.run(prompt, turnOptions);
+ let response: unknown;
+ try {
+ response = JSON.parse(turn.finalResponse);
+ } catch (error) {
+ throw new CodexSecurityError("Scan comparison returned invalid JSON.", {
+ cause: error,
+ });
}
- } else if (
- result.matches.length > 0 ||
- result.uncertain.length > 0 ||
- (result.related?.length ?? 0) > 0
- ) {
- throw new CodexSecurityError(
- "Scan comparison cannot request evidence and finish at the same time.",
- );
- }
- if (request != null) {
- if (runtimeOptions.singleTurn) {
- throw new CodexSecurityError(AUTOMATIC_MATCHING_LIMIT_MESSAGE);
+ const parsed = matchingTurnSchema.safeParse(response);
+ if (!parsed.success) {
+ throw new CodexSecurityError(
+ "Scan comparison returned an invalid match result.",
+ );
}
- if (request.kind === "catalogue") {
- const page = pages[request.page];
- if (page === undefined) {
- throw new CodexSecurityError(
- "Scan comparison requested an unknown catalogue page.",
+ const { request: modelRequest, ...result } = parsed.data;
+ let request = modelRequest;
+ if (request == null) {
+ const unseenPage = remainingPages.values().next().value;
+ if (unseenPage !== undefined) {
+ request = { kind: "catalogue", page: unseenPage };
+ } else {
+ validateComparison(
+ initialCatalogue,
+ result,
+ options.allowHistoricalUncertainty ?? false,
);
- }
- if (!remainingPages.delete(request.page)) {
- throw new CodexSecurityError(
- "Scan comparison repeated a request without making progress.",
+ // Omitted descriptions need evidence even for a no-match decision.
+ request = requiredEvidenceRequest(
+ result.matches,
+ omittedEvidence,
+ requestedEvidence,
);
}
- prompt = comparisonPrompt(page, request.page, pages.length);
- progress("catalogue", request.page + 1);
- } else {
- request.beforeOccurrenceIds = [
- ...new Set(request.beforeOccurrenceIds),
- ].sort();
- request.afterOccurrenceIds = [
- ...new Set(request.afterOccurrenceIds),
- ].sort();
- if (
- (request.beforeOccurrenceIds.length === 0 &&
- request.afterOccurrenceIds.length === 0) ||
- request.beforeOccurrenceIds.some((id) => !catalogue.has(id)) ||
- request.afterOccurrenceIds.some((id) => !after.has(id))
- ) {
- throw new CodexSecurityError(
- "Scan comparison requested evidence outside its findings.",
- );
- }
- const requestKey = JSON.stringify([
- request.beforeOccurrenceIds,
- request.afterOccurrenceIds,
- ]);
- const previous = evidenceCursors.get(requestKey);
- const expectedOffset = previous === undefined ? 0 : previous.nextOffset;
- if (request.offset !== expectedOffset) {
- throw new CodexSecurityError(
- "Scan comparison requested an invalid evidence offset; start at 0 and follow nextOffset.",
- );
+ } else if (
+ result.matches.length > 0 ||
+ result.uncertain.length > 0 ||
+ (result.related?.length ?? 0) > 0
+ ) {
+ throw new CodexSecurityError(
+ "Scan comparison cannot request evidence and finish at the same time.",
+ );
+ }
+ if (request != null) {
+ if (runtimeOptions.singleTurn) {
+ throw new CodexSecurityError(AUTOMATIC_MATCHING_LIMIT_MESSAGE);
}
- let cursor = previous;
- if (cursor === undefined) {
- const beforeOccurrenceIds = request.beforeOccurrenceIds.filter(
- (id) => !requestedEvidence.before.has(id),
- );
- const afterOccurrenceIds = request.afterOccurrenceIds.filter(
- (id) => !requestedEvidence.after.has(id),
- );
+ if (request.kind === "catalogue") {
+ const page = pages[request.page];
+ if (page === undefined) {
+ throw new CodexSecurityError(
+ "Scan comparison requested an unknown catalogue page.",
+ );
+ }
+ if (!remainingPages.delete(request.page)) {
+ throw new CodexSecurityError(
+ "Scan comparison repeated a request without making progress.",
+ );
+ }
+ prompt = comparisonPrompt(page, request.page, pages.length);
+ progress("catalogue", request.page + 1);
+ } else {
+ request.beforeOccurrenceIds = [
+ ...new Set(request.beforeOccurrenceIds),
+ ].sort();
+ request.afterOccurrenceIds = [
+ ...new Set(request.afterOccurrenceIds),
+ ].sort();
if (
- beforeOccurrenceIds.length === 0 &&
- afterOccurrenceIds.length === 0
+ (request.beforeOccurrenceIds.length === 0 &&
+ request.afterOccurrenceIds.length === 0) ||
+ request.beforeOccurrenceIds.some((id) => !catalogue.has(id)) ||
+ request.afterOccurrenceIds.some((id) => !after.has(id))
) {
throw new CodexSecurityError(
- "Scan comparison repeated evidence without making progress. Continue an unfinished selection with its returned IDs and nextOffset.",
+ "Scan comparison requested evidence outside its findings.",
+ );
+ }
+ const requestKey = JSON.stringify([
+ request.beforeOccurrenceIds,
+ request.afterOccurrenceIds,
+ ]);
+ const previous = evidenceCursors.get(requestKey);
+ const expectedOffset =
+ previous === undefined ? 0 : previous.nextOffset;
+ if (request.offset !== expectedOffset) {
+ throw new CodexSecurityError(
+ "Scan comparison requested an invalid evidence offset; start at 0 and follow nextOffset.",
+ );
+ }
+ let cursor = previous;
+ if (cursor === undefined) {
+ const beforeOccurrenceIds = request.beforeOccurrenceIds.filter(
+ (id) => !requestedEvidence.before.has(id),
+ );
+ const afterOccurrenceIds = request.afterOccurrenceIds.filter(
+ (id) => !requestedEvidence.after.has(id),
);
+ if (
+ beforeOccurrenceIds.length === 0 &&
+ afterOccurrenceIds.length === 0
+ ) {
+ throw new CodexSecurityError(
+ "Scan comparison repeated evidence without making progress. Continue an unfinished selection with its returned IDs and nextOffset.",
+ );
+ }
+ cursor = {
+ beforeOccurrenceIds,
+ afterOccurrenceIds,
+ text: JSON.stringify({
+ before: beforeOccurrenceIds.flatMap(
+ (id) => catalogue.get(id)!.occurrences,
+ ),
+ after: afterOccurrenceIds.map((id) => after.get(id)!),
+ }),
+ utf16Offset: 0,
+ nextOffset: 0,
+ };
}
- cursor = {
- beforeOccurrenceIds,
- afterOccurrenceIds,
- text: JSON.stringify({
- before: beforeOccurrenceIds.flatMap(
- (id) => catalogue.get(id)!.occurrences,
- ),
- after: afterOccurrenceIds.map((id) => after.get(id)!),
- }),
- utf16Offset: 0,
- nextOffset: 0,
- };
+ const page = evidencePage(cursor, request.offset);
+ cursor.nextOffset = page.nextOffset;
+ cursor.utf16Offset = page.nextUtf16Offset;
+ // Keep completed cursors to reject repeats, but release their evidence.
+ if (page.nextOffset === null) cursor.text = "";
+ // Either the original selection or the returned fresh IDs can resume it.
+ evidenceCursors.set(requestKey, cursor);
+ evidenceCursors.set(
+ JSON.stringify([
+ cursor.beforeOccurrenceIds,
+ cursor.afterOccurrenceIds,
+ ]),
+ cursor,
+ );
+ for (const id of cursor.beforeOccurrenceIds)
+ requestedEvidence.before.set(id, cursor);
+ for (const id of cursor.afterOccurrenceIds)
+ requestedEvidence.after.set(id, cursor);
+ prompt = page.prompt;
+ progress("evidence");
}
- const page = evidencePage(cursor, request.offset);
- cursor.nextOffset = page.nextOffset;
- cursor.utf16Offset = page.nextUtf16Offset;
- // Keep completed cursors to reject repeats, but release their evidence.
- if (page.nextOffset === null) cursor.text = "";
- // Either the original selection or the returned fresh IDs can resume it.
- evidenceCursors.set(requestKey, cursor);
- evidenceCursors.set(
- JSON.stringify([
- cursor.beforeOccurrenceIds,
- cursor.afterOccurrenceIds,
- ]),
- cursor,
- );
- for (const id of cursor.beforeOccurrenceIds)
- requestedEvidence.before.set(id, cursor);
- for (const id of cursor.afterOccurrenceIds)
- requestedEvidence.after.set(id, cursor);
- prompt = page.prompt;
- progress("evidence");
+ continue;
}
- continue;
- }
- const expandBefore = (id: string) =>
- catalogue.get(id)!.occurrences.map(({ occurrenceId }) => occurrenceId);
- const expandPairs = (pairs: ScanComparisonResult["uncertain"]) =>
- pairs.flatMap((pair) =>
- expandBefore(pair.beforeOccurrenceId).map((beforeOccurrenceId) => ({
- ...pair,
- beforeOccurrenceId,
- })),
+ const expandBefore = (id: string) =>
+ catalogue.get(id)!.occurrences.map(({ occurrenceId }) => occurrenceId);
+ const expandPairs = (pairs: ScanComparisonResult["uncertain"]) =>
+ pairs.flatMap((pair) =>
+ expandBefore(pair.beforeOccurrenceId).map((beforeOccurrenceId) => ({
+ ...pair,
+ beforeOccurrenceId,
+ })),
+ );
+ const expanded = reconcileComparison(
+ input,
+ {
+ matches: result.matches.map((match) => ({
+ ...match,
+ beforeOccurrenceIds:
+ match.beforeOccurrenceIds.flatMap(expandBefore),
+ })),
+ uncertain: expandPairs(result.uncertain),
+ ...(result.related === undefined
+ ? {}
+ : { related: expandPairs(result.related) }),
+ },
+ options.allowHistoricalUncertainty ?? false,
);
- const expanded = reconcileComparison(
- input,
- {
- matches: result.matches.map((match) => ({
- ...match,
- beforeOccurrenceIds: match.beforeOccurrenceIds.flatMap(expandBefore),
- })),
- uncertain: expandPairs(result.uncertain),
- ...(result.related === undefined
- ? {}
- : { related: expandPairs(result.related) }),
- },
- options.allowHistoricalUncertainty ?? false,
- );
- progress("complete");
- return expanded.comparison;
+ progress("complete");
+ return expanded.comparison;
+ }
+ } finally {
+ await cleanup?.();
}
}
async function startReadOnlyCodexThread(
options: ReadOnlyCodexOptions,
runtimeOptions: Parameters<typeof runReadOnlyCodex>[3],
-): Promise<ReturnType<ReadOnlyCodex["startThread"]>> {
+): Promise<{
+ thread: ReturnType<ReadOnlyCodex["startThread"]>;
+ cleanup?: () => Promise<void>;
+}> {
const config =
options.config === undefined
? undefined
@@ -523,17 +545,37 @@ async function startReadOnlyCodexThread(
const model = options.model ?? configuredModel?.model;
const reasoningEffort =
options.reasoningEffort ?? configuredModel?.reasoningEffort ?? "medium";
+ const threadOptions: ThreadOptions = {
+ threadSource: runtimeOptions.threadSource,
+ ...(model === undefined ? {} : { model }),
+ // Native Codex accepts strings before the pinned SDK widens its effort type.
+ modelReasoningEffort: reasoningEffort as ModelReasoningEffort,
+ sandboxMode: "read-only",
+ approvalPolicy: "never",
+ networkAccessEnabled: false,
+ webSearchMode: "disabled",
+ workingDirectory: options.workingDirectory ?? process.cwd(),
+ skipGitRepoCheck: true,
+ };
+ if (options.codex !== undefined) {
+ return { thread: options.codex.startThread(threadOptions) };
+ }
const source = options.environment ?? process.env;
- const providerConfig =
- options.codex === undefined
- ? resolveCommandAuthConfig(
- deepMerge(
- await readCodexHomeConfig(source, options.signal),
- config ?? {},
- ),
- configuredCodexHome(source),
- )
- : {};
+ const homeConfig = await readCodexHomeConfig(source, options.signal);
+ const homeExecutionConfig = resolveCodexProfile(homeConfig);
+ normalizeLegacyWindowsSandboxOverride(homeExecutionConfig);
+ const providerConfig = resolveCommandAuthConfig(
+ deepMerge(homeConfig, config ?? {}),
+ configuredCodexHome(source),
+ );
+ const suppliedConfig = resolveCodexProfile(
+ options.config?.codexOverrides ?? {},
+ );
+ normalizeLegacyWindowsSandboxOverride(suppliedConfig);
+ const windows =
+ suppliedConfig["windows"] === undefined
+ ? (homeExecutionConfig["windows"] ?? DEFAULT_CODEX_CONFIG["windows"])
+ : resolveCodexProfile(config ?? {})["windows"];
const commandAuth = hasCommandAuth(providerConfig);
if (
commandAuth &&
@@ -547,83 +589,111 @@ async function startReadOnlyCodexThread(
"Remove the conflicting provider configuration or select command authentication through codexOverrides.",
);
}
- const sdkConfig = { ...config };
- if (commandAuth) delete sdkConfig["model_providers"];
+ const sdkConfig = structuredCodexConfig(config);
+ delete sdkConfig["default_permissions"];
+ const providerSettings = commandAuth ? providerConfig : (config ?? {});
const effectiveFeatures = resolveCodexProfile(
scanCyberAccessConfig(providerConfig, options.cyberAccessProgram),
)["features"] as JsonObject | undefined;
- const environment =
- options.codex === undefined
- ? await comparisonEnvironment(
- options.environment,
- accountStatus,
- options.signal,
- undefined,
- providerConfig,
+ const environment = await comparisonEnvironment(
+ options.environment,
+ accountStatus,
+ options.signal,
+ undefined,
+ providerConfig,
+ );
+ const command = resolveCodexCommand(environment);
+ const codexOptions: CodexOptions = {
+ codexPathOverride: executablePathForSpawn(command.command),
+ env: environment,
+ // The SDK forwards its apiKey option as CODEX_API_KEY for Codex exec.
+ apiKey:
+ environmentEntry(environment, "OPENAI_API_KEY")?.trim() ||
+ environmentEntry(environment, "CODEX_API_KEY")?.trim() ||
+ undefined,
+ config: {
+ ...sdkConfig,
+ windows,
+ mcp_servers: await disabledMcpServers(
+ await providerPreflightCommand(command, providerSettings),
+ config,
+ environment,
+ options,
+ ),
+ allow_login_shell: false,
+ project_doc_max_bytes: 0,
+ responses_api_metadata: {
+ codex_security_surface: runtimeOptions.surface,
+ },
+ features: {
+ api_key_cyber_access_programs:
+ effectiveFeatures?.["api_key_cyber_access_programs"],
+ api_key_model_discovery: effectiveFeatures?.["api_key_model_discovery"],
+ apps: false,
+ code_mode: false,
+ code_mode_only: false,
+ js_repl: false,
+ multi_agent: false,
+ multi_agent_v2: false,
+ plugins: false,
+ shell_tool: false,
+ unified_exec: false,
+ },
+ shell_environment_policy: {
+ inherit: "core",
+ ignore_default_excludes: false,
+ exclude: ["CODEX_HOME", "*KEY*", "*SECRET*", "*TOKEN*"],
+ },
+ } as NonNullable<CodexOptions["config"]>,
+ };
+ const providers = resolveCodexProfile(providerSettings)["model_providers"];
+ const ownProfile =
+ options.nativeProfile === undefined &&
+ isRecord(providers) &&
+ Object.keys(providers).length > 0
+ ? await createProviderProfile(
+ configuredCodexHome(environment),
+ providerSettings,
)
: undefined;
- const command =
- environment === undefined ? undefined : resolveCodexCommand(environment);
- const codex =
- options.codex ??
- new Codex({
- codexPathOverride: executablePathForSpawn(command!.command),
- env: environment,
- // The SDK forwards its apiKey option as CODEX_API_KEY for Codex exec.
- apiKey:
- environmentEntry(environment!, "OPENAI_API_KEY")?.trim() ||
- environmentEntry(environment!, "CODEX_API_KEY")?.trim() ||
- undefined,
- ...(commandAuth
- ? { configOverrides: modelProviderConfigOverride(providerConfig) }
- : {}),
- config: {
- ...sdkConfig,
- mcp_servers: await disabledMcpServers(
- command!,
- config,
- environment!,
- options,
- ),
- allow_login_shell: false,
- project_doc_max_bytes: 0,
- responses_api_metadata: {
- codex_security_surface: runtimeOptions.surface,
- },
- features: {
- api_key_cyber_access_programs:
- effectiveFeatures?.["api_key_cyber_access_programs"],
- api_key_model_discovery:
- effectiveFeatures?.["api_key_model_discovery"],
- apps: false,
- code_mode: false,
- code_mode_only: false,
- js_repl: false,
- multi_agent: false,
- multi_agent_v2: false,
- plugins: false,
- shell_tool: false,
- unified_exec: false,
- },
- shell_environment_policy: {
- inherit: "core",
- ignore_default_excludes: false,
- exclude: ["CODEX_HOME", "*KEY*", "*SECRET*", "*TOKEN*"],
+ const profile = options.nativeProfile ?? ownProfile;
+ try {
+ let requestedPermissionProfile: string | undefined;
+ if (profile !== undefined) {
+ delete threadOptions.sandboxMode;
+ const permissions = await preflightReadOnlyProfileCodex(
+ codexOptions,
+ {
+ extends: ":read-only",
+ filesystem: {
+ ":root": "read",
+ [dirname(profile.path)]: { ".": "deny" },
+ },
+ network: { enabled: false },
},
- } as NonNullable<CodexOptions["config"]>,
- });
- return codex.startThread({
- threadSource: runtimeOptions.threadSource,
- ...(model === undefined ? {} : { model }),
- // Native Codex accepts strings before the pinned SDK widens its effort type.
- modelReasoningEffort: reasoningEffort as ModelReasoningEffort,
- sandboxMode: "read-only",
- approvalPolicy: "never",
- networkAccessEnabled: false,
- webSearchMode: "disabled",
- workingDirectory: options.workingDirectory ?? process.cwd(),
- skipGitRepoCheck: true,
- });
+ providerSettings,
+ threadOptions.workingDirectory!,
+ options.signal,
+ );
+ codexOptions.configOverrides = permissions.configOverrides;
+ requestedPermissionProfile = permissions.permissionProfileId;
+ }
+ const codex =
+ profile === undefined
+ ? new Codex(codexOptions)
+ : await createProfileCodex(
+ codexOptions,
+ profile.name,
+ requestedPermissionProfile,
+ );
+ return {
+ thread: codex.startThread(threadOptions),
+ ...(ownProfile === undefined ? {} : { cleanup: ownProfile.cleanup }),
+ };
+ } catch (error) {
+ await ownProfile?.cleanup();
+ throw error;
+ }
}
export async function runReadOnlyCodex(
@@ -635,13 +705,20 @@ export async function runReadOnlyCodex(
threadSource: ReadOnlyCodexThreadSource;
},
): Promise<string> {
- const thread = await startReadOnlyCodexThread(options, runtimeOptions);
- const turn = await thread.run(prompt, {
- outputSchema,
- cyberAccessProgram: options.cyberAccessProgram,
- signal: options.signal,
- });
- return turn.finalResponse;
+ const { thread, cleanup } = await startReadOnlyCodexThread(
+ options,
+ runtimeOptions,
+ );
+ try {
+ const turn = await thread.run(prompt, {
+ outputSchema,
+ cyberAccessProgram: options.cyberAccessProgram,
+ signal: options.signal,
+ });
+ return turn.finalResponse;
+ } finally {
+ await cleanup?.();
+ }
}
export async function disabledMcpServers(
@@ -734,9 +811,11 @@ export async function matchCompletedScan(
};
const comparison = await (options.matchFindings ?? matchScanFindings)(input, {
allowHistoricalUncertainty: true,
+ config: options.config,
cyberAccessProgram: options.cyberAccessProgram,
environment: options.environment,
model: options.model,
+ nativeProfile: options.nativeProfile,
signal: options.signal,
workingDirectory: options.repository,
});
@@ -1139,7 +1218,7 @@ export async function comparisonEnvironment(
}
storedEnvironment["CODEX_HOME"] = canonicalCredentialHome;
const status = await nativeAccountStatus(
- resolveCodexCommand(source),
+ await providerPreflightCommand(resolveCodexCommand(source), config ?? {}),
storedEnvironment,
signal,
);
diff --git a/sdk/typescript/src/server/serve.ts b/sdk/typescript/src/server/serve.ts
index 3b718fbbd..edce375ed 100644
--- a/sdk/typescript/src/server/serve.ts
+++ b/sdk/typescript/src/server/serve.ts
@@ -6,12 +6,13 @@ export async function serveFindings(
environment: NodeJS.ProcessEnv = process.env,
output: Pick<NodeJS.WriteStream, "write"> = process.stdout,
): Promise<void> {
- const host = environment["HOST"] ?? "127.0.0.1";
- const port = Number(environment["PORT"] ?? 3000);
+ const host = environment["HOST"]?.trim() || "127.0.0.1";
+ const port = Number(environment["PORT"]?.trim() || 3000);
const server = await startFindingsServer({
store: new SqliteFindingsStore(environment),
embeddings: new OpenAiFindingEmbedder(
- environment["OPENAI_API_KEY"] ?? environment["CODEX_API_KEY"],
+ environment["OPENAI_API_KEY"]?.trim() ||
+ environment["CODEX_API_KEY"]?.trim(),
fetch,
environment["CODEX_SECURITY_EMBEDDINGS_URL"] || undefined,
),
diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.ts
index b37708141..abe9614e1 100644
--- a/sdk/typescript/tests-ts/api-credentials.test.ts
+++ b/sdk/typescript/tests-ts/api-credentials.test.ts
@@ -13,16 +13,27 @@ import { copyCompletedScan, PLUGIN_ROOT } from "./plugin-root.js";
import { shellEnvironmentReference, TestClient } from "./support/api-client.js";
import { completedEvents, preparedRuntime } from "./support/api-events.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
-import { rejecting } from "./support/errors.js";
const { cleanup, temporaryDirectory } = createApiTestFixtures();
afterEach(cleanup);
describe("CodexSecurity orchestration", () => {
- test.each(["direct", "profile"])(
+ test.each([
+ "direct",
+ "profile",
+ "profile-providers",
+ "profile-providers-ambient",
+ "profile-inherited-cwd",
+ "profile-overridden-cwd",
+ "profile-strict",
+ ])(
"runs native command authentication without importing credentials (%s)",
async (selection) => {
- const profile = selection === "profile";
+ const profile = selection !== "direct";
+ const profileProviders = profile && selection !== "profile";
+ const inheritedCwd = selection === "profile-inherited-cwd";
+ const overriddenCwd = selection === "profile-overridden-cwd";
+ const strict = selection === "profile-strict";
const root = await temporaryDirectory();
const repository = join(root, "repository");
const home = join(root, "model-home");
@@ -40,30 +51,63 @@ describe("CodexSecurity orchestration", () => {
refresh_interval_ms: 1000,
...(profile ? { cwd: "helpers" } : {}),
};
+ const definition = {
+ name: "Synthetic",
+ base_url: "https://provider.example/v1",
+ wire_api: "responses",
+ auth,
+ };
+ const rootDefinition = {
+ ...definition,
+ auth: {
+ ...auth,
+ ...(inheritedCwd || overriddenCwd ? { cwd: "root-helpers" } : {}),
+ },
+ };
+ const selectedDefinition =
+ inheritedCwd || overriddenCwd
+ ? {
+ auth: {
+ command: "./selected-auth",
+ ...(overriddenCwd ? { cwd: "selected-helpers" } : {}),
+ },
+ }
+ : definition;
const overrides = {
+ ...(strict ? { approval_policy: "never" } : {}),
...(profile
? {
profile: "review",
- profiles: { review: { model_provider: "synthetic.provider" } },
+ profiles: {
+ review: {
+ model_provider: "synthetic.provider",
+ service_tier: "fast",
+ ...(strict ? { approval_policy: "on-request" } : {}),
+ ...(profileProviders
+ ? {
+ model_providers: {
+ "synthetic.provider": selectedDefinition,
+ },
+ }
+ : {}),
+ },
+ },
}
: { model_provider: "synthetic.provider" }),
- model_providers: {
- "synthetic.provider": {
- name: "Synthetic",
- base_url: "https://provider.example/v1",
- wire_api: "responses",
- auth,
- },
- },
+ ...(!profileProviders || inheritedCwd || overriddenCwd
+ ? { model_providers: { "synthetic.provider": rootDefinition } }
+ : {}),
};
- let captured: CodexOptions | undefined;
+ const originalOverrides = structuredClone(overrides);
+ let captured: (CodexOptions & { nativeProfile?: string }) | undefined;
const client = new TestClient(
{ pluginPath: PLUGIN_ROOT, codexOverrides: overrides },
{
environment: {
CODEX_HOME: relative(process.cwd(), home),
CODEX_SECURITY_STATE_DIR: state,
- ...(profile
+ ...(selection === "profile" ||
+ selection === "profile-providers-ambient"
? {
OPENAI_API_KEY: "synthetic-ambient-key",
CODEX_API_KEY: "synthetic-other-key",
@@ -86,7 +130,30 @@ describe("CodexSecurity orchestration", () => {
return {
startThread: () => ({
id: null,
- runStreamed: rejecting("synthetic command-auth scan started"),
+ 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");
+ },
}),
};
},
@@ -107,26 +174,56 @@ describe("CodexSecurity orchestration", () => {
expect(captured?.env).not.toHaveProperty("CODEX_API_KEY");
expect(captured?.env?.["CODEX_HOME"]).toBe(join(state, "codex-home"));
const provider = {
- ...overrides.model_providers["synthetic.provider"],
- auth: { ...auth, cwd: profile ? join(home, "helpers") : home },
+ ...definition,
+ auth: {
+ ...auth,
+ ...(inheritedCwd || overriddenCwd
+ ? { command: "./selected-auth" }
+ : {}),
+ cwd: !profile
+ ? home
+ : join(
+ home,
+ inheritedCwd
+ ? "root-helpers"
+ : overriddenCwd
+ ? "selected-helpers"
+ : "helpers",
+ ),
+ },
};
- expect(parseToml(captured!.configOverrides![0]!)).toEqual({
+ expect(JSON.stringify(captured!.configOverrides ?? [])).not.toContain(
+ "model_providers",
+ );
+ expect(
+ parseToml(
+ await readFile(
+ join(runtimeHome, `${captured!.nativeProfile}.config.toml`),
+ "utf8",
+ ),
+ ),
+ ).toEqual({
model_providers: { "synthetic.provider": provider },
});
if (profile) {
- expect(captured?.config?.["profile"]).toBe("review");
- expect(captured?.config?.["profiles"]).toEqual({
- review: { model_provider: "synthetic.provider" },
- });
+ expect(captured?.config?.["profile"]).toBeUndefined();
+ expect(captured?.config?.["profiles"]).toBeUndefined();
+ expect(captured?.config?.["model_provider"]).toBe(
+ "synthetic.provider",
+ );
+ expect(captured?.config?.["service_tier"]).toBe("fast");
+ if (strict)
+ expect(captured?.config?.["approval_policy"]).toBe("never");
} else {
const saved = parseToml(
await readFile(join(runtimeHome, "config.toml"), "utf8"),
);
- expect(saved["model_providers"]).toEqual({
- "synthetic.provider": provider,
- });
+ expect(saved["model_provider"]).toBeUndefined();
+ expect(saved["model_providers"]).toBeUndefined();
+ expect(saved["profiles"]).toBeUndefined();
}
expect(existsSync(join(state, "codex-home", "auth.json"))).toBe(false);
+ expect(overrides).toEqual(originalOverrides);
} finally {
await client.close();
}
@@ -213,7 +310,7 @@ describe("CodexSecurity orchestration", () => {
"plugins",
"codex-security",
"codex-home",
- )]: "read",
+ )]: { ".": "deny" },
},
},
},
@@ -232,7 +329,7 @@ describe("CodexSecurity orchestration", () => {
allow_login_shell: false,
model_reasoning_summary: "detailed",
show_raw_agent_reasoning: true,
- windows: { sandbox: "unelevated" },
+ windows: { sandbox: "elevated" },
mcp_servers: {
private: {
command: "echo",
diff --git a/sdk/typescript/tests-ts/api-login.test.ts b/sdk/typescript/tests-ts/api-login.test.ts
new file mode 100644
index 000000000..a59a97c1f
--- /dev/null
+++ b/sdk/typescript/tests-ts/api-login.test.ts
@@ -0,0 +1,53 @@
+import { existsSync } from "node:fs";
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { afterEach, expect, test } from "bun:test";
+import { TestClient } from "./support/api-client.js";
+import { nodeCommand } from "./support/shell.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+
+const { temporaryDirectory, cleanup } = createApiTestFixtures(
+ "codex-security-api-login-",
+);
+afterEach(cleanup);
+
+test.each(["loginChatGPT", "loginChatGPTDeviceCode"] as const)(
+ "%s does not start a child when closed during provider command preparation",
+ async (method) => {
+ const root = await temporaryDirectory();
+ const marker = join(root, "child-started");
+ const script = join(root, "synthetic-native.mjs");
+ await writeFile(
+ script,
+ `import { writeFileSync } from "node:fs";
+writeFileSync(${JSON.stringify(marker)}, "synthetic child started");
+console.error("Open https://auth.example.test/device");
+console.error("User code: ABCD-EFGH");
+process.exit(1);
+`,
+ );
+ let closing: Promise<void> | undefined;
+ const client = new TestClient(
+ {},
+ {
+ environment: {
+ ...process.env,
+ CODEX_SECURITY_STATE_DIR: root,
+ NODE_OPTIONS: `--import=${pathToFileURL(script).href}`,
+ },
+ resolveCodexCommand: () => {
+ closing = Promise.resolve().then(() => client.close());
+ return nodeCommand();
+ },
+ },
+ );
+ try {
+ await expect(client[method]()).rejects.toThrow("CodexSecurity is closed");
+ await closing;
+ expect(existsSync(marker)).toBe(false);
+ } finally {
+ await client.close();
+ }
+ },
+);
diff --git a/sdk/typescript/tests-ts/api-preflight-config.test.ts b/sdk/typescript/tests-ts/api-preflight-config.test.ts
index 63839c9e1..9b3df38c2 100644
--- a/sdk/typescript/tests-ts/api-preflight-config.test.ts
+++ b/sdk/typescript/tests-ts/api-preflight-config.test.ts
@@ -442,7 +442,7 @@ describe("CodexSecurity preflight configuration", () => {
});
});
- test("keeps persistent credentials and their ancestry read-only", () => {
+ test("denies model commands access to the persistent credential home", () => {
const stateDirectory = join(tmpdir(), "codex-security-persistent-state");
const credentialHome = join(stateDirectory, "codex-home");
const config = scanRuntimeCodexConfig({}, credentialHome);
@@ -452,7 +452,7 @@ describe("CodexSecurity preflight configuration", () => {
filesystem: {
":root": "read",
":workspace_roots": "write",
- [credentialHome]: "read",
+ [credentialHome]: { ".": "deny" },
},
},
codex_security_policy: {
diff --git a/sdk/typescript/tests-ts/api-provider-isolation.test.ts b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
new file mode 100644
index 000000000..3382380b3
--- /dev/null
+++ b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
@@ -0,0 +1,937 @@
+import { afterEach, expect, spyOn, test } from "bun:test";
+import { build } from "esbuild";
+import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
+import { resolveCodexProfile, type JsonObject } from "../src/config.js";
+import * as childProcess from "node:child_process";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import { existsSync } from "node:fs";
+import { cp, mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { createInterface } from "node:readline";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { executablePathForSpawn, resolveCodexCommand } from "../src/runtime.js";
+import { PLUGIN_ROOT } from "./plugin-root.js";
+import { profileConfigOverrides } from "../../../plugins/codex-security/scripts/codex_profile.mjs";
+import { TestClient } from "./support/api-client.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+
+const { temporaryDirectory, cleanup } = createApiTestFixtures();
+afterEach(cleanup);
+
+async function nativeRequest(
+ environment: Record<string, string>,
+ cwd: string,
+ args: string[],
+ method: string,
+ params: unknown,
+) {
+ const child = spawn(
+ executablePathForSpawn(resolveCodexCommand({}).command),
+ [...args, "app-server", "--stdio"],
+ {
+ cwd,
+ env: { PATH: process.env["PATH"], ...environment },
+ windowsHide: true,
+ },
+ );
+ const closed = once(child, "close");
+ const lines = createInterface({ input: child.stdout });
+ let stderr = "";
+ child.stderr.on("data", (chunk) => (stderr += chunk));
+ const timer = setTimeout(() => child.kill(), 15_000);
+ const send = (message: unknown) =>
+ child.stdin.write(JSON.stringify(message) + "\n");
+ try {
+ send({
+ id: 1,
+ method: "initialize",
+ params: {
+ clientInfo: { name: "synthetic_provider_test", version: "1" },
+ capabilities: { experimentalApi: true },
+ },
+ });
+ for await (const line of lines) {
+ const response = JSON.parse(line);
+ if (response.error) throw new Error(JSON.stringify(response.error));
+ if (response.id === 1) {
+ send({ method: "initialized", params: {} });
+ send({ id: 2, method, params });
+ }
+ if (response.id === 2) return response.result;
+ }
+ throw new Error(`Native ${method} probe did not finish: ${stderr}`);
+ } finally {
+ clearTimeout(timer);
+ lines.close();
+ child.kill();
+ await closed;
+ }
+}
+
+async function effectiveProvider(
+ environment: Record<string, string>,
+ cwd: string,
+ overrides: string[],
+ nativeProfile?: string,
+) {
+ if (nativeProfile !== undefined) {
+ const config = parseToml(
+ await readFile(
+ join(environment["CODEX_HOME"]!, `${nativeProfile}.config.toml`),
+ "utf8",
+ ),
+ );
+ const result = await nativeRequest(environment, cwd, [], "thread/start", {
+ cwd,
+ ephemeral: true,
+ // This no-turn configuration check never executes model commands.
+ sandbox: "danger-full-access",
+ threadSource: "security_scan",
+ config: { ...config, ...parseToml(overrides.join("\n")) },
+ });
+ return (config["model_providers"] as Record<string, unknown>)?.[
+ result.modelProvider
+ ];
+ }
+ const { config } = await nativeRequest(
+ environment,
+ cwd,
+ overrides.flatMap((value) => ["-c", value]),
+ "config/read",
+ { cwd, includeLayers: false },
+ );
+ return config.model_providers?.[config.model_provider];
+}
+
+test("native worker override tables retain inherited features and MCP servers", async () => {
+ const root = await temporaryDirectory();
+ const home = join(root, "home");
+ await mkdir(home, { mode: 0o700 });
+ const original = stringifyToml({
+ features: { shell_tool: false, view_image: false },
+ mcp_servers: {
+ "inherited.server": { command: "node", args: ["inherited-argument"] },
+ "codex-security": { command: "node", enabled: true },
+ },
+ });
+ await writeFile(join(home, "config.toml"), original);
+ const { config } = await nativeRequest(
+ { CODEX_HOME: home },
+ root,
+ profileConfigOverrides({
+ features: { api_key_model_discovery: false },
+ mcp_servers: { "codex-security": { command: "node", enabled: false } },
+ }).flatMap((value) => ["--config", value]),
+ "config/read",
+ { cwd: root, includeLayers: false },
+ );
+ expect(config.features).toMatchObject({
+ shell_tool: false,
+ view_image: false,
+ api_key_model_discovery: false,
+ });
+ expect(config.mcp_servers["inherited.server"]).toMatchObject({
+ command: "node",
+ args: ["inherited-argument"],
+ enabled: true,
+ });
+ expect(config.mcp_servers["codex-security"].enabled).toBe(false);
+ expect(await readFile(join(home, "config.toml"), "utf8")).toBe(original);
+});
+
+async function bundleWorkerSettings(root: string) {
+ const executor = fileURLToPath(
+ new URL(
+ "../../../plugins/codex-security/mcp-app/src/deep-scan/executor.ts",
+ import.meta.url,
+ ),
+ );
+ const bundled = await build({
+ bundle: true,
+ format: "esm",
+ platform: "node",
+ write: false,
+ define: { "import.meta.url": JSON.stringify(pathToFileURL(executor).href) },
+ stdin: {
+ contents:
+ (await readFile(executor, "utf8")) +
+ "\nexport { workerRuntimeSettings };",
+ loader: "ts",
+ resolveDir: dirname(executor),
+ sourcefile: executor,
+ },
+ });
+ const bundledPath = join(root, "worker-settings.mjs");
+ await writeFile(bundledPath, bundled.outputFiles[0]!.contents);
+ return bundledPath;
+}
+
+async function loadWorkerSettings(root: string) {
+ const { workerRuntimeSettings } = (await import(
+ pathToFileURL(await bundleWorkerSettings(root)).href
+ )) as {
+ workerRuntimeSettings: (environment: Record<string, string>) => Promise<{
+ config: JsonObject;
+ nativeProfile?: string;
+ environment?: Record<string, string>;
+ }>;
+ };
+
+ return workerRuntimeSettings;
+}
+
+test.each(["root", "profile override", "profile only"] as const)(
+ "concurrent provider snapshots preserve %s credentials",
+ async (selection) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const state = join(root, "state");
+ const sharedHome = join(state, "codex-home");
+ const sourceHome = join(root, "source-home");
+ await mkdir(repository);
+ await mkdir(sourceHome, { mode: 0o700 });
+ await mkdir(sharedHome, { recursive: true, mode: 0o700 });
+ // Initialize native state before the mocked primary scans start concurrently.
+ await effectiveProvider({ CODEX_HOME: sharedHome }, repository, []);
+
+ const workerRuntimeSettings = await loadWorkerSettings(root);
+
+ const ready = [
+ Promise.withResolvers<void>(),
+ Promise.withResolvers<void>(),
+ ];
+ const clients: TestClient[] = [];
+ const runs: Promise<unknown>[] = [];
+ const snapshots: string[] = [];
+ const filesystems: Array<Record<string, unknown>> = [];
+ try {
+ for (let index = 0; index < 2; index++) {
+ const scan = join(root, `scan-${index}`);
+ await mkdir(scan, { mode: 0o700 });
+ const provider = {
+ name: `Synthetic ${index}`,
+ base_url: `https://provider-${index}.example.test/v1`,
+ wire_api: "responses",
+ env_key: "SYNTHETIC_CUSTOM_API_KEY",
+ env_http_headers: {
+ "X-Synthetic-Token": "SYNTHETIC_CUSTOM_HEADER",
+ "X-Synthetic-Missing": "SYNTHETIC_UNSET",
+ },
+ ...(index === 1
+ ? { http_headers: { "X-Gateway-Token": "synthetic-key-B" } }
+ : {}),
+ };
+ const webSearch = index === 0 ? "disabled" : "cached";
+ const featureOverrides = {
+ shell_tool: index === 1,
+ unified_exec: false,
+ view_image: index === 0,
+ };
+ const providerEnvironment = {
+ SYNTHETIC_CUSTOM_API_KEY: ` synthetic-key-${index} `,
+ SYNTHETIC_CUSTOM_HEADER: ` synthetic-header-${index} `,
+ SYNTHETIC_REQUIRED_KEY: `synthetic-required-${index}`,
+ };
+ clients.push(
+ new TestClient(
+ {
+ pluginPath: PLUGIN_ROOT,
+ codexOverrides: {
+ model_provider: "openrouter",
+ web_search: selection === "root" ? webSearch : "live",
+ features: selection === "root" ? featureOverrides : {},
+ ...(selection === "profile only"
+ ? {}
+ : {
+ model_providers: {
+ openrouter:
+ selection === "root"
+ ? provider
+ : {
+ ...provider,
+ env_key: "SYNTHETIC_UNUSED_KEY",
+ },
+ "required.gateway": {
+ name: "Managed selection",
+ wire_api: "responses",
+ env_key: "SYNTHETIC_REQUIRED_KEY",
+ },
+ },
+ }),
+ ...(selection === "root"
+ ? {}
+ : {
+ profile: "selected",
+ profiles: {
+ selected: {
+ features: featureOverrides,
+ web_search: webSearch,
+ model_provider: "openrouter",
+ model_providers: {
+ openrouter: provider,
+ "required.gateway": {
+ name: "Managed selection",
+ wire_api: "responses",
+ env_key: "SYNTHETIC_REQUIRED_KEY",
+ },
+ },
+ },
+ },
+ }),
+ },
+ },
+ {
+ environment: {
+ CODEX_HOME: sourceHome,
+ CODEX_SECURITY_STATE_DIR: state,
+ OPENAI_API_KEY: "synthetic-account-key",
+ OPENROUTER_API_KEY: "synthetic-sdk-account-key",
+ ...providerEnvironment,
+ SYNTHETIC_UNUSED_KEY: "synthetic-unused-key",
+ },
+ 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);
+ const actual = await effectiveProvider(
+ environment,
+ repository,
+ profileConfigOverrides(settings.config),
+ settings.nativeProfile,
+ );
+ 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");
+ },
+ }),
+ }),
+ },
+ ),
+ );
+ }
+ // A's snapshot exists before B updates the shared credential home.
+ runs.push(clients[0]!.run(repository, { mode: "deep" }));
+ await Promise.race([ready[0]!.promise, runs[0]]);
+ runs.push(
+ clients[1]!
+ .run(repository, { mode: "deep" })
+ .finally(() => ready[1]!.resolve()),
+ );
+ const outcomes = await Promise.allSettled(runs);
+ for (const outcome of outcomes) {
+ expect(outcome).toMatchObject({
+ status: "rejected",
+ reason: expect.objectContaining({
+ message: "synthetic provider configuration checked",
+ }),
+ });
+ }
+ } finally {
+ ready.forEach((entry) => entry.resolve());
+ await Promise.allSettled(runs);
+ await Promise.all(clients.map((client) => client.close()));
+ }
+ for (const snapshot of snapshots) {
+ expect(existsSync(dirname(snapshot))).toBe(false);
+ }
+ expect(existsSync(sharedHome)).toBe(true);
+ },
+ 30_000,
+);
+
+test("workers preserve native provider inheritance without an explicit selection", async () => {
+ const root = await temporaryDirectory();
+ const home = join(root, "native-home");
+ await mkdir(home, { mode: 0o700 });
+ const provider = {
+ name: "Inherited gateway",
+ base_url: "https://inherited.example.test/v1",
+ wire_api: "responses",
+ };
+ await writeFile(
+ join(home, "config.toml"),
+ stringifyToml({
+ model_provider: "inherited.gateway",
+ model_providers: { "inherited.gateway": provider },
+ }),
+ );
+ const snapshot = join(root, "snapshot.toml");
+ const workerSnapshot = join(root, "worker-snapshot.toml");
+ const environment = {
+ CODEX_HOME: home,
+ CODEX_SECURITY_CONFIG_PATH: snapshot,
+ CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH: workerSnapshot,
+ };
+ const workerRuntimeSettings = await loadWorkerSettings(root);
+ for (const providers of [
+ undefined,
+ {
+ "inherited.gateway": {
+ ...provider,
+ base_url: "https://selected.example.test/v1",
+ },
+ },
+ ]) {
+ await writeFile(snapshot, stringifyToml({}));
+ if (providers)
+ await writeFile(
+ join(home, "synthetic.config.toml"),
+ stringifyToml({ model_providers: providers }),
+ );
+ await writeFile(
+ workerSnapshot,
+ stringifyToml({
+ worker_runtime: providers ? { native_profile: "synthetic" } : {},
+ }),
+ );
+ const settings = await workerRuntimeSettings(environment);
+ expect(settings.config["model_provider"]).toBeUndefined();
+ expect(
+ await effectiveProvider(
+ environment,
+ root,
+ profileConfigOverrides(settings.config),
+ settings.nativeProfile,
+ ),
+ ).toMatchObject(providers?.["inherited.gateway"] ?? provider);
+ }
+});
+
+const legacyProviders: Array<[string, JsonObject]> = [
+ [
+ "explicit gateway",
+ {
+ model_provider: "openrouter",
+ model_providers: {
+ openrouter: {
+ name: "Synthetic gateway",
+ base_url: "https://gateway.example.test/v1",
+ wire_api: "responses",
+ env_key: "OPENROUTER_API_KEY",
+ },
+ },
+ },
+ ],
+ [
+ "OpenAI with custom definitions",
+ {
+ model_provider: "openai",
+ model_providers: {
+ synthetic: {
+ name: "Synthetic",
+ wire_api: "responses",
+ base_url: "https://gateway.example.test/v1",
+ env_key: "SYNTHETIC_OPENAI_API_KEY",
+ },
+ },
+ },
+ ],
+ [
+ "profile OpenAI with custom definitions",
+ {
+ profile: "selected",
+ profiles: {
+ selected: {
+ model_provider: "openai",
+ model_providers: {
+ synthetic: {
+ name: "Synthetic",
+ wire_api: "responses",
+ base_url: "https://gateway.example.test/v1",
+ env_key: "SYNTHETIC_OPENAI_API_KEY",
+ },
+ },
+ },
+ },
+ },
+ ],
+ [
+ "inherited provider definition",
+ {
+ model_providers: {
+ "amazon-bedrock": {
+ aws: { region: "us-east-1" },
+ base_url: "https://gateway.example.test/v1",
+ },
+ },
+ },
+ ],
+];
+const legacyScanCases: Array<
+ [
+ string,
+ "standard" | "deep",
+ JsonObject,
+ {
+ capability?: true | number;
+ inherited?: string;
+ managed?: string;
+ rejects?: boolean;
+ reads?: boolean;
+ },
+ ]
+> = [
+ ...legacyProviders.map(
+ ([name, overrides]): (typeof legacyScanCases)[number] => [
+ `deep with incompatible ${name}`,
+ "deep",
+ overrides,
+ { capability: 3, rejects: true },
+ ],
+ ),
+ ["standard", "standard", {}, {}],
+ ["deep", "deep", {}, {}],
+ ["standard with explicit provider", "standard", legacyProviders[0]![1], {}],
+ [
+ "deep with explicit OpenAI",
+ "deep",
+ { model_provider: "openai" },
+ { reads: true },
+ ],
+ [
+ "deep with profile-selected OpenAI",
+ "deep",
+ {
+ profile: "selected",
+ profiles: { selected: { model_provider: "openai" } },
+ },
+ { reads: true },
+ ],
+ [
+ "deep with a conflicting native provider",
+ "deep",
+ { model_provider: "openai" },
+ {
+ inherited: "synthetic.system",
+ reads: true,
+ rejects: true,
+ },
+ ],
+ [
+ "deep with the same managed provider",
+ "deep",
+ { model_provider: "openai" },
+ {
+ inherited: "synthetic.system",
+ managed: "synthetic.required",
+ reads: true,
+ },
+ ],
+ ...([true, 2, 3] as const).map(
+ (capability): (typeof legacyScanCases)[number] => [
+ `deep with selector snapshot ${capability}`,
+ "deep",
+ { model_provider: "openai" },
+ {
+ capability,
+ inherited: "synthetic.system",
+ },
+ ],
+ ),
+ [
+ "deep with a filtered profile and readable snapshot",
+ "deep",
+ {
+ profile: "selected.profile",
+ profiles: { "selected.profile": { model_provider: "openai" } },
+ },
+ {
+ capability: true,
+ inherited: "synthetic.system",
+ reads: true,
+ rejects: true,
+ },
+ ],
+];
+test.each(legacyScanCases)(
+ "checks effective worker compatibility for %s scans",
+ async (_scenario, mode, overrides, native) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const scan = join(root, "scan");
+ const plugin = join(root, "custom-plugin");
+ await mkdir(repository);
+ await mkdir(scan, { mode: 0o700 });
+ await cp(PLUGIN_ROOT, plugin, { recursive: true });
+ const manifestPath = join(plugin, ".codex-plugin", "plugin.json");
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+ if (native.capability === undefined) delete manifest.codexSecurity;
+ else manifest.codexSecurity = { workerProviderSnapshot: native.capability };
+ await writeFile(manifestPath, JSON.stringify(manifest));
+ const callsPath = join(root, "config-reads.jsonl");
+ const fakeNative = join(root, "native-config.mjs");
+ await writeFile(
+ fakeNative,
+ `
+ import { appendFileSync, existsSync } from "node:fs";
+ import { join } from "node:path";
+ import { createInterface } from "node:readline";
+ const args = process.argv.slice(2);
+ const selected = args.some((arg) => arg === 'model_provider="openai"') ? "openai" : ${JSON.stringify(native.inherited ?? "openai")};
+ for await (const line of createInterface({ input: process.stdin })) {
+ const request = JSON.parse(line);
+ if (request.id === undefined) continue;
+ if (request.method === "config/read") appendFileSync(${JSON.stringify(callsPath)}, JSON.stringify({
+ args, cwd: process.cwd(), params: request.params,
+ home: process.env.CODEX_HOME, key: process.env.CODEX_API_KEY,
+ openai: process.env.OPENAI_API_KEY,
+ lockHeld: existsSync(join(process.env.CODEX_HOME, ".codex-security-preflight", ".codex-security-scan.lock", "owner.json")),
+ }) + "\\n");
+ console.log(JSON.stringify({ id: request.id, result: request.method === "config/read"
+ ? { config: { model_provider: ${JSON.stringify(native.managed)} ?? selected } } : {} }));
+ }
+ `,
+ );
+ const command = resolveCodexCommand({});
+ const commandArgs = ["-c", "features.api_key_model_discovery=false"];
+ const originalSpawn = childProcess.spawn;
+ const spawnSpy = spyOn(childProcess, "spawn").mockImplementation(((
+ ...input: Parameters<typeof originalSpawn>
+ ) => {
+ const [, args, options] = input;
+ return args?.includes("app-server")
+ ? originalSpawn(process.execPath, [fakeNative, ...args], options ?? {})
+ : originalSpawn(...input);
+ }) as typeof originalSpawn);
+ let launched = false;
+ const client = new TestClient(
+ { pluginPath: plugin, codexOverrides: overrides },
+ {
+ environment: {
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ OPENAI_API_KEY: "synthetic-openai-key",
+ OPENROUTER_API_KEY: "synthetic-gateway-key",
+ },
+ resolveCodexCommand: () => ({ ...command, args: commandArgs }),
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scan,
+ 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"]);
+ 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");
+ },
+ }),
+ };
+ },
+ },
+ );
+ try {
+ await expect(client.run(repository, { mode })).rejects.toThrow(
+ native.rejects
+ ? "Update the custom plugin or use the bundled plugin"
+ : "synthetic compatible scan started",
+ );
+ expect(launched).toBe(!native.rejects);
+ const calls = existsSync(callsPath)
+ ? (await readFile(callsPath, "utf8"))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line))
+ : [];
+ expect(calls).toHaveLength(native.reads ? 2 : 0);
+ for (const call of calls) {
+ expect(call.cwd).toBe(scan);
+ expect(call.params).toEqual({ cwd: scan, includeLayers: false });
+ expect(call.home).toBe(join(root, "state", "codex-home"));
+ expect(call.key).toBe("synthetic-openai-key");
+ expect(call.openai).toBeUndefined();
+ expect(call.lockHeld).toBe(true);
+ expect(call.args.slice(0, commandArgs.length)).toEqual(commandArgs);
+ expect(JSON.stringify(call.args)).not.toContain("synthetic-openai-key");
+ }
+ if (native.reads) {
+ expect(calls[0].args).not.toContain('model_provider="openai"');
+ expect(calls[1].args).toContain('model_provider="openai"');
+ }
+ } finally {
+ await client.close();
+ spawnSpy.mockRestore();
+ }
+ },
+);
+
+async function createPluginProbe(root: string, report: string) {
+ const plugin = join(root, "plugin");
+ await cp(PLUGIN_ROOT, plugin, { recursive: true });
+ await bundleWorkerSettings(plugin);
+ const probe = join(plugin, "environment-probe.mjs");
+ await writeFile(
+ probe,
+ `import { writeFile } from "node:fs/promises";
+import { createInterface } from "node:readline";
+import { workerRuntimeSettings } from "./worker-settings.mjs";
+for await (const line of createInterface({ input: process.stdin })) {
+ const request = JSON.parse(line);
+ if (request.id === undefined) continue;
+ let result = {};
+ if (request.method === "initialize") {
+ result = { protocolVersion: request.params.protocolVersion,
+ capabilities: { tools: {} }, serverInfo: { name: "synthetic-environment", version: "1" } };
+ } else if (request.method === "tools/list") {
+ const settings = await workerRuntimeSettings(process.env);
+ await writeFile(process.argv[2], JSON.stringify({
+ inherited: Object.fromEntries([
+ "SYNTHETIC_CUSTOM_API_KEY", "SYNTHETIC_CUSTOM_HEADER",
+ "SYNTHETIC_REQUIRED_KEY", "SYNTHETIC_UNUSED_KEY",
+ ].map((name) => [name, process.env[name] ?? null])),
+ recovered: settings.environment,
+ }));
+ result = { tools: [{ name: "synthetic_environment",
+ description: "Synthetic provider environment probe",
+ inputSchema: { type: "object", properties: {} } }] };
+ }
+ console.log(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }));
+}
+`,
+ );
+ const manifestPath = join(plugin, ".mcp.json");
+ const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+ const server = manifest.mcpServers["codex-security"];
+ expect(server.env_vars).not.toContain("SYNTHETIC_CUSTOM_API_KEY");
+ expect(server.env_vars).not.toContain("SYNTHETIC_CUSTOM_HEADER");
+ // Keep the plugin registration and production environment allowlist. Only
+ // replace its MCP implementation with a no-turn observation tool.
+ server.command = process.execPath;
+ server.args = [probe, report];
+ await writeFile(manifestPath, JSON.stringify(manifest));
+ return plugin;
+}
+
+test.each(["SYNTHETIC_CUSTOM_API_KEY", "CODEX_API_KEY"])(
+ "native plugin workers recover the selected %s and other provider variables",
+ async (providerKey) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const scan = join(root, "scan");
+ const sourceHome = join(root, "source-home");
+ const report = join(root, "environment.json");
+ await mkdir(repository);
+ await mkdir(scan, { mode: 0o700 });
+ await mkdir(sourceHome, { mode: 0o700 });
+ const plugin = await createPluginProbe(root, report);
+ const providerEnvironment = {
+ [providerKey]: " synthetic-custom-key ",
+ SYNTHETIC_CUSTOM_HEADER: " synthetic-custom-header ",
+ SYNTHETIC_REQUIRED_KEY: "synthetic-required-key",
+ };
+ const client = new TestClient(
+ {
+ pluginPath: plugin,
+ codexOverrides: {
+ model_provider: "synthetic.gateway",
+ model_providers: {
+ "synthetic.gateway": {
+ name: "Synthetic gateway",
+ wire_api: "responses",
+ base_url: "https://provider.example.test/v1",
+ env_key: providerKey,
+ env_http_headers: {
+ "X-Synthetic-Token": "SYNTHETIC_CUSTOM_HEADER",
+ "X-Synthetic-Missing": "SYNTHETIC_UNSET_KEY",
+ },
+ },
+ "required.gateway": {
+ name: "Managed selection",
+ wire_api: "responses",
+ env_key: "SYNTHETIC_REQUIRED_KEY",
+ },
+ },
+ },
+ },
+ {
+ environment: {
+ CODEX_HOME: sourceHome,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ OPENAI_API_KEY: "synthetic-account-key",
+ ...providerEnvironment,
+ SYNTHETIC_UNUSED_KEY: "synthetic-unused-key",
+ },
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scan,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: (options) => ({
+ startThread: () => ({
+ id: null,
+ async runStreamed() {
+ expect(options.apiKey).toBe("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,
+ ...(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");
+ },
+ }),
+ }),
+ },
+ );
+ try {
+ await expect(client.run(repository, { mode: "deep" })).rejects.toThrow(
+ "synthetic native plugin environment checked",
+ );
+ } finally {
+ await client.close();
+ }
+ },
+ 30_000,
+);
diff --git a/sdk/typescript/tests-ts/api-runtime-storage.test.ts b/sdk/typescript/tests-ts/api-runtime-storage.test.ts
new file mode 100644
index 000000000..fc266efb7
--- /dev/null
+++ b/sdk/typescript/tests-ts/api-runtime-storage.test.ts
@@ -0,0 +1,158 @@
+import { mkdir, readFile, readdir, stat } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+import { afterEach, expect, spyOn, test } from "bun:test";
+import * as runtime from "../src/runtime.js";
+import { TestClient } from "./support/api-client.js";
+import { parse as parseToml } from "smol-toml";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+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) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ const scan = join(root, "scan");
+ await mkdir(repository);
+ await mkdir(scan, { mode: 0o700 });
+ const original = runtime.requirePrivateCredentialHome;
+ let protectedDirectory: string | undefined;
+ let workerFile: string | undefined;
+ let launched = false;
+ let operation: "deep" | "standard" | "validation" = "deep";
+ const guard = spyOn(
+ runtime,
+ "requirePrivateCredentialHome",
+ ).mockImplementation(async (metadata, path, options) => {
+ if (!basename(path).startsWith("openai-codex-security-home-"))
+ return original(metadata, path, options);
+ await original(metadata, path, {
+ platform: "win32",
+ secureWindowsHome: async (directory) => {
+ expect(await readdir(directory)).toEqual([]);
+ protectedDirectory = directory;
+ if (failAcl) throw new Error("synthetic ACL denial");
+ },
+ });
+ });
+ const client = new TestClient(
+ {
+ pluginPath: PLUGIN_ROOT,
+ codexOverrides: {
+ model_provider: "synthetic.provider",
+ model_providers: {
+ "synthetic.provider": {
+ name: "Synthetic provider",
+ base_url: "https://provider.example.test/v1",
+ wire_api: "responses",
+ auth: {
+ command: "synthetic-auth",
+ env: { CLIENT_SECRET: "synthetic-client-secret" },
+ },
+ },
+ },
+ },
+ },
+ {
+ environment: { CODEX_SECURITY_STATE_DIR: join(root, "state") },
+ 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,
+ );
+ 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");
+ },
+ }),
+ }),
+ },
+ );
+ try {
+ await expect(client.run(repository, { mode: "deep" })).rejects.toThrow(
+ failAcl ? "synthetic ACL denial" : "synthetic scan reached",
+ );
+ expect(protectedDirectory).toBeDefined();
+ expect(launched).toBe(!failAcl);
+ if (!failAcl) {
+ operation = "standard";
+ await expect(client.run(repository)).rejects.toThrow(
+ "synthetic scan reached",
+ );
+ operation = "validation";
+ await expect(
+ client.validate({
+ repositoryPath: repository,
+ finding: "Synthetic finding",
+ outputDir: join(root, "validation"),
+ }),
+ ).rejects.toThrow("synthetic scan reached");
+ }
+ } finally {
+ guard.mockRestore();
+ await client.close();
+ }
+ expect(existsSync(protectedDirectory!)).toBe(false);
+ if (workerFile !== undefined) {
+ expect(existsSync(dirname(workerFile))).toBe(false);
+ }
+ },
+);
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 48f567a35..3efcb70e1 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -15,6 +15,7 @@ import {
} from "node:fs/promises";
import * as fsPromises from "node:fs/promises";
import { execFileSync } from "node:child_process";
+import * as childProcess from "node:child_process";
import { hash } from "node:crypto";
import { existsSync } from "node:fs";
import { basename, delimiter, dirname, join, relative, win32 } from "node:path";
@@ -48,6 +49,7 @@ import {
initialCredentialsAvailable,
} from "../src/api.js";
import {
+ DEFAULT_CODEX_CONFIG,
FIREWORKS_CODEX_PROVIDER,
OPENROUTER_CODEX_PROVIDER,
resolveCodexProfile,
@@ -90,6 +92,7 @@ import { runTestInSubprocess } from "./support/test-subprocess.js";
import { writeSession as writeUsageSession } from "./support/usage-rollout.js";
import { FindingWorkflow } from "../src/finding-workflow.js";
import { DEFAULT_DEEP_SCAN_SETTINGS } from "../src/deep-scan-defaults.js";
+import { createProviderProfile } from "../src/provider-profile.js";
import { pythonExecutable, nodeCommand, gitText } from "./support/shell.js";
import { fail, rejecting, throwing } from "./support/errors.js";
import { mockFs, restoreFs } from "./support/module-mocks.js";
@@ -1391,9 +1394,11 @@ describe("CodexSecurity orchestration", () => {
},
);
- await expect(client.run(repository)).rejects.toThrow(
- `Set ${apiKey} to run a scan through ${name}.`,
- );
+ for (const operation of ["preflight", "run"] as const) {
+ await expect(client[operation](repository)).rejects.toThrow(
+ `Set ${apiKey} to run a scan through ${name}.`,
+ );
+ }
expect(prepareRuntime).not.toHaveBeenCalled();
await client.close();
},
@@ -1659,6 +1664,9 @@ describe("CodexSecurity orchestration", () => {
{
environment: { AWS_PROFILE: "synthetic-bedrock" },
...scanRuntimeDependencies(codexHome, scanDir),
+ prepareRuntime: runtimePreparer(codexHome, () => ({
+ deepScanConfigPath: join(codexHome, "deep-scan.toml"),
+ })),
createCodex: () => ({
startThread: () => ({
id: null,
@@ -1693,7 +1701,11 @@ describe("CodexSecurity orchestration", () => {
const scenarios: [JsonObject, string, string | undefined][] = [
[{}, "none", undefined],
[
- { model_reasoning_summary: "auto", service_tier: "flex" },
+ {
+ model_reasoning_summary: "auto",
+ service_tier: "flex",
+ windows: { sandbox: "unelevated" },
+ },
"auto",
"flex",
],
@@ -1701,7 +1713,11 @@ describe("CodexSecurity orchestration", () => {
{
profile: "cloud",
profiles: {
- cloud: { model_reasoning_summary: "concise", service_tier: "fast" },
+ cloud: {
+ model_reasoning_summary: "concise",
+ service_tier: "fast",
+ windows: { sandbox: "elevated" },
+ },
},
},
"concise",
@@ -1710,10 +1726,14 @@ describe("CodexSecurity orchestration", () => {
[
{
profile: "cloud.production",
+ windows: { sandbox: "elevated" },
profiles: {
"cloud.production": {
model_reasoning_summary: "concise",
service_tier: "fast",
+ model_instructions_file: "profile-instructions.md",
+ model_verbosity: "high",
+ windows: { sandbox: "unelevated" },
},
},
},
@@ -1734,6 +1754,12 @@ describe("CodexSecurity orchestration", () => {
scenarios.map(async ([overrides, expected, expectedTier], index) => {
const scanDir = join(root, `scan-${index}`);
await mkdir(scanDir, { mode: 0o700 });
+ const instructionsFile =
+ resolveCodexProfile(overrides)["model_instructions_file"];
+ const instructions = `Synthetic instructions for scan ${index}.\n`;
+ if (typeof instructionsFile === "string") {
+ await writeFile(join(scanDir, instructionsFile), instructions);
+ }
return new TestClient(
{
pluginPath: PLUGIN_ROOT,
@@ -1753,9 +1779,10 @@ describe("CodexSecurity orchestration", () => {
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
createCodex: (options: CodexOptions) => ({
- startThread: () => ({
+ startThread: (threadOptions: ThreadOptions) => ({
id: null,
async runStreamed() {
+ expect(threadOptions.workingDirectory).toBe(scanDir);
if (++started === scenarios.length) allStarted.resolve();
await allStarted.promise;
const mcpEnvironment = Object.fromEntries(
@@ -1781,6 +1808,31 @@ describe("CodexSecurity orchestration", () => {
subagents: index,
stop_after_consecutive_errors: index + 2,
});
+ const workerConfig = parseToml(
+ await readFile(deepConfigPath, "utf8"),
+ )["worker_runtime"] as JsonObject;
+ const windows = (resolveCodexProfile(overrides)["windows"] ??
+ DEFAULT_CODEX_CONFIG["windows"]) as { sandbox: string };
+ expect(workerConfig["windows"] as JsonObject).toEqual(
+ windows,
+ );
+ expect(options.config?.["windows"]).toEqual(windows);
+ expect(workerConfig["model_verbosity"]).toBe(
+ resolveCodexProfile(overrides)["model_verbosity"],
+ );
+ expect(workerConfig["model_instructions_file"]).toBe(
+ typeof instructionsFile === "string"
+ ? join(scanDir, instructionsFile)
+ : undefined,
+ );
+ if (typeof instructionsFile === "string") {
+ expect(
+ await readFile(
+ workerConfig["model_instructions_file"] as string,
+ "utf8",
+ ),
+ ).toBe(instructions);
+ }
const config = parseToml(
await readFile(configPath!, "utf8"),
) as JsonObject;
@@ -1789,9 +1841,7 @@ describe("CodexSecurity orchestration", () => {
model_reasoning_effort: "xhigh",
model_provider: "amazon-bedrock",
});
- expect(resolveCodexProfile(config)["service_tier"]).toBe(
- expectedTier,
- );
+ expect(config["service_tier"]).toBe(expectedTier);
expect(mcpEnvironment["AWS_BEARER_TOKEN_BEDROCK"]).toBe(
"synthetic-bedrock-key",
);
@@ -3732,6 +3782,7 @@ describe("CodexSecurity orchestration", () => {
"dismissed",
undefined,
],
+ ["managed provider selection retains matching", "managed", undefined],
] as const)(
"keeps a completed scan when %s",
async (_scenario, failure, warning) => {
@@ -3759,10 +3810,136 @@ describe("CodexSecurity orchestration", () => {
let observedSingleTurn: boolean | undefined;
let matched = false;
let savedComparisonInput: string | undefined;
+ const managedProvider = {
+ name: "Synthetic managed provider",
+ wire_api: "responses",
+ requires_openai_auth: false,
+ http_headers: { "X-Synthetic-Key": "synthetic-managed-secret" },
+ };
+ const providerConfig = {
+ features: { shell_tool: false, unified_exec: false, view_image: false },
+ windows: { sandbox: "unelevated" },
+ model_provider: "synthetic.provider",
+ model_providers: {
+ "synthetic.provider": {
+ name: "Synthetic provider",
+ base_url: "https://provider.example.test/v1",
+ wire_api: "responses",
+ env_http_headers: {
+ "X-Synthetic-Context": "SYNTHETIC_MATCH_HEADER",
+ },
+ auth: { command: "synthetic-auth" },
+ },
+ ...(failure === "managed"
+ ? { "synthetic.managed": managedProvider }
+ : {}),
+ },
+ };
+ const executable = join(codexHome, "synthetic-native.mjs");
+ const startupCallsPath = join(codexHome, "matching-calls.jsonl");
+ let spawnSpy: ReturnType<typeof spyOn> | undefined;
+ if (failure === "managed") {
+ await writeFile(
+ executable,
+ `import { appendFileSync, readFileSync } from "node:fs";
+ import { join } from "node:path";
+ import { createInterface } from "node:readline";
+ import { parse } from ${JSON.stringify(pathToFileURL(Bun.resolveSync("smol-toml", import.meta.dir)).href)};
+ const args = process.argv.slice(2);
+ const config = {};
+ for (let index = 0; index < args.length; index++) {
+ if (args[index] === "-c" || args[index] === "--config")
+ Object.assign(config, parse(args[++index]));
+ }
+ const kind = args.includes("mcp") ? "mcp" : args.includes("app-server") ? "preflight" : "exec";
+ const call = { kind, args };
+ if (kind !== "exec") {
+ call.metadata = config.model_providers;
+ appendFileSync(${JSON.stringify(startupCallsPath)}, JSON.stringify(call) + "\\n");
+ if (!config.model_providers?.["synthetic.managed"]) {
+ console.error(${JSON.stringify("Model provider `synthetic.managed` not found")});
+ process.exit(1);
+ }
+ } else {
+ const name = args[args.indexOf("--profile") + 1];
+ const profile = parse(readFileSync(join(process.env.CODEX_HOME, name + ".config.toml"), "utf8"));
+ call.providers = Object.keys(profile.model_providers);
+ call.privateSecretLoaded = profile.model_providers["synthetic.managed"].http_headers["X-Synthetic-Key"] === "synthetic-managed-secret";
+ call.permissions = config.permissions[config.default_permissions];
+ appendFileSync(${JSON.stringify(startupCallsPath)}, JSON.stringify(call) + "\\n");
+ }
+ if (kind === "mcp") { console.log("[]"); process.exit(0); }
+ if (kind === "exec") {
+ console.log(JSON.stringify({ type: "thread.started", thread_id: "matching-thread" }));
+ console.log(JSON.stringify({ type: "turn.started" }));
+ console.log(JSON.stringify({ type: "item.completed", item: { id: "matching-result", type: "agent_message", text: ${JSON.stringify(JSON.stringify({ matches: [{ beforeOccurrenceIds: [previous.occurrenceId], afterOccurrenceIds: [current.occurrenceId], confidence: "high", reason: "Same synthetic root cause." }], uncertain: [] }))} } }));
+ console.log(JSON.stringify({ type: "turn.completed", usage: { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 } }));
+ process.exit(0);
+ }
+ const lines = createInterface({ input: process.stdin });
+ for await (const line of lines) {
+ const request = JSON.parse(line);
+ if (request.id === undefined) continue;
+ const result = request.method === "config/read"
+ ? { config: { ...config, model_provider: "synthetic.managed" } }
+ : request.method === "permissionProfile/list"
+ ? { data: [{ id: config.default_permissions, allowed: true }], nextCursor: null }
+ : {};
+ console.log(JSON.stringify({ id: request.id, result }));
+ }`,
+ );
+ const originalSpawn = childProcess.spawn;
+ spawnSpy = spyOn(childProcess, "spawn").mockImplementation(((
+ ...input: Parameters<typeof originalSpawn>
+ ) => {
+ const [command, args, options] = input;
+ return (command === process.execPath ||
+ command === runtime.executablePathForSpawn(process.execPath)) &&
+ args?.some((arg) => ["mcp", "app-server", "exec"].includes(arg))
+ ? originalSpawn(
+ process.execPath,
+ [executable, ...args],
+ options ?? {},
+ )
+ : originalSpawn(...input);
+ }) as typeof originalSpawn);
+ }
const client = new TestClient(
- {},
+ {
+ codexOverrides: {
+ ...providerConfig,
+ ...(failure === "budget-context"
+ ? {
+ model: "gpt-6.1-sol",
+ model_reasoning_effort: "xhigh",
+ profile: "cloud.production",
+ profiles: {
+ "cloud.production": {
+ model: "gpt-5.6-sol",
+ model_reasoning_effort: "medium",
+ features: { shell_tool: true, view_image: true },
+ },
+ },
+ }
+ : {}),
+ },
+ },
{
...scanRuntimeDependencies(codexHome, scanDir),
+ prepareRuntime: runtimePreparer(codexHome, () => ({
+ environment: {
+ SYNTHETIC_MATCH_HEADER: "synthetic-comparison-header",
+ ...(failure === "managed"
+ ? {
+ PATH: process.env["PATH"] ?? "",
+ ...(process.env["SystemRoot"] === undefined
+ ? {}
+ : { SystemRoot: process.env["SystemRoot"] }),
+ CODEX_CLI_PATH: process.execPath,
+ }
+ : {}),
+ },
+ })),
runWorkbench: async (
_options: unknown,
args: readonly string[],
@@ -3789,7 +3966,7 @@ describe("CodexSecurity orchestration", () => {
}
if (args[0] === "list-global-findings") {
if (failure === "index") throw new Error("index unavailable");
- if (failure === "dismissed") {
+ if (failure === "dismissed" || failure === "managed") {
return {
findings: args.includes("--status")
? matched
@@ -3813,16 +3990,54 @@ describe("CodexSecurity orchestration", () => {
},
async matchFindings(input, options, runtimeOptions) {
expect(options?.cyberAccessProgram).toBe("daybreak_blue");
+ if (failure !== "managed")
+ expect(options?.config?.codexOverrides).toMatchObject({
+ ...providerConfig,
+ features: {
+ ...providerConfig.features,
+ ...(failure === "budget-context"
+ ? { shell_tool: true, view_image: true }
+ : {}),
+ },
+ });
+ expect(
+ options?.config?.codexOverrides?.["environment"],
+ ).toBeUndefined();
+ expect(options?.environment?.["SYNTHETIC_MATCH_HEADER"]).toBe(
+ "synthetic-comparison-header",
+ );
+ const nativeProfile = await import(
+ pathToFileURL(join(PLUGIN_ROOT, "scripts", "codex_profile.mjs"))
+ .href
+ );
+ const matcherArguments = nativeProfile.profileConfigOverrides(
+ options?.config?.codexOverrides ?? {},
+ ) as string[];
+ expect(
+ matcherArguments.some((value) =>
+ value.includes("synthetic-comparison-header"),
+ ),
+ ).toBe(false);
modelCalled = true;
observedSingleTurn = runtimeOptions.singleTurn;
if (failure === "matcher") throw new Error("matcher unavailable");
+ if (failure === "managed")
+ return await matchScanFindingsInternal(
+ input,
+ options,
+ runtimeOptions,
+ );
if (failure === "budget-context") {
return await matchScanFindingsInternal(
input,
{
...options,
codex: {
- startThread() {
+ startThread(threadOptions) {
+ expect(threadOptions).toMatchObject({
+ model: "gpt-5.6-sol",
+ modelReasoningEffort: "medium",
+ });
return {
async run(_input, turnOptions) {
expect(turnOptions.cyberAccessProgram).toBe(
@@ -3849,66 +4064,135 @@ describe("CodexSecurity orchestration", () => {
runtimeOptions,
);
}
- return {
- matches: [
- {
- beforeOccurrenceIds: [previous.occurrenceId],
- afterOccurrenceIds: [current.occurrenceId],
- confidence: "high",
- reason: "Same dismissed root cause.",
+ return await matchScanFindingsInternal(
+ input,
+ {
+ ...options,
+ codex: {
+ startThread(threadOptions) {
+ expect(threadOptions).toMatchObject({
+ sandboxMode: "read-only",
+ approvalPolicy: "never",
+ networkAccessEnabled: false,
+ });
+ return {
+ async run() {
+ matchingTurns += 1;
+ return {
+ finalResponse: JSON.stringify({
+ matches: [
+ {
+ beforeOccurrenceIds: [previous.occurrenceId],
+ afterOccurrenceIds: [current.occurrenceId],
+ confidence: "high",
+ reason: "Same dismissed root cause.",
+ },
+ ],
+ uncertain: [],
+ }),
+ };
+ },
+ };
+ },
},
- ],
- uncertain: [],
- };
+ },
+ runtimeOptions,
+ );
},
createCodex: completedCodex(root),
},
);
- const result = await client.run(repository, {
- ...(limited ? { maxCostUsd: 1 } : {}),
- cyberAccessProgram: "daybreak_blue",
- onWarning: (message) => warnings.push(message),
- });
- expect(result.threadId).toBe("thread-1");
- expect(
- result.repositoryFindings?.map(({ findingId }) => findingId),
- ).toEqual(
- failure === "budget"
- ? ["another-open-finding"]
- : failure === "dismissed"
- ? []
- : undefined,
- );
- expect(warnings).toEqual(
- warning === undefined ? [] : [expect.stringContaining(warning)],
- );
- expect(modelCalled).toBe(failure !== "index");
- expect(observedSingleTurn).toBe(
- failure === "index" ? undefined : limited,
- );
- if (failure === "budget-context") {
- expect(matchingTurns).toBe(1);
- expect(matched).toBe(false);
- }
- expect(commands.some(([command]) => command === "complete-scan")).toBe(
- true,
- );
- expect(
- commands.some(([command]) => command === "list-global-findings"),
- ).toBe(true);
- if (failure === "dismissed") {
- expect(JSON.parse(savedComparisonInput!)).toMatchObject({
- matches: [
- {
- beforeOccurrenceIds: [previous.occurrenceId],
- afterOccurrenceIds: [current.occurrenceId],
- },
- ],
- uncertain: [],
+ try {
+ const result = await client.run(repository, {
+ ...(limited ? { maxCostUsd: 1 } : {}),
+ cyberAccessProgram: "daybreak_blue",
+ onWarning: (message) => warnings.push(message),
});
+ expect(result.threadId).toBe("thread-1");
+ expect(warnings).toEqual(
+ warning === undefined ? [] : [expect.stringContaining(warning)],
+ );
+ expect(
+ result.repositoryFindings?.map(({ findingId }) => findingId),
+ ).toEqual(
+ failure === "budget"
+ ? ["another-open-finding"]
+ : failure === "dismissed" || failure === "managed"
+ ? []
+ : undefined,
+ );
+ expect(modelCalled).toBe(failure !== "index");
+ expect(observedSingleTurn).toBe(
+ failure === "index" ? undefined : limited,
+ );
+ expect(matchingTurns).toBe(
+ failure === "index" || failure === "matcher" || failure === "managed"
+ ? 0
+ : 1,
+ );
+ if (failure === "budget-context") {
+ expect(matched).toBe(false);
+ }
+ expect(commands.some(([command]) => command === "complete-scan")).toBe(
+ true,
+ );
+ expect(
+ commands.some(([command]) => command === "list-global-findings"),
+ ).toBe(true);
+ if (failure === "dismissed" || failure === "managed") {
+ expect(JSON.parse(savedComparisonInput!)).toMatchObject({
+ matches: [
+ {
+ beforeOccurrenceIds: [previous.occurrenceId],
+ afterOccurrenceIds: [current.occurrenceId],
+ },
+ ],
+ uncertain: [],
+ });
+ }
+ if (failure === "managed") {
+ const calls = (await readFile(startupCallsPath, "utf8"))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ expect(calls.map(({ kind }) => kind)).toEqual([
+ "mcp",
+ "preflight",
+ "exec",
+ ]);
+ const metadata = {
+ "synthetic.provider": {
+ name: "Synthetic provider",
+ wire_api: "responses",
+ },
+ "synthetic.managed": {
+ name: "Synthetic managed provider",
+ wire_api: "responses",
+ requires_openai_auth: false,
+ },
+ };
+ expect(calls[0].metadata).toEqual(metadata);
+ expect(calls[1].metadata).toEqual(metadata);
+ expect(calls[2]).toMatchObject({
+ providers: ["synthetic.provider", "synthetic.managed"],
+ privateSecretLoaded: true,
+ permissions: {
+ filesystem: { [codexHome]: { ".": "deny" } },
+ network: { enabled: false },
+ },
+ });
+ expect(JSON.stringify(calls.map(({ args }) => args))).not.toContain(
+ "synthetic-managed-secret",
+ );
+ expect(JSON.stringify(calls.map(({ args }) => args))).not.toContain(
+ "provider.example.test",
+ );
+ }
+ } finally {
+ await client.close();
+ spawnSpy?.mockRestore();
}
- await client.close();
},
);
@@ -5163,6 +5447,22 @@ describe("CodexSecurity orchestration", () => {
test.each([
["OpenAI", undefined, "OPENAI_API_KEY", "gpt-5.6-sol", undefined],
...EXTERNAL_PROVIDER_CASES,
+ [
+ "managed custom",
+ "synthetic.gateway",
+ "OPENAI_API_KEY",
+ "gpt-5.6-sol",
+ {
+ name: "Synthetic",
+ wire_api: "responses",
+ requires_openai_auth: false,
+ http_headers: { "X-Synthetic-Key": "synthetic-provider-secret" },
+ auth: {
+ command: "synthetic-auth",
+ args: ["synthetic-command-secret"] as string[],
+ },
+ },
+ ],
] as const)(
"retains %s scan sessions in the managed Codex home",
async (_name, provider, apiKey, model, providerConfig) => {
@@ -5204,6 +5504,30 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
+ probeCodexSandbox: async (command) => {
+ if (provider === undefined) {
+ expect(command.args).toBeUndefined();
+ } else {
+ expect(command.args?.[0]).toBe("-c");
+ expect(parseToml(command.args![1]!)).toEqual({
+ model_providers: {
+ [provider]: {
+ name: providerConfig!.name,
+ wire_api: providerConfig!.wire_api,
+ ...(provider === "synthetic.gateway"
+ ? { requires_openai_auth: false }
+ : {}),
+ },
+ },
+ });
+ expect(command.args!.join(" ")).not.toContain(
+ "synthetic-provider-secret",
+ );
+ expect(command.args!.join(" ")).not.toContain(
+ "synthetic-command-secret",
+ );
+ }
+ },
createCodex: (options: CodexOptions) => ({
startThread: () => ({
id: null,
@@ -5228,6 +5552,9 @@ describe("CodexSecurity orchestration", () => {
await expect(client.run(repository)).rejects.toThrow(
"persistent session recorded",
);
+ await expect(client.run(repository)).rejects.toThrow(
+ "persistent session recorded",
+ );
} finally {
await client.close();
}
@@ -5252,12 +5579,8 @@ describe("CodexSecurity orchestration", () => {
expect(persistentConfigText).not.toContain("synthetic-transient-key");
const persistentConfig = parseToml(persistentConfigText);
expect(persistentConfig["model"]).toBeUndefined();
- if (provider !== undefined) {
- expect(persistentConfig).toMatchObject({
- model_provider: provider,
- model_providers: { [provider]: providerConfig },
- });
- }
+ expect(persistentConfig["model_provider"]).toBeUndefined();
+ expect(persistentConfig["model_providers"]).toBeUndefined();
},
);
@@ -5302,7 +5625,9 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- createCodex: (options: CodexOptions) => {
+ createCodex: async (
+ options: CodexOptions & { nativeProfile?: string },
+ ) => {
expect(options.env?.["CODEX_HOME"]).toBe(codexHome);
expect(options.config).toMatchObject({
model,
@@ -5310,17 +5635,39 @@ describe("CodexSecurity orchestration", () => {
? {}
: {
model_provider: provider,
- model_providers: {
- [provider]: OPENROUTER_CODEX_PROVIDER,
- },
}),
});
+ expect(options.config?.["model_providers"]).toBeUndefined();
+ if (provider !== undefined) {
+ expect(
+ parseToml(
+ await readFile(
+ join(codexHome, `${options.nativeProfile}.config.toml`),
+ "utf8",
+ ),
+ ),
+ ).toEqual({
+ model_providers: { [provider]: OPENROUTER_CODEX_PROVIDER },
+ });
+ }
return {
startThread: () => ({
id: null,
async runStreamed() {
if (++scansStarted === 2) concurrentScans.resolve();
await concurrentScans.promise;
+ const workerConfig = parseToml(
+ await readFile(
+ options.env!["CODEX_SECURITY_CONFIG_PATH"]!,
+ "utf8",
+ ),
+ );
+ expect(workerConfig["model_provider"]).toBe(provider);
+ if (provider !== undefined) {
+ expect(workerConfig["model_providers"]).toEqual({
+ [provider]: OPENROUTER_CODEX_PROVIDER,
+ });
+ }
throw new Error("parallel API-key scan reached");
},
}),
@@ -6062,6 +6409,84 @@ describe("CodexSecurity orchestration", () => {
await client.close();
});
+ test("Windows shim fallback restores bundled tools in the child environment", async () => {
+ if (
+ runTestInSubprocess(
+ import.meta.path,
+ "Windows shim fallback restores bundled tools in the child environment",
+ )
+ )
+ return;
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
+ const executable = join(
+ root,
+ "vendor",
+ "synthetic-target",
+ "bin",
+ "codex.exe",
+ );
+ const bundledTools = join(dirname(dirname(executable)), "codex-path");
+ const inheritedTools = join(root, "operator-tools");
+ await mkdir(bundledTools, { recursive: true });
+ await mkdir(inheritedTools);
+ const originalPlatform = Object.getOwnPropertyDescriptor(
+ process,
+ "platform",
+ )!;
+ let childPath: string | undefined;
+ const client = new TestClient(
+ {},
+ {
+ environment: {
+ CODEX_CLI_PATH: join(root, "codex.cmd"),
+ OPENAI_API_KEY: "synthetic-key",
+ },
+ prepareRuntime: runtimePreparer(codexHome, () => ({
+ environment: {
+ CODEX_HOME: codexHome,
+ CODEX_CLI_PATH: executable,
+ PATH: inheritedTools,
+ },
+ })),
+ resolveCodexCommand: () => ({ command: executable }),
+ resolvePluginPython: async () => {
+ Object.defineProperty(process, "platform", {
+ value: "win32",
+ configurable: true,
+ });
+ return "/managed/python";
+ },
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: (options) => ({
+ startThread: () => ({
+ id: null,
+ async runStreamed() {
+ childPath = execFileSync(
+ process.execPath,
+ ["-e", "console.log(process.env.PATH)"],
+ { env: options.env, encoding: "utf8" },
+ ).trim();
+ throw new Error("child environment captured");
+ },
+ }),
+ }),
+ },
+ );
+ try {
+ await expect(client.run(repository)).rejects.toThrow(
+ "child environment captured",
+ );
+ expect(childPath?.split(delimiter)).toEqual([
+ bundledTools,
+ inheritedTools,
+ ]);
+ } finally {
+ Object.defineProperty(process, "platform", originalPlatform);
+ await client.close();
+ }
+ });
+
test.each(["native", "shim"])(
"uses one spawnable Codex executable for scans and nested workers (%s)",
async (kind) => {
@@ -6118,7 +6543,17 @@ describe("CodexSecurity orchestration", () => {
expect(createCodex.mock.lastCall?.[0]?.env?.["CODEX_CLI_PATH"]).toBe(
selectedExecutable,
);
- expect(createCodex.mock.lastCall?.[0]?.env?.["PATH"]).toBe(searchPath);
+ const bundledTools = join(
+ dirname(dirname(selectedExecutable)),
+ "codex-path",
+ );
+ expect(createCodex.mock.lastCall?.[0]?.env?.["PATH"]).toBe(
+ process.platform === "win32" &&
+ kind === "shim" &&
+ existsSync(bundledTools)
+ ? [bundledTools, searchPath].join(delimiter)
+ : searchPath,
+ );
await client.close();
},
);
@@ -6514,6 +6949,107 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
await client.close();
});
+ test("respects an external logout when reusing an API-key runtime", async () => {
+ const { root, repository, codexHome, scanDir } = await scanDirectories();
+ const ambientHome = join(root, "ambient-home");
+ await mkdir(ambientHome);
+ if (process.platform !== "win32") await chmod(codexHome, 0o700);
+ await writeFile(
+ join(ambientHome, "auth.json"),
+ '{"auth_mode":"chatgpt"}\n',
+ );
+ const fakeCodex = join(root, "logged-out.mjs");
+ await writeFile(
+ fakeCodex,
+ 'console.error("Not logged in"); process.exit(1);',
+ );
+ const fake = nodeCodex(fakeCodex);
+ const createCodex = mock(throwing("scan reached"));
+ const client = new TestClient(
+ {},
+ {
+ environment: {
+ CODEX_HOME: ambientHome,
+ OPENAI_API_KEY: "synthetic-key",
+ },
+ prepareRuntime: unauthenticatedRuntime(codexHome, () => ({
+ CODEX_HOME: codexHome,
+ ...fake.environment,
+ })),
+ resolveCodexCommand: () => fake.command,
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex,
+ },
+ );
+ try {
+ await expect(client.run(repository)).rejects.toThrow("scan reached");
+ await runtime.setCodexSecurityCredentialLogout(codexHome, true);
+ await expect(
+ client.run(repository, { auth: "chatgpt" }),
+ ).rejects.toBeInstanceOf(AuthenticationRequiredError);
+ expect(createCodex).toHaveBeenCalledTimes(1);
+ expect(existsSync(join(codexHome, "auth.json"))).toBe(false);
+ } finally {
+ await client.close();
+ }
+ });
+
+ test.each(["standard", "deep"] as const)(
+ "refreshes inherited environment for a reused %s runtime",
+ async (mode) => {
+ const { root, repository, scanDir } = await scanDirectories();
+ const environment: Record<string, string> = {
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ OPENAI_API_KEY: "synthetic-first-key",
+ AWS_REGION: "synthetic-first-region",
+ REMOVED_SETTING: "first-value",
+ };
+ const observed: CodexOptions[] = [];
+ const client = new TestClient(
+ { pluginPath: PLUGIN_ROOT },
+ {
+ environment,
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: (options) => {
+ observed.push(options);
+ throw new Error("environment captured");
+ },
+ },
+ );
+ try {
+ await expect(client.run(repository, { mode })).rejects.toThrow(
+ "environment captured",
+ );
+ environment["OPENAI_API_KEY"] = "synthetic-second-key";
+ environment["AWS_REGION"] = "synthetic-second-region";
+ delete environment["REMOVED_SETTING"];
+ environment["ADDED_SETTING"] = "second-value";
+ await expect(client.run(repository, { mode })).rejects.toThrow(
+ "environment captured",
+ );
+ expect(observed.map((value) => value.apiKey)).toEqual([
+ "synthetic-first-key",
+ "synthetic-second-key",
+ ]);
+ expect(observed[1]?.env).toMatchObject({
+ AWS_REGION: "synthetic-second-region",
+ ADDED_SETTING: "second-value",
+ });
+ expect(observed[1]?.env).not.toHaveProperty("REMOVED_SETTING");
+ expect(observed[0]?.env).toMatchObject({
+ AWS_REGION: "synthetic-first-region",
+ REMOVED_SETTING: "first-value",
+ });
+ } finally {
+ await client.close();
+ }
+ },
+ );
+
test("uses a rotated environment API key on the next scan", async () => {
const { repository, codexHome, scanDir } = await scanDirectories();
const environment: Record<string, string | undefined> = {
@@ -6750,47 +7286,156 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
await expect(client.close()).resolves.toBeUndefined();
});
- test("propagates bootstrap workspace cleanup failures from close", async () => {
+ test("retains provider profiles for close when replacement cleanup fails", async () => {
+ const { repository, codexHome, scanDir } = await scanDirectories();
+ const prepared = preparedRuntime(codexHome);
+ const createCodex = mock(throwing("synthetic scan reached"));
+ const client = new TestClient(
+ {
+ codexOverrides: {
+ model_provider: "synthetic-provider",
+ model_providers: {
+ "synthetic-provider": {
+ name: "Synthetic provider",
+ base_url: "https://provider.example.test/v1",
+ wire_api: "responses",
+ requires_openai_auth: false,
+ http_headers: {
+ "X-Synthetic-Token": "synthetic-private-value",
+ },
+ },
+ },
+ },
+ },
+ {
+ ...scanRuntimeDependencies(codexHome, scanDir),
+ prepareRuntime: async () => prepared,
+ createCodex,
+ },
+ );
+ try {
+ await expect(
+ client.run(repository, { mode: "standard" }),
+ ).rejects.toThrow("synthetic scan reached");
+ const previous = prepared.providerProfile!;
+ const cleanup = previous.cleanup;
+ const failure = new Error("synthetic raw profile cleanup failure");
+ let cleanups = 0;
+ previous.cleanup = async () => {
+ if (++cleanups === 1) throw failure;
+ await cleanup();
+ };
+ await expect(client.run(repository, { mode: "standard" })).rejects.toBe(
+ failure,
+ );
+ expect(createCodex).toHaveBeenCalledTimes(1);
+ const profiles = (await readdir(codexHome)).filter((name) =>
+ name.endsWith(".config.toml"),
+ );
+ await client.close();
+ expect(existsSync(previous.path)).toBe(false);
+ expect(cleanups).toBe(2);
+ expect(profiles).toEqual([`${previous.name}.config.toml`]);
+ } finally {
+ await client.close();
+ }
+ });
+
+ test("attempts all runtime cleanup and preserves failures from close", async () => {
if (
runTestInSubprocess(
import.meta.path,
- "propagates bootstrap workspace cleanup failures from close",
+ "attempts all runtime cleanup and preserves failures from close",
)
) {
return;
}
- const { root, repository, codexHome } = await runtimeDirectories();
- const bootstrapWorkspace = join(root, "bootstrap-workspace");
- await mkdir(bootstrapWorkspace);
- const client = new TestClient(
- {},
- {
- environment: {
- CODEX_SECURITY_STATE_DIR: join(root, "state"),
- OPENAI_API_KEY: "ambient-key",
+ for (const failures of [
+ ["profile"],
+ ["deep"],
+ ["bootstrap"],
+ ["deep", "bootstrap"],
+ ["profile", "deep", "bootstrap"],
+ ]) {
+ const { root, repository, codexHome } = await runtimeDirectories();
+ const bootstrapWorkspace = join(root, "bootstrap-workspace");
+ const deepScanConfigDirectory = join(codexHome, "worker-config");
+ await mkdir(bootstrapWorkspace);
+ await mkdir(deepScanConfigDirectory, { recursive: true });
+ const prepared = {
+ ...preparedRuntime(codexHome),
+ bootstrapWorkspace,
+ deepScanConfigDirectory,
+ };
+ const client = new TestClient(
+ {},
+ {
+ environment: {
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ OPENAI_API_KEY: "ambient-key",
+ },
+ prepareRuntime: async () => prepared,
+ resolvePluginPython: async () => "/managed/python",
+ repositoryRevision: async () => null,
+ createCodex: () => fail("scan reached"),
},
- prepareRuntime: runtimePreparer(codexHome, () => ({
+ );
+ await expect(client.run(repository)).rejects.toThrow("scan reached");
+ const profile = await createProviderProfile(codexHome, {
+ model_providers: {
+ "synthetic-provider": {
+ name: "Synthetic provider",
+ http_headers: { "X-Synthetic-Token": "synthetic-private-value" },
+ },
+ },
+ });
+ prepared.providerProfile = profile;
+ const originalRm = fsPromises.rm;
+ const cleanupFailures: Record<string, Error> = {
+ profile: new Error("synthetic raw profile cleanup failure"),
+ deep: new Error("synthetic raw worker cleanup failure"),
+ bootstrap: new Error("synthetic raw bootstrap cleanup failure"),
+ };
+ const attempted: string[] = [];
+ mockFs(() => ({
+ rm: async (...args: Parameters<typeof originalRm>) => {
+ const path = String(args[0]);
+ attempted.push(path);
+ if (path === profile.path && failures.includes("profile"))
+ throw cleanupFailures["profile"];
+ if (path === deepScanConfigDirectory && failures.includes("deep"))
+ throw cleanupFailures["deep"];
+ if (path === bootstrapWorkspace && failures.includes("bootstrap"))
+ throw cleanupFailures["bootstrap"];
+ return await originalRm(...args);
+ },
+ }));
+ try {
+ const error = await client.close().catch((error: unknown) => error);
+ if (failures.length === 1) {
+ expect(error).toBe(cleanupFailures[failures[0]!]);
+ } else {
+ expect(error).toBeInstanceOf(AggregateError);
+ expect((error as AggregateError).errors).toEqual(
+ failures.map((name) => cleanupFailures[name]),
+ );
+ }
+ expect(attempted).toEqual([
+ profile.path,
+ deepScanConfigDirectory,
bootstrapWorkspace,
- })),
- resolvePluginPython: async () => "/managed/python",
- repositoryRevision: async () => null,
- createCodex: () => fail("scan reached"),
- },
- );
- await expect(client.run(repository)).rejects.toThrow("scan reached");
- const originalRm = fsPromises.rm;
- const failure = new Error("synthetic raw bootstrap cleanup failure");
- mockFs(() => ({
- rm: async (...args: Parameters<typeof originalRm>) => {
- if (String(args[0]) === bootstrapWorkspace) throw failure;
- return await originalRm(...args);
- },
- }));
- try {
- await expect(client.close()).rejects.toBe(failure);
- expect(existsSync(codexHome)).toBe(true);
- } finally {
- restoreFs({ rm: originalRm });
+ ]);
+ expect(existsSync(profile.path)).toBe(failures.includes("profile"));
+ expect(existsSync(deepScanConfigDirectory)).toBe(
+ failures.includes("deep"),
+ );
+ expect(existsSync(bootstrapWorkspace)).toBe(
+ failures.includes("bootstrap"),
+ );
+ expect(existsSync(codexHome)).toBe(true);
+ } finally {
+ restoreFs({ rm: originalRm });
+ }
}
});
diff --git a/sdk/typescript/tests-ts/build-plugin.test.ts b/sdk/typescript/tests-ts/build-plugin.test.ts
index 86880407b..7b9c08faf 100644
--- a/sdk/typescript/tests-ts/build-plugin.test.ts
+++ b/sdk/typescript/tests-ts/build-plugin.test.ts
@@ -10,7 +10,7 @@ import {
writeFile,
} from "node:fs/promises";
import { basename, delimiter, join } from "node:path";
-import { fileURLToPath } from "node:url";
+import { fileURLToPath, pathToFileURL } from "node:url";
import { brotliDecompressSync } from "node:zlib";
import { promisify } from "node:util";
import { afterEach, describe, expect, test } from "bun:test";
@@ -98,14 +98,17 @@ describe("bundled plugin build", () => {
await cp(join(plugin, "schemas"), join(source, "schemas"), {
recursive: true,
});
- await writeFixture(
- source,
- "scripts/reserved_artifact_paths.json",
- await readFile(
- join(plugin, "scripts", "reserved_artifact_paths.json"),
- "utf8",
- ),
- );
+ for (const file of [
+ "reserved_artifact_paths.json",
+ "codex_profile.mjs",
+ "codex_profile.d.mts",
+ ]) {
+ await writeFixture(
+ source,
+ `scripts/${file}`,
+ await readFile(join(plugin, "scripts", file), "utf8"),
+ );
+ }
await symlink(
join(plugin, "mcp-app", "node_modules"),
join(source, "mcp-app", "node_modules"),
@@ -205,6 +208,26 @@ describe("bundled plugin build", () => {
]);
expect(helper.stdout).toBe("[]\n");
expect(helper.stderr).toBe("");
+ const preflight = await execFileAsync(
+ "node",
+ [
+ "--input-type=module",
+ "--eval",
+ `const runtime = await import(process.argv[1]);
+ console.log(JSON.stringify({
+ preflight: typeof runtime.preflightDeepScanWorkerPermissionProfile,
+ profileId: runtime.DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID,
+ }));`,
+ pathToFileURL(join(destination, "permission-profile-preflight.mjs"))
+ .href,
+ ],
+ { cwd: root },
+ );
+ expect(JSON.parse(preflight.stdout)).toEqual({
+ preflight: "function",
+ profileId: "codex_security_deep_scan_worker",
+ });
+ expect(preflight.stderr).toBe("");
},
);
diff --git a/sdk/typescript/tests-ts/cli-serve.test.ts b/sdk/typescript/tests-ts/cli-serve.test.ts
index 2670e5b5e..6961216e1 100644
--- a/sdk/typescript/tests-ts/cli-serve.test.ts
+++ b/sdk/typescript/tests-ts/cli-serve.test.ts
@@ -5,7 +5,7 @@ import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
-import { expect, test } from "bun:test";
+import { expect, mock, test } from "bun:test";
import { main } from "../src/cli.js";
import type { FindingsDocument } from "../src/models.js";
import {
@@ -16,15 +16,23 @@ import { capture, dependencies } from "./cli-fixtures.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
import { runCommand } from "./support/shell.js";
import { createCliTest } from "./support/cli-run.js";
+import { runTestInSubprocess } from "./support/test-subprocess.js";
const packageRoot = join(import.meta.dir, "..");
const cli = join(packageRoot, "src", "cli.ts");
-for (const [name, args, port, customEmbeddings] of [
+for (const [name, args, port, customEmbeddings, blankEnvironment] of [
["CLI", [cli, "serve"], "0"],
["CLI --port overrides PORT", [cli, "serve", "--port", "0"], "invalid"],
["CLI --port=0 overrides PORT", [cli, "serve", "--port=0"], "invalid"],
["CLI with custom embeddings URL", [cli, "serve"], "0", true],
+ [
+ "standalone blank host and primary key",
+ [join(packageRoot, "src", "server", "index.ts")],
+ "0",
+ true,
+ true,
+ ],
[
"standalone entrypoint",
[join(packageRoot, "src", "server", "index.ts")],
@@ -81,10 +89,14 @@ for (const [name, args, port, customEmbeddings] of [
env: {
...process.env,
CODEX_SECURITY_STATE_DIR: state,
- HOST: "127.0.0.1",
+ HOST: blankEnvironment ? " " : "127.0.0.1",
PORT: port,
- OPENAI_API_KEY: customEmbeddings ? "synthetic-key" : "",
- CODEX_API_KEY: "",
+ OPENAI_API_KEY: blankEnvironment
+ ? " "
+ : customEmbeddings
+ ? "synthetic-key"
+ : "",
+ CODEX_API_KEY: blankEnvironment ? "synthetic-key" : "",
CODEX_SECURITY_EMBEDDINGS_URL: embeddingsUrl,
},
stdio: ["ignore", "pipe", "pipe"],
@@ -221,3 +233,38 @@ test("serve rejects missing or invalid ports", async () => {
expect(stderr.text()).toContain("port");
}
});
+
+test("blank standalone settings use documented defaults", async () => {
+ if (
+ runTestInSubprocess(
+ import.meta.path,
+ "blank standalone settings use documented defaults",
+ )
+ )
+ return;
+ const selected: Array<{ host: string; port: number }> = [];
+ mock.module("../src/server/server.js", () => ({
+ startFindingsServer: async (options: { host: string; port: number }) => {
+ selected.push({ host: options.host, port: options.port });
+ return { address: () => null };
+ },
+ }));
+ const { serveFindings } = await import("../src/server/serve.js");
+ const before = {
+ SIGINT: process.listeners("SIGINT"),
+ SIGTERM: process.listeners("SIGTERM"),
+ };
+ try {
+ for (const value of [undefined, "", " "])
+ await serveFindings({ HOST: value, PORT: value }, { write: () => true });
+ expect(selected).toEqual(
+ Array.from({ length: 3 }, () => ({ host: "127.0.0.1", port: 3000 })),
+ );
+ } finally {
+ for (const signal of ["SIGINT", "SIGTERM"] as const)
+ for (const listener of process.listeners(signal)) {
+ if (!before[signal].includes(listener))
+ process.removeListener(signal, listener);
+ }
+ }
+});
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index 6ea3e743b..d21a61552 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -2326,7 +2326,12 @@ describe("CLI", () => {
await runCapturedCli(
main,
["scan", ".", ...options],
- dependencies({ onConfig: (value) => (config = value) }),
+ dependencies({
+ environment: {
+ [providerConfig.env_key]: "synthetic-provider-key",
+ },
+ onConfig: (value) => (config = value),
+ }),
),
).toBe(0);
expect(config?.codexOverrides).toEqual({
diff --git a/sdk/typescript/tests-ts/codex-review.test.ts b/sdk/typescript/tests-ts/codex-review.test.ts
index 8e7c1b321..90d3a592e 100644
--- a/sdk/typescript/tests-ts/codex-review.test.ts
+++ b/sdk/typescript/tests-ts/codex-review.test.ts
@@ -8,6 +8,7 @@ import { parse, stringify } from "smol-toml";
import { fileURLToPath } from "node:url";
import { expect, mock, test } from "bun:test";
import { CodexReviewRunner } from "../src/deduplication/codex-review.js";
+import { DEFAULT_CODEX_CONFIG, type JsonObject } from "../src/config.js";
import { CheckpointedReviewRunner } from "../src/deduplication/checkpointed-review.js";
import { FindingWorkflow } from "../src/finding-workflow.js";
import { checkpointWorkbench } from "./support/workbench-fakes.js";
@@ -87,18 +88,28 @@ const transportCases: {
extraEnvironment?: Record<string, string>;
windowsOnly?: boolean;
commandAuth?: "direct" | "ambient";
+ windowsConfig?: JsonObject;
+ expectedWindowsSandbox?: string;
}[] = [
{
scenario: "correction",
name: "command auth without an API key",
commandAuth: "direct",
+ windowsConfig: { features: { elevated_windows_sandbox: false } },
+ expectedWindowsSandbox: "unelevated",
},
{
scenario: "correction",
name: "command auth with ambient API key and relative home",
commandAuth: "ambient",
+ windowsConfig: { windows: { sandbox: "unelevated" } },
+ expectedWindowsSandbox: "unelevated",
+ },
+ {
+ scenario: "retry-correction",
+ windowsConfig: { features: { elevated_windows_sandbox: true } },
+ expectedWindowsSandbox: "elevated",
},
- { scenario: "retry-correction" },
{ scenario: "text-only-correction" },
{ scenario: "cancel-continuation" },
{ scenario: "accepted-no-replay" },
@@ -145,6 +156,8 @@ for (const {
extraEnvironment,
windowsOnly = false,
commandAuth,
+ windowsConfig,
+ expectedWindowsSandbox,
} of transportCases) {
const runCase = test.skipIf(windowsOnly && process.platform !== "win32");
runCase(`Codex review transport: ${name}`, async () => {
@@ -169,6 +182,7 @@ for (const {
};
const configuration = stringify({
mcp_servers: { synthetic: { command: "synthetic-unused-command" } },
+ ...windowsConfig,
...(commandAuth
? {
model_provider: "synthetic.provider",
@@ -422,6 +436,13 @@ for (const {
expect(args).toContain('cli_auth_credentials_store="ephemeral"');
}
expect(args.join(" ")).not.toContain("synthetic-review-key");
+ expect(
+ parse(args.find((value) => value.startsWith("windows="))!)["windows"],
+ ).toEqual({
+ sandbox:
+ expectedWindowsSandbox ??
+ (DEFAULT_CODEX_CONFIG["windows"] as { sandbox: string }).sandbox,
+ });
const permissions = args.find((argument) =>
argument.startsWith("permissions.codex_security_review="),
);
diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.ts
index 597b689b1..62be16cab 100644
--- a/sdk/typescript/tests-ts/component-scan.test.ts
+++ b/sdk/typescript/tests-ts/component-scan.test.ts
@@ -1442,6 +1442,37 @@ test.each(["auto", "chatgpt", "api-key"] as const)(
},
);
+test.each([
+ ["openrouter", "api-key"],
+ ["openrouter", "chatgpt"],
+ ["fireworks", "api-key"],
+ ["fireworks", "chatgpt"],
+] as const)(
+ "component planning honors command authentication for %s with %s selection",
+ async (provider, auth) => {
+ const paths = await fixture();
+ const plan = mock(async () => ({ components }));
+ const result = await scan(paths, {
+ components: undefined,
+ auto: true,
+ planOnly: true,
+ environment: {},
+ config: {
+ codexOverrides: {
+ model_provider: provider,
+ model_providers: {
+ [provider]: { auth: { command: "synthetic-auth-helper" } },
+ },
+ },
+ },
+ scanOptions: { auth },
+ planComponents: plan,
+ });
+ expect(result.total).toBe(components.length);
+ expect(plan).toHaveBeenCalledTimes(1);
+ },
+);
+
test("CLI requires an explicitly selected API key before automatic planning", async () => {
const paths = await fixture();
const planComponentsMock = mock(resolving({ components }));
diff --git a/sdk/typescript/tests-ts/config.test.ts b/sdk/typescript/tests-ts/config.test.ts
index 7d8d1cb58..901687210 100644
--- a/sdk/typescript/tests-ts/config.test.ts
+++ b/sdk/typescript/tests-ts/config.test.ts
@@ -5,6 +5,7 @@ import { parse } from "smol-toml";
import { scanRuntimeCodexConfig } from "../src/api.js";
import {
type JsonObject,
+ inlineToml,
resolveCodexProfile,
scanModelConfiguration,
scanModelProvider,
@@ -30,6 +31,16 @@ const { temporaryDirectory, cleanup } = createApiTestFixtures(
afterEach(cleanup);
+test("inline Codex overrides reject null values instead of emitting invalid TOML", () => {
+ for (const value of [null, { args: null }, { args: ["fixture", null] }]) {
+ expect(() => inlineToml(value)).toThrow(ConfigurationError);
+ }
+ const provider = { fixture: { args: ["fixture", 4], enabled: true } };
+ expect(parse(`model_providers = ${inlineToml(provider)}`)).toEqual({
+ model_providers: provider,
+ });
+});
+
function runPinnedCodex(
codexHome: string,
arguments_: readonly string[],
@@ -368,7 +379,7 @@ describe("Codex configuration", () => {
});
expect(merged).toMatchObject({
- windows: { sandbox: "unelevated" },
+ windows: { sandbox: "elevated" },
profiles: {
elevated: {
features: { elevated_windows_sandbox: true },
@@ -443,7 +454,7 @@ describe("Codex configuration", () => {
const merged = await mergedCodexConfig({});
expect(scanRuntimeCodexConfig(merged)).toMatchObject({
- windows: { sandbox: "unelevated" },
+ windows: { sandbox: "elevated" },
default_permissions: "codex_security_scan",
permissions: {
codex_security_scan: {
@@ -635,9 +646,12 @@ describe("Codex configuration", () => {
details,
)) ||
(process.platform === "win32" &&
- details.includes(
+ (details.includes(
"Restricted read-only access requires the elevated Windows sandbox backend",
- ))
+ ) ||
+ details.includes(
+ "elevated Windows sandbox requires effective `:root` read access",
+ )))
) {
expect(runPinnedCodex(codexHome, ["features", "list"]).exitCode).toBe(
0,
@@ -691,7 +705,7 @@ describe("Codex configuration", () => {
await writeCodexConfig(path, await mergedCodexConfig({}));
expect(parse(await readFile(path, "utf8"))).toMatchObject({
- windows: { sandbox: "unelevated" },
+ windows: { sandbox: "elevated" },
});
const result = runPinnedCodex(root, ["features", "list"]);
@@ -778,7 +792,7 @@ describe("Codex configuration", () => {
model_reasoning_summary: "detailed",
show_raw_agent_reasoning: true,
windows: {
- sandbox: "unelevated",
+ sandbox: "elevated",
},
});
});
diff --git a/sdk/typescript/tests-ts/custom-validation.test.ts b/sdk/typescript/tests-ts/custom-validation.test.ts
index c6b3d4078..eec3d5cfc 100644
--- a/sdk/typescript/tests-ts/custom-validation.test.ts
+++ b/sdk/typescript/tests-ts/custom-validation.test.ts
@@ -502,6 +502,12 @@ describe("custom validation", () => {
const commands: string[] = [];
const activities: ScanActivity[] = [];
const validationActivity = "Synthetic validation activity.";
+ const profileDisabledTools =
+ scenario === "standard"
+ ? []
+ : diff
+ ? ["profile_disabled_tool"]
+ : undefined;
const workbench = (args: readonly string[], input?: string) =>
runWorkbench(
{
@@ -516,7 +522,22 @@ describe("custom validation", () => {
input,
);
const client = new TestClient(
- {},
+ profileDisabledTools === undefined
+ ? {}
+ : {
+ codexOverrides: {
+ profile: "synthetic.validation",
+ profiles: {
+ "synthetic.validation": {
+ mcp_servers: {
+ "codex-security": {
+ disabled_tools: profileDisabledTools,
+ },
+ },
+ },
+ },
+ },
+ },
{
environment: { CODEX_SECURITY_STATE_DIR: stateDir },
prepareRuntime: async () => {
@@ -534,7 +555,13 @@ describe("custom validation", () => {
expect(options.config?.["mcp_servers"]).toMatchObject({
"codex-security": {
disabled_tools: expect.arrayContaining([
+ "start_codex_security_standard_scan",
+ "start_codex_security_prompt_only_scan",
+ "start_codex_security_deep_scan",
"complete_codex_security_scan",
+ "record_codex_security_candidate_validations",
+ "record_candidate_attack_paths",
+ ...(profileDisabledTools ?? []),
]),
},
});
diff --git a/sdk/typescript/tests-ts/deep-scan-parent-denials.test.ts b/sdk/typescript/tests-ts/deep-scan-parent-denials.test.ts
index 8b0ad149b..26840ce85 100644
--- a/sdk/typescript/tests-ts/deep-scan-parent-denials.test.ts
+++ b/sdk/typescript/tests-ts/deep-scan-parent-denials.test.ts
@@ -4,6 +4,7 @@ import * as util from "node:util";
import { expect, test } from "bun:test";
import { parse } from "smol-toml";
import { loadBundledRuntime } from "./plugin-root.js";
+import { profileConfigOverrides } from "../../../plugins/codex-security/scripts/codex_profile.mjs";
type Sandbox = { filesystemDenies: string[]; globScanMaxDepth?: number };
@@ -35,26 +36,20 @@ async function bundledPolicy() {
),
Error,
) as (metadata: unknown) => Sandbox;
- const serializer = [
- "workerPermissionProfile",
- "workerPermissionProfileConfigOverrides",
- "tomlInlineValue",
- "tomlKey",
- "tomlString",
- ]
- .map((name) => {
- const definition = new RegExp(
- `function ${name}\\([^\\n]*\\) \\{[\\s\\S]*?\\n\\}`,
- "u",
- ).exec(runtime)?.[0];
- if (!definition) throw new Error(`Missing bundled function: ${name}`);
- return definition;
- })
- .join("\n");
- const overrides = new Function(
- "DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID",
- `${serializer}\nreturn sandbox => workerPermissionProfileConfigOverrides(workerPermissionProfile(sandbox));`,
- )("codex_security_deep_scan_worker") as (sandbox: Sandbox) => string[];
+ const profileSource =
+ /function workerPermissionProfile\([^\n]*\) \{[\s\S]*?\n\}/u.exec(
+ runtime,
+ )?.[0];
+ expect(profileSource).toBeDefined();
+ const profile = new Function(
+ `${profileSource}\nreturn workerPermissionProfile;`,
+ ) as () => (sandbox: Sandbox) => Record<string, unknown>;
+ const workerProfile = profile();
+ const overrides = (sandbox: Sandbox) =>
+ profileConfigOverrides({
+ default_permissions: "codex_security_deep_scan_worker",
+ "permissions.codex_security_deep_scan_worker": workerProfile(sandbox),
+ });
return { resolve, overrides };
}
diff --git a/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts b/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts
index 9ec71e796..9425d263d 100644
--- a/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts
+++ b/sdk/typescript/tests-ts/deep-scan-worker-shutdown.test.ts
@@ -1,5 +1,6 @@
import { expect, test } from "bun:test";
import { loadBundledRuntime } from "./plugin-root.js";
+import { profileConfigOverrides } from "../../../plugins/codex-security/scripts/codex_profile.mjs";
type WorkerEvent =
| { type: "thread.started"; thread_id: string }
@@ -52,7 +53,8 @@ async function bundledWorkerExecutor(
"Codex",
fileSystemImport!,
"workerPermissionProfile",
- "workerPermissionProfileConfigOverrides",
+ "profileConfigOverrides",
+ "DEEP_SCAN_WORKER_PERMISSION_PROFILE_ID",
"snapshotWorkerEnvironment",
"workerRuntimeSettings",
"environmentVariable",
@@ -68,9 +70,10 @@ async function bundledWorkerExecutor(
FakeCodex,
{ promises: { readFile: async () => "fixture worker prompt" } },
() => ({}),
- () => [],
- async () => ({}),
+ profileConfigOverrides,
+ "codex_security_deep_scan_worker",
async () => ({}),
+ async () => ({ config: {} }),
() => undefined,
preflight,
() => undefined,
diff --git a/sdk/typescript/tests-ts/finding-workflow.test.ts b/sdk/typescript/tests-ts/finding-workflow.test.ts
index 43ab8b4d8..7d417f982 100644
--- a/sdk/typescript/tests-ts/finding-workflow.test.ts
+++ b/sdk/typescript/tests-ts/finding-workflow.test.ts
@@ -16,6 +16,7 @@ import {
scriptedWorkbench,
} from "./support/workbench-fakes.js";
import { workflowFixture } from "./support/workflow-fixture.js";
+import { runCommand } from "./support/shell.js";
const distinct: DuplicateDecision = {
decision: "DISTINCT",
@@ -245,3 +246,50 @@ test("normalizes a workflow destination without storing URL credentials", () =>
"http://synthetic.test/",
);
});
+
+test("blank home digests follow effective Codex configuration", async () => {
+ await using fixture = await workflowFixture();
+ const home = join(fixture.root, "home");
+ await mkdir(join(home, ".codex"), { recursive: true });
+ const moduleUrl = new URL(
+ "../src/deduplication/checkpointed-review.ts",
+ import.meta.url,
+ ).href;
+ const result = await runCommand(
+ process.execPath,
+ [
+ "-e",
+ `
+ import {writeFile} from "node:fs/promises";
+ import {join} from "node:path";
+ const {reviewSettingsDigest} = await import(${JSON.stringify(moduleUrl)});
+ const env = {...process.env, CODEX_HOME: ""};
+ const effective = join(process.env.HOME, ".codex", "config.toml");
+ await writeFile(effective, 'model="first"\\n');
+ const initial = await reviewSettingsDigest(env);
+ await writeFile(effective, 'model="second"\\n');
+ const changed = await reviewSettingsDigest(env);
+ await writeFile("config.toml", 'model="irrelevant"\\n');
+ const unrelated = await reviewSettingsDigest(env);
+ console.log(JSON.stringify({changed: initial !== changed, unrelated: changed === unrelated,
+ whitespace: changed === await reviewSettingsDigest({...env, CODEX_HOME: " "})}));
+ `,
+ ],
+ {
+ cwd: fixture.root,
+ timeout: 30_000,
+ env: {
+ ...process.env,
+ HOME: home,
+ USERPROFILE: home,
+ CODEX_SECURITY_STATE_DIR: fixture.environment.CODEX_SECURITY_STATE_DIR,
+ },
+ },
+ );
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout)).toEqual({
+ changed: true,
+ unrelated: true,
+ whitespace: true,
+ });
+});
diff --git a/sdk/typescript/tests-ts/knowledge-base.test.ts b/sdk/typescript/tests-ts/knowledge-base.test.ts
index f824f3087..68de78b6b 100644
--- a/sdk/typescript/tests-ts/knowledge-base.test.ts
+++ b/sdk/typescript/tests-ts/knowledge-base.test.ts
@@ -1,3 +1,5 @@
+import { spawnSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
import {
chmod,
mkdir,
@@ -62,6 +64,177 @@ function pdf(text: string): Uint8Array {
}
describe("scan knowledge bases", () => {
+ test.each(["win32", "darwin", "linux"])(
+ "matches case-variant Git metadata using %s platform and filesystem rules",
+ async (platform) => {
+ const root = await temporaryDirectory();
+ await mkdir(join(root, ".GIT"));
+ await writeFile(join(root, ".GIT", "config"), "Synthetic metadata");
+ await writeFile(join(root, "guide.md"), "Synthetic guide");
+ const aliasesGit = await filesystem.lstat(join(root, ".git")).then(
+ () => true,
+ () => false,
+ );
+ const result = spawnSync(
+ process.execPath,
+ [
+ "-e",
+ `
+ Object.defineProperty(process, "platform", { value: process.argv[1] });
+ const { prepareKnowledgeBase } = await import(process.argv[2]);
+ const { readdir, readFile } = await import("node:fs/promises");
+ const { join } = await import("node:path");
+ const prepared = await prepareKnowledgeBase([process.argv[3]]);
+ try {
+ console.log(JSON.stringify(await Promise.all((await readdir(prepared.path)).map(name => readFile(join(prepared.path, name), "utf8")))));
+ } finally { await prepared.cleanup(); }
+ `,
+ platform,
+ fileURLToPath(new URL("../src/knowledge-base.ts", import.meta.url)),
+ root,
+ ],
+ { encoding: "utf8" },
+ );
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout).sort()).toEqual(
+ platform === "win32" || aliasesGit
+ ? ["Synthetic guide"]
+ : ["Synthetic guide", "Synthetic metadata"],
+ );
+ },
+ );
+
+ test.each([
+ [".git", "directory"],
+ [".GIT", "directory"],
+ [".GIT", "directory link"],
+ [".GIT", "Git file"],
+ ] as const)(
+ "directory knowledge bases handle %s metadata with %s while direct files remain explicit",
+ async (metadataName, metadataKind) => {
+ const linked = metadataKind === "directory link";
+ const gitFile = metadataKind === "Git file";
+ const root = await temporaryDirectory();
+ if (gitFile) {
+ const template = await temporaryDirectory();
+ const initialized = spawnSync(
+ "git",
+ [
+ "init",
+ "--quiet",
+ `--template=${template}`,
+ "--initial-branch=synthetic",
+ root,
+ ],
+ { encoding: "utf8" },
+ );
+ expect(initialized.status, initialized.stderr).toBe(0);
+ await filesystem.rename(join(root, ".git"), join(root, ".GIT"));
+ const aliasesGit = await filesystem.lstat(join(root, ".git")).then(
+ () => true,
+ () => false,
+ );
+ // Case-insensitive filesystems cannot represent this separate Git file.
+ if (!aliasesGit) await writeFile(join(root, ".git"), "gitdir: .GIT\n");
+ const recognized = spawnSync(
+ "git",
+ ["-C", root, "rev-parse", "--absolute-git-dir"],
+ { encoding: "utf8" },
+ );
+ expect(recognized.status, recognized.stderr).toBe(0);
+ expect(await filesystem.realpath(recognized.stdout.trim())).toBe(
+ await filesystem.realpath(join(root, ".GIT")),
+ );
+ } else {
+ await mkdir(join(root, metadataName));
+ }
+ const metadata = join(root, metadataName, "config");
+ await writeFile(
+ metadata,
+ (gitFile ? await readFile(metadata, "utf8") : "") +
+ "[http]\nextraheader = synthetic-authorization\n",
+ );
+ await writeFile(
+ join(root, "guide.md"),
+ "Documented application behavior.",
+ );
+ const aliasesGit = await filesystem.lstat(join(root, ".git")).then(
+ () => true,
+ () => false,
+ );
+ if (metadataName !== ".git" && !aliasesGit) {
+ if (linked) {
+ await symlink(
+ join(root, metadataName),
+ join(root, ".git"),
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ } else {
+ await mkdir(join(root, ".git"));
+ await writeFile(
+ join(root, ".git", "config"),
+ "Separate Git metadata.",
+ );
+ }
+ }
+ const directory = await prepareKnowledgeBase([root]);
+ temporaryDirectories.track(directory.path);
+ expect((await extractedDocuments(directory.path)).sort()).toEqual(
+ [
+ "Documented application behavior.",
+ ...(process.platform !== "win32" && !aliasesGit && !linked
+ ? [await readFile(metadata, "utf8")]
+ : []),
+ ].sort(),
+ );
+ const explicit = await prepareKnowledgeBase([metadata]);
+ temporaryDirectories.track(explicit.path);
+ expect(await extractedDocuments(explicit.path)).toEqual([
+ await readFile(metadata, "utf8"),
+ ]);
+ },
+ );
+
+ testPosix(
+ "omits case-variant metadata aliases on a case-insensitive filesystem",
+ async () => {
+ const root = await temporaryDirectory();
+ const preservedGit = join(root, ".GIT");
+ await mkdir(preservedGit);
+ const metadata = join(preservedGit, "config");
+ await writeFile(
+ metadata,
+ "[http]\nextraheader = synthetic-authorization\n",
+ );
+ await writeFile(
+ join(root, "guide.md"),
+ "Documented application behavior.",
+ );
+ const originalStat = filesystem.stat;
+ const aliasSpy = spyOn(filesystem, "stat").mockImplementation(
+ async (path, options?) =>
+ Reflect.apply(originalStat, filesystem, [
+ path === join(root, ".git") ? preservedGit : path,
+ options,
+ ]),
+ );
+ try {
+ const directory = await prepareKnowledgeBase([root]);
+ temporaryDirectories.track(directory.path);
+ expect(await extractedDocuments(directory.path)).toEqual([
+ "Documented application behavior.",
+ ]);
+ const explicit = await prepareKnowledgeBase([metadata]);
+ temporaryDirectories.track(explicit.path);
+ expect(await extractedDocuments(explicit.path)).toEqual([
+ await readFile(metadata, "utf8"),
+ ]);
+ } finally {
+ aliasSpy.mockRestore();
+ }
+ },
+ );
+
test("prepares nested supported documents and retains requested source roots", async () => {
const root = await temporaryDirectory();
const nested = join(root, "architecture", "threats");
@@ -70,8 +243,8 @@ describe("scan knowledge bases", () => {
await writeFile(scope, "Ignore local debug endpoints.");
await writeFile(join(nested, "deployment.MARKDOWN"), "Public API gateway.");
await writeFile(join(nested, "notes.txt"), "Prioritize SSRF.");
- await mkdir(join(root, ".GiT"));
- await writeFile(join(root, ".GiT", "config"), "Repository metadata.");
+ await mkdir(join(root, ".git"));
+ await writeFile(join(root, ".git", "config"), "Repository metadata.");
await writeFile(join(nested, ".git"), "gitdir: /synthetic/metadata");
await writeFile(join(root, "ignored.bin"), new Uint8Array([0, 1, 2]));
await writeFile(join(root, "invalid-utf8.bin"), new Uint8Array([0xff]));
diff --git a/sdk/typescript/tests-ts/provider-profile.test.ts b/sdk/typescript/tests-ts/provider-profile.test.ts
new file mode 100644
index 000000000..4f1f5c4f4
--- /dev/null
+++ b/sdk/typescript/tests-ts/provider-profile.test.ts
@@ -0,0 +1,425 @@
+import { existsSync } from "node:fs";
+import {
+ chmod,
+ mkdir,
+ readFile,
+ readdir,
+ stat,
+ writeFile,
+} from "node:fs/promises";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { afterEach, expect, test } from "bun:test";
+import { parse } from "smol-toml";
+import {
+ createProviderProfile,
+ providerPreflightCommand,
+} from "../src/provider-profile.js";
+import { CodexLoginHandle } from "../src/auth.js";
+import {
+ bundledPluginRoot,
+ resolveCodexCommand,
+ runCodexCommand,
+} from "../src/runtime.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+
+const { temporaryDirectory, cleanup } = createApiTestFixtures(
+ "codex-security-provider-profile-",
+);
+afterEach(cleanup);
+
+const provider = {
+ name: "Synthetic",
+ wire_api: "responses",
+ http_headers: { "X-Synthetic-Key": "synthetic-provider-secret" },
+};
+const config = {
+ model_provider: "synthetic.gateway",
+ model_providers: { "synthetic.gateway": provider },
+};
+
+const startupProvider = {
+ ...provider,
+ requires_openai_auth: true,
+ base_url: "https://provider.example.test/v1",
+ env_key: "SYNTHETIC_API_KEY",
+ auth: {
+ command: "synthetic-auth",
+ args: ["synthetic-command-secret"],
+ },
+};
+const startupProviders = { "synthetic.gateway": startupProvider };
+
+test.each([
+ [
+ "explicit custom",
+ { ...config, model_providers: startupProviders },
+ "synthetic.gateway",
+ true,
+ ],
+ [
+ "selected profile",
+ {
+ model_provider: "openai",
+ model_providers: startupProviders,
+ profile: "cloud.production",
+ profiles: { "cloud.production": { model_provider: "synthetic.gateway" } },
+ },
+ "synthetic.gateway",
+ true,
+ ],
+ [
+ "explicit OpenAI without definitions",
+ { model_provider: "openai" },
+ "openai",
+ false,
+ ],
+ [
+ "explicit OpenAI with empty definitions",
+ { model_provider: "openai", model_providers: {} },
+ "openai",
+ false,
+ ],
+ ["inherited provider", {}, undefined, false],
+ [
+ "inherited provider with metadata",
+ { model_providers: startupProviders },
+ undefined,
+ true,
+ ],
+ ["empty provider definitions", { model_providers: {} }, undefined, false],
+ ["explicit empty selection", { model_provider: "" }, "", false],
+] as const)(
+ "native startup preserves %s selection and private credentials",
+ async (_case, settings, selection, metadata) => {
+ const home = await temporaryDirectory();
+ const inherited = "synthetic.inherited";
+ const sharedConfig = `approval_policy = "never"\ncli_auth_credentials_store = "file"\nmodel_provider = "${inherited}"\n${selection === undefined ? `[model_providers."${inherited}"]\nname = "Synthetic inherited"\nwire_api = "responses"\nrequires_openai_auth = false\n` : ""}`;
+ await writeFile(join(home, "config.toml"), sharedConfig);
+ const script = join(home, "native startup.mjs");
+ await writeFile(
+ script,
+ `import { readFileSync } from "node:fs";
+ import { join } from "node:path";
+ console.log(JSON.stringify({
+ args: process.argv.slice(2),
+ home: process.env.CODEX_HOME,
+ config: readFileSync(join(process.env.CODEX_HOME, "config.toml"), "utf8"),
+ }));`,
+ );
+ const command = await providerPreflightCommand(
+ { command: process.execPath, args: [script] },
+ settings,
+ );
+ const environment = { ...process.env, CODEX_HOME: home };
+ const result = await runCodexCommand(
+ command,
+ ["plugin", "marketplace", "list"],
+ environment,
+ );
+ expect(result.success).toBe(true);
+ const observed = JSON.parse(result.stdout);
+ expect(observed.home).toBe(home);
+ expect(observed.config).toBe(sharedConfig);
+ const overrides = observed.args.slice(0, -3);
+ const decoded: Record<string, unknown> = {};
+ for (let index = 0; index < overrides.length; index += 2) {
+ expect(overrides[index]).toBe("-c");
+ Object.assign(decoded, parse(overrides[index + 1]));
+ }
+ expect(decoded).toEqual({
+ ...(selection === undefined ? {} : { model_provider: selection }),
+ ...(metadata
+ ? {
+ model_providers: {
+ "synthetic.gateway": {
+ name: "Synthetic",
+ wire_api: "responses",
+ requires_openai_auth: true,
+ },
+ },
+ }
+ : {}),
+ });
+ expect(observed.args.slice(-3)).toEqual(["plugin", "marketplace", "list"]);
+ for (const marker of [
+ "synthetic-provider-secret",
+ "synthetic-command-secret",
+ "SYNTHETIC_API_KEY",
+ "provider.example.test",
+ ]) {
+ expect(JSON.stringify(observed.args)).not.toContain(marker);
+ }
+ const login = new CodexLoginHandle(
+ command,
+ ["login"],
+ environment,
+ () => {},
+ );
+ const completed = await login.wait();
+ expect(completed.success).toBe(true);
+ expect(JSON.parse(completed.stdout)).toEqual({
+ ...observed,
+ args: [...overrides, "login"],
+ });
+
+ const prefix = [
+ "-c",
+ "features.api_key_model_discovery=false",
+ "-c",
+ "features.plugins=false",
+ ];
+ const native = await providerPreflightCommand(
+ { ...resolveCodexCommand({}), args: prefix },
+ settings,
+ );
+ expect(native.args?.slice(0, prefix.length)).toEqual(prefix);
+ const { readDeepScanRuntimeConfig } = await import(
+ pathToFileURL(
+ join(
+ await bundledPluginRoot(),
+ "mcp",
+ "permission-profile-preflight.mjs",
+ ),
+ ).href
+ );
+ const read = () =>
+ readDeepScanRuntimeConfig({
+ codexPath: native.command,
+ commandArgs: native.args,
+ cwd: home,
+ configOverrides: [],
+ env: {
+ PATH: process.env["PATH"] ?? "",
+ ...(process.env["SystemRoot"] === undefined
+ ? {}
+ : { SystemRoot: process.env["SystemRoot"] }),
+ ...(process.env["TMPDIR"] === undefined
+ ? {}
+ : { TMPDIR: process.env["TMPDIR"] }),
+ HOME: home,
+ CODEX_HOME: home,
+ },
+ signal: new AbortController().signal,
+ context: "helper",
+ });
+ if (selection === "") {
+ await expect(read()).rejects.toThrow("Model provider `` not found");
+ } else {
+ const effective = await read();
+ expect(effective.model_provider).toBe(selection ?? inherited);
+ }
+ expect(await readFile(join(home, "config.toml"), "utf8")).toBe(
+ sharedConfig,
+ );
+ },
+);
+
+test("private profiles retain providers for native required and inherited selection", async () => {
+ const home = await temporaryDirectory();
+ const definitions = {
+ "synthetic.selected": { name: "Synthetic selected", wire_api: "responses" },
+ "synthetic.required": { name: "Synthetic required", wire_api: "responses" },
+ "amazon-bedrock": {
+ aws: { region: "us-east-1" },
+ http_headers: { "X-Synthetic-Key": "synthetic-inherited-header" },
+ },
+ };
+ const profile = await createProviderProfile(home, {
+ model_provider: "synthetic.selected",
+ model_providers: definitions,
+ });
+ try {
+ for (const selection of ["synthetic.required", "amazon-bedrock"]) {
+ // Managed requirements can override the initial selection. Exercise the
+ // same native file lookup without writing platform-specific system policy.
+ const result = await runCodexCommand(
+ resolveCodexCommand({}),
+ [
+ "--profile",
+ profile.name,
+ "-c",
+ `model_provider=${JSON.stringify(selection)}`,
+ "mcp",
+ "list",
+ "--json",
+ ],
+ {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: home,
+ },
+ );
+ expect(result.success, result.stderr).toBe(true);
+ expect(JSON.parse(result.stdout)).toEqual([]);
+ }
+ expect(parse(await readFile(profile.path, "utf8"))).toEqual({
+ model_providers: definitions,
+ });
+ } finally {
+ await profile.cleanup();
+ }
+});
+
+async function inspectHome(home: string) {
+ const auth = join(home, "auth.json");
+ return {
+ files: (await readdir(home)).sort(),
+ auth: existsSync(auth) ? await readFile(auth, "utf8") : null,
+ };
+}
+
+test.each(["existing", "new"])(
+ "secures the %s Windows credential home before writing a provider profile",
+ async (kind) => {
+ const root = await temporaryDirectory();
+ const home = join(root, "credential home");
+ const auth = '{"api_key":"synthetic-existing-auth"}\n';
+ const originalConfig = 'model = "synthetic-model"\n';
+ if (kind === "existing") {
+ await mkdir(home);
+ await writeFile(join(home, "auth.json"), auth);
+ await writeFile(join(home, "config.toml"), originalConfig);
+ }
+ let secured = false;
+ const profile = await createProviderProfile(home, config, {
+ platform: "win32",
+ async secureWindowsHome(path) {
+ expect(path).toBe(home);
+ expect(await inspectHome(path)).toEqual({
+ files: kind === "existing" ? ["auth.json", "config.toml"] : [],
+ auth: kind === "existing" ? auth : null,
+ });
+ secured = true;
+ },
+ });
+ try {
+ expect(secured).toBe(true);
+ expect(profile.path).toBe(join(home, `${profile.name}.config.toml`));
+ expect(parse(await readFile(profile.path, "utf8"))).toEqual({
+ model_providers: { "synthetic.gateway": provider },
+ });
+ expect(await inspectHome(home)).toEqual({
+ files: [
+ ...(kind === "existing" ? ["auth.json", "config.toml"] : []),
+ `${profile.name}.config.toml`,
+ ].sort(),
+ auth: kind === "existing" ? auth : null,
+ });
+ if (kind === "existing") {
+ expect(await readFile(join(home, "config.toml"), "utf8")).toBe(
+ originalConfig,
+ );
+ }
+ } finally {
+ await profile.cleanup();
+ }
+ expect(
+ (await readdir(home)).some((name) => name.startsWith("codex_security_")),
+ ).toBe(false);
+ },
+);
+
+test.each(["rejected", "aborted"])(
+ "leaves no provider file when Windows credential protection is %s",
+ async (kind) => {
+ const root = await temporaryDirectory();
+ const home = join(root, "credential home");
+ const failure = new Error("synthetic ACL failure");
+ if (kind === "aborted") failure.name = "AbortError";
+ await expect(
+ createProviderProfile(home, config, {
+ platform: "win32",
+ async secureWindowsHome(path) {
+ expect((await inspectHome(path)).files).toEqual([]);
+ throw failure;
+ },
+ }),
+ ).rejects.toMatchObject({ cause: failure });
+ expect((await inspectHome(home)).files).toEqual([]);
+ },
+);
+
+(process.platform === "win32" ? test.skip : test)(
+ "keeps provider files private in an existing readable POSIX home",
+ async () => {
+ const home = await temporaryDirectory();
+ await chmod(home, 0o755);
+ const profile = await createProviderProfile(home, config);
+ try {
+ expect((await stat(home)).mode & 0o777).toBe(0o755);
+ expect((await stat(profile.path)).mode & 0o777).toBe(0o600);
+ expect(parse(await readFile(profile.path, "utf8"))).toEqual({
+ model_providers: { "synthetic.gateway": provider },
+ });
+ } finally {
+ await profile.cleanup();
+ }
+ },
+);
+
+test.each([
+ ["synthetic-tools", false],
+ ["synthetic.tools", false],
+ ["synthetic.tools", true],
+] as const)(
+ "native overrides disable inherited MCP server %s (private profile: %j)",
+ async (name, privateProfile) => {
+ const home = await temporaryDirectory();
+ const sharedConfig = `[mcp_servers.${JSON.stringify(name)}]\ncommand = "synthetic-never-launched"\nenabled = true\n`;
+ await writeFile(join(home, "config.toml"), sharedConfig);
+ const profile = privateProfile
+ ? await createProviderProfile(home, config)
+ : undefined;
+ const { profileConfigOverrides } = await import(
+ pathToFileURL(
+ join(await bundledPluginRoot(), "scripts", "codex_profile.mjs"),
+ ).href
+ );
+ const command = resolveCodexCommand({});
+ const environment = {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: home,
+ };
+ try {
+ const inherited = await runCodexCommand(
+ command,
+ ["mcp", "list", "--json"],
+ environment,
+ );
+ expect(inherited.success, inherited.stderr).toBe(true);
+ expect(JSON.parse(inherited.stdout)).toMatchObject([
+ { name, enabled: true },
+ ]);
+ const overrides = profileConfigOverrides({
+ features: { plugins: false },
+ mcp_servers: { [name]: { enabled: false } },
+ });
+ const result = await runCodexCommand(
+ command,
+ [
+ ...(profile ? ["--profile", profile.name] : []),
+ ...overrides.flatMap((value: string) => ["-c", value]),
+ "mcp",
+ "list",
+ "--json",
+ ],
+ environment,
+ );
+ expect(result.success, result.stderr).toBe(true);
+ expect(JSON.parse(result.stdout)).toMatchObject([
+ {
+ name,
+ enabled: false,
+ transport: { command: "synthetic-never-launched" },
+ },
+ ]);
+ expect(await readFile(join(home, "config.toml"), "utf8")).toBe(
+ sharedConfig,
+ );
+ } finally {
+ await profile?.cleanup();
+ }
+ },
+);
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index a6f68a5b1..9706bde4e 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -2,7 +2,7 @@ import { createApiTestFixtures } from "./support/temporary-directories.js";
import { parseJsonLines, jsonLines } from "./support/json.js";
import { execFile, spawnSync } from "node:child_process";
import * as childProcess from "node:child_process";
-import { EventEmitter } from "node:events";
+import { EventEmitter, once } from "node:events";
import { existsSync, renameSync, symlinkSync } from "node:fs";
import {
chmod,
@@ -36,6 +36,7 @@ import {
win32,
} from "node:path";
import { PassThrough } from "node:stream";
+import { createInterface } from "node:readline";
import { setImmediate as nextTurn } from "node:timers/promises";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
@@ -619,7 +620,7 @@ describe("plugin runtime preparation", () => {
}
});
- test("projects only the unchanged external payload from the source checkout", async () => {
+ test("preserves the external payload while routing the installed launcher", async () => {
const root = await temporaryDirectory();
const workspace = join(root, "workspace");
await mkdir(workspace);
@@ -674,10 +675,19 @@ describe("plugin runtime preparation", () => {
readFile(sourcePath),
readFile(projectedPath),
]);
- expect({
- path,
- unchanged: projectedContents.equals(sourceContents),
- }).toEqual({ path, unchanged: true });
+ if (path === ".mcp.json") {
+ const expected = JSON.parse(sourceContents.toString("utf8"));
+ expected.mcpServers["codex-security"].command =
+ "./scripts/launch_codex_security_mcp_sdk";
+ expect(JSON.parse(projectedContents.toString("utf8"))).toEqual(
+ expected,
+ );
+ } else {
+ expect({
+ path,
+ unchanged: projectedContents.equals(sourceContents),
+ }).toEqual({ path, unchanged: true });
+ }
}),
);
await expect(stat(join(projected, ".internal"))).rejects.toThrow();
@@ -865,6 +875,301 @@ describe("plugin runtime preparation", () => {
).toBeDefined();
});
+ test.each([
+ "shell",
+ "shell with root",
+ "node",
+ "node with root",
+ "direct node",
+ "direct node with root",
+ "direct node with flags",
+ "direct node unprefixed",
+ ])(
+ "keeps %s MCP roots isolated outside the credential home",
+ async (interpreter) => {
+ const root = await temporaryDirectory();
+ const selected = await plugin(root);
+ const second = join(root, "second plugin");
+ const home = join(root, "home");
+ const work = join(root, "work");
+ await mkdir(home, { mode: 0o700 });
+ await mkdir(work);
+ await mkdir(join(selected, "mcp"));
+ await writeFile(join(home, "config.toml"), "[features]\nplugins=true\n");
+ const directNode = interpreter.startsWith("direct node");
+ const declaredRoot = interpreter.endsWith("with root");
+ const nodeOptions =
+ interpreter === "direct node with flags"
+ ? ["--enable-source-maps"]
+ : [];
+ const nodeCommand = declaredRoot
+ ? (
+ await promisify(execFile)("node", ["-p", "process.execPath"], {
+ encoding: "utf8",
+ })
+ ).stdout.trim()
+ : process.platform === "win32"
+ ? "node.exe"
+ : "node";
+ const nodeEntry =
+ interpreter === "direct node unprefixed"
+ ? "mcp/server.mjs"
+ : "./mcp/server.mjs";
+ const argumentsAfterEntry = [
+ "--stdio",
+ "synthetic ! % & argument",
+ nodeEntry,
+ ];
+ const mcp = {
+ mcpServers: {
+ "codex-security": {
+ command: directNode
+ ? nodeCommand
+ : "./scripts/launch_codex_security_mcp",
+ args: directNode
+ ? [...nodeOptions, nodeEntry, ...argumentsAfterEntry]
+ : argumentsAfterEntry,
+ cwd: ".",
+ env_vars: [
+ "CODEX_HOME",
+ "CODEX_MCP_NODE_PATH",
+ ...(declaredRoot ? ["CODEX_SECURITY_PLUGIN_ROOT"] : []),
+ ],
+ startup_timeout_sec: 20,
+ },
+ },
+ };
+ await writeFile(join(selected, ".mcp.json"), JSON.stringify(mcp));
+ for (const launcher of [
+ "launch_codex_security_mcp",
+ "launch_codex_security_mcp.cmd",
+ ]) {
+ await copyFile(
+ join(PLUGIN_ROOT, "scripts", launcher),
+ join(selected, "scripts", launcher),
+ );
+ }
+ await chmod(
+ join(selected, "scripts", "launch_codex_security_mcp"),
+ 0o755,
+ );
+ const serverProgram = `
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { createInterface } from "node:readline";
+const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+${directNode ? "if (import.meta.main ?? true) {" : ""}
+for await (const line of createInterface({ input: process.stdin })) {
+ const request = JSON.parse(line);
+ if (request.id === undefined) continue;
+ const result = request.method === "initialize"
+ ? { protocolVersion: request.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "synthetic-legacy", version: "1" } }
+ : request.method === "tools/list"
+ ? { tools: [{ name: "probe", description: pluginRoot + "\\n" + JSON.stringify({ args: process.argv.slice(2), execArgv: process.execArgv, cwd: process.cwd(), entry: process.argv[1] }), inputSchema: { type: "object", properties: {} } }] }
+ : request.method === "resources/list" ? { resources: [] }
+ : request.method === "resources/templates/list" ? { resourceTemplates: [] }
+ : {};
+ console.log(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }));
+}
+${directNode ? "}" : ""}
+`;
+ await writeFile(join(selected, "mcp", "server.mjs"), serverProgram);
+ if (interpreter.startsWith("node")) {
+ await writeFile(
+ join(selected, "scripts", "launch_codex_security_mcp"),
+ `#!/usr/bin/env node\n${serverProgram}`,
+ );
+ }
+ const originals = new Map(
+ await Promise.all(
+ [
+ "scripts/launch_codex_security_mcp",
+ "scripts/launch_codex_security_mcp.cmd",
+ "mcp/server.mjs",
+ ].map(
+ async (path) =>
+ [path, await readFile(join(selected, path))] as const,
+ ),
+ ),
+ );
+ await cp(selected, second, { recursive: true });
+ if (declaredRoot) {
+ // Replace same-version installed code before either client starts MCP.
+ for (const path of [
+ "mcp/server.mjs",
+ ...(interpreter.startsWith("node")
+ ? ["scripts/launch_codex_security_mcp"]
+ : []),
+ ]) {
+ const file = join(second, path);
+ await writeFile(
+ file,
+ (await readFile(file, "utf8")).replace(
+ 'version: "1"',
+ 'version: "2"',
+ ),
+ );
+ }
+ }
+ const installedOriginals = new Map(
+ await Promise.all(
+ [...originals.keys()].map(
+ async (path) => [path, await readFile(join(second, path))] as const,
+ ),
+ ),
+ );
+ const environment = {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ PATHEXT: process.env["PATHEXT"],
+ CODEX_MCP_NODE_PATH: process.execPath,
+ };
+ const command = resolveCodexCommand({});
+ const installed = await bootstrapPlugin(home, selected, {
+ codexCommand: command,
+ environment,
+ });
+ expect(
+ (
+ await bootstrapPlugin(home, second, {
+ codexCommand: command,
+ environment,
+ })
+ ).installedRoot,
+ ).toBe(installed.installedRoot);
+ const installedMcp = JSON.parse(
+ await readFile(join(installed.installedRoot, ".mcp.json"), "utf8"),
+ );
+ expect(installedMcp.mcpServers["codex-security"]).toMatchObject({
+ cwd: mcp.mcpServers["codex-security"].cwd,
+ startup_timeout_sec:
+ mcp.mcpServers["codex-security"].startup_timeout_sec,
+ env_vars: declaredRoot
+ ? mcp.mcpServers["codex-security"].env_vars
+ : [
+ ...mcp.mcpServers["codex-security"].env_vars,
+ "CODEX_SECURITY_PLUGIN_ROOT",
+ ],
+ });
+ expect(
+ JSON.parse(await readFile(join(selected, ".mcp.json"), "utf8")),
+ ).toEqual(mcp);
+ for (const [path, contents] of originals) {
+ expect(await readFile(join(selected, path))).toEqual(contents);
+ if (
+ directNode ? path.startsWith("scripts/") : path.startsWith("mcp/")
+ ) {
+ expect(await readFile(join(installed.installedRoot, path))).toEqual(
+ installedOriginals.get(path)!,
+ );
+ }
+ }
+
+ const readRoot = async (pluginRoot?: string) => {
+ const child = childProcess.spawn(
+ executablePathForSpawn(command.command),
+ ["app-server", "--stdio"],
+ {
+ cwd: work,
+ env: {
+ ...environment,
+ CODEX_HOME: home,
+ ...(pluginRoot === undefined
+ ? {}
+ : { CODEX_SECURITY_PLUGIN_ROOT: pluginRoot }),
+ },
+ windowsHide: true,
+ },
+ );
+ const closed = once(child, "close");
+ const lines = createInterface({ input: child.stdout });
+ let stderr = "";
+ child.stderr.on("data", (chunk) => (stderr += chunk));
+ const send = (id: number, method: string, params: unknown) =>
+ child.stdin.write(JSON.stringify({ id, method, params }) + "\n");
+ try {
+ send(1, "initialize", {
+ clientInfo: { name: "synthetic_legacy_root", version: "1" },
+ capabilities: { experimentalApi: true },
+ });
+ for await (const line of lines) {
+ const response = JSON.parse(line);
+ if (response.error) throw new Error(JSON.stringify(response.error));
+ if (response.id === 1) {
+ child.stdin.write(
+ JSON.stringify({ method: "initialized", params: {} }) + "\n",
+ );
+ send(2, "mcpServerStatus/list", { detail: "full" });
+ }
+ if (response.id === 2) return response.result.data[0];
+ }
+ throw new Error(`Native MCP status did not finish: ${stderr}`);
+ } finally {
+ lines.close();
+ child.stdin.end();
+ child.kill();
+ await closed;
+ }
+ };
+ // Warm native session storage independently of this concurrent root check.
+ await readRoot(selected);
+ const servers = await Promise.all([readRoot(selected), readRoot(second)]);
+ const assertServer = async (
+ server: Awaited<ReturnType<typeof readRoot>>,
+ pluginRoot: string,
+ version: string,
+ ) => {
+ expect(structuredClone(server)).toMatchObject({
+ pluginId: "codex-security@codex-security-sdk",
+ serverInfo: { name: "synthetic-legacy", version },
+ tools: { probe: { description: expect.any(String) } },
+ });
+ expect(server.tools.probe.description).toStartWith(
+ await realpath(pluginRoot),
+ );
+ const details = JSON.parse(
+ server.tools.probe.description.match(/\n(\{.+\})/)![1],
+ );
+ expect(details.args).toEqual(argumentsAfterEntry);
+ expect(details.cwd).toBe(
+ process.platform === "win32" && !directNode
+ ? parse(await realpath(pluginRoot)).root
+ : await realpath(installed.installedRoot),
+ );
+ if (directNode) {
+ expect(details.execArgv).toEqual(nodeOptions);
+ expect(details.entry).toBe(
+ join(await realpath(pluginRoot), "mcp", "server.mjs"),
+ );
+ }
+ };
+ for (const [index, pluginRoot] of [selected, second].entries()) {
+ await assertServer(
+ servers[index],
+ pluginRoot,
+ index === 1 && declaredRoot ? "2" : "1",
+ );
+ }
+ await assertServer(
+ await readRoot(),
+ installed.installedRoot,
+ declaredRoot ? "2" : "1",
+ );
+ await rm(selected, { recursive: true });
+ await rm(second, { recursive: true });
+ await assertServer(
+ await readRoot(),
+ installed.installedRoot,
+ declaredRoot ? "2" : "1",
+ );
+ for (const [path, contents] of installedOriginals) {
+ expect(await readFile(join(installed.installedRoot, path))).toEqual(
+ contents,
+ );
+ }
+ },
+ );
+
test("copies configured plugins with more than 4,096 entries", async () => {
const root = await temporaryDirectory();
const source = await plugin(root);
@@ -1593,7 +1898,7 @@ describe("plugin runtime preparation", () => {
});
describe("installed plugin reuse", () => {
- async function fixture() {
+ async function fixture(legacy: false | "shell" | "node" = false) {
const root = await temporaryDirectory();
const selected = await plugin(root);
const home = join(root, "home");
@@ -1603,9 +1908,47 @@ describe("plugin runtime preparation", () => {
const record = join(marketplace, "installed-plugin.json");
const configuration = `[marketplaces.codex-security-sdk]\nsource_type = "local"\nsource = ${JSON.stringify(marketplace)}\n`;
const calls: string[][] = [];
+ if (legacy) {
+ await writeFile(
+ join(selected, ".mcp.json"),
+ JSON.stringify({
+ mcpServers: {
+ "codex-security": {
+ command:
+ legacy === "node"
+ ? "node"
+ : "./scripts/launch_codex_security_mcp",
+ args: [
+ ...(legacy === "node" ? ["./mcp/server.mjs"] : []),
+ "--stdio",
+ "synthetic argument",
+ ],
+ cwd: ".",
+ env_vars: ["CODEX_HOME"],
+ },
+ },
+ }),
+ );
+ if (legacy === "node") {
+ await mkdir(join(selected, "mcp"));
+ await writeFile(
+ join(selected, "mcp", "server.mjs"),
+ "// synthetic server\n",
+ );
+ }
+ for (const launcher of [
+ "launch_codex_security_mcp",
+ "launch_codex_security_mcp.cmd",
+ ]) {
+ await copyFile(
+ join(PLUGIN_ROOT, "scripts", launcher),
+ join(selected, "scripts", launcher),
+ );
+ }
+ }
await mkdir(home);
- const bootstrap = () =>
- bootstrapPlugin(home, selected, {
+ const bootstrap = (pluginRoot = selected) =>
+ bootstrapPlugin(home, pluginRoot, {
codexCommand: { command: "/codex" },
runCodex: async (_command, args) => {
calls.push([...args]);
@@ -1629,6 +1972,118 @@ describe("plugin runtime preparation", () => {
return { selected, home, staged, installed, record, calls, bootstrap };
}
+ test("reuses root-independent legacy launchers and refreshes source changes", async () => {
+ const { selected, staged, installed, calls, bootstrap } =
+ await fixture("shell");
+ const second = join(dirname(selected), "second plugin");
+ await cp(selected, second, { recursive: true });
+ expect((await bootstrap(second)).installedRoot).toBe(installed);
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(1);
+ const mcp = JSON.parse(await readFile(join(staged, ".mcp.json"), "utf8"));
+ expect(mcp.mcpServers["codex-security"]).toEqual({
+ command: "./scripts/launch_codex_security_mcp_sdk",
+ args: ["--stdio", "synthetic argument"],
+ cwd: ".",
+ env_vars: ["CODEX_HOME", "CODEX_SECURITY_PLUGIN_ROOT"],
+ });
+ expect(
+ (await stat(join(staged, "scripts", "launch_codex_security_mcp")))
+ .mode & 0o111,
+ ).toBe(
+ (await stat(join(selected, "scripts", "launch_codex_security_mcp")))
+ .mode & 0o111,
+ );
+ let installs = 1;
+ for (const cache of [staged, installed]) {
+ for (const name of [
+ "launch_codex_security_mcp_sdk",
+ "launch_codex_security_mcp_sdk.cmd",
+ ]) {
+ const shim = join(cache, "scripts", name);
+ const contents = await readFile(shim);
+ await writeFile(shim, "synthetic changed shim");
+ await bootstrap();
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(
+ ++installs,
+ );
+ expect(await readFile(shim)).toEqual(contents);
+ }
+ }
+ if (process.platform !== "win32") {
+ const shim = join(
+ installed,
+ "scripts",
+ "launch_codex_security_mcp_sdk",
+ );
+ await chmod(shim, 0o644);
+ await bootstrap();
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(
+ ++installs,
+ );
+ expect((await stat(shim)).mode & 0o111).toBe(0o111);
+ }
+ const script = join(selected, "scripts", "launch_codex_security_mcp.cmd");
+ await writeFile(
+ script,
+ Buffer.concat([
+ await readFile(script),
+ Buffer.from("\r\nrem synthetic changed source\r\n"),
+ ]),
+ );
+ await bootstrap();
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(
+ ++installs,
+ );
+ expect(
+ await readFile(
+ join(installed, "scripts", "launch_codex_security_mcp.cmd"),
+ "utf8",
+ ),
+ ).toEndWith("\r\nrem synthetic changed source\r\n");
+ const sourceMcp = JSON.parse(
+ await readFile(join(selected, ".mcp.json"), "utf8"),
+ );
+ sourceMcp.mcpServers["codex-security"].cwd = dirname(selected);
+ sourceMcp.mcpServers["codex-security"].args.push(
+ "literal ! % & diagnostic",
+ );
+ await writeFile(join(selected, ".mcp.json"), JSON.stringify(sourceMcp));
+ await bootstrap();
+ const changed = JSON.parse(
+ await readFile(join(installed, ".mcp.json"), "utf8"),
+ );
+ expect(changed.mcpServers["codex-security"].cwd).toBe(dirname(selected));
+ expect(changed.mcpServers["codex-security"].args).toEqual(
+ sourceMcp.mcpServers["codex-security"].args,
+ );
+ });
+
+ test("reuses the root-independent direct Node server across clients", async () => {
+ const { selected, staged, installed, calls, bootstrap } =
+ await fixture("node");
+ const second = join(dirname(selected), "second plugin");
+ await cp(selected, second, { recursive: true });
+ expect((await bootstrap(second)).installedRoot).toBe(installed);
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(1);
+ let installs = 1;
+ for (const cache of [staged, installed]) {
+ const shim = join(cache, "mcp", "codex_security_sdk_bridge.mjs");
+ const contents = await readFile(shim);
+ await rm(shim);
+ await bootstrap();
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(
+ ++installs,
+ );
+ expect(await readFile(shim)).toEqual(contents);
+ await writeFile(shim, "synthetic changed bridge");
+ await bootstrap();
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(
+ ++installs,
+ );
+ expect(await readFile(shim)).toEqual(contents);
+ }
+ });
+
test("preserves generated installed files during reuse", async () => {
const { installed, calls, bootstrap } = await fixture();
const generated = join(installed, "scripts", "__pycache__", "helper.pyc");
@@ -1686,6 +2141,8 @@ describe("plugin runtime preparation", () => {
"invalid record",
"disabled plugin",
"missing registration",
+ "missing marketplace manifest",
+ "incomplete marketplace manifest",
"extra staged file",
])("repairs %s before reusing the installation", async (damage) => {
const { home, staged, installed, record, calls, bootstrap } =
@@ -1723,13 +2180,43 @@ describe("plugin runtime preparation", () => {
case "missing registration":
await writeFile(join(home, "config.toml"), "");
break;
+ case "missing marketplace manifest":
+ await rm(
+ join(
+ home,
+ "sdk-marketplace",
+ ".agents",
+ "plugins",
+ "marketplace.json",
+ ),
+ );
+ break;
+ case "incomplete marketplace manifest":
+ await writeFile(
+ join(
+ home,
+ "sdk-marketplace",
+ ".agents",
+ "plugins",
+ "marketplace.json",
+ ),
+ "{",
+ );
+ break;
case "extra staged file":
await writeFile(join(staged, "stale.py"), "pass\n");
break;
}
+ const expectedInstalls =
+ damage === "missing marketplace manifest" ||
+ damage === "incomplete marketplace manifest"
+ ? 1
+ : 2;
await bootstrap();
- expect(calls.filter((args) => args[1] === "add")).toHaveLength(2);
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(
+ expectedInstalls,
+ );
expect(await readFile(helper, "utf8")).toBe("print('ok')\n");
expect(existsSync(join(staged, "stale.py"))).toBe(false);
expect(await readFile(manifest, "utf8")).toBe(expectedManifest);
@@ -1738,7 +2225,9 @@ describe("plugin runtime preparation", () => {
version: "1.2.3",
});
await bootstrap();
- expect(calls.filter((args) => args[1] === "add")).toHaveLength(2);
+ expect(calls.filter((args) => args[1] === "add")).toHaveLength(
+ expectedInstalls,
+ );
});
});
@@ -2129,7 +2618,7 @@ describe("plugin runtime preparation", () => {
};
const server = configuration.mcpServers["codex-security"];
- expect(server?.command).toBe("./scripts/launch_codex_security_mcp");
+ expect(server?.command).toBe("./scripts/launch_codex_security_mcp_sdk");
expect(server?.env_vars).toContain("CODEX_SAFETY_IDENTIFIER");
expect(server?.env_vars).toContain("CODEX_MANAGED_PACKAGE_ROOT");
expect(server?.env_vars).toContain("CODEX_MCP_NODE_PATH");
@@ -5694,6 +6183,48 @@ describe("runtime directories and plugin Python boundary", () => {
},
);
+ test("uses XDG_CACHE_HOME for Windows managed Python", async () => {
+ const root = await temporaryDirectory();
+ const cache = join(root, "Custom Cache");
+ const python = join(
+ cache,
+ "codex-runtimes",
+ "codex-primary-runtime",
+ "dependencies",
+ "python",
+ "python.exe",
+ );
+ await mkdir(dirname(python), { recursive: true });
+ await writeFile(python, "Synthetic executable");
+ const result = spawnSync(
+ process.execPath,
+ [
+ "-e",
+ `
+ import { mock } from "bun:test";
+ import * as childProcess from "node:child_process";
+ import { promisify } from "node:util";
+ const probe = () => {};
+ probe[promisify.custom] = async (command) => {
+ if (command !== process.argv[3]) throw new Error("Unexpected Python probe: " + command);
+ return { stdout: "codex-security-python-ok\\n", stderr: "" };
+ };
+ mock.module("node:child_process", () => ({ ...childProcess, execFile: probe }));
+ Object.defineProperty(process, "platform", { value: "win32" });
+ const { resolvePluginPython } = await import(process.argv[1]);
+ console.log(await resolvePluginPython({ environment: { PATH: "", XDG_CACHE_HOME: process.argv[2] }, homeDirectory: process.argv[4] }));
+ `,
+ fileURLToPath(new URL("../src/runtime.ts", import.meta.url)),
+ cache,
+ python,
+ join(root, "unused-home"),
+ ],
+ { encoding: "utf8" },
+ );
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout.trim()).toBe(python);
+ });
+
testPosix("uses configured, inherited, and managed Python", async () => {
const root = await temporaryDirectory();
const configured = join(root, "configured-python");
@@ -5737,6 +6268,20 @@ describe("runtime directories and plugin Python boundary", () => {
managedRuntimeRoots: [managedRoot],
}),
).toBe(managed);
+ const cacheDirectory = join(root, "custom-cache");
+ const cachedPython = join(
+ cacheDirectory,
+ "codex-runtimes/codex-primary-runtime/dependencies/python/bin/python3",
+ );
+ await mkdir(dirname(cachedPython), { recursive: true });
+ await copyFile(managed, cachedPython);
+ await chmod(cachedPython, 0o700);
+ expect(
+ await resolvePluginPython({
+ environment: { PATH: "", XDG_CACHE_HOME: cacheDirectory },
+ homeDirectory: join(root, "unused-home"),
+ }),
+ ).toBe(cachedPython);
expect(pluginExecutionEnvironment(managed, { TEST: "1" })).toEqual({
TEST: "1",
PYTHON: managed,
@@ -5808,7 +6353,7 @@ describe("runtime directories and plugin Python boundary", () => {
);
test.skipIf(process.platform !== "win32")(
- "discovers Python through the standard Windows py launcher",
+ "discovers Windows Python through the standard py launcher and a custom cache",
async () => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
@@ -5851,6 +6396,48 @@ describe("runtime directories and plugin Python boundary", () => {
protectedRoot: repository,
}),
).resolves.toBe(await realpath(launcher));
+
+ const cacheDirectory = join(root, "custom-cache");
+ const managedDirectory = join(
+ cacheDirectory,
+ "codex-runtimes",
+ "codex-primary-runtime",
+ "dependencies",
+ "python",
+ );
+ const managedPython = join(root, "python.exe");
+ await copyFile(installedPython, managedPython);
+ await mkdir(dirname(managedDirectory), { recursive: true });
+ await symlink(root, managedDirectory, "junction");
+ const environment = {
+ ...process.env,
+ PYTHON: "",
+ PATH: "",
+ XDG_CACHE_HOME: cacheDirectory,
+ };
+ const selected = await resolvePluginPython({
+ environment,
+ homeDirectory: join(root, "unused-home"),
+ protectedRoot: repository,
+ });
+ expect(selected).toBe(await realpath(managedPython));
+ const child = spawnSync(
+ selected,
+ [
+ "-I",
+ "-c",
+ "import os; print(os.environ['XDG_CACHE_HOME']); print(os.environ['PYTHON'])",
+ ],
+ {
+ env: pluginExecutionEnvironment(selected, environment),
+ encoding: "utf8",
+ },
+ );
+ expect(child.status).toBe(0);
+ expect(child.stdout.trim().split(/\r?\n/u)).toEqual([
+ cacheDirectory,
+ selected,
+ ]);
},
);
diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.ts
index 60f6fbbee..9d1aca6f6 100644
--- a/sdk/typescript/tests-ts/scan-comparison.test.ts
+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts
@@ -1,16 +1,22 @@
import { modelResponseText } from "./support/model-response-text.js";
import { once } from "node:events";
+import * as childProcess from "node:child_process";
+import { spawn } from "node:child_process";
+import { createInterface } from "node:readline";
+import { existsSync } from "node:fs";
import {
copyFile,
+ chmod,
mkdir,
- rm,
readFile,
+ readdir,
realpath,
symlink,
+ stat,
writeFile,
} from "node:fs/promises";
import { join, relative, win32 } from "node:path";
-import { parse, stringify } from "smol-toml";
+import { parse, stringify, type TomlTable } from "smol-toml";
import {
Codex,
type CodexOptions,
@@ -18,7 +24,14 @@ import {
type TurnOptions,
} from "@openai/codex-sdk";
import { afterEach, describe, expect, spyOn, test, mock } from "bun:test";
-import { resolveCodexCommand, runCodexCommand } from "../src/runtime.js";
+import * as runtimeCommands from "../src/runtime.js";
+import {
+ executablePathForSpawn,
+ resolveCodexCommand,
+ runCodexCommand,
+} from "../src/runtime.js";
+import { resolveCommandAuthConfig } from "../src/config.js";
+import * as providerProfiles from "../src/provider-profile.js";
import {
comparisonForScan,
comparisonEnvironment,
@@ -30,29 +43,17 @@ import {
type ScanComparisonOptions,
type ScanComparisonResult,
} from "../src/scan-comparison.js";
-import { temporaryDirectory as createTemporaryDirectory } from "./support/temporary-directories.js";
+import {
+ temporaryDirectory as createTemporaryDirectory,
+ removeTemporaryDirectory,
+} from "./support/temporary-directories.js";
import { fail } from "./support/errors.js";
const temporaryDirectories: string[] = [];
afterEach(async () => {
await Promise.all(
- temporaryDirectories.splice(0).map(async (path) => {
- // Bun 1.3.13 ignores fs.rm's retry options.
- for (let attempt = 0; ; attempt++) {
- try {
- await rm(path, { recursive: true, force: true });
- return;
- } catch (error) {
- if (
- (error as NodeJS.ErrnoException).code !== "EBUSY" ||
- attempt === 10
- )
- throw error;
- await Bun.sleep(100 * (attempt + 1));
- }
- }
- }),
+ temporaryDirectories.splice(0).map(removeTemporaryDirectory),
);
});
@@ -87,6 +88,41 @@ function fakeCodex(response: unknown) {
return { codex, calls };
}
+function observeCodexOptions(
+ codex: NonNullable<ScanComparisonOptions["codex"]>,
+ observe: (options: CodexOptions) => void,
+) {
+ return spyOn(Codex.prototype, "startThread").mockImplementation(function (
+ this: Codex,
+ options,
+ ) {
+ observe((this as unknown as { options: CodexOptions }).options);
+ return codex.startThread(options!) as ReturnType<Codex["startThread"]>;
+ });
+}
+
+function captureProfileClient() {
+ const profiles: {
+ name: string;
+ path: string;
+ config: TomlTable;
+ scanId: string | undefined;
+ }[] = [];
+ const spy = spyOn(providerProfiles, "createProfileCodex").mockImplementation(
+ async (options, name) => {
+ const path = join(options.env!["CODEX_HOME"]!, `${name}.config.toml`);
+ profiles.push({
+ name,
+ path,
+ config: parse(await readFile(path, "utf8")),
+ scanId: options.env?.["CODEX_SECURITY_SCAN_ID"],
+ });
+ return new Codex(options);
+ },
+ );
+ return { profiles, spy };
+}
+
describe("semantic scan comparison", () => {
test("uses comparison attribution for CLI comparison turns", async () => {
const { codex, calls } = fakeCodex({ matches: [], uncertain: [] });
@@ -98,6 +134,618 @@ describe("semantic scan comparison", () => {
expect(calls.threadOptions?.threadSource).toBe("security_scan_comparison");
});
+ test.each(["synthetic.gateway", "fireworks", "amazon-bedrock", "command"])(
+ "automatic matching retains the per-scan %s provider",
+ async (selection) => {
+ const home = await temporaryDirectory();
+ await writeFile(join(home, "config.toml"), "");
+ const providerName =
+ selection === "command" ? "synthetic.command" : selection;
+ const provider = {
+ ...(selection === "amazon-bedrock"
+ ? { aws: { region: "us-east-1" } }
+ : {
+ name: "Synthetic",
+ wire_api: "responses",
+ requires_openai_auth: false,
+ }),
+ base_url: "https://provider.example.test/v1",
+ http_headers: { "X-Synthetic-Secret": "synthetic-header-marker" },
+ ...(selection === "command"
+ ? {
+ auth: {
+ command: "synthetic-auth",
+ cwd: join(home, "helpers"),
+ env: { SYNTHETIC_AUTH_KEY: "synthetic-command-marker" },
+ },
+ }
+ : selection === "amazon-bedrock"
+ ? {}
+ : { env_key: "SYNTHETIC_PROVIDER_KEY" }),
+ };
+ const parentProfile =
+ selection === "fireworks"
+ ? await providerProfiles.createProviderProfile(home, {
+ model_provider: providerName,
+ model_providers: { [providerName]: provider },
+ })
+ : undefined;
+ const profileClient = captureProfileClient();
+ const startupCommands: Parameters<typeof runCodexCommand>[0][] = [];
+ const runNativeCommand = runtimeCommands.runCodexCommand;
+ const nativeCommand = spyOn(
+ runtimeCommands,
+ "runCodexCommand",
+ ).mockImplementation((...args) => {
+ if (args[1].includes("mcp")) startupCommands.push(args[0]);
+ return runNativeCommand(...args);
+ });
+ const before = finding("before");
+ const after = finding("after");
+ const { codex, calls } = fakeCodex({ matches: [], uncertain: [] });
+ let captured: CodexOptions | undefined;
+ let saved = false;
+ const startThread = observeCodexOptions(codex, (options) => {
+ captured = options;
+ });
+ try {
+ await matchCompletedScan({
+ scanId: "current",
+ repository: home,
+ previousFindings: [before],
+ falsePositives: [],
+ findings: [after],
+ ...(parentProfile === undefined
+ ? {}
+ : { nativeProfile: parentProfile }),
+ environment: {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: home,
+ CODEX_SECURITY_SCAN_ID: "current",
+ OPENAI_API_KEY: "synthetic-ambient-key",
+ SYNTHETIC_PROVIDER_KEY: "synthetic-provider-key",
+ },
+ config: {
+ codexOverrides: {
+ profile: "selected",
+ profiles: {
+ selected: {
+ model_provider: providerName,
+ model_providers: { [providerName]: provider },
+ },
+ },
+ model_providers: { [providerName]: provider },
+ default_permissions: "codex_security_scan",
+ permissions: {
+ codex_security_scan: { filesystem: { [home]: "write" } },
+ },
+ projects: { [home]: { trust_level: "trusted" } },
+ },
+ },
+ async workbench(args) {
+ if (args[0] === "list-unmatched-scan-pairs") {
+ return {
+ batches: [
+ {
+ afterScanId: "current",
+ afterFindings: [after],
+ beforeScans: [{ scanId: "prior", findings: [before] }],
+ },
+ ],
+ };
+ }
+ saved = args[0] === "save-scan-comparison";
+ return {};
+ },
+ });
+ expect(startThread).toHaveBeenCalledTimes(1);
+ expect(captured?.config).toMatchObject({
+ model_provider: providerName,
+ });
+ expect(profileClient.profiles).toHaveLength(1);
+ const profile = profileClient.profiles[0]!;
+ expect(profile.config).toEqual({
+ model_providers: { [providerName]: provider },
+ });
+ expect(startupCommands).toHaveLength(1);
+ expect(parse(startupCommands[0]!.args![1]!)).toEqual({
+ model_providers: {
+ [providerName]:
+ selection === "amazon-bedrock"
+ ? {}
+ : {
+ name: "Synthetic",
+ wire_api: "responses",
+ requires_openai_auth: false,
+ },
+ },
+ });
+ expect(startupCommands[0]!.args!.join("\n")).not.toContain(
+ "synthetic-header-marker",
+ );
+ expect(startupCommands[0]!.args!.join("\n")).not.toContain(
+ "synthetic-command-marker",
+ );
+ expect(parse(captured!.configOverrides!.join("\n"))).toEqual({
+ default_permissions: "codex_security_deep_scan_worker",
+ permissions: {
+ codex_security_deep_scan_worker: {
+ extends: ":read-only",
+ filesystem: { ":root": "read", [home]: { ".": "deny" } },
+ network: { enabled: false },
+ },
+ },
+ });
+ expect(JSON.stringify(captured?.config)).not.toContain(
+ "synthetic-header-marker",
+ );
+ expect(captured!.configOverrides!.join("\n")).not.toContain(
+ "synthetic-header-marker",
+ );
+ expect(JSON.stringify(captured?.config)).not.toContain(
+ "synthetic-command-marker",
+ );
+ expect(captured!.configOverrides!.join("\n")).not.toContain(
+ "synthetic-command-marker",
+ );
+ if (parentProfile === undefined) {
+ await expect(readFile(profile.path, "utf8")).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ } else {
+ expect(profile.name).toBe(parentProfile.name);
+ expect(parse(await readFile(parentProfile.path, "utf8"))).toEqual(
+ profile.config,
+ );
+ }
+ for (const key of [
+ "model_providers",
+ "default_permissions",
+ "permissions",
+ "projects",
+ "profile",
+ "profiles",
+ ]) {
+ expect(captured?.config).not.toHaveProperty(key);
+ }
+ if (selection === "command") {
+ expect(captured?.apiKey).toBeUndefined();
+ expect(captured?.env).not.toHaveProperty("OPENAI_API_KEY");
+ }
+ expect(calls.threadOptions).toMatchObject({
+ approvalPolicy: "never",
+ networkAccessEnabled: false,
+ });
+ expect(calls.threadOptions?.sandboxMode).toBeUndefined();
+ expect(saved).toBe(true);
+ expect(await readFile(join(home, "config.toml"), "utf8")).toBe("");
+ } finally {
+ nativeCommand.mockRestore();
+ profileClient.spy.mockRestore();
+ startThread.mockRestore();
+ await parentProfile?.cleanup();
+ }
+ },
+ );
+
+ test.each(["complete", "turn error", "abort"])(
+ "keeps its private provider profile through evidence turns and cleans up on %s",
+ async (outcome) => {
+ const home = await temporaryDirectory();
+ const controller = new AbortController();
+ const profileClient = captureProfileClient();
+ let turns = 0;
+ const startThread = spyOn(
+ Codex.prototype,
+ "startThread",
+ ).mockImplementation(
+ () =>
+ ({
+ async run() {
+ expect(
+ parse(await readFile(profileClient.profiles[0]!.path, "utf8")),
+ ).toMatchObject({
+ model_providers: {
+ synthetic: {
+ http_headers: {
+ "X-Synthetic-Secret": "synthetic-lifecycle-marker",
+ },
+ },
+ },
+ });
+ turns++;
+ if (turns === 2 && outcome === "turn error")
+ throw new Error("synthetic turn failure");
+ if (turns === 1 && outcome === "abort")
+ controller.abort(new DOMException("canceled", "AbortError"));
+ return {
+ finalResponse: JSON.stringify({
+ matches: [],
+ uncertain: [],
+ ...(turns === 1
+ ? {
+ request: {
+ kind: "evidence",
+ beforeOccurrenceIds: ["before"],
+ afterOccurrenceIds: ["after"],
+ offset: 0,
+ },
+ }
+ : {}),
+ }),
+ };
+ },
+ }) as unknown as ReturnType<Codex["startThread"]>,
+ );
+ try {
+ const result = matchScanFindings(
+ { before: [finding("before")], after: [finding("after")] },
+ {
+ signal: controller.signal,
+ environment: {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: home,
+ },
+ config: {
+ codexOverrides: {
+ model_provider: "synthetic",
+ model_providers: {
+ synthetic: {
+ name: "Synthetic",
+ wire_api: "responses",
+ base_url: "https://provider.example.test/v1",
+ http_headers: {
+ "X-Synthetic-Secret": "synthetic-lifecycle-marker",
+ },
+ },
+ },
+ },
+ },
+ },
+ );
+ if (outcome === "complete")
+ await expect(result).resolves.toEqual({ matches: [], uncertain: [] });
+ else if (outcome === "turn error")
+ await expect(result).rejects.toThrow("synthetic turn failure");
+ else await expect(result).rejects.toMatchObject({ name: "AbortError" });
+ expect(turns).toBe(outcome === "abort" ? 1 : 2);
+ expect(profileClient.profiles).toHaveLength(1);
+ await expect(
+ readFile(profileClient.profiles[0]!.path, "utf8"),
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ } finally {
+ profileClient.spy.mockRestore();
+ startThread.mockRestore();
+ }
+ },
+ );
+
+ test.each(["codex_security_policy", "codex_security_deep_scan_worker"])(
+ "does not inherit write grants from the existing %s permission profile",
+ async (permissionId) => {
+ const home = await temporaryDirectory();
+ const work = await temporaryDirectory();
+ await writeFile(
+ join(home, "config.toml"),
+ stringify({
+ default_permissions: permissionId,
+ permissions: {
+ [permissionId]: {
+ extends: ":read-only",
+ filesystem: { [work]: "write" },
+ },
+ },
+ }),
+ );
+ const profileClient = captureProfileClient();
+ const { codex } = fakeCodex({ matches: [], uncertain: [] });
+ let captured: CodexOptions | undefined;
+ const startThread = observeCodexOptions(codex, (options) => {
+ captured = options;
+ });
+ try {
+ const matching = matchScanFindings(
+ { before: [finding("before")], after: [finding("after")] },
+ {
+ workingDirectory: work,
+ environment: {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: home,
+ },
+ config: {
+ codexOverrides: {
+ model_provider: "synthetic",
+ model_providers: {
+ synthetic: {
+ name: "Synthetic",
+ wire_api: "responses",
+ base_url: "https://provider.example.test/v1",
+ },
+ },
+ },
+ },
+ },
+ );
+ if (permissionId === "codex_security_deep_scan_worker") {
+ await expect(matching).rejects.toThrow(
+ "existing Codex configuration changes the reserved",
+ );
+ expect(startThread).not.toHaveBeenCalled();
+ expect(
+ (await readdir(home)).filter((name) =>
+ name.endsWith(".config.toml"),
+ ),
+ ).toEqual([]);
+ return;
+ }
+ await matching;
+ // App-server reads the same native permission layers without a model turn.
+ // Provider definitions stay in their private file and are unnecessary here.
+ const child = spawn(
+ executablePathForSpawn(resolveCodexCommand({}).command),
+ [
+ ...captured!.configOverrides!.flatMap((value) => ["-c", value]),
+ "-c",
+ 'model_provider="openai"',
+ "app-server",
+ "--stdio",
+ ],
+ {
+ cwd: work,
+ env: {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: home,
+ },
+ windowsHide: true,
+ },
+ );
+ const closed = once(child, "close");
+ const lines = createInterface({ input: child.stdout });
+ let stderr = "";
+ child.stderr.on("data", (chunk) => {
+ stderr += chunk;
+ });
+ try {
+ child.stdin.write(
+ JSON.stringify({
+ id: 1,
+ method: "initialize",
+ params: {
+ clientInfo: { name: "synthetic_permission_test", version: "1" },
+ capabilities: { experimentalApi: true },
+ },
+ }) + "\n",
+ );
+ let inspected = false;
+ for await (const line of lines) {
+ const message = JSON.parse(line);
+ if (message.error) throw new Error(JSON.stringify(message.error));
+ if (message.id === 1)
+ child.stdin.write(
+ JSON.stringify({
+ id: 2,
+ method: "config/read",
+ params: { cwd: work, includeLayers: false },
+ }) + "\n",
+ );
+ if (message.id === 2) {
+ const config = message.result.config;
+ expect(
+ config.permissions[config.default_permissions].filesystem,
+ ).not.toHaveProperty(work);
+ expect(config.default_permissions).toBe(
+ "codex_security_deep_scan_worker",
+ );
+ expect(
+ config.permissions.codex_security_deep_scan_worker.filesystem,
+ ).toMatchObject({
+ ":root": "read",
+ [home]: { ".": "deny" },
+ });
+ expect(
+ config.permissions.codex_security_policy.filesystem[work],
+ ).toBe("write");
+ inspected = true;
+ break;
+ }
+ }
+ expect(inspected, stderr).toBe(true);
+ } finally {
+ lines.close();
+ child.kill();
+ await closed;
+ }
+ } finally {
+ profileClient.spy.mockRestore();
+ startThread.mockRestore();
+ }
+ },
+ );
+
+ test.each(["allowed", "disallowed", "fallback", "empty"])(
+ "checks the actual helper permission child before starting a turn when %s",
+ async (mode) => {
+ const home = await temporaryDirectory();
+ const work = await temporaryDirectory();
+ const executable = join(home, "synthetic-codex.mjs");
+ const callsPath = join(home, "preflight-calls.jsonl");
+ const profileId = "codex_security_deep_scan_worker";
+ await writeFile(
+ executable,
+ `
+ import { appendFileSync, existsSync } from "node:fs";
+ import { join } from "node:path";
+ import { createInterface } from "node:readline";
+ const args = process.argv.slice(2);
+ if (args.includes("mcp")) { console.log("[]"); process.exit(0); }
+ const id = ${JSON.stringify(profileId)};
+ const mode = ${JSON.stringify(mode)};
+ const profile = {
+ extends: ":read-only",
+ filesystem: { ":root": "read", [process.env.CODEX_HOME]: { ".": "deny" } },
+ network: { enabled: false },
+ };
+ const lines = createInterface({ input: process.stdin });
+ for await (const line of lines) {
+ const request = JSON.parse(line);
+ appendFileSync(${JSON.stringify(callsPath)}, JSON.stringify({
+ method: request.method, args, cwd: process.cwd(),
+ home: process.env.CODEX_HOME, sentinel: process.env.SYNTHETIC_PREFLIGHT_SENTINEL,
+ lockHeld: existsSync(join(process.env.CODEX_HOME, ".codex-security-preflight", ".codex-security-scan.lock", "owner.json")),
+ }) + "\\n");
+ if (request.id === undefined) continue;
+ const result = request.method === "config/read"
+ ? { config: { default_permissions: mode === "fallback" ? ":workspace" : id, permissions: { [id]: profile } } }
+ : request.method === "permissionProfile/list"
+ ? { data: [{ id, allowed: mode !== "disallowed" }], nextCursor: null }
+ : request.method === "configRequirements/read"
+ ? { requirements: { allowedPermissionProfiles: { ":workspace": true } } }
+ : {};
+ console.log(JSON.stringify({ id: request.id, result }));
+ }
+ `,
+ );
+ const originalSpawn = childProcess.spawn;
+ const spawnSpy = spyOn(childProcess, "spawn").mockImplementation(((
+ ...input: Parameters<typeof originalSpawn>
+ ) => {
+ const [command, args, options] = input;
+ return command === process.execPath ||
+ command === executablePathForSpawn(process.execPath)
+ ? originalSpawn(
+ process.execPath,
+ [executable, ...(args ?? [])],
+ options ?? {},
+ )
+ : originalSpawn(...input);
+ }) as typeof originalSpawn);
+ const profileClient = captureProfileClient();
+ const { codex } = fakeCodex({ matches: [], uncertain: [] });
+ const lockPath = join(
+ home,
+ ".codex-security-preflight",
+ ".codex-security-scan.lock",
+ );
+ let windows: unknown;
+ const startThread = spyOn(
+ Codex.prototype,
+ "startThread",
+ ).mockImplementation(function (this: Codex, options) {
+ windows = (this as unknown as { options: CodexOptions }).options
+ .config?.["windows"];
+ expect(existsSync(lockPath)).toBe(false);
+ return codex.startThread(options!) as ReturnType<Codex["startThread"]>;
+ });
+ try {
+ const matching = matchScanFindings(
+ { before: [finding("before")], after: [finding("after")] },
+ {
+ workingDirectory: work,
+ environment: {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_CLI_PATH: process.execPath,
+ CODEX_HOME: home,
+ SYNTHETIC_PREFLIGHT_SENTINEL: "synthetic-inherited-setting",
+ ...(mode === "empty"
+ ? { OPENAI_API_KEY: "synthetic-api-key" }
+ : {}),
+ },
+ config: {
+ codexOverrides:
+ mode === "empty"
+ ? { model_providers: {} }
+ : {
+ model_provider: "synthetic.provider",
+ model_providers: {
+ "synthetic.provider": {
+ name: "Synthetic provider",
+ wire_api: "responses",
+ auth: {
+ command: "synthetic-auth",
+ env: {
+ SYNTHETIC_SECRET: "synthetic-private-marker",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ );
+ if (mode === "allowed" || mode === "empty") {
+ await expect(matching).resolves.toEqual({
+ matches: [],
+ uncertain: [],
+ });
+ expect(startThread).toHaveBeenCalledTimes(1);
+ } else {
+ await expect(matching).rejects.toThrow(
+ mode === "disallowed"
+ ? "organization policy does not allow"
+ : "did not select",
+ );
+ expect(startThread).not.toHaveBeenCalled();
+ }
+ if (mode === "empty") {
+ expect(windows).toEqual({ sandbox: "elevated" });
+ expect(existsSync(callsPath)).toBe(false);
+ expect(profileClient.profiles).toEqual([]);
+ return;
+ }
+ const calls = (await readFile(callsPath, "utf8"))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ expect(calls.map(({ method }) => method)).toEqual([
+ "initialize",
+ "initialized",
+ "config/read",
+ "permissionProfile/list",
+ ...(mode === "disallowed" ? ["configRequirements/read"] : []),
+ ]);
+ expect(calls[0]).toMatchObject({
+ cwd: work,
+ home,
+ sentinel: "synthetic-inherited-setting",
+ lockHeld: true,
+ });
+ expect(existsSync(lockPath)).toBe(false);
+ const args = calls[0].args as string[];
+ const overrides = args.flatMap((arg, index) =>
+ arg === "--config" ? [args[index + 1]!] : [],
+ );
+ expect(parse(overrides.join("\n"))).toMatchObject({
+ default_permissions: profileId,
+ permissions: {
+ [profileId]: {
+ filesystem: { [home]: { ".": "deny" } },
+ network: { enabled: false },
+ },
+ },
+ model_providers: {
+ "synthetic.provider": {
+ name: "Synthetic provider",
+ wire_api: "responses",
+ },
+ },
+ });
+ expect(args.join("\n")).not.toContain("synthetic-private-marker");
+ expect(
+ (await readdir(home)).filter((name) => name.endsWith(".config.toml")),
+ ).toEqual([]);
+ } finally {
+ startThread.mockRestore();
+ profileClient.spy.mockRestore();
+ spawnSpy.mockRestore();
+ }
+ },
+ );
+
test.each([
[
"OPENAI_API_KEY",
@@ -129,12 +777,8 @@ describe("semantic scan comparison", () => {
const home = await temporaryDirectory("codex-security-matcher-auth-");
let captured: CodexOptions | undefined;
const { codex } = fakeCodex({ matches: [], uncertain: [] });
- const startThread = spyOn(
- Codex.prototype,
- "startThread",
- ).mockImplementation(function (this: Codex, options) {
- captured = (this as unknown as { options: CodexOptions }).options;
- return codex.startThread(options!) as ReturnType<Codex["startThread"]>;
+ const startThread = observeCodexOptions(codex, (options) => {
+ captured = options;
});
try {
await matchScanFindings(
@@ -195,14 +839,8 @@ describe("semantic scan comparison", () => {
};
let captured: CodexOptions | undefined;
const { codex, calls } = fakeCodex({ matches: [], uncertain: [] });
- const startThread = spyOn(
- Codex.prototype,
- "startThread",
- ).mockImplementation(function (this: Codex, threadOptions) {
- captured = (this as unknown as { options: CodexOptions }).options;
- return codex.startThread(threadOptions!) as ReturnType<
- Codex["startThread"]
- >;
+ const startThread = observeCodexOptions(codex, (options) => {
+ captured = options;
});
try {
for (const helper of ["matching", "planning"]) {
@@ -246,7 +884,7 @@ describe("semantic scan comparison", () => {
},
);
- test.each(["home", "profile", "overrides", "override-away"])(
+ test.each(["home", "home-override", "profile", "overrides", "override-away"])(
"preserves native command auth selection from %s",
async (selection) => {
const home = await temporaryDirectory(
@@ -264,6 +902,9 @@ describe("semantic scan comparison", () => {
},
};
const config = {
+ ...(selection === "home-override"
+ ? { windows: { sandbox: "unelevated" } }
+ : {}),
model_provider:
selection === "overrides" || selection === "profile"
? "openai"
@@ -281,6 +922,7 @@ describe("semantic scan comparison", () => {
};
let captured: CodexOptions | undefined;
let threadOptions: ThreadOptions | undefined;
+ const profileClient = captureProfileClient();
const { codex } = fakeCodex({ matches: [], uncertain: [] });
const startThread = spyOn(
Codex.prototype,
@@ -326,13 +968,22 @@ describe("semantic scan comparison", () => {
},
);
expect(captured?.env?.["CODEX_HOME"]).toBe(home);
- if (selection === "profile")
- expect(captured?.config?.["profile"]).toBe("review");
+ if (selection === "profile") {
+ expect(captured?.config?.["model_provider"]).toBe(
+ "synthetic.provider",
+ );
+ expect(captured?.config).not.toHaveProperty("profile");
+ expect(captured?.config).not.toHaveProperty("profiles");
+ }
if (commandAuth) {
+ expect(captured?.config?.["windows"]).toEqual({
+ sandbox: selection === "home-override" ? "unelevated" : "elevated",
+ });
expect(captured?.env).not.toHaveProperty("OPENAI_API_KEY");
expect(captured?.env).not.toHaveProperty("CODEX_API_KEY");
expect(captured?.apiKey).toBeUndefined();
- expect(parse(captured!.configOverrides![0]!)).toEqual({
+ expect(profileClient.profiles).toHaveLength(1);
+ expect(profileClient.profiles[0]!.config).toEqual({
model_providers: {
"synthetic.provider": {
...provider,
@@ -344,22 +995,183 @@ describe("semantic scan comparison", () => {
},
},
});
+ await expect(
+ readFile(profileClient.profiles[0]!.path, "utf8"),
+ ).rejects.toMatchObject({ code: "ENOENT" });
} else {
expect(captured?.env?.["OPENAI_API_KEY"]).toBe(
"synthetic-ambient-key",
);
+ expect(captured?.config?.["model_provider"]).toBe("openai");
expect(captured?.configOverrides).toBeUndefined();
+ expect(profileClient.profiles).toHaveLength(0);
}
expect(threadOptions).toMatchObject({
workingDirectory: home,
- sandboxMode: "read-only",
approvalPolicy: "never",
networkAccessEnabled: false,
});
+ expect(threadOptions?.sandboxMode).toBe(
+ commandAuth ? undefined : "read-only",
+ );
expect(await readFile(join(home, "config.toml"), "utf8")).toBe(
contents,
);
} finally {
+ profileClient.spy.mockRestore();
+ startThread.mockRestore();
+ }
+ },
+ );
+
+ test.each(["command", "environment", "permissions"] as const)(
+ "automatic matching keeps concurrent %s configurations isolated",
+ async (mode) => {
+ const home = await temporaryDirectory(
+ "codex-security-automatic-matching-",
+ );
+ await writeFile(join(home, "config.toml"), "");
+ if (process.platform !== "win32") await chmod(home, 0o755);
+ const providers = [0, 1].map((index) => ({
+ name: `Synthetic provider ${index}`,
+ base_url: `https://provider-${index}.example.test/v1`,
+ wire_api: "responses",
+ http_headers: {
+ "X-Synthetic-Secret": `synthetic-concurrent-header-${index}`,
+ },
+ ...(mode === "environment"
+ ? { env_key: "SYNTHETIC_PROVIDER_KEY" }
+ : {
+ auth: {
+ command: `synthetic-auth-${index}`,
+ cwd: join(home, `native-${index}`, "helpers"),
+ },
+ }),
+ }));
+ const captured: CodexOptions[] = [];
+ const profileClient = captureProfileClient();
+ const { codex } = fakeCodex({ matches: [], uncertain: [] });
+ const turnsStarted = Promise.withResolvers<void>();
+ let runningTurns = 0;
+ const startThread = spyOn(
+ Codex.prototype,
+ "startThread",
+ ).mockImplementation(function (this: Codex, options) {
+ captured.push((this as unknown as { options: CodexOptions }).options);
+ const thread = codex.startThread(options!);
+ return {
+ async run(...args: Parameters<typeof thread.run>) {
+ if (++runningTurns === 2) turnsStarted.resolve();
+ await turnsStarted.promise;
+ return thread.run(...args);
+ },
+ } as ReturnType<Codex["startThread"]>;
+ });
+ try {
+ await Promise.all(
+ providers.map(async (provider, index) => {
+ const before = finding(`before-${index}`);
+ const after = finding(`after-${index}`);
+ const scanId = `current-${index}`;
+ const codexConfig = resolveCommandAuthConfig(
+ {
+ ...(mode === "permissions"
+ ? {
+ permissions: {
+ audit: { filesystem: { [home]: { ".": "read" } } },
+ },
+ }
+ : {}),
+ model_provider: "synthetic.provider",
+ model_providers: {
+ "synthetic.provider": {
+ ...provider,
+ ...(!("auth" in provider)
+ ? {}
+ : { auth: { ...provider.auth, cwd: "helpers" } }),
+ },
+ },
+ },
+ join(home, `native-${index}`),
+ );
+ await matchCompletedScan({
+ scanId,
+ repository: home,
+ previousFindings: [before],
+ falsePositives: [],
+ findings: [after],
+ config: { codexOverrides: codexConfig },
+ environment: {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: home,
+ CODEX_SECURITY_SCAN_ID: scanId,
+ OPENAI_API_KEY: "synthetic-ambient-key",
+ SYNTHETIC_PROVIDER_KEY: `synthetic-provider-${index}`,
+ },
+ async workbench(args) {
+ return args[0] === "list-unmatched-scan-pairs"
+ ? {
+ batches: [
+ {
+ afterScanId: scanId,
+ afterFindings: [after],
+ beforeScans: [
+ { scanId: `prior-${index}`, findings: [before] },
+ ],
+ },
+ ],
+ }
+ : {};
+ },
+ });
+ }),
+ );
+ expect(captured).toHaveLength(2);
+ for (const [index, provider] of providers.entries()) {
+ const options = captured.find(
+ ({ env }) => env?.["CODEX_SECURITY_SCAN_ID"] === `current-${index}`,
+ );
+ expect(options?.config?.["model_provider"]).toBe(
+ "synthetic.provider",
+ );
+ const profile = profileClient.profiles.find(
+ ({ scanId }) => scanId === `current-${index}`,
+ );
+ expect(profile).toBeDefined();
+ expect(profile!.config).toEqual({
+ model_providers: { "synthetic.provider": provider },
+ });
+ for (const markerIndex of [0, 1]) {
+ expect(JSON.stringify(options!.config)).not.toContain(
+ `synthetic-concurrent-header-${markerIndex}`,
+ );
+ expect(options!.configOverrides!.join("\n")).not.toContain(
+ `synthetic-concurrent-header-${markerIndex}`,
+ );
+ }
+ await expect(readFile(profile!.path, "utf8")).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ expect(options?.config).not.toHaveProperty("permissions");
+ if (mode !== "environment") {
+ expect(options?.apiKey).toBeUndefined();
+ expect(options?.env).not.toHaveProperty("OPENAI_API_KEY");
+ } else {
+ expect(options?.env?.["SYNTHETIC_PROVIDER_KEY"]).toBe(
+ `synthetic-provider-${index}`,
+ );
+ }
+ }
+ expect(await readFile(join(home, "config.toml"), "utf8")).toBe("");
+ if (process.platform !== "win32") {
+ expect((await stat(home)).mode & 0o777).toBe(0o755);
+ expect(
+ (await stat(join(home, ".codex-security-preflight"))).mode & 0o777,
+ ).toBe(0o700);
+ }
+ } finally {
+ profileClient.spy.mockRestore();
startThread.mockRestore();
}
},
@@ -409,6 +1221,7 @@ describe("semantic scan comparison", () => {
workingDirectory: home,
};
const { codex } = fakeCodex({ matches: [], uncertain: [] });
+ const profileClient = captureProfileClient();
const startThread = spyOn(
Codex.prototype,
"startThread",
@@ -450,104 +1263,123 @@ describe("semantic scan comparison", () => {
).rejects.toThrow("conflicts with command authentication");
expect(startThread).not.toHaveBeenCalled();
} finally {
+ profileClient.spy.mockRestore();
startThread.mockRestore();
}
},
);
- test("disables explicit and inherited MCP servers for read-only helper turns", async () => {
- const home = await temporaryDirectory("codex-security-comparison-");
- await writeFile(
- join(home, "config.toml"),
- '[mcp_servers.inherited]\ncommand = "synthetic-inherited"\n',
- );
- const executable = join(
- home,
- process.platform === "win32" ? "custom-codex.exe" : "custom-codex",
- );
- await copyFile(resolveCodexCommand({}).command, executable);
- const environment = {
- PATH: process.env["PATH"],
- SystemRoot: process.env["SystemRoot"],
- TEMP: process.env["TEMP"],
- TMP: process.env["TMP"],
- CODEX_HOME: home,
- CODEX_CLI_PATH: executable,
- OPENAI_API_KEY: "synthetic-key",
- };
- const { codex } = fakeCodex({ matches: [], uncertain: [] });
- let config: CodexOptions["config"];
- let codexPath: string | undefined;
- let codexEnvironment: CodexOptions["env"];
- const startThread = spyOn(
- Codex.prototype,
- "startThread",
- ).mockImplementation(function (this: Codex, options) {
- config = (this as unknown as { options: CodexOptions }).options.config;
- codexPath = (this as unknown as { options: CodexOptions }).options
- .codexPathOverride;
- codexEnvironment = (this as unknown as { options: CodexOptions }).options
- .env;
- return codex.startThread(options!) as ReturnType<Codex["startThread"]>;
- });
- try {
- await matchScanFindings(
- { before: [finding("before")], after: [finding("after")] },
- {
- environment,
- workingDirectory: home,
- config: {
- codexOverrides: {
- mcp_servers: {
- synthetic: { command: "synthetic-integration", enabled: true },
+ test.each([
+ ["default", {}, "elevated"],
+ ["elevated", { windows: { sandbox: "elevated" } }, "elevated"],
+ ["unelevated", { windows: { sandbox: "unelevated" } }, "unelevated"],
+ ["legacy", { features: { elevated_windows_sandbox: false } }, "unelevated"],
+ [
+ "profile",
+ {
+ profile: "selected",
+ profiles: { selected: { windows: { sandbox: "unelevated" } } },
+ },
+ "unelevated",
+ ],
+ ] as const)(
+ "keeps MCP servers disabled with %s Windows settings",
+ async (name, homeConfig, sandbox) => {
+ const home = await temporaryDirectory("codex-security-comparison-");
+ await writeFile(
+ join(home, "config.toml"),
+ stringify({
+ ...(name === "profile" ? {} : homeConfig),
+ mcp_servers: { inherited: { command: "synthetic-inherited" } },
+ }),
+ );
+ const executable = join(
+ home,
+ process.platform === "win32" ? "custom-codex.exe" : "custom-codex",
+ );
+ await copyFile(resolveCodexCommand({}).command, executable);
+ const environment = {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ TEMP: process.env["TEMP"],
+ TMP: process.env["TMP"],
+ CODEX_HOME: home,
+ CODEX_CLI_PATH: executable,
+ OPENAI_API_KEY: "synthetic-key",
+ };
+ const { codex } = fakeCodex({ matches: [], uncertain: [] });
+ let config: CodexOptions["config"];
+ let codexPath: string | undefined;
+ let codexEnvironment: CodexOptions["env"];
+ const startThread = observeCodexOptions(codex, (options) => {
+ config = options.config;
+ codexPath = options.codexPathOverride;
+ codexEnvironment = options.env;
+ });
+ try {
+ await matchScanFindings(
+ { before: [finding("before")], after: [finding("after")] },
+ {
+ environment,
+ workingDirectory: home,
+ config: {
+ codexOverrides: {
+ ...(name === "profile" ? homeConfig : {}),
+ mcp_servers: {
+ synthetic: {
+ command: "synthetic-integration",
+ enabled: true,
+ },
+ },
},
},
},
- },
- );
- expect(config?.["mcp_servers"]).toEqual({
- synthetic: { command: "synthetic-integration", enabled: false },
- inherited: { enabled: false },
- });
- expect(codexPath).toBe(
- process.platform === "win32"
- ? win32.toNamespacedPath(executable)
- : executable,
- );
- expect(codexEnvironment?.["CODEX_CLI_PATH"]).toBe(executable);
- const effective = await runCodexCommand(
- resolveCodexCommand(environment),
- [
- "-C",
- home,
- "-c",
- 'mcp_servers.synthetic.command="synthetic-integration"',
- ...Object.keys(config!["mcp_servers"]!).flatMap((name) => [
+ );
+ expect(config?.["mcp_servers"]).toEqual({
+ synthetic: { command: "synthetic-integration", enabled: false },
+ inherited: { enabled: false },
+ });
+ expect(config?.["windows"]).toEqual({ sandbox });
+ expect(codexPath).toBe(
+ process.platform === "win32"
+ ? win32.toNamespacedPath(executable)
+ : executable,
+ );
+ expect(codexEnvironment?.["CODEX_CLI_PATH"]).toBe(executable);
+ const effective = await runCodexCommand(
+ resolveCodexCommand(environment),
+ [
+ "-C",
+ home,
"-c",
- `mcp_servers.${name}.enabled=false`,
- ]),
- "mcp",
- "list",
- "--json",
- ],
- environment,
- );
- expect(effective.success).toBe(true);
- expect(
- JSON.parse(effective.stdout).map(
- (server: { name: string; enabled: boolean }) => ({
- name: server.name,
- enabled: server.enabled,
- }),
- ),
- ).toEqual([
- { name: "inherited", enabled: false },
- { name: "synthetic", enabled: false },
- ]);
- } finally {
- startThread.mockRestore();
- }
- });
+ 'mcp_servers.synthetic.command="synthetic-integration"',
+ ...Object.keys(config!["mcp_servers"]!).flatMap((name) => [
+ "-c",
+ `mcp_servers.${name}.enabled=false`,
+ ]),
+ "mcp",
+ "list",
+ "--json",
+ ],
+ environment,
+ );
+ expect(effective.success).toBe(true);
+ expect(
+ JSON.parse(effective.stdout).map(
+ (server: { name: string; enabled: boolean }) => ({
+ name: server.name,
+ enabled: server.enabled,
+ }),
+ ),
+ ).toEqual([
+ { name: "inherited", enabled: false },
+ { name: "synthetic", enabled: false },
+ ]);
+ } finally {
+ startThread.mockRestore();
+ }
+ },
+ );
test("preserves environment API-key precedence over managed credentials", async () => {
const root = await temporaryDirectory("codex-security-comparison-");
diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.ts
index c3a71693c..22565c3ce 100644
--- a/sdk/typescript/tests-ts/scan-resume.test.ts
+++ b/sdk/typescript/tests-ts/scan-resume.test.ts
@@ -405,28 +405,34 @@ test("resumed Bedrock scans retain provider context for the account advisory", a
const code = await runCli(["scans", "resume", f.scanId, "--json"], {
...dependencies({ environment: f.environment, currentDirectory: f.root }),
runWorkbench: f.command,
- createSecurity: resumeClient(f, (options) => ({
- startThread() {
- throw new Error("Resume must not create a new thread.");
- },
- resumeThread(threadId) {
- expect(threadId).toBe(f.threadId);
- expect(options.env).toMatchObject({
- AWS_PROFILE: "synthetic-bedrock",
- });
- expect(options.apiKey).toBeUndefined();
- return {
- id: threadId,
- async runStreamed(prompt) {
- expect(prompt).toContain("Amazon Bedrock with AWS authentication");
- expect(prompt).toContain(
- "Skip the ChatGPT account Daybreak access advisory",
- );
- throw new Error("Resumed Bedrock prompt captured");
- },
- };
- },
- })),
+ createSecurity: resumeClient(
+ f,
+ (options) => ({
+ startThread() {
+ throw new Error("Resume must not create a new thread.");
+ },
+ resumeThread(threadId) {
+ expect(threadId).toBe(f.threadId);
+ expect(options.env).toMatchObject({
+ AWS_PROFILE: "synthetic-bedrock",
+ });
+ expect(options.apiKey).toBeUndefined();
+ return {
+ id: threadId,
+ async runStreamed(prompt) {
+ expect(prompt).toContain(
+ "Amazon Bedrock with AWS authentication",
+ );
+ expect(prompt).toContain(
+ "Skip the ChatGPT account Daybreak access advisory",
+ );
+ throw new Error("Resumed Bedrock prompt captured");
+ },
+ };
+ },
+ }),
+ { deepScanConfigPath: join(f.codexHome, "deep-scan.toml") },
+ ),
});
expect(code).not.toBe(0);
expect(stderr.text()).toContain("Resumed Bedrock prompt captured");
@@ -437,12 +443,16 @@ function resumeClient(
createCodex: NonNullable<
ConstructorParameters<typeof TestClient>[1]["createCodex"]
>,
+ runtimeOverrides: Partial<ReturnType<typeof preparedRuntime>> = {},
) {
return (config: ConstructorParameters<typeof TestClient>[0]) =>
new TestClient(config, {
environment: f.environment,
prepareRuntime: async () => {
- const runtime = preparedRuntime(f.codexHome);
+ const runtime = {
+ ...preparedRuntime(f.codexHome),
+ ...runtimeOverrides,
+ };
runtime.configPath = join(f.root, "resumed-runtime.toml");
runtime.environment = Object.fromEntries(
Object.entries(f.environment).filter(