-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathImds.spec.ts
1102 lines (978 loc) · 47.8 KB
/
Imds.spec.ts
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.
*/
import { ManagedIdentityApplication } from "../../../src/client/ManagedIdentityApplication.js";
import { ManagedIdentityConfiguration } from "../../../src/config/Configuration.js";
import {
CAE_CONSTANTS,
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT,
DEFAULT_USER_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT,
IMDS_EXPONENTIAL_STRATEGY_MAX_RETRIES_IN_MS,
IMDS_EXPONENTIAL_STRATEGY_MAX_RETRIES_NUM_REQUESTS,
IMDS_EXPONENTIAL_STRATEGY_TWO_RETRIES_IN_MS,
MANAGED_IDENTITY_IMDS_NETWORK_REQUEST_400_ERROR,
MANAGED_IDENTITY_NETWORK_REQUEST_500_ERROR,
MANAGED_IDENTITY_RESOURCE,
MANAGED_IDENTITY_RESOURCE_BASE,
MANAGED_IDENTITY_RESOURCE_ID,
MANAGED_IDENTITY_RESOURCE_ID_2,
MANAGED_IDENTITY_TOKEN_RETRIEVAL_ERROR_MESSAGE,
ONE_HUNDRED_TIMES_FASTER,
TEST_CONFIG,
TEST_TOKEN_LIFETIMES,
getCacheKey,
} from "../../test_kit/StringConstants.js";
import {
ManagedIdentityNetworkClient,
ManagedIdentityNetworkErrorClient,
networkClient,
userAssignedClientIdConfig,
managedIdentityRequestParams,
systemAssignedConfig,
userAssignedResourceIdConfig,
} from "../../test_kit/ManagedIdentityTestUtils.js";
import {
DEFAULT_MANAGED_IDENTITY_ID,
ManagedIdentityQueryParameters,
ManagedIdentitySourceNames,
} from "../../../src/utils/Constants.js";
import {
AccessTokenEntity,
AuthenticationResult,
CacheHelpers,
ClientConfigurationErrorCodes,
createClientConfigurationError,
DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,
HttpStatus,
ServerError,
TimeUtils,
} from "@azure/msal-common";
import { ManagedIdentityClient } from "../../../src/client/ManagedIdentityClient.js";
import {
ManagedIdentityErrorCodes,
createManagedIdentityError,
} from "../../../src/error/ManagedIdentityError.js";
import { mockCrypto } from "../ClientTestUtils.js";
// NodeJS 16+ provides a built-in version of setTimeout that is promise-based
import { setTimeout } from "timers/promises";
import { ClientCredentialClient } from "../../../src/client/ClientCredentialClient.js";
import { NodeStorage } from "../../../src/cache/NodeStorage.js";
import { CacheKVStore } from "../../../src/cache/serializer/SerializerTypes.js";
import { ManagedIdentityUserAssignedIdQueryParameterNames } from "../../../src/client/ManagedIdentitySources/BaseManagedIdentitySource.js";
import { ImdsRetryPolicy } from "../../../src/retry/ImdsRetryPolicy.js";
describe("Acquires a token successfully via an IMDS Managed Identity", () => {
// IMDS doesn't need environment variables because there is a default IMDS endpoint
afterEach(() => {
delete ManagedIdentityClient["identitySource"];
delete ManagedIdentityApplication["nodeStorage"];
jest.restoreAllMocks();
});
const managedIdentityNetworkErrorClientDefault500 =
new ManagedIdentityNetworkErrorClient();
const managedIdentityNetworkErrorClient400 =
new ManagedIdentityNetworkErrorClient(
MANAGED_IDENTITY_IMDS_NETWORK_REQUEST_400_ERROR,
undefined,
HttpStatus.BAD_REQUEST
);
const userAssignedObjectIdConfig: ManagedIdentityConfiguration = {
system: {
networkClient,
},
managedIdentityIdParams: {
userAssignedObjectId: MANAGED_IDENTITY_RESOURCE_ID,
},
};
describe("User Assigned", () => {
test("acquires a User Assigned Client Id token", async () => {
const sendGetRequestAsyncSpy: jest.SpyInstance = jest.spyOn(
networkClient,
<any>"sendGetRequestAsync"
);
const managedIdentityApplication: ManagedIdentityApplication =
new ManagedIdentityApplication(userAssignedClientIdConfig);
expect(managedIdentityApplication.getManagedIdentitySource()).toBe(
ManagedIdentitySourceNames.DEFAULT_TO_IMDS
);
const networkManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_USER_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
const url: URLSearchParams = new URLSearchParams(
sendGetRequestAsyncSpy.mock.lastCall[0]
);
expect(
url.has(
ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID
)
).toBe(true);
expect(
url.has(
ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017
)
).toBe(false);
});
test("acquires a User Assigned Object Id token", async () => {
const managedIdentityApplication: ManagedIdentityApplication =
new ManagedIdentityApplication(userAssignedObjectIdConfig);
expect(managedIdentityApplication.getManagedIdentitySource()).toBe(
ManagedIdentitySourceNames.DEFAULT_TO_IMDS
);
const networkManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_USER_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
});
test("acquires a User Assigned Resource Id token", async () => {
const sendGetRequestAsyncSpy: jest.SpyInstance = jest.spyOn(
networkClient,
<any>"sendGetRequestAsync"
);
const managedIdentityApplication: ManagedIdentityApplication =
new ManagedIdentityApplication(userAssignedResourceIdConfig);
expect(managedIdentityApplication.getManagedIdentitySource()).toBe(
ManagedIdentitySourceNames.DEFAULT_TO_IMDS
);
const networkManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_USER_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
const url: URLSearchParams = new URLSearchParams(
sendGetRequestAsyncSpy.mock.lastCall[0]
);
expect(
url.has(
ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_IMDS
)
).toBe(true);
expect(
url.get(
ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_IMDS
)
).toEqual(MANAGED_IDENTITY_RESOURCE_ID);
jest.restoreAllMocks();
});
});
describe("System Assigned", () => {
let managedIdentityApplication: ManagedIdentityApplication;
beforeEach(() => {
managedIdentityApplication = new ManagedIdentityApplication(
systemAssignedConfig
);
expect(managedIdentityApplication.getManagedIdentitySource()).toBe(
ManagedIdentitySourceNames.DEFAULT_TO_IMDS
);
});
test("acquires a token", async () => {
const networkManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
});
test("returns an already acquired token from the cache", async () => {
const networkManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
const cachedManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(cachedManagedIdentityResult.fromCache).toBe(true);
expect(cachedManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
});
});
describe("Managed Identity Retry Policy", () => {
let uamiApplication: ManagedIdentityApplication; // user-assigned
let samiApplication: ManagedIdentityApplication; // system-assigned
beforeEach(() => {
jest.spyOn(
ImdsRetryPolicy,
"MIN_EXPONENTIAL_BACKOFF_MS",
"get"
).mockReturnValue(
ImdsRetryPolicy.MIN_EXPONENTIAL_BACKOFF_MS *
ONE_HUNDRED_TIMES_FASTER
);
jest.spyOn(
ImdsRetryPolicy,
"MAX_EXPONENTIAL_BACKOFF_MS",
"get"
).mockReturnValue(
ImdsRetryPolicy.MAX_EXPONENTIAL_BACKOFF_MS *
ONE_HUNDRED_TIMES_FASTER
);
jest.spyOn(
ImdsRetryPolicy,
"EXPONENTIAL_DELTA_BACKOFF_MS",
"get"
).mockReturnValue(
ImdsRetryPolicy.EXPONENTIAL_DELTA_BACKOFF_MS *
ONE_HUNDRED_TIMES_FASTER
);
jest.spyOn(
ImdsRetryPolicy,
"HTTP_STATUS_GONE_RETRY_AFTER_MS",
"get"
).mockReturnValue(
ImdsRetryPolicy.HTTP_STATUS_GONE_RETRY_AFTER_MS *
ONE_HUNDRED_TIMES_FASTER
);
uamiApplication = new ManagedIdentityApplication(
userAssignedClientIdConfig
);
expect(uamiApplication.getManagedIdentitySource()).toBe(
ManagedIdentitySourceNames.DEFAULT_TO_IMDS
);
samiApplication = new ManagedIdentityApplication(
systemAssignedConfig
);
expect(samiApplication.getManagedIdentitySource()).toBe(
ManagedIdentitySourceNames.DEFAULT_TO_IMDS
);
});
test.each([
["UAMI", () => uamiApplication],
["SAMI", () => samiApplication],
])(
"%s: returns a 404 error response from the network request, the first two times",
async (_description, getMIA) => {
const managedIdentityApplication = getMIA();
const managedIdentityNetworkErrorClient404 =
new ManagedIdentityNetworkErrorClient(
MANAGED_IDENTITY_IMDS_NETWORK_REQUEST_400_ERROR,
undefined,
HttpStatus.NOT_FOUND
);
const sendGetRequestAsyncSpy: jest.SpyInstance = jest
.spyOn(networkClient, <any>"sendGetRequestAsync")
.mockReturnValueOnce(
// initial request, will trigger first retry
managedIdentityNetworkErrorClient404.sendGetRequestAsync()
)
.mockReturnValueOnce(
// first retry, will trigger second retry
managedIdentityNetworkErrorClient404.sendGetRequestAsync()
);
const timeBeforeNetworkRequest = new Date();
const networkManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
const timeAfterNetworkRequest = new Date();
/**
* ensure that each retry followed the exponential backoff strategy
* 2 x exponential backoff (1 second -> 2 seconds)
*/
expect(
timeAfterNetworkRequest.valueOf() -
timeBeforeNetworkRequest.valueOf()
).toBeGreaterThanOrEqual(
IMDS_EXPONENTIAL_STRATEGY_TWO_RETRIES_IN_MS *
ONE_HUNDRED_TIMES_FASTER
);
expect(sendGetRequestAsyncSpy).toHaveBeenCalledTimes(3); // request + 2 retries
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_USER_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
}
);
test.each([
["UAMI", () => uamiApplication],
["SAMI", () => samiApplication],
])(
"%s: returns a 410 error response from the network request, the first four times",
async (_description, getMIA) => {
const managedIdentityApplication = getMIA();
const managedIdentityNetworkErrorClient410 =
new ManagedIdentityNetworkErrorClient(
MANAGED_IDENTITY_IMDS_NETWORK_REQUEST_400_ERROR,
undefined,
HttpStatus.GONE
);
const sendGetRequestAsyncSpy: jest.SpyInstance = jest
.spyOn(networkClient, <any>"sendGetRequestAsync")
.mockReturnValueOnce(
// initial request, will trigger first retry
managedIdentityNetworkErrorClient410.sendGetRequestAsync()
)
.mockReturnValueOnce(
// first retry, will trigger second retry
managedIdentityNetworkErrorClient410.sendGetRequestAsync()
)
.mockReturnValueOnce(
// second retry, will trigger third retry
managedIdentityNetworkErrorClient410.sendGetRequestAsync()
)
.mockReturnValueOnce(
// third retry, will trigger fourth retry
managedIdentityNetworkErrorClient410.sendGetRequestAsync()
);
const timeBeforeNetworkRequest = new Date();
const networkManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
const timeAfterNetworkRequest = new Date();
/**
* ensure that each retry followed the exponential backoff strategy
* 7 x linear backoff (10 seconds)
*/
expect(
timeAfterNetworkRequest.valueOf() -
timeBeforeNetworkRequest.valueOf()
).toBeGreaterThanOrEqual(
ImdsRetryPolicy.HTTP_STATUS_GONE_RETRY_AFTER_MS *
4 *
ONE_HUNDRED_TIMES_FASTER
);
expect(sendGetRequestAsyncSpy).toHaveBeenCalledTimes(5); // request + 4 retries
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_USER_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
}
);
test.each([
["UAMI", () => uamiApplication],
["SAMI", () => samiApplication],
])(
"%s: returns a 410 error response from the network request permanently",
async (_description, getMIA) => {
const managedIdentityApplication = getMIA();
const managedIdentityNetworkErrorClient410 =
new ManagedIdentityNetworkErrorClient(
MANAGED_IDENTITY_IMDS_NETWORK_REQUEST_400_ERROR,
undefined,
HttpStatus.GONE
);
const sendGetRequestAsyncSpy: jest.SpyInstance = jest
.spyOn(networkClient, <any>"sendGetRequestAsync")
// permanently override the networkClient's sendGetRequestAsync method to return a 504
.mockReturnValue(
managedIdentityNetworkErrorClient410.sendGetRequestAsync()
);
const timeBeforeNetworkRequest = new Date();
let serverError: ServerError = new ServerError();
try {
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
} catch (e) {
serverError = e as ServerError;
}
const timeAfterNetworkRequest = new Date();
/**
* ensure that each retry followed the exponential backoff strategy
* 7 x linear backoff (10 seconds)
*/
expect(
timeAfterNetworkRequest.valueOf() -
timeBeforeNetworkRequest.valueOf()
).toBeGreaterThanOrEqual(
ImdsRetryPolicy.HTTP_STATUS_GONE_RETRY_AFTER_MS *
7 *
ONE_HUNDRED_TIMES_FASTER
);
expect(
serverError.errorMessage.includes(
MANAGED_IDENTITY_TOKEN_RETRIEVAL_ERROR_MESSAGE
)
).toBe(true);
expect(sendGetRequestAsyncSpy).toHaveBeenCalledTimes(8); // request + 7 retries
}
);
test.each([
["UAMI", () => uamiApplication],
["SAMI", () => samiApplication],
])(
"%s: returns a 5xx (504) error response from the network request permanently",
async (_description, getMIA) => {
const managedIdentityApplication = getMIA();
const managedIdentityNetworkErrorClient504 =
new ManagedIdentityNetworkErrorClient(
MANAGED_IDENTITY_NETWORK_REQUEST_500_ERROR,
undefined,
HttpStatus.GATEWAY_TIMEOUT
);
const sendGetRequestAsyncSpy: jest.SpyInstance = jest
.spyOn(networkClient, <any>"sendGetRequestAsync")
// permanently override the networkClient's sendGetRequestAsync method to return a 504
.mockReturnValue(
managedIdentityNetworkErrorClient504.sendGetRequestAsync()
);
const timeBeforeNetworkRequest = new Date();
let serverError: ServerError = new ServerError();
try {
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
} catch (e) {
serverError = e as ServerError;
}
const timeAfterNetworkRequest = new Date();
/**
* ensure that each retry followed the exponential backoff strategy
* 3 x exponential backoff (1 second -> 2 seconds -> 4 seconds)
*/
expect(
timeAfterNetworkRequest.valueOf() -
timeBeforeNetworkRequest.valueOf()
).toBeGreaterThanOrEqual(
IMDS_EXPONENTIAL_STRATEGY_MAX_RETRIES_IN_MS *
ONE_HUNDRED_TIMES_FASTER
);
expect(
serverError.errorMessage.includes(
MANAGED_IDENTITY_TOKEN_RETRIEVAL_ERROR_MESSAGE
)
).toBe(true);
expect(sendGetRequestAsyncSpy).toHaveBeenCalledTimes(4); // request + 3 retries
}
);
test.each([
["UAMI", () => uamiApplication],
["SAMI", () => samiApplication],
])(
"%s: makes three acquireToken calls on the same managed identity application (which returns a 500 error response from the network request permanently) to ensure that retry policy lifetime is per request",
async (_description, getMIA) => {
const managedIdentityApplication = getMIA();
const sendGetRequestAsyncSpyApp: jest.SpyInstance = jest
.spyOn(networkClient, <any>"sendGetRequestAsync")
// permanently override the networkClient's sendGetRequestAsync method to return a 500
.mockReturnValue(
managedIdentityNetworkErrorClientDefault500.sendGetRequestAsync()
);
try {
await managedIdentityApplication.acquireToken({
resource: "https://graph.microsoft1.com",
});
} catch (e) {
expect(sendGetRequestAsyncSpyApp).toHaveBeenCalledTimes(
IMDS_EXPONENTIAL_STRATEGY_MAX_RETRIES_NUM_REQUESTS
); // request + 3 retries
}
try {
await managedIdentityApplication.acquireToken({
resource: "https://graph.microsoft2.com",
});
} catch (e) {
expect(sendGetRequestAsyncSpyApp).toHaveBeenCalledTimes(
IMDS_EXPONENTIAL_STRATEGY_MAX_RETRIES_NUM_REQUESTS * 2
); // 8 total, 2 x (request + 3 retries)
}
try {
await managedIdentityApplication.acquireToken({
resource: "https://graph.microsoft3.com",
});
} catch (e) {
expect(sendGetRequestAsyncSpyApp).toHaveBeenCalledTimes(
IMDS_EXPONENTIAL_STRATEGY_MAX_RETRIES_NUM_REQUESTS * 3
); // 12 total, 3 x (request + 3 retries)
}
}
);
test.each([
["UAMI", () => uamiApplication],
["SAMI", () => samiApplication],
])(
"%s: ensures that a retry does not happen when the http status code from a failed network response (400) is not included in the list of retriable status codes",
async (_description, getMIA) => {
const managedIdentityApplication = getMIA();
const sendGetRequestAsyncSpyApp: jest.SpyInstance = jest
.spyOn(networkClient, <any>"sendGetRequestAsync")
// permanently override the networkClient's sendGetRequestAsync method to return a 400
.mockReturnValue(
managedIdentityNetworkErrorClient400.sendGetRequestAsync()
);
let serverError: ServerError = new ServerError();
try {
await managedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
} catch (e) {
serverError = e as ServerError;
}
expect(
serverError.errorMessage.includes(
MANAGED_IDENTITY_TOKEN_RETRIEVAL_ERROR_MESSAGE
)
).toBe(true);
expect(sendGetRequestAsyncSpyApp).toHaveBeenCalledTimes(1);
}
);
test.each([
["UAMI", userAssignedClientIdConfig],
["SAMI", systemAssignedConfig],
])(
"%s: ensures that a retry does not happen when the http status code from a failed network response (500) is included in the list of retriable status codes, but the retry policy has been disabled",
async (_description, config) => {
const managedIdentityApplicationNoRetry: ManagedIdentityApplication =
new ManagedIdentityApplication({
system: {
...config.system,
disableInternalRetries: true,
},
});
const sendGetRequestAsyncSpy: jest.SpyInstance = jest
.spyOn(networkClient, <any>"sendGetRequestAsync")
// permanently override the networkClient's sendGetRequestAsync method to return a 500
.mockReturnValue(
managedIdentityNetworkErrorClientDefault500.sendGetRequestAsync()
);
let serverError: ServerError = new ServerError();
try {
await managedIdentityApplicationNoRetry.acquireToken(
managedIdentityRequestParams
);
} catch (e) {
serverError = e as ServerError;
}
expect(
serverError.errorMessage.includes(
MANAGED_IDENTITY_TOKEN_RETRIEVAL_ERROR_MESSAGE
)
).toBe(true);
expect(sendGetRequestAsyncSpy).toHaveBeenCalledTimes(1);
}
);
});
describe("Miscellaneous", () => {
let systemAssignedManagedIdentityApplication: ManagedIdentityApplication;
beforeEach(() => {
systemAssignedManagedIdentityApplication =
new ManagedIdentityApplication(systemAssignedConfig);
expect(
systemAssignedManagedIdentityApplication.getManagedIdentitySource()
).toBe(ManagedIdentitySourceNames.DEFAULT_TO_IMDS);
});
test("acquires a token from the network and then the same token from the cache, then acquires a different token for another scope", async () => {
let networkManagedIdentityResult: AuthenticationResult =
await systemAssignedManagedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
const cachedManagedIdentityResult: AuthenticationResult =
await systemAssignedManagedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(cachedManagedIdentityResult.fromCache).toBe(true);
expect(cachedManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
networkManagedIdentityResult =
await systemAssignedManagedIdentityApplication.acquireToken({
// different resource id means the token will be different
resource: `${MANAGED_IDENTITY_RESOURCE}${Math.random().toString()}`,
});
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
});
test("ignores a cached token when claims are provided and the Managed Identity does not support token revocation, and ensures the token revocation query parameter token_sha256_to_refresh was not included in the network request to the Managed Identity", async () => {
const sendGetRequestAsyncSpy: jest.SpyInstance = jest.spyOn(
networkClient,
<any>"sendGetRequestAsync"
);
const managedIdentityApplication: ManagedIdentityApplication =
new ManagedIdentityApplication({
...systemAssignedConfig,
clientCapabilities: CAE_CONSTANTS.CLIENT_CAPABILITIES,
});
let networkManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
expect(sendGetRequestAsyncSpy.mock.calls.length).toEqual(1);
const firstNetworkRequestUrlParams: URLSearchParams =
new URLSearchParams(sendGetRequestAsyncSpy.mock.lastCall[0]);
expect(
firstNetworkRequestUrlParams.get(
ManagedIdentityQueryParameters.XMS_CC
)
).toEqual(CAE_CONSTANTS.CLIENT_CAPABILITIES.toString());
const cachedManagedIdentityResult: AuthenticationResult =
await managedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(cachedManagedIdentityResult.fromCache).toBe(true);
expect(cachedManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
expect(sendGetRequestAsyncSpy.mock.calls.length).toEqual(1);
networkManagedIdentityResult =
await managedIdentityApplication.acquireToken({
claims: TEST_CONFIG.CLAIMS,
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
expect(sendGetRequestAsyncSpy.mock.calls.length).toEqual(2);
const secondNetworkRequestUrlParams: URLSearchParams =
new URLSearchParams(sendGetRequestAsyncSpy.mock.lastCall[0]);
expect(
secondNetworkRequestUrlParams.has(
ManagedIdentityQueryParameters.SHA256_TOKEN_TO_REFRESH
)
).toBe(false);
});
test("ignores a cached token when forceRefresh is set to true", async () => {
let networkManagedIdentityResult: AuthenticationResult =
await systemAssignedManagedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
const cachedManagedIdentityResult: AuthenticationResult =
await systemAssignedManagedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(cachedManagedIdentityResult.fromCache).toBe(true);
expect(cachedManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
networkManagedIdentityResult =
await systemAssignedManagedIdentityApplication.acquireToken({
forceRefresh: true,
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
});
test("proactively refreshes a token in the background when its refresh_in value is expired.", async () => {
let networkManagedIdentityResult: AuthenticationResult =
await systemAssignedManagedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(networkManagedIdentityResult.fromCache).toBe(false);
expect(networkManagedIdentityResult.accessToken).toEqual(
DEFAULT_SYSTEM_ASSIGNED_MANAGED_IDENTITY_AUTHENTICATION_RESULT.accessToken
);
const nowSeconds: number = TimeUtils.nowSeconds();
const expiredRefreshOn: number = nowSeconds - 3600;
const fakeAccessTokenEntity: AccessTokenEntity =
CacheHelpers.createAccessTokenEntity(
"", // homeAccountId
"https://login.microsoftonline.com/common/", // environment
"thisIs.an.accessT0ken", // accessToken
DEFAULT_MANAGED_IDENTITY_ID, // clientId
"managed_identity", // tenantId
[MANAGED_IDENTITY_RESOURCE_BASE].toString(), // scopes
nowSeconds + 3600, // expiresOn
nowSeconds + 3600, // extExpiresOn
mockCrypto.base64Decode, // cryptoUtils
expiredRefreshOn // refreshOn
);
jest.spyOn(
ClientCredentialClient.prototype,
<any>"readAccessTokenFromCache"
).mockReturnValueOnce(fakeAccessTokenEntity);
let cachedManagedIdentityResult: AuthenticationResult =
await systemAssignedManagedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(cachedManagedIdentityResult.fromCache).toBe(true);
expect(cachedManagedIdentityResult.refreshOn).toEqual(
new Date(expiredRefreshOn * 1000)
);
expect(
TimeUtils.isTokenExpired(
(
cachedManagedIdentityResult.refreshOn !== undefined &&
cachedManagedIdentityResult.refreshOn.getTime() / 1000
).toString(),
DEFAULT_TOKEN_RENEWAL_OFFSET_SEC
)
).toBe(true);
// wait two seconds
await setTimeout(2000);
// get the token from the cache again, but it should be refeshed after waiting two seconds
cachedManagedIdentityResult =
await systemAssignedManagedIdentityApplication.acquireToken({
resource: MANAGED_IDENTITY_RESOURCE,
});
expect(cachedManagedIdentityResult.fromCache).toBe(true);
expect(cachedManagedIdentityResult.refreshOn).not.toEqual(
new Date(expiredRefreshOn * 1000)
);
expect(
TimeUtils.isTokenExpired(
(
cachedManagedIdentityResult.refreshOn !== undefined &&
cachedManagedIdentityResult.refreshOn.getTime() / 1000
).toString(),
DEFAULT_TOKEN_RENEWAL_OFFSET_SEC
)
).toBe(false);
}, 10000); // double the timeout value for this test because it waits two seconds in between the acquireToken call and the cache lookup
test("ensures an ISO 8601 date returned by the Managed Identity is converted to a Unix timestamp (seconds since epoch)", async () => {
// get an ISO 8601 date 3 hours in the future
// (the default length of time in ManagedIdentityNetworkClient's getSuccessResponse())
const threeHoursInMilliseconds =
TEST_TOKEN_LIFETIMES.DEFAULT_EXPIRES_IN * 3 * 1000;
const now = new Date();
now.setTime(now.getTime() + threeHoursInMilliseconds);
const isoDate = now.toISOString();
jest.spyOn(
networkClient,
<any>"sendGetRequestAsync"
).mockReturnValue(networkClient.getSuccessResponse(isoDate));
const { expiresOn } =
await systemAssignedManagedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
expect(expiresOn?.toISOString() === isoDate).toBe(true);
});
test("requests three tokens with two different resources while switching between user and system assigned, then requests them again to verify they are retrieved from the cache, then verifies that their cache keys are correct", async () => {
// the imported systemAssignedManagedIdentityApplication is the default System Assigned Managed Identity Application.
// for reference, in this case it is equivalent to systemAssignedManagedIdentityApplicationResource1
const userAssignedClientIdManagedIdentityApplicationResource1: ManagedIdentityApplication =
new ManagedIdentityApplication({
system: {
networkClient,
},
managedIdentityIdParams: {
userAssignedClientId: MANAGED_IDENTITY_RESOURCE_ID,
},
});
expect(
userAssignedClientIdManagedIdentityApplicationResource1.getManagedIdentitySource()
).toBe(ManagedIdentitySourceNames.DEFAULT_TO_IMDS);
const userAssignedObjectIdManagedIdentityApplicationResource2: ManagedIdentityApplication =
new ManagedIdentityApplication({
system: {
networkClient: new ManagedIdentityNetworkClient(
MANAGED_IDENTITY_RESOURCE_ID_2
),
},
managedIdentityIdParams: {
userAssignedObjectId: MANAGED_IDENTITY_RESOURCE_ID_2,
},
});
expect(
userAssignedObjectIdManagedIdentityApplicationResource2.getManagedIdentitySource()
).toBe(ManagedIdentitySourceNames.DEFAULT_TO_IMDS);
// ********** begin: return access tokens from a network request **********
// resource R1 for system assigned - returned from a network request
let networkManagedIdentityResult: AuthenticationResult =
await systemAssignedManagedIdentityApplication.acquireToken(
managedIdentityRequestParams
);
expect(networkManagedIdentityResult.fromCache).toBe(false);
// not needed in production, but this resets the network client for the next application
// since the network client is mocked for each application
delete ManagedIdentityClient["identitySource"];
// resource R2 for system assigned - returned from a network request
networkManagedIdentityResult =
await userAssignedClientIdManagedIdentityApplicationResource1.acquireToken(
managedIdentityRequestParams
);
expect(networkManagedIdentityResult.fromCache).toBe(false);
// not needed in production, but this resets the network client for the next application
// since the network client is mocked for each application
delete ManagedIdentityClient["identitySource"];
// resource R2 for user assigned - returned from a network request
networkManagedIdentityResult =
await userAssignedObjectIdManagedIdentityApplicationResource2.acquireToken(
managedIdentityRequestParams
);
expect(networkManagedIdentityResult.fromCache).toBe(false);
// ********** end: return access tokens from a network request **********
// ********** begin: return access tokens from the cache **********
// resource R1 for system assigned - new application (to prove static cache persists), but same request as before, returned from the cache this time
const systemAssignedManagedIdentityApplicationClone: ManagedIdentityApplication =
new ManagedIdentityApplication(systemAssignedConfig);
expect(
systemAssignedManagedIdentityApplicationClone.getManagedIdentitySource()
).toBe(ManagedIdentitySourceNames.DEFAULT_TO_IMDS);
let cachedManagedIdentityResult: AuthenticationResult =
await systemAssignedManagedIdentityApplicationClone.acquireToken(
{
resource: MANAGED_IDENTITY_RESOURCE,
}
);
expect(cachedManagedIdentityResult.fromCache).toBe(true);
// resource R2 for system assigned - new application (to prove static cache persists), but same request as before, returned from the cache this time
const userAssignedClientIdManagedIdentityApplicationResource1Clone: ManagedIdentityApplication =
new ManagedIdentityApplication({
system: {
networkClient,
},
managedIdentityIdParams: {
userAssignedClientId: MANAGED_IDENTITY_RESOURCE_ID,
},
});
expect(
userAssignedClientIdManagedIdentityApplicationResource1Clone.getManagedIdentitySource()
).toBe(ManagedIdentitySourceNames.DEFAULT_TO_IMDS);
cachedManagedIdentityResult =
await userAssignedClientIdManagedIdentityApplicationResource1Clone.acquireToken(
{
resource: MANAGED_IDENTITY_RESOURCE,
}
);
expect(cachedManagedIdentityResult.fromCache).toBe(true);
// resource R2 for user assigned - new application (to prove static cache persists), but same request as before, returned from the cache this time
const userAssignedObjectIdManagedIdentityApplicationResource2Clone: ManagedIdentityApplication =
new ManagedIdentityApplication({
system: {
networkClient: new ManagedIdentityNetworkClient(
MANAGED_IDENTITY_RESOURCE_ID_2 // client id
),
},
managedIdentityIdParams: {
userAssignedObjectId: MANAGED_IDENTITY_RESOURCE_ID_2,
},
});
expect(
userAssignedObjectIdManagedIdentityApplicationResource2Clone.getManagedIdentitySource()
).toBe(ManagedIdentitySourceNames.DEFAULT_TO_IMDS);
cachedManagedIdentityResult =
await userAssignedObjectIdManagedIdentityApplicationResource2Clone.acquireToken(
{
resource: MANAGED_IDENTITY_RESOURCE,
}
);
expect(cachedManagedIdentityResult.fromCache).toBe(true);
// ********** end: return access tokens from the cache **********
const cache: CacheKVStore = (
ManagedIdentityApplication["nodeStorage"] as NodeStorage
)["cache"];
// the cache is static, and should have persisted across all six of the managed identity applications in this test
// there should be three items in the cache
expect(Object.keys(cache).length).toEqual(3);
const cacheKeys: Array<string> = [
getCacheKey(),
getCacheKey(MANAGED_IDENTITY_RESOURCE_ID),
getCacheKey(MANAGED_IDENTITY_RESOURCE_ID_2),
];
// verify the cache keys
const allCacheKeysExistandAreCorrect: boolean = cacheKeys.every(