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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. function fixture(options: { jwtTtl?: number; expiresIn?: number; failures?: number[] } = {}) {
  5. let logins = 0;
  6. let issues = 0;
  7. const failures = [...(options.failures ?? [])];
  8. const request = vi.fn(async (req: { url: string }) => {
  9. let body: unknown;
  10. let status = 200;
  11. if (req.url.endsWith("/api/auth/z/login")) {
  12. logins++;
  13. const claims = { exp: Date.now() / 1000 + (options.jwtTtl ?? 600), sub: String(logins) };
  14. const token = `header.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.signature`;
  15. body = {
  16. code: 200,
  17. data: {
  18. access_token: token,
  19. ...(options.expiresIn === undefined ? {} : { expires_in: options.expiresIn }),
  20. },
  21. };
  22. } else if (req.url.endsWith("/getCustomerInfo")) {
  23. body = {
  24. code: 200,
  25. data: {
  26. organizations: [
  27. {
  28. organizationId: "org",
  29. organizationName: "默认机构",
  30. projects: [{ projectId: "project", projectName: "默认项目" }],
  31. },
  32. ],
  33. },
  34. };
  35. } else if (req.url.endsWith("/api_keys")) {
  36. body = { code: 200, data: [{ apiKey: "key", name: "zcode-api-key" }] };
  37. } else {
  38. issues++;
  39. status = failures.shift() ?? 200;
  40. body = {
  41. code: status,
  42. data: {
  43. accessToken: `pat-${issues}`,
  44. tokenType: "Bearer",
  45. expiresIn: 1,
  46. expiresAt: Date.now() / 1000 + 1,
  47. },
  48. };
  49. }
  50. return { status, body: new TextEncoder().encode(JSON.stringify(body)) };
  51. });
  52. const resolver = createCodingPlanApiKeyResolver({
  53. httpClient: { request } as unknown as HttpClientPort,
  54. });
  55. const input = { family: "zai", accessToken: "oauth", accountIdentity: "user" } as const;
  56. return {
  57. resolve: () => resolver.resolve(input),
  58. clear: () => resolver.clear(),
  59. logins: () => logins,
  60. issues: () => issues,
  61. request,
  62. };
  63. }
  64. afterEach(() => vi.useRealTimers());
  65. describe("Z.ai 业务登录 Token 刷新", () => {
  66. it.each([{ jwtTtl: 600 }, { jwtTtl: 3600, expiresIn: 600 }])(
  67. "最早 TTL 到刷新窗口后重新交换且并发合并:%j",
  68. async (options) => {
  69. vi.useFakeTimers();
  70. const f = fixture(options);
  71. await f.resolve();
  72. vi.setSystemTime(Date.now() + 481_000);
  73. await Promise.all([f.resolve(), f.resolve(), f.resolve()]);
  74. expect(f.logins()).toBe(2);
  75. },
  76. );
  77. it("业务 401 只重新交换一次,不重复发送旧业务 JWT", async () => {
  78. const f = fixture({ failures: [401, 200] });
  79. await expect(f.resolve()).resolves.toBe("pat-2");
  80. expect(f.logins()).toBe(2);
  81. });
  82. it("连续 401 有限失败,下次调用不永久粘住旧业务 JWT", async () => {
  83. const f = fixture({ failures: [401, 401, 200] });
  84. await expect(f.resolve()).rejects.toThrow("project_token_request_failed");
  85. expect(f.logins()).toBe(2);
  86. await expect(f.resolve()).resolves.toBe("pat-3");
  87. expect(f.logins()).toBe(3);
  88. });
  89. it.each([403, 500])("%s 不触发重新交换", async (status) => {
  90. const f = fixture({ failures: [status] });
  91. await expect(f.resolve()).rejects.toThrow();
  92. expect(f.logins()).toBe(1);
  93. expect(f.issues()).toBe(1);
  94. });
  95. });
  96. it("并发业务 401 合并重新交换,所有调用都能恢复", async () => {
  97. const f = fixture({ failures: [401, 200] });
  98. await expect(Promise.all([f.resolve(), f.resolve(), f.resolve()])).resolves.toEqual([
  99. "pat-2",
  100. "pat-2",
  101. "pat-2",
  102. ]);
  103. expect(f.logins()).toBe(2);
  104. });
  105. it.each([
  106. "network_error",
  107. "timeout",
  108. "cancelled",
  109. "egress_blocked",
  110. "invalid",
  111. "unknown",
  112. 429,
  113. 503,
  114. 401,
  115. 403,
  116. 404,
  117. ] as const)("业务 JWT 提前刷新 %s 的分类、日志、退避和原有效期边界", async (failure) => {
  118. vi.useFakeTimers();
  119. const start = Date.now();
  120. let logins = 0;
  121. let recovered = false;
  122. const request = vi.fn(async ({ url }: { url: string }) => {
  123. let data: unknown;
  124. if (url.endsWith("/api/auth/z/login")) {
  125. logins++;
  126. if (logins > 1 && !recovered) {
  127. if (failure === "invalid")
  128. return { status: 200, body: new TextEncoder().encode("invalid secret JSON") };
  129. if (failure === "unknown") throw new Error("secret failure");
  130. if (typeof failure === "string")
  131. throw createHttpClientError({ code: failure, message: "secret failure" });
  132. return { status: failure, body: new TextEncoder().encode("secret failure") };
  133. }
  134. data = { access_token: `business-jwt-${logins}`, expires_in: 600 };
  135. } else if (url.endsWith("getCustomerInfo")) {
  136. data = { organizations: [{ organizationId: "org", projects: [{ projectId: "project" }] }] };
  137. } else if (url.endsWith("api_keys")) {
  138. data = [{ apiKey: "key", name: "zcode-api-key" }];
  139. } else {
  140. data = {
  141. accessToken: "valid-pat",
  142. tokenType: "Bearer",
  143. expiresIn: 1800,
  144. expiresAt: start / 1000 + 1800,
  145. };
  146. }
  147. return { status: 200, body: new TextEncoder().encode(JSON.stringify({ code: 200, data })) };
  148. });
  149. const observe = vi.fn();
  150. const resolver = createCodingPlanApiKeyResolver({
  151. httpClient: { request } as unknown as HttpClientPort,
  152. observe,
  153. });
  154. const input = { family: "zai", accessToken: "oauth", accountIdentity: "user" } as const;
  155. await expect(resolver.resolve(input)).resolves.toBe("valid-pat");
  156. vi.setSystemTime(start + 481_000);
  157. if (["network_error", "timeout", 429, 503].includes(failure)) {
  158. await expect(Promise.all([resolver.resolve(input), resolver.resolve(input)])).resolves.toEqual([
  159. "valid-pat",
  160. "valid-pat",
  161. ]);
  162. await resolver.resolve(input);
  163. expect(logins).toBe(2);
  164. expect(observe).toHaveBeenCalledExactlyOnceWith({
  165. family: "zai",
  166. stage: "resolve",
  167. code: "project_token_business_login_refresh_deferred",
  168. });
  169. // 业务 JWT 到期后即使 PAT 仍有效,也不能把临时故障当作成功。
  170. vi.setSystemTime(start + 600_000);
  171. }
  172. await expect(resolver.resolve(input)).rejects.toThrow("project_token_login_failed");
  173. recovered = true;
  174. await expect(resolver.resolve(input)).resolves.toBe("valid-pat");
  175. expect(JSON.stringify(observe.mock.calls)).not.toMatch(/secret|business-jwt|valid-pat|oauth/);
  176. });