projectAccessTokenKeyContract.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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([
  36. { ...teamKey, name: "other" },
  37. { ...teamKey, keyType: 1 },
  38. { ...teamKey, keyType: undefined },
  39. { ...teamKey, apiKey: " " },
  40. ])("拒绝错误团队创建结果 %j,不换证", async (created) => {
  41. const f = fixture({ created });
  42. await expect(f.client.resolve({ ...scope, team })).rejects.toThrow(
  43. "project_token_invalid_response",
  44. );
  45. expect(f.request.mock.calls.some(([url]) => url.endsWith("/access_tokens"))).toBe(false);
  46. });
  47. it.each([false, true])("无关缺 ID 条目不影响已有专用 Key,团队=%s", async (isTeam) => {
  48. const f = fixture({
  49. keys: [{ name: "other", apiKey: "" }, { name: "another" }, isTeam ? teamKey : personalKey],
  50. });
  51. await expect(
  52. f.client.resolve({ ...scope, ...(isTeam ? { team } : {}) }),
  53. ).resolves.toMatchObject({ apiKeyId: "key" });
  54. expect(
  55. f.request.mock.calls.filter(
  56. ([url, init]) => url.endsWith("/api_keys") && init.method === "POST",
  57. ),
  58. ).toHaveLength(0);
  59. });
  60. it("个人同名 Key 缺 ID 时失败,不重复创建", async () => {
  61. const f = fixture({ keys: [{ name: "zcode-api-key", apiKey: "" }], created: personalKey });
  62. await expect(f.client.resolve(scope)).rejects.toThrow("project_token_invalid_response");
  63. expect(f.request.mock.calls.some(([, init]) => init.method === "POST")).toBe(false);
  64. });
  65. it("团队跳过不可用同名 Key,创建后严格校验;个人创建无需返回同名", async () => {
  66. const f = fixture({ keys: [{ ...teamKey, apiKey: "" }], created: teamKey });
  67. await expect(f.client.resolve({ ...scope, team })).resolves.toMatchObject({ apiKeyId: "key" });
  68. const personal = fixture({ created: { apiKey: "personal-key", name: "server-name" } });
  69. await expect(personal.client.resolve(scope)).resolves.toMatchObject({
  70. apiKeyId: "personal-key",
  71. });
  72. });
  73. it("桌面跳过空组织 ID 和带空白的团队项目类型", async () => {
  74. const f = fixture({
  75. keys: [personalKey],
  76. organizations: [
  77. { organizationId: "", organizationName: "默认机构", projects: [{ projectId: "bad" }] },
  78. {
  79. organizationId: "org",
  80. projects: [
  81. { projectId: "team", projectName: "默认项目", projectType: " 2 " },
  82. { projectId: "personal", projectType: 1 },
  83. ],
  84. },
  85. ],
  86. });
  87. await expect(f.client.resolve(scope)).resolves.toMatchObject({
  88. organizationId: "org",
  89. projectId: "personal",
  90. });
  91. });
  92. it("团队归属比较保留 ID 去空白行为", async () => {
  93. const f = fixture({
  94. keys: [teamKey],
  95. organizations: [{ organizationId: " org ", projects: [{ projectId: " project " }] }],
  96. });
  97. await expect(f.client.resolve({ ...scope, team })).resolves.toMatchObject(team);
  98. });
  99. });
  100. it("个人项目选择策略隔离内存和持久化 ID,重启后各自复用", async () => {
  101. const f = fixture({
  102. keys: [personalKey],
  103. organizations: [
  104. {
  105. organizationId: "org",
  106. projects: [
  107. { projectId: "team", projectName: "默认项目", projectType: 2 },
  108. { projectId: "personal", projectType: 1 },
  109. ],
  110. },
  111. ],
  112. });
  113. const values = new Map<string, string>();
  114. const locationStore = {
  115. load: async (key: string) => values.get(key) ?? null,
  116. save: async (key: string, value: string) => {
  117. values.set(key, value);
  118. },
  119. delete: async (key: string) => {
  120. values.delete(key);
  121. },
  122. };
  123. const client = new ProjectAccessTokenClient({ request: f.request, locationStore });
  124. await expect(client.resolve(scope)).resolves.toMatchObject({ projectId: "personal" });
  125. await expect(
  126. client.resolve({ ...scope, personalProjectSelection: "default" }),
  127. ).resolves.toMatchObject({ projectId: "team" });
  128. expect(values.size).toBe(2);
  129. f.request.mockClear();
  130. const restarted = new ProjectAccessTokenClient({ request: f.request, locationStore });
  131. await expect(restarted.resolve(scope)).resolves.toMatchObject({ projectId: "personal" });
  132. await expect(
  133. restarted.resolve({ ...scope, personalProjectSelection: "default" }),
  134. ).resolves.toMatchObject({ projectId: "team" });
  135. expect(f.request.mock.calls.every(([url]) => url.endsWith("/access_tokens"))).toBe(true);
  136. expect(f.request).toHaveBeenCalledTimes(2);
  137. });