Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ class AadInstanceDiscoveryProvider {
"login.chinacloudapi.cn",
Comment thread
bgavrilMS marked this conversation as resolved.
"login-us.microsoftonline.com",
Comment thread
bgavrilMS marked this conversation as resolved.
"login.microsoftonline.de",
"login.microsoftonline.us"));
"login.microsoftonline.us",
"login.sovcloud-identity.fr",
"login.sovcloud-identity.de",
"login.sovcloud-identity.sg"));

TRUSTED_HOSTS_SET.addAll(Arrays.asList(
DEFAULT_TRUSTED_HOST,
Expand Down Expand Up @@ -340,7 +343,20 @@ private static void doInstanceDiscoveryAndCache(URL authorityUrl,
AadInstanceDiscoveryResponse aadInstanceDiscoveryResponse = null;

if (msalRequest.application().authenticationAuthority.authorityType.equals(AuthorityType.AAD)) {
aadInstanceDiscoveryResponse = sendInstanceDiscoveryRequest(authorityUrl, msalRequest, serviceBundle);
try {
aadInstanceDiscoveryResponse = sendInstanceDiscoveryRequest(authorityUrl, msalRequest, serviceBundle);
} catch (MsalServiceException ex) {
// MsalServiceException indicates a definitive HTTP-level error from the server
Comment thread
bgavrilMS marked this conversation as resolved.
Outdated
// (e.g. invalid_instance, bad request, server error) — always propagate.
throw ex;
} catch (Exception e) {
// Network failures (timeout, DNS, connection refused) — cache a fallback
// self-entry so subsequent calls don't retry the failing network call.
LOG.warn("Instance discovery network request failed. " +
"MSAL will use fallback instance metadata with {} as the host. Exception: {}", authorityUrl.getHost(), e.getMessage());
cacheInstanceDiscoveryMetadata(authorityUrl.getHost());
return;
}

if (validateAuthority) {
validate(aadInstanceDiscoveryResponse);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.times;

import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;

Expand Down Expand Up @@ -137,6 +143,143 @@ void aadInstanceDiscoveryTest_AutoDetectRegion_NoRegionDetected() throws Excepti
}
}

@Test
void discoveryEndpoint_routesToSovereignHost() throws Exception {
Comment thread
bgavrilMS marked this conversation as resolved.
Outdated
// Arrange
URL sovereignUrl = new URL("https://login.sovcloud-identity.fr/my_tenant");
Method method = AadInstanceDiscoveryProvider.class.getDeclaredMethod("getInstanceDiscoveryEndpoint", URL.class);
method.setAccessible(true);

// Act
String endpoint = (String) method.invoke(null, sovereignUrl);

// Assert
assertTrue(endpoint.contains("login.sovcloud-identity.fr"),
"Discovery endpoint should use the sovereign host, got: " + endpoint);
}

@Test
void regionalEndpoint_usesSovereignTemplate() throws Exception {
// Arrange
Method method = AadInstanceDiscoveryProvider.class.getDeclaredMethod("getRegionalizedHost", String.class, String.class);
method.setAccessible(true);

// Act
String result = (String) method.invoke(null, "login.sovcloud-identity.fr", "westeurope");

// Assert
assertEquals("westeurope.login.sovcloud-identity.fr", result);
}

@Test
void networkException_cachesFallbackAndDoesNotPropagate() throws Exception {
// Arrange
PublicClientApplication app = PublicClientApplication.builder("client_id")
.correlationId("correlation_id")
.authority("https://login.microsoftonline.com/my_tenant")
.build();

MsalRequest msalRequest = new AuthorizationCodeRequest(
parameters,
app,
new RequestContext(app, PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE, parameters));

URL authority = new URL(app.authority());

try (MockedStatic<AadInstanceDiscoveryProvider> mocked = mockStatic(AadInstanceDiscoveryProvider.class, CALLS_REAL_METHODS)) {

mocked.when(() -> AadInstanceDiscoveryProvider.sendInstanceDiscoveryRequest(authority,
msalRequest,
app.serviceBundle())).thenThrow(new MsalClientException("Network timeout", AuthenticationErrorCode.UNKNOWN));

// Act — should not throw
InstanceDiscoveryMetadataEntry entry = assertDoesNotThrow(() ->
AadInstanceDiscoveryProvider.getMetadataEntry(
authority,
false,
msalRequest,
app.serviceBundle()));

// Assert — cache should contain a self-entry
assertNotNull(entry);
String host = authority.getHost();
InstanceDiscoveryMetadataEntry cached = AadInstanceDiscoveryProvider.cache.get(host);
assertNotNull(cached, "Fallback entry should be cached");
assertEquals(host, cached.preferredNetwork);
assertEquals(host, cached.preferredCache);
assertTrue(cached.aliases.contains(host));
}
}

@Test
void subsequentCallAfterNetworkFailure_usesCacheNoRetry() throws Exception {
// Arrange
PublicClientApplication app = PublicClientApplication.builder("client_id")
.correlationId("correlation_id")
.authority("https://login.microsoftonline.com/my_tenant")
.build();

MsalRequest msalRequest = new AuthorizationCodeRequest(
parameters,
app,
new RequestContext(app, PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE, parameters));

URL authority = new URL(app.authority());

try (MockedStatic<AadInstanceDiscoveryProvider> mocked = mockStatic(AadInstanceDiscoveryProvider.class, CALLS_REAL_METHODS)) {

mocked.when(() -> AadInstanceDiscoveryProvider.sendInstanceDiscoveryRequest(any(URL.class),
any(MsalRequest.class),
any(ServiceBundle.class))).thenThrow(new MsalClientException("Network timeout", AuthenticationErrorCode.UNKNOWN));

// Act — first call triggers network failure + fallback cache
AadInstanceDiscoveryProvider.getMetadataEntry(authority, false, msalRequest, app.serviceBundle());

// Act — second call should hit cache, not retry network
InstanceDiscoveryMetadataEntry entry = AadInstanceDiscoveryProvider.getMetadataEntry(authority, false, msalRequest, app.serviceBundle());

// Assert — sendInstanceDiscoveryRequest should have been called only once
mocked.verify(() -> AadInstanceDiscoveryProvider.sendInstanceDiscoveryRequest(any(URL.class),
any(MsalRequest.class),
any(ServiceBundle.class)), times(1));
assertNotNull(entry);
}
}

@Test
void invalidInstanceException_stillPropagates() throws Exception {
// Arrange
PublicClientApplication app = PublicClientApplication.builder("client_id")
.correlationId("correlation_id")
.authority("https://login.microsoftonline.com/my_tenant")
.build();

MsalRequest msalRequest = new AuthorizationCodeRequest(
parameters,
app,
new RequestContext(app, PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE, parameters));

URL authority = new URL(app.authority());

try (MockedStatic<AadInstanceDiscoveryProvider> mocked = mockStatic(AadInstanceDiscoveryProvider.class, CALLS_REAL_METHODS)) {

mocked.when(() -> AadInstanceDiscoveryProvider.sendInstanceDiscoveryRequest(authority,
msalRequest,
app.serviceBundle())).thenThrow(new MsalServiceException("invalid_instance", "invalid_instance"));

// Act / Assert — MsalServiceException should propagate
assertThrows(MsalServiceException.class, () ->
AadInstanceDiscoveryProvider.getMetadataEntry(
authority,
false,
msalRequest,
app.serviceBundle()));

// Assert — nothing should be cached
assertNull(AadInstanceDiscoveryProvider.cache.get(authority.getHost()));
}
}

void assertValidResponse(InstanceDiscoveryMetadataEntry entry) {
assertEquals(entry.preferredNetwork(), "login.microsoftonline.com");
assertEquals(entry.preferredCache(), "login.windows.net");
Expand Down
Loading