standalone-project-token.test.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import { ProviderConfig, ProviderConfigMap, ZhipuAccountAccessConfig } from "@zcode/provider";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. createStandaloneProviderRuntimeHeadersPort,
  5. readStandaloneAccountProviderConfigSnapshot,
  6. standaloneAccountAuthSourceCredentialKey,
  7. standaloneAccountIdentityCredentialKey,
  8. standaloneAccountProviderCredentialKey,
  9. } from "../src/app/standalone-account-provider-runtime.js";
  10. function fixture() {
  11. const providerId = "account:bigmodel-individual-coding-plan";
  12. const identityKey = standaloneAccountIdentityCredentialKey(providerId);
  13. const sourceKey = standaloneAccountAuthSourceCredentialKey(providerId);
  14. const legacyKey = standaloneAccountProviderCredentialKey({
  15. providerId,
  16. accountIdentity: "account-a",
  17. });
  18. const loginKey = "oauth:bigmodel:access_token";
  19. const values = new Map([
  20. [identityKey, "account-a"],
  21. [sourceKey, "oauth"],
  22. [legacyKey, "legacy-secret"],
  23. [loginKey, "login-a"],
  24. ]);
  25. const store = {
  26. load: async (key: string) => values.get(key) ?? null,
  27. loadMany: async (keys: readonly string[]) =>
  28. Object.fromEntries(keys.map((key) => [key, values.get(key) ?? null])),
  29. save: vi.fn(async (key: string, value: string) => {
  30. values.set(key, value);
  31. }),
  32. delete: async (key: string) => {
  33. values.delete(key);
  34. },
  35. };
  36. const resolver = {
  37. resolve: vi.fn(async () => "short-token"),
  38. resolveMaterial: vi.fn(async () => ({
  39. token: "short-token",
  40. apiKeyId: "real-key-id",
  41. organizationId: "org",
  42. projectId: "proj",
  43. })),
  44. clear: vi.fn(),
  45. };
  46. const port = createStandaloneProviderRuntimeHeadersPort(store, {}, resolver);
  47. const request = (
  48. recovery: { expectedAccountScope?: string; rejectedProjectTokenFingerprint?: string } = {},
  49. ) =>
  50. port.refreshBeforeModelRequest({
  51. ...recovery,
  52. providerId,
  53. modelId: "glm",
  54. accountAccess: {
  55. type: "zhipu-account",
  56. accountType: "bigmodel",
  57. entitled: true,
  58. mode: "individual-coding-plan",
  59. },
  60. reason: "model-request",
  61. sessionId: "session" as never,
  62. traceContext: { traceId: "trace" } as never,
  63. });
  64. return {
  65. values,
  66. store,
  67. resolver,
  68. port,
  69. request,
  70. providerId,
  71. loginKey,
  72. identityKey,
  73. sourceKey,
  74. legacyKey,
  75. };
  76. }
  77. describe("Standalone Project Token", () => {
  78. it("401 恢复携带失败指纹;重新登录和手工模式切换后拒绝旧作用域", async () => {
  79. const f = fixture();
  80. const initial = await f.request();
  81. const expectedAccountScope = initial.requestAuth?.accountScope;
  82. expect(expectedAccountScope).toMatch(/^[a-f0-9]{64}$/);
  83. const recovery = { expectedAccountScope, rejectedProjectTokenFingerprint: "b".repeat(64) };
  84. await f.request(recovery);
  85. expect(f.resolver.resolveMaterial).toHaveBeenLastCalledWith(
  86. expect.objectContaining({
  87. rejectedProjectTokenFingerprint: recovery.rejectedProjectTokenFingerprint,
  88. }),
  89. { signal: undefined },
  90. );
  91. f.values.set(f.loginKey, "login-b");
  92. await expect(f.request(recovery)).rejects.toThrow("scope_invalidated");
  93. f.values.set(f.sourceKey, "manual");
  94. await expect(f.request(recovery)).rejects.toThrow("scope_invalidated");
  95. expect(f.resolver.resolveMaterial).toHaveBeenCalledTimes(2);
  96. });
  97. it("请求时取得 Token,旧 Key 不参与,Token 不落盘", async () => {
  98. const f = fixture();
  99. await expect(f.request()).resolves.toMatchObject({
  100. requestAuth: { apiKey: "short-token", apiKeyId: "real-key-id" },
  101. });
  102. expect(f.resolver.resolveMaterial).toHaveBeenCalledWith(
  103. {
  104. family: "bigmodel",
  105. accessToken: "login-a",
  106. accountIdentity: "account-a",
  107. rejectedProjectTokenFingerprint: undefined,
  108. trace: { traceId: "trace" },
  109. },
  110. { signal: undefined },
  111. );
  112. expect(JSON.stringify([...f.values])).not.toContain("short-token");
  113. expect(f.values.get(f.legacyKey)).toBe("legacy-secret");
  114. });
  115. it.each(["missing", "corrupt"])("旧 OAuth 用户无来源标记且旧 Key=%s 时可恢复", async (legacy) => {
  116. const f = fixture();
  117. f.values.delete(f.sourceKey);
  118. f.values.delete(f.legacyKey);
  119. const loadMany = vi.fn(async (keys: readonly string[]) => {
  120. if (legacy === "corrupt" && keys.includes(f.legacyKey))
  121. throw new Error("legacy ciphertext corrupt");
  122. return f.store.loadMany(keys);
  123. });
  124. const snapshot = await readStandaloneAccountProviderConfigSnapshot(
  125. { loadMany },
  126. {},
  127. {
  128. revision: "builtin",
  129. providers: new ProviderConfigMap([
  130. [
  131. f.providerId,
  132. new ProviderConfig({
  133. access: new ZhipuAccountAccessConfig({
  134. accountType: "bigmodel",
  135. mode: "individual-coding-plan",
  136. }),
  137. builtinModelIds: ["glm"],
  138. }),
  139. ],
  140. ]),
  141. },
  142. );
  143. expect(snapshot.providers.get(f.providerId)?.access).toMatchObject({ entitled: true });
  144. expect(loadMany.mock.calls.flatMap(([keys]) => keys)).not.toContain(f.legacyKey);
  145. await expect(f.request()).resolves.toMatchObject({
  146. requestAuth: { apiKey: "short-token", apiKeyId: "real-key-id" },
  147. });
  148. expect(f.values.get(f.sourceKey)).toBe("oauth");
  149. });
  150. it("明确手工模式不读取损坏的 OAuth", async () => {
  151. const f = fixture();
  152. f.values.set(f.sourceKey, "manual");
  153. const originalLoad = f.store.load;
  154. f.store.load = async (key) => {
  155. if (key === f.loginKey) throw new Error("unused OAuth ciphertext corrupt");
  156. return originalLoad(key);
  157. };
  158. await expect(f.request()).resolves.toMatchObject({ requestAuth: { apiKey: "legacy-secret" } });
  159. const snapshot = await readStandaloneAccountProviderConfigSnapshot(
  160. {
  161. loadMany: async (keys) => {
  162. if (keys.includes(f.loginKey)) throw new Error("unused OAuth ciphertext corrupt");
  163. return f.store.loadMany(keys);
  164. },
  165. },
  166. {},
  167. {
  168. revision: "builtin",
  169. providers: new ProviderConfigMap([
  170. [
  171. f.providerId,
  172. new ProviderConfig({
  173. access: new ZhipuAccountAccessConfig({
  174. accountType: "bigmodel",
  175. mode: "individual-coding-plan",
  176. }),
  177. builtinModelIds: ["glm"],
  178. }),
  179. ],
  180. ]),
  181. },
  182. );
  183. expect(snapshot.providers.get(f.providerId)?.access).toMatchObject({ entitled: true });
  184. });
  185. it("缺失 OAuth 不回退到旧 Key", async () => {
  186. const f = fixture();
  187. f.values.delete(f.loginKey);
  188. await expect(f.request()).rejects.toThrow("project_token_login_required");
  189. expect(f.resolver.resolveMaterial).not.toHaveBeenCalled();
  190. });
  191. it("退出后丢弃迟到 Token 并清除内存缓存", async () => {
  192. const f = fixture();
  193. let release!: (value: {
  194. token: string;
  195. apiKeyId: string;
  196. organizationId: string;
  197. projectId: string;
  198. }) => void;
  199. f.resolver.resolveMaterial.mockImplementation(
  200. () =>
  201. new Promise((resolve) => {
  202. release = resolve;
  203. }),
  204. );
  205. const pending = f.request();
  206. const rejected = expect(pending).rejects.toThrow("project_token_scope_invalidated");
  207. await vi.waitFor(() => expect(f.resolver.resolveMaterial).toHaveBeenCalled());
  208. f.values.delete(f.loginKey);
  209. await f.port.invalidateChangedCredentials();
  210. release({ token: "late-token", apiKeyId: "key-id", organizationId: "org", projectId: "proj" });
  211. await rejected;
  212. expect(f.resolver.clear).toHaveBeenCalled();
  213. });
  214. it("旧记录无来源标记且无登录态时,不猜测为手工 Key", async () => {
  215. const f = fixture();
  216. f.values.delete(f.sourceKey);
  217. f.values.delete(f.loginKey);
  218. await expect(f.request()).rejects.toThrow("project_token_login_required");
  219. expect(f.resolver.resolveMaterial).not.toHaveBeenCalled();
  220. });
  221. it("用户手工 Key 保留独立请求方式", async () => {
  222. const f = fixture();
  223. f.values.set(f.sourceKey, "manual");
  224. await expect(f.request()).resolves.toMatchObject({
  225. requestAuth: { apiKey: "legacy-secret" },
  226. });
  227. expect(f.resolver.resolveMaterial).not.toHaveBeenCalled();
  228. });
  229. });