Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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 @@ -235,8 +235,8 @@ static AadInstanceDiscoveryResponse sendInstanceDiscoveryRequest(URL authorityUr

AadInstanceDiscoveryResponse response = JsonHelper.convertJsonStringToJsonSerializableObject(httpResponse.body(), AadInstanceDiscoveryResponse::fromJson);

if (httpResponse.statusCode() != HttpHelper.HTTP_STATUS_200) {
if (httpResponse.statusCode() == HttpHelper.HTTP_STATUS_400 && response.error().equals("invalid_instance")) {
if (httpResponse.statusCode() != HttpStatus.HTTP_OK) {
if (httpResponse.statusCode() == HttpStatus.HTTP_BAD_REQUEST && response.error().equals("invalid_instance")) {
// instance discovery failed due to an invalid authority, throw an exception.
throw MsalServiceExceptionFactory.fromHttpResponse(httpResponse);
}
Expand Down Expand Up @@ -310,7 +310,7 @@ static String discoverRegion(MsalRequest msalRequest, ServiceBundle serviceBundl
log.info("Starting call to IMDS endpoint.");
IHttpResponse httpResponse = future.get(IMDS_TIMEOUT, IMDS_TIMEOUT_UNIT);
//If call to IMDS endpoint was successful, return region from response body
if (httpResponse.statusCode() == HttpHelper.HTTP_STATUS_200 && !httpResponse.body().isEmpty()) {
if (httpResponse.statusCode() == HttpStatus.HTTP_OK && !httpResponse.body().isEmpty()) {
log.info(String.format("Region retrieved from IMDS endpoint: %s", httpResponse.body()));
currentRequest.regionSource(RegionTelemetry.REGION_SOURCE_IMDS.telemetryValue);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class AuthorizationResponseHandler implements HttpHandler {
public void handle(HttpExchange httpExchange) throws IOException {
try {
if (!httpExchange.getRequestURI().getPath().equalsIgnoreCase("/")) {
httpExchange.sendResponseHeaders(200, 0);
httpExchange.sendResponseHeaders(HttpStatus.HTTP_OK, 0);
return;
}
String responseBody = new BufferedReader(new InputStreamReader(
Expand Down Expand Up @@ -92,13 +92,13 @@ private void sendErrorResponse(HttpExchange httpExchange, String response) throw
private void send302Response(HttpExchange httpExchange, String redirectUri) throws IOException {
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.set("Location", redirectUri);
httpExchange.sendResponseHeaders(302, 0);
httpExchange.sendResponseHeaders(HttpStatus.HTTP_FOUND, 0);
}

private void send200Response(HttpExchange httpExchange, String response) throws IOException {
byte[] responseBytes = response.getBytes("UTF-8");
httpExchange.getResponseHeaders().set("Content-Type", "text/html; charset=UTF-8");
httpExchange.sendResponseHeaders(200, responseBytes.length);
httpExchange.sendResponseHeaders(HttpStatus.HTTP_OK, responseBytes.length);
OutputStream os = httpExchange.getResponseBody();
os.write(responseBytes);
os.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ DeviceCode acquireDeviceCode(String url,
this.requestContext(),
serviceBundle);

if (response.statusCode() != HttpHelper.HTTP_STATUS_200) {
if (response.statusCode() != HttpStatus.HTTP_OK) {
throw MsalServiceExceptionFactory.fromHttpResponse(response);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@ class HttpHelper implements IHttpHelper {
private static final Logger log = LoggerFactory.getLogger(HttpHelper.class);
public static final String RETRY_AFTER_HEADER = "Retry-After";

public static final int HTTP_STATUS_200 = 200;
public static final int HTTP_STATUS_400 = 400;
public static final int HTTP_STATUS_429 = 429;
public static final int HTTP_STATUS_500 = 500;

private IHttpClient httpClient;
private IRetryPolicy retryPolicy;

Expand Down Expand Up @@ -179,8 +174,8 @@ private void processThrottlingInstructions(IHttpResponse httpResponse, RequestCo
Integer retryAfterHeaderVal = getRetryAfterHeader(httpResponse);
if (retryAfterHeaderVal != null) {
expirationTimestamp = System.currentTimeMillis() + retryAfterHeaderVal * 1000;
} else if (httpResponse.statusCode() == HTTP_STATUS_429 ||
(httpResponse.statusCode() >= HTTP_STATUS_500)) {
} else if (httpResponse.statusCode() == HttpStatus.HTTP_TOO_MANY_REQUESTS ||
(httpResponse.statusCode() >= HttpStatus.HTTP_INTERNAL_ERROR)) {

expirationTimestamp = System.currentTimeMillis() + ThrottlingCache.DEFAULT_THROTTLING_TIME_SEC * 1000;
}
Expand Down
45 changes: 18 additions & 27 deletions msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/HttpStatus.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,26 @@

package com.microsoft.aad.msal4j;

enum HttpStatus {
OK(200, "OK"),
FOUND(302, "Found"),
BAD_REQUEST(400, "Bad Request"),
NOT_FOUND(404, "Not Found"),
REQUEST_TIMEOUT(408, "Request Timeout"),
GONE(410, "Gone"),
TOO_MANY_REQUESTS(429, "Too Many Requests"),
INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
SERVICE_UNAVAILABLE(503, "Service Unavailable"),
GATEWAY_TIMEOUT(504, "Gateway Timeout");
class HttpStatus {

private final int code;
private final String description;
static final int HTTP_OK = 200;
static final int HTTP_FOUND = 302;
static final int HTTP_BAD_REQUEST = 400;
static final int HTTP_UNAUTHORIZED = 401;
static final int HTTP_NOT_FOUND = 404;
static final int HTTP_REQUEST_TIMEOUT = 408;
static final int HTTP_GONE = 410;
static final int HTTP_TOO_MANY_REQUESTS = 429;
static final int HTTP_INTERNAL_ERROR = 500;
static final int HTTP_UNAVAILABLE = 503;
static final int HTTP_GATEWAY_TIMEOUT = 504;

HttpStatus(int code, String description) {
this.code = code;
this.description = description;
}

int getCode() {
return code;
}

String getDescription() {
return description;
}

//All 5xx errors
/**
* Determines if the status code represents a server error (5xx).
*
* @param code The HTTP status code
* @return true if the status code is between 500 and 599, inclusive
*/
static boolean isServerError(int code) {
return code >= 500 && code < 600;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ class IMDSRetryPolicy extends ManagedIdentityRetryPolicy {

private static final Set<Integer> RETRYABLE_STATUS_CODES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(
HttpStatus.NOT_FOUND.getCode(),
HttpStatus.REQUEST_TIMEOUT.getCode(),
HttpStatus.GONE.getCode(),
HttpStatus.TOO_MANY_REQUESTS.getCode()
HttpStatus.HTTP_NOT_FOUND,
HttpStatus.HTTP_REQUEST_TIMEOUT,
HttpStatus.HTTP_GONE,
HttpStatus.HTTP_TOO_MANY_REQUESTS
))
);

Expand All @@ -40,13 +40,13 @@ public boolean isRetryable(IHttpResponse httpResponse) {

@Override
public int getMaxRetryCount(IHttpResponse httpResponse) {
return (httpResponse.statusCode() == HttpStatus.GONE.getCode()) ? LINEAR_RETRY_NUM : EXPONENTIAL_RETRY_NUM;
return (httpResponse.statusCode() == HttpStatus.HTTP_GONE) ? LINEAR_RETRY_NUM : EXPONENTIAL_RETRY_NUM;
}

@Override
public int getRetryDelayMs(IHttpResponse httpResponse) {
// Use exponential backoff for non-410 status codes
if (lastStatusCode == HttpStatus.GONE.getCode()) {
if (lastStatusCode == HttpStatus.HTTP_GONE) {
return currentLinearRetryDelayMs;
} else {
return (int) (Math.pow(2, currentRetryCount) * exponentialLinearRetryDelayMs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ class ManagedIdentityRetryPolicy implements IRetryPolicy {

private static final Set<Integer> RETRYABLE_STATUS_CODES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(
HttpStatus.NOT_FOUND.getCode(),
HttpStatus.REQUEST_TIMEOUT.getCode(),
HttpStatus.TOO_MANY_REQUESTS.getCode(),
HttpStatus.INTERNAL_SERVER_ERROR.getCode(),
HttpStatus.SERVICE_UNAVAILABLE.getCode(),
HttpStatus.GATEWAY_TIMEOUT.getCode()
HttpStatus.HTTP_NOT_FOUND,
HttpStatus.HTTP_REQUEST_TIMEOUT,
HttpStatus.HTTP_TOO_MANY_REQUESTS,
HttpStatus.HTTP_INTERNAL_ERROR,
HttpStatus.HTTP_UNAVAILABLE,
HttpStatus.HTTP_GATEWAY_TIMEOUT
))
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ static OidcDiscoveryResponse performOidcDiscovery(OidcAuthority authority, Abstr

OidcDiscoveryResponse response = JsonHelper.convertJsonStringToJsonSerializableObject(httpResponse.body(), OidcDiscoveryResponse::fromJson);

if (httpResponse.statusCode() != HttpHelper.HTTP_STATUS_200) {
if (httpResponse.statusCode() != HttpStatus.HTTP_OK) {
throw MsalServiceExceptionFactory.fromHttpResponse(httpResponse);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ private AuthenticationResult createAuthenticationResultFromOauthHttpResponse(

} else {
// http codes indicating that STS did not log request
if (oauthHttpResponse.getStatusCode() == HttpHelper.HTTP_STATUS_429 || oauthHttpResponse.getStatusCode() >= HttpHelper.HTTP_STATUS_500) {
if (oauthHttpResponse.getStatusCode() == HttpStatus.HTTP_TOO_MANY_REQUESTS || oauthHttpResponse.getStatusCode() >= HttpStatus.HTTP_INTERNAL_ERROR) {
serviceBundle.getServerSideTelemetry().previousRequests.putAll(
serviceBundle.getServerSideTelemetry().previousRequestInProgress);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ static UserDiscoveryResponse execute(
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri, headers);
IHttpResponse response = serviceBundle.getHttpHelper().executeHttpRequest(httpRequest, requestContext, serviceBundle);

if (response.statusCode() != HttpHelper.HTTP_STATUS_200) {
if (response.statusCode() != HttpStatus.HTTP_OK) {
throw MsalServiceExceptionFactory.fromHttpResponse(response);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ static WSTrustResponse execute(String url,
HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, url);
IHttpResponse mexResponse = serviceBundle.getHttpHelper().executeHttpRequest(httpRequest, requestContext, serviceBundle);

if (mexResponse.statusCode() != HttpHelper.HTTP_STATUS_200 || StringHelper.isBlank(mexResponse.body())) {
if (mexResponse.statusCode() != HttpStatus.HTTP_OK || StringHelper.isBlank(mexResponse.body())) {
throw MsalServiceExceptionFactory.fromHttpResponse(mexResponse);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ void testTokenRefreshReasons() throws Exception {
responseParameters.put("access_token", "expiredToken");
responseParameters.put("id_token", TestHelper.createIdToken(new HashMap<>()));
responseParameters.put("expires_in", "0");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), 200);
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);

OnBehalfOfParameters parameters = OnBehalfOfParameters.builder(Collections.singleton("someScopes"), new UserAssertion(TestHelper.signedAssertion)).build();
IAuthenticationResult result = cca.acquireToken(parameters).get();
Expand All @@ -149,7 +149,7 @@ void testTokenRefreshReasons() throws Exception {
// In this test, it will be replaced with a token that expires in 1 minute
responseParameters.put("access_token", "nearlyExpiredToken");
responseParameters.put("expires_in", "60");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), 200);
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);

SilentParameters silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).build();
result = cca.acquireTokenSilently(silentParameters).get();
Expand All @@ -162,7 +162,7 @@ void testTokenRefreshReasons() throws Exception {
responseParameters.put("access_token", "refreshInToken");
responseParameters.put("expires_in", "3600");
responseParameters.put("refresh_in", "1");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), 200);
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);

silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).build();
result = cca.acquireTokenSilently(silentParameters).get();
Expand All @@ -174,7 +174,7 @@ void testTokenRefreshReasons() throws Exception {
responseParameters.put("access_token", "normalToken");
responseParameters.put("expires_in", "3600");
responseParameters.put("refresh_in", "0");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), 200);
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);

//refresh_in values are in seconds, so we must wait to guarantee it is past the proactive refresh time
TimeUnit.SECONDS.sleep(2);
Expand All @@ -186,7 +186,7 @@ void testTokenRefreshReasons() throws Exception {

//Force the token to be refreshed
responseParameters.put("access_token", "forcedRefreshToken");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), 200);
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);

silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).forceRefresh(true).build();
result = cca.acquireTokenSilently(silentParameters).get();
Expand All @@ -195,7 +195,7 @@ void testTokenRefreshReasons() throws Exception {

//Finally, force a refresh by setting claims
responseParameters.put("access_token", "claimsToken");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), 200);
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), HttpStatus.HTTP_OK);

silentParameters = SilentParameters.builder(Collections.singleton("someScopes"), result.account()).claims(new ClaimsRequest()).build();
result = cca.acquireTokenSilently(silentParameters).get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public void tokenCacheEntitiesFormatTest(String folder) throws URISyntaxExceptio

doReturn(msalOAuthHttpRequest).when(request).createOauthHttpRequest();
doReturn(httpResponse).when(msalOAuthHttpRequest).send();
doReturn(200).when(httpResponse).getStatusCode();
doReturn(HttpStatus.HTTP_OK).when(httpResponse).getStatusCode();
doReturn(JSONObjectUtils.parse(tokenResponse)).when(httpResponse).getContentAsJSONObject();

final AuthenticationResult result = request.executeTokenRequest();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ void cacheLookup_MixAccountBasedAndAssertionBasedSilentFlows() throws Exception
responseParameters.put("access_token", "accessTokenNoAccount");

ClientCredentialParameters clientCredentialParameters = ClientCredentialParameters.builder(Collections.singleton("someScopes")).build();
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(responseParameters)));
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(HttpStatus.HTTP_OK, TestHelper.getSuccessfulTokenResponse(responseParameters)));
IAuthenticationResult resultNoAccount = cca.acquireToken(clientCredentialParameters).get();

//Ensure there is one token in the cache, and the result had no account
Expand All @@ -47,7 +47,7 @@ void cacheLookup_MixAccountBasedAndAssertionBasedSilentFlows() throws Exception
responseParameters.put("access_token", "accessTokenWithAccount");
responseParameters.put("id_token", TestHelper.createIdToken(new HashMap<>()));

when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(responseParameters)));
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(HttpStatus.HTTP_OK, TestHelper.getSuccessfulTokenResponse(responseParameters)));
OnBehalfOfParameters onBehalfOfParametersarameters = OnBehalfOfParameters.builder(Collections.singleton("someOtherScopes"), new UserAssertion(TestHelper.signedAssertion)).build();
IAuthenticationResult resultWithAccount = cca.acquireToken(onBehalfOfParametersarameters).get();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ void testIClientCertificateInterface_CredentialFactoryUsesSha256() throws Except
if (request.body().contains(((PrivateKeyJWT) cca.clientAuthentication()).getClientAssertion().serialize())
&& headerParams.contains("x5t#S256")) {

return TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(tokenResponseValues));
return TestHelper.expectedResponse(HttpStatus.HTTP_OK, TestHelper.getSuccessfulTokenResponse(tokenResponseValues));
}
return null;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ void testSecretNullAndEmpty() {
void OnBehalfOf_InternalCacheLookup_Success() throws Exception {
DefaultHttpClient httpClientMock = mock(DefaultHttpClient.class);

when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(new HashMap<>())));
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(HttpStatus.HTTP_OK, TestHelper.getSuccessfulTokenResponse(new HashMap<>())));

ConfidentialClientApplication cca =
ConfidentialClientApplication.builder("clientId", ClientCredentialFactory.createFromSecret("password"))
Expand Down Expand Up @@ -82,7 +82,7 @@ void OnBehalfOf_TenantOverride() throws Exception {
HashMap<String, String> tokenResponseValues = new HashMap<>();
tokenResponseValues.put("access_token", "accessTokenFirstCall");

when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(tokenResponseValues)));
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(HttpStatus.HTTP_OK, TestHelper.getSuccessfulTokenResponse(tokenResponseValues)));
ClientCredentialParameters parameters = ClientCredentialParameters.builder(Collections.singleton("scopes")).build();

//The two acquireToken calls have the same parameters...
Expand All @@ -95,7 +95,7 @@ void OnBehalfOf_TenantOverride() throws Exception {

tokenResponseValues.put("access_token", "accessTokenSecondCall");

when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(tokenResponseValues)));
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(HttpStatus.HTTP_OK, TestHelper.getSuccessfulTokenResponse(tokenResponseValues)));
parameters = ClientCredentialParameters.builder(Collections.singleton("scopes")).tenant("otherTenant").build();

//Overriding the tenant parameter in the request should lead to a new token call being made...
Expand Down
Loading