zai-business-token-refresh.test.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. import { fixture } from "./zai-business-token-refresh-fixture.js";
  5. afterEach(() => vi.useRealTimers());
  6. describe("Z.ai 业务登录 Token 刷新", () => {
  7. it.each([{ jwtTtl: 600 }, { jwtTtl: 3600, expiresIn: 600 }])(
  8. "最早 TTL 到刷新窗口后重新交换且并发合并:%j",
  9. async (options) => {
  10. vi.useFakeTimers();
  11. const f = fixture(options);
  12. await f.resolve();
  13. vi.setSystemTime(Date.now() + 481_000);
  14. await Promise.all([f.resolve(), f.resolve(), f.resolve()]);
  15. expect(f.logins()).toBe(2);
  16. },
  17. );
  18. it("业务 401 只重新交换一次,不重复发送旧业务 JWT", async () => {
  19. const f = fixture({ failures: [401, 200] });
  20. await expect(f.resolve()).resolves.toBe("pat-2");
  21. expect(f.logins()).toBe(2);
  22. });
  23. it("连续 401 有限失败,下次调用不永久粘住旧业务 JWT", async () => {
  24. const f = fixture({ failures: [401, 401, 200] });
  25. await expect(f.resolve()).rejects.toThrow("project_token_http_401");
  26. expect(f.logins()).toBe(2);
  27. await expect(f.resolve()).resolves.toBe("pat-3");
  28. expect(f.logins()).toBe(3);
  29. });
  30. it.each([403])("%s 不触发重新交换", async (status) => {
  31. const f = fixture({ failures: [status] });
  32. await expect(f.resolve()).rejects.toThrow();
  33. expect(f.logins()).toBe(1);
  34. expect(f.issues()).toBe(1);
  35. });
  36. });
  37. it("并发业务 401 合并重新交换,所有调用都能恢复", async () => {
  38. const f = fixture({ failures: [401, 200] });
  39. await expect(Promise.all([f.resolve(), f.resolve(), f.resolve()])).resolves.toEqual([
  40. "pat-2",
  41. "pat-2",
  42. "pat-2",
  43. ]);
  44. expect(f.logins()).toBe(2);
  45. });
  46. it.each([
  47. "network_error",
  48. "timeout",
  49. "cancelled",
  50. "egress_blocked",
  51. "invalid",
  52. "unknown",
  53. 429,
  54. 503,
  55. 401,
  56. 403,
  57. 404,
  58. ] as const)("业务 JWT 提前刷新 %s 的分类、日志、退避和原有效期边界", async (failure) => {
  59. vi.useFakeTimers();
  60. const start = Date.now();
  61. let logins = 0;
  62. let recovered = false;
  63. const request = vi.fn(async ({ url }: { url: string }) => {
  64. let data: unknown;
  65. if (url.endsWith("/api/auth/z/login")) {
  66. logins++;
  67. if (logins > 1 && !recovered) {
  68. if (failure === "invalid")
  69. return { status: 200, body: new TextEncoder().encode("invalid secret JSON") };
  70. if (failure === "unknown") throw new Error("secret failure");
  71. if (typeof failure === "string")
  72. throw createHttpClientError({ code: failure, message: "secret failure" });
  73. return { status: failure, body: new TextEncoder().encode("secret failure") };
  74. }
  75. data = { access_token: `business-jwt-${logins}`, expires_in: 600 };
  76. } else if (url.endsWith("getCustomerInfo")) {
  77. data = { organizations: [{ organizationId: "org", projects: [{ projectId: "project" }] }] };
  78. } else if (url.endsWith("api_keys")) {
  79. data = [{ apiKey: "key", name: "zcode-api-key" }];
  80. } else {
  81. data = {
  82. accessToken: "valid-pat",
  83. tokenType: "Bearer",
  84. expiresIn: 1800,
  85. expiresAt: start / 1000 + 1800,
  86. };
  87. }
  88. return { status: 200, body: new TextEncoder().encode(JSON.stringify({ code: 200, data })) };
  89. });
  90. const observe = vi.fn();
  91. const resolver = createCodingPlanApiKeyResolver({
  92. httpClient: { request } as unknown as HttpClientPort,
  93. observe,
  94. });
  95. const input = { family: "zai", accessToken: "oauth", accountIdentity: "user" } as const;
  96. await expect(resolver.resolve(input)).resolves.toBe("valid-pat");
  97. vi.setSystemTime(start + 481_000);
  98. if (["network_error", "timeout", 429, 503].includes(failure)) {
  99. await expect(Promise.all([resolver.resolve(input), resolver.resolve(input)])).resolves.toEqual([
  100. "valid-pat",
  101. "valid-pat",
  102. ]);
  103. await resolver.resolve(input);
  104. expect(logins).toBe(2);
  105. expect(observe).toHaveBeenCalledExactlyOnceWith({
  106. family: "zai",
  107. stage: "resolve",
  108. code: "project_token_business_login_refresh_deferred",
  109. });
  110. // 业务 JWT 到期后即使 PAT 仍有效,也不能把临时故障当作成功。
  111. vi.setSystemTime(start + 600_000);
  112. }
  113. await expect(resolver.resolve(input)).rejects.toThrow("project_token_login_failed");
  114. recovered = true;
  115. await expect(resolver.resolve(input)).resolves.toBe("valid-pat");
  116. expect(JSON.stringify(observe.mock.calls)).not.toMatch(/secret|business-jwt|valid-pat|oauth/);
  117. });