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(config): inherit null overrides and preserve literal paths (#1290)

mldangelo-oaif5b725f4a35e
diff --git a/plugins/codex-security/mcp-app/tests/test_codex_profile.ts b/plugins/codex-security/mcp-app/tests/test_codex_profile.ts
index 10167a3da..7c2b4091c 100644
--- a/plugins/codex-security/mcp-app/tests/test_codex_profile.ts
+++ b/plugins/codex-security/mcp-app/tests/test_codex_profile.ts
@@ -36,6 +36,7 @@ test("native startup provider metadata preserves identity and auth without priva
wire_api: "responses",
},
"amazon-bedrock": { aws: { region: "us-east-1" } },
+ "omitted-provider": null,
};
const before = structuredClone(providers);
assert.deepEqual(preflightProviderDefinitions(providers), {
@@ -78,6 +79,13 @@ test("native overrides preserve literal paths, prototype keys, and TOML control
});
});
+test("native overrides reject null array elements", () => {
+ assert.throws(
+ () => profileConfigOverrides({ values: [null] }),
+ /must contain finite TOML values/,
+ );
+});
+
async function fixture(mode = "success") {
const directory = await mkdtemp(path.join(tmpdir(), "codex-profile-test-"));
const script = path.join(directory, "native-fixture.mjs");
@@ -178,9 +186,10 @@ test("native profile turns preserve settings, JSON events, schema cleanup, and r
...f.options,
baseUrl: "https://provider.example.test/v1",
config: {
- features: { plugins: true },
+ features: { plugins: true, optional: null },
+ service_tier: null,
empty: {},
- values: [1, { "dotted.key": "value" }],
+ values: [1, { "dotted.key": "value", optional: null }],
},
configOverrides: ["features.plugins=false"],
});
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 c58b8ba70..64fd66877 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
@@ -961,8 +961,15 @@ async function testOpenAiCredentialsReachWorker() {
requiresOpenaiAuth: boolean;
};
nativeProvider?: string;
+ configuration?: string;
}[] = [
{ openai: "synthetic-openai-key", expected: "synthetic-openai-key" },
+ {
+ openai: "synthetic-openai-key",
+ expected: "synthetic-openai-key",
+ // Optional null auth is omitted from the SDK's private TOML snapshot.
+ configuration: 'model_provider = "openai"\n[model_providers.openai]\n',
+ },
{
openai: " synthetic-openai-key ",
codex: " ",
@@ -1030,6 +1037,7 @@ async function testOpenAiCredentialsReachWorker() {
"CODEX_API_KEY",
"CODEX_CLI_PATH",
"CODEX_HOME",
+ "CODEX_SECURITY_CONFIG_PATH",
...Object.keys(runtimeEnvironment),
].map((name) => [name, process.env[name]] as const);
const originalSpawn = childProcess.spawn;
@@ -1038,6 +1046,9 @@ async function testOpenAiCredentialsReachWorker() {
restoreEnv("CODEX_API_KEY", entry.codex);
process.env.CODEX_CLI_PATH = process.execPath;
process.env.CODEX_HOME = fixture.root;
+ const configPath = path.join(fixture.root, "scan-settings.toml");
+ await writeFile(configPath, entry.configuration ?? "");
+ process.env.CODEX_SECURITY_CONFIG_PATH = configPath;
Object.assign(process.env, runtimeEnvironment);
if (entry.nativeProvider !== undefined) {
await writeFile(
@@ -1391,7 +1402,10 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
auth: {
type: "command",
command: "synthetic-auth",
- cwd: path.join(codexHome, `helpers ${index}`),
+ cwd: path.join(
+ fixture.root,
+ `selected helper home ${index}`,
+ ),
args: [String(index)],
env: { CLIENT_SECRET: `synthetic-client-secret-${index}` },
},
@@ -1554,7 +1568,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
workerConfigurations[index].path;
process.env.XDG_CACHE_HOME = path.join(
fixture.root,
- `cache-${index}`,
+ `cache-${index} `,
);
process.env.CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH =
workerConfigurations[index].deepPath;
@@ -1648,7 +1662,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
});
assert.equal(
invocation.cacheDirectory,
- path.join(fixture.root, `cache-${index}`),
+ path.join(fixture.root, `cache-${index} `),
);
assert.deepEqual(
invocation.argv.filter((arg: string) =>
@@ -1789,7 +1803,7 @@ env_key = "SYNTHETIC_GATEWAY_KEY"`,
preflight.cacheDirectory,
path.join(
fixture.root,
- `cache-${workerConfigurations.indexOf(selectedProvider)}`,
+ `cache-${workerConfigurations.indexOf(selectedProvider)} `,
),
);
assert.deepEqual(
diff --git a/plugins/codex-security/scripts/codex_profile.mjs b/plugins/codex-security/scripts/codex_profile.mjs
index 6ef081633..8ad053f1c 100644
--- a/plugins/codex-security/scripts/codex_profile.mjs
+++ b/plugins/codex-security/scripts/codex_profile.mjs
@@ -8,14 +8,16 @@ import { createInterface } from "node:readline";
// 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]]),
- ),
- ]),
+ Object.entries(providers)
+ .filter(([, provider]) => provider != null)
+ .map(([id, provider]) => [
+ id,
+ Object.fromEntries(
+ ["name", "wire_api", "requires_openai_auth"]
+ .filter((key) => Object.hasOwn(provider, key))
+ .map((key) => [key, provider[key]]),
+ ),
+ ]),
);
}
@@ -30,7 +32,7 @@ export function isPermissionProfileFallbackWarning(message, profileId) {
export function profileConfigOverrides(config) {
return Object.entries(config)
- .filter(([, value]) => value !== undefined)
+ .filter(([, value]) => value != null)
.map(([key, value]) => `${key}=${toml(value)}`);
}
@@ -185,7 +187,7 @@ function toml(value) {
if (Array.isArray(value)) return `[${value.map(toml).join(", ")}]`;
if (value !== null && typeof value === "object") {
return `{${Object.entries(value)
- .filter(([, child]) => child !== undefined)
+ .filter(([, child]) => child != null)
.map(
([key, child]) =>
`${/^[A-Za-z0-9_-]+$/.test(key) ? key : toml(key)} = ${toml(child)}`,
diff --git a/plugins/codex-security/scripts/workbench_scan_usage.py b/plugins/codex-security/scripts/workbench_scan_usage.py
index 63fa3b45a..463a23585 100644
--- a/plugins/codex-security/scripts/workbench_scan_usage.py
+++ b/plugins/codex-security/scripts/workbench_scan_usage.py
@@ -219,17 +219,19 @@ def _codex_state_database() -> Path | None:
path = Path(configured_database).expanduser()
return path.resolve() if path.is_file() and os.access(path, os.R_OK) else None
- configured_home = os.environ.get("CODEX_HOME", "").strip()
- codex_home = Path(configured_home).expanduser() if configured_home else Path.home() / ".codex"
- configured_sqlite_home = os.environ.get("CODEX_SQLITE_HOME", "").strip()
+ configured_home = os.environ.get("CODEX_HOME", "")
+ codex_home = Path(configured_home) if configured_home.strip() else Path.home() / ".codex"
+ configured_sqlite_home = os.environ.get("CODEX_SQLITE_HOME", "")
search_roots = [
- *([Path(configured_sqlite_home).expanduser()] if configured_sqlite_home else []),
+ *([Path(configured_sqlite_home)] if configured_sqlite_home.strip() else []),
codex_home,
codex_home / "sqlite",
]
seen: set[Path] = set()
for search_root in search_roots:
try:
+ if search_root.parts[:1] == ("~",):
+ search_root = search_root.expanduser()
resolved_root = search_root.resolve()
if resolved_root in seen:
continue
diff --git a/plugins/codex-security/tests/test_workbench_scan_usage.py b/plugins/codex-security/tests/test_workbench_scan_usage.py
index ea9fdeedd..9133b0f20 100644
--- a/plugins/codex-security/tests/test_workbench_scan_usage.py
+++ b/plugins/codex-security/tests/test_workbench_scan_usage.py
@@ -480,6 +480,40 @@ def test_completion_marks_unverifiable_workers_partial(
assert usage["totalTokens"] == 16
[email protected]("home_variable", ["CODEX_HOME", "CODEX_SQLITE_HOME"])
[email protected]("home_kind", ["absolute", "literal_tilde", "relative_home", "home"])
+def test_completion_reads_usage_from_literal_home(
+ tmp_path: Path, home_variable: str, home_kind: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fixture = _start_scan(tmp_path)
+ home = tmp_path / ("native home" if sys.platform == "win32" else "native home ")
+ if home_kind == "literal_tilde":
+ home = tmp_path / ("~ literal" if sys.platform == "win32" else "~ ")
+ fixture.environment["CODEX_SQLITE_HOME"] = str(home)
+ parent = _rollout(
+ tmp_path,
+ "scan-parent",
+ [_token_event(fixture.started_at + timedelta(microseconds=1), 12, 3)],
+ )
+ _state_graph(fixture.environment, {"scan-parent": parent}, [])
+ configured_home = str(home)
+ if home_kind == "literal_tilde":
+ monkeypatch.chdir(tmp_path)
+ configured_home = home.name
+ elif home_kind in {"relative_home", "home"}:
+ monkeypatch.setenv("HOME", str(home if home_kind == "home" else tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(home if home_kind == "home" else tmp_path))
+ configured_home = "~" if home_kind == "home" else f"~/{home.name}"
+ fixture.environment[home_variable] = configured_home
+ if home_variable == "CODEX_HOME":
+ fixture.environment["CODEX_SQLITE_HOME"] = ""
+
+ usage = _complete_scan(fixture)["scan"]["usage"]
+
+ assert usage["coverage"] == "complete"
+ assert usage["totalTokens"] == 15
+
+
def test_completion_reports_unavailable_without_fabricating_zero(tmp_path: Path) -> None:
fixture = _start_scan(tmp_path)
usage = _complete_scan(fixture)["scan"]["usage"]
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 52e96efc8..35ee2413f 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -4874,13 +4874,13 @@ function selectedWorkerRuntimeConfig(
: [];
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);
+ const key =
+ process.platform === "win32"
+ ? Object.keys(environment)
+ .sort()
+ .find((key) => key.toUpperCase() === name.toUpperCase())
+ : name;
+ const value = key === undefined ? undefined : environment[key];
return value === undefined ? [] : [[name, value]];
}),
);
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.ts
index 892aa6afc..88ccf5769 100644
--- a/sdk/typescript/src/auth.ts
+++ b/sdk/typescript/src/auth.ts
@@ -43,10 +43,10 @@ export function withoutOpenAiApiKeys<Value>(
/** @internal */
export function configuredCodexHome(environment: ProcessEnvironment): string {
+ const configured = environmentEntry(environment, "CODEX_HOME");
return resolve(
expandHome(
- environmentEntry(environment, "CODEX_HOME")?.trim() ||
- join(homedir(), ".codex"),
+ configured?.trim() ? configured : join(homedir(), ".codex"),
environment,
),
);
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index c0d2b8013..ccded69ff 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -59,7 +59,7 @@ import {
type ArtifactExportArguments,
} from "./artifact-export.js";
export { exportEnvironment } from "./artifact-export.js";
-import { parse as parseToml } from "smol-toml";
+import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import {
classifyConnectionFailure,
CodexSecurity,
@@ -1356,7 +1356,9 @@ export async function runCodexSkillCommand(
output.appServer === undefined
? {}
: resolveCodexProfile(await readCodexHomeConfig(processEnvironment));
- const overrides = structuredClone(output.codexOverrides ?? {});
+ const overrides = parseToml(
+ stringifyToml(output.codexOverrides ?? {}),
+ ) as JsonObject;
const config = deepMerge(ambientConfig, overrides);
const provider = output.modelProvider ?? scanModelProvider(config);
// Native Codex ignores configured tables for these built-in providers.
@@ -1372,7 +1374,7 @@ export async function runCodexSkillCommand(
typeof providerConfiguration?.["env_key"] === "string"
? providerConfiguration["env_key"]
: undefined;
- const commandAuth = providerConfiguration?.["auth"] !== undefined;
+ const commandAuth = providerConfiguration?.["auth"] != null;
const explicitChatgpt =
output.auth === "chatgpt" && !isExternalModelProvider(provider);
const providerBearer =
diff --git a/sdk/typescript/src/cloud-publish.ts b/sdk/typescript/src/cloud-publish.ts
index 44b161ccf..5d3d9fe26 100644
--- a/sdk/typescript/src/cloud-publish.ts
+++ b/sdk/typescript/src/cloud-publish.ts
@@ -252,8 +252,9 @@ async function publishCloudPayload(
}
async function readCloudCredentials(environment: NodeJS.ProcessEnv) {
+ const configuredHome = environment["CODEX_HOME"];
let home = expandHome(
- environment["CODEX_HOME"]?.trim() || "~/.codex",
+ configuredHome?.trim() ? configuredHome : "~/.codex",
environment,
);
let requireFileStorage = true;
diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.ts
index 1b5fb524a..d4ab296e3 100644
--- a/sdk/typescript/src/config.ts
+++ b/sdk/typescript/src/config.ts
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import { mkdir, open, rename, unlink } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import type { CyberAccessProgram } from "@openai/codex-sdk";
-import { stringify } from "smol-toml";
+import { parse, stringify } from "smol-toml";
import { ConfigurationError } from "./errors.js";
export type JsonPrimitive = string | number | boolean | null;
@@ -85,10 +85,8 @@ export function scanModelConfiguration(
);
}
const reasoningEffort =
- selectedProfile !== undefined &&
- Object.hasOwn(selectedProfile, "model_reasoning_effort")
- ? selectedProfile["model_reasoning_effort"]
- : config["model_reasoning_effort"];
+ selectedProfile?.["model_reasoning_effort"] ??
+ config["model_reasoning_effort"];
if (
typeof reasoningEffort !== "string" ||
reasoningEffort.trim().length === 0
@@ -102,18 +100,12 @@ export function scanModelConfiguration(
export function scanModel(config: Readonly<JsonObject>): unknown {
const selectedProfile = selectedScanProfile(config);
- return selectedProfile !== undefined &&
- Object.hasOwn(selectedProfile, "model")
- ? selectedProfile["model"]
- : config["model"];
+ return selectedProfile?.["model"] ?? config["model"];
}
export function scanModelProvider(config: Readonly<JsonObject>): unknown {
const selectedProfile = selectedScanProfile(config);
- return selectedProfile !== undefined &&
- Object.hasOwn(selectedProfile, "model_provider")
- ? selectedProfile["model_provider"]
- : config["model_provider"];
+ return selectedProfile?.["model_provider"] ?? config["model_provider"];
}
/** @internal Native Codex validates the auth table, including invalid selections. */
@@ -124,7 +116,7 @@ export function hasCommandAuth(config: Readonly<JsonObject>): boolean {
typeof selected === "string" && isObject(providers)
? providers[selected]
: undefined;
- return isObject(provider) && provider["auth"] !== undefined;
+ return isObject(provider) && provider["auth"] != null;
}
/** @internal Keep host-side helpers independent of the source checkout. */
@@ -141,7 +133,7 @@ export function resolveCommandAuthConfig(
const auth = provider["auth"];
const cwd = auth["cwd"];
if (
- cwd === undefined ||
+ cwd == null ||
(typeof cwd === "string" && !/^~(?:[/\\]|$)/u.test(cwd))
) {
auth["cwd"] = resolve(home, cwd ?? ".");
@@ -153,7 +145,7 @@ export function resolveCommandAuthConfig(
/** @internal CLI dotted keys cannot represent provider IDs containing dots. */
export function modelProviderConfigOverride(config: JsonObject): string[] {
- return config["model_providers"] === undefined
+ return config["model_providers"] == null
? []
: [`model_providers=${inlineToml(config["model_providers"])}`];
}
@@ -176,6 +168,7 @@ export function inlineToml(value: JsonValue): string {
if (Array.isArray(value)) return `[${value.map(inlineToml).join(",")}]`;
if (isObject(value)) {
return `{${Object.entries(value)
+ .filter(([, item]) => item !== null)
.map(([key, item]) => `${JSON.stringify(key)}=${inlineToml(item)}`)
.join(",")}}`;
}
@@ -206,10 +199,8 @@ function selectedScanProfile(
}
export function resolveCodexProfile(config: JsonObject): JsonObject {
- const resolved = deepMerge(
- structuredClone(config),
- selectedScanProfile(config) ?? {},
- );
+ const normalized = parse(stringify(config)) as JsonObject;
+ const resolved = deepMerge(normalized, selectedScanProfile(normalized) ?? {});
delete resolved["profile"];
delete resolved["profiles"];
return resolved;
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 514553f04..686d10da6 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -193,14 +193,15 @@ export interface ScanArtifactRestorer {
function environmentValue(
environment: ProcessEnvironment,
requested: string,
+ preserveWhitespace = false,
): string | undefined {
- const exact = environment[requested]?.trim();
- if (exact) return exact;
- return Object.entries(environment)
- .find(
- ([name, value]) => name.toUpperCase() === requested && value?.trim(),
- )?.[1]
- ?.trim();
+ const exact = environment[requested];
+ const value = exact?.trim()
+ ? exact
+ : Object.entries(environment).find(
+ ([name, value]) => name.toUpperCase() === requested && value?.trim(),
+ )?.[1];
+ return preserveWhitespace ? value : value?.trim();
}
export function codexSecurityStateDirectory(
@@ -212,7 +213,7 @@ export function codexSecurityStateDirectory(
? resolve(expandHome(configured, environment))
: resolve(
expandHome(
- environmentValue(environment, "CODEX_HOME") ??
+ environmentValue(environment, "CODEX_HOME", true) ??
join(homedir(), ".codex"),
environment,
),
@@ -2897,7 +2898,8 @@ export async function resolvePluginPython(
const home = options.homeDirectory ?? homedir();
const cacheDirectory =
- environmentValue(environment, "XDG_CACHE_HOME") || join(home, ".cache");
+ environmentValue(environment, "XDG_CACHE_HOME", true) ||
+ join(home, ".cache");
const managedRoots = options.managedRuntimeRoots ?? [
join(cacheDirectory, "codex-runtimes", "codex-primary-runtime"),
];
diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.ts
index 4ba52e932..0826b4ab4 100644
--- a/sdk/typescript/src/scan-comparison.ts
+++ b/sdk/typescript/src/scan-comparison.ts
@@ -1,6 +1,5 @@
import { existsSync } from "node:fs";
import { isRecord } from "./record.js";
-import { homedir } from "node:os";
import { dirname, join } from "node:path";
import {
Codex,
@@ -11,6 +10,7 @@ import {
type TurnOptions,
} from "@openai/codex-sdk";
import { z } from "incur";
+import { parse, stringify } from "smol-toml";
import type { CodexSecuritySurface, ScanAuthMode } from "./api.js";
import {
accountStatus,
@@ -51,7 +51,6 @@ import {
import {
codexSecurityCredentialHome,
executablePathForSpawn,
- expandHome,
prepareCodexSecurityCredentialHome,
resolveCodexCommand,
runCodexCommand,
@@ -565,7 +564,7 @@ async function startReadOnlyCodexThread(
const homeExecutionConfig = resolveCodexProfile(homeConfig);
normalizeLegacyWindowsSandboxOverride(homeExecutionConfig);
const providerConfig = resolveCommandAuthConfig(
- deepMerge(homeConfig, config ?? {}),
+ deepMerge(homeConfig, parse(stringify(config ?? {})) as JsonObject),
configuredCodexHome(source),
);
const suppliedConfig = resolveCodexProfile(
@@ -1222,11 +1221,7 @@ export async function comparisonEnvironment(
);
if (status.authenticated) return storedEnvironment;
}
- const configuredHome = environmentEntry(environment, "CODEX_HOME")?.trim();
- const codexHome = configuredHome
- ? expandHome(configuredHome, environment)
- : join(homedir(), ".codex");
- if (existsSync(join(codexHome, "auth.json"))) {
+ if (existsSync(join(home, "auth.json"))) {
return withoutOpenAiApiKeys(environment);
}
return environment;
diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.ts
index 0c295f6ef..12436ccfe 100644
--- a/sdk/typescript/tests-ts/api-credentials.test.ts
+++ b/sdk/typescript/tests-ts/api-credentials.test.ts
@@ -30,10 +30,13 @@ describe("CodexSecurity orchestration", () => {
"profile-inherited-cwd",
"profile-overridden-cwd",
"profile-strict",
+ "null optional args",
+ "null optional cwd",
])(
"runs native command authentication without importing credentials (%s)",
async (selection) => {
- const profile = selection !== "direct";
+ const profile =
+ selection === "profile" || selection.startsWith("profile-");
const profileProviders = profile && selection !== "profile";
const inheritedCwd = selection === "profile-inherited-cwd";
const overriddenCwd = selection === "profile-overridden-cwd";
@@ -51,9 +54,13 @@ describe("CodexSecurity orchestration", () => {
await writeFile(join(home, "auth.json"), '{"auth_mode":"chatgpt"}\n');
const auth = {
command: "./synthetic-auth",
- args: ["token"],
+ args: selection === "null optional args" ? null : ["token"],
refresh_interval_ms: 1000,
- ...(profile ? { cwd: "helpers" } : {}),
+ ...(profile
+ ? { cwd: "helpers" }
+ : selection === "null optional cwd"
+ ? { cwd: null }
+ : {}),
};
const definition = {
name: "Synthetic",
@@ -180,7 +187,9 @@ describe("CodexSecurity orchestration", () => {
const provider = {
...definition,
auth: {
- ...auth,
+ command: auth.command,
+ refresh_interval_ms: auth.refresh_interval_ms,
+ ...(auth.args === null ? {} : { args: auth.args }),
...(inheritedCwd || overriddenCwd
? { command: "./selected-auth" }
: {}),
@@ -603,7 +612,20 @@ describe("CodexSecurity orchestration", () => {
await writeFile(join(ambientHome, "auth.json"), ambientAuthentication);
const runs: Array<{ home: string; apiKey?: string }> = [];
const client = new TestClient(
- { pluginPath: PLUGIN_ROOT },
+ {
+ pluginPath: PLUGIN_ROOT,
+ codexOverrides: {
+ model_provider: "synthetic.account",
+ model_providers: {
+ "synthetic.account": {
+ name: "Synthetic account provider",
+ wire_api: "responses",
+ requires_openai_auth: true,
+ auth: null,
+ },
+ },
+ },
+ },
{
environment: {
CODEX_HOME: ambientHome,
diff --git a/sdk/typescript/tests-ts/api-preflight-config.test.ts b/sdk/typescript/tests-ts/api-preflight-config.test.ts
index 9b3df38c2..e1b90d3ed 100644
--- a/sdk/typescript/tests-ts/api-preflight-config.test.ts
+++ b/sdk/typescript/tests-ts/api-preflight-config.test.ts
@@ -70,6 +70,46 @@ function runPreflight(
}
describe("CodexSecurity preflight configuration", () => {
+ test.each([
+ ["model", { model: null }, true],
+ ["reasoning effort", { model_reasoning_effort: null }, true],
+ ["both", { model: null, model_reasoning_effort: null }, true],
+ ["defaults", { model: null, model_reasoning_effort: null }, false],
+ ] as const)(
+ "inherits %s when selected profile settings are null",
+ async (_name, profile, explicitRoot) => {
+ const root = await temporaryDirectory();
+ const repository = join(root, "repository");
+ await mkdir(repository);
+ await using client = new TestClient(
+ {
+ codexOverrides: {
+ ...(explicitRoot
+ ? { model: "gpt-5.6-terra", model_reasoning_effort: "low" }
+ : {}),
+ profile: "review",
+ profiles: { review: profile },
+ },
+ },
+ {
+ environment: { CODEX_SECURITY_STATE_DIR: join(root, "state") },
+ prepareRuntime: async () => {
+ throw new Error("Local preflight must not start the runtime");
+ },
+ },
+ );
+ for (const mode of ["standard", "deep"] as const) {
+ await expect(
+ client.preflight(repository, { mode }),
+ ).resolves.toMatchObject({
+ mode,
+ model: explicitRoot ? "gpt-5.6-terra" : "gpt-5.6-sol",
+ reasoningEffort: explicitRoot ? "low" : "xhigh",
+ });
+ }
+ },
+ );
+
test.each([
["standard", "openai.gpt-daybreak-blue-5.6-sol"],
["deep", "openai.gpt-daybreak-blue-5.6-sol"],
diff --git a/sdk/typescript/tests-ts/api-provider-isolation.test.ts b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
index d01072630..4ed84eeeb 100644
--- a/sdk/typescript/tests-ts/api-provider-isolation.test.ts
+++ b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
@@ -181,7 +181,13 @@ async function loadWorkerSettings(root: string) {
return workerRuntimeSettings;
}
-test.each(["root", "profile override", "profile only"] as const)(
+test.each([
+ "root",
+ "selected profile",
+ "null profile",
+ "profile override",
+ "profile only",
+] as const)(
"concurrent provider snapshots preserve %s credentials",
async (selection) => {
const root = await temporaryDirectory();
@@ -247,12 +253,12 @@ test.each(["root", "profile override", "profile only"] as const)(
: {
model_providers: {
openrouter:
- selection === "root"
- ? provider
- : {
+ selection === "profile override"
+ ? {
...provider,
env_key: "SYNTHETIC_UNUSED_KEY",
- },
+ }
+ : provider,
"required.gateway": {
name: "Managed selection",
wire_api: "responses",
@@ -268,15 +274,25 @@ test.each(["root", "profile override", "profile only"] as const)(
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",
- },
- },
+ ...(selection === "null profile"
+ ? {
+ model_provider: null,
+ model: null,
+ model_reasoning_effort: null,
+ }
+ : selection === "selected profile"
+ ? {}
+ : {
+ model_provider: "openrouter",
+ model_providers: {
+ openrouter: provider,
+ "required.gateway": {
+ name: "Managed selection",
+ wire_api: "responses",
+ env_key: "SYNTHETIC_REQUIRED_KEY",
+ },
+ },
+ }),
},
},
}),
@@ -820,7 +836,12 @@ for await (const line of createInterface({ input: process.stdin })) {
return plugin;
}
-test.each(["SYNTHETIC_CUSTOM_API_KEY", "CODEX_API_KEY"])(
+test.each([
+ "SYNTHETIC_CUSTOM_API_KEY",
+ "CODEX_API_KEY",
+ "OPENROUTER_API_KEY",
+ "FIREWORKS_API_KEY",
+])(
"native plugin workers recover the selected %s and other provider variables",
async (providerKey) => {
const root = await temporaryDirectory();
@@ -832,24 +853,36 @@ test.each(["SYNTHETIC_CUSTOM_API_KEY", "CODEX_API_KEY"])(
await mkdir(scan, { mode: 0o700 });
await mkdir(sourceHome, { mode: 0o700 });
const plugin = await createPluginProbe(root, report);
+ const external = ["OPENROUTER_API_KEY", "FIREWORKS_API_KEY"].includes(
+ providerKey,
+ );
+ const providerId = external
+ ? providerKey.split("_")[0]!.toLowerCase()
+ : "synthetic.gateway";
+ const headerKey =
+ process.platform === "win32"
+ ? "synthetic_custom_header"
+ : "SYNTHETIC_CUSTOM_HEADER";
const providerEnvironment = {
- [providerKey]: " synthetic-custom-key ",
- SYNTHETIC_CUSTOM_HEADER: " synthetic-custom-header ",
+ [providerKey]: external
+ ? " synthetic-custom-key\n"
+ : " synthetic-custom-key ",
+ [headerKey]: " synthetic-custom-header ",
SYNTHETIC_REQUIRED_KEY: "synthetic-required-key",
};
const client = new TestClient(
{
pluginPath: plugin,
codexOverrides: {
- model_provider: "synthetic.gateway",
+ model_provider: providerId,
model_providers: {
- "synthetic.gateway": {
+ [providerId]: {
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-Token": headerKey,
"X-Synthetic-Missing": "SYNTHETIC_UNSET_KEY",
},
},
@@ -867,6 +900,9 @@ test.each(["SYNTHETIC_CUSTOM_API_KEY", "CODEX_API_KEY"])(
CODEX_SECURITY_STATE_DIR: join(root, "state"),
OPENAI_API_KEY: "synthetic-account-key",
...providerEnvironment,
+ ...(process.platform === "win32"
+ ? { SYNTHETIC_CUSTOM_HEADER: " synthetic-child-header " }
+ : {}),
SYNTHETIC_UNUSED_KEY: "synthetic-unused-key",
},
resolvePluginPython: async () => "/managed/python",
@@ -876,7 +912,9 @@ test.each(["SYNTHETIC_CUSTOM_API_KEY", "CODEX_API_KEY"])(
startThread: () => ({
id: null,
async runStreamed() {
- expect(options.apiKey).toBe("synthetic-account-key");
+ expect(options.apiKey).toBe(
+ external ? undefined : "synthetic-account-key",
+ );
const status = await nativeRequest(
{
...options.env!,
@@ -905,6 +943,12 @@ test.each(["SYNTHETIC_CUSTOM_API_KEY", "CODEX_API_KEY"])(
},
recovered: {
...providerEnvironment,
+ ...(process.platform === "win32"
+ ? { [headerKey]: " synthetic-child-header " }
+ : {}),
+ ...(external
+ ? { [providerKey]: "synthetic-custom-key" }
+ : {}),
...(providerKey === "CODEX_API_KEY"
? { CODEX_API_KEY: "synthetic-account-key" }
: {}),
diff --git a/sdk/typescript/tests-ts/build-plugin.test.ts b/sdk/typescript/tests-ts/build-plugin.test.ts
index 7b9c08faf..149269de3 100644
--- a/sdk/typescript/tests-ts/build-plugin.test.ts
+++ b/sdk/typescript/tests-ts/build-plugin.test.ts
@@ -133,6 +133,13 @@ describe("bundled plugin build", () => {
"plugin-files.json",
await readFile(join(plugin, "plugin-files.json"), "utf8"),
);
+ for (const name of ["codex_profile.mjs", "codex_profile.d.mts"]) {
+ await writeFixture(
+ source,
+ `scripts/${name}`,
+ await readFile(join(plugin, "scripts", name), "utf8"),
+ );
+ }
const platformSource = join(source, "native", "platform.mts");
await writeFile(
platformSource,
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index 4b4885341..115335023 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -1252,6 +1252,30 @@ describe("CLI authentication", () => {
});
describe("skill authentication", () => {
+ test.each(["patch", "verify-fix"] as const)(
+ "%s inherits ambient command authentication through a null optional override",
+ async (command) => {
+ const result = await runProviderSkill(stateDirectory, {
+ command,
+ overrides: { model_providers: { gateway: { auth: null } } },
+ ambientConfig: [
+ 'model_provider="gateway"',
+ "[model_providers.gateway]",
+ 'name="Synthetic gateway"',
+ 'base_url="https://gateway.example.test/v1"',
+ 'wire_api="responses"',
+ "[model_providers.gateway.auth]",
+ 'command="synthetic-auth"',
+ ].join("\n"),
+ });
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.launch).toBeDefined();
+ expect(result.requests.map((request) => request.method)).not.toContain(
+ "account/login/start",
+ );
+ },
+ );
+
test.each([
["validate", "auto", "gateway"],
["validate", "api-key", "gateway"],
@@ -1291,6 +1315,47 @@ describe("skill authentication", () => {
},
);
+ for (const nullAuth of [false, true]) {
+ test.each(["validate", "patch", "verify-fix"] as const)(
+ `%s forwards a provider's OpenAI-named key (null auth: ${nullAuth})`,
+ async (command) => {
+ const stdout = capture();
+ const stderr = capture();
+ const status = await runCodexSkillCommand(
+ [
+ "-e",
+ 'console.log(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:JSON.stringify({key:process.env.OPENAI_API_KEY})}}))',
+ ],
+ {
+ command,
+ auth: "api-key",
+ modelProvider: "gateway",
+ codexOverrides: {
+ model_provider: "gateway",
+ model_providers: {
+ gateway: {
+ env_key: "OPENAI_API_KEY",
+ ...(nullAuth ? { auth: null } : {}),
+ },
+ },
+ },
+ stdout: stdout.stream,
+ stderr: stderr.stream,
+ },
+ { command: process.execPath },
+ {
+ CODEX_HOME: join(stateDirectory, "ambient"),
+ OPENAI_API_KEY: "SYNTHETIC_PROVIDER_KEY",
+ },
+ );
+ expect(status, stderr.text()).toBe(0);
+ expect(JSON.parse(stdout.text())).toEqual({
+ key: "SYNTHETIC_PROVIDER_KEY",
+ });
+ },
+ );
+ }
+
test("rejects a missing custom provider API key before launch", async () => {
const result = await runProviderSkill(stateDirectory, {
overrides: [
diff --git a/sdk/typescript/tests-ts/cloud-publish.test.ts b/sdk/typescript/tests-ts/cloud-publish.test.ts
index d931a3654..cf1a22921 100644
--- a/sdk/typescript/tests-ts/cloud-publish.test.ts
+++ b/sdk/typescript/tests-ts/cloud-publish.test.ts
@@ -75,10 +75,10 @@ async function csvFixture(contents = `${csvHeader}\n${csvRow}\n`) {
afterEach(cleanup);
-async function fixture() {
+async function fixture(homeName = "home") {
const root = await temporaryDirectory("codex-security-cloud-");
const scan = join(root, "scan");
- const home = join(root, "home");
+ const home = join(root, homeName);
await copyCompletedScanFixture(scan);
if (process.platform !== "win32") await chmod(scan, 0o700);
await mkdir(home, { mode: 0o700 });
@@ -366,7 +366,24 @@ describe("Cloud publication", () => {
});
test("posts validated findings and scan provenance with only ChatGPT access credentials", async () => {
- const { scan, environment } = await fixture();
+ const { scan, home, environment } = await fixture(
+ process.platform === "win32" ? "home" : " home ",
+ );
+ if (home !== home.trim()) {
+ await mkdir(home.trim(), { mode: 0o700 });
+ await writeFile(
+ join(home.trim(), "config.toml"),
+ 'cli_auth_credentials_store = "file"\n',
+ );
+ await writeFile(
+ join(home.trim(), "auth.json"),
+ JSON.stringify({
+ ...login,
+ tokens: { ...login.tokens, access_token: "wrong-trimmed-home-token" },
+ }),
+ { mode: 0o600 },
+ );
+ }
const manifest = JSON.parse(
await readFile(join(scan, "scan-manifest.json"), "utf8"),
);
diff --git a/sdk/typescript/tests-ts/config.test.ts b/sdk/typescript/tests-ts/config.test.ts
index 901687210..427f57513 100644
--- a/sdk/typescript/tests-ts/config.test.ts
+++ b/sdk/typescript/tests-ts/config.test.ts
@@ -6,6 +6,7 @@ import { scanRuntimeCodexConfig } from "../src/api.js";
import {
type JsonObject,
inlineToml,
+ modelProviderConfigOverride,
resolveCodexProfile,
scanModelConfiguration,
scanModelProvider,
@@ -31,13 +32,29 @@ 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] }]) {
+test("inline Codex overrides omit optional null fields like the file writer", async () => {
+ for (const value of [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,
+ expect(modelProviderConfigOverride({ model_providers: null })).toEqual([]);
+ const provider = {
+ fixture: {
+ auth: { command: "synthetic-helper", args: null },
+ enabled: true,
+ },
+ };
+ const root = await temporaryDirectory();
+ const config = await mergedCodexConfig({
+ codexOverrides: { model_providers: provider },
+ });
+ const path = join(root, "config.toml");
+ await writeCodexConfig(path, config);
+ const written = parse(await readFile(path, "utf8"));
+ expect(
+ parse(`model_providers = ${inlineToml(provider)}`)["model_providers"],
+ ).toEqual(written["model_providers"]);
+ expect(written["model_providers"]).toEqual({
+ fixture: { auth: { command: "synthetic-helper" }, enabled: true },
});
});
@@ -240,10 +257,15 @@ describe("Codex configuration", () => {
test("rejects invalid model settings from the selected Codex profile", async () => {
for (const [profile, message] of [
[{ model: " " }, "model must be a nonempty string"],
+ [{ model: 12 }, "model must be a nonempty string"],
[
{ model_reasoning_effort: " " },
"reasoning effort must be a nonempty string",
],
+ [
+ { model_reasoning_effort: false },
+ "reasoning effort must be a nonempty string",
+ ],
] as const) {
const config = await mergedCodexConfig({
codexOverrides: { profile: "review", profiles: { review: profile } },
@@ -253,6 +275,19 @@ describe("Codex configuration", () => {
}
});
+ test("still requires root model and effort when the profile omits them", async () => {
+ for (const field of ["model", "model_reasoning_effort"]) {
+ const config = await mergedCodexConfig({
+ codexOverrides: {
+ [field]: null,
+ profile: "review",
+ profiles: { review: { model: null, model_reasoning_effort: null } },
+ },
+ });
+ expect(() => scanModelConfiguration(config)).toThrow(ConfigurationError);
+ }
+ });
+
test("disables reasoning summaries by default for the selected Bedrock provider", async () => {
const scenarios: JsonObject[] = [
{ model_provider: "amazon-bedrock" },
diff --git a/sdk/typescript/tests-ts/provider-profile.test.ts b/sdk/typescript/tests-ts/provider-profile.test.ts
index 4f1f5c4f4..c1aa902a1 100644
--- a/sdk/typescript/tests-ts/provider-profile.test.ts
+++ b/sdk/typescript/tests-ts/provider-profile.test.ts
@@ -10,12 +10,15 @@ import {
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, expect, test } from "bun:test";
+import type { CodexOptions } from "@openai/codex-sdk";
import { parse } from "smol-toml";
import {
+ createProfileCodex,
createProviderProfile,
providerPreflightCommand,
} from "../src/provider-profile.js";
import { CodexLoginHandle } from "../src/auth.js";
+import { structuredCodexConfig } from "../src/config.js";
import {
bundledPluginRoot,
resolveCodexCommand,
@@ -48,7 +51,10 @@ const startupProvider = {
args: ["synthetic-command-secret"],
},
};
-const startupProviders = { "synthetic.gateway": startupProvider };
+const startupProviders = {
+ omitted: null,
+ "synthetic.gateway": startupProvider,
+};
test.each([
[
@@ -215,6 +221,72 @@ test.each([
},
);
+test("native profile turns omit optional null fields and retain array errors", async () => {
+ const home = await temporaryDirectory();
+ const script = join(home, "profile child.mjs");
+ await writeFile(
+ script,
+ `for await (const chunk of process.stdin) {}
+ console.log(JSON.stringify({ type: "thread.started", thread_id: "synthetic-thread" }));
+ console.log(JSON.stringify({ type: "item.completed", item: {
+ type: "agent_message", id: "answer", text: JSON.stringify(process.argv.slice(1)),
+ } }));
+ console.log(JSON.stringify({ type: "turn.completed", usage: { input_tokens: 1, output_tokens: 1 } }));
+ process.exit(0);`,
+ );
+ const node = Bun.which("node");
+ expect(node).not.toBeNull();
+ const options = {
+ codexPathOverride: node!,
+ env: {
+ ...process.env,
+ CODEX_HOME: home,
+ NODE_OPTIONS: `--import=${pathToFileURL(script).href}`,
+ },
+ };
+ const codex = await createProfileCodex(
+ {
+ ...options,
+ config: structuredCodexConfig({
+ model_provider: "synthetic.gateway",
+ service_tier: "fast",
+ profile: "review",
+ profiles: { review: { model_provider: null, service_tier: null } },
+ features: { plugins: false, optional: null },
+ nested: [{ enabled: true, optional: null }],
+ }) as CodexOptions["config"],
+ },
+ "synthetic-profile",
+ );
+ for (const resumed of [false, true]) {
+ const thread = resumed
+ ? codex.resumeThread("synthetic-thread")
+ : codex.startThread();
+ const result = await thread.run("synthetic prompt");
+ const args: string[] = JSON.parse(result.finalResponse);
+ const overrides = args.flatMap((arg, index) =>
+ arg === "--config" ? [args[index + 1]!] : [],
+ );
+ expect(parse(overrides.join("\n"))).toEqual({
+ model_provider: "synthetic.gateway",
+ service_tier: "fast",
+ features: { plugins: false },
+ nested: [{ enabled: true }],
+ });
+ expect(args.includes("resume")).toBe(resumed);
+ }
+ const invalid = await createProfileCodex(
+ {
+ ...options,
+ config: { invalid: [null] } as unknown as CodexOptions["config"],
+ },
+ "synthetic-profile",
+ );
+ await expect(invalid.startThread().run("synthetic prompt")).rejects.toThrow(
+ "Codex config overrides must contain finite TOML values",
+ );
+});
+
test("private profiles retain providers for native required and inherited selection", async () => {
const home = await temporaryDirectory();
const definitions = {
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 8605c755f..c039f1d94 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -88,6 +88,7 @@ import {
requireSecureOutputAncestry,
requireTrustedOutputAncestor,
runWorkbench,
+ workbenchEnvironment,
setCodexSecurityCredentialLogout,
streamWindowsCredentialAclDescriptors,
} from "../src/runtime.js";
@@ -5152,6 +5153,52 @@ describe("runtime directories and plugin Python boundary", () => {
}
});
+ testPosix.each(["absolute", "relative"])(
+ "shares literal CODEX_HOME paths with plugin storage (%s)",
+ async (kind) => {
+ const root = await temporaryDirectory();
+ const home = join(root, " selected home ");
+ const pluginRoot = join(root, "fixture-plugin");
+ await mkdir(home);
+ await mkdir(join(root, " selected home"));
+ await mkdir(join(pluginRoot, "scripts"), { recursive: true });
+ const script = join(pluginRoot, "scripts", "workbench_db.py");
+ await writeFile(
+ script,
+ [
+ "import json, runpy",
+ `storage = runpy.run_path(${JSON.stringify(join(PLUGIN_ROOT, "scripts", "workbench", "storage.py"))})`,
+ "print(json.dumps({'stateDir': str(storage['state_dir']())}))",
+ ].join("\n"),
+ );
+ const python = await resolvePluginPython();
+ const environment = {
+ PATH: process.env["PATH"],
+ CODEX_HOME: kind === "absolute" ? home : relative(process.cwd(), home),
+ };
+ const direct = spawnSync(python, ["-I", "-B", script], {
+ env: environment,
+ encoding: "utf8",
+ });
+ expect(direct.status, direct.stderr).toBe(0);
+ const expected = {
+ stateDir: join(home, "state", "plugins", "codex-security"),
+ };
+ expect(JSON.parse(direct.stdout)).toEqual(expected);
+ expect(
+ await runWorkbench(
+ {
+ python,
+ pluginRoot,
+ environment: workbenchEnvironment(environment),
+ },
+ ["test-command"],
+ ),
+ ).toEqual(expected);
+ expect(codexSecurityStateDirectory(environment)).toBe(expected.stateDir);
+ },
+ );
+
test("runs workbench commands without output limits, credentials, or generated bytecode", async () => {
const root = await temporaryDirectory();
const pluginRoot = join(root, "plugin");
@@ -6236,20 +6283,22 @@ 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);
+ for (const name of ["custom-cache", "custom-cache "]) {
+ const cacheDirectory = join(root, name);
+ 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,
diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.ts
index 9d1aca6f6..99f3a6f48 100644
--- a/sdk/typescript/tests-ts/scan-comparison.test.ts
+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts
@@ -30,7 +30,7 @@ import {
resolveCodexCommand,
runCodexCommand,
} from "../src/runtime.js";
-import { resolveCommandAuthConfig } from "../src/config.js";
+import { resolveCommandAuthConfig, type JsonObject } from "../src/config.js";
import * as providerProfiles from "../src/provider-profile.js";
import {
comparisonForScan,
@@ -887,9 +887,21 @@ describe("semantic scan comparison", () => {
test.each(["home", "home-override", "profile", "overrides", "override-away"])(
"preserves native command auth selection from %s",
async (selection) => {
- const home = await temporaryDirectory(
+ const root = await temporaryDirectory(
"codex-security-command-comparison-",
);
+ const home =
+ selection === "home" && process.platform !== "win32"
+ ? join(root, " selected home ")
+ : root;
+ if (home !== root) {
+ await mkdir(home, { mode: 0o700 });
+ await mkdir(home.trim());
+ await writeFile(
+ join(home.trim(), "config.toml"),
+ 'model_provider = "openai"\n',
+ );
+ }
const commandAuth = selection !== "override-away";
const provider = {
name: "Synthetic",
@@ -1230,13 +1242,24 @@ describe("semantic scan comparison", () => {
codex.startThread(options!) as ReturnType<Codex["startThread"]>,
);
try {
- await expect(
- matchScanFindings(
- { before: [finding("before")], after: [finding("after")] },
- options,
- ),
- ).rejects.toThrow("conflicts with command authentication");
- expect(startThread).not.toHaveBeenCalled();
+ for (const codexOverrides of [
+ {},
+ { model_providers: { synthetic: { auth: null } } },
+ { model_providers: null },
+ {
+ profile: "review",
+ profiles: { review: { model_provider: "synthetic" } },
+ model_providers: { synthetic: { auth: null } },
+ },
+ ] as JsonObject[]) {
+ await expect(
+ matchScanFindings(
+ { before: [finding("before")], after: [finding("after")] },
+ { ...options, config: { codexOverrides } },
+ ),
+ ).rejects.toThrow("conflicts with command authentication");
+ expect(startThread).not.toHaveBeenCalled();
+ }
// A complete command provider selected by the caller keeps scan precedence.
await matchScanFindings(
@@ -1567,6 +1590,24 @@ describe("semantic scan comparison", () => {
expect(environment["CODEX_HOME"]).toBe(ambientHome);
});
+ test.skipIf(process.platform === "win32")(
+ "recognizes stored credentials in a literal spaced home",
+ async () => {
+ const root = await temporaryDirectory("codex-security-spaced-home-");
+ const home = join(root, " selected home ");
+ await mkdir(home);
+ await mkdir(home.trim());
+ await writeFile(join(home, "auth.json"), "{}");
+ const environment = await comparisonEnvironment({
+ CODEX_HOME: home,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ OPENAI_API_KEY: "",
+ });
+ expect(environment["CODEX_HOME"]).toBe(home);
+ expect(environment["OPENAI_API_KEY"]).toBeUndefined();
+ },
+ );
+
test.skipIf(process.platform !== "win32")(
"recognizes stored credentials under a backslash home-relative path",
async () => {
diff --git a/sdk/typescript/tests-ts/support/cli-provider-authentication.ts b/sdk/typescript/tests-ts/support/cli-provider-authentication.ts
index 7be95737a..284289029 100644
--- a/sdk/typescript/tests-ts/support/cli-provider-authentication.ts
+++ b/sdk/typescript/tests-ts/support/cli-provider-authentication.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect } from "bun:test";
import { main, runCodexSkillCommand } from "../../src/cli.js";
+import type { JsonObject } from "../../src/index.js";
import { dependencies as cliDependencies } from "../cli-fixtures.js";
import { createCliTest } from "./cli-run.js";
import { readJsonLines } from "./json.js";
@@ -20,7 +21,7 @@ export async function runProviderSkill(
}: {
command?: "validate" | "patch" | "verify-fix";
auth?: "auto" | "chatgpt" | "api-key";
- overrides: readonly string[];
+ overrides: readonly string[] | JsonObject;
environment?: NodeJS.ProcessEnv;
ambientConfig?: string;
storedCredentials?: boolean;
@@ -52,7 +53,9 @@ export async function runProviderSkill(
"Synthetic issue",
"--auth",
auth,
- ...overrides.flatMap((value) => ["--codex", value]),
+ ...(Array.isArray(overrides)
+ ? overrides.flatMap((value) => ["--codex", value])
+ : []),
],
cliDependencies({
currentDirectory: repository,
@@ -64,6 +67,8 @@ export async function runProviderSkill(
SYNTHETIC_SKILL_COMMAND: command,
},
onCodex: async (args, output, environment, input) => {
+ if (!Array.isArray(overrides) && output !== undefined)
+ output = { ...output, codexOverrides: overrides as JsonObject };
const originalOverrides = structuredClone(output?.codexOverrides);
const result = await runCodexSkillCommand(
[