accountProjectTokenRefresh.test.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { createAccountProjectTokenClient } from "../src/model-provider/accountProjectTokenClient.js";
  3. import { createNodeApiClient } from "../src/providers/api/nodeApiClient.js";
  4. afterEach(() => vi.useRealTimers());
  5. describe("Desktop PAT 临时故障分类", () => {
  6. it.each(["network", "timeout", 429, 503, 401, 403, 404, "invalid", "unknown"])(
  7. "%s 只在允许范围内复用未过期 PAT",
  8. async (failure) => {
  9. vi.useFakeTimers();
  10. const start = Date.now();
  11. let issues = 0;
  12. const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {
  13. const url = String(input);
  14. let data: unknown;
  15. if (url.endsWith("getCustomerInfo"))
  16. data = {
  17. organizations: [{ organizationId: "org", projects: [{ projectId: "project" }] }],
  18. };
  19. else if (url.endsWith("api_keys")) data = [{ apiKey: "key", name: "zcode-api-key" }];
  20. else {
  21. issues++;
  22. if (issues > 1) {
  23. if (failure === "network") throw new TypeError("fetch failed: secret must not escape");
  24. if (failure === "timeout") throw new DOMException("timeout", "AbortError");
  25. if (failure === "unknown") throw new Error("unknown secret");
  26. if (failure === "invalid") return new Response("invalid secret JSON");
  27. return new Response("upstream secret", { status: failure });
  28. }
  29. data = {
  30. accessToken: "old-pat",
  31. tokenType: "Bearer",
  32. expiresIn: 600,
  33. expiresAt: start / 1000 + 600,
  34. };
  35. }
  36. return Response.json({ code: "0", data });
  37. });
  38. const values = new Map<string, string>();
  39. const client = createAccountProjectTokenClient(createNodeApiClient({ fetchImpl }), {
  40. load: async (key) => values.get(key) ?? null,
  41. save: async (key, value) => {
  42. values.set(key, value);
  43. },
  44. delete: async (key) => {
  45. values.delete(key);
  46. },
  47. });
  48. const input = {
  49. family: "bigmodel" as const,
  50. origin: "https://example.invalid",
  51. accountId: "user",
  52. loginToken: "login",
  53. };
  54. await expect(client.resolve(input)).resolves.toMatchObject({ token: "old-pat" });
  55. vi.setSystemTime(start + 481_000);
  56. if (["network", "timeout", 429, 503].includes(failure)) {
  57. const results = await Promise.all([client.resolve(input), client.resolve(input)]);
  58. expect(results.map((value) => value.token)).toEqual(["old-pat", "old-pat"]);
  59. await client.resolve(input);
  60. expect(issues).toBe(2);
  61. vi.setSystemTime(start + 600_000);
  62. }
  63. await expect(client.resolve(input)).rejects.toThrow(
  64. /^project_token_(request_failed|invalid_response)$/,
  65. );
  66. expect(JSON.stringify([...values])).not.toMatch(/old-pat|login/);
  67. },
  68. );
  69. });