OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(auth): preserve verified hard-linked credentials during logout (#2354)
erantianantha72907bc7ec1c
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 0ac9d20d9..4b8bb48d5 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -110,6 +110,12 @@ Stored OpenAI credentials live inoutside the target and every enclosing Git worktree. It also serves providerswith `requires_openai_auth = true`.+If you manually hard-linked the two homes’ `auth.json` files, keep both homes+accessible when running `codex-security logout`. When the CLI verifies the+two hard links, it removes the private link before invoking native logout.+If the ambient home is unavailable, the configured credential store handles+logout normally.+Codex carries credential-storage, forced-login, and workspace settings from theambient configuration into this home. Managed-device policies still apply;workspace-managed policies may require ChatGPT credentials even with an API key.diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex b88f4359c..d1aeac404 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -264,6 +264,7 @@ import {codexSecurityStateDirectory,codexExecutableReadPaths,createIsolatedHome,+ logoutCredentialHome,executablePathForSpawn,expandHome,importAmbientAuth,@@ -4217,25 +4218,26 @@ export class CodexSecurity {public async logout(): Promise<void> {await this.#trackOperation(async () => {- const authentication = await this.#authentication();+ const { codexHome, environment } = await this.#authentication();+ const signal = this.#abortController.signal;this.#requireOpen();await withCredentialHomeLock(- authentication.codexHome,+ codexHome,async () => {- await codexLogout(- await this.#providerPreflightCommand(),- authentication.environment,- this.#abortController.signal,- );- await setCodexSecurityCredentialLogout(- authentication.codexHome,- true,+ const command = await this.#providerPreflightCommand();+ await logoutCredentialHome(+ codexHome,+ scanCodexHome(this.#dependencies.environment),+ () => codexLogout(command, environment, signal),+ () => {+ if (this.#runtime !== null)+ this.#runtime.credentialsAvailable = false;+ this.#runtimeCredentialSource = null;+ },);},- this.#abortController.signal,+ signal,);- if (this.#runtime !== null) this.#runtime.credentialsAvailable = false;- this.#runtimeCredentialSource = null;this.#requireOpen();});}diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 0ee19491c..e80edd705 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -301,6 +301,7 @@ import {codexSecurityCredentialHome,codexSecurityHasStoredFileCredentials,codexSecurityStateDirectory,+ logoutCredentialHome,executablePathForSpawn,environmentWithGit,expandHome,@@ -7238,20 +7239,18 @@ export async function main(const credentialHome = await prepareCodexSecurityCredentialHome(dependencies.environment,);- const authenticationEnvironment = {- ...dependencies.environment,- CODEX_HOME: credentialHome,- };- await withCredentialHomeLock(credentialHome, async () => {- exitCode = await dependencies.runCodex(- ["logout"],- undefined,- authenticationEnvironment,- );- if (exitCode === 0) {- await setCodexSecurityCredentialLogout(credentialHome, true);- }- });+ const runLogout = () =>+ dependencies.runCodex(["logout"], undefined, {+ ...dependencies.environment,+ CODEX_HOME: credentialHome,+ });+ exitCode = await withCredentialHomeLock(credentialHome, () =>+ logoutCredentialHome(+ credentialHome,+ scanCodexHome(dependencies.environment),+ runLogout,+ ),+ );},}).command("init", {diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.tsindex 4ca9d1749..f5c2ae349 100644--- a/sdk/typescript/src/runtime.ts+++ b/sdk/typescript/src/runtime.ts@@ -1452,6 +1452,59 @@ async function recoverStaleCredentialHomeLock(lock: string): Promise<boolean> {return true;}+function sameInode(left: BigIntStats, right: BigIntStats): boolean {+ return left.dev === right.dev && left.ino === right.ino;+}++/** Distinguish two hard links from two paths to the same directory entry. */+async function hasSeparateAmbientLink(+ localPath: string,+ ambientHome: string,+): Promise<boolean> {+ try {+ const local = await lstat(localPath, { bigint: true });+ if (!local.isFile() || local.nlink < 2n || local.ino === 0n) return false;+ const ambient = await lstat(join(ambientHome, "auth.json"), {+ bigint: true,+ });+ if (!ambient.isFile() || !sameInode(local, ambient)) return false;+ const [localDir, ambientDir] = await Promise.all([+ stat(dirname(localPath), { bigint: true }),+ stat(ambientHome, { bigint: true }),+ ]);+ return (+ localDir.ino !== 0n &&+ ambientDir.ino !== 0n &&+ !sameInode(localDir, ambientDir)+ );+ } catch {+ // Without a verified second link, leave logout to the configured native store.+ return false;+ }+}++/** Run under the credential-home lock so status cannot reimport the sign-in during logout. */+export async function logoutCredentialHome<T extends number | void>(+ home: string,+ ambientHome: string,+ nativeLogout: () => Promise<T>,+ onLoggedOut?: () => void,+): Promise<T> {+ const localPath = join(home, "auth.json");+ const shared = await hasSeparateAmbientLink(localPath, ambientHome);+ const recordLogout = async () => {+ await setCodexSecurityCredentialLogout(home, true);+ if (shared) await rm(localPath);+ onLoggedOut?.();+ };++ // Detach before native logout can revoke a shared token, even if native cleanup fails.+ if (shared) await recordLogout();+ const status = await nativeLogout();+ if (!shared && (status === undefined || status === 0)) await recordLogout();+ return status;+}+export async function setCodexSecurityCredentialLogout(codexHome: string,loggedOut: boolean,@@ -3622,9 +3675,7 @@ export function sameFile(left: string, right: string): Promise<boolean> {stat(left, { bigint: true }),stat(right, { bigint: true }),]).then(- ([leftMetadata, rightMetadata]) =>- leftMetadata.dev === rightMetadata.dev &&- leftMetadata.ino === rightMetadata.ino,+ ([leftMetadata, rightMetadata]) => sameInode(leftMetadata, rightMetadata),() => false,);}diff --git a/sdk/typescript/tests-ts/auth-status-concurrency.test.ts b/sdk/typescript/tests-ts/auth-status-concurrency.test.tsindex 37080e427..63444c73e 100644--- a/sdk/typescript/tests-ts/auth-status-concurrency.test.ts+++ b/sdk/typescript/tests-ts/auth-status-concurrency.test.ts@@ -55,11 +55,10 @@ for (const surface of ["CLI", "SDK"] as const) {await runtime.prepareCodexSecurityCredentialHome(environment);const credentials = join(home, "auth.json");if (first === "logout") {- await fs.writeFile(credentials, '{"auth_mode":"chatgpt"}\n', {- mode: 0o600,- });+ await fs.link(source, credentials);}const removeCredentials = async (): Promise<void> => {+ if (first === "logout") expect(existsSync(credentials)).toBe(false);await fs.rm(credentials, { force: true });if (first === "logout") {reachedPause = true;@@ -132,6 +131,9 @@ for (const surface of ["CLI", "SDK"] as const) {resume.resolve();await Promise.all([firstOperation, secondOperation]);expect(existsSync(credentials)).toBe(false);+ expect(await fs.readFile(source, "utf8")).toBe(+ '{"auth_mode":"chatgpt"}\n',+ );expect(await runtime.codexSecurityCredentialAllowsAmbientImport(home),).toBe(false);diff --git a/sdk/typescript/tests-ts/cli-authentication.test.ts b/sdk/typescript/tests-ts/cli-authentication.test.tsindex d11688486..8d30b3cf4 100644--- a/sdk/typescript/tests-ts/cli-authentication.test.ts+++ b/sdk/typescript/tests-ts/cli-authentication.test.ts@@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process";import { existsSync } from "node:fs";import {chmod,+ link,mkdir,realpath,readFile,@@ -148,6 +149,56 @@ describe("CLI authentication", () => {}});+ test("logout detaches only a separate ambient hard link before native failure", async () => {+ const home = await createCredentialHome();+ const auth = join(home, "auth.json");+ const ambient = join(stateDirectory, "ambient");+ await mkdir(ambient);+ const source = join(ambient, "auth.json");+ const backing = join(ambient, "backing.json");+ await writeFile(auth, "session", { mode: 0o600 });+ await link(auth, backing);++ const logout = async (sourceHome: string, expectDetached: boolean) => {+ const deps = dependencies({ environment: { CODEX_HOME: sourceHome } });+ deps.runCodex = async () => {+ expect(existsSync(auth)).toBe(!expectDetached);+ return 19;+ };+ const { runCli, stderr } = createCliTest(main);+ const status = await runCli(["logout"], deps);+ expect(status, stderr.text()).toBe(19);+ expect(await codexSecurityCredentialAllowsAmbientImport(home)).toBe(+ !expectDetached,+ );+ };++ // A backup link in another directory does not make an independent sign-in shared.+ await writeFile(source, "independent", { mode: 0o600 });+ await logout(ambient, false);+ expect(await readFile(source, "utf8")).toBe("independent");+ await rm(source);+ // ENOTDIR makes the ambient file uninspectable even when tests run as root.+ await logout(backing, false);++ const alias = join(ambient, "home-alias");+ await symlink(+ home,+ alias,+ process.platform === "win32" ? "junction" : "dir",+ );+ await logout(alias, false);++ if (process.platform !== "win32") {+ await symlink(backing, source);+ await logout(ambient, false);+ await rm(source);+ }+ await link(auth, source);+ await logout(ambient, true);+ expect(await readFile(source, "utf8")).toBe("session");+ });+test.skipIf(process.platform === "win32")("validates and canonicalizes the credential home for status and logout",async () => {