project-token-request-auth.test.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import { generateText } from "ai";
  2. import { describe, expect, it } from "vitest";
  3. import { createRegistryProviderConfig, parseProviderConfig } from "@zcode/provider";
  4. import { AiSdkModelExecution } from "../src/model/model-execution.js";
  5. const TOKEN = [
  6. Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT", sign_type: "SIGN" })).toString(
  7. "base64url",
  8. ),
  9. Buffer.from(JSON.stringify({ token_use: "project_access", sub: "test-account" })).toString(
  10. "base64url",
  11. ),
  12. "synthetic_signature_only_for_test",
  13. ].join(".");
  14. const API_TYPES = ["anthropic-messages", "openai-chat-completions", "openai-responses"] as const;
  15. const OPTIONS = { reasoningLevel: "disabled", maxOutputTokens: 64 };
  16. const STATIC_HEADERS = [
  17. { Authorization: "Bearer old-key", "x-api-key": "old-key" },
  18. { authorization: "Bearer old-key", "X-API-KEY": "old-key" },
  19. { AuThOrIzAtIoN: "Bearer old-key", "X-Api-Key": "old-key" },
  20. ];
  21. function fixture(
  22. apiType: (typeof API_TYPES)[number],
  23. access: Record<string, unknown>,
  24. headers: Record<string, string>,
  25. ) {
  26. const requests: Request[] = [];
  27. const execution = new AiSdkModelExecution(
  28. {
  29. env: {},
  30. defaultHeaders: { AUTHORIZATION: "Bearer default-old-key", "X-API-KEY": "default-old-key" },
  31. },
  32. {
  33. transport: async (input, init) => {
  34. requests.push(new Request(input, init));
  35. // 捕获真实 SDK 最终请求头;不访问网络,不依赖各协议的成功响应格式。
  36. return Response.json(
  37. { error: { type: "invalid_request_error", message: "captured" } },
  38. { status: 400 },
  39. );
  40. },
  41. },
  42. );
  43. const provider = createRegistryProviderConfig(
  44. parseProviderConfig({
  45. group: "standard-personal",
  46. access,
  47. api: { type: apiType, baseUrl: "https://open.bigmodel.cn/api/anthropic", headers },
  48. }),
  49. );
  50. if (!provider.ok) throw new Error("invalid auth fixture");
  51. const bound = execution.bindModel({
  52. providerId: "auth-fixture",
  53. modelId: "GLM-5.3",
  54. providerConfig: provider.config,
  55. supportsJsonSchemaOutput: false,
  56. optionSpecs: { reasoningLevel: { map: "{}" }, maxOutputTokens: { map: "{}" } },
  57. });
  58. return { requests, bound };
  59. }
  60. async function capture(model: Parameters<typeof generateText>[0]["model"]) {
  61. await expect(generateText({ model, prompt: "test", maxRetries: 0 })).rejects.toThrow();
  62. }
  63. describe.each(API_TYPES)("%s 请求期账号鉴权", (apiType) => {
  64. it.each(["individual-coding-plan", "team-coding-plan"] as const)(
  65. "%s 的 PAT 覆盖静态认证头,轮换不修改绑定配置",
  66. async (mode) => {
  67. for (const stale of STATIC_HEADERS) {
  68. const headers = { ...stale, "X-Session-ID": "session", "X-Custom": "keep" };
  69. const original = { ...headers };
  70. const { requests, bound } = fixture(
  71. apiType,
  72. { type: "zhipu-account", accountType: "bigmodel", mode, entitled: true },
  73. headers,
  74. );
  75. const tokens = [TOKEN, TOKEN.replace("test", "next")];
  76. for (const apiKey of tokens) {
  77. await capture(bound.resolveRequest({ options: OPTIONS, requestAuth: { apiKey } }).model);
  78. }
  79. expect(requests).toHaveLength(2);
  80. requests.forEach((request, index) => {
  81. expect(request.headers.get("authorization")).toBe(`Bearer ${tokens[index]}`);
  82. expect(request.headers.get("x-api-key")).toBe(
  83. apiType === "anthropic-messages" ? tokens[index] : null,
  84. );
  85. expect(request.headers.get("x-session-id")).toBe("session");
  86. expect(request.headers.get("x-custom")).toBe("keep");
  87. });
  88. expect(headers).toEqual(original);
  89. }
  90. },
  91. );
  92. it.each(["api-key", "zhipu-coding-plan-api-key"] as const)(
  93. "%s 保留自定义认证头",
  94. async (type) => {
  95. // 使用合法 PAT 形状隔离官方版本请求安全校验的旧路径,access 类型仍是手工 Key。
  96. const { requests, bound } = fixture(apiType, { type, apiKey: TOKEN }, STATIC_HEADERS[0]!);
  97. await capture(
  98. bound.resolveRequest({ options: OPTIONS, requestAuth: { apiKey: TOKEN } }).model,
  99. );
  100. expect(requests).toHaveLength(1);
  101. expect(requests[0]!.headers.get("authorization")).toBe("Bearer old-key");
  102. expect(requests[0]!.headers.get("x-api-key")).toBe("old-key");
  103. },
  104. );
  105. });
  106. describe("账号 owner 的动态身份头", () => {
  107. it.each(["start-plan", "off-peak", "highspeed"] as const)(
  108. "%s 保留独立 JWT 和票据头",
  109. async (mode) => {
  110. const { requests, bound } = fixture(
  111. "anthropic-messages",
  112. { type: "zhipu-account", accountType: "bigmodel", mode, entitled: true },
  113. STATIC_HEADERS[0]!,
  114. );
  115. await capture(
  116. bound.resolveRequest({
  117. options: OPTIONS,
  118. requestAuth: {
  119. apiKey: "runtime-jwt",
  120. headers: {
  121. Authorization: "Bearer owner-jwt",
  122. "X-API-KEY": "owner-key",
  123. "X-Off-Peak-Ticket-ID": "ticket",
  124. },
  125. },
  126. }).model,
  127. );
  128. expect(requests).toHaveLength(1);
  129. expect(requests[0]!.headers.get("authorization")).toBe("Bearer owner-jwt");
  130. expect(requests[0]!.headers.get("x-api-key")).toBe("owner-key");
  131. expect(requests[0]!.headers.get("x-off-peak-ticket-id")).toBe("ticket");
  132. },
  133. );
  134. });