Skip to content

Commit 2494dc5

Browse files
committed
fix(oauth): redact public authentication errors
1 parent d4bdbc9 commit 2494dc5

3 files changed

Lines changed: 122 additions & 12 deletions

File tree

‎src/server/responses/core.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { formatPassthroughUpstreamError } from "./passthrough-error";
44
import { checkInputAdmission } from "./input-admission";
55
import { describeUpstreamConnectFailure } from "./upstream-error";
66
import {
7-
getConfigPath,
87
multiAgentGuidanceEnabled,
98
resolveEnvValue,
109
} from "../../config";
@@ -61,6 +60,9 @@ import {
6160
getOAuthCredentialApiBaseUrl,
6261
getValidAccessTokenForAccount,
6362
getValidAccessTokenSnapshot,
63+
OAuthLoginRequiredError,
64+
OAuthTokenRefreshBusyError,
65+
OAuthTokenRefreshStaleError,
6466
type OAuthAccessSnapshot,
6567
UnsupportedOAuthProviderError,
6668
} from "../../oauth";
@@ -337,7 +339,14 @@ function isFixedCodexAccount(authCtx: CodexAuthContext): boolean {
337339
&& authCtx.fixedAccount === true;
338340
}
339341

340-
342+
function publicOAuthAuthenticationErrorMessage(error: unknown): string {
343+
if (
344+
error instanceof OAuthLoginRequiredError
345+
|| error instanceof OAuthTokenRefreshBusyError
346+
|| error instanceof OAuthTokenRefreshStaleError
347+
) return error.message;
348+
return "OAuth authentication failed. Check the OpenCodex account status and retry.";
349+
}
341350

342351
export function usesCodexForwardPoolAuth(
343352
authCtx: CodexAuthContext,
@@ -2054,10 +2063,10 @@ async function handleResponsesInner(
20542063
return formatErrorResponse(
20552064
400,
20562065
"invalid_request_error",
2057-
`${err.message}. Remove or reconfigure provider '${route.providerName}' in ${getConfigPath()}.`,
2066+
`${err.message}. Remove or reconfigure provider '${route.providerName}' in the OpenCodex configuration.`,
20582067
);
20592068
}
2060-
return formatErrorResponse(401, "authentication_error", err instanceof Error ? err.message : String(err));
2069+
return formatErrorResponse(401, "authentication_error", publicOAuthAuthenticationErrorMessage(err));
20612070
}
20622071
}
20632072
route.provider = resolveProviderTransport(
@@ -3579,7 +3588,7 @@ async function handleResponsesInner(
35793588
refreshed = await forceRefreshOAuthAccessSnapshot(sentOAuthSnapshot);
35803589
} catch (err) {
35813590
cleanupUpstreamAbort();
3582-
return formatErrorResponse(401, "authentication_error", err instanceof Error ? err.message : String(err));
3591+
return formatErrorResponse(401, "authentication_error", publicOAuthAuthenticationErrorMessage(err));
35833592
}
35843593
sentOAuthSnapshot = refreshed;
35853594
replayOAuthCredentialSnapshot = {

‎tests/oauth-status-privacy.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync
33
import { join } from "node:path";
44
import { getLoginStatus, getValidAccessToken, UnsupportedOAuthProviderError } from "../src/oauth";
55
import { saveCredential } from "../src/oauth/store";
6+
import { handleResponses } from "../src/server/responses";
7+
import type { OcxConfig } from "../src/types";
68

79
const TEST_DIR = join(import.meta.dir, ".tmp-oauth-status-privacy-test");
810
let previousOpencodexHome: string | undefined;
@@ -158,6 +160,37 @@ describe("OAuth status privacy", () => {
158160
await expect(getValidAccessToken("removed-provider")).rejects.toBeInstanceOf(UnsupportedOAuthProviderError);
159161
});
160162

163+
test("stale OAuth provider responses do not disclose the config path", async () => {
164+
await saveCredential("removed-provider", {
165+
access: "access-token",
166+
refresh: "refresh-token",
167+
expires: Date.now() + 60_000,
168+
});
169+
const config = {
170+
defaultProvider: "removed-provider",
171+
providers: {
172+
"removed-provider": {
173+
adapter: "openai-responses",
174+
authMode: "oauth",
175+
baseUrl: "https://provider.example/v1",
176+
},
177+
},
178+
} as OcxConfig;
179+
180+
const response = await handleResponses(new Request("http://localhost/v1/responses", {
181+
method: "POST",
182+
headers: { "content-type": "application/json" },
183+
body: JSON.stringify({ model: "test-model", input: "hello", stream: false }),
184+
}), config, { model: "", provider: "" });
185+
const body = await response.text();
186+
187+
expect(response.status).toBe(400);
188+
expect(body).toContain("Unsupported OAuth provider");
189+
expect(body).toContain("Remove or reconfigure provider 'removed-provider'");
190+
expect(body).not.toContain(TEST_DIR);
191+
expect(body).not.toContain("config.json");
192+
});
193+
161194
test("malformed oauth token store is backed up before a new credential save overwrites it", async () => {
162195
const authPath = join(TEST_DIR, "auth.json");
163196
writeFileSync(authPath, "{not valid json", "utf8");

‎tests/server-xai-oauth-401-replay.test.ts‎

Lines changed: 75 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ import { installIsolatedCodexHome, type IsolatedCodexHome } from "./helpers/isol
1212

1313
const TOKEN_ENDPOINT = "https://auth.x.ai/oauth/token";
1414
const CHAT_ENDPOINT = `${XAI_GROK_CLI_BASE_URL}/chat/completions`;
15+
const PUBLIC_OAUTH_AUTHENTICATION_ERROR = "OAuth authentication failed. Check the OpenCodex account status and retry.";
16+
const WINDOWS_PATH_CANARY = "C:\\Users\\Alice\\.opencodex\\auth.json.ocx-tmp";
17+
const UNC_PATH_CANARY = "\\\\server\\share\\opencodex\\auth.json.ocx-tmp";
18+
const POSIX_PATH_CANARY = "/home/alice/.opencodex/auth.json.ocx-tmp";
1519

1620
let testDir = "";
1721
let previousHome: string | undefined;
@@ -35,11 +39,11 @@ afterEach(() => {
3539
if (testDir) rmSync(testDir, { recursive: true, force: true });
3640
});
3741

38-
function seedOAuth(): void {
39-
saveCredential("xai", {
42+
async function seedOAuth(expires = Date.now() + 3_600_000): Promise<void> {
43+
await saveCredential("xai", {
4044
access: "rejected-access",
4145
refresh: "initial-refresh",
42-
expires: Date.now() + 3_600_000,
46+
expires,
4347
accountId: "xai-test-account",
4448
source: "oauth",
4549
});
@@ -79,7 +83,10 @@ async function post(server: ReturnType<typeof startServer>): Promise<Response> {
7983
});
8084
}
8185

82-
function installOAuthFetch(chatStatuses: number[]): { chatAuth: string[]; counts: { refresh: number } } {
86+
function installOAuthFetch(
87+
chatStatuses: number[],
88+
options: { tokenErrorDescription?: string } = {},
89+
): { chatAuth: string[]; counts: { refresh: number } } {
8390
const chatAuth: string[] = [];
8491
const counts = { refresh: 0 };
8592
globalThis.fetch = (async (input, init) => {
@@ -92,6 +99,15 @@ function installOAuthFetch(chatStatuses: number[]): { chatAuth: string[]; counts
9299
}
93100
if (url === TOKEN_ENDPOINT) {
94101
counts.refresh += 1;
102+
if (options.tokenErrorDescription !== undefined) {
103+
return new Response(JSON.stringify({
104+
error: "temporarily_unavailable",
105+
error_description: options.tokenErrorDescription,
106+
}), {
107+
status: 400,
108+
headers: { "content-type": "application/json" },
109+
});
110+
}
95111
return new Response(JSON.stringify({
96112
access_token: "fresh-access",
97113
refresh_token: "fresh-refresh",
@@ -115,8 +131,60 @@ function installOAuthFetch(chatStatuses: number[]): { chatAuth: string[]; counts
115131
}
116132

117133
describe("xAI OAuth upstream 401 replay", () => {
134+
test("initial OAuth refresh projects raw provider failures before responding", async () => {
135+
await seedOAuth(0);
136+
saveConfig(xaiConfig());
137+
const observed = installOAuthFetch([], {
138+
tokenErrorDescription: `EACCES writing ${WINDOWS_PATH_CANARY}, ${UNC_PATH_CANARY}, or ${POSIX_PATH_CANARY}`,
139+
});
140+
const server = startServer(0);
141+
try {
142+
const response = await post(server);
143+
const json = await response.json() as { error?: { code?: string; message?: string; type?: string } };
144+
const message = json.error?.message ?? "";
145+
expect(response.status).toBe(401);
146+
expect(json.error?.type).toBe("authentication_error");
147+
expect(json.error?.code).toBe("invalid_api_key");
148+
expect(message).toBe(PUBLIC_OAUTH_AUTHENTICATION_ERROR);
149+
expect(message).not.toContain(WINDOWS_PATH_CANARY);
150+
expect(message).not.toContain(UNC_PATH_CANARY);
151+
expect(message).not.toContain(POSIX_PATH_CANARY);
152+
expect(message).not.toContain("auth.json");
153+
expect(observed.counts.refresh).toBe(1);
154+
expect(observed.chatAuth).toEqual([]);
155+
} finally {
156+
await server.stop(true);
157+
}
158+
});
159+
160+
test("OAuth 401 replay projects raw refresh failures before responding", async () => {
161+
await seedOAuth();
162+
saveConfig(xaiConfig());
163+
const observed = installOAuthFetch([401], {
164+
tokenErrorDescription: `EACCES writing ${WINDOWS_PATH_CANARY}, ${UNC_PATH_CANARY}, or ${POSIX_PATH_CANARY}`,
165+
});
166+
const server = startServer(0);
167+
try {
168+
const response = await post(server);
169+
const json = await response.json() as { error?: { code?: string; message?: string; type?: string } };
170+
const message = json.error?.message ?? "";
171+
expect(response.status).toBe(401);
172+
expect(json.error?.type).toBe("authentication_error");
173+
expect(json.error?.code).toBe("invalid_api_key");
174+
expect(message).toBe(PUBLIC_OAUTH_AUTHENTICATION_ERROR);
175+
expect(message).not.toContain(WINDOWS_PATH_CANARY);
176+
expect(message).not.toContain(UNC_PATH_CANARY);
177+
expect(message).not.toContain(POSIX_PATH_CANARY);
178+
expect(message).not.toContain("auth.json");
179+
expect(observed.counts.refresh).toBe(1);
180+
expect(observed.chatAuth).toEqual(["Bearer rejected-access"]);
181+
} finally {
182+
await server.stop(true);
183+
}
184+
});
185+
118186
test("401 then 200 performs one refresh and one replay", async () => {
119-
seedOAuth();
187+
await seedOAuth();
120188
saveConfig(xaiConfig());
121189
const observed = installOAuthFetch([401, 200]);
122190
const server = startServer(0);
@@ -133,7 +201,7 @@ describe("xAI OAuth upstream 401 replay", () => {
133201
});
134202

135203
test("401 then 401 replays once and propagates the second error", async () => {
136-
seedOAuth();
204+
await seedOAuth();
137205
saveConfig(xaiConfig());
138206
const observed = installOAuthFetch([401, 401]);
139207
const server = startServer(0);
@@ -181,7 +249,7 @@ describe("xAI OAuth upstream 401 replay", () => {
181249
});
182250

183251
test("concurrent 401 responses join one IdP refresh", async () => {
184-
seedOAuth();
252+
await seedOAuth();
185253
saveConfig(xaiConfig());
186254
let refreshCalls = 0;
187255
let signalRefreshStarted!: () => void;

0 commit comments

Comments
 (0)