-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauthClient.test.ts
More file actions
588 lines (492 loc) · 17.6 KB
/
Copy pathauthClient.test.ts
File metadata and controls
588 lines (492 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import fs from "fs";
import os from "os";
import path from "path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
PORTAL_PROFILE_NAME,
savePortalSession,
upsertProfile,
} from "./config.js";
import { isRateLimited } from "./http.js";
import {
getTokens,
KeychainUnavailableError,
saveTokens,
setBackendForTesting,
type KeychainBackend,
} from "./keychain.js";
import {
createAuthClient,
createPortalClient,
ReauthRequiredError,
tokensFromAuthResponse,
tokensFromRefreshResponse,
} from "./authClient.js";
function fakeBackend(): KeychainBackend {
const store = new Map<string, string>();
return {
get: (account) => store.get(account) ?? null,
set: (account, secret) => {
store.set(account, secret);
},
delete: (account) => store.delete(account),
};
}
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json" },
});
}
interface Call {
url: string;
init: RequestInit;
}
function mockFetch(makers: Array<() => Response>): Call[] {
const calls: Call[] = [];
let i = 0;
vi.stubGlobal(
"fetch",
vi.fn(async (url: string, init: RequestInit = {}) => {
calls.push({ url, init });
const make = makers[Math.min(i, makers.length - 1)];
i++;
return make();
}),
);
return calls;
}
function authHeader(call: Call): string | undefined {
return (call.init.headers as Record<string, string> | undefined)
?.Authorization;
}
const profile = { name: "default", instanceUrl: "https://auth.example.com" };
let configHome: string;
beforeEach(async () => {
configHome = fs.mkdtempSync(path.join(os.tmpdir(), "seamless-http-"));
process.env.XDG_CONFIG_HOME = configHome;
delete process.env.SEAMLESS_REFRESH_TOKEN;
setBackendForTesting(fakeBackend());
upsertProfile({ name: "default", instanceUrl: "https://auth.example.com" });
});
afterEach(() => {
vi.unstubAllGlobals();
setBackendForTesting(null);
fs.rmSync(configHome, { recursive: true, force: true });
delete process.env.XDG_CONFIG_HOME;
delete process.env.SEAMLESS_REFRESH_TOKEN;
});
describe("createAuthClient", () => {
it("throws a reauth error when there is no active profile", async () => {
await expect(
createAuthClient({ profileFlag: "ghost" }),
).rejects.toBeInstanceOf(ReauthRequiredError);
});
it("throws a reauth error when there is no session", async () => {
await expect(createAuthClient()).rejects.toBeInstanceOf(ReauthRequiredError);
});
it("points at the instance login command when a profile has no session", async () => {
await expect(createAuthClient()).rejects.toThrow(
"Run: seamless profile login default.",
);
});
});
describe("createPortalClient", () => {
const portalUrl = "https://portal.example.com";
const portalTarget = { name: PORTAL_PROFILE_NAME, instanceUrl: portalUrl };
beforeEach(() => {
process.env.SEAMLESS_PORTAL_AUTH_URL = portalUrl;
});
afterEach(() => {
delete process.env.SEAMLESS_PORTAL_AUTH_URL;
});
it("throws a reauth error naming seamless login when signed out", async () => {
await expect(createPortalClient()).rejects.toBeInstanceOf(
ReauthRequiredError,
);
await expect(createPortalClient()).rejects.toThrow("Run: seamless login.");
});
// An instance profile with a session must not stand in for a portal account:
// its token is issued by a different host and the control plane would reject it.
it("ignores an instance profile session", async () => {
await saveTokens(profile, { accessToken: "a", refreshToken: "r" });
await expect(createPortalClient()).rejects.toBeInstanceOf(
ReauthRequiredError,
);
});
it("sends the portal session to an absolute control-plane URL", async () => {
savePortalSession({ instanceUrl: portalUrl });
await saveTokens(portalTarget, {
accessToken: "portal-access",
refreshToken: "portal-refresh",
});
const calls = mockFetch([() => json({ applications: [] })]);
const client = await createPortalClient();
await client.get("https://api.seamlessauth.com/applications");
expect(calls[0].url).toBe("https://api.seamlessauth.com/applications");
expect(authHeader(calls[0])).toBe("Bearer portal-access");
});
it("refreshes against the portal auth host, not the control plane", async () => {
savePortalSession({ instanceUrl: portalUrl });
await saveTokens(portalTarget, {
accessToken: "stale",
refreshToken: "portal-refresh",
});
const calls = mockFetch([
() => json({ error: "expired" }, 401),
() => json({ token: "fresh", refreshToken: "rotated" }),
() => json({ applications: [] }),
]);
const client = await createPortalClient();
await client.get("https://api.seamlessauth.com/applications");
expect(calls[1].url).toBe(`${portalUrl}/refresh`);
expect(authHeader(calls[2])).toBe("Bearer fresh");
expect((await getTokens(portalTarget))?.refreshToken).toBe("rotated");
});
});
describe("transparent refresh", () => {
it("refreshes on 401, stores the rotated pair, and retries once", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "old-refresh",
});
const calls = mockFetch([
() => new Response(null, { status: 401 }),
() =>
json({
token: "new-access",
refreshToken: "new-refresh",
ttl: 900,
refreshTtl: 86400,
}),
() => json({ sub: "user-1" }),
]);
const client = await createAuthClient();
const res = await client.get<{ sub: string }>("/whoami");
expect(res.ok).toBe(true);
expect(res.data?.sub).toBe("user-1");
expect(calls).toHaveLength(3);
expect(authHeader(calls[0])).toBe("Bearer old-access");
expect(calls[1].url).toBe("https://auth.example.com/refresh");
expect(authHeader(calls[1])).toBe("Bearer old-refresh");
expect(authHeader(calls[2])).toBe("Bearer new-access");
const stored = await getTokens(profile);
expect(stored?.refreshToken).toBe("new-refresh");
expect(stored?.accessTokenExpiresAt).toBeGreaterThan(Date.now());
});
it("re-sends the request body on the retried call", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "old-refresh",
});
const calls = mockFetch([
() => new Response(null, { status: 401 }),
() => json({ token: "new-access", refreshToken: "new-refresh" }),
() => json({ ok: true }),
]);
const client = await createAuthClient();
await client.post("/things", { name: "widget" });
expect(calls[2].init.body).toBe(JSON.stringify({ name: "widget" }));
expect(authHeader(calls[2])).toBe("Bearer new-access");
});
it("clears the session and demands re-login when refresh is rejected", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "reused-refresh",
});
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ error: "token reuse detected" }, 401),
]);
const client = await createAuthClient();
await expect(client.get("/whoami")).rejects.toBeInstanceOf(
ReauthRequiredError,
);
expect(await getTokens(profile)).toBeNull();
});
it("demands re-login when the refresh response is missing token fields", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "old-refresh",
});
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ message: "no tokens here" }),
]);
const client = await createAuthClient();
await expect(client.get("/whoami")).rejects.toThrow(
/unexpected refresh response/,
);
expect(await getTokens(profile)).toBeNull();
});
it("swallows a KeychainUnavailableError when persisting rotated tokens", async () => {
const store = new Map<string, string>();
const key = `${profile.name}::${profile.instanceUrl}`;
store.set(
key,
JSON.stringify({ accessToken: "old-access", refreshToken: "old-refresh" }),
);
setBackendForTesting({
get: (account) => store.get(account) ?? null,
set: () => {
throw new KeychainUnavailableError();
},
delete: (account) => store.delete(account),
});
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ token: "new-access", refreshToken: "new-refresh" }),
() => json({ sub: "user-1" }),
]);
const client = await createAuthClient();
const res = await client.get("/whoami");
expect(res.ok).toBe(true);
});
it("propagates unexpected errors when persisting rotated tokens", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "old-refresh",
});
const client = await createAuthClient();
setBackendForTesting({
get: () => null,
set: () => {
throw new Error("disk full");
},
delete: () => false,
});
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ token: "new-access", refreshToken: "new-refresh" }),
]);
await expect(client.get("/whoami")).rejects.toThrow("disk full");
});
it("propagates unexpected errors when clearing a rejected session", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "reused-refresh",
});
const client = await createAuthClient();
setBackendForTesting({
get: () => null,
set: () => {},
delete: () => {
throw new Error("keychain locked");
},
});
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ error: "token reuse detected" }, 401),
]);
await expect(client.get("/whoami")).rejects.toThrow("keychain locked");
});
it("swallows a KeychainUnavailableError when clearing a rejected session", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "reused-refresh",
});
const client = await createAuthClient();
setBackendForTesting({
get: () => null,
set: () => {},
delete: () => {
throw new KeychainUnavailableError();
},
});
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ error: "token reuse detected" }, 401),
]);
await expect(client.get("/whoami")).rejects.toBeInstanceOf(
ReauthRequiredError,
);
});
});
describe("error and edge responses", () => {
beforeEach(async () => {
await saveTokens(profile, {
accessToken: "access",
refreshToken: "refresh",
});
});
it("surfaces 429 without attempting a refresh", async () => {
const calls = mockFetch([() => json({ error: "rate limited" }, 429)]);
const client = await createAuthClient();
const res = await client.get("/otp/generate-login-email-otp");
expect(res.status).toBe(429);
expect(isRateLimited(res)).toBe(true);
expect(calls).toHaveLength(1);
});
it("does not crash on an HTML body", async () => {
mockFetch([
() =>
new Response("<html><body>502 Bad Gateway</body></html>", {
status: 502,
headers: { "content-type": "text/html" },
}),
]);
const client = await createAuthClient();
const res = await client.get("/whoami");
expect(res.ok).toBe(false);
expect(res.status).toBe(502);
expect(res.data).toBeNull();
});
it("does not crash on an empty body", async () => {
mockFetch([() => new Response(null, { status: 204 })]);
const client = await createAuthClient();
const res = await client.get("/whoami");
expect(res.ok).toBe(true);
expect(res.data).toBeNull();
});
});
describe("tokensFromAuthResponse", () => {
it("maps the contract fields and computes expiries", () => {
const before = Date.now();
const bundle = tokensFromAuthResponse({
token: "a",
refreshToken: "r",
ttl: 300,
refreshTtl: 3600,
});
expect(bundle?.accessToken).toBe("a");
expect(bundle?.refreshToken).toBe("r");
expect(bundle?.accessTokenExpiresAt).toBeGreaterThanOrEqual(before + 300 * 1000);
expect(bundle?.refreshTokenExpiresAt).toBeGreaterThanOrEqual(before + 3600 * 1000);
});
it("returns null when required fields are missing", () => {
expect(tokensFromAuthResponse({ token: "a" })).toBeNull();
expect(tokensFromAuthResponse(null)).toBeNull();
});
});
describe("tokensFromRefreshResponse", () => {
const current = {
accessToken: "old-access",
refreshToken: "old-refresh",
refreshTokenExpiresAt: 4_000,
};
// The response schema marks both tokens optional. Requiring the pair, as a login
// rightly does, wiped a session the instance had just renewed.
it("keeps the current refresh token when only the access token comes back", () => {
const bundle = tokensFromRefreshResponse({ token: "new-access" }, current);
expect(bundle?.accessToken).toBe("new-access");
expect(bundle?.refreshToken).toBe("old-refresh");
expect(bundle?.refreshTokenExpiresAt).toBe(4_000);
});
it("takes the rotated refresh token when the instance sends one", () => {
const bundle = tokensFromRefreshResponse(
{ token: "new-access", refreshToken: "new-refresh", refreshTtl: 3600 },
current,
);
expect(bundle?.refreshToken).toBe("new-refresh");
expect(bundle?.refreshTokenExpiresAt).toBeGreaterThan(Date.now());
});
it("returns null without a usable access token", () => {
expect(tokensFromRefreshResponse({ refreshToken: "r" }, current)).toBeNull();
expect(tokensFromRefreshResponse({}, current)).toBeNull();
expect(tokensFromRefreshResponse(null, current)).toBeNull();
});
});
describe("refresh robustness", () => {
it("keeps working when the instance rotates only the access token", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "old-refresh",
});
const calls = mockFetch([
() => new Response(null, { status: 401 }),
() => json({ message: "Success", token: "new-access" }),
() => json({ ok: true }),
]);
const client = await createAuthClient();
const res = await client.get("/whoami");
expect(res.status).toBe(200);
expect(authHeader(calls[2])).toBe("Bearer new-access");
expect((await getTokens(profile))?.refreshToken).toBe("old-refresh");
});
// The instance revokes the whole session chain when it sees a refresh token twice,
// so parallel refreshes would log the developer out rather than merely race.
it("refreshes once for concurrent 401s", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "old-refresh",
});
const calls: Call[] = [];
let refreshes = 0;
vi.stubGlobal(
"fetch",
vi.fn(async (url: string, init: RequestInit = {}) => {
calls.push({ url, init });
if (url.endsWith("/refresh")) {
refreshes++;
await new Promise((resolve) => setTimeout(resolve, 5));
return json({ token: "new-access", refreshToken: "new-refresh" });
}
const auth = (init.headers as Record<string, string>)?.Authorization;
return auth === "Bearer new-access"
? json({ ok: true })
: new Response(null, { status: 401 });
}),
);
const client = await createAuthClient();
const results = await Promise.all([
client.get("/a"),
client.get("/b"),
client.get("/c"),
]);
expect(refreshes).toBe(1);
expect(results.every((r) => r.status === 200)).toBe(true);
});
it("raises ReauthRequired when a refreshed token is still rejected", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "old-refresh",
});
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ token: "new-access", refreshToken: "new-refresh" }),
() => new Response(null, { status: 401 }),
]);
const client = await createAuthClient();
const err = await client.get("/whoami").catch((e: Error) => e);
expect(err).toBeInstanceOf(ReauthRequiredError);
expect((err as Error).message).toMatch(/rejected after refreshing it/);
expect(await getTokens(profile)).toBeNull();
});
it("leaves a non-401 failure to the caller", async () => {
await saveTokens(profile, {
accessToken: "old-access",
refreshToken: "old-refresh",
});
mockFetch([() => json({ error: "nope" }, 403)]);
const client = await createAuthClient();
expect((await client.get("/whoami")).status).toBe(403);
});
});
describe("a headless session", () => {
beforeEach(() => {
process.env.SEAMLESS_REFRESH_TOKEN = "env-refresh";
});
// getTokens reads the environment fresh on every run, so a rotated token written
// to the keychain is never read back: storing it only makes it look preserved.
it("does not write a rotated token to the keychain", async () => {
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ token: "new-access", refreshToken: "rotated" }),
() => json({ ok: true }),
]);
const client = await createAuthClient();
await client.get("/whoami");
delete process.env.SEAMLESS_REFRESH_TOKEN;
expect(await getTokens(profile)).toBeNull();
});
it("explains rotation when the environment's token is rejected", async () => {
mockFetch([
() => new Response(null, { status: 401 }),
() => json({ error: "refresh_token_reused" }, 401),
]);
const client = await createAuthClient();
await expect(client.get("/whoami")).rejects.toThrow(
/SEAMLESS_REFRESH_TOKEN.*rotates the refresh token on every refresh/s,
);
});
});