From 1505acff7e479a67a0cd47cfa94ad079dc158918 Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Mon, 12 Oct 2026 11:36:00 -0700 Subject: [PATCH 1/5] Preserve Native Auth V2 unified-error diagnostics Fixes AB#3784695 Keep raw suberrors and validated attribute details through parser and command results. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 0bcd671b-73fa-4ee6-bcd6-65d7eea4d753 --- .../v2/NativeAuthV2FlowController.kt | 22 +++++++++++-- .../results/INativeAuthCommandResult.kt | 6 ++-- .../results/NativeAuthV2CommandResult.kt | 4 +++ .../providers/responses/ApiErrorResult.kt | 5 +-- .../v2/AuthorizeChallengeApiResult.kt | 4 ++- .../v2/NativeAuthV2InteractionApiResult.kt | 12 +++++-- .../v2/NativeAuthV2ResponseParser.kt | 29 ++++++++++++----- .../NativeAuthV2SignUpResponseParserTest.kt | 32 +++++++++++++++++++ 8 files changed, 95 insertions(+), 19 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 e7a6208846..92ba4d9d5d 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 @@ -188,6 +188,8 @@ 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, @@ -714,6 +716,8 @@ 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, @@ -1085,6 +1089,8 @@ 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( @@ -1109,6 +1115,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) return NativeAuthV2CommandResult.Complete( + subError = tokenResult.subError, + attributeValidationDetails = tokenResult.attributeValidationDetails, correlationId = complete.correlationId, authenticationResult = complete.authenticationResult, continuationToken = null, @@ -1191,6 +1199,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { result = startResult, retryState = null, upfront = parameters + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, ) return result as? NativeAuthV2SignUpStartCommandResult ?: unexpectedSignUpApiError(result, correlationId) @@ -1333,7 +1343,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = result.correlationId, error = result.error, errorDescription = result.errorDescription, - errorCodes = result.errorCodes + errorCodes = result.errorCodes, + subError = result.subError, + attributeValidationDetails = result.attributeValidationDetails ) is NativeAuthV2InteractionApiResult.InvalidAttributes -> if (retryState != null) { NativeAuthV2CommandResult.AttributesInvalid( @@ -1342,7 +1354,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { invalidAttributes = result.invalidAttributes, error = result.error, errorDescription = result.errorDescription, - errorCodes = result.errorCodes + errorCodes = result.errorCodes, + subError = result.subError, + attributeValidationDetails = result.attributeValidationDetails ) } else { mapInteractionError(result) @@ -1562,7 +1576,9 @@ 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 ) } } 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..7a447ce10d 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 @@ -60,13 +60,15 @@ 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 ): 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..264446c9e0 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 @@ -371,6 +371,8 @@ interface NativeAuthV2CommandResult { val error: String, val errorDescription: String, val errorCodes: List? = null, + val subError: String? = null, + val attributeValidationDetails: List>? = null, ) : NativeAuthV2SignUpStartCommandResult, NativeAuthV2SubmitAttributesCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.AttributesInvalid(correlationId=$correlationId, invalidAttributes=$invalidAttributes, error=$error, errorDescription=$errorDescription)" @@ -388,6 +390,8 @@ interface NativeAuthV2CommandResult { val error: String, val errorDescription: String, val errorCodes: List? = null, + val subError: String? = null, + val attributeValidationDetails: List>? = 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..b98610748c 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,12 +25,13 @@ 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 { companion object { 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..f3b5349c6d 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 @@ -76,7 +76,9 @@ sealed interface AuthorizeChallengeApiResult : ApiResult { 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 ) : ApiErrorResult( error = error, errorDescription = errorDescription, 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..f87f8ef19e 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 @@ -278,7 +278,9 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { 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 ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -300,7 +302,9 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { 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 ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -342,7 +346,9 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { 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 ) : 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..a1edb0ff2d 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 @@ -84,7 +84,9 @@ class NativeAuthV2ResponseParser { ?.takeUnless { it.isBlank() } ?: response.correlationId, error = serverError.code ?: ApiErrorResult.INVALID_STATE, errorDescription = serverError.message.orEmpty(), - errorCodes = extractAadstsCodes(serverError.message) + errorCodes = extractAadstsCodes(serverError.message), + subError = serverError.innerErrorCode, + attributeValidationDetails = validationDetails(serverError) ) } @@ -558,7 +560,7 @@ class NativeAuthV2ResponseParser { ) innerErrorCode == INNER_ERROR_INVALID_CONTINUATION_TOKEN -> - unknownInteractionError(correlationId, code, message, errorCodes) + unknownInteractionError(correlationId, code, message, errorCodes, innerErrorCode, validationDetails(serverError)) scenario == NativeAuthV2FlowScenario.SIGN_UP && innerErrorCode == INNER_ERROR_ATTRIBUTE_VALIDATION_FAILED -> @@ -568,14 +570,16 @@ class NativeAuthV2ResponseParser { .flatMap { it.attributeIds } .distinct() if (invalidAttributes.isEmpty()) { - unknownInteractionError(correlationId, code, message, errorCodes) + unknownInteractionError(correlationId, code, message, errorCodes, innerErrorCode, validationDetails(serverError)) } else { NativeAuthV2InteractionApiResult.InvalidAttributes( correlationId = correlationId, invalidAttributes = invalidAttributes, error = code.orEmpty(), errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + subError = innerErrorCode, + attributeValidationDetails = validationDetails(serverError) ) } } @@ -587,7 +591,9 @@ class NativeAuthV2ResponseParser { correlationId = correlationId, error = code.orEmpty(), errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + subError = innerErrorCode, + attributeValidationDetails = validationDetails(serverError) ) code == ERROR_INVALID_REQUEST && innerErrorCode in INNER_ERROR_INVALID_PASSWORD -> @@ -621,7 +627,7 @@ class NativeAuthV2ResponseParser { errorCodes = errorCodes ) - else -> unknownInteractionError(correlationId, code, message, errorCodes) + else -> unknownInteractionError(correlationId, code, message, errorCodes, innerErrorCode, validationDetails(serverError)) } } @@ -629,14 +635,21 @@ class NativeAuthV2ResponseParser { correlationId: String, code: String?, message: String?, - errorCodes: List? + errorCodes: List?, + subError: String? = null, + attributeValidationDetails: List>? = null ): NativeAuthV2InteractionApiResult.UnknownError = NativeAuthV2InteractionApiResult.UnknownError( correlationId = correlationId, error = code ?: ApiErrorResult.INVALID_STATE, errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + subError = subError, + attributeValidationDetails = attributeValidationDetails ) + private fun validationDetails(error: NativeAuthV2HalApiResponse.HalServerError): List> = + error.details.map { mapOf("code" to it.code, "attributeIds" to it.attributeIds) } + private fun missingLinkError( correlationId: String, relation: NativeAuthV2LinkRelation 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"}"""), From 3265533f27d8c4054fc5b020ec0228bb872b8344 Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Mon, 12 Oct 2026 12:07:07 -0700 Subject: [PATCH 2/5] 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 --- .../v2/NativeAuthV2FlowController.kt | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 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..0cf8e3ffea 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 @@ -177,6 +177,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -188,8 +190,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, @@ -705,6 +705,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -716,8 +718,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, @@ -1077,6 +1077,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = continueResult.error, errorDescription = continueResult.errorDescription, errorCodes = continueResult.errorCodes, + subError = continueResult.subError, + attributeValidationDetails = continueResult.attributeValidationDetails, correlationId = continueResult.correlationId ) } @@ -1089,8 +1091,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 +1103,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = tokenResult.error, errorDescription = tokenResult.errorDescription, errorCodes = tokenResult.errorCodes, + subError = tokenResult.subError, + attributeValidationDetails = tokenResult.attributeValidationDetails, correlationId = tokenResult.correlationId ) } @@ -1115,8 +1117,6 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) return NativeAuthV2CommandResult.Complete( - subError = tokenResult.subError, - attributeValidationDetails = tokenResult.attributeValidationDetails, correlationId = complete.correlationId, authenticationResult = complete.authenticationResult, continuationToken = null, @@ -1187,6 +1187,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -1199,8 +1201,6 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { result = startResult, retryState = null, upfront = parameters - subError = authChallengeResult.subError, - attributeValidationDetails = authChallengeResult.attributeValidationDetails, ) return result as? NativeAuthV2SignUpStartCommandResult ?: unexpectedSignUpApiError(result, correlationId) From 0e45650da664d3bcc93b6876ec042382bb6613f6 Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Thu, 15 Oct 2026 12:38:38 -0700 Subject: [PATCH 3/5] Preserve Native Auth V2 service error diagnostics Forward trace IDs, timestamps, numeric error codes, and token suberrors through response parsing and V2 command results. Preserve explicit-code precedence and cover typed, generic, and browser fallback mappings. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 55791345-e680-4927-a364-f6de503184be --- .../v2/NativeAuthV2FlowController.kt | 96 +++++++++++++- .../NativeAuthV2SignUpFlowControllerTest.kt | 93 +++++++++++-- .../results/INativeAuthCommandResult.kt | 17 ++- .../results/NativeAuthV2CommandResult.kt | 28 +++- .../providers/responses/ApiErrorResult.kt | 6 + .../signin/SignInTokenApiResponse.kt | 71 +++++++--- .../responses/signin/SignInTokenApiResult.kt | 47 +++++-- .../v2/AuthorizeChallengeApiResult.kt | 13 +- .../v2/NativeAuthV2HalApiResponse.kt | 16 ++- .../v2/NativeAuthV2InteractionApiResult.kt | 49 ++++--- .../v2/NativeAuthV2ResponseParser.kt | 77 ++++++----- .../v2/NativeAuthV2ErrorDiagnostics.kt | 32 +++++ .../v2/NativeAuthV2ResponseHandler.kt | 33 ++++- .../v2/NativeAuthV2ResponseParserTest.kt | 105 ++++++++++++++- .../v2/NativeAuthV2ResponseHandlerTest.kt | 122 ++++++++++++++++++ 15 files changed, 693 insertions(+), 112 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 0cf8e3ffea..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,6 +179,8 @@ 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, @@ -195,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) @@ -289,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) @@ -341,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) @@ -389,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) @@ -439,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) @@ -494,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) @@ -546,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) @@ -603,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) @@ -688,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 -> { @@ -704,6 +746,8 @@ 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, @@ -723,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) @@ -771,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) @@ -806,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) @@ -868,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) @@ -922,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) @@ -970,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) @@ -1065,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( @@ -1076,6 +1149,8 @@ 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, @@ -1095,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 -> { @@ -1102,6 +1180,8 @@ 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, @@ -1171,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 -> { @@ -1186,6 +1269,8 @@ 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, @@ -1343,6 +1428,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = result.correlationId, error = result.error, errorDescription = result.errorDescription, + traceId = result.traceId, + timestamp = result.timestamp, errorCodes = result.errorCodes, subError = result.subError, attributeValidationDetails = result.attributeValidationDetails @@ -1354,6 +1441,8 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { invalidAttributes = result.invalidAttributes, error = result.error, errorDescription = result.errorDescription, + traceId = result.traceId, + timestamp = result.timestamp, errorCodes = result.errorCodes, subError = result.subError, attributeValidationDetails = result.attributeValidationDetails @@ -1363,6 +1452,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { } is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = result.correlationId, + traceId = result.traceId, + timestamp = result.timestamp, + errorCodes = result.errorCodes, redirectReason = result.redirectReason ) else -> mapInteractionError(result) @@ -1578,7 +1670,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { errorCodes = errorCodes, correlationId = result.correlationId, subError = (result as? ApiErrorResult)?.subError, - attributeValidationDetails = (result as? ApiErrorResult)?.attributeValidationDetails + 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/NativeAuthV2SignUpFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt index 2eae4a90f5..41ce331281 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,36 @@ class NativeAuthV2SignUpFlowControllerTest { @Test fun testSignUpStartSurfacesUserAlreadyExists() { val entryState = mockContinuationState() + val details = listOf(mapOf("code" to "userAlreadyExists", "attributeIds" to listOf("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"))) every { entryState.withAdditionalSubmittedAttributes( match { @@ -190,7 +199,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 +211,46 @@ 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"))) + 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 +286,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 +525,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 +537,8 @@ class NativeAuthV2SignUpFlowControllerTest { "expected_test_error", (result as INativeAuthCommandResult.APIError).error ) + assertEquals("authorize-trace", result.traceId) + assertEquals("authorize-time", result.timestamp) } @Test @@ -536,17 +595,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 7a447ce10d..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, @@ -68,7 +75,9 @@ interface INativeAuthCommandResult : ILoggable { override val errorCodes: List? = null, val exception: Exception? = null, val subError: String? = null, - val attributeValidationDetails: List>? = 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 264446c9e0..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,7 +374,7 @@ 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, @@ -373,6 +383,8 @@ interface NativeAuthV2CommandResult { 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)" @@ -385,13 +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 b98610748c..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 @@ -34,6 +34,12 @@ abstract class ApiErrorResult @JvmOverloads constructor( 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 f3b5349c6d..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,13 +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 subError: String? = null, - override val attributeValidationDetails: List>? = 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..7af0c5df5f 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,7 +76,10 @@ 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 ) /** @@ -328,7 +332,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 +345,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 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 f87f8ef19e..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,13 +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 subError: String? = null, - override val attributeValidationDetails: List>? = null + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -297,14 +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 subError: String? = null, - override val attributeValidationDetails: List>? = null + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -342,13 +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 subError: String? = null, - override val attributeValidationDetails: List>? = 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 a1edb0ff2d..c5d4e801e9 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,9 +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) + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) } @@ -175,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) ) } @@ -547,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 -> @@ -556,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, innerErrorCode, validationDetails(serverError)) + unknownInteractionError(correlationId, serverError, errorCodes) scenario == NativeAuthV2FlowScenario.SIGN_UP && innerErrorCode == INNER_ERROR_ATTRIBUTE_VALIDATION_FAILED -> @@ -570,7 +581,7 @@ class NativeAuthV2ResponseParser { .flatMap { it.attributeIds } .distinct() if (invalidAttributes.isEmpty()) { - unknownInteractionError(correlationId, code, message, errorCodes, innerErrorCode, validationDetails(serverError)) + unknownInteractionError(correlationId, serverError, errorCodes) } else { NativeAuthV2InteractionApiResult.InvalidAttributes( correlationId = correlationId, @@ -579,7 +590,9 @@ class NativeAuthV2ResponseParser { errorDescription = message.orEmpty(), errorCodes = errorCodes, subError = innerErrorCode, - attributeValidationDetails = validationDetails(serverError) + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) } } @@ -593,7 +606,9 @@ class NativeAuthV2ResponseParser { errorDescription = message.orEmpty(), errorCodes = errorCodes, subError = innerErrorCode, - attributeValidationDetails = validationDetails(serverError) + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) code == ERROR_INVALID_REQUEST && innerErrorCode in INNER_ERROR_INVALID_PASSWORD -> @@ -602,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 && @@ -612,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 @@ -624,27 +643,28 @@ 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, innerErrorCode, validationDetails(serverError)) + else -> unknownInteractionError(correlationId, serverError, errorCodes) } } private fun unknownInteractionError( correlationId: String, - code: String?, - message: String?, - errorCodes: List?, - subError: String? = null, - attributeValidationDetails: List>? = null + serverError: NativeAuthV2HalApiResponse.HalServerError, + errorCodes: List? ): NativeAuthV2InteractionApiResult.UnknownError = NativeAuthV2InteractionApiResult.UnknownError( correlationId = correlationId, - error = code ?: ApiErrorResult.INVALID_STATE, - errorDescription = message.orEmpty(), + error = serverError.code ?: ApiErrorResult.INVALID_STATE, + errorDescription = serverError.message.orEmpty(), errorCodes = errorCodes, - subError = subError, - attributeValidationDetails = attributeValidationDetails + subError = serverError.innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) private fun validationDetails(error: NativeAuthV2HalApiResponse.HalServerError): List> = @@ -698,19 +718,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/NativeAuthV2ResponseParserTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt index 901f7d913f..530eba3619 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,105 @@ 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 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 +1237,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/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 From 525c8621af137e5c5b8634e21b37f0d8f51d98a3 Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Thu, 15 Oct 2026 13:55:17 -0700 Subject: [PATCH 4/5] Preserve Native Auth V2 attribute validation messages Retain service-provided detail messages alongside validation codes and attribute IDs without changing error classification. Cover supported payload shapes and controller forwarding. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 495388ac-9812-45ec-9120-b110dcbe5903 --- .../NativeAuthV2SignUpFlowControllerTest.kt | 18 ++- .../v2/NativeAuthV2HalApiResponse.kt | 9 +- .../v2/NativeAuthV2ResponseParser.kt | 5 +- .../v2/NativeAuthV2HalApiResponseTest.kt | 42 +++++++ .../v2/NativeAuthV2ResponseParserTest.kt | 108 ++++++++++++++++++ 5 files changed, 175 insertions(+), 7 deletions(-) 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 41ce331281..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 @@ -147,7 +147,11 @@ class NativeAuthV2SignUpFlowControllerTest { @Test fun testSignUpStartSurfacesUserAlreadyExists() { val entryState = mockContinuationState() - val details = listOf(mapOf("code" to "userAlreadyExists", "attributeIds" to listOf("email"))) + 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( @@ -176,7 +180,11 @@ class NativeAuthV2SignUpFlowControllerTest { fun testSignUpStartMapsInvalidAttributesToRetryableAttributesInvalid() { val entryState = mockContinuationState() val submittedState = mockContinuationState() - val details = listOf(mapOf("code" to "attributeRequired", "attributeIds" to listOf("city"))) + val details = listOf(mapOf( + "code" to "attributeRequired", + "attributeIds" to listOf("city"), + "message" to "Enter a city." + )) every { entryState.withAdditionalSubmittedAttributes( match { @@ -223,7 +231,11 @@ class NativeAuthV2SignUpFlowControllerTest { @Test fun testSignUpStartPreservesUnknownErrorDiagnostics() { val entryState = mockContinuationState() - val details = listOf(mapOf("code" to "futureValidationCode", "attributeIds" to listOf("city"))) + 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( 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 7af0c5df5f..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 @@ -84,11 +84,13 @@ class NativeAuthV2HalApiResponse private constructor( /** * 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 @@ -370,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/NativeAuthV2ResponseParser.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt index c5d4e801e9..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 @@ -668,7 +668,10 @@ class NativeAuthV2ResponseParser { ) private fun validationDetails(error: NativeAuthV2HalApiResponse.HalServerError): List> = - error.details.map { mapOf("code" to it.code, "attributeIds" to it.attributeIds) } + 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, 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 530eba3619..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 @@ -57,6 +57,114 @@ class NativeAuthV2ResponseParserTest { } } + @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( From 98b83431ebd6df6529bae42ba73d099f1b2d35dc Mon Sep 17 00:00:00 2001 From: Disha Janardhan Date: Thu, 15 Oct 2026 23:45:12 -0700 Subject: [PATCH 5/5] Increase Native Auth V2 controller error-path coverage Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 495388ac-9812-45ec-9120-b110dcbe5903 --- .../NativeAuthV2SignInFlowControllerTest.kt | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) 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 // -----------------------------------------------------------------------------------------