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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. // 旧夹具依赖不完整凭据绕过校验;此处注入中性端口,安全合同由独立用例验证。
  34. requestSecurityState: {
  35. createExecution: () => ({
  36. protectTransport: ({ transport }) => transport,
  37. take: () => [],
  38. }),
  39. },
  40. transport: async (input, init) => {
  41. requests.push(new Request(input, init));
  42. // 捕获真实 SDK 最终请求头;不访问网络,不依赖各协议的成功响应格式。
  43. return Response.json(
  44. { error: { type: "invalid_request_error", message: "captured" } },
  45. { status: 400 },
  46. );
  47. },
  48. },
  49. );
  50. const provider = createRegistryProviderConfig(
  51. parseProviderConfig({
  52. group: "standard-personal",
  53. access,
  54. api: { type: apiType, baseUrl: "https://model.example/api/anthropic", headers },
  55. }),
  56. );
  57. if (!provider.ok) throw new Error("invalid auth fixture");
  58. const bound = execution.bindModel({
  59. providerId: "auth-fixture",
  60. modelId: "GLM-5.3",
  61. providerConfig: provider.config,
  62. supportsJsonSchemaOutput: false,
  63. optionSpecs: { reasoningLevel: { map: "{}" }, maxOutputTokens: { map: "{}" } },
  64. });
  65. return { requests, bound };
  66. }
  67. async function capture(model: Parameters<typeof generateText>[0]["model"]) {
  68. await expect(generateText({ model, prompt: "test", maxRetries: 0 })).rejects.toThrow();
  69. }
  70. describe.each(API_TYPES)("%s 请求期账号鉴权", (apiType) => {
  71. it.each(["individual-coding-plan", "team-coding-plan"] as const)(
  72. "%s 的 PAT 覆盖静态认证头,轮换不修改绑定配置",
  73. async (mode) => {
  74. for (const stale of STATIC_HEADERS) {
  75. const headers = { ...stale, "X-Session-ID": "session", "X-Custom": "keep" };
  76. const original = { ...headers };
  77. const { requests, bound } = fixture(
  78. apiType,
  79. { type: "zhipu-account", accountType: "bigmodel", mode, entitled: true },
  80. headers,
  81. );
  82. const tokens = [TOKEN, TOKEN.replace("test", "next")];
  83. for (const apiKey of tokens) {
  84. await capture(bound.resolveRequest({ options: OPTIONS, requestAuth: { apiKey } }).model);
  85. }
  86. expect(requests).toHaveLength(2);
  87. requests.forEach((request, index) => {
  88. expect(request.headers.get("authorization")).toBe(`Bearer ${tokens[index]}`);
  89. expect(request.headers.get("x-api-key")).toBe(
  90. apiType === "anthropic-messages" ? tokens[index] : null,
  91. );
  92. expect(request.headers.get("x-session-id")).toBe("session");
  93. expect(request.headers.get("x-custom")).toBe("keep");
  94. });
  95. expect(headers).toEqual(original);
  96. }
  97. },
  98. );
  99. it.each(["api-key", "zhipu-coding-plan-api-key"] as const)(
  100. "%s 保留自定义认证头",
  101. async (type) => {
  102. // access 类型决定认证头优先级;手工 Key 必须保留调用方自定义头。
  103. const { requests, bound } = fixture(apiType, { type, apiKey: TOKEN }, STATIC_HEADERS[0]!);
  104. await capture(
  105. bound.resolveRequest({ options: OPTIONS, requestAuth: { apiKey: TOKEN } }).model,
  106. );
  107. expect(requests).toHaveLength(1);
  108. expect(requests[0]!.headers.get("authorization")).toBe("Bearer old-key");
  109. expect(requests[0]!.headers.get("x-api-key")).toBe("old-key");
  110. },
  111. );
  112. });
  113. describe("账号 owner 的动态身份头", () => {
  114. it.each(["start-plan", "off-peak", "highspeed"] as const)(
  115. "%s 保留独立 JWT 和票据头",
  116. async (mode) => {
  117. const { requests, bound } = fixture(
  118. "anthropic-messages",
  119. { type: "zhipu-account", accountType: "bigmodel", mode, entitled: true },
  120. STATIC_HEADERS[0]!,
  121. );
  122. await capture(
  123. bound.resolveRequest({
  124. options: OPTIONS,
  125. requestAuth: {
  126. apiKey: "runtime-jwt",
  127. headers: {
  128. Authorization: "Bearer owner-jwt",
  129. "X-API-KEY": "owner-key",
  130. "X-Off-Peak-Ticket-ID": "ticket",
  131. },
  132. },
  133. }).model,
  134. );
  135. expect(requests).toHaveLength(1);
  136. expect(requests[0]!.headers.get("authorization")).toBe("Bearer owner-jwt");
  137. expect(requests[0]!.headers.get("x-api-key")).toBe("owner-key");
  138. expect(requests[0]!.headers.get("x-off-peak-ticket-id")).toBe("ticket");
  139. },
  140. );
  141. });