-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlogin.test.ts
More file actions
551 lines (460 loc) · 21 KB
/
login.test.ts
File metadata and controls
551 lines (460 loc) · 21 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
import type { Config } from '@oclif/core';
import { type Mock, type MockedFunction, vi } from 'vitest';
import { ensureUserSetup } from '../../../src/api/user-setup.client.ts';
import AuthLogin from '../../../src/commands/auth/login.ts';
import { refreshIdentityFromStoredToken } from '../../../src/service/analytics.svc.ts';
import { persistTokenResponse } from '../../../src/service/auth.svc.ts';
import type { TokenResponse } from '../../../src/types/auth.ts';
import { openInBrowser } from '../../../src/utils/open-in-browser.ts';
type ServerRequest = { url?: string };
type ServerResponse = { writeHead: Mock; end: Mock };
type ServerHandler = (req: ServerRequest, res: ServerResponse) => void;
interface ServerStub {
handler: ServerHandler;
listen: MockedFunction<(port: number, cb?: () => void) => ServerStub>;
close: MockedFunction<(cb?: (err?: Error) => void) => ServerStub>;
on: MockedFunction<(event: string, cb: (err: Error) => void) => ServerStub>;
triggerRequest: (url?: string) => { writeHead: Mock; end: Mock };
emitError: (error: Error) => void;
}
const serverInstances: ServerStub[] = [];
class ServerNotRunningError extends Error implements NodeJS.ErrnoException {
code = 'ERR_SERVER_NOT_RUNNING';
constructor() {
super('Server is not running.');
this.name = 'ServerNotRunningError';
}
}
const createServerStub = (handler: ServerHandler): ServerStub => {
let errorListener: ((error: Error) => void) | undefined;
let closed = false;
const stub: ServerStub = {
handler,
listen: vi.fn((_port: number, cb?: () => void) => {
if (cb) {
setImmediate(cb);
}
return stub;
}),
close: vi.fn((cb?: (err?: Error) => void) => {
const closeError = closed ? new ServerNotRunningError() : undefined;
closed = true;
setImmediate(() => cb?.(closeError));
return stub;
}),
on: vi.fn((event: string, cb: (err: Error) => void) => {
if (event === 'error') {
errorListener = cb;
}
return stub;
}),
triggerRequest: (url?: string) => {
const res = {
writeHead: vi.fn(),
end: vi.fn(),
};
stub.handler({ url } as ServerRequest, res as ServerResponse);
return res;
},
emitError: (error: Error) => {
errorListener?.(error);
},
};
return stub;
};
vi.mock('http', () => ({
__esModule: true,
default: {
createServer: vi.fn((handler: ServerHandler) => {
const server = createServerStub(handler);
serverInstances.push(server);
return server;
}),
},
}));
vi.mock('../../../src/api/user-setup.client.ts', () => ({
__esModule: true,
ensureUserSetup: vi.fn(),
}));
vi.mock('../../../src/config/constants.ts', async (importOriginal) => importOriginal());
vi.mock('../../../src/utils/open-in-browser.ts', () => ({
__esModule: true,
openInBrowser: vi.fn(),
}));
const questionMock = vi.fn<(question: string, callback: (answer: string) => void) => void>();
const closeMock = vi.fn<() => void>();
vi.mock('node:readline', () => ({
__esModule: true,
createInterface: vi.fn(() => ({
question: questionMock,
close: closeMock,
})),
}));
vi.mock('../../../src/service/auth.svc.ts', () => ({
__esModule: true,
persistTokenResponse: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('../../../src/service/analytics.svc.ts', () => ({
__esModule: true,
refreshIdentityFromStoredToken: vi.fn().mockResolvedValue(undefined),
}));
const openMock = vi.mocked(openInBrowser) as MockedFunction<typeof openInBrowser>;
const persistTokenResponseMock = vi.mocked(persistTokenResponse);
const ensureUserSetupMock = vi.mocked(ensureUserSetup);
const refreshIdentityFromStoredTokenMock = vi.mocked(refreshIdentityFromStoredToken);
const flushAsync = () => new Promise((resolve) => setImmediate(resolve));
const getLatestServer = () => {
const server = serverInstances.at(-1);
if (!server) {
throw new Error('HTTP server stub was not initialized');
}
return server;
};
const sendCallbackThroughStub = (params: Record<string, string | undefined>) => {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== undefined) {
search.append(key, value);
}
}
const query = search.toString();
const path = `/oauth2/callback${query ? `?${query}` : ''}`;
return getLatestServer().triggerRequest(path);
};
const createCommand = (port: number) => {
process.env.OAUTH_CALLBACK_PORT = `${port}`;
const mockConfig = {} as Config;
return new AuthLogin([], mockConfig);
};
describe('AuthLogin', () => {
beforeEach(() => {
questionMock.mockImplementation((_q, cb) => cb(''));
closeMock.mockClear();
openMock.mockResolvedValue(undefined);
ensureUserSetupMock.mockResolvedValue(undefined);
refreshIdentityFromStoredTokenMock.mockResolvedValue(undefined);
});
afterEach(() => {
vi.clearAllMocks();
delete process.env.OAUTH_CALLBACK_PORT;
serverInstances.length = 0;
persistTokenResponseMock.mockClear();
});
describe('startServerAndAwaitToken', () => {
const authUrl = 'https://login.example/auth';
const basePort = 4900;
it('resolves with the token response when the callback is valid', async () => {
const command = createCommand(basePort);
const state = 'expected-state';
const codeVerifier = 'verifier-123';
const commandWithInternals = command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<TokenResponse>;
exchangeCodeForToken: (...args: unknown[]) => Promise<TokenResponse>;
};
const tokenResponse = { access_token: 'access', refresh_token: 'refresh' };
vi.spyOn(commandWithInternals, 'exchangeCodeForToken').mockResolvedValue(tokenResponse);
const pendingCode = commandWithInternals.startServerAndAwaitToken(authUrl, state, codeVerifier);
const server = getLatestServer();
await flushAsync();
sendCallbackThroughStub({ code: 'test-code', state });
await expect(pendingCode).resolves.toBe(tokenResponse);
expect(questionMock).toHaveBeenCalledWith(expect.stringContaining(authUrl), expect.any(Function));
expect(closeMock).toHaveBeenCalledTimes(1);
expect(openMock).toHaveBeenCalledWith(authUrl);
expect(server.close).toHaveBeenCalledTimes(1);
});
it('rejects when the callback is missing the state parameter', async () => {
const command = createCommand(basePort + 1);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
sendCallbackThroughStub({ code: 'test-code', state: undefined });
await expect(pendingCode).rejects.toThrow('Missing state parameter in callback');
expect(server.close).toHaveBeenCalledTimes(1);
});
it('rejects when the callback state does not match', async () => {
const command = createCommand(basePort + 2);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
sendCallbackThroughStub({ code: 'test-code', state: 'different' });
await expect(pendingCode).rejects.toThrow('State verification failed');
expect(server.close).toHaveBeenCalledTimes(1);
});
it('rejects with guidance when callback returns already_logged_in', async () => {
const command = createCommand(basePort + 3);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
const response = sendCallbackThroughStub({ error: 'already_logged_in', state: 'expected-state' });
expect(response.writeHead).toHaveBeenCalledWith(400, { 'Content-Type': 'text/plain' });
expect(response.end).toHaveBeenCalledWith(
"You're already signed in. We'll continue for you. Return to the terminal.",
);
await expect(pendingCode).rejects.toThrow(`You're already signed in. Run "hd auth login" again to continue.`);
expect(server.close).toHaveBeenCalledTimes(1);
});
it('rejects when callback returns a generic OAuth error', async () => {
const command = createCommand(basePort + 4);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
const response = sendCallbackThroughStub({
error: 'access_denied',
error_description: 'User denied access',
state: 'expected-state',
});
expect(response.writeHead).toHaveBeenCalledWith(400, { 'Content-Type': 'text/plain' });
expect(response.end).toHaveBeenCalledWith("We couldn't complete sign-in. Return to the terminal and try again.");
await expect(pendingCode).rejects.toThrow(`We couldn't complete sign-in. Please run "hd auth login" again.`);
expect(server.close).toHaveBeenCalledTimes(1);
});
it('rejects with guidance when callback returns different_user_authenticated', async () => {
const command = createCommand(basePort + 5);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
const response = sendCallbackThroughStub({ error: 'different_user_authenticated', state: 'expected-state' });
expect(response.writeHead).toHaveBeenCalledWith(400, { 'Content-Type': 'text/plain' });
expect(response.end).toHaveBeenCalledWith(
"You're signed in with a different account than this sign-in attempt. Return to the terminal.",
);
await expect(pendingCode).rejects.toThrow(
`You're signed in with a different account than this sign-in attempt. ` +
`Choose another account, or reset this sign-in session and try again. ` +
`If needed, run "hd auth logout" and then "hd auth login".`,
);
expect(server.close).toHaveBeenCalledTimes(1);
});
it('rejects when the callback omits the authorization code', async () => {
const command = createCommand(basePort + 6);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
sendCallbackThroughStub({ state: 'expected-state' });
await expect(pendingCode).rejects.toThrow('No code returned from Keycloak');
expect(server.close).toHaveBeenCalledTimes(1);
});
it('rejects when the callback URL is invalid', async () => {
const command = createCommand(basePort + 7);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
const response = server.triggerRequest('http://%');
expect(response.writeHead).toHaveBeenCalledWith(400, { 'Content-Type': 'text/plain' });
expect(response.end).toHaveBeenCalledWith('Invalid callback URL');
await expect(pendingCode).rejects.toThrow('Invalid callback URL');
expect(server.close).toHaveBeenCalledTimes(1);
});
it('returns a 400 response when the incoming request is missing a URL', async () => {
const command = createCommand(basePort + 8);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
const response = server.triggerRequest(undefined);
expect(response.writeHead).toHaveBeenCalledWith(400);
expect(response.end).toHaveBeenCalledWith('Invalid request');
const shutdownError = new Error('test shutdown');
server.emitError(shutdownError);
await expect(pendingCode).rejects.toBe(shutdownError);
expect(server.close).toHaveBeenCalledTimes(1);
});
it('responds with not found for unrelated paths', async () => {
const command = createCommand(basePort + 9);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
const response = server.triggerRequest('/not-supported');
expect(response.writeHead).toHaveBeenCalledWith(404);
expect(response.end).toHaveBeenCalledWith();
const shutdownError = new Error('not found handled');
server.emitError(shutdownError);
await expect(pendingCode).rejects.toBe(shutdownError);
expect(server.close).toHaveBeenCalledTimes(1);
});
it('rejects when the local HTTP server emits an error', async () => {
const command = createCommand(basePort + 10);
const pendingCode = (
command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<string>;
}
).startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
const error = new Error('listener failed');
server.emitError(error);
await expect(pendingCode).rejects.toBe(error);
expect(server.close).toHaveBeenCalledTimes(1);
});
it('warns and allows manual navigation when browser launch fails', async () => {
openMock.mockRejectedValueOnce(new Error('browser unavailable'));
const command = createCommand(basePort + 11);
const warnSpy = vi
.spyOn(command as unknown as { warn: (...args: unknown[]) => unknown }, 'warn')
.mockImplementation(() => {});
const state = 'expected-state';
try {
const commandWithInternals = command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<TokenResponse>;
exchangeCodeForToken: (...args: unknown[]) => Promise<TokenResponse>;
};
const tokenResponse = { access_token: 'access', refresh_token: 'refresh' };
vi.spyOn(commandWithInternals, 'exchangeCodeForToken').mockResolvedValue(tokenResponse);
const pendingCode = commandWithInternals.startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
await flushAsync();
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Failed to open browser automatically'));
sendCallbackThroughStub({ code: 'manual-code', state });
await expect(pendingCode).resolves.toBe(tokenResponse);
expect(server.close).toHaveBeenCalledTimes(1);
} finally {
warnSpy.mockRestore();
}
});
it('deduplicates shutdown when callback success and server error race', async () => {
const command = createCommand(basePort + 12);
const state = 'expected-state';
const commandWithInternals = command as unknown as {
startServerAndAwaitToken: (url: string, state: string, codeVerifier: string) => Promise<TokenResponse>;
};
const pendingCode = commandWithInternals.startServerAndAwaitToken(authUrl, 'expected-state', 'code-verifier');
const server = getLatestServer();
const warnSpy = vi
.spyOn(command as unknown as { warn: (...args: unknown[]) => unknown }, 'warn')
.mockImplementation(() => {});
try {
await flushAsync();
sendCallbackThroughStub({ code: 'race-code', state });
server.emitError(new Error('late listener error'));
await expect(pendingCode).rejects.toThrow('late listener error');
expect(server.close).toHaveBeenCalledTimes(1);
expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining('Failed to stop local OAuth callback server'));
} finally {
warnSpy.mockRestore();
}
});
});
describe('exchangeCodeForToken', () => {
it('posts the authorization code and returns the parsed token response', async () => {
const command = createCommand(5000);
const mockResponse = { access_token: 'abc123' };
const jsonMock = vi.fn().mockResolvedValue(mockResponse);
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
json: jsonMock,
} as unknown as Response);
try {
const token = await (
command as unknown as { exchangeCodeForToken: (code: string, verifier: string) => Promise<unknown> }
).exchangeCodeForToken('code-123', 'verifier-456');
expect(fetchSpy).toHaveBeenCalledTimes(1);
const [url, options] = fetchSpy.mock.calls[0];
expect(url).toMatch(/\/token$/);
expect(options).toMatchObject({
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
expect(options?.body).toContain('code=code-123');
expect(options?.body).toContain('code_verifier=verifier-456');
expect(options?.body).toContain('grant_type=authorization_code');
expect(token).toEqual(mockResponse);
} finally {
fetchSpy.mockRestore();
}
});
it('throws an error that includes the response body when the exchange fails', async () => {
const command = createCommand(5001);
const textMock = vi.fn().mockResolvedValue('error-details');
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: false,
status: 500,
statusText: 'Server Error',
text: textMock,
} as unknown as Response);
try {
await expect(
(
command as unknown as { exchangeCodeForToken: (code: string, verifier: string) => Promise<unknown> }
).exchangeCodeForToken('code-123', 'verifier-456'),
).rejects.toThrow('Token exchange failed: 500 Server Error');
expect(textMock).toHaveBeenCalled();
} finally {
fetchSpy.mockRestore();
}
});
});
describe('run', () => {
it('stores tokens after successful authentication', async () => {
const command = createCommand(6000);
const tokenResponse = { access_token: 'access', refresh_token: 'refresh' };
const commandWithInternals = command as unknown as {
startServerAndAwaitToken: (...args: unknown[]) => Promise<unknown>;
};
vi.spyOn(commandWithInternals, 'startServerAndAwaitToken').mockResolvedValue(tokenResponse);
await command.run();
expect(persistTokenResponseMock).toHaveBeenCalledWith(tokenResponse);
expect(ensureUserSetupMock).toHaveBeenCalledTimes(1);
expect(ensureUserSetupMock).toHaveBeenCalledWith({ preferOAuth: true });
expect(refreshIdentityFromStoredTokenMock).toHaveBeenCalledTimes(1);
});
it('runs user setup after login', async () => {
const command = createCommand(6001);
const tokenResponse = { access_token: 'access', refresh_token: 'refresh' };
const commandWithInternals = command as unknown as {
startServerAndAwaitToken: (...args: unknown[]) => Promise<unknown>;
};
vi.spyOn(commandWithInternals, 'startServerAndAwaitToken').mockResolvedValue(tokenResponse);
await command.run();
expect(ensureUserSetupMock).toHaveBeenCalledTimes(1);
expect(ensureUserSetupMock).toHaveBeenCalledWith({ preferOAuth: true });
expect(refreshIdentityFromStoredTokenMock).toHaveBeenCalledTimes(1);
});
it('fails login when user setup fails', async () => {
ensureUserSetupMock.mockRejectedValueOnce(new Error('setup failed'));
const command = createCommand(6002);
const tokenResponse = { access_token: 'access', refresh_token: 'refresh' };
const commandWithInternals = command as unknown as {
startServerAndAwaitToken: (...args: unknown[]) => Promise<unknown>;
};
vi.spyOn(commandWithInternals, 'startServerAndAwaitToken').mockResolvedValue(tokenResponse);
await expect(command.run()).rejects.toThrow('User setup failed');
expect(refreshIdentityFromStoredTokenMock).not.toHaveBeenCalled();
});
});
});