Skip to content

Commit 4ff6535

Browse files
author
Xinwei Gao
committed
fix(anthropic): honor bearer key auth for gateway models
Use apiKeyTransport when building Anthropic key-auth requests and normalize Anthropic model discovery URLs so /v1 base URLs do not become /v1/v1/models.
1 parent 903b62c commit 4ff6535

5 files changed

Lines changed: 57 additions & 6 deletions

File tree

‎src/adapters/anthropic.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,10 @@ function usesNativeAnthropicEndpoint(provider: OcxProviderConfig): boolean {
250250
}
251251
}
252252

253+
function anthropicKeyUsesBearer(provider: OcxProviderConfig): boolean {
254+
return provider.apiKeyTransport === "bearer";
255+
}
256+
253257
/** Map a Responses reasoning effort to an Anthropic extended-thinking budget (tokens, >= 1024). */
254258
function reasoningBudget(effort: string): number {
255259
switch (effort) {
@@ -694,7 +698,8 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti
694698
headers["X-Claude-Code-Session-Id"] = claudeCodeSessionId(provider.apiKey);
695699
headers["x-client-request-id"] = crypto.randomUUID();
696700
} else {
697-
headers["x-api-key"] = provider.apiKey;
701+
if (anthropicKeyUsesBearer(provider)) headers["Authorization"] = `Bearer ${provider.apiKey}`;
702+
else headers["x-api-key"] = provider.apiKey;
698703
}
699704
if (provider.headers) Object.assign(headers, provider.headers);
700705

‎src/oauth/index.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -464,8 +464,9 @@ export async function resolveModelsAuthToken(name: string, prov: OcxProviderConf
464464
/**
465465
* Provider-correct `GET /models` request (URL + headers), so both model-listing paths fetch the
466466
* LIVE catalog correctly per adapter. Anthropic is the special case: its endpoint is `/v1/models`
467-
* (not `/models`), it needs `anthropic-version`, and it authenticates with `x-api-key` (key) or
468-
* `Authorization: Bearer` + the OAuth beta (oauth) — not a bare Bearer. Google (ai-studio mode)
467+
* (not `/models`), it needs `anthropic-version`, and it authenticates with `x-api-key` by default
468+
* (or `Authorization: Bearer` when `apiKeyTransport = "bearer"`), plus the OAuth beta for oauth
469+
* mode — not a bare Bearer. Google (ai-studio mode)
469470
* is the other special case: `x-goog-api-key` + `/v1beta/models`, returning `{ models: [...] }`.
470471
* The catalog authority gate intentionally degrades that non-OpenAI shape to stale/static data.
471472
* Everyone else uses the OpenAI-style `/models` + Bearer with a `{ data: [{ id, owned_by? }] }`
@@ -488,14 +489,16 @@ export function buildModelsRequest(prov: OcxProviderConfig, apiKey: string | und
488489
return { url: `${effectiveProvider.baseUrl}/v1beta/models?pageSize=1000`, headers };
489490
}
490491
if (effectiveProvider.adapter === "anthropic") {
492+
const base = effectiveProvider.baseUrl.replace(/\/v1\/?$/, "");
491493
headers["anthropic-version"] = "2023-06-01";
492494
if (effectiveProvider.authMode === "oauth") {
493495
headers["anthropic-beta"] = ANTHROPIC_OAUTH_BETA;
494496
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
495497
} else if (apiKey) {
496-
headers["x-api-key"] = apiKey;
498+
if (effectiveProvider.apiKeyTransport === "bearer") headers["Authorization"] = `Bearer ${apiKey}`;
499+
else headers["x-api-key"] = apiKey;
497500
}
498-
return { url: `${effectiveProvider.baseUrl}/v1/models?limit=1000`, headers };
501+
return { url: `${base}/v1/models?limit=1000`, headers };
499502
}
500503
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
501504
return { url: `${effectiveProvider.baseUrl}/models`, headers };

‎src/types.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -873,6 +873,12 @@ export interface OcxProviderConfig {
873873
*/
874874
codexAccountMode?: CodexAccountMode;
875875
apiKey?: string;
876+
/**
877+
* Key-auth header style for Anthropic-compatible providers.
878+
* Defaults to the native Anthropic `x-api-key`; gateways may require
879+
* `Authorization: Bearer <key>` instead.
880+
*/
881+
apiKeyTransport?: "x-api-key" | "bearer";
876882
/**
877883
* Multi-key pool (API-key twin of OAuth multiauth). `apiKey` always mirrors the ACTIVE
878884
* entry so routing stays single-key; managed via /api/providers/keys. A legacy bare

‎tests/google-models-listing.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,34 @@ describe("buildModelsRequest google routing", () => {
4949
});
5050
});
5151

52+
describe("buildModelsRequest anthropic routing", () => {
53+
test("normalizes a /v1 baseUrl and keeps the Anthropic models path singular", () => {
54+
const prov = {
55+
adapter: "anthropic",
56+
authMode: "key",
57+
apiKeyTransport: "bearer",
58+
baseUrl: "https://gateway.example.com/v1",
59+
} as OcxProviderConfig;
60+
const { url, headers } = buildModelsRequest(prov, "sk-ant", "gateway");
61+
expect(url).toBe("https://gateway.example.com/v1/models?limit=1000");
62+
expect(headers["Authorization"]).toBe("Bearer sk-ant");
63+
expect(headers["x-api-key"]).toBeUndefined();
64+
expect(headers["anthropic-version"]).toBe("2023-06-01");
65+
});
66+
67+
test("uses x-api-key by default for key-auth Anthropic providers", () => {
68+
const prov = {
69+
adapter: "anthropic",
70+
authMode: "key",
71+
baseUrl: "https://gateway.example.com",
72+
} as OcxProviderConfig;
73+
const { url, headers } = buildModelsRequest(prov, "sk-ant", "gateway");
74+
expect(url).toBe("https://gateway.example.com/v1/models?limit=1000");
75+
expect(headers["x-api-key"]).toBe("sk-ant");
76+
expect(headers["Authorization"]).toBeUndefined();
77+
});
78+
});
79+
5280
describe("google models listing via catalog", () => {
5381
test("treats a { models } 2xx shape as malformed and degrades to the static seed", async () => {
5482
clearModelCache("google");

‎tests/umans-provider.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@ import { providerConfigFromKeyLoginProvider } from "../src/oauth/login-cli";
44
import { enrichProviderFromCatalog, KEY_LOGIN_PROVIDERS, validateApiKey } from "../src/oauth/key-providers";
55
import type { AdapterEvent, OcxParsedRequest, OcxProviderConfig } from "../src/types";
66

7-
function umansProvider(apiKey = "sk-umans"): OcxProviderConfig {
7+
function umansProvider(apiKey = "sk-umans", apiKeyTransport?: OcxProviderConfig["apiKeyTransport"]): OcxProviderConfig {
88
return {
99
adapter: "anthropic",
1010
baseUrl: "https://api.code.umans.ai",
1111
apiKey,
12+
...(apiKeyTransport ? { apiKeyTransport } : {}),
1213
defaultModel: "umans-coder",
1314
escapeBuiltinToolNames: true,
1415
};
@@ -113,6 +114,14 @@ describe("Umans provider", () => {
113114
expect(body.tool_choice).toEqual({ type: "tool", name: "cx_web_search" });
114115
});
115116

117+
test("Anthropic adapter honors apiKeyTransport=bearer for key-auth gateways", async () => {
118+
const req = await createAnthropicAdapter(umansProvider("sk-umans", "bearer")).buildRequest(parsedWithWebSearchTool());
119+
120+
expect(req.headers.Authorization).toBe("Bearer sk-umans");
121+
expect(req.headers["x-api-key"]).toBeUndefined();
122+
expect(req.headers["anthropic-version"]).toBe("2023-06-01");
123+
});
124+
116125
test("Anthropic adapter filters Umans tools for Responses allowed_tools choices", async () => {
117126
const req = await createAnthropicAdapter(umansProvider()).buildRequest({
118127
modelId: "umans-kimi-k2.7",

0 commit comments

Comments
 (0)