Skip to content

Commit fa4ca86

Browse files
committed
fix: stop labeling upstream 403s as invalid_api_key
Map permission and subscription gates to permission_denied / subscription_required so Logs Details match Forbidden, not a bad key.
1 parent b373137 commit fa4ca86

6 files changed

Lines changed: 212 additions & 81 deletions

File tree

‎gui/src/status-codes.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ const STATUS_CODES: Record<number, LocalizedInfo> = {
2323
de: { label: "Zahlung erforderlich", description: "Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln." },
2424
},
2525
403: {
26-
en: { label: "Forbidden", description: "The account is authenticated but not allowed to use this model or operation. Check provider permissions, org access, and policy restrictions." },
27-
ko: { label: "권한 없음", description: "계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 제공자 권한, 조직 접근, 정책 제한을 확인해야 합니다." },
28-
zh: { label: "禁止访问", description: "账号已认证,但无权使用此模型或操作。请检查提供商权限、组织访问权限和策略限制。" },
29-
de: { label: "Verboten", description: "Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Prüfe Anbieterberechtigungen, Organisationszugriff und Richtlinien." },
26+
en: { label: "Forbidden", description: "The account is authenticated but not allowed to use this model or operation. Often a plan/subscription gate (e.g. Ollama Cloud Pro), org policy, or model permission — not necessarily a bad API key." },
27+
ko: { label: "권한 없음", description: "계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 플랜/구독 제한(예: Ollama Cloud Pro), 조직 정책, 모델 권한 문제인 경우가 많으며 API 키가 잘못된 것은 아닐 수 있습니다." },
28+
zh: { label: "禁止访问", description: "账号已认证,但无权使用此模型或操作。常见原因是套餐/订阅限制(例如 Ollama Cloud Pro)、组织策略或模型权限——不一定是 API 密钥无效。" },
29+
de: { label: "Verboten", description: "Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Oft Plan-/Abo-Sperre (z. B. Ollama Cloud Pro), Organisationsrichtlinie oder Modellrecht — nicht zwingend ein ungültiger API-Key." },
3030
},
3131
404: {
3232
en: { label: "Not found", description: "The requested route, model, account, or upstream resource was not found. Verify the model name and opencodex provider configuration." },

‎src/lib/errors.ts‎

Lines changed: 128 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -4,75 +4,122 @@ export interface OcxErrorPayload {
44
code: string | null;
55
}
66

7+
function isSubscriptionGateMessage(text: string): boolean {
8+
return (
9+
text.includes("requires a subscription")
10+
|| text.includes("requires subscription")
11+
|| text.includes("subscription required")
12+
|| text.includes("upgrade for access")
13+
|| text.includes("upgrade to pro")
14+
|| text.includes("pro subscription")
15+
|| text.includes("ollama.com/upgrade")
16+
|| (text.includes("upgrade") && text.includes("subscription"))
17+
);
18+
}
19+
20+
function isAuthenticationMessage(text: string): boolean {
21+
return (
22+
text.includes("authentication failed")
23+
|| text.includes("invalid_api_key")
24+
|| text.includes("invalid api key")
25+
|| text.includes("invalid token")
26+
|| text.includes("unauthorizedexception")
27+
|| text.includes("unrecognizedclientexception")
28+
|| text.includes("unrecognizedclient")
29+
|| text.includes("expired token")
30+
|| text.includes("expiredtoken")
31+
|| text.includes("unauthenticated")
32+
|| text.includes("unauthorized")
33+
// Kiro / AWS often wrap credential failures as AccessDeniedException.
34+
|| text.includes("access denied")
35+
);
36+
}
37+
38+
function isPermissionMessage(text: string): boolean {
39+
return (
40+
text.includes("permission_denied")
41+
|| text.includes("permission denied")
42+
|| text.includes("forbidden")
43+
|| text.includes("not allowed to use")
44+
|| text.includes("model access")
45+
|| isSubscriptionGateMessage(text)
46+
);
47+
}
48+
749
export function classifyError(status: number, type: string, message: string): OcxErrorPayload {
850
const text = message.toLowerCase();
951
if (
10-
text.includes("context_length_exceeded") ||
11-
text.includes("context window") ||
12-
text.includes("context length") ||
13-
text.includes("maximum context") ||
14-
text.includes("too many tokens")
52+
text.includes("context_length_exceeded")
53+
|| text.includes("context window")
54+
|| text.includes("context length")
55+
|| text.includes("maximum context")
56+
|| text.includes("too many tokens")
1557
) {
1658
return { message, type: "invalid_request_error", code: "context_length_exceeded" };
1759
}
1860
if (
19-
text.includes("insufficient_quota") ||
20-
text.includes("exceeded your current quota") ||
21-
text.includes("quota exhausted") ||
22-
text.includes("account quota exceeded") ||
23-
text.includes("monthly quota exceeded") ||
24-
text.includes("daily quota exceeded")
61+
text.includes("insufficient_quota")
62+
|| text.includes("exceeded your current quota")
63+
|| text.includes("quota exhausted")
64+
|| text.includes("account quota exceeded")
65+
|| text.includes("monthly quota exceeded")
66+
|| text.includes("daily quota exceeded")
2567
) {
2668
return { message, type: "insufficient_quota", code: "insufficient_quota" };
2769
}
2870
if (
29-
status === 429 ||
30-
text.includes("rate limit") ||
31-
text.includes("rate limited") ||
32-
text.includes("too many requests") ||
33-
text.includes("resource_exhausted") ||
34-
text.includes("resource exhausted") ||
35-
text.includes("throttlingexception") ||
36-
text.includes("throttling")
71+
status === 429
72+
|| text.includes("rate limit")
73+
|| text.includes("rate limited")
74+
|| text.includes("too many requests")
75+
|| text.includes("resource_exhausted")
76+
|| text.includes("resource exhausted")
77+
|| text.includes("throttlingexception")
78+
|| text.includes("throttling")
3779
) {
3880
return { message, type: "rate_limit_error", code: "rate_limit_exceeded" };
3981
}
4082
if (type === "origin_rejected") {
4183
return { message, type: "invalid_request_error", code: "origin_rejected" };
4284
}
85+
// Plan / model gates before auth: providers (e.g. Ollama Cloud) return 403 for Pro-only
86+
// models with a valid key. Those must not look like invalid_api_key in Logs.
87+
if (isSubscriptionGateMessage(text)) {
88+
return { message, type: "permission_error", code: "subscription_required" };
89+
}
4390
if (
44-
status === 401 ||
45-
status === 403 ||
46-
type === "authentication_error" ||
47-
text.includes("authentication failed") ||
48-
text.includes("access denied") ||
49-
text.includes("unauthorizedexception") ||
50-
text.includes("unrecognizedclientexception") ||
51-
text.includes("unrecognizedclient") ||
52-
text.includes("expired token") ||
53-
text.includes("expiredtoken")
91+
status === 401
92+
|| type === "authentication_error"
93+
|| isAuthenticationMessage(text)
5494
) {
5595
return { message, type: "authentication_error", code: "invalid_api_key" };
5696
}
5797
if (
58-
status === 503 ||
59-
text.includes("overloaded") ||
60-
text.includes("server is busy") ||
61-
text.includes("temporarily unavailable")
98+
status === 403
99+
|| type === "permission_error"
100+
|| isPermissionMessage(text)
101+
) {
102+
return { message, type: "permission_error", code: "permission_denied" };
103+
}
104+
if (
105+
status === 503
106+
|| text.includes("overloaded")
107+
|| text.includes("server is busy")
108+
|| text.includes("temporarily unavailable")
62109
) {
63110
// Codex recognizes "server_is_overloaded" and applies retry-after backoff
64111
// (responses.rs is_server_overloaded_error); generic "upstream_server_error" is not recognized.
65112
return { message, type: "server_error", code: "server_is_overloaded" };
66113
}
67114
if (
68-
text.includes("validationexception") ||
69-
text.includes("invalid request") ||
70-
text.includes("model unavailable") ||
71-
text.includes("model not found") ||
72-
text.includes("unsupported model") ||
73-
text.includes("profile arn") ||
74-
text.includes("wrong region") ||
75-
text.includes("invalid region")
115+
text.includes("validationexception")
116+
|| text.includes("invalid request")
117+
|| text.includes("model unavailable")
118+
|| text.includes("model not found")
119+
|| text.includes("unsupported model")
120+
|| text.includes("profile arn")
121+
|| text.includes("wrong region")
122+
|| text.includes("invalid region")
76123
) {
77124
return { message, type: "invalid_request_error", code: "invalid_request_error" };
78125
}
@@ -105,41 +152,42 @@ export function parseRetryAfterFromMessage(message: string): number | undefined
105152
export function inferHttpStatusFromAdapterMessage(message: string): number {
106153
const lower = message.toLowerCase();
107154
if (
108-
lower.includes("resource_exhausted") ||
109-
lower.includes("resource exhausted") ||
110-
lower.includes("rate limit") ||
111-
lower.includes("too many requests") ||
112-
lower.includes("throttling")
155+
lower.includes("resource_exhausted")
156+
|| lower.includes("resource exhausted")
157+
|| lower.includes("rate limit")
158+
|| lower.includes("too many requests")
159+
|| lower.includes("throttling")
113160
) return 429;
161+
if (isSubscriptionGateMessage(lower) || isPermissionMessage(lower)) return 403;
114162
if (
115-
lower.includes("unauthenticated") ||
116-
lower.includes("unauthorized") ||
117-
lower.includes("permission_denied") ||
118-
lower.includes("permission denied") ||
119-
lower.includes("forbidden") ||
120-
lower.includes("invalid token") ||
121-
lower.includes("expired token") ||
122-
lower.includes("authentication") ||
123-
lower.includes("access denied")
163+
lower.includes("unauthenticated")
164+
|| lower.includes("unauthorized")
165+
|| lower.includes("invalid token")
166+
|| lower.includes("expired token")
167+
|| lower.includes("authentication")
168+
|| lower.includes("invalid api key")
169+
|| lower.includes("invalid_api_key")
124170
) return 401;
171+
// AccessDenied without an auth/subscription cue — keep historical 401 mapping for Kiro-style text.
172+
if (lower.includes("access denied")) return 401;
125173
if (
126-
lower.includes("unavailable") ||
127-
lower.includes("overloaded") ||
128-
lower.includes("temporarily") ||
129-
lower.includes("server is busy")
174+
lower.includes("unavailable")
175+
|| lower.includes("overloaded")
176+
|| lower.includes("temporarily")
177+
|| lower.includes("server is busy")
130178
) return 503;
131179
if (
132-
lower.includes("invalid") ||
133-
lower.includes("not found") ||
134-
lower.includes("unsupported") ||
135-
lower.includes("malformed") ||
136-
lower.includes("unimplemented")
180+
lower.includes("invalid")
181+
|| lower.includes("not found")
182+
|| lower.includes("unsupported")
183+
|| lower.includes("malformed")
184+
|| lower.includes("unimplemented")
137185
) return 400;
138186
if (
139-
lower.includes("timed out") ||
140-
lower.includes("timeout") ||
141-
lower.includes("etimedout") ||
142-
lower.includes("deadline")
187+
lower.includes("timed out")
188+
|| lower.includes("timeout")
189+
|| lower.includes("etimedout")
190+
|| lower.includes("deadline")
143191
) return 504;
144192
return 502;
145193
}
@@ -156,11 +204,13 @@ export function adapterFailureFromMessage(message: string): { httpStatus: number
156204
? "rate_limit_error"
157205
: httpStatus === 401
158206
? "authentication_error"
159-
: httpStatus === 503 || httpStatus === 504
160-
? "server_error"
161-
: httpStatus === 400
162-
? "invalid_request_error"
163-
: "upstream_error";
207+
: httpStatus === 403
208+
? "permission_error"
209+
: httpStatus === 503 || httpStatus === 504
210+
? "server_error"
211+
: httpStatus === 400
212+
? "invalid_request_error"
213+
: "upstream_error";
164214
return {
165215
httpStatus,
166216
error: classifyError(httpStatus, errorType, finalMessage),
@@ -176,6 +226,11 @@ export function httpStatusFromTerminalError(error: {
176226
if (!error) return 502;
177227
if (error.type === "rate_limit_error" || error.code === "rate_limit_exceeded") return 429;
178228
if (error.type === "authentication_error" || error.code === "invalid_api_key") return 401;
229+
if (
230+
error.type === "permission_error"
231+
|| error.code === "permission_denied"
232+
|| error.code === "subscription_required"
233+
) return 403;
179234
if (error.type === "insufficient_quota" || error.code === "insufficient_quota") return 429;
180235
if (error.type === "server_error" && error.code === "server_is_overloaded") return 503;
181236
if (error.type === "invalid_request_error") return 400;

‎src/server/request-log.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { existsSync, readFileSync } from "node:fs";
22
import type { ResponsesTerminalStatus } from "../bridge";
3-
import { httpStatusFromTerminalError as httpStatusFromClassifiedTerminalError } from "../lib/errors";
3+
import {
4+
classifyError,
5+
httpStatusFromTerminalError as httpStatusFromClassifiedTerminalError,
6+
} from "../lib/errors";
47
import { CODEX_CONFIG_PATH, readRootTomlString } from "../codex/paths";
58
import { readCodexCatalogPath } from "../codex/catalog";
69
import type { OcxUsage } from "../types";
@@ -119,10 +122,19 @@ export function nextRequestLogId(timestamp = Date.now()): string {
119122
return `ocx-${timestamp.toString(36)}-${requestLogSeq.toString(36)}`;
120123
}
121124

122-
export function requestLogErrorCode(status: number): string | undefined {
125+
export function requestLogErrorCode(status: number, upstreamError?: string): string | undefined {
123126
if (status >= 200 && status < 400) return undefined;
124127
if (status === 400 || status === 409) return "invalid_request_error";
125-
if (status === 401 || status === 403) return "invalid_api_key";
128+
if (status === 401) return "invalid_api_key";
129+
if (status === 403) {
130+
// Prefer message-aware codes (e.g. Ollama Cloud subscription gates) over a blunt
131+
// invalid_api_key — 403 usually means authenticated but not allowed.
132+
if (upstreamError?.trim()) {
133+
const code = classifyError(403, "upstream_error", upstreamError).code;
134+
if (code) return code;
135+
}
136+
return "permission_denied";
137+
}
126138
if (status === 429) return "rate_limit_exceeded";
127139
if (status === 499) return "client_closed_request";
128140
if (status === 503) return "server_is_overloaded";
@@ -375,7 +387,7 @@ export function addFinalRequestLog(
375387
meta?: Pick<RequestLogEntry, "terminalStatus" | "closeReason">,
376388
addLog: (entry: RequestLogEntry) => void = addRequestLog,
377389
): void {
378-
const errorCode = requestLogErrorCode(status);
390+
const errorCode = requestLogErrorCode(status, logCtx.upstreamError);
379391
// Estimated-usage detection prefers the route ADAPTER: configured provider names
380392
// ("cursor-mykey") broke the old exact-name match and cursor rows logged as
381393
// accurately "reported" (devlog 130 B2).

‎tests/error-fidelity.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@ describe("error fidelity", () => {
5454
type: "authentication_error",
5555
code: "invalid_api_key",
5656
});
57+
expect(classifyError(403, "upstream_error", "Provider error 403")).toMatchObject({
58+
type: "permission_error",
59+
code: "permission_denied",
60+
});
61+
expect(classifyError(403, "upstream_error", "this model requires a subscription, upgrade for access: https://ollama.com/upgrade")).toMatchObject({
62+
type: "permission_error",
63+
code: "subscription_required",
64+
});
5765
expect(classifyError(502, "upstream_error", "Kiro invalid request: ValidationException: model not found")).toMatchObject({
5866
type: "invalid_request_error",
5967
code: "invalid_request_error",

‎tests/errors-adapter-failure.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,15 @@ describe("adapterFailureFromMessage", () => {
2525
error: { type: "authentication_error" },
2626
});
2727
});
28+
29+
test("maps forbidden / subscription gates to 403 permission_error", () => {
30+
expect(adapterFailureFromMessage("Provider stream error: forbidden")).toMatchObject({
31+
httpStatus: 403,
32+
error: { type: "permission_error", code: "permission_denied" },
33+
});
34+
expect(adapterFailureFromMessage("this model requires a subscription, upgrade for access: https://ollama.com/upgrade")).toMatchObject({
35+
httpStatus: 403,
36+
error: { type: "permission_error", code: "subscription_required" },
37+
});
38+
});
2839
});

0 commit comments

Comments
 (0)