Skip to content

Commit 446d365

Browse files
committed
fix(oauth): redact remaining public auth errors
1 parent 8a86aae commit 446d365

10 files changed

Lines changed: 407 additions & 42 deletions

File tree

‎src/codex/auth-api.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1791,7 +1791,7 @@ export async function handleCodexAuthAPI(
17911791
const loginOwner: CodexLoginStateRow = { status: "starting", startedAt: Date.now() };
17921792
codexAuthLoginState.set(flowId, loginOwner);
17931793
try {
1794-
const { startLoginFlow, getLoginStatus } = await import("../oauth");
1794+
const { startLoginFlow, getLoginStatus, publicOAuthAuthenticationErrorMessage } = await import("../oauth");
17951795
const result = await startLoginFlow("chatgpt", { forceLogin: true });
17961796

17971797
// Open the browser server-side (same pattern as /api/oauth/login in management-api.ts).
@@ -1993,7 +1993,11 @@ export async function handleCodexAuthAPI(
19931993
break;
19941994
}
19951995
if (st.done && st.error) {
1996-
setCodexLoginState(flowId, { status: "error", error: st.error, doneAt: Date.now() });
1996+
setCodexLoginState(flowId, {
1997+
status: "error",
1998+
error: publicOAuthAuthenticationErrorMessage(new Error(st.error)),
1999+
doneAt: Date.now(),
2000+
});
19972001
completed = true;
19982002
break;
19992003
}
@@ -2011,7 +2015,7 @@ export async function handleCodexAuthAPI(
20112015
? "Configuration is busy; retry login shortly."
20122016
: error instanceof CodexCredentialRefreshBusyError || error instanceof CodexCredentialRefreshStaleError
20132017
? "Credential refresh is busy; retry login shortly."
2014-
: error instanceof Error ? error.message : String(error);
2018+
: publicOAuthAuthenticationErrorMessage(error);
20152019
setCodexLoginState(flowId, {
20162020
status: "error",
20172021
error: message,
@@ -2028,15 +2032,15 @@ export async function handleCodexAuthAPI(
20282032
} catch (e) {
20292033
if (codexAuthLoginState.get(flowId) === loginOwner) codexAuthLoginState.delete(flowId);
20302034
const msg = e instanceof Error ? e.message : String(e);
2031-
if (msg.includes("already in progress")) {
2035+
if (msg === "A login for chatgpt is already in progress") {
20322036
return jsonResponse({ error: msg, status: "pending" }, 409);
20332037
}
20342038
if (e instanceof CodexCredentialRefreshBusyError || e instanceof CodexCredentialRefreshStaleError) {
20352039
const response = jsonResponse({ error: "server_busy", code: "server_busy" }, 503);
20362040
response.headers.set("Retry-After", "1");
20372041
return response;
20382042
}
2039-
return jsonResponse({ error: msg }, 500);
2043+
return jsonResponse({ error: "OAuth authentication failed. Check the OpenCodex account status and retry." }, 500);
20402044
}
20412045
}
20422046

‎src/oauth/index.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,12 +292,25 @@ export class UnsupportedOAuthProviderError extends Error {
292292
}
293293

294294
export class OAuthLoginRequiredError extends Error {
295+
readonly provider: string;
296+
295297
constructor(provider: string) {
296298
super(`Not logged in to ${provider}. Run: ocx login ${provider}`);
297299
this.name = "OAuthLoginRequiredError";
300+
this.provider = provider;
298301
}
299302
}
300303

304+
/** Project arbitrary OAuth failures onto the small, stable public error vocabulary. */
305+
export function publicOAuthAuthenticationErrorMessage(error: unknown): string {
306+
if (
307+
(error instanceof OAuthLoginRequiredError && isOAuthProvider(error.provider))
308+
|| error instanceof OAuthTokenRefreshBusyError
309+
|| error instanceof OAuthTokenRefreshStaleError
310+
) return error.message;
311+
return "OAuth authentication failed. Check the OpenCodex account status and retry.";
312+
}
313+
301314
function accessSnapshot(provider: string, accountId: string, cred: OAuthCredentials): OAuthAccessSnapshot {
302315
const storedKiroRouting = {
303316
...(cred.kiro?.profileArn ? { profileArn: cred.kiro.profileArn } : {}),

‎src/server/management/oauth-account-routes.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
getLoginStatus,
2020
isPublicOAuthProvider,
2121
listOAuthProviders,
22+
publicOAuthAuthenticationErrorMessage,
2223
startLoginFlow,
2324
submitManualLoginCode,
2425
} from "../../oauth";
@@ -175,7 +176,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
175176
return jsonResponse({ url: authUrl, instructions, deviceCode });
176177
} catch (err) {
177178
if (err instanceof OAuthMutationBusyError) throw err;
178-
return jsonResponse({ error: err instanceof Error ? err.message : String(err) }, 409);
179+
return jsonResponse({ error: publicOAuthAuthenticationErrorMessage(err) }, 409);
179180
}
180181
}
181182

@@ -208,7 +209,10 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
208209
if (url.pathname === "/api/oauth/status" && req.method === "GET") {
209210
const provider = (url.searchParams.get("provider") ?? "").trim().toLowerCase();
210211
if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
211-
return jsonResponse(getLoginStatus(provider));
212+
const status = getLoginStatus(provider);
213+
return jsonResponse(status.error
214+
? { ...status, error: publicOAuthAuthenticationErrorMessage(new Error(status.error)) }
215+
: status);
212216
}
213217

214218
if (url.pathname === "/api/oauth/logout" && req.method === "POST") {

‎src/server/responses/core.ts‎

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,7 @@ import {
6161
getOAuthCredentialApiBaseUrl,
6262
getValidAccessTokenForAccount,
6363
getValidAccessTokenSnapshot,
64-
OAuthLoginRequiredError,
65-
OAuthTokenRefreshBusyError,
66-
OAuthTokenRefreshStaleError,
64+
publicOAuthAuthenticationErrorMessage,
6765
type OAuthAccessSnapshot,
6866
UnsupportedOAuthProviderError,
6967
} from "../../oauth";
@@ -351,15 +349,6 @@ function isFixedCodexAccount(authCtx: CodexAuthContext): boolean {
351349
&& authCtx.fixedAccount === true;
352350
}
353351

354-
function publicOAuthAuthenticationErrorMessage(error: unknown): string {
355-
if (
356-
error instanceof OAuthLoginRequiredError
357-
|| error instanceof OAuthTokenRefreshBusyError
358-
|| error instanceof OAuthTokenRefreshStaleError
359-
) return error.message;
360-
return "OAuth authentication failed. Check the OpenCodex account status and retry.";
361-
}
362-
363352
export function usesCodexForwardPoolAuth(
364353
authCtx: CodexAuthContext,
365354
provider: OcxProviderConfig,
@@ -2114,10 +2103,11 @@ async function handleResponsesInner(
21142103
}
21152104
} catch (err) {
21162105
if (err instanceof UnsupportedOAuthProviderError) {
2106+
const safeProviderName = redactSecretString(route.providerName);
21172107
return formatErrorResponse(
21182108
400,
21192109
"invalid_request_error",
2120-
`${err.message}. Remove or reconfigure provider '${route.providerName}' in the OpenCodex configuration.`,
2110+
`${redactSecretString(err.message)}. Remove or reconfigure provider '${safeProviderName}' in the OpenCodex configuration.`,
21212111
);
21222112
}
21232113
return formatErrorResponse(401, "authentication_error", publicOAuthAuthenticationErrorMessage(err));

‎src/vision/anthropic-describe.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { CLAUDE_CODE_HEADERS, claudeCodeSessionId } from "../adapters/client-fin
33
import { signalWithTimeout, cancelBodyOnAbort } from "../lib/abort";
44
import { sidecarEnter } from "../lib/sidecar-tracker";
55
import { fetchWithResetRetry } from "../lib/upstream-retry";
6-
import { getValidAccessToken } from "../oauth";
6+
import { getValidAccessToken, publicOAuthAuthenticationErrorMessage } from "../oauth";
77
import { ANTHROPIC_OAUTH_BETA, CLAUDE_CODE_SYSTEM_INSTRUCTION } from "../oauth/anthropic";
88
import type { DescribeOutcome, VisionSettings } from "./describe";
99

@@ -67,8 +67,8 @@ export async function parseAnthropicVisionSSE(res: Response): Promise<DescribeOu
6767
const delta = isRecord(data.delta) ? data.delta : {};
6868
if (delta.type === "text_delta" && typeof delta.text === "string") text += delta.text;
6969
} else if (data.type === "error") {
70-
const error = isRecord(data.error) ? data.error : {};
71-
terminalError = typeof error.message === "string" ? error.message : "anthropic vision sidecar stream error";
70+
// Provider-authored stream errors can contain credentials, paths, or response bodies.
71+
terminalError = "anthropic vision sidecar stream error";
7272
}
7373
};
7474

@@ -116,7 +116,7 @@ export async function describeImageAnthropic(
116116
try {
117117
token = await getValidAccessToken(providerName);
118118
} catch (error) {
119-
return { text: "", error: `anthropic vision sidecar auth failed: ${error instanceof Error ? error.message : String(error)}` };
119+
return { text: "", error: `anthropic vision sidecar auth failed: ${publicOAuthAuthenticationErrorMessage(error)}` };
120120
}
121121

122122
const headers: Record<string, string> = {
@@ -166,7 +166,11 @@ export async function describeImageAnthropic(
166166
if (!res.ok) {
167167
const responseText = await res.text().catch(() => "");
168168
console.warn(`[vision] anthropic sidecar HTTP ${res.status} (${Date.now() - startedAt}ms)`);
169-
return { text: "", error: `anthropic vision sidecar HTTP ${res.status}: ${responseText.slice(0, 200)}` };
169+
if (res.status === 401) {
170+
return { text: "", error: `anthropic vision sidecar auth failed: ${publicOAuthAuthenticationErrorMessage(new Error(responseText))}` };
171+
}
172+
// Upstream bodies are untrusted and may contain credentials, paths, or provider diagnostics.
173+
return { text: "", error: `anthropic vision sidecar HTTP ${res.status}` };
170174
}
171175
const detachBodyGuard = cancelBodyOnAbort(res.body, linkedSignal.signal);
172176
try {
@@ -177,7 +181,7 @@ export async function describeImageAnthropic(
177181
} catch (error) {
178182
const kind = error instanceof Error && error.name === "TimeoutError" ? "timeout" : "connect_error";
179183
console.warn(`[vision] anthropic sidecar ${kind} (${Date.now() - startedAt}ms)`);
180-
return { text: "", error: error instanceof Error ? error.message : String(error) };
184+
return { text: "", error: `anthropic vision sidecar ${kind}` };
181185
} finally {
182186
sidecarExit();
183187
linkedSignal.cleanup();

‎src/web-search/anthropic-executor.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import type { OcxProviderConfig } from "../types";
2-
import { getValidAccessToken } from "../oauth";
2+
import { getValidAccessToken, publicOAuthAuthenticationErrorMessage } from "../oauth";
33
import { ANTHROPIC_OAUTH_BETA, CLAUDE_CODE_SYSTEM_INSTRUCTION } from "../oauth/anthropic";
44
import { CLAUDE_CODE_HEADERS, claudeCodeSessionId } from "../adapters/client-fingerprint";
55
import { signalWithTimeout, cancelBodyOnAbort } from "../lib/abort";
6-
import { redactSecretString } from "../lib/redact";
76
import { sidecarEnter } from "../lib/sidecar-tracker";
87
import { fetchWithResetRetry } from "../lib/upstream-retry";
98
import type { WebSearchSource } from "./parse";
@@ -127,7 +126,7 @@ export async function runAnthropicWebSearch(
127126
try {
128127
token = await getValidAccessToken(providerName);
129128
} catch (e) {
130-
return { text: "", sources: [], error: `anthropic sidecar auth failed: ${e instanceof Error ? e.message : String(e)}` };
129+
return { text: "", sources: [], error: `anthropic sidecar auth failed: ${publicOAuthAuthenticationErrorMessage(e)}` };
131130
}
132131
const headers: Record<string, string> = {
133132
"Content-Type": "application/json",
@@ -174,8 +173,11 @@ export async function runAnthropicWebSearch(
174173
const t = await res.text().catch(() => "");
175174
detachBodyGuard();
176175
console.warn(`[web-search] anthropic sidecar HTTP ${res.status} for query "${query.slice(0, 80)}" (${Date.now() - t0}ms)`);
177-
// Redact before surfacing: the body can echo auth headers/tokens (#398 review).
178-
return { text: "", sources: [], error: `sidecar HTTP ${res.status}: ${redactSecretString(t.slice(0, 200))}` };
176+
if (res.status === 401) {
177+
return { text: "", sources: [], error: `anthropic sidecar auth failed: ${publicOAuthAuthenticationErrorMessage(new Error(t))}` };
178+
}
179+
// Upstream bodies are untrusted and may contain credentials, paths, or provider diagnostics.
180+
return { text: "", sources: [], error: `sidecar HTTP ${res.status}` };
179181
}
180182
try {
181183
return await parseAnthropicSidecarSSE(res);
@@ -185,7 +187,7 @@ export async function runAnthropicWebSearch(
185187
} catch (e) {
186188
const kind = e instanceof Error && e.name === "TimeoutError" ? "timeout" : "connect_error";
187189
console.warn(`[web-search] anthropic sidecar ${kind} for query "${query.slice(0, 80)}" (${Date.now() - t0}ms)`);
188-
return { text: "", sources: [], error: e instanceof Error ? e.message : String(e) };
190+
return { text: "", sources: [], error: `anthropic sidecar ${kind}` };
189191
} finally {
190192
sidecarExit();
191193
linkedSignal.cleanup();

‎tests/codex-auth-api.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3365,6 +3365,81 @@ describe("codex-auth API", () => {
33653365
expect(data.status).toBe("expired");
33663366
});
33673367

3368+
test("Codex OAuth login responses project raw provider errors", async () => {
3369+
const oauth = await import("../src/oauth");
3370+
const startSpy = spyOn(oauth, "startLoginFlow").mockImplementation(async () => {
3371+
throw new Error("already in progress at C:\\Users\\Alice\\.opencodex\\auth.json.ocx-tmp sk-secret-provider-key");
3372+
});
3373+
try {
3374+
const req = new Request("http://localhost/api/codex-auth/login", {
3375+
method: "POST",
3376+
headers: { "content-type": "application/json" },
3377+
body: "{}",
3378+
});
3379+
const resp = await handleCodexAuthAPI(req, new URL(req.url), makeConfig());
3380+
const data = await resp!.json() as { error?: string };
3381+
3382+
expect(resp!.status).toBe(500);
3383+
expect(data.error).toBe("OAuth authentication failed. Check the OpenCodex account status and retry.");
3384+
expect(JSON.stringify(data)).not.toContain("Alice");
3385+
expect(JSON.stringify(data)).not.toContain("sk-secret-provider-key");
3386+
} finally {
3387+
startSpy.mockRestore();
3388+
}
3389+
});
3390+
3391+
test("Codex OAuth login status projects late provider errors", async () => {
3392+
const oauth = await import("../src/oauth");
3393+
const openUrlMod = await import("../src/lib/open-url");
3394+
const startSpy = spyOn(oauth, "startLoginFlow").mockResolvedValue({ url: "https://example.test/oauth" });
3395+
const statusSpy = spyOn(oauth, "getLoginStatus").mockReturnValue({
3396+
done: true,
3397+
loggedIn: false,
3398+
error: "late failure at /home/alice/.opencodex/auth.json.ocx-tmp sk-secret-provider-key",
3399+
} as ReturnType<typeof oauth.getLoginStatus>);
3400+
const openSpy = spyOn(openUrlMod, "openUrl").mockImplementation(() => {});
3401+
const timeoutSpy = spyOn(globalThis, "setTimeout").mockImplementation(((
3402+
callback: (...args: unknown[]) => void,
3403+
delay?: number,
3404+
...args: unknown[]
3405+
) => {
3406+
if (delay === 2_000) queueMicrotask(() => callback(...args));
3407+
return 0 as unknown as ReturnType<typeof setTimeout>;
3408+
}) as typeof setTimeout);
3409+
try {
3410+
const req = new Request("http://localhost/api/codex-auth/login", {
3411+
method: "POST",
3412+
headers: { "content-type": "application/json" },
3413+
body: "{}",
3414+
});
3415+
const startResponse = await handleCodexAuthAPI(req, new URL(req.url), makeConfig());
3416+
const started = await startResponse!.json() as { flowId: string };
3417+
expect(startResponse!.status).toBe(200);
3418+
3419+
let state: { status?: string; error?: string } = {};
3420+
for (let attempt = 0; attempt < 50 && state.status !== "error"; attempt += 1) {
3421+
const statusReq = new Request(
3422+
`http://localhost/api/codex-auth/login-status?flowId=${encodeURIComponent(started.flowId)}`,
3423+
);
3424+
const statusResponse = await handleCodexAuthAPI(statusReq, new URL(statusReq.url), makeConfig());
3425+
state = await statusResponse!.json() as typeof state;
3426+
if (state.status !== "error") await new Promise<void>(resolve => setImmediate(resolve));
3427+
}
3428+
3429+
expect(state).toMatchObject({
3430+
status: "error",
3431+
error: "OAuth authentication failed. Check the OpenCodex account status and retry.",
3432+
});
3433+
expect(JSON.stringify(state)).not.toContain("/home/alice");
3434+
expect(JSON.stringify(state)).not.toContain("sk-secret-provider-key");
3435+
} finally {
3436+
timeoutSpy.mockRestore();
3437+
openSpy.mockRestore();
3438+
statusSpy.mockRestore();
3439+
startSpy.mockRestore();
3440+
}
3441+
});
3442+
33683443
test("POST /api/codex-auth/login/cancel expires the pending flow", async () => {
33693444
const flowId = "flow-cancel-test";
33703445
const req = new Request("http://localhost/api/codex-auth/login/cancel", {

0 commit comments

Comments
 (0)