Repository navigation
Expand file tree
/
Copy pathoauth.test.ts
More file actions
2392 lines (2030 loc) · 89.3 KB
/
Copy pathoauth.test.ts
File metadata and controls
2392 lines (2030 loc) · 89.3 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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import * as sinon from 'sinon';
import {
buildIdJagExchangeBody,
buildResourceRedemptionBody,
getClaimsFromJWT,
getDefaultMetadataForUrl,
isAuthorizationAuthorizeResponse,
isAuthorizationDeviceResponse,
isAuthorizationErrorResponse,
isAuthorizationDynamicClientRegistrationResponse,
isAuthorizationProtectedResourceMetadata,
isAuthorizationServerMetadata,
isAuthorizationTokenResponse,
parseWWWAuthenticateHeader,
fetchDynamicRegistration,
fetchResourceMetadata,
fetchAuthorizationServerMetadata,
scopesMatch,
IAuthorizationJWTClaims,
IAuthorizationServerMetadata,
DEFAULT_AUTH_FLOW_PORT
} from '../../common/oauth.js';
import { ensureNoDisposablesAreLeakedInTestSuite } from './utils.js';
import { encodeBase64, VSBuffer } from '../../common/buffer.js';
suite('OAuth', () => {
ensureNoDisposablesAreLeakedInTestSuite();
suite('Type Guards', () => {
test('isAuthorizationProtectedResourceMetadata should correctly identify protected resource metadata', () => {
// Valid metadata with minimal required fields
assert.strictEqual(isAuthorizationProtectedResourceMetadata({ resource: 'https://example.com' }), true);
// Valid metadata with scopes_supported as array
assert.strictEqual(isAuthorizationProtectedResourceMetadata({
resource: 'https://example.com',
scopes_supported: ['read', 'write']
}), true);
// Invalid cases - missing resource
assert.strictEqual(isAuthorizationProtectedResourceMetadata(null), false);
assert.strictEqual(isAuthorizationProtectedResourceMetadata(undefined), false);
assert.strictEqual(isAuthorizationProtectedResourceMetadata({}), false);
assert.strictEqual(isAuthorizationProtectedResourceMetadata('not an object'), false);
// Invalid cases - scopes_supported is not an array when provided
assert.strictEqual(isAuthorizationProtectedResourceMetadata({
resource: 'https://example.com',
scopes_supported: 'not an array'
}), false);
});
test('isAuthorizationServerMetadata should correctly identify server metadata', () => {
// Valid metadata with minimal required fields
assert.strictEqual(isAuthorizationServerMetadata({
issuer: 'https://example.com',
response_types_supported: ['code']
}), true);
// Valid metadata with valid URLs
assert.strictEqual(isAuthorizationServerMetadata({
issuer: 'https://example.com',
authorization_endpoint: 'https://example.com/auth',
token_endpoint: 'https://example.com/token',
registration_endpoint: 'https://example.com/register',
jwks_uri: 'https://example.com/jwks',
response_types_supported: ['code']
}), true);
// Valid metadata with http URLs (for localhost/testing)
assert.strictEqual(isAuthorizationServerMetadata({
issuer: 'http://localhost:8080',
authorization_endpoint: 'http://localhost:8080/auth',
token_endpoint: 'http://localhost:8080/token',
response_types_supported: ['code']
}), true);
// Invalid cases - not an object
assert.strictEqual(isAuthorizationServerMetadata(null), false);
assert.strictEqual(isAuthorizationServerMetadata(undefined), false);
assert.strictEqual(isAuthorizationServerMetadata('not an object'), false);
// Invalid cases - missing issuer should throw
assert.throws(() => isAuthorizationServerMetadata({}), /Authorization server metadata must have an issuer/);
assert.throws(() => isAuthorizationServerMetadata({ response_types_supported: ['code'] }), /Authorization server metadata must have an issuer/);
// Invalid cases - URI fields must be strings when provided (truthy values)
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'https://example.com',
authorization_endpoint: 123,
response_types_supported: ['code']
}), /Authorization server metadata 'authorization_endpoint' must be a string/);
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'https://example.com',
token_endpoint: 123,
response_types_supported: ['code']
}), /Authorization server metadata 'token_endpoint' must be a string/);
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'https://example.com',
registration_endpoint: [],
response_types_supported: ['code']
}), /Authorization server metadata 'registration_endpoint' must be a string/);
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'https://example.com',
jwks_uri: {},
response_types_supported: ['code']
}), /Authorization server metadata 'jwks_uri' must be a string/);
// Invalid cases - URI fields must start with http:// or https://
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'ftp://example.com',
response_types_supported: ['code']
}), /Authorization server metadata 'issuer' must start with http:\/\/ or https:\/\//);
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'https://example.com',
authorization_endpoint: 'ftp://example.com/auth',
response_types_supported: ['code']
}), /Authorization server metadata 'authorization_endpoint' must start with http:\/\/ or https:\/\//);
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'https://example.com',
token_endpoint: 'file:///path/to/token',
response_types_supported: ['code']
}), /Authorization server metadata 'token_endpoint' must start with http:\/\/ or https:\/\//);
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'https://example.com',
registration_endpoint: 'mailto:admin@example.com',
response_types_supported: ['code']
}), /Authorization server metadata 'registration_endpoint' must start with http:\/\/ or https:\/\//);
assert.throws(() => isAuthorizationServerMetadata({
issuer: 'https://example.com',
jwks_uri: 'data:application/json,{}',
response_types_supported: ['code']
}), /Authorization server metadata 'jwks_uri' must start with http:\/\/ or https:\/\//);
});
test('isAuthorizationDynamicClientRegistrationResponse should correctly identify registration response', () => {
// Valid response
assert.strictEqual(isAuthorizationDynamicClientRegistrationResponse({
client_id: 'client-123',
client_name: 'Test Client'
}), true);
// Invalid cases
assert.strictEqual(isAuthorizationDynamicClientRegistrationResponse(null), false);
assert.strictEqual(isAuthorizationDynamicClientRegistrationResponse(undefined), false);
assert.strictEqual(isAuthorizationDynamicClientRegistrationResponse({}), false);
assert.strictEqual(isAuthorizationDynamicClientRegistrationResponse({ client_id: 'just-id' }), true);
assert.strictEqual(isAuthorizationDynamicClientRegistrationResponse({ client_name: 'missing-id' }), false);
assert.strictEqual(isAuthorizationDynamicClientRegistrationResponse('not an object'), false);
});
test('isAuthorizationAuthorizeResponse should correctly identify authorization response', () => {
// Valid response
assert.strictEqual(isAuthorizationAuthorizeResponse({
code: 'auth-code-123',
state: 'state-123'
}), true);
// Invalid cases
assert.strictEqual(isAuthorizationAuthorizeResponse(null), false);
assert.strictEqual(isAuthorizationAuthorizeResponse(undefined), false);
assert.strictEqual(isAuthorizationAuthorizeResponse({}), false);
assert.strictEqual(isAuthorizationAuthorizeResponse({ code: 'missing-state' }), false);
assert.strictEqual(isAuthorizationAuthorizeResponse({ state: 'missing-code' }), false);
assert.strictEqual(isAuthorizationAuthorizeResponse('not an object'), false);
});
test('isAuthorizationTokenResponse should correctly identify token response', () => {
// Valid response
assert.strictEqual(isAuthorizationTokenResponse({
access_token: 'token-123',
token_type: 'Bearer'
}), true);
// Invalid cases
assert.strictEqual(isAuthorizationTokenResponse(null), false);
assert.strictEqual(isAuthorizationTokenResponse(undefined), false);
assert.strictEqual(isAuthorizationTokenResponse({}), false);
assert.strictEqual(isAuthorizationTokenResponse({ access_token: 'missing-type' }), false);
assert.strictEqual(isAuthorizationTokenResponse({ token_type: 'missing-token' }), false);
assert.strictEqual(isAuthorizationTokenResponse('not an object'), false);
});
test('isAuthorizationDeviceResponse should correctly identify device authorization response', () => {
// Valid response
assert.strictEqual(isAuthorizationDeviceResponse({
device_code: 'device-code-123',
user_code: 'ABCD-EFGH',
verification_uri: 'https://example.com/verify',
expires_in: 1800
}), true);
// Valid response with optional fields
assert.strictEqual(isAuthorizationDeviceResponse({
device_code: 'device-code-123',
user_code: 'ABCD-EFGH',
verification_uri: 'https://example.com/verify',
verification_uri_complete: 'https://example.com/verify?user_code=ABCD-EFGH',
expires_in: 1800,
interval: 5
}), true);
// Invalid cases
assert.strictEqual(isAuthorizationDeviceResponse(null), false);
assert.strictEqual(isAuthorizationDeviceResponse(undefined), false);
assert.strictEqual(isAuthorizationDeviceResponse({}), false);
assert.strictEqual(isAuthorizationDeviceResponse({ device_code: 'missing-others' }), false);
assert.strictEqual(isAuthorizationDeviceResponse({ user_code: 'missing-others' }), false);
assert.strictEqual(isAuthorizationDeviceResponse({ verification_uri: 'missing-others' }), false);
assert.strictEqual(isAuthorizationDeviceResponse({ expires_in: 1800 }), false);
assert.strictEqual(isAuthorizationDeviceResponse({
device_code: 'device-code-123',
user_code: 'ABCD-EFGH',
verification_uri: 'https://example.com/verify'
// Missing expires_in
}), false);
assert.strictEqual(isAuthorizationDeviceResponse('not an object'), false);
});
test('isAuthorizationErrorResponse should correctly identify error response', () => {
// Valid error response
assert.strictEqual(isAuthorizationErrorResponse({
error: 'authorization_pending',
error_description: 'The authorization request is still pending'
}), true);
// Valid error response with different error codes
assert.strictEqual(isAuthorizationErrorResponse({
error: 'slow_down',
error_description: 'Polling too fast'
}), true);
assert.strictEqual(isAuthorizationErrorResponse({
error: 'access_denied',
error_description: 'The user denied the request'
}), true);
assert.strictEqual(isAuthorizationErrorResponse({
error: 'expired_token',
error_description: 'The device code has expired'
}), true);
// Valid response with optional error_uri
assert.strictEqual(isAuthorizationErrorResponse({
error: 'invalid_request',
error_description: 'The request is missing a required parameter',
error_uri: 'https://example.com/error'
}), true);
// Invalid cases
assert.strictEqual(isAuthorizationErrorResponse(null), false);
assert.strictEqual(isAuthorizationErrorResponse(undefined), false);
assert.strictEqual(isAuthorizationErrorResponse({}), false);
assert.strictEqual(isAuthorizationErrorResponse({ error_description: 'missing-error' }), false);
assert.strictEqual(isAuthorizationErrorResponse('not an object'), false);
});
});
suite('Scope Matching', () => {
test('scopesMatch should return true for identical scopes', () => {
const scopes1 = ['test', 'scopes'];
const scopes2 = ['test', 'scopes'];
assert.strictEqual(scopesMatch(scopes1, scopes2), true);
});
test('scopesMatch should return true for scopes in different order', () => {
const scopes1 = ['6f1cc985-85e8-487e-b0dd-aa633302a731/.default', 'VSCODE_TENANT:organizations'];
const scopes2 = ['VSCODE_TENANT:organizations', '6f1cc985-85e8-487e-b0dd-aa633302a731/.default'];
assert.strictEqual(scopesMatch(scopes1, scopes2), true);
});
test('scopesMatch should return false for different scopes', () => {
const scopes1 = ['test', 'scopes'];
const scopes2 = ['different', 'scopes'];
assert.strictEqual(scopesMatch(scopes1, scopes2), false);
});
test('scopesMatch should return false for different length arrays', () => {
const scopes1 = ['test'];
const scopes2 = ['test', 'scopes'];
assert.strictEqual(scopesMatch(scopes1, scopes2), false);
});
test('scopesMatch should handle complex Microsoft scopes', () => {
const scopes1 = ['6f1cc985-85e8-487e-b0dd-aa633302a731/.default', 'VSCODE_TENANT:organizations'];
const scopes2 = ['VSCODE_TENANT:organizations', '6f1cc985-85e8-487e-b0dd-aa633302a731/.default'];
assert.strictEqual(scopesMatch(scopes1, scopes2), true);
});
test('scopesMatch should handle empty arrays', () => {
assert.strictEqual(scopesMatch([], []), true);
});
test('scopesMatch should handle single scope arrays', () => {
assert.strictEqual(scopesMatch(['single'], ['single']), true);
assert.strictEqual(scopesMatch(['single'], ['different']), false);
});
test('scopesMatch should handle duplicate scopes within arrays', () => {
const scopes1 = ['scope1', 'scope2', 'scope1'];
const scopes2 = ['scope2', 'scope1', 'scope1'];
assert.strictEqual(scopesMatch(scopes1, scopes2), true);
});
test('scopesMatch should handle undefined values', () => {
assert.strictEqual(scopesMatch(undefined, undefined), true);
assert.strictEqual(scopesMatch(['read'], undefined), false);
assert.strictEqual(scopesMatch(undefined, ['write']), false);
});
test('scopesMatch should handle mixed undefined and empty arrays', () => {
assert.strictEqual(scopesMatch([], undefined), false);
assert.strictEqual(scopesMatch(undefined, []), false);
assert.strictEqual(scopesMatch([], []), true);
});
});
suite('Utility Functions', () => {
test('getDefaultMetadataForUrl should return correct default endpoints', () => {
const authorizationServer = new URL('https://auth.example.com');
const metadata = getDefaultMetadataForUrl(authorizationServer);
assert.strictEqual(metadata.issuer, 'https://auth.example.com/');
assert.strictEqual(metadata.authorization_endpoint, 'https://auth.example.com/authorize');
assert.strictEqual(metadata.token_endpoint, 'https://auth.example.com/token');
assert.strictEqual(metadata.registration_endpoint, 'https://auth.example.com/register');
assert.deepStrictEqual(metadata.response_types_supported, ['code', 'id_token', 'id_token token']);
});
});
suite('Parsing Functions', () => {
test('parseWWWAuthenticateHeader should correctly parse simple header', () => {
const result = parseWWWAuthenticateHeader('Bearer');
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].scheme, 'Bearer');
assert.deepStrictEqual(result[0].params, {});
});
test('parseWWWAuthenticateHeader should correctly parse header with parameters', () => {
const result = parseWWWAuthenticateHeader('Bearer realm="api", error="invalid_token", error_description="The access token expired"');
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].scheme, 'Bearer');
assert.deepStrictEqual(result[0].params, {
realm: 'api',
error: 'invalid_token',
error_description: 'The access token expired'
});
});
test('parseWWWAuthenticateHeader should correctly parse parameters with equal signs', () => {
const result = parseWWWAuthenticateHeader('Bearer resource_metadata="https://example.com/.well-known/oauth-protected-resource?v=1"');
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].scheme, 'Bearer');
assert.deepStrictEqual(result[0].params, {
resource_metadata: 'https://example.com/.well-known/oauth-protected-resource?v=1'
});
});
test('parseWWWAuthenticateHeader should correctly parse multiple', () => {
const result = parseWWWAuthenticateHeader('Bearer realm="api", error="invalid_token", error_description="The access token expired", Basic realm="hi"');
assert.strictEqual(result.length, 2);
assert.strictEqual(result[0].scheme, 'Bearer');
assert.deepStrictEqual(result[0].params, {
realm: 'api',
error: 'invalid_token',
error_description: 'The access token expired'
});
assert.strictEqual(result[1].scheme, 'Basic');
assert.deepStrictEqual(result[1].params, {
realm: 'hi'
});
});
test('getClaimsFromJWT should correctly parse a JWT token', () => {
// Create a sample JWT with known payload
const payload: IAuthorizationJWTClaims = {
jti: 'id123',
sub: 'user123',
iss: 'https://example.com',
aud: 'client123',
exp: 1716239022,
iat: 1716235422,
name: 'Test User'
};
// Create fake but properly formatted JWT
const header = { alg: 'HS256', typ: 'JWT' };
const encodedHeader = encodeBase64(VSBuffer.fromString(JSON.stringify(header)));
const encodedPayload = encodeBase64(VSBuffer.fromString(JSON.stringify(payload)));
const fakeSignature = 'fake-signature';
const token = `${encodedHeader}.${encodedPayload}.${fakeSignature}`;
const claims = getClaimsFromJWT(token);
assert.deepStrictEqual(claims, payload);
});
test('getClaimsFromJWT should throw for invalid JWT format', () => {
// Test with wrong number of parts - should throw "Invalid JWT token format"
assert.throws(() => getClaimsFromJWT('only.two'), /Invalid JWT token format.*three parts/);
assert.throws(() => getClaimsFromJWT('one'), /Invalid JWT token format.*three parts/);
assert.throws(() => getClaimsFromJWT('has.four.parts.here'), /Invalid JWT token format.*three parts/);
});
test('getClaimsFromJWT should throw for invalid header content', () => {
// Create JWT with invalid header
const encodedHeader = encodeBase64(VSBuffer.fromString('not-json'));
const encodedPayload = encodeBase64(VSBuffer.fromString(JSON.stringify({ sub: 'test' })));
const token = `${encodedHeader}.${encodedPayload}.signature`;
assert.throws(() => getClaimsFromJWT(token), /Failed to parse JWT token/);
});
test('getClaimsFromJWT should throw for invalid payload content', () => {
// Create JWT with valid header but invalid payload
const header = { alg: 'HS256', typ: 'JWT' };
const encodedHeader = encodeBase64(VSBuffer.fromString(JSON.stringify(header)));
const encodedPayload = encodeBase64(VSBuffer.fromString('not-json'));
const token = `${encodedHeader}.${encodedPayload}.signature`;
assert.throws(() => getClaimsFromJWT(token), /Failed to parse JWT token/);
});
});
suite('Network Functions', () => {
let sandbox: sinon.SinonSandbox;
let fetchStub: sinon.SinonStub;
setup(() => {
sandbox = sinon.createSandbox();
fetchStub = sandbox.stub(globalThis, 'fetch');
});
teardown(() => {
sandbox.restore();
});
test('fetchDynamicRegistration should make correct request and parse response', async () => {
// Setup successful response
const mockResponse = {
client_id: 'generated-client-id',
client_name: 'Test Client',
client_uri: 'https://code.visualstudio.com'
};
fetchStub.resolves({
ok: true,
json: async () => mockResponse
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
const result = await fetchDynamicRegistration(
serverMetadata,
'Test Client'
);
// Verify fetch was called correctly
assert.strictEqual(fetchStub.callCount, 1);
const [url, options] = fetchStub.firstCall.args;
assert.strictEqual(url, 'https://auth.example.com/register');
assert.strictEqual(options.method, 'POST');
assert.strictEqual(options.headers['Content-Type'], 'application/json');
// Verify request body
const requestBody = JSON.parse(options.body as string);
assert.strictEqual(requestBody.client_name, 'Test Client');
assert.strictEqual(requestBody.client_uri, 'https://code.visualstudio.com');
assert.deepStrictEqual(requestBody.grant_types, ['authorization_code', 'refresh_token', 'urn:ietf:params:oauth:grant-type:device_code']);
assert.deepStrictEqual(requestBody.response_types, ['code']);
assert.deepStrictEqual(requestBody.redirect_uris, [
'https://insiders.vscode.dev/redirect',
'https://vscode.dev/redirect',
'http://127.0.0.1/',
`http://127.0.0.1:${DEFAULT_AUTH_FLOW_PORT}/`
]);
// Verify response is processed correctly
assert.deepStrictEqual(result, mockResponse);
});
test('fetchDynamicRegistration should throw error on non-OK response', async () => {
fetchStub.resolves({
ok: false,
statusText: 'Bad Request',
text: async () => 'Bad Request'
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Registration to https:\/\/auth\.example\.com\/register failed: Bad Request/
);
});
test('fetchDynamicRegistration should throw error on invalid response format', async () => {
fetchStub.resolves({
ok: true,
json: async () => ({ invalid: 'response' }) // Missing required fields
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Invalid authorization dynamic client registration response/
);
});
test('fetchDynamicRegistration should filter grant types based on server metadata', async () => {
// Setup successful response
const mockResponse = {
client_id: 'generated-client-id',
client_name: 'Test Client'
};
fetchStub.resolves({
ok: true,
json: async () => mockResponse
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'client_credentials', 'refresh_token'] // Mix of supported and unsupported
};
await fetchDynamicRegistration(serverMetadata, 'Test Client');
// Verify fetch was called correctly
assert.strictEqual(fetchStub.callCount, 1);
const [, options] = fetchStub.firstCall.args;
// Verify request body contains only the intersection of supported grant types
const requestBody = JSON.parse(options.body as string);
assert.deepStrictEqual(requestBody.grant_types, ['authorization_code', 'refresh_token']); // client_credentials should be filtered out
});
test('fetchDynamicRegistration should use default grant types when server metadata has none', async () => {
// Setup successful response
const mockResponse = {
client_id: 'generated-client-id',
client_name: 'Test Client'
};
fetchStub.resolves({
ok: true,
json: async () => mockResponse
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
// No grant_types_supported specified
};
await fetchDynamicRegistration(serverMetadata, 'Test Client');
// Verify fetch was called correctly
assert.strictEqual(fetchStub.callCount, 1);
const [, options] = fetchStub.firstCall.args;
// Verify request body contains default grant types
const requestBody = JSON.parse(options.body as string);
assert.deepStrictEqual(requestBody.grant_types, ['authorization_code', 'refresh_token', 'urn:ietf:params:oauth:grant-type:device_code']);
});
test('fetchDynamicRegistration should throw error when registration endpoint is missing', async () => {
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
response_types_supported: ['code']
// registration_endpoint is missing
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Server does not support dynamic registration/
);
});
test('fetchDynamicRegistration should handle structured error response', async () => {
const errorResponse = {
error: 'invalid_client_metadata',
error_description: 'The client metadata is invalid'
};
fetchStub.resolves({
ok: false,
text: async () => JSON.stringify(errorResponse)
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Registration to https:\/\/auth\.example\.com\/register failed: invalid_client_metadata: The client metadata is invalid/
);
});
test('fetchDynamicRegistration should handle structured error response without description', async () => {
const errorResponse = {
error: 'invalid_redirect_uri'
};
fetchStub.resolves({
ok: false,
text: async () => JSON.stringify(errorResponse)
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Registration to https:\/\/auth\.example\.com\/register failed: invalid_redirect_uri/
);
});
test('fetchDynamicRegistration should handle malformed JSON error response', async () => {
fetchStub.resolves({
ok: false,
text: async () => 'Invalid JSON {'
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Registration to https:\/\/auth\.example\.com\/register failed: Invalid JSON \{/
);
});
test('fetchDynamicRegistration should include scopes in request when provided', async () => {
const mockResponse = {
client_id: 'generated-client-id',
client_name: 'Test Client'
};
fetchStub.resolves({
ok: true,
json: async () => mockResponse
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await fetchDynamicRegistration(serverMetadata, 'Test Client', ['read', 'write']);
// Verify request includes scopes
const [, options] = fetchStub.firstCall.args;
const requestBody = JSON.parse(options.body as string);
assert.strictEqual(requestBody.scope, 'read write');
});
test('fetchDynamicRegistration should omit scope from request when not provided', async () => {
const mockResponse = {
client_id: 'generated-client-id',
client_name: 'Test Client'
};
fetchStub.resolves({
ok: true,
json: async () => mockResponse
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await fetchDynamicRegistration(serverMetadata, 'Test Client');
// Verify request does not include scope when not provided
const [, options] = fetchStub.firstCall.args;
const requestBody = JSON.parse(options.body as string);
assert.strictEqual(requestBody.scope, undefined);
});
test('fetchDynamicRegistration should handle empty scopes array', async () => {
const mockResponse = {
client_id: 'generated-client-id',
client_name: 'Test Client'
};
fetchStub.resolves({
ok: true,
json: async () => mockResponse
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await fetchDynamicRegistration(serverMetadata, 'Test Client', []);
// Verify request includes empty scope
const [, options] = fetchStub.firstCall.args;
const requestBody = JSON.parse(options.body as string);
assert.strictEqual(requestBody.scope, '');
});
test('fetchDynamicRegistration should handle network fetch failure', async () => {
fetchStub.rejects(new Error('Network error'));
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Network error/
);
});
test('fetchDynamicRegistration should handle response.json() failure', async () => {
fetchStub.resolves({
ok: true,
json: async () => {
throw new Error('JSON parsing failed');
}
} as unknown as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/JSON parsing failed/
);
});
test('fetchDynamicRegistration should handle response.text() failure for error cases', async () => {
fetchStub.resolves({
ok: false,
text: async () => {
throw new Error('Text parsing failed');
}
} as unknown as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Text parsing failed/
);
});
});
suite('Client ID Fallback Scenarios', () => {
let sandbox: sinon.SinonSandbox;
let fetchStub: sinon.SinonStub;
setup(() => {
sandbox = sinon.createSandbox();
fetchStub = sandbox.stub(globalThis, 'fetch');
});
teardown(() => {
sandbox.restore();
});
test('fetchDynamicRegistration should throw specific error for missing registration endpoint', async () => {
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
response_types_supported: ['code']
// registration_endpoint is missing
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
{
message: 'Server does not support dynamic registration'
}
);
});
test('fetchDynamicRegistration should throw specific error for DCR failure', async () => {
fetchStub.resolves({
ok: false,
text: async () => 'DCR not supported'
} as Response);
const serverMetadata: IAuthorizationServerMetadata = {
issuer: 'https://auth.example.com',
registration_endpoint: 'https://auth.example.com/register',
response_types_supported: ['code']
};
await assert.rejects(
async () => await fetchDynamicRegistration(serverMetadata, 'Test Client'),
/Registration to https:\/\/auth\.example\.com\/register failed: DCR not supported/
);
});
});
suite('fetchResourceMetadata', () => {
let sandbox: sinon.SinonSandbox;
let fetchStub: sinon.SinonStub;
setup(() => {
sandbox = sinon.createSandbox();
fetchStub = sandbox.stub();
});
teardown(() => {
sandbox.restore();
});
test('should successfully fetch and validate resource metadata', async () => {
const targetResource = 'https://example.com/api';
const resourceMetadataUrl = 'https://example.com/.well-known/oauth-protected-resource';
const expectedMetadata = {
resource: 'https://example.com/api',
scopes_supported: ['read', 'write']
};
fetchStub.resolves({
status: 200,
json: async () => expectedMetadata,
text: async () => JSON.stringify(expectedMetadata)
});
const result = await fetchResourceMetadata(
targetResource,
resourceMetadataUrl,
{ fetch: fetchStub }
);
assert.deepStrictEqual(result.metadata, expectedMetadata);
assert.strictEqual(result.discoveryUrl, resourceMetadataUrl);
assert.deepStrictEqual(result.errors, []);
assert.strictEqual(fetchStub.callCount, 1);
assert.strictEqual(fetchStub.firstCall.args[0], resourceMetadataUrl);
assert.strictEqual(fetchStub.firstCall.args[1].method, 'GET');
assert.strictEqual(fetchStub.firstCall.args[1].headers['Accept'], 'application/json');
});
test('should include same-origin headers when origins match', async () => {
const targetResource = 'https://example.com/api';
const resourceMetadataUrl = 'https://example.com/.well-known/oauth-protected-resource';
const sameOriginHeaders = {
'X-Test-Header': 'test-value',
'X-Custom-Header': 'value'
};
const expectedMetadata = {
resource: 'https://example.com/api'
};
fetchStub.resolves({
status: 200,
json: async () => expectedMetadata,
text: async () => JSON.stringify(expectedMetadata)
});
const result = await fetchResourceMetadata(
targetResource,
resourceMetadataUrl,
{ fetch: fetchStub, sameOriginHeaders }
);
assert.strictEqual(result.discoveryUrl, resourceMetadataUrl);
const headers = fetchStub.firstCall.args[1].headers;
assert.strictEqual(headers['Accept'], 'application/json');
assert.strictEqual(headers['X-Test-Header'], 'test-value');
assert.strictEqual(headers['X-Custom-Header'], 'value');
});
test('should not include same-origin headers when origins differ', async () => {
const targetResource = 'https://example.com/api';
const resourceMetadataUrl = 'https://other-domain.com/.well-known/oauth-protected-resource';
const sameOriginHeaders = {
'X-Test-Header': 'test-value'
};
const expectedMetadata = {
resource: 'https://example.com/api'
};
fetchStub.resolves({
status: 200,
json: async () => expectedMetadata,
text: async () => JSON.stringify(expectedMetadata)
});
const result = await fetchResourceMetadata(
targetResource,
resourceMetadataUrl,
{ fetch: fetchStub, sameOriginHeaders }
);
assert.strictEqual(result.discoveryUrl, resourceMetadataUrl);
const headers = fetchStub.firstCall.args[1].headers;
assert.strictEqual(headers['Accept'], 'application/json');
assert.strictEqual(headers['X-Test-Header'], undefined);
});
test('should throw error when fetch returns non-200 status', async () => {
const targetResource = 'https://example.com/api';
const resourceMetadataUrl = 'https://example.com/.well-known/oauth-protected-resource';
// Stub all possible URLs to return 404 for robust fallback testing
fetchStub.resolves({
status: 404,
text: async () => 'Not Found'
});
await assert.rejects(
async () => fetchResourceMetadata(targetResource, resourceMetadataUrl, { fetch: fetchStub }),
(error: any) => {
// Should be AggregateError since all URLs fail
assert.ok(error instanceof AggregateError || /Failed to fetch resource metadata from.*404 Not Found/.test(error.message));
return true;
}
);
});
test('should handle error when response.text() throws', async () => {
const targetResource = 'https://example.com/api';
const resourceMetadataUrl = 'https://example.com/.well-known/oauth-protected-resource';
// Stub all possible URLs to return 500 for robust fallback testing
fetchStub.resolves({
status: 500,
statusText: 'Internal Server Error',
text: async () => { throw new Error('Cannot read response'); }
});
await assert.rejects(
async () => fetchResourceMetadata(targetResource, resourceMetadataUrl, { fetch: fetchStub }),
(error: any) => {
// Should be AggregateError since all URLs fail
assert.ok(error instanceof AggregateError || /Failed to fetch resource metadata from.*500 Internal Server Error/.test(error.message));
return true;
}
);
});
test('should throw error when resource property does not match target resource', async () => {
const targetResource = 'https://example.com/api';
const resourceMetadataUrl = 'https://example.com/.well-known/oauth-protected-resource';
const metadata = {
resource: 'https://different.com/api'
};
// Stub all possible URLs to return invalid metadata for robust fallback testing
fetchStub.resolves({