project-token-refresh.test.ts 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { createHttpClientError, type HttpClientPort } from "@zcode/contracts";
  3. import { createCodingPlanApiKeyResolver } from "../src/auth/coding-plan-api-key.js";
  4. afterEach(() => vi.useRealTimers());
  5. describe.each(["bigmodel", "zai"] as const)("%s PAT 临时刷新失败", (family) => {
  6. it.each([
  7. "network_error",
  8. "timeout",
  9. "cancelled",
  10. "egress_blocked",
  11. "invalid",
  12. 429,
  13. 503,
  14. 403,
  15. 404,
  16. ] as const)("%s 分类、并发与过期", async (failure) => {
  17. vi.useFakeTimers();
  18. const start = Date.now();
  19. let issues = 0;
  20. const request = vi.fn(async ({ url }: { url: string }) => {
  21. let data: unknown;
  22. let status = 200;
  23. if (url.endsWith("/api/auth/z/login"))
  24. data = { access_token: "business-jwt", expires_in: 3600 };
  25. else if (url.endsWith("getCustomerInfo"))
  26. data = { organizations: [{ organizationId: "org", projects: [{ projectId: "project" }] }] };
  27. else if (url.endsWith("api_keys")) data = [{ apiKey: "key", name: "zcode-api-key" }];
  28. else {
  29. issues++;
  30. if (issues > 1) {
  31. if (failure === "invalid")
  32. return { status: 200, body: new TextEncoder().encode("invalid secret JSON") };
  33. if (typeof failure === "string")
  34. throw createHttpClientError({ code: failure, message: "secret failure" });
  35. status = failure;
  36. }
  37. data = {
  38. accessToken: "old-pat",
  39. tokenType: "Bearer",
  40. expiresIn: 600,
  41. expiresAt: start / 1000 + 600,
  42. };
  43. }
  44. return { status, body: new TextEncoder().encode(JSON.stringify({ code: "0", data })) };
  45. });
  46. const observe = vi.fn();
  47. const resolver = createCodingPlanApiKeyResolver({
  48. httpClient: { request } as unknown as HttpClientPort,
  49. observe,
  50. });
  51. const input = { family, accessToken: "oauth", accountIdentity: "user" };
  52. await expect(resolver.resolve(input)).resolves.toBe("old-pat");
  53. vi.setSystemTime(start + 481_000);
  54. if (["network_error", "timeout", 429, 503].includes(failure)) {
  55. await expect(
  56. Promise.all([resolver.resolve(input), resolver.resolve(input)]),
  57. ).resolves.toEqual(["old-pat", "old-pat"]);
  58. await resolver.resolve(input);
  59. expect(issues).toBe(2);
  60. expect(observe).toHaveBeenCalledExactlyOnceWith({
  61. family,
  62. stage: "resolve",
  63. code: "project_token_refresh_deferred",
  64. });
  65. vi.setSystemTime(start + 600_000);
  66. }
  67. // ZCT-2111046389485834240:最终失败保留固定类别;未分类的 HttpClientPort 错误仍归 request_failed。
  68. const expectedCode: Record<string, string> = {
  69. network_error: "project_token_network_error",
  70. timeout: "project_token_timeout",
  71. cancelled: "project_token_request_failed",
  72. egress_blocked: "project_token_request_failed",
  73. invalid: "project_token_invalid_response",
  74. 429: "project_token_http_429",
  75. 503: "project_token_http_503",
  76. 403: "project_token_http_403",
  77. 404: "project_token_invalid_response",
  78. };
  79. await expect(resolver.resolve(input)).rejects.toThrow(
  80. new RegExp(`^${expectedCode[String(failure)]}$`),
  81. );
  82. expect(JSON.stringify(observe.mock.calls)).not.toMatch(/secret|old-pat|oauth|business-jwt/);
  83. });
  84. });