oauthCompletionRace.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import { BIGMODEL_PROVIDER_ID, type OAuthTokenSet } from "@zcode/shared";
  3. import { OAuthService } from "#src/oauth/oauthService.js";
  4. import { parseOAuthLoginAttribution } from "#src/oauth/callbackAttribution.js";
  5. function deferred<T>() {
  6. let resolve!: (value: T) => void;
  7. let reject!: (reason: Error) => void;
  8. const promise = new Promise<T>((yes, no) => {
  9. resolve = yes;
  10. reject = no;
  11. });
  12. return { promise, resolve, reject };
  13. }
  14. const services: OAuthService[] = [];
  15. afterEach(async () => {
  16. await Promise.all(services.splice(0).map((s) => s.cancelPending()));
  17. });
  18. async function setup() {
  19. let now = 2_000_000_000_000;
  20. const credentials = new Map<string, string>();
  21. const exchange = deferred<OAuthTokenSet>();
  22. const normalize = deferred<OAuthTokenSet>();
  23. const pollResponse = deferred<Response>();
  24. const parse = vi.fn((url: string) => {
  25. const params = new URL(url).searchParams;
  26. return {
  27. code: params.get("code")!,
  28. state: params.get("state")!,
  29. attribution: parseOAuthLoginAttribution(params),
  30. };
  31. });
  32. const exchangeToken = vi.fn(() => exchange.promise);
  33. const normalizePolledTokenSet = vi.fn(() => normalize.promise);
  34. const request = vi.fn<typeof fetch>(async (url) =>
  35. String(url).endsWith("/init")
  36. ? Response.json({
  37. code: 0,
  38. data: {
  39. authorize_url: "https://example.com/authorize?state=race-state&channel_id=launch",
  40. expires_at: 2_000_000_300,
  41. flow_id: "race",
  42. poll_interval_sec: 1,
  43. },
  44. })
  45. : pollResponse.promise,
  46. );
  47. const save = vi.fn(async (key: string, value: string) => {
  48. credentials.set(key, value);
  49. });
  50. const service = new OAuthService(
  51. {
  52. load: async (key) => credentials.get(key) ?? null,
  53. save,
  54. delete: async (key) => {
  55. credentials.delete(key);
  56. },
  57. },
  58. {
  59. now: () => now,
  60. apiClient: { request },
  61. adapters: [
  62. {
  63. providerId: BIGMODEL_PROVIDER_ID,
  64. meta: { id: BIGMODEL_PROVIDER_ID, displayName: "BigModel", enabled: true, order: 1 },
  65. redirectUri: "zcode://oauth/callback",
  66. buildAuthorizeUrl: () => "",
  67. parseCallbackParams: parse,
  68. exchangeToken,
  69. normalizePolledTokenSet,
  70. normalizeError: (e) => (e instanceof Error ? e : new Error(String(e))),
  71. },
  72. ],
  73. },
  74. );
  75. services.push(service);
  76. const started = await service.startOAuthWithPolling(BIGMODEL_PROVIDER_ID);
  77. expect(new URL(started.authorizeUrl).searchParams.get("channel_id")).toBe("launch");
  78. const callback =
  79. "zcode://oauth/callback?state=race-state&code=code&channel_id=desktop&utm_source=site&utm_campaign=launch";
  80. const ready = () =>
  81. pollResponse.resolve(
  82. Response.json({
  83. code: 0,
  84. data: {
  85. status: "ready",
  86. token: "poll-jwt",
  87. user: { user_id: "user", name: "User" },
  88. bigmodel: { access_token: "poll-token" },
  89. },
  90. }),
  91. );
  92. return {
  93. service,
  94. advanceTime: (milliseconds: number) => {
  95. now += milliseconds;
  96. },
  97. credentials,
  98. save,
  99. exchange,
  100. normalize,
  101. pollResponse,
  102. parse,
  103. exchangeToken,
  104. normalizePolledTokenSet,
  105. callback,
  106. ready,
  107. };
  108. }
  109. const attribution = JSON.stringify({
  110. channel_id: "desktop",
  111. utm_source: "site",
  112. utm_campaign: "launch",
  113. });
  114. describe("OAuth completion arbitration", () => {
  115. it.each(["callback", "poll"] as const)(
  116. "%s first succeeds: skips the second exchange but preserves attribution",
  117. async (first) => {
  118. const f = await setup();
  119. const firstCall =
  120. first === "callback" ? f.service.handleCallback(f.callback) : f.service.pollPendingOAuth();
  121. f.ready();
  122. await vi.waitFor(() =>
  123. expect(
  124. first === "callback" ? f.exchangeToken : f.normalizePolledTokenSet,
  125. ).toHaveBeenCalledOnce(),
  126. );
  127. const secondCall =
  128. first === "callback" ? f.service.pollPendingOAuth() : f.service.handleCallback(f.callback);
  129. await new Promise((resolve) => setImmediate(resolve));
  130. expect(first === "callback" ? f.normalizePolledTokenSet : f.parse).not.toHaveBeenCalled();
  131. (first === "callback" ? f.exchange : f.normalize).resolve({
  132. accessToken: "winner",
  133. zcodeJwtToken: "winner-jwt",
  134. });
  135. expect(await firstCall).toMatchObject({ kind: "session" });
  136. const secondResult = await secondCall;
  137. expect(secondResult?.kind).not.toBe("session");
  138. expect(f.credentials.get("oauth:bigmodel:access_token")).toBe("winner");
  139. expect(f.credentials.get("oauth:login_attribution")).toBe(attribution);
  140. expect(f.save.mock.calls.filter(([key]) => key === "oauth:active_provider")).toHaveLength(1);
  141. },
  142. );
  143. it.each(["callback", "poll"] as const)(
  144. "%s first fails: queued alternative succeeds without propagating failure",
  145. async (first) => {
  146. const f = await setup();
  147. const firstCall =
  148. first === "callback" ? f.service.handleCallback(f.callback) : f.service.pollPendingOAuth();
  149. f.ready();
  150. await vi.waitFor(() =>
  151. expect(
  152. first === "callback" ? f.exchangeToken : f.normalizePolledTokenSet,
  153. ).toHaveBeenCalledOnce(),
  154. );
  155. const secondCall =
  156. first === "callback" ? f.service.pollPendingOAuth() : f.service.handleCallback(f.callback);
  157. await new Promise((resolve) => setImmediate(resolve));
  158. (first === "callback" ? f.exchange : f.normalize).reject(new Error("first route failed"));
  159. (first === "callback" ? f.normalize : f.exchange).resolve({
  160. accessToken: "fallback",
  161. zcodeJwtToken: "fallback-jwt",
  162. });
  163. const results = await Promise.all([firstCall, secondCall]);
  164. expect(results.filter((r) => r?.kind === "session")).toHaveLength(1);
  165. expect(f.credentials.get("oauth:bigmodel:access_token")).toBe("fallback");
  166. expect(f.credentials.get("oauth:login_attribution")).toBe(attribution);
  167. },
  168. );
  169. it("preserves attribution from a late callback without parsing its code", async () => {
  170. const f = await setup();
  171. f.ready();
  172. f.normalize.resolve({ accessToken: "poll", zcodeJwtToken: "jwt" });
  173. await f.service.pollPendingOAuth();
  174. expect(await f.service.handleCallback(f.callback)).toMatchObject({ kind: "duplicate" });
  175. expect(f.parse).not.toHaveBeenCalled();
  176. expect(f.credentials.get("oauth:login_attribution")).toBe(attribution);
  177. await expect(
  178. f.service.handleCallback(f.callback.replace("race-state", "wrong-state")),
  179. ).rejects.toThrow();
  180. expect(f.credentials.get("oauth:login_attribution")).toBe(attribution);
  181. });
  182. it.each(["callback", "poll"] as const)(
  183. "%s first and both paths fail: reports failure without credentials",
  184. async (first) => {
  185. const f = await setup();
  186. const a =
  187. first === "callback" ? f.service.handleCallback(f.callback) : f.service.pollPendingOAuth();
  188. f.ready();
  189. await vi.waitFor(() =>
  190. expect(
  191. first === "callback" ? f.exchangeToken : f.normalizePolledTokenSet,
  192. ).toHaveBeenCalledOnce(),
  193. );
  194. const b =
  195. first === "callback" ? f.service.pollPendingOAuth() : f.service.handleCallback(f.callback);
  196. const results = Promise.allSettled([a, b]);
  197. await new Promise((resolve) => setImmediate(resolve));
  198. const firstError = new Error("first failed");
  199. const secondError = new Error("second failed");
  200. (first === "callback" ? f.exchange : f.normalize).reject(firstError);
  201. await vi.waitFor(() =>
  202. expect(
  203. first === "callback" ? f.normalizePolledTokenSet : f.exchangeToken,
  204. ).toHaveBeenCalledOnce(),
  205. );
  206. (first === "callback" ? f.normalize : f.exchange).reject(secondError);
  207. expect(await results).toEqual([
  208. { status: "rejected", reason: firstError },
  209. { status: "rejected", reason: secondError },
  210. ]);
  211. expect(f.credentials.has("oauth:active_provider")).toBe(false);
  212. expect(await f.service.pollPendingOAuth()).toBeNull();
  213. },
  214. );
  215. it("cancellation skips a queued callback including its attribution", async () => {
  216. const f = await setup();
  217. const poll = f.service.pollPendingOAuth();
  218. f.ready();
  219. await vi.waitFor(() => expect(f.normalizePolledTokenSet).toHaveBeenCalledOnce());
  220. const callback = f.service.handleCallback(f.callback);
  221. await f.service.cancelPending();
  222. f.normalize.resolve({ accessToken: "cancelled" });
  223. expect(await poll).toBeNull();
  224. expect(await callback).toBeNull();
  225. expect(f.credentials.size).toBe(0);
  226. expect(f.parse).not.toHaveBeenCalled();
  227. });
  228. it("a stale HTTP 401 cannot clear a replacement flow", async () => {
  229. const f = await setup();
  230. const oldPoll = f.service.pollPendingOAuth();
  231. await f.service.startOAuthWithPolling(BIGMODEL_PROVIDER_ID);
  232. f.pollResponse.resolve(Response.json({ code: 401 }, { status: 401 }));
  233. expect(await oldPoll).toBeNull();
  234. f.exchange.resolve({ accessToken: "new-flow" });
  235. expect(await f.service.handleCallback(f.callback)).toMatchObject({ kind: "session" });
  236. expect(f.credentials.get("oauth:bigmodel:access_token")).toBe("new-flow");
  237. });
  238. it("ignores an invalid polling result when the earlier callback succeeds", async () => {
  239. const f = await setup();
  240. const callback = f.service.handleCallback(f.callback);
  241. await vi.waitFor(() => expect(f.exchangeToken).toHaveBeenCalledOnce());
  242. const poll = f.service.pollPendingOAuth();
  243. f.pollResponse.resolve(Response.json({ code: 0, data: { status: "invalid" } }));
  244. await new Promise((resolve) => setImmediate(resolve));
  245. f.exchange.resolve({ accessToken: "winner" });
  246. expect(await callback).toMatchObject({ kind: "session" });
  247. expect(await poll).toMatchObject({ kind: "duplicate" });
  248. expect(f.normalizePolledTokenSet).not.toHaveBeenCalled();
  249. });
  250. it("does not accept attribution after a completed flow is cancelled", async () => {
  251. const f = await setup();
  252. f.ready();
  253. f.normalize.resolve({ accessToken: "poll" });
  254. await f.service.pollPendingOAuth();
  255. await f.service.cancelPending();
  256. await expect(f.service.handleCallback(f.callback)).rejects.toThrow("OAuth state");
  257. expect(f.credentials.has("oauth:login_attribution")).toBe(false);
  258. });
  259. });
  260. it.each(["pending", "completed"])(
  261. "keeps %s callbacks admitted before the grace deadline",
  262. async (phase) => {
  263. const f = await setup();
  264. const gate = deferred<void>();
  265. f.save.mockImplementation(async (key, value) => {
  266. if (key === "oauth:login_attribution") await gate.promise;
  267. f.credentials.set(key, value);
  268. });
  269. const poll = f.service.pollPendingOAuth();
  270. f.ready();
  271. await vi.waitFor(() => expect(f.normalizePolledTokenSet).toHaveBeenCalledOnce());
  272. if (phase === "completed") {
  273. f.normalize.resolve({ accessToken: "winner" });
  274. await poll;
  275. }
  276. const first = f.service.handleCallback(f.callback);
  277. const second = f.service.handleCallback(
  278. f.callback.replace("utm_campaign=launch", "utm_campaign=queued"),
  279. );
  280. f.normalize.resolve({ accessToken: "winner" });
  281. await poll;
  282. await vi.waitFor(() =>
  283. expect(f.save.mock.calls.some(([key]) => key === "oauth:login_attribution")).toBe(true),
  284. );
  285. f.advanceTime(30_001);
  286. gate.resolve();
  287. expect(await first).toMatchObject({ kind: "duplicate" });
  288. expect(await second).toMatchObject({ kind: "duplicate" });
  289. expect(JSON.parse(f.credentials.get("oauth:login_attribution")!).utm_campaign).toBe("queued");
  290. expect(f.parse).not.toHaveBeenCalled();
  291. await expect(f.service.handleCallback(f.callback)).rejects.toThrow("OAuth state");
  292. },
  293. );