Skip to content

Commit

Permalink
Merge branch 'dev' into feature/handle-error-when-activity-not-found
Browse files Browse the repository at this point in the history
  • Loading branch information
denniskniep authored Dec 21, 2024
2 parents 8b43097 + 2541bf6 commit 9773a6b
Show file tree
Hide file tree
Showing 44 changed files with 391 additions and 224 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ public class LabApiAuthenticationClient implements IAccessTokenSupplier {
private final static String AUTHORITY = "https://login.microsoftonline.com/" + TENANT_ID;
private final static String KEYSTORE_TYPE = "Windows-MY";
private final static String KEYSTORE_PROVIDER = "SunMSCAPI";
private final int DEFAULT_ACCESS_TOKEN_RETRIES = 2;
private final int ATTEMPT_RETRY_WAIT = 3;
private final static int DEFAULT_ACCESS_TOKEN_RETRIES = 2;
private final static int ATTEMPT_RETRY_WAIT = 3;
private final String mLabCredential;
private final String mLabCertPassword;
private final String mScope;
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ For more information see the [Code of Conduct FAQ](https://opensource.microsoft.
contact [[email protected]](mailto:[email protected]) with any additional questions or comments.

### Android Studio Build Requirement
Please note that this project uses [Lombok](https://projectlombok.org/) internally and while using Android Studio you will need to install [Lobmok Plugin](https://plugins.jetbrains.com/plugin/6317-lombok) to get the project to build successfully within Android Studio.
Please note that this project uses [Lombok](https://projectlombok.org/) internally and while using Android Studio you will need to install [Lombok Plugin](https://plugins.jetbrains.com/plugin/6317-lombok) to get the project to build successfully within Android Studio.
8 changes: 8 additions & 0 deletions changelog.txt
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
vNext
----------
- [MINOR] Add switch_browser toMicrosoftStsAuthorizationRequest (#2550)
- [MAJOR] Add suberror for network errors (#2537)
- [PATCH] Translate MFA token error to UIRequiredException instead of ServiceException (#2538)
- [MINOR] Add Child Spans for Interactive Span (#2516)
- [MINOR] For MSAL CPP flows, match exact claims when deleting AT with intersecting scopes (#2548)
- [MINOR] Handle error gracefully when amazon app url scheme is not found (#2515)
- [MINOR] Replace Deprecated Keystore API for Android 28+ (#2558)

Version 18.2.2
----------
(common4j 15.2.2)
- [PATCH] Debug errors in Keystore layer (#2544)

Version 18.2.1
----------
(common4j 15.2.1)
- [PATCH] Translate MFA token error to UIRequiredException instead of ServiceException (#2538)

Version 18.2.0
----------
(common4j 15.2.0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import android.content.Context;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;

import androidx.annotation.RequiresApi;

Expand All @@ -44,7 +46,9 @@
import java.security.KeyStore;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import javax.crypto.SecretKey;
import javax.security.auth.x500.X500Principal;
Expand Down Expand Up @@ -269,12 +273,13 @@ public void deleteSecretKeyFromStorage() throws ClientException {
/**
* Generate a self-signed cert and derive an AlgorithmParameterSpec from that.
* This is for the key to be generated in {@link KeyStore} via {@link KeyPairGenerator}
* Note : This is now only for API level < 28
*
* @param context an Android {@link Context} object.
* @return a {@link AlgorithmParameterSpec} for the keystore key (that we'll use to wrap the secret key).
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private static AlgorithmParameterSpec getSpecForKeyStoreKey(@NonNull final Context context,
private static AlgorithmParameterSpec getLegacySpecForKeyStoreKey(@NonNull final Context context,
@NonNull final String alias) {
// Generate a self-signed cert.
final String certInfo = String.format(Locale.ROOT, "CN=%s, OU=%s",
Expand All @@ -295,6 +300,34 @@ private static AlgorithmParameterSpec getSpecForKeyStoreKey(@NonNull final Conte
.build();
}

/**
* Generate a self-signed cert and derive an AlgorithmParameterSpec from that.
* This is for the key to be generated in {@link KeyStore} via {@link KeyPairGenerator}
*
* @param context an Android {@link Context} object.
* @return a {@link AlgorithmParameterSpec} for the keystore key (that we'll use to wrap the secret key).
*/
private static AlgorithmParameterSpec getSpecForKeyStoreKey(@NonNull final Context context, @NonNull final String alias) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return getLegacySpecForKeyStoreKey(context, alias);
} else {
final String certInfo = String.format(Locale.ROOT, "CN=%s, OU=%s",
alias,
context.getPackageName());
final int certValidYears = 100;
int purposes = KeyProperties.PURPOSE_WRAP_KEY | KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT;
return new KeyGenParameterSpec.Builder(alias, purposes)
.setCertificateSubject(new X500Principal(certInfo))
.setCertificateSerialNumber(BigInteger.ONE)
.setCertificateNotBefore(new Date())
.setCertificateNotAfter(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365 * certValidYears)))
.setKeySize(2048)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.build();
}
}

/**
* Get the file that stores the wrapped key.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import com.microsoft.identity.common.java.exception.ErrorStrings;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
Expand Down Expand Up @@ -647,7 +646,7 @@ public Builder correlationId(final String correlationId) {
return this;
}

public Builder oauthSubErrorCode(final String subErrorCode) {
public Builder subErrorCode(final String subErrorCode) {
this.mSubErrorCode = subErrorCode;
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.microsoft.identity.common.adal.internal.AuthenticationConstants;
import com.microsoft.identity.common.java.exception.ClientException;
import com.microsoft.identity.common.java.exception.ServiceException;
import com.microsoft.identity.common.adal.internal.cache.ADALTokenCacheItem;
import com.microsoft.identity.common.java.providers.microsoft.MicrosoftAccount;
Expand Down Expand Up @@ -239,7 +240,7 @@ public static boolean loadCloudDiscoveryMetadata() {
if (!AzureActiveDirectory.isInitialized()) {
try {
AzureActiveDirectory.performCloudDiscovery();
} catch (final IOException | URISyntaxException e) {
} catch (final ClientException e) {
Logger.error(
methodTag,
"Failed to load instance discovery metadata",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ private void setServiceExceptionPropertiesToBundle(@NonNull final Bundle resultB
// so adding values to these constants as well
resultBundle.putString(AuthenticationConstants.OAuth2.ERROR, serviceException.getErrorCode());
resultBundle.putString(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION, serviceException.getMessage());
resultBundle.putString(AuthenticationConstants.OAuth2.SUBERROR, serviceException.getOAuthSubErrorCode());
resultBundle.putString(AuthenticationConstants.OAuth2.SUBERROR, serviceException.getSubErrorCode());

if (null != serviceException.getHttpResponseBody()) {
resultBundle.putSerializable(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@
import com.microsoft.identity.common.java.opentelemetry.OTelUtility;
import com.microsoft.identity.common.java.opentelemetry.SpanExtension;
import com.microsoft.identity.common.java.opentelemetry.SpanName;
import com.microsoft.identity.common.java.providers.microsoft.azureactivedirectory.ClientInfo;
import com.microsoft.identity.common.java.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResult;
import com.microsoft.identity.common.java.providers.oauth2.AuthorizationResult;
import com.microsoft.identity.common.java.request.SdkType;
Expand Down Expand Up @@ -308,6 +307,7 @@ public Bundle bundleFromBaseException(@NonNull final BaseException exception,
final BrokerResult.Builder builder = new BrokerResult.Builder()
.success(false)
.errorCode(exception.getErrorCode())
.subErrorCode(exception.getSubErrorCode())
.errorMessage(exception.getMessage())
.exceptionType(exception.getExceptionName())
.correlationId(exception.getCorrelationId())
Expand All @@ -318,7 +318,7 @@ public Bundle bundleFromBaseException(@NonNull final BaseException exception,

if (exception instanceof ServiceException) {
final ServiceException serviceException = (ServiceException) exception;
builder.oauthSubErrorCode(serviceException.getOAuthSubErrorCode())
builder.subErrorCode(serviceException.getSubErrorCode())
.httpStatusCode(serviceException.getHttpStatusCode())
.httpResponseBody(AuthenticationSchemeTypeAdapter.getGsonInstance().toJson(
serviceException.getHttpResponseBody()));
Expand Down Expand Up @@ -522,6 +522,7 @@ private BaseException getBaseExceptionFromExceptionType(@NonNull final String ex
);
}

baseException.setSubErrorCode(brokerResult.getSubErrorCode());
baseException.setCliTelemErrorCode(brokerResult.getCliTelemErrorCode());
baseException.setCliTelemSubErrorCode(brokerResult.getCliTelemSubErrorCode());
baseException.setCorrelationId(brokerResult.getCorrelationId());
Expand Down Expand Up @@ -595,6 +596,7 @@ private BaseException getBaseExceptionFromErrorCodes(@NonNull final BrokerResult
);
}

baseException.setSubErrorCode(brokerResult.getSubErrorCode());
baseException.setCliTelemErrorCode(brokerResult.getCliTelemErrorCode());
baseException.setCliTelemSubErrorCode(brokerResult.getCliTelemSubErrorCode());
baseException.setCorrelationId(brokerResult.getCorrelationId());
Expand All @@ -620,7 +622,7 @@ private IntuneAppProtectionPolicyRequiredException getIntuneProtectionRequiredEx
exception.setAuthorityUrl(brokerResult.getAuthority());
exception.setAccountUserId(brokerResult.getLocalAccountId());
exception.setAccountUpn(brokerResult.getUserName());
exception.setOauthSubErrorCode(brokerResult.getSubErrorCode());
exception.setSubErrorCode(brokerResult.getSubErrorCode());
try {
exception.setHttpResponseBody(HashMapExtensions.jsonStringAsMap(
brokerResult.getHttpResponseBody())
Expand Down Expand Up @@ -649,8 +651,6 @@ private ServiceException getServiceException(@NonNull final BrokerResult brokerR
null
);

serviceException.setOauthSubErrorCode(brokerResult.getSubErrorCode());

try {
serviceException.setHttpResponseBody(
brokerResult.getHttpResponseBody() != null ?
Expand Down Expand Up @@ -686,7 +686,7 @@ private UiRequiredException getUiRequiredException(@NonNull final BrokerResult b
);
if (OAuth2ErrorCode.INTERACTION_REQUIRED.equalsIgnoreCase(errorCode) ||
OAuth2ErrorCode.INVALID_GRANT.equalsIgnoreCase(errorCode)) {
exception.setOauthSubErrorCode(brokerResult.getSubErrorCode());
exception.setSubErrorCode(brokerResult.getSubErrorCode());
}
return exception;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
@RunWith(RobolectricTestRunner.class)
public class AzureActiveDirectoryAuthorityTests {
@Test
public void isSameCloudAsAuthority_Returns_True_For_Authority_With_ValidAliases_For_SameCloud() throws IOException, URISyntaxException {
public void isSameCloudAsAuthority_Returns_True_For_Authority_With_ValidAliases_For_SameCloud() throws ClientException {
final String[] cloudAliasesWW = new String[]{"https://login.microsoftonline.com", "https://login.windows.net", "https://login.microsoft.com", "https://sts.windows.net"};
final String[] cloudAliasesCN = new String[]{"https://login.chinacloudapi.cn", "https://login.partner.microsoftonline.cn"};
final String[] cloudAliasesUSGov = new String[]{"https://login.microsoftonline.us", "https://login.usgovcloudapi.net"};
Expand All @@ -69,7 +69,7 @@ public void isSameCloudAsAuthority_Returns_True_For_Authority_With_ValidAliases_
}

@Test
public void isSameCloudAsAuthority_Returns_False_For_Authorities_From_Different_Clouds() throws IOException, URISyntaxException {
public void isSameCloudAsAuthority_Returns_False_For_Authorities_From_Different_Clouds() throws ClientException {
final AzureActiveDirectoryAuthority authorityWW = new AzureActiveDirectoryAuthority(new AllAccounts("https://login.microsoftonline.com"));
final AzureActiveDirectoryAuthority authorityCN = new AzureActiveDirectoryAuthority(new AllAccounts("https://login.partner.microsoftonline.cn"));
final AzureActiveDirectoryAuthority authorityUSGov = new AzureActiveDirectoryAuthority(new AllAccounts("https://login.microsoftonline.us"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ public int hashCode() {
private static final Object sLock = new Object();

private static void performCloudDiscovery()
throws IOException, URISyntaxException {
throws ClientException {
final String methodName = ":performCloudDiscovery";
Logger.verbose(
TAG + methodName,
Expand Down Expand Up @@ -389,18 +389,8 @@ public static KnownAuthorityResult getKnownAuthorityResult(Authority authority)

try {
performCloudDiscovery();
} catch (final IOException ex) {
clientException = new ClientException(
ClientException.IO_ERROR,
"Unable to perform cloud discovery",
ex
);
} catch (final URISyntaxException ex) {
clientException = new ClientException(
ClientException.MALFORMED_URL,
"Unable to construct cloud discovery URL",
ex
);
} catch (final ClientException ex) {
clientException = ex;
}

Logger.info(TAG + methodName, "Cloud discovery complete.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import com.microsoft.identity.common.java.util.CommonURIBuilder;
import com.microsoft.identity.common.java.util.StringUtil;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
Expand Down Expand Up @@ -177,7 +176,7 @@ public OAuth2Strategy createOAuth2Strategy(@NonNull final OAuth2StrategyParamete
*/
//@WorkerThread
public synchronized boolean isSameCloudAsAuthority(@NonNull final AzureActiveDirectoryAuthority authorityToCheck)
throws IOException, URISyntaxException {
throws ClientException {
if (!AzureActiveDirectory.isInitialized()) {
// Cloud discovery is needed in order to make sure that we have a preferred_network_host_name to cloud aliases mappings
AzureActiveDirectory.performCloudDiscovery();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@
import com.microsoft.identity.common.java.exception.ClientException;
import com.microsoft.identity.common.java.logging.Logger;

import java.io.IOException;
import java.net.URISyntaxException;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.experimental.SuperBuilder;
Expand Down Expand Up @@ -90,12 +87,9 @@ private boolean authorityMatchesAccountEnvironment() {
}
final AzureActiveDirectoryCloud cloud = AzureActiveDirectory.getAzureActiveDirectoryCloudFromHostName(getAccount().getEnvironment());
return cloud != null && cloud.getPreferredNetworkHostName().equals(getAuthority().getAuthorityURL().getAuthority());
} catch (final IOException e) {
cause = e;
errorCode = ClientException.IO_ERROR;
} catch (final URISyntaxException e) {
} catch (final ClientException e) {
cause = e;
errorCode = ClientException.MALFORMED_URL;
errorCode = e.getErrorCode();
}

Logger.error(
Expand All @@ -109,7 +103,7 @@ private boolean authorityMatchesAccountEnvironment() {
}

private static void performCloudDiscovery()
throws IOException, URISyntaxException {
throws ClientException {
final String methodName = ":performCloudDiscovery";
Logger.verbose(
TAG + methodName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ public static ServiceException getExceptionFromTokenErrorResponse(@NonNull final
null);
}

outErr.setOauthSubErrorCode(errorResponse.getSubError());
outErr.setSubErrorCode(errorResponse.getSubError());
setHttpResponseUsingTokenErrorResponse(outErr, errorResponse);
return outErr;
}
Expand Down Expand Up @@ -262,7 +262,7 @@ public static ServiceException convertToNativeAuthException(@NonNull final Servi
exception.getHttpStatusCode(),
exception
);
outErr.setOauthSubErrorCode(exception.getOAuthSubErrorCode());
outErr.setSubErrorCode(exception.getSubErrorCode());
outErr.setHttpResponseHeaders(exception.getHttpResponseHeaders());
outErr.setHttpResponseBody(exception.getHttpResponseBody());
return outErr;
Expand Down Expand Up @@ -291,7 +291,7 @@ public static ServiceException getExceptionFromTokenErrorResponse(@Nullable fina
(BrokerSilentTokenCommandParameters) commandParameters
);
}
policyRequiredException.setOauthSubErrorCode(errorResponse.getSubError());
policyRequiredException.setSubErrorCode(errorResponse.getSubError());
setHttpResponseUsingTokenErrorResponse(policyRequiredException, errorResponse);

return policyRequiredException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ public class BaseException extends Exception implements IErrorInformation, ITele

private String mErrorCode;

private String mSubErrorCode;

private String mCorrelationId;

// The username of the account that owns the flow.
Expand Down Expand Up @@ -133,13 +135,24 @@ public BaseException(final String errorCode, final String errorMessage,
}

/**
* @return The error code for the exception, could be null. {@link BaseException} is the top level base exception, for the
* constants value of all the error code.
* @return The error code of the exception, may not be null.
*/
public String getErrorCode() {
return mErrorCode;
}

/**
* @return Sub error code of the exception, could be null.
*/
public String getSubErrorCode() { return mSubErrorCode; }

/**
* @param subErrorCode - The sub error code for the exception.
*/
public void setSubErrorCode(@Nullable final String subErrorCode) {
mSubErrorCode = subErrorCode;
}

/**
* {@inheritDoc}
* Return the detailed description explaining why the exception is returned back.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ public class ClientException extends BaseException {
public static final String MULTIPLE_MATCHING_TOKENS_DETECTED = "multiple_matching_tokens_detected";

/**
* No active network is available on the device.
* Failed to make a network request from the device.
* See {@link BaseException#getSubErrorCode()} for more details.
*/
public static final String DEVICE_NETWORK_NOT_AVAILABLE = "device_network_not_available";

Expand Down
Loading

0 comments on commit 9773a6b

Please sign in to comment.