fix: keep Cloudflare Anthropic provider auth header

This commit is contained in:
Peter Steinberger
2026-05-26 23:06:07 +01:00
parent cdf77cd972
commit dfb86df6fc
2 changed files with 62 additions and 3 deletions

View File

@@ -0,0 +1,61 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Context, Model } from "../types.js";
const anthropicMockState = vi.hoisted(() => ({
configs: [] as unknown[],
}));
vi.mock("@anthropic-ai/sdk", () => ({
default: class MockAnthropic {
messages = {
create: vi.fn(() => {
throw new Error("stop after constructor");
}),
};
constructor(config: unknown) {
anthropicMockState.configs.push(config);
}
},
}));
import { streamAnthropic } from "./anthropic.js";
describe("Anthropic provider", () => {
beforeEach(() => {
anthropicMockState.configs = [];
});
it("keeps Cloudflare AI Gateway upstream provider auth on the Anthropic API key", async () => {
const model = {
id: "claude-sonnet-4-6",
provider: "cloudflare-ai-gateway",
api: "anthropic-messages",
baseUrl:
"https://gateway.ai.cloudflare.com/v1/account/gateway/anthropic/v1/messages",
maxTokens: 4096,
headers: {
"cf-aig-authorization": "Bearer gateway-token",
},
} satisfies Model<"anthropic-messages">;
const context = {
messages: [{ role: "user", content: "hello" }],
} satisfies Context;
streamAnthropic(model, context, {
apiKey: "sk-ant-provider",
});
await vi.waitFor(() => expect(anthropicMockState.configs).toHaveLength(1));
const config = anthropicMockState.configs[0] as {
apiKey?: string | null;
authToken?: string | null;
defaultHeaders?: Record<string, string | null>;
};
expect(config.apiKey).toBe("sk-ant-provider");
expect(config.authToken).toBeNull();
expect(config.defaultHeaders?.["x-api-key"]).toBeUndefined();
expect(config.defaultHeaders?.["cf-aig-authorization"]).toBe("Bearer gateway-token");
});
});

View File

@@ -833,7 +833,7 @@ function createClient(
if (model.provider === "cloudflare-ai-gateway") {
const client = new Anthropic({
apiKey: null,
apiKey,
authToken: null,
baseURL: resolveCloudflareBaseUrl(model),
dangerouslyAllowBrowser: true,
@@ -841,8 +841,6 @@ function createClient(
{
accept: "application/json",
"anthropic-dangerous-direct-browser-access": "true",
"cf-aig-authorization": `Bearer ${apiKey}`,
"x-api-key": null,
Authorization: null,
...(betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}),
},