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(cli): reuse scan authentication for patch and validation (#871)

mldangelo-oaif3b3bdea8f45
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 7b3d1fef9..e321c22a0 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -186,7 +186,7 @@ For CI, set `OPENAI_API_KEY` or `CODEX_API_KEY`. To save a key, pass it on stdin
printenv OPENAI_API_KEY | npx @openai/codex-security login --with-api-key
```
-Environment API keys apply to the current scan; only `login --with-api-key`
+Environment API keys apply to the current command; only `login --with-api-key`
saves them. Pass Codex access tokens on stdin to `login --with-access-token`.
Access-token environment variables are not scan API keys.
@@ -235,11 +235,23 @@ $env:OPENAI_API_KEY = "<your-api-key>"
npx @openai/codex-security scan C:\code\repository
```
-Login, logout, and scans share a private credential home:
+Login, logout, scans, validation, patching, and fix verification share a private
+credential home for stored OpenAI credentials, including custom providers with
+`requires_openai_auth = true`:
`$CODEX_SECURITY_STATE_DIR/codex-home`, or
-`$CODEX_HOME/state/plugins/codex-security/codex-home`. Codex uses the configured
-file or keyring storage and managed-device policies. If this home has no
-credentials, it imports an existing file-based Codex sign-in. Logout disables
+`$CODEX_HOME/state/plugins/codex-security/codex-home`. Keep this credential
+home outside the target directory and every enclosing Git worktree, including
+when running a command from a subdirectory. Codex carries
+`cli_auth_credentials_store`, `forced_login_method`, and
+`forced_chatgpt_workspace_id` from the ambient configuration into this home,
+including removing settings that are no longer present in the ambient configuration.
+Each command carries its selected provider into this home. Patching and fix
+verification also synchronize the ambient home's project-trust decisions and
+project-root markers, preserving which project configuration Codex loads.
+They hold the credential-home lock until the app-server thread is ready,
+then release it before model execution.
+Managed-device policies still apply. If this home has no credentials, it imports
+an existing file-based Codex sign-in. Logout disables
imports until you log in again.
Finish operations using older versions before upgrading. Runtime preparation
@@ -264,11 +276,23 @@ npx @openai/codex-security scan . --auth chatgpt
npx @openai/codex-security scan . --auth api-key
```
+`--auth` also works with `validate`, `patch`, and `verify-fix`. These commands
+use the same stored login as `scan`, including a sign-in created with
+`codex-security login --device-auth`:
+
+```bash
+npx @openai/codex-security patch OCCURRENCE_ID --auth chatgpt
+npx @openai/codex-security verify-fix OCCURRENCE_ID --auth api-key
+```
+
`--auth chatgpt` ignores environment API keys. `--auth api-key` requires
-`OPENAI_API_KEY` or `CODEX_API_KEY`. The default is `--auth auto`; unset both
-variables to default to ChatGPT. The SDK uses the same `auth` option on `run`
-and `preflight`. Codex may still need ChatGPT credentials to load
-workspace-managed policies when using an API key.
+`OPENAI_API_KEY` or `CODEX_API_KEY`. The default is `--auth auto`; noninteractive
+commands prefer `OPENAI_API_KEY`, then `CODEX_API_KEY`, then stored credentials.
+Patch follow-up assessment uses the same selection, and `scan --patch` keeps
+the scan's choice. Environment API keys do not replace the saved login.
+The SDK uses the same `auth` option on `run`, `validate`, and `preflight`.
+Codex may still need ChatGPT credentials to load workspace-managed policies
+when using an API key.
Some cybersecurity requests and protected findings require Trusted Access for
Cyber approval. Apply or check your access at
@@ -705,7 +729,7 @@ or `features.plugins` are rejected, including in profiles. Multi-agent v2 must
stay enabled: `agents.max_threads` and
`features.multi_agent_v2.enabled=false` are rejected.
-`validate`, `patch`, and `verify-fix` accept `--effort` and the `model`,
+`validate`, `patch`, and `verify-fix` accept `--auth`, `--effort`, and the `model`,
`model_reasoning_effort`, and `analytics.enabled` keys in `--codex`, but no
other runtime overrides.
@@ -722,9 +746,12 @@ The same setting works for `scan` and `bulk-scan`. An explicit setting is
preserved when `scan --patch` starts remediation and when
`patch --assess-patch-risk` starts its follow-up assessment. Boolean `true`
is also accepted; omitting the setting preserves the command's existing
-configuration and Codex defaults. Validation continues to ignore user
-configuration, while patching and verification retain their existing ambient
-configuration and project-trust behavior.
+configuration and Codex defaults. Validation ignores user configuration.
+For stored OpenAI credentials, patching and verification read configuration
+from the shared credential home. API-key commands and custom providers that use their own credentials retain
+their ambient Codex configuration. Patching and verification preserve project trust from the
+ambient home; explicit `--codex` settings apply to the command and its
+patch-risk assessment.
This setting does not control explicitly configured OpenTelemetry log or trace
exporters, authentication, integrations, or CLI update checks.
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index eca39b40e..838dadfa6 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -36,6 +36,8 @@ import {
} from "smol-toml";
import { z } from "incur";
import {
+ CODEX_AUTH_CONFIG_KEYS,
+ NO_CREDENTIALS_MESSAGE,
accountStatus,
configuredCodexHome,
CodexLoginHandle,
@@ -2848,11 +2850,7 @@ export class CodexSecurity {
!commandAuth &&
authentication.method !== "aws_credentials"
) {
- throw new AuthenticationRequiredError(
- "No credentials were found. Run 'codex-security login', use " +
- "'codex-security login --device-auth' on a remote or headless machine, or set " +
- "OPENAI_API_KEY or CODEX_API_KEY for CI.",
- );
+ throw new AuthenticationRequiredError(NO_CREDENTIALS_MESSAGE);
}
if (!commandAuth)
authentication = await runtimeScanAuthentication(
@@ -4294,7 +4292,8 @@ export function formatEnvironmentVariableRemovalGuidance(
return `remove ${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]} from the environment`;
}
-async function runtimeScanAuthentication(
+/** @internal */
+export async function runtimeScanAuthentication(
environment: ProcessEnvironment,
codexHome: string,
auth: ScanAuthMode = "auto",
@@ -4614,11 +4613,7 @@ function sharedCredentialCodexConfig(
approval_policy: scanApprovalPolicy(config),
features: { plugins: true },
};
- for (const key of [
- "cli_auth_credentials_store",
- "forced_login_method",
- "forced_chatgpt_workspace_id",
- ]) {
+ for (const key of CODEX_AUTH_CONFIG_KEYS) {
if (Object.hasOwn(config, key)) shared[key] = structuredClone(config[key]!);
}
const modelProvider = scanModelProvider(config);
diff --git a/sdk/typescript/src/auth.ts b/sdk/typescript/src/auth.ts
index 2224e506a..933ba35fb 100644
--- a/sdk/typescript/src/auth.ts
+++ b/sdk/typescript/src/auth.ts
@@ -289,6 +289,19 @@ export async function logout(
}
}
+/** @internal Authentication settings shared by login and model commands. */
+export const CODEX_AUTH_CONFIG_KEYS = [
+ "cli_auth_credentials_store",
+ "forced_login_method",
+ "forced_chatgpt_workspace_id",
+] as const;
+
+/** @internal Shared login recovery guidance for model commands. */
+export const NO_CREDENTIALS_MESSAGE =
+ "No credentials were found. Run 'codex-security login', use " +
+ "'codex-security login --device-auth' on a remote or headless machine, or set " +
+ "OPENAI_API_KEY or CODEX_API_KEY for CI.";
+
function preferredAuthUrl(value: string): string | null {
for (const match of plainTerminalText(value).matchAll(
/https?:\/\/[^\s<>"']+/g,
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 783bcb746..881293d28 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -57,13 +57,21 @@ import {
listRepositoryFindings,
SCAN_AUTH_MODES,
scanAuthentication,
+ runtimeScanAuthentication,
+ selectedScanEnvironment,
type DeepScanOptions,
type ScanAuthMode,
type ScanAuthentication,
type ScanOptions,
type ScanPreflight,
} from "./api.js";
-import { accountStatus } from "./auth.js";
+import {
+ accountStatus,
+ CODEX_AUTH_CONFIG_KEYS,
+ NO_CREDENTIALS_MESSAGE,
+ configuredCodexHome,
+ readCodexHomeConfig,
+} from "./auth.js";
import { loadContract } from "./contract.js";
import { publishScanToCustom } from "./custom-publish.js";
import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";
@@ -92,9 +100,14 @@ import {
DEFAULT_CODEX_CONFIG,
EXTERNAL_CODEX_PROVIDERS,
isExternalModelProvider,
+ hasCommandAuth,
+ inlineToml,
+ modelProviderConfigOverride,
+ resolveCommandAuthConfig,
mergedCodexConfig,
scanModelConfiguration,
scanModelProvider,
+ writeCodexConfig,
type CodexSecurityConfig,
type ExternalModelProvider,
type JsonObject,
@@ -104,6 +117,7 @@ import { formatUsd, type ScanCost } from "./cost.js";
import { formatScanCostTokens, formatTokenUsage } from "./cost-model.js";
import {
CodexSecurityError,
+ AuthenticationRequiredError,
ConfigurationError,
InvalidTargetError,
OutputDirectoryError,
@@ -144,6 +158,8 @@ import type { ScanResult } from "./result.js";
import { importScan, type ImportScanOptions } from "./import-scan.js";
import {
bundledPluginRoot,
+ acquireCodexSecurityCredentialHomeLock,
+ requireOutputOutsideRepositories,
canonicalizeModelSafePath,
codexSecurityCredentialHome,
codexSecurityStateDirectory,
@@ -198,6 +214,7 @@ import {
import {
abortable,
DiffTarget,
+ enclosingGitWorktreeRoots,
type ScanMode,
type ScanTarget,
} from "./targets.js";
@@ -1075,6 +1092,10 @@ type SkillThreadSource = Extract<
>;
interface SkillCommandOutput {
+ readonly directory?: string;
+ readonly auth?: ScanAuthMode;
+ readonly modelProvider?: string;
+ readonly providerConfiguration?: JsonObject;
readonly command: "validate" | "patch" | "verify-fix";
readonly stdout: Writable;
readonly stderr: Writable;
@@ -1106,6 +1127,7 @@ const findingVerificationSchema = z.object({
type FindingVerification = z.infer<typeof findingVerificationSchema>;
interface SkillRunOptions {
+ readonly auth?: ScanAuthMode;
safetyIdentifier?: string;
directory?: string;
findings?: readonly Finding[];
@@ -1133,6 +1155,8 @@ interface SelectedFindings {
}
interface PatchRiskRequest {
+ readonly auth?: ScanAuthMode;
+ readonly environment?: NodeJS.ProcessEnv;
repository: string;
base: string;
files?: readonly string[];
@@ -1389,157 +1413,327 @@ export async function runCodexSkillCommand(
processEnvironment: NodeJS.ProcessEnv = process.env,
input?: string,
): Promise<number> {
- const configuredHome =
- process.platform === "win32"
- ? environmentValue(processEnvironment, "CODEX_HOME")
- : processEnvironment["CODEX_HOME"];
- const environment = { ...processEnvironment };
- for (const name of Object.keys(environment)) {
- if (name.toUpperCase() === "CODEX_HOME") delete environment[name];
- }
- if (configuredHome?.trim()) {
- environment["CODEX_HOME"] = resolve(
- expandHome(configuredHome, processEnvironment),
- );
- }
- const invocation = spawn(executablePathForSpawn(command.command), [...args], {
- env: environment,
- cwd: output?.appServer?.directory ?? parse(process.execPath).root,
- stdio:
- output === undefined
- ? input === undefined
- ? "inherit"
- : ["pipe", "inherit", "inherit"]
- : [
- output.appServer !== undefined || input !== undefined
- ? "pipe"
- : "ignore",
- "pipe",
- "pipe",
- ],
- windowsHide: true,
- });
- if (input !== undefined) {
- invocation.stdin?.on("error", () => {});
- invocation.stdin?.end(input);
- }
- let requestedSignal: SignalName | null = null;
- let forcedTermination: ReturnType<typeof setTimeout> | undefined;
- let forceStatusCompletion: (() => void) | null = null;
- let forceCaptureCompletion: (() => void) | null = null;
- let invocationStatus: Promise<number> | undefined;
- const requestTermination = (signal: SignalName): void => {
- requestedSignal = signal;
- invocation.kill(signal);
- if (forcedTermination !== undefined) return;
- forcedTermination = setTimeout(() => {
- forcedTermination = undefined;
- if (invocation.exitCode === null && invocation.signalCode === null) {
- invocation.kill("SIGKILL");
- }
- forceCaptureCompletion?.();
- invocation.stdout?.destroy();
- invocation.stderr?.destroy();
- forceStatusCompletion?.();
- }, CHILD_TERMINATION_GRACE_MS);
- };
- const onInterrupt = (): void => {
- requestTermination("SIGINT");
- };
- const onTerminate = (): void => {
- requestTermination("SIGTERM");
- };
- process.on("SIGINT", onInterrupt);
- process.on("SIGTERM", onTerminate);
+ let releaseCredentialHome: (() => Promise<void>) | undefined;
try {
- let diagnostic = "";
- invocation.stderr?.on("data", (chunk: Buffer) => {
- diagnostic = `${diagnostic}${chunk.toString("utf8")}`.slice(-64 * 1_024);
- });
- const captured =
- output === undefined || invocation.stdout === null
- ? Promise.resolve(undefined)
- : Promise.race([
- readSkillCommandOutput(
- invocation.stdout,
- output.appServer === undefined
- ? undefined
+ let apiKey: string | undefined;
+ let authentication: ScanAuthentication | null = null;
+ let modelProvider: string | undefined;
+ // runSkill selects auth; other process callers supply their own environment.
+ if (output?.auth !== undefined) {
+ const config =
+ output.modelProvider !== undefined
+ ? {
+ model_provider: output.modelProvider,
+ ...(output.providerConfiguration === undefined
+ ? {}
: {
- directory: output.appServer.directory,
- prompt: output.appServer.prompt,
- threadSource: output.appServer.threadSource,
- input: invocation.stdin!,
- sandbox: output.appServer.sandbox,
- onEvent: output.appServer.onEvent,
- },
- ),
- new Promise<undefined>((resolve) => {
- forceCaptureCompletion = () => resolve(undefined);
- }),
- ]);
- invocationStatus = new Promise<number>((resolve, reject) => {
- let completed = false;
- const complete = (
- code: number | null,
- signal: NodeJS.Signals | null,
- ): void => {
- if (completed) return;
- completed = true;
- forceStatusCompletion = null;
- resolve(
- requestedSignal === "SIGINT" || signal === "SIGINT"
- ? 130
- : requestedSignal === "SIGTERM" || signal === "SIGTERM"
- ? 143
- : code ?? 1,
+ model_providers: {
+ [output.modelProvider]: output.providerConfiguration,
+ },
+ }),
+ }
+ : output.appServer === undefined
+ ? {}
+ : await readCodexHomeConfig(processEnvironment);
+ const provider = scanModelProvider(config);
+ const providerConfiguration =
+ typeof provider === "string"
+ ? (
+ config["model_providers"] as
+ | Record<string, JsonObject>
+ | undefined
+ )?.[provider]
+ : undefined;
+ const requiresOpenAiAuth =
+ provider === undefined ||
+ provider === "openai" ||
+ providerConfiguration?.["requires_openai_auth"] === true;
+ modelProvider = output.modelProvider;
+ let credentialConfig: JsonObject | undefined;
+ authentication = scanAuthentication(
+ processEnvironment,
+ output.auth,
+ provider,
+ hasCommandAuth(config),
+ );
+ if (
+ authentication.method === "stored_credentials" &&
+ isExternalModelProvider(provider)
+ ) {
+ const externalProvider = EXTERNAL_CODEX_PROVIDERS[provider];
+ throw new AuthenticationRequiredError(
+ `Set ${externalProvider.env_key} to run ${output.command} through ${externalProvider.name}.`,
);
- };
- forceStatusCompletion = () => complete(null, null);
- invocation.once("error", (error) => {
- if (completed) return;
- completed = true;
- forceStatusCompletion = null;
- reject(error);
- });
- invocation.once(output === undefined ? "exit" : "close", complete);
- });
- let [status, events] = await Promise.all([invocationStatus, captured]);
- if (status === 0 && output?.appServer !== undefined && events?.error) {
- status = 1;
- }
- if (output === undefined || status === 130 || status === 143) return status;
- if (status !== 0) {
- await writeCliOutput(
- output.stderr,
- `codex-security: ${skillCommandFailure(output.command, status, events?.error ?? diagnostic)}\n`,
+ }
+ let selected = selectedScanEnvironment(
+ processEnvironment,
+ authentication.method === "command" ? "chatgpt" : output.auth,
+ provider,
);
- return status;
+ if (
+ authentication.method === "stored_credentials" &&
+ requiresOpenAiAuth
+ ) {
+ const directory = await realpath(
+ output.directory ?? output.appServer?.directory ?? process.cwd(),
+ );
+ const protectedRoots = [
+ directory,
+ ...(await enclosingGitWorktreeRoots(directory)),
+ ];
+ const codexHome = await prepareCodexSecurityCredentialHome(
+ selected,
+ (path) =>
+ requireOutputOutsideRepositories(protectedRoots, path, "runtime"),
+ );
+ releaseCredentialHome =
+ await acquireCodexSecurityCredentialHomeLock(codexHome);
+ let credentialsAvailable: boolean;
+ const ambientConfig = await readCodexHomeConfig(selected);
+ credentialConfig = await readCodexHomeConfig({
+ ...selected,
+ CODEX_HOME: codexHome,
+ });
+ // Let native Codex apply the ambient home's project-trust decisions.
+ for (const key of [
+ ...CODEX_AUTH_CONFIG_KEYS,
+ "projects",
+ "project_root_markers",
+ ]) {
+ const value = ambientConfig[key];
+ if (value === undefined) delete credentialConfig[key];
+ else credentialConfig[key] = value;
+ }
+ if (typeof provider === "string")
+ credentialConfig["model_provider"] = provider;
+ else delete credentialConfig["model_provider"];
+ delete credentialConfig["profile"];
+ if (typeof provider !== "string" || providerConfiguration === undefined)
+ delete credentialConfig["model_providers"];
+ else
+ credentialConfig["model_providers"] = {
+ [provider]: providerConfiguration,
+ };
+ await writeCodexConfig(
+ join(codexHome, "config.toml"),
+ credentialConfig,
+ );
+ credentialsAvailable = await initialCredentialsAvailable(
+ selected,
+ configuredCodexHome(selected),
+ codexHome,
+ );
+ selected = {
+ ...selected,
+ CODEX_HOME: codexHome,
+ CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(selected),
+ };
+ if (
+ !credentialsAvailable &&
+ !(await accountStatus(command, selected)).authenticated
+ ) {
+ throw new AuthenticationRequiredError(NO_CREDENTIALS_MESSAGE);
+ }
+ authentication = await runtimeScanAuthentication(
+ selected,
+ codexHome,
+ output.auth,
+ provider,
+ );
+ } else if (authentication.method === "api_key" && requiresOpenAiAuth) {
+ apiKey = environmentValue(selected, authentication.source)?.trim();
+ // Match the SDK's key selection for native and nested plugin workers.
+ selected = {
+ ...selectedScanEnvironment(selected, "chatgpt"),
+ CODEX_API_KEY: apiKey,
+ };
+ if (output.appServer !== undefined) {
+ args = [
+ ...args,
+ "--config",
+ 'cli_auth_credentials_store="ephemeral"',
+ ];
+ }
+ }
+ if (output.appServer === undefined) {
+ const authConfig =
+ credentialConfig ?? (await readCodexHomeConfig(selected));
+ args = [
+ ...args,
+ ...CODEX_AUTH_CONFIG_KEYS.flatMap((key) =>
+ authConfig[key] === undefined
+ ? []
+ : ["--config", `${key}=${inlineToml(authConfig[key])}`],
+ ),
+ ];
+ }
+ if (output.appServer === undefined) await releaseCredentialHome?.();
+ processEnvironment = selected;
}
- if (
- (output.appServer !== undefined && events?.completed !== true) ||
- events?.message === undefined ||
- events.message.trim().length === 0
- ) {
- await writeCliOutput(
- output.stderr,
- `codex-security: Codex did not return a completed ${output.command} response.\n`,
+ const configuredHome =
+ process.platform === "win32"
+ ? environmentValue(processEnvironment, "CODEX_HOME")
+ : processEnvironment["CODEX_HOME"];
+ const environment = { ...processEnvironment };
+ for (const name of Object.keys(environment)) {
+ if (name.toUpperCase() === "CODEX_HOME") delete environment[name];
+ }
+ if (configuredHome?.trim()) {
+ environment["CODEX_HOME"] = resolve(
+ expandHome(configuredHome, processEnvironment),
);
- return 2;
}
- await writeCliOutput(output.stdout, `${events.message.trimEnd()}\n`);
- return status;
- } catch (error) {
- invocation.stdout?.destroy();
- invocation.stderr?.destroy();
- requestTermination("SIGTERM");
- await invocationStatus?.catch(() => undefined);
- throw error;
+ const invocation = spawn(
+ executablePathForSpawn(command.command),
+ [...args],
+ {
+ env: environment,
+ cwd: output?.appServer?.directory ?? parse(process.execPath).root,
+ stdio:
+ output === undefined
+ ? input === undefined
+ ? "inherit"
+ : ["pipe", "inherit", "inherit"]
+ : [
+ output.appServer !== undefined || input !== undefined
+ ? "pipe"
+ : "ignore",
+ "pipe",
+ "pipe",
+ ],
+ windowsHide: true,
+ },
+ );
+ if (input !== undefined) {
+ invocation.stdin?.on("error", () => {});
+ invocation.stdin?.end(input);
+ }
+ let requestedSignal: SignalName | null = null;
+ let forcedTermination: ReturnType<typeof setTimeout> | undefined;
+ let forceStatusCompletion: (() => void) | null = null;
+ let forceCaptureCompletion: (() => void) | null = null;
+ let invocationStatus: Promise<number> | undefined;
+ const requestTermination = (signal: SignalName): void => {
+ requestedSignal = signal;
+ invocation.kill(signal);
+ if (forcedTermination !== undefined) return;
+ forcedTermination = setTimeout(() => {
+ forcedTermination = undefined;
+ if (invocation.exitCode === null && invocation.signalCode === null) {
+ invocation.kill("SIGKILL");
+ }
+ forceCaptureCompletion?.();
+ invocation.stdout?.destroy();
+ invocation.stderr?.destroy();
+ forceStatusCompletion?.();
+ }, CHILD_TERMINATION_GRACE_MS);
+ };
+ const onInterrupt = (): void => {
+ requestTermination("SIGINT");
+ };
+ const onTerminate = (): void => {
+ requestTermination("SIGTERM");
+ };
+ process.on("SIGINT", onInterrupt);
+ process.on("SIGTERM", onTerminate);
+ try {
+ let diagnostic = "";
+ invocation.stderr?.on("data", (chunk: Buffer) => {
+ diagnostic = `${diagnostic}${chunk.toString("utf8")}`.slice(
+ -64 * 1_024,
+ );
+ });
+ const captured =
+ output === undefined || invocation.stdout === null
+ ? Promise.resolve(undefined)
+ : Promise.race([
+ readSkillCommandOutput(
+ invocation.stdout,
+ output.appServer === undefined
+ ? undefined
+ : {
+ apiKey,
+ modelProvider,
+ onThreadStarted: releaseCredentialHome,
+ directory: output.appServer.directory,
+ prompt: output.appServer.prompt,
+ threadSource: output.appServer.threadSource,
+ input: invocation.stdin!,
+ sandbox: output.appServer.sandbox,
+ onEvent: output.appServer.onEvent,
+ },
+ ),
+ new Promise<undefined>((resolve) => {
+ forceCaptureCompletion = () => resolve(undefined);
+ }),
+ ]);
+ invocationStatus = new Promise<number>((resolve, reject) => {
+ let completed = false;
+ const complete = (
+ code: number | null,
+ signal: NodeJS.Signals | null,
+ ): void => {
+ if (completed) return;
+ completed = true;
+ forceStatusCompletion = null;
+ resolve(
+ requestedSignal === "SIGINT" || signal === "SIGINT"
+ ? 130
+ : requestedSignal === "SIGTERM" || signal === "SIGTERM"
+ ? 143
+ : code ?? 1,
+ );
+ };
+ forceStatusCompletion = () => complete(null, null);
+ invocation.once("error", (error) => {
+ if (completed) return;
+ completed = true;
+ forceStatusCompletion = null;
+ reject(error);
+ });
+ invocation.once(output === undefined ? "exit" : "close", complete);
+ });
+ let [status, events] = await Promise.all([invocationStatus, captured]);
+ if (status === 0 && output?.appServer !== undefined && events?.error) {
+ status = 1;
+ }
+ if (output === undefined || status === 130 || status === 143)
+ return status;
+ if (status !== 0) {
+ await writeCliOutput(
+ output.stderr,
+ `codex-security: ${skillCommandFailure(output.command, status, events?.error ?? diagnostic, authentication)}\n`,
+ );
+ return status;
+ }
+ if (
+ (output.appServer !== undefined && events?.completed !== true) ||
+ events?.message === undefined ||
+ events.message.trim().length === 0
+ ) {
+ await writeCliOutput(
+ output.stderr,
+ `codex-security: Codex did not return a completed ${output.command} response.\n`,
+ );
+ return 2;
+ }
+ await writeCliOutput(output.stdout, `${events.message.trimEnd()}\n`);
+ return status;
+ } catch (error) {
+ invocation.stdout?.destroy();
+ invocation.stderr?.destroy();
+ requestTermination("SIGTERM");
+ await invocationStatus?.catch(() => undefined);
+ throw error;
+ } finally {
+ if (forcedTermination !== undefined) clearTimeout(forcedTermination);
+ forceStatusCompletion = null;
+ forceCaptureCompletion = null;
+ process.off("SIGINT", onInterrupt);
+ process.off("SIGTERM", onTerminate);
+ }
} finally {
- if (forcedTermination !== undefined) clearTimeout(forcedTermination);
- forceStatusCompletion = null;
- forceCaptureCompletion = null;
- process.off("SIGINT", onInterrupt);
- process.off("SIGTERM", onTerminate);
+ await releaseCredentialHome?.();
}
}
@@ -4377,6 +4571,10 @@ export async function main(
.describe("Finding text or a file containing findings."),
}),
options: z.object({
+ auth: z
+ .enum(SCAN_AUTH_MODES)
+ .default("auto")
+ .describe("Credential source: auto, chatgpt, or api-key."),
effort: effortOption(),
codex: z
.array(optionValue("--codex"))
@@ -4395,6 +4593,7 @@ export async function main(
output,
errorOutput,
dependencies,
+ { auth: options.auth },
);
} catch (error) {
exitCode = 2;
@@ -4415,6 +4614,10 @@ export async function main(
.describe("Finding text, a file, or a saved finding identifier."),
}),
options: z.object({
+ auth: z
+ .enum(SCAN_AUTH_MODES)
+ .default("auto")
+ .describe("Credential source: auto, chatgpt, or api-key."),
effort: effortOption(),
scan: optionValue("--scan")
.optional()
@@ -4555,6 +4758,7 @@ export async function main(
...(selected === undefined
? {}
: { findings: selected.findings }),
+ auth: options.auth,
verificationIds: identifiers,
environment,
onEvent: progress.observe.bind(progress),
@@ -4631,6 +4835,10 @@ export async function main(
.describe("Issue text or a file containing issues."),
}),
options: z.object({
+ auth: z
+ .enum(SCAN_AUTH_MODES)
+ .default("auto")
+ .describe("Credential source: auto, chatgpt, or api-key."),
effort: effortOption(),
scan: optionValue("--scan")
.optional()
@@ -4680,6 +4888,7 @@ export async function main(
options.linearFilter !== undefined ||
options.linearApiKey !== undefined ||
options.effort !== undefined ||
+ options.auth !== "auto" ||
options.codex.length > 0
) {
throw new CodexSecurityError(
@@ -4736,6 +4945,7 @@ export async function main(
options.effort,
errorOutput,
dependencies,
+ { auth: options.auth },
);
exitCode = patchExitCode(patches);
let patchRisk: PatchRiskAssessment | undefined;
@@ -4749,6 +4959,7 @@ export async function main(
files,
codexOverrides: options.codex,
effort: options.effort,
+ auth: options.auth,
},
errorOutput,
dependencies,
@@ -4836,7 +5047,7 @@ export async function main(
output,
errorOutput,
dependencies,
- { environment },
+ { environment, auth: options.auth },
);
if (patchBase !== undefined && exitCode === 0) {
const files = await changedPatchFiles(
@@ -4848,10 +5059,12 @@ export async function main(
? await runPatchRiskAssessment(
{
repository,
+ environment,
base: patchBase,
files,
codexOverrides: options.codex,
effort: options.effort,
+ auth: options.auth,
},
errorOutput,
dependencies,
@@ -6409,6 +6622,8 @@ async function assessPatchRisk(
dependencies,
{
directory: request.repository,
+ auth: request.auth,
+ environment: request.environment,
patchArtifact: {
path: patchPath,
repository: basename(resolve(request.repository)),
@@ -6738,12 +6953,21 @@ async function runSkill(
...(options.provider === undefined
? []
: ["--config", `model_provider=${JSON.stringify(options.provider)}`]),
- ...Object.entries(options.providerConfiguration ?? {}).flatMap(
- ([key, value]) => [
- "--config",
- `model_providers.${options.provider}.${key}=${JSON.stringify(value)}`,
- ],
- ),
+ ...(options.provider === undefined ||
+ options.providerConfiguration === undefined
+ ? []
+ : modelProviderConfigOverride(
+ resolveCommandAuthConfig(
+ {
+ model_providers: {
+ [options.provider]: options.providerConfiguration,
+ },
+ },
+ configuredCodexHome(
+ options.environment ?? dependencies.environment,
+ ),
+ ),
+ ).flatMap((value) => ["--config", value])),
"--config",
verify || assess
? 'approval_policy="on-request"'
@@ -6772,6 +6996,10 @@ async function runSkill(
],
{
command: verify ? "verify-fix" : patch || assess ? "patch" : "validate",
+ auth: options.auth ?? "auto",
+ directory,
+ modelProvider: options.provider,
+ providerConfiguration: options.providerConfiguration,
stdout,
stderr,
...(appServer
@@ -6788,7 +7016,7 @@ async function runSkill(
}
: {}),
},
- options.environment,
+ options.environment ?? dependencies.environment,
appServer ? undefined : prompt,
);
}
@@ -6796,6 +7024,9 @@ async function runSkill(
export async function readSkillCommandOutput(
stream: AsyncIterable<Buffer | string>,
appServer?: {
+ readonly apiKey?: string;
+ readonly modelProvider?: string;
+ readonly onThreadStarted?: () => Promise<void>;
readonly directory?: string;
readonly prompt: string;
readonly threadSource: SkillThreadSource;
@@ -6827,6 +7058,9 @@ export async function readSkillCommandOutput(
// Inherit the child process cwd and preserve the user's decision.
params: {
threadSource: appServer.threadSource,
+ ...(appServer.modelProvider === undefined
+ ? {}
+ : { modelProvider: appServer.modelProvider }),
approvalPolicy:
appServer?.sandbox === "read-only" ? "on-request" : "never",
sandbox: appServer?.sandbox ?? "workspace-write",
@@ -6879,8 +7113,18 @@ export async function readSkillCommandOutput(
} else if (value["error"] !== undefined) {
error = (value["error"] as { message: string }).message;
appServer.input.end();
- } else if (value["id"] === 1) {
- send({ method: "notifications/initialized" });
+ } else if (value["id"] === 1 || value["id"] === "login") {
+ if (value["id"] === 1) {
+ send({ method: "notifications/initialized" });
+ if (appServer.apiKey !== undefined) {
+ send({
+ id: "login",
+ method: "account/login/start",
+ params: { type: "apiKey", apiKey: appServer.apiKey },
+ });
+ continue;
+ }
+ }
if (appServer.sandbox === "read-only") {
if (appServer.directory === undefined) {
error =
@@ -6959,6 +7203,7 @@ export async function readSkillCommandOutput(
},
);
} else if (value["id"] === 2) {
+ await appServer.onThreadStarted?.();
threadId = (value["result"] as { thread: { id: string } }).thread.id;
send({
id: 3,
@@ -7051,13 +7296,14 @@ export function skillCommandFailure(
command: "validate" | "patch" | "verify-fix",
status: number,
detail: string,
+ authentication: ScanAuthentication | null = null,
): string {
if (
/401|invalid.api.key|token.expired|unauthori[sz]ed|authorizationrequired/iu.test(
detail,
)
) {
- return "Authentication failed. Run codex-security login or check the configured API key.";
+ return authenticationFailureMessage(authentication);
}
if (
/403|model.not.found|model.*access|access.*model|permission/iu.test(detail)
@@ -7384,7 +7630,8 @@ async function executeScan(
let effectiveModel = DEFAULT_SCAN_MODEL_CONFIGURATION.model;
let effectiveReasoningEffort =
DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort;
- let providerOptions: SkillRunOptions = {};
+ let providerOptions: SkillRunOptions = { provider: "openai" };
+ let auth = arguments_.auth;
let patchAnalyticsOverride: string | undefined;
let selectedAuthentication: ScanAuthentication | null = null;
let repository = "";
@@ -7429,7 +7676,7 @@ async function executeScan(
) {
patchAnalyticsOverride = `analytics.enabled=${JSON.stringify(analytics["enabled"])}`;
}
- const auth =
+ auth =
!arguments_.dryRun && !arguments_.mock && interactive
? await chooseInteractiveAuthentication(
{
@@ -7442,19 +7689,28 @@ async function executeScan(
dependencies,
)
: arguments_.auth;
- if (typeof provider === "string" && provider !== "openai") {
+ if (typeof provider === "string") {
providerOptions = {
provider,
- providerConfiguration: (
- effectiveConfiguration["model_providers"] as
- | Record<string, JsonObject>
- | undefined
- )?.[provider],
+ providerConfiguration:
+ (
+ effectiveConfiguration["model_providers"] as
+ | Record<string, JsonObject>
+ | undefined
+ )?.[provider] ??
+ (isExternalModelProvider(provider)
+ ? EXTERNAL_CODEX_PROVIDERS[provider]
+ : undefined),
};
}
selectedAuthentication = arguments_.mock
? null
- : scanAuthentication(dependencies.environment, auth, provider);
+ : scanAuthentication(
+ dependencies.environment,
+ auth,
+ provider,
+ hasCommandAuth(effectiveConfiguration),
+ );
diagnostic("scan.configuration", {
cli_version: VERSION,
bundled_plugin_version: BUNDLED_PLUGIN_VERSION,
@@ -8009,17 +8265,6 @@ async function executeScan(
patchSelection.occurrenceIds.includes(finding.occurrenceId)),
),
};
- const environment = { ...dependencies.environment };
- if (selectedAuthentication?.method === "stored_credentials") {
- for (const name of Object.keys(environment)) {
- if (["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase())) {
- delete environment[name];
- }
- }
- environment["CODEX_HOME"] = codexSecurityCredentialHome(
- dependencies.environment,
- );
- }
try {
patches = await runFindingPatches(
selected,
@@ -8035,7 +8280,7 @@ async function executeScan(
{
...providerOptions,
safetyIdentifier: arguments_.safetyIdentifier,
- environment,
+ auth,
findingInstructions: patchSelection?.instructions,
},
);
@@ -8121,6 +8366,48 @@ function isLocalScanFailure(error: unknown): boolean {
);
}
+function authenticationFailureMessage(
+ authentication: ScanAuthentication | null,
+): string {
+ if (authentication?.method === "command") {
+ return "Native Codex command authentication failed. Check the configured provider auth command.";
+ }
+ if (authentication?.method === "aws_credentials") {
+ return (
+ `Authentication failed using AWS credentials from ${authentication.source}. ` +
+ "Check your Amazon Bedrock bearer token or AWS credential chain."
+ );
+ }
+ if (
+ authentication?.method === "stored_credentials" &&
+ authentication.credentialType === "api_key"
+ ) {
+ return (
+ "Authentication failed using a stored API key. " +
+ "Sign in again with 'codex-security login --with-api-key' or provide a valid API key."
+ );
+ }
+ if (authentication?.method === "api_key") {
+ const openAiKey =
+ authentication.source === "OPENAI_API_KEY" ||
+ authentication.source === "CODEX_API_KEY";
+ return (
+ `Authentication failed using ${authentication.source}. ` +
+ (openAiKey
+ ? "Retry with '--auth chatgpt' or provide a valid API key."
+ : `Provide a valid ${authentication.source} for the selected provider.`)
+ );
+ }
+ if (authentication?.method === "stored_credentials") {
+ return authentication.credentialType === "chatgpt"
+ ? "Authentication failed using stored ChatGPT credentials. " +
+ "Sign in again with 'codex-security login' or provide a valid API key."
+ : "Authentication failed using stored credentials. " +
+ "Check 'codex-security login status' and refresh the stored login or provide a valid API key.";
+ }
+ return "Authentication failed. Check the selected provider's credentials and retry.";
+}
+
function scanFailureMessage(
error: unknown,
authentication: ScanAuthentication | null,
@@ -8153,20 +8440,7 @@ function scanFailureMessage(
}
switch (classifyConnectionFailure(error)) {
case "unauthorized":
- if (authentication?.method === "command") {
- return "Native Codex command authentication failed. Check the configured provider auth command.";
- }
- if (authentication?.method === "aws_credentials") {
- return (
- `Authentication failed using AWS credentials from ${authentication.source}. ` +
- "Check your Amazon Bedrock bearer token or AWS credential chain."
- );
- }
- return authentication?.method === "api_key"
- ? `Authentication failed using ${authentication.source}. ` +
- "Retry with '--auth chatgpt' or provide a valid API key."
- : "Authentication failed using stored ChatGPT credentials. " +
- "Sign in again with 'codex-security login' or provide a valid API key.";
+ return authenticationFailureMessage(authentication);
case "forbidden":
if (authentication?.method === "command") {
return "The configured Codex provider denied access. Check the command credentials and provider permissions.";
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index 76c45852e..60cde9ba2 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -5,6 +5,7 @@ import {
mkdir,
mkdtemp,
realpath,
+ readFile,
rm,
stat,
symlink,
@@ -12,12 +13,15 @@ import {
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { main } from "../src/cli.js";
+import { parse as parseToml } from "smol-toml";
+import { main, runCodexSkillCommand } from "../src/cli.js";
import { CodexSecurityError, type ScanOptions } from "../src/index.js";
import {
codexSecurityCredentialAllowsAmbientImport,
prepareCodexSecurityCredentialHome,
+ resolveCodexCommand,
setCodexSecurityCredentialLogout,
} from "../src/runtime.js";
import {
@@ -46,6 +50,7 @@ function dependencies(
return cliDependencies({
...options,
environment: {
+ CODEX_HOME: join(stateDirectory, "ambient"),
CODEX_SECURITY_STATE_DIR: stateDirectory,
...options.environment,
},
@@ -1156,3 +1161,563 @@ describe("CLI authentication", () => {
}
});
});
+
+describe("skill authentication", () => {
+ test.each(["validate", "patch", "verify-fix"])(
+ "%s advertises scan auth modes",
+ async (command) => {
+ const stdout = capture();
+ expect(
+ await main(
+ [command, "--schema", "--format", "json"],
+ stdout.stream,
+ capture().stream,
+ dependencies(),
+ ),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text()).options.properties.auth).toMatchObject({
+ enum: ["auto", "chatgpt", "api-key"],
+ default: "auto",
+ });
+ const help = capture();
+ expect(
+ await main(
+ [command, "--help"],
+ help.stream,
+ capture().stream,
+ dependencies(),
+ ),
+ ).toBe(0);
+ expect(help.text()).toContain("--auth");
+ },
+ );
+
+ test.each(["validate", "patch", "verify-fix"] as const)(
+ "%s reads the login credential home",
+ async (command) => {
+ const environment = {
+ CODEX_HOME: join(stateDirectory, "ambient"),
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ };
+ const credentialHome =
+ await prepareCodexSecurityCredentialHome(environment);
+ await writeFile(
+ join(credentialHome, "auth.json"),
+ JSON.stringify({
+ auth_mode: "apikey",
+ OPENAI_API_KEY: "SYNTHETIC_STORED_KEY",
+ }),
+ { mode: 0o600 },
+ );
+ const stdout = capture();
+ const stderr = capture();
+ const script = `console.log(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:JSON.stringify({home:process.env.CODEX_HOME,state:process.env.CODEX_SECURITY_STATE_DIR})}}))`;
+ expect(
+ await runCodexSkillCommand(
+ ["-e", script],
+ {
+ command,
+ auth: "auto",
+ stdout: stdout.stream,
+ stderr: stderr.stream,
+ },
+ { command: process.execPath },
+ environment,
+ ),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text())).toEqual({
+ home: credentialHome,
+ state: stateDirectory,
+ });
+ },
+ );
+
+ test.each(["validate", "patch", "verify-fix"])(
+ "%s rejects missing explicit API-key authentication before launch",
+ async (command) => {
+ const stderr = capture();
+ expect(
+ await main(
+ [command, "Synthetic issue", "--auth", "api-key"],
+ capture().stream,
+ stderr.stream,
+ dependencies({
+ onCodex: (_args, output, environment, input) =>
+ runCodexSkillCommand(
+ ["-e", 'throw new Error("must not launch")'],
+ output,
+ { command: process.execPath },
+ environment,
+ input,
+ ),
+ }),
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain(
+ "API-key authentication requires OPENAI_API_KEY or CODEX_API_KEY",
+ );
+ },
+ );
+ test.each([
+ ["auto", false, undefined],
+ ["chatgpt", false, undefined],
+ ["chatgpt", true, undefined],
+ ["chatgpt", false, "synthetic"],
+ ["api-key", false, undefined],
+ ["api-key", true, undefined],
+ ["auto", false, "synthetic"],
+ ["api-key", false, "synthetic"],
+ ] as const)(
+ "patch uses %s auth without replacing a saved login (failure: %s, provider: %s)",
+ async (auth, loginFailure, provider) => {
+ const repository = join(stateDirectory, "repository");
+ await mkdir(repository);
+ const ambientHome = join(stateDirectory, "ambient");
+ await mkdir(ambientHome);
+ const credentialHome = await prepareCodexSecurityCredentialHome({
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ });
+ await writeFile(
+ join(credentialHome, "config.toml"),
+ [
+ 'model_provider = "stale"',
+ 'profile = "stale"',
+ "[profiles.stale]",
+ 'model_provider = "stale"',
+ "[model_providers.stale]",
+ 'name = "Stale provider"',
+ 'base_url = "https://example.com/v1"',
+ 'env_key = "STALE_API_KEY"',
+ ].join("\n"),
+ );
+ const stored = JSON.stringify({
+ auth_mode: "apikey",
+ OPENAI_API_KEY: "SYNTHETIC_STORED_KEY",
+ });
+ await writeFile(join(credentialHome, "auth.json"), stored, {
+ mode: 0o600,
+ });
+ await writeFile(join(ambientHome, "auth.json"), stored, { mode: 0o600 });
+ if (auth === "chatgpt") {
+ await writeFile(
+ join(ambientHome, "config.toml"),
+ 'forced_login_method = "api"',
+ );
+ }
+ if (provider !== undefined) {
+ await writeFile(
+ join(ambientHome, "config.toml"),
+ [
+ ...(auth === "chatgpt" ? ['forced_login_method = "api"'] : []),
+ 'model_provider = "synthetic"',
+ "[model_providers.synthetic]",
+ 'name = "Synthetic provider"',
+ 'base_url = "https://example.com/v1"',
+ 'env_key = "OPENAI_API_KEY"',
+ `requires_openai_auth = ${auth === "chatgpt"}`,
+ ].join("\n"),
+ );
+ }
+ const usesSessionKey = auth !== "chatgpt" && provider === undefined;
+ const requestLog = join(stateDirectory, "requests.jsonl");
+ const stderr = capture();
+ const stdout = capture();
+ const environment = {
+ CODEX_HOME: ambientHome,
+ ...(provider === undefined || auth === "chatgpt"
+ ? {
+ OpenAI_API_KEY: " SYNTHETIC_OPENAI_KEY ",
+ CODEX_API_KEY: "SYNTHETIC_CODEX_KEY",
+ }
+ : {
+ OPENAI_API_KEY: "SYNTHETIC_CUSTOM_KEY",
+ SYNTHETIC_EXPECTED_CUSTOM_KEY: "SYNTHETIC_CUSTOM_KEY",
+ }),
+ SYNTHETIC_REQUEST_LOG: requestLog,
+ ...(auth === "chatgpt"
+ ? { SYNTHETIC_EXPECTED_PROVIDER: provider ?? "" }
+ : {}),
+ ...(auth === "chatgpt" && provider === undefined
+ ? { SYNTHETIC_CHECK_STARTUP_LOCK: "1" }
+ : {}),
+ ...(loginFailure ? { SYNTHETIC_LOGIN_FAILURE: "1" } : {}),
+ SYNTHETIC_EXPECTED_HOME:
+ auth === "chatgpt" ? credentialHome : ambientHome,
+ ...(usesSessionKey
+ ? { SYNTHETIC_EXPECTED_KEY: "SYNTHETIC_OPENAI_KEY" }
+ : {}),
+ };
+ expect(
+ await main(
+ ["patch", "Synthetic issue", "--auth", auth],
+ stdout.stream,
+ stderr.stream,
+ dependencies({
+ environment,
+ currentDirectory: repository,
+ onCodex: (args, output, environment, input) =>
+ runCodexSkillCommand(
+ [
+ fileURLToPath(
+ new URL("./fixtures/skill-auth.mjs", import.meta.url),
+ ),
+ ...args,
+ ],
+ output,
+ { command: process.execPath },
+ environment,
+ input,
+ ),
+ }),
+ ),
+ ).toBe(loginFailure ? 1 : 0);
+ expect(stdout.text()).toBe(
+ loginFailure ? "" : "Synthetic patch complete\n",
+ );
+ if (loginFailure)
+ expect(stderr.text()).toContain(
+ auth === "chatgpt"
+ ? "Authentication failed using a stored API key"
+ : "Authentication failed using OPENAI_API_KEY",
+ );
+ else expect(stderr.text()).toBe("");
+ const requests = (await readFile(requestLog, "utf8"))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ const methods = requests.map((request) => request.method);
+ if (!loginFailure) {
+ expect(
+ requests.find((request) => request.method === "thread/start").params
+ .modelProvider,
+ ).toBeUndefined();
+ }
+ expect(methods).toEqual([
+ "initialize",
+ "notifications/initialized",
+ ...(usesSessionKey ? ["account/login/start"] : []),
+ ...(loginFailure && usesSessionKey ? [] : ["thread/start"]),
+ ...(loginFailure ? [] : ["turn/start"]),
+ ]);
+ expect(await readFile(join(credentialHome, "auth.json"), "utf8")).toBe(
+ stored,
+ );
+ expect(await readFile(join(ambientHome, "auth.json"), "utf8")).toBe(
+ stored,
+ );
+ if (auth === "chatgpt") {
+ expect(
+ existsSync(join(credentialHome, ".codex-security-scan.lock")),
+ ).toBe(false);
+ expect(
+ parseToml(
+ await readFile(join(credentialHome, "config.toml"), "utf8"),
+ ),
+ ).toMatchObject({ forced_login_method: "api" });
+ }
+ },
+ );
+
+ test("imports an ambient login once and respects logout", async () => {
+ const ambientHome = join(stateDirectory, "ambient");
+ const environment = {
+ CODEX_HOME: ambientHome,
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ };
+ await mkdir(ambientHome);
+ const credentialHome =
+ await prepareCodexSecurityCredentialHome(environment);
+ const stored = JSON.stringify({
+ auth_mode: "apikey",
+ OPENAI_API_KEY: "SYNTHETIC_STORED_KEY",
+ });
+ await writeFile(join(ambientHome, "auth.json"), stored, { mode: 0o600 });
+ const run = () =>
+ runCodexSkillCommand(
+ [
+ "-e",
+ 'console.log(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:"done"}}))',
+ ],
+ {
+ command: "validate",
+ auth: "auto",
+ stdout: capture().stream,
+ stderr: capture().stream,
+ },
+ { command: process.execPath },
+ environment,
+ );
+ expect(await run()).toBe(0);
+ expect(await readFile(join(credentialHome, "auth.json"), "utf8")).toBe(
+ stored,
+ );
+ await rm(join(credentialHome, "auth.json"));
+ await setCodexSecurityCredentialLogout(credentialHome, true);
+ await expect(run()).rejects.toThrow("No credentials were found");
+ expect(existsSync(join(credentialHome, "auth.json"))).toBe(false);
+ });
+ test.each([
+ ["shared", "auto"],
+ ["ambient", "auto"],
+ ["ambient", "api-key"],
+ ] as const)(
+ "validation honors %s credential storage and login restrictions with %s auth",
+ async (authSource, auth) => {
+ const environment = {
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ CODEX_HOME: join(stateDirectory, "ambient"),
+ ...(auth === "api-key"
+ ? { OPENAI_API_KEY: "SYNTHETIC_SESSION_KEY" }
+ : {}),
+ };
+ const home = await prepareCodexSecurityCredentialHome(environment);
+ const sourceHome =
+ authSource === "shared" ? home : environment.CODEX_HOME;
+ await mkdir(environment.CODEX_HOME, { recursive: true });
+ await writeFile(join(home, "config.toml"), 'model = "existing-model"');
+ await writeFile(
+ join(environment.CODEX_HOME, "config.toml"),
+ [
+ 'cli_auth_credentials_store = "keyring"',
+ 'forced_login_method = "chatgpt"',
+ 'forced_chatgpt_workspace_id = "synthetic-workspace"',
+ 'model = "unrelated-model"',
+ ].join("\n"),
+ );
+ await writeFile(
+ join(sourceHome, "auth.json"),
+ JSON.stringify({
+ auth_mode: "apikey",
+ OPENAI_API_KEY: "SYNTHETIC_KEY",
+ }),
+ { mode: 0o600 },
+ );
+ const run = async () => {
+ const stdout = capture();
+ const source =
+ 'console.log(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:JSON.stringify({args:process.argv,home:process.env.CODEX_HOME})}}))';
+ expect(
+ await runCodexSkillCommand(
+ ["-e", source, "--"],
+ {
+ command: "validate",
+ auth,
+ stdout: stdout.stream,
+ stderr: capture().stream,
+ },
+ { command: process.execPath },
+ environment,
+ ),
+ ).toBe(0);
+ return JSON.parse(stdout.text());
+ };
+ const { args, home: runtimeHome } = await run();
+ expect(runtimeHome).toBe(
+ auth === "api-key" ? environment.CODEX_HOME : home,
+ );
+ expect(args).toContain('cli_auth_credentials_store="keyring"');
+ expect(args).toContain('forced_login_method="chatgpt"');
+ expect(args).toContain(
+ 'forced_chatgpt_workspace_id="synthetic-workspace"',
+ );
+ expect(args).not.toContain('model="unrelated-model"');
+ expect(
+ parseToml(await readFile(join(runtimeHome, "config.toml"), "utf8")),
+ ).toMatchObject({
+ cli_auth_credentials_store: "keyring",
+ forced_login_method: "chatgpt",
+ forced_chatgpt_workspace_id: "synthetic-workspace",
+ model: auth === "auto" ? "existing-model" : "unrelated-model",
+ });
+ await writeFile(
+ join(environment.CODEX_HOME, "config.toml"),
+ 'model = "unrelated-model"',
+ );
+ expect((await run()).args).toEqual([process.execPath]);
+ expect(
+ parseToml(await readFile(join(runtimeHome, "config.toml"), "utf8")),
+ ).toEqual({
+ model: auth === "auto" ? "existing-model" : "unrelated-model",
+ });
+ },
+ );
+ test.each(["patch", "verify-fix"] as const)(
+ "%s requires the selected external provider key",
+ async (command) => {
+ for (const [provider, key] of [
+ ["fireworks", "FIREWORKS_API_KEY"],
+ ["openrouter", "OPENROUTER_API_KEY"],
+ ] as const) {
+ for (const auth of ["api-key", "auto", "chatgpt"] as const) {
+ await expect(
+ runCodexSkillCommand(
+ ["-e", "process.exit(0)"],
+ {
+ command,
+ auth,
+ modelProvider: provider,
+ stdout: capture().stream,
+ stderr: capture().stream,
+ },
+ { command: process.execPath },
+ {
+ CODEX_HOME: join(stateDirectory, "ambient"),
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ },
+ ),
+ ).rejects.toThrow(key);
+ }
+ }
+ },
+ );
+
+ test.each(["validate", "patch", "verify-fix"] as const)(
+ "%s stops before starting a model command without a stored login",
+ async (command) => {
+ for (const auth of ["auto", "chatgpt"] as const) {
+ await expect(
+ runCodexSkillCommand(
+ ["invalid-synthetic-command"],
+ {
+ command,
+ auth,
+ stdout: capture().stream,
+ stderr: capture().stream,
+ },
+ resolveCodexCommand({}),
+ {
+ CODEX_HOME: join(stateDirectory, "ambient"),
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ },
+ ),
+ ).rejects.toThrow("No credentials were found");
+ }
+ },
+ );
+
+ test.each(["ChatGPT", "an API key"])(
+ "checks native login status without a credential file (%s)",
+ async (credentialLabel) => {
+ const environment = {
+ CODEX_HOME: join(stateDirectory, "ambient"),
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ };
+ const home = await prepareCodexSecurityCredentialHome(environment);
+ const preload = join(stateDirectory, "native-status.mjs");
+ const marker = join(home, "status-home");
+ await writeFile(
+ preload,
+ `
+import { basename, join } from "node:path";
+import { writeFileSync } from "node:fs";
+if (basename(process.argv[1] ?? "") === "login" && process.argv[2] === "status") {
+ writeFileSync(join(process.env.CODEX_HOME, "status-home"), process.env.CODEX_HOME);
+ console.log(${JSON.stringify("Logged in using " + credentialLabel)});
+ process.exit(0);
+}
+`,
+ );
+ const node = spawnSync("node", ["-p", "process.execPath"], {
+ encoding: "utf8",
+ });
+ expect(node.status, node.stderr).toBe(0);
+ const stderr = capture();
+ const unauthorized = credentialLabel === "an API key";
+ expect(
+ await runCodexSkillCommand(
+ [
+ "-e",
+ unauthorized
+ ? 'console.error("401 Unauthorized"); process.exit(1)'
+ : 'console.log(JSON.stringify({type:"item.completed",item:{type:"agent_message",text:"done"}}))',
+ ],
+ {
+ command: "validate",
+ auth: "chatgpt",
+ stdout: capture().stream,
+ stderr: stderr.stream,
+ },
+ { command: node.stdout.trim() },
+ {
+ ...environment,
+ NODE_OPTIONS: `--import=${pathToFileURL(preload).href}`,
+ },
+ ),
+ ).toBe(unauthorized ? 1 : 0);
+ if (unauthorized) {
+ expect(stderr.text()).toContain(
+ "Authentication failed using stored credentials",
+ );
+ expect(stderr.text()).not.toContain("ChatGPT");
+ }
+ expect(await readFile(marker, "utf8")).toBe(home);
+ expect(existsSync(join(home, "auth.json"))).toBe(false);
+ },
+ );
+ test.each(["validate", "patch", "verify-fix"] as const)(
+ "%s keeps imported credentials outside enclosing worktrees, including subdirectories and aliases",
+ async (command) => {
+ const repository = join(stateDirectory, "repository");
+ const ambientHome = join(stateDirectory, "ambient");
+ const alias = join(stateDirectory, "repository-alias");
+ const component = join(repository, "component");
+ const nestedRepository = join(repository, "nested");
+ await mkdir(component, { recursive: true });
+ await mkdir(nestedRepository);
+ for (const root of [repository, nestedRepository]) {
+ expect(spawnSync("git", ["init", "--quiet", root]).status).toBe(0);
+ }
+ await mkdir(ambientHome);
+ await symlink(
+ repository,
+ alias,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ await writeFile(
+ join(ambientHome, "auth.json"),
+ JSON.stringify({
+ auth_mode: "apikey",
+ OPENAI_API_KEY: "SYNTHETIC_STORED_KEY",
+ }),
+ { mode: 0o600 },
+ );
+ for (const target of [
+ repository,
+ alias,
+ component,
+ join(alias, "component"),
+ nestedRepository,
+ ]) {
+ const stderr = capture();
+ const status = await main(
+ [command, "Synthetic issue", "--auth", "chatgpt"],
+ capture().stream,
+ stderr.stream,
+ dependencies({
+ currentDirectory: target,
+ environment: {
+ CODEX_HOME: ambientHome,
+ CODEX_SECURITY_STATE_DIR: join(repository, "state"),
+ },
+ onCodex: (_args, output, environment) => {
+ if (output === undefined)
+ throw new Error("Missing model-command output");
+ expect(output.directory).toBe(target);
+ return runCodexSkillCommand(
+ ["-e", "process.exit(0)"],
+ { ...output, appServer: undefined },
+ { command: process.execPath },
+ environment,
+ );
+ },
+ }),
+ );
+ expect(
+ existsSync(join(repository, "state", "codex-home", "auth.json")),
+ ).toBe(false);
+ expect(status).toBe(2);
+ expect(stderr.text()).toContain("outside");
+ }
+ },
+ );
+});
diff --git a/sdk/typescript/tests-ts/cli-patch-trust.test.ts b/sdk/typescript/tests-ts/cli-patch-trust.test.ts
index 8ac158d40..5991fa6a5 100644
--- a/sdk/typescript/tests-ts/cli-patch-trust.test.ts
+++ b/sdk/typescript/tests-ts/cli-patch-trust.test.ts
@@ -1,7 +1,14 @@
import { execFileSync, spawn } from "node:child_process";
import { once } from "node:events";
import { existsSync } from "node:fs";
-import { mkdir, mkdtemp, readFile, realpath, rm } from "node:fs/promises";
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ writeFile,
+} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
@@ -204,3 +211,104 @@ test.each([
}
},
);
+
+test.each(["openai", undefined])(
+ "app-server preserves explicit and native providers during ephemeral API-key login (%s)",
+ async (selectedProvider) => {
+ const codexHome = await realpath(
+ await mkdtemp(join(tmpdir(), "codex-security-key-login-")),
+ );
+ const stored = JSON.stringify({
+ auth_mode: "apikey",
+ OPENAI_API_KEY: "SYNTHETIC_SAVED_KEY",
+ });
+ await writeFile(join(codexHome, "auth.json"), stored, { mode: 0o600 });
+ await writeCodexConfig(join(codexHome, "config.toml"), {
+ model_provider: "synthetic",
+ model_providers: {
+ synthetic: {
+ name: "Synthetic",
+ base_url: "http://127.0.0.1:9/v1",
+ wire_api: "responses",
+ requires_openai_auth: true,
+ },
+ },
+ });
+ let modelProvider: unknown;
+ const child = spawn(
+ resolveCodexCommand({}).command,
+ [
+ "app-server",
+ "--disable",
+ "plugins",
+ "--config",
+ 'cli_auth_credentials_store="ephemeral"',
+ ],
+ {
+ cwd: codexHome,
+ env: {
+ ...Object.fromEntries(
+ Object.entries(process.env).filter(([name]) =>
+ /^(path|systemroot|comspec|temp|tmp|tmpdir)$/iu.test(name),
+ ),
+ ),
+ CODEX_HOME: codexHome,
+ },
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ },
+ );
+ child.stderr.resume();
+ const closed = once(child, "close");
+ let account: unknown;
+ const input = new Writable({
+ write(chunk, _encoding, callback) {
+ const request = JSON.parse(chunk.toString());
+ // Inspect authentication before the first model request.
+ child.stdin.write(
+ request.method === "turn/start"
+ ? JSON.stringify({
+ id: "inspect",
+ method: "account/read",
+ params: { refreshToken: false },
+ }) + "\n"
+ : chunk,
+ callback,
+ );
+ },
+ final(callback) {
+ child.stdin.end(callback);
+ },
+ });
+ async function* events() {
+ for await (const line of createInterface({ input: child.stdout })) {
+ const event = JSON.parse(line);
+ if (event.id === 2) modelProvider = event.result?.modelProvider;
+ if (event.id === "inspect") {
+ account = event.result?.account;
+ child.stdin.end();
+ }
+ yield line + "\n";
+ }
+ }
+ try {
+ const result = await readSkillCommandOutput(events(), {
+ apiKey: "SYNTHETIC_SESSION_KEY",
+ modelProvider: selectedProvider,
+ prompt: "Synthetic finding",
+ directory: codexHome,
+ threadSource: "security_remediation",
+ input,
+ });
+ expect(result.error).toBeUndefined();
+ expect(account).toEqual({ type: "apiKey" });
+ expect(modelProvider).toBe(selectedProvider ?? "synthetic");
+ expect(await closed).toEqual([0, null]);
+ expect(await readFile(join(codexHome, "auth.json"), "utf8")).toBe(stored);
+ } finally {
+ child.kill();
+ await closed;
+ await rm(codexHome, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/sdk/typescript/tests-ts/cli-patch.test.ts b/sdk/typescript/tests-ts/cli-patch.test.ts
index 7493298ba..1fe49c5bd 100644
--- a/sdk/typescript/tests-ts/cli-patch.test.ts
+++ b/sdk/typescript/tests-ts/cli-patch.test.ts
@@ -1,3 +1,4 @@
+import { parse as parseToml } from "smol-toml";
import { describe, expect, test } from "bun:test";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
@@ -141,6 +142,8 @@ describe("scan and patch workflow", () => {
const outcome = await runWorkflow(
[
"patch",
+ "--auth",
+ "chatgpt",
"--scan",
"scan-1",
"--json",
@@ -149,11 +152,17 @@ describe("scan and patch workflow", () => {
{
result,
onWorkbench: () => savedScan(result),
+ onCodex: (args, output) => {
+ expect(output?.auth).toBe("chatgpt");
+ completePatches(args, output);
+ return 0;
+ },
},
{
configure: (current) => {
Object.assign(current, {
- assessPatchRisk: async () => {
+ assessPatchRisk: async (request: { auth?: string }) => {
+ expect(request.auth).toBe("chatgpt");
assessments += 1;
return patchRiskAssessment();
},
@@ -567,10 +576,58 @@ describe("scan and patch workflow", () => {
});
});
+ test.each(["synthetic.provider", "openai"])(
+ "preserves %s command-provider authentication when patching after a scan",
+ async (provider) => {
+ const home = join(tmpdir(), "synthetic-auth-home");
+ let providerOverride: string | undefined;
+ const outcome = await runWorkflow(
+ [
+ "scan",
+ "--patch",
+ "--auth",
+ "api-key",
+ "--json",
+ "--codex",
+ `model_provider=${JSON.stringify(provider)}`,
+ "--codex",
+ `model_providers={${JSON.stringify(provider)}={name="Synthetic",auth={command="./synthetic-auth",args=["--json"]}}}`,
+ ],
+ {
+ result: resultWithFindings(["high"]),
+ environment: {
+ CODEX_HOME: home,
+ },
+ onCodex: (args, output) => {
+ providerOverride = args.find((arg) =>
+ arg.startsWith("model_providers="),
+ );
+ expect(output?.modelProvider).toBe(provider);
+ expect(output?.providerConfiguration?.["auth"]).toEqual({
+ command: "./synthetic-auth",
+ args: ["--json"],
+ });
+ completePatches(args, output);
+ return 0;
+ },
+ },
+ );
+ expect(outcome.exitCode, outcome.stderr).toBe(0);
+ expect(parseToml(providerOverride!)).toEqual({
+ model_providers: {
+ [provider]: {
+ name: "Synthetic",
+ auth: { command: "./synthetic-auth", args: ["--json"], cwd: home },
+ },
+ },
+ });
+ },
+ );
+
test("passes the scan model, provider, and selected authentication to patching", async () => {
const result = resultWithFindings(["high"]);
let invocation: readonly string[] = [];
- let environment: NodeJS.ProcessEnv | undefined;
+ let authentication: string | undefined;
const chatgpt = await runWorkflow(
[
"scan",
@@ -591,7 +648,10 @@ describe("scan and patch workflow", () => {
},
onCodex: (args, output, selectedEnvironment) => {
invocation = args;
- environment = selectedEnvironment;
+ authentication = output?.auth;
+ expect(selectedEnvironment?.["CODEX_SECURITY_STATE_DIR"]).toBe(
+ STATE_DIRECTORY,
+ );
completePatches(args, output);
return 0;
},
@@ -600,11 +660,7 @@ describe("scan and patch workflow", () => {
expect(chatgpt.exitCode).toBe(0);
expect(invocation).toContain('model="gpt-5.6-terra"');
expect(invocation).toContain('model_reasoning_effort="high"');
- expect(environment).not.toHaveProperty("OPENAI_API_KEY");
- expect(environment).toHaveProperty(
- "CODEX_HOME",
- join(STATE_DIRECTORY, "codex-home"),
- );
+ expect(authentication).toBe("chatgpt");
const attributed = await runWorkflow(
[
@@ -629,31 +685,45 @@ describe("scan and patch workflow", () => {
expect(attributed.exitCode).toBe(0);
expect(invocation).toContain('safety_identifier="synthetic-user"');
- const provider = await runWorkflow(
+ for (const selection of [
+ ["--provider", "fireworks"],
+ ["--codex", 'model_provider="fireworks"'],
[
- "scan",
- "--patch",
- "--provider",
- "fireworks",
- "--model",
- "accounts/fireworks/models/example",
- "--json",
+ "--codex",
+ 'profile="synthetic"',
+ "--codex",
+ 'profiles.synthetic.model_provider="fireworks"',
],
- {
- result,
- environment: { FIREWORKS_API_KEY: "SYNTHETIC_FIREWORKS_KEY_123" },
- onCodex: (args, output) => {
- invocation = args;
- completePatches(args, output);
- return 0;
+ ]) {
+ const provider = await runWorkflow(
+ [
+ "scan",
+ "--patch",
+ ...selection,
+ "--model",
+ "accounts/fireworks/models/example",
+ "--json",
+ ],
+ {
+ result,
+ environment: { FIREWORKS_API_KEY: "SYNTHETIC_FIREWORKS_KEY_123" },
+ onCodex: (args, output) => {
+ invocation = args;
+ completePatches(args, output);
+ return 0;
+ },
},
- },
- );
- expect(provider.exitCode).toBe(0);
- expect(invocation).toContain('model_provider="fireworks"');
- expect(invocation).toContain(
- 'model_providers.fireworks.env_key="FIREWORKS_API_KEY"',
- );
+ );
+ expect(provider.exitCode).toBe(0);
+ expect(invocation).toContain('model_provider="fireworks"');
+ expect(
+ invocation.some(
+ (argument) =>
+ argument.startsWith("model_providers=") &&
+ argument.includes('"env_key"="FIREWORKS_API_KEY"'),
+ ),
+ ).toBe(true);
+ }
});
test("publishes only verified patch files and preserves unrelated staged changes", async () => {
diff --git a/sdk/typescript/tests-ts/cli-skill-native-config.test.ts b/sdk/typescript/tests-ts/cli-skill-native-config.test.ts
new file mode 100644
index 000000000..e01a74744
--- /dev/null
+++ b/sdk/typescript/tests-ts/cli-skill-native-config.test.ts
@@ -0,0 +1,115 @@
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect, test } from "bun:test";
+import { runCodexSkillCommand } from "../src/cli.js";
+import { writeCodexConfig } from "../src/config.js";
+import {
+ prepareCodexSecurityCredentialHome,
+ resolveCodexCommand,
+} from "../src/runtime.js";
+import { capture } from "./cli-fixtures.js";
+
+test.each([
+ ["trusted", undefined, "patch", ""],
+ ["untrusted", undefined, "patch", ""],
+ [undefined, undefined, "patch", ""],
+ ["trusted", "openai", "patch", ""],
+ ["trusted", undefined, "verify-fix", ""],
+ ["trusted", undefined, "patch", "component"],
+] as const)(
+ "stored-auth commands preserve native project configuration (%s, provider: %s, command: %s, subdirectory: %s)",
+ async (trust, modelProvider, command, subdirectory) => {
+ const root = await realpath(
+ await mkdtemp(join(tmpdir(), "codex-security-native-config-")),
+ );
+ const repository = join(root, "repository");
+ const directory = join(repository, subdirectory);
+ const ambientHome = join(root, "ambient");
+ const environment = {
+ ...Object.fromEntries(
+ Object.entries(process.env).filter(([name]) =>
+ /^(path|systemroot|comspec|temp|tmp|tmpdir)$/iu.test(name),
+ ),
+ ),
+ CODEX_HOME: ambientHome,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ SYNTHETIC_NATIVE_CODEX: resolveCodexCommand({}).command,
+ };
+ try {
+ await mkdir(directory, { recursive: true });
+ execFileSync("git", ["init", "--quiet", repository]);
+ await writeCodexConfig(join(repository, ".codex", "config.toml"), {
+ mcp_servers: {
+ synthetic: { command: "synthetic-unused-command", enabled: false },
+ },
+ });
+ await writeCodexConfig(join(ambientHome, "config.toml"), {
+ cli_auth_credentials_store: "file",
+ ...(trust === undefined
+ ? {}
+ : { projects: { [repository]: { trust_level: trust } } }),
+ });
+ const sharedHome = await prepareCodexSecurityCredentialHome(environment);
+ await writeCodexConfig(join(sharedHome, "config.toml"), {
+ projects: {
+ [repository]: {
+ trust_level: trust === "trusted" ? "untrusted" : "trusted",
+ },
+ },
+ });
+ await writeFile(
+ join(sharedHome, "auth.json"),
+ JSON.stringify({
+ auth_mode: "apikey",
+ OPENAI_API_KEY: "SYNTHETIC_KEY",
+ }),
+ { mode: 0o600 },
+ );
+ const stdout = capture();
+ const stderr = capture();
+ const status = await runCodexSkillCommand(
+ [
+ fileURLToPath(
+ new URL("./fixtures/skill-native-config.mjs", import.meta.url),
+ ),
+ "app-server",
+ "--disable",
+ "plugins",
+ "--config",
+ "analytics.enabled=false",
+ ],
+ {
+ command,
+ auth: "chatgpt",
+ modelProvider,
+ directory,
+ stdout: stdout.stream,
+ stderr: stderr.stream,
+ appServer: {
+ directory,
+ prompt: "Synthetic finding",
+ threadSource:
+ command === "patch"
+ ? "security_remediation"
+ : "security_validation",
+ ...(command === "verify-fix"
+ ? { sandbox: "read-only" as const }
+ : {}),
+ },
+ },
+ { command: process.execPath },
+ environment,
+ );
+ expect(status, stderr.text()).toBe(0);
+ expect(JSON.parse(stdout.text())).toEqual({
+ modelProvider: "openai",
+ projectServerConfigured: trust === "trusted",
+ });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/sdk/typescript/tests-ts/cli-skills.test.ts b/sdk/typescript/tests-ts/cli-skills.test.ts
index 252f8d15f..3fcb306d9 100644
--- a/sdk/typescript/tests-ts/cli-skills.test.ts
+++ b/sdk/typescript/tests-ts/cli-skills.test.ts
@@ -1244,6 +1244,36 @@ process.stdout.write(JSON.stringify({
}
});
+ test("keeps unknown credential failures neutral", () => {
+ for (const authentication of [
+ null,
+ { method: "stored_credentials", verified: false } as const,
+ ]) {
+ const message = skillCommandFailure(
+ "patch",
+ 1,
+ "401 Unauthorized",
+ authentication,
+ );
+ expect(message).toContain("Authentication failed");
+ expect(message).not.toContain("ChatGPT");
+ expect(message).not.toContain("--auth chatgpt");
+ }
+ });
+
+ test.each(["FIREWORKS_API_KEY", "OPENROUTER_API_KEY"] as const)(
+ "external-provider failures recommend the selected key (%s)",
+ (source) => {
+ const message = skillCommandFailure("patch", 1, "401 Unauthorized", {
+ method: "api_key",
+ source,
+ verified: false,
+ });
+ expect(message).toContain(source);
+ expect(message).not.toContain("--auth chatgpt");
+ },
+ );
+
test("forwards only completed skill output and redacts subprocess diagnostics", async () => {
const cases = [
{
diff --git a/sdk/typescript/tests-ts/fixtures/skill-auth.mjs b/sdk/typescript/tests-ts/fixtures/skill-auth.mjs
new file mode 100644
index 000000000..f0a790360
--- /dev/null
+++ b/sdk/typescript/tests-ts/fixtures/skill-auth.mjs
@@ -0,0 +1,107 @@
+import assert from "node:assert/strict";
+import { appendFileSync, readFileSync, existsSync } from "node:fs";
+import { join } from "node:path";
+import { parse as parseToml } from "smol-toml";
+import { createInterface } from "node:readline";
+
+const send = (value) => process.stdout.write(`${JSON.stringify(value)}\n`);
+let loggedIn = false;
+for await (const line of createInterface({ input: process.stdin })) {
+ const request = JSON.parse(line);
+ appendFileSync(process.env.SYNTHETIC_REQUEST_LOG, `${line}\n`);
+ if (request.method === "initialize") {
+ if (process.env.SYNTHETIC_CHECK_STARTUP_LOCK) {
+ assert.equal(
+ existsSync(join(process.env.CODEX_HOME, ".codex-security-scan.lock")),
+ true,
+ );
+ }
+ send({ id: request.id, result: {} });
+ } else if (request.method === "account/login/start") {
+ assert.deepEqual(request.params, {
+ type: "apiKey",
+ apiKey: process.env.SYNTHETIC_EXPECTED_KEY,
+ });
+ assert.ok(process.argv.includes('cli_auth_credentials_store="ephemeral"'));
+ if (process.env.SYNTHETIC_LOGIN_FAILURE) {
+ send({
+ id: request.id,
+ error: { code: -32000, message: "Unauthorized" },
+ });
+ } else {
+ loggedIn = true;
+ send({ id: request.id, result: { type: "apiKey" } });
+ }
+ } else if (request.method === "thread/start") {
+ if (process.env.SYNTHETIC_CHECK_STARTUP_LOCK) {
+ assert.equal(
+ existsSync(join(process.env.CODEX_HOME, ".codex-security-scan.lock")),
+ true,
+ );
+ }
+ if (process.env.SYNTHETIC_EXPECTED_PROVIDER !== undefined) {
+ const config = parseToml(
+ readFileSync(join(process.env.CODEX_HOME, "config.toml"), "utf8"),
+ );
+ assert.equal(
+ config.model_provider,
+ process.env.SYNTHETIC_EXPECTED_PROVIDER || undefined,
+ );
+ assert.equal(config.profile, undefined);
+ assert.equal(config.model_providers?.stale, undefined);
+ if (config.model_provider === "synthetic")
+ assert.equal(
+ config.model_providers.synthetic.requires_openai_auth,
+ true,
+ );
+ }
+ assert.equal(loggedIn, Boolean(process.env.SYNTHETIC_EXPECTED_KEY));
+ assert.equal(process.env.CODEX_HOME, process.env.SYNTHETIC_EXPECTED_HOME);
+ assert.equal(process.env.CODEX_API_KEY, process.env.SYNTHETIC_EXPECTED_KEY);
+ assert.deepEqual(
+ Object.keys(process.env).filter((key) =>
+ ["OPENAI_API_KEY", "CODEX_API_KEY"].includes(key.toUpperCase()),
+ ),
+ process.env.SYNTHETIC_EXPECTED_CUSTOM_KEY
+ ? ["OPENAI_API_KEY"]
+ : process.env.SYNTHETIC_EXPECTED_KEY
+ ? ["CODEX_API_KEY"]
+ : [],
+ );
+ assert.equal(
+ process.env.OPENAI_API_KEY,
+ process.env.SYNTHETIC_EXPECTED_CUSTOM_KEY,
+ );
+ if (process.env.SYNTHETIC_LOGIN_FAILURE) {
+ send({
+ id: request.id,
+ error: { code: -32000, message: "Unauthorized" },
+ });
+ } else {
+ send({ id: request.id, result: { thread: { id: "synthetic-thread" } } });
+ }
+ } else if (request.method === "turn/start") {
+ if (process.env.SYNTHETIC_CHECK_STARTUP_LOCK) {
+ assert.equal(
+ existsSync(join(process.env.CODEX_HOME, ".codex-security-scan.lock")),
+ false,
+ );
+ }
+ send({ id: request.id, result: { turn: { id: "synthetic-turn" } } });
+ send({
+ method: "item/completed",
+ params: {
+ threadId: "synthetic-thread",
+ turnId: "synthetic-turn",
+ item: { type: "agentMessage", text: "Synthetic patch complete" },
+ },
+ });
+ send({
+ method: "turn/completed",
+ params: {
+ threadId: "synthetic-thread",
+ turn: { id: "synthetic-turn", status: "completed" },
+ },
+ });
+ }
+}
diff --git a/sdk/typescript/tests-ts/fixtures/skill-native-config.mjs b/sdk/typescript/tests-ts/fixtures/skill-native-config.mjs
new file mode 100644
index 000000000..7a201bcca
--- /dev/null
+++ b/sdk/typescript/tests-ts/fixtures/skill-native-config.mjs
@@ -0,0 +1,63 @@
+import { spawn } from "node:child_process";
+import { createInterface } from "node:readline";
+
+const child = spawn(process.env.SYNTHETIC_NATIVE_CODEX, process.argv.slice(2), {
+ env: process.env,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+});
+child.stderr.pipe(process.stderr);
+const send = (value) => process.stdout.write(JSON.stringify(value) + "\n");
+let turnRequest;
+let modelProvider;
+await Promise.all([
+ (async () => {
+ for await (const line of createInterface({ input: process.stdin })) {
+ const request = JSON.parse(line);
+ if (request.method === "turn/start") {
+ turnRequest = request;
+ child.stdin.write(
+ JSON.stringify({
+ id: "inspect-config",
+ method: "config/read",
+ params: { cwd: process.cwd(), includeLayers: true },
+ }) + "\n",
+ );
+ } else child.stdin.write(line + "\n");
+ }
+ child.stdin.end();
+ })(),
+ (async () => {
+ for await (const line of createInterface({ input: child.stdout })) {
+ const response = JSON.parse(line);
+ if (response.id === 2) modelProvider = response.result?.modelProvider;
+ if (response.id !== "inspect-config") {
+ process.stdout.write(line + "\n");
+ continue;
+ }
+ const threadId = turnRequest.params.threadId;
+ const turnId = "synthetic-turn";
+ const config = response.result.config;
+ send({ id: turnRequest.id, result: { turn: { id: turnId } } });
+ send({
+ method: "item/completed",
+ params: {
+ threadId,
+ turnId,
+ item: {
+ type: "agentMessage",
+ text: JSON.stringify({
+ modelProvider,
+ projectServerConfigured:
+ config.mcp_servers?.synthetic !== undefined,
+ }),
+ },
+ },
+ });
+ send({
+ method: "turn/completed",
+ params: { threadId, turn: { id: turnId, status: "completed" } },
+ });
+ }
+ })(),
+]);