diff --git a/changelog b/changelog index df4044d2a..e6e339ccc 100644 --- a/changelog +++ b/changelog @@ -3,6 +3,7 @@ MSAL Wiki : https://github.com/AzureAD/microsoft-authentication-library-for-andr vNext ---------- - [MAJOR] Native Auth V2 errors now use NativeAuthErrorV2. Replace operation-specific V2 error type checks with its classifiers; rejected sign-in passwords use isInvalidCredentials, not isInvalidPassword. V1 is unchanged (AB#3784695). +- [MINOR] Native Auth V2 sign-in, sign-up and password-reset entries accept scopes and claims. Scope is also sent at token exchange; claims are sent only at entry. Null continuation scopes retain entry scopes, while explicit empty scopes request default OIDC scopes (AB#3784690). Version 8.5.0 ---------- diff --git a/common b/common index cc25e6e77..0bf4510df 160000 --- a/common +++ b/common @@ -1 +1 @@ -Subproject commit cc25e6e77ab023f5b16332329a200112f45f7c56 +Subproject commit 0bf4510df6fd0257fb359267635223640ce31dcb diff --git a/msal/src/main/java/com/microsoft/identity/client/internal/CommandParametersAdapter.java b/msal/src/main/java/com/microsoft/identity/client/internal/CommandParametersAdapter.java index 8a96decec..303ea7aed 100644 --- a/msal/src/main/java/com/microsoft/identity/client/internal/CommandParametersAdapter.java +++ b/msal/src/main/java/com/microsoft/identity/client/internal/CommandParametersAdapter.java @@ -1077,9 +1077,7 @@ public static ResetPasswordSubmitNewPasswordCommandParameters createResetPasswor /** * Creates command parameter for [NativeAuthV2ResetPasswordStartCommand] of Native Auth. * - * No scopes are supplied at the start of a reset-password flow. Matching MSAL iOS/macOS, the - * scopes for the resulting access token are supplied at the sign-in-after-reset-password step - * instead, since no token is issued until then. + * Scopes and claims are supplied at V2 authorize-challenge entry. * * @param configuration PCA configuration * @param tokenCache token cache for storing results @@ -1090,6 +1088,16 @@ public static ResetPasswordV2StartCommandParameters createResetPasswordV2StartCo @NonNull final NativeAuthPublicClientApplicationConfiguration configuration, @NonNull final OAuth2TokenCache tokenCache, @NonNull final String username) throws ClientException { + return createResetPasswordV2StartCommandParameters(configuration, tokenCache, username, null, null); + } + + /** Creates V2 reset entry parameters with optional scopes and claims. */ + public static ResetPasswordV2StartCommandParameters createResetPasswordV2StartCommandParameters( + @NonNull final NativeAuthPublicClientApplicationConfiguration configuration, + @NonNull final OAuth2TokenCache tokenCache, + @NonNull final String username, + @Nullable final List scopes, + @Nullable final ClaimsRequest claimsRequest) throws ClientException { final NativeAuthCIAMAuthority authority = ((NativeAuthCIAMAuthority) configuration.getDefaultAuthority()); @@ -1100,6 +1108,8 @@ public static ResetPasswordV2StartCommandParameters createResetPasswordV2StartCo final ResetPasswordV2StartCommandParameters commandParameters = ResetPasswordV2StartCommandParameters.builder() + .scopes(scopes == null ? null : new ArrayList<>(scopes)) + .claimsRequestJson(ClaimsRequest.getJsonStringFromClaimsRequest(claimsRequest)) .platformComponents(AndroidPlatformComponentsFactory.createFromContext(configuration.getAppContext())) .applicationName(configuration.getAppContext().getPackageName()) .applicationVersion(getPackageVersion(configuration.getAppContext())) @@ -1141,6 +1151,18 @@ public static SignUpV2StartCommandParameters createSignUpV2StartCommandParameter @NonNull final String username, @Nullable final char[] password, @Nullable final Map attributes) throws ClientException { + return createSignUpV2StartCommandParameters(configuration, tokenCache, username, password, attributes, null, null); + } + + /** Creates V2 sign-up entry parameters with optional scopes and claims. */ + public static SignUpV2StartCommandParameters createSignUpV2StartCommandParameters( + @NonNull final NativeAuthPublicClientApplicationConfiguration configuration, + @NonNull final OAuth2TokenCache tokenCache, + @NonNull final String username, + @Nullable final char[] password, + @Nullable final Map attributes, + @Nullable final List scopes, + @Nullable final ClaimsRequest claimsRequest) throws ClientException { final NativeAuthCIAMAuthority authority = ((NativeAuthCIAMAuthority) configuration.getDefaultAuthority()); @@ -1151,6 +1173,8 @@ public static SignUpV2StartCommandParameters createSignUpV2StartCommandParameter final SignUpV2StartCommandParameters commandParameters = SignUpV2StartCommandParameters.builder() + .scopes(scopes == null ? null : new ArrayList<>(scopes)) + .claimsRequestJson(ClaimsRequest.getJsonStringFromClaimsRequest(claimsRequest)) .platformComponents(AndroidPlatformComponentsFactory.createFromContext(configuration.getAppContext())) .applicationName(configuration.getAppContext().getPackageName()) .applicationVersion(getPackageVersion(configuration.getAppContext())) diff --git a/msal/src/main/java/com/microsoft/identity/nativeauth/NativeAuthPublicClientApplication.kt b/msal/src/main/java/com/microsoft/identity/nativeauth/NativeAuthPublicClientApplication.kt index 2bf917de4..f5c0cd274 100644 --- a/msal/src/main/java/com/microsoft/identity/nativeauth/NativeAuthPublicClientApplication.kt +++ b/msal/src/main/java/com/microsoft/identity/nativeauth/NativeAuthPublicClientApplication.kt @@ -818,14 +818,32 @@ class NativeAuthPublicClientApplication( correlationId = null, methodName = "${TAG}.signInV2(parameters: NativeAuthSignInParameters, callback: NativeAuthV2Callback)" ) - val parametersSnapshot = NativeAuthSignInParameters(parameters.username).also { - it.password = parameters.password?.copyOf() - it.scopes = parameters.scopes?.toList() - it.claimsRequest = parameters.claimsRequest + val parametersSnapshot = NativeAuthSignInParameters(parameters.username) + val snapshotError = try { + parametersSnapshot.password = parameters.password?.copyOf() + parametersSnapshot.scopes = parameters.scopes?.toList() + parametersSnapshot.claimsRequest = parameters.claimsRequest?.let { claims -> + ClaimsRequest.getClaimsRequestFromJsonString(ClaimsRequest.getJsonStringFromClaimsRequest(claims)) + } + null + } catch (e: CancellationException) { + StringUtil.overwriteWithNull(parametersSnapshot.password) + throw e + } catch (e: Exception) { + StringUtil.overwriteWithNull(parametersSnapshot.password) + val correlationId = DiagnosticContext.INSTANCE.threadCorrelationId ?: "UNSET" + Logger.error(TAG, correlationId, "Exception thrown in signInV2", e) + NativeAuthErrorV2( + errorType = ErrorTypes.CLIENT_EXCEPTION, + errorMessage = "MSAL client exception occurred in signInV2.", + correlationId = correlationId, + scenario = NativeAuthFlowScenarioV2.SIGN_IN, + exception = e + ) } pcaScope.launchOwningPasswordSnapshot(parametersSnapshot.password) { try { - callback.onResult(signInV2(parametersSnapshot)) + callback.onResult(snapshotError ?: signInV2(parametersSnapshot)) } catch (e: MsalException) { Logger.error(TAG, "Exception thrown in signInV2", e) callback.onError(e) @@ -865,7 +883,9 @@ class NativeAuthPublicClientApplication( nativeAuthConfig.oAuth2TokenCache, parameters.username, passwordCopy, - parameters.attributes?.toMap() + parameters.attributes?.toMap(), + parameters.scopes?.toList(), + parameters.claimsRequest ) correlationId = cmdParams.correlationId ?: correlationId @@ -1034,15 +1054,35 @@ class NativeAuthPublicClientApplication( correlationId = null, methodName = "${TAG}.signUpV2(parameters: NativeAuthSignUpParameters, callback: NativeAuthV2Callback)" ) - val parametersSnapshot = NativeAuthSignUpParameters(parameters.username).also { - it.password = parameters.password?.copyOf() - it.attributes = parameters.attributes?.let { attributes -> + val parametersSnapshot = NativeAuthSignUpParameters(parameters.username) + val snapshotError = try { + parametersSnapshot.password = parameters.password?.copyOf() + parametersSnapshot.scopes = parameters.scopes?.toList() + parametersSnapshot.claimsRequest = parameters.claimsRequest?.let { claims -> + ClaimsRequest.getClaimsRequestFromJsonString(ClaimsRequest.getJsonStringFromClaimsRequest(claims)) + } + parametersSnapshot.attributes = parameters.attributes?.let { attributes -> UserAttributes(attributes.toMap()) } + null + } catch (e: CancellationException) { + StringUtil.overwriteWithNull(parametersSnapshot.password) + throw e + } catch (e: Exception) { + StringUtil.overwriteWithNull(parametersSnapshot.password) + val correlationId = DiagnosticContext.INSTANCE.threadCorrelationId ?: "UNSET" + Logger.error(TAG, correlationId, "Exception thrown in signUpV2", e) + NativeAuthErrorV2( + errorType = ErrorTypes.CLIENT_EXCEPTION, + errorMessage = "MSAL client exception occurred in signUpV2.", + correlationId = correlationId, + scenario = NativeAuthFlowScenarioV2.SIGN_UP, + exception = e + ) } pcaScope.launchOwningPasswordSnapshot(parametersSnapshot.password) { try { - callback.onResult(signUpV2(parametersSnapshot)) + callback.onResult(snapshotError ?: signUpV2(parametersSnapshot)) } catch (e: MsalException) { Logger.error(TAG, "Exception thrown in signUpV2", e) callback.onError(e) @@ -1076,7 +1116,9 @@ class NativeAuthPublicClientApplication( val cmdParams = CommandParametersAdapter.createResetPasswordV2StartCommandParameters( nativeAuthConfig, nativeAuthConfig.oAuth2TokenCache, - parameters.username + parameters.username, + parameters.scopes?.toList(), + parameters.claimsRequest ) correlationId = cmdParams.correlationId ?: correlationId @@ -1230,9 +1272,29 @@ class NativeAuthPublicClientApplication( correlationId = null, methodName = "${TAG}.resetPasswordV2(parameters: NativeAuthResetPasswordParameters, callback: NativeAuthV2Callback)" ) + val parametersSnapshot = NativeAuthResetPasswordParameters(parameters.username) + val snapshotError = try { + parametersSnapshot.scopes = parameters.scopes?.toList() + parametersSnapshot.claimsRequest = parameters.claimsRequest?.let { claims -> + ClaimsRequest.getClaimsRequestFromJsonString(ClaimsRequest.getJsonStringFromClaimsRequest(claims)) + } + null + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + val correlationId = DiagnosticContext.INSTANCE.threadCorrelationId ?: "UNSET" + Logger.error(TAG, correlationId, "Exception thrown in resetPasswordV2", e) + NativeAuthErrorV2( + errorType = ErrorTypes.CLIENT_EXCEPTION, + errorMessage = "MSAL client exception occurred in resetPasswordV2.", + correlationId = correlationId, + scenario = NativeAuthFlowScenarioV2.RESET_PASSWORD, + exception = e + ) + } pcaScope.launch { try { - callback.onResult(resetPasswordV2(parameters)) + callback.onResult(snapshotError ?: resetPasswordV2(parametersSnapshot)) } catch (e: MsalException) { Logger.error(TAG, "Exception thrown in resetPasswordV2", e) callback.onError(e) diff --git a/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthResetPasswordParameters.kt b/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthResetPasswordParameters.kt index f01ad7d31..04b9ae333 100644 --- a/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthResetPasswordParameters.kt +++ b/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthResetPasswordParameters.kt @@ -23,6 +23,8 @@ package com.microsoft.identity.nativeauth.parameters +import com.microsoft.identity.client.claims.ClaimsRequest + /** * Encapsulates the parameters passed to the resetPassword methods of NativeAuthPublicClientApplication. * @@ -30,4 +32,10 @@ package com.microsoft.identity.nativeauth.parameters */ class NativeAuthResetPasswordParameters( val username: String -) \ No newline at end of file +) { + /** V2-only requested scopes. Null or empty uses default OIDC scopes; ignored by V1. */ + var scopes: List? = null + + /** V2-only claims sent at authorize-challenge entry; ignored by V1. */ + var claimsRequest: ClaimsRequest? = null +} \ No newline at end of file diff --git a/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthSignInContinuationParameters.kt b/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthSignInContinuationParameters.kt index 0077d85b5..85b33f079 100644 --- a/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthSignInContinuationParameters.kt +++ b/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthSignInContinuationParameters.kt @@ -33,11 +33,13 @@ class NativeAuthSignInContinuationParameters { /** * Permissions you want included in the access token received. * Not all scopes are guaranteed to be included in the access token returned. + * For V2, null retains entry scopes; an explicit empty list requests only default OIDC scopes. */ var scopes: List? = null /** - * The claims parameter that needs to be sent to the service. + * Claims sent to the service in V1. In V2, claims are retained locally for token/cache + * semantics, but the token exchange omits claims; supply service claims at flow entry. */ var claimsRequest: ClaimsRequest? = null } \ No newline at end of file diff --git a/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthSignUpParameters.kt b/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthSignUpParameters.kt index ac07dbf13..21481980d 100644 --- a/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthSignUpParameters.kt +++ b/msal/src/main/java/com/microsoft/identity/nativeauth/parameters/NativeAuthSignUpParameters.kt @@ -24,6 +24,7 @@ package com.microsoft.identity.nativeauth.parameters import com.microsoft.identity.nativeauth.UserAttributes +import com.microsoft.identity.client.claims.ClaimsRequest /** * Encapsulates the parameters passed to the signUp methods of NativeAuthPublicClientApplication @@ -47,4 +48,10 @@ class NativeAuthSignUpParameters( * Supply them through the dedicated [username] and [password] properties instead. */ var attributes: UserAttributes? = null + + /** V2-only requested scopes. Null or empty uses default OIDC scopes; ignored by V1. */ + var scopes: List? = null + + /** V2-only claims sent at authorize-challenge entry; ignored by V1. */ + var claimsRequest: ClaimsRequest? = null } \ No newline at end of file diff --git a/msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/CodeRequiredStateV2.kt b/msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/CodeRequiredStateV2.kt index f6e436ade..f7e29631e 100644 --- a/msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/CodeRequiredStateV2.kt +++ b/msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/CodeRequiredStateV2.kt @@ -116,14 +116,6 @@ class CodeRequiredStateV2 internal constructor( methodName = "${TAG}.submitCode(code: String)" ) val state = continuationState ?: return invalidState() - if (code.isEmpty()) { - return NativeAuthErrorV2( - errorType = ErrorTypes.INVALID_CODE, - errorMessage = "Code cannot be empty.", - correlationId = correlationId, - scenario = scenario - ) - } if (scenario == NativeAuthFlowScenarioV2.UNKNOWN) { return invalidState() } diff --git a/msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/MFAVerificationRequiredStateV2.kt b/msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/MFAVerificationRequiredStateV2.kt index 17c82553d..39fb9aed7 100644 --- a/msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/MFAVerificationRequiredStateV2.kt +++ b/msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/MFAVerificationRequiredStateV2.kt @@ -127,14 +127,6 @@ class MFAVerificationRequiredStateV2 internal constructor( methodName = "${TAG}.submitChallenge(challenge: String)" ) val state = continuationState ?: return invalidState() - if (challenge.isEmpty()) { - return NativeAuthErrorV2( - errorType = ErrorTypes.INVALID_CODE, - errorMessage = "Challenge cannot be empty.", - correlationId = correlationId, - scenario = scenario - ) - } return withContext(Dispatchers.IO) { try { val parameters = CommandParametersAdapter.createNativeAuthV2SubmitMFAChallengeCommandParameters( diff --git a/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2InterfaceKotlinTest.kt b/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2InterfaceKotlinTest.kt index 66b220fa5..09062326f 100644 --- a/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2InterfaceKotlinTest.kt +++ b/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2InterfaceKotlinTest.kt @@ -34,6 +34,8 @@ import com.microsoft.identity.client.exception.MsalClientException import com.microsoft.identity.client.exception.MsalException import com.microsoft.identity.client.IAccount import com.microsoft.identity.client.IAuthenticationResult +import com.microsoft.identity.client.claims.ClaimsRequest +import com.microsoft.identity.client.claims.RequestedClaimAdditionalInformation import com.microsoft.identity.common.java.commands.BaseCommand import com.microsoft.identity.common.java.commands.ICommandResult import com.microsoft.identity.common.java.controllers.CommandDispatcher @@ -55,6 +57,7 @@ import com.microsoft.identity.common.java.nativeauth.providers.responses.v2.Nati import com.microsoft.identity.common.java.result.FinalizableResultFuture import com.microsoft.identity.common.java.result.ILocalAuthenticationResult import com.microsoft.identity.common.java.util.ResultFuture +import com.microsoft.identity.common.java.util.StringUtil import com.microsoft.identity.common.nativeauth.internal.commands.NativeAuthV2ResendCodeCommand import com.microsoft.identity.common.nativeauth.internal.commands.NativeAuthV2ResetPasswordSubmitCodeCommand import com.microsoft.identity.common.nativeauth.internal.commands.NativeAuthV2ResetPasswordStartCommand @@ -89,6 +92,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch @@ -114,6 +118,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.io.File import java.util.concurrent.CountDownLatch +import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import kotlin.reflect.KClass @@ -127,6 +132,265 @@ class NativeAuthV2InterfaceKotlinTest : PublicClientApplicationAbstractTest() { private lateinit var application: INativeAuthPublicClientApplication private val username = "user@email.com" + @Test + fun allV2EntriesPropagateNullableScopesAndTypedClaimsThroughAdapters() = runTest { + val claims = com.microsoft.identity.client.claims.ClaimsRequest().also { + it.requestClaimInIdToken("auth_time", null) + } + val expectedClaims = com.microsoft.identity.client.claims.ClaimsRequest.getJsonStringFromClaimsRequest(claims) + listOf?>(null, emptyList(), listOf("User.Read")).forEach { scopes -> + var captured: com.microsoft.identity.common.java.nativeauth.commands.parameters.BaseSignInTokenCommandParameters? = null + fun capture(command: BaseCommand<*>) { + captured = command.parameters as com.microsoft.identity.common.java.nativeauth.commands.parameters.BaseSignInTokenCommandParameters + } + fun assertCaptured() { + assertTrue(captured != null) + assertEquals(scopes, captured?.scopes) + assertEquals(expectedClaims, captured?.claimsRequestJson) + captured = null + } + val result = INativeAuthCommandResult.APIError("test_stop", "test stop", correlationId = correlationId) + enqueueResult(result, com.microsoft.identity.common.nativeauth.internal.commands.NativeAuthV2SignInStartCommand::class, ::capture) + application.signInV2(NativeAuthSignInParameters(username).also { + it.scopes = scopes + it.claimsRequest = claims + }) + assertCaptured() + enqueueResult(result, NativeAuthV2SignUpStartCommand::class, ::capture) + application.signUpV2(NativeAuthSignUpParameters(username).also { + it.scopes = scopes + it.claimsRequest = claims + }) + assertCaptured() + enqueueResult(result, NativeAuthV2ResetPasswordStartCommand::class, ::capture) + application.resetPasswordV2(NativeAuthResetPasswordParameters(username).also { + it.scopes = scopes + it.claimsRequest = claims + }) + assertCaptured() + } + } + + @Test + fun sharedEntryScopesAndClaimsDoNotChangeV1CommandInputsOrErrors() = runTest { + val claims = com.microsoft.identity.client.claims.ClaimsRequest().also { it.requestClaimInIdToken("auth_time", null) } + var signUpInputs: com.microsoft.identity.common.java.nativeauth.commands.parameters.SignUpStartCommandParameters? = null + var resetInputs: com.microsoft.identity.common.java.nativeauth.commands.parameters.ResetPasswordStartCommandParameters? = null + val result = INativeAuthCommandResult.APIError("test_stop", "test stop", correlationId = correlationId) + enqueueResult(result, com.microsoft.identity.common.nativeauth.internal.commands.SignUpStartCommand::class) { + signUpInputs = it.parameters as com.microsoft.identity.common.java.nativeauth.commands.parameters.SignUpStartCommandParameters + } + enqueueResult(result, com.microsoft.identity.common.nativeauth.internal.commands.ResetPasswordStartCommand::class) { + resetInputs = it.parameters as com.microsoft.identity.common.java.nativeauth.commands.parameters.ResetPasswordStartCommandParameters + } + val signUp = application.signUp(NativeAuthSignUpParameters(username).also { + it.scopes = listOf("V2.Only") + it.claimsRequest = claims + }) + val reset = application.resetPassword(NativeAuthResetPasswordParameters(username).also { + it.scopes = listOf("V2.Only") + it.claimsRequest = claims + }) + assertTrue(signUp is com.microsoft.identity.nativeauth.statemachine.errors.SignUpError) + assertTrue(reset is com.microsoft.identity.nativeauth.statemachine.errors.ResetPasswordError) + assertEquals(username, signUpInputs?.username) + assertEquals(null, signUpInputs?.userAttributes) + assertEquals(null, signUpInputs?.password) + assertEquals(username, resetInputs?.username) + assertEquals("test_stop", (reset as com.microsoft.identity.nativeauth.statemachine.errors.ResetPasswordError).error) + } + + @Test + fun resetPasswordCallbackSnapshotsScopesAndMutableClaimsBeforeLaunch() = runTest { + val scopes = mutableListOf("User.Read") + val claims = com.microsoft.identity.client.claims.ClaimsRequest().also { + it.requestClaimInIdToken("auth_time", null) + } + val expectedClaims = com.microsoft.identity.client.claims.ClaimsRequest.getJsonStringFromClaimsRequest(claims) + var captured: com.microsoft.identity.common.java.nativeauth.commands.parameters.BaseSignInTokenCommandParameters? = null + enqueueResult( + INativeAuthCommandResult.APIError("test_stop", "test stop", correlationId = correlationId), + NativeAuthV2ResetPasswordStartCommand::class + ) { command -> + captured = command.parameters as com.microsoft.identity.common.java.nativeauth.commands.parameters.BaseSignInTokenCommandParameters + } + val parameters = NativeAuthResetPasswordParameters(username).also { + it.scopes = scopes + it.claimsRequest = claims + } + val future = ResultFuture() + application.resetPasswordV2(parameters, object : NativeAuthPublicClientApplication.NativeAuthV2Callback { + override fun onResult(result: NativeAuthResultV2) = future.setResult(result) + override fun onError(exception: BaseException) = future.setException(exception) + }) + scopes.clear() + claims.requestClaimInIdToken("changed", null) + parameters.claimsRequest = null + assertTrue(future.get(30, TimeUnit.SECONDS) is NativeAuthErrorV2) + assertTrue(captured != null) + assertEquals(listOf("User.Read"), captured?.scopes) + assertEquals(expectedClaims, captured?.claimsRequestJson) + } + + @Test + fun callbackSnapshotFailuresReturnClientExceptionsOnPcaScopeAndClearOwnedPasswords() { + val claims = ClaimsRequest().also { + it.requestClaimInIdToken("auth_time", RequestedClaimAdditionalInformation().also { info -> + info.setValues(null) + }) + } + val clearedPasswords = CopyOnWriteArrayList() + mockkStatic(StringUtil::class) + mockkObject(DiagnosticContext.INSTANCE) + try { + every { DiagnosticContext.INSTANCE.threadCorrelationId } returns correlationId + every { StringUtil.overwriteWithNull(any()) } answers { + firstArg()?.let { clearedPasswords.add(it) } + callOriginal() + } + listOf( + NativeAuthFlowScenarioV2.SIGN_IN, + NativeAuthFlowScenarioV2.SIGN_UP, + NativeAuthFlowScenarioV2.RESET_PASSWORD + ).forEach { scenario -> + clearedPasswords.clear() + val password = "Password123!".toCharArray() + val callerThread = Thread.currentThread() + val future = ResultFuture() + var callbackThread: Thread? = null + var scopeChildActive = false + val callback = object : NativeAuthPublicClientApplication.NativeAuthV2Callback { + override fun onResult(result: NativeAuthResultV2) { + callbackThread = Thread.currentThread() + scopeChildActive = NativeAuthPublicClientApplication.pcaScope + .coroutineContext[Job]!!.children.any { it.isActive } + future.setResult(result) + } + override fun onError(exception: BaseException) = future.setException(exception) + } + invokeCallbackEntry(scenario, password, claims, null, callback) + + assertEquals("Password123!", String(password)) + if (scenario == NativeAuthFlowScenarioV2.RESET_PASSWORD) { + assertTrue(clearedPasswords.isEmpty()) + } else { + assertTrue(clearedPasswords.isNotEmpty()) + } + clearedPasswords.forEach { + assertTrue(it !== password) + assertTrue(it.all { char -> char == '\u0000' }) + } + val error = future.get(30, TimeUnit.SECONDS) as NativeAuthErrorV2 + assertTrue(callbackThread !== callerThread) + assertTrue(scopeChildActive) + assertEquals(ErrorTypes.CLIENT_EXCEPTION, error.errorType) + assertEquals(scenario, error.scenario) + assertEquals(correlationId, error.correlationId) + assertTrue(error.exception is NullPointerException) + runBlocking { + NativeAuthPublicClientApplication.pcaScope.coroutineContext[Job]!! + .children.toList().forEach { it.join() } + } + } + } finally { + unmockkObject(DiagnosticContext.INSTANCE) + unmockkStatic(StringUtil::class) + } + } + + @Test + fun callbackSnapshotCancellationIsRethrownAndClearsOnlyOwnedPasswords() { + val cancellation = CancellationException("snapshot cancelled") + val scopes = object : AbstractList() { + override val size: Int get() = throw cancellation + override fun get(index: Int): String = throw cancellation + } + val clearedPasswords = mutableListOf() + mockkStatic(StringUtil::class) + try { + every { StringUtil.overwriteWithNull(any()) } answers { + firstArg()?.let { clearedPasswords.add(it) } + callOriginal() + } + listOf( + NativeAuthFlowScenarioV2.SIGN_IN, + NativeAuthFlowScenarioV2.SIGN_UP, + NativeAuthFlowScenarioV2.RESET_PASSWORD + ).forEach { scenario -> + clearedPasswords.clear() + val password = "Password123!".toCharArray() + val callback = object : NativeAuthPublicClientApplication.NativeAuthV2Callback { + override fun onResult(result: NativeAuthResultV2) { fail("Cancellation must not deliver a result") } + override fun onError(exception: BaseException) { fail("Cancellation must not deliver an error") } + } + try { + invokeCallbackEntry(scenario, password, null, scopes, callback) + fail("Expected CancellationException") + } catch (e: CancellationException) { + assertSame(cancellation, e) + } + assertEquals("Password123!", String(password)) + assertEquals(if (scenario == NativeAuthFlowScenarioV2.RESET_PASSWORD) 0 else 1, clearedPasswords.size) + clearedPasswords.forEach { + assertTrue(it !== password) + assertTrue(it.all { char -> char == '\u0000' }) + } + } + } finally { + unmockkStatic(StringUtil::class) + } + } + + @Test + fun callbackSnapshotFailuresPreserveCallbackExceptionRouting() { + val claims = ClaimsRequest().also { + it.requestClaimInIdToken("auth_time", RequestedClaimAdditionalInformation().also { info -> + info.setValues(null) + }) + } + listOf( + NativeAuthFlowScenarioV2.SIGN_IN, + NativeAuthFlowScenarioV2.SIGN_UP, + NativeAuthFlowScenarioV2.RESET_PASSWORD + ).forEach { scenario -> + assertRoutesToOnError { future -> + invokeCallbackEntry(scenario, "Password123!".toCharArray(), claims, null, throwingCallback(future)) + } + } + } + + private fun invokeCallbackEntry( + scenario: NativeAuthFlowScenarioV2, + password: CharArray, + claims: ClaimsRequest?, + scopes: List?, + callback: NativeAuthPublicClientApplication.NativeAuthV2Callback + ) { + when (scenario) { + NativeAuthFlowScenarioV2.SIGN_IN -> application.signInV2( + NativeAuthSignInParameters(username).also { + it.password = password + it.claimsRequest = claims + it.scopes = scopes + }, callback + ) + NativeAuthFlowScenarioV2.SIGN_UP -> application.signUpV2( + NativeAuthSignUpParameters(username).also { + it.password = password + it.claimsRequest = claims + it.scopes = scopes + }, callback + ) + NativeAuthFlowScenarioV2.RESET_PASSWORD -> application.resetPasswordV2( + NativeAuthResetPasswordParameters(username).also { + it.claimsRequest = claims + it.scopes = scopes + }, callback + ) + else -> fail("Unexpected entry scenario: $scenario") + } + } + override fun getConfigFilePath() = "src/test/res/raw/native_auth_native_only_test_config.json" @Before @@ -573,12 +837,21 @@ class NativeAuthV2InterfaceKotlinTest : PublicClientApplicationAbstractTest() { } @Test - fun submitCodeRejectsEmptyInputWithRetryableInvalidCodeError() = runTest { + fun submitCodeSendsEmptyAndShortInputToServiceAndRemainsRetryable() = runTest { val state = codeRequiredState() - val error = state.submitCode("") as NativeAuthErrorV2 - - assertTrue(error.isInvalidCode()) + listOf("", "1").forEach { code -> + var submittedCode: String? = null + enqueueResult( + NativeAuthV2CommandResult.IncorrectCode(correlationId, "invalidGrant", "invalid", "invalidOneTimeCode"), + NativeAuthV2ResetPasswordSubmitCodeCommand::class + ) { command -> + submittedCode = (command.parameters as com.microsoft.identity.common.java.nativeauth.commands.parameters.NativeAuthV2SubmitCodeCommandParameters).code + } + val error = state.submitCode(code) as NativeAuthErrorV2 + assertTrue(error.isInvalidCode()) + assertEquals(code, submittedCode) + } } @Test diff --git a/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2SignInTest.kt b/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2SignInTest.kt index a0119d683..9ee4ad63d 100644 --- a/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2SignInTest.kt +++ b/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2SignInTest.kt @@ -379,17 +379,25 @@ class NativeAuthV2SignInTest : PublicClientApplicationAbstractTest() { @Test fun signInV2CallbackSnapshotsThePasswordSynchronouslyBeforeLaunch() = runTest { var capturedPassword: CharArray? = null + var capturedScopes: List? = null + var capturedClaims: String? = null enqueueResult( NativeAuthV2CommandResult.PasswordRequired(correlationId, createContinuationState()), NativeAuthV2SignInStartCommand::class ) { command -> - capturedPassword = (command.parameters as SignInV2StartCommandParameters).password?.copyOf() + val commandParameters = command.parameters as SignInV2StartCommandParameters + capturedPassword = commandParameters.password?.copyOf() + capturedScopes = commandParameters.scopes + capturedClaims = commandParameters.claimsRequestJson } val callerPassword = "Password123!".toCharArray() val future = ResultFuture() + val scopes = mutableListOf("User.Read") + val claims = com.microsoft.identity.client.claims.ClaimsRequest().also { it.requestClaimInIdToken("auth_time", null) } + val expectedClaims = com.microsoft.identity.client.claims.ClaimsRequest.getJsonStringFromClaimsRequest(claims) application.signInV2( - signInParameters(password = callerPassword), + signInParameters(password = callerPassword, scopes = scopes).also { it.claimsRequest = claims }, object : NativeAuthPublicClientApplication.NativeAuthV2Callback { override fun onResult(result: NativeAuthResultV2) = future.setResult(result) override fun onError(exception: BaseException) = future.setException(exception) @@ -400,10 +408,14 @@ class NativeAuthV2SignInTest : PublicClientApplicationAbstractTest() { // the coroutine body, as opposed to synchronously before launch), this mutation could race // with -- and change -- what actually gets submitted to Common. callerPassword.fill('X') + scopes.clear() + claims.requestClaimInIdToken("changed", null) future.get(10, TimeUnit.SECONDS) assertEquals("Password123!", String(capturedPassword!!)) + assertEquals(listOf("User.Read"), capturedScopes) + assertEquals(expectedClaims, capturedClaims) } @Test @@ -986,13 +998,22 @@ class NativeAuthV2SignInTest : PublicClientApplicationAbstractTest() { } @Test - fun submitChallengeRejectsAnEmptyCodeWithoutIssuingACommand() = runTest { + fun submitChallengeSendsEmptyAndShortCodesToServiceAndRemainsRetryable() = runTest { val verificationState = mfaVerificationState(mfaRequiredState()) - val result = verificationState.submitChallenge("") as NativeAuthErrorV2 - - assertTrue(result.isInvalidChallenge()) - assertEquals(ErrorTypes.INVALID_CODE, result.errorType) + listOf("", "1").forEach { code -> + var submittedCode: String? = null + enqueueResult( + NativeAuthV2CommandResult.IncorrectCode(correlationId, "invalidGrant", "invalid", "invalidOneTimeCode"), + NativeAuthV2SubmitMFAChallengeCommand::class + ) { command -> + submittedCode = (command.parameters as com.microsoft.identity.common.java.nativeauth.commands.parameters.NativeAuthV2SubmitMFAChallengeCommandParameters).code + } + val result = verificationState.submitChallenge(code) as NativeAuthErrorV2 + assertTrue(result.isInvalidChallenge()) + assertTrue(result.isInvalidCode()) + assertEquals(code, submittedCode) + } } @Test diff --git a/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2SignUpTest.kt b/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2SignUpTest.kt index d375cf107..a69bd88c4 100644 --- a/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2SignUpTest.kt +++ b/msal/src/test/java/com/microsoft/identity/nativeauth/v2/NativeAuthV2SignUpTest.kt @@ -462,6 +462,8 @@ class NativeAuthV2SignUpTest : PublicClientApplicationAbstractTest() { var capturedUsername: String? = null var capturedPassword: CharArray? = null var capturedAttributes: Map? = null + var capturedScopes: List? = null + var capturedClaims: String? = null enqueueResult( NativeAuthV2CommandResult.PasswordRequired(correlationId, createContinuationState()), NativeAuthV2SignUpStartCommand::class @@ -470,6 +472,8 @@ class NativeAuthV2SignUpTest : PublicClientApplicationAbstractTest() { capturedUsername = commandParameters.username capturedPassword = commandParameters.password?.copyOf() capturedAttributes = commandParameters.attributes?.toMap() + capturedScopes = commandParameters.scopes + capturedClaims = commandParameters.claimsRequestJson } val callerPassword = "Password123!".toCharArray() @@ -479,6 +483,11 @@ class NativeAuthV2SignUpTest : PublicClientApplicationAbstractTest() { password = callerPassword, attributes = attributesBuilder.build() ) + val scopes = mutableListOf("User.Read") + val claims = com.microsoft.identity.client.claims.ClaimsRequest().also { it.requestClaimInIdToken("auth_time", null) } + val expectedClaims = com.microsoft.identity.client.claims.ClaimsRequest.getJsonStringFromClaimsRequest(claims) + parameters.scopes = scopes + parameters.claimsRequest = claims val future = ResultFuture() application.signUpV2( parameters, @@ -491,12 +500,17 @@ class NativeAuthV2SignUpTest : PublicClientApplicationAbstractTest() { attributesBuilder.city("Seattle") parameters.password = null parameters.attributes = null + scopes.clear() + claims.requestClaimInIdToken("changed", null) + parameters.claimsRequest = null future.get(10, TimeUnit.SECONDS) assertEquals(username, capturedUsername) assertEquals("Password123!", String(capturedPassword!!)) assertEquals(mapOf("city" to "Redmond"), capturedAttributes) + assertEquals(listOf("User.Read"), capturedScopes) + assertEquals(expectedClaims, capturedClaims) } @Test