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(auth): honor native provider API-key settings for scans (#139)

Alessio Doriadc63c5defe07
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 bcf54cfcf..d9ce81d57 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/executor.ts
@@ -76,6 +76,7 @@ export interface CodexSdkWorkerArtifactContext {
}
interface CodexSdkWorkerRuntimeSettings {
+ hasProviderEnvKey?: boolean;
environment?: Record<string, string>;
config: Record<string, unknown>;
preflightProviderOverrides?: string[];
@@ -290,7 +291,9 @@ export class CodexSdkWorkerExecutor implements CodexWorkerExecutor {
await preflightDeepScanWorkerPermissionProfile({
...preflightOptions,
expectedProfile: workerProfile,
- allowOpenAiApiKeyFallback: Boolean(openAiApiKey && !codexApiKey),
+ allowOpenAiApiKeyFallback: Boolean(
+ openAiApiKey && !codexApiKey && !runtimeSettings.hasProviderEnvKey,
+ ),
});
const inheritedServers = new Set([
...mcpServerNames,
@@ -738,6 +741,23 @@ export async function workerRuntimeSettings(
);
}
if (isRecord(nativeProfileConfig.model_providers)) {
+ const providerId = workerConfig.model_provider ?? selected.model_provider;
+ const provider =
+ typeof providerId === "string"
+ ? nativeProfileConfig.model_providers[providerId]
+ : undefined;
+ if (
+ isRecord(provider) &&
+ typeof provider.env_key === "string" &&
+ provider.auth == null
+ ) {
+ settings.hasProviderEnvKey =
+ environmentVariable(
+ settings.environment ?? {},
+ provider.env_key,
+ process.platform,
+ ) !== undefined;
+ }
const providers = preflightProviderDefinitions(
nativeProfileConfig.model_providers,
);
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 b673a0600..c70fab0d7 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
@@ -2731,19 +2731,28 @@ async function testBedrockCredentialsReachWorker(
}
async function testExternalProviderCredentialsReachWorker() {
- for (const [provider, key] of [
+ for (const [provider, key, headerKey] of [
["openrouter", "OPENROUTER_API_KEY"],
["fireworks", "FIREWORKS_API_KEY"],
- ]) {
- await withWorkerFixture(async (fixture, promptPath, workingDirectory) => {
+ ["synthetic", "SYNTHETIC_GATEWAY_KEY", "CODEX_API_KEY"],
+ ["synthetic", "SYNTHETIC_GATEWAY_KEY", "OPENAI_API_KEY"],
+ ] as const) {
+ const verifyCredentials: Parameters<typeof withWorkerFixture>[0] = async (
+ fixture,
+ promptPath,
+ workingDirectory,
+ ) => {
const configPath = path.join(fixture.root, "provider.toml");
const deepPath = path.join(fixture.root, "workers.toml");
const profile = `scan-${provider}`;
const selectedKey = `synthetic-${provider}-scan-key`;
+ const accountHeaders = headerKey
+ ? { [headerKey]: "private-scan-header" }
+ : {};
const settings = {
model_provider: provider,
native_profile: profile,
- environment: { [key]: selectedKey },
+ environment: { [key]: selectedKey, ...accountHeaders },
};
await writeFile(configPath, stringifyToml({ model_provider: provider }));
await writeFile(deepPath, stringifyToml({ worker_runtime: settings }));
@@ -2757,11 +2766,18 @@ async function testExternalProviderCredentialsReachWorker() {
base_url: `https://${provider}.example.test/v1`,
wire_api: "responses",
env_key: key,
+ ...(headerKey === "OPENAI_API_KEY"
+ ? { requires_openai_auth: true }
+ : {}),
+ ...(headerKey
+ ? { env_http_headers: { "X-Scan-Header": headerKey } }
+ : {}),
},
},
}),
);
- await writeFile(promptPath, "synthetic provider credential fixture");
+ const prompt = "CAPTURE_SYNTHETIC_OPENAI_AUTH";
+ await writeFile(promptPath, prompt);
const environment = {
CODEX_HOME: fixture.root,
CODEX_SECURITY_CONFIG_PATH: configPath,
@@ -2770,53 +2786,49 @@ async function testExternalProviderCredentialsReachWorker() {
CODEX_API_KEY: undefined,
OPENROUTER_API_KEY: undefined,
FIREWORKS_API_KEY: undefined,
+ SYNTHETIC_GATEWAY_KEY: undefined,
};
const saved = Object.keys(environment).map(
(name) => [name, process.env[name]] as const,
);
- const originalSpawn = childProcess.spawn;
- const launches: {
- args: readonly string[];
- environment: NodeJS.ProcessEnv;
- }[] = [];
try {
for (const [name, value] of Object.entries(environment))
restoreEnv(name, value);
- childProcess.spawn = ((
- command: string,
- args: readonly string[],
- options: SpawnOptions,
- ) => {
- if (args[0] === "exec")
- launches.push({ args, environment: { ...options.env } });
- return originalSpawn(command, args, options);
- }) as typeof childProcess.spawn;
- syncBuiltinESMExports();
const executor = new CodexSdkWorkerExecutor({
parentSandbox: trustedParentSandbox,
});
- for (const resumeThreadId of [undefined, "fixture-provider-resume"]) {
- launches.length = 0;
+ for (const turn of ["fresh", "resume", "compare"]) {
process.env[key] = "changed-ambient-key";
- await executor.run(
- workerRequest(promptPath, workingDirectory, {
- resumeThreadId,
- }),
+ if (headerKey) process.env[headerKey] = "changed-ambient-header";
+ if (turn === "compare") {
+ await executor.compareFindings(
+ prompt,
+ workingDirectory,
+ new AbortController().signal,
+ { type: "object" },
+ );
+ } else {
+ await executor.run(
+ workerRequest(promptPath, workingDirectory, {
+ resumeThreadId:
+ turn === "resume" ? "fixture-provider-resume" : undefined,
+ }),
+ );
+ }
+ const invocation = await readJson(fixture.markerPath);
+ assert.equal(
+ invocation.providerKey ?? invocation.providerHeaders[key],
+ selectedKey,
);
- assert.equal(launches.length, 1);
- const launch = launches[0];
- assert.equal(launch.environment[key], selectedKey);
- assert.equal(launch.environment.OPENAI_API_KEY, undefined);
- assert.equal(launch.environment.CODEX_API_KEY, undefined);
- assertFlagPair(launch.args, "--profile", profile);
- assertConfigOverrides(launch.args, {
+ assert.deepEqual(invocation.openaiAuthentication, accountHeaders);
+ assertFlagPair(invocation.argv, "--profile", profile);
+ assertConfigOverrides(invocation.argv, {
model_provider: provider,
"mcp_servers.codex-security.enabled": false,
+ "responses_api_metadata.codex_security_worker_role":
+ turn === "compare" ? "compare" : "discovery",
});
- assert.equal(
- launch.args.includes("resume"),
- resumeThreadId !== undefined,
- );
+ assert.equal(invocation.argv.includes("resume"), turn === "resume");
await writeFile(
deepPath,
stringifyToml({
@@ -2828,10 +2840,12 @@ async function testExternalProviderCredentialsReachWorker() {
);
}
} finally {
- childProcess.spawn = originalSpawn;
- syncBuiltinESMExports();
for (const [name, value] of saved) restoreEnv(name, value);
}
+ };
+ await withWorkerFixture(verifyCredentials, undefined, true, {
+ account: null,
+ requiresOpenaiAuth: headerKey === "OPENAI_API_KEY",
});
}
}
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 8bf0d386d..e98b1d3aa 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -104,6 +104,13 @@ the stored login. Patch follow-up assessments and `scan --patch` retain the
chosen authentication. Environment keys do not replace the saved login.
The SDK uses `auth` on `run()`, `validate()`, and `preflight()`.
+For a scan using a custom native provider, `auto` and `api-key` use the
+environment variable declared by `model_providers.<id>.env_key`, including
+when a Codex file profile selects that provider. Set that variable before
+starting the scan. To use `--auth chatgpt`, select a provider configured for
+account authentication. A custom provider that requires its own key cannot
+honor that combination.
+
Stored OpenAI credentials live in
`$CODEX_SECURITY_STATE_DIR/codex-home`, or
`$CODEX_HOME/state/plugins/codex-security/codex-home`. Keep this private home
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 3cada68ed..4c6004641 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -67,6 +67,7 @@ import {
NO_CREDENTIALS_MESSAGE,
accountStatus,
configuredCodexHome,
+ environmentEntry,
CodexLoginHandle,
loginApiKey as persistApiKey,
logout as codexLogout,
@@ -341,12 +342,8 @@ interface PreparedSession {
preflightConfig: JsonObject;
sessionConfig: JsonObject;
modelProvider: unknown;
- externalProvider:
- | (Omit<
- (typeof EXTERNAL_CODEX_PROVIDERS)[keyof typeof EXTERNAL_CODEX_PROVIDERS],
- "env_key"
- > & { env_key: string })
- | null;
+ providerEnvKey?: string;
+ nativeProviderEnvironment?: Record<string, string>;
apiKey: string | null;
scanEnvironment: ProcessEnvironment;
authentication: ScanAuthentication;
@@ -987,10 +984,14 @@ export class CodexSecurity {
);
const git = await inspectTrustedExecutable(
"git",
- selectedScanEnvironment(
- runtime.environment,
- options.auth,
- session.modelProvider,
+ withoutProviderKey(
+ selectedScanEnvironment(
+ runtime.environment,
+ options.auth,
+ session.modelProvider,
+ session.providerEnvKey,
+ ),
+ session.providerEnvKey,
),
[
(await gitMarkerRoot(inputs.repository, signal, "outermost")) ??
@@ -2187,11 +2188,14 @@ export class CodexSecurity {
} = session;
let git: InspectedExecutable = {
executable: null,
- environment: selectedScanEnvironment(
- runtime.environment,
- options.auth,
- modelProvider,
- session.externalProvider?.env_key,
+ environment: withoutProviderKey(
+ selectedScanEnvironment(
+ runtime.environment,
+ options.auth,
+ modelProvider,
+ session.providerEnvKey,
+ ),
+ session.providerEnvKey,
),
};
for (const root of [
@@ -2253,14 +2257,13 @@ export class CodexSecurity {
runtime.environment,
options.auth,
modelProvider,
- session.externalProvider?.env_key,
+ session.providerEnvKey,
),
),
...(session.apiKey === null
? {}
: {
- [session.externalProvider?.env_key ?? "CODEX_API_KEY"]:
- session.apiKey,
+ [session.providerEnvKey ?? "CODEX_API_KEY"]: session.apiKey,
}),
};
const { environment: workerEnvironment, ...workerRuntimeConfig } =
@@ -2269,6 +2272,7 @@ export class CodexSecurity {
modelProvider,
scanDir,
workerProviderEnvironment,
+ session.nativeProviderEnvironment,
);
const sqliteHome = workerRuntimeConfig["sqlite_home"];
const sqliteEnvironment: Record<string, string> =
@@ -3640,6 +3644,7 @@ export class CodexSecurity {
{
surface: this.#surface,
singleTurn: options.maxCostUsd !== undefined,
+ nativeProviderEnvironment: session.nativeProviderEnvironment,
},
),
...inferenceOptions,
@@ -4169,7 +4174,7 @@ export class CodexSecurity {
runtimeHome,
python,
modelProvider,
- externalProvider,
+ providerEnvKey,
apiKey,
sessionConfig,
} = session;
@@ -4185,15 +4190,13 @@ export class CodexSecurity {
: runtime.environment,
auth,
modelProvider,
- externalProvider?.env_key,
+ providerEnvKey,
),
),
),
git,
),
- ...(externalProvider === null
- ? {}
- : { [externalProvider.env_key]: apiKey! }),
+ ...(providerEnvKey === undefined ? {} : { [providerEnvKey]: apiKey! }),
CODEX_HOME: runtime.codexHome,
...runtimePaths,
};
@@ -4238,10 +4241,9 @@ export class CodexSecurity {
? undefined
: this.#codexCommand().command;
let sdkEnvironment = definedEnvironment({
+ ...session.nativeProviderEnvironment,
...withoutOpenAiApiKeys(environment),
- ...(externalProvider === null
- ? {}
- : { [externalProvider.env_key]: apiKey! }),
+ ...(providerEnvKey === undefined ? {} : { [providerEnvKey]: apiKey! }),
});
if (
process.platform === "win32" &&
@@ -4258,7 +4260,7 @@ export class CodexSecurity {
...(codexPathOverride === undefined
? {}
: { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
- ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
+ ...(providerEnvKey !== undefined || apiKey === null ? {} : { apiKey }),
...(runtime.providerProfile === undefined
? {}
: { nativeProfile: runtime.providerProfile.name }),
@@ -4337,7 +4339,6 @@ export class CodexSecurity {
preflightConfig,
sessionConfig: preflightConfig,
modelProvider: "host",
- externalProvider: null,
apiKey: null,
scanEnvironment: environment,
authentication: { method: "host", verified: false },
@@ -4360,27 +4361,23 @@ export class CodexSecurity {
);
const commandAuth = hasCommandAuth(requestedConfig);
const modelProvider = scanModelProvider(requestedConfig);
- const externalProvider =
- !commandAuth && isExternalModelProvider(modelProvider)
- ? {
- ...EXTERNAL_CODEX_PROVIDERS[modelProvider],
- env_key: scanProviderEnvKey(requestedConfig)!,
- }
- : null;
+ const providerEnvKey = commandAuth
+ ? undefined
+ : scanProviderEnvKey(requestedConfig);
let authentication = scanAuthentication(
this.#dependencies.environment,
options.auth,
modelProvider,
commandAuth,
false,
- externalProvider?.env_key,
+ providerEnvKey,
);
const apiKey =
authentication.method === "api_key"
? environmentApiKey(
this.#dependencies.environment,
modelProvider,
- externalProvider?.env_key,
+ providerEnvKey,
)
: null;
const scanEnvironment = selectedScanEnvironment(
@@ -4389,7 +4386,7 @@ export class CodexSecurity {
: this.#dependencies.environment,
options.auth,
modelProvider,
- externalProvider?.env_key,
+ providerEnvKey,
);
if (this.#dependencies.prepareRuntime === undefined) {
const credentialHome = await prepareCodexSecurityCredentialHome(
@@ -4487,7 +4484,7 @@ export class CodexSecurity {
}
await releaseCredentialHome?.();
releaseCredentialHome = null;
- if (externalProvider === null && apiKey !== null) {
+ if (providerEnvKey === undefined && apiKey !== null) {
this.#runtimeCredentialSource = "api_key";
}
if (
@@ -4518,7 +4515,7 @@ export class CodexSecurity {
runtime.codexHome,
options.auth,
modelProvider,
- externalProvider?.env_key,
+ providerEnvKey,
);
if (
options.safetyIdentifier !== undefined &&
@@ -4533,11 +4530,15 @@ export class CodexSecurity {
);
}
notifyObserver(options, "onAuthentication")(authentication);
+ const helperEnvironment = withoutProviderKey(
+ scanEnvironment,
+ providerEnvKey,
+ );
const python = await (
this.#dependencies.resolvePluginPython ?? resolvePluginPython
)({
configuredPath: this.config.pythonPath,
- environment: scanEnvironment,
+ environment: helperEnvironment,
protectedRoot,
signal,
});
@@ -4550,9 +4551,23 @@ export class CodexSecurity {
preflightConfig,
sessionConfig,
modelProvider,
- externalProvider,
+ providerEnvKey,
+ nativeProviderEnvironment:
+ providerEnvKey !== undefined &&
+ apiKey !== null &&
+ !isExternalModelProvider(modelProvider)
+ ? {
+ ...declaredProviderEnvironment(providers, {
+ ...(options.auth === "chatgpt"
+ ? withoutOpenAiApiKeys(this.#dependencies.environment)
+ : this.#dependencies.environment),
+ ...withoutOpenAiApiKeys(runtime.environment),
+ }),
+ [providerEnvKey]: apiKey,
+ }
+ : undefined,
apiKey,
- scanEnvironment,
+ scanEnvironment: helperEnvironment,
authentication,
approvalPolicy,
python,
@@ -5057,13 +5072,14 @@ export class CodexSecurity {
return await this.#dependencies.prepareRuntime(this.config, signal);
}
const modelProvider = scanModelProvider(requestedConfig);
+ const providerEnvKey = scanProviderEnvKey(requestedConfig);
const processEnvironment = selectedScanEnvironment(
hasCommandAuth(requestedConfig)
? withoutOpenAiApiKeys(this.#dependencies.environment)
: this.#dependencies.environment,
auth,
modelProvider,
- scanProviderEnvKey(requestedConfig),
+ providerEnvKey,
);
const codexHome = await realpath(
codexSecurityCredentialHome(processEnvironment),
@@ -5118,7 +5134,7 @@ export class CodexSecurity {
: join(deepScanConfigDirectory, "deep-scan-config.toml");
const credentialsAvailable =
hasCommandAuth(requestedConfig) ||
- isExternalModelProvider(modelProvider) ||
+ providerEnvKey !== undefined ||
modelProvider === "amazon-bedrock"
? false
: await initialCredentialsAvailable(
@@ -5973,32 +5989,31 @@ export function scanAuthentication(
verified: false,
};
}
- if (auth === "chatgpt" && !isExternalModelProvider(modelProvider)) {
+ const provider = isExternalModelProvider(modelProvider)
+ ? EXTERNAL_CODEX_PROVIDERS[modelProvider]
+ : undefined;
+ const selectedKey = providerEnvKey ?? provider?.env_key;
+ if (auth === "chatgpt" && provider === undefined) {
+ if (selectedKey !== undefined)
+ throw new ConfigurationError(
+ `ChatGPT authentication cannot use the ${modelProvider} provider's required ${selectedKey} environment key. Use '--auth api-key' or choose a provider configured for ChatGPT.`,
+ );
return { method: "stored_credentials", verified: false };
}
- const key = environmentApiKeyEntry(
- environment,
- modelProvider,
- providerEnvKey,
- );
- if (key === null && isExternalModelProvider(modelProvider)) {
- const provider = EXTERNAL_CODEX_PROVIDERS[modelProvider];
+ const key = environmentApiKeyEntry(environment, modelProvider, selectedKey);
+ if (key === null && selectedKey !== undefined) {
if (preflight && auth === "auto") {
return {
method: "api_key",
- source: providerEnvKey ?? provider.env_key,
+ source: selectedKey,
verified: false,
};
}
throw new AuthenticationRequiredError(
- `Set ${providerEnvKey ?? provider.env_key} to run a scan through ${provider.name}.`,
+ `Set ${selectedKey} to run a scan through ${provider?.name ?? modelProvider}.`,
);
}
- if (
- auth === "api-key" &&
- key === null &&
- !isExternalModelProvider(modelProvider)
- ) {
+ if (auth === "api-key" && key === null) {
throw new AuthenticationRequiredError(
"API-key authentication requires OPENAI_API_KEY or CODEX_API_KEY. " +
"Set a valid API key or use '--auth chatgpt'.",
@@ -6063,20 +6078,32 @@ export async function runtimeScanAuthentication(
return authentication;
}
+/** Local helpers do not authenticate model requests. */
+function withoutProviderKey(
+ environment: ProcessEnvironment,
+ key: string | undefined,
+): ProcessEnvironment {
+ if (key === undefined) return environment;
+ const child = { ...environment };
+ for (const name of Object.keys(child)) {
+ if (name.toUpperCase() === key.toUpperCase()) delete child[name];
+ }
+ forwardExternalImportSetting(environment, child);
+ return child;
+}
+
/** @internal */
export function selectedScanEnvironment(
environment: ProcessEnvironment,
auth: ScanAuthMode = "auto",
modelProvider?: unknown,
providerEnvKey?: string,
+ config?: JsonObject,
): ProcessEnvironment {
const standardProviderKey = isExternalModelProvider(modelProvider)
? EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key
: null;
- const selectedProviderKey =
- standardProviderKey === null
- ? null
- : (providerEnvKey ?? standardProviderKey);
+ const selectedProviderKey = providerEnvKey ?? standardProviderKey;
const bedrockProvider = modelProvider === "amazon-bedrock";
if (auth !== "chatgpt" && selectedProviderKey === null && !bedrockProvider) {
return environment;
@@ -6105,6 +6132,20 @@ export function selectedScanEnvironment(
return true;
}),
);
+ if (
+ config !== undefined &&
+ providerEnvKey !== undefined &&
+ standardProviderKey === null &&
+ !hasCommandAuth(config)
+ ) {
+ Object.assign(
+ selected,
+ declaredProviderEnvironment(
+ resolveCodexProfile(config)["model_providers"],
+ auth === "chatgpt" ? withoutOpenAiApiKeys(environment) : environment,
+ ),
+ );
+ }
forwardExternalImportSetting(environment, selected);
return selected;
}
@@ -6213,9 +6254,14 @@ function environmentApiKeyEntry(
modelProvider?: unknown,
providerEnvKey?: string,
): { source: string; value: string } | null {
- const keys = isExternalModelProvider(modelProvider)
- ? [providerEnvKey ?? EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key]
- : (["OPENAI_API_KEY", "CODEX_API_KEY"] as const);
+ if (providerEnvKey !== undefined && !isExternalModelProvider(modelProvider)) {
+ const value = environmentEntry(environment, providerEnvKey);
+ return value?.trim() ? { source: providerEnvKey, value } : null;
+ }
+ const keys =
+ providerEnvKey === undefined
+ ? ["OPENAI_API_KEY", "CODEX_API_KEY"]
+ : [providerEnvKey];
for (const requested of keys) {
const value = environmentValue(environment, requested)?.trim();
if (value) return { source: requested, value };
@@ -6686,18 +6732,11 @@ async function requireCurrentDeepScanPlugin(
}
}
-function selectedWorkerRuntimeConfig(
- config: JsonObject,
- selectedProvider: unknown,
- workingDirectory: string,
+function declaredProviderEnvironment(
+ providers: unknown,
environment: ProcessEnvironment,
-): JsonObject {
- const provider =
- typeof selectedProvider === "string" ? selectedProvider : undefined;
- const resolved = resolveCodexProfile(config);
- resolveNestedConfigPaths(resolved, workingDirectory);
- const providers = resolved["model_providers"];
- const providerEnvironmentNames = isRecord(providers)
+): Record<string, string> {
+ const names = isRecord(providers)
? Object.values(providers)
.flatMap((providerConfig) =>
isRecord(providerConfig)
@@ -6711,8 +6750,8 @@ function selectedWorkerRuntimeConfig(
)
.filter((name): name is string => typeof name === "string")
: [];
- const providerEnvironment = Object.fromEntries(
- providerEnvironmentNames.flatMap((name) => {
+ return Object.fromEntries(
+ names.flatMap((name) => {
const key =
process.platform === "win32"
? Object.keys(environment)
@@ -6723,6 +6762,23 @@ function selectedWorkerRuntimeConfig(
return value === undefined ? [] : [[name, value]];
}),
);
+}
+
+function selectedWorkerRuntimeConfig(
+ config: JsonObject,
+ selectedProvider: unknown,
+ workingDirectory: string,
+ environment: ProcessEnvironment,
+ nativeProviderEnvironment?: Record<string, string>,
+): JsonObject {
+ const provider =
+ typeof selectedProvider === "string" ? selectedProvider : undefined;
+ const resolved = resolveCodexProfile(config);
+ resolveNestedConfigPaths(resolved, workingDirectory);
+ const providers = resolved["model_providers"];
+ const providerEnvironment =
+ nativeProviderEnvironment ??
+ declaredProviderEnvironment(providers, environment);
// Workers use separate directories; preserve the parent scan's native paths.
for (const key of [...MODEL_FILE_SETTINGS, "sqlite_home"]) {
const file = resolved[key];
@@ -6840,7 +6896,8 @@ function standaloneFindingForPrompt(finding: string | object): string {
return jsonForPrompt(finding);
}
-function definedEnvironment(
+/** @internal */
+export function definedEnvironment(
environment: ProcessEnvironment,
): Record<string, string> {
const child = Object.fromEntries(
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index f9aa8bec8..97adc7705 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -1656,7 +1656,6 @@ export async function runCodexSkillCommand(
codexHome,
output.auth,
provider,
- providerEnvKey,
);
if (output.appServer !== undefined) {
const controller = new AbortController();
@@ -4723,11 +4722,10 @@ export async function main(
config,
scanCodexHome(dependencies.environment),
);
- if (hasCommandAuth(effectiveConfig)) return auth;
return await chooseInteractiveAuthentication(
{
auth,
- provider: scanModelProvider(effectiveConfig),
+ config: effectiveConfig,
command: "policy",
signal,
},
@@ -9781,24 +9779,25 @@ function diagnosticValue(value: unknown): string {
async function chooseInteractiveAuthentication(
options: {
auth: ScanAuthMode | undefined;
- provider: unknown;
+ config: JsonObject;
command: "scan" | "policy";
signal: AbortSignal;
},
errorOutput: Writable,
dependencies: CliDependencies,
): Promise<ScanAuthMode | undefined> {
- const { auth, provider, signal } = options;
+ const { auth, config, signal } = options;
if (
errorOutput.isTTY !== true ||
- isExternalModelProvider(provider) ||
+ hasCommandAuth(config) ||
+ scanProviderEnvKey(config) !== undefined ||
(auth !== undefined && auth !== "auto")
)
return auth;
const authentication = scanAuthentication(
dependencies.environment,
auth,
- provider,
+ scanModelProvider(config),
);
if (authentication.method !== "api_key") return auth;
const prompt =
@@ -10061,7 +10060,7 @@ async function executeScan(
? await chooseInteractiveAuthentication(
{
auth: arguments_.auth,
- provider,
+ config: effectiveConfiguration,
command: "scan",
signal: preparationAbortController.signal,
},
diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.ts
index e51b675af..605726d86 100644
--- a/sdk/typescript/src/component-scan.ts
+++ b/sdk/typescript/src/component-scan.ts
@@ -169,6 +169,7 @@ export async function runComponentScans(
auth,
provider,
providerEnvKey,
+ configuration,
);
}
const repository = await normalizeRepository(
diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.ts
index a3c900f8c..1ffa9d0f6 100644
--- a/sdk/typescript/src/config.ts
+++ b/sdk/typescript/src/config.ts
@@ -127,12 +127,18 @@ export function scanProviderEnvKey(
config: Readonly<JsonObject>,
): string | undefined {
const selected = scanModelProvider(config);
- if (!isExternalModelProvider(selected)) return undefined;
+ if (
+ typeof selected !== "string" ||
+ ["openai", "ollama", "lmstudio", "amazon-bedrock"].includes(selected)
+ )
+ return undefined;
const providers = resolveCodexProfile(config)["model_providers"];
const provider = isObject(providers) ? providers[selected] : undefined;
return isObject(provider) && typeof provider["env_key"] === "string"
? provider["env_key"]
- : EXTERNAL_CODEX_PROVIDERS[selected].env_key;
+ : isExternalModelProvider(selected)
+ ? EXTERNAL_CODEX_PROVIDERS[selected].env_key
+ : undefined;
}
/** @internal Native Codex validates the auth table, including invalid selections. */
diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.ts
index 4b64d5d2b..046736c39 100644
--- a/sdk/typescript/src/scan-comparison.ts
+++ b/sdk/typescript/src/scan-comparison.ts
@@ -15,6 +15,9 @@ import { z } from "zod";
import { characterCount, MAX_CODEX_INPUT_CHARACTERS } from "./codex-prompt.js";
import {
scanCodexHome,
+ scanAuthentication,
+ selectedScanEnvironment,
+ definedEnvironment,
type CodexSecuritySurface,
type ScanAuthMode,
} from "./api.js";
@@ -29,6 +32,8 @@ import {
DEFAULT_CODEX_CONFIG,
deepMerge,
hasCommandAuth,
+ isExternalModelProvider,
+ scanProviderEnvKey,
mergedCodexConfig,
readCodexFileProfile,
normalizeLegacyWindowsSandboxOverride,
@@ -269,7 +274,11 @@ export async function matchScanFindings(
export async function matchScanFindingsInternal(
input: ScanComparisonInput & SavedComparisonContext,
options: ScanComparisonOptions = {},
- runtimeOptions: { surface: CodexSecuritySurface; singleTurn?: boolean },
+ runtimeOptions: {
+ surface: CodexSecuritySurface;
+ singleTurn?: boolean;
+ nativeProviderEnvironment?: Record<string, string>;
+ },
): Promise<ScanComparisonResult> {
options.signal?.throwIfAborted();
validateComparisonInput(input);
@@ -543,7 +552,9 @@ export async function matchScanFindingsInternal(
async function startReadOnlyCodexThread(
options: ReadOnlyCodexOptions,
- runtimeOptions: Parameters<typeof runReadOnlyCodex>[3],
+ runtimeOptions: Parameters<typeof runReadOnlyCodex>[3] & {
+ nativeProviderEnvironment?: Record<string, string>;
+ },
): Promise<{
thread: ReturnType<ReadOnlyCodex["startThread"]>;
cleanup?: () => Promise<void>;
@@ -635,12 +646,19 @@ async function startReadOnlyCodexThread(
const effectiveFeatures = resolveCodexProfile(
scanCyberAccessConfig(providerConfig, options.cyberAccessProgram),
)["features"] as JsonObject | undefined;
+ const modelProvider = scanModelProvider(providerConfig);
+ const nativeKey =
+ !commandAuth && !isExternalModelProvider(modelProvider)
+ ? scanProviderEnvKey(providerConfig)
+ : undefined;
const environment = await comparisonEnvironment(
source,
accountStatus,
options.signal,
undefined,
providerConfig,
+ nativeKey,
+ options.auth,
);
const command = resolveCodexCommand(environment);
const codexOptions: CodexOptions = {
@@ -649,9 +667,11 @@ async function startReadOnlyCodexThread(
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,
+ nativeKey !== undefined
+ ? undefined
+ : environmentEntry(environment, "OPENAI_API_KEY")?.trim() ||
+ environmentEntry(environment, "CODEX_API_KEY")?.trim() ||
+ undefined,
config: {
...sdkConfig,
windows,
@@ -717,6 +737,15 @@ async function startReadOnlyCodexThread(
codexOptions.configOverrides = permissions.configOverrides;
requestedPermissionProfile = permissions.permissionProfileId;
}
+ if (
+ nativeKey !== undefined &&
+ runtimeOptions.nativeProviderEnvironment !== undefined
+ ) {
+ codexOptions.env = {
+ ...runtimeOptions.nativeProviderEnvironment,
+ ...environment,
+ };
+ }
const codex =
profile === undefined
? new Codex(codexOptions)
@@ -1221,6 +1250,8 @@ export async function comparisonEnvironment(
signal?: AbortSignal,
prepareCredentialHome: typeof prepareCodexSecurityCredentialHome = prepareCodexSecurityCredentialHome,
config?: JsonObject,
+ nativeKey?: string,
+ auth: ScanAuthMode = "api-key",
): Promise<Record<string, string>> {
signal?.throwIfAborted();
const environment = Object.fromEntries(
@@ -1235,6 +1266,13 @@ export async function comparisonEnvironment(
environment[key] = home;
}
}
+ if (nativeKey !== undefined && config !== undefined) {
+ const provider = scanModelProvider(config);
+ scanAuthentication(environment, auth, provider, false, false, nativeKey);
+ return definedEnvironment(
+ selectedScanEnvironment(environment, auth, provider, nativeKey, config),
+ );
+ }
if (
hasCommandAuth(config ?? (await readCodexHomeConfig(environment, signal)))
) {
diff --git a/sdk/typescript/tests-ts/api-events.test.ts b/sdk/typescript/tests-ts/api-events.test.ts
index fbe55f0bf..827f3f05c 100644
--- a/sdk/typescript/tests-ts/api-events.test.ts
+++ b/sdk/typescript/tests-ts/api-events.test.ts
@@ -266,6 +266,7 @@ describe("one-shot scan events", () => {
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
"CHEAPER_INFERENCE_API_KEY",
+ "CUSTOM_GATEWAY_TOKEN",
] as const) {
for (const status of ["not_granted", "unknown"] as const) {
const { warnings } = await runTacEvents(
diff --git a/sdk/typescript/tests-ts/api-provider-isolation.test.ts b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
index 80a4b1f6f..b93552717 100644
--- a/sdk/typescript/tests-ts/api-provider-isolation.test.ts
+++ b/sdk/typescript/tests-ts/api-provider-isolation.test.ts
@@ -11,7 +11,7 @@ import { createInterface } from "node:readline";
import { executablePathForSpawn, resolveCodexCommand } from "../src/runtime.js";
import { copyCredentialTestPlugin, PLUGIN_ROOT } from "./plugin-root.js";
import { profileConfigOverrides } from "../../../plugins/codex-security/scripts/codex_profile.mjs";
-import { TestClient } from "./support/api-client.js";
+import { TestClient, mockWorkbench } from "./support/api-client.js";
import { preparedRuntime } from "./support/api-events.js";
import { createApiTestFixtures } from "./support/temporary-directories.js";
@@ -273,6 +273,8 @@ test.each([
await mkdir(sourceHome, { mode: 0o700 });
await mkdir(sharedHome, { recursive: true, mode: 0o700 });
+ const providerId =
+ selection === "file custom only" ? "synthetic.gateway" : "openrouter";
const ready = [
Promise.withResolvers<void>(),
Promise.withResolvers<void>(),
@@ -377,9 +379,9 @@ test.each([
join(sourceHome, `review-${index}.config.toml`),
stringifyToml({
model: "gpt-5.6-terra",
- model_provider: "openrouter",
+ model_provider: providerId,
model_providers: {
- openrouter: provider,
+ [providerId]: provider,
"required.gateway": {
name: "Managed selection",
wire_api: "responses",
@@ -576,7 +578,7 @@ test.each([
shellPolicy,
);
expect(settings.config["agents"]).toEqual(resolvedAgents);
- expect(settings.config["model_provider"]).toBe("openrouter");
+ expect(settings.config["model_provider"]).toBe(providerId);
expect(settings.nativeProfile).toBeDefined();
expect(settings.nativeProfile).toBe(options.nativeProfile);
expect(
@@ -594,7 +596,7 @@ test.each([
);
const actual = (
nativeConfig["model_providers"] as JsonObject
- )["openrouter"] as JsonObject;
+ )[providerId] as JsonObject;
expect(actual).toMatchObject(provider);
expect(actual["http_headers"] ?? {}).toEqual(
provider.http_headers ?? {},
@@ -627,7 +629,7 @@ test.each([
await client.preflight(repository, { mode: "deep" }),
).toMatchObject({
model: "gpt-5.6-terra",
- modelProvider: "openrouter",
+ modelProvider: providerId,
});
}
}
@@ -661,6 +663,12 @@ test.each([
);
const fileProviderKeyCases = [
+ ["gateway", "custom only", "SYNTHETIC_GATEWAY_TOKEN"],
+ ["gateway", "account-named primary", "OPENAI_API_KEY"],
+ ["gateway", "declared external header", "SYNTHETIC_GATEWAY_TOKEN"],
+ ["gateway", "declared Codex account header", "SYNTHETIC_GATEWAY_TOKEN"],
+ ["gateway", "declared OpenAI account header", "SYNTHETIC_GATEWAY_TOKEN"],
+ ["gateway", "missing custom primary", "SYNTHETIC_GATEWAY_TOKEN"],
["openrouter", "default", "OPENROUTER_API_KEY"],
["openrouter", "custom only", "SYNTHETIC_CUSTOM_API_KEY"],
["openrouter", "canonical header", "SYNTHETIC_CUSTOM_API_KEY"],
@@ -673,6 +681,12 @@ const fileProviderKeyCases = [
["openrouter", "other external key", "FIREWORKS_API_KEY"],
] as const;
+const gatewayHeaders = new Map<string, string>([
+ ["declared external header", "FIREWORKS_API_KEY"],
+ ["declared Codex account header", "CODEX_API_KEY"],
+ ["declared OpenAI account header", "OPENAI_API_KEY"],
+]);
+
test.each(["openrouter", "fireworks"] as const)(
"native file profile accepts the %s custom environment key",
async (providerId) => {
@@ -719,14 +733,24 @@ for (const mode of ["standard", "deep"] as const) {
await mkdir(sourceHome, { mode: 0o700 });
const plugin = await createPluginProbe(root, report);
const canonicalKey = `${providerId.toUpperCase()}_API_KEY`;
+ const gatewayHeader = gatewayHeaders.get(_selection);
+ const headerKey =
+ gatewayHeader ??
+ (_selection === "canonical header" ? canonicalKey : undefined);
const headerEnvironment =
- _selection === "canonical header" ||
- _selection === "missing custom primary"
- ? { [canonicalKey]: " synthetic-header-key " }
+ headerKey || _selection === "missing custom primary"
+ ? { [headerKey ?? canonicalKey]: " synthetic-header-key " }
: {};
- const inheritedEnvironment = {
+ const inactiveKey = gatewayHeader
+ ? "CHEAPER_INFERENCE_API_KEY"
+ : "INACTIVE_GATEWAY_TOKEN";
+ const inactiveEnvironment = gatewayHeader
+ ? { [inactiveKey]: "synthetic-inactive-key" }
+ : {};
+ const inheritedEnvironment: Record<string, string> = {
...(_selection === "custom Codex key" ||
- _selection === "other external key"
+ _selection === "other external key" ||
+ gatewayHeader
? Object.fromEntries(
[
"OPENAI_API_KEY",
@@ -739,12 +763,17 @@ for (const mode of ["standard", "deep"] as const) {
)
: {}),
...headerEnvironment,
+ ...inactiveEnvironment,
...(_selection === "missing custom primary"
- ? {}
+ ? {
+ OPENAI_API_KEY: "synthetic-unrelated-account",
+ INACTIVE_GATEWAY_TOKEN: "synthetic-unrelated-provider",
+ }
: { [providerKey]: "synthetic-file-key" }),
};
const workerEnvironment = {
...headerEnvironment,
+ ...inactiveEnvironment,
[providerKey]: "synthetic-file-key",
};
const provider = {
@@ -752,14 +781,20 @@ for (const mode of ["standard", "deep"] as const) {
wire_api: "responses",
base_url: "https://provider.example.test/v1",
env_key: providerKey,
- ...(_selection === "canonical header"
- ? { env_http_headers: { "X-Synthetic-Token": canonicalKey } }
+ ...(gatewayHeader === "OPENAI_API_KEY"
+ ? { requires_openai_auth: true }
+ : {}),
+ ...(headerKey
+ ? { env_http_headers: { "X-Synthetic-Token": headerKey } }
: {}),
};
const original = stringifyToml({
model: "synthetic-model",
model_provider: providerId,
- model_providers: { [providerId]: provider },
+ model_providers: {
+ [providerId]: provider,
+ inactive: { ...provider, env_key: inactiveKey },
+ },
features: { shell_tool: false, unified_exec: false },
});
await writeFile(join(sourceHome, "review.config.toml"), original);
@@ -775,6 +810,16 @@ for (const mode of ["standard", "deep"] as const) {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scan,
repositoryRevision: async () => "deadbeef",
+ runWorkbench: async (options, args, input) => {
+ if (args[0] === "register-cli-scan") {
+ expect(options.environment).not.toHaveProperty(providerKey);
+ if (gatewayHeader) {
+ expect(options.environment).not.toHaveProperty(gatewayHeader);
+ expect(options.environment).not.toHaveProperty(inactiveKey);
+ }
+ }
+ return mockWorkbench(args, input);
+ },
createCodex: (options) => {
launched = true;
return {
@@ -789,9 +834,13 @@ for (const mode of ["standard", "deep"] as const) {
"CODEX_API_KEY",
"OPENROUTER_API_KEY",
"FIREWORKS_API_KEY",
+ "CHEAPER_INFERENCE_API_KEY",
]) {
expect(environment[name]).toBe(
- name === providerKey || name === canonicalKey
+ name === providerKey ||
+ name === canonicalKey ||
+ name === headerKey ||
+ name === inactiveKey
? inheritedEnvironment[name]
: undefined,
);
@@ -844,6 +893,7 @@ for (const mode of ["standard", "deep"] as const) {
]) {
expect(text).not.toContain("synthetic-file-key");
expect(text).not.toContain("synthetic-header-key");
+ expect(text).not.toContain("synthetic-inactive-key");
}
throw new Error("synthetic file provider child checked");
},
@@ -860,6 +910,21 @@ for (const mode of ["standard", "deep"] as const) {
verified: false,
});
expect(preflight.modelProvider).toBe(providerId);
+ if (
+ providerId === "gateway" &&
+ (_selection === "custom only" ||
+ _selection === "account-named primary")
+ ) {
+ const request = { mode, auth: "chatgpt" as const };
+ const guidance = `ChatGPT authentication cannot use the gateway provider's required ${providerKey}`;
+ await expect(client.preflight(repository, request)).rejects.toThrow(
+ guidance,
+ );
+ await expect(client.run(repository, request)).rejects.toThrow(
+ guidance,
+ );
+ expect(launched).toBe(false);
+ }
if (_selection === "missing custom primary") {
await expect(
client.preflight(repository, { mode, auth: "api-key" }),
@@ -1196,6 +1261,7 @@ test.each([
env_key: providerKey,
env_http_headers: {
"X-Synthetic-Token": headerKey,
+ ...(!external ? { "X-Synthetic-Primary": providerKey } : {}),
"X-Synthetic-Missing": "SYNTHETIC_UNSET_KEY",
},
},
@@ -1225,16 +1291,14 @@ test.each([
startThread: () => ({
id: null,
async runStreamed() {
- expect(options.apiKey).toBe(
- external ? undefined : "synthetic-account-key",
- );
+ expect(options.apiKey).toBeUndefined();
+ expect(options.env!["OPENAI_API_KEY"]).toBeUndefined();
+ const selectedKey = external
+ ? "synthetic-custom-key"
+ : providerEnvironment[providerKey];
+ expect(options.env![providerKey]).toBe(selectedKey);
const status = await nativeRequest(
- {
- ...options.env!,
- ...(options.apiKey === undefined
- ? {}
- : { CODEX_API_KEY: options.apiKey }),
- },
+ options.env!,
repository,
[],
// Tool enumeration starts the real MCP child without a model turn.
@@ -1259,12 +1323,7 @@ test.each([
...(process.platform === "win32"
? { [headerKey]: " synthetic-child-header " }
: {}),
- ...(external
- ? { [providerKey]: "synthetic-custom-key" }
- : {}),
- ...(providerKey === "CODEX_API_KEY"
- ? { CODEX_API_KEY: "synthetic-account-key" }
- : {}),
+ [providerKey]: selectedKey,
},
});
for (const text of [
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index b6e8008b9..5184dda02 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -13708,10 +13708,33 @@ if __name__ == "__main__":
undefined,
],
["managed provider selection retains matching", "managed", undefined],
+ [
+ "post-scan inference needs a declared Codex header",
+ "CODEX_API_KEY",
+ undefined,
+ ],
+ [
+ "post-scan inference needs a declared OpenAI header",
+ "OPENAI_API_KEY",
+ undefined,
+ ],
["relative model files preserve scan origin", "model-files", undefined],
] as const)(
"keeps a completed scan when %s",
- async (_scenario, failure, warning) => {
+ async (_scenario, variant, warning) => {
+ const nativeHeader =
+ variant === "OPENAI_API_KEY" || variant === "CODEX_API_KEY"
+ ? variant
+ : undefined;
+ const failure = nativeHeader ? "managed" : variant;
+ const gatewayEnvironment: Record<string, string> = nativeHeader
+ ? {
+ GATEWAY_TOKEN: "synthetic-gateway-primary",
+ CODEX_API_KEY: "synthetic-unrelated",
+ OPENAI_API_KEY: "synthetic-unrelated",
+ [nativeHeader]: " synthetic-required-header ",
+ }
+ : {};
const limited = failure === "budget" || failure === "budget-context";
const { root, repository, codexHome, scanDir } = await scanDirectories();
const current = {
@@ -13771,8 +13794,11 @@ if __name__ == "__main__":
wire_api: "responses",
env_http_headers: {
"X-Synthetic-Context": "SYNTHETIC_MATCH_HEADER",
+ ...(nativeHeader ? { "X-Gateway-Header": nativeHeader } : {}),
},
- auth: { command: "synthetic-auth" },
+ ...(nativeHeader
+ ? { env_key: "GATEWAY_TOKEN" }
+ : { auth: { command: "synthetic-auth" } }),
},
...(failure === "managed"
? { "synthetic.managed": managedProvider }
@@ -13797,6 +13823,13 @@ if __name__ == "__main__":
}
const kind = args.includes("mcp") ? "mcp" : args.includes("app-server") ? "preflight" : "exec";
const call = { kind, args };
+ if (${Boolean(nativeHeader)}) {
+ call.credentials = {
+ GATEWAY_TOKEN: process.env.GATEWAY_TOKEN,
+ OPENAI_API_KEY: process.env.OPENAI_API_KEY,
+ CODEX_API_KEY: process.env.CODEX_API_KEY,
+ };
+ }
if (kind !== "exec") {
call.metadata = config.model_providers;
appendFileSync(${JSON.stringify(startupCallsPath)}, JSON.stringify(call) + "\\n");
@@ -13825,7 +13858,7 @@ if __name__ == "__main__":
const request = JSON.parse(line);
if (request.id === undefined) continue;
const result = request.method === "config/read"
- ? { config: { ...config, model_provider: "synthetic.managed" } }
+ ? { config: { ...config, model_provider: ${JSON.stringify(nativeHeader ? "synthetic.provider" : "synthetic.managed")} } }
: request.method === "permissionProfile/list"
? { data: [{ id: config.default_permissions, allowed: true }], nextCursor: null }
: {};
@@ -13876,9 +13909,11 @@ if __name__ == "__main__":
},
{
...scanRuntimeDependencies(codexHome, scanDir),
+ environment: gatewayEnvironment,
prepareRuntime: runtimePreparer(codexHome, () => ({
environment: {
SYNTHETIC_MATCH_HEADER: "synthetic-comparison-header",
+ ...gatewayEnvironment,
...(failure === "managed"
? {
PATH: process.env["PATH"] ?? "",
@@ -14086,7 +14121,7 @@ if __name__ == "__main__":
);
const ownerSpy =
- failure === "managed"
+ failure === "managed" && !nativeHeader
? spyOn(
ownerArtifacts,
"writeScanOwnerSuggestions",
@@ -14117,7 +14152,7 @@ if __name__ == "__main__":
: undefined;
try {
const result = await client.run(repository, {
- ownerSuggestions: failure === "managed",
+ ownerSuggestions: ownerSpy !== undefined,
...(limited ? { maxCostUsd: 1 } : {}),
cyberAccessProgram: "daybreak_blue",
onProgress() {},
@@ -14176,18 +14211,16 @@ if __name__ == "__main__":
.trim()
.split("\n")
.map((line) => JSON.parse(line));
- expect(ownerSpy).toHaveBeenCalledTimes(1);
- expect(result.ownerSuggestionsPath).toBe(
- join(scanDir, "owner-suggestions.json"),
+ if (ownerSpy) {
+ expect(ownerSpy).toHaveBeenCalledTimes(1);
+ expect(result.ownerSuggestionsPath).toBe(
+ join(scanDir, "owner-suggestions.json"),
+ );
+ }
+ const startup = ["mcp", "preflight", "exec"];
+ expect(calls.map(({ kind }) => kind)).toEqual(
+ ownerSpy ? [...startup, ...startup] : startup,
);
- expect(calls.map(({ kind }) => kind)).toEqual([
- "mcp",
- "preflight",
- "exec",
- "mcp",
- "preflight",
- "exec",
- ]);
const metadata = {
"synthetic.provider": {
name: "Synthetic provider",
@@ -14199,6 +14232,19 @@ if __name__ == "__main__":
requires_openai_auth: false,
},
};
+ if (nativeHeader) {
+ for (const call of calls) {
+ if (call.kind === "exec") {
+ expect(call.credentials).toEqual({
+ GATEWAY_TOKEN: "synthetic-gateway-primary",
+ [nativeHeader]: " synthetic-required-header ",
+ });
+ } else {
+ expect(call.credentials).not.toHaveProperty("OPENAI_API_KEY");
+ expect(call.credentials).not.toHaveProperty("CODEX_API_KEY");
+ }
+ }
+ }
expect(calls[0].metadata).toEqual(metadata);
expect(calls[1].metadata).toEqual(metadata);
expect(calls[2]).toMatchObject({
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index ab5def889..1da891be5 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -1,5 +1,6 @@
import { readJsonLines } from "./support/json.js";
import { runProviderSkill } from "./support/cli-provider-authentication.js";
+import { TestClient } from "./support/api-client.js";
import { resolving } from "./support/promises.js";
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
@@ -1152,6 +1153,45 @@ describe("CLI authentication", () => {
}
});
+ test("scan rejects an explicit ChatGPT login with a required native provider key", async () => {
+ const home = await createCredentialHome();
+ await writeFile(join(home, "review.config.toml"), GATEWAY_CONFIGURATION);
+ const environment = {
+ CODEX_HOME: home,
+ GATEWAY_API_KEY: "synthetic-provider-secret",
+ OPENAI_API_KEY: "synthetic-unrelated-secret",
+ };
+ const { runCli, stdout, stderr } = createCliTest(main);
+ const deps = dependencies({
+ environment,
+ currentDirectory: stateDirectory,
+ });
+ deps.createSecurity = (config) => new TestClient(config, { environment });
+ expect(
+ await runCli(
+ [
+ "scan",
+ ".",
+ "--dry-run",
+ "--auth",
+ "chatgpt",
+ "--codex",
+ 'profile="review"',
+ ],
+ deps,
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain(
+ "ChatGPT authentication cannot use the gateway provider's required GATEWAY_API_KEY",
+ );
+ expect(stdout.text() + stderr.text()).not.toContain(
+ "synthetic-provider-secret",
+ );
+ expect(stdout.text() + stderr.text()).not.toContain(
+ "synthetic-unrelated-secret",
+ );
+ });
+
test("keeps selected dry-run authentication metadata safe and machine readable", async () => {
const { stdout, stderr, runCli } = createCliTest(main);
diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.ts
index e1e7f0c36..3543581a5 100644
--- a/sdk/typescript/tests-ts/scan-comparison.test.ts
+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts
@@ -251,13 +251,28 @@ describe("semantic scan comparison", () => {
);
test.each([false, true])(
- "preserves literal metadata keys in SDK arguments with provider profile %p",
+ "preserves literal metadata and provider header values in SDK children with a private profile %p",
async (withProfile) => {
const home = await temporaryDirectory();
+ const repository = await temporaryDirectory();
+ await writeFile(join(repository, "source.ts"), "export {};\n");
+ const gateway = (env_key = "SYNTHETIC_GATEWAY_TOKEN") => ({
+ model_provider: "gateway",
+ model_providers: {
+ gateway: {
+ name: "Synthetic",
+ wire_api: "responses",
+ base_url: "https://provider.example.test/v1",
+ env_key,
+ env_http_headers: { "X-Gateway-Key": "CODEX_API_KEY" },
+ },
+ },
+ });
const preload = join(home, "capture-codex.mjs");
await writeFile(
join(home, "config.toml"),
stringify({
+ ...(withProfile ? {} : gateway()),
responses_api_metadata: {
"team.tag": "from-home",
"overlap.tag": "home",
@@ -270,51 +285,65 @@ describe("semantic scan comparison", () => {
"for await (const _chunk of process.stdin) {}",
"const send = (event) => console.log(JSON.stringify(event));",
'send({ type: "thread.started", thread_id: "fixture-thread" });',
- 'send({ type: "item.completed", item: { id: "reply", type: "agent_message", text: JSON.stringify(process.argv.slice(2)) } });',
+ "const { SYNTHETIC_GATEWAY_TOKEN: primary, CODEX_API_KEY: header, OPENAI_API_KEY: account } = process.env;",
+ "const text = JSON.stringify({ args: process.argv.slice(2), credentials: { primary, header, account } });",
+ 'send({ type: "item.completed", item: { id: "reply", type: "agent_message", text } });',
'send({ type: "turn.completed", usage: { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 } });',
"process.exit(0);",
].join("\n"),
);
let captured: CodexOptions | undefined;
const profileClient = captureProfileClient();
- const { codex } = fakeCodex({ matches: [], uncertain: [] });
+ const { codex } = fakeCodex(
+ withProfile
+ ? { components: [{ name: "Source", paths: ["source.ts"] }] }
+ : { matches: [], uncertain: [] },
+ );
const startThread = observeCodexOptions(codex, (options) => {
captured = options;
});
try {
- await matchScanFindings(
- { before: [finding("before")], after: [finding("after")] },
- {
- environment: {
- PATH: process.env["PATH"],
- SystemRoot: process.env["SystemRoot"],
- CODEX_HOME: home,
- CODEX_SECURITY_STATE_DIR: join(home, "state"),
- OPENAI_API_KEY: "synthetic-key",
- },
- workingDirectory: home,
- config: {
- codexOverrides: {
- responses_api_metadata: {
- "caller.tag": "from-caller",
- "overlap.tag": "caller",
- },
- ...(withProfile
- ? {
- model_provider: "synthetic",
- model_providers: {
- synthetic: {
- name: "Synthetic",
- wire_api: "responses",
- base_url: "https://provider.example.test/v1",
- },
- },
- }
- : {}),
+ const options = {
+ environment: {
+ PATH: process.env["PATH"],
+ SystemRoot: process.env["SystemRoot"],
+ CODEX_HOME: home,
+ CODEX_SECURITY_STATE_DIR: join(home, "state"),
+ OPENAI_API_KEY: "synthetic-unrelated-account",
+ CODEX_API_KEY: " synthetic-header ",
+ SYNTHETIC_GATEWAY_TOKEN: "synthetic-primary",
+ },
+ workingDirectory: home,
+ config: {
+ codexOverrides: {
+ responses_api_metadata: {
+ "caller.tag": "from-caller",
+ "overlap.tag": "caller",
},
+ ...(withProfile ? gateway() : {}),
},
},
- );
+ };
+ if (withProfile) {
+ await planComponents(repository, options);
+ await expect(
+ planComponents(repository, { ...options, auth: "chatgpt" }),
+ ).rejects.toThrow(
+ "ChatGPT authentication cannot use the gateway provider's required SYNTHETIC_GATEWAY_TOKEN",
+ );
+ await expect(
+ planComponents(repository, {
+ ...options,
+ config: { codexOverrides: gateway("CODEX_API_KEY") },
+ environment: { ...options.environment, CODEX_API_KEY: undefined },
+ }),
+ ).rejects.toThrow("Set CODEX_API_KEY");
+ expect(startThread).toHaveBeenCalledTimes(1);
+ } else
+ await matchScanFindings(
+ { before: [finding("before")], after: [finding("after")] },
+ options,
+ );
} finally {
startThread.mockRestore();
profileClient.spy.mockRestore();
@@ -332,7 +361,18 @@ describe("semantic scan comparison", () => {
const turn = await capture
.startThread({ workingDirectory: home, skipGitRepoCheck: true })
.run("Capture the invocation.");
- const args: string[] = JSON.parse(turn.finalResponse);
+ const {
+ args,
+ credentials,
+ }: {
+ args: string[];
+ credentials: Record<string, string>;
+ } = JSON.parse(turn.finalResponse);
+ expect(credentials).toEqual({
+ primary: "synthetic-primary",
+ header: " synthetic-header ",
+ });
+ expect(captured!.apiKey).toBeUndefined();
const metadataOverrides = args
.flatMap((arg, index) => (arg === "--config" ? [args[index + 1]!] : []))
.filter((value) => value.startsWith("responses_api_metadata"));
@@ -343,7 +383,7 @@ describe("semantic scan comparison", () => {
"caller.tag": "from-caller",
"overlap.tag": "caller",
codex_security_surface: "sdk",
- codex_security_command: "compare",
+ codex_security_command: withProfile ? "scan-components" : "compare",
codex_security_package_version: VERSION,
...(withProfile ? { codex_security_provider: "custom" } : {}),
},