projectAccessTokenCache.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. ProjectAccessTokenCache,
  4. ProjectAccessTokenTransientError,
  5. projectAccessTokenFingerprint,
  6. type ProjectAccessTokenScope,
  7. } from "../src/project-access-token.js";
  8. const scope: ProjectAccessTokenScope = {
  9. origin: "https://example.invalid",
  10. family: "bigmodel",
  11. accountId: "account",
  12. organizationId: "org",
  13. projectId: "project",
  14. apiKeyId: "key",
  15. usageScene: 1,
  16. loginGeneration: "session-1",
  17. };
  18. const START = 1_800_000_000_000;
  19. function token(value = "token", expiresIn = 600, issuedAt = START) {
  20. return {
  21. code: 200,
  22. data: {
  23. enable: true,
  24. accessToken: value,
  25. tokenType: "Bearer",
  26. expiresIn,
  27. expiresAt: issuedAt / 1000 + expiresIn,
  28. },
  29. };
  30. }
  31. function deferred<T>() {
  32. let resolve!: (value: T) => void;
  33. let reject!: (error: Error) => void;
  34. const promise = new Promise<T>((yes, no) => {
  35. resolve = yes;
  36. reject = no;
  37. });
  38. return { promise, resolve, reject };
  39. }
  40. describe("ProjectAccessTokenCache", () => {
  41. it.each([0, 200, "0", "200"])("签发成功码 %s 与管理接口一致", async (code) => {
  42. const cache = new ProjectAccessTokenCache({ now: () => START });
  43. await expect(cache.resolve(scope, async () => ({ ...token(), code }))).resolves.toMatchObject({
  44. token: "token",
  45. });
  46. });
  47. it("提前刷新临时失败时并发共享有效 PAT,5 秒退避后恢复,绝不延长 expiresAt", async () => {
  48. let now = START;
  49. const cache = new ProjectAccessTokenCache({ now: () => now, random: () => 0 });
  50. await cache.resolve(scope, async () => token("old"));
  51. now += 480_000;
  52. const issue = vi.fn(async () => {
  53. throw new ProjectAccessTokenTransientError();
  54. });
  55. const results = await Promise.all([cache.resolve(scope, issue), cache.resolve(scope, issue)]);
  56. expect(results).toEqual([
  57. { enabled: true, token: "old", expiresAt: START + 600_000 },
  58. { enabled: true, token: "old", expiresAt: START + 600_000 },
  59. ]);
  60. now += 4_999;
  61. await expect(cache.resolve(scope, issue)).resolves.toMatchObject({ token: "old" });
  62. expect(issue).toHaveBeenCalledTimes(1);
  63. now++;
  64. await expect(cache.resolve(scope, issue)).resolves.toMatchObject({ token: "old" });
  65. expect(issue).toHaveBeenCalledTimes(2);
  66. now = START + 600_000;
  67. await expect(cache.resolve(scope, issue)).rejects.toThrow("project_token_transient_failure");
  68. await expect(cache.resolve(scope, async () => token("new", 600, now))).resolves.toMatchObject({
  69. token: "new",
  70. });
  71. });
  72. it.each(["clear", "rejected", "expired"])("在途刷新失败时 %s 不能降级到旧 PAT", async (event) => {
  73. let now = START;
  74. const cache = new ProjectAccessTokenCache({ now: () => now, random: () => 0 });
  75. await cache.resolve(scope, async () => token("old"));
  76. now += 480_000;
  77. const issued = deferred<unknown>();
  78. const first = cache.resolve(scope, () => issued.promise);
  79. const check = expect(first).rejects.toThrow();
  80. await Promise.resolve();
  81. let second: Promise<unknown> | undefined;
  82. if (event === "clear") cache.clear();
  83. if (event === "expired") now = START + 600_000;
  84. if (event === "rejected") {
  85. second = expect(
  86. cache.resolve(scope, () => issued.promise, await projectAccessTokenFingerprint("old")),
  87. ).rejects.toThrow();
  88. }
  89. issued.reject(new ProjectAccessTokenTransientError());
  90. await check;
  91. await second;
  92. });
  93. it("401 按失败 PAT 指纹失效,并发合并且迟到的旧 401 不清除新 PAT", async () => {
  94. const cache = new ProjectAccessTokenCache({ now: () => START });
  95. await cache.resolve(scope, async () => token("old-pat"));
  96. const fingerprint = await projectAccessTokenFingerprint("old-pat");
  97. const issue = vi.fn(async () => token("new-pat"));
  98. const results = await Promise.all([
  99. cache.resolve(scope, issue, fingerprint),
  100. cache.resolve(scope, issue, fingerprint),
  101. ]);
  102. expect(results.every((value) => value.enabled && value.token === "new-pat")).toBe(true);
  103. await cache.resolve(scope, issue, fingerprint);
  104. expect(issue).toHaveBeenCalledTimes(1);
  105. });
  106. it("合并并发签发,在提前刷新窗口之前复用进程内凭据", async () => {
  107. let now = START;
  108. const pending = deferred<unknown>();
  109. const issue = vi.fn(() => pending.promise);
  110. const cache = new ProjectAccessTokenCache({
  111. now: () => now,
  112. random: () => 0,
  113. });
  114. const first = cache.resolve(scope, issue);
  115. const second = cache.resolve(scope, issue);
  116. pending.resolve(token());
  117. expect(await first).toEqual({
  118. enabled: true,
  119. token: "token",
  120. expiresAt: START + 600_000,
  121. });
  122. expect(await second).toEqual(await first);
  123. now += 479_999;
  124. expect(await cache.resolve(scope, issue)).toEqual(await first);
  125. expect(issue).toHaveBeenCalledTimes(1);
  126. });
  127. it("抖动只提前刷新,并在每次请求前检查 TTL", async () => {
  128. let now = START;
  129. const issue = vi.fn(async () => token(String(now), 600, now));
  130. const cache = new ProjectAccessTokenCache({
  131. now: () => now,
  132. random: () => 1,
  133. });
  134. await cache.resolve(scope, issue);
  135. now += 419_999;
  136. await cache.resolve(scope, issue);
  137. expect(issue).toHaveBeenCalledTimes(1);
  138. now++;
  139. await cache.resolve(scope, issue);
  140. expect(issue).toHaveBeenCalledTimes(2);
  141. now += 700_000;
  142. expect(await cache.resolve(scope, issue)).toMatchObject({
  143. token: String(now),
  144. });
  145. expect(issue).toHaveBeenCalledTimes(3);
  146. });
  147. it.each([
  148. "origin",
  149. "family",
  150. "accountId",
  151. "organizationId",
  152. "projectId",
  153. "apiKeyId",
  154. "usageScene",
  155. "loginGeneration",
  156. ] as const)("按 %s 隔离缓存", async (field) => {
  157. const cache = new ProjectAccessTokenCache({ now: () => START });
  158. const issue = vi.fn(async () => token());
  159. await cache.resolve(scope, issue);
  160. const other = {
  161. ...scope,
  162. [field]: field === "usageScene" ? 2 : field === "family" ? "zai" : `other-${scope[field]}`,
  163. };
  164. await cache.resolve(other as ProjectAccessTokenScope, issue);
  165. expect(issue).toHaveBeenCalledTimes(2);
  166. });
  167. it("退出期间的迟到结果不得恢复缓存或返回给旧请求", async () => {
  168. const pending = deferred<unknown>();
  169. const cache = new ProjectAccessTokenCache({ now: () => START });
  170. const old = cache.resolve(scope, () => pending.promise);
  171. const rejected = expect(old).rejects.toMatchObject({
  172. code: "project_token_scope_invalidated",
  173. });
  174. await Promise.resolve();
  175. cache.clear();
  176. const issue = vi.fn(async () => token("new-token"));
  177. await cache.resolve(scope, issue);
  178. pending.resolve(token("old-token"));
  179. await rejected;
  180. expect(await cache.resolve(scope, issue)).toMatchObject({
  181. token: "new-token",
  182. });
  183. expect(issue).toHaveBeenCalledTimes(1);
  184. });
  185. it("签发尚未发出时退出,不再使用旧登录态发送请求", async () => {
  186. const cache = new ProjectAccessTokenCache({ now: () => START });
  187. const issue = vi.fn(async () => token());
  188. const pending = cache.resolve(scope, issue);
  189. cache.clear();
  190. await expect(pending).rejects.toMatchObject({
  191. code: "project_token_scope_invalidated",
  192. });
  193. expect(issue).not.toHaveBeenCalled();
  194. });
  195. it("定点失效不影响另一个账号,失败请求允许重新签发", async () => {
  196. const cache = new ProjectAccessTokenCache({ now: () => START });
  197. const other = { ...scope, accountId: "other" };
  198. const issue = vi.fn(async () => token());
  199. await cache.resolve(scope, issue);
  200. await cache.resolve(other, issue);
  201. cache.invalidate(scope);
  202. await cache.resolve(other, issue);
  203. expect(issue).toHaveBeenCalledTimes(2);
  204. await expect(
  205. cache.resolve(scope, async () => {
  206. throw new Error("network failure");
  207. }),
  208. ).rejects.toThrow("network failure");
  209. await cache.resolve(scope, issue);
  210. expect(issue).toHaveBeenCalledTimes(3);
  211. });
  212. it("仅明确关闭返回 disabled,且不永久缓存关闭开关", async () => {
  213. const cache = new ProjectAccessTokenCache({ now: () => START });
  214. expect(
  215. await cache.resolve(scope, async () => ({
  216. code: 200,
  217. data: { enable: false },
  218. })),
  219. ).toEqual({ enabled: false });
  220. expect(await cache.resolve(scope, async () => token())).toMatchObject({
  221. enabled: true,
  222. });
  223. });
  224. it.each([
  225. {},
  226. { code: 401, data: { enable: false } },
  227. { code: 200, data: {} },
  228. { code: 200, data: { ...token().data, accessToken: "" } },
  229. { code: 200, data: { ...token().data, tokenType: "Basic" } },
  230. { code: 200, data: { ...token().data, expiresIn: -1 } },
  231. { code: 200, data: { ...token().data, expiresAt: START / 1000 } },
  232. ])("拒绝畸形/过期响应,不把失败降级为 disabled:%j", async (response) => {
  233. const cache = new ProjectAccessTokenCache({ now: () => START });
  234. await expect(cache.resolve(scope, async () => response)).rejects.toMatchObject({
  235. code: "project_token_invalid_response",
  236. });
  237. });
  238. it("计入签发网络耗时,expiresIn 不能从收包时重新起算", async () => {
  239. let now = START;
  240. const cache = new ProjectAccessTokenCache({ now: () => now });
  241. await expect(
  242. cache.resolve(scope, async () => {
  243. now += 700_000;
  244. return token();
  245. }),
  246. ).rejects.toMatchObject({ code: "project_token_invalid_response" });
  247. });
  248. it.each(["network", "503", "401", "403", "404", "invalid", "disabled"])(
  249. "未分类异常/业务错误 %s 不视作临时传输故障,不复用旧 PAT,后续可恢复",
  250. async (failure) => {
  251. let now = START;
  252. const cache = new ProjectAccessTokenCache({
  253. now: () => now,
  254. random: () => 0,
  255. });
  256. await cache.resolve(scope, async () => token("old"));
  257. now += 480_000;
  258. const refresh = cache.resolve(scope, async () => {
  259. if (failure === "network") throw new TypeError("fetch failed");
  260. if (failure === "disabled") return { code: 200, data: { enable: false } };
  261. return failure === "invalid" ? {} : { code: Number(failure) };
  262. });
  263. if (failure === "disabled") await expect(refresh).resolves.toEqual({ enabled: false });
  264. else await expect(refresh).rejects.toThrow();
  265. const issue = vi.fn(async () => token("new", 600, now));
  266. await expect(cache.resolve(scope, issue)).resolves.toMatchObject({
  267. token: "new",
  268. });
  269. expect(issue).toHaveBeenCalledOnce();
  270. },
  271. );
  272. it("刷新失败不泄露过期凭据,拒绝认证失败时回退旧 Token", async () => {
  273. let now = START;
  274. const cache = new ProjectAccessTokenCache({ now: () => now });
  275. await cache.resolve(scope, async () => token());
  276. now += 601_000;
  277. await expect(cache.resolve(scope, async () => ({ code: 401 }))).rejects.toMatchObject({
  278. code: "project_token_invalid_response",
  279. });
  280. });
  281. });