project-token-refresh.test.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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(
  61. observe.mock.calls.filter(([event]) => event.code === "project_token_refresh_deferred"),
  62. ).toEqual([
  63. [
  64. {
  65. family,
  66. stage: "resolve",
  67. code: "project_token_refresh_deferred",
  68. },
  69. ],
  70. ]);
  71. vi.setSystemTime(start + 600_000);
  72. }
  73. // ZCT-2111046389485834240:最终失败保留固定类别;未分类的 HttpClientPort 错误仍归 request_failed。
  74. const expectedCode: Record<string, string> = {
  75. network_error: "project_token_network_error",
  76. timeout: "project_token_timeout",
  77. cancelled: "project_token_request_failed",
  78. egress_blocked: "project_token_request_failed",
  79. invalid: "project_token_invalid_response",
  80. 429: "project_token_http_429",
  81. 503: "project_token_http_503",
  82. 403: "project_token_http_403",
  83. 404: "project_token_invalid_response",
  84. };
  85. const rejection = expect(resolver.resolve(input)).rejects.toThrow(
  86. new RegExp(`^${expectedCode[String(failure)]}$`),
  87. );
  88. await vi.runAllTimersAsync();
  89. await rejection;
  90. expect(JSON.stringify(observe.mock.calls)).not.toMatch(/secret|old-pat|oauth|business-jwt/);
  91. });
  92. it.each([
  93. [481_000, "old-pat", 2],
  94. [599_000, "new-pat", 3],
  95. ] as const)("刷新从 %dms 开始时,按失败时的有效期处理", async (offset, expected, count) => {
  96. vi.useFakeTimers();
  97. const start = Date.now();
  98. let issues = 0;
  99. const request = vi.fn(async ({ url }: { url: string }) => {
  100. let data: unknown;
  101. if (url.endsWith("/api/auth/z/login"))
  102. data = { access_token: "business-jwt", expires_in: 3600 };
  103. else if (url.endsWith("getCustomerInfo"))
  104. data = { organizations: [{ organizationId: "org", projects: [{ projectId: "project" }] }] };
  105. else if (url.endsWith("api_keys")) data = [{ apiKey: "key", name: "zcode-api-key" }];
  106. else {
  107. issues++;
  108. if (issues === 2) {
  109. await new Promise((resolve) => setTimeout(resolve, 15_000));
  110. throw createHttpClientError({ code: "timeout", message: "synthetic timeout" });
  111. }
  112. data = {
  113. accessToken: issues === 1 ? "old-pat" : "new-pat",
  114. tokenType: "Bearer",
  115. expiresIn: 600,
  116. expiresAt: Date.now() / 1000 + 600,
  117. };
  118. }
  119. return { status: 200, body: new TextEncoder().encode(JSON.stringify({ code: 0, data })) };
  120. });
  121. const resolver = createCodingPlanApiKeyResolver({
  122. httpClient: { request } as unknown as HttpClientPort,
  123. });
  124. const input = { family, accessToken: "oauth", accountIdentity: "user" };
  125. await resolver.resolve(input);
  126. vi.setSystemTime(start + offset);
  127. let result: string | undefined;
  128. const pending = resolver.resolve(input).then((token) => {
  129. result = token;
  130. });
  131. try {
  132. await vi.advanceTimersByTimeAsync(15_000);
  133. expect(issues).toBe(count);
  134. await pending;
  135. expect(result).toBe(expected);
  136. } finally {
  137. await vi.runAllTimersAsync();
  138. await pending;
  139. }
  140. });
  141. });