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): respect the dedicated sign-in in the authentication prompt (#2348)

Dipesh Babu7f04446af136
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index d98492299..0ac9d20d9 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -78,7 +78,9 @@ your local browser. Keep SSH connected until login finishes.
### OpenAI credentials
Interactive scans ask which credentials to use when both ChatGPT and an
-environment API key are available. Noninteractive commands prefer
+environment API key are available. A dedicated sign-in takes precedence. After
+`codex-security logout`, the prompt skips the ambient sign-in until you log in
+again. Noninteractive commands prefer
`OPENAI_API_KEY`, then `CODEX_API_KEY`, then stored credentials. Choose explicitly
with `--auth`:
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index fd518dcc3..0ee19491c 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -107,6 +107,7 @@ import {
configuredCodexHome,
environmentEntry,
readCodexHomeConfig,
+ withoutOpenAiApiKeys,
} from "./auth.js";
import { loadContract, sha256Text } from "./contract.js";
import type { DeepScanDiagnostic } from "./deep-scan.js";
@@ -296,7 +297,9 @@ import {
withCredentialHomeLock,
requireOutputOutsideRepositories,
canonicalizeModelSafePath,
+ codexSecurityCredentialAllowsAmbientImport,
codexSecurityCredentialHome,
+ codexSecurityHasStoredFileCredentials,
codexSecurityStateDirectory,
executablePathForSpawn,
environmentWithGit,
@@ -1401,6 +1404,38 @@ export const runRepositoryCommand: CliDependencies["runRepositoryCommand"] =
return options?.trim === false ? stdout : stdout.trim();
};
+/** @internal Inspect the sign-in that an interactive scan could actually select. */
+export async function hasStoredChatGPTSignIn(
+ environment: NodeJS.ProcessEnv,
+ signal?: AbortSignal,
+): Promise<boolean> {
+ signal?.throwIfAborted();
+ const storedEnvironment = withoutOpenAiApiKeys(environment);
+ const command = resolveCodexCommand(storedEnvironment);
+ if (existsSync(codexSecurityCredentialHome(environment))) {
+ const home = await prepareCodexSecurityCredentialHome(environment);
+ const dedicated = await accountStatus(
+ command,
+ { ...storedEnvironment, CODEX_HOME: home },
+ signal,
+ );
+ if (dedicated.authenticated) return /\bchatgpt\b/iu.test(dedicated.details);
+ try {
+ if (
+ !(await codexSecurityCredentialAllowsAmbientImport(home)) ||
+ (await codexSecurityHasStoredFileCredentials(home))
+ ) {
+ return false;
+ }
+ } catch {
+ // An unusable credential file or logout marker does not prevent API-key scans.
+ return false;
+ }
+ }
+ const ambient = await accountStatus(command, storedEnvironment, signal);
+ return ambient.authenticated && /\bchatgpt\b/iu.test(ambient.details);
+}
+
const DEFAULT_DEPENDENCIES: CliDependencies = {
createSecurity: (config, onDeepScanDiagnostic) =>
new CodexSecurity(config, undefined, {
@@ -1410,37 +1445,8 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
environment: process.env,
checkForUpdate: (signal) =>
checkForUpdate({ environment: process.env, signal }),
- hasStoredChatGPTSignIn: async (signal) => {
- signal?.throwIfAborted();
- const environment = Object.fromEntries(
- Object.entries(process.env).filter(
- ([name]) =>
- name.toUpperCase() !== "OPENAI_API_KEY" &&
- name.toUpperCase() !== "CODEX_API_KEY",
- ),
- );
- const command = resolveCodexCommand(environment);
- if (existsSync(codexSecurityCredentialHome(process.env))) {
- const dedicatedStatus = await accountStatus(
- command,
- {
- ...environment,
- CODEX_HOME: await prepareCodexSecurityCredentialHome(process.env),
- },
- signal,
- );
- if (
- dedicatedStatus.authenticated &&
- /\bchatgpt\b/iu.test(dedicatedStatus.details)
- ) {
- return true;
- }
- }
- const ambientStatus = await accountStatus(command, environment, signal);
- return (
- ambientStatus.authenticated && /\bchatgpt\b/iu.test(ambientStatus.details)
- );
- },
+ hasStoredChatGPTSignIn: (signal) =>
+ hasStoredChatGPTSignIn(process.env, signal),
currentDirectory: cwd,
now: Date.now,
setInterval: (callback, milliseconds) => setInterval(callback, milliseconds),
diff --git a/sdk/typescript/tests-ts/auth-status-scan.test.ts b/sdk/typescript/tests-ts/auth-status-scan.test.ts
new file mode 100644
index 000000000..7da169ddc
--- /dev/null
+++ b/sdk/typescript/tests-ts/auth-status-scan.test.ts
@@ -0,0 +1,84 @@
+import { afterEach, expect, test } from "bun:test";
+import { mkdir, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { main } from "../src/cli.js";
+import { resolveCodexCommand, runCodexCommand } from "../src/runtime.js";
+import { capture, dependencies } from "./cli-fixtures.js";
+import { copyCredentialTestPlugin } from "./plugin-root.js";
+import { TestClient } from "./support/api-client.js";
+import { chatGptTokens } from "./support/chatgpt-credentials.js";
+import { createApiTestFixtures } from "./support/temporary-directories.js";
+
+const { cleanup, temporaryDirectory } = createApiTestFixtures();
+afterEach(cleanup);
+
+test.each(["CLI", "SDK"] as const)(
+ "%s status keeps a later scan authenticated after the ambient login file disappears",
+ async (surface) => {
+ const root = await temporaryDirectory();
+ const ambientHome = join(root, "ambient-home");
+ const state = join(root, "state");
+ const repository = join(root, "repository");
+ const scanDir = join(root, "scan");
+ for (const directory of [ambientHome, repository, scanDir])
+ await mkdir(directory, { mode: 0o700 });
+ const source = join(ambientHome, "auth.json");
+ await writeFile(
+ source,
+ JSON.stringify({ auth_mode: "chatgpt", tokens: chatGptTokens }),
+ { mode: 0o600 },
+ );
+ const environment = {
+ PATH: process.env["PATH"],
+ HOME: root,
+ USERPROFILE: root,
+ CODEX_HOME: ambientHome,
+ CODEX_SECURITY_STATE_DIR: state,
+ };
+
+ if (surface === "CLI") {
+ const stderr = capture();
+ expect(
+ await main(
+ ["login", "status"],
+ capture().stream,
+ stderr.stream,
+ dependencies({
+ environment,
+ onCodex: async (args, _output, childEnvironment) => {
+ const result = await runCodexCommand(
+ resolveCodexCommand(childEnvironment!),
+ args,
+ childEnvironment!,
+ );
+ return result.exitCode ?? 1;
+ },
+ }),
+ ),
+ stderr.text(),
+ ).toBe(0);
+ } else {
+ await using client = TestClient.withDependencies({ environment });
+ expect((await client.account()).authenticated).toBe(true);
+ }
+
+ await rm(source);
+ await using scanner = new TestClient(
+ { pluginPath: await copyCredentialTestPlugin(root) },
+ {
+ environment,
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: (options) => {
+ expect(options.env?.["CODEX_HOME"]).toBe(join(state, "codex-home"));
+ throw new Error("authenticated scan reached execution");
+ },
+ },
+ );
+ await expect(scanner.run(repository, { auth: "chatgpt" })).rejects.toThrow(
+ "authenticated scan reached execution",
+ );
+ },
+ 60_000,
+);
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index 492a44630..d11688486 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -18,7 +18,11 @@ import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { afterEach, beforeEach, describe, expect, test, mock } from "bun:test";
import { parse as parseToml } from "smol-toml";
-import { main, runCodexSkillCommand } from "../src/cli.js";
+import {
+ hasStoredChatGPTSignIn,
+ main,
+ runCodexSkillCommand,
+} from "../src/cli.js";
import {
CodexSecurityError,
type JsonObject,
@@ -38,6 +42,7 @@ import {
fakeSecurity,
failingSecurity,
} from "./cli-fixtures.js";
+import { chatGptTokens } from "./support/chatgpt-credentials.js";
import { temporaryDirectory } from "./support/temporary-directories.js";
import { throwing } from "./support/errors.js";
@@ -627,6 +632,50 @@ describe("CLI authentication", () => {
}
});
+ test.each([
+ ["ambient ChatGPT", true],
+ ["dedicated API key", false],
+ ["truncated dedicated credential file", false],
+ ["explicit logout", false],
+ ["invalid logout marker", false],
+ ] as const)(
+ "offers an interactive ChatGPT choice with %s: %p",
+ async (source, offered) => {
+ const ambientHome = join(stateDirectory, "ambient");
+ const dedicatedHome = await createCredentialHome();
+ await mkdir(ambientHome, { mode: 0o700 });
+ await writeFile(
+ join(ambientHome, "auth.json"),
+ JSON.stringify({ auth_mode: "chatgpt", tokens: chatGptTokens }),
+ { mode: 0o600 },
+ );
+ if (source === "explicit logout") {
+ await setCodexSecurityCredentialLogout(dedicatedHome, true);
+ } else if (source === "invalid logout marker") {
+ await mkdir(join(dedicatedHome, ".codex-security-logged-out"));
+ } else if (source !== "ambient ChatGPT") {
+ await writeFile(
+ join(dedicatedHome, "auth.json"),
+ source === "dedicated API key"
+ ? '{"OPENAI_API_KEY":"synthetic-stored-key"}'
+ : "{",
+ { mode: 0o600 },
+ );
+ }
+ const deps = dependencies({
+ environment: { OPENAI_API_KEY: "synthetic-environment-key" },
+ });
+ deps.hasStoredChatGPTSignIn = (signal) =>
+ hasStoredChatGPTSignIn(deps.environment, signal);
+ deps.scanAuthenticationPrompt = selectionPrompt(
+ async (_message, options) => options[0]!.value,
+ );
+ const stderr = captureCli(main, "stderr", true);
+ expect(await stderr.run(["scan"], deps), stderr.text()).toBe(0);
+ expect(stderr.text().includes("Both a ChatGPT sign-in")).toBe(offered);
+ },
+ );
+
test("cancels sign-in discovery and authentication prompts before starting a scan", async () => {
for (const stage of ["status", "prompt"] as const) {
const signals = new FakeSignals();
diff --git a/sdk/typescript/tests-ts/support/chatgpt-credentials.ts b/sdk/typescript/tests-ts/support/chatgpt-credentials.ts
new file mode 100644
index 000000000..912b7472f
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/chatgpt-credentials.ts
@@ -0,0 +1,6 @@
+// Syntactically valid ID-token claims for the pinned native login status command.
+export const chatGptTokens = {
+ id_token: "eyJhbGciOiJub25lIn0.eyJzdWIiOiJ0ZXN0In0.c2ln",
+ access_token: "synthetic-access",
+ refresh_token: "synthetic-refresh",
+};