projectAccessTokenKeyContract.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import { describe, expect, it, vi } from "vitest";
  2. import { ProjectAccessTokenClient } from "../src/project-access-token-client.js";
  3. const scope = {
  4. origin: "https://example.invalid",
  5. family: "bigmodel" as const,
  6. loginToken: "login",
  7. accountId: "user",
  8. };
  9. const team = { organizationId: "org", projectId: "project" };
  10. const teamKey = { apiKey: "key", name: "zcode-team-api-key", keyType: 2 };
  11. const personalKey = { apiKey: "key", name: "zcode-api-key" };
  12. function fixture(options: { keys?: unknown[]; created?: unknown; organizations?: unknown[] } = {}) {
  13. const request = vi.fn(async (url: string, init: RequestInit) => {
  14. let data: unknown;
  15. if (url.endsWith("/getCustomerInfo"))
  16. data = {
  17. organizations: options.organizations ?? [
  18. { organizationId: "org", projects: [{ projectId: "project" }] },
  19. ],
  20. };
  21. else if (url.endsWith("/api_keys"))
  22. data = init.method === "POST" ? options.created : (options.keys ?? []);
  23. else
  24. data = {
  25. accessToken: "short-token",
  26. tokenType: "Bearer",
  27. expiresIn: 600,
  28. expiresAt: Date.now() / 1000 + 600,
  29. };
  30. return { code: 200, data };
  31. });
  32. return { request, client: new ProjectAccessTokenClient({ request }) };
  33. }
  34. describe("专用 Key 管理兼容契约", () => {
  35. it.each(["bigmodel", "zai"] as const)(
  36. "%s 身份读取使用裸 token,Key 管理和签发保留各自格式",
  37. async (family) => {
  38. for (const isTeam of [false, true]) {
  39. const f = fixture({ created: isTeam ? teamKey : personalKey });
  40. await expect(
  41. f.client.resolve({ ...scope, family, ...(isTeam ? { team } : {}) }),
  42. ).resolves.toMatchObject({ token: "short-token" });
  43. const customer = f.request.mock.calls.find(([url]) => url.endsWith("/getCustomerInfo"))!;
  44. expect(new Headers(customer[1].headers).get("authorization")).toBe("login");
  45. for (const [, init] of f.request.mock.calls.filter(([url]) => url.endsWith("/api_keys")))
  46. expect(new Headers(init.headers).get("authorization")).toBe(
  47. !isTeam && family === "zai" ? "Bearer login" : "login",
  48. );
  49. const issue = f.request.mock.calls.find(([url]) => url.endsWith("/access_tokens"))!;
  50. expect(new Headers(issue[1].headers).get("authorization")).toBe("Bearer login");
  51. }
  52. },
  53. );
  54. it.each([
  55. { ...teamKey, name: "other" },
  56. { ...teamKey, keyType: 1 },
  57. { ...teamKey, keyType: undefined },
  58. { ...teamKey, apiKey: " " },
  59. ])("拒绝错误团队创建结果 %j,不换证", async (created) => {
  60. const f = fixture({ created });
  61. await expect(f.client.resolve({ ...scope, team })).rejects.toThrow(
  62. "project_token_invalid_response",
  63. );
  64. expect(f.request.mock.calls.some(([url]) => url.endsWith("/access_tokens"))).toBe(false);
  65. });
  66. it.each([false, true])("无关缺 ID 条目不影响已有专用 Key,团队=%s", async (isTeam) => {
  67. const f = fixture({
  68. keys: [{ name: "other", apiKey: "" }, { name: "another" }, isTeam ? teamKey : personalKey],
  69. });
  70. await expect(
  71. f.client.resolve({ ...scope, ...(isTeam ? { team } : {}) }),
  72. ).resolves.toMatchObject({ apiKeyId: "key" });
  73. expect(
  74. f.request.mock.calls.filter(
  75. ([url, init]) => url.endsWith("/api_keys") && init.method === "POST",
  76. ),
  77. ).toHaveLength(0);
  78. });
  79. it("个人同名 Key 缺 ID 时失败,不重复创建", async () => {
  80. const f = fixture({ keys: [{ name: "zcode-api-key", apiKey: "" }], created: personalKey });
  81. await expect(f.client.resolve(scope)).rejects.toThrow("project_token_invalid_response");
  82. expect(f.request.mock.calls.some(([, init]) => init.method === "POST")).toBe(false);
  83. });
  84. it("团队跳过不可用同名 Key,创建后严格校验;个人创建无需返回同名", async () => {
  85. const f = fixture({ keys: [{ ...teamKey, apiKey: "" }], created: teamKey });
  86. await expect(f.client.resolve({ ...scope, team })).resolves.toMatchObject({ apiKeyId: "key" });
  87. const personal = fixture({ created: { apiKey: "personal-key", name: "server-name" } });
  88. await expect(personal.client.resolve(scope)).resolves.toMatchObject({
  89. apiKeyId: "personal-key",
  90. });
  91. });
  92. it("桌面跳过空组织 ID 和带空白的团队项目类型", async () => {
  93. const f = fixture({
  94. keys: [personalKey],
  95. organizations: [
  96. { organizationId: "", organizationName: "默认机构", projects: [{ projectId: "bad" }] },
  97. {
  98. organizationId: "org",
  99. projects: [
  100. { projectId: "team", projectName: "默认项目", projectType: " 2 " },
  101. { projectId: "personal", projectType: 1 },
  102. ],
  103. },
  104. ],
  105. });
  106. await expect(f.client.resolve(scope)).resolves.toMatchObject({
  107. organizationId: "org",
  108. projectId: "personal",
  109. });
  110. });
  111. it("团队归属比较保留 ID 去空白行为", async () => {
  112. const f = fixture({
  113. keys: [teamKey],
  114. organizations: [{ organizationId: " org ", projects: [{ projectId: " project " }] }],
  115. });
  116. await expect(f.client.resolve({ ...scope, team })).resolves.toMatchObject(team);
  117. });
  118. });
  119. it("个人项目选择策略隔离内存和持久化 ID,重启后各自复用", async () => {
  120. const f = fixture({
  121. keys: [personalKey],
  122. organizations: [
  123. {
  124. organizationId: "org",
  125. projects: [
  126. { projectId: "team", projectName: "默认项目", projectType: 2 },
  127. { projectId: "personal", projectType: 1 },
  128. ],
  129. },
  130. ],
  131. });
  132. const values = new Map<string, string>();
  133. const locationStore = {
  134. load: async (key: string) => values.get(key) ?? null,
  135. save: async (key: string, value: string) => {
  136. values.set(key, value);
  137. },
  138. delete: async (key: string) => {
  139. values.delete(key);
  140. },
  141. };
  142. const client = new ProjectAccessTokenClient({ request: f.request, locationStore });
  143. await expect(client.resolve(scope)).resolves.toMatchObject({ projectId: "personal" });
  144. await expect(
  145. client.resolve({ ...scope, personalProjectSelection: "default" }),
  146. ).resolves.toMatchObject({ projectId: "team" });
  147. expect(values.size).toBe(2);
  148. f.request.mockClear();
  149. const restarted = new ProjectAccessTokenClient({ request: f.request, locationStore });
  150. await expect(restarted.resolve(scope)).resolves.toMatchObject({ projectId: "personal" });
  151. await expect(
  152. restarted.resolve({ ...scope, personalProjectSelection: "default" }),
  153. ).resolves.toMatchObject({ projectId: "team" });
  154. expect(f.request.mock.calls.every(([url]) => url.endsWith("/access_tokens"))).toBe(true);
  155. expect(f.request).toHaveBeenCalledTimes(2);
  156. });