-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathline.spec.js
More file actions
641 lines (546 loc) · 18.6 KB
/
line.spec.js
File metadata and controls
641 lines (546 loc) · 18.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
const LineAdapter = require('../../../lib/Adapters/Auth/line').default;
const jwt = require('jsonwebtoken');
const authUtils = require('../../../lib/Adapters/Auth/utils');
describe('LineAdapter', function () {
let adapter;
const validOptions = {
clientId: 'validClientId',
clientSecret: 'validClientSecret',
};
// Stub LINE JWKS lookup and JWT verification so auth-flow tests stay deterministic
// and do not depend on live LINE signing keys.
function mockEs256IdTokenVerification(claims = {}) {
const jwtClaims = {
iss: 'https://access.line.me',
aud: 'validClientId',
exp: Math.floor(Date.now() / 1000) + 3600,
sub: 'mockUserId',
...claims,
};
const getHeaderSpy = jasmine.isSpy(authUtils.getHeaderFromToken)
? authUtils.getHeaderFromToken
: spyOn(authUtils, 'getHeaderFromToken');
const getSigningKeySpy = jasmine.isSpy(authUtils.getSigningKey)
? authUtils.getSigningKey
: spyOn(authUtils, 'getSigningKey');
const verifySpy = jasmine.isSpy(jwt.verify) ? jwt.verify : spyOn(jwt, 'verify');
getHeaderSpy.and.returnValue({ kid: '123', alg: 'ES256' });
getSigningKeySpy.and.resolveTo({ publicKey: 'line_public_key' });
verifySpy.and.returnValue(jwtClaims);
return jwtClaims;
}
beforeEach(function () {
adapter = new LineAdapter.constructor();
adapter.clientId = 'validClientId';
adapter.clientSecret = 'validClientSecret';
});
describe('validateOptions', function () {
it('should allow secure id token validation with clientId only', function () {
expect(() => adapter.validateOptions({ clientId: 'validClientId' })).not.toThrow();
expect(adapter.clientId).toBe('validClientId');
expect(adapter.clientSecret).toBeUndefined();
});
it('should allow insecure-only configuration when explicitly enabled', function () {
expect(() => adapter.validateOptions({ enableInsecureAuth: true })).not.toThrow();
expect(adapter.enableInsecureAuth).toBeTrue();
});
it('should require clientId when secure auth is configured', function () {
expect(() => adapter.validateOptions({ clientSecret: 'validClientSecret' })).toThrowError(
'Line clientId is required.'
);
});
});
describe('verifyIdToken', function () {
beforeEach(function () {
adapter.validateOptions(validOptions);
});
it('should throw an error if id_token is missing', async function () {
await expectAsync(adapter.verifyIdToken({})).toBeRejectedWithError(
'id token is invalid for this user.'
);
});
it('should not decode an invalid id_token', async function () {
await expectAsync(adapter.verifyIdToken({ id_token: 'the_token' })).toBeRejectedWithError(
'provided token does not decode as JWT'
);
});
it('should throw an error if public key used to encode token is not available', async function () {
spyOn(authUtils, 'getHeaderFromToken').and.returnValue({ kid: '789', alg: 'ES256' });
spyOn(authUtils, 'getSigningKey').and.returnValue(Promise.reject(new Error('missing key')));
await expectAsync(adapter.verifyIdToken({ id_token: 'the_token' })).toBeRejectedWithError(
'Unable to find matching key for Key ID: 789'
);
});
it('should guard and pass only a valid supported algorithm to jwt.verify', async function () {
const fakeClaim = mockEs256IdTokenVerification();
const result = await adapter.verifyIdToken({
id: 'mockUserId',
id_token: 'the_token',
});
expect(result).toEqual(fakeClaim);
expect(jwt.verify.calls.first().args[2].algorithms).toEqual(['ES256']);
});
it('should verify a valid id_token without an explicit id', async function () {
const fakeClaim = mockEs256IdTokenVerification({ sub: 'line-subject' });
const result = await adapter.verifyIdToken({ id_token: 'the_token' });
expect(result).toEqual(fakeClaim);
});
it('should reject a token with an invalid issuer', async function () {
mockEs256IdTokenVerification({ iss: 'https://invalid.line.me' });
await expectAsync(
adapter.verifyIdToken({ id: 'mockUserId', id_token: 'the_token' })
).toBeRejectedWithError(
'id token not issued by correct OpenID provider - expected: https://access.line.me | from: https://invalid.line.me'
);
});
it('should reject a token with a mismatched sub claim', async function () {
mockEs256IdTokenVerification({ sub: 'another-user' });
await expectAsync(
adapter.verifyIdToken({ id: 'mockUserId', id_token: 'the_token' })
).toBeRejectedWithError('auth data is invalid for this user.');
});
it('should reject a token with a mismatched nonce', async function () {
mockEs256IdTokenVerification({ nonce: 'server-nonce' });
await expectAsync(
adapter.verifyIdToken({
id_token: 'the_token',
nonce: 'different-nonce',
})
).toBeRejectedWithError('auth data is invalid for this user.');
});
it('should verify an HS256 token when clientSecret is configured', async function () {
spyOn(authUtils, 'getHeaderFromToken').and.returnValue({ alg: 'HS256' });
spyOn(jwt, 'verify').and.returnValue({
iss: 'https://access.line.me',
aud: 'validClientId',
exp: Date.now() + 1000,
sub: 'mockUserId',
});
const result = await adapter.verifyIdToken({
id: 'mockUserId',
id_token: 'the_token',
});
expect(result.sub).toBe('mockUserId');
expect(jwt.verify.calls.first().args[1]).toBe('validClientSecret');
expect(jwt.verify.calls.first().args[2].algorithms).toEqual(['HS256']);
});
it('should reject an HS256 token when clientSecret is missing', async function () {
adapter.validateOptions({ clientId: 'validClientId' });
spyOn(authUtils, 'getHeaderFromToken').and.returnValue({ alg: 'HS256' });
await expectAsync(adapter.verifyIdToken({ id_token: 'the_token' })).toBeRejectedWithError(
'Line clientSecret is required to verify HS256 id_token.'
);
});
});
describe('getAccessTokenFromCode', function () {
beforeEach(function () {
adapter.validateOptions(validOptions);
});
it('should throw an error if code is missing in authData', async function () {
const authData = { redirect_uri: 'http://example.com' };
await expectAsync(adapter.getAccessTokenFromCode(authData)).toBeRejectedWithError(
'Line auth is invalid for this user.'
);
});
it('should throw an error if clientSecret is missing in server-side auth flows', async function () {
adapter.validateOptions({ clientId: 'validClientId' });
await expectAsync(
adapter.getAccessTokenFromCode({ code: 'validCode', redirect_uri: 'http://example.com' })
).toBeRejectedWithError('Line clientSecret is required to exchange code for token.');
});
it('should fetch an access token successfully', async function () {
mockFetch([
{
url: 'https://api.line.me/oauth2/v2.1/token',
method: 'POST',
response: {
ok: true,
json: () =>
Promise.resolve({
access_token: 'mockAccessToken',
}),
},
},
]);
const authData = {
code: 'validCode',
redirect_uri: 'http://example.com',
};
const token = await adapter.getAccessTokenFromCode(authData);
expect(token).toBe('mockAccessToken');
});
it('should throw an error if response is not ok', async function () {
mockFetch([
{
url: 'https://api.line.me/oauth2/v2.1/token',
method: 'POST',
response: {
ok: false,
statusText: 'Bad Request',
},
},
]);
const authData = {
code: 'invalidCode',
redirect_uri: 'http://example.com',
};
await expectAsync(adapter.getAccessTokenFromCode(authData)).toBeRejectedWithError(
'Failed to exchange code for token: Bad Request'
);
});
it('should throw an error if response contains an error object', async function () {
mockFetch([
{
url: 'https://api.line.me/oauth2/v2.1/token',
method: 'POST',
response: {
ok: true,
json: () =>
Promise.resolve({
error: 'invalid_grant',
error_description: 'Code is invalid',
}),
},
},
]);
const authData = {
code: 'invalidCode',
redirect_uri: 'http://example.com',
};
await expectAsync(adapter.getAccessTokenFromCode(authData)).toBeRejectedWithError(
'Code is invalid'
);
});
});
describe('getUserFromAccessToken', function () {
beforeEach(function () {
adapter.validateOptions(validOptions);
});
it('should fetch user data successfully and normalize the user id', async function () {
mockFetch([
{
url: 'https://api.line.me/v2/profile',
method: 'GET',
response: {
ok: true,
json: () =>
Promise.resolve({
userId: 'mockUserId',
displayName: 'mockDisplayName',
}),
},
},
]);
const accessToken = 'validAccessToken';
const user = await adapter.getUserFromAccessToken(accessToken);
expect(user).toEqual({
userId: 'mockUserId',
displayName: 'mockDisplayName',
id: 'mockUserId',
});
});
it('should throw an error if response is not ok', async function () {
mockFetch([
{
url: 'https://api.line.me/v2/profile',
method: 'GET',
response: {
ok: false,
statusText: 'Unauthorized',
},
},
]);
const accessToken = 'invalidAccessToken';
await expectAsync(adapter.getUserFromAccessToken(accessToken)).toBeRejectedWithError(
'Failed to fetch Line user: Unauthorized'
);
});
it('should throw an error if user data is invalid', async function () {
mockFetch([
{
url: 'https://api.line.me/v2/profile',
method: 'GET',
response: {
ok: true,
json: () => Promise.resolve({}),
},
},
]);
const accessToken = 'validAccessToken';
await expectAsync(adapter.getUserFromAccessToken(accessToken)).toBeRejectedWithError(
'Invalid Line user data received.'
);
});
});
describe('beforeFind', function () {
beforeEach(function () {
adapter.validateOptions(validOptions);
});
it('should populate authData.id from a verified id_token', async function () {
spyOn(adapter, 'verifyIdToken').and.resolveTo({ sub: 'mockUserId' });
const authData = {
id_token: 'the_token',
nonce: 'nonce',
};
await adapter.beforeFind(authData);
expect(authData).toEqual({ id: 'mockUserId' });
});
it('should block insecure auth unless explicitly enabled', async function () {
const authData = {
id: 'mockUserId',
access_token: 'validAccessToken',
};
await expectAsync(adapter.beforeFind(authData)).toBeRejectedWithError(
'Line code is required.'
);
});
});
describe('LineAdapter E2E Test', function () {
beforeEach(async function () {
await reconfigureServer({
auth: {
line: {
clientId: 'validClientId',
clientSecret: 'validClientSecret',
},
},
});
});
it('should log in user successfully with valid code', async function () {
mockFetch([
{
url: 'https://api.line.me/oauth2/v2.1/token',
method: 'POST',
response: {
ok: true,
json: () =>
Promise.resolve({
access_token: 'mockAccessToken123',
}),
},
},
{
url: 'https://api.line.me/v2/profile',
method: 'GET',
response: {
ok: true,
json: () =>
Promise.resolve({
userId: 'mockUserId',
displayName: 'mockDisplayName',
}),
},
},
]);
const authData = {
code: 'validCode',
redirect_uri: 'http://example.com',
};
const user = await Parse.User.logInWith('line', { authData });
expect(user.id).toBeDefined();
});
it('should handle error when token exchange fails', async function () {
mockFetch([
{
url: 'https://api.line.me/oauth2/v2.1/token',
method: 'POST',
response: {
ok: false,
statusText: 'Invalid code',
},
},
]);
const authData = {
code: 'invalidCode',
redirect_uri: 'http://example.com',
};
await expectAsync(Parse.User.logInWith('line', { authData })).toBeRejectedWithError(
'Failed to exchange code for token: Invalid code'
);
});
it('should handle error when user data fetch fails', async function () {
mockFetch([
{
url: 'https://api.line.me/oauth2/v2.1/token',
method: 'POST',
response: {
ok: true,
json: () =>
Promise.resolve({
access_token: 'mockAccessToken123',
}),
},
},
{
url: 'https://api.line.me/v2/profile',
method: 'GET',
response: {
ok: false,
statusText: 'Unauthorized',
},
},
]);
const authData = {
code: 'validCode',
redirect_uri: 'http://example.com',
};
await expectAsync(Parse.User.logInWith('line', { authData })).toBeRejectedWithError(
'Failed to fetch Line user: Unauthorized'
);
});
it('should handle error when user data is invalid', async function () {
mockFetch([
{
url: 'https://api.line.me/oauth2/v2.1/token',
method: 'POST',
response: {
ok: true,
json: () =>
Promise.resolve({
access_token: 'mockAccessToken123',
}),
},
},
{
url: 'https://api.line.me/v2/profile',
method: 'GET',
response: {
ok: true,
json: () => Promise.resolve({}),
},
},
]);
const authData = {
code: 'validCode',
redirect_uri: 'http://example.com',
};
await expectAsync(Parse.User.logInWith('line', { authData })).toBeRejectedWithError(
'Invalid Line user data received.'
);
});
it('should handle error when no code is provided', async function () {
mockFetch();
const authData = {
redirect_uri: 'http://example.com',
};
await expectAsync(Parse.User.logInWith('line', { authData })).toBeRejectedWithError(
'Line code is required.'
);
});
});
describe('LineAdapter E2E id_token Test', function () {
beforeEach(async function () {
await reconfigureServer({
auth: {
line: {
clientId: 'validClientId',
},
},
});
});
it('should log in user successfully with a valid id_token', async function () {
mockEs256IdTokenVerification();
const authData = {
id_token: 'the_token',
};
const user = await Parse.User.logInWith('line', { authData });
await user.fetch({ useMasterKey: true });
expect(user.id).toBeDefined();
expect(user.get('authData').line.id).toBe('mockUserId');
});
it('should link line auth to an existing logged-in user with an id_token', async function () {
mockEs256IdTokenVerification({ sub: 'link-user-id' });
const user = await Parse.User.signUp('line-link-user', 'password');
await user.save(
{
authData: {
line: {
id_token: 'the_token',
},
},
},
{ sessionToken: user.getSessionToken() }
);
await user.fetch({ useMasterKey: true });
expect(user.get('authData').line.id).toBe('link-user-id');
});
it('should allow updating existing LINE auth with id_token', async function () {
mockEs256IdTokenVerification({ sub: 'existing-line-user' });
const user = await Parse.User.logInWith('line', {
authData: {
id_token: 'first_token',
},
});
mockEs256IdTokenVerification({ sub: 'existing-line-user' });
await user.save(
{
authData: {
line: {
id_token: 'second_token',
},
},
},
{ sessionToken: user.getSessionToken() }
);
await user.fetch({ useMasterKey: true });
expect(user.get('authData').line.id).toBe('existing-line-user');
});
it('should reject insecure authData when insecure auth is disabled', async function () {
await expectAsync(
Parse.User.logInWith('line', {
authData: {
id: 'mockUserId',
access_token: 'validAccessToken',
},
})
).toBeRejectedWithError('Line code is required.');
});
it('should handle invalid id_token claims during login', async function () {
mockEs256IdTokenVerification({ iss: 'https://invalid.line.me' });
await expectAsync(
Parse.User.logInWith('line', {
authData: {
id_token: 'the_token',
},
})
).toBeRejectedWithError(
'id token not issued by correct OpenID provider - expected: https://access.line.me | from: https://invalid.line.me'
);
});
});
describe('LineAdapter E2E legacy access token Test', function () {
beforeEach(async function () {
await reconfigureServer({
auth: {
line: {
enableInsecureAuth: true,
},
},
});
});
it('should allow insecure auth only when explicitly enabled', async function () {
mockFetch([
{
url: 'https://api.line.me/v2/profile',
method: 'GET',
response: {
ok: true,
json: () =>
Promise.resolve({
userId: 'mockUserId',
displayName: 'mockDisplayName',
}),
},
},
]);
const user = await Parse.User.logInWith('line', {
authData: {
id: 'mockUserId',
access_token: 'validAccessToken',
},
});
expect(user.id).toBeDefined();
expect(user.get('authData').line.id).toBe('mockUserId');
});
});
});