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): preserve logout across credential imports (#759)

mldangelo-oai69e9bfaa7071
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 6415afabd..a3b5957d2 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
@@ -989,6 +989,9 @@ async function testOpenAiCredentialsReachWorker() {
openai: "synthetic-openai-key",
accountResult: { account: { type: "chatgpt" }, requiresOpenaiAuth: true },
},
+ {
+ accountResult: { account: { type: "chatgpt" }, requiresOpenaiAuth: true },
+ },
{
openai: "synthetic-provider-key",
accountResult: { account: null, requiresOpenaiAuth: false },
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index fbab74222..afe62db69 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -82,8 +82,15 @@ with `requires_openai_auth = true`.
Codex carries credential-storage, forced-login, and workspace settings from the
ambient configuration into this home. Managed-device policies still apply;
workspace-managed policies may require ChatGPT credentials even with an API key.
-If the home has no credentials, it imports an existing file-based Codex login.
-Logout disables imports until the next login.
+Without an overriding environment API key, scans and status checks import
+existing file-based Codex credentials when this home is empty. Import errors make
+`login status` exit with code 2 and SDK `account()` reject its promise. Logout
+disables imports until you log in again. Status imports and logout share the
+credential-home lock so a concurrent status check cannot restore credentials
+after logout completes.
+
+Scans and status checks expand a home-relative `CODEX_HOME` using the caller's
+`HOME` or `USERPROFILE` environment setting.
If credentials cannot refresh, run `login status`. Retry if the sign-in recently
changed; otherwise run `logout`, then `login`.
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 86a0088e7..a2954e565 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -12,7 +12,7 @@ import {
writeFile,
} from "node:fs/promises";
import { randomUUID } from "node:crypto";
-import { homedir, tmpdir } from "node:os";
+import { tmpdir } from "node:os";
import { isDeepStrictEqual } from "node:util";
import {
basename,
@@ -182,6 +182,7 @@ import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";
import {
canonicalConfigPath,
acquireCodexSecurityCredentialHomeLock,
+ withCredentialHomeLock,
bootstrapPlugin,
bundledPluginRoot,
cleanupSdkDirectory,
@@ -2549,13 +2550,16 @@ export class CodexSecurity {
}
const authentication = await this.#authentication();
this.#requireOpen();
- const ambientHome =
- environmentValue(this.#dependencies.environment, "CODEX_HOME") ??
- join(homedir(), ".codex");
- await initialCredentialsAvailable(
- this.#dependencies.environment,
- ambientHome,
+ const ambientHome = scanCodexHome(this.#dependencies.environment);
+ await withCredentialHomeLock(
authentication.codexHome,
+ () =>
+ initialCredentialsAvailable(
+ this.#dependencies.environment,
+ ambientHome,
+ authentication.codexHome,
+ ),
+ this.#abortController.signal,
);
return await accountStatus(
await this.#providerPreflightCommand(),
@@ -2569,12 +2573,21 @@ export class CodexSecurity {
await this.#trackOperation(async () => {
const authentication = await this.#authentication();
this.#requireOpen();
- await codexLogout(
- await this.#providerPreflightCommand(),
- authentication.environment,
+ await withCredentialHomeLock(
+ authentication.codexHome,
+ async () => {
+ await codexLogout(
+ await this.#providerPreflightCommand(),
+ authentication.environment,
+ this.#abortController.signal,
+ );
+ await setCodexSecurityCredentialLogout(
+ authentication.codexHome,
+ true,
+ );
+ },
this.#abortController.signal,
);
- await setCodexSecurityCredentialLogout(authentication.codexHome, true);
if (this.#runtime !== null) this.#runtime.credentialsAvailable = false;
this.#runtimeCredentialSource = null;
this.#requireOpen();
@@ -2943,9 +2956,7 @@ export class CodexSecurity {
authentication.method === "stored_credentials" &&
this.#runtimeCredentialSource === "api_key"
) {
- const ambientHome =
- environmentValue(this.#dependencies.environment, "CODEX_HOME") ??
- join(homedir(), ".codex");
+ const ambientHome = scanCodexHome(this.#dependencies.environment);
runtime.credentialsAvailable = await initialCredentialsAvailable(
scanEnvironment,
ambientHome,
@@ -3485,13 +3496,7 @@ export class CodexSecurity {
deepScanConfiguration: await resolveDeepScanConfig(
deep,
join(
- expandHome(
- environmentValue(
- this.#dependencies.environment,
- "CODEX_HOME",
- ) ?? join(homedir(), ".codex"),
- this.#dependencies.environment,
- ),
+ scanCodexHome(this.#dependencies.environment),
"codex-security",
"config.toml",
),
@@ -3540,12 +3545,7 @@ export class CodexSecurity {
bootstrapWorkspace,
signal,
);
- const nodeAmbientHome = join(homedir(), ".codex");
- const configuredAmbientHome = environmentValue(
- processEnvironment,
- "CODEX_HOME",
- );
- const ambientHome = configuredAmbientHome ?? nodeAmbientHome;
+ const ambientHome = scanCodexHome(processEnvironment);
const codexConfig = await preserveCodexSecurityPluginRegistration(
codexHome,
sharedCredentialCodexConfig(requestedConfig, codexHome),
@@ -3654,6 +3654,14 @@ export function createSecurity(
return new CodexSecurity(config);
}
+// Scan settings accept case-insensitive environment keys on every platform.
+export function scanCodexHome(environment: ProcessEnvironment): string {
+ return configuredCodexHome({
+ ...environment,
+ CODEX_HOME: environmentValue(environment, "CODEX_HOME"),
+ });
+}
+
export async function initialCredentialsAvailable(
environment: ProcessEnvironment,
ambientHome: string,
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 4bb90e321..e27d36891 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -29,7 +29,7 @@ import {
rm,
writeFile,
} from "node:fs/promises";
-import { homedir, tmpdir } from "node:os";
+import { tmpdir } from "node:os";
import {
basename,
dirname,
@@ -66,6 +66,7 @@ import {
environmentValue,
formatEnvironmentVariableRemovalGuidance,
initialCredentialsAvailable,
+ scanCodexHome,
listRepositoryFindings,
SCAN_AUTH_MODES,
scanAuthentication,
@@ -185,6 +186,7 @@ import { importScan, type ImportScanOptions } from "./import-scan.js";
import {
bundledPluginRoot,
acquireCodexSecurityCredentialHomeLock,
+ withCredentialHomeLock,
requireOutputOutsideRepositories,
canonicalizeModelSafePath,
codexSecurityCredentialHome,
@@ -1159,9 +1161,6 @@ interface CliDependencies {
createPolicySecurity?: (config: CodexSecurityConfig) => PolicySecurity;
policyPrompt?: PolicyPrompt;
environment: NodeJS.ProcessEnv;
- prepareAuthenticationHome?: (
- environment: NodeJS.ProcessEnv,
- ) => Promise<string>;
hasStoredChatGPTSignIn?: (signal?: AbortSignal) => Promise<boolean>;
scanAuthenticationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;
scanInput?: ConstructorParameters<typeof ScanDashboard>[1]["input"];
@@ -1228,7 +1227,6 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
createSecurity: (config) =>
new CodexSecurity(config, undefined, { surface: "cli" }),
environment: process.env,
- prepareAuthenticationHome: prepareCodexSecurityCredentialHome,
checkForUpdate: (signal) =>
checkForUpdate({ environment: process.env, signal }),
hasStoredChatGPTSignIn: async (signal) => {
@@ -5408,22 +5406,18 @@ export async function main(
{ args: { action: "status" }, description: "Check authentication." },
],
async run({ args, options }) {
- const credentialHome =
- dependencies.prepareAuthenticationHome !== undefined
- ? await dependencies.prepareAuthenticationHome(
- dependencies.environment,
- )
- : await prepareCodexSecurityCredentialHome(
- dependencies.environment,
- );
- if (args.action === "status" && existsSync(credentialHome)) {
- const ambientHome =
- environmentValue(dependencies.environment, "CODEX_HOME") ??
- join(homedir(), ".codex");
- await initialCredentialsAvailable(
- dependencies.environment,
- ambientHome,
- credentialHome,
+ const credentialHome = await prepareCodexSecurityCredentialHome(
+ dependencies.environment,
+ );
+ const authentication = scanAuthentication(dependencies.environment);
+ if (args.action === "status" && authentication.method !== "api_key") {
+ const ambientHome = scanCodexHome(dependencies.environment);
+ await withCredentialHomeLock(credentialHome, () =>
+ initialCredentialsAvailable(
+ dependencies.environment,
+ ambientHome,
+ credentialHome,
+ ),
);
}
const authenticationEnvironment = {
@@ -5441,15 +5435,10 @@ export async function main(
undefined,
authenticationEnvironment,
);
- if (
- args.action === undefined &&
- exitCode === 0 &&
- dependencies.prepareAuthenticationHome !== undefined
- ) {
+ if (args.action === undefined && exitCode === 0) {
await setCodexSecurityCredentialLogout(credentialHome, false);
}
if (args.action === "status") {
- const authentication = scanAuthentication(dependencies.environment);
if (
authentication.method === "api_key" &&
(exitCode === 0 || exitCode === 1)
@@ -5463,7 +5452,6 @@ export async function main(
);
}
} else if (exitCode === 0 && !options.withApiKey) {
- const authentication = scanAuthentication(dependencies.environment);
if (authentication.method === "api_key") {
const configuredApiKeyVariables = Object.entries(
dependencies.environment,
@@ -5495,29 +5483,23 @@ export async function main(
destructive: true,
mcp: false,
async run() {
- const credentialHome =
- dependencies.prepareAuthenticationHome !== undefined
- ? await dependencies.prepareAuthenticationHome(
- dependencies.environment,
- )
- : await prepareCodexSecurityCredentialHome(
- dependencies.environment,
- );
+ const credentialHome = await prepareCodexSecurityCredentialHome(
+ dependencies.environment,
+ );
const authenticationEnvironment = {
...dependencies.environment,
CODEX_HOME: credentialHome,
};
- exitCode = await dependencies.runCodex(
- ["logout"],
- undefined,
- authenticationEnvironment,
- );
- if (
- exitCode === 0 &&
- dependencies.prepareAuthenticationHome !== undefined
- ) {
- await setCodexSecurityCredentialLogout(credentialHome, true);
- }
+ await withCredentialHomeLock(credentialHome, async () => {
+ exitCode = await dependencies.runCodex(
+ ["logout"],
+ undefined,
+ authenticationEnvironment,
+ );
+ if (exitCode === 0) {
+ await setCodexSecurityCredentialLogout(credentialHome, true);
+ }
+ });
},
})
.command("serve", {
@@ -5693,11 +5675,7 @@ export async function main(
? await resolveDeepScanConfig(
resolved.options,
join(
- expandHome(
- environmentValue(dependencies.environment, "CODEX_HOME") ??
- join(homedir(), ".codex"),
- dependencies.environment,
- ),
+ scanCodexHome(dependencies.environment),
"codex-security",
"config.toml",
),
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 32e7f3217..7194ca23b 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -1134,6 +1134,22 @@ async function secureWindowsCredentialHome(path: string): Promise<void> {
}
}
+export async function withCredentialHomeLock<T>(
+ codexHome: string,
+ operation: () => Promise<T>,
+ signal?: AbortSignal,
+): Promise<T> {
+ const release = await acquireCodexSecurityCredentialHomeLock(
+ codexHome,
+ signal,
+ );
+ try {
+ return await operation();
+ } finally {
+ await release();
+ }
+}
+
export async function acquireCodexSecurityCredentialHomeLock(
codexHome: string,
signal?: AbortSignal,
diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.ts
index 12436ccfe..e3b15c51a 100644
--- a/sdk/typescript/tests-ts/api-credentials.test.ts
+++ b/sdk/typescript/tests-ts/api-credentials.test.ts
@@ -1,13 +1,14 @@
import { nodeCommand } from "./support/shell.js";
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
-import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import { chmod, mkdir, readFile, stat, writeFile } from "node:fs/promises";
import { join, relative } from "node:path";
import { pathToFileURL } from "node:url";
import type { CodexOptions } from "@openai/codex-sdk";
import { afterEach, describe, expect, test, mock } from "bun:test";
import { parse as parseToml } from "smol-toml";
import { initialCredentialsAvailable } from "../src/api.js";
+import { AuthenticationRequiredError } from "../src/errors.js";
import { setCodexSecurityCredentialLogout } from "../src/runtime.js";
import { copyCompletedScan, PLUGIN_ROOT } from "./plugin-root.js";
import { shellEnvironmentReference, TestClient } from "./support/api-client.js";
@@ -464,7 +465,9 @@ describe("CodexSecurity orchestration", () => {
{ pluginPath: PLUGIN_ROOT },
{
environment: {
- CODEX_HOME: ambientHome,
+ HOME: root,
+ USERPROFILE: root,
+ CODEX_HOME: "~/ambient-codex-home",
CODEX_SECURITY_STATE_DIR: stateDirectory,
},
resolvePluginPython: async () => "/managed/python",
@@ -628,7 +631,9 @@ describe("CodexSecurity orchestration", () => {
},
{
environment: {
- CODEX_HOME: ambientHome,
+ HOME: root,
+ USERPROFILE: root,
+ CODEX_HOME: "~/ambient-codex-home",
CODEX_SECURITY_STATE_DIR: stateDirectory,
OPENAI_API_KEY: "synthetic-transient-key",
},
@@ -700,20 +705,103 @@ describe("CodexSecurity orchestration", () => {
).resolves.toBe(true);
});
- test("recognizes ambient credentials during account() on a fresh instance", async () => {
+ test("respects another client's logout when switching from API-key to ChatGPT scans", async () => {
const root = await temporaryDirectory();
+ const repository = join(root, "repository");
const ambientHome = join(root, "ambient-home");
- const stateDir = join(root, "state");
- const script = join(root, "codex.mjs");
+ const stateDirectory = join(root, "state");
+ const scanDir = join(root, "scan");
+ await mkdir(repository);
await mkdir(ambientHome);
- await mkdir(stateDir, { mode: 0o700 });
+ await mkdir(scanDir, { mode: 0o700 });
await writeFile(
join(ambientHome, "auth.json"),
'{"auth_mode":"chatgpt"}\n',
);
- await writeFile(
- script,
- `
+ const environment = {
+ CODEX_HOME: ambientHome,
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ OPENAI_API_KEY: "synthetic-transient-key",
+ };
+ const client = new TestClient(
+ {
+ pluginPath: PLUGIN_ROOT,
+ codexOverrides: { cli_auth_credentials_store: "file" },
+ },
+ {
+ environment,
+ resolvePluginPython: async () => "/managed/python",
+ prepareOutputDir: async () => scanDir,
+ repositoryRevision: async () => "deadbeef",
+ createCodex: () => {
+ throw new Error("synthetic scan started");
+ },
+ },
+ );
+ const logoutClient = new TestClient({}, { environment });
+ const credentials = join(stateDirectory, "codex-home", "auth.json");
+ try {
+ await expect(client.run(repository, { auth: "api-key" })).rejects.toThrow(
+ "synthetic scan started",
+ );
+ await logoutClient.logout();
+ expect(existsSync(credentials)).toBe(false);
+ await expect(client.run(repository, { auth: "chatgpt" })).rejects.toThrow(
+ AuthenticationRequiredError,
+ );
+ expect(existsSync(credentials)).toBe(false);
+ } finally {
+ await Promise.all([client.close(), logoutClient.close()]);
+ }
+ });
+
+ test.skipIf(process.platform === "win32" || process.geteuid?.() === 0)(
+ "reports unreadable ambient credentials during account()",
+ async () => {
+ const root = await temporaryDirectory();
+ const ambientHome = join(root, "ambient-home");
+ const authPath = join(ambientHome, "auth.json");
+ await mkdir(ambientHome);
+ await writeFile(authPath, '{"auth_mode":"chatgpt"}\n', { mode: 0o000 });
+ const client = new TestClient(
+ {},
+ {
+ environment: {
+ CODEX_HOME: ambientHome,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ },
+ resolveCodexCommand: () => {
+ throw new Error("Must not query Codex after an import failure");
+ },
+ },
+ );
+ try {
+ await expect(client.account()).rejects.toThrow(
+ "Unable to copy ambient Codex authentication.",
+ );
+ } finally {
+ await chmod(authPath, 0o600);
+ await client.close();
+ }
+ },
+ );
+
+ test.each([false, true])(
+ "recognizes ambient credentials during account() on a fresh instance (home-relative: %p)",
+ async (homeRelative) => {
+ const root = await temporaryDirectory();
+ const ambientHome = join(root, "ambient-home");
+ const stateDir = join(root, "state");
+ const script = join(root, "codex.mjs");
+ await mkdir(ambientHome);
+ await mkdir(stateDir, { mode: 0o700 });
+ await writeFile(
+ join(ambientHome, "auth.json"),
+ '{"auth_mode":"chatgpt"}\n',
+ );
+ await writeFile(
+ script,
+ `
import { existsSync } from "node:fs";
import { basename, join } from "node:path";
@@ -730,26 +818,31 @@ if (args.join(" ") === "login status") {
}
process.exit(process.exitCode ?? 0);
`,
- );
- const client = new TestClient(
- { pluginPath: PLUGIN_ROOT },
- {
- environment: {
- PATH: process.env["PATH"],
- NODE_OPTIONS: `--import=${pathToFileURL(script).href}`,
- CODEX_HOME: ambientHome,
- CODEX_SECURITY_STATE_DIR: stateDir,
+ );
+ const client = new TestClient(
+ { pluginPath: PLUGIN_ROOT },
+ {
+ environment: {
+ PATH: process.env["PATH"],
+ NODE_OPTIONS: `--import=${pathToFileURL(script).href}`,
+ HOME: root,
+ USERPROFILE: root,
+ CODEX_HOME: homeRelative ? "~/ambient-home" : ambientHome,
+ CODEX_SECURITY_STATE_DIR: stateDir,
+ },
+ resolveCodexCommand: nodeCommand,
},
- resolveCodexCommand: nodeCommand,
- },
- );
- try {
- const status = await client.account();
- expect(status.authenticated).toBe(true);
- expect(status.details).toContain("Logged in using ChatGPT");
- expect(existsSync(join(stateDir, "codex-home", "auth.json"))).toBe(true);
- } finally {
- await client.close();
- }
- });
+ );
+ try {
+ const status = await client.account();
+ expect(status.authenticated).toBe(true);
+ expect(status.details).toContain("Logged in using ChatGPT");
+ expect(existsSync(join(stateDir, "codex-home", "auth.json"))).toBe(
+ true,
+ );
+ } finally {
+ await client.close();
+ }
+ },
+ );
});
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index bb25db78f..d50e04c59 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -6736,6 +6736,7 @@ describe("CodexSecurity orchestration", () => {
{ pluginPath: join(root, "missing-plugin") },
{
environment: {
+ CODEX_HOME: join(root, "ambient-codex-home"),
CODEX_SECURITY_STATE_DIR: stateDirectory,
...fakeCommand.environment,
},
diff --git a/sdk/typescript/tests-ts/auth-status-concurrency.test.ts b/sdk/typescript/tests-ts/auth-status-concurrency.test.ts
new file mode 100644
index 000000000..10c8c63e7
--- /dev/null
+++ b/sdk/typescript/tests-ts/auth-status-concurrency.test.ts
@@ -0,0 +1,193 @@
+import { existsSync } from "node:fs";
+import * as fs from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, mock, test } from "bun:test";
+import { runTestInSubprocess } from "./support/test-subprocess.js";
+
+for (const surface of ["CLI", "SDK"] as const) {
+ for (const first of ["status", "logout"] as const) {
+ const name = `${surface} keeps credentials removed when ${first} starts before a concurrent ${first === "status" ? "logout" : "status"}`;
+ test(name, async () => {
+ if (runTestInSubprocess(import.meta.filename, name)) return;
+
+ const originalFs = { ...fs };
+ const root = await fs.realpath(
+ await fs.mkdtemp(join(tmpdir(), "codex-security-auth-concurrency-")),
+ );
+ const ambientHome = join(root, "ambient");
+ const source = join(ambientHome, "auth.json");
+ await fs.mkdir(ambientHome, { mode: 0o700 });
+ await fs.writeFile(source, '{"auth_mode":"chatgpt"}\n', { mode: 0o600 });
+ const paused = Promise.withResolvers<void>();
+ const resume = Promise.withResolvers<void>();
+ const contending = Promise.withResolvers<void>();
+ let reachedPause = false;
+ mock.module("node:fs/promises", () => ({
+ ...originalFs,
+ copyFile: async (...args: Parameters<typeof fs.copyFile>) => {
+ if (first === "status" && String(args[0]) === source) {
+ reachedPause = true;
+ paused.resolve();
+ await resume.promise;
+ }
+ return await originalFs.copyFile(...args);
+ },
+ }));
+ const runtime = { ...(await import("../src/runtime.js")) };
+ let lockRequests = 0;
+ mock.module("../src/runtime.js", () => ({
+ ...runtime,
+ withCredentialHomeLock: (
+ ...args: Parameters<typeof runtime.withCredentialHomeLock>
+ ) => {
+ if (++lockRequests === 2) contending.resolve();
+ return runtime.withCredentialHomeLock(...args);
+ },
+ }));
+ const environment = {
+ CODEX_HOME: ambientHome,
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ };
+ const home =
+ await runtime.prepareCodexSecurityCredentialHome(environment);
+ const credentials = join(home, "auth.json");
+ if (first === "logout") {
+ await fs.writeFile(credentials, '{"auth_mode":"chatgpt"}\n', {
+ mode: 0o600,
+ });
+ }
+ const removeCredentials = async (): Promise<void> => {
+ await fs.rm(credentials, { force: true });
+ if (first === "logout") {
+ reachedPause = true;
+ paused.resolve();
+ await resume.promise;
+ }
+ };
+ let operations: Record<"status" | "logout", () => Promise<unknown>>;
+ const clients: Array<{ close(): Promise<void> }> = [];
+ if (surface === "CLI") {
+ const { main } = await import("../src/cli.js");
+ const { capture, dependencies } = await import("./cli-fixtures.js");
+ const run = async (args: string[]): Promise<number> =>
+ await main(args, capture().stream, capture().stream, {
+ ...dependencies({ environment }),
+ runCodex: async (command) => {
+ if (command[0] === "logout") {
+ await removeCredentials();
+ return 0;
+ }
+ return existsSync(credentials) ? 0 : 1;
+ },
+ });
+ operations = {
+ status: async () => {
+ expect([0, 1]).toContain(await run(["login", "status"]));
+ },
+ logout: async () => {
+ expect(await run(["logout"])).toBe(0);
+ },
+ };
+ } else {
+ const auth = { ...(await import("../src/auth.js")) };
+ mock.module("../src/auth.js", () => ({
+ ...auth,
+ accountStatus: async () => ({
+ authenticated: existsSync(credentials),
+ details: "Synthetic credential status",
+ }),
+ logout: removeCredentials,
+ }));
+ const { TestClient } = await import("./support/api-client.js");
+ const createClient = () =>
+ new TestClient(
+ {},
+ {
+ environment,
+ resolveCodexCommand: () => ({ command: process.execPath }),
+ },
+ );
+ const statusClient = createClient();
+ const logoutClient = createClient();
+ clients.push(statusClient, logoutClient);
+ operations = {
+ status: () => statusClient.account(),
+ logout: () => logoutClient.logout(),
+ };
+ }
+ let firstOperation: Promise<unknown> | undefined;
+ let secondOperation: Promise<unknown> | undefined;
+ try {
+ firstOperation = operations[first]();
+ await Promise.race([paused.promise, firstOperation]);
+ expect(reachedPause).toBe(true);
+ secondOperation =
+ operations[first === "status" ? "logout" : "status"]();
+ // Continue once the other operation finishes or queues for the lock,
+ // without depending on a particular scheduler delay.
+ await Promise.race([secondOperation, contending.promise]);
+ resume.resolve();
+ await Promise.all([firstOperation, secondOperation]);
+ expect(existsSync(credentials)).toBe(false);
+ expect(
+ await runtime.codexSecurityCredentialAllowsAmbientImport(home),
+ ).toBe(false);
+ } finally {
+ resume.resolve();
+ await Promise.allSettled([firstOperation, secondOperation]);
+ await Promise.all(clients.map((client) => client.close()));
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+ }
+}
+
+for (const operation of ["account", "logout"] as const) {
+ const name = `SDK close cancels ${operation} waiting for the credential-home lock`;
+ test(name, async () => {
+ if (runTestInSubprocess(import.meta.filename, name)) return;
+
+ const root = await fs.realpath(
+ await fs.mkdtemp(join(tmpdir(), "codex-security-auth-cancel-")),
+ );
+ const environment = {
+ CODEX_HOME: join(root, "ambient"),
+ CODEX_SECURITY_STATE_DIR: join(root, "state"),
+ };
+ const runtime = { ...(await import("../src/runtime.js")) };
+ const home = await runtime.prepareCodexSecurityCredentialHome(environment);
+ const release = await runtime.acquireCodexSecurityCredentialHomeLock(home);
+ const waiting = Promise.withResolvers<void>();
+ mock.module("../src/runtime.js", () => ({
+ ...runtime,
+ withCredentialHomeLock: (
+ ...args: Parameters<typeof runtime.withCredentialHomeLock>
+ ) => {
+ waiting.resolve();
+ return runtime.withCredentialHomeLock(...args);
+ },
+ }));
+ const { TestClient } = await import("./support/api-client.js");
+ const client = new TestClient(
+ {},
+ {
+ environment,
+ resolveCodexCommand: () => {
+ throw new Error("Must not invoke Codex while waiting for the lock");
+ },
+ },
+ );
+ const pending = client[operation]();
+ const outcome = pending.catch((error: unknown) => error);
+ try {
+ await Promise.race([waiting.promise, pending]);
+ await client.close();
+ expect(await outcome).toMatchObject({ name: "AbortError" });
+ } finally {
+ await release();
+ await client.close();
+ await fs.rm(root, { recursive: true, force: true });
+ }
+ });
+}
diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.ts
index 115335023..371e2bed2 100644
--- a/sdk/typescript/tests-ts/cli-authentication.test.ts
+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts
@@ -98,8 +98,6 @@ describe("CLI authentication", () => {
const { stdout, stderr, runCli } = createCliTest(main);
const deps = dependencies();
- deps.prepareAuthenticationHome = async () =>
- join(stateDirectory, "codex-home");
const runCodex = mock<typeof deps.runCodex>(resolving(17));
deps.createSecurity = throwing("must not initialize Codex Security");
deps.runCodex = runCodex;
@@ -135,6 +133,9 @@ describe("CLI authentication", () => {
expect(forwarded).toEqual([...argv]);
expect(environment?.["CODEX_HOME"]).toBe(expectedHome);
expect(environment?.["CODEX_SECURITY_STATE_DIR"]).toBe(stateDirectory);
+ expect(
+ await codexSecurityCredentialAllowsAmbientImport(expectedHome),
+ ).toBe(argv[0] !== "logout");
}
});
@@ -157,7 +158,6 @@ describe("CLI authentication", () => {
const deps = dependencies({
environment: { CODEX_SECURITY_STATE_DIR: linkedState },
});
- deps.prepareAuthenticationHome = prepareCodexSecurityCredentialHome;
let forwardedHome: string | undefined;
deps.runCodex = async (_args, _output, environment) => {
forwardedHome = environment?.["CODEX_HOME"];
@@ -177,7 +177,6 @@ describe("CLI authentication", () => {
const deps = dependencies({
environment: { CODEX_SECURITY_STATE_DIR: linkedState },
});
- deps.prepareAuthenticationHome = prepareCodexSecurityCredentialHome;
deps.runCodex = async () => 0;
expect(await runCli(["login"], deps)).toBe(0);
expect(
@@ -1180,41 +1179,82 @@ describe("CLI authentication", () => {
expect(`${stdout.text()}${stderr.text()}`).not.toContain("synthetic");
});
- test("recognizes existing ambient Codex authentication on a fresh state directory during login status", async () => {
- const root = await realpath(
- await temporaryDirectory("codex-security-cli-ambient-auth-"),
- );
- try {
- const ambientHome = join(root, "ambient-codex");
- await mkdir(ambientHome, { mode: 0o700 });
- await writeFile(
- join(ambientHome, "auth.json"),
- '{"auth_mode":"chatgpt"}\n',
- );
-
- const { runCli } = createCliTest(main);
-
- let forwardedHome: string | undefined;
- const deps = dependencies({
- environment: {
- CODEX_HOME: ambientHome,
- CODEX_SECURITY_STATE_DIR: stateDirectory,
- },
- });
- deps.runCodex = async (_args, _output, authEnvironment) => {
- forwardedHome = authEnvironment?.["CODEX_HOME"];
- return 0;
+ test.skipIf(process.platform === "win32" || process.geteuid?.() === 0)(
+ "reports unreadable ambient credentials during login status",
+ async () => {
+ const ambientHome = join(stateDirectory, "ambient-codex");
+ const authPath = join(ambientHome, "auth.json");
+ await mkdir(ambientHome);
+ await writeFile(authPath, '{"auth_mode":"chatgpt"}\n', { mode: 0o000 });
+ const deps = dependencies({ environment: { CODEX_HOME: ambientHome } });
+ deps.runCodex = async () => {
+ throw new Error("Must not query Codex after an import failure");
};
+ const stderr = capture();
+ try {
+ expect(
+ await main(
+ ["login", "status"],
+ capture().stream,
+ stderr.stream,
+ deps,
+ ),
+ ).toBe(2);
+ expect(stderr.text()).toContain(
+ "Unable to copy ambient Codex authentication.",
+ );
+ } finally {
+ await chmod(authPath, 0o600);
+ }
+ deps.runCodex = async () => 0;
+ expect(
+ await main(["login", "status"], capture().stream, stderr.stream, deps),
+ ).toBe(0);
+ },
+ );
- expect(await runCli(["login", "status"], deps)).toBe(0);
- expect(forwardedHome).toBe(join(stateDirectory, "codex-home"));
- expect(existsSync(join(stateDirectory, "codex-home", "auth.json"))).toBe(
- true,
+ test.each([false, true])(
+ "recognizes existing ambient Codex authentication on a fresh state directory during login status (home-relative: %p)",
+ async (homeRelative) => {
+ const root = await realpath(
+ await temporaryDirectory("codex-security-cli-ambient-auth-"),
);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
+ try {
+ const ambientHome = join(root, "ambient-codex");
+ await mkdir(ambientHome, { mode: 0o700 });
+ await writeFile(
+ join(ambientHome, "auth.json"),
+ '{"auth_mode":"chatgpt"}\n',
+ );
+
+ const stdout = capture();
+ const stderr = capture();
+ let forwardedHome: string | undefined;
+ const deps = dependencies({
+ environment: {
+ HOME: root,
+ USERPROFILE: root,
+ CODEX_HOME: homeRelative ? "~/ambient-codex" : ambientHome,
+ CODEX_SECURITY_STATE_DIR: stateDirectory,
+ },
+ });
+ deps.runCodex = async (_args, _output, authEnvironment) => {
+ forwardedHome = authEnvironment?.["CODEX_HOME"];
+ return 0;
+ };
+
+ expect(
+ await main(["login", "status"], stdout.stream, stderr.stream, deps),
+ ).toBe(0);
+ expect(forwardedHome).toBe(join(stateDirectory, "codex-home"));
+ expect(
+ existsSync(join(stateDirectory, "codex-home", "auth.json")),
+ ).toBe(true);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
test("does not import ambient Codex authentication during login status after explicit logout", async () => {
const root = await realpath(
diff --git a/sdk/typescript/tests-ts/cli-help.test.ts b/sdk/typescript/tests-ts/cli-help.test.ts
index 1e56330ad..e18fdf96f 100644
--- a/sdk/typescript/tests-ts/cli-help.test.ts
+++ b/sdk/typescript/tests-ts/cli-help.test.ts
@@ -19,8 +19,6 @@ async function help(args: readonly string[], columns?: number) {
onRepositoryCommand: () => unexpected("runRepositoryCommand"),
onUpdateCheck: async () => unexpected("checkForUpdate"),
});
- deps.prepareAuthenticationHome = async () =>
- unexpected("prepareAuthenticationHome");
deps.importScan = async () => unexpected("importScan");
const code = await main(
args,
diff --git a/sdk/typescript/tests-ts/publish.test.ts b/sdk/typescript/tests-ts/publish.test.ts
index 9b68f31d4..a58acf3f3 100644
--- a/sdk/typescript/tests-ts/publish.test.ts
+++ b/sdk/typescript/tests-ts/publish.test.ts
@@ -2816,7 +2816,9 @@ describe("connected Linear publication", () => {
' "const fs = require(\\"node:fs\\");",',
' "process.on(\\"SIGTERM\\", () => {});",',
' "process.on(\\"SIGINT\\", () => {});",',
- ' "fs.writeFileSync(process.env.CODEX_PUBLICATION_DESCENDANT_PID, String(process.pid));",',
+ ' "const pidFile = process.env.CODEX_PUBLICATION_DESCENDANT_PID;",',
+ ' "fs.writeFileSync(`${pidFile}.tmp`, String(process.pid));",',
+ ' "fs.renameSync(`${pidFile}.tmp`, pidFile);",',
' "setInterval(() => {}, 1000);",',
'].join("");',
'spawn(process.execPath, ["-e", descendant], { env: { CODEX_PUBLICATION_DESCENDANT_PID: process.env.CODEX_PUBLICATION_DESCENDANT_PID }, stdio: "ignore" });',