From e0c63e8daa51b2394ed82cfa520924d00276cd05 Mon Sep 17 00:00:00 2001 From: Silviu Petrescu Date: Wed, 30 Sep 2026 16:52:07 +0100 Subject: [PATCH 01/16] add scopes for sign in --- .../v2/NativeAuthV2FlowController.kt | 2 +- .../providers/NativeAuthV2OAuth2Strategy.kt | 4 +-- .../interactors/NativeAuthV2Interactor.kt | 5 +++- .../v2/AuthorizeChallengeStartRequest.kt | 27 ++++++++++++++++--- .../v2/NativeAuthV2RequestProvider.kt | 13 ++++++++- 5 files changed, 43 insertions(+), 8 deletions(-) diff --git a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt index 92ba4d9d5d..eea7e84883 100644 --- a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt +++ b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt @@ -680,7 +680,7 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = correlationId, entryRelation = NativeAuthV2LinkRelation.SIGN_IN.value, scenario = NativeAuthV2FlowScenario.SIGN_IN, - scopes = parameters.scopes ?: emptyList(), + scopes = addDefaultScopes(parameters.scopes), claimsRequestJson = parameters.claimsRequestJson ) diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/NativeAuthV2OAuth2Strategy.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/NativeAuthV2OAuth2Strategy.kt index 3b1d28fd58..708de13fd3 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/NativeAuthV2OAuth2Strategy.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/NativeAuthV2OAuth2Strategy.kt @@ -79,8 +79,8 @@ class NativeAuthV2OAuth2Strategy( * * [entryRelation] is accepted as a raw relation string at this public boundary for Java * interoperability, then wrapped immediately into [NativeAuthV2LinkRelation] for internal - * type safety. [scopes] are retained only for the later authorization-code token exchange; - * they are not sent on the authorize-challenge request itself. + * type safety. [scopes] are sent on the initial authorize-challenge request and retained for + * the later authorization-code token exchange. */ fun performAuthorizeChallengeStart( correlationId: String, diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2Interactor.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2Interactor.kt index fe9e16f629..25a8cbcf72 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2Interactor.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2Interactor.kt @@ -86,7 +86,10 @@ class NativeAuthV2Interactor( methodName = "$TAG.performAuthorizeChallengeStart" ) - val request = requestProvider.createAuthorizeChallengeStartRequest(correlationId = correlationId) + val request = requestProvider.createAuthorizeChallengeStartRequest( + correlationId = correlationId, + scopes = scopes + ) Logger.infoWithObject( "$TAG.performAuthorizeChallengeStart", diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/AuthorizeChallengeStartRequest.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/AuthorizeChallengeStartRequest.kt index a8070c02ab..c4aa7248b0 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/AuthorizeChallengeStartRequest.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/AuthorizeChallengeStartRequest.kt @@ -43,8 +43,24 @@ data class AuthorizeChallengeStartRequest private constructor( clientId: String, requestUrl: String, headers: Map + ): AuthorizeChallengeStartRequest = create( + clientId = clientId, + scopes = emptyList(), + requestUrl = requestUrl, + headers = headers + ) + + fun create( + clientId: String, + scopes: List, + requestUrl: String, + headers: Map ): AuthorizeChallengeStartRequest { ArgUtils.validateNonNullArg(clientId, "clientId") + ArgUtils.validateNonNullArg(scopes, "scopes") + scopes.forEachIndexed { index, scope -> + ArgUtils.validateNonNullArg(scope, "scopes[$index]") + } ArgUtils.validateNonNullArg(requestUrl, "requestUrl") ArgUtils.validateNonNullArg(headers, "headers") @@ -52,7 +68,8 @@ data class AuthorizeChallengeStartRequest private constructor( requestUrl = URL(requestUrl), headers = headers, parameters = NativeAuthAuthorizeChallengeStartRequestParameters( - clientId = clientId + clientId = clientId, + scope = scopes.takeUnless { it.isEmpty() }?.joinToString(" ") ) ) } @@ -67,9 +84,13 @@ data class AuthorizeChallengeStartRequest private constructor( * part of the `/oauth2/v2.0/authorize-challenge` API call that starts a Native Auth V2 flow. */ data class NativeAuthAuthorizeChallengeStartRequestParameters( - @SerializedName("client_id") override val clientId: String + @SerializedName("client_id") override val clientId: String, + @SerializedName("scope") val scope: String? = null ) : NativeAuthRequestParameters() { - override fun toUnsanitizedString(): String = "NativeAuthAuthorizeChallengeStartRequestParameters(clientId=$clientId)" + constructor(clientId: String) : this(clientId, null) + + override fun toUnsanitizedString(): String = + "NativeAuthAuthorizeChallengeStartRequestParameters(clientId=$clientId, scope=$scope)" override fun toString(): String = toUnsanitizedString() } diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2RequestProvider.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2RequestProvider.kt index 09c2d0c6b1..1cadd1bfa2 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2RequestProvider.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2RequestProvider.kt @@ -56,7 +56,17 @@ class NativeAuthV2RequestProvider( * Creates the request object for the first call of a Native Auth V2 flow to * `/oauth2/v2.0/authorize-challenge`. */ - fun createAuthorizeChallengeStartRequest(correlationId: String): AuthorizeChallengeStartRequest { + fun createAuthorizeChallengeStartRequest( + correlationId: String + ): AuthorizeChallengeStartRequest = createAuthorizeChallengeStartRequest( + correlationId = correlationId, + scopes = emptyList() + ) + + fun createAuthorizeChallengeStartRequest( + correlationId: String, + scopes: List + ): AuthorizeChallengeStartRequest { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, @@ -65,6 +75,7 @@ class NativeAuthV2RequestProvider( return AuthorizeChallengeStartRequest.create( clientId = config.clientId, + scopes = scopes, requestUrl = config.getNativeAuthV2AuthorizeChallengeEndpoint(correlationId).toString(), headers = getV2RequestHeaders(correlationId, NativeAuthContentType.FORM_URL_ENCODED) ) From 52e5eb6b3ca1cd5690ce97f7b3f7461b2fd4ea57 Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Mon, 12 Oct 2026 11:36:01 -0700 Subject: [PATCH 02/16] Send Native Auth V2 entry scopes and claims with JS token parity Fixes AB#3784690 Initial authorize-challenge carries scopes and claims; token carries scope only. Preserve continuation and local claims metadata. Include JS8898 OTP service-validation parity without altering V1. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 0bcd671b-73fa-4ee6-bcd6-65d7eea4d753 --- .../v2/NativeAuthV2FlowController.kt | 51 +++++++++++------- .../v2/NativeAuthV2SSPRFlowControllerTest.kt | 54 +++++++++++++++---- .../NativeAuthV2SignInFlowControllerTest.kt | 2 +- .../NativeAuthV2SignUpFlowControllerTest.kt | 34 +++++++++++- .../BaseSignInTokenCommandParameters.java | 3 +- .../interactors/NativeAuthV2Interactor.kt | 3 +- .../v2/AuthorizeChallengeStartRequest.kt | 21 +++++--- .../requests/v2/NativeAuthV2TokenRequest.kt | 3 +- .../requests/v2/NativeAuthV2VerifyRequest.kt | 1 - .../v2/NativeAuthV2RequestProvider.kt | 8 +++ .../interactors/NativeAuthV2InteractorTest.kt | 23 +++++--- .../NativeAuthV2RequestSerializationTest.kt | 46 ++++++++++++++++ .../v2/NativeAuthV2TokenRequestTest.kt | 7 ++- 13 files changed, 204 insertions(+), 52 deletions(-) diff --git a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt index eea7e84883..40fc7a88e6 100644 --- a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt +++ b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt @@ -22,6 +22,7 @@ // THE SOFTWARE. package com.microsoft.identity.common.nativeauth.internal.controllers.v2 +import com.microsoft.identity.common.java.AuthenticationConstants import com.microsoft.identity.common.java.logging.LogSession import com.microsoft.identity.common.java.logging.Logger import com.microsoft.identity.common.java.nativeauth.commands.parameters.BaseSignInTokenCommandParameters @@ -77,6 +78,16 @@ import lombok.EqualsAndHashCode @EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true) class NativeAuthV2FlowController : BaseNativeAuthController() { + private fun addV2DefaultScopes(scopes: List?): List { + val requestedScopes = scopes?.filterNotNull()?.filter { it.isNotEmpty() }?.toMutableList() ?: mutableListOf() + AuthenticationConstants.DEFAULT_SCOPES.forEach { defaultScope -> + if (requestedScopes.none { it.equals(defaultScope, ignoreCase = true) }) { + requestedScopes.add(defaultScope) + } + } + return requestedScopes + } + companion object { private val TAG = NativeAuthV2FlowController::class.java.simpleName @@ -152,8 +163,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = correlationId, entryRelation = NativeAuthV2LinkRelation.RESET_PASSWORD.value, scenario = NativeAuthV2FlowScenario.RESET_PASSWORD, - scopes = emptyList(), - claimsRequestJson = null + scopes = addV2DefaultScopes(parameters.scopes), + claimsRequestJson = parameters.claimsRequestJson ) val initialState = when (authChallengeResult) { @@ -177,6 +188,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -188,8 +201,6 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) val challenge = when (startResult) { - subError = authChallengeResult.subError, - attributeValidationDetails = authChallengeResult.attributeValidationDetails, is NativeAuthV2InteractionApiResult.ChallengeRequired -> startResult is NativeAuthV2InteractionApiResult.UserNotFound -> return NativeAuthV2CommandResult.UserNotFound( correlationId = startResult.correlationId, @@ -680,7 +691,7 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = correlationId, entryRelation = NativeAuthV2LinkRelation.SIGN_IN.value, scenario = NativeAuthV2FlowScenario.SIGN_IN, - scopes = addDefaultScopes(parameters.scopes), + scopes = addV2DefaultScopes(parameters.scopes), claimsRequestJson = parameters.claimsRequestJson ) @@ -705,6 +716,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -716,8 +729,6 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) val firstFactorChallenge = when (startResult) { - subError = authChallengeResult.subError, - attributeValidationDetails = authChallengeResult.attributeValidationDetails, is NativeAuthV2InteractionApiResult.ChallengeRequired -> startResult is NativeAuthV2InteractionApiResult.UserNotFound -> return NativeAuthV2CommandResult.UserNotFound( correlationId = startResult.correlationId, @@ -1010,8 +1021,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { methodName = "$TAG.completeFlow" ) - val scopes = addDefaultScopes(parameters.scopes) + val scopes = addV2DefaultScopes(parameters.scopes ?: state.scopesForTokenRequest()) val claimsRequestJson = parameters.claimsRequestJson?.takeUnless { it.isBlank() } + ?: state.claimsRequestJsonForTokenRequest()?.takeUnless { it.isBlank() } return exchangeCodeAndSaveTokens( oAuth2Strategy = oAuth2Strategy, tokenCommandParameters = parameters.toBuilder() @@ -1037,7 +1049,7 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return exchangeCodeAndSaveTokens( oAuth2Strategy = oAuth2Strategy, tokenCommandParameters = parametersBuilder - .scopes(addDefaultScopes(scopes)) + .scopes(addV2DefaultScopes(scopes)) .claimsRequestJson(claimsRequestJson?.takeUnless { it.isBlank() }) .build(), state = state @@ -1077,6 +1089,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = continueResult.error, errorDescription = continueResult.errorDescription, errorCodes = continueResult.errorCodes, + subError = continueResult.subError, + attributeValidationDetails = continueResult.attributeValidationDetails, correlationId = continueResult.correlationId ) } @@ -1089,8 +1103,6 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { claimsRequestJson = tokenCommandParameters.claimsRequestJson ) - subError = continueResult.subError, - attributeValidationDetails = continueResult.attributeValidationDetails, val successTokenResult = when (tokenResult) { is SignInTokenApiResult.Success -> tokenResult is SignInTokenApiResult.Redirect -> return INativeAuthCommandResult.Redirect( @@ -1103,6 +1115,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = tokenResult.error, errorDescription = tokenResult.errorDescription, errorCodes = tokenResult.errorCodes, + subError = tokenResult.subError, + attributeValidationDetails = tokenResult.attributeValidationDetails, correlationId = tokenResult.correlationId ) } @@ -1115,8 +1129,6 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) return NativeAuthV2CommandResult.Complete( - subError = tokenResult.subError, - attributeValidationDetails = tokenResult.attributeValidationDetails, correlationId = complete.correlationId, authenticationResult = complete.authenticationResult, continuationToken = null, @@ -1163,7 +1175,7 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = correlationId, entryRelation = NativeAuthV2LinkRelation.SIGN_UP.value, scenario = NativeAuthV2FlowScenario.SIGN_UP, - scopes = parameters.scopes ?: emptyList(), + scopes = addV2DefaultScopes(parameters.scopes), claimsRequestJson = parameters.claimsRequestJson ) @@ -1187,6 +1199,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -1199,8 +1213,6 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { result = startResult, retryState = null, upfront = parameters - subError = authChallengeResult.subError, - attributeValidationDetails = authChallengeResult.attributeValidationDetails, ) return result as? NativeAuthV2SignUpStartCommandResult ?: unexpectedSignUpApiError(result, correlationId) @@ -1516,11 +1528,10 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { methodName = "$TAG.completeFlowSignUp" ) - val requestedScopes = parameters.scopes?.takeUnless { it.isEmpty() } - ?: state.scopesForTokenRequest() - val scopes = addDefaultScopes(requestedScopes) + val requestedScopes = parameters.scopes ?: state.scopesForTokenRequest() + val scopes = addV2DefaultScopes(requestedScopes) val claimsRequestJson = parameters.claimsRequestJson?.takeUnless { it.isBlank() } - ?: state.claimsRequestJsonForTokenRequest() + ?: state.claimsRequestJsonForTokenRequest()?.takeUnless { it.isBlank() } return exchangeCodeAndSaveTokens( oAuth2Strategy = oAuth2Strategy, tokenCommandParameters = parameters.toBuilder() diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SSPRFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SSPRFlowControllerTest.kt index 8fc052bfc8..0310380726 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SSPRFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SSPRFlowControllerTest.kt @@ -145,7 +145,7 @@ class NativeAuthV2SSPRFlowControllerTest { private fun signInAfterResetPasswordParameters( state: NativeAuthV2ContinuationState, - scopes: List = emptyList(), + scopes: List? = null, claimsRequestJson: String? = null ): NativeAuthV2SignInAfterResetPasswordCommandParameters = NativeAuthV2SignInAfterResetPasswordCommandParameters.builder() @@ -162,7 +162,7 @@ class NativeAuthV2SSPRFlowControllerTest { // ----------------------------------------------------------------------------------------- @Test - fun testResetPasswordStartDoesNotSendTokenScopesOrClaims() { + fun testResetPasswordStartSendsDefaultScopesAndEntryClaims() { val claimsRequestJson = """{"access_token":{"xms_cc":{"values":["cp1"]}}}""" every { @@ -170,8 +170,8 @@ class NativeAuthV2SSPRFlowControllerTest { correlationId = correlationId, entryRelation = any(), scenario = any(), - scopes = emptyList(), - claimsRequestJson = null + scopes = match { it.toSet() == setOf("openid", "profile", "offline_access") }, + claimsRequestJson = claimsRequestJson ) } returns AuthorizeChallengeApiResult.UnknownError( correlationId = correlationId, @@ -188,8 +188,25 @@ class NativeAuthV2SSPRFlowControllerTest { correlationId = correlationId, entryRelation = any(), scenario = any(), - scopes = emptyList(), - claimsRequestJson = null + scopes = match { it.toSet() == setOf("openid", "profile", "offline_access") }, + claimsRequestJson = claimsRequestJson + ) + } + } + + @Test + fun testEntryExplicitOidcScopesDoNotDuplicateDefaultsIgnoringCase() { + every { mockStrategy.performAuthorizeChallengeStart(any(), any(), any(), any(), any()) } returns + AuthorizeChallengeApiResult.UnknownError(correlationId, "test_stop", "test stop") + controller.resetPasswordStart( + resetPasswordStartParameters().toBuilder().scopes(listOf("OPENID", "User.Read")).build() + ) + verify(exactly = 1) { + mockStrategy.performAuthorizeChallengeStart( + correlationId, any(), any(), + match { it.size == 4 && it.contains("OPENID") && it.contains("User.Read") && + it.containsAll(listOf("profile", "offline_access")) }, + null ) } } @@ -836,7 +853,7 @@ class NativeAuthV2SSPRFlowControllerTest { } @Test - fun testSignInAfterResetPasswordTreatsBlankCallerClaimsAsAbsentWithoutFallback() { + fun testSignInAfterResetPasswordTreatsBlankCallerClaimsAsAbsentAndRetainsEntryClaims() { val state = mockContinuationState() val flowScopes = listOf("openid", "offline_access") val flowClaims = """{"id_token":{"auth_time":{"essential":true}}}""" @@ -846,7 +863,7 @@ class NativeAuthV2SSPRFlowControllerTest { every { mockStrategy.performAuthorizeChallengeContinue(state) } returns AuthorizeChallengeApiResult.AuthorizationCode(correlationId, "auth-code") every { - mockStrategy.performTokenRequest(any(), any(), any(), null) + mockStrategy.performTokenRequest(any(), any(), any(), flowClaims) } returns SignInTokenApiResult.UnknownError( correlationId = correlationId, error = "invalid_grant", @@ -865,7 +882,7 @@ class NativeAuthV2SSPRFlowControllerTest { it.toSet() == setOf("openid", "offline_access", "profile") }, correlationId = correlationId, - claimsRequestJson = null + claimsRequestJson = flowClaims ) } } @@ -959,4 +976,23 @@ class NativeAuthV2SSPRFlowControllerTest { assertEquals(ClientException.TOKEN_CACHE_SAVE_FAILED, thrown.errorCode) } + + @Test + fun testContinuationNullScopesRetainEntryButExplicitEmptyUsesOnlyDefaults() { + val state = mockContinuationState() + every { state.scopesForTokenRequest() } returns listOf("Retained.Scope") + every { state.claimsRequestJsonForTokenRequest() } returns null + every { mockStrategy.performAuthorizeChallengeContinue(state) } returns + AuthorizeChallengeApiResult.AuthorizationCode(correlationId, "auth-code") + every { mockStrategy.performTokenRequest(any(), any(), any(), any()) } returns + SignInTokenApiResult.UnknownError(correlationId, "test_stop", "test stop", emptyList()) + listOf?>(null, emptyList()).forEach { scopes -> + controller.signInAfterResetPassword(signInAfterResetPasswordParameters(state, scopes)) + val expected = setOf("openid", "profile", "offline_access") + + if (scopes == null) setOf("Retained.Scope") else emptySet() + verify(exactly = 1) { + mockStrategy.performTokenRequest("auth-code", match { it.toSet() == expected }, correlationId, null) + } + } + } } diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt index 7d62e9b53d..4611e6c2c0 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt @@ -424,7 +424,7 @@ class NativeAuthV2SignInFlowControllerTest { correlationId = correlationId, entryRelation = "signIn", scenario = any(), - scopes = listOf("User.Read"), + scopes = match { it.toSet() == setOf("User.Read", "openid", "profile", "offline_access") }, claimsRequestJson = claims ) } diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt index 2eae4a90f5..01fae464d7 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt @@ -44,6 +44,7 @@ import com.microsoft.identity.common.java.providers.microsoft.microsoftsts.Micro import com.microsoft.identity.common.java.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy import com.microsoft.identity.common.java.providers.microsoft.microsoftsts.MicrosoftStsTokenResponse import com.microsoft.identity.common.java.providers.oauth2.OAuth2TokenCache +import io.mockk.clearMocks import io.mockk.every import io.mockk.mockk import io.mockk.slot @@ -603,7 +604,7 @@ class NativeAuthV2SignUpFlowControllerTest { errorCodes = emptyList() ) - controller.signInAfterSignUp(signInAfterSignUpParameters(state)) + controller.signInAfterSignUp(signInAfterSignUpParameters(state, scopes = null)) verify(exactly = 1) { mockStrategy.performTokenRequest( @@ -613,6 +614,15 @@ class NativeAuthV2SignUpFlowControllerTest { claimsRequestJson = any() ) } + controller.signInAfterSignUp(signInAfterSignUpParameters(state, scopes = emptyList())) + verify(exactly = 1) { + mockStrategy.performTokenRequest( + code = "auth-code", + scopes = match { it.toSet() == setOf("openid", "profile", "offline_access") }, + correlationId = correlationId, + claimsRequestJson = any() + ) + } } @Test @@ -701,6 +711,26 @@ class NativeAuthV2SignUpFlowControllerTest { assertEquals(ClientException.TOKEN_CACHE_SAVE_FAILED, thrown.errorCode) } + @Test + fun testSignUpEntrySendsDefaultScopesAndClaimsForNullEmptyAndExplicitScopes() { + every { mockStrategy.performAuthorizeChallengeStart(any(), any(), any(), any(), any()) } returns + AuthorizeChallengeApiResult.UnknownError(correlationId, "test_stop", "test stop") + for (scopes in listOf(null, emptyList(), listOf("User.Read"))) { + controller.signUpStart( + signUpStartParameters().toBuilder().scopes(scopes) + .claimsRequestJson("{\"id_token\":{}}").build() + ) + verify(exactly = 1) { + mockStrategy.performAuthorizeChallengeStart( + correlationId, any(), any(), + match { it.toSet() == (scopes.orEmpty() + listOf("openid", "profile", "offline_access")).toSet() }, + "{\"id_token\":{}}" + ) + } + clearMocks(mockStrategy, answers = false) + } + } + // ----------------------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------------------- @@ -776,7 +806,7 @@ class NativeAuthV2SignUpFlowControllerTest { private fun signInAfterSignUpParameters( state: NativeAuthV2ContinuationState, - scopes: List = emptyList(), + scopes: List? = null, claimsRequestJson: String? = null, tokenCache: OAuth2TokenCache? = null ): NativeAuthV2SignInAfterSignUpCommandParameters = diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/commands/parameters/BaseSignInTokenCommandParameters.java b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/commands/parameters/BaseSignInTokenCommandParameters.java index 4b205c9603..6c11b69741 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/commands/parameters/BaseSignInTokenCommandParameters.java +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/commands/parameters/BaseSignInTokenCommandParameters.java @@ -47,7 +47,8 @@ public abstract class BaseSignInTokenCommandParameters extends BaseNativeAuthCom public final List scopes; /** - * Claims to send to the token endpoint. + * Claims for the requested token. V1 sends these to the token endpoint; V2 retains them + * for local cache/result handling and sends claims only on the initial authorize-challenge. */ @Nullable public final String claimsRequestJson; diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2Interactor.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2Interactor.kt index 25a8cbcf72..d74a27be77 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2Interactor.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2Interactor.kt @@ -88,7 +88,8 @@ class NativeAuthV2Interactor( val request = requestProvider.createAuthorizeChallengeStartRequest( correlationId = correlationId, - scopes = scopes + scopes = scopes, + claimsRequestJson = claimsRequestJson ) Logger.infoWithObject( diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/AuthorizeChallengeStartRequest.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/AuthorizeChallengeStartRequest.kt index c4aa7248b0..7c5a71464f 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/AuthorizeChallengeStartRequest.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/AuthorizeChallengeStartRequest.kt @@ -55,9 +55,17 @@ data class AuthorizeChallengeStartRequest private constructor( scopes: List, requestUrl: String, headers: Map + ): AuthorizeChallengeStartRequest = create(clientId, scopes, requestUrl, headers, null) + + /** Creates an entry request with optional claims, never added to intermediate HAL calls. */ + fun create( + clientId: String, + scopes: List, + requestUrl: String, + headers: Map, + claimsRequestJson: String? ): AuthorizeChallengeStartRequest { ArgUtils.validateNonNullArg(clientId, "clientId") - ArgUtils.validateNonNullArg(scopes, "scopes") scopes.forEachIndexed { index, scope -> ArgUtils.validateNonNullArg(scope, "scopes[$index]") } @@ -69,7 +77,8 @@ data class AuthorizeChallengeStartRequest private constructor( headers = headers, parameters = NativeAuthAuthorizeChallengeStartRequestParameters( clientId = clientId, - scope = scopes.takeUnless { it.isEmpty() }?.joinToString(" ") + scope = scopes.takeUnless { it.isEmpty() }?.joinToString(" "), + claimsRequestJson = claimsRequestJson?.takeUnless { it.isBlank() } ) ) } @@ -83,15 +92,15 @@ data class AuthorizeChallengeStartRequest private constructor( * NativeAuthAuthorizeChallengeStartRequestParameters represents the request parameters sent as * part of the `/oauth2/v2.0/authorize-challenge` API call that starts a Native Auth V2 flow. */ - data class NativeAuthAuthorizeChallengeStartRequestParameters( + data class NativeAuthAuthorizeChallengeStartRequestParameters @JvmOverloads constructor( @SerializedName("client_id") override val clientId: String, - @SerializedName("scope") val scope: String? = null + @SerializedName("scope") val scope: String? = null, + @SerializedName("claims") val claimsRequestJson: String? = null ) : NativeAuthRequestParameters() { - constructor(clientId: String) : this(clientId, null) override fun toUnsanitizedString(): String = "NativeAuthAuthorizeChallengeStartRequestParameters(clientId=$clientId, scope=$scope)" - override fun toString(): String = toUnsanitizedString() + override fun toString(): String = "NativeAuthAuthorizeChallengeStartRequestParameters()" } } diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2TokenRequest.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2TokenRequest.kt index c152113c02..02a198111e 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2TokenRequest.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2TokenRequest.kt @@ -84,7 +84,8 @@ data class NativeAuthV2TokenRequest private constructor( @SerializedName("grant_type") val grantType: String, @SerializedName("code") val code: String, @SerializedName("scope") val scope: String, - @SerializedName("claims") val claimsRequestJson: String?, + // V2 claims belong on initial authorize-challenge, never on the token wire request. + @Transient val claimsRequestJson: String?, @SerializedName("client_info") private val clientInfo: Boolean = true ) : NativeAuthRequestParameters() { override fun toUnsanitizedString(): String = "NativeAuthV2TokenRequestParameters(clientId=$clientId, grantType=$grantType, scope=$scope, clientInfo=$clientInfo)" diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2VerifyRequest.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2VerifyRequest.kt index 748dd41b23..bbc0aead85 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2VerifyRequest.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2VerifyRequest.kt @@ -43,7 +43,6 @@ data class NativeAuthV2VerifyRequest private constructor( headers: Map ): NativeAuthV2VerifyRequest { ArgUtils.validateNonNullArg(continuationToken, "continuationToken") - ArgUtils.validateNonNullArg(otp, "otp") ArgUtils.validateNonNullArg(requestUrl, "requestUrl") ArgUtils.validateNonNullArg(headers, "headers") diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2RequestProvider.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2RequestProvider.kt index 1cadd1bfa2..0f93d8fd09 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2RequestProvider.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2RequestProvider.kt @@ -66,6 +66,13 @@ class NativeAuthV2RequestProvider( fun createAuthorizeChallengeStartRequest( correlationId: String, scopes: List + ): AuthorizeChallengeStartRequest = createAuthorizeChallengeStartRequest(correlationId, scopes, null) + + /** Builds the entry form with scopes and optional claims. */ + fun createAuthorizeChallengeStartRequest( + correlationId: String, + scopes: List, + claimsRequestJson: String? ): AuthorizeChallengeStartRequest { LogSession.logMethodCall( tag = TAG, @@ -76,6 +83,7 @@ class NativeAuthV2RequestProvider( return AuthorizeChallengeStartRequest.create( clientId = config.clientId, scopes = scopes, + claimsRequestJson = claimsRequestJson, requestUrl = config.getNativeAuthV2AuthorizeChallengeEndpoint(correlationId).toString(), headers = getV2RequestHeaders(correlationId, NativeAuthContentType.FORM_URL_ENCODED) ) diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2InteractorTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2InteractorTest.kt index 636545b3ff..771030bd21 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2InteractorTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/interactors/NativeAuthV2InteractorTest.kt @@ -90,8 +90,11 @@ class NativeAuthV2InteractorTest { @Test fun performAuthorizeChallengeStart_postsFormBodyAndParsesAuthorizeChallengeResult() { val scopes = listOf("openid", "profile") + val claims = """{"id_token":{"auth_time":null}}""" val request = AuthorizeChallengeStartRequest.create( clientId = CLIENT_ID, + scopes = scopes, + claimsRequestJson = claims, requestUrl = authorizeChallengeUrl.toString(), headers = formHeaders() ) @@ -100,14 +103,15 @@ class NativeAuthV2InteractorTest { val expected = AuthorizeChallengeApiResult.AuthorizationCode(CORRELATION_ID, "auth-code") val captured = capturePost(httpResponse) - every { requestProvider.createAuthorizeChallengeStartRequest(CORRELATION_ID) } returns request + every { requestProvider.createAuthorizeChallengeStartRequest(CORRELATION_ID, scopes, claims) } returns request every { responseHandler.getHalApiResponse(CORRELATION_ID, httpResponse) } returns halResponse every { responseParser.parseAuthorizeChallenge( response = halResponse, entryRelation = NativeAuthV2LinkRelation.RESET_PASSWORD, scenario = NativeAuthV2FlowScenario.RESET_PASSWORD, - scopes = scopes + scopes = scopes, + claimsRequestJson = claims ) } returns expected @@ -115,7 +119,8 @@ class NativeAuthV2InteractorTest { correlationId = CORRELATION_ID, entryRelation = NativeAuthV2LinkRelation.RESET_PASSWORD, scenario = NativeAuthV2FlowScenario.RESET_PASSWORD, - scopes = scopes + scopes = scopes, + claimsRequestJson = claims ) assertSame(expected, actual) @@ -124,17 +129,20 @@ class NativeAuthV2InteractorTest { assertFormBody( captured.body.captured, mapOf( - "client_id" to CLIENT_ID + "client_id" to CLIENT_ID, + "scope" to "openid profile", + "claims" to claims ) ) - verify(exactly = 1) { requestProvider.createAuthorizeChallengeStartRequest(CORRELATION_ID) } + verify(exactly = 1) { requestProvider.createAuthorizeChallengeStartRequest(CORRELATION_ID, scopes, claims) } verify(exactly = 1) { responseHandler.getHalApiResponse(CORRELATION_ID, httpResponse) } verify(exactly = 1) { responseParser.parseAuthorizeChallenge( response = halResponse, entryRelation = NativeAuthV2LinkRelation.RESET_PASSWORD, scenario = NativeAuthV2FlowScenario.RESET_PASSWORD, - scopes = scopes + scopes = scopes, + claimsRequestJson = claims ) } } @@ -554,7 +562,6 @@ class NativeAuthV2InteractorTest { "grant_type" to "authorization_code", "code" to AUTHORIZATION_CODE, "scope" to "User.Read offline_access", - "claims" to claimsRequestJson, "client_info" to "true" ) ) @@ -623,7 +630,7 @@ class NativeAuthV2InteractorTest { val expectedFailure = IllegalStateException("parser failure") capturePost(httpResponse) - every { requestProvider.createAuthorizeChallengeStartRequest(CORRELATION_ID) } returns request + every { requestProvider.createAuthorizeChallengeStartRequest(CORRELATION_ID, listOf("openid", "profile"), null) } returns request every { responseHandler.getHalApiResponse(CORRELATION_ID, httpResponse) } returns halResponse every { responseParser.parseAuthorizeChallenge( diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2RequestSerializationTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2RequestSerializationTest.kt index 49fb46bef8..a8209887fd 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2RequestSerializationTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2RequestSerializationTest.kt @@ -31,6 +31,50 @@ import org.junit.Test class NativeAuthV2RequestSerializationTest { + @Test + fun authorizeChallenge_serializesEntryScopesAndClaimsWithoutLoggingClaims() { + listOf(null, "", """{"id_token":{"test":null}}""").forEach { claims -> + val request = AuthorizeChallengeStartRequest.create( + clientId = CLIENT_ID, + scopes = listOf("openid", "profile", "offline_access", "User.Read"), + requestUrl = "https://contoso.com/oauth2/v2.0/authorize-challenge", + headers = mapOf("Content-Type" to "application/x-www-form-urlencoded"), + claimsRequestJson = claims + ) + val form = ObjectMapper.serializeObjectToFormUrlEncoded(request.parameters) + assertTrue(form.contains("scope=openid+profile+offline_access+User.Read")) + assertEquals(!claims.isNullOrEmpty(), form.contains("claims=")) + assertFalse(request.toString().contains("id_token")) + assertFalse(request.parameters.toString().contains("id_token")) + } + } + + @Test + fun verifyRequest_sendsEmptyAndShortOtpWithoutLocalRejection() { + listOf("", "1").forEach { otp -> + val request = NativeAuthV2VerifyRequest.create( + CONTINUATION_TOKEN, otp, "https://contoso.com/verify", + mapOf("Content-Type" to "application/json") + ) + val serialized = JSONObject(ObjectMapper.serializeObjectToJsonString(request.parameters)) + assertEquals(otp, serialized.getString("otp")) + assertFalse(serialized.has("scope")) + assertFalse(serialized.has("claims")) + } + } + + @Test + fun authorizeChallenge_emptyScopes_omitsScope() { + val request = AuthorizeChallengeStartRequest.create( + clientId = CLIENT_ID, + scopes = emptyList(), + requestUrl = "https://contoso.com/oauth2/v2.0/authorize-challenge", + headers = mapOf("Content-Type" to "application/x-www-form-urlencoded") + ) + val form = ObjectMapper.serializeObjectToFormUrlEncoded(request.parameters) + assertFalse(form.contains("scope=")) + } + @Test fun jsonRequestParameters_serializeExpectedWireFieldsWithoutClientId() { val cases = listOf( @@ -61,6 +105,8 @@ class NativeAuthV2RequestSerializationTest { assertEquals(expected.toString(), serialized.toString()) assertFalse(serialized.has("clientId")) assertFalse(serialized.has("client_id")) + assertFalse(serialized.has("scope")) + assertFalse(serialized.has("claims")) } } diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2TokenRequestTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2TokenRequestTest.kt index 75ed0e089c..b791b2217b 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2TokenRequestTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/requests/v2/NativeAuthV2TokenRequestTest.kt @@ -25,6 +25,7 @@ package com.microsoft.identity.common.java.nativeauth.providers.requests.v2 import com.microsoft.identity.common.java.exception.ClientException import com.microsoft.identity.common.java.util.ObjectMapper import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test @@ -63,7 +64,7 @@ class NativeAuthV2TokenRequestTest { } @Test - fun create_whenClaimsAreProvided_serializesClaimsInFinalFormBody() { + fun create_whenClaimsAreProvided_retainsLocalClaimsButOmitsThemFromTokenForm() { val request = createRequest( scopes = listOf("openid"), claimsRequestJson = CLAIMS_REQUEST_JSON @@ -71,7 +72,9 @@ class NativeAuthV2TokenRequestTest { val formBody = ObjectMapper.serializeObjectToFormUrlEncoded(request.parameters) - assertEquals(CLAIMS_REQUEST_JSON, parseFormBody(formBody)["claims"]) + assertEquals(CLAIMS_REQUEST_JSON, request.parameters.claimsRequestJson) + assertFalse(parseFormBody(formBody).containsKey("claims")) + assertEquals("openid", parseFormBody(formBody)["scope"]) } private fun createRequest( From 5325fa9f9579e6f58e348c16f3dd97e0c542708a Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Mon, 12 Oct 2026 12:07:07 -0700 Subject: [PATCH 03/16] Repair unified-error diagnostic forwarding in split controller Fixes AB#3784695 Move diagnostic arguments into their authorize/continue/token APIError constructors; preserve errors-only scope behavior. Independently compiled and covered by focused MSAL/Common suites. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 0bcd671b-73fa-4ee6-bcd6-65d7eea4d753 (cherry picked from commit 3265533f27d8c4054fc5b020ec0228bb872b8344) From 41f9c0f74a636b1ae2f62abcb3ee6a94906f1d86 Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Mon, 12 Oct 2026 12:16:53 -0700 Subject: [PATCH 04/16] Canonicalize only Native Auth V2 OIDC default scopes Fixes AB#3784690 Canonicalize recognized OIDC defaults to lowercase exactly once at entry and token exchange, preserving resource scope casing, order and duplicates. Keep V1 behavior unchanged. Cover all three entry and token paths with red-green regressions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 0bcd671b-73fa-4ee6-bcd6-65d7eea4d753 --- .../v2/NativeAuthV2FlowController.kt | 13 +++++++++-- .../v2/NativeAuthV2SSPRFlowControllerTest.kt | 20 ++++++++++++---- .../NativeAuthV2SignInFlowControllerTest.kt | 8 ++++--- .../NativeAuthV2SignUpFlowControllerTest.kt | 23 +++++++++++++++++++ 4 files changed, 55 insertions(+), 9 deletions(-) diff --git a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt index 40fc7a88e6..ad04d032fb 100644 --- a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt +++ b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt @@ -79,9 +79,18 @@ import lombok.EqualsAndHashCode class NativeAuthV2FlowController : BaseNativeAuthController() { private fun addV2DefaultScopes(scopes: List?): List { - val requestedScopes = scopes?.filterNotNull()?.filter { it.isNotEmpty() }?.toMutableList() ?: mutableListOf() + val requestedScopes = mutableListOf() + scopes.orEmpty().filterNotNull().filter { it.isNotEmpty() }.forEach { scope -> + // Only OIDC defaults are canonicalized; resource scopes remain case-sensitive. + val defaultScope = AuthenticationConstants.DEFAULT_SCOPES.firstOrNull { + it.equals(scope, ignoreCase = true) + } + if (defaultScope == null || defaultScope !in requestedScopes) { + requestedScopes.add(defaultScope ?: scope) + } + } AuthenticationConstants.DEFAULT_SCOPES.forEach { defaultScope -> - if (requestedScopes.none { it.equals(defaultScope, ignoreCase = true) }) { + if (defaultScope !in requestedScopes) { requestedScopes.add(defaultScope) } } diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SSPRFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SSPRFlowControllerTest.kt index 0310380726..ea12883891 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SSPRFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SSPRFlowControllerTest.kt @@ -195,20 +195,32 @@ class NativeAuthV2SSPRFlowControllerTest { } @Test - fun testEntryExplicitOidcScopesDoNotDuplicateDefaultsIgnoringCase() { + fun testEntryAndTokenCanonicalizeOidcDefaultsWithoutChangingResourceScopes() { + val requestedScopes = listOf("OPENID", "PROFILE", "OFFLINE_ACCESS", "User.Read", "user.read", "User.Read", "openid", "profile", "offline_access") + val expectedScopes = listOf("openid", "profile", "offline_access", "User.Read", "user.read", "User.Read") every { mockStrategy.performAuthorizeChallengeStart(any(), any(), any(), any(), any()) } returns AuthorizeChallengeApiResult.UnknownError(correlationId, "test_stop", "test stop") controller.resetPasswordStart( - resetPasswordStartParameters().toBuilder().scopes(listOf("OPENID", "User.Read")).build() + resetPasswordStartParameters().toBuilder().scopes(requestedScopes).build() ) verify(exactly = 1) { mockStrategy.performAuthorizeChallengeStart( correlationId, any(), any(), - match { it.size == 4 && it.contains("OPENID") && it.contains("User.Read") && - it.containsAll(listOf("profile", "offline_access")) }, + expectedScopes, null ) } + val state = mockContinuationState() + every { state.scopesForTokenRequest() } returns requestedScopes + every { state.claimsRequestJsonForTokenRequest() } returns null + every { mockStrategy.performAuthorizeChallengeContinue(state) } returns + AuthorizeChallengeApiResult.AuthorizationCode(correlationId, "auth-code") + every { mockStrategy.performTokenRequest(any(), any(), any(), any()) } returns + SignInTokenApiResult.UnknownError(correlationId, "test_stop", "test stop", emptyList()) + controller.signInAfterResetPassword(signInAfterResetPasswordParameters(state, null)) + verify(exactly = 1) { + mockStrategy.performTokenRequest("auth-code", expectedScopes, correlationId, null) + } } @Test diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt index 4611e6c2c0..e1d22ed805 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt @@ -397,6 +397,8 @@ class NativeAuthV2SignInFlowControllerTest { fun testSignInStartCarriesScopesAndClaimsIntoAuthorizeChallengeAndToken() { val passwordState = mockContinuationState() val readyState = mockContinuationState() + val requestedScopes = listOf("OPENID", "PROFILE", "OFFLINE_ACCESS", "User.Read", "user.read", "User.Read", "openid", "profile", "offline_access") + val expectedScopes = listOf("openid", "profile", "offline_access", "User.Read", "user.read", "User.Read") val claims = """{"access_token":{"xms_cc":{"values":["cp1"]}}}""" val tokenScopes = slot>() stubStartThroughPasswordChallenge(passwordState) @@ -416,7 +418,7 @@ class NativeAuthV2SignInFlowControllerTest { ) controller.signInStart( - signInStartParameters(scopes = listOf("User.Read"), claimsRequestJson = claims) + signInStartParameters(scopes = requestedScopes, claimsRequestJson = claims) ) verify(exactly = 1) { @@ -424,7 +426,7 @@ class NativeAuthV2SignInFlowControllerTest { correlationId = correlationId, entryRelation = "signIn", scenario = any(), - scopes = match { it.toSet() == setOf("User.Read", "openid", "profile", "offline_access") }, + scopes = expectedScopes, claimsRequestJson = claims ) } @@ -436,7 +438,7 @@ class NativeAuthV2SignInFlowControllerTest { claimsRequestJson = claims ) } - assertTrue(tokenScopes.captured.containsAll(listOf("User.Read", "openid", "offline_access", "profile"))) + assertEquals(expectedScopes, tokenScopes.captured) } // ----------------------------------------------------------------------------------------- diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt index 01fae464d7..99c8d5561e 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt @@ -711,6 +711,29 @@ class NativeAuthV2SignUpFlowControllerTest { assertEquals(ClientException.TOKEN_CACHE_SAVE_FAILED, thrown.errorCode) } + @Test + fun testSignUpEntryAndTokenCanonicalizeOidcDefaultsWithoutChangingResourceScopes() { + val requestedScopes = listOf("OPENID", "PROFILE", "OFFLINE_ACCESS", "User.Read", "user.read", "User.Read", "openid", "profile", "offline_access") + val expectedScopes = listOf("openid", "profile", "offline_access", "User.Read", "user.read", "User.Read") + every { mockStrategy.performAuthorizeChallengeStart(any(), any(), any(), any(), any()) } returns + AuthorizeChallengeApiResult.UnknownError(correlationId, "test_stop", "test stop") + controller.signUpStart(signUpStartParameters().toBuilder().scopes(requestedScopes).build()) + verify(exactly = 1) { + mockStrategy.performAuthorizeChallengeStart(correlationId, any(), any(), expectedScopes, null) + } + val state = mockContinuationState() + every { state.scopesForTokenRequest() } returns requestedScopes + every { state.claimsRequestJsonForTokenRequest() } returns null + every { mockStrategy.performAuthorizeChallengeContinue(state) } returns + AuthorizeChallengeApiResult.AuthorizationCode(correlationId, "auth-code") + every { mockStrategy.performTokenRequest(any(), any(), any(), any()) } returns + SignInTokenApiResult.UnknownError(correlationId, "test_stop", "test stop", emptyList()) + controller.signInAfterSignUp(signInAfterSignUpParameters(state, scopes = null)) + verify(exactly = 1) { + mockStrategy.performTokenRequest("auth-code", expectedScopes, correlationId, null) + } + } + @Test fun testSignUpEntrySendsDefaultScopesAndClaimsForNullEmptyAndExplicitScopes() { every { mockStrategy.performAuthorizeChallengeStart(any(), any(), any(), any(), any()) } returns From 665e9128d28cff8aa30feadb5a16bea66a86c743 Mon Sep 17 00:00:00 2001 From: Mohit Date: Mon, 12 Oct 2026 13:23:57 -0700 Subject: [PATCH 05/16] Preserve device token results during R8 shrinking, Fixes AB#3784571 (#3305) ## Summary Fixes [AB#3784571](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3784571) - Preserve `DeviceTokenResult` and its members through Common's consumer ProGuard rules so Moshi can construct and populate the nested response model in minified clients. - Move the V1 device-token success log after deserialization and extraction of a non-null, explicitly typed result. - Add regression tests for successful parsing, malformed JSON, and a null result. Failed parsing must not emit the success message. ## Why The existing broad identity rule permits shrinking and optimization. Protocol implementations and device-registration records have stronger keep rules, but the nested `DeviceTokenResult` model does not implement either protected interface. Referencing the model or its getters does not preserve reflective construction. The broker and calling application are optimized separately. An isolated client-side R8 reproduction loses the model's reflective construction surface without the new rule and succeeds with it. ## Validation - After integrating latest `dev`, freshly ran `:common:testLocalDebugUnitTest --tests com.microsoft.identity.deviceregistration.api.DeviceRegistrationClientApplicationTest --rerun`: **18 tests passed**, none skipped. - `:common:bundleLocalReleaseAar` succeeded; verified that the resulting AAR contains the new consumer keep rule. - Earlier isolated R8 validation with packaged rules preserved all eight token-result fields and absent optional values; removing only the new rule reproduced reflective deserialization failure. - Expanded R8 flow validation also covered registration lookup/list, both record subtypes, V0/V1 requests and responses, and the UUID adapter. No additional keep rules were needed. - `git diff --check` passed. ## Scope and follow-up - No public API, wire-format, V0 behavior, or exception-mapping changes. - No changelog update. - Keep this PR in draft pending a consuming application's minified release-build retest. The isolated R8 failure demonstrates the preservation defect, but does not establish the cause of every device-token NPE. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- common/consumer-rules.pro | 2 + .../DeviceRegistrationClientApplication.kt | 4 +- ...DeviceRegistrationClientApplicationTest.kt | 85 +++++++++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) diff --git a/common/consumer-rules.pro b/common/consumer-rules.pro index bdfaad0420..8e979e80d9 100644 --- a/common/consumer-rules.pro +++ b/common/consumer-rules.pro @@ -27,6 +27,8 @@ -keep class com.microsoft.identity.common.internal.broker.AuthUxJsonPayload { *; } -keep class * extends com.microsoft.identity.deviceregistration.java.protocol.IDeviceRegistrationProtocol { *; } -keep class * extends com.microsoft.identity.deviceregistration.java.api.IDeviceRegistrationRecord { *; } +# Moshi constructs and populates this nested result reflectively. +-keep class com.microsoft.identity.deviceregistration.java.api.DeviceTokenResult { *; } # Keep WebView JS bridge methods annotated with @JavascriptInterface -keepclassmembers class com.microsoft.identity.** { diff --git a/common/src/main/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplication.kt b/common/src/main/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplication.kt index 1cbf00a203..21232b2bbd 100644 --- a/common/src/main/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplication.kt +++ b/common/src/main/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplication.kt @@ -331,8 +331,10 @@ class DeviceRegistrationClientApplication { val responseSerialized = mController.execute( GetDeviceTokenV1Parameters(correlationId, deviceRegistrationRecord, resources, clientId, redirectUri, scope) ) + val result: DeviceTokenResult = + GetDeviceTokenV1Response.create(responseSerialized).deviceTokenResult Logger.info(methodTag, "Get device token ended successfully.") - return GetDeviceTokenV1Response.create(responseSerialized).deviceTokenResult + return result } /** diff --git a/common/src/test/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplicationTest.kt b/common/src/test/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplicationTest.kt index e431f4111f..a8a6b213b2 100644 --- a/common/src/test/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplicationTest.kt +++ b/common/src/test/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplicationTest.kt @@ -29,8 +29,10 @@ import com.microsoft.identity.common.internal.activebrokerdiscovery.IBrokerDisco import com.microsoft.identity.common.internal.broker.BrokerData import com.microsoft.identity.common.internal.broker.ipc.BrokerOperationBundle import com.microsoft.identity.common.internal.broker.ipc.IIpcStrategy +import com.microsoft.identity.common.java.exception.ClientException import com.microsoft.identity.common.java.interfaces.IPlatformComponents import com.microsoft.identity.common.java.interfaces.IStorageSupplier +import com.microsoft.identity.common.logging.Logger import com.microsoft.identity.deviceregistration.AndroidDeviceRegistrationProtocolPacker import com.microsoft.identity.deviceregistration.DeviceRegistrationIpcStrategiesProvider import com.microsoft.identity.deviceregistration.java.DeviceState @@ -309,6 +311,89 @@ class DeviceRegistrationClientApplicationTest { Assert.assertNull(result.notBefore) } + @Test + fun getDeviceTokenResult_v1_validResult_logsSuccess() { + val expected = DeviceTokenResult.builder().accessToken("device.token.jwt").build() + val response = GetDeviceTokenV1Response(UUID.randomUUID(), expected) + val drca = createDrca(successStrategy(packer.pack(response))) + + Mockito.mockStatic(Logger::class.java).use { logger -> + val result = drca.getDeviceTokenResult( + DeviceRegistrationRecord("tenant", "upn", "device", false, false), + "https://resource.example.com", + UUID.randomUUID(), + "test-client-id", + "msauth://com.test.app/callback" + ) + + Assert.assertEquals("device.token.jwt", result.accessToken) + logger.verify { + Logger.info( + "DeviceRegistrationClientApplication:getDeviceTokenResult", + "Get device token ended successfully." + ) + } + } + } + + @Test + fun getDeviceTokenResult_v1_malformedResponse_doesNotLogSuccess() { + val response = Bundle().apply { + putByteArray("protocol.data", "{".toByteArray(Charsets.UTF_8)) + } + val drca = createDrca(successStrategy(response)) + + Mockito.mockStatic(Logger::class.java).use { logger -> + val exception = Assert.assertThrows(ClientException::class.java) { + drca.getDeviceTokenResult( + DeviceRegistrationRecord("tenant", "upn", "device", false, false), + "https://resource.example.com", + UUID.randomUUID(), + "test-client-id", + "msauth://com.test.app/callback" + ) + } + + Assert.assertEquals(ClientException.JSON_PARSE_FAILURE, exception.errorCode) + logger.verify({ + Logger.info( + "DeviceRegistrationClientApplication:getDeviceTokenResult", + "Get device token ended successfully." + ) + }, Mockito.never()) + } + } + + @Test + fun getDeviceTokenResult_v1_nullResult_doesNotLogSuccess() { + val response = Bundle().apply { + putByteArray( + "protocol.data", + """{"mDeviceTokenResult":null}""".toByteArray(Charsets.UTF_8) + ) + } + val drca = createDrca(successStrategy(response)) + + Mockito.mockStatic(Logger::class.java).use { logger -> + Assert.assertThrows(NullPointerException::class.java) { + drca.getDeviceTokenResult( + DeviceRegistrationRecord("tenant", "upn", "device", false, false), + "https://resource.example.com", + UUID.randomUUID(), + "test-client-id", + "msauth://com.test.app/callback" + ) + } + + logger.verify({ + Logger.info( + "DeviceRegistrationClientApplication:getDeviceTokenResult", + "Get device token ended successfully." + ) + }, Mockito.never()) + } + } + @Test fun getDeviceTokenResult_v1_withScope_returnsDeviceToken() { val expected = DeviceTokenResult.builder().accessToken("device.token.jwt.scoped").build() From a9ee08c3237a3b3bce8779c4f16f8bdc013e332e Mon Sep 17 00:00:00 2001 From: Shahzaib <37125644+shahzaibj@users.noreply.github.com> Date: Mon, 12 Oct 2026 18:00:12 -0700 Subject: [PATCH 06/16] Review dispatched calls under locks with concrete evidence, AB#3778034, Fixes AB#3778034 (#3292) [AB#3778034](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3778034) ## Summary - Extend the Common code-review guidance for interface, abstract, overridable, and callback calls made while a monitor or lock is held. - Route implementation, injection, hierarchy, callback, and registration changes into this analysis even when the caller's synchronization is unchanged. - Keep `.github/copilot-instructions.md` and the skill's routing, concurrency reference, and false-positive rules consistent. ## Review behavior - Resolve the concrete held lock and runtime target before tracing additional lock acquisition, wait dependencies, or callback access to a partially updated invariant. - Distinguish hidden-override ABBA cycles, awaited workers needing the held lock, and non-reentrant Mutex reacquisition from safe consistent ordering and benign JVM monitor reentry. - Distinguish synchronous invocation from genuinely deferred registration/queueing. A verified collection leaf is not a blanket exemption for operations such as `contains` that can invoke user-defined `equals`, or for custom implementations. - Bound analysis of unavailable external, native, or reflective implementations. Unknown dispatch alone is not a defect; any contract clarification is specific and non-blocking rather than an invented High-severity deadlock. - Recommend an open-call/snapshot design only when state validity, ordering, lifetime, and atomicity remain protected, with reservation/revalidation where necessary. - Deduplicate overlap with the existing lock-order rules and determine severity from demonstrated impact, not from interface syntax. ## Scope Four existing documentation files only. The preceding general synchronization analysis, corrected guarded cache example, and existing suppressions are preserved. Flighting recommendations, runtime authentication changes, static analyzers, dependencies, and CI additions are out of scope. ## Kotlin-first examples - Use Kotlin for the language-neutral lock-order, mutable-monitor, callback-state, collection-dispatch, snapshot/revalidation, critical-section, and helper-extraction examples. - Preserve explicit `open`/`override`, JVM monitor identity, and safe/unsafe distinctions when translating. JVM `synchronized` remains separate from coroutine `Mutex`; this is not a conversion of monitor-based examples to coroutines. - Retain compact Java comparisons for virtual-by-default methods and instance synchronized methods, plus the legacy `Thread.join` wait-cycle example. - The main concurrency reference now contains seventeen Kotlin and three Java code blocks, rather than four Kotlin and twelve Java blocks. - Review policy, severities, exclusions, and suppressions are unchanged by this example-language update. The newer upstream merge is retained in the branch history. ## Verification - Validated 114 structure, semantic, and scope assertions on the updated examples, including frontmatter, links/anchors, code fences, and TOC. - Reviewed 35 positive, negative, unknown-contract, and remediation cases in the session acceptance matrix. - Compiled all seventeen exact Kotlin blocks with the cached repository-pinned Kotlin 2.0.21 compiler and `kotlinx-coroutines-core-jvm` 1.6.4, using owner-only wrappers for fragments. All three retained Java blocks also compile. - A bounded JVM harness passed eighty-one assertions covering actual Kotlin lock cycles, ordering, callback invariants, deferred delivery, custom collection dispatch, invalidation, mutable monitors, synchronized helper protection, Java join waits, and documented Mutex cancellation/release behavior. - Preserved the meaning of preceding general synchronization examples, guarded cache guidance, and unrelated Common references. - Only documented Mutex scenarios are included in the runtime results; the supplemental repeated-owner-token probe is not claimed as validated. - No repository dependencies or global tooling were installed. No production Android build or live Copilot detection-accuracy benchmark was run. - Checked the staged and committed diffs for whitespace errors and independently verified the published PR head. --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 20 +- .github/skills/code-review/SKILL.md | 2 +- .../references/concurrency-threading.md | 369 ++++++++++++++++-- .../references/false-positive-suppression.md | 8 + 4 files changed, 357 insertions(+), 42 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 3304994881..7db2a076a5 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -183,6 +183,8 @@ Escalate to Security if a race compromises auth, tokens, or sensitive data integ Route changed, added, removed, or moved `synchronized` blocks/methods, Kotlin `@Synchronized`, explicit `Lock`/`withLock`/`Mutex`, and changes to lock expressions, helpers, receivers, or shared-state access paths to deeper concurrency analysis. Include refactors whose diff has no new locking tokens. The presence of synchronization elsewhere in a file is not a finding or a reason to audit unrelated code. +Also route changed interface/abstract calls, concrete overridable-method calls in Java and Kotlin (including Java virtual and Kotlin `open` methods), and synchronous callback/listener/lambda invocations while a lock is held. Include changes to injected implementations, hierarchies, overrides, or callback bodies reached by an unchanged locked caller, even without synchronization keywords in the diff. This is focused routing, not a blanket arbitrary-call-under-lock defect. + ### 3.1 What to Flag (Non-Security) - Unsynchronized mutable shared state accessed across threads/coroutine contexts (lists/maps/caches/flags). - Lazy init races (double-checked locking lacking `volatile` / `@Volatile`). @@ -250,10 +252,12 @@ Do NOT flag: - Intentional thread confinement (single-thread dispatcher/executor) clearly enforced. - Read-only data after construction (effectively immutable). - Generated code with known synchronization wrappers. -- Consistent acquisition order across reachable paths, or same-monitor JVM reentry, without a demonstrated conflicting path. +- Consistent acquisition order across reachable paths, or same-monitor JVM reentry, without a demonstrated conflicting path or invalid intermediate-state access. - Stable private `final`/`val` monitors used by all relevant accesses; non-final syntax alone is not a concurrency defect. - Helper extraction retaining the same monitor for every caller, or bounded pure computation on thread-owned inputs moved outside a lock while preserving the protected invariant and ordering. +These suppressions require the changed path to preserve confinement, immutability, or the generated wrapper's protection. A new override/callback that bypasses that boundary is not suppressed. + ### 3.8 Lock Identity and Before/After Analysis - Trace the actual monitor object and aliases, not just lock variable names: an instance synchronized method locks `this`, while a static synchronized method locks the declaring class's `Class` object. Resolve the actual JVM owner for Kotlin `@Synchronized`, including object/companion and static bridges. - Compare before/after held-lock sets at each affected shared read/write and call boundary. Trace relevant caller/callee acquisitions, release paths, receiver changes, state ownership, visibility, and concurrent reachability. Follow concrete callees to establish lock order, not to speculate about unknown implementations; state any unresolved call/alias boundary and do not claim a proven deadlock beyond it. @@ -272,11 +276,21 @@ Do NOT flag: ### 3.11 Refactors and Finding Evidence - Compare protection before and after a refactor, including a removed `synchronized`/`@Synchronized`, class-to-instance monitor change, different receiver, or helper extraction. Replacing the original caller's monitor with a helper's own monitor does not preserve the original protection. -- Dangerous example: `synchronized nextId()` becomes an unsynchronized wrapper calling an unguarded increment helper; concurrent calls on the same instance can lose updates. Changing a static synchronized method to instance synchronization while retaining shared static state likewise splits protection across instances. +- Dangerous example: Kotlin `@Synchronized fun nextId()` becomes an unannotated wrapper calling an unguarded increment helper; concurrent calls on the same instance can lose updates. The annotation and Java's instance-method `synchronized` hold `this`; changing a static synchronized method to instance synchronization while retaining shared static state likewise splits protection across instances. - Safe counterexample: the original synchronized entry point calls a private helper under the same monitor, and every other helper caller holds that same monitor across the entire invariant. Do not demand redundant synchronization on the helper. - Cite a changed line (or the affected call/declaration for removed locking), the concrete monitor identity, conflicting paths/threads, before/after protection, actual impact, and minimal invariant-preserving fix. Apply the existing High/Medium impact criteria; never assign blanket severity based on nested locks, non-final references, or scope size. -See [concurrency examples and counterexamples](skills/code-review/references/concurrency-threading.md) for the corresponding review procedure and compact cases. +### 3.12 Runtime Call Targets and Callbacks Under Locks +- Resolve the concrete held monitors/locks and possible runtime targets through construction, injection, hierarchy, overrides, and callback/lambda wiring. Trace actual callee bodies while the lock remains held, including further acquisitions, blocking/wait dependencies, and access to the caller's invariant. A declared interface/abstract type, a concrete overridable Java or Kotlin method, or a collection name proves neither safety nor a defect. +- Distinguish registration/enqueueing from invocation before release. Verify the dispatcher/executor's behavior: an executor may run inline. An asynchronous callback is not safe merely because it runs elsewhere if the caller waits for it while holding a lock it needs. `join`/`Future.get`/latch waits do not release held monitors; `Object.wait` releases only its target monitor, not other held locks. +- Report runtime-target ABBA only with an actual override/callee taking a second distinct lock and a concurrently reachable reverse path on those same objects. Report a waiting-worker cycle only with the caller's wait and the worker's dependency on the held lock. Reacquiring the same non-reentrant `Mutex` through a callback can self-suspend or fail for a repeated owner token. +- Same-thread JVM monitor reentry itself is benign, but a concrete callback can observe or mutate invalid intermediate state. Name the incomplete invariant, the actual callback access, and the resulting incorrect behavior; complete-state reentry without conflicting accesses is a counterexample. +- For external/native/reflective targets or unresolved injection, stop at the exact missing implementation/contract; do not invent lock edges, assert a safe default, or call it probable/proven deadlock. At most one clearly non-blocking `Sanity check:` contract note is permitted for a changed risk already established locally, such as new uncontrolled callback execution while a shared auth-cache lock is held. Specify the missing contract and local consequence; a generic interface call alone warrants silence. Do not duplicate an existing lock-order finding. +- Suppress known bounded, pure, nonblocking leaves and verified targets. For example, an actual non-escaping standard `ArrayList`'s `size()` or indexed `get()` under its owner guard adds no lock/wait edge; still trace operations invoking element/callback code, such as `contains` calling `equals`. A declared `List`/`Map` can instead dispatch to custom code. Truly deferred callbacks after release with no caller wait are counterexamples when state, ordering, and lifetime remain valid. +- Recommend a snapshot/open call only when state transition or reservation remains atomic under the original guard, the snapshot is immutable, and callback ordering, thread affinity, visibility, resource lifetime, and auth semantics are preserved. Revalidate generation/state or reconcile results after the call where needed. Revalidation alone cannot undo an irreversible operation: establish reservation/ownership and cancellation semantics before starting it; do not introduce duplicate side effects, stale-token/key use, check-then-act splits, or unsafe `volatile` substitutions. A verified consistent lock-order contract can be an alternative; do not mechanically finalize global APIs. +- Cite the changed call or implementation/injection/override/callback line plus the held monitor, actual runtime callee, competing path or invariant access, and concrete impact. Use existing severity criteria; an interface call is not automatically High severity or a merge blocker. + +See [concurrency examples and counterexamples](skills/code-review/references/concurrency-threading.md) for the corresponding review procedure and Kotlin-first compact cases. Preserve intended polymorphism with Kotlin `open`/`override` (classes/functions are final by default); retain Java comparisons for virtual-by-default methods and legacy blocking-thread APIs. Translating examples does not justify changing JVM monitors to coroutine mutexes. -------------------------------------------------------------------------------- diff --git a/.github/skills/code-review/SKILL.md b/.github/skills/code-review/SKILL.md index 7189454ebc..2f63ddaede 100644 --- a/.github/skills/code-review/SKILL.md +++ b/.github/skills/code-review/SKILL.md @@ -14,7 +14,7 @@ Use this skill only for pull-request review in `AzureAD/microsoft-authentication - Always: [comment quality and severity](references/comment-quality-severity.md) and [false-positive suppression](references/false-positive-suppression.md). - Commands, controllers, OAuth/OIDC, cache, authority, IPC, errors, shared contracts, or downstream consumers: [domain context](references/domain-context.md) and [correctness and API compatibility](references/correctness-api-compatibility.md). - Authentication, authorization, tokens, claims, logs, telemetry data, feature flags, intents, deserialization, keys, certificates, or cryptography: [security, privacy, and cryptography](references/security-privacy-crypto.md). - - Shared mutable state, executors, threads, coroutines, flows, cancellation, cache updates, or key rotation; changed/added/removed/moved `synchronized` blocks/methods, Kotlin `@Synchronized`, explicit `Lock`/`withLock`/`Mutex`, or modified lock expressions/helpers/receivers/shared-state paths: [concurrency and threading](references/concurrency-threading.md). Follow its [change-driven analysis](references/concurrency-threading.md#lock-identity-and-beforeafter-analysis) even for refactors without new locking tokens; synchronization merely present elsewhere in a file is not a finding. + - Shared mutable state, executors, threads, coroutines, flows, cancellation, cache updates, or key rotation; changed/added/removed/moved `synchronized` blocks/methods, Kotlin `@Synchronized`, explicit `Lock`/`withLock`/`Mutex`, or modified lock expressions/helpers/receivers/shared-state paths: [concurrency and threading](references/concurrency-threading.md). Follow its [change-driven analysis](references/concurrency-threading.md#lock-identity-and-beforeafter-analysis) even for refactors without new locking tokens. Also follow [runtime call targets](references/concurrency-threading.md#runtime-target-trace) for changed interface/abstract calls, concrete overridable calls in Java and Kotlin (including Java virtual and Kotlin `open` methods), injected implementations, hierarchy/override changes, or callback/listener/lambda invocations/bodies reached while a lock is held, even when that caller is unchanged. Synchronization merely present elsewhere in a file, or an interface call alone, is not a finding. - Java/Kotlin production logic, validation, nullability, collections, serialization, error modeling, or public/shared APIs: [correctness and API compatibility](references/correctness-api-compatibility.md). - Cache/serialization hot paths, authority discovery, token parsing, allocations, build/dependency files, or resource ownership: [performance, resources, and dependencies](references/performance-resources-dependencies.md). - OpenTelemetry spans, attributes, status, correlation IDs, `SpanName`, or `AttributeName`: [telemetry and observability](references/telemetry-observability.md). diff --git a/.github/skills/code-review/references/concurrency-threading.md b/.github/skills/code-review/references/concurrency-threading.md index 9a059b16f6..e4b7607473 100644 --- a/.github/skills/code-review/references/concurrency-threading.md +++ b/.github/skills/code-review/references/concurrency-threading.md @@ -6,6 +6,11 @@ - [Review targets](#review-targets) - [Lock identity and before/after analysis](#lock-identity-and-beforeafter-analysis) - [Nested acquisitions](#nested-acquisitions) +- [Calls under locks](#calls-under-locks) + - [Runtime-target trace](#runtime-target-trace) + - [Unknown target boundaries](#unknown-target-boundaries) + - [Invariant-preserving remediation](#invariant-preserving-remediation) + - [Synthetic paired cases](#synthetic-paired-cases) - [Monitor stability](#monitor-stability) - [Critical-section scope](#critical-section-scope) - [Refactors that lose protection](#refactors-that-lose-protection) @@ -19,6 +24,8 @@ Escalate a concurrency issue to security when it can bypass authentication/permi Perform deeper analysis for changed, added, removed, or moved `synchronized` blocks/methods, Kotlin `@Synchronized`, explicit `Lock`/`withLock`/`Mutex`, and modified lock expressions, helpers, receivers, or shared-state access paths. Include refactors without new locking tokens in the diff, such as moving a guarded mutation into another helper or changing its callers. +Also route changed interface/abstract calls, concrete overridable-method calls in Java and Kotlin (including Java virtual and Kotlin `open` methods), and synchronous callback/listener/lambda invocations under a held lock. Follow changed injection, implementation selection, hierarchy, override, or callback bodies back to affected locked callers even when those callers and synchronization keywords are absent from the diff. This is focused routing, not a rule that arbitrary calls under locks are defective. + Limit the trace to changed behavior and the callers/callees needed to establish its protection. Do not flag a file merely because it contains synchronization elsewhere. ## Review targets @@ -58,21 +65,21 @@ Avoid `GlobalScope`; use lifecycle, `ViewModel`, or injected scopes. When a thre Report an order inversion only with distinct locks, conflicting held-lock order, and concurrently reachable paths. For this illustrative shared instance, concurrent `refresh()` and `rotate()` can deadlock: -```java -final class LockOrderExample { - private final Object cacheLock = new Object(); - private final Object keyLock = new Object(); - private int version; - - void refresh() { - synchronized (cacheLock) { - synchronized (keyLock) { version++; } +```kotlin +private class LockOrderExample { + private val cacheLock = Any() + private val keyLock = Any() + private var version = 0 + + fun refresh() { + synchronized(cacheLock) { + synchronized(keyLock) { version++ } } } - void rotate() { - synchronized (keyLock) { - synchronized (cacheLock) { version++; } + fun rotate() { + synchronized(keyLock) { + synchronized(cacheLock) { version++ } } } } @@ -83,31 +90,300 @@ ABBA evidence: T1 in `refresh` holds `cacheLock` and waits for `keyLock`; T2 in True negatives, absent another conflicting path: - Both entry points acquire `cacheLock` then `keyLock` on this same instance. Nesting alone is not a defect. -- `synchronized (cacheLock) { synchronized (cacheLock) { version++; } }` reenters the same JVM monitor on one thread. The same applies when a helper reacquires that exact monitor. +- `synchronized(cacheLock) { synchronized(cacheLock) { version++ } }` reenters the same JVM monitor on one thread. The same applies when a helper reacquires that exact monitor. - Different instances' locks do not form this ABBA cycle unless aliases or shared callees connect them; verify object identity first. Do not apply JVM reentry reasoning to `mutex.withLock { mutex.withLock { update() } }`: if that path reacquires the same Kotlin mutex before release, it cannot reenter. Establish the actual path/identity rather than treating every nested locking construct alike. -## Monitor stability +## Calls under locks + +### Runtime-target trace + +1. Locate the changed call or implementation/injection/hierarchy/override/callback and the affected locked caller. Resolve the concrete held monitors/locks and compare before/after held-lock sets through invocation and release, including exceptional exits. Apply this to Java/Kotlin `synchronized`/`@Synchronized`, explicit `Lock`/`withLock`, and `Mutex`. +2. Resolve possible runtime targets from constructors, factories, dependency injection, subtype/override relationships, and listener/lambda wiring. Inspect actual implementations, including Java virtual methods and Kotlin `open` methods or non-final overrides. Declared type or method name proves neither safety nor danger; a harmless base body does not describe an injected override. Bound the trace to targets and callers relevant to changed behavior. +3. Follow each resolved callee while the caller's lock remains held. Identify actual additional acquisitions, blocking I/O, waits, and reentrant reads/writes of the caller's invariant. For ABBA, show distinct lock identities and a concurrently reachable reverse path; another lock inside an override alone is insufficient. +4. Distinguish registering/enqueueing a callback from invoking it before release. Inspect executor/dispatcher behavior rather than assuming asynchronous delivery: inline execution is possible. For a deferred worker, check whether the caller waits via `join`, `Future.get`, a latch, or another dependency while holding a lock the worker needs. Those waits do not release monitors; `Object.wait` releases its target monitor only, so other held locks may still participate. +5. For same-thread callbacks, separate benign JVM monitor reentry from actual observation/mutation of incomplete state. Show the partial invariant, concrete callback access, and incorrect result or state. For the same non-reentrant Kotlin `Mutex`, a callback that reacquires it before release can self-suspend or fail with a repeated owner token. Check the actual explicit `Lock` contract rather than borrowing JVM semantics. + +### Unknown target boundaries + +For unresolved injection or external/native/reflective callees, record the exact boundary and missing contract (for example, dispatch timing, additional locks, worker waits, or access to a partially updated invariant). Do not invent a lock edge, presume a safe implementation/default, or report probable/proven deadlock without that evidence. -Flag replacement only when it can split protection for the same shared state. Example members of a shared object: +Stay silent when the only evidence is a generic interface or unknown method under a lock. At most one clearly non-blocking `Sanity check:` contract note is permitted for a changed risk already established locally, such as newly executing an uncontrolled callback while a shared auth-cache lock is held. State that local fact and ask for the specific missing contract; do not warn about every unknown callee or duplicate an existing order-inversion finding. + +### Invariant-preserving remediation + +Do not mechanically move an external call outside its guard. Capture an immutable snapshot and complete the owning state transition or reservation under the original lock only when the open call preserves atomicity, visibility, invocation order, thread affinity, resource lifetime, and auth/token/key semantics. Revalidate a generation/state before commit or reconcile completion where required. A mutable alias is not a snapshot. + +Revalidation after an irreversible call cannot undo stale authorization, duplicate side effects, or use of an invalidated resource. Establish reservation/ownership, cancellation, and completion ordering before starting such work; do not split check-and-act or add retries that repeat irreversible operations. A verified lock-order contract across the concrete targets can be an alternative. Do not replace compound protection with `volatile` or finalize global APIs merely to prevent overrides. + +### Synthetic paired cases + +These are synthetic teaching examples, not claims about an actual incident/PR or Common runtime code. Assume safe publication and shared-instance concurrent reachability where specified. A negative applies only under its stated target, state, and lifetime constraints. + +Use Kotlin for language-neutral examples, matching the default for new code. Kotlin classes/functions are final by default; preserve intended virtual dispatch with explicit `open`/`override`. Java comparisons remain where virtual-by-default methods or legacy blocking-thread APIs are the teaching point. Translating a JVM monitor example does not mean replacing its monitor with a coroutine `Mutex`. + +#### Runtime override: ABBA versus the same target with consistent order + +Suppose only factory/implementation selection changed from exact `BaseWork` to `LockingWork`; the interface call and its outer acquisition are unchanged: + +```kotlin +private class DispatchExample { + interface Work { fun run() } + open class BaseWork : Work { + override fun run() {} + } + + private val cacheLock = Any() + private val keyLock = Any() + private val work: Work = LockingWork() + private var version = 0 + + private inner class LockingWork : BaseWork() { + override fun run() { + synchronized(keyLock) { version++ } + } + } + + fun refresh() { + synchronized(cacheLock) { work.run() } + } + + fun rotate() { + synchronized(keyLock) { + synchronized(cacheLock) { version++ } + } + } +} +``` + +**Positive:** T1 `refresh -> LockingWork.run` holds this instance's `cacheLock` and waits for `keyLock`; T2 `rotate` holds the same `keyLock` and waits for `cacheLock`. Cite the changed target selection/override, unchanged locked call, both bodies, identities, and stalled operations. The base class's concrete overridable method being empty is not proof of the runtime target. + +**Negative with the same runtime target:** replace `rotate` with the following, with no other reachable reverse path. Both operations acquire `cacheLock -> keyLock`; do not flag the interface or overridable call: + +```kotlin +fun rotate() { + synchronized(cacheLock) { + synchronized(keyLock) { version++ } + } +} +``` + +Exact `BaseWork` with its verified empty nonblocking body is another negative. Abstract-method dispatch requires the same runtime-target analysis, not an automatic finding. + +Compact Java comparison: a non-final instance method is virtual without Kotlin's `open`; the actual injected subclass body still matters. In Kotlin, `open class BaseWork` allows subclassing and its `override fun run()` remains overridable unless explicitly marked `final`. ```java -private volatile Object lock = new Object(); -private int count; +class JavaBaseWork { + void run() { } +} +final class JavaOverrideWork extends JavaBaseWork { + @Override void run() { } +} +``` + +#### Callback: partial invariant versus completed-state JVM reentry -void increment() { - synchronized (lock) { count++; } +```kotlin +private class CallbackStateExample { + private val stateLock = Any() + private var left = 0 + private var right = 0 + + fun balanced(): Boolean = synchronized(stateLock) { left == right } + + fun updatePartial(value: Int, listener: () -> Unit) { + synchronized(stateLock) { + left = value + listener() + right = value + } + } + + fun updateComplete(value: Int, listener: () -> Unit) { + synchronized(stateLock) { + left = value + right = value + listener() + } + } } +``` + +**Positive:** with initial `(0, 0)`, `value == 1`, and the actual wired listener reading `balanced()` to choose a result, `updatePartial` reports an unbalanced state. JVM reentry succeeds; the defect is observation of the incomplete `left == right` invariant, not self-deadlock. A changed callback body can introduce this access without changing the locked caller. + +**Negative:** `updateComplete` with that same bounded read-only listener observes completed state. Do not flag JVM reentry itself. This is not a blanket guarantee for other listeners that mutate state, acquire another lock, throw before required completion, or wait. + +#### Worker wait versus a truly deferred queue with no await + +```java +final class WorkerExample { + private final Object stateLock = new Object(); + private int value; + + int read() { + synchronized (stateLock) { return value; } + } + + void notifyAndWait() throws InterruptedException { + synchronized (stateLock) { + final Thread worker = new Thread(() -> { read(); }); + worker.start(); + worker.join(); + } + } -void replaceLock() { - lock = new Object(); +} +``` + +**Positive (legacy Java thread API):** T1 holds `stateLock` and waits for worker completion in `join`; the worker waits for that exact monitor in `read`. Async execution does not break this wait cycle. + +For the deferred negative, use a Kotlin function type rather than Java `Runnable` interop: + +```kotlin +private class DeferredExample { + private val stateLock = Any() + private val pending = java.util.ArrayDeque<() -> Unit>() + private var value = 0 + + fun read(): Int = synchronized(stateLock) { value } + + fun enqueue() { + synchronized(stateLock) { pending.add { read(); Unit } } + } + + fun drainOne() { + val notification = synchronized(stateLock) { pending.poll() } + notification?.invoke() + } +} +``` + +**Negative:** `enqueue` only stores the lambda; `drainOne` invokes it after releasing its acquisition, and no caller waits under `stateLock`. With all queue accesses guarded and no outer lock held by the draining caller, registration is not invocation-under-lock. This notification intentionally reads current state at delivery; if the contract instead needs event-time state/order, preserve that with a snapshot/ordered delivery rather than assuming equivalence. + +The queue is a verified private standard `ArrayDeque`, not an unknown executor that might invoke inline. `Thread.join` intentionally remains Java; coroutine suspension and `Mutex` ownership require their own analysis below. + +#### Collection read: verified standard implementation versus unknown custom dispatch + +```kotlin +private class CollectionExample { + private val ownerGuard = Any() + private val owned: MutableList = java.util.ArrayList() + + fun ownedSize(): Int = synchronized(ownerGuard) { owned.size } + + fun suppliedSize(supplied: List<*>): Int = + synchronized(ownerGuard) { supplied.size } +} +``` + +**Negative:** `owned` is an actual non-escaping standard `ArrayList`; every access uses `ownerGuard`. Its bounded `size` read adds no lock/wait edge. This conclusion follows the construction and guard, not the declared `List` name. + +Do not generalize this leaf to all read operations: even standard `ArrayList.contains` can invoke the search argument's `equals`. Trace that target/body and any subclass override rather than treating the collection class as a whitelist. + +**Unknown:** `suppliedSize` alone does not establish the runtime target or a cycle. Do not call it safe or warn merely because it is an interface call. A verified custom `size` getter taking B plus a reachable B -> this instance's `ownerGuard` path would be a positive ABBA case; inspect that implementation rather than whitelisting `Map`/`List` or inventing the path. For example, this runtime target adds a real edge to `secondLock`, but the reverse path must still be established: + +```kotlin +val custom = object : AbstractList() { + override val size: Int + get() = synchronized(secondLock) { 0 } + + override fun get(index: Int): String = + throw IndexOutOfBoundsException(index.toString()) +} +``` + +#### Open call: version revalidation versus an invalidation race + +```kotlin +private class OpenCallExample { + private val stateLock = Any() + private var generation = 0L + private var allowed = true + private var value = 0 + + fun invalidate() { + synchronized(stateLock) { + allowed = false + generation++ + } + } + + fun computeUnsafe(compute: () -> Int): Boolean { + synchronized(stateLock) { + if (!allowed) return false + } + val result = compute() + synchronized(stateLock) { + value = result + return true + } + } + + fun computeValidated(compute: () -> Int): Boolean { + val observed = synchronized(stateLock) { + if (!allowed) return false + generation + } + val result = compute() + synchronized(stateLock) { + if (!allowed || generation != observed) return false + value = result + return true + } + } +} +``` + +Assume the verified computation uses immutable thread-owned input, produces a discardable value, has no irreversible business side effects or invalidatable resource, and may complete in either order across callers. All state accesses remain under `stateLock`. + +**Positive:** a mechanical move leading to `computeUnsafe` lets T2 invalidate after T1's check but before T1's commit. T1 still writes `value` and returns success while `allowed == false`. Keeping individual accesses synchronized did not preserve the invariant. + +**Negative:** `computeValidated` rejects the stale result under the original guard; `invalidate` changes permission/generation atomically. This is a safe open call under the stated constraints, not a fix for arbitrary auth/network/key operations or ordered callbacks. If the computation performs an irreversible operation, revalidation afterward is too late; require a proven reservation/lifetime protocol instead. + +#### Mutex callback: reacquisition versus invocation after release + +This Kotlin example owns one `kotlinx.coroutines.sync.Mutex`, guards mutable `value` with that mutex, and assumes a suspending caller with a callback wired to `write()`: + +```kotlin +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +private class MutexCallbackExample { + private val mutex = Mutex() + private var value = 0 + + suspend fun write() = mutex.withLock { value++ } + suspend fun invokeLocked(callback: suspend () -> Unit) = mutex.withLock { callback() } +} +``` + +**Positive:** `invokeLocked { write() }` reacquires that same non-reentrant mutex before the outer release and self-suspends (or fails with a repeated owner token). Cite both the callback wiring and the concrete mutex identity, not just nested syntax. + +**Negative:** a verified invocation of `write()` after the outer release, with no outer caller waiting while holding that mutex and with state/lifetime/order preserved, has no reacquisition-under-lock cycle. Do not recommend that move unless those constraints actually hold. + +## Monitor stability + +Flag replacement only when it can split protection for the same shared state. Example shared object: + +```kotlin +private class MonitorExample { + @Volatile private var lock: Any = Any() + private var count = 0 + + fun increment() { + synchronized(lock) { count++ } + } + + fun replaceLock() { + lock = Any() + } } ``` T1 can hold the old monitor while another thread replaces `lock` and T2 enters on the new monitor. Both increments now access `count` without a common exclusion/visibility boundary. `volatile` makes replacement visible, not mutually exclusive with holders of the old object. -Safe counterexample: remove replacement, use `private final Object lock = new Object()` (or Kotlin `private val lock = Any()`), safely publish the owning object, and guard every relevant state access with that one stable monitor. Do not request `final` just because a monitor field is non-final if identity is verified stable. +Safe counterexample: remove replacement, use `private val lock = Any()` (Java: `private final Object lock = new Object()`), safely publish the owning object, and guard every relevant state access with that one stable monitor. Do not request `val`/`final` just because a monitor field is mutable/non-final if identity is verified stable. A final reference alone is not proof: two instances' private-final monitors do not protect the same static mutable map, and a final lock does not protect accesses that bypass it. @@ -117,14 +393,19 @@ Require a concrete blocking/contended path **and** a safe narrowing. Example: a Do not recommend moving guarded reads/writes outside a lock or removing synchronization for style. A shorter lock is not automatically safer. Unsafe check-then-act split for shared reservation state: -```java -boolean reserve() { - final boolean available; - synchronized (lock) { available = reserved < capacity; } - if (available) { - synchronized (lock) { reserved++; } +```kotlin +private class ReservationExample { + private val lock = Any() + private val capacity = 1 + private var reserved = 0 + + fun reserve(): Boolean { + val available = synchronized(lock) { reserved < capacity } + if (available) { + synchronized(lock) { reserved++ } + } + return available } - return available; } ``` @@ -151,19 +432,26 @@ Moving this bounded, pure normalization before acquisition is safe: each call ow Compare effective coverage, not just keywords. Before, concurrent callers on the same instance serialize ID allocation: -```java -synchronized int nextId() { return ++id; } +```kotlin +@Synchronized fun nextId(): Int = ++id ``` -Dangerous after: a changed wrapper and helper have lost that monitor, so T1 and T2 can lose updates and return duplicate IDs: +Here `id` is a mutable instance field and `@Synchronized` holds that instance's JVM monitor (`this`), not a coroutine mutex. Dangerous after: a changed wrapper and helper have lost that monitor, so T1 and T2 can lose updates and return duplicate IDs: -```java -int nextId() { return increment(); } -private int increment() { return ++id; } +```kotlin +fun nextId(): Int = increment() +private fun increment(): Int = ++id ``` Safe extraction: retain the entry point's instance monitor for the whole operation, with every other helper caller holding that exact monitor: +```kotlin +@Synchronized fun nextId(): Int = increment() +private fun increment(): Int = ++id +``` + +Brief Java comparison: the instance method's `synchronized` modifier holds the same `this` monitor; removing it from an unguarded wrapper loses the same protection. + ```java synchronized int nextId() { return increment(); } private int increment() { return ++id; } @@ -204,11 +492,11 @@ Require safe publication of this instance and **all** map reads, writes, removal ## Finding evidence -Anchor each finding to a changed line (or the affected call/declaration when locking was removed). Name the actual monitor(s), competing paths/threads, before/after held locks, broken invariant or concrete contention, impact, and minimal safe fix. An unresolved call boundary is an analysis limit, not evidence of deadlock. +Anchor each finding to a changed line (or the affected call/declaration when locking was removed). For changed implementation/injection/override/callback bodies, cite that changed line and the affected locked call. Name the actual monitor(s), runtime callee/callback, competing paths/threads or reentrant invariant access, before/after held locks, broken invariant or concrete contention, impact, and minimal safe fix. An unresolved call boundary is an analysis limit, not evidence of deadlock; apply the bounded [unknown-target rule](#unknown-target-boundaries). For example, on the changed outer acquisition in `rotate`: "`rotate` now holds this instance's `keyLock` while waiting for `cacheLock`; concurrent `refresh` holds the same `cacheLock` while waiting for `keyLock`, so both operations can stop progressing. Acquire `cacheLock` before `keyLock` on both paths." Confirm that ordering also holds in relevant concrete callees. -Use the existing [High/Medium impact criteria](comment-quality-severity.md#severity); never assign blanket severity to nesting, non-final references, or large scopes. Escalate security-relevant races based on their demonstrated impact, not the syntax of the locking construct. +Use the existing [High/Medium impact criteria](comment-quality-severity.md#severity); never assign blanket severity to nesting, non-final references, large scopes, or interface/abstract/overridable dispatch. An interface call is not automatically High severity or a merge blocker. Escalate security-relevant races based on their demonstrated impact, not the syntax of the locking construct. ## Suppressions @@ -217,7 +505,12 @@ Do not flag: - Intentional thread confinement through a clearly enforced single-thread dispatcher/executor. - Read-only data after construction (effectively immutable). - Generated code with known synchronization wrappers. -- Consistent lock order across reachable paths or same-monitor JVM reentry without a demonstrated conflicting path. +- Consistent lock order across reachable paths or same-monitor JVM reentry without a demonstrated conflicting path or invalid intermediate-state access. - Stable private-final/`val` monitors guarding all relevant accesses, or non-final syntax without actual replacement/inconsistent protection. - Helper extraction preserving the original monitor on all callers. - Bounded pure computation on thread-owned inputs outside a lock when invariants, visibility, ordering, snapshots, and resource lifetimes remain valid. +- Known bounded, pure, nonblocking leaves and verified nonblocking standard-collection reads under their owner guard with no user-code dispatch; verify actual runtime targets instead of whitelisting `List`/`Map` by name. +- Truly deferred callbacks invoked after release with no caller wait, with valid state, ordering, and lifetime. +- Generic interface/abstract/overridable calls or unknown external targets without concrete local risk evidence. + +Confinement, immutability, and generated-wrapper suppressions require the changed path to retain those boundaries; do not suppress a new override/callback bypass or a concrete reentrant access to partial state. diff --git a/.github/skills/code-review/references/false-positive-suppression.md b/.github/skills/code-review/references/false-positive-suppression.md index 422ed5f5f3..ad515d6c91 100644 --- a/.github/skills/code-review/references/false-positive-suppression.md +++ b/.github/skills/code-review/references/false-positive-suppression.md @@ -47,3 +47,11 @@ For example, verify the actual population logic before claiming where `clientDat - Do not ask for redundant documentation that accurately restates all non-obvious behavior already. - Do not suggest `val final`, Java `final` for a Kotlin local/property, or `@NonNull` for Kotlin. - Do not flag intentional thread confinement, read-only data after construction, or generated code with known synchronization wrappers. + +## Calls under locks + +Do not flag a call solely because its declared type is an interface/abstract class, its concrete Java or Kotlin method is overridable (including Java virtual and Kotlin `open` methods), or it invokes a callback under a lock. Verify runtime implementations, actual lock/wait edges, concurrent reachability, and invariant access using the [focused concurrency trace](concurrency-threading.md#runtime-target-trace). Do not whitelist `List`/`Map` by name: suppress a bounded nonblocking read only after verifying the concrete implementation and owner guard. + +Suppress benign same-thread JVM monitor reentry when the invariant is complete, and verified deferred callbacks after release with no caller wait when state, ordering, and lifetime remain valid. These are not exemptions for a callback accessing partial state, a worker awaited under its required lock, or non-reentrant `Mutex` reacquisition. Confinement, immutability, and generated-wrapper suppressions apply only if the changed implementation/callback preserves those boundaries. + +An unknown external/native/reflective callee is an analysis limit, not a probable deadlock or proof of safety. Allow at most one clearly non-blocking `Sanity check:` contract note only when the diff already establishes a specific local risk, such as uncontrolled callback execution under a shared auth-cache lock; identify the exact missing contract. Stay silent for a generic unresolved interface call without such evidence, and do not duplicate a lock-order finding. Do not assign automatic High severity or merge-blocker status to dispatch syntax. From 9b7ceef40e1d77172418ff049f1a7669e03d0af5 Mon Sep 17 00:00:00 2001 From: Sowmya Malayanur <69237821+somalaya@users.noreply.github.com> Date: Mon, 12 Oct 2026 23:34:47 -0700 Subject: [PATCH 07/16] Premortem doc for ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF flight (#3300) Added ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF in PR https://github.com/AzureAD/microsoft-authentication-library-common-for-android/pull/3290 This PR contains the premortem doc for the same flight --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...ICE_CA_MANAGEMENT_APP_HANDOFF-Dashboard.md | 325 ++++++++++++++++++ ...ICE_CA_MANAGEMENT_APP_HANDOFF-Premortem.md | 155 +++++++++ 2 files changed, 480 insertions(+) create mode 100644 docs/premortem/ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Dashboard.md create mode 100644 docs/premortem/ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Premortem.md diff --git a/docs/premortem/ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Dashboard.md b/docs/premortem/ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Dashboard.md new file mode 100644 index 0000000000..53c0314e12 --- /dev/null +++ b/docs/premortem/ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Dashboard.md @@ -0,0 +1,325 @@ + + +# `ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF` dashboard setup + +**Dashboard:** [New Android Broker Dashboard - Device CA native management-app handoff](https://dataexplorer.azure.com/dashboards/3f6536b7-62e6-407d-8071-31575adb78bb#627f67cd-0bfd-450e-8a81-f5e03758a4c3) + +**Status:** Panels 1-6 below are configured on the dashboard. + +**Cluster:** `https://idsharedeus2.kusto.windows.net/` + +**Production database:** `ad-accounts-android-otel` + +**Validation database:** `android-broker-otel-sandbox` + +**Table:** `android_spans` + +**Span:** `ProcessDeviceCaRequest` + +> **Data-source note:** The production dashboard uses `ad-accounts-android-otel`. As of 2026-10-08, that database has no `ProcessDeviceCaRequest` spans, so these tiles correctly display no results. To inspect the pre-deployment test spans, temporarily run the query against `android-broker-otel-sandbox`, select Broker Host App Version `6.2610.6718`, and use a time range containing `2026-10-08 20:17 UTC`. Do not point the production monitoring tiles permanently at the sandbox database. + +These query bodies were executed against the sandbox database on 2026-10-08 using local `let` values for the dashboard parameters. After correcting the version parameter to the dashboard's actual `_broker_host_app_version` name, all six queries were rerun successfully with both `["all"]` and `["6.2610.6718"]`. Panels 1-6 are now configured as tiles in the dashboard linked above. + +At the time of the version-specific validation, sandbox contained two spans from app version `6.2610.6718`, both with the flight and WebCP enabled: + +- `native_handoff_failed_app_link_fallback_succeeded` +- `webview_load_succeeded` + +Both spans had `span_status=OK`, a terminal routing outcome, and `google_dpc_device_owner` as the detected management owner. Production contained no `ProcessDeviceCaRequest` spans at validation time, which is expected before a build containing the new telemetry is deployed. + +The flight defaults to `true`. `is_native_device_ca_management_app_handoff_enabled` records the effective native-routing gate (`isRunningOnAuthService && flight enabled`), not the raw ECS value. Within this dashboard's measured brokered WebCP scope, normal production telemetry should report `true`; `false` is expected after the ECS kill switch is used. The Teams IP Phone compatibility path returns before evaluating this gate and is displayed as `not_evaluated`. + +The queries use `column_ifexists()` because some newly added optional fallback columns will not be present in the production table schema until telemetry carrying those attributes is ingested. + +## Dashboard parameters + +Use the dashboard's existing `_startTime`, `_endTime`, and `_broker_host_app_version` parameters. `_broker_host_app_version` filters `AppInfo_Version` and already provides the Broker Host App Version selector shown on the dashboard; do not add a separate app-version parameter. + +## Page description + +**Device CA native management-app handoff monitoring** + +This page monitors how Android Broker routes WebCP Device CA requests when `EnableNativeDeviceCaManagementAppHandoff` is enabled by default. The tiles verify that routing telemetry is complete, the correct management owner is detected, the targeted native Re-WPJ handoff is accepted, and the ordered App Link, generic HTTPS, WebView, or browser fallbacks remain available when an earlier route cannot be launched. + +For this feature, a successful routing outcome means that Android accepted the intended management-app or fallback launch/load and the broker returned `MDM_FLOW`. The original authorization request then ends with `device_needs_to_be_managed`. Re-WPJ behavior inside the management app and later authentication attempts are outside this page's scope. + +The page also highlights terminal broker-side routing failures, changes in fallback usage, missing terminal outcomes, and unexpected effective routing-gate state. `Flight=true` is normal for measured brokered WebCP traffic, `Flight=not_evaluated` is expected for the Teams IP Phone compatibility path, and `Flight=false` is expected after rollback. + +## Panel 1 - Device CA span volume and telemetry completeness + +**Visualization:** Line chart + +**X axis:** `Day` + +**Y axes:** `Spans`, `MissingOutcome` + +**Series:** `Flight` + +**Title:** `Device CA span volume and telemetry completeness` + +```kusto +android_spans +| where EventInfo_Time between (_startTime .. _endTime) +| where _broker_host_app_version has "all" + or AppInfo_Version in (_broker_host_app_version) +| where span_name == "ProcessDeviceCaRequest" +| extend Outcome = tostring(column_ifexists("device_ca_routing_outcome", "")), + RawFlight = tolower(tostring(column_ifexists( + "is_native_device_ca_management_app_handoff_enabled", ""))) +| extend Flight = iff( + Outcome == "legacy_company_portal_launch_succeeded", + "not_evaluated", + RawFlight) +| summarize Spans = count(), + MissingOutcome = countif(isempty(Outcome)) + by Day = bin(EventInfo_Time, 1d), Flight +| order by Day asc, Flight asc +``` + +Expected during normal operation: + +- `Flight` is `true` for measured brokered WebCP traffic. +- `Flight` is `not_evaluated` for the Teams IP Phone compatibility path. +- `MissingOutcome` is zero. +- `false` appears only after rollback. + +Any other missing flight value or terminal outcome requires investigation before interpreting the other panels. + +## Panel 2 - Device CA routing success rate + +**Visualization:** Line chart + +**X axis:** `Hour` + +**Y axis:** `RoutingSuccessRatePct` + +**Title:** `Device CA routing success rate` + +```kusto +android_spans +| where EventInfo_Time between (_startTime .. _endTime) +| where _broker_host_app_version has "all" + or AppInfo_Version in (_broker_host_app_version) +| where span_name == "ProcessDeviceCaRequest" +| extend Outcome = tostring(column_ifexists("device_ca_routing_outcome", "")) +| summarize Total = count(), + TerminalFailures = countif( + span_status =~ "ERROR" + or Outcome in ( + "browser_launch_failed", + "webview_load_failed", + "unexpected_routing_failure")) + by Hour = bin(EventInfo_Time, 1h) +| extend RoutingSuccessRatePct = + round(100.0 * (Total - TerminalFailures) / Total, 2) +| project Hour, Total, TerminalFailures, RoutingSuccessRatePct +| order by Hour asc +``` + +Investigate a decrease greater than 0.5 percentage points or a terminal-failure rate greater than 2x the stable baseline, sustained for one hour with at least 100 sampled spans. + +## Panel 3 - Terminal routing outcome distribution + +**Visualization:** Table + +**Category:** `Outcome` + +**Values:** `Count`, `SharePct`, `NativeHandoffSuccessPct` + +**Split/filter:** `AppInfo_Version`, `Owner` + +**Title:** `Device CA terminal routing outcomes` + +```kusto +let Base = android_spans +| where EventInfo_Time between (_startTime .. _endTime) +| where _broker_host_app_version has "all" + or AppInfo_Version in (_broker_host_app_version) +| where span_name == "ProcessDeviceCaRequest" +| extend Outcome = tostring(column_ifexists("device_ca_routing_outcome", "")), + Owner = tostring(column_ifexists("device_ca_management_owner", "")); +let Counts = Base +| summarize Count = count() by Outcome, Owner, AppInfo_Version; +let Totals = Base +| summarize Total = count() by AppInfo_Version; +let Eligible = Base +| where Owner in ( + "company_portal_profile_owner", + "google_dpc_profile_owner", + "google_dpc_device_owner") +| summarize EligibleTotal = count(), + NativeSuccess = countif(Outcome == "native_handoff_succeeded") + by AppInfo_Version; +Counts +| join kind=inner Totals on AppInfo_Version +| join kind=leftouter Eligible on AppInfo_Version +| extend SharePct = round(100.0 * Count / Total, 2), + NativeHandoffSuccessPct = iff( + EligibleTotal > 0, + round(100.0 * NativeSuccess / EligibleTotal, 2), + real(null)) +| project AppInfo_Version, Owner, Outcome, Count, SharePct, + EligibleTotal, NativeSuccess, NativeHandoffSuccessPct +| order by AppInfo_Version asc, Owner asc, Count desc +``` + +Successful terminal outcomes include: + +- `legacy_company_portal_launch_succeeded` - Teams IP Phone compatibility path only. +- `native_handoff_succeeded` +- `native_handoff_failed_app_link_fallback_succeeded` +- `native_handoff_app_link_failed_generic_https_fallback_succeeded` +- `browser_launch_succeeded` +- `webview_load_succeeded` + +Failure outcomes are: + +- `browser_launch_failed` +- `webview_load_failed` +- `unexpected_routing_failure` + +Track the fallback share even when the terminal result succeeds. Investigate a fallback-share increase greater than 5 percentage points or 2x the stable baseline. + +`NativeHandoffSuccessPct` uses only requests with a supported management owner as its denominator. Investigate a value below 95% when there are at least 100 eligible sampled spans. + +## Panel 4 - Detected management owner + +**Visualization:** Table or stacked bar chart + +**Category:** `Owner` + +**Value:** `Count` + +**Split/filter:** `AppInfo_Version` + +**Title:** `Device CA management owner distribution` + +```kusto +android_spans +| where EventInfo_Time between (_startTime .. _endTime) +| where _broker_host_app_version has "all" + or AppInfo_Version in (_broker_host_app_version) +| where span_name == "ProcessDeviceCaRequest" +| extend Owner = tostring(column_ifexists("device_ca_management_owner", "")) +| summarize Count = count() by Owner, AppInfo_Version +| order by AppInfo_Version asc, Count desc +``` + +Expected owner values: + +- `company_portal_profile_owner` +- `google_dpc_profile_owner` +- `google_dpc_device_owner` +- `none` +- `device_policy_manager_unavailable` +- `not_evaluated` + +`not_evaluated` is expected when the Teams IP Phone compatibility path succeeds or native routing is ineligible. Investigate unexpected `none`, `device_policy_manager_unavailable`, or a distribution shift concentrated in an app version, Android version, OEM, or management mode. + +## Panel 5 - Fallback-stage outcomes + +**Visualization:** Table or stacked bar chart + +**Category:** `Stage` + +**Series:** `Outcome` + +**Value:** `Count` + +**Title:** `Device CA fallback-stage outcomes` + +```kusto +let Base = android_spans +| where EventInfo_Time between (_startTime .. _endTime) +| where _broker_host_app_version has "all" + or AppInfo_Version in (_broker_host_app_version) +| where span_name == "ProcessDeviceCaRequest" +| extend AppLink = tostring(column_ifexists( + "device_ca_management_app_link_outcome", "")), + GenericHttps = tostring(column_ifexists( + "device_ca_generic_https_launch_outcome", "")), + WebView = tostring(column_ifexists( + "device_ca_webview_load_outcome", "")); +union + (Base + | where isnotempty(AppLink) + | project EventInfo_Time, Stage = "Package App Link", + Outcome = AppLink, AppInfo_Version), + (Base + | where isnotempty(GenericHttps) + | project EventInfo_Time, Stage = "Generic HTTPS", + Outcome = GenericHttps, AppInfo_Version), + (Base + | where isnotempty(WebView) + | project EventInfo_Time, Stage = "WebView", + Outcome = WebView, AppInfo_Version) +| summarize Count = count() by Stage, Outcome, AppInfo_Version +| order by AppInfo_Version asc, Stage asc, Count desc +``` + +Possible package App Link outcomes: + +- `launch_succeeded` +- `launch_failed` + +Possible generic HTTPS outcomes: + +- `handler_not_found` +- `launch_succeeded` +- `launch_failed` + +Possible WebView outcomes: + +- `load_succeeded` +- `load_failed` + +The package App Link, generic HTTPS, and WebView attributes are stage-specific and may be empty when that stage was not attempted. + +## Panel 6 - Terminal routing failures + +**Visualization:** Table + +**Columns:** `Count`, `Outcome`, `error_code`, `span_status_description`, `AppInfo_Version` + +**Title:** `Device CA terminal routing failures` + +```kusto +android_spans +| where EventInfo_Time between (_startTime .. _endTime) +| where _broker_host_app_version has "all" + or AppInfo_Version in (_broker_host_app_version) +| where span_name == "ProcessDeviceCaRequest" +| extend Outcome = tostring(column_ifexists("device_ca_routing_outcome", "")) +| where span_status =~ "ERROR" + or Outcome in ( + "browser_launch_failed", + "webview_load_failed", + "unexpected_routing_failure") +| summarize Count = count() + by Outcome, error_code, span_status_description, AppInfo_Version +| order by Count desc +``` + +Any new terminal outcome or error concentration in one app version requires investigation. Do not make a rollback decision from fewer than 100 sampled spans in the selected segment unless the failure is deterministic or severe. + +## Monitoring order + +Review panels in this order: + +1. **Volume and completeness** - verify sufficient sample size, `Flight=true`, and no missing terminal outcomes. +2. **Routing success rate** - check the broad guardrail. +3. **Terminal outcome distribution** - identify whether native launch or a fallback path changed. +4. **Management owner** - locate owner-detection changes. +5. **Fallback-stage outcomes** - identify the failing launch/load stage. +6. **Terminal failures** - inspect bounded failure categories by app version. + +The Broker default sampling configuration currently samples `ProcessDeviceCaRequest` at 50%. Always display sampled counts next to percentages and avoid decisions based on sparse points. + +## Rollback validation + +After setting `EnableNativeDeviceCaManagementAppHandoff=false` in ECS: + +1. Confirm new spans report `Flight=false`. +2. Confirm `native_handoff_succeeded` and native-specific App Link/generic HTTPS outcomes stop after ECS propagation. +3. Confirm requests use the legacy WebView/browser outcomes. +4. Compare terminal routing failures with the stable default-on baseline. diff --git a/docs/premortem/ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Premortem.md b/docs/premortem/ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Premortem.md new file mode 100644 index 0000000000..8f9b7c7749 --- /dev/null +++ b/docs/premortem/ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Premortem.md @@ -0,0 +1,155 @@ + + +# Premortem - `ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF` + +**Owner:** Sowmya Malayanur | **Approver:** TBD + +**Common PR:** [AzureAD/microsoft-authentication-library-common-for-android#3290](https://github.com/AzureAD/microsoft-authentication-library-common-for-android/pull/3290) | **Broker PR:** [security/ad-accounts-for-android#321](https://msft.ghe.com/security/ad-accounts-for-android/pull/321) | **Work item:** [AB#3779482](https://identitydivision.visualstudio.com/Engineering/_workitems/edit/3779482) + +**Monitoring dashboard:** [New Android Broker Dashboard - Device CA native management-app handoff](https://dataexplorer.azure.com/dashboards/3f6536b7-62e6-407d-8071-31575adb78bb#627f67cd-0bfd-450e-8a81-f5e03758a4c3) | **Query/runbook:** [`ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Dashboard.md`](./ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF-Dashboard.md) + +`ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF` defaults to `true`. Set it to `false` in ECS to stop native management-app routing and restore the existing Device CA WebView/browser behavior without an app release. + +The router contains a separate pre-existing exception for production-signed Teams IP Phone devices (`com.microsoft.skype.teams.ipphone`) with Company Portal installed. It launches Company Portal before evaluating this flight because those devices have no browser or Back button. This branch does not execute on ordinary non-Teams devices and is not a risk introduced by this flight. + +| Flight | ON does | +|---|---| +| `ENABLE_NATIVE_DEVICE_CA_MANAGEMENT_APP_HANDOFF` (`EnableNativeDeviceCaManagementAppHandoff`) | For brokered WebCP Device CA requests, detects a supported profile/device owner and targets `intune-remediation://re-wpj` to that management app. If native launch fails, routing falls back in order to a package-targeted HTTPS App Link, generic HTTPS, and the existing WebView/browser path. Brokerless and non-WebCP flows retain their existing behavior. | + +## Intended routing + +1. On Teams IP Phone devices only, the pre-existing compatibility branch launches Company Portal and stops before evaluating the flight. +2. On all other devices, continue through legacy WebView/browser routing when WebCP-in-WebView is disabled, the request is brokerless, or this flight is disabled. +3. When the flight is eligible, detect a supported management owner in the current Android user: + - Company Portal profile owner -> target Company Portal. + - Google DPC profile owner -> target Intune. + - Google DPC device owner -> target Intune. +4. Launch the package-targeted native Re-WPJ URI. +5. If native launch fails with an expected resolution or security error, try: + 1. package-targeted HTTPS App Link; + 2. generic HTTPS handler; + 3. the existing WebView path. +6. Unexpected runtime failures remain terminal and return the existing authorization error. + +## Risks and mitigations + +The likelihood ratings below are qualitative assessments based on routing scope, automated tests, and manual validation. They are not production incident probabilities; a production baseline does not exist yet. + +1. **The wrong management app is selected or no owner is detected** + - **Likelihood:** Low for selecting the wrong app. A missing supported owner is possible on an unsupported or unexpected management topology, but it is a safe fallback condition rather than a terminal failure. + - **Why it is bounded:** The router does not infer the owner from installed packages. It asks Android `DevicePolicyManager` whether Company Portal or Google DPC is the profile/device owner and uses a fixed mapping: Company Portal owner -> Company Portal; Google DPC owner -> Intune. + - **Pre-release evidence:** Unit tests cover Company Portal profile owner, Google DPC profile owner, Google DPC device owner, no supported owner, and unavailable `DevicePolicyManager`. Manual validation results are linked below. + - **Mitigation and response:** If no supported owner is detected, the request stays on the existing WebView/browser path. The management-owner tile exposes `none`, `device_policy_manager_unavailable`, and distribution changes. If telemetry indicates incorrect routing, disable the flight in ECS to restore legacy routing. + +2. **The fallback chain fails after native launch fails** + - **Likelihood:** Low to medium for an individual fallback failure because package visibility, App Link verification, browser policy, and OEM behavior vary. Low for a terminal failure because every recovery route must fail. + - **Why it is bounded:** Expected native-launch failures (`ActivityNotFoundException` or `SecurityException`) proceed through package-targeted App Link, generic HTTPS, and finally the existing WebView path. + - **Pre-release evidence:** Unit tests cover App Link success, App Link failure followed by generic HTTPS success, missing browser followed by WebView success, policy-denied launches, WebView load failure, and terminal error handling. Sandbox telemetry validated both App Link fallback success and WebView fallback success. + - **Mitigation and response:** Dashboard tiles separately show terminal outcomes, stage-level fallback outcomes, and terminal failures. A successful fallback completes this flight's responsibility. If terminal failures breach the documented threshold, disable the flight to bypass the native-specific routes. + +3. **The flight affects an unintended flow** + - **Likelihood:** Very low. + - **Why it is bounded:** Native routing is reachable only for a URL whose parsed `ismdmurl` query parameter equals `1`, while running in the auth service with WebCP-in-WebView enabled. Brokerless requests, non-WebCP requests, and ordinary external website redirects retain their existing paths. + - **Pre-release evidence:** Parser tests accept the marker in any query position and reject `ismdmurl=0`, `notismdmurl=1`, and malformed substring matches. Existing browser-redirect tests verify that an ordinary `browser://` URL opens in the browser and returns `CANCELLED`. + - **Mitigation and response:** Unexpected `ProcessDeviceCaRequest` volume is visible on the dashboard and can be inspected at trace level to confirm scope. The ECS kill switch removes native owner detection and handoff without changing the ordinary browser redirect path. + +4. **Routing launches the management app more than once** + - **Likelihood:** Low, but not directly measurable as a distinct telemetry outcome. + - **Why it is bounded:** Each router invocation makes one native launch attempt. On accepted handoff, it stops WebView loading and returns `MDM_FLOW`, which ends the original authorization request. Recovery-path tests verify a single completion callback. + - **Pre-release evidence:** Unit tests verify one native launch attempt per routed request. Visible duplicate activity is a manual-validation check because telemetry cannot prove how many activities the user saw. + - **Mitigation and response:** Investigate duplicate-launch reports together with same-trace Device CA span volume and lifecycle details; telemetry alone cannot prove that two visible activities opened. Disable the flight in ECS if duplication is reproducible. + +## Rollout decision + +Keep the flight defaulted to `true`; do not use a percentage-based slow rollout. + +- The effective cohort is already narrowly constrained to brokered WebCP Device CA requests with the exact Device CA marker. Ordinary sign-ins and ordinary `browser://` redirects do not enter native routing. +- A missing owner or expected launch failure degrades through the ordered fallbacks to the pre-existing WebView/browser behavior. +- Automated tests cover each owner decision, eligibility boundary, fallback stage, terminal failure, and flight-off behavior; manual validation is linked below. +- Six production dashboard tiles cover volume/completeness, routing success, terminal outcomes, owner detection, fallback stages, and terminal failures. +- ECS remains an immediate kill switch that restores legacy routing without an app release. + +A percentage rollout would reduce the already-low sampled Device CA volume and delay useful confidence without materially reducing risk to ineligible authentication traffic. The release guardrail is therefore default-on monitoring with explicit thresholds and immediate ECS rollback, not progressive exposure. + +## Can we measure failure? + +**Yes.** The flight is responsible for selecting and launching the management app, executing the fallback chain when needed, and returning `MDM_FLOW` error code. + +The `ProcessDeviceCaRequest` span records the flight gate, detected management owner, terminal routing outcome, and each fallback stage. It can detect owner-resolution changes, native launch failures, fallback concentration, and terminal broker-side failures. + +The original authorization request ends when `MDM_FLOW` is returned and is converted to an `AuthorizationStatus.FAIL` / `device_needs_to_be_managed` error. What happens inside the management app after the accepted handoff, and any later authentication request, are outside this flight's monitoring contract. + +## Monitoring baseline + +For the default-on production release: + +1. Use the six Device CA tiles in the [New Android Broker Dashboard](https://dataexplorer.azure.com/dashboards/3f6536b7-62e6-407d-8071-31575adb78bb#627f67cd-0bfd-450e-8a81-f5e03758a4c3) to monitor volume/completeness, routing success, terminal outcomes, management owner, fallback stages, and terminal failures. Use the existing Broker Host App Version parameter for release-specific filtering. +2. Establish a stable effective native-routing-gate baseline (`is_native_device_ca_management_app_handoff_enabled=true`) for terminal routing failures, fallback outcomes, and Device CA request volume. +3. Validate that every sampled span has a terminal `device_ca_routing_outcome`. +4. Confirm that measured brokered WebCP telemetry reports the effective native-routing gate as `true`. The Teams IP Phone compatibility path does not evaluate the gate. Within this measured scope, `false` should appear after rollback. +5. Use ad-hoc Kusto investigation to split a suspicious app-version or management-owner segment further by Android version, broker package, OEM, or management mode. +6. Do not make a rollback decision from fewer than 100 sampled Device CA spans in the selected app-version or management-owner segment. The Broker default sampling configuration currently samples `ProcessDeviceCaRequest` at 50%, so review sampled counts with every rate. + +The dashboard uses the production `ad-accounts-android-otel` database. Before a build containing `ProcessDeviceCaRequest` telemetry reaches production, empty tiles are expected. Pre-deployment test spans are available only in `android-broker-otel-sandbox`. + +## Monitoring plan + +Review the [Device CA dashboard](https://dataexplorer.azure.com/dashboards/3f6536b7-62e6-407d-8071-31575adb78bb#627f67cd-0bfd-450e-8a81-f5e03758a4c3) at least twice daily for the first 14 days of the default-on production release. Review the six tiles in this order: + +1. **Device CA span volume and telemetry completeness** + - Compare `ProcessDeviceCaRequest` volume by app version. + - Confirm the effective native-routing gate is `true`; `not_evaluated` is expected for the Teams IP Phone compatibility path, and `false` is expected after rollback. + - Verify all sampled spans have a terminal routing outcome. + - Investigate any spans that are brokerless or not in WebCP. +2. **Device CA routing success rate** + - Count `browser_launch_failed`, `webview_load_failed`, `unexpected_routing_failure`, and `ERROR` spans. + - Investigate an increase greater than 0.5 percentage points or 2x the stable baseline, sustained for one hour with at least 100 sampled spans. +3. **Device CA terminal routing outcomes** + - Among requests with a supported owner, track `native_handoff_succeeded`. + - Track the share of requests ending in App Link, generic HTTPS, WebView, or browser fallback. + - Investigate any app-version, Android-version, or management-owner segment where native handoff success drops below 95% with at least 100 eligible sampled spans. + - Investigate a fallback-share increase greater than 5 percentage points or 2x baseline. +4. **Device CA management owner distribution** + - Break down `device_ca_management_owner`. + - Investigate `device_policy_manager_unavailable`, unexpected `none`, or a sudden owner-distribution shift concentrated in an Android version, OEM, or management mode. +5. **Device CA fallback-stage outcomes** + - Identify whether package App Link, generic HTTPS, or WebView is absorbing a native handoff failure. + - Investigate any new `launch_failed`, `handler_not_found`, or `load_failed` concentration. +6. **Device CA terminal routing failures** + - Inspect terminal failures by outcome, error, and Broker Host App Version. + - A successful fallback is not a reason to ignore a native-routing regression, but only terminal broker-side failures directly indicate that no recovery surface was accepted. +7. **Support and incidents** + - Search for the wrong management app opening, the management app not opening, duplicate launches, or all routing fallbacks failing. + +## Manual validation + +All manually validated tests are documented in the [Device CA manual validation results](https://microsoft.sharepoint-df.com/:fl:/g/contentstorage/CSP_1bb4c07e-c0f1-4d85-8af0-3549e849e1b6/IQDjl-wiXVX2S64cOGBm1TvvAa6uxLWfPHBbsAVm9rbOtOc?e=RFUA78&nav=cz0lMkZjb250ZW50c3RvcmFnZSUyRkNTUF8xYmI0YzA3ZS1jMGYxLTRkODUtOGFmMC0zNTQ5ZTg0OWUxYjYmZD1iJTIxZnNDMEdfSEFoVTJLOERWSjZFbmh0bnBnLTFOc2hybEVxNU9OR2VpMXJELUhEYnpmUmY5SlQ2U2lmRTJVa3VnTiZmPTAxV05PRUJPN0RTN1dDRVhLVjZaRjI0SEJZTUJUTktPN1AmYz0lMkYmYT1Mb29wQXBwJnA9JTQwZmx1aWR4JTJGbG9vcC1wYWdlLWNvbnRhaW5lcg%3D%3D). + +## Rollback + +Set `EnableNativeDeviceCaManagementAppHandoff` to `false` in ECS. + +Expected behavior after propagation: + +- The separate Teams IP Phone compatibility branch remains unchanged because it runs before the flight check. +- Brokered WebCP Device CA requests stop management-owner detection and targeted native Re-WPJ launch. +- Requests return to the existing WebView/browser routing. +- App Link and generic HTTPS fallbacks that are specific to native routing are no longer attempted. +- No app release is required. + +After rollback: + +1. Confirm new non-compatibility spans report `is_native_device_ca_management_app_handoff_enabled=false`. +2. Confirm native outcomes stop for the affected app versions after ECS propagation; use both signals as rollback evidence. +3. Compare terminal routing failure rates with the stable default-on baseline. +4. Preserve the affected app-version, Android-version, and management-owner dimensions plus example correlation IDs for investigation. + +## Post-release criteria to keep the default enabled + +- No monitoring threshold breach during the first 14 days of the production release. +- At least 5,000 sampled Device CA spans with the effective native-routing gate reported as `true` across supported Android versions and management modes. +- No unexplained telemetry completeness gaps. +- Terminal routing failures remain within the thresholds above. +- Native handoff and fallback distributions remain stable by management owner and app version. +- Intune-owned management-mode validation is complete. +- No Sev 2 or higher IcM attributed to native Device CA management-app routing. From a14a3f52c5d9679e35d564bfee6af5263fe85de1 Mon Sep 17 00:00:00 2001 From: Sowmya Malayanur <69237821+somalaya@users.noreply.github.com> Date: Tue, 13 Oct 2026 10:06:30 -0700 Subject: [PATCH 08/16] Handle OpenID VC target-blank navigation (#3299) ### Issue - eSTS/Unified platform team made some changes recently to some of the total loss recovery and VID stepup CA button URLs. The buttons are supposed to push the user out of the webview. The way this happens is when they trigger target=_blank urls. However, they previously used to have a pattern like /tlr/start/ when they. But now, there is no such set pattern and they cannot add it as well due to some code complexities. - Previously, we relied on the path /tlr/start/ and conditionally enabled mWebView.getSettings().setSupportMultipleWindows. - But now, we have to enable it for all URLs as there is no deterministic way to figure out a TLR/Stepup URL needed for VID scenarios. ### Fix - We will be enabling setting mWebView.getSettings().setSupportMultipleWindows(true) by default. The changes are put behind a flight, so we should be able to disable it if needed. - Once it was enabled, the button that triggers verified credential presentation in stepup flows also needed special handling as open-id:vc// scheme url also is triggered with target=_blank. We were previously only allowing https schemes. Note, this does not need to be put behind flight as we are anyway protecting the whole changes under CommonFlight.ENABLE_WEBVIEW_MULTIPLE_WINDOWS - Also, iOS enabled this behavior about three months ago and has not reported issues. - eSTS code review confirmed `target=_blank` is currently used for auxiliary URLs such as Terms of Use, privacy, and help documentation. - Note : We have raised a request to eSTS to atleast add a Query parameter for us to make this process more deterministic. They have raised a PR https://msazure.visualstudio.com/One/_git/ESTS-Main/pullrequest/17442421. I will test with this fix and if it works, I will create another PR to reduce the risk. ### Summary - Handle `target=_blank` OpenID VC links in the authentication WebView through the existing wallet handler. - Route user-initiated HTTPS popups to the system browser; allow non-user-initiated popups inline only for HTTPS URLs and reject other schemes. - Add routing and telemetry coverage. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .../internal/AuthenticationConstants.java | 25 +- .../oauth2/WebViewAuthorizationFragment.java | 228 +++-- .../AzureActiveDirectoryWebViewClient.java | 150 ++- ...wAuthorizationFragmentMultiWindowTest.java | 942 ++++++++++++++++-- ...AzureActiveDirectoryWebViewClientTest.java | 273 ++++- .../common/java/flighting/CommonFlight.java | 3 +- .../java/opentelemetry/AttributeName.java | 20 +- .../java/opentelemetry/SpanExtension.java | 36 + .../flighting/CommonFlightsManagerTest.java | 24 + .../java/opentelemetry/SpanExtensionTest.kt | 73 ++ 10 files changed, 1574 insertions(+), 200 deletions(-) create mode 100644 common4j/src/test/com/microsoft/identity/common/java/opentelemetry/SpanExtensionTest.kt diff --git a/common/src/main/java/com/microsoft/identity/common/adal/internal/AuthenticationConstants.java b/common/src/main/java/com/microsoft/identity/common/adal/internal/AuthenticationConstants.java index 1e48c0d7c3..a1de78107a 100644 --- a/common/src/main/java/com/microsoft/identity/common/adal/internal/AuthenticationConstants.java +++ b/common/src/main/java/com/microsoft/identity/common/adal/internal/AuthenticationConstants.java @@ -1317,12 +1317,17 @@ public static String computeMaxHostBrokerProtocol() { */ public static final String AMAZON_APP_REDIRECT_PREFIX = "aea://"; + /** + * Custom URI scheme for OpenID Verifiable Credentials. + */ + public static final String OPENID_VC_SCHEME = "openid-vc"; + /** * Custom URI scheme prefix for OpenID Verifiable Credentials. * WebView cannot load this scheme natively; it must be intercepted and * forwarded to an external handler (wallet app) via an ACTION_VIEW intent. */ - public static final String OPENID_VC_SCHEME_PREFIX = "openid-vc://"; + public static final String OPENID_VC_SCHEME_PREFIX = OPENID_VC_SCHEME + "://"; /** * Prefix for the Authenticator MFA linking. @@ -1500,11 +1505,6 @@ public static String computeMaxHostBrokerProtocol() { */ public static final String REDIRECT_SSL_PREFIX = "https://"; - /** - * Path segment for the TLR (Total loss recovery) start page. - */ - public static final String TLR_START_PATH = "/tlr/start"; - /** * WebView routing value when the target URL from a target=_blank navigation is null. */ @@ -1516,14 +1516,19 @@ public static String computeMaxHostBrokerProtocol() { public static final String WEBVIEW_TARGET_BLANK_ROUTE_NON_SSL = "non_ssl"; /** - * WebView routing value when the target URL is loaded inline (non-TLR page). + * WebView routing value when an OpenID VC target is delegated to the authentication WebView. + */ + public static final String WEBVIEW_TARGET_BLANK_ROUTE_OPENID_VC = "openid_vc"; + + /** + * WebView routing value when the target URL is delegated to the system browser. */ - public static final String WEBVIEW_TARGET_BLANK_ROUTE_NON_TLR = "non_tlr_flow"; + public static final String WEBVIEW_TARGET_BLANK_ROUTE_BROWSER = "browser"; /** - * WebView routing value when the target URL is delegated to the system browser (TLR page). + * HTTPS popup loaded inline after external browser dispatch failed. */ - public static final String WEBVIEW_TARGET_BLANK_ROUTE_TLR = "tlr_flow"; + public static final String WEBVIEW_TARGET_BLANK_ROUTE_BROWSER_FALLBACK = "browser_fallback"; /** * WebView routing value when the popup was not initiated by a user gesture. diff --git a/common/src/main/java/com/microsoft/identity/common/internal/providers/oauth2/WebViewAuthorizationFragment.java b/common/src/main/java/com/microsoft/identity/common/internal/providers/oauth2/WebViewAuthorizationFragment.java index a366133f5a..7397a778bb 100644 --- a/common/src/main/java/com/microsoft/identity/common/internal/providers/oauth2/WebViewAuthorizationFragment.java +++ b/common/src/main/java/com/microsoft/identity/common/internal/providers/oauth2/WebViewAuthorizationFragment.java @@ -90,9 +90,12 @@ import com.microsoft.identity.common.java.opentelemetry.AttributeName; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import static com.microsoft.identity.common.java.AuthenticationConstants.OAuth2.UTID; @@ -117,6 +120,7 @@ public class WebViewAuthorizationFragment extends AuthorizationFragment { private static final String PKEYAUTH_STATUS = "pkeyAuthStatus"; private WebView mWebView; + private final Set mInterceptorWebViews = new HashSet<>(); private boolean mPasskeyWebListenerHooked; @@ -346,12 +350,10 @@ public void onPageLoaded(final String url) { mWebView.evaluateJavascript(javascriptToExecute[0], null); } - // Dynamically toggle multiple-windows support so that target="_blank" - // interception is active ONLY on the TLR start page. On all other - // pages the WebView behaves exactly as before. + // Enable target="_blank" interception for all pages when flighted. if (CommonFlightsManager.INSTANCE.getFlightsProvider() .isFlightEnabled(CommonFlight.ENABLE_WEBVIEW_MULTIPLE_WINDOWS)) { - mWebView.getSettings().setSupportMultipleWindows(isTlrUrl(url)); + mWebView.getSettings().setSupportMultipleWindows(true); } } }, @@ -394,6 +396,7 @@ public void handleBackButtonPressed() { /** * Set up the web view configurations. + * Popup window creation is logged; navigation telemetry starts only when a URL is intercepted. * * @param view View * @param webViewClient AzureActiveDirectoryWebViewClient @@ -479,52 +482,101 @@ public Bitmap getDefaultVideoPoster() { @Override public boolean onCreateWindow(final WebView view, boolean isDialog, boolean isUserGesture, final Message resultMsg) { - if (resultMsg.obj == null) { - Logger.error(methodTag, "onCreateWindow: resultMsg.obj is null, cannot set up transport.", null); - return false; - } - - final SpanContext parentSpanContext = requireActivity() instanceof AuthorizationActivity - ? ((AuthorizationActivity) requireActivity()).getSpanContext() : null; - final Span span = OTelUtility.createSpanFromParent( - SpanName.WebViewTargetBlankNavigation.name(), parentSpanContext); + final FragmentActivity host = getActivity(); + final SpanContext parentSpanContext = host instanceof AuthorizationActivity + ? ((AuthorizationActivity) host).getSpanContext() : null; boolean windowHandled = false; - try (final Scope scope = SpanExtension.makeCurrentSpan(span)) { + WebView interceptorWebView = null; + try { + if (host == null) { + Logger.error(methodTag, "onCreateWindow: authorization host is unavailable.", null); + return false; + } + if (resultMsg == null || !(resultMsg.obj instanceof WebView.WebViewTransport)) { + Logger.error(methodTag, "onCreateWindow: missing or invalid WebView transport.", null); + return false; + } Logger.info(methodTag, "onCreateWindow: intercepting target=_blank navigation."); - final WebView interceptorWebView = new WebView(view.getContext()); + interceptorWebView = new WebView(view.getContext()); + mInterceptorWebViews.add(interceptorWebView); + interceptorWebView.setWebChromeClient(this); interceptorWebView.setWebViewClient(new WebViewClient() { + private boolean mNavigationHandled; + @Override public boolean shouldOverrideUrlLoading(WebView v, WebResourceRequest request) { - handleInterceptedUrlFromNewWindow(view, v, request, span, isUserGesture); + if (mNavigationHandled || !mInterceptorWebViews.contains(v)) { + return true; + } + mNavigationHandled = true; + boolean handlerStarted = false; + try { + final Span navigationSpan = OTelUtility.createSpanFromParent( + SpanName.WebViewTargetBlankNavigation.name(), parentSpanContext); + handlerStarted = true; + handleInterceptedUrlFromNewWindow(view, v, request, navigationSpan, isUserGesture); + } finally { + if (!handlerStarted) { + scheduleInterceptorWebViewCleanup(v); + } + } return true; } }); final WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(interceptorWebView); resultMsg.sendToTarget(); - // Span status and end are handled in handleInterceptedUrlFromNewWindow, - // which fires asynchronously when shouldOverrideUrlLoading is called. windowHandled = true; } catch (@NonNull final Exception e) { Logger.error(methodTag, "Error handling target=_blank navigation.", e); - span.recordException(e); - span.setStatus(StatusCode.ERROR); - span.end(); + } finally { + if (!windowHandled && interceptorWebView != null) { + destroyInterceptorWebView(interceptorWebView); + } } return windowHandled; } + + @Override + public void onCloseWindow(final WebView window) { + destroyInterceptorWebView(window); + } }); setupPasskeyWebListener(mWebView, webViewClient); } + private void scheduleInterceptorWebViewCleanup(@NonNull final WebView interceptorWebView) { + if (mInterceptorWebViews.contains(interceptorWebView) + && !interceptorWebView.post(() -> destroyInterceptorWebView(interceptorWebView))) { + Logger.warn(TAG, "Unable to post popup cleanup; destroying the interceptor immediately."); + destroyInterceptorWebView(interceptorWebView); + } + } + + private void destroyInterceptorWebView(@NonNull final WebView interceptorWebView) { + if (mInterceptorWebViews.remove(interceptorWebView)) { + interceptorWebView.destroy(); + } + } + + private void destroyInterceptorWebViews() { + for (final WebView interceptorWebView : new ArrayList<>(mInterceptorWebViews)) { + destroyInterceptorWebView(interceptorWebView); + } + } + /** * Handles the URL intercepted from a target=_blank navigation (onCreateWindow). - * Routes the URL based on whether the main WebView is currently on a TLR page: - * - TLR page: opens the URL in an external browser. - * - Non-TLR page: loads the URL inline in the main WebView. + * User-initiated OpenID VC targets are delegated to the authentication WebView so its + * WebViewClient can launch the wallet. User-initiated HTTPS URLs open in the external browser + * without navigating the authentication WebView away from its current page. HTTPS URLs from + * non-user-initiated popups are loaded inline; other schemes are refused. If browser dispatch + * throws, HTTPS URLs are loaded inline. Wallet failures remain authentication errors, without + * inline fallback. * * @param mainWebView The main authentication WebView. - * @param interceptorWebView The temporary interceptor WebView (will be destroyed after handling). + * @param interceptorWebView The temporary interceptor WebView. Cleanup is posted after handling; + * window close or fragment teardown also releases it if still outstanding. * @param request The intercepted URL request. * @param span The telemetry span to record which routing path is taken. * @param isUserGesture Whether the popup was initiated by a user gesture (e.g. a click). @@ -536,62 +588,106 @@ void handleInterceptedUrlFromNewWindow(@NonNull final WebView mainWebView, @NonNull final Span span, final boolean isUserGesture) { final String methodTag = TAG + ":handleInterceptedUrlFromNewWindow"; + mInterceptorWebViews.add(interceptorWebView); try { - final String targetUrl = request.getUrl().toString(); - final String currentPageUrl = mainWebView.getUrl(); - - if (targetUrl == null) { + span.setAttribute(AttributeName.target_blank_navigation_is_user_gesture.name(), isUserGesture); + final String correlationId = getCorrelationId(); + if (!StringUtil.isNullOrEmpty(correlationId)) { + span.setAttribute(AttributeName.correlation_id.name(), correlationId); + } + final Uri targetUri = request.getUrl(); + if (targetUri == null || StringUtil.isNullOrEmpty(targetUri.toString())) { span.setAttribute(AttributeName.target_blank_navigation_route.name(), AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NULL_URL); - Logger.warn(methodTag, "onCreateWindow: target URL is null, ignoring."); - } else if (!isUserGesture) { - // Not initiated by user gesture: load inline as a safe fallback instead of - // opening an external browser, to prevent programmatic/scripted popups. + span.setStatus(StatusCode.ERROR, "Missing popup destination"); + Logger.error(methodTag, "onCreateWindow: popup destination is missing.", null); + return; + } + final String targetUrl = targetUri.toString(); + final String destinationHost = targetUri.getHost(); + final boolean isHttpsDestination = + AuthenticationConstants.Broker.HTTPS_SCHEME.equalsIgnoreCase(targetUri.getScheme()) + && !StringUtil.isNullOrEmpty(destinationHost); + if (!StringUtil.isNullOrEmpty(destinationHost)) { + span.setAttribute( + AttributeName.target_blank_navigation_destination_host.name(), + destinationHost); + } + + if (!isUserGesture) { span.setAttribute(AttributeName.target_blank_navigation_route.name(), AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NO_USER_GESTURE); - Logger.warn(methodTag, "onCreateWindow: popup not initiated by user gesture, loading URL inline."); + if (!isHttpsDestination) { + span.setStatus(StatusCode.ERROR); + Logger.warn(methodTag, "onCreateWindow: refusing invalid HTTPS destination without user gesture."); + return; + } + Logger.warn(methodTag, "onCreateWindow: popup not initiated by user gesture, loading HTTPS URL inline."); mainWebView.loadUrl(targetUrl); - } else if (!targetUrl.toLowerCase().startsWith(AuthenticationConstants.Broker.REDIRECT_SSL_PREFIX)) { - // Non-SSL URL: refuse to open, matching AzureActiveDirectoryWebViewClient behavior. + span.setStatus(StatusCode.OK); + } else if (AuthenticationConstants.Broker.OPENID_VC_SCHEME.equalsIgnoreCase(targetUri.getScheme())) { + dispatchPopupToWallet(mainWebView, targetUrl, span); + } else if (!isHttpsDestination) { span.setAttribute(AttributeName.target_blank_navigation_route.name(), AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NON_SSL); - Logger.error(methodTag, "onCreateWindow: URL is not SSL protected, refusing to open.", null); - } else if (!isTlrUrl(currentPageUrl)) { - // Non-TLR page: load inline, same as WebView default behavior. - span.setAttribute(AttributeName.target_blank_navigation_route.name(), AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NON_TLR); - Logger.warn(methodTag, "onCreateWindow: non-TLR page, loading URL inline as fallback."); - mainWebView.loadUrl(targetUrl); + span.setStatus(StatusCode.ERROR); + Logger.error(methodTag, "onCreateWindow: URL is not a valid HTTPS destination, refusing to open.", null); } else { - // TLR page: delegate to system browser so user can view terms externally. - span.setAttribute(AttributeName.target_blank_navigation_route.name(), AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_TLR); - Logger.info(methodTag, "onCreateWindow: TLR page, delegating URL to system browser."); - final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(targetUrl)); - mainWebView.getContext().startActivity(browserIntent); + dispatchPopupToBrowser(mainWebView, targetUrl, span, methodTag); } - span.setStatus(StatusCode.OK); } catch (final Exception e) { span.recordException(e); span.setStatus(StatusCode.ERROR); Logger.error(methodTag, "Error handling target=_blank URL.", e); } finally { - span.end(); - // Destroy the interceptor WebView after it has served its purpose - interceptorWebView.post(interceptorWebView::destroy); + try { + span.end(); + } finally { + scheduleInterceptorWebViewCleanup(interceptorWebView); + } } } - /** - * Checks whether the given URL corresponds to a TLR (Terms, License, and Restrictions) - * start page. - * - * @param url The URL to check. - * @return {@code true} if the URL is a TLR start page, {@code false} otherwise. - */ - @VisibleForTesting - boolean isTlrUrl(@Nullable final String url) { - if (url == null) { - return false; + private void dispatchPopupToWallet(@NonNull final WebView mainWebView, + @NonNull final String targetUrl, + @NonNull final Span span) { + span.setAttribute( + AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_OPENID_VC); + if (mAADWebViewClient != null) { + mAADWebViewClient.processOpenIdVcRequest(mainWebView, targetUrl, span); + } else { + throw new IllegalStateException("Authentication WebView client is unavailable."); + } + } + + private void dispatchPopupToBrowser(@NonNull final WebView mainWebView, + @NonNull final String targetUrl, + @NonNull final Span span, + @NonNull final String methodTag) { + span.setAttribute( + AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_BROWSER); + Logger.info(methodTag, "onCreateWindow: delegating user-initiated HTTPS URL to system browser."); + final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(targetUrl)); + final Context context = mainWebView.getContext(); + try { + context.startActivity(browserIntent); + } catch (final Exception e) { + final String exceptionType = e.getClass().getSimpleName(); + SpanExtension.recordOutcome(span, "browser_launch", "failed", exceptionType); + span.setAttribute(AttributeName.target_blank_navigation_route.name(), AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_BROWSER_FALLBACK); + Logger.warn(methodTag, "onCreateWindow: browser dispatch failed (" + + exceptionType + "); requesting HTTPS inline fallback."); + try { + mainWebView.loadUrl(targetUrl); + } catch (final Exception fallbackException) { + SpanExtension.recordOutcome(span, "browser_fallback", "failed", + fallbackException.getClass().getSimpleName()); + throw fallbackException; + } + SpanExtension.recordOutcome(span, "browser_fallback", "inline_fallback_requested"); + span.setStatus(StatusCode.OK); + return; } - final String lowerUrl = url.toLowerCase(); - return lowerUrl.startsWith(AuthenticationConstants.Broker.REDIRECT_SSL_PREFIX) - && lowerUrl.contains(AuthenticationConstants.Broker.TLR_START_PATH); + span.setStatus(StatusCode.OK); } /** @@ -781,6 +877,7 @@ public void run() { // the smartcard manager needs to stop discovering Usb devices upon fragment destroy. @Override public void onDestroy() { + destroyInterceptorWebViews(); super.onDestroy(); final String methodTag = TAG + ":onDestroy"; // Cancel any in-flight switch-browser async work so its continuation does not resume @@ -814,6 +911,7 @@ public void onDestroy() { @Override public void onDestroyView() { + destroyInterceptorWebViews(); if (mPasskeyWebListenerHooked && mWebView != null) { PasskeyWebListener.unhook(mWebView); mPasskeyWebListenerHooked = false; diff --git a/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClient.java b/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClient.java index f120aa0988..0c36bec8a6 100644 --- a/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClient.java +++ b/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClient.java @@ -147,6 +147,7 @@ */ public class AzureActiveDirectoryWebViewClient extends OAuth2WebViewClient { private static final String TAG = AzureActiveDirectoryWebViewClient.class.getSimpleName(); + private static final String TELEMETRY_OUTCOME_FAILED = "failed"; /** * Package name of the Google Play Store, the legitimate launch target for a broker-install @@ -1031,11 +1032,11 @@ private boolean isAmazonAppRedirect(@NonNull final String url) { * This scheme is used by OpenID Verifiable Credentials flows and must be * intercepted so a registered wallet app can handle it. * - * @param url The lowercase URL to check. - * @return true if the URL starts with the openid-vc:// scheme. + * @param url The URL to check. + * @return true if the parsed scheme is openid-vc, ignoring case. */ private boolean isOpenIdVcUrl(@NonNull final String url) { - return url.startsWith(AuthenticationConstants.Broker.OPENID_VC_SCHEME_PREFIX); + return AuthenticationConstants.Broker.OPENID_VC_SCHEME.equalsIgnoreCase(Uri.parse(url).getScheme()); } private boolean isWebCpEnrollmentUrl(@NonNull final String url) { @@ -1484,63 +1485,105 @@ private void processAmazonAppUri(@NonNull final String url) { * @param view The WebView that intercepted the navigation. * @param url The original (non-lowercased) openid-vc:// URL. */ - private void processOpenIdVcRequest(@NonNull final WebView view, @NonNull final String url) { - final String methodTag = TAG + ":processOpenIdVcRequest"; - view.stopLoading(); + public boolean processOpenIdVcRequest(@NonNull final WebView view, @NonNull final String url) { final Span span = createSpanWithAttributesFromParent(SpanName.ProcessOpenIdVcRequest.name()); + try { + return processOpenIdVcRequest(view, url, span); + } finally { + span.end(); + } + } + + /** + * Handles an OpenID VC request using the caller-owned span. + * + * Dispatch exceptions are delivered through the authorization error callback. + * Fatal errors and telemetry failures propagate without invoking that callback. + * + * @param view the authentication WebView associated with the request. + * @param url the original OpenID VC URL. + * @param span the caller-owned span, which the caller must end. + * @return whether Android accepted wallet dispatch. + */ + public boolean processOpenIdVcRequest(@NonNull final WebView view, + @NonNull final String url, + @NonNull final Span span) { + final String methodTag = TAG + ":processOpenIdVcRequest"; + String errorCode; + String errorMessage; try (final Scope scope = SpanExtension.makeCurrentSpan(span)) { - final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + Boolean handlerFound = null; + boolean untrustedHandler = false; + Exception dispatchFailure = null; + try { + view.stopLoading(); + final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // Resolve after any pinning so the handler check matches the final intent we will launch. + final android.content.pm.PackageManager pm = getActivity().getPackageManager(); + + // Return-to-caller is wired ONLY for the brokered flow, i.e. when this WebView is + // hosted in the broker's auth-service process (Authenticator / Company Portal / Link to + // Windows). In the brokerless/embedded case we fall back to the pre-existing behavior + // (launch the openid-vc handler without a return PendingIntent) - identical to + // ENABLE_OPEN_ID_VC_RETURN_TO_CALLER being off - as the embedded return path is not + // validated. It is also gated by its own flight so it can be rolled back entirely. + if (CommonFlightsManager.INSTANCE.getFlightsProvider().isFlightEnabled(ENABLE_OPEN_ID_VC_RETURN_TO_CALLER) + && ProcessUtil.isRunningOnAuthService(getActivity().getApplicationContext())) { + // The Microsoft VID CA-block flow can only be completed by Microsoft Authenticator, + // so target it explicitly when it is an installed openid-vc:// handler. We do NOT + // rely on resolveActivity() here: when more than one app claims the scheme it returns + // the system chooser (package "android"), which would drop the return PendingIntent + // even if the user then picked Authenticator. Pinning to a verified Authenticator + // fixes that and avoids showing a wallet chooser for a request only it can fulfill. + if (isAuthenticatorOpenIdVcHandler(intent) + && isTrustedVcWalletPackage(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME)) { + intent.setPackage(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME); + attachReturnPendingIntent(intent, methodTag); + } else { + // Authenticator is not an installed/verified openid-vc handler: preserve the + // existing dispatch behavior but do NOT attach a return PendingIntent. + untrustedHandler = true; + } + } - // Resolve after any pinning so the handler check matches the final intent we will launch. - final android.content.pm.PackageManager pm = getActivity().getPackageManager(); - - // Return-to-caller is wired ONLY for the brokered flow, i.e. when this WebView is - // hosted in the broker's auth-service process (Authenticator / Company Portal / Link to - // Windows). In the brokerless/embedded case we fall back to the pre-existing behavior - // (launch the openid-vc handler without a return PendingIntent) - identical to - // ENABLE_OPEN_ID_VC_RETURN_TO_CALLER being off - as the embedded return path is not - // validated. It is also gated by its own flight so it can be rolled back entirely. - if (CommonFlightsManager.INSTANCE.getFlightsProvider().isFlightEnabled(ENABLE_OPEN_ID_VC_RETURN_TO_CALLER) - && ProcessUtil.isRunningOnAuthService(getActivity().getApplicationContext())) { - // The Microsoft VID CA-block flow can only be completed by Microsoft Authenticator, - // so target it explicitly when it is an installed openid-vc:// handler. We do NOT - // rely on resolveActivity() here: when more than one app claims the scheme it returns - // the system chooser (package "android"), which would drop the return PendingIntent - // even if the user then picked Authenticator. Pinning to a verified Authenticator - // fixes that and avoids showing a wallet chooser for a request only it can fulfill. - if (isAuthenticatorOpenIdVcHandler(intent) - && isTrustedVcWalletPackage(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME)) { - intent.setPackage(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME); - attachReturnPendingIntent(intent, methodTag); - } else { - // Authenticator is not an installed/verified openid-vc handler: preserve the - // existing dispatch behavior but do NOT attach a return PendingIntent. - Logger.warn(methodTag, "Microsoft Authenticator is not the verified openid-vc handler; launching without return PendingIntent."); + final ComponentName resolved = intent.resolveActivity(pm); + handlerFound = resolved != null; + if (resolved != null) { + getActivity().startActivity(intent); } + } catch (final Exception e) { + dispatchFailure = e; } - - final ComponentName resolved = intent.resolveActivity(pm); - if (resolved != null) { - getActivity().startActivity(intent); + if (untrustedHandler) { + Logger.warn(methodTag, "Microsoft Authenticator is not the verified openid-vc handler; launching without return PendingIntent."); + SpanExtension.recordOutcome(span, "return_to_caller", "untrusted_handler"); + } + if (handlerFound != null) { + span.setAttribute(AttributeName.is_openid_vc_handler_found.name(), handlerFound.booleanValue()); + } + if (dispatchFailure != null) { + Logger.error(methodTag, "Failed to launch handler for openid-vc:// URI.", null); + SpanExtension.recordOutcome(span, "vc_dispatch", TELEMETRY_OUTCOME_FAILED, + dispatchFailure.getClass().getSimpleName()); + span.setStatus(StatusCode.ERROR, "Failed to launch handler for openid-vc:// URI"); + errorCode = dispatchFailure instanceof ActivityNotFoundException ? ErrorStrings.ACTIVITY_NOT_FOUND : ErrorStrings.UNKNOWN_ERROR; + errorMessage = "Failed to dispatch the OpenID Verifiable Credentials request."; + } else if (Boolean.TRUE.equals(handlerFound)) { Logger.info(methodTag, "Launched external handler for OpenID VC request."); - span.setAttribute(AttributeName.is_openid_vc_handler_found.name(), true); span.setStatus(StatusCode.OK); + return true; } else { Logger.warn(methodTag, "No application found to handle openid-vc:// URI."); - span.setAttribute(AttributeName.is_openid_vc_handler_found.name(), false); span.setStatus(StatusCode.ERROR, "No handler found for openid-vc:// URI"); - returnError(ErrorStrings.ACTIVITY_NOT_FOUND, "No application found to handle the OpenID Verifiable Credentials request."); + errorCode = ErrorStrings.ACTIVITY_NOT_FOUND; + errorMessage = "No application found to handle the OpenID Verifiable Credentials request."; } - } catch (final ActivityNotFoundException e) { - Logger.error(methodTag, "Failed to launch handler for openid-vc:// URI.", e); - span.setAttribute(AttributeName.is_openid_vc_handler_found.name(), false); - span.recordException(e); - span.setStatus(StatusCode.ERROR, "Failed to launch handler for openid-vc:// URI"); - returnError(ErrorStrings.ACTIVITY_NOT_FOUND, "Failed to launch handler for the OpenID Verifiable Credentials request."); - } finally { - span.end(); } + // Callback failures must not be caught as dispatch failures and delivered a second time. + returnError(errorCode, errorMessage); + return false; } /** @@ -1585,8 +1628,10 @@ private void attachReturnPendingIntent(@NonNull final Intent intent, @NonNull fi com.microsoft.identity.common.internal.ui.OpenIdVcReturnActivity.RETURN_PENDING_INTENT_EXTRA, returnPendingIntent); Logger.info(methodTag, "Attached return PendingIntent to openid-vc intent."); + SpanExtension.recordOutcome(SpanExtension.current(), "return_to_caller", "attached"); } catch (final Exception e) { // Best-effort: if we cannot build the return PendingIntent, still launch the VID flow without it. + SpanExtension.recordOutcome(SpanExtension.current(), "return_to_caller", TELEMETRY_OUTCOME_FAILED, e.getClass().getSimpleName()); Logger.warn(methodTag, "Could not attach return PendingIntent: " + e.getMessage()); } } @@ -1603,8 +1648,11 @@ private boolean isTrustedVcWalletPackage(@NonNull final String packageName) { return false; } try { - return new BrokerValidator(getActivity().getApplicationContext()).isValidBrokerPackage(packageName); + final boolean trusted = new BrokerValidator(getActivity().getApplicationContext()).isValidBrokerPackage(packageName); + SpanExtension.recordOutcome(SpanExtension.current(), "wallet_verification", trusted ? "verified" : "rejected"); + return trusted; } catch (final Exception e) { + SpanExtension.recordOutcome(SpanExtension.current(), "wallet_verification", TELEMETRY_OUTCOME_FAILED, e.getClass().getSimpleName()); Logger.warn(TAG + ":isTrustedVcWalletPackage", "Wallet verification failed: " + e.getMessage()); return false; } @@ -1622,12 +1670,16 @@ private boolean isAuthenticatorOpenIdVcHandler(@NonNull final Intent intent) { try { for (final ResolveInfo info : getActivity().getPackageManager().queryIntentActivities(intent, 0)) { if (info.activityInfo != null && authenticatorPackage.equals(info.activityInfo.packageName)) { + SpanExtension.recordOutcome(SpanExtension.current(), "authenticator_lookup", "found"); return true; } } } catch (final Exception e) { + SpanExtension.recordOutcome(SpanExtension.current(), "authenticator_lookup", TELEMETRY_OUTCOME_FAILED, e.getClass().getSimpleName()); Logger.warn(TAG + ":isAuthenticatorOpenIdVcHandler", "Handler lookup failed: " + e.getMessage()); + return false; } + SpanExtension.recordOutcome(SpanExtension.current(), "authenticator_lookup", "not_found"); return false; } diff --git a/common/src/test/java/com/microsoft/identity/common/internal/providers/oauth2/WebViewAuthorizationFragmentMultiWindowTest.java b/common/src/test/java/com/microsoft/identity/common/internal/providers/oauth2/WebViewAuthorizationFragmentMultiWindowTest.java index 94e143521d..eb648d67ab 100644 --- a/common/src/test/java/com/microsoft/identity/common/internal/providers/oauth2/WebViewAuthorizationFragmentMultiWindowTest.java +++ b/common/src/test/java/com/microsoft/identity/common/internal/providers/oauth2/WebViewAuthorizationFragmentMultiWindowTest.java @@ -22,39 +22,80 @@ // THE SOFTWARE. package com.microsoft.identity.common.internal.providers.oauth2; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; +import android.content.ActivityNotFoundException; +import android.content.Intent; import android.net.Uri; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.view.View; +import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; +import android.webkit.WebSettings; import android.webkit.WebView; +import androidx.fragment.app.FragmentActivity; import androidx.test.core.app.ApplicationProvider; +import com.microsoft.identity.common.R; import com.microsoft.identity.common.adal.internal.AuthenticationConstants; +import com.microsoft.identity.common.internal.mocks.MockCommonFlightsManager; +import com.microsoft.identity.common.internal.ui.webview.AzureActiveDirectoryWebViewClient; +import com.microsoft.identity.common.java.flighting.CommonFlight; +import com.microsoft.identity.common.java.flighting.CommonFlightsManager; +import com.microsoft.identity.common.java.flighting.IFlightsProvider; +import com.microsoft.identity.common.java.logging.DiagnosticContext; +import com.microsoft.identity.common.java.logging.IRequestContext; +import com.microsoft.identity.common.java.logging.RequestContext; import com.microsoft.identity.common.java.opentelemetry.AttributeName; +import com.microsoft.identity.common.java.opentelemetry.OTelUtility; +import com.microsoft.identity.common.java.opentelemetry.SpanName; +import com.microsoft.identity.common.logging.Logger; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.mockito.MockedConstruction; +import org.mockito.InOrder; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; +import org.robolectric.Shadows; +import org.robolectric.util.ReflectionHelpers; + +import java.util.Locale; +import java.util.HashMap; import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.api.common.Attributes; /** - * Tests for the multi-window (target=_blank) URL handling logic and - * TLR URL detection in {@link WebViewAuthorizationFragment}. + * Tests for the multi-window (target=_blank) URL handling logic in + * {@link WebViewAuthorizationFragment}. */ @RunWith(RobolectricTestRunner.class) public class WebViewAuthorizationFragmentMultiWindowTest { @@ -62,19 +103,14 @@ public class WebViewAuthorizationFragmentMultiWindowTest { private WebViewAuthorizationFragment mFragment; private Context mContext; - // TLR URLs - private static final String TLR_URL = "https://login.microsoftonline.com/tlr/start?param=1"; - private static final String TLR_URL_UPPER_CASE = "HTTPS://LOGIN.MICROSOFTONLINE.COM/TLR/START?PARAM=1"; - private static final String TLR_URL_MIXED_CASE = "https://Login.Microsoftonline.com/Tlr/Start?param=1"; - - // Non-TLR URLs - private static final String NON_TLR_HTTPS_URL = "https://login.microsoftonline.com/common/oauth2/authorize"; private static final String HTTP_URL = "http://example.com/tlr/start"; private static final String FTP_URL = "ftp://files.example.com/document.pdf"; // Target URLs for handleInterceptedUrlFromNewWindow private static final String HTTPS_TARGET_URL = "https://terms.example.com/privacy"; private static final String HTTP_TARGET_URL = "http://terms.example.com/privacy"; + private static final String OPENID_VC_TARGET_URL = "openid-vc://authorize?request_uri=https%3A%2F%2Fexample.com"; + private static final String HOSTLESS_TARGET_URL = "custom-scheme:path"; @Before public void setUp() throws Exception { @@ -82,69 +118,360 @@ public void setUp() throws Exception { mFragment = new WebViewAuthorizationFragment(); } - // ----------------------------------------------------------------------- - // isTlrUrl tests - // ----------------------------------------------------------------------- + @After + public void tearDown() { + CommonFlightsManager.INSTANCE.resetFlightsManager(); + } + + private WebResourceRequest mockRequest(final String url) { + final WebResourceRequest request = mock(WebResourceRequest.class); + when(request.getUrl()).thenReturn(Uri.parse(url)); + return request; + } + + private Span mockSpan() { + return mock(Span.class); + } + + private WebChromeClient setUpWindowClient(final WebView mainWebView) { + setOpenIdVcRedirectFlightEnabled(false); + when(mainWebView.getSettings()).thenReturn(mock(WebSettings.class)); + when(mainWebView.getContext()).thenReturn(mContext); + final View rootView = mock(View.class); + when(rootView.findViewById(R.id.common_auth_webview)).thenReturn(mainWebView); + ReflectionHelpers.setField(mFragment, "mRequestHeaders", new HashMap()); + ReflectionHelpers.callInstanceMethod(mFragment, "setUpWebView", + ReflectionHelpers.ClassParameter.from(View.class, rootView), + ReflectionHelpers.ClassParameter.from(AzureActiveDirectoryWebViewClient.class, + mock(AzureActiveDirectoryWebViewClient.class))); + final ArgumentCaptor client = ArgumentCaptor.forClass(WebChromeClient.class); + verify(mainWebView).setWebChromeClient(client.capture()); + return client.getValue(); + } @Test - public void testIsTlrUrl_nullUrl_returnsFalse() { - assertFalse(mFragment.isTlrUrl(null)); + public void testOnCreateWindow_setupFailureAfterAllocation_destroysInterceptor() { + mFragment = spy(mFragment); + when(mFragment.getActivity()).thenReturn(mock(FragmentActivity.class)); + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + final Message message = Message.obtain(); + message.obj = mainWebView.new WebViewTransport(); + + try (final MockedConstruction windows = mockConstruction(WebView.class)) { + assertFalse(client.onCreateWindow(mainWebView, false, true, message)); + final WebView interceptor = windows.constructed().get(0); + verify(interceptor).destroy(); + client.onCloseWindow(interceptor); + mFragment.onDestroyView(); + verify(interceptor, times(1)).destroy(); + } } @Test - public void testIsTlrUrl_emptyString_returnsFalse() { - assertFalse(mFragment.isTlrUrl("")); + public void testOnCloseWindow_withoutNavigation_destroysOnlyTrackedInterceptor() { + mFragment = spy(mFragment); + when(mFragment.getActivity()).thenReturn(mock(FragmentActivity.class)); + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + final Message message = Message.obtain(new Handler(Looper.getMainLooper()), 0, + mainWebView.new WebViewTransport()); + + try (final MockedConstruction windows = mockConstruction(WebView.class)) { + assertTrue(client.onCreateWindow(mainWebView, false, true, message)); + final WebView interceptor = windows.constructed().get(0); + verify(interceptor).setWebChromeClient(client); + client.onCloseWindow(mainWebView); + verify(mainWebView, never()).destroy(); + client.onCloseWindow(interceptor); + client.onCloseWindow(interceptor); + mFragment.onDestroyView(); + verify(interceptor, times(1)).destroy(); + } } @Test - public void testIsTlrUrl_validTlrUrl_returnsTrue() { - assertTrue(mFragment.isTlrUrl(TLR_URL)); + public void testOnDestroyView_withoutNavigation_destroysAllOutstandingInterceptors() { + mFragment = spy(mFragment); + when(mFragment.getActivity()).thenReturn(mock(FragmentActivity.class)); + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + + try (final MockedConstruction windows = mockConstruction(WebView.class)) { + for (int i = 0; i < 2; i++) { + final Message message = Message.obtain(new Handler(Looper.getMainLooper()), 0, + mainWebView.new WebViewTransport()); + assertTrue(client.onCreateWindow(mainWebView, false, true, message)); + } + mFragment.onDestroyView(); + mFragment.onDestroyView(); + for (final WebView interceptor : windows.constructed()) { + verify(interceptor, times(1)).destroy(); + } + verify(mainWebView, never()).destroy(); + } } @Test - public void testIsTlrUrl_upperCaseTlrUrl_returnsTrue() { - assertTrue(mFragment.isTlrUrl(TLR_URL_UPPER_CASE)); + public void testNavigationCleanup_pendingAtTeardown_destroysOnce() { + final WebView mainWebView = mock(WebView.class); + final WebView interceptor = mock(WebView.class); + when(interceptor.post(ArgumentMatchers.any(Runnable.class))).thenReturn(true); + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptor, mockRequest(HTTPS_TARGET_URL), mockSpan(), false); + final ArgumentCaptor cleanup = ArgumentCaptor.forClass(Runnable.class); + verify(interceptor).post(cleanup.capture()); + verify(interceptor, never()).destroy(); + + mFragment.onDestroyView(); + cleanup.getValue().run(); + verify(interceptor, times(1)).destroy(); } @Test - public void testIsTlrUrl_mixedCaseTlrUrl_returnsTrue() { - assertTrue(mFragment.isTlrUrl(TLR_URL_MIXED_CASE)); + public void testNavigationCleanup_postRejected_destroysImmediately() { + final WebView mainWebView = mock(WebView.class); + final WebView interceptor = mock(WebView.class); + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptor, mockRequest(HTTPS_TARGET_URL), mockSpan(), false); + + verify(interceptor).destroy(); + mFragment.onDestroyView(); + verify(interceptor, times(1)).destroy(); } @Test - public void testIsTlrUrl_httpsNonTlrPath_returnsFalse() { - assertFalse(mFragment.isTlrUrl(NON_TLR_HTTPS_URL)); + public void testOnDestroy_pendingCleanup_destroysInterceptorWithoutDestroyView() { + final WebView mainWebView = mock(WebView.class); + final WebView interceptor = mock(WebView.class); + when(interceptor.post(ArgumentMatchers.any(Runnable.class))).thenReturn(true); + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptor, mockRequest(HTTPS_TARGET_URL), mockSpan(), false); + final ArgumentCaptor cleanup = ArgumentCaptor.forClass(Runnable.class); + verify(interceptor).post(cleanup.capture()); + + mFragment.onDestroy(); + cleanup.getValue().run(); + verify(interceptor, times(1)).destroy(); } @Test - public void testIsTlrUrl_httpWithTlrPath_returnsFalse() { - // Must be HTTPS to be considered a TLR URL - assertFalse(mFragment.isTlrUrl(HTTP_URL)); + public void testNavigationCleanup_spanCreationThrows_stillDestroysInterceptor() { + mFragment = spy(mFragment); + when(mFragment.getActivity()).thenReturn(mock(FragmentActivity.class)); + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + final Message message = Message.obtain(new Handler(Looper.getMainLooper()), 0, + mainWebView.new WebViewTransport()); + + try (final MockedConstruction windows = mockConstruction(WebView.class); + final MockedStatic telemetry = mockStatic(OTelUtility.class)) { + assertTrue(client.onCreateWindow(mainWebView, false, true, message)); + final WebView interceptor = windows.constructed().get(0); + final ArgumentCaptor callback = + ArgumentCaptor.forClass(android.webkit.WebViewClient.class); + verify(interceptor).setWebViewClient(callback.capture()); + telemetry.when(() -> OTelUtility.createSpanFromParent( + eq(SpanName.WebViewTargetBlankNavigation.name()), ArgumentMatchers.isNull())) + .thenThrow(new IllegalStateException("Span creation failed")); + + assertThrows(IllegalStateException.class, () -> ReflectionHelpers.callInstanceMethod( + callback.getValue(), "shouldOverrideUrlLoading", + ReflectionHelpers.ClassParameter.from(WebView.class, interceptor), + ReflectionHelpers.ClassParameter.from(WebResourceRequest.class, + mockRequest(HTTPS_TARGET_URL)))); + + verify(interceptor).destroy(); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + } } @Test - public void testIsTlrUrl_ftpScheme_returnsFalse() { - assertFalse(mFragment.isTlrUrl(FTP_URL)); + public void testNavigationCleanup_spanEndThrows_stillPostsCleanup() { + final WebView mainWebView = mock(WebView.class); + final WebView interceptor = mock(WebView.class); + final Span span = mockSpan(); + doThrow(new IllegalStateException("Telemetry failure")).when(span).end(); + + assertThrows(IllegalStateException.class, () -> mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptor, mockRequest(HTTPS_TARGET_URL), span, false)); + + verify(interceptor).post(ArgumentMatchers.any(Runnable.class)); + verify(interceptor).destroy(); } @Test - public void testIsTlrUrl_tlrPathOnly_returnsFalse() { - // No scheme prefix, just path - assertFalse(mFragment.isTlrUrl("/tlr/start")); + public void testOnCreateWindow_hostUnavailable_logsWithoutTelemetry() { + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + try (final MockedStatic telemetry = mockStatic(OTelUtility.class); + final MockedStatic logger = mockStatic(Logger.class)) { + assertFalse(client.onCreateWindow(mainWebView, false, true, null)); + logger.verify(() -> Logger.error(ArgumentMatchers.anyString(), + eq("onCreateWindow: authorization host is unavailable."), ArgumentMatchers.isNull())); + telemetry.verifyNoInteractions(); + } } - // ----------------------------------------------------------------------- - // handleInterceptedUrlFromNewWindow tests - // ----------------------------------------------------------------------- + @Test + public void testOnCreateWindow_invalidTransport_logsWithoutTelemetry() { + mFragment = spy(mFragment); + when(mFragment.getActivity()).thenReturn(mock(FragmentActivity.class)); + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + final Message invalidMessage = Message.obtain(); + invalidMessage.obj = new Object(); + try (final MockedStatic telemetry = mockStatic(OTelUtility.class); + final MockedStatic logger = mockStatic(Logger.class)) { + assertFalse(client.onCreateWindow(mainWebView, false, true, null)); + assertFalse(client.onCreateWindow(mainWebView, false, true, invalidMessage)); + logger.verify(() -> Logger.error(ArgumentMatchers.anyString(), + eq("onCreateWindow: missing or invalid WebView transport."), + ArgumentMatchers.isNull()), times(2)); + telemetry.verifyNoInteractions(); + } + } - private WebResourceRequest mockRequest(final String url) { - final WebResourceRequest request = mock(WebResourceRequest.class); - when(request.getUrl()).thenReturn(Uri.parse(url)); - return request; + @Test + public void testOnCreateWindow_creationThrows_logsFailureWithoutTelemetry() { + mFragment = spy(mFragment); + when(mFragment.getActivity()).thenReturn(mock(FragmentActivity.class)); + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + final IllegalStateException failure = new IllegalStateException("Window creation failed."); + when(mainWebView.getContext()).thenThrow(failure); + final Message message = Message.obtain(); + message.obj = mainWebView.new WebViewTransport(); + try (final MockedStatic telemetry = mockStatic(OTelUtility.class); + final MockedStatic logger = mockStatic(Logger.class)) { + assertFalse(client.onCreateWindow(mainWebView, false, true, message)); + logger.verify(() -> Logger.error(ArgumentMatchers.anyString(), + eq("Error handling target=_blank navigation."), + eq(failure))); + telemetry.verifyNoInteractions(); + } } - private Span mockSpan() { - return mock(Span.class); + @Test + public void testOnCreateWindow_createsAndEndsSpanOnlyOnNavigation() { + mFragment = spy(mFragment); + final String correlationId = "11111111-1111-4111-8111-111111111111"; + ReflectionHelpers.setField(mFragment, "mCorrelationId", correlationId); + final AuthorizationActivity host = mock(AuthorizationActivity.class); + final SpanContext parentSpanContext = SpanContext.getInvalid(); + when(host.getSpanContext()).thenReturn(parentSpanContext); + when(mFragment.getActivity()).thenReturn(host); + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + final WebView.WebViewTransport transport = mainWebView.new WebViewTransport(); + final Message message = Message.obtain(new Handler(Looper.getMainLooper()), 0, transport); + final Span span = mockSpan(); + final IRequestContext previousContext = DiagnosticContext.INSTANCE.getRequestContext(); + try (final MockedStatic telemetry = mockStatic(OTelUtility.class)) { + final RequestContext otherRequestContext = new RequestContext(); + otherRequestContext.put(DiagnosticContext.CORRELATION_ID, + "22222222-2222-4222-8222-222222222222"); + DiagnosticContext.INSTANCE.setRequestContext(otherRequestContext); + telemetry.when(() -> OTelUtility.createSpanFromParent( + SpanName.WebViewTargetBlankNavigation.name(), parentSpanContext)).thenReturn(span); + + assertTrue(client.onCreateWindow(mainWebView, false, false, message)); + telemetry.verifyNoInteractions(); + verify(span, never()).end(); + + final WebView interceptor = transport.getWebView(); + // The test SDK predates this overload on the framework's WebViewClient. + final boolean navigationHandled = ReflectionHelpers.callInstanceMethod( + Shadows.shadowOf(interceptor).getWebViewClient(), "shouldOverrideUrlLoading", + ReflectionHelpers.ClassParameter.from(WebView.class, interceptor), + ReflectionHelpers.ClassParameter.from(WebResourceRequest.class, + mockRequest(HTTPS_TARGET_URL))); + assertTrue(navigationHandled); + assertTrue(ReflectionHelpers.callInstanceMethod( + Shadows.shadowOf(interceptor).getWebViewClient(), "shouldOverrideUrlLoading", + ReflectionHelpers.ClassParameter.from(WebView.class, interceptor), + ReflectionHelpers.ClassParameter.from(WebResourceRequest.class, + mockRequest(HTTPS_TARGET_URL)))); + + telemetry.verify(() -> OTelUtility.createSpanFromParent( + SpanName.WebViewTargetBlankNavigation.name(), parentSpanContext)); + verify(mainWebView).loadUrl(HTTPS_TARGET_URL); + verify(span).setAttribute(AttributeName.correlation_id.name(), correlationId); + verify(span).setAttribute(AttributeName.target_blank_navigation_is_user_gesture.name(), false); + verify(span).setStatus(StatusCode.OK); + verify(span).end(); + Shadows.shadowOf(Looper.getMainLooper()).idle(); + } finally { + DiagnosticContext.INSTANCE.setRequestContext(previousContext); + } + } + + @Test + public void testOnCreateWindow_noGestureOpenIdVc_refusesWalletDispatch() { + mFragment = spy(mFragment); + final AuthorizationActivity host = mock(AuthorizationActivity.class); + final SpanContext parentSpanContext = SpanContext.getInvalid(); + when(host.getSpanContext()).thenReturn(parentSpanContext); + when(mFragment.getActivity()).thenReturn(host); + final WebView mainWebView = mock(WebView.class); + final WebChromeClient client = setUpWindowClient(mainWebView); + final AzureActiveDirectoryWebViewClient webViewClient = + mock(AzureActiveDirectoryWebViewClient.class); + ReflectionHelpers.setField(mFragment, "mAADWebViewClient", webViewClient); + final WebView.WebViewTransport transport = mainWebView.new WebViewTransport(); + final Message message = Message.obtain(new Handler(Looper.getMainLooper()), 0, transport); + final Span span = mockSpan(); + + try (final MockedStatic telemetry = mockStatic(OTelUtility.class)) { + telemetry.when(() -> OTelUtility.createSpanFromParent( + SpanName.WebViewTargetBlankNavigation.name(), parentSpanContext)).thenReturn(span); + + assertTrue(client.onCreateWindow(mainWebView, false, false, message)); + final WebView interceptor = transport.getWebView(); + final boolean navigationHandled = ReflectionHelpers.callInstanceMethod( + Shadows.shadowOf(interceptor).getWebViewClient(), "shouldOverrideUrlLoading", + ReflectionHelpers.ClassParameter.from(WebView.class, interceptor), + ReflectionHelpers.ClassParameter.from(WebResourceRequest.class, + mockRequest(OPENID_VC_TARGET_URL))); + + assertTrue(navigationHandled); + telemetry.verify(() -> OTelUtility.createSpanFromParent( + SpanName.WebViewTargetBlankNavigation.name(), parentSpanContext)); + verify(webViewClient, never()).processOpenIdVcRequest( + mainWebView, OPENID_VC_TARGET_URL, span); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setAttribute(AttributeName.target_blank_navigation_is_user_gesture.name(), false); + verify(span).setAttribute(AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NO_USER_GESTURE); + verify(span).setStatus(StatusCode.ERROR); + verify(span).end(); + } + } + + @Test + public void testHandleInterceptedUrl_missingCorrelationId_doesNotSetAttribute() { + for (final String correlationId : new String[]{null, ""}) { + ReflectionHelpers.setField(mFragment, "mCorrelationId", correlationId); + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = mock(WebView.class); + final Span span = mockSpan(); + + mFragment.handleInterceptedUrlFromNewWindow(mainWebView, interceptorWebView, + mockRequest(HTTPS_TARGET_URL), span, false); + + verify(span, never()).setAttribute(eq(AttributeName.correlation_id.name()), + ArgumentMatchers.any()); + verify(mainWebView).loadUrl(HTTPS_TARGET_URL); + verify(span).end(); + } + } + + private void setOpenIdVcRedirectFlightEnabled(final boolean enabled) { + final IFlightsProvider flightsProvider = mock(IFlightsProvider.class); + when(flightsProvider.isFlightEnabled(CommonFlight.ENABLE_OPEN_ID_VC_REDIRECT)).thenReturn(enabled); + final MockCommonFlightsManager flightsManager = new MockCommonFlightsManager(); + flightsManager.setMockCommonFlightsProvider(flightsProvider); + CommonFlightsManager.INSTANCE.initializeCommonFlightsManager(flightsManager); } @Test @@ -158,6 +485,9 @@ public void testHandleInterceptedUrl_nonUserGesture_loadsInline() { // Should load URL inline in the main WebView verify(mainWebView).loadUrl(eq(HTTPS_TARGET_URL)); + verify(span).setAttribute( + eq(AttributeName.target_blank_navigation_destination_host.name()), + eq("terms.example.com")); verify(span).setAttribute( eq(AttributeName.target_blank_navigation_route.name()), eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NO_USER_GESTURE)); @@ -165,6 +495,77 @@ public void testHandleInterceptedUrl_nonUserGesture_loadsInline() { verify(span).end(); } + @Test + public void testHandleInterceptedUrl_nonHttpsWithoutUserGesture_refusesToOpen() { + for (final String targetUrl : new String[]{OPENID_VC_TARGET_URL, FTP_URL, HTTP_TARGET_URL}) { + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = mock(WebView.class); + final Span span = mockSpan(); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(targetUrl), span, false); + + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setAttribute(AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NO_USER_GESTURE); + verify(span).setStatus(StatusCode.ERROR); + verify(span).end(); + } + } + + @Test + public void testHandleInterceptedUrl_hostlessHttps_refusesToOpenWithOrWithoutGesture() { + for (final String targetUrl : new String[]{ + "https://", "https:///path", "https://?query=value", + "https:path", "HTTPS://#fragment", "https://:443/path"}) { + for (final boolean isUserGesture : new boolean[]{false, true}) { + final Context context = mock(Context.class); + final WebView mainWebView = mock(WebView.class); + final Span span = mockSpan(); + when(mainWebView.getContext()).thenReturn(context); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, mock(WebView.class), mockRequest(targetUrl), span, isUserGesture); + + verify(context, never()).startActivity(ArgumentMatchers.any(Intent.class)); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setAttribute(AttributeName.target_blank_navigation_route.name(), + isUserGesture + ? AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NON_SSL + : AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NO_USER_GESTURE); + verify(span).setStatus(StatusCode.ERROR); + verify(span).end(); + } + } + } + + @Test + public void testHandleInterceptedUrl_mixedCaseHttps_preservesOriginalUrlWithOrWithoutGesture() { + final String targetUrl = "HtTpS://terms.example.com/CaseSensitive?Token=AbCd#Section"; + for (final boolean isUserGesture : new boolean[]{false, true}) { + final Context context = mock(Context.class); + final WebView mainWebView = mock(WebView.class); + final Span span = mockSpan(); + when(mainWebView.getContext()).thenReturn(context); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, mock(WebView.class), mockRequest(targetUrl), span, isUserGesture); + + if (isUserGesture) { + final ArgumentCaptor intent = ArgumentCaptor.forClass(Intent.class); + verify(context).startActivity(intent.capture()); + assertEquals(Intent.ACTION_VIEW, intent.getValue().getAction()); + assertEquals(targetUrl, intent.getValue().getDataString()); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + } else { + verify(mainWebView).loadUrl(targetUrl); + verify(context, never()).startActivity(ArgumentMatchers.any(Intent.class)); + } + verify(span).setStatus(StatusCode.OK); + verify(span).end(); + } + } + @Test public void testHandleInterceptedUrl_nonSslUrl_refusesToOpen() { final WebView mainWebView = spy(new WebView(mContext)); @@ -180,80 +581,196 @@ public void testHandleInterceptedUrl_nonSslUrl_refusesToOpen() { verify(span).setAttribute( eq(AttributeName.target_blank_navigation_route.name()), eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NON_SSL)); - verify(span).setStatus(StatusCode.OK); + verify(span, never()).addEvent(ArgumentMatchers.anyString(), ArgumentMatchers.any(Attributes.class)); + verify(span).setStatus(StatusCode.ERROR); verify(span).end(); } @Test - public void testHandleInterceptedUrl_nonTlrPage_loadsInline() { + public void testHandleInterceptedUrl_openIdVc_loadsInAuthenticationWebView() { + setOpenIdVcRedirectFlightEnabled(true); final WebView mainWebView = spy(new WebView(mContext)); final WebView interceptorWebView = spy(new WebView(mContext)); final Span span = mockSpan(); - final WebResourceRequest request = mockRequest(HTTPS_TARGET_URL); + final WebResourceRequest request = mockRequest(OPENID_VC_TARGET_URL); + final AzureActiveDirectoryWebViewClient webViewClient = + mock(AzureActiveDirectoryWebViewClient.class); + ReflectionHelpers.setField(mFragment, "mAADWebViewClient", webViewClient); + when(webViewClient.processOpenIdVcRequest(mainWebView, OPENID_VC_TARGET_URL, span)).thenReturn(true); - // mainWebView is on a non-TLR page - // Robolectric WebView.getUrl() returns null by default (no page loaded), which is non-TLR mFragment.handleInterceptedUrlFromNewWindow(mainWebView, interceptorWebView, request, span, true); - // Should load URL inline - verify(mainWebView).loadUrl(eq(HTTPS_TARGET_URL)); + verify(webViewClient).processOpenIdVcRequest(mainWebView, OPENID_VC_TARGET_URL, span); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setAttribute( + eq(AttributeName.target_blank_navigation_destination_host.name()), + eq("authorize")); verify(span).setAttribute( eq(AttributeName.target_blank_navigation_route.name()), - eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NON_TLR)); - verify(span).setStatus(StatusCode.OK); + eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_OPENID_VC)); + verify(span, never()).setStatus(ArgumentMatchers.any(StatusCode.class)); verify(span).end(); } @Test - public void testHandleInterceptedUrl_tlrPage_delegatesToBrowser() { + public void testHandleInterceptedUrl_openIdVcWithoutAuthority_launchesWallet() { + setOpenIdVcRedirectFlightEnabled(true); + for (final String targetUrl : new String[]{"openid-vc:authorize", "openid-vc:/authorize"}) { + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = mock(WebView.class); + final Span span = mockSpan(); + final AzureActiveDirectoryWebViewClient webViewClient = + mock(AzureActiveDirectoryWebViewClient.class); + ReflectionHelpers.setField(mFragment, "mAADWebViewClient", webViewClient); + when(webViewClient.processOpenIdVcRequest(mainWebView, targetUrl, span)).thenReturn(true); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(targetUrl), span, true); + + verify(webViewClient).processOpenIdVcRequest(mainWebView, targetUrl, span); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setAttribute( + AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_OPENID_VC); + verify(span).end(); + } + } + + @Test + public void testHandleInterceptedUrl_nonVcSchemes_doNotLaunchWallet() { + setOpenIdVcRedirectFlightEnabled(true); + for (final String targetUrl : new String[]{"openid-vc-extra://authorize", "authorize", "http://openid-vc"}) { + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = mock(WebView.class); + final Span span = mockSpan(); + final AzureActiveDirectoryWebViewClient webViewClient = + mock(AzureActiveDirectoryWebViewClient.class); + ReflectionHelpers.setField(mFragment, "mAADWebViewClient", webViewClient); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(targetUrl), span, true); + + verify(webViewClient, never()).processOpenIdVcRequest( + mainWebView, targetUrl, span); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setAttribute( + AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NON_SSL); + verify(span).end(); + } + } + + @Test + public void testHandleInterceptedUrl_uppercaseOpenIdVc_turkishLocale_launchesWallet() { + final Locale originalLocale = Locale.getDefault(); + try { + Locale.setDefault(new Locale("tr", "TR")); + setOpenIdVcRedirectFlightEnabled(true); + final String targetUrl = "OPENID-VC://authorize?request_uri=https%3A%2F%2Fexample.com%2FCaseSensitive"; + final WebView mainWebView = spy(new WebView(mContext)); + final WebView interceptorWebView = spy(new WebView(mContext)); + final Span span = mockSpan(); + final AzureActiveDirectoryWebViewClient webViewClient = + mock(AzureActiveDirectoryWebViewClient.class); + ReflectionHelpers.setField(mFragment, "mAADWebViewClient", webViewClient); + when(webViewClient.processOpenIdVcRequest(mainWebView, targetUrl, span)).thenReturn(true); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(targetUrl), span, true); + + verify(webViewClient).processOpenIdVcRequest(mainWebView, targetUrl, span); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setAttribute( + eq(AttributeName.target_blank_navigation_route.name()), + eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_OPENID_VC)); + verify(span, never()).setStatus(ArgumentMatchers.any(StatusCode.class)); + verify(span).end(); + } finally { + Locale.setDefault(originalLocale); + } + } + + @Test + public void testHandleInterceptedUrl_openIdVc_flightDisabled_launchesWallet() { + setOpenIdVcRedirectFlightEnabled(false); + final WebView mainWebView = spy(new WebView(mContext)); + final WebView interceptorWebView = spy(new WebView(mContext)); + final Span span = mockSpan(); + final WebResourceRequest request = mockRequest(OPENID_VC_TARGET_URL); + final AzureActiveDirectoryWebViewClient webViewClient = + mock(AzureActiveDirectoryWebViewClient.class); + ReflectionHelpers.setField(mFragment, "mAADWebViewClient", webViewClient); + + when(webViewClient.processOpenIdVcRequest(mainWebView, OPENID_VC_TARGET_URL, span)).thenReturn(true); + + mFragment.handleInterceptedUrlFromNewWindow(mainWebView, interceptorWebView, request, span, true); + + verify(webViewClient, never()).processOpenIdVcRequest( + ArgumentMatchers.any(WebView.class), ArgumentMatchers.anyString()); + verify(webViewClient).processOpenIdVcRequest(mainWebView, OPENID_VC_TARGET_URL, span); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setAttribute( + eq(AttributeName.target_blank_navigation_route.name()), + eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_OPENID_VC)); + verify(span, never()).addEvent(ArgumentMatchers.anyString(), ArgumentMatchers.any(Attributes.class)); + verify(span, never()).setStatus(ArgumentMatchers.any(StatusCode.class), ArgumentMatchers.anyString()); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_httpsUrl_delegatesToBrowserRegardlessOfCurrentPage() { final Activity activity = Robolectric.buildActivity(Activity.class).get(); final WebView mainWebView = mock(WebView.class); final WebView interceptorWebView = spy(new WebView(mContext)); final Span span = mockSpan(); final WebResourceRequest request = mockRequest(HTTPS_TARGET_URL); - // Simulate main WebView being on a TLR page - when(mainWebView.getUrl()).thenReturn(TLR_URL); when(mainWebView.getContext()).thenReturn(activity); mFragment.handleInterceptedUrlFromNewWindow(mainWebView, interceptorWebView, request, span, true); - // Should NOT load inline + final Intent launched = Shadows.shadowOf(activity).getNextStartedActivity(); + assertNotNull(launched); + assertEquals(Intent.ACTION_VIEW, launched.getAction()); + assertEquals(HTTPS_TARGET_URL, launched.getDataString()); + verify(mainWebView, never()).getUrl(); verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); verify(span).setAttribute( eq(AttributeName.target_blank_navigation_route.name()), - eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_TLR)); + eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_BROWSER)); verify(span).setStatus(StatusCode.OK); + verify(span, never()).addEvent(ArgumentMatchers.anyString(), ArgumentMatchers.any(Attributes.class)); verify(span).end(); } @Test - public void testHandleInterceptedUrl_spanEndsInFinally() { + public void testHandleInterceptedUrl_hostlessUrl_omitsDestinationHost() { final WebView mainWebView = spy(new WebView(mContext)); final WebView interceptorWebView = spy(new WebView(mContext)); final Span span = mockSpan(); - final WebResourceRequest request = mockRequest(HTTPS_TARGET_URL); + final WebResourceRequest request = mockRequest(HOSTLESS_TARGET_URL); - // Even for a normal non-TLR case, span.end() should always be called mFragment.handleInterceptedUrlFromNewWindow(mainWebView, interceptorWebView, request, span, true); + + verify(span, never()).setAttribute( + eq(AttributeName.target_blank_navigation_destination_host.name()), + ArgumentMatchers.anyString()); + verify(span).setAttribute( + eq(AttributeName.target_blank_navigation_route.name()), + eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NON_SSL)); + verify(span).setStatus(StatusCode.ERROR); verify(span).end(); } @Test - public void testHandleInterceptedUrl_nonUserGesture_nonSslUrl_loadsInline() { - // Non-user-gesture takes priority over non-SSL check + public void testHandleInterceptedUrl_spanEndsInFinally() { final WebView mainWebView = spy(new WebView(mContext)); final WebView interceptorWebView = spy(new WebView(mContext)); final Span span = mockSpan(); - final WebResourceRequest request = mockRequest(HTTP_TARGET_URL); - - mFragment.handleInterceptedUrlFromNewWindow(mainWebView, interceptorWebView, request, span, false); + final WebResourceRequest request = mockRequest(HTTPS_TARGET_URL); - // Even though URL is http, non-user-gesture check comes first and loads inline - verify(mainWebView).loadUrl(eq(HTTP_TARGET_URL)); - verify(span).setAttribute( - eq(AttributeName.target_blank_navigation_route.name()), - eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NO_USER_GESTURE)); + mFragment.handleInterceptedUrlFromNewWindow(mainWebView, interceptorWebView, request, span, true); + verify(span).end(); } @Test @@ -270,7 +787,296 @@ public void testHandleInterceptedUrl_ftpScheme_refusesToOpen() { verify(span).setAttribute( eq(AttributeName.target_blank_navigation_route.name()), eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NON_SSL)); + verify(span).setStatus(StatusCode.ERROR); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_noBrowser_fallsBackInline() { + verifyBrowserFallback(new ActivityNotFoundException("Sensitive URL must not enter telemetry.")); + } + + @Test + public void testHandleInterceptedUrl_browserSecurityException_fallsBackInline() { + verifyBrowserFallback(new SecurityException("Launch denied.")); + } + + @Test + public void testHandleInterceptedUrl_browserError_propagatesWithoutFallback() { + for (final Error error : new Error[]{new AssertionError(), new OutOfMemoryError()}) { + final Context context = mock(Context.class); + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = mock(WebView.class); + final Span span = mockSpan(); + when(mainWebView.getContext()).thenReturn(context); + doThrow(error).when(context).startActivity(ArgumentMatchers.any(Intent.class)); + + assertSame(error, assertThrows(Error.class, () -> + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(HTTPS_TARGET_URL), span, true))); + + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span, never()).addEvent(ArgumentMatchers.anyString(), ArgumentMatchers.any(Attributes.class)); + verify(span, never()).recordException(ArgumentMatchers.any(Throwable.class)); + verify(span, never()).setStatus(ArgumentMatchers.any(StatusCode.class)); + verify(span).end(); + verify(interceptorWebView).post(ArgumentMatchers.any(Runnable.class)); + } + } + + @Test + public void testHandleInterceptedUrl_browserSuccessTelemetryFails_doesNotFallback() { + final Context context = mock(Context.class); + final WebView mainWebView = mock(WebView.class); + final Span span = mockSpan(); + final IllegalStateException failure = new IllegalStateException("Telemetry failed"); + when(mainWebView.getContext()).thenReturn(context); + doThrow(failure).when(span).setStatus(StatusCode.OK); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, mock(WebView.class), mockRequest(HTTPS_TARGET_URL), span, true); + + verify(context).startActivity(ArgumentMatchers.any(Intent.class)); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span, never()).addEvent(ArgumentMatchers.anyString(), ArgumentMatchers.any(Attributes.class)); + verify(span, never()).setAttribute(AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_BROWSER_FALLBACK); + verify(span).recordException(failure); + verify(span).setStatus(StatusCode.ERROR); + verify(span).end(); + } + + private void verifyBrowserFallback(final Throwable exception) { + final Context context = mock(Context.class); + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = spy(new WebView(mContext)); + final Span span = mockSpan(); + when(mainWebView.getContext()).thenReturn(context); + doThrow(exception).when(context).startActivity(ArgumentMatchers.any(Intent.class)); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(HTTPS_TARGET_URL), span, true); + + verify(mainWebView).loadUrl(HTTPS_TARGET_URL); + final InOrder decisions = org.mockito.Mockito.inOrder(span); + decisions.verify(span).addEvent("browser_launch", failure(exception.getClass().getSimpleName())); + decisions.verify(span).addEvent("browser_fallback", outcome("inline_fallback_requested")); + verify(span).setAttribute(eq(AttributeName.target_blank_navigation_route.name()), + eq(AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_BROWSER_FALLBACK)); + verify(span, never()).setAttribute(eq(AttributeName.operation_outcome.name()), ArgumentMatchers.anyString()); + verify(span, never()).setStatus(eq(StatusCode.ERROR), ArgumentMatchers.anyString()); verify(span).setStatus(StatusCode.OK); + verify(span, never()).recordException(ArgumentMatchers.any(Throwable.class)); verify(span).end(); } + + @Test + public void testHandleInterceptedUrl_browserAndFallbackFail_recordsBothFailures() { + verifyBrowserAndFallbackFailure(new IllegalStateException()); + } + + @Test + public void testHandleInterceptedUrl_fallbackError_propagates() { + verifyInlineErrorPropagates(true); + } + + private void verifyBrowserAndFallbackFailure(final Throwable fallbackFailure) { + final Context context = mock(Context.class); + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = spy(new WebView(mContext)); + final Span span = mockSpan(); + when(mainWebView.getContext()).thenReturn(context); + doThrow(new ActivityNotFoundException()).when(context).startActivity(ArgumentMatchers.any(Intent.class)); + doThrow(fallbackFailure).when(mainWebView).loadUrl(HTTPS_TARGET_URL); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(HTTPS_TARGET_URL), span, true); + + final InOrder decisions = org.mockito.Mockito.inOrder(span); + decisions.verify(span).addEvent("browser_launch", failure("ActivityNotFoundException")); + decisions.verify(span).addEvent("browser_fallback", failure(fallbackFailure.getClass().getSimpleName())); + verify(span).recordException(fallbackFailure); + verify(span).setStatus(StatusCode.ERROR); + verify(span).setAttribute(AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_BROWSER_FALLBACK); + verify(span, never()).setStatus(StatusCode.OK); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_nonUserGesture_inlineFailure_recordsError() { + verifyInlineFailure(new IllegalStateException()); + } + + @Test + public void testHandleInterceptedUrl_nonUserGesture_inlineError_propagates() { + verifyInlineErrorPropagates(false); + } + + private void verifyInlineErrorPropagates(final boolean isUserGesture) { + final Context context = mock(Context.class); + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = mock(WebView.class); + final Span span = mockSpan(); + final OutOfMemoryError failure = new OutOfMemoryError(); + when(mainWebView.getContext()).thenReturn(context); + doThrow(new ActivityNotFoundException()).when(context).startActivity(ArgumentMatchers.any(Intent.class)); + doThrow(failure).when(mainWebView).loadUrl(HTTPS_TARGET_URL); + + assertSame(failure, assertThrows(OutOfMemoryError.class, () -> + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(HTTPS_TARGET_URL), span, isUserGesture))); + + verify(span, never()).addEvent(eq("browser_fallback"), ArgumentMatchers.any(Attributes.class)); + verify(span, never()).recordException(ArgumentMatchers.any(Throwable.class)); + verify(span, never()).setStatus(ArgumentMatchers.any(StatusCode.class)); + verify(span).end(); + verify(interceptorWebView).post(ArgumentMatchers.any(Runnable.class)); + } + + private void verifyInlineFailure(final Throwable failure) { + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = spy(new WebView(mContext)); + final Span span = mockSpan(); + doThrow(failure).when(mainWebView).loadUrl(HTTPS_TARGET_URL); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(HTTPS_TARGET_URL), span, false); + + verify(span, never()).addEvent(eq("browser_launch"), ArgumentMatchers.any(Attributes.class)); + verify(span, never()).addEvent(ArgumentMatchers.anyString(), ArgumentMatchers.any(Attributes.class)); + verify(span).recordException(failure); + verify(span).setStatus(StatusCode.ERROR); + verify(span).setAttribute(AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_NO_USER_GESTURE); + verify(span, never()).setStatus(StatusCode.OK); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_nullDestination_recordsError() { + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = spy(new WebView(mContext)); + final Span span = mockSpan(); + final WebResourceRequest request = mock(WebResourceRequest.class); + + mFragment.handleInterceptedUrlFromNewWindow(mainWebView, interceptorWebView, request, span, true); + + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span, never()).addEvent(ArgumentMatchers.anyString(), ArgumentMatchers.any(Attributes.class)); + verify(span).setStatus(StatusCode.ERROR, "Missing popup destination"); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_walletFailure_doesNotFallbackOrReportSuccess() { + setOpenIdVcRedirectFlightEnabled(true); + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = spy(new WebView(mContext)); + final Span span = mockSpan(); + final AzureActiveDirectoryWebViewClient webViewClient = mock(AzureActiveDirectoryWebViewClient.class); + ReflectionHelpers.setField(mFragment, "mAADWebViewClient", webViewClient); + when(webViewClient.processOpenIdVcRequest(mainWebView, OPENID_VC_TARGET_URL, span)).thenAnswer(invocation -> { + span.setStatus(StatusCode.ERROR, "No handler found for openid-vc:// URI"); + return false; + }); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(OPENID_VC_TARGET_URL), span, true); + + verify(span, never()).addEvent(eq("vc_dispatch"), ArgumentMatchers.any(Attributes.class)); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).setStatus(StatusCode.ERROR, "No handler found for openid-vc:// URI"); + verify(span, never()).setStatus(StatusCode.ERROR, "Wallet dispatch failed"); + verify(span, never()).setStatus(StatusCode.OK); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_missingWalletClient_recordsError() { + setOpenIdVcRedirectFlightEnabled(true); + final WebView mainWebView = mock(WebView.class); + final WebView interceptorWebView = spy(new WebView(mContext)); + final Span span = mockSpan(); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, interceptorWebView, mockRequest(OPENID_VC_TARGET_URL), span, true); + + verify(span).recordException(ArgumentMatchers.any(IllegalStateException.class)); + verify(span).setStatus(StatusCode.ERROR); + verify(span).setAttribute(AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_OPENID_VC); + verify(span, never()).addEvent(eq("vc_client_check"), ArgumentMatchers.any(Attributes.class)); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span, never()).setStatus(StatusCode.OK); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_emptyDestination_recordsError() { + final WebView mainWebView = mock(WebView.class); + final Span span = mockSpan(); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, mock(WebView.class), mockRequest(""), span, true); + + verify(span, never()).addEvent(ArgumentMatchers.anyString(), ArgumentMatchers.any(Attributes.class)); + verify(span).setStatus(StatusCode.ERROR, "Missing popup destination"); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_walletThrows_recordsFailureWithoutFallback() { + setOpenIdVcRedirectFlightEnabled(true); + final WebView mainWebView = mock(WebView.class); + final Span span = mockSpan(); + final AzureActiveDirectoryWebViewClient client = mock(AzureActiveDirectoryWebViewClient.class); + ReflectionHelpers.setField(mFragment, "mAADWebViewClient", client); + when(client.processOpenIdVcRequest(mainWebView, OPENID_VC_TARGET_URL, span)) + .thenThrow(new IllegalStateException()); + + mFragment.handleInterceptedUrlFromNewWindow( + mainWebView, mock(WebView.class), mockRequest(OPENID_VC_TARGET_URL), span, true); + + verify(span).recordException(ArgumentMatchers.any(IllegalStateException.class)); + verify(span).setStatus(StatusCode.ERROR); + verify(span).setAttribute(AttributeName.target_blank_navigation_route.name(), + AuthenticationConstants.Broker.WEBVIEW_TARGET_BLANK_ROUTE_OPENID_VC); + verify(span, never()).addEvent(eq("vc_dispatch"), ArgumentMatchers.any(Attributes.class)); + verify(mainWebView, never()).loadUrl(ArgumentMatchers.anyString()); + verify(span, never()).setStatus(StatusCode.OK); + verify(span).end(); + } + + @Test + public void testHandleInterceptedUrl_cleanupIsPostedToInterceptor() { + final WebView interceptor = mock(WebView.class); + final Span span = mockSpan(); + final ArgumentCaptor cleanup = ArgumentCaptor.forClass(Runnable.class); + when(interceptor.post(ArgumentMatchers.any(Runnable.class))).thenReturn(true); + + mFragment.handleInterceptedUrlFromNewWindow( + mock(WebView.class), interceptor, mockRequest(HTTPS_TARGET_URL), span, false); + + final InOrder order = org.mockito.Mockito.inOrder(span, interceptor); + order.verify(span).end(); + order.verify(interceptor).post(cleanup.capture()); + verify(interceptor, never()).destroy(); + cleanup.getValue().run(); + verify(interceptor).destroy(); + verify(span).setStatus(StatusCode.OK); + verify(span, never()).setStatus(eq(StatusCode.ERROR), ArgumentMatchers.anyString()); + } + + private static Attributes outcome(final String value) { + return Attributes.builder().put(AttributeName.operation_outcome.name(), value).build(); + } + + private static Attributes failure(final String exceptionType) { + return Attributes.builder() + .put(AttributeName.operation_outcome.name(), "failed") + .put(AttributeName.error_type.name(), exceptionType) + .build(); + } } diff --git a/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java b/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java index 35c607e4be..2406938df3 100644 --- a/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java +++ b/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java @@ -37,6 +37,8 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -110,6 +112,9 @@ import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.concurrent.TimeUnit; import io.opentelemetry.api.common.AttributeKey; @@ -338,7 +343,6 @@ public void cleanUp(){ .save(""); } } - @Test(expected = IllegalArgumentException.class) public void testUrlOverrideHandlesEmptyString() { assertTrue(mWebViewClient.shouldOverrideUrlLoading(mMockWebView, "")); @@ -372,6 +376,8 @@ public void testOpenIdVcUrl_TrustedAuthenticator_AttachesReturnPendingIntent() { // Arrange: the return-to-caller flight is on, and Microsoft Authenticator is the resolved handler... enableOpenIdVcReturnToCallerFlight(); registerOpenIdVcHandler(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); // ...and it passes BrokerValidator signature-pinning. try (final MockedConstruction ignored = mockConstruction( @@ -388,6 +394,11 @@ public void testOpenIdVcUrl_TrustedAuthenticator_AttachesReturnPendingIntent() { AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME, started.getPackage()); assertTrue("Trusted wallet must receive the return-to-caller PendingIntent", started.hasExtra(OpenIdVcReturnActivity.RETURN_PENDING_INTENT_EXTRA)); + assertEquals(Arrays.asList("authenticator_lookup", "wallet_verification", "return_to_caller"), + telemetry.captured().mEventNames); + assertEquals("found", telemetry.captured().eventAttribute("authenticator_lookup", AttributeName.operation_outcome)); + assertEquals("verified", telemetry.captured().eventAttribute("wallet_verification", AttributeName.operation_outcome)); + assertEquals("attached", telemetry.captured().eventAttribute("return_to_caller", AttributeName.operation_outcome)); } @Test @@ -396,6 +407,8 @@ public void testOpenIdVcUrl_UntrustedHandler_DoesNotAttachReturnPendingIntent() // Arrange: the return-to-caller flight is on, but a non-Authenticator app claims the scheme. enableOpenIdVcReturnToCallerFlight(); registerOpenIdVcHandler("com.example.malicious"); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); // Act: the untrusted package fails the Authenticator check before BrokerValidator is even consulted. final boolean result = mWebViewClient.shouldOverrideUrlLoading(mMockWebView, TEST_OPENID_VC_URL); @@ -406,6 +419,10 @@ public void testOpenIdVcUrl_UntrustedHandler_DoesNotAttachReturnPendingIntent() assertNotNull("Expected the openid-vc handler to be started", started); assertFalse("Untrusted handler must NOT receive the return-to-caller PendingIntent", started.hasExtra(OpenIdVcReturnActivity.RETURN_PENDING_INTENT_EXTRA)); + assertEquals("not_found", telemetry.captured().eventAttribute("authenticator_lookup", AttributeName.operation_outcome)); + assertEquals("untrusted_handler", telemetry.captured().eventAttribute("return_to_caller", AttributeName.operation_outcome)); + assertEquals(StatusCode.OK, telemetry.captured().mStatusCode); + assertNull(telemetry.captured().attribute(AttributeName.operation_outcome.name())); } @Test @@ -417,6 +434,8 @@ public void testOpenIdVcUrl_AuthenticatorFailsSignatureVerification_DoesNotPinOr // gate (not just the package-name check) must prevent both package-pinning and attaching. enableOpenIdVcReturnToCallerFlight(); registerOpenIdVcHandler(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); try (final MockedConstruction ignored = mockConstruction( BrokerValidator.class, @@ -433,6 +452,35 @@ public void testOpenIdVcUrl_AuthenticatorFailsSignatureVerification_DoesNotPinOr AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME, started.getPackage()); assertFalse("Signature-failing Authenticator must NOT receive the return-to-caller PendingIntent", started.hasExtra(OpenIdVcReturnActivity.RETURN_PENDING_INTENT_EXTRA)); + assertEquals("rejected", telemetry.captured().eventAttribute("wallet_verification", AttributeName.operation_outcome)); + assertEquals(StatusCode.OK, telemetry.captured().mStatusCode); + assertNull(telemetry.captured().attribute(AttributeName.operation_outcome.name())); + } + + @Test + @Config(shadows = {ShadowProcessUtil.class}) + public void testOpenIdVcUrl_verificationThrows_retainsFailureAfterLaunchAccepted() { + enableOpenIdVcReturnToCallerFlight(); + registerOpenIdVcHandler(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); + + try (final MockedConstruction ignored = mockConstruction( + BrokerValidator.class, + (mock, ctx) -> when(mock.isValidBrokerPackage(anyString())) + .thenThrow(new SecurityException("sensitive-query")))) { + assertTrue(mWebViewClient.processOpenIdVcRequest(mMockWebView, TEST_OPENID_VC_URL)); + } + + assertEquals("failed", telemetry.captured().eventAttribute("wallet_verification", AttributeName.operation_outcome)); + assertEquals("SecurityException", telemetry.captured().eventAttribute("wallet_verification", AttributeName.error_type)); + assertEquals("untrusted_handler", telemetry.captured().eventAttribute("return_to_caller", AttributeName.operation_outcome)); + assertEquals(StatusCode.OK, telemetry.captured().mStatusCode); + assertNull(telemetry.captured().attribute(AttributeName.operation_outcome.name())); + assertFalse(telemetry.captured().mEvents.toString().contains("sensitive-query")); + final Intent started = Shadows.shadowOf(mActivity).getNextStartedActivity(); + assertNotNull(started); + assertFalse(started.hasExtra(OpenIdVcReturnActivity.RETURN_PENDING_INTENT_EXTRA)); } @Test @@ -564,6 +612,191 @@ public void testOpenIdVcUrl_StopsWebViewAndReturnsError_WhenNoHandlerFound() { capturedResult.getException().getMessage().contains("No application found")); } + @Test + public void testOpenIdVcDispatch_returnsTrueOnlyWhenLaunchAccepted() { + registerOpenIdVcHandler("com.example.wallet"); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); + + assertTrue(mWebViewClient.processOpenIdVcRequest(mMockWebView, TEST_OPENID_VC_URL)); + + assertEquals(1, telemetry.captured().mEndCount); + assertEquals(StatusCode.OK, telemetry.captured().mStatusCode); + assertNull(telemetry.captured().attribute(AttributeName.operation_outcome.name())); + assertTrue(telemetry.captured().mEventNames.isEmpty()); + assertEquals(true, telemetry.captured().attribute(AttributeName.is_openid_vc_handler_found.name())); + } + + @Test + public void testOpenIdVcDispatch_existingSpan_reusesWithoutCreatingOrEndingSpan() { + registerOpenIdVcHandler("com.example.wallet"); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); + final RecordingSpan span = new RecordingSpan(); + final Span previousSpan = SpanExtension.current(); + + assertTrue(mWebViewClient.processOpenIdVcRequest(mMockWebView, TEST_OPENID_VC_URL, span)); + + assertNull(telemetry.captured()); + assertEquals(0, span.mEndCount); + assertEquals(StatusCode.OK, span.mStatusCode); + assertEquals(true, span.attribute(AttributeName.is_openid_vc_handler_found.name())); + assertTrue(span.mEventNames.isEmpty()); + assertEquals(previousSpan, SpanExtension.current()); + } + + @Test + public void testOpenIdVcDispatch_existingSpan_noHandler_preservesErrorAndCallerOwnership() { + final WebView webView = Mockito.mock(WebView.class); + final IAuthorizationCompletionCallback callback = Mockito.mock(IAuthorizationCompletionCallback.class); + final AzureActiveDirectoryWebViewClient client = new AzureActiveDirectoryWebViewClient( + mActivity, callback, url -> {}, TEST_REDIRECT_URI, + Mockito.mock(SwitchBrowserProtocolCoordinator.class), "homeTenantId", false); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); + final RecordingSpan span = new RecordingSpan(); + + assertFalse(client.processOpenIdVcRequest(webView, TEST_OPENID_VC_URL, span)); + + assertNull(telemetry.captured()); + assertEquals(0, span.mEndCount); + assertEquals(StatusCode.ERROR, span.mStatusCode); + assertEquals("No handler found for openid-vc:// URI", span.mStatusDescription); + assertEquals(false, span.attribute(AttributeName.is_openid_vc_handler_found.name())); + Mockito.verify(callback).onChallengeResponseReceived(any(RawAuthorizationResult.class)); + Mockito.verify(webView, Mockito.never()).loadUrl(anyString()); + } + + @Test + public void testOpenIdVcDispatch_noHandler_returnsFalseWithExplicitError() { + final IAuthorizationCompletionCallback callback = Mockito.mock(IAuthorizationCompletionCallback.class); + final AzureActiveDirectoryWebViewClient client = new AzureActiveDirectoryWebViewClient( + mActivity, callback, url -> {}, TEST_REDIRECT_URI, + Mockito.mock(SwitchBrowserProtocolCoordinator.class), "homeTenantId", false); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); + + assertFalse(client.processOpenIdVcRequest(mMockWebView, TEST_OPENID_VC_URL)); + + final ArgumentCaptor result = ArgumentCaptor.forClass(RawAuthorizationResult.class); + Mockito.verify(callback).onChallengeResponseReceived(result.capture()); + assertEquals(ErrorStrings.ACTIVITY_NOT_FOUND, ((ClientException) result.getValue().getException()).getErrorCode()); + assertEquals(StatusCode.ERROR, telemetry.captured().mStatusCode); + assertEquals(1, telemetry.captured().mEndCount); + assertNull(telemetry.captured().attribute(AttributeName.operation_outcome.name())); + assertEquals("No handler found for openid-vc:// URI", telemetry.captured().mStatusDescription); + assertFalse(telemetry.captured().mEventNames.contains("resolve_handler")); + assertEquals(false, telemetry.captured().attribute(AttributeName.is_openid_vc_handler_found.name())); + } + + @Test + public void testOpenIdVcDispatch_securityException_returnsFalseWithExplicitError() { + verifyWalletDispatchFailure(new SecurityException("sensitive-query"), ErrorStrings.UNKNOWN_ERROR); + } + + @Test + public void testOpenIdVcDispatch_activityDisappears_returnsFalseWithExplicitError() { + verifyWalletDispatchFailure(new ActivityNotFoundException("sensitive-query"), ErrorStrings.ACTIVITY_NOT_FOUND); + } + + @Test + public void testOpenIdVcDispatch_error_propagatesWithoutErrorCallback() { + registerOpenIdVcHandler("com.example.wallet"); + final Activity activity = Mockito.spy(mActivity); + final OutOfMemoryError failure = new OutOfMemoryError(); + Mockito.doThrow(failure).when(activity).startActivity(any(Intent.class)); + final IAuthorizationCompletionCallback callback = Mockito.mock(IAuthorizationCompletionCallback.class); + final AzureActiveDirectoryWebViewClient client = new AzureActiveDirectoryWebViewClient( + activity, callback, url -> {}, TEST_REDIRECT_URI, + Mockito.mock(SwitchBrowserProtocolCoordinator.class), "homeTenantId", false); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); + final Span previousSpan = SpanExtension.current(); + + assertSame(failure, assertThrows(OutOfMemoryError.class, () -> + client.processOpenIdVcRequest(mMockWebView, TEST_OPENID_VC_URL))); + + Mockito.verify(callback, never()).onChallengeResponseReceived(any(RawAuthorizationResult.class)); + assertNull(telemetry.captured().mRecordedException); + assertEquals(1, telemetry.captured().mEndCount); + assertEquals(previousSpan, SpanExtension.current()); + } + + @Test + public void testOpenIdVcDispatch_successTelemetryFails_doesNotDeliverErrorCallback() { + registerOpenIdVcHandler("com.example.wallet"); + final Activity activity = Mockito.spy(mActivity); + final IAuthorizationCompletionCallback callback = Mockito.mock(IAuthorizationCompletionCallback.class); + final AzureActiveDirectoryWebViewClient client = new AzureActiveDirectoryWebViewClient( + activity, callback, url -> {}, TEST_REDIRECT_URI, + Mockito.mock(SwitchBrowserProtocolCoordinator.class), "homeTenantId", false); + final RecordingSpan span = Mockito.spy(new RecordingSpan()); + final IllegalStateException failure = new IllegalStateException("Telemetry failed"); + Mockito.doThrow(failure).when(span).setStatus(StatusCode.OK); + final Span previousSpan = SpanExtension.current(); + + assertSame(failure, assertThrows(IllegalStateException.class, () -> + client.processOpenIdVcRequest(mMockWebView, TEST_OPENID_VC_URL, span))); + + Mockito.verify(activity).startActivity(any(Intent.class)); + Mockito.verify(callback, never()).onChallengeResponseReceived(any(RawAuthorizationResult.class)); + assertNull(span.mRecordedException); + assertEquals(0, span.mEndCount); + assertEquals(previousSpan, SpanExtension.current()); + } + + private void verifyWalletDispatchFailure(final Throwable exception, final String errorCode) { + registerOpenIdVcHandler("com.example.wallet"); + final WebView webView = Mockito.mock(WebView.class); + final Activity failingActivity = Mockito.spy(mActivity); + Mockito.doThrow(exception).when(failingActivity).startActivity(any(Intent.class)); + final IAuthorizationCompletionCallback callback = Mockito.mock(IAuthorizationCompletionCallback.class); + final AzureActiveDirectoryWebViewClient client = new AzureActiveDirectoryWebViewClient( + failingActivity, callback, url -> {}, TEST_REDIRECT_URI, + Mockito.mock(SwitchBrowserProtocolCoordinator.class), "homeTenantId", false); + final CapturingSpanFactory telemetry = new CapturingSpanFactory(SpanName.ProcessOpenIdVcRequest.name()); + OTelUtility.setSpanFactory(telemetry); + + assertFalse(client.processOpenIdVcRequest(webView, TEST_OPENID_VC_URL)); + + final ArgumentCaptor result = ArgumentCaptor.forClass(RawAuthorizationResult.class); + Mockito.verify(callback).onChallengeResponseReceived(result.capture()); + assertEquals(errorCode, ((ClientException) result.getValue().getException()).getErrorCode()); + assertNull(telemetry.captured().mRecordedException); + assertEquals(StatusCode.ERROR, telemetry.captured().mStatusCode); + assertEquals("Failed to launch handler for openid-vc:// URI", + telemetry.captured().mStatusDescription); + assertEquals("failed", telemetry.captured().eventAttribute("vc_dispatch", AttributeName.operation_outcome)); + assertEquals(exception.getClass().getSimpleName(), + telemetry.captured().eventAttribute("vc_dispatch", AttributeName.error_type)); + assertNull(telemetry.captured().attribute(AttributeName.operation_outcome.name())); + assertFalse(telemetry.captured().mEventNames.contains("resolve_handler")); + assertFalse(telemetry.captured().mEventNames.contains("launch_wallet")); + assertNull(telemetry.captured().attribute(AttributeName.error_type.name())); + assertEquals(true, telemetry.captured().attribute(AttributeName.is_openid_vc_handler_found.name())); + assertFalse(telemetry.captured().mAttributes.values().toString().contains("sensitive-query")); + assertFalse(telemetry.captured().mEvents.toString().contains("sensitive-query")); + Mockito.verify(webView, never()).loadUrl(anyString()); + } + + @Test + public void testOpenIdVcDispatch_callbackThrows_doesNotDeliverTwice() { + final IAuthorizationCompletionCallback callback = Mockito.mock(IAuthorizationCompletionCallback.class); + final IllegalStateException failure = new IllegalStateException("Callback failed"); + Mockito.doThrow(failure).when(callback).onChallengeResponseReceived(any(RawAuthorizationResult.class)); + final AzureActiveDirectoryWebViewClient client = new AzureActiveDirectoryWebViewClient( + mActivity, callback, url -> {}, TEST_REDIRECT_URI, + Mockito.mock(SwitchBrowserProtocolCoordinator.class), "homeTenantId", false); + + try { + client.processOpenIdVcRequest(mMockWebView, TEST_OPENID_VC_URL); + Assert.fail("Expected callback exception"); + } catch (final IllegalStateException e) { + assertEquals(failure, e); + } + Mockito.verify(callback).onChallengeResponseReceived(any(RawAuthorizationResult.class)); + } + @Test public void testUrlOverrideHandlesOpenIdVcUrl_FlightDisabled() { // When the flight is disabled, the openid-vc:// URL bypasses the VC handler @@ -1052,6 +1285,18 @@ public void testUrlOverrideHandlesInvalidUrl() { assertFalse(mWebViewClient.shouldOverrideUrlLoading(mMockWebView, TEST_INVALID_URL)); } + @Test + public void testUrlOverrideDefersMyAccountUrlToWebView() { + final String url = "https://myaccount.microsoft.com/"; + + assertFalse(mWebViewClient.shouldOverrideUrlLoading(mMockWebView, url)); + assertFalse(mWebViewClient.shouldOverrideUrlLoading( + mMockWebView, mockNavigationRequest(url, true))); + assertFalse(mWebViewClient.shouldOverrideUrlLoading( + mMockWebView, mockNavigationRequest(url, false))); + assertNull(Shadows.shadowOf(mActivity).getNextStartedActivity()); + } + @Test public void testUrlOverrideHandlesHeaderForwardingRequiredUrl() { assertTrue(mWebViewClient.shouldOverrideUrlLoading(mMockWebView, TEST_MSA_HEADER_FORWARDING_POSITIVE_URL)); @@ -1650,8 +1895,18 @@ public Span createSpanFromParent(final String name, final SpanContext parentSpan */ private static final class RecordingSpan implements Span { private final Map, Object> mAttributes = new HashMap<>(); - private int mRecordedExceptionCount; - private StatusCode mStatusCode = StatusCode.UNSET; + private final List mEventNames = new ArrayList<>(); + private final List mEvents = new ArrayList<>(); + private StatusCode mStatusCode = StatusCode.UNSET; + private String mStatusDescription = ""; + private int mEndCount; + private Throwable mRecordedException; + private int mRecordedExceptionCount; + + Object eventAttribute(final String eventName, final AttributeName attribute) { + final int index = mEventNames.indexOf(eventName); + return index < 0 ? null : mEvents.get(index).get(AttributeKey.stringKey(attribute.name())); + } /** Returns the value recorded for the attribute with the given key name, or {@code null}. */ Object attribute(final String keyName) { @@ -1679,24 +1934,28 @@ public Span setAttribute(final AttributeKey key, final T value) { @Override public Span addEvent(final String name, final Attributes attributes) { + mEventNames.add(name); + mEvents.add(attributes); return this; } @Override public Span addEvent(final String name, final Attributes attributes, final long timestamp, final TimeUnit unit) { - return this; + return addEvent(name, attributes); } @Override public Span setStatus(final StatusCode statusCode, final String description) { - mStatusCode = statusCode; + mStatusCode = statusCode; + mStatusDescription = description; return this; } @Override public Span recordException(final Throwable exception, final Attributes additionalAttributes) { - mRecordedExceptionCount++; + mRecordedException = exception; + mRecordedExceptionCount++; return this; } @@ -1707,10 +1966,12 @@ public Span updateName(final String name) { @Override public void end() { + mEndCount++; } @Override public void end(final long timestamp, final TimeUnit unit) { + end(); } @Override diff --git a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java index 6c57051a79..945972a08a 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java +++ b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java @@ -231,8 +231,9 @@ public enum CommonFlight implements IFlightConfig { /** * Flight to enable multiple window support in WebView, which allows target="_blank" links * to be intercepted via onCreateWindow and opened in an external browser. + * Defaults off for brokerless consumers; BrokerFlight supplies the broker default. */ - ENABLE_WEBVIEW_MULTIPLE_WINDOWS("EnableWebViewMultipleWindows", true), + ENABLE_WEBVIEW_MULTIPLE_WINDOWS("EnableWebViewMultipleWindows", false), /** * Flight to enable file upload support in the embedded WebView. diff --git a/common4j/src/main/com/microsoft/identity/common/java/opentelemetry/AttributeName.java b/common4j/src/main/com/microsoft/identity/common/java/opentelemetry/AttributeName.java index 1cdd8f722c..17d2890dab 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/opentelemetry/AttributeName.java +++ b/common4j/src/main/com/microsoft/identity/common/java/opentelemetry/AttributeName.java @@ -864,10 +864,28 @@ public enum AttributeName { /** * Indicates which routing path was taken for a target=_blank URL intercepted - * by onCreateWindow: "null_url", "non_ssl", "non_tlr_inline", or "tlr_browser". + * by onCreateWindow: null_url, no_user_gesture, openid_vc, + * non_ssl, browser, or browser_fallback. */ target_blank_navigation_route, + /** + * The destination host for a target=_blank URL intercepted by onCreateWindow. + */ + target_blank_navigation_destination_host, + + /** + * Whether the popup was initiated by a user gesture. + */ + target_blank_navigation_is_user_gesture, + + /** + * Latest operation result. Named span events retain each decision's outcome independently; + * failures use the existing error_type attribute with an exception class only. + * Dispatch/load acceptance does not confirm destination completion. + */ + operation_outcome, + //endregion //region x-ms-clientdata server telemetry attributes diff --git a/common4j/src/main/com/microsoft/identity/common/java/opentelemetry/SpanExtension.java b/common4j/src/main/com/microsoft/identity/common/java/opentelemetry/SpanExtension.java index d023bd81ad..7a9d19fcc8 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/opentelemetry/SpanExtension.java +++ b/common4j/src/main/com/microsoft/identity/common/java/opentelemetry/SpanExtension.java @@ -24,6 +24,8 @@ import com.microsoft.identity.common.java.logging.Logger; import io.opentelemetry.api.internal.ImmutableSpanContext; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; @@ -72,6 +74,40 @@ public static Span current() { } } + /** + * Records a named decision. Distinct event names retain + * earlier decisions (for example a failed dispatch followed by a successful fallback). + * + * @param span the operation span + * @param stage the decision name + * @param outcome the decision result + */ + public static void recordOutcome(@NonNull final Span span, + @NonNull final String stage, + @NonNull final String outcome) { + recordOutcome(span, stage, outcome, null); + } + + /** + * Records a decision with a sanitized exception type, never an exception message or stack trace. + * + * @param span the operation span + * @param stage the decision name + * @param outcome the decision result + * @param exceptionType the exception class name, or null when there is no exception + */ + public static void recordOutcome(@NonNull final Span span, + @NonNull final String stage, + @NonNull final String outcome, + final String exceptionType) { + final AttributesBuilder attributes = Attributes.builder() + .put(AttributeName.operation_outcome.name(), outcome); + if (exceptionType != null) { + attributes.put(AttributeName.error_type.name(), exceptionType); + } + span.addEvent(stage, attributes.build()); + } + /** * A safe implementation of {@link ImplicitContextKeyed#makeCurrent()} that doesn't crash. The * default implementation in Open Telemetry sometimes throws an NPE deep into OTel's code. Per diff --git a/common4j/src/test/com/microsoft/identity/common/java/flighting/CommonFlightsManagerTest.java b/common4j/src/test/com/microsoft/identity/common/java/flighting/CommonFlightsManagerTest.java index aedff8ca0a..49dc95c00f 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/flighting/CommonFlightsManagerTest.java +++ b/common4j/src/test/com/microsoft/identity/common/java/flighting/CommonFlightsManagerTest.java @@ -53,4 +53,28 @@ public void testCommonFlightsManager() { public void tearDown() { CommonFlightsManager.INSTANCE.resetFlightsManager(); } + + @Test + public void testMultipleWindows_defaultsOffWithoutConsumerFlightsManager() { + CommonFlightsManager.INSTANCE.resetFlightsManager(); + Assert.assertEquals(Boolean.FALSE, CommonFlight.ENABLE_WEBVIEW_MULTIPLE_WINDOWS.getDefaultValue()); + Assert.assertFalse(CommonFlightsManager.INSTANCE.getFlightsProvider() + .isFlightEnabled(CommonFlight.ENABLE_WEBVIEW_MULTIPLE_WINDOWS)); + } + + @Test + public void testMultipleWindows_consumerCanExplicitlyEnableAndDisable() { + final MockFlightsProvider provider = new MockFlightsProvider(); + final MockFlightsManager manager = new MockFlightsManager(); + manager.setMockBrokerFlightsProvider(provider); + CommonFlightsManager.INSTANCE.initializeCommonFlightsManager(manager); + + provider.addFlight(CommonFlight.ENABLE_WEBVIEW_MULTIPLE_WINDOWS.getKey(), "true"); + Assert.assertTrue(CommonFlightsManager.INSTANCE.getFlightsProvider() + .isFlightEnabled(CommonFlight.ENABLE_WEBVIEW_MULTIPLE_WINDOWS)); + + provider.addFlight(CommonFlight.ENABLE_WEBVIEW_MULTIPLE_WINDOWS.getKey(), "false"); + Assert.assertFalse(CommonFlightsManager.INSTANCE.getFlightsProvider() + .isFlightEnabled(CommonFlight.ENABLE_WEBVIEW_MULTIPLE_WINDOWS)); + } } diff --git a/common4j/src/test/com/microsoft/identity/common/java/opentelemetry/SpanExtensionTest.kt b/common4j/src/test/com/microsoft/identity/common/java/opentelemetry/SpanExtensionTest.kt new file mode 100644 index 0000000000..745b800078 --- /dev/null +++ b/common4j/src/test/com/microsoft/identity/common/java/opentelemetry/SpanExtensionTest.kt @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// Licensed under the MIT License. + +package com.microsoft.identity.common.java.opentelemetry + +import io.opentelemetry.api.common.Attributes +import io.opentelemetry.api.trace.Span +import org.junit.Test +import org.mockito.Mockito.mock +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyNoMoreInteractions + +/** + * Tests the event payload emitted by the span outcome helpers. + */ +class SpanExtensionTest { + @Test + fun recordOutcome_withoutException_recordsOnlyOutcome() { + val span = mock(Span::class.java) + + SpanExtension.recordOutcome(span, "browser_launch", "succeeded") + + verify(span).addEvent( + "browser_launch", + Attributes.builder() + .put(AttributeName.operation_outcome.name, "succeeded") + .build() + ) + verifyNoMoreInteractions(span) + } + + @Test + fun recordOutcome_withException_recordsOutcomeAndExceptionType() { + val span = mock(Span::class.java) + + SpanExtension.recordOutcome(span, "vc_dispatch", "failed", "SecurityException") + + verify(span).addEvent( + "vc_dispatch", + Attributes.builder() + .put(AttributeName.operation_outcome.name, "failed") + .put(AttributeName.error_type.name, "SecurityException") + .build() + ) + verifyNoMoreInteractions(span) + } + + @Test + fun recordOutcome_fallback_recordsBothDecisionsWithoutChangingSpanStatus() { + val span = mock(Span::class.java) + + SpanExtension.recordOutcome(span, "browser_launch", "failed", "ActivityNotFoundException") + SpanExtension.recordOutcome(span, "browser_fallback", "inline_fallback_requested") + + val ordered = org.mockito.Mockito.inOrder(span) + ordered.verify(span).addEvent( + "browser_launch", + Attributes.builder() + .put(AttributeName.operation_outcome.name, "failed") + .put(AttributeName.error_type.name, "ActivityNotFoundException") + .build() + ) + ordered.verify(span).addEvent( + "browser_fallback", + Attributes.builder() + .put(AttributeName.operation_outcome.name, "inline_fallback_requested") + .build() + ) + verifyNoMoreInteractions(span) + } +} From faa3352386da81b51a01e93d44389b1dc359f43c Mon Sep 17 00:00:00 2001 From: Mohit Date: Tue, 13 Oct 2026 13:50:45 -0700 Subject: [PATCH 09/16] Add Common preprovisioning and combined registration APIs, Fixes AB#3784684 (#3306) ## Summary - Add `getPreprovisioningBlob` with an optional resource-account ID. - Add combined device/resource-account registration returning both records. - Add Java protocol DTOs using the existing Moshi serializer, focused tests, and concise API documentation. ## Scope Common API and IPC contracts only. Broker implementation follows separately. Existing registration APIs remain unchanged. No changelog changes. ## Validation 69 focused device-registration tests passed across `common4j:test` and `common:testLocalDebugUnitTest` (0 failures, 0 skipped). [AB#3784684](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3784684) ```text assistance: agentic-ide type: feature agent-tool: copilot-chat agent-model: n/a work-item: [AB#3784684](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3784684) ``` --------- Co-authored-by: Mohit --- .../DeviceRegistrationClientApplication.kt | 100 ++++++++ ...DeviceRegistrationClientApplicationTest.kt | 218 +++++++++++++++- ...iceAndResourceAccountRegistrationResult.kt | 37 +++ .../DeviceRegistrationProtocolConstants.java | 3 + .../PreprovisioningBlobV1Parameters.java | 94 +++++++ ...ithPreauthorizedChallengeV0Parameters.java | 120 +++++++++ .../PreprovisioningBlobV1Response.java | 78 ++++++ ...tWithPreauthorizedChallengeV0Response.java | 88 +++++++ ...ndResourceAccountRegistrationResultTest.kt | 59 +++++ .../DeviceRegistrationV1ProtocolTest.kt | 242 ++++++++++++++++++ 10 files changed, 1038 insertions(+), 1 deletion(-) create mode 100644 common4j/src/main/com/microsoft/identity/deviceregistration/java/api/DeviceAndResourceAccountRegistrationResult.kt create mode 100644 common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/parameters/PreprovisioningBlobV1Parameters.java create mode 100644 common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/parameters/RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.java create mode 100644 common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/response/PreprovisioningBlobV1Response.java create mode 100644 common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/response/RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response.java create mode 100644 common4j/src/test/com/microsoft/identity/deviceregistration/java/api/DeviceAndResourceAccountRegistrationResultTest.kt create mode 100644 common4j/src/test/com/microsoft/identity/deviceregistration/java/packer/DeviceRegistrationV1ProtocolTest.kt diff --git a/common/src/main/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplication.kt b/common/src/main/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplication.kt index 21232b2bbd..fdc63d1be3 100644 --- a/common/src/main/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplication.kt +++ b/common/src/main/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplication.kt @@ -41,10 +41,12 @@ import com.microsoft.identity.deviceregistration.AndroidDeviceRegistrationClient import com.microsoft.identity.deviceregistration.DeviceRegistrationIpcStrategiesProvider import com.microsoft.identity.deviceregistration.java.DeviceState import com.microsoft.identity.deviceregistration.java.DrsDiscoveryEndpoint +import com.microsoft.identity.deviceregistration.java.api.DeviceAndResourceAccountRegistrationResult import com.microsoft.identity.deviceregistration.java.api.DeviceTokenResult import com.microsoft.identity.deviceregistration.java.api.IDeviceRegistrationRecord import com.microsoft.identity.deviceregistration.java.exception.DeviceRegistrationException import com.microsoft.identity.deviceregistration.java.protocol.parameters.DeviceRegistrationPreAuthorizedV0Parameters +import com.microsoft.identity.deviceregistration.java.protocol.parameters.RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.DeviceRegistrationWithTokensV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.GetDeviceRegistrationRecordV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.GetDeviceRegistrationRecordsV0Parameters @@ -54,9 +56,11 @@ import com.microsoft.identity.deviceregistration.java.protocol.parameters.GetIns import com.microsoft.identity.deviceregistration.java.protocol.parameters.GetRegistrationStateV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.InstallCertificateSilentlyV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.PreProvisionedBlobV0Parameters +import com.microsoft.identity.deviceregistration.java.protocol.parameters.PreprovisioningBlobV1Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.ProvisionResourceAccountCredentialsV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.UnregisterDeviceV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.response.DeviceRegistrationPreAuthorizedV0Response +import com.microsoft.identity.deviceregistration.java.protocol.response.RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response import com.microsoft.identity.deviceregistration.java.protocol.response.DeviceRegistrationWithTokensV0Response import com.microsoft.identity.deviceregistration.java.protocol.response.GetDeviceRegistrationRecordV0Response import com.microsoft.identity.deviceregistration.java.protocol.response.GetDeviceRegistrationRecordsV0Response @@ -66,6 +70,7 @@ import com.microsoft.identity.deviceregistration.java.protocol.response.GetInsta import com.microsoft.identity.deviceregistration.java.protocol.response.GetRegistrationStateV0Response import com.microsoft.identity.deviceregistration.java.protocol.response.InstallCertificateSilentlyV0Response import com.microsoft.identity.deviceregistration.java.protocol.response.PreProvisionedBlobV0Response +import com.microsoft.identity.deviceregistration.java.protocol.response.PreprovisioningBlobV1Response import com.microsoft.identity.deviceregistration.java.protocol.response.ProvisionResourceAccountCredentialsV0Response import com.microsoft.identity.common.java.dto.AccountRecord import com.microsoft.identity.common.java.request.SdkType @@ -213,6 +218,48 @@ class DeviceRegistrationClientApplication { return result } + /** + * Requests Broker to prepare device/session transport keys and return a signed provisioning blob. + * + * Forward the blob to the provisioning service for a registration challenge. If an RA is supplied, + * complete with [registerDeviceAndResourceAccountWithPreauthorizedChallenge] using the same + * tenant, account, and environment. Requires Broker support; no legacy fallback. + * Synchronous: call off the main thread and do not log the blob. + * + * @param tenantId Tenant in which the device will be registered. + * @param resourceAccountId Optional tenant-local Entra object ID; null omits RA-key preparation. + * @param correlationId Correlation ID for request tracing. + * @param drsDiscoveryEndpoint DRS environment for preparation and registration. + * @return Signed provisioning blob, not a registration challenge. + * @throws BaseException If Broker communication or preparation fails. + * @throws ClientException If the response JWS is missing or blank. + */ + @JvmOverloads + @Throws(BaseException::class) + fun getPreprovisioningBlob( + tenantId: String, + resourceAccountId: String? = null, + correlationId: UUID, + drsDiscoveryEndpoint: DrsDiscoveryEndpoint = DrsDiscoveryEndpoint.PROD + ): String { + val methodTag = "$TAG:getPreprovisioningBlob" + Logger.info(methodTag, "GetPreprovisioningBlob (V1) started. CorrelationId: $correlationId") + val responseSerialized = mController.execute( + PreprovisioningBlobV1Parameters( + correlationId, tenantId, resourceAccountId, drsDiscoveryEndpoint.name + ) + ) + val result: String? = PreprovisioningBlobV1Response.create(responseSerialized).jws + if (result.isNullOrBlank()) { + throw ClientException( + ClientException.INVALID_BROKER_BUNDLE, + "Provisioning response must contain a non-blank JWS." + ) + } + Logger.info(methodTag, "Blob returned successfully.") + return result + } + /** * Gets the registration state from ADRS. * @@ -260,6 +307,59 @@ class DeviceRegistrationClientApplication { ) } + /** + * Registers a device and provisions its resource account using previously prepared keys. + * + * First call [getPreprovisioningBlob] with the same tenant, resource account, and environment. + * Supply the service's challenge encrypted to the prepared session transport key (STK). + * Requires Broker support; no legacy or unencrypted fallback. Synchronous: call off the main + * thread and do not log the challenge or account metadata. + * + * @param tenantId Tenant used during preprovisioning. + * @param resourceAccountId Required tenant-local Entra object ID used during preprovisioning. + * @param encryptedPreAuthorizedToken STK-encrypted preauthorized challenge returned by the service. + * @param registerAsSharedDevice Whether the device should be registered as shared. + * @param correlationId Correlation ID for request tracing. + * @param sdkType Calling SDK type. + * @param sdkVersion Calling SDK version. + * @param drsDiscoveryEndpoint DRS environment used during preprovisioning. + * @return Device and resource-account metadata after both operations succeed. + * @throws BaseException If Broker communication, registration, or resource-account provisioning fails. + * @throws ClientException If the response is missing either registration record. + */ + @JvmOverloads + @Throws(BaseException::class) + fun registerDeviceAndResourceAccountWithPreauthorizedChallenge( + tenantId: String, + resourceAccountId: String, + encryptedPreAuthorizedToken: String, + registerAsSharedDevice: Boolean, + correlationId: UUID, + sdkType: SdkType, + sdkVersion: String, + drsDiscoveryEndpoint: DrsDiscoveryEndpoint = DrsDiscoveryEndpoint.PROD + ): DeviceAndResourceAccountRegistrationResult { + val methodTag = "$TAG:registerDeviceAndResourceAccountWithPreauthorizedChallenge" + Logger.info(methodTag, "Registration (V0) started. CorrelationId: $correlationId") + val responseSerialized = mController.execute( + RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters( + correlationId, tenantId, resourceAccountId, encryptedPreAuthorizedToken, + registerAsSharedDevice, sdkType.name, sdkVersion, drsDiscoveryEndpoint.name + ) + ) + val response = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response.create(responseSerialized) + val deviceRegistrationRecord: IDeviceRegistrationRecord? = response.deviceRegistrationRecord + val resourceAccountRecord: AccountRecord? = response.resourceAccountRecord + if (deviceRegistrationRecord == null || resourceAccountRecord == null) { + throw ClientException( + ClientException.INVALID_BROKER_BUNDLE, + "Registration response must contain both device and resource-account records." + ) + } + Logger.info(methodTag, "Device registration and resource-account provisioning completed.") + return DeviceAndResourceAccountRegistrationResult(deviceRegistrationRecord, resourceAccountRecord) + } + /** * Registers device with preAuthorizedJoinChallenge. * diff --git a/common/src/test/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplicationTest.kt b/common/src/test/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplicationTest.kt index a8a6b213b2..4d5a9fce80 100644 --- a/common/src/test/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplicationTest.kt +++ b/common/src/test/java/com/microsoft/identity/deviceregistration/api/DeviceRegistrationClientApplicationTest.kt @@ -36,28 +36,36 @@ import com.microsoft.identity.common.logging.Logger import com.microsoft.identity.deviceregistration.AndroidDeviceRegistrationProtocolPacker import com.microsoft.identity.deviceregistration.DeviceRegistrationIpcStrategiesProvider import com.microsoft.identity.deviceregistration.java.DeviceState +import com.microsoft.identity.deviceregistration.java.DrsDiscoveryEndpoint import com.microsoft.identity.deviceregistration.java.api.DeviceRegistrationRecord import com.microsoft.identity.deviceregistration.java.api.DeviceTokenResult import com.microsoft.identity.deviceregistration.java.api.IDeviceRegistrationRecord import com.microsoft.identity.deviceregistration.java.protocol.parameters.GetDeviceTokenV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.GetDeviceTokenV1Parameters import com.microsoft.identity.deviceregistration.java.protocol.parameters.PreProvisionedBlobV0Parameters +import com.microsoft.identity.deviceregistration.java.protocol.parameters.PreprovisioningBlobV1Parameters +import com.microsoft.identity.deviceregistration.java.protocol.parameters.RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.response.GetDeviceRegistrationRecordV0Response import com.microsoft.identity.deviceregistration.java.protocol.response.GetDeviceRegistrationRecordsV0Response import com.microsoft.identity.deviceregistration.java.protocol.response.GetDeviceTokenV1Response import com.microsoft.identity.deviceregistration.java.protocol.response.GetRegistrationStateV0Response import com.microsoft.identity.deviceregistration.java.protocol.response.PreProvisionedBlobV0Response +import com.microsoft.identity.deviceregistration.java.protocol.response.PreprovisioningBlobV1Response +import com.microsoft.identity.deviceregistration.java.protocol.response.RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response import com.microsoft.identity.deviceregistration.java.protocol.parameters.ProvisionResourceAccountCredentialsV0Parameters import com.microsoft.identity.deviceregistration.java.protocol.response.ProvisionResourceAccountCredentialsV0Response import com.microsoft.identity.common.java.dto.AccountRecord import com.microsoft.identity.common.java.request.SdkType +import org.json.JSONObject import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.mock +import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import java.util.UUID @@ -65,7 +73,7 @@ import java.util.UUID /** * Unit tests for [DeviceRegistrationClientApplication]. * Uses mock IPC strategy to verify DRCA methods call the controller - * with correct V0 params and return correctly parsed responses. + * with correct protocol parameters and return correctly parsed responses. */ @RunWith(RobolectricTestRunner::class) class DeviceRegistrationClientApplicationTest { @@ -104,6 +112,14 @@ class DeviceRegistrationClientApplicationTest { return strategy } + private fun captureProtocolData(strategy: IIpcStrategy, protocolName: String): ByteArray { + val requestCaptor = argumentCaptor() + verify(strategy).communicateToBroker(requestCaptor.capture()) + val bundle = requireNotNull(requestCaptor.firstValue.bundle) + Assert.assertEquals(protocolName, bundle.getString("protocol.name")) + return requireNotNull(bundle.getByteArray("protocol.data")) + } + @Test fun getPreProvisionedBlob_returnsJws() { val expectedJws = "test.jws.blob" @@ -116,6 +132,206 @@ class DeviceRegistrationClientApplicationTest { Assert.assertEquals(expectedJws, result) } + @Test + fun getPreprovisioningBlob_withResourceAccount_packsParametersAndReturnsJws() { + val correlationId = UUID.randomUUID() + val expectedJws = "signed.preprovisioning.blob" + val response = PreprovisioningBlobV1Response(correlationId, expectedJws) + val strategy = successStrategy(packer.pack(response)) + val drca = createDrca(strategy) + + val result = drca.getPreprovisioningBlob( + "test-tenant", "test-resource-account", correlationId, DrsDiscoveryEndpoint.PPE + ) + + val parameters = PreprovisioningBlobV1Parameters.create( + captureProtocolData(strategy, "protocol.get.pre.provisioned.blob.v1") + ) + Assert.assertEquals(correlationId, parameters.correlationId) + Assert.assertEquals("test-tenant", parameters.tenantId) + Assert.assertEquals("test-resource-account", parameters.resourceAccountId) + Assert.assertEquals("PPE", parameters.discoveryEndpointName) + Assert.assertEquals(expectedJws, result) + } + + @Test + fun getPreprovisioningBlob_withoutResourceAccount_packsDefaultParametersAndReturnsJws() { + val correlationId = UUID.randomUUID() + val expectedJws = "signed.device.blob" + val response = PreprovisioningBlobV1Response(correlationId, expectedJws) + val strategy = successStrategy(packer.pack(response)) + val drca = createDrca(strategy) + + val result = drca.getPreprovisioningBlob("test-tenant", correlationId = correlationId) + + val parameters = PreprovisioningBlobV1Parameters.create( + captureProtocolData(strategy, "protocol.get.pre.provisioned.blob.v1") + ) + Assert.assertEquals(correlationId, parameters.correlationId) + Assert.assertEquals("test-tenant", parameters.tenantId) + Assert.assertNull(parameters.resourceAccountId) + Assert.assertEquals("PROD", parameters.discoveryEndpointName) + Assert.assertEquals(expectedJws, result) + } + + @Test + fun getPreprovisioningBlob_rejectsMissingOrBlankJws() { + val correlationId = UUID.randomUUID() + val response = PreprovisioningBlobV1Response(correlationId, "signed.valid.blob") + val serializedResponse = String(response.serialize(), Charsets.UTF_8) + val invalidPayloads = listOf(null, JSONObject.NULL, "", " ", "\t\r\n") + .map { invalidJws -> JSONObject(serializedResponse).put("mJws", invalidJws) } + JSONObject() + + for (payload in invalidPayloads) { + val responseBundle = packer.pack(response).apply { + putByteArray("protocol.data", payload.toString().toByteArray(Charsets.UTF_8)) + } + val drca = createDrca(successStrategy(responseBundle)) + + val exception = Assert.assertThrows(ClientException::class.java) { + drca.getPreprovisioningBlob("test-tenant", correlationId = correlationId) + } + + Assert.assertEquals(ClientException.INVALID_BROKER_BUNDLE, exception.errorCode) + } + } + + @Test + fun getPreprovisioningBlob_javaOverloads_supportOptionalResourceAccount() { + for (resourceAccountId in listOf(null, "test-resource-account")) { + val correlationId = UUID.randomUUID() + val expectedJws = "signed.java.blob" + val response = PreprovisioningBlobV1Response(correlationId, expectedJws) + val strategy = successStrategy(packer.pack(response)) + val drca = createDrca(strategy) + + val result = if (resourceAccountId == null) { + DeviceRegistrationClientApplication::class.java.getMethod( + "getPreprovisioningBlob", String::class.java, UUID::class.java + ).invoke(drca, "test-tenant", correlationId) + } else { + DeviceRegistrationClientApplication::class.java.getMethod( + "getPreprovisioningBlob", String::class.java, String::class.java, UUID::class.java + ).invoke(drca, "test-tenant", resourceAccountId, correlationId) + } + + val parameters = PreprovisioningBlobV1Parameters.create( + captureProtocolData(strategy, "protocol.get.pre.provisioned.blob.v1") + ) + Assert.assertEquals(correlationId, parameters.correlationId) + Assert.assertEquals("test-tenant", parameters.tenantId) + Assert.assertEquals(resourceAccountId, parameters.resourceAccountId) + Assert.assertEquals("PROD", parameters.discoveryEndpointName) + Assert.assertEquals(expectedJws, result) + } + } + + @Test + fun registerDeviceAndResourceAccountWithPreauthorizedChallenge_packsParametersAndReturnsBothRecords() { + val correlationId = UUID.randomUUID() + val deviceRecord = DeviceRegistrationRecord("test-tenant", "ra@test.com", "device-123", true, true) + val accountRecord = AccountRecord().apply { + homeAccountId = "test-resource-account.test-tenant" + localAccountId = "test-resource-account" + username = "ra@test.com" + environment = "login.windows-ppe.net" + realm = "test-tenant" + } + val response = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response( + correlationId, deviceRecord, accountRecord + ) + val strategy = successStrategy(packer.pack(response)) + val drca = createDrca(strategy) + + val result = drca.registerDeviceAndResourceAccountWithPreauthorizedChallenge( + "test-tenant", "test-resource-account", "encrypted-challenge", true, + correlationId, SdkType.MSAL, "4.2.0", DrsDiscoveryEndpoint.PPE + ) + + val parameters = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.create( + captureProtocolData(strategy, "protocol.register.device.and.resource.account.with.preauthorized.challenge.v0") + ) + Assert.assertEquals(correlationId, parameters.correlationId) + Assert.assertEquals("test-tenant", parameters.tenantId) + Assert.assertEquals("test-resource-account", parameters.resourceAccountId) + Assert.assertEquals("encrypted-challenge", parameters.encryptedPreAuthorizedToken) + Assert.assertTrue(parameters.isRegisterAsSharedDevice) + Assert.assertEquals("MSAL", parameters.sdkType) + Assert.assertEquals("4.2.0", parameters.sdkVersion) + Assert.assertEquals("PPE", parameters.discoveryEndpointName) + Assert.assertEquals(deviceRecord.javaClass, result.deviceRegistrationRecord.javaClass) + Assert.assertEquals(deviceRecord.tenantId, result.deviceRegistrationRecord.tenantId) + Assert.assertEquals(deviceRecord.upn, result.deviceRegistrationRecord.upn) + Assert.assertEquals(deviceRecord.deviceId, result.deviceRegistrationRecord.deviceId) + Assert.assertEquals(accountRecord, result.resourceAccountRecord) + } + + @Test + fun registerDeviceAndResourceAccountWithPreauthorizedChallenge_defaultsToProd() { + val correlationId = UUID.randomUUID() + val deviceRecord = DeviceRegistrationRecord("test-tenant", "ra@test.com", "device-123", false, true) + val accountRecord = AccountRecord().apply { localAccountId = "test-resource-account" } + val response = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response( + correlationId, deviceRecord, accountRecord + ) + val strategy = successStrategy(packer.pack(response)) + val drca = createDrca(strategy) + + val result = drca.registerDeviceAndResourceAccountWithPreauthorizedChallenge( + "test-tenant", "test-resource-account", "encrypted-challenge", false, + correlationId, SdkType.MSAL, "4.2.0" + ) + + val parameters = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.create( + captureProtocolData(strategy, "protocol.register.device.and.resource.account.with.preauthorized.challenge.v0") + ) + Assert.assertEquals(correlationId, parameters.correlationId) + Assert.assertEquals("test-tenant", parameters.tenantId) + Assert.assertEquals("test-resource-account", parameters.resourceAccountId) + Assert.assertEquals("encrypted-challenge", parameters.encryptedPreAuthorizedToken) + Assert.assertFalse(parameters.isRegisterAsSharedDevice) + Assert.assertEquals("MSAL", parameters.sdkType) + Assert.assertEquals("4.2.0", parameters.sdkVersion) + Assert.assertEquals("PROD", parameters.discoveryEndpointName) + Assert.assertEquals(deviceRecord.deviceId, result.deviceRegistrationRecord.deviceId) + Assert.assertEquals(accountRecord, result.resourceAccountRecord) + } + + @Test + fun registerDeviceAndResourceAccountWithPreauthorizedChallenge_rejectsMissingRecords() { + val correlationId = UUID.randomUUID() + val deviceRecord = DeviceRegistrationRecord("test-tenant", "ra@test.com", "device-123", false, true) + val accountRecord = AccountRecord().apply { username = "ra@test.com" } + val response = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response( + correlationId, deviceRecord, accountRecord + ) + val serializedResponse = String(response.serialize(), Charsets.UTF_8) + val invalidPayloads = listOf("mDeviceRegistrationRecord", "mResourceAccountRecord").flatMap { fieldName -> + listOf( + JSONObject(serializedResponse).apply { remove(fieldName) }, + JSONObject(serializedResponse).put(fieldName, JSONObject.NULL) + ) + } + JSONObject() + + for (payload in invalidPayloads) { + val responseBundle = packer.pack(response).apply { + putByteArray("protocol.data", payload.toString().toByteArray(Charsets.UTF_8)) + } + val drca = createDrca(successStrategy(responseBundle)) + + val exception = Assert.assertThrows(ClientException::class.java) { + drca.registerDeviceAndResourceAccountWithPreauthorizedChallenge( + "test-tenant", "test-resource-account", "encrypted-challenge", false, + correlationId, SdkType.MSAL, "4.2.0" + ) + } + + Assert.assertEquals(ClientException.INVALID_BROKER_BUNDLE, exception.errorCode) + Assert.assertFalse(exception.message.orEmpty().contains("ra@test.com")) + Assert.assertFalse(exception.message.orEmpty().contains("encrypted-challenge")) + } + } + @Test fun getRegistrationState_returnsDeviceState() { val response = GetRegistrationStateV0Response(UUID.randomUUID(), "DEVICE_VALID") diff --git a/common4j/src/main/com/microsoft/identity/deviceregistration/java/api/DeviceAndResourceAccountRegistrationResult.kt b/common4j/src/main/com/microsoft/identity/deviceregistration/java/api/DeviceAndResourceAccountRegistrationResult.kt new file mode 100644 index 0000000000..cad52a65f3 --- /dev/null +++ b/common4j/src/main/com/microsoft/identity/deviceregistration/java/api/DeviceAndResourceAccountRegistrationResult.kt @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// This code is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package com.microsoft.identity.deviceregistration.java.api + +import com.microsoft.identity.common.java.dto.IAccountRecord + +/** + * Metadata from completed device registration and initial resource-account provisioning. + * + * @property deviceRegistrationRecord Required device registration metadata. + * @property resourceAccountRecord Required resource-account metadata. + */ +class DeviceAndResourceAccountRegistrationResult( + val deviceRegistrationRecord: IDeviceRegistrationRecord, + val resourceAccountRecord: IAccountRecord +) \ No newline at end of file diff --git a/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/DeviceRegistrationProtocolConstants.java b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/DeviceRegistrationProtocolConstants.java index 000aae27ce..4354cdab42 100644 --- a/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/DeviceRegistrationProtocolConstants.java +++ b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/DeviceRegistrationProtocolConstants.java @@ -28,7 +28,10 @@ public final class DeviceRegistrationProtocolConstants { public static final String DEVICE_REGISTRATION_WITH_TOKENS_V0 = "protocol.device.registration.with.tokens.v0"; public static final String DEVICE_REGISTRATION_PREAUTHORIZED_V0 = "protocol.device.registration.preauthorized.v0"; + public static final String REGISTER_DEVICE_AND_RESOURCE_ACCOUNT_WITH_PREAUTHORIZED_CHALLENGE_V0 = + "protocol.register.device.and.resource.account.with.preauthorized.challenge.v0"; public static final String GET_PRE_PROVISIONED_BLOB_V0 = "protocol.get.pre.provisioned.blob.v0"; + public static final String GET_PRE_PROVISIONED_BLOB_V1 = "protocol.get.pre.provisioned.blob.v1"; public static final String GET_REGISTRATION_STATE_V0 = "protocol.get.state.v0"; public static final String GET_DEVICE_TOKEN_V0 = "protocol.get.device.token.v0"; public static final String GET_DEVICE_TOKEN_V1 = "protocol.get.device.token.v1"; diff --git a/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/parameters/PreprovisioningBlobV1Parameters.java b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/parameters/PreprovisioningBlobV1Parameters.java new file mode 100644 index 0000000000..ec9bd8e22e --- /dev/null +++ b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/parameters/PreprovisioningBlobV1Parameters.java @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// This code is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +package com.microsoft.identity.deviceregistration.java.protocol.parameters; + +import com.microsoft.identity.common.java.exception.ClientException; +import com.microsoft.identity.deviceregistration.java.protocol.DeviceRegistrationProtocolConstants; +import com.microsoft.identity.deviceregistration.java.protocol.packer.DeviceRegistrationProtocolMoshiSerializer; +import com.microsoft.identity.deviceregistration.java.protocol.packer.IDeviceRegistrationProtocolSerializer; + +import java.util.UUID; + +import edu.umd.cs.findbugs.annotations.Nullable; +import lombok.Getter; +import lombok.NonNull; +import lombok.experimental.Accessors; + +/** + * Requests Broker key preparation and a signed preprovisioning blob. + * A resource-account ID also requests an RA key; null requests device-only preparation. + */ +@Accessors(prefix = "m") +public class PreprovisioningBlobV1Parameters extends AbstractDeviceRegistrationProtocolParameters { + + private static final IDeviceRegistrationProtocolSerializer serializer + = new DeviceRegistrationProtocolMoshiSerializer<>(PreprovisioningBlobV1Parameters.class); + + /** + * Deserializes protocol parameters. + * + * @param serializedData serialized protocol data + */ + public static PreprovisioningBlobV1Parameters create(final byte[] serializedData) throws ClientException { + return serializer.deserialize(serializedData); + } + + /** + * @param correlationId correlation ID for request tracing + * @param tenantId tenant in which the device will be registered + * @param resourceAccountId optional tenant-local Entra object ID; null omits RA-key preparation + * @param discoveryEndpointName DRS environment used for preparation and registration + */ + public PreprovisioningBlobV1Parameters(@NonNull final UUID correlationId, + @NonNull final String tenantId, + @Nullable final String resourceAccountId, + @NonNull final String discoveryEndpointName) { + super(correlationId); + mTenantId = tenantId; + mResourceAccountId = resourceAccountId; + mDiscoveryEndpointName = discoveryEndpointName; + } + + @Getter + @NonNull + private final String mTenantId; + + @Getter + @Nullable + private final String mResourceAccountId; + + @Getter + @NonNull + private final String mDiscoveryEndpointName; + + @Override + @NonNull + public String getProtocolName() { + return DeviceRegistrationProtocolConstants.GET_PRE_PROVISIONED_BLOB_V1; + } + + @Override + public byte[] serialize() { + return serializer.serialize(this); + } +} \ No newline at end of file diff --git a/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/parameters/RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.java b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/parameters/RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.java new file mode 100644 index 0000000000..efa2e26764 --- /dev/null +++ b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/parameters/RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// This code is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +package com.microsoft.identity.deviceregistration.java.protocol.parameters; + +import com.microsoft.identity.common.java.exception.ClientException; +import com.microsoft.identity.deviceregistration.java.protocol.DeviceRegistrationProtocolConstants; +import com.microsoft.identity.deviceregistration.java.protocol.packer.DeviceRegistrationProtocolMoshiSerializer; +import com.microsoft.identity.deviceregistration.java.protocol.packer.IDeviceRegistrationProtocolSerializer; + +import java.util.UUID; + +import lombok.Getter; +import lombok.NonNull; +import lombok.experimental.Accessors; + +/** + * Requests device registration and initial resource-account provisioning with prepared keys. + * The tenant, resource account, and environment must match preprovisioning. + */ +@Accessors(prefix = "m") +public class RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters extends AbstractDeviceRegistrationProtocolParameters { + + private static final IDeviceRegistrationProtocolSerializer serializer + = new DeviceRegistrationProtocolMoshiSerializer<>(RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.class); + + /** + * Deserializes protocol parameters. + * + * @param serializedData serialized protocol data + */ + public static RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters create(final byte[] serializedData) throws ClientException { + return serializer.deserialize(serializedData); + } + + /** + * @param correlationId correlation ID for request tracing + * @param tenantId tenant used during preprovisioning + * @param resourceAccountId required tenant-local Entra object ID used during preprovisioning + * @param encryptedPreAuthorizedToken STK-encrypted preauthorized challenge returned by the service + * @param registerAsSharedDevice whether the device should be registered as shared + * @param sdkType calling SDK type name + * @param sdkVersion calling SDK version + * @param discoveryEndpointName DRS environment used during preprovisioning + */ + public RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters(@NonNull final UUID correlationId, + @NonNull final String tenantId, + @NonNull final String resourceAccountId, + @NonNull final String encryptedPreAuthorizedToken, + final boolean registerAsSharedDevice, + @NonNull final String sdkType, + @NonNull final String sdkVersion, + @NonNull final String discoveryEndpointName) { + super(correlationId); + mTenantId = tenantId; + mResourceAccountId = resourceAccountId; + mEncryptedPreAuthorizedToken = encryptedPreAuthorizedToken; + mRegisterAsSharedDevice = registerAsSharedDevice; + mSdkType = sdkType; + mSdkVersion = sdkVersion; + mDiscoveryEndpointName = discoveryEndpointName; + } + + @Getter + @NonNull + private final String mTenantId; + + @Getter + @NonNull + private final String mResourceAccountId; + + @Getter + @NonNull + private final String mEncryptedPreAuthorizedToken; + + @Getter + private final boolean mRegisterAsSharedDevice; + + @Getter + @NonNull + private final String mSdkType; + + @Getter + @NonNull + private final String mSdkVersion; + + @Getter + @NonNull + private final String mDiscoveryEndpointName; + + @Override + @NonNull + public String getProtocolName() { + return DeviceRegistrationProtocolConstants.REGISTER_DEVICE_AND_RESOURCE_ACCOUNT_WITH_PREAUTHORIZED_CHALLENGE_V0; + } + + @Override + public byte[] serialize() { + return serializer.serialize(this); + } +} \ No newline at end of file diff --git a/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/response/PreprovisioningBlobV1Response.java b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/response/PreprovisioningBlobV1Response.java new file mode 100644 index 0000000000..6e65d044d5 --- /dev/null +++ b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/response/PreprovisioningBlobV1Response.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// This code is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +package com.microsoft.identity.deviceregistration.java.protocol.response; + +import com.microsoft.identity.common.java.exception.ClientException; +import com.microsoft.identity.deviceregistration.java.protocol.DeviceRegistrationProtocolConstants; +import com.microsoft.identity.deviceregistration.java.protocol.packer.DeviceRegistrationProtocolMoshiSerializer; +import com.microsoft.identity.deviceregistration.java.protocol.packer.IDeviceRegistrationProtocolSerializer; + +import java.util.UUID; + +import lombok.Getter; +import lombok.NonNull; +import lombok.experimental.Accessors; + +/** + * Signed preprovisioning blob from Broker to forward to the provisioning service. + * This response does not represent completed registration. + */ +@Accessors(prefix = "m") +public class PreprovisioningBlobV1Response extends AbstractDeviceRegistrationProtocolResponse { + + private static final IDeviceRegistrationProtocolSerializer serializer + = new DeviceRegistrationProtocolMoshiSerializer<>(PreprovisioningBlobV1Response.class); + + /** + * Deserializes a protocol response. + * + * @param serializedData serialized protocol data + */ + public static PreprovisioningBlobV1Response create(final byte[] serializedData) throws ClientException { + return serializer.deserialize(serializedData); + } + + /** + * @param correlationId correlation ID of the request + * @param jws signed provisioning blob; do not log this value + */ + public PreprovisioningBlobV1Response(@NonNull final UUID correlationId, @NonNull final String jws) { + super(correlationId); + mJws = jws; + } + + @Getter + @NonNull + private final String mJws; + + @Override + @NonNull + public String getProtocolName() { + return DeviceRegistrationProtocolConstants.GET_PRE_PROVISIONED_BLOB_V1; + } + + @Override + public byte[] serialize() { + return serializer.serialize(this); + } +} \ No newline at end of file diff --git a/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/response/RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response.java b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/response/RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response.java new file mode 100644 index 0000000000..171c5fabc9 --- /dev/null +++ b/common4j/src/main/com/microsoft/identity/deviceregistration/java/protocol/response/RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// This code is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +package com.microsoft.identity.deviceregistration.java.protocol.response; + +import com.microsoft.identity.common.java.dto.AccountRecord; +import com.microsoft.identity.common.java.exception.ClientException; +import com.microsoft.identity.deviceregistration.java.api.IDeviceRegistrationRecord; +import com.microsoft.identity.deviceregistration.java.protocol.DeviceRegistrationProtocolConstants; +import com.microsoft.identity.deviceregistration.java.protocol.packer.DeviceRegistrationProtocolMoshiSerializer; +import com.microsoft.identity.deviceregistration.java.protocol.packer.IDeviceRegistrationProtocolSerializer; + +import java.util.UUID; + +import lombok.Getter; +import lombok.NonNull; +import lombok.experimental.Accessors; + +/** + * Response after device registration and initial resource-account provisioning both succeed. + * Both records are required. {@link AccountRecord} provides the concrete type for deserialization. + */ +@Accessors(prefix = "m") +public class RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response extends AbstractDeviceRegistrationProtocolResponse { + + private static final IDeviceRegistrationProtocolSerializer serializer + = new DeviceRegistrationProtocolMoshiSerializer<>(RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response.class); + + /** + * Deserializes a protocol response. + * + * @param serializedData serialized protocol data + */ + public static RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response create(final byte[] serializedData) throws ClientException { + return serializer.deserialize(serializedData); + } + + /** + * @param correlationId correlation ID of the request + * @param deviceRegistrationRecord completed device registration + * @param resourceAccountRecord metadata for the provisioned resource account + */ + public RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response(@NonNull final UUID correlationId, + @NonNull final IDeviceRegistrationRecord deviceRegistrationRecord, + @NonNull final AccountRecord resourceAccountRecord) { + super(correlationId); + mDeviceRegistrationRecord = deviceRegistrationRecord; + mResourceAccountRecord = resourceAccountRecord; + } + + @Getter + @NonNull + private final IDeviceRegistrationRecord mDeviceRegistrationRecord; + + @Getter + @NonNull + private final AccountRecord mResourceAccountRecord; + + @Override + @NonNull + public String getProtocolName() { + return DeviceRegistrationProtocolConstants.REGISTER_DEVICE_AND_RESOURCE_ACCOUNT_WITH_PREAUTHORIZED_CHALLENGE_V0; + } + + @Override + public byte[] serialize() { + return serializer.serialize(this); + } +} \ No newline at end of file diff --git a/common4j/src/test/com/microsoft/identity/deviceregistration/java/api/DeviceAndResourceAccountRegistrationResultTest.kt b/common4j/src/test/com/microsoft/identity/deviceregistration/java/api/DeviceAndResourceAccountRegistrationResultTest.kt new file mode 100644 index 0000000000..a6d3308e7c --- /dev/null +++ b/common4j/src/test/com/microsoft/identity/deviceregistration/java/api/DeviceAndResourceAccountRegistrationResultTest.kt @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// This code is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package com.microsoft.identity.deviceregistration.java.api + +import com.microsoft.identity.common.java.dto.AccountRecord +import com.microsoft.identity.common.java.dto.IAccountRecord +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +class DeviceAndResourceAccountRegistrationResultTest { + @Test + fun exposesBothRecordsWithoutIncludingThemInToString() { + val deviceRecord = DeviceRegistrationRecord("tenant", "resource@example.com", "device", true, true) + val accountRecord = AccountRecord().apply { username = "resource@example.com" } + val result = DeviceAndResourceAccountRegistrationResult(deviceRecord, accountRecord) + + assertSame(deviceRecord, result.deviceRegistrationRecord) + assertSame(accountRecord, result.resourceAccountRecord) + assertFalse(result.toString().contains("resource@example.com")) + } + + @Test + fun rejectsNullResourceAccountFromJava() { + val deviceRecord = DeviceRegistrationRecord("tenant", "", "device", false, true) + val constructor = DeviceAndResourceAccountRegistrationResult::class.java.getConstructor( + IDeviceRegistrationRecord::class.java, IAccountRecord::class.java + ) + try { + constructor.newInstance(deviceRecord, null) + fail("Expected the required resource account record to reject null") + } catch (exception: java.lang.reflect.InvocationTargetException) { + assertTrue(exception.cause is NullPointerException) + } + } +} \ No newline at end of file diff --git a/common4j/src/test/com/microsoft/identity/deviceregistration/java/packer/DeviceRegistrationV1ProtocolTest.kt b/common4j/src/test/com/microsoft/identity/deviceregistration/java/packer/DeviceRegistrationV1ProtocolTest.kt new file mode 100644 index 0000000000..1a987ab126 --- /dev/null +++ b/common4j/src/test/com/microsoft/identity/deviceregistration/java/packer/DeviceRegistrationV1ProtocolTest.kt @@ -0,0 +1,242 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// This code is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +package com.microsoft.identity.deviceregistration.java.packer + +import com.microsoft.identity.common.java.dto.AccountRecord +import com.microsoft.identity.deviceregistration.java.api.DeviceRegistrationRecord +import com.microsoft.identity.deviceregistration.java.api.DeviceRegistrationRecordWithAccount +import com.microsoft.identity.deviceregistration.java.protocol.DeviceRegistrationProtocolConstants +import com.microsoft.identity.deviceregistration.java.protocol.IDeviceRegistrationProtocol +import com.microsoft.identity.deviceregistration.java.protocol.parameters.DeviceRegistrationPreAuthorizedV0Parameters +import com.microsoft.identity.deviceregistration.java.protocol.parameters.RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters +import com.microsoft.identity.deviceregistration.java.protocol.parameters.PreProvisionedBlobV0Parameters +import com.microsoft.identity.deviceregistration.java.protocol.parameters.PreprovisioningBlobV1Parameters +import com.microsoft.identity.deviceregistration.java.protocol.response.DeviceRegistrationPreAuthorizedV0Response +import com.microsoft.identity.deviceregistration.java.protocol.response.RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response +import com.microsoft.identity.deviceregistration.java.protocol.response.PreProvisionedBlobV0Response +import com.microsoft.identity.deviceregistration.java.protocol.response.PreprovisioningBlobV1Response +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.util.UUID + +class DeviceRegistrationV1ProtocolTest { + private val correlationId = UUID.fromString("5f3a7734-7554-4a99-aed3-309093ce80cf") + + @Test + fun protocolIdentifiersMatchOperationsAndPreserveV0() { + assertEquals( + "protocol.get.pre.provisioned.blob.v1", + DeviceRegistrationProtocolConstants.GET_PRE_PROVISIONED_BLOB_V1 + ) + assertEquals( + "protocol.register.device.and.resource.account.with.preauthorized.challenge.v0", + DeviceRegistrationProtocolConstants.REGISTER_DEVICE_AND_RESOURCE_ACCOUNT_WITH_PREAUTHORIZED_CHALLENGE_V0 + ) + assertEquals( + "protocol.get.pre.provisioned.blob.v0", + DeviceRegistrationProtocolConstants.GET_PRE_PROVISIONED_BLOB_V0 + ) + assertEquals( + "protocol.device.registration.preauthorized.v0", + DeviceRegistrationProtocolConstants.DEVICE_REGISTRATION_PREAUTHORIZED_V0 + ) + } + + @Test + fun protocolTypeVersionsMatchWireVersions() { + val protocols = listOf( + PreprovisioningBlobV1Parameters(correlationId, "tenant", null, "PROD"), + PreprovisioningBlobV1Response(correlationId, "signed-blob"), + RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters( + correlationId, "tenant", "resource", "challenge", false, "MSAL", "1.0", "PROD" + ), + RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response( + correlationId, DeviceRegistrationRecord("tenant", "", "device", false, true), AccountRecord() + ) + ) + val versionSuffix = Regex("V(\\d+)(Parameters|Response)$") + + for (protocol in protocols) { + val typeName = protocol.javaClass.simpleName + val version = requireNotNull(versionSuffix.find(typeName)).groupValues[1] + assertEquals(typeName, "v$version", protocol.protocolName.substringAfterLast('.')) + } + } + + @Test + fun protocolConstantVersionsMatchWireVersions() { + val versionSuffix = Regex("_V(\\d+)$") + for (field in DeviceRegistrationProtocolConstants::class.java.fields) { + val version = versionSuffix.find(field.name)?.groupValues?.get(1) ?: continue + val protocolName = field.get(null) as String + assertEquals(field.name, "v$version", protocolName.substringAfterLast('.')) + } + } + + @Test + fun blobParametersRoundTrip() { + val request = PreprovisioningBlobV1Parameters(correlationId, "tenant", "resource", "PPE") + val restored = PreprovisioningBlobV1Parameters.create(request.serialize()) + + assertEquals(correlationId, restored.correlationId) + assertEquals("tenant", restored.tenantId) + assertEquals("resource", restored.resourceAccountId) + assertEquals("PPE", restored.discoveryEndpointName) + assertEquals(DeviceRegistrationProtocolConstants.GET_PRE_PROVISIONED_BLOB_V1, restored.protocolName) + assertTrue(String(request.serialize(), Charsets.UTF_8).contains("\"mResourceAccountId\":\"resource\"")) + } + + @Test + fun blobParametersRoundTripWithoutResourceAccount() { + val request = PreprovisioningBlobV1Parameters(correlationId, "tenant", null, "PPE") + val restored = PreprovisioningBlobV1Parameters.create(request.serialize()) + + assertEquals(correlationId, restored.correlationId) + assertEquals("tenant", restored.tenantId) + assertNull(restored.resourceAccountId) + assertEquals("PPE", restored.discoveryEndpointName) + assertEquals(DeviceRegistrationProtocolConstants.GET_PRE_PROVISIONED_BLOB_V1, restored.protocolName) + assertFalse(String(request.serialize(), Charsets.UTF_8).contains("mResourceAccountId")) + } + + @Test + fun registrationParametersRoundTrip() { + for (sharedDevice in listOf(true, false)) { + val request = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters( + correlationId, "tenant", "resource", "encrypted-challenge", sharedDevice, "ONEAUTH", "1.0", "PROD" + ) + val restored = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.create(request.serialize()) + + assertEquals(correlationId, restored.correlationId) + assertEquals("tenant", restored.tenantId) + assertEquals("resource", restored.resourceAccountId) + assertEquals("encrypted-challenge", restored.encryptedPreAuthorizedToken) + assertEquals(sharedDevice, restored.isRegisterAsSharedDevice) + assertEquals("ONEAUTH", restored.sdkType) + assertEquals("1.0", restored.sdkVersion) + assertEquals("PROD", restored.discoveryEndpointName) + assertEquals(DeviceRegistrationProtocolConstants.REGISTER_DEVICE_AND_RESOURCE_ACCOUNT_WITH_PREAUTHORIZED_CHALLENGE_V0, restored.protocolName) + assertFalse(request.toString().contains("encrypted-challenge")) + } + } + + @Test + fun blobResponseRoundTrip() { + val response = PreprovisioningBlobV1Response(correlationId, "signed-blob") + val restored = PreprovisioningBlobV1Response.create(response.serialize()) + + assertEquals(correlationId, restored.correlationId) + assertEquals("signed-blob", restored.jws) + assertEquals(DeviceRegistrationProtocolConstants.GET_PRE_PROVISIONED_BLOB_V1, restored.protocolName) + assertFalse(response.toString().contains("signed-blob")) + } + + @Test + fun registrationResponseRoundTripsBothRecordTypes() { + val account = AccountRecord().apply { + homeAccountId = "resource.tenant" + localAccountId = "resource" + realm = "tenant" + username = "resource@example.com" + environment = "login.microsoftonline.com" + } + val records = listOf( + DeviceRegistrationRecord("tenant", "resource@example.com", "device", true, true), + DeviceRegistrationRecordWithAccount("account", "tenant", "resource@example.com", "device", true, true) + ) + for (record in records) { + val response = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response(correlationId, record, account) + val restored = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response.create(response.serialize()) + + assertEquals(correlationId, restored.correlationId) + assertEquals(record.javaClass, restored.deviceRegistrationRecord.javaClass) + assertEquals("device", restored.deviceRegistrationRecord.deviceId) + assertEquals(account, restored.resourceAccountRecord) + assertEquals(DeviceRegistrationProtocolConstants.REGISTER_DEVICE_AND_RESOURCE_ACCOUNT_WITH_PREAUTHORIZED_CHALLENGE_V0, restored.protocolName) + } + } + + @Test + fun responseDeserializationMatchesExistingV0Defaults() { + val serialized = "{}".toByteArray(Charsets.UTF_8) + val oldBlob = PreProvisionedBlobV0Response.create(serialized) + val newBlob = PreprovisioningBlobV1Response.create(serialized) + assertEquals(oldBlob.correlationId, newBlob.correlationId) + assertEquals(oldBlob.jws, newBlob.jws) + + val oldJoin = DeviceRegistrationPreAuthorizedV0Response.create(serialized) + val newJoin = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Response.create(serialized) + assertEquals(oldJoin.correlationId, newJoin.correlationId) + assertEquals(oldJoin.deviceRegistrationRecord, newJoin.deviceRegistrationRecord) + assertNull(newJoin.resourceAccountRecord) + } + + @Test + fun blankBlobDeserializationMatchesExistingV0() { + val payload = """{"mCorrelationId":"$correlationId","mJws":" "}""" + val serialized = payload.toByteArray(Charsets.UTF_8) + val oldBlob = PreProvisionedBlobV0Response.create(serialized) + val newBlob = PreprovisioningBlobV1Response.create(serialized) + assertEquals(oldBlob.correlationId, newBlob.correlationId) + assertEquals(oldBlob.jws, newBlob.jws) + } + + @Test + fun javaBooleanGetterMatchesExistingProtocols() { + val request = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters( + correlationId, "tenant", "resource", "challenge", true, "ONEAUTH", "1.0", "PROD" + ) + assertEquals( + true, + RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters::class.java + .getMethod("isRegisterAsSharedDevice").invoke(request) + ) + } + + @Test + fun parameterDeserializationMatchesExistingV0Defaults() { + val serialized = "{}".toByteArray(Charsets.UTF_8) + val oldBlob = PreProvisionedBlobV0Parameters.create(serialized) + val newBlob = PreprovisioningBlobV1Parameters.create(serialized) + assertEquals(oldBlob.correlationId, newBlob.correlationId) + assertEquals(oldBlob.tenantId, newBlob.tenantId) + assertNull(newBlob.resourceAccountId) + assertNull(newBlob.discoveryEndpointName) + + val oldJoin = DeviceRegistrationPreAuthorizedV0Parameters.create(serialized) + val newJoin = RegisterDeviceAndResourceAccountWithPreauthorizedChallengeV0Parameters.create(serialized) + assertEquals(oldJoin.correlationId, newJoin.correlationId) + assertEquals(oldJoin.tenantId, newJoin.tenantId) + assertEquals(oldJoin.isRegisterAsSharedDevice, newJoin.isRegisterAsSharedDevice) + assertFalse(newJoin.isRegisterAsSharedDevice) + assertNull(newJoin.resourceAccountId) + assertNull(newJoin.encryptedPreAuthorizedToken) + assertNull(newJoin.sdkType) + assertNull(newJoin.sdkVersion) + assertNull(newJoin.discoveryEndpointName) + } +} \ No newline at end of file From b32f4a2acb333d02e59ab6e7210bc222625ac51f Mon Sep 17 00:00:00 2001 From: Praveen Kumar Date: Tue, 13 Oct 2026 15:22:38 -0700 Subject: [PATCH 10/16] Make Device-CA authorize-only forwarding default-off, Fixes AB#3766458 (#3312) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Work item [AB#3766458](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3766458)

Summary

Changes ENABLE_DEVICE_CA_AUTHORIZE_ONLY_CREDENTIAL_FORWARDING from default-on to default-off so the authorize-only behavior introduced by #3287 can be enabled progressively through ECS instead of applying automatically to every Common consumer.

This PR does not change the Device-CA routing implementation, browser fallback behavior, or telemetry schema. It changes only the flight’s fallback/default state and updates the associated documentation and tests.

Tracking

This PR is the approved follow-up to the Device-CA authorize-only credential-forwarding work in Common. The corresponding Azure DevOps PBI remains the internal source for rollout ownership, acceptance criteria, and release tracking. Its identifier is intentionally omitted from this public repository’s PR description.

Background

The authorize-only forwarding implementation prevents the original WebView request headers from being attached to Device-CA navigation when the flight is enabled. This ensures credential forwarding occurs only through the validated WebCP authorize path.

The initial implementation defaulted the flight to true. This follow-up changes the rollout policy so both Broker-hosted and brokerless Common consumers begin with the feature disabled. Broker-hosted flows can then be enabled gradually by setting the Common flight to true through Broker ECS.

No separate Broker flight is required. Broker’s ECS provider can resolve the existing Common flight directly.

Behavior

Flight value | Device-CA WebView behavior | Telemetry -- | -- | -- Missing or false | Uses the legacy path and loads the Device-CA URL with the original request headers | device_ca_authorize_only_forwarding_enabled=false; device_ca_request_headers_skipped is not emitted true | Uses authorize-only forwarding and loads the Device-CA URL without the original request headers | device_ca_authorize_only_forwarding_enabled=true; device_ca_request_headers_skipped=true

An explicit ECS value of true enables authorize-only forwarding for selected Broker cohorts. An explicit value of false keeps or restores the legacy behavior.

Consumers that do not install an ECS-backed or host-provided Common flight manager—including brokerless consumers relying on Common defaults—remain on the default-off legacy path.

Changes

  • Change ENABLE_DEVICE_CA_AUTHORIZE_ONLY_CREDENTIAL_FORWARDING default from true to false.
  • Update the flight documentation to describe explicit opt-in and gradual rollout.
  • Update the flight configuration assertion to expect Boolean.FALSE.
  • Add router-level coverage confirming that the disabled path uses the existing request-header loader.
  • Add a separate vNext changelog entry for the default-off rollout policy without rewriting the original authorize-only forwarding entry.

Rollout plan

The initial rollout will:

  1. Keep the Common fallback value at false.
  2. Set the Common flight to true through ECS for selected Broker cohorts.
  3. Compare control (false) and treatment (true) telemetry.
  4. Expand treatment gradually after each rollout stage is validated.
  5. Use an explicit ECS value of false for control or rollback.

Removing an ECS assignment should not be treated as the rollback mechanism because clients may retain previously cached configuration. Rollback should explicitly deliver false.

Brokerless MSAL and OneAuth-hosted flows are intentionally default-off and are outside the Broker ECS rollout. Enabling brokerless flows later requires a separate host-controlled mechanism or a future change to the Common default.

Security considerations

This is an intentional rollout-policy change. When the flight is missing or disabled, Common retains the legacy behavior of forwarding the original request headers during Device-CA WebView navigation. Those headers may include credential-bearing values.

When the flight resolves to true, Common loads the Device-CA URL without the original request headers. Credential forwarding is then limited to the validated WebCP authorize path.

Browser fallback remains independent of this flight. This PR does not add URL, request-header, credential, PRT, host, login-hint, or other sensitive data to telemetry.

Telemetry

The existing bounded boolean attributes remain unchanged:

  • device_ca_authorize_only_forwarding_enabled
  • device_ca_request_headers_skipped

Expected interpretation:

  • Control or default-off traffic emits device_ca_authorize_only_forwarding_enabled=false.
  • device_ca_request_headers_skipped is absent when the feature is disabled because the legacy header-forwarding path is used.
  • Treatment traffic emits device_ca_authorize_only_forwarding_enabled=true and device_ca_request_headers_skipped=true.

Validation

The following validation completed successfully:

  • Focused Common unit tests:
    • AzureActiveDirectoryWebViewClientTest
    • DeviceCaRequestRouterTest
  • Common local-debug assembly:
    • :common:assembleLocalDebug

Commands:

.\gradlew.bat
:common:testLocalDebugUnitTest `
--tests
"com.microsoft.identity.common.internal.ui.webview.AzureActiveDirectoryWebViewClientTest"
`
--tests
"com.microsoft.identity.common.internal.ui.webview.DeviceCaRequestRouterTest"
`
  --no-daemon

.\gradlew.bat :common:assembleLocalDebug --no-daemon --console=plain

Review notes

Two independent reviews were run against the original immutable implementation diff:

  • One reviewer reported no actionable findings.
  • One reviewer identified that default-off restores legacy credential-header forwarding when ECS or another flight provider is unavailable.

That behavior is understood and accepted as the intentional consequence of the approved default-off gradual-rollout policy.

Co-authored-by: prsaminathan Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- changelog.txt | 1 + .../AzureActiveDirectoryWebViewClientTest.java | 2 +- .../internal/ui/webview/DeviceCaRequestRouterTest.kt | 11 +++++++++++ .../identity/common/java/flighting/CommonFlight.java | 5 +++-- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/changelog.txt b/changelog.txt index 70dcbe5c41..99b7a55297 100644 --- a/changelog.txt +++ b/changelog.txt @@ -1,6 +1,7 @@ vNext ---------- - [MINOR] Add the InstallCertDeepLinkActivity span name for Broker's legacy install-certificate deep-link caller telemetry (AB#3771034) (#3293) +- [PATCH] Default authorize-only Device-CA credential forwarding to off for gradual ECS rollout - [PATCH] Enforce authorize-only Device-CA credential forwarding by withholding original request headers from Device-CA WebView loads by default, with explicit ECS disablement as the rollback path (AB#3766458) - [PATCH] Enable WebCP flows in WebView by default for brokerless MSAL requests while preserving the host-provided override used by OneAuth flighting diff --git a/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java b/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java index 2406938df3..ceef8b71f9 100644 --- a/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java +++ b/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java @@ -2105,7 +2105,7 @@ public void testUrlOverrideHandleWebCPEnrollmentUrlDisabled() { public void testDeviceCaAuthorizeOnlyFlightConfiguration() { assertEquals("EnableDeviceCaAuthorizeOnlyCredentialForwarding", CommonFlight.ENABLE_DEVICE_CA_AUTHORIZE_ONLY_CREDENTIAL_FORWARDING.getKey()); - assertEquals(Boolean.TRUE, + assertEquals(Boolean.FALSE, CommonFlight.ENABLE_DEVICE_CA_AUTHORIZE_ONLY_CREDENTIAL_FORWARDING.getDefaultValue()); } diff --git a/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/DeviceCaRequestRouterTest.kt b/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/DeviceCaRequestRouterTest.kt index a2cf876fae..f4778eae67 100644 --- a/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/DeviceCaRequestRouterTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/DeviceCaRequestRouterTest.kt @@ -247,6 +247,17 @@ class DeviceCaRequestRouterTest { assertNull(host.loadedUrl) } + @Test + fun loadInWebViewOrBrowser_authorizeOnlyDisabledByDefault_loadsWithRequestHeaders() { + host.webCpInWebViewEnabled = true + + val result = router.loadInWebViewOrBrowser(DEVICE_CA_URL, webView) + + assertSame(DeviceCaRequestRouter.RoutingResult.Completed, result) + assertEquals(HTTPS_DEVICE_CA_URL, host.loadedUrl) + verify(webView, never()).loadUrl(anyString()) + } + @Test fun loadInWebViewOrBrowser_replacesOnlyLeadingBrowserScheme() { host.webCpInWebViewEnabled = true diff --git a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java index 945972a08a..12c4da9e39 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java +++ b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java @@ -146,11 +146,12 @@ public enum CommonFlight implements IFlightConfig { /** * Flight to withhold the original request headers from Device-CA loads so credentials are - * forwarded only by the validated WebCP authorize path. + * forwarded only by the validated WebCP authorize path. This is disabled by default for + * gradual rollout; an explicit {@code true} value enables authorize-only forwarding. */ ENABLE_DEVICE_CA_AUTHORIZE_ONLY_CREDENTIAL_FORWARDING( "EnableDeviceCaAuthorizeOnlyCredentialForwarding", - true), + false), /** * Flight to enable the Playstore URL launch for broker apps. From 2e49192564e23ccac7513105577f50cb443d7698 Mon Sep 17 00:00:00 2001 From: Sowmya Malayanur <69237821+somalaya@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:58:50 -0700 Subject: [PATCH 11/16] Handle marked broker WebView redirects in external browser, Fixes AB#3785260 (#3304) ## Summary - Recognize `broker_webview_external_browser=1` on HTTPS navigations in Common WebViews, including brokered and brokerless flows. - Gate handling with the default-on `EnableBrokerWebViewExternalBrowserRedirect` Common flight. - Launch the original marked URL unchanged in the system browser and keep the current authorization session active. - If no browser can handle the URL or the external launch fails, return control to the WebView so it loads the original URL; do not complete or cancel authorization. - Emit `ProcessWebsiteRequest` telemetry with `operation_outcome=broker_external_browser_launched` and `is_redirect_url_opened_in_browser=true` on success, or `operation_outcome=broker_external_browser_launch_failed` and `is_redirect_url_opened_in_browser=false` when falling back to the WebView. ## Testing - Added focused unit coverage for exact marker parsing, HTTPS eligibility in brokered and brokerless flows, flight behavior, unchanged URL forwarding, successful browser launch, WebView fallback, callback behavior, and telemetry. - Common build/test, lint, SpotBugs, consumer assembly, and instrumented-test validations passed on the prior PR revision. ## Work item [AB#3781149](https://identitydivision.visualstudio.com/Engineering/_workitems/edit/3781149) --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../AzureActiveDirectoryWebViewClient.java | 36 +++++ .../BrokerWebViewExternalBrowserRedirect.kt | 86 ++++++++++++ ...AzureActiveDirectoryWebViewClientTest.java | 129 ++++++++++++++++++ .../common/java/flighting/CommonFlight.java | 7 + 4 files changed, 258 insertions(+) create mode 100644 common/src/main/java/com/microsoft/identity/common/internal/ui/webview/BrokerWebViewExternalBrowserRedirect.kt diff --git a/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClient.java b/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClient.java index 0c36bec8a6..efdee96645 100644 --- a/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClient.java +++ b/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClient.java @@ -529,6 +529,9 @@ else if (mSwitchBrowserProtocolCoordinator.isSwitchBrowserRequest(formattedURL, } else if (!isUriSSLProtected(formattedURL)) { Logger.info(methodTag,"Check for SSL protection"); processSSLProtectionCheck(view, url); + } else if (isBrokerExternalBrowserRedirect(url)) { + Logger.info(methodTag, "Broker WebView received an external-browser redirect."); + return processBrokerExternalBrowserRedirect(view, url); } else if (isHeaderForwardingRequiredUri(url)) { processHeaderForwardingRequiredUri(view, url); } else if (CommonFlightsManager.INSTANCE.getFlightsProvider().isFlightEnabled(CommonFlight.ENABLE_ATTACH_PRT_HEADER_WHEN_CROSS_CLOUD) && isCrossCloudRedirect(formattedURL)) { @@ -580,6 +583,39 @@ private boolean isUriSSLProtected(@NonNull final String url) { return url.startsWith(AuthenticationConstants.Broker.REDIRECT_SSL_PREFIX); } + @VisibleForTesting + boolean isBrokerExternalBrowserRedirect(@NonNull final String url) { + return CommonFlightsManager.INSTANCE.getFlightsProvider().isFlightEnabled( + CommonFlight.ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT) + && BrokerWebViewExternalBrowserRedirect.isMarked(url); + } + + private boolean processBrokerExternalBrowserRedirect( + @NonNull final WebView view, + @NonNull final String url) { + final Span span = createSpanWithAttributesFromParent(SpanName.ProcessWebsiteRequest.name()); + try (final Scope scope = SpanExtension.makeCurrentSpan(span)) { + if (BrokerWebViewExternalBrowserRedirect.launch(getActivity(), url)) { + view.stopLoading(); + span.setAttribute(AttributeName.is_redirect_url_opened_in_browser.name(), true); + span.setAttribute( + AttributeName.operation_outcome.name(), + "broker_external_browser_launched"); + span.setStatus(StatusCode.OK); + return true; + } else { + span.setAttribute(AttributeName.is_redirect_url_opened_in_browser.name(), false); + span.setAttribute( + AttributeName.operation_outcome.name(), + "broker_external_browser_launch_failed"); + span.setStatus(StatusCode.ERROR); + return false; + } + } finally { + span.end(); + } + } + private boolean isBlankPageRequest(@NonNull final String url) { return "about:blank".equals(url); } diff --git a/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/BrokerWebViewExternalBrowserRedirect.kt b/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/BrokerWebViewExternalBrowserRedirect.kt new file mode 100644 index 0000000000..23155f0062 --- /dev/null +++ b/common/src/main/java/com/microsoft/identity/common/internal/ui/webview/BrokerWebViewExternalBrowserRedirect.kt @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// All rights reserved. +// +// This code is licensed under the MIT License. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +package com.microsoft.identity.common.internal.ui.webview + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.net.Uri +import com.microsoft.identity.common.logging.Logger + +/** + * Recognizes and launches server-selected external URLs from brokered and brokerless WebViews. + */ +object BrokerWebViewExternalBrowserRedirect { + private val TAG = BrokerWebViewExternalBrowserRedirect::class.java.simpleName + + /** Query parameter used by eSTS to opt a destination into external-browser routing. */ + const val QUERY_PARAMETER = "broker_webview_external_browser" + + /** The only query parameter value that opts into external-browser routing. */ + const val ENABLED_VALUE = "1" + + /** + * Returns whether [url] is an HTTPS destination explicitly marked for external-browser routing. + */ + @JvmStatic + fun isMarked(url: String): Boolean { + return try { + val uri = Uri.parse(url) + uri.scheme.equals("https", ignoreCase = true) && + uri.getQueryParameter(QUERY_PARAMETER) == ENABLED_VALUE + } catch (exception: IllegalArgumentException) { + Logger.warn("$TAG:isMarked", "Unable to parse external-browser redirect marker.") + false + } catch (exception: UnsupportedOperationException) { + Logger.warn("$TAG:isMarked", "External-browser redirect URL is not hierarchical.") + false + } + } + + /** + * Opens [url] unchanged with an external activity. + * + * @return `true` when the launch was requested, or `false` when no handler is available. + */ + @JvmStatic + fun launch(context: Context, url: String): Boolean { + val methodTag = "$TAG:launch" + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addCategory(Intent.CATEGORY_BROWSABLE) + if (intent.resolveActivity(context.packageManager) == null) { + Logger.warn(methodTag, "Unable to find an app to handle the external-browser redirect.") + return false + } + + return try { + context.startActivity(intent) + true + } catch (exception: ActivityNotFoundException) { + Logger.error(methodTag, "External-browser redirect handler is no longer available.", exception) + false + } catch (exception: SecurityException) { + Logger.error(methodTag, "External-browser redirect launch was denied.", exception) + false + } + } +} diff --git a/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java b/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java index ceef8b71f9..426296a86d 100644 --- a/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java +++ b/common/src/test/java/com/microsoft/identity/common/internal/ui/webview/AzureActiveDirectoryWebViewClientTest.java @@ -277,6 +277,11 @@ public class AzureActiveDirectoryWebViewClientTest { private static final String TEST_PLAYSTORE_REDIRECT_WITH_BROWSER_PROTOCOL = "browser://play.app.goo.gl/?link=https://play.google.com/store/apps/details?id=com.microsoft.windowsintune.companyportal"; private static final String TEST_OPENID_VC_URL = "openid-vc://credential-offer?credential_issuer=https%3A%2F%2Fexample.com&credential_configuration_ids=VerifiedEmployee"; + private static final String TEST_BROKER_EXTERNAL_BROWSER_URL = + "https://issuer.example/issuance?tokenId=example-token" + + "&broker_webview_external_browser=1&other=value#credential"; + private static final String TEST_BROKER_EXTERNAL_BROWSER_DISABLED_URL = + "https://issuer.example/issuance?broker_webview_external_browser=true"; // Authenticator activation app link test URLs private static final String TEST_AUTHENTICATOR_ACTIVATION_GLOBAL = @@ -365,6 +370,130 @@ public void testUrlOverrideHandlesWebsiteRequestUrl() { assertTrue(mWebViewClient.shouldOverrideUrlLoading(mMockWebView, TEST_PLAYSTORE_REDIRECT_WITH_BROWSER_PROTOCOL)); } + @Test + @Config(shadows = {ShadowProcessUtil.class}) + public void testUrlOverrideMarkedBrokerExternalBrowserUrl_preservesUrlAndSession() { + enableBrokerWebViewExternalBrowserRedirectFlight(); + final IAuthorizationCompletionCallback callback = + Mockito.mock(IAuthorizationCompletionCallback.class); + final AzureActiveDirectoryWebViewClient webViewClient = + new AzureActiveDirectoryWebViewClient( + mActivity, + callback, + url -> { }, + TEST_REDIRECT_URI, + Mockito.mock(SwitchBrowserProtocolCoordinator.class), + "homeTenantId", + false); + final Intent browserIntent = + new Intent(Intent.ACTION_VIEW, Uri.parse(TEST_BROKER_EXTERNAL_BROWSER_URL)) + .addCategory(Intent.CATEGORY_BROWSABLE); + final ResolveInfo resolveInfo = new ResolveInfo(); + resolveInfo.activityInfo = new ActivityInfo(); + resolveInfo.activityInfo.packageName = "com.example.browser"; + resolveInfo.activityInfo.name = "com.example.browser.BrowserActivity"; + Shadows.shadowOf(mActivity.getPackageManager()) + .addResolveInfoForIntent(browserIntent, resolveInfo); + final WebView webView = Mockito.mock(WebView.class); + final CapturingSpanFactory spanFactory = + new CapturingSpanFactory(SpanName.ProcessWebsiteRequest.name()); + OTelUtility.setSpanFactory(spanFactory); + + assertTrue(webViewClient.shouldOverrideUrlLoading( + webView, TEST_BROKER_EXTERNAL_BROWSER_URL)); + + Mockito.verify(webView).stopLoading(); + Mockito.verify(callback, never()) + .onChallengeResponseReceived(Mockito.any(RawAuthorizationResult.class)); + final Intent startedIntent = Shadows.shadowOf(mActivity).getNextStartedActivity(); + assertNotNull(startedIntent); + assertEquals(TEST_BROKER_EXTERNAL_BROWSER_URL, startedIntent.getDataString()); + final RecordingSpan span = spanFactory.captured(); + assertNotNull(span); + assertEquals(Boolean.TRUE, + span.attribute(AttributeName.is_redirect_url_opened_in_browser.name())); + assertEquals("broker_external_browser_launched", + span.attribute(AttributeName.operation_outcome.name())); + assertEquals(StatusCode.OK, span.statusCode()); + } + + @Test + @Config(shadows = {ShadowProcessUtil.class}) + public void testUrlOverrideExternalBrowserMarkerRequiresLiteralOne() { + enableBrokerWebViewExternalBrowserRedirectFlight(); + assertFalse(mWebViewClient.shouldOverrideUrlLoading( + mMockWebView, TEST_BROKER_EXTERNAL_BROWSER_DISABLED_URL)); + } + + @Test + @Config(shadows = {ShadowProcessUtil.class}) + public void testMarkedExternalBrowserUrlWithFlightDisabled_isNotIntercepted() { + setBrokerWebViewExternalBrowserRedirectFlight(false); + assertFalse(mWebViewClient.shouldOverrideUrlLoading( + mMockWebView, TEST_BROKER_EXTERNAL_BROWSER_URL)); + } + + @Test + public void testMarkedExternalBrowserUrlOutsideBroker_isIntercepted() { + enableBrokerWebViewExternalBrowserRedirectFlight(); + try (final MockedStatic processUtil = Mockito.mockStatic(ProcessUtil.class)) { + processUtil.when(() -> ProcessUtil.isRunningOnAuthService(Mockito.any(Context.class))) + .thenReturn(false); + + assertTrue(mWebViewClient.isBrokerExternalBrowserRedirect( + TEST_BROKER_EXTERNAL_BROWSER_URL)); + } + } + + @Test + @Config(shadows = {ShadowProcessUtil.class}) + public void testUrlOverrideMarkedBrokerExternalBrowserUrlWithoutBrowser_loadsInWebView() { + enableBrokerWebViewExternalBrowserRedirectFlight(); + final IAuthorizationCompletionCallback callback = + Mockito.mock(IAuthorizationCompletionCallback.class); + final AzureActiveDirectoryWebViewClient webViewClient = + new AzureActiveDirectoryWebViewClient( + mActivity, + callback, + url -> { }, + TEST_REDIRECT_URI, + Mockito.mock(SwitchBrowserProtocolCoordinator.class), + "homeTenantId", + false); + final WebView webView = Mockito.mock(WebView.class); + final CapturingSpanFactory spanFactory = + new CapturingSpanFactory(SpanName.ProcessWebsiteRequest.name()); + OTelUtility.setSpanFactory(spanFactory); + + assertFalse(webViewClient.shouldOverrideUrlLoading( + webView, TEST_BROKER_EXTERNAL_BROWSER_URL)); + + Mockito.verify(webView, never()).stopLoading(); + Mockito.verify(callback, never()) + .onChallengeResponseReceived(Mockito.any(RawAuthorizationResult.class)); + assertNull(Shadows.shadowOf(mActivity).getNextStartedActivity()); + final RecordingSpan span = spanFactory.captured(); + assertNotNull(span); + assertEquals(Boolean.FALSE, + span.attribute(AttributeName.is_redirect_url_opened_in_browser.name())); + assertEquals("broker_external_browser_launch_failed", + span.attribute(AttributeName.operation_outcome.name())); + assertEquals(StatusCode.ERROR, span.statusCode()); + } + + private void enableBrokerWebViewExternalBrowserRedirectFlight() { + setBrokerWebViewExternalBrowserRedirectFlight(true); + } + + private void setBrokerWebViewExternalBrowserRedirectFlight(final boolean enabled) { + final IFlightsProvider mockFlightsProvider = Mockito.mock(IFlightsProvider.class); + when(mockFlightsProvider.isFlightEnabled( + CommonFlight.ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT)).thenReturn(enabled); + final MockCommonFlightsManager mockCommonFlightsManager = new MockCommonFlightsManager(); + mockCommonFlightsManager.setMockCommonFlightsProvider(mockFlightsProvider); + CommonFlightsManager.INSTANCE.initializeCommonFlightsManager(mockCommonFlightsManager); + } + @Test public void testUrlOverrideHandlesOpenIdVcUrl() { assertTrue(mWebViewClient.shouldOverrideUrlLoading(mMockWebView, TEST_OPENID_VC_URL)); diff --git a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java index 12c4da9e39..a2a872712f 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java +++ b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java @@ -236,6 +236,13 @@ public enum CommonFlight implements IFlightConfig { */ ENABLE_WEBVIEW_MULTIPLE_WINDOWS("EnableWebViewMultipleWindows", false), + /** + * Flight to enable external-browser routing for marked URLs in brokered and brokerless WebViews. + */ + ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT( + "EnableBrokerWebViewExternalBrowserRedirect", + true), + /** * Flight to enable file upload support in the embedded WebView. * When enabled, the WebView will handle file chooser requests from web pages. From 9294353eb1d679ad99107152f8afaba5dbde0d33 Mon Sep 17 00:00:00 2001 From: Sowmya Malayanur <69237821+somalaya@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:33:30 -0700 Subject: [PATCH 12/16] Add broker external browser redirect premortem, Fixes AB#3781149 (#3313) ## Summary - add the rollout premortem for broker external-browser redirects - add the production monitoring dashboard queries and interpretation guidance - document brokered and brokerless eligibility plus Broker-dashboard coverage limits - document best-effort eSTS correlation when `correlation_id_v2` is available ## Validation - `git diff --cached --check` - documentation-only change Related implementation: #3304 Related work item: [AB#3781149](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3781149) --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...IEW_EXTERNAL_BROWSER_REDIRECT-Dashboard.md | 312 ++++++++++++++++++ ...IEW_EXTERNAL_BROWSER_REDIRECT-Premortem.md | 168 ++++++++++ 2 files changed, 480 insertions(+) create mode 100644 docs/premortem/ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Dashboard.md create mode 100644 docs/premortem/ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Premortem.md diff --git a/docs/premortem/ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Dashboard.md b/docs/premortem/ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Dashboard.md new file mode 100644 index 0000000000..59bebccebb --- /dev/null +++ b/docs/premortem/ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Dashboard.md @@ -0,0 +1,312 @@ + + +# Dashboard - `ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT` + +## Data source + +- **Cluster:** `https://idsharedeus2.kusto.windows.net/` +- **Database:** `ad-accounts-android-otel` +- **Table:** `android_spans` +- **Feature span:** `ProcessWebsiteRequest` +- **Sampling:** The Broker default configuration samples this span at 50%. All counts below + are sampled spans, not total requests. + +This dashboard uses Android Broker telemetry and monitors broker-hosted execution. The +client feature also applies to brokerless WebViews, but brokerless execution is not measured +by this dashboard. + +The feature-specific `operation_outcome` column is not present in production until a build +containing the telemetry contract is deployed. The queries use `column_ifexists()` so the +dashboard remains valid and returns empty results before deployment. + +Feature outcomes: + +- `broker_external_browser_launched`: the marked URL opened externally. +- `broker_external_browser_launch_failed`: external launch failed and the URL continued in + the WebView. + +Before public preview, no more than 10 total marked requests per day are expected. Because +the feature span is sampled, do not multiply the sampled result to report an exact total or +treat an empty interval as proof of no usage. + +## Tile 1: Daily sampled feature volume and launch outcomes + +Use stacked columns for `launched` and `fell_back_to_webview`, with +`sampled_launch_success_pct` as a line. + +```kusto +let feature_spans = android_spans +| where EventInfo_Time >= ago(30d) +| where span_name == "ProcessWebsiteRequest" +| extend operation_outcome = + tostring(column_ifexists("operation_outcome", "")) +| where operation_outcome in ( + "broker_external_browser_launched", + "broker_external_browser_launch_failed" +); +feature_spans +| summarize + sampled_spans = count(), + launched = countif( + operation_outcome == "broker_external_browser_launched"), + fell_back_to_webview = countif( + operation_outcome == "broker_external_browser_launch_failed") + by bin(EventInfo_Time, 1d) +| extend sampled_launch_success_pct = + round(100.0 * launched / sampled_spans, 2) +| order by EventInfo_Time asc +``` + +## Tile 2: Outcomes by Broker host app version + +Use this table to identify which Broker host versions receive marked traffic and whether +failures cluster on a version. + +```kusto +let feature_spans = android_spans +| where EventInfo_Time >= ago(30d) +| where span_name == "ProcessWebsiteRequest" +| extend operation_outcome = + tostring(column_ifexists("operation_outcome", "")) +| where operation_outcome in ( + "broker_external_browser_launched", + "broker_external_browser_launch_failed" +); +feature_spans +| summarize + sampled_spans = count(), + launched = countif( + operation_outcome == "broker_external_browser_launched"), + fell_back_to_webview = countif( + operation_outcome == "broker_external_browser_launch_failed") + by AppInfo_Version +| extend sampled_launch_success_pct = + round(100.0 * launched / sampled_spans, 2) +| order by sampled_spans desc +``` + +## Tile 3: Outcome and span-status consistency + +The expected mappings are: + +- `broker_external_browser_launched` to `OK` +- `broker_external_browser_launch_failed` to `ERROR` + +Any nonzero `status_mismatches` value requires investigation. + +```kusto +android_spans +| where EventInfo_Time >= ago(30d) +| where span_name == "ProcessWebsiteRequest" +| extend operation_outcome = + tostring(column_ifexists("operation_outcome", "")) +| where operation_outcome in ( + "broker_external_browser_launched", + "broker_external_browser_launch_failed" +) +| extend expected_status = iff( + operation_outcome == "broker_external_browser_launched", + "OK", + "ERROR") +| summarize + sampled_spans = count(), + status_mismatches = countif(span_status != expected_status) + by operation_outcome, span_status, expected_status +| extend mismatch_pct = + round(100.0 * status_mismatches / sampled_spans, 2) +``` + +This query validates status consistency only among spans already classified by a recognized +feature outcome. It cannot detect a feature span that completely omitted +`operation_outcome`, because the outcome is also the attribute used to identify the feature +span. Do not use this tile as an outcome-attribute completeness guardrail. + +## Tile 4: Failed-launch WebView fallback drilldown + +Review every row during the initial rollout. A row means external launch failed and the URL +continued in the WebView; it does not mean the authorization request was terminated. + +```kusto +android_spans +| where EventInfo_Time >= ago(30d) +| where span_name == "ProcessWebsiteRequest" +| extend operation_outcome = + tostring(column_ifexists("operation_outcome", "")) +| where operation_outcome == + "broker_external_browser_launch_failed" +| project + EventInfo_Time, + AppInfo_Version, + calling_package_name, + DeviceInfo_OsVersion, + DeviceInfo_Model, + span_status, + correlation_id_v2, + trace_id +| order by EventInfo_Time desc +| take 100 +``` + +## Tile 5: Best-effort Broker-to-eSTS correlation and VID flight attribution + +This cross-cluster query joins sampled feature spans to Android eSTS requests using +`correlation_id_v2 == CorrelationId`. It checks whether the eSTS request recorded +`EnableAndroidBrokerWebViewExternalBrowserRedirect` in `FeatureV2InRollOut` or +`FeatureV2Switches`. This tile includes only spans with an exported +`correlation_id_v2`. Successful spans without tenant context do not receive +`correlation_id_v2`, so they are intentionally absent from this tile even when the feature +span itself was exported. Empty results do not prove that no marked traffic occurred. + +```kusto +let broker_feature = android_spans +| where EventInfo_Time >= ago(7d) +| where span_name == "ProcessWebsiteRequest" +| extend operation_outcome = + tostring(column_ifexists("operation_outcome", "")) +| where operation_outcome in ( + "broker_external_browser_launched", + "broker_external_browser_launch_failed" +) +| where isnotempty(correlation_id_v2) + and correlation_id_v2 != "Scrubbed" +| project + broker_time = EventInfo_Time, + operation_outcome, + AppInfo_Version, + calling_package_name, + trace_id, + broker_correlation_id = tostring(correlation_id_v2); + +let ests_android = + cluster("https://estswus2.kusto.windows.net/") + .database("ESTS").AllPerRequestTable +| where env_time >= ago(7d) +| where DevicePlatformForUI == "Android" +| extend vid_redirect_flight_present = + FeatureV2InRollOut contains + "EnableAndroidBrokerWebViewExternalBrowserRedirect" + or FeatureV2Switches contains + "EnableAndroidBrokerWebViewExternalBrowserRedirect" +| project + ests_time = env_time, + ests_correlation_id = tostring(CorrelationId), + RequestId, + Call, + Result, + ErrorCode, + ScenarioId, + vid_redirect_flight_present; + +broker_feature +| join kind=leftouter hint.remote=right ests_android + on $left.broker_correlation_id == $right.ests_correlation_id +| summarize + ests_rows = countif(isnotempty(RequestId)), + vid_redirect_flight_rows = countif(vid_redirect_flight_present), + ests_calls = make_set(Call, 20), + ests_results = make_set(Result, 20), + ests_error_codes = make_set_if( + ErrorCode, + isnotempty(ErrorCode), + 20), + ests_scenarios = make_set_if( + ScenarioId, + isnotempty(ScenarioId), + 20), + first_ests_time = min(ests_time), + last_ests_time = max(ests_time) + by + broker_time, + operation_outcome, + AppInfo_Version, + calling_package_name, + trace_id, + broker_correlation_id +| extend vid_attribution = case( + ests_rows == 0, + "no_ests_match", + vid_redirect_flight_rows > 0, + "vid_redirect_flight_present", + "ests_match_without_vid_redirect_flight") +| order by broker_time desc +| take 100 +``` + +The query was validated against the production clusters before the feature was deployed. +No Android eSTS rows from the preceding seven days contained the new flight name, so empty +feature results are currently expected. After rollout: + +- `vid_redirect_flight_present` confirms that at least one correlated eSTS request recorded + the server flight. +- `ests_match_without_vid_redirect_flight` means the correlation ID matched eSTS, but the + flight was not present in the queried feature fields. +- `no_ests_match` means no Android eSTS request was returned for the sampled correlation ID + and time window. + +## Tile 6: Directional authentication outcome after successful handoff + +This query joins successful external launches to `AcquireTokenInteractive` by `trace_id`. +It is directional only: `missing_terminal_span` means telemetry-incomplete and is not +evidence that the authorization session was lost. + +```kusto +let successful_handoffs = android_spans +| where EventInfo_Time >= ago(30d) +| where span_name == "ProcessWebsiteRequest" +| extend operation_outcome = + tostring(column_ifexists("operation_outcome", "")) +| where operation_outcome == + "broker_external_browser_launched" +| summarize + handoff_time = min(EventInfo_Time), + broker_host_app_version = take_any(AppInfo_Version) + by trace_id; + +let terminal_auth = android_spans +| where EventInfo_Time >= ago(30d) +| where span_name == "AcquireTokenInteractive" +| summarize arg_max( + EventInfo_Time, + span_status, + error_code, + error_message) + by trace_id +| project + trace_id, + auth_time = EventInfo_Time, + auth_span_status = span_status, + auth_error_code = error_code, + auth_error_message = error_message; + +successful_handoffs +| join kind=leftouter terminal_auth on trace_id +| extend auth_outcome = case( + isempty(auth_time), + "missing_terminal_span", + auth_error_code in ( + "User cancelled", + "auth_cancelled_by_sdk", + "Broker request cancelled", + "CANCELED") + or tolower(auth_error_message) contains "cancel", + "cancelled", + auth_span_status == "ERROR", + "error", + auth_span_status == "OK", + "success", + "other") +| summarize sampled_traces = count() + by bin(handoff_time, 1d), auth_outcome +| order by handoff_time asc +``` + +## Interpretation and response + +- Inspect every sampled `broker_external_browser_launch_failed` row during the initial + rollout. +- Use `correlation_id_v2`, when present, to confirm sampled requests against eSTS or VID + telemetry. +- Do not classify `missing_terminal_span` as session loss. +- Do not report sampled counts as total devices or requests. +- If a sign-in regression is attributed to the client path, set + `EnableBrokerWebViewExternalBrowserRedirect` to `false` in ECS. diff --git a/docs/premortem/ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Premortem.md b/docs/premortem/ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Premortem.md new file mode 100644 index 0000000000..6b5a49c802 --- /dev/null +++ b/docs/premortem/ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Premortem.md @@ -0,0 +1,168 @@ + + +# Premortem - `ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT` + +**Owner:** Sowmya Malayanur | **Approver:** TBD + +**Common PR:** [AzureAD/microsoft-authentication-library-common-for-android#3304](https://github.com/AzureAD/microsoft-authentication-library-common-for-android/pull/3304) | **Work item:** [AB#3781149](https://identitydivision.visualstudio.com/Engineering/_workitems/edit/3781149) + +**Monitoring dashboard:** [ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Dashboard.md](./ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT-Dashboard.md) + +`ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT` defaults to `true`. Set +`EnableBrokerWebViewExternalBrowserRedirect` to `false` in ECS to stop marked URLs from +opening externally and restore the existing WebView behavior without an app release. + +| Flight | ON does | +|---|---| +| `ENABLE_BROKER_WEBVIEW_EXTERNAL_BROWSER_REDIRECT` (`EnableBrokerWebViewExternalBrowserRedirect`) | In brokered and brokerless WebViews, recognizes an HTTPS destination whose `broker_webview_external_browser` query parameter has the literal value `1` and opens the supplied URL through an external `ACTION_VIEW` intent. Unmarked URLs and marker values other than `1` retain their existing behavior. | + +## Intended routing + +1. Preserve all existing special-protocol, redirect URI, install, WebCP, app-link, and + non-HTTPS handling that runs before this feature. +2. Continue through existing WebView behavior when the client flight is disabled or the + marker value is not the literal `1`. +3. For an eligible HTTPS URL, stop the pending WebView load. +4. Pass the supplied URL unchanged to an external `ACTION_VIEW` intent. +5. If an external handler accepts the intent, preserve the original authorization session. + Opening the external activity does not complete or cancel authentication. +6. If no external handler can launch, continue loading the supplied URL in the WebView. + +## Risks, completed validation, and rollback +This is a new client path for a new Verified ID (VID) server-side feature. The server adds +`broker_webview_external_browser=1` only to URLs for that feature, and the client changes +behavior only when that exact marker is present. Existing unmarked sign-in paths retain +their current behavior, so the likelihood of this change affecting an existing sign-in +path is very low and the overall client change is low risk. + +1. **The marker affects an unintended navigation** + - **Likelihood:** Very low. + - **Why it is bounded:** The path requires both the default-on client flight and an HTTPS + URL with the exact query value `broker_webview_external_browser=1`. Substring or + non-literal values do not enter this path. Before public preview is announced, no more + than 10 marked requests per day are expected; GA is planned for February. + - **Production monitoring and rollback:** Sample feature spans by their feature-specific + outcome. Where `correlation_id_v2` is present, cross-reference it with eSTS or VID + telemetry to confirm that the request belongs to the new VID feature. The correlation + ID alone does not identify the server scenario. If a sign-in regression is attributed + to this client path, disable the client flight in ECS to restore existing WebView + routing. + +2. **No external handler is available or Android denies the launch** + - **Likelihood:** Low + - **Why it is bounded:** Before launching, the client checks whether Android can find an + app capable of handling the HTTPS URL. It also handles cases where the app becomes + unavailable or the launch is blocked. In either case, the client records a failed + launch and continues loading the original URL in the WebView. + - **Production monitoring and rollback:** Monitor + `operation_outcome=broker_external_browser_launch_failed`. Disable the client flight + in ECS if failures are confirmed to be caused by client-side external launch. + +3. **The external activity launches but the original authorization session is lost** + - **Likelihood:** Low to medium because lifecycle behavior varies with memory pressure, + activity launch mode, OEM process management, and flow-specific continuation. + - **Why it is bounded:** This path does not invoke the authorization completion callback + after a successful launch. The original activity and WebView are not explicitly + finished by the feature. + + - **Production monitoring and rollback:** Join redirect success spans to later + `AcquireTokenInteractive` spans by `trace_id` for directional investigation of + cancellation or error. A missing terminal span is telemetry-incomplete and is not + evidence of session loss. If session loss is reproducible, disable the client flight + in ECS. + + +## Rollout decision + +Keep the client flight defaulted to `true`; do not use a percentage-based client rollout. + +- The client and eSTS changes ship independently. The client rollout does not gate, stage, + or approve eSTS exposure. +- On client versions containing this change, the new path applies to brokered and + brokerless HTTPS WebView navigations whose destination URL contains + `broker_webview_external_browser=1`. +- Unmarked URLs and non-literal marker values retain existing behavior. +- The client ECS value remains an immediate kill switch that restores existing WebView + behavior without an app release. +- Automated tests cover eligibility boundaries, exact URI preservation, successful launch, + failure, telemetry, and client flight rollback. + +The server team independently controls when eSTS adds the query parameter. Client +monitoring begins when both a client version containing this change and marked eSTS traffic +are present in production. + +## Monitoring guardrails + +There is no production baseline for this feature. Existing `ProcessWebsiteRequest` traffic +cannot provide one because it contains other website-routing scenarios and does not carry +the new feature-specific outcomes. The production `android_spans` schema also does not expose `operation_outcome` until the +telemetry contract is deployed. The accompanying dashboard uses Android Broker telemetry +and therefore monitors broker-hosted execution; brokerless behavior is covered by the +client tests but is not measured by this dashboard. + +1. Once the client build and marked traffic are present in production, verify that + `operation_outcome` is queryable in `android_spans` and that spans classified by a + recognized feature outcome have the expected status. Because there is no independent + feature discriminator, the dashboard cannot detect feature spans that omit + `operation_outcome`. +2. Review every sampled `broker_external_browser_launch_failed` span during the initial + client rollout because no production failure baseline exists. Fewer than 10 marked + requests per day are expected before public preview. +3. Disable `EnableBrokerWebViewExternalBrowserRedirect` if failures are confirmed to be + caused by client marker handling or external intent launch. + +Before a build containing this telemetry reaches production, empty production tiles are +expected. Use the local console exporter or an explicitly sandbox-configured build for +pre-deployment validation. + +## Monitoring plan + +Review the dashboard after a client version containing the change begins receiving marked +traffic. Review tiles in this order: + +1. **Feature span volume and classified outcome consistency** + - Count `ProcessWebsiteRequest` spans with either feature-specific outcome by Broker Host + App Version. + - Before public preview is announced, compare the sampled volume with the expectation of + no more than 10 total marked requests per day. Because the span is sampled at 50%, do + not expect telemetry for every request or treat an empty interval as proof of no usage. + - Verify that each classified feature span has the expected outcome-to-status mapping. + These tiles cannot measure outcome-attribute completeness because `operation_outcome` + is also the feature discriminator. + - For sampled feature spans where `correlation_id_v2` is present, cross-reference it with + eSTS or VID telemetry and confirm that the request belongs to the new VID feature. +2. **External launch success rate** + - Calculate success from `broker_external_browser_launched` divided by all feature + outcomes. + - Track `broker_external_browser_launch_failed` and `ERROR` spans. + - Inspect each sampled failure during the initial rollout because no production failure + baseline exists yet. +3. **Authentication outcomes after handoff** + - Join successful launch spans to `AcquireTokenInteractive` by `trace_id` for directional + investigation of later cancellation or error. + - Treat traces without a terminal span as telemetry-incomplete, not as confirmed session + loss; current telemetry does not provide definitive return/resume measurement. + +## Rollback + +To stop client interception, set +`EnableBrokerWebViewExternalBrowserRedirect` to `false` in ECS. + +Expected client behavior after propagation: + +- Marked URLs stop entering the new external-launch path. +- No new `broker_external_browser_launched` or + `broker_external_browser_launch_failed` outcomes are emitted for affected app versions. +- The marker remains an ordinary query parameter and the existing WebView behavior applies. +- Marked URLs in brokered and brokerless WebViews return to existing WebView behavior; + unmarked flows remain unchanged. +- No app release is required. + +After rollback: + +1. Confirm the effective ECS value is `false` for the affected audience. +2. Confirm feature-specific outcomes stop after ECS propagation, accounting for in-flight + sessions and telemetry delay. +3. Confirm that the reported failure no longer reproduces after rollback. +4. Preserve affected app-version, Android-version, OEM, and scenario dimensions plus + example correlation IDs for investigation. From 42725a4ec5243db3579a25aea2bb2355f2bc2699 Mon Sep 17 00:00:00 2001 From: Shahzaib <37125644+shahzaibj@users.noreply.github.com> Date: Wed, 14 Oct 2026 09:47:07 -0700 Subject: [PATCH 13/16] Add Island Browser SSO signing identities, Fixes AB#3780783 (#3298) [AB#3780783](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3780783) ## Summary - Register one Island production family list with 14 package/certificate identities over eight package names: six Play Store signers plus the shared direct-distribution signer for all eight variants, including IslandDev and Dev Intune. - Island clarified that its historically named debug/userdebug signer is a production pre-store signing key for directly distributed enterprise/MDM APKs. All eight direct-distribution package identities are explicitly approved for production support. - Simplify AppFamily to one apps set. Derive BROWSER_SSO_AUTHORIZED_APPS from Chrome and Island families; preserve App/IAppIdentity and existing Chrome/MSAL test-app behavior. - Remove Island debug-trust gating and family debug-selection machinery. Every Island variant remains subject to the existing default-off Island flight in Broker; no additional Dev-specific flight. - Keep explicit package/certificate checks and exclude Island from unrelated privileged allowlists. ## Verification - The simplified AppFamily model and unchanged App source compiled with cached Kotlin 2.0.21; all six isolated JUnit 4.13.2 model tests passed. - Added exact 14-identity/eight-package tests and production Broker regressions for all identities with debug trust disabled, unlisted/wrong signers, and rollback across every identity. - Full targeted Gradle validation remains blocked before compilation by NewAndroid HTTP 401 for BouncyCastle 1.86 and OpenTelemetry 1.62.0. Android integration compilation/tests remain unverified. - Actual APK certificate matching and partner E2E remain rollout prerequisites. Fingerprint length verifies SHA-512-sized format, not signer authenticity. ## Dependencies and rollout - Companion Broker PR: https://msft.ghe.com/security/ad-accounts-for-android/pull/330 ([AB#3780785](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3780785)). - Merge Common first and ship both changes together; older Broker code consuming the expanded allowlist does not enforce the new Island flight. - No live ECS configuration or production enablement is changed. --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- changelog.txt | 1 + .../common/internal/apps/AppRegistry.kt | 107 ++++++++- .../common/internal/apps/AppRegistryTest.kt | 225 +++++++++++++++++- .../common/java/flighting/CommonFlight.java | 6 + 4 files changed, 324 insertions(+), 15 deletions(-) diff --git a/changelog.txt b/changelog.txt index 99b7a55297..31e94a4288 100644 --- a/changelog.txt +++ b/changelog.txt @@ -1,5 +1,6 @@ vNext ---------- +- [MAJOR] Replace AppRegistry.BROWSER_SSO_AUTHORIZED_APPS with getBrowserSsoAuthorizedApps(), which evaluates default-off EnableIslandBrowserSso per request and preserves Chrome/debug-trusted MSAL test-app support alongside eligible Island production identities (AB#3780783) (#3298) - [MINOR] Add the InstallCertDeepLinkActivity span name for Broker's legacy install-certificate deep-link caller telemetry (AB#3771034) (#3293) - [PATCH] Default authorize-only Device-CA credential forwarding to off for gradual ECS rollout - [PATCH] Enforce authorize-only Device-CA credential forwarding by withholding original request headers from Device-CA WebView loads by default, with explicit ECS disablement as the rollback path (AB#3766458) diff --git a/common/src/main/java/com/microsoft/identity/common/internal/apps/AppRegistry.kt b/common/src/main/java/com/microsoft/identity/common/internal/apps/AppRegistry.kt index 1cded93ca1..5f7139c8d5 100644 --- a/common/src/main/java/com/microsoft/identity/common/internal/apps/AppRegistry.kt +++ b/common/src/main/java/com/microsoft/identity/common/internal/apps/AppRegistry.kt @@ -36,6 +36,8 @@ import com.microsoft.identity.common.adal.internal.AuthenticationConstants.Broke import com.microsoft.identity.common.adal.internal.AuthenticationConstants.Broker.SHARED_EDGE_SIGNATURE import com.microsoft.identity.common.internal.broker.BrokerData import com.microsoft.identity.common.java.broker.App +import com.microsoft.identity.common.java.flighting.CommonFlight +import com.microsoft.identity.common.java.flighting.CommonFlightsManager /** * Registry of known apps and their signing certificate thumbprints. @@ -103,6 +105,51 @@ object AppRegistry { signingCertificateThumbprint = "QfTWFoLyXuOCZ7bMYlMN+la3J3rau5x8p+w2v7vf1gOPiTyIMgdbNDzLaLWhgiC2ioj/hFqk8oZyqdJbFG6G4g==" ) + /** Play Store signing identity for Island. */ + val ISLAND = App( + nickName = "Island", + packageName = "io.island.Island", + signingCertificateThumbprint = "9A0EWFnAmSLLMpJP9YP/zZL2PUxLL+eTfnTgI4wsCylaHdd5o4lwjZLjNkPZ7cu5tPYZHLCrEPJVJJNcgoRrAw==" + ) + + /** Play Store signing identity for Island Canary. */ + val ISLAND_CANARY = App( + nickName = "Island Canary", + packageName = "io.island.IslandCanary", + signingCertificateThumbprint = "TwrYxhsZaPoxnXrFnGt5gzMg9WsV2V0LTHFd0KvqACW9cKfCQc9yPkV+e+f7lAfalMs3zdMfIzUpJZIT7tbOfQ==" + ) + + /** Play Store signing identity for Island Beta. */ + val ISLAND_BETA = App( + nickName = "Island Beta", + packageName = "io.island.IslandBeta", + signingCertificateThumbprint = "KcVfTD7f9blSNklGx92FzIx1qwo1l7Vtp+sOUq+P2RNb7sSFZNLIBU6JdftdcNmmmv7rpMVcHTs7H1MJMfRkjA==" + ) + + /** Play Store signing identity for Island with Intune integration. */ + val ISLAND_INTUNE = App( + nickName = "Island Intune", + packageName = "io.island.island.intune", + signingCertificateThumbprint = "q4Ycw2UxQJfVXEcREJwIeszP88D8QKdQw82y3m9Zmg8Sg+2YYP+wq9TATX9PgGjpgd2YfgcrXgsbuubbzdRqtA==" + ) + + /** Play Store signing identity for Island Canary with Intune integration. */ + val ISLAND_CANARY_INTUNE = App( + nickName = "Island Canary Intune", + packageName = "io.island.island.canary.intune", + signingCertificateThumbprint = "XVdkJe6bsmBS3/a2utbFAfXVTg0IaXJS6hvzjx0Uyg+7q7187oXRAAxROMj8NkTiRlI43SCippiDTtRam5asww==" + ) + + /** Play Store signing identity for Island Beta with Intune integration. */ + val ISLAND_BETA_INTUNE = App( + nickName = "Island Beta Intune", + packageName = "io.island.island.beta.intune", + signingCertificateThumbprint = "djswQiqC4rjGg2rNmkm+Y090echgP5JGoVesHJ2NnC1q7lQWJ/2a70HSOzMdXbYGtl0aZydlkR2sbMqRbeb4Lg==" + ) + + private const val ISLAND_DIRECT_DISTRIBUTION_SIGNATURE = + "+P6Af2Jk8nb0tvnmyhZ6d6mrsJ5znPI597Vq7t5EvgcgsM3LYBmwnBnrI5z/RGBZTzwHVG3+nz8Ostf13u/4YQ==" + val INTUNE_CE_PROD = App( nickName = "Intune Company Portal (prod)", packageName = INTUNE_APP_PACKAGE_NAME, @@ -219,19 +266,65 @@ object AppRegistry { } } + /** Chrome browser variants with their individual signing identities. */ + @JvmField + val CHROME_BROWSER_SSO_APPS = setOf(CHROME, CHROME_BETA, CHROME_DEV, CHROME_CANARY) + /** - * Apps authorized to request Browser SSO headers (PRT credentials). - * Currently limited to Chrome browser variants. + * Island production identities: six Play Store signers and the shared direct-distribution + * signer for eight packages, including both Dev variants. The partner's historically named + * "debug" signer is a production distribution key, not a Broker debug-trust identity. + * Broker must enforce the Island flight for every variant. */ @JvmField - val BROWSER_SSO_AUTHORIZED_APPS = buildSet { - add(CHROME) - add(CHROME_BETA) - add(CHROME_DEV) - add(CHROME_CANARY) + val ISLAND_BROWSER_SSO_APPS = buildSet { + val playStoreApps = listOf( + ISLAND, ISLAND_CANARY, ISLAND_BETA, + ISLAND_INTUNE, ISLAND_CANARY_INTUNE, ISLAND_BETA_INTUNE + ) + addAll(playStoreApps) + playStoreApps.forEach { app -> + add( + App( + nickName = "${app.nickName} (direct distribution)", + packageName = app.packageName, + signingCertificateThumbprint = ISLAND_DIRECT_DISTRIBUTION_SIGNATURE + ) + ) + } + add( + App( + nickName = "Island Dev (direct distribution)", + packageName = "io.island.IslandDev", + signingCertificateThumbprint = ISLAND_DIRECT_DISTRIBUTION_SIGNATURE + ) + ) + add( + App( + nickName = "Island Dev Intune (direct distribution)", + packageName = "io.island.island.dev.intune", + signingCertificateThumbprint = ISLAND_DIRECT_DISTRIBUTION_SIGNATURE + ) + ) + } + + /** + * Returns Browser SSO identities eligible for the current request. + * Evaluates the current Island flight through the shared Common flight manager. + * Without a host-initialized provider, the flight's default denies Island. + * Every returned identity still requires package and signing-certificate validation. + * + * @return Chrome, the MSAL test app when debug trust permits it, and Island only when enabled. + */ + @JvmStatic + fun getBrowserSsoAuthorizedApps(): Set = buildSet { + addAll(CHROME_BROWSER_SSO_APPS) if (BrokerData.getShouldTrustDebugBrokers()) { add(MSAL_TEST_APP) } + if (CommonFlightsManager.getFlightsProvider().isFlightEnabled(CommonFlight.ENABLE_ISLAND_BROWSER_SSO)) { + addAll(ISLAND_BROWSER_SSO_APPS) + } } /** diff --git a/common/src/test/java/com/microsoft/identity/common/internal/apps/AppRegistryTest.kt b/common/src/test/java/com/microsoft/identity/common/internal/apps/AppRegistryTest.kt index 7546d80cf3..38b92afd25 100644 --- a/common/src/test/java/com/microsoft/identity/common/internal/apps/AppRegistryTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/internal/apps/AppRegistryTest.kt @@ -23,19 +23,30 @@ package com.microsoft.identity.common.internal.apps import android.os.Build +import android.util.Base64 import com.microsoft.identity.common.BuildConfig import com.microsoft.identity.common.adal.internal.AuthenticationConstants import com.microsoft.identity.common.internal.broker.BrokerData import com.microsoft.identity.common.java.broker.App +import com.microsoft.identity.common.java.flighting.CommonFlight +import com.microsoft.identity.common.java.flighting.CommonFlightsManager +import com.microsoft.identity.common.java.flighting.IFlightsManager +import com.microsoft.identity.common.java.flighting.IFlightsProvider +import org.junit.After import org.junit.AfterClass import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.BeforeClass +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import java.lang.reflect.Modifier /** * Unit tests for [AppRegistry]. @@ -43,6 +54,22 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.P]) class AppRegistryTest { + private var islandEnabled = false + + @Before + fun setUpFlights() { + val provider = mock() + whenever(provider.isFlightEnabled(CommonFlight.ENABLE_ISLAND_BROWSER_SSO)) + .thenAnswer { islandEnabled } + val manager = mock() + whenever(manager.getFlightsProvider(any())).thenReturn(provider) + CommonFlightsManager.initializeCommonFlightsManager(manager) + } + + @After + fun resetFlights() { + CommonFlightsManager.resetFlightsManager() + } @Test fun edgeApps_haveSharedSignatureAndDistinctPackages() { @@ -245,14 +272,159 @@ class AppRegistryTest { } @Test - fun browserSsoAuthorizedApps_whenDebugBrokersTrusted_containsChromeVariantsAndMsalTestApp() { - assertEquals(5, AppRegistry.BROWSER_SSO_AUTHORIZED_APPS.size) - assertTrue(AppRegistry.BROWSER_SSO_AUTHORIZED_APPS.contains(AppRegistry.CHROME)) - assertTrue(AppRegistry.BROWSER_SSO_AUTHORIZED_APPS.contains(AppRegistry.CHROME_BETA)) - assertTrue(AppRegistry.BROWSER_SSO_AUTHORIZED_APPS.contains(AppRegistry.CHROME_DEV)) - assertTrue(AppRegistry.BROWSER_SSO_AUTHORIZED_APPS.contains(AppRegistry.CHROME_CANARY)) - assertTrue(AppRegistry.BROWSER_SSO_AUTHORIZED_APPS.contains(AppRegistry.MSAL_TEST_APP)) - assertFalse(AppRegistry.BROWSER_SSO_AUTHORIZED_APPS.contains(AppRegistry.EDGE)) + fun browserSsoAuthorizedApps_whenDebugBrokersTrusted_containsChromeAndMsalTestAppOnly() { + val authorizedApps = AppRegistry.getBrowserSsoAuthorizedApps() + assertEquals(5, authorizedApps.size) + assertTrue(authorizedApps.containsAll(AppRegistry.CHROME_BROWSER_SSO_APPS)) + assertTrue(authorizedApps.contains(AppRegistry.MSAL_TEST_APP)) + assertFalse(authorizedApps.contains(AppRegistry.EDGE)) + assertTrue(authorizedApps.intersect(AppRegistry.ISLAND_BROWSER_SSO_APPS).isEmpty()) + } + + @Test + fun islandPlayStoreApps_haveExactlyTheProvidedPackageAndCertificatePairs() { + val expectedIdentities = mapOf( + "io.island.Island" to "9A0EWFnAmSLLMpJP9YP/zZL2PUxLL+eTfnTgI4wsCylaHdd5o4lwjZLjNkPZ7cu5tPYZHLCrEPJVJJNcgoRrAw==", + "io.island.IslandCanary" to "TwrYxhsZaPoxnXrFnGt5gzMg9WsV2V0LTHFd0KvqACW9cKfCQc9yPkV+e+f7lAfalMs3zdMfIzUpJZIT7tbOfQ==", + "io.island.IslandBeta" to "KcVfTD7f9blSNklGx92FzIx1qwo1l7Vtp+sOUq+P2RNb7sSFZNLIBU6JdftdcNmmmv7rpMVcHTs7H1MJMfRkjA==", + "io.island.island.intune" to "q4Ycw2UxQJfVXEcREJwIeszP88D8QKdQw82y3m9Zmg8Sg+2YYP+wq9TATX9PgGjpgd2YfgcrXgsbuubbzdRqtA==", + "io.island.island.canary.intune" to "XVdkJe6bsmBS3/a2utbFAfXVTg0IaXJS6hvzjx0Uyg+7q7187oXRAAxROMj8NkTiRlI43SCippiDTtRam5asww==", + "io.island.island.beta.intune" to "djswQiqC4rjGg2rNmkm+Y090echgP5JGoVesHJ2NnC1q7lQWJ/2a70HSOzMdXbYGtl0aZydlkR2sbMqRbeb4Lg==" + ) + + val islandPlayStoreApps = AppRegistry.ISLAND_BROWSER_SSO_APPS.filter { + it.signingCertificateThumbprint != DIRECT_DISTRIBUTION_SIGNATURE + } + assertEquals(6, islandPlayStoreApps.size) + assertEquals( + expectedIdentities, + islandPlayStoreApps.associate { + it.packageName to it.signingCertificateThumbprint + } + ) + } + + @Test + fun islandDirectDistributionApps_haveExactlyEightPackagesAndTheSharedProductionCertificate() { + val expectedPackages = setOf( + "io.island.Island", + "io.island.IslandCanary", + "io.island.IslandBeta", + "io.island.island.intune", + "io.island.island.canary.intune", + "io.island.island.beta.intune", + "io.island.IslandDev", + "io.island.island.dev.intune" + ) + val directDistributionApps = AppRegistry.ISLAND_BROWSER_SSO_APPS.filter { + it.signingCertificateThumbprint == DIRECT_DISTRIBUTION_SIGNATURE + } + assertEquals(8, directDistributionApps.size) + assertEquals( + expectedPackages, + directDistributionApps.map { it.packageName }.toSet() + ) + islandEnabled = true + assertTrue(AppRegistry.getBrowserSsoAuthorizedApps().containsAll(directDistributionApps)) + } + + @Test + fun islandBrowserSsoApps_haveSha512SizedCertificateThumbprints() { + AppRegistry.ISLAND_BROWSER_SSO_APPS.forEach { + assertEquals(it.packageName, 64, Base64.decode(it.signingCertificateThumbprint, Base64.NO_WRAP).size) + } + } + + @Test + fun islandBrowserSsoApps_areNotAddedToOtherPrivilegedAuthorizationLists() { + val islandPackages = AppRegistry.ISLAND_BROWSER_SSO_APPS.map { it.packageName }.toSet() + val existingAuthorizationLists = listOf( + AppRegistry.SSO_TOKEN_AUTHORIZED_APPS, + AppRegistry.GET_DEVICE_TOKEN_AUTHORIZED_APPS, + AppRegistry.DEVICE_REGISTRATION_AUTHORIZED_APPS, + AppRegistry.FORCE_BROKER_DISCOVERY_ALLOW_LIST + ) + + existingAuthorizationLists.forEach { authorizedApps -> + assertTrue(authorizedApps.none { it.packageName in islandPackages }) + } + } + + @Test + fun browserIdentitySets_haveExactlyTheRegisteredVariants() { + assertEquals( + setOf(AppRegistry.CHROME, AppRegistry.CHROME_BETA, + AppRegistry.CHROME_DEV, AppRegistry.CHROME_CANARY), + AppRegistry.CHROME_BROWSER_SSO_APPS + ) + assertEquals(14, AppRegistry.ISLAND_BROWSER_SSO_APPS.size) + assertEquals(8, AppRegistry.ISLAND_BROWSER_SSO_APPS.map { it.packageName }.toSet().size) + assertEquals( + setOf(AppRegistry.ISLAND, AppRegistry.ISLAND_CANARY, AppRegistry.ISLAND_BETA, + AppRegistry.ISLAND_INTUNE, AppRegistry.ISLAND_CANARY_INTUNE, + AppRegistry.ISLAND_BETA_INTUNE), + AppRegistry.ISLAND_BROWSER_SSO_APPS.filter { + it.signingCertificateThumbprint != DIRECT_DISTRIBUTION_SIGNATURE + }.toSet() + ) + } + + @Test + fun browserSsoEligibility_usesTheCurrentFlightWithoutChangingTheBaseline() { + val baseline = AppRegistry.getBrowserSsoAuthorizedApps() + islandEnabled = true + assertEquals( + baseline + AppRegistry.ISLAND_BROWSER_SSO_APPS, + AppRegistry.getBrowserSsoAuthorizedApps() + ) + assertEquals(19, AppRegistry.getBrowserSsoAuthorizedApps().size) + islandEnabled = false + assertEquals(baseline, AppRegistry.getBrowserSsoAuthorizedApps()) + assertEquals(5, baseline.size) + assertTrue(baseline.intersect(AppRegistry.ISLAND_BROWSER_SSO_APPS).isEmpty()) + } + + @Test + fun browserSsoEligibility_exposesAJavaStaticEntryPoint() { + val method = AppRegistry::class.java.getDeclaredMethod( + "getBrowserSsoAuthorizedApps" + ) + assertTrue(Modifier.isStatic(method.modifiers)) + assertEquals(AppRegistry.getBrowserSsoAuthorizedApps(), method.invoke(null)) + islandEnabled = true + assertEquals(AppRegistry.getBrowserSsoAuthorizedApps(), method.invoke(null)) + } + + @Test + fun browserSsoEligibility_preservesMsalTestAppUnderCurrentDebugTrust() { + val originalDebugTrust = BrokerData.getShouldTrustDebugBrokers() + try { + listOf(false, true, false).forEach { trustDebug -> + BrokerData.setShouldTrustDebugBrokers(trustDebug) + listOf(false, true).forEach { enabled -> + islandEnabled = enabled + val authorizedApps = AppRegistry.getBrowserSsoAuthorizedApps() + assertEquals(trustDebug, authorizedApps.contains(AppRegistry.MSAL_TEST_APP)) + assertTrue(authorizedApps.containsAll(AppRegistry.CHROME_BROWSER_SSO_APPS)) + assertEquals( + enabled, + authorizedApps.containsAll(AppRegistry.ISLAND_BROWSER_SSO_APPS) + ) + } + } + } finally { + BrokerData.setShouldTrustDebugBrokers(originalDebugTrust) + } + } + + @Test + fun islandEligibility_withoutAHostFlightProvider_usesTheDisabledDefault() { + CommonFlightsManager.resetFlightsManager() + assertEquals("EnableIslandBrowserSso", CommonFlight.ENABLE_ISLAND_BROWSER_SSO.key) + assertEquals(false, CommonFlight.ENABLE_ISLAND_BROWSER_SSO.defaultValue) + val apps = AppRegistry.getBrowserSsoAuthorizedApps() + assertTrue(apps.containsAll(AppRegistry.CHROME_BROWSER_SSO_APPS)) + assertTrue(apps.intersect(AppRegistry.ISLAND_BROWSER_SSO_APPS).isEmpty()) } @Test @@ -279,6 +451,9 @@ class AppRegistryTest { } companion object { + private const val DIRECT_DISTRIBUTION_SIGNATURE = + "+P6Af2Jk8nb0tvnmyhZ6d6mrsJ5znPI597Vq7t5EvgcgsM3LYBmwnBnrI5z/RGBZTzwHVG3+nz8Ostf13u/4YQ==" + @JvmStatic @BeforeClass fun setUpClass() { @@ -296,6 +471,40 @@ class AppRegistryTest { @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.S]) class AppRegistryProductionTrustTest { + private var islandEnabled = false + + @Before + fun setUpFlights() { + val provider = mock() + whenever(provider.isFlightEnabled(CommonFlight.ENABLE_ISLAND_BROWSER_SSO)) + .thenAnswer { islandEnabled } + val manager = mock() + whenever(manager.getFlightsProvider(any())).thenReturn(provider) + CommonFlightsManager.initializeCommonFlightsManager(manager) + } + + @After + fun resetFlights() { + CommonFlightsManager.resetFlightsManager() + } + + @Test + fun browserSsoEligibility_initializedWithoutDebugTrust_islandRequiresOnlyItsFlight() { + assertFalse(BrokerData.getShouldTrustDebugBrokers()) + + val baseline = AppRegistry.getBrowserSsoAuthorizedApps() + assertEquals(4, baseline.size) + assertTrue(baseline.intersect(AppRegistry.ISLAND_BROWSER_SSO_APPS).isEmpty()) + islandEnabled = true + val authorizedApps = AppRegistry.getBrowserSsoAuthorizedApps() + assertEquals(18, authorizedApps.size) + assertEquals(14, AppRegistry.ISLAND_BROWSER_SSO_APPS.size) + assertTrue(authorizedApps.containsAll(AppRegistry.ISLAND_BROWSER_SSO_APPS)) + assertTrue(authorizedApps.containsAll(AppRegistry.CHROME_BROWSER_SSO_APPS)) + assertFalse(authorizedApps.contains(AppRegistry.MSAL_TEST_APP)) + islandEnabled = false + assertEquals(baseline, AppRegistry.getBrowserSsoAuthorizedApps()) + } @Test fun deviceAllowlists_whenDebugBrokersNotTrusted_containOnlyProductionMdepApps() { diff --git a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java index a2a872712f..2ce0f0ab5c 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java +++ b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java @@ -37,6 +37,12 @@ * running in the app process should take the decision from the host SDK instead. */ public enum CommonFlight implements IFlightConfig { + /** + * Allows registered Island production browser identities to request Browser SSO headers. + * Disabled by default; the Broker Browser SSO entry point also requires its global SSO flight. + */ + ENABLE_ISLAND_BROWSER_SSO("EnableIslandBrowserSso", false), + /** * Flight to control whether or not to use Network capability for performing network check. */ From 076482fcb106dff3ed92a2a9a9e217d2ad83a723 Mon Sep 17 00:00:00 2001 From: pedro romero vargas <76129899+p3dr0rv@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:59:57 -0700 Subject: [PATCH 14/16] Move native ATS caller validation to Broker ingress, AB#3751475, Fixes AB#3751475 (#3311) ## Summary - Remove native MSAL silent-caller UID/package and redirect checks from Common command-parameter validation; Broker performs these checks at first-hop request admission, before local execution or passthrough. - Retain parameter preconditions and the existing WEB_APPS silent allowlist check in Common. - Update Common flight/API documentation and parameter tests to reflect the new ownership boundary. ## Validation - `:common4j:compileJava` passed. - `:common4j:test --tests com.microsoft.identity.common.java.commands.parameters.BrokerSilentTokenCommandParametersTest` passed. ## Rollout dependency **Do not merge or ship this change without the paired Broker ingress-validation change.** A Broker without first-hop validation must not consume a Common version that removes the command-level native caller check. WEB_APPS validation remains in Common; moving it to first-hop WebApps admission is deferred for follow-up review. [AB#3751475](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3751475) --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../BrokerSilentTokenCommandParameters.java | 25 ---- .../common/java/flighting/CommonFlight.java | 12 +- .../common/java/util/IPlatformUtil.java | 6 +- ...rokerSilentTokenCommandParametersTest.java | 120 ++++++------------ .../flighting/CommonFlightsManagerTest.java | 16 +++ 5 files changed, 63 insertions(+), 116 deletions(-) diff --git a/common4j/src/main/com/microsoft/identity/common/java/commands/parameters/BrokerSilentTokenCommandParameters.java b/common4j/src/main/com/microsoft/identity/common/java/commands/parameters/BrokerSilentTokenCommandParameters.java index 249c15ff76..b09032da89 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/commands/parameters/BrokerSilentTokenCommandParameters.java +++ b/common4j/src/main/com/microsoft/identity/common/java/commands/parameters/BrokerSilentTokenCommandParameters.java @@ -129,30 +129,5 @@ && getRequestType() == BrokerRequestType.WEB_APPS) { platformUtil.isValidCallingAppForWebApps(getCallerUid()); return; } - // SECURITY (AB#3687466): reject any silent request whose self-reported caller package (from the - // untrusted request bundle) is not owned by the kernel-attested calling uid, before the redirect-URI - // check runs against the verified caller. getCallerUid() is the Binder-attested uid: every silent - // entry point overwrites CALLER_INFO_UID with Binder.getCallingUid() before the parameters are - // built. When the VALIDATE_SILENT_CALLER flight is enabled (ECS-backed, secure-by-default - // kill-switch), we use the caller-validating isValidCallingApp overload, which enforces uid->package - // ownership first (throwing unknown_caller / ClientException) and then applies the redirect-URI - // check. With the flight off we fall back to the redirect-only two-argument overload (pre-fix - // behavior). The uid->package resolution lives behind IPlatformUtil (mirroring - // isValidCallingAppForWebApps). - final boolean isCallerValid; - if (CommonFlightsManager.INSTANCE.getFlightsProvider() - .isFlightEnabled(CommonFlight.VALIDATE_SILENT_CALLER)) { - isCallerValid = platformUtil.isValidCallingApp( - getRedirectUri(), getCallerPackageName(), getCallerUid()); - } else { - isCallerValid = platformUtil.isValidCallingApp(getRedirectUri(), getCallerPackageName()); - } - if (!isCallerValid) { - throw new ArgumentException( - ArgumentException.ACQUIRE_TOKEN_SILENT_OPERATION_NAME, - "mRedirectUri", "The redirect URI doesn't match the uri" + - " generated with caller package name and signature" - ); - } } } diff --git a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java index 2ce0f0ab5c..14be0a69e2 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java +++ b/common4j/src/main/com/microsoft/identity/common/java/flighting/CommonFlight.java @@ -205,13 +205,15 @@ public enum CommonFlight implements IFlightConfig { DISABLE_WEB_APPS_API("DisableWebAppsApi", false), /** - * Flight controlling silent-caller validation: when enabled (default), a silent broker token + * Flight controlling silent-caller validation: when enabled, a silent broker token * request whose self-reported caller package is not owned by the kernel-attested calling uid - * ({@code Binder.getCallingUid()}) is rejected with {@code unknown_caller} (AB#3687466). Acts as a - * secure-by-default, ECS-backed kill-switch for the check in - * {@code BrokerSilentTokenCommandParameters.validate()}. + * ({@code Binder.getCallingUid()}) fails the platform check with {@code unknown_caller} + * (AB#3687466). Broker ATS admission returns an {@code ArgumentException} for that failure. + * Broker applies this gate when admitting the original request, before local execution or + * passthrough. Disabled by default while rolling out; redirect validation still runs. + * Token command parameter validation does not repeat this caller check. */ - VALIDATE_SILENT_CALLER("ValidateSilentCaller", true), + VALIDATE_SILENT_CALLER("ValidateSilentCaller", false), /** * Flight to control whether or not to use in memory cache for accounts and credentials. diff --git a/common4j/src/main/com/microsoft/identity/common/java/util/IPlatformUtil.java b/common4j/src/main/com/microsoft/identity/common/java/util/IPlatformUtil.java index b41cf771e9..9ca1d4880d 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/util/IPlatformUtil.java +++ b/common4j/src/main/com/microsoft/identity/common/java/util/IPlatformUtil.java @@ -85,9 +85,9 @@ public interface IPlatformUtil { * *

The default implementation performs no uid check and simply delegates to * {@link #isValidCallingApp(String, String)} — appropriate for platforms with no per-app uid model - * (e.g. Linux) and for test doubles. Currently wired to the silent broker token path (gated by - * {@code VALIDATE_SILENT_CALLER}); the two-argument overload is used directly for the interactive path - * and for the silent path when the flight is disabled. + * (e.g. Linux) and for test doubles. Broker uses this overload to admit the original silent + * caller before local execution or passthrough when {@code VALIDATE_SILENT_CALLER} is enabled; + * the two-argument overload remains available when the flight is disabled. * * @param redirectUri the redirect URI to validate ownership of. * @param packageName the self-reported caller package from the (untrusted) request bundle. diff --git a/common4j/src/test/com/microsoft/identity/common/java/commands/parameters/BrokerSilentTokenCommandParametersTest.java b/common4j/src/test/com/microsoft/identity/common/java/commands/parameters/BrokerSilentTokenCommandParametersTest.java index beda1864ff..c64fb5df60 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/commands/parameters/BrokerSilentTokenCommandParametersTest.java +++ b/common4j/src/test/com/microsoft/identity/common/java/commands/parameters/BrokerSilentTokenCommandParametersTest.java @@ -22,14 +22,11 @@ // THE SOFTWARE. package com.microsoft.identity.common.java.commands.parameters; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import com.microsoft.identity.common.java.authorities.Authority; @@ -37,12 +34,12 @@ import com.microsoft.identity.common.java.cache.BrokerOAuth2TokenCache; import com.microsoft.identity.common.java.exception.ArgumentException; import com.microsoft.identity.common.java.exception.ClientException; -import com.microsoft.identity.common.java.exception.ErrorStrings; import com.microsoft.identity.common.java.flighting.CommonFlight; import com.microsoft.identity.common.java.flighting.CommonFlightsManager; import com.microsoft.identity.common.java.flighting.MockFlightsManager; import com.microsoft.identity.common.java.flighting.MockFlightsProvider; import com.microsoft.identity.common.java.interfaces.IPlatformComponents; +import com.microsoft.identity.common.java.request.BrokerRequestType; import com.microsoft.identity.common.java.util.IPlatformUtil; import org.junit.After; @@ -53,17 +50,8 @@ import java.util.Collections; /** - * Unit tests for the silent-caller validation gate in {@link BrokerSilentTokenCommandParameters#validate()}. - * - *

Shape C moved the enforcement decision into this (common4j) {@code validate()}: when the - * {@link CommonFlight#VALIDATE_SILENT_CALLER} flight is enabled (default), it delegates to the - * caller-validating {@link IPlatformUtil#isValidCallingApp(String, String, int)} overload with the - * request's {@code callerUid} (which the broker entry points overwrite with the kernel-attested - * {@code Binder.getCallingUid()}) and {@code callerPackageName}; that overload enforces uid->package - * ownership before the redirect-URI check. With the flight off it falls back to the redirect-only - * two-argument overload. These tests verify that wiring against a mock {@link IPlatformUtil} — the - * platform-specific {@code getPackagesForUid} membership behavior is covered separately by - * {@code AndroidPlatformUtilTest} against the real implementation. + * Unit tests for silent token command preconditions after native caller validation moved + * to the Broker request boundary. WEB_APPS retains its dedicated platform validation. */ @RunWith(JUnit4.class) public class BrokerSilentTokenCommandParametersTest { @@ -77,89 +65,55 @@ public void tearDown() { CommonFlightsManager.INSTANCE.resetFlightsManager(); } - /** - * Flight on + caller accepted: the gate calls the caller-validating overload with the request's - * {@code redirectUri}, {@code callerPackageName} and {@code callerUid}, then validate() completes - * without throwing. - */ @Test - public void validate_flightOn_callerAccepted_delegatesWithCallerUidAndPackage() throws Exception { - setValidateSilentCallerFlight(true); + public void validate_nativeRequestDoesNotRepeatCallerCheckRegardlessOfFlight() throws Exception { final IPlatformUtil platformUtil = mock(IPlatformUtil.class); - when(platformUtil.isValidCallingApp(anyString(), anyString(), anyInt())).thenReturn(true); - - final BrokerSilentTokenCommandParameters params = params(platformUtil); - params.validate(); - - verify(platformUtil).isValidCallingApp(eq(REDIRECT_URI), eq(CALLER_PACKAGE), eq(CALLER_UID)); + for (final boolean enabled : new boolean[]{true, false}) { + setFlight(CommonFlight.VALIDATE_SILENT_CALLER, enabled); + params(platformUtil).validate(); + } + verifyNoInteractions(platformUtil); } - /** - * Flight on + caller rejected: validate() propagates the {@code UNKNOWN_CALLER} - * {@link ClientException} (a spoofed caller is rejected before token issuance). - */ @Test - public void validate_flightOn_callerRejected_throwsUnknownCaller() { - setValidateSilentCallerFlight(true); + public void validate_nativeRequestRetainsParameterPreconditions() throws Exception { final IPlatformUtil platformUtil = mock(IPlatformUtil.class); - try { - when(platformUtil.isValidCallingApp(anyString(), anyString(), anyInt())) - .thenThrow(new ClientException(ErrorStrings.UNKNOWN_CALLER, "spoofed")); - - params(platformUtil).validate(); - fail("Expected ClientException(UNKNOWN_CALLER) to propagate from the caller-validation gate."); - } catch (final ClientException e) { - assertEquals(ErrorStrings.UNKNOWN_CALLER, e.getErrorCode()); - } catch (final ArgumentException e) { - fail("Expected ClientException(UNKNOWN_CALLER), not ArgumentException: " + e.getMessage()); - } + final BrokerSilentTokenCommandParameters valid = params(platformUtil); + assertInvalid(valid.toBuilder().callerUid(0).build()); + assertInvalid(valid.toBuilder().authority(null).build()); + assertInvalid(valid.toBuilder().scopes(Collections.emptySet()).build()); + assertInvalid(valid.toBuilder().clientId("").build()); + assertInvalid(valid.toBuilder().oAuth2TokenCache(null).build()); + assertInvalid(valid.toBuilder().brokerAccount(null).build()); + verifyNoInteractions(platformUtil); } - /** - * Flight off (kill-switch): the caller-validating overload is never invoked — the gate falls back to - * the redirect-only two-argument overload even for a caller that would otherwise be rejected, restoring - * the pre-fix behavior. - */ @Test - public void validate_flightOff_callerCheckSkipped() throws Exception { - setValidateSilentCallerFlight(false); + public void validate_webAppsUsesDedicatedCallerCheck() throws Exception { final IPlatformUtil platformUtil = mock(IPlatformUtil.class); - when(platformUtil.isValidCallingApp(anyString(), anyString())).thenReturn(true); - // Would reject if consulted; the flight-off gate must not consult the caller-validating overload. - when(platformUtil.isValidCallingApp(anyString(), anyString(), anyInt())) - .thenThrow(new ClientException(ErrorStrings.UNKNOWN_CALLER, "spoofed")); - - params(platformUtil).validate(); - - verify(platformUtil, never()).isValidCallingApp(anyString(), anyString(), anyInt()); + params(platformUtil).toBuilder().requestType(BrokerRequestType.WEB_APPS).build().validate(); + verify(platformUtil).isValidCallingAppForWebApps(eq(CALLER_UID)); } - /** - * Sanity: the gate reads {@code getCallerUid()} (the trusted uid), not some other field. A params - * object whose callerUid differs from a stale value still forwards callerUid to the platform util. - */ @Test - public void validate_flightOn_forwardsGetCallerUid() throws Exception { - setValidateSilentCallerFlight(true); + public void validate_disabledWebAppsDoesNotInvokeDedicatedCallerCheck() throws Exception { + setFlight(CommonFlight.DISABLE_WEB_APPS_API, true); final IPlatformUtil platformUtil = mock(IPlatformUtil.class); - when(platformUtil.isValidCallingApp(anyString(), anyString(), anyInt())).thenReturn(true); - - final BrokerSilentTokenCommandParameters params = params(platformUtil); - assertEquals("Precondition: params must expose the configured caller uid.", - CALLER_UID, params.getCallerUid()); - - params.validate(); - - verify(platformUtil).isValidCallingApp(eq(REDIRECT_URI), eq(CALLER_PACKAGE), eq(params.getCallerUid())); + params(platformUtil).toBuilder().requestType(BrokerRequestType.WEB_APPS).build().validate(); + verifyNoInteractions(platformUtil); } - // ---- helpers ------------------------------------------------------------------------------ + private void assertInvalid(final BrokerSilentTokenCommandParameters parameters) throws ClientException { + try { + parameters.validate(); + fail("Expected invalid token command parameters to be rejected."); + } catch (final ArgumentException expected) { + // Parameter preconditions remain in Common even though caller admission moved to Broker. + } + } /** - * Builds a minimal but valid {@link BrokerSilentTokenCommandParameters} that reaches the silent-caller - * gate: every earlier {@code validate()} precondition (callerUid, authority, scopes, clientId, broker - * cache, broker account) is satisfied, {@code requestType} is left non-WebApps so the WebApps early - * return does not apply, and the platform util is the supplied mock. + * Builds valid parameters for the broker request after caller admission. */ private BrokerSilentTokenCommandParameters params(final IPlatformUtil platformUtil) { final IPlatformComponents components = mock(IPlatformComponents.class); @@ -178,9 +132,9 @@ private BrokerSilentTokenCommandParameters params(final IPlatformUtil platformUt .build(); } - private void setValidateSilentCallerFlight(final boolean enabled) { + private void setFlight(final CommonFlight flight, final boolean enabled) { final MockFlightsProvider provider = new MockFlightsProvider(); - provider.addFlight(CommonFlight.VALIDATE_SILENT_CALLER.getKey(), Boolean.toString(enabled)); + provider.addFlight(flight.getKey(), Boolean.toString(enabled)); final MockFlightsManager manager = new MockFlightsManager(); manager.setMockBrokerFlightsProvider(provider); diff --git a/common4j/src/test/com/microsoft/identity/common/java/flighting/CommonFlightsManagerTest.java b/common4j/src/test/com/microsoft/identity/common/java/flighting/CommonFlightsManagerTest.java index 49dc95c00f..273c7064fb 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/flighting/CommonFlightsManagerTest.java +++ b/common4j/src/test/com/microsoft/identity/common/java/flighting/CommonFlightsManagerTest.java @@ -54,6 +54,22 @@ public void tearDown() { CommonFlightsManager.INSTANCE.resetFlightsManager(); } + @Test + public void testSilentCallerValidationDefaultsOffButCanBeEnabled() { + CommonFlightsManager.INSTANCE.resetFlightsManager(); + Assert.assertEquals(Boolean.FALSE, CommonFlight.VALIDATE_SILENT_CALLER.getDefaultValue()); + Assert.assertFalse(CommonFlightsManager.INSTANCE.getFlightsProvider() + .isFlightEnabled(CommonFlight.VALIDATE_SILENT_CALLER)); + + final MockFlightsProvider provider = new MockFlightsProvider(); + provider.addFlight(CommonFlight.VALIDATE_SILENT_CALLER.getKey(), "true"); + final MockFlightsManager manager = new MockFlightsManager(); + manager.setMockBrokerFlightsProvider(provider); + CommonFlightsManager.INSTANCE.initializeCommonFlightsManager(manager); + Assert.assertTrue(CommonFlightsManager.INSTANCE.getFlightsProvider() + .isFlightEnabled(CommonFlight.VALIDATE_SILENT_CALLER)); + } + @Test public void testMultipleWindows_defaultsOffWithoutConsumerFlightsManager() { CommonFlightsManager.INSTANCE.resetFlightsManager(); From 98bc54fcb9732de3a2733e63f43ffe92c70993fe Mon Sep 17 00:00:00 2001 From: pedro romero vargas <76129899+p3dr0rv@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:59:52 -0700 Subject: [PATCH 15/16] Fix AppRegistry test initialization order, Fixes AB#3791209 (#3314) ## Summary - initialize trust-dependent AppRegistry snapshots while debug broker trust is enabled - prevent test ordering from producing a production-only force-discovery allow-list ## Validation - AppRegistryTest: 20 tests passed - BUILD SUCCESSFUL ## Work item [AB#3791209](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3791209) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../microsoft/identity/common/internal/apps/AppRegistryTest.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/common/src/test/java/com/microsoft/identity/common/internal/apps/AppRegistryTest.kt b/common/src/test/java/com/microsoft/identity/common/internal/apps/AppRegistryTest.kt index 38b92afd25..b14f519b4f 100644 --- a/common/src/test/java/com/microsoft/identity/common/internal/apps/AppRegistryTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/internal/apps/AppRegistryTest.kt @@ -458,6 +458,8 @@ class AppRegistryTest { @BeforeClass fun setUpClass() { BrokerData.setShouldTrustDebugBrokers(true) + // Initialize trust-dependent snapshots before any test temporarily changes debug trust. + AppRegistry.FORCE_BROKER_DISCOVERY_ALLOW_LIST } @JvmStatic From cc25e6e77ab023f5b16332329a200112f45f7c56 Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Mon, 19 Oct 2026 07:57:04 -0700 Subject: [PATCH 16/16] Preserve Native Auth V2 unified-error diagnostics, Fixes AB#3784695 (#3307) ## Summary Preserve Common diagnostics needed by the shared Android Native Auth V2 error surface, matching AzureAD/microsoft-authentication-library-for-js#8900. - Retain suberrors and attribute-validation details in V2 API, interaction, and command results. - Forward those diagnostics through V2 controllers and preserve unknown service errors. - Use additive, defaulted diagnostic fields and preserve V1 behavior. Fixes [AB#3784695](https://identitydivision.visualstudio.com/fac9d424-53d2-45c0-91b5-ef6ba7a6bf26/_workitems/edit/3784695) ## Dependencies Consumed by the paired MSAL unified-errors PR: AzureAD/microsoft-authentication-library-for-android#2618. Authorize-request scopes/claims changes are intentionally excluded. ## Validation Errors-only snapshot: **651 selected unit tests passed** (215 MSAL, 346 Common4j, 90 Common Android), with zero failures, errors, or skips in the final XML reports. The gate includes diagnostic parsing/forwarding and standalone V1 regression coverage. Final integrated-stack PR2601 validation: **20 live signup/reset E2E tests and 4 recorder tests passed**, with 3 known duplicate-account service-test skips. One Mail.tm `/accounts` HTTP 429 attempt passed on the existing automatic retry; no assertions or retry configuration were changed. Live validation was executed against the final stacked errors plus scopes/claims sources, not the standalone errors snapshot. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 0bcd671b-73fa-4ee6-bcd6-65d7eea4d753 Copilot-Session: 55791345-e680-4927-a364-f6de503184be Copilot-Session: 495388ac-9812-45ec-9120-b110dcbe5903 --- .../v2/NativeAuthV2FlowController.kt | 116 +++++++++- .../NativeAuthV2SignInFlowControllerTest.kt | 134 +++++++++++ .../NativeAuthV2SignUpFlowControllerTest.kt | 105 ++++++++- .../results/INativeAuthCommandResult.kt | 21 +- .../results/NativeAuthV2CommandResult.kt | 32 ++- .../providers/responses/ApiErrorResult.kt | 11 +- .../signin/SignInTokenApiResponse.kt | 71 ++++-- .../responses/signin/SignInTokenApiResult.kt | 47 +++- .../v2/AuthorizeChallengeApiResult.kt | 15 +- .../v2/NativeAuthV2HalApiResponse.kt | 25 +- .../v2/NativeAuthV2InteractionApiResult.kt | 55 +++-- .../v2/NativeAuthV2ResponseParser.kt | 83 ++++--- .../v2/NativeAuthV2ErrorDiagnostics.kt | 32 +++ .../v2/NativeAuthV2ResponseHandler.kt | 33 ++- .../v2/NativeAuthV2HalApiResponseTest.kt | 42 ++++ .../v2/NativeAuthV2ResponseParserTest.kt | 213 +++++++++++++++++- .../NativeAuthV2SignUpResponseParserTest.kt | 32 +++ .../v2/NativeAuthV2ResponseHandlerTest.kt | 122 ++++++++++ 18 files changed, 1074 insertions(+), 115 deletions(-) create mode 100644 common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ErrorDiagnostics.kt diff --git a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt index e7a6208846..c93865aa75 100644 --- a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt +++ b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt @@ -160,6 +160,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is AuthorizeChallengeApiResult.ContinuationRequired -> authChallengeResult.continuationState is AuthorizeChallengeApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = authChallengeResult.correlationId, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, + errorCodes = authChallengeResult.errorCodes, redirectReason = authChallengeResult.redirectReason ) is AuthorizeChallengeApiResult.AuthorizationCode -> { @@ -176,7 +179,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -193,10 +200,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = startResult.correlationId, error = startResult.error, errorDescription = startResult.errorDescription, + traceId = startResult.traceId, + timestamp = startResult.timestamp, errorCodes = startResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = startResult.correlationId, + traceId = startResult.traceId, + timestamp = startResult.timestamp, + errorCodes = startResult.errorCodes, redirectReason = startResult.redirectReason ) else -> return mapInteractionError(startResult) @@ -287,6 +299,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verificationResult.correlationId, + traceId = verificationResult.traceId, + timestamp = verificationResult.timestamp, + errorCodes = verificationResult.errorCodes, redirectReason = verificationResult.redirectReason ) else -> mapInteractionError(verificationResult) @@ -339,10 +354,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -387,10 +407,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -437,10 +462,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -492,6 +522,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = resendResult.correlationId, + traceId = resendResult.traceId, + timestamp = resendResult.timestamp, + errorCodes = resendResult.errorCodes, redirectReason = resendResult.redirectReason ) else -> mapInteractionError(resendResult) @@ -544,10 +577,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = updateResult.error, errorDescription = updateResult.errorDescription, subError = updateResult.subError, + traceId = updateResult.traceId, + timestamp = updateResult.timestamp, errorCodes = updateResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = updateResult.correlationId, + traceId = updateResult.traceId, + timestamp = updateResult.timestamp, + errorCodes = updateResult.errorCodes, redirectReason = updateResult.redirectReason ) else -> mapInteractionError(updateResult) @@ -601,6 +639,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { } is NativeAuthV2InteractionApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = pollResult.correlationId, + traceId = pollResult.traceId, + timestamp = pollResult.timestamp, + errorCodes = pollResult.errorCodes, redirectReason = pollResult.redirectReason ) else -> return mapInteractionError(pollResult) @@ -686,6 +727,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is AuthorizeChallengeApiResult.ContinuationRequired -> authChallengeResult.continuationState is AuthorizeChallengeApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = authChallengeResult.correlationId, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, + errorCodes = authChallengeResult.errorCodes, redirectReason = authChallengeResult.redirectReason ) is AuthorizeChallengeApiResult.AuthorizationCode -> { @@ -702,7 +746,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -719,10 +767,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = startResult.correlationId, error = startResult.error, errorDescription = startResult.errorDescription, + traceId = startResult.traceId, + timestamp = startResult.timestamp, errorCodes = startResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = startResult.correlationId, + traceId = startResult.traceId, + timestamp = startResult.timestamp, + errorCodes = startResult.errorCodes, redirectReason = startResult.redirectReason ) else -> return mapInteractionError(startResult) @@ -767,6 +820,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is NativeAuthV2InteractionApiResult.PasswordRequired -> firstFactorChallengeResult.continuationState is NativeAuthV2InteractionApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = firstFactorChallengeResult.correlationId, + traceId = firstFactorChallengeResult.traceId, + timestamp = firstFactorChallengeResult.timestamp, + errorCodes = firstFactorChallengeResult.errorCodes, redirectReason = firstFactorChallengeResult.redirectReason ) else -> return mapInteractionError(firstFactorChallengeResult) @@ -802,10 +858,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -864,10 +925,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -918,6 +984,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verificationResult.correlationId, + traceId = verificationResult.traceId, + timestamp = verificationResult.timestamp, + errorCodes = verificationResult.errorCodes, redirectReason = verificationResult.redirectReason ) else -> mapInteractionError(verificationResult) @@ -966,10 +1035,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -1061,6 +1135,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is AuthorizeChallengeApiResult.AuthorizationCode -> continueResult.code is AuthorizeChallengeApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = continueResult.correlationId, + traceId = continueResult.traceId, + timestamp = continueResult.timestamp, + errorCodes = continueResult.errorCodes, redirectReason = continueResult.redirectReason ) is AuthorizeChallengeApiResult.ContinuationRequired -> return INativeAuthCommandResult.APIError( @@ -1072,7 +1149,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = continueResult.error, errorDescription = continueResult.errorDescription, + traceId = continueResult.traceId, + timestamp = continueResult.timestamp, errorCodes = continueResult.errorCodes, + subError = continueResult.subError, + attributeValidationDetails = continueResult.attributeValidationDetails, correlationId = continueResult.correlationId ) } @@ -1089,6 +1170,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is SignInTokenApiResult.Success -> tokenResult is SignInTokenApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = tokenResult.correlationId, + traceId = tokenResult.traceId, + timestamp = tokenResult.timestamp, + errorCodes = tokenResult.errorCodes, redirectReason = tokenResult.redirectReason ) else -> { @@ -1096,7 +1180,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = tokenResult.error, errorDescription = tokenResult.errorDescription, + traceId = tokenResult.traceId, + timestamp = tokenResult.timestamp, errorCodes = tokenResult.errorCodes, + subError = tokenResult.subError, + attributeValidationDetails = tokenResult.attributeValidationDetails, correlationId = tokenResult.correlationId ) } @@ -1163,6 +1251,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is AuthorizeChallengeApiResult.ContinuationRequired -> authChallengeResult.continuationState is AuthorizeChallengeApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = authChallengeResult.correlationId, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, + errorCodes = authChallengeResult.errorCodes, redirectReason = authChallengeResult.redirectReason ) is AuthorizeChallengeApiResult.AuthorizationCode -> { @@ -1178,7 +1269,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -1333,7 +1428,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = result.correlationId, error = result.error, errorDescription = result.errorDescription, - errorCodes = result.errorCodes + traceId = result.traceId, + timestamp = result.timestamp, + errorCodes = result.errorCodes, + subError = result.subError, + attributeValidationDetails = result.attributeValidationDetails ) is NativeAuthV2InteractionApiResult.InvalidAttributes -> if (retryState != null) { NativeAuthV2CommandResult.AttributesInvalid( @@ -1342,13 +1441,20 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { invalidAttributes = result.invalidAttributes, error = result.error, errorDescription = result.errorDescription, - errorCodes = result.errorCodes + traceId = result.traceId, + timestamp = result.timestamp, + errorCodes = result.errorCodes, + subError = result.subError, + attributeValidationDetails = result.attributeValidationDetails ) } else { mapInteractionError(result) } is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = result.correlationId, + traceId = result.traceId, + timestamp = result.timestamp, + errorCodes = result.errorCodes, redirectReason = result.redirectReason ) else -> mapInteractionError(result) @@ -1562,7 +1668,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = error, errorDescription = errorDescription, errorCodes = errorCodes, - correlationId = result.correlationId + correlationId = result.correlationId, + subError = (result as? ApiErrorResult)?.subError, + attributeValidationDetails = (result as? ApiErrorResult)?.attributeValidationDetails, + traceId = (result as? ApiErrorResult)?.traceId, + timestamp = (result as? ApiErrorResult)?.timestamp ) } } diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt index 7d62e9b53d..b19a013ddf 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt @@ -43,7 +43,9 @@ import io.mockk.slot import io.mockk.verify import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame import org.junit.Assert.assertTrue +import org.junit.Assert.fail import org.junit.Before import org.junit.Test @@ -817,6 +819,138 @@ class NativeAuthV2SignInFlowControllerTest { } } + @Test + fun testSignInSubmissionsPreserveUnknownErrorDiagnostics() { + val state = mockContinuationState() + val apiError = NativeAuthV2InteractionApiResult.UnknownError( + correlationId = correlationId, + error = "service_error", + errorDescription = "The service could not verify the request.", + errorCodes = listOf(50126), + subError = "verification_failed", + attributeValidationDetails = listOf(mapOf("name" to "email", "reason" to "invalid")), + traceId = "service-trace", + timestamp = "service-time" + ) + every { mockStrategy.performPasswordVerify(state, any()) } returns apiError + every { mockStrategy.performVerify(state, any()) } returns apiError + every { mockStrategy.performMethodChallenge(state, "email-1") } returns apiError + + val results = listOf( + controller.submitPassword(submitPasswordParameters(state)), + controller.submitSignInCode(submitCodeParameters(state, "123456")), + controller.selectMFAMethod(selectMFAMethodParameters(state, "email-1")), + controller.submitMFAChallenge(submitMFAChallengeParameters(state, "123456")) + ) + + results.forEach { result -> + assertTrue(result is INativeAuthCommandResult.APIError) + result as INativeAuthCommandResult.APIError + assertEquals(apiError.correlationId, result.correlationId) + assertEquals(apiError.error, result.error) + assertEquals(apiError.errorDescription, result.errorDescription) + assertEquals(apiError.errorCodes, result.errorCodes) + assertEquals(apiError.subError, result.subError) + assertEquals(apiError.attributeValidationDetails, result.attributeValidationDetails) + assertEquals(apiError.traceId, result.traceId) + assertEquals(apiError.timestamp, result.timestamp) + } + } + + @Test + fun testSignInSubmissionsPreserveBrowserRedirectDiagnostics() { + val state = mockContinuationState() + val redirect = NativeAuthV2InteractionApiResult.Redirect( + correlationId = correlationId, + redirectReason = "browser_required", + traceId = "redirect-trace", + timestamp = "redirect-time", + errorCodes = listOf(50076) + ) + every { mockStrategy.performPasswordVerify(state, any()) } returns redirect + every { mockStrategy.performVerify(state, any()) } returns redirect + every { mockStrategy.performMethodChallenge(state, "email-1") } returns redirect + + val results = listOf( + controller.submitPassword(submitPasswordParameters(state)), + controller.submitSignInCode(submitCodeParameters(state, "123456")), + controller.selectMFAMethod(selectMFAMethodParameters(state, "email-1")), + controller.submitMFAChallenge(submitMFAChallengeParameters(state, "123456")) + ) + + results.forEach { result -> + assertTrue(result is INativeAuthCommandResult.Redirect) + result as INativeAuthCommandResult.Redirect + assertEquals(redirect.correlationId, result.correlationId) + assertEquals(redirect.redirectReason, result.redirectReason) + assertEquals(redirect.traceId, result.traceId) + assertEquals(redirect.timestamp, result.timestamp) + assertEquals(redirect.errorCodes, result.errorCodes) + } + } + + @Test + fun testSelectMFAMethodPreservesRiskVerificationErrors() { + val state = mockContinuationState() + val riskState = mockContinuationState() + every { mockStrategy.performMethodChallenge(state, "sms-1") } returns + NativeAuthV2InteractionApiResult.RiskVerificationRequired(correlationId, riskState) + every { mockStrategy.performRiskVerification(riskState) } returns + NativeAuthV2InteractionApiResult.UnknownError( + correlationId, + "risk_failed", + "Risk verification failed.", + traceId = "risk-trace" + ) + + val result = controller.selectMFAMethod(selectMFAMethodParameters(state, "sms-1")) + + assertTrue(result is INativeAuthCommandResult.APIError) + result as INativeAuthCommandResult.APIError + assertEquals("risk_failed", result.error) + assertEquals("risk-trace", result.traceId) + verify(exactly = 1) { mockStrategy.performRiskVerification(riskState) } + verify(exactly = 0) { mockStrategy.performVerify(any(), any()) } + } + + @Test + fun testSubmitPasswordRethrowsStrategyFailureAndClearsPassword() { + val state = mockContinuationState() + val password = "Password123!".toCharArray() + val failure = IllegalStateException("verification failed") + every { mockStrategy.performPasswordVerify(state, any()) } throws failure + + try { + controller.submitPassword(submitPasswordParameters(state, password)) + fail("Expected the strategy exception") + } catch (exception: IllegalStateException) { + assertSame(failure, exception) + } + + assertArrayEquals(CharArray(password.size), password) + } + + @Test + fun testMfaCommandsRethrowStrategyFailures() { + val state = mockContinuationState() + val failure = IllegalStateException("verification failed") + every { mockStrategy.performMethodChallenge(state, "email-1") } throws failure + every { mockStrategy.performVerify(state, any()) } throws failure + + try { + controller.selectMFAMethod(selectMFAMethodParameters(state, "email-1")) + fail("Expected the method-selection exception") + } catch (exception: IllegalStateException) { + assertSame(failure, exception) + } + try { + controller.submitMFAChallenge(submitMFAChallengeParameters(state, "123456")) + fail("Expected the challenge-verification exception") + } catch (exception: IllegalStateException) { + assertSame(failure, exception) + } + } + // ----------------------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------------------- diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt index 2eae4a90f5..7c885890a3 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt @@ -35,6 +35,7 @@ import com.microsoft.identity.common.java.nativeauth.controllers.results.INative import com.microsoft.identity.common.java.nativeauth.controllers.results.NativeAuthV2CommandResult import com.microsoft.identity.common.java.nativeauth.controllers.results.SignUpCommandResult import com.microsoft.identity.common.java.nativeauth.providers.NativeAuthV2OAuth2Strategy +import com.microsoft.identity.common.java.nativeauth.providers.responses.signin.SignInTokenApiResponse import com.microsoft.identity.common.java.nativeauth.providers.responses.signin.SignInTokenApiResult import com.microsoft.identity.common.java.nativeauth.providers.responses.v2.AuthorizeChallengeApiResult import com.microsoft.identity.common.java.nativeauth.providers.responses.v2.NativeAuthV2ContinuationState @@ -146,28 +147,44 @@ class NativeAuthV2SignUpFlowControllerTest { @Test fun testSignUpStartSurfacesUserAlreadyExists() { val entryState = mockContinuationState() + val details = listOf(mapOf( + "code" to "userAlreadyExists", + "attributeIds" to listOf("email"), + "message" to "An account already exists for this email." + )) stubAuthorizeChallengeStart(entryState) every { mockStrategy.performSignUpStart(entryState) } returns NativeAuthV2InteractionApiResult.UserAlreadyExists( correlationId = correlationId, error = "user_already_exists", errorDescription = "AADSTS1003037: account already exists.", - errorCodes = listOf(1003037) + errorCodes = listOf(1003037), + subError = "attributeValidationError", + traceId = "service-trace", + timestamp = "service-time", + attributeValidationDetails = details ) val result = controller.signUpStart(signUpStartParameters()) assertTrue(result is NativeAuthV2CommandResult.UserAlreadyExists) - assertEquals( - listOf(1003037), - (result as NativeAuthV2CommandResult.UserAlreadyExists).errorCodes - ) + result as NativeAuthV2CommandResult.UserAlreadyExists + assertEquals(listOf(1003037), result.errorCodes) + assertEquals("attributeValidationError", result.subError) + assertEquals("service-trace", result.traceId) + assertEquals("service-time", result.timestamp) + assertEquals(details, result.attributeValidationDetails) } @Test fun testSignUpStartMapsInvalidAttributesToRetryableAttributesInvalid() { val entryState = mockContinuationState() val submittedState = mockContinuationState() + val details = listOf(mapOf( + "code" to "attributeRequired", + "attributeIds" to listOf("city"), + "message" to "Enter a city." + )) every { entryState.withAdditionalSubmittedAttributes( match { @@ -190,7 +207,11 @@ class NativeAuthV2SignUpFlowControllerTest { invalidAttributes = listOf("city"), error = "attribute_validation_failed", errorDescription = "AADSTS1002027: attribute validation failed.", - errorCodes = listOf(1002027) + errorCodes = listOf(1002027), + subError = "attributeValidationError", + traceId = "service-trace", + timestamp = "service-time", + attributeValidationDetails = details ) val result = controller.signUpStart(signUpStartParameters()) @@ -198,11 +219,50 @@ class NativeAuthV2SignUpFlowControllerTest { assertTrue(result is NativeAuthV2CommandResult.AttributesInvalid) result as NativeAuthV2CommandResult.AttributesInvalid assertEquals(listOf("city"), result.invalidAttributes) + assertEquals("service-trace", result.traceId) + assertEquals("service-time", result.timestamp) + assertEquals("attributeValidationError", result.subError) + assertEquals(details, result.attributeValidationDetails) // The validation-error body carries no fresh continuation token, so retry with a state // that remembers the email and password submitted by the rejected request. assertSame(submittedState, result.continuationState) } + @Test + fun testSignUpStartPreservesUnknownErrorDiagnostics() { + val entryState = mockContinuationState() + val details = listOf(mapOf( + "code" to "futureValidationCode", + "attributeIds" to listOf("city"), + "message" to "Unrecognized attribute diagnostic." + )) + stubAuthorizeChallengeStart(entryState) + every { mockStrategy.performSignUpStart(entryState) } returns + NativeAuthV2InteractionApiResult.UnknownError( + correlationId = correlationId, + error = "future_error", + errorDescription = "Unrecognized service error.", + errorCodes = listOf(90000), + subError = "future_suberror", + traceId = "service-trace", + timestamp = "service-time", + attributeValidationDetails = details + ) + + val result = controller.signUpStart(signUpStartParameters()) + + assertTrue(result is INativeAuthCommandResult.APIError) + result as INativeAuthCommandResult.APIError + assertEquals("future_error", result.error) + assertEquals("Unrecognized service error.", result.errorDescription) + assertEquals(listOf(90000), result.errorCodes) + assertEquals(correlationId, result.correlationId) + assertEquals("future_suberror", result.subError) + assertEquals("service-trace", result.traceId) + assertEquals("service-time", result.timestamp) + assertEquals(details, result.attributeValidationDetails) + } + @Test fun testSignUpStartWithoutPasswordDefersToPasswordRequired() { val entryState = mockContinuationState() @@ -238,12 +298,19 @@ class NativeAuthV2SignUpFlowControllerTest { every { mockStrategy.performSignUpStart(entryState) } returns NativeAuthV2InteractionApiResult.Redirect( correlationId = correlationId, - redirectReason = "fallback_required" + redirectReason = "fallback_required", + errorCodes = listOf(123), + traceId = "redirect-trace", + timestamp = "redirect-time" ) val result = controller.signUpStart(signUpStartParameters()) assertTrue(result is INativeAuthCommandResult.Redirect) + result as INativeAuthCommandResult.Redirect + assertEquals(listOf(123), result.errorCodes) + assertEquals("redirect-trace", result.traceId) + assertEquals("redirect-time", result.timestamp) } @Test @@ -470,7 +537,9 @@ class NativeAuthV2SignUpFlowControllerTest { AuthorizeChallengeApiResult.UnknownError( correlationId = correlationId, error = "expected_test_error", - errorDescription = "Expected test error." + errorDescription = "Expected test error.", + traceId = "authorize-trace", + timestamp = "authorize-time" ) val result = controller.signInAfterSignUp(signInAfterSignUpParameters(state)) @@ -480,6 +549,8 @@ class NativeAuthV2SignUpFlowControllerTest { "expected_test_error", (result as INativeAuthCommandResult.APIError).error ) + assertEquals("authorize-trace", result.traceId) + assertEquals("authorize-time", result.timestamp) } @Test @@ -536,17 +607,27 @@ class NativeAuthV2SignUpFlowControllerTest { correlationId = correlationId, claimsRequestJson = any() ) - } returns SignInTokenApiResult.UnknownError( + } returns SignInTokenApiResponse( + statusCode = 400, correlationId = correlationId, + continuationToken = null, error = "invalid_grant", errorDescription = "The authorization code is no longer valid.", - errorCodes = emptyList() - ) + errorCodes = emptyList(), + errorUri = null, + traceId = "token-trace", + timestamp = "token-time", + subError = "future_suberror" + ).toErrorResult() val result = controller.signInAfterSignUp(signInAfterSignUpParameters(state)) assertTrue(result is INativeAuthCommandResult.APIError) - assertEquals("invalid_grant", (result as INativeAuthCommandResult.APIError).error) + result as INativeAuthCommandResult.APIError + assertEquals("invalid_grant", result.error) + assertEquals("token-trace", result.traceId) + assertEquals("token-time", result.timestamp) + assertEquals("future_suberror", result.subError) } @Test diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/INativeAuthCommandResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/INativeAuthCommandResult.kt index 3705ac3e6d..e76ca1c2ce 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/INativeAuthCommandResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/INativeAuthCommandResult.kt @@ -31,10 +31,17 @@ import com.microsoft.identity.common.java.nativeauth.util.ILoggable */ interface INativeAuthCommandResult : ILoggable { val correlationId: String - data class Redirect( + /** Service diagnostics are absent on locally generated results. */ + val traceId: String? get() = null + val timestamp: String? get() = null + + data class Redirect @JvmOverloads constructor( override val correlationId: String, - val redirectReason: String - ) : Error(error = BROWSER_REQUIRED_ERROR, errorDescription = redirectReason.ifEmpty { BROWSER_REQUIRED_ERROR_DESCRIPTION }, correlationId = correlationId), + val redirectReason: String, + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null + ) : Error(error = BROWSER_REQUIRED_ERROR, errorDescription = redirectReason.ifEmpty { BROWSER_REQUIRED_ERROR_DESCRIPTION }, correlationId = correlationId, errorCodes = errorCodes), SignInStartCommandResult, SignInWithContinuationTokenCommandResult, SignInSubmitCodeCommandResult, SignInResendCodeCommandResult, SignInSubmitPasswordCommandResult, SignUpStartCommandResult, SignUpSubmitCodeCommandResult, SignUpResendCodeCommandResult, SignUpSubmitPasswordCommandResult, SignUpSubmitUserAttributesCommandResult, ResetPasswordStartCommandResult, ResetPasswordSubmitCodeCommandResult, ResetPasswordResendCodeCommandResult, ResetPasswordSubmitNewPasswordCommandResult, @@ -60,13 +67,17 @@ interface INativeAuthCommandResult : ILoggable { /** * UnknownError is base class to represent various kinds of errors in NativeAuth. */ - data class APIError( + data class APIError @JvmOverloads constructor( override val error: String?, override val errorDescription: String?, override val details: List>? = null, override val correlationId: String, override val errorCodes: List? = null, - val exception: Exception? = null + val exception: Exception? = null, + val subError: String? = null, + val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ): Error(error, errorDescription, details, correlationId, errorCodes), INativeAuthCommandResult, SignInStartCommandResult, SignInWithContinuationTokenCommandResult, SignInSubmitCodeCommandResult, SignInResendCodeCommandResult, SignInSubmitPasswordCommandResult, diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/NativeAuthV2CommandResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/NativeAuthV2CommandResult.kt index 68268acfb4..ad6bbd4702 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/NativeAuthV2CommandResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/NativeAuthV2CommandResult.kt @@ -175,12 +175,14 @@ interface NativeAuthV2CommandResult { * The developer can retry through the state object used for the failed call. * Applies to the submit-code step. */ - data class IncorrectCode( + data class IncorrectCode @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val subError: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2ResetPasswordSubmitCodeCommandResult, NativeAuthV2SignUpSubmitCodeCommandResult, NativeAuthV2SignInSubmitCodeCommandResult, @@ -253,12 +255,14 @@ interface NativeAuthV2CommandResult { * The developer must restart the flow with corrected credentials. * Applies to the sign-in start step. */ - data class InvalidCredentials( + data class InvalidCredentials @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val subError: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SignInStartCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.InvalidCredentials(correlationId=$correlationId, error=$error, errorDescription=$errorDescription, subError=$subError)" @@ -272,12 +276,14 @@ interface NativeAuthV2CommandResult { * retry through the state object used for the failed call. * Applies to the submit-password step. */ - data class IncorrectPassword( + data class IncorrectPassword @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val subError: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SubmitPasswordCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.IncorrectPassword(correlationId=$correlationId, error=$error, errorDescription=$errorDescription, subError=$subError)" @@ -291,12 +297,14 @@ interface NativeAuthV2CommandResult { * The developer can retry through the state object used for the failed call. * Applies to the submit-new-password step. */ - data class PasswordNotAccepted( + data class PasswordNotAccepted @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val subError: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SubmitNewPasswordCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.PasswordNotAccepted(correlationId=$correlationId, error=$error, errorDescription=$errorDescription, subError=$subError)" @@ -325,11 +333,13 @@ interface NativeAuthV2CommandResult { * The username provided is not registered in the tenant. * Applies to the start step. */ - data class UserNotFound( + data class UserNotFound @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2ResetPasswordStartCommandResult, NativeAuthV2SignInStartCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.UserNotFound(correlationId=$correlationId, error=$error, errorDescription=$errorDescription)" @@ -364,13 +374,17 @@ interface NativeAuthV2CommandResult { * [continuationState] with corrected values. Applies to the sign-up start and submit-attributes * steps. */ - data class AttributesInvalid( + data class AttributesInvalid @JvmOverloads constructor( override val correlationId: String, val continuationState: NativeAuthV2ContinuationState, val invalidAttributes: List, val error: String, val errorDescription: String, val errorCodes: List? = null, + val subError: String? = null, + val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SignUpStartCommandResult, NativeAuthV2SubmitAttributesCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.AttributesInvalid(correlationId=$correlationId, invalidAttributes=$invalidAttributes, error=$error, errorDescription=$errorDescription)" @@ -383,11 +397,15 @@ interface NativeAuthV2CommandResult { * An account already exists for the identifier supplied to sign-up. * Applies to the sign-up start and submit-attributes steps. */ - data class UserAlreadyExists( + data class UserAlreadyExists @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val errorCodes: List? = null, + val subError: String? = null, + val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SignUpStartCommandResult, NativeAuthV2SubmitAttributesCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.UserAlreadyExists(correlationId=$correlationId, error=$error, errorDescription=$errorDescription)" diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/ApiErrorResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/ApiErrorResult.kt index f942c8e43e..4e4f4fb66a 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/ApiErrorResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/ApiErrorResult.kt @@ -25,14 +25,21 @@ package com.microsoft.identity.common.java.nativeauth.providers.responses /** * Base class to encapsulate various error response from the Native Auth API. */ -abstract class ApiErrorResult( +abstract class ApiErrorResult @JvmOverloads constructor( open val error: String?, open val subError: String? = null, open val errorDescription: String?, open val errorCodes: List? = null, - override val correlationId: String + override val correlationId: String, + open val attributeValidationDetails: List>? = null ): ApiResult { + /** Unmodified service trace identifier, when supplied by the endpoint. */ + open val traceId: String? get() = null + + /** Unmodified service timestamp; no client-side date conversion is applied. */ + open val timestamp: String? get() = null + companion object { val INVALID_STATE = "invalid_state" } diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResponse.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResponse.kt index 43c7610d5b..eb5d44c3ee 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResponse.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResponse.kt @@ -42,7 +42,7 @@ import com.microsoft.identity.common.java.nativeauth.util.isUserNotFound * Note: mainly used for representing error cases from the /token endpoint. Successful responses are otherwise mapped to MicrosoftStsTokenResponse instead. * @see com.microsoft.identity.common.java.providers.microsoft.microsoftsts.MicrosoftStsTokenResponse */ -class SignInTokenApiResponse( +class SignInTokenApiResponse @JvmOverloads constructor( @Expose override var statusCode: Int, correlationId: String, @SerializedName("continuation_token") override val continuationToken: String?, @@ -51,6 +51,8 @@ class SignInTokenApiResponse( @SerializedName("error_uri") val errorUri: String?, @SerializedName("suberror") val subError: String?, @SerializedName("error_codes") val errorCodes: List?, + @SerializedName("trace_id") val traceId: String? = null, + @SerializedName("timestamp") val timestamp: String? = null, ): INativeAuthApiResponse(statusCode, correlationId, continuationToken, error = error, errorDescription = errorDescription) { override fun toUnsanitizedString(): String { @@ -69,9 +71,12 @@ class SignInTokenApiResponse( /** * Maps potential errors returned from the server response. + * @param diagnosticErrorCodes codes exposed to callers, without changing classification based + * on the original [errorCodes]. V2 may supply codes extracted from the message as a fallback. * @see com.microsoft.identity.common.java.nativeauth.providers.responses.signin.SignInTokenApiResult */ - fun toErrorResult(): SignInTokenApiResult { + @JvmOverloads + fun toErrorResult(diagnosticErrorCodes: List? = errorCodes): SignInTokenApiResult { return when { error.isInvalidRequest() -> { when { @@ -79,7 +84,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -89,7 +97,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = customDescription, - errorCodes = errorCodes, + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -97,7 +108,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes, + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -109,7 +123,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.InvalidCredentials( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes, + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -121,11 +138,16 @@ class SignInTokenApiResponse( return SignInTokenApiResult.UnknownError( error = ApiErrorResult.INVALID_STATE, errorDescription = "oauth/v2.0/token did not return a continuation token", - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ), subError = subError.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -137,11 +159,16 @@ class SignInTokenApiResponse( return SignInTokenApiResult.UnknownError( error = ApiErrorResult.INVALID_STATE, errorDescription = "oauth/v2.0/token did not return a continuation token", - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ), subError = subError.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -149,8 +176,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.CodeIncorrect( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), subError = subError.orEmpty(), + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -158,7 +187,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.InvalidAuthenticationType( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes, + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -166,7 +198,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -176,7 +211,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UserNotFound( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -184,7 +222,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResult.kt index 22825cb6a5..ad03a8332b 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResult.kt @@ -33,9 +33,12 @@ import com.microsoft.identity.common.java.providers.microsoft.microsoftsts.Micro */ sealed interface SignInTokenApiResult: ApiResult, ILoggable { - data class Redirect( + data class Redirect @JvmOverloads constructor( override val correlationId: String, - val redirectReason: String + val redirectReason: String, + val errorCodes: List? = null, + val traceId: String? = null, + val timestamp: String? = null ) : SignInTokenApiResult { override fun toUnsanitizedString(): String { return "Redirect(correlationId=$correlationId, redirectReason=$redirectReason)" @@ -55,13 +58,15 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = toUnsanitizedString() } - data class MFARequired( + data class MFARequired @JvmOverloads constructor( override val correlationId: String, val continuationToken: String, override val error: String, override val subError: String, override val errorDescription: String, - override val errorCodes: List + override val errorCodes: List, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -75,13 +80,15 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "MFARequired(correlationId=$correlationId)" } - data class JITRequired( + data class JITRequired @JvmOverloads constructor( override val correlationId: String, val continuationToken: String, override val error: String, override val subError: String, override val errorDescription: String, - override val errorCodes: List + override val errorCodes: List, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -95,15 +102,19 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "JITRequired(correlationId=$correlationId)" } - data class UserNotFound( + data class UserNotFound @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, + override val subError: String? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, errorCodes = errorCodes, + subError = subError, correlationId = correlationId ), SignInTokenApiResult { override fun toUnsanitizedString() = "UserNotFound(correlationId=$correlationId, " + @@ -112,15 +123,19 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "UserNotFound(correlationId=$correlationId)" } - data class InvalidCredentials( + data class InvalidCredentials @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, + override val subError: String? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, errorCodes = errorCodes, + subError = subError, correlationId = correlationId ), SignInTokenApiResult { override fun toUnsanitizedString() = "InvalidCredentials(correlationId=$correlationId, " + @@ -129,12 +144,14 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "InvalidCredentials(correlationId=$correlationId)" } - data class CodeIncorrect( + data class CodeIncorrect @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, override val subError: String, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -148,15 +165,19 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "CodeIncorrect(correlationId=$correlationId)" } - data class InvalidAuthenticationType( + data class InvalidAuthenticationType @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, + override val subError: String? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, errorCodes = errorCodes, + subError = subError, correlationId = correlationId ), SignInTokenApiResult { override fun toUnsanitizedString() = "InvalidAuthenticationType(correlationId=$correlationId, " + @@ -165,15 +186,19 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "InvalidAuthenticationType(correlationId=$correlationId)" } - data class UnknownError( + data class UnknownError @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, + override val subError: String? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, errorCodes = errorCodes, + subError = subError, correlationId = correlationId ), SignInTokenApiResult { override fun toUnsanitizedString() = "UnknownError(correlationId=$correlationId, " + diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/AuthorizeChallengeApiResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/AuthorizeChallengeApiResult.kt index 3967e32547..ae18730364 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/AuthorizeChallengeApiResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/AuthorizeChallengeApiResult.kt @@ -59,9 +59,12 @@ sealed interface AuthorizeChallengeApiResult : ApiResult { /** * The server requires the flow to fall back to a web-based (interactive browser) experience. */ - data class Redirect( + data class Redirect @JvmOverloads constructor( override val correlationId: String, - val redirectReason: String + val redirectReason: String, + val errorCodes: List? = null, + val traceId: String? = null, + val timestamp: String? = null ) : AuthorizeChallengeApiResult { override fun toUnsanitizedString(): String = "Redirect(correlationId=$correlationId, redirectReason=$redirectReason)" @@ -72,11 +75,15 @@ sealed interface AuthorizeChallengeApiResult : ApiResult { * An error was returned (or the response shape was otherwise unusable) that this SDK version * does not map to a more specific case. */ - data class UnknownError( + data class UnknownError @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val subError: String? = null, + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponse.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponse.kt index 604d7cb472..1d9c809d57 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponse.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponse.kt @@ -23,6 +23,7 @@ package com.microsoft.identity.common.java.nativeauth.providers.responses.v2 import com.microsoft.identity.common.java.nativeauth.providers.INativeAuthApiResponse +import com.microsoft.identity.common.java.nativeauth.providers.v2.NativeAuthV2ErrorDiagnostics /** * Single wire model for every V2 HAL Native Auth API response body. There are no response @@ -75,16 +76,21 @@ class NativeAuthV2HalApiResponse private constructor( // Per-attribute error details from `error.innerError.details`. Empty when the server sent // no such array. Used to attribute a sign-up failure (for example `userAlreadyExists` or // `passwordPolicyViolation`) to the specific attribute(s) it concerns. - val details: List + val details: List, + val traceId: String? = null, + val timestamp: String? = null, + val errorCodes: List? = null ) /** * A single entry of `error.innerError.details`, pairing an error [code] (for example - * `userAlreadyExists` or `passwordPolicyViolation`) with the [attributeIds] it applies to. + * `userAlreadyExists` or `passwordPolicyViolation`) with the [attributeIds] it applies to + * and the optional, unmodified service [message]. */ data class HalErrorDetail( val code: String?, - val attributeIds: List + val attributeIds: List, + val message: String? = null ) val isWebFallbackRequired: Boolean @@ -328,7 +334,10 @@ class NativeAuthV2HalApiResponse private constructor( message = errorValue[ERROR_MESSAGE_KEY] as? String, innerErrorCode = innerErrorMap?.get(ERROR_CODE_KEY) as? String, correlationId = errorValue[ERROR_CORRELATION_ID_KEY] as? String, - details = extractErrorDetails(innerErrorMap) + details = extractErrorDetails(innerErrorMap), + traceId = errorValue["traceId"] as? String, + timestamp = errorValue["timestamp"] as? String, + errorCodes = NativeAuthV2ErrorDiagnostics.readErrorCodes(errorValue["error_codes"]) ) } @@ -338,7 +347,10 @@ class NativeAuthV2HalApiResponse private constructor( innerErrorCode = null, correlationId = halResource.string(ERROR_CORRELATION_ID_SNAKE_KEY) ?: halResource.string(ERROR_CORRELATION_ID_KEY), - details = emptyList() + details = emptyList(), + traceId = halResource.string("trace_id"), + timestamp = halResource.string("timestamp"), + errorCodes = NativeAuthV2ErrorDiagnostics.readErrorCodes(halResource.properties["error_codes"]) ) else -> null @@ -360,7 +372,8 @@ class NativeAuthV2HalApiResponse private constructor( .orEmpty() HalErrorDetail( code = detailMap[ERROR_CODE_KEY] as? String, - attributeIds = attributeIds + attributeIds = attributeIds, + message = detailMap[ERROR_MESSAGE_KEY] as? String ) } } diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2InteractionApiResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2InteractionApiResult.kt index 8288d881d8..3b8e2e9f20 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2InteractionApiResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2InteractionApiResult.kt @@ -163,9 +163,12 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * The server requires the flow to fall back to a web-based (interactive browser) experience. */ - data class Redirect( + data class Redirect @JvmOverloads constructor( override val correlationId: String, - val redirectReason: String + val redirectReason: String, + val errorCodes: List? = null, + val traceId: String? = null, + val timestamp: String? = null ) : NativeAuthV2InteractionApiResult { override fun toUnsanitizedString(): String = "Redirect(correlationId=$correlationId, redirectReason=$redirectReason)" @@ -175,11 +178,13 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * No account matches the identifier supplied to reset-password /start. */ - data class UserNotFound( + data class UserNotFound @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -194,12 +199,14 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * The submitted verification code was invalid. */ - data class InvalidCode( + data class InvalidCode @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val subError: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, subError = subError, @@ -215,12 +222,14 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * The submitted password was invalid (for example, too weak). */ - data class InvalidPassword( + data class InvalidPassword @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val subError: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, subError = subError, @@ -236,12 +245,14 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * The submitted username/password combination was rejected by the service. */ - data class InvalidCredentials( + data class InvalidCredentials @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val subError: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, subError = subError, @@ -274,11 +285,15 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * An account already exists for the identifier supplied to sign-up. */ - data class UserAlreadyExists( + data class UserAlreadyExists @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val subError: String? = null, + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -295,12 +310,16 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { * wire names of the attributes the server rejected (for example `password` when the value * violated password policy), in server order. */ - data class InvalidAttributes( + data class InvalidAttributes @JvmOverloads constructor( override val correlationId: String, val invalidAttributes: List, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val subError: String? = null, + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -338,11 +357,15 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { * An error was returned (or the response shape was otherwise unusable) that this SDK version * does not map to a more specific case. */ - data class UnknownError( + data class UnknownError @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val subError: String? = null, + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt index c9a2614255..09db930546 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt @@ -27,6 +27,7 @@ import com.microsoft.identity.common.java.logging.Logger import com.microsoft.identity.common.java.nativeauth.providers.NativeAuthConstants import com.microsoft.identity.common.java.nativeauth.providers.responses.ApiErrorResult import com.microsoft.identity.common.java.nativeauth.providers.v2.NativeAuthV2FlowScenario +import com.microsoft.identity.common.java.nativeauth.providers.v2.NativeAuthV2ErrorDiagnostics import java.util.Locale /** @@ -70,7 +71,10 @@ class NativeAuthV2ResponseParser { return AuthorizeChallengeApiResult.Redirect( correlationId = response.serverError?.correlationId ?.takeUnless { it.isBlank() } ?: response.correlationId, - redirectReason = response.serverError?.code ?: response.state ?: WEB_FALLBACK_REDIRECT_REASON + redirectReason = response.serverError?.code ?: response.state ?: WEB_FALLBACK_REDIRECT_REASON, + traceId = response.serverError?.traceId, + timestamp = response.serverError?.timestamp, + errorCodes = response.serverError?.errorCodes ?: extractAadstsCodes(response.serverError?.message) ) } @@ -84,7 +88,11 @@ class NativeAuthV2ResponseParser { ?.takeUnless { it.isBlank() } ?: response.correlationId, error = serverError.code ?: ApiErrorResult.INVALID_STATE, errorDescription = serverError.message.orEmpty(), - errorCodes = extractAadstsCodes(serverError.message) + errorCodes = serverError.errorCodes ?: extractAadstsCodes(serverError.message), + subError = serverError.innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) } @@ -173,7 +181,10 @@ class NativeAuthV2ResponseParser { if (response.isWebFallbackRequired) { return NativeAuthV2InteractionApiResult.Redirect( correlationId = errorCorrelationId, - redirectReason = response.serverError?.code ?: response.state ?: WEB_FALLBACK_REDIRECT_REASON + redirectReason = response.serverError?.code ?: response.state ?: WEB_FALLBACK_REDIRECT_REASON, + traceId = response.serverError?.traceId, + timestamp = response.serverError?.timestamp, + errorCodes = response.serverError?.errorCodes ?: extractAadstsCodes(response.serverError?.message) ) } @@ -545,7 +556,7 @@ class NativeAuthV2ResponseParser { val code = serverError.code val innerErrorCode = serverError.innerErrorCode val message = serverError.message - val errorCodes = extractAadstsCodes(message) + val errorCodes = serverError.errorCodes ?: extractAadstsCodes(message) return when { code == ERROR_INVALID_GRANT && innerErrorCode == INNER_ERROR_INVALID_ONE_TIME_CODE -> @@ -554,11 +565,13 @@ class NativeAuthV2ResponseParser { error = code.orEmpty(), errorDescription = message.orEmpty(), subError = innerErrorCode.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + traceId = serverError.traceId, + timestamp = serverError.timestamp ) innerErrorCode == INNER_ERROR_INVALID_CONTINUATION_TOKEN -> - unknownInteractionError(correlationId, code, message, errorCodes) + unknownInteractionError(correlationId, serverError, errorCodes) scenario == NativeAuthV2FlowScenario.SIGN_UP && innerErrorCode == INNER_ERROR_ATTRIBUTE_VALIDATION_FAILED -> @@ -568,14 +581,18 @@ class NativeAuthV2ResponseParser { .flatMap { it.attributeIds } .distinct() if (invalidAttributes.isEmpty()) { - unknownInteractionError(correlationId, code, message, errorCodes) + unknownInteractionError(correlationId, serverError, errorCodes) } else { NativeAuthV2InteractionApiResult.InvalidAttributes( correlationId = correlationId, invalidAttributes = invalidAttributes, error = code.orEmpty(), errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + subError = innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) } } @@ -587,7 +604,11 @@ class NativeAuthV2ResponseParser { correlationId = correlationId, error = code.orEmpty(), errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + subError = innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) code == ERROR_INVALID_REQUEST && innerErrorCode in INNER_ERROR_INVALID_PASSWORD -> @@ -596,7 +617,9 @@ class NativeAuthV2ResponseParser { error = code.orEmpty(), errorDescription = message.orEmpty(), subError = innerErrorCode.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + traceId = serverError.traceId, + timestamp = serverError.timestamp ) code == ERROR_INVALID_GRANT && @@ -606,7 +629,9 @@ class NativeAuthV2ResponseParser { error = code.orEmpty(), errorDescription = message.orEmpty(), subError = innerErrorCode.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + traceId = serverError.traceId, + timestamp = serverError.timestamp ) // The account does not exist in the directory. This response carries no inner error @@ -618,25 +643,36 @@ class NativeAuthV2ResponseParser { correlationId = correlationId, error = code.orEmpty(), errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + traceId = serverError.traceId, + timestamp = serverError.timestamp ) - else -> unknownInteractionError(correlationId, code, message, errorCodes) + else -> unknownInteractionError(correlationId, serverError, errorCodes) } } private fun unknownInteractionError( correlationId: String, - code: String?, - message: String?, + serverError: NativeAuthV2HalApiResponse.HalServerError, errorCodes: List? ): NativeAuthV2InteractionApiResult.UnknownError = NativeAuthV2InteractionApiResult.UnknownError( correlationId = correlationId, - error = code ?: ApiErrorResult.INVALID_STATE, - errorDescription = message.orEmpty(), - errorCodes = errorCodes + error = serverError.code ?: ApiErrorResult.INVALID_STATE, + errorDescription = serverError.message.orEmpty(), + errorCodes = errorCodes, + subError = serverError.innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) + private fun validationDetails(error: NativeAuthV2HalApiResponse.HalServerError): List> = + error.details.map { detail -> + val fields = mapOf("code" to detail.code, "attributeIds" to detail.attributeIds) + detail.message?.let { fields + ("message" to it) } ?: fields + } + private fun missingLinkError( correlationId: String, relation: NativeAuthV2LinkRelation @@ -685,19 +721,12 @@ class NativeAuthV2ResponseParser { * surfacing service error codes via [ApiErrorResult.errorCodes]. Returns `null` (rather than * an empty list) when none are present, matching [ApiErrorResult.errorCodes]'s own default. */ - private fun extractAadstsCodes(message: String?): List? { - if (message.isNullOrBlank()) { - return null - } - val codes = AADSTS_CODE_REGEX.findAll(message).mapNotNull { it.groupValues[1].toIntOrNull() }.toList() - return codes.ifEmpty { null } - } + private fun extractAadstsCodes(message: String?): List? = + NativeAuthV2ErrorDiagnostics.codesFromMessage(message) private companion object { private val TAG: String = NativeAuthV2ResponseParser::class.java.simpleName - private val AADSTS_CODE_REGEX = Regex("AADSTS(\\d+)") - private const val STATE_CONTINUE = "continue" private const val WEB_FALLBACK_REDIRECT_REASON = "web_fallback_required" diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ErrorDiagnostics.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ErrorDiagnostics.kt new file mode 100644 index 0000000000..40a3438b36 --- /dev/null +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ErrorDiagnostics.kt @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.microsoft.identity.common.java.nativeauth.providers.v2 + +import java.math.BigDecimal + +/** Shared diagnostic decoding for V2 HAL and OAuth error envelopes. */ +internal object NativeAuthV2ErrorDiagnostics { + private val aadstsCodeRegex = Regex("AADSTS(\\d+)") + + /** A malformed array is rejected as a whole; an explicit empty array remains authoritative. */ + fun readErrorCodes(value: Any?): List? { + val values = value as? List<*> ?: return null + return values.map { + val number = it as? Number ?: return null + try { + BigDecimal(number.toString()).intValueExact() + } catch (e: NumberFormatException) { + return null + } catch (e: ArithmeticException) { + return null + } + } + } + + fun codesFromMessage(message: String?): List? = + message?.let { + aadstsCodeRegex.findAll(it).mapNotNull { match -> + match.groupValues[1].toIntOrNull() + }.toList().ifEmpty { null } + } +} diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandler.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandler.kt index e7f7c39a31..abf19ce59e 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandler.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandler.kt @@ -22,6 +22,9 @@ // THE SOFTWARE. package com.microsoft.identity.common.java.nativeauth.providers.v2 +import com.google.gson.JsonArray +import com.google.gson.JsonObject +import com.google.gson.JsonPrimitive import com.microsoft.identity.common.java.AuthenticationConstants import com.microsoft.identity.common.java.exception.ClientException import com.microsoft.identity.common.java.logging.LogSession @@ -175,19 +178,36 @@ class NativeAuthV2ResponseHandler { errorCodes = null ) } else { - ObjectMapper.deserializeJsonStringToObject( + val body = ObjectMapper.deserializeJsonStringToObject( response.body, - SignInTokenApiResponse::class.java + JsonObject::class.java ) ?: return buildTokenErrorResult( statusCode = response.statusCode, correlationId = correlationId, errorCode = NativeAuthResponseHandler.EMPTY_RESPONSE_ERROR, errorMessage = NativeAuthResponseHandler.EMPTY_RESPONSE_ERROR_ERROR_DESCRIPTION ) + // Keep the original numeric representation; Double coercion can hide fractions. + val rawErrorCodes = (body["error_codes"] as? JsonArray)?.map { + (it as? JsonPrimitive)?.takeIf { value -> value.isNumber }?.asNumber + } + SignInTokenApiResponse( + statusCode = response.statusCode, + correlationId = correlationId, + continuationToken = body.string("continuation_token"), + error = body.string("error"), + errorDescription = body.string("error_description"), + errorUri = body.string("error_uri"), + subError = body.string("suberror"), + errorCodes = NativeAuthV2ErrorDiagnostics.readErrorCodes(rawErrorCodes), + traceId = body.string("trace_id"), + timestamp = body.string("timestamp") + ) } - apiResponse.statusCode = response.statusCode - apiResponse.correlationId = correlationId - apiResponse.toErrorResult() + apiResponse.toErrorResult( + diagnosticErrorCodes = apiResponse.errorCodes + ?: NativeAuthV2ErrorDiagnostics.codesFromMessage(apiResponse.errorDescription) + ) } else { val tokenResponse = ObjectMapper.deserializeJsonStringToObject( response.body, @@ -212,6 +232,9 @@ class NativeAuthV2ResponseHandler { } } + private fun JsonObject.string(name: String): String? = + (get(name) as? JsonPrimitive)?.takeIf { it.isString }?.asString + private fun buildTokenErrorResult( statusCode: Int, correlationId: String, diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponseTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponseTest.kt index 82cb52f205..b5e32e9fc1 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponseTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponseTest.kt @@ -30,6 +30,48 @@ import org.junit.Test class NativeAuthV2HalApiResponseTest { + @Test + fun from_preservesAttributeDetailMessagesVerbatim() { + val response = responseFrom( + """{"error":{"code":"invalidRequest","innerError":{"code":"attributeValidationError", + "details":[ + {"code":"attributeValidationFailed","attributeIds":["email"],"message":"Enter a valid value."}, + {"code":"attributeRequired","message":"A \"quoted\" value.\nNext line."}, + {"code":"futureDetail","attributeIds":[],"message":""} + ]}}}""" + ) + + assertEquals( + listOf( + NativeAuthV2HalApiResponse.HalErrorDetail( + "attributeValidationFailed", listOf("email"), "Enter a valid value." + ), + NativeAuthV2HalApiResponse.HalErrorDetail( + "attributeRequired", emptyList(), "A \"quoted\" value.\nNext line." + ), + NativeAuthV2HalApiResponse.HalErrorDetail("futureDetail", emptyList(), "") + ), + response.serverError?.details + ) + } + + @Test + fun from_missingOrMalformedDetailMessagesDoNotDiscardOtherFields() { + for (messageField in listOf("", ""","message":null""", ""","message":42""", + ""","message":{}""", ""","message":[]""", ""","message":false""")) { + val response = responseFrom( + """{"error":{"code":"invalidRequest","innerError":{"details":[ + {"code":"attributeValidationFailed","attributeIds":["email"]$messageField} + ]}}}""" + ) + + assertEquals( + listOf(NativeAuthV2HalApiResponse.HalErrorDetail("attributeValidationFailed", listOf("email"))), + response.serverError?.details + ) + } + } + @Test fun error_buildsClientSideErrorWithoutFlowState() { val response = NativeAuthV2HalApiResponse.error( diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt index 901f7d913f..0ef241b5b2 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt @@ -36,6 +36,213 @@ import org.junit.Test class NativeAuthV2ResponseParserTest { private val parser = NativeAuthV2ResponseParser() + @Test + fun parseAuthorizeChallenge_prefersExplicitErrorCodesIncludingEmptyArray() { + for (codes in listOf(listOf(100, 200), emptyList())) { + val result = parser.parseAuthorizeChallenge( + response = responseFrom( + """{"error":"InsufficientAuthorization", + "error_description":"AADSTS500127: No authenticated credentials.", + "error_codes":$codes,"trace_id":"server-trace", + "timestamp":"2026-10-15 11:00:20Z"}""" + ), + entryRelation = NativeAuthV2LinkRelation.SIGN_IN, + scenario = NativeAuthV2FlowScenario.SIGN_IN, + scopes = emptyList() + ) as AuthorizeChallengeApiResult.UnknownError + + assertEquals(codes, result.errorCodes) + assertEquals("server-trace", result.traceId) + assertEquals("2026-10-15 11:00:20Z", result.timestamp) + } + } + + @Test + fun parseErrors_preservesSuppliedPayloadDiagnosticsAcrossScenarios() { + val attributeMessage = "Enter a valid \"email\" value.\nTry again." + val details = listOf( + mapOf( + "code" to "attributeValidationFailed", + "attributeIds" to listOf("email"), + "message" to attributeMessage + ) + ) + val cases = listOf( + Triple( + """{"error":"InsufficientAuthorization", + "error_description":"AADSTS500127: No authenticated credentials.", + "error_codes":[500127],"correlation_id":"service-correlation", + "trace_id":"service-trace","timestamp":"service-time"}""", + null, 500127 + ), + Triple( + """{"error":{"code":"invalidRequest", + "message":"AADSTS1002027: Attribute validation failed.", + "correlationId":"service-correlation","traceId":"service-trace", + "timestamp":"service-time","innerError":{"code":"attributeValidationError", + "details":[{"code":"attributeValidationFailed","attributeIds":["email"], + "message":"Enter a valid \"email\" value.\nTry again."}]}}}""", + "attributeValidationError", 1002027 + ), + Triple( + """{"error":{"code":"invalidRequest", + "message":"AADSTS10040172: User not found.", + "correlationId":"service-correlation","traceId":"service-trace", + "timestamp":"service-time","innerError":{"code":"userNotFound"}}, + "sign_up":"/tenant/api/v0.1/signup/start"}""", + "userNotFound", 10040172 + ) + ) + val scenarios = listOf( + NativeAuthV2FlowScenario.SIGN_IN, + NativeAuthV2FlowScenario.SIGN_UP, + NativeAuthV2FlowScenario.RESET_PASSWORD + ) + for ((json, subError, errorCode) in cases) { + fun assertDiagnostics(error: ApiErrorResult) { + assertEquals( + if (subError == null) "InsufficientAuthorization" else "invalidRequest", + error.error + ) + assertEquals( + when (errorCode) { + 500127 -> "AADSTS500127: No authenticated credentials." + 1002027 -> "AADSTS1002027: Attribute validation failed." + else -> "AADSTS10040172: User not found." + }, + error.errorDescription + ) + assertEquals(listOf(errorCode), error.errorCodes) + assertEquals("service-correlation", error.correlationId) + assertEquals("service-trace", error.traceId) + assertEquals("service-time", error.timestamp) + assertEquals(subError, error.subError) + assertEquals( + if (subError == "attributeValidationError") details else emptyList(), + error.attributeValidationDetails + ) + } + for (scenario in scenarios) { + val response = responseFrom(json) + val authorizeResult = parser.parseAuthorizeChallenge( + response, NativeAuthV2LinkRelation.SIGN_IN, scenario, emptyList() + ) + assertTrue(authorizeResult is AuthorizeChallengeApiResult.UnknownError) + assertDiagnostics(authorizeResult as ApiErrorResult) + + val interactionResult = parser.parseInteraction(response, previousState(scenario)) + if (scenario == NativeAuthV2FlowScenario.SIGN_UP && + subError == "attributeValidationError") { + assertTrue(interactionResult is NativeAuthV2InteractionApiResult.InvalidAttributes) + assertEquals( + listOf("email"), + (interactionResult as NativeAuthV2InteractionApiResult.InvalidAttributes).invalidAttributes + ) + } else { + assertTrue(interactionResult is NativeAuthV2InteractionApiResult.UnknownError) + } + assertDiagnostics(interactionResult as ApiErrorResult) + } + } + } + + @Test + fun parseInteraction_missingOrMalformedDetailMessagesPreservesExistingMapShape() { + for (messageField in listOf("", ""","message":null""", ""","message":42""", + ""","message":{}""", ""","message":[]""", ""","message":false""")) { + val result = parser.parseInteraction( + responseFrom( + """{"error":{"code":"invalidRequest","innerError":{"code":"attributeValidationError", + "details":[{"code":"attributeValidationFailed","attributeIds":["email"]$messageField}]}}}""" + ), + previousState(NativeAuthV2FlowScenario.SIGN_UP) + ) as NativeAuthV2InteractionApiResult.InvalidAttributes + + assertEquals( + listOf(mapOf("code" to "attributeValidationFailed", "attributeIds" to listOf("email"))), + result.attributeValidationDetails + ) + } + } + + @Test + fun parseInteraction_preservesDiagnosticsAcrossTypedAndUnknownErrors() { + val cases = listOf( + Triple("invalidGrant", "invalidOneTimeCode", NativeAuthV2InteractionApiResult.InvalidCode::class.java), + Triple("invalidGrant", "invalidUserNameOrPassword", NativeAuthV2InteractionApiResult.InvalidCredentials::class.java), + Triple("invalidRequest", "passwordTooWeak", NativeAuthV2InteractionApiResult.InvalidPassword::class.java), + Triple("invalidRequest", "attributeValidationError", NativeAuthV2InteractionApiResult.InvalidAttributes::class.java), + Triple("invalidRequest", "userNotFound", NativeAuthV2InteractionApiResult.UnknownError::class.java) + ) + for ((code, innerCode, expectedClass) in cases) { + val result = parser.parseInteraction( + responseFrom( + """{"error":{"code":"$code","message":"AADSTS10040172: Service diagnostic.", + "correlationId":"service-correlation","traceId":"service-trace", + "timestamp":"unmodified-timestamp","innerError":{"code":"$innerCode", + "details":[{"code":"attributeValidationFailed","attributeIds":["email"]}]}}}""" + ), + previousState(NativeAuthV2FlowScenario.SIGN_UP) + ) + + assertEquals(innerCode, expectedClass, result.javaClass) + val error = result as ApiErrorResult + assertEquals("service-trace", error.traceId) + assertEquals("unmodified-timestamp", error.timestamp) + assertEquals("service-correlation", error.correlationId) + assertEquals(listOf(10040172), error.errorCodes) + } + } + + @Test + fun parseAuthorizeChallenge_missingOrMalformedDiagnosticFieldsRemainNull() { + for (json in listOf( + """{"error":"future_error"}""", + """{"error":"future_error","trace_id":123,"timestamp":{}}""", + """{"error":{"code":"future_error","traceId":[],"timestamp":false}}""" + )) { + val result = parser.parseAuthorizeChallenge( + responseFrom(json), NativeAuthV2LinkRelation.SIGN_IN, + NativeAuthV2FlowScenario.SIGN_IN, emptyList() + ) as AuthorizeChallengeApiResult.UnknownError + assertNull(result.traceId) + assertNull(result.timestamp) + assertNull(result.errorCodes) + } + } + + @Test + fun parseAuthorizeChallenge_browserFallbackRetainsDiagnostics() { + val result = parser.parseAuthorizeChallenge( + responseFrom( + """{"error":{"code":"redirect_to_web","message":"AADSTS123: Browser required.", + "traceId":"fallback-trace","timestamp":"service-time"}}""" + ), + NativeAuthV2LinkRelation.SIGN_IN, NativeAuthV2FlowScenario.SIGN_IN, emptyList() + ) as AuthorizeChallengeApiResult.Redirect + assertEquals("fallback-trace", result.traceId) + assertEquals("service-time", result.timestamp) + assertEquals(listOf(123), result.errorCodes) + } + + @Test + fun parseAuthorizeChallenge_invalidErrorCodesFallBackToMessage() { + for (codes in listOf("null", "\"bad\"", "[100,\"200\"]", "[1.5]", "[2147483648]", "[2147483647.0000001]", "[null]")) { + val result = parser.parseAuthorizeChallenge( + response = responseFrom( + """{"error":"InsufficientAuthorization", + "error_description":"AADSTS500127: No authenticated credentials.", + "error_codes":$codes}""" + ), + entryRelation = NativeAuthV2LinkRelation.SIGN_IN, + scenario = NativeAuthV2FlowScenario.SIGN_IN, + scopes = emptyList() + ) as AuthorizeChallengeApiResult.UnknownError + + assertEquals(codes, listOf(500127), result.errorCodes) + } + } + @Test fun parseInteraction_whenActionMissing_returnsUnknownErrorForMissingActionField() { val response = responseFrom("""{"continuationToken":"token"}""") @@ -1138,14 +1345,16 @@ class NativeAuthV2ResponseParserTest { correlationId = CORRELATION_ID ) - private fun previousState(): NativeAuthV2ContinuationState { + private fun previousState( + scenario: NativeAuthV2FlowScenario = NativeAuthV2FlowScenario.RESET_PASSWORD + ): NativeAuthV2ContinuationState { val seedResponse = responseFrom("""{"continuationToken":"seed"}""") return NativeAuthV2ContinuationState.fromAuthorizeChallengeResponse( response = seedResponse, continuationToken = "seed", entryRelation = NativeAuthV2LinkRelation.RESET_PASSWORD, scopes = listOf("User.Read"), - scenario = NativeAuthV2FlowScenario.RESET_PASSWORD + scenario = scenario ) } diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2SignUpResponseParserTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2SignUpResponseParserTest.kt index 79e403ac70..434056d5dd 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2SignUpResponseParserTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2SignUpResponseParserTest.kt @@ -129,6 +129,10 @@ class NativeAuthV2SignUpResponseParserTest { ) assertTrue(result is NativeAuthV2InteractionApiResult.UserAlreadyExists) + assertEquals( + "userAlreadyExists", + (result as NativeAuthV2InteractionApiResult.UserAlreadyExists).attributeValidationDetails?.first()?.get("code") + ) } @Test @@ -250,6 +254,34 @@ class NativeAuthV2SignUpResponseParserTest { correlationId = CORRELATION_ID ) + @Test + fun parseInteraction_preservesRuntimeValidatedPolicyAndRequiredDetails() { + val result = parser.parseInteraction( + responseFrom("""{"error":{"code":"invalidRequest","message":"validation","innerError":{ + "code":"attributeValidationError","details":[null,42, + {"code":"passwordPolicyViolation","attributeIds":[42,"PASSWORD"]}, + {"code":"attributeRequired","attributeIds":["city"]}]}}}"""), + signUpState() + ) as NativeAuthV2InteractionApiResult.InvalidAttributes + assertEquals("attributeValidationError", result.subError) + assertEquals(listOf("PASSWORD", "city"), result.invalidAttributes) + assertEquals(2, result.attributeValidationDetails?.size) + assertEquals("passwordPolicyViolation", result.attributeValidationDetails?.first()?.get("code")) + } + + @Test + fun parseInteraction_unknownErrorRetainsSubErrorAndRejectsMalformedDetails() { + val result = parser.parseInteraction( + responseFrom("""{"error":{"code":"futureError","message":"diagnostic","innerError":{ + "code":"futureSubError","details":"bad"}}}"""), + signUpState() + ) as NativeAuthV2InteractionApiResult.UnknownError + assertEquals("futureError", result.error) + assertEquals("diagnostic", result.errorDescription) + assertEquals("futureSubError", result.subError) + assertTrue(result.attributeValidationDetails.orEmpty().isEmpty()) + } + private fun signUpState(): NativeAuthV2ContinuationState = NativeAuthV2ContinuationState.fromAuthorizeChallengeResponse( response = responseFrom("""{"continuationToken":"seed","signUp":"/tenant/signup/start"}"""), diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandlerTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandlerTest.kt index 7e867f43b2..40c403204b 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandlerTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandlerTest.kt @@ -36,6 +36,60 @@ import org.junit.Test class NativeAuthV2ResponseHandlerTest { private val handler = NativeAuthV2ResponseHandler() + @Test + fun getTokenApiResponse_explicitErrorCodesIncludingEmptyArrayOverrideMessage() { + for (codes in listOf(emptyList(), listOf(123, 456))) { + val result = handler.getTokenApiResponse( + CORRELATION_ID, + response(400, """{"error":"invalid_grant", + "error_description":"AADSTS50126: Credentials rejected.","error_codes":$codes, + "trace_id":123,"timestamp":{}}""") + ) as SignInTokenApiResult.UnknownError + assertEquals(codes, result.errorCodes) + assertNull(result.traceId) + assertNull(result.timestamp) + } + } + + @Test + fun getTokenApiResponse_preservesDiagnosticsForRecoverableTokenErrors() { + val cases = listOf( + "mfa_required" to SignInTokenApiResult.MFARequired::class.java, + "registration_required" to SignInTokenApiResult.JITRequired::class.java, + "invalid_oob_value" to SignInTokenApiResult.CodeIncorrect::class.java + ) + for ((subError, expectedClass) in cases) { + val result = handler.getTokenApiResponse( + CORRELATION_ID, + response(400, """{"error":"invalid_grant","suberror":"$subError", + "continuation_token":"token","error_description":"AADSTS123: Diagnostic.", + "trace_id":"recoverable-trace","timestamp":"raw-time"}""") + ) + assertEquals(expectedClass, result.javaClass) + val error = result as ApiErrorResult + assertEquals(listOf(123), error.errorCodes) + assertEquals("recoverable-trace", error.traceId) + assertEquals("raw-time", error.timestamp) + } + } + + @Test + fun getTokenApiResponse_invalidErrorCodesFallBackToMessageWithoutChangingClassification() { + for (codes in listOf("null", "\"bad\"", "[100,\"200\"]", "[1.5]", "[2147483648]", "[2147483647.0000001]", "[null]")) { + val result = handler.getTokenApiResponse( + CORRELATION_ID, + response( + 400, + """{"error":"invalid_grant","error_description":"AADSTS50126: Credentials rejected.", + "error_codes":$codes}""" + ) + ) + + assertTrue(codes, result is SignInTokenApiResult.UnknownError) + assertEquals(codes, listOf(50126), (result as ApiErrorResult).errorCodes) + } + } + @Test fun getTokenApiResponse_whenStatusCodeUnavailable_returnsTypedUnknownError() { val result = handler.getTokenApiResponse( @@ -219,6 +273,74 @@ class NativeAuthV2ResponseHandlerTest { assertEquals(CORRELATION_ID, error.correlationId) assertEquals("invalid_request", error.error) assertEquals("Bad request.", error.errorDescription) + assertNull(error.subError) + } + + @Test + fun getTokenApiResponse_preservesSubErrorsAcrossTokenErrorMappings() { + val cases = listOf( + Triple("invalid_request", emptyList(), SignInTokenApiResult.UnknownError::class.java), + Triple("invalid_request", listOf(90000), SignInTokenApiResult.UnknownError::class.java), + Triple("invalid_request", listOf(50142), SignInTokenApiResult.UnknownError::class.java), + Triple("invalid_grant", emptyList(), SignInTokenApiResult.UnknownError::class.java), + Triple("invalid_grant", listOf(50126), SignInTokenApiResult.InvalidCredentials::class.java), + Triple("invalid_grant", listOf(400002), SignInTokenApiResult.InvalidAuthenticationType::class.java), + Triple("user_not_found", listOf(50034), SignInTokenApiResult.UserNotFound::class.java), + Triple("future_error", listOf(90000), SignInTokenApiResult.UnknownError::class.java) + ) + + for ((errorCode, errorCodes, resultClass) in cases) { + for (subError in listOf("FutureServiceSubError", "", null)) { + val context = "$errorCode, $errorCodes, suberror=$subError" + val subErrorJson = subError?.let { "\"$it\"" } ?: "null" + val result = handler.getTokenApiResponse( + requestCorrelationId = CORRELATION_ID, + response = response( + statusCode = 400, + body = """{ + "error":"$errorCode", + "error_description":"Service diagnostic.", + "error_codes":$errorCodes, + "trace_id":"token-trace", + "timestamp":"2026-10-15 11:00:20Z", + "suberror":$subErrorJson + }""" + ) + ) + + assertEquals(context, resultClass, result.javaClass) + val error = result as ApiErrorResult + assertEquals(context, subError, error.subError) + assertEquals(context, "token-trace", error.traceId) + assertEquals(context, "2026-10-15 11:00:20Z", error.timestamp) + assertEquals(context, errorCode, error.error) + assertEquals(context, errorCodes, error.errorCodes) + assertEquals(context, CORRELATION_ID, error.correlationId) + assertTrue(context, error.errorDescription.orEmpty().endsWith("Service diagnostic.")) + } + } + } + + @Test + fun getTokenApiResponse_whenRequiredContinuationTokenIsMissing_preservesSubError() { + for (subError in listOf("mfa_required", "registration_required")) { + val result = handler.getTokenApiResponse( + requestCorrelationId = CORRELATION_ID, + response = response( + statusCode = 400, + body = """{"error":"invalid_grant","suberror":"$subError", + "trace_id":"token-trace","timestamp":"raw-time"}""" + ) + ) + + assertTrue(result is SignInTokenApiResult.UnknownError) + val error = result as ApiErrorResult + assertEquals(subError, error.subError) + assertEquals("token-trace", error.traceId) + assertEquals("raw-time", error.timestamp) + assertEquals(ApiErrorResult.INVALID_STATE, error.error) + assertEquals("oauth/v2.0/token did not return a continuation token", error.errorDescription) + } } @Test