-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathManagedIdentityTests.java
More file actions
912 lines (695 loc) · 45.3 KB
/
ManagedIdentityTests.java
File metadata and controls
912 lines (695 loc) · 45.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.aad.msal4j;
import com.nimbusds.oauth2.sdk.util.URLUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.junit.jupiter.MockitoExtension;
import java.net.SocketException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static com.microsoft.aad.msal4j.ManagedIdentitySourceType.*;
import static com.microsoft.aad.msal4j.MsalError.MANAGED_IDENTITY_FILE_READ_ERROR;
import static com.microsoft.aad.msal4j.MsalError.MANAGED_IDENTITY_REQUEST_FAILED;
import static com.microsoft.aad.msal4j.MsalErrorMessage.*;
import static java.util.Collections.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
class ManagedIdentityTests {
@BeforeAll
static void setupRetryPolicies() {
// Set retry delays to 1ms for faster test execution
ManagedIdentityRetryPolicy.setRetryDelayMs(1);
IMDSRetryPolicy.setRetryDelayMs(1);
}
@AfterAll
static void resetRetryPolicies() {
// Reset retry delays to default values
ManagedIdentityRetryPolicy.resetToDefaults();
IMDSRetryPolicy.resetToDefaults();
}
@AfterAll
static void resetServiceFabricHttpClient() {
ServiceFabricManagedIdentitySource.resetHttpClient();
}
private String getSuccessfulResponse(String resource) {
long expiresOn = (System.currentTimeMillis() / 1000) + (24 * 3600);//A long-lived, 24 hour token
return "{\"access_token\":\"accesstoken\",\"expires_on\":\"" + expiresOn + "\",\"resource\":\"" + resource + "\",\"token_type\":" +
"\"Bearer\",\"client_id\":\"client_id\"}";
}
private String getSuccessfulResponseWithISOExpiresOn(String resource) {
String expiresOn = DateTimeFormatter.ISO_INSTANT.format(Instant.now().plus(24, ChronoUnit.HOURS));//A long-lived, 24 hour token
return "{\"access_token\":\"accesstoken\",\"expires_on\":\"" + expiresOn + "\",\"resource\":\"" + resource + "\",\"token_type\":" +
"\"Bearer\",\"client_id\":\"client_id\"}";
}
private HttpRequest expectedRequest(ManagedIdentitySourceType source, String resource) {
return expectedRequest(source, resource, ManagedIdentityId.systemAssigned(), false, false, null);
}
private HttpRequest expectedRequest(ManagedIdentitySourceType source, String resource, ManagedIdentityId id) {
return expectedRequest(source, resource, id, false, false, null);
}
private HttpRequest expectedRequest(ManagedIdentitySourceType source, String resource,
boolean hasClaims, boolean hasCapabilities, String expectedTokenHash) {
return expectedRequest(source, resource, ManagedIdentityId.systemAssigned(), hasClaims, hasCapabilities, expectedTokenHash);
}
private HttpRequest expectedRequest(ManagedIdentitySourceType source, String resource,
ManagedIdentityId id, boolean hasClaims, boolean hasCapabilities, String expectedTokenHash) {
// Create maps for headers and query parameters
Map<String, String> headers = new HashMap<>();
Map<String, List<String>> queryParameters = new HashMap<>();
// Add resource to query parameters (common for all sources)
queryParameters.put("resource", singletonList(resource));
// Handle claims and capabilities if supported
if (Constants.TOKEN_REVOCATION_SUPPORTED_ENVIRONMENTS.contains(source)) {
if (hasCapabilities) {
queryParameters.put(Constants.CLIENT_CAPABILITY_REQUEST_PARAM, singletonList("cp1"));
}
if (hasClaims) {
queryParameters.put(Constants.TOKEN_HASH_CLAIM, singletonList(expectedTokenHash));
}
}
// Configure source-specific parameters
String endpoint = configureSourceSpecificParameters(source, headers, queryParameters);
// Configure idType-specific parameters
if (id.getIdType() != ManagedIdentityId.systemAssigned().getIdType()) {
configureIdentitySpecificParameters(id, queryParameters);
}
if (!queryParameters.isEmpty()) {
endpoint = endpoint + "?" + URLUtils.serializeParameters(queryParameters);
}
return new HttpRequest(HttpMethod.GET, endpoint, headers);
}
private String configureSourceSpecificParameters(ManagedIdentitySourceType source,
Map<String, String> headers,
Map<String, List<String>> queryParameters) {
switch (source) {
case APP_SERVICE:
queryParameters.put("api-version", singletonList("2019-08-01"));
headers.put("X-IDENTITY-HEADER", "secret");
return ManagedIdentityTestConstants.APP_SERVICE_ENDPOINT;
case CLOUD_SHELL:
headers.put("ContentType", "application/x-www-form-urlencoded");
headers.put("Metadata", "true");
return ManagedIdentityTestConstants.CLOUDSHELL_ENDPOINT;
case AZURE_ARC:
queryParameters.put("api-version", singletonList("2019-11-01"));
headers.put("Metadata", "true");
return ManagedIdentityTestConstants.AZURE_ARC_ENDPOINT;
case SERVICE_FABRIC:
queryParameters.put("api-version", singletonList("2019-07-01-preview"));
headers.put("secret", "secret");
return ManagedIdentityTestConstants.SERVICE_FABRIC_ENDPOINT;
case IMDS:
case NONE:
case DEFAULT_TO_IMDS:
default:
queryParameters.put("api-version", singletonList("2018-02-01"));
headers.put("Metadata", "true");
return ManagedIdentityTestConstants.IMDS_ENDPOINT;
}
}
private void configureIdentitySpecificParameters(ManagedIdentityId id, Map<String, List<String>> queryParameters) {
switch (id.getIdType()) {
case SYSTEM_ASSIGNED:
break;
case CLIENT_ID:
queryParameters.put("client_id", singletonList(id.getUserAssignedId()));
break;
case RESOURCE_ID:
if (ManagedIdentityClient.getManagedIdentitySource() == ManagedIdentitySourceType.IMDS) {
queryParameters.put(Constants.MANAGED_IDENTITY_RESOURCE_ID_IMDS, Collections.singletonList(id.getUserAssignedId()));
} else {
queryParameters.put(Constants.MANAGED_IDENTITY_RESOURCE_ID, Collections.singletonList(id.getUserAssignedId()));
}
break;
case OBJECT_ID:
queryParameters.put("object_id", singletonList(id.getUserAssignedId()));
break;
default:
throw new IllegalStateException("Unexpected value: " + id.getIdType());
}
}
private HttpResponse expectedResponse(int statusCode, String response) {
HttpResponse httpResponse = new HttpResponse();
httpResponse.statusCode(statusCode);
httpResponse.body(response);
return httpResponse;
}
abstract class BaseManagedIdentityTest {
protected ManagedIdentityApplication miApp;
protected DefaultHttpClient httpClientMock;
protected IEnvironmentVariables environmentVariables;
void setUpCommonTest(ManagedIdentitySourceType source, String endpoint, ManagedIdentityId idType) {
initEnvironmentVariables(source, endpoint);
initHttpClientMock(source);
initManagedIdentityApplication(idType);
}
void initEnvironmentVariables(ManagedIdentitySourceType source, String endpoint) {
environmentVariables = new EnvironmentVariablesHelper(source, endpoint);
ManagedIdentityApplication.setEnvironmentVariables(environmentVariables);
}
void initHttpClientMock(ManagedIdentitySourceType source) {
httpClientMock = mock(DefaultHttpClient.class);
if (source == SERVICE_FABRIC) {
ServiceFabricManagedIdentitySource.setHttpClient(httpClientMock);
}
}
void initManagedIdentityApplication(ManagedIdentityId idType) {
miApp = ManagedIdentityApplication
.builder(idType)
.httpClient(httpClientMock)
.build();
// ManagedIdentityApplication uses a static token cache, avoid cross test pollution by clearing it
miApp.tokenCache().accessTokens.clear();
}
void setUpTestWithoutHttpClientMock(ManagedIdentitySourceType source, String endpoint) {
initEnvironmentVariables(source, endpoint);
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.build();
// ManagedIdentityApplication uses a static token cache, avoid cross test pollution by clearing it
miApp.tokenCache().accessTokens.clear();
}
void assertTokenFromIdentityProvider(IAuthenticationResult result) {
assertNotNull(result.accessToken());
assertEquals(TokenSource.IDENTITY_PROVIDER, result.metadata().tokenSource());
}
void assertTokenFromCache(IAuthenticationResult result) {
assertNotNull(result.accessToken());
assertEquals(TokenSource.CACHE, result.metadata().tokenSource());
}
void assertMsalServiceException(CompletableFuture<IAuthenticationResult> future,
ManagedIdentitySourceType expectedSource,
String expectedErrorCode) {
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalServiceException.class, ex.getCause());
MsalServiceException msalException = (MsalServiceException) ex.getCause();
assertEquals(expectedSource.name(), msalException.managedIdentitySource());
assertEquals(expectedErrorCode, msalException.errorCode());
}
void assertMsalClientException(CompletableFuture<IAuthenticationResult> future,
String expectedErrorCode) {
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalClientException.class, ex.getCause());
MsalClientException msalException = (MsalClientException) ex.getCause();
assertEquals(expectedErrorCode, msalException.errorCode());
}
CompletableFuture<IAuthenticationResult> acquireTokenCommon(String resource) throws Exception {
return miApp.acquireTokenForManagedIdentity(
ManagedIdentityParameters.builder(resource)
.build());
}
}
@Nested
class TokenAcquisitionAndCachingTests extends BaseManagedIdentityTest {
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createData")
void managedIdentityTest_SystemAssigned_SuccessfulResponse(ManagedIdentitySourceType source, String endpoint, String resource) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(any())).thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(resource)));
IAuthenticationResult result = acquireTokenCommon(resource).get();
assertTokenFromIdentityProvider(result);
result = acquireTokenCommon(resource).get();
assertTokenFromCache(result);
verify(httpClientMock, times(1)).send(any());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataUserAssigned")
void managedIdentityTest_UserAssigned_SuccessfulResponse(ManagedIdentitySourceType source, String endpoint, ManagedIdentityId id) throws Exception {
setUpCommonTest(source, endpoint, id);
when(httpClientMock.send(expectedRequest(source, ManagedIdentityTestConstants.RESOURCE, id)))
.thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
IAuthenticationResult result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromIdentityProvider(result);
verify(httpClientMock, times(1)).send(any());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataError")
void managedIdentity_SharedCache(ManagedIdentitySourceType source, String endpoint) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(any())).thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
ManagedIdentityApplication miApp2 = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.httpClient(httpClientMock)
.build();
IAuthenticationResult resultMiApp1 = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromIdentityProvider(resultMiApp1);
IAuthenticationResult resultMiApp2 = miApp2.acquireTokenForManagedIdentity(
ManagedIdentityParameters.builder(ManagedIdentityTestConstants.RESOURCE)
.build()).get();
assertTokenFromCache(resultMiApp2);
//acquireTokenForManagedIdentity does a cache lookup by default, and all ManagedIdentityApplication's share a cache,
// so calling acquireTokenForManagedIdentity with the same parameters in two different ManagedIdentityApplications
// should return the same token
assertEquals(resultMiApp1.accessToken(), resultMiApp2.accessToken());
verify(httpClientMock, times(1)).send(any());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createData")
void managedIdentityTest_DifferentScopes_RequestsNewToken(ManagedIdentitySourceType source, String endpoint) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(any())).thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
String anotherResource = "https://graph.microsoft.com";
when(httpClientMock.send(expectedRequest(source, anotherResource))).thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
IAuthenticationResult result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromIdentityProvider(result);
result = acquireTokenCommon(anotherResource).get();
assertTokenFromIdentityProvider(result);
verify(httpClientMock, times(2)).send(any());
}
}
@Nested
class ManagedIdentityBehaviorTests extends BaseManagedIdentityTest {
//Tests covering specific behavior/scenarios/use cases/etc. for Managed Identity flows
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataError")
void managedIdentityTest_WithClaims(ManagedIdentitySourceType source, String endpoint) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(any())).thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
String claimsJson = "{\"default\":\"claim\"}";
// First call, get the token from the identity provider.
IAuthenticationResult result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromIdentityProvider(result);
// Second call, get the token from the cache without passing the claims.
result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromCache(result);
String expectedTokenHash = StringHelper.createSha256HashHexString(result.accessToken());
when(httpClientMock.send(expectedRequest(source, ManagedIdentityTestConstants.RESOURCE, true, false, expectedTokenHash)))
.thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
// Third call, when claims are passed bypass the cache.
result = miApp.acquireTokenForManagedIdentity(
ManagedIdentityParameters.builder(ManagedIdentityTestConstants.RESOURCE)
.claims(claimsJson)
.build()).get();
assertTokenFromIdentityProvider(result);
verify(httpClientMock, times(2)).send(any());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataError")
void managedIdentityTest_WithCapabilitiesOnly(ManagedIdentitySourceType source, String endpoint) throws Exception {
initEnvironmentVariables(source, endpoint);
initHttpClientMock(source);
when(httpClientMock.send(expectedRequest(source, ManagedIdentityTestConstants.RESOURCE, false, true, null)))
.thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.httpClient(httpClientMock)
.clientCapabilities(singletonList("cp1"))
.build();
miApp.tokenCache.accessTokens.clear();
// First call, get the token from the identity provider.
IAuthenticationResult result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromIdentityProvider(result);
// Second call, get the token from the cache without passing the claims.
result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromCache(result);
verify(httpClientMock, times(1)).send(any());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataError")
void managedIdentity_ClaimsAndCapabilities(ManagedIdentitySourceType source, String endpoint) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(expectedRequest(source, ManagedIdentityTestConstants.RESOURCE, false, true, null)))
.thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.clientCapabilities(singletonList("cp1"))
.httpClient(httpClientMock)
.build();
String claimsJson = "{\"default\":\"claim\"}";
// First call, get the token from the identity provider.
IAuthenticationResult result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromIdentityProvider(result);
// Second call, get the token from the cache without passing the claims.
result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromCache(result);
String expectedTokenHash = StringHelper.createSha256HashHexString(result.accessToken());
when(httpClientMock.send(expectedRequest(source, ManagedIdentityTestConstants.RESOURCE, true, true, expectedTokenHash)))
.thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
// Third call, when claims are passed bypass the cache.
result = miApp.acquireTokenForManagedIdentity(
ManagedIdentityParameters.builder(ManagedIdentityTestConstants.RESOURCE)
.claims(claimsJson)
.build()).get();
assertTokenFromIdentityProvider(result);
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataGetSource")
void managedIdentity_GetManagedIdentitySource(ManagedIdentitySourceType source, String endpoint, ManagedIdentitySourceType expectedSource) {
setUpTestWithoutHttpClientMock(source, endpoint);
ManagedIdentitySourceType miClientSourceType = ManagedIdentityClient.getManagedIdentitySource();
ManagedIdentitySourceType miAppSourceType = ManagedIdentityApplication.getManagedIdentitySource();
assertEquals(expectedSource, miClientSourceType);
assertEquals(expectedSource, miAppSourceType);
}
@Test
void managedIdentityTest_RefreshOnHalfOfExpiresOn() throws Exception {
//All managed identity flows use the same AcquireTokenByManagedIdentitySupplier where refreshOn is set,
// so any of the MI options should let us verify that it's being set correctly
setUpCommonTest(APP_SERVICE, ManagedIdentityTestConstants.APP_SERVICE_ENDPOINT, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(expectedRequest(APP_SERVICE, ManagedIdentityTestConstants.RESOURCE))).thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
AuthenticationResult result = (AuthenticationResult) acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
long timestampSeconds = (System.currentTimeMillis() / 1000);
long expectedRefreshIn = result.refreshOn() - timestampSeconds;
long actualRefreshIn = (result.expiresOn() - timestampSeconds)/2;
assertTokenFromIdentityProvider(result);
//Allow a few seconds of difference to account for execution time
assertTrue((actualRefreshIn - expectedRefreshIn) <= 5);
verify(httpClientMock, times(1)).send(any());
}
@Test
void managedIdentityTest_ISOExpiresOn() throws Exception {
//All managed identity flows use the same AcquireTokenByManagedIdentitySupplier where refreshOn is set,
// so any of the MI options should let us verify that it's being set correctly
setUpCommonTest(APP_SERVICE, ManagedIdentityTestConstants.APP_SERVICE_ENDPOINT, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(expectedRequest(ManagedIdentitySourceType.APP_SERVICE, ManagedIdentityTestConstants.RESOURCE))).thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponseWithISOExpiresOn(ManagedIdentityTestConstants.RESOURCE)));
AuthenticationResult result = (AuthenticationResult) miApp.acquireTokenForManagedIdentity(
ManagedIdentityParameters.builder(ManagedIdentityTestConstants.RESOURCE)
.build()).get();
// Calculate what the expected expiration time should be
long expectedExpiresOn = System.currentTimeMillis() / 1000 + (24 * 3600); // 24 hours from now, used in getSuccessfulResponseWithISOExpiresOn
assertTokenFromIdentityProvider(result);
//Allow a few seconds of difference to account for execution time
assertTrue((result.expiresOn() - expectedExpiresOn) <= 5);
verify(httpClientMock, times(1)).send(any());
}
}
@Nested
class ErrorHandlingTests extends BaseManagedIdentityTest {
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createData")
void managedIdentityTest_SuccessfulResponse_WithInvalidJson(ManagedIdentitySourceType source, String endpoint, String resource) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(expectedRequest(source, resource))).thenReturn(expectedResponse(HttpStatus.HTTP_OK, ManagedIdentityTestConstants.RESPONSE_MALFORMED_JSON));
assertMsalServiceException(acquireTokenCommon(resource), source, MsalError.MANAGED_IDENTITY_RESPONSE_PARSE_FAILURE);
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataUserAssignedNotSupported")
void managedIdentityTest_UserAssigned_NotSupported(ManagedIdentitySourceType source, String endpoint, ManagedIdentityId id) throws Exception {
setUpCommonTest(source, endpoint, id);
assertMsalServiceException(acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE), source, MsalError.USER_ASSIGNED_MANAGED_IDENTITY_NOT_SUPPORTED);
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataWrongScope")
void managedIdentityTest_WrongScopes(ManagedIdentitySourceType source, String endpoint, String resource) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
if (environmentVariables.getEnvironmentVariable("SourceType").equals(CLOUD_SHELL.toString())) {
when(httpClientMock.send(expectedRequest(source, resource))).thenReturn(expectedResponse(HttpStatus.HTTP_INTERNAL_ERROR, ManagedIdentityTestConstants.CLOUDSHELL_ERROR_RESPONSE));
} else {
when(httpClientMock.send(expectedRequest(source, resource))).thenReturn(expectedResponse(HttpStatus.HTTP_INTERNAL_ERROR, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_500));
}
assertMsalServiceException(acquireTokenCommon(resource), source, MsalError.MANAGED_IDENTITY_REQUEST_FAILED);
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataWrongScope")
void managedIdentityTest_Retry(ManagedIdentitySourceType source, String endpoint, String resource) throws Exception {
IEnvironmentVariables environmentVariables = new EnvironmentVariablesHelper(source, endpoint);
ManagedIdentityApplication.setEnvironmentVariables(environmentVariables);
DefaultHttpClientManagedIdentity httpClientMock = mock(DefaultHttpClientManagedIdentity.class);
if (source == SERVICE_FABRIC) {
ServiceFabricManagedIdentitySource.setHttpClient(httpClientMock);
}
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.httpClient(httpClientMock)
.build();
//Several specific 4xx and 5xx errors, such as 500, should trigger MSAL's retry logic
when(httpClientMock.send(expectedRequest(source, resource))).thenReturn(expectedResponse(HttpStatus.HTTP_INTERNAL_ERROR, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_500));
try {
acquireTokenCommon(resource).get();
} catch (Exception exception) {
assert(exception.getCause() instanceof MsalServiceException);
//There should be three retries for certain MSI error codes, so there will be four invocations of
// HttpClient's send method: the original call, and the three retries
verify(httpClientMock, times(4)).send(any());
}
clearInvocations(httpClientMock);
//Status codes that aren't on the list, such as 123, should not cause a retry
when(httpClientMock.send(expectedRequest(source, resource))).thenReturn(expectedResponse(123, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_NORETRY));
try {
acquireTokenCommon(resource).get();
} catch (Exception exception) {
assert(exception.getCause() instanceof MsalServiceException);
//Because there was no retry, there should only be one invocation of HttpClient's send method
verify(httpClientMock, times(1)).send(any());
return;
}
fail("MsalServiceException is expected but not thrown.");
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataWrongScope")
void managedIdentityTest_RetriesDisabled(ManagedIdentitySourceType source, String endpoint, String resource) throws Exception {
IEnvironmentVariables environmentVariables = new EnvironmentVariablesHelper(source, endpoint);
ManagedIdentityApplication.setEnvironmentVariables(environmentVariables);
DefaultHttpClientManagedIdentity httpClientMock = mock(DefaultHttpClientManagedIdentity.class);
if (source == SERVICE_FABRIC) {
ServiceFabricManagedIdentitySource.setHttpClient(httpClientMock);
}
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.httpClient(httpClientMock)
.disableInternalRetries()
.build();
//Several specific 4xx and 5xx errors, such as 500, should trigger MSAL's retry logic
when(httpClientMock.send(expectedRequest(source, resource))).thenReturn(expectedResponse(500, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_500));
try {
acquireTokenCommon(resource).get();
} catch (Exception exception) {
assert(exception.getCause() instanceof MsalServiceException);
//But because retries are disabled at the app level, there should be no retries for any source except Service Fabric, which uses its own HttpClient
if (source == SERVICE_FABRIC) {
verify(httpClientMock, times(4)).send(any());
} else {
verify(httpClientMock, times(1)).send(any());
}
}
}
@Test
void managedIdentityTest_IMDSRetry() throws Exception {
IEnvironmentVariables environmentVariables = new EnvironmentVariablesHelper(IMDS, ManagedIdentityTestConstants.IMDS_ENDPOINT);
ManagedIdentityApplication.setEnvironmentVariables(environmentVariables);
DefaultHttpClientManagedIdentity httpClientMock = mock(DefaultHttpClientManagedIdentity.class);
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.httpClient(httpClientMock)
.build();
// IMDS has different retry logic for certain status codes, such as 410
when(httpClientMock.send(expectedRequest(IMDS, ManagedIdentityTestConstants.RESOURCE))).thenReturn(expectedResponse(HttpStatus.HTTP_GONE, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_500));
try {
acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
} catch (Exception exception) {
assert(exception.getCause() instanceof MsalServiceException);
//A 410 status code should trigger the linear retry policy, with a total of 8 attempts (1 original + 7 retries)
verify(httpClientMock, times(8)).send(any());
}
clearInvocations(httpClientMock);
when(httpClientMock.send(expectedRequest(IMDS, ManagedIdentityTestConstants.RESOURCE))).thenReturn(expectedResponse(HttpStatus.HTTP_INTERNAL_ERROR, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_500));
try {
acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
} catch (Exception exception) {
assert(exception.getCause() instanceof MsalServiceException);
//A 500 status code should trigger the exponential retry policy, with a total of 4 attempts (1 original + 3 retries)
verify(httpClientMock, times(4)).send(any());
return;
}
fail("MsalServiceException is expected but not thrown.");
}
@Test
void managedIdentityTest_RetrySucceedsAfterFailure() throws Exception {
IEnvironmentVariables environmentVariables = new EnvironmentVariablesHelper(IMDS, ManagedIdentityTestConstants.IMDS_ENDPOINT);
ManagedIdentityApplication.setEnvironmentVariables(environmentVariables);
DefaultHttpClientManagedIdentity httpClientMock = mock(DefaultHttpClientManagedIdentity.class);
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.httpClient(httpClientMock)
.build();
// First call returns 500, subsequent calls return 200
when(httpClientMock.send(expectedRequest(IMDS, ManagedIdentityTestConstants.RESOURCE)))
.thenReturn(expectedResponse(HttpStatus.HTTP_INTERNAL_ERROR, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_500))
.thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
IAuthenticationResult result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromIdentityProvider(result);
assertNotNull(result.accessToken());
// Verify that the client was called exactly twice (first attempt + one retry)
verify(httpClientMock, times(2)).send(any());
}
@Test
void managedIdentityTest_NonRetryableError() throws Exception {
IEnvironmentVariables environmentVariables = new EnvironmentVariablesHelper(IMDS, ManagedIdentityTestConstants.IMDS_ENDPOINT);
ManagedIdentityApplication.setEnvironmentVariables(environmentVariables);
DefaultHttpClientManagedIdentity httpClientMock = mock(DefaultHttpClientManagedIdentity.class);
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.httpClient(httpClientMock)
.build();
// Use a status code that doesn't trigger retries (499)
when(httpClientMock.send(expectedRequest(IMDS, ManagedIdentityTestConstants.RESOURCE)))
.thenReturn(expectedResponse(499, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_NORETRY));
CompletableFuture<IAuthenticationResult> future = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE);
// Verify that an exception is thrown
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalServiceException.class, ex.getCause());
MsalServiceException msalException = (MsalServiceException) ex.getCause();
assertEquals(MsalError.MANAGED_IDENTITY_REQUEST_FAILED, msalException.errorCode());
// Verify the client was called exactly once (no retries attempted)
verify(httpClientMock, times(1)).send(any());
}
@Test
void managedIdentityTest_RetriesARePerRequest() throws Exception {
IEnvironmentVariables environmentVariables = new EnvironmentVariablesHelper(IMDS, ManagedIdentityTestConstants.IMDS_ENDPOINT);
ManagedIdentityApplication.setEnvironmentVariables(environmentVariables);
DefaultHttpClientManagedIdentity httpClientMock = mock(DefaultHttpClientManagedIdentity.class);
miApp = ManagedIdentityApplication
.builder(ManagedIdentityId.systemAssigned())
.httpClient(httpClientMock)
.build();
// First call returns 500, subsequent calls return 200
when(httpClientMock.send(expectedRequest(IMDS, ManagedIdentityTestConstants.RESOURCE)))
.thenReturn(expectedResponse(HttpStatus.HTTP_INTERNAL_ERROR, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_500))
.thenReturn(expectedResponse(HttpStatus.HTTP_OK, getSuccessfulResponse(ManagedIdentityTestConstants.RESOURCE)));
IAuthenticationResult result = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE).get();
assertTokenFromIdentityProvider(result);
assertNotNull(result.accessToken());
// Verify that the client was called exactly twice (first attempt + one retry)
verify(httpClientMock, times(2)).send(any());
//All calls return 500
when(httpClientMock.send(expectedRequest(IMDS, "otherResource")))
.thenReturn(expectedResponse(HttpStatus.HTTP_INTERNAL_ERROR, ManagedIdentityTestConstants.MSI_ERROR_RESPONSE_500));
CompletableFuture<IAuthenticationResult> future = acquireTokenCommon("otherResource");
// Verify that an exception is thrown
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalServiceException.class, ex.getCause());
MsalServiceException msalException = (MsalServiceException) ex.getCause();
assertEquals(MsalError.MANAGED_IDENTITY_REQUEST_FAILED, msalException.errorCode());
// Verify that the client was called four more times (new first attempt + three new retries)
verify(httpClientMock, times(6)).send(any());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataError")
void managedIdentity_RequestFailed_NoPayload(ManagedIdentitySourceType source, String endpoint) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(expectedRequest(source, ManagedIdentityTestConstants.RESOURCE))).thenReturn(expectedResponse(500, ""));
assertMsalServiceException(acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE), source, MsalError.MANAGED_IDENTITY_RESPONSE_PARSE_FAILURE);
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataError")
void managedIdentity_RequestFailed_NullResponse(ManagedIdentitySourceType source, String endpoint) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(expectedRequest(source, ManagedIdentityTestConstants.RESOURCE))).thenReturn(expectedResponse(HttpStatus.HTTP_OK, ""));
assertMsalServiceException(acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE), source, MsalError.MANAGED_IDENTITY_REQUEST_FAILED);
verify(httpClientMock, times(1)).send(any());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createDataError")
void managedIdentity_RequestFailed_UnreachableNetwork(ManagedIdentitySourceType source, String endpoint) throws Exception {
setUpCommonTest(source, endpoint, ManagedIdentityId.systemAssigned());
when(httpClientMock.send(expectedRequest(source, ManagedIdentityTestConstants.RESOURCE))).thenThrow(new SocketException("A socket operation was attempted to an unreachable network."));
assertMsalServiceException(acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE), source, MsalError.MANAGED_IDENTITY_UNREACHABLE_NETWORK);
verify(httpClientMock, times(1)).send(any());
}
@ParameterizedTest
@MethodSource("com.microsoft.aad.msal4j.ManagedIdentityTestDataProvider#createInvalidClaimsData")
void managedIdentity_InvalidClaims(String claimsJson) throws Exception {
setUpCommonTest(APP_SERVICE, ManagedIdentityTestConstants.APP_SERVICE_ENDPOINT, ManagedIdentityId.systemAssigned());
CompletableFuture<IAuthenticationResult> future = miApp.acquireTokenForManagedIdentity(
ManagedIdentityParameters.builder(ManagedIdentityTestConstants.RESOURCE)
.claims(claimsJson)
.build());
assertMsalClientException(future, AuthenticationErrorCode.INVALID_JSON);
// Verify no HTTP requests were made for invalid claims
verify(httpClientMock, never()).send(any());
}
@Test
void managedIdentityTest_WithEmptyClaims() throws Exception {
setUpCommonTest(APP_SERVICE, ManagedIdentityTestConstants.APP_SERVICE_ENDPOINT, ManagedIdentityId.systemAssigned());
try {
miApp.acquireTokenForManagedIdentity(
ManagedIdentityParameters.builder(ManagedIdentityTestConstants.RESOURCE)
.claims("")
.build());
} catch (Exception exception) {
assert(exception instanceof IllegalArgumentException);
}
try {
miApp.acquireTokenForManagedIdentity(
ManagedIdentityParameters.builder(ManagedIdentityTestConstants.RESOURCE)
.claims(null)
.build());
} catch (Exception exception) {
assert(exception instanceof IllegalArgumentException);
}
// Verify no HTTP requests were made for invalid claims
verify(httpClientMock, never()).send(any());
}
}
@Nested
class AzureArc extends BaseManagedIdentityTest{
@Test
void missingAuthHeader() throws Exception {
mockHttpResponse(emptyMap());
assertMsalServiceException(MANAGED_IDENTITY_REQUEST_FAILED, MANAGED_IDENTITY_NO_CHALLENGE_ERROR);
}
@ParameterizedTest
@ValueSource(strings = {"WWW-Authenticate", "Www-Authenticate"})
void invalidAuthHeader(String authHeaderKey) throws Exception {
mockHttpResponse(singletonMap(authHeaderKey, singletonList("xyz")));
assertMsalServiceException(MANAGED_IDENTITY_REQUEST_FAILED,
MANAGED_IDENTITY_INVALID_CHALLENGE);
}
@ParameterizedTest
@ValueSource(strings = {"WWW-Authenticate", "Www-Authenticate"})
void validPathWithMissingFile(String authHeaderKey)
throws Exception {
Path validPathWithMissingFile = Paths.get(
System.getenv("ProgramData") + "/AzureConnectedMachineAgent/Tokens/secret.key");
mockHttpResponse(singletonMap(authHeaderKey, singletonList("Basic realm=" + validPathWithMissingFile)));
assertMsalServiceException(MANAGED_IDENTITY_FILE_READ_ERROR,
MANAGED_IDENTITY_INVALID_FILEPATH);
}
@ParameterizedTest
@ValueSource(strings = {"WWW-Authenticate", "Www-Authenticate"})
void invalidPathWithRealFile(String authHeaderKey)
throws Exception {
Path invalidPathWithRealFile = Paths.get(
this.getClass().getResource("/msi-azure-arc-secret.txt").toURI());
mockHttpResponse(singletonMap(authHeaderKey, singletonList("Basic realm=" + invalidPathWithRealFile)));
assertMsalServiceException(MANAGED_IDENTITY_FILE_READ_ERROR,
MANAGED_IDENTITY_INVALID_FILEPATH);
}
private void mockHttpResponse(Map<String, ? extends List<String>> responseHeaders) throws Exception {
setUpCommonTest(AZURE_ARC, ManagedIdentityTestConstants.AZURE_ARC_ENDPOINT, ManagedIdentityId.systemAssigned());
HttpResponse response = new HttpResponse();
response.statusCode(HttpStatus.HTTP_UNAUTHORIZED);
response.headers().putAll(responseHeaders);
when(httpClientMock.send(
expectedRequest(AZURE_ARC, ManagedIdentityTestConstants.RESOURCE))).thenReturn(
response);
}
private void assertMsalServiceException(String errorCode, String message) throws Exception {
CompletableFuture<IAuthenticationResult> future = acquireTokenCommon(ManagedIdentityTestConstants.RESOURCE);
ExecutionException ex = assertThrows(ExecutionException.class, future::get);
assertInstanceOf(MsalServiceException.class, ex.getCause());
MsalServiceException msalException = (MsalServiceException) ex.getCause();
assertEquals(AZURE_ARC.name(),
msalException.managedIdentitySource());
assertEquals(errorCode, msalException.errorCode());
assertTrue(ex.getMessage().contains(message));
}
}
}