diff --git a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt index e7a6208846..c93865aa75 100644 --- a/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt +++ b/common/src/main/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2FlowController.kt @@ -160,6 +160,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is AuthorizeChallengeApiResult.ContinuationRequired -> authChallengeResult.continuationState is AuthorizeChallengeApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = authChallengeResult.correlationId, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, + errorCodes = authChallengeResult.errorCodes, redirectReason = authChallengeResult.redirectReason ) is AuthorizeChallengeApiResult.AuthorizationCode -> { @@ -176,7 +179,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -193,10 +200,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = startResult.correlationId, error = startResult.error, errorDescription = startResult.errorDescription, + traceId = startResult.traceId, + timestamp = startResult.timestamp, errorCodes = startResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = startResult.correlationId, + traceId = startResult.traceId, + timestamp = startResult.timestamp, + errorCodes = startResult.errorCodes, redirectReason = startResult.redirectReason ) else -> return mapInteractionError(startResult) @@ -287,6 +299,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verificationResult.correlationId, + traceId = verificationResult.traceId, + timestamp = verificationResult.timestamp, + errorCodes = verificationResult.errorCodes, redirectReason = verificationResult.redirectReason ) else -> mapInteractionError(verificationResult) @@ -339,10 +354,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -387,10 +407,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -437,10 +462,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -492,6 +522,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = resendResult.correlationId, + traceId = resendResult.traceId, + timestamp = resendResult.timestamp, + errorCodes = resendResult.errorCodes, redirectReason = resendResult.redirectReason ) else -> mapInteractionError(resendResult) @@ -544,10 +577,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = updateResult.error, errorDescription = updateResult.errorDescription, subError = updateResult.subError, + traceId = updateResult.traceId, + timestamp = updateResult.timestamp, errorCodes = updateResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = updateResult.correlationId, + traceId = updateResult.traceId, + timestamp = updateResult.timestamp, + errorCodes = updateResult.errorCodes, redirectReason = updateResult.redirectReason ) else -> mapInteractionError(updateResult) @@ -601,6 +639,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { } is NativeAuthV2InteractionApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = pollResult.correlationId, + traceId = pollResult.traceId, + timestamp = pollResult.timestamp, + errorCodes = pollResult.errorCodes, redirectReason = pollResult.redirectReason ) else -> return mapInteractionError(pollResult) @@ -686,6 +727,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is AuthorizeChallengeApiResult.ContinuationRequired -> authChallengeResult.continuationState is AuthorizeChallengeApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = authChallengeResult.correlationId, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, + errorCodes = authChallengeResult.errorCodes, redirectReason = authChallengeResult.redirectReason ) is AuthorizeChallengeApiResult.AuthorizationCode -> { @@ -702,7 +746,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -719,10 +767,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = startResult.correlationId, error = startResult.error, errorDescription = startResult.errorDescription, + traceId = startResult.traceId, + timestamp = startResult.timestamp, errorCodes = startResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = startResult.correlationId, + traceId = startResult.traceId, + timestamp = startResult.timestamp, + errorCodes = startResult.errorCodes, redirectReason = startResult.redirectReason ) else -> return mapInteractionError(startResult) @@ -767,6 +820,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is NativeAuthV2InteractionApiResult.PasswordRequired -> firstFactorChallengeResult.continuationState is NativeAuthV2InteractionApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = firstFactorChallengeResult.correlationId, + traceId = firstFactorChallengeResult.traceId, + timestamp = firstFactorChallengeResult.timestamp, + errorCodes = firstFactorChallengeResult.errorCodes, redirectReason = firstFactorChallengeResult.redirectReason ) else -> return mapInteractionError(firstFactorChallengeResult) @@ -802,10 +858,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -864,10 +925,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -918,6 +984,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verificationResult.correlationId, + traceId = verificationResult.traceId, + timestamp = verificationResult.timestamp, + errorCodes = verificationResult.errorCodes, redirectReason = verificationResult.redirectReason ) else -> mapInteractionError(verificationResult) @@ -966,10 +1035,15 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = verifyResult.error, errorDescription = verifyResult.errorDescription, subError = verifyResult.subError, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, errorCodes = verifyResult.errorCodes ) is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = verifyResult.correlationId, + traceId = verifyResult.traceId, + timestamp = verifyResult.timestamp, + errorCodes = verifyResult.errorCodes, redirectReason = verifyResult.redirectReason ) else -> mapInteractionError(verifyResult) @@ -1061,6 +1135,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is AuthorizeChallengeApiResult.AuthorizationCode -> continueResult.code is AuthorizeChallengeApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = continueResult.correlationId, + traceId = continueResult.traceId, + timestamp = continueResult.timestamp, + errorCodes = continueResult.errorCodes, redirectReason = continueResult.redirectReason ) is AuthorizeChallengeApiResult.ContinuationRequired -> return INativeAuthCommandResult.APIError( @@ -1072,7 +1149,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = continueResult.error, errorDescription = continueResult.errorDescription, + traceId = continueResult.traceId, + timestamp = continueResult.timestamp, errorCodes = continueResult.errorCodes, + subError = continueResult.subError, + attributeValidationDetails = continueResult.attributeValidationDetails, correlationId = continueResult.correlationId ) } @@ -1089,6 +1170,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is SignInTokenApiResult.Success -> tokenResult is SignInTokenApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = tokenResult.correlationId, + traceId = tokenResult.traceId, + timestamp = tokenResult.timestamp, + errorCodes = tokenResult.errorCodes, redirectReason = tokenResult.redirectReason ) else -> { @@ -1096,7 +1180,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = tokenResult.error, errorDescription = tokenResult.errorDescription, + traceId = tokenResult.traceId, + timestamp = tokenResult.timestamp, errorCodes = tokenResult.errorCodes, + subError = tokenResult.subError, + attributeValidationDetails = tokenResult.attributeValidationDetails, correlationId = tokenResult.correlationId ) } @@ -1163,6 +1251,9 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { is AuthorizeChallengeApiResult.ContinuationRequired -> authChallengeResult.continuationState is AuthorizeChallengeApiResult.Redirect -> return INativeAuthCommandResult.Redirect( correlationId = authChallengeResult.correlationId, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, + errorCodes = authChallengeResult.errorCodes, redirectReason = authChallengeResult.redirectReason ) is AuthorizeChallengeApiResult.AuthorizationCode -> { @@ -1178,7 +1269,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { return INativeAuthCommandResult.APIError( error = authChallengeResult.error, errorDescription = authChallengeResult.errorDescription, + traceId = authChallengeResult.traceId, + timestamp = authChallengeResult.timestamp, errorCodes = authChallengeResult.errorCodes, + subError = authChallengeResult.subError, + attributeValidationDetails = authChallengeResult.attributeValidationDetails, correlationId = authChallengeResult.correlationId ) } @@ -1333,7 +1428,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { correlationId = result.correlationId, error = result.error, errorDescription = result.errorDescription, - errorCodes = result.errorCodes + traceId = result.traceId, + timestamp = result.timestamp, + errorCodes = result.errorCodes, + subError = result.subError, + attributeValidationDetails = result.attributeValidationDetails ) is NativeAuthV2InteractionApiResult.InvalidAttributes -> if (retryState != null) { NativeAuthV2CommandResult.AttributesInvalid( @@ -1342,13 +1441,20 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { invalidAttributes = result.invalidAttributes, error = result.error, errorDescription = result.errorDescription, - errorCodes = result.errorCodes + traceId = result.traceId, + timestamp = result.timestamp, + errorCodes = result.errorCodes, + subError = result.subError, + attributeValidationDetails = result.attributeValidationDetails ) } else { mapInteractionError(result) } is NativeAuthV2InteractionApiResult.Redirect -> INativeAuthCommandResult.Redirect( correlationId = result.correlationId, + traceId = result.traceId, + timestamp = result.timestamp, + errorCodes = result.errorCodes, redirectReason = result.redirectReason ) else -> mapInteractionError(result) @@ -1562,7 +1668,11 @@ class NativeAuthV2FlowController : BaseNativeAuthController() { error = error, errorDescription = errorDescription, errorCodes = errorCodes, - correlationId = result.correlationId + correlationId = result.correlationId, + subError = (result as? ApiErrorResult)?.subError, + attributeValidationDetails = (result as? ApiErrorResult)?.attributeValidationDetails, + traceId = (result as? ApiErrorResult)?.traceId, + timestamp = (result as? ApiErrorResult)?.timestamp ) } } diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt index 7d62e9b53d..b19a013ddf 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignInFlowControllerTest.kt @@ -43,7 +43,9 @@ import io.mockk.slot import io.mockk.verify import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame import org.junit.Assert.assertTrue +import org.junit.Assert.fail import org.junit.Before import org.junit.Test @@ -817,6 +819,138 @@ class NativeAuthV2SignInFlowControllerTest { } } + @Test + fun testSignInSubmissionsPreserveUnknownErrorDiagnostics() { + val state = mockContinuationState() + val apiError = NativeAuthV2InteractionApiResult.UnknownError( + correlationId = correlationId, + error = "service_error", + errorDescription = "The service could not verify the request.", + errorCodes = listOf(50126), + subError = "verification_failed", + attributeValidationDetails = listOf(mapOf("name" to "email", "reason" to "invalid")), + traceId = "service-trace", + timestamp = "service-time" + ) + every { mockStrategy.performPasswordVerify(state, any()) } returns apiError + every { mockStrategy.performVerify(state, any()) } returns apiError + every { mockStrategy.performMethodChallenge(state, "email-1") } returns apiError + + val results = listOf( + controller.submitPassword(submitPasswordParameters(state)), + controller.submitSignInCode(submitCodeParameters(state, "123456")), + controller.selectMFAMethod(selectMFAMethodParameters(state, "email-1")), + controller.submitMFAChallenge(submitMFAChallengeParameters(state, "123456")) + ) + + results.forEach { result -> + assertTrue(result is INativeAuthCommandResult.APIError) + result as INativeAuthCommandResult.APIError + assertEquals(apiError.correlationId, result.correlationId) + assertEquals(apiError.error, result.error) + assertEquals(apiError.errorDescription, result.errorDescription) + assertEquals(apiError.errorCodes, result.errorCodes) + assertEquals(apiError.subError, result.subError) + assertEquals(apiError.attributeValidationDetails, result.attributeValidationDetails) + assertEquals(apiError.traceId, result.traceId) + assertEquals(apiError.timestamp, result.timestamp) + } + } + + @Test + fun testSignInSubmissionsPreserveBrowserRedirectDiagnostics() { + val state = mockContinuationState() + val redirect = NativeAuthV2InteractionApiResult.Redirect( + correlationId = correlationId, + redirectReason = "browser_required", + traceId = "redirect-trace", + timestamp = "redirect-time", + errorCodes = listOf(50076) + ) + every { mockStrategy.performPasswordVerify(state, any()) } returns redirect + every { mockStrategy.performVerify(state, any()) } returns redirect + every { mockStrategy.performMethodChallenge(state, "email-1") } returns redirect + + val results = listOf( + controller.submitPassword(submitPasswordParameters(state)), + controller.submitSignInCode(submitCodeParameters(state, "123456")), + controller.selectMFAMethod(selectMFAMethodParameters(state, "email-1")), + controller.submitMFAChallenge(submitMFAChallengeParameters(state, "123456")) + ) + + results.forEach { result -> + assertTrue(result is INativeAuthCommandResult.Redirect) + result as INativeAuthCommandResult.Redirect + assertEquals(redirect.correlationId, result.correlationId) + assertEquals(redirect.redirectReason, result.redirectReason) + assertEquals(redirect.traceId, result.traceId) + assertEquals(redirect.timestamp, result.timestamp) + assertEquals(redirect.errorCodes, result.errorCodes) + } + } + + @Test + fun testSelectMFAMethodPreservesRiskVerificationErrors() { + val state = mockContinuationState() + val riskState = mockContinuationState() + every { mockStrategy.performMethodChallenge(state, "sms-1") } returns + NativeAuthV2InteractionApiResult.RiskVerificationRequired(correlationId, riskState) + every { mockStrategy.performRiskVerification(riskState) } returns + NativeAuthV2InteractionApiResult.UnknownError( + correlationId, + "risk_failed", + "Risk verification failed.", + traceId = "risk-trace" + ) + + val result = controller.selectMFAMethod(selectMFAMethodParameters(state, "sms-1")) + + assertTrue(result is INativeAuthCommandResult.APIError) + result as INativeAuthCommandResult.APIError + assertEquals("risk_failed", result.error) + assertEquals("risk-trace", result.traceId) + verify(exactly = 1) { mockStrategy.performRiskVerification(riskState) } + verify(exactly = 0) { mockStrategy.performVerify(any(), any()) } + } + + @Test + fun testSubmitPasswordRethrowsStrategyFailureAndClearsPassword() { + val state = mockContinuationState() + val password = "Password123!".toCharArray() + val failure = IllegalStateException("verification failed") + every { mockStrategy.performPasswordVerify(state, any()) } throws failure + + try { + controller.submitPassword(submitPasswordParameters(state, password)) + fail("Expected the strategy exception") + } catch (exception: IllegalStateException) { + assertSame(failure, exception) + } + + assertArrayEquals(CharArray(password.size), password) + } + + @Test + fun testMfaCommandsRethrowStrategyFailures() { + val state = mockContinuationState() + val failure = IllegalStateException("verification failed") + every { mockStrategy.performMethodChallenge(state, "email-1") } throws failure + every { mockStrategy.performVerify(state, any()) } throws failure + + try { + controller.selectMFAMethod(selectMFAMethodParameters(state, "email-1")) + fail("Expected the method-selection exception") + } catch (exception: IllegalStateException) { + assertSame(failure, exception) + } + try { + controller.submitMFAChallenge(submitMFAChallengeParameters(state, "123456")) + fail("Expected the challenge-verification exception") + } catch (exception: IllegalStateException) { + assertSame(failure, exception) + } + } + // ----------------------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------------------- diff --git a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt index 2eae4a90f5..7c885890a3 100644 --- a/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt +++ b/common/src/test/java/com/microsoft/identity/common/nativeauth/internal/controllers/v2/NativeAuthV2SignUpFlowControllerTest.kt @@ -35,6 +35,7 @@ import com.microsoft.identity.common.java.nativeauth.controllers.results.INative import com.microsoft.identity.common.java.nativeauth.controllers.results.NativeAuthV2CommandResult import com.microsoft.identity.common.java.nativeauth.controllers.results.SignUpCommandResult import com.microsoft.identity.common.java.nativeauth.providers.NativeAuthV2OAuth2Strategy +import com.microsoft.identity.common.java.nativeauth.providers.responses.signin.SignInTokenApiResponse import com.microsoft.identity.common.java.nativeauth.providers.responses.signin.SignInTokenApiResult import com.microsoft.identity.common.java.nativeauth.providers.responses.v2.AuthorizeChallengeApiResult import com.microsoft.identity.common.java.nativeauth.providers.responses.v2.NativeAuthV2ContinuationState @@ -146,28 +147,44 @@ class NativeAuthV2SignUpFlowControllerTest { @Test fun testSignUpStartSurfacesUserAlreadyExists() { val entryState = mockContinuationState() + val details = listOf(mapOf( + "code" to "userAlreadyExists", + "attributeIds" to listOf("email"), + "message" to "An account already exists for this email." + )) stubAuthorizeChallengeStart(entryState) every { mockStrategy.performSignUpStart(entryState) } returns NativeAuthV2InteractionApiResult.UserAlreadyExists( correlationId = correlationId, error = "user_already_exists", errorDescription = "AADSTS1003037: account already exists.", - errorCodes = listOf(1003037) + errorCodes = listOf(1003037), + subError = "attributeValidationError", + traceId = "service-trace", + timestamp = "service-time", + attributeValidationDetails = details ) val result = controller.signUpStart(signUpStartParameters()) assertTrue(result is NativeAuthV2CommandResult.UserAlreadyExists) - assertEquals( - listOf(1003037), - (result as NativeAuthV2CommandResult.UserAlreadyExists).errorCodes - ) + result as NativeAuthV2CommandResult.UserAlreadyExists + assertEquals(listOf(1003037), result.errorCodes) + assertEquals("attributeValidationError", result.subError) + assertEquals("service-trace", result.traceId) + assertEquals("service-time", result.timestamp) + assertEquals(details, result.attributeValidationDetails) } @Test fun testSignUpStartMapsInvalidAttributesToRetryableAttributesInvalid() { val entryState = mockContinuationState() val submittedState = mockContinuationState() + val details = listOf(mapOf( + "code" to "attributeRequired", + "attributeIds" to listOf("city"), + "message" to "Enter a city." + )) every { entryState.withAdditionalSubmittedAttributes( match { @@ -190,7 +207,11 @@ class NativeAuthV2SignUpFlowControllerTest { invalidAttributes = listOf("city"), error = "attribute_validation_failed", errorDescription = "AADSTS1002027: attribute validation failed.", - errorCodes = listOf(1002027) + errorCodes = listOf(1002027), + subError = "attributeValidationError", + traceId = "service-trace", + timestamp = "service-time", + attributeValidationDetails = details ) val result = controller.signUpStart(signUpStartParameters()) @@ -198,11 +219,50 @@ class NativeAuthV2SignUpFlowControllerTest { assertTrue(result is NativeAuthV2CommandResult.AttributesInvalid) result as NativeAuthV2CommandResult.AttributesInvalid assertEquals(listOf("city"), result.invalidAttributes) + assertEquals("service-trace", result.traceId) + assertEquals("service-time", result.timestamp) + assertEquals("attributeValidationError", result.subError) + assertEquals(details, result.attributeValidationDetails) // The validation-error body carries no fresh continuation token, so retry with a state // that remembers the email and password submitted by the rejected request. assertSame(submittedState, result.continuationState) } + @Test + fun testSignUpStartPreservesUnknownErrorDiagnostics() { + val entryState = mockContinuationState() + val details = listOf(mapOf( + "code" to "futureValidationCode", + "attributeIds" to listOf("city"), + "message" to "Unrecognized attribute diagnostic." + )) + stubAuthorizeChallengeStart(entryState) + every { mockStrategy.performSignUpStart(entryState) } returns + NativeAuthV2InteractionApiResult.UnknownError( + correlationId = correlationId, + error = "future_error", + errorDescription = "Unrecognized service error.", + errorCodes = listOf(90000), + subError = "future_suberror", + traceId = "service-trace", + timestamp = "service-time", + attributeValidationDetails = details + ) + + val result = controller.signUpStart(signUpStartParameters()) + + assertTrue(result is INativeAuthCommandResult.APIError) + result as INativeAuthCommandResult.APIError + assertEquals("future_error", result.error) + assertEquals("Unrecognized service error.", result.errorDescription) + assertEquals(listOf(90000), result.errorCodes) + assertEquals(correlationId, result.correlationId) + assertEquals("future_suberror", result.subError) + assertEquals("service-trace", result.traceId) + assertEquals("service-time", result.timestamp) + assertEquals(details, result.attributeValidationDetails) + } + @Test fun testSignUpStartWithoutPasswordDefersToPasswordRequired() { val entryState = mockContinuationState() @@ -238,12 +298,19 @@ class NativeAuthV2SignUpFlowControllerTest { every { mockStrategy.performSignUpStart(entryState) } returns NativeAuthV2InteractionApiResult.Redirect( correlationId = correlationId, - redirectReason = "fallback_required" + redirectReason = "fallback_required", + errorCodes = listOf(123), + traceId = "redirect-trace", + timestamp = "redirect-time" ) val result = controller.signUpStart(signUpStartParameters()) assertTrue(result is INativeAuthCommandResult.Redirect) + result as INativeAuthCommandResult.Redirect + assertEquals(listOf(123), result.errorCodes) + assertEquals("redirect-trace", result.traceId) + assertEquals("redirect-time", result.timestamp) } @Test @@ -470,7 +537,9 @@ class NativeAuthV2SignUpFlowControllerTest { AuthorizeChallengeApiResult.UnknownError( correlationId = correlationId, error = "expected_test_error", - errorDescription = "Expected test error." + errorDescription = "Expected test error.", + traceId = "authorize-trace", + timestamp = "authorize-time" ) val result = controller.signInAfterSignUp(signInAfterSignUpParameters(state)) @@ -480,6 +549,8 @@ class NativeAuthV2SignUpFlowControllerTest { "expected_test_error", (result as INativeAuthCommandResult.APIError).error ) + assertEquals("authorize-trace", result.traceId) + assertEquals("authorize-time", result.timestamp) } @Test @@ -536,17 +607,27 @@ class NativeAuthV2SignUpFlowControllerTest { correlationId = correlationId, claimsRequestJson = any() ) - } returns SignInTokenApiResult.UnknownError( + } returns SignInTokenApiResponse( + statusCode = 400, correlationId = correlationId, + continuationToken = null, error = "invalid_grant", errorDescription = "The authorization code is no longer valid.", - errorCodes = emptyList() - ) + errorCodes = emptyList(), + errorUri = null, + traceId = "token-trace", + timestamp = "token-time", + subError = "future_suberror" + ).toErrorResult() val result = controller.signInAfterSignUp(signInAfterSignUpParameters(state)) assertTrue(result is INativeAuthCommandResult.APIError) - assertEquals("invalid_grant", (result as INativeAuthCommandResult.APIError).error) + result as INativeAuthCommandResult.APIError + assertEquals("invalid_grant", result.error) + assertEquals("token-trace", result.traceId) + assertEquals("token-time", result.timestamp) + assertEquals("future_suberror", result.subError) } @Test diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/INativeAuthCommandResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/INativeAuthCommandResult.kt index 3705ac3e6d..e76ca1c2ce 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/INativeAuthCommandResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/INativeAuthCommandResult.kt @@ -31,10 +31,17 @@ import com.microsoft.identity.common.java.nativeauth.util.ILoggable */ interface INativeAuthCommandResult : ILoggable { val correlationId: String - data class Redirect( + /** Service diagnostics are absent on locally generated results. */ + val traceId: String? get() = null + val timestamp: String? get() = null + + data class Redirect @JvmOverloads constructor( override val correlationId: String, - val redirectReason: String - ) : Error(error = BROWSER_REQUIRED_ERROR, errorDescription = redirectReason.ifEmpty { BROWSER_REQUIRED_ERROR_DESCRIPTION }, correlationId = correlationId), + val redirectReason: String, + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null + ) : Error(error = BROWSER_REQUIRED_ERROR, errorDescription = redirectReason.ifEmpty { BROWSER_REQUIRED_ERROR_DESCRIPTION }, correlationId = correlationId, errorCodes = errorCodes), SignInStartCommandResult, SignInWithContinuationTokenCommandResult, SignInSubmitCodeCommandResult, SignInResendCodeCommandResult, SignInSubmitPasswordCommandResult, SignUpStartCommandResult, SignUpSubmitCodeCommandResult, SignUpResendCodeCommandResult, SignUpSubmitPasswordCommandResult, SignUpSubmitUserAttributesCommandResult, ResetPasswordStartCommandResult, ResetPasswordSubmitCodeCommandResult, ResetPasswordResendCodeCommandResult, ResetPasswordSubmitNewPasswordCommandResult, @@ -60,13 +67,17 @@ interface INativeAuthCommandResult : ILoggable { /** * UnknownError is base class to represent various kinds of errors in NativeAuth. */ - data class APIError( + data class APIError @JvmOverloads constructor( override val error: String?, override val errorDescription: String?, override val details: List>? = null, override val correlationId: String, override val errorCodes: List? = null, - val exception: Exception? = null + val exception: Exception? = null, + val subError: String? = null, + val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ): Error(error, errorDescription, details, correlationId, errorCodes), INativeAuthCommandResult, SignInStartCommandResult, SignInWithContinuationTokenCommandResult, SignInSubmitCodeCommandResult, SignInResendCodeCommandResult, SignInSubmitPasswordCommandResult, diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/NativeAuthV2CommandResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/NativeAuthV2CommandResult.kt index 68268acfb4..ad6bbd4702 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/NativeAuthV2CommandResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/controllers/results/NativeAuthV2CommandResult.kt @@ -175,12 +175,14 @@ interface NativeAuthV2CommandResult { * The developer can retry through the state object used for the failed call. * Applies to the submit-code step. */ - data class IncorrectCode( + data class IncorrectCode @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val subError: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2ResetPasswordSubmitCodeCommandResult, NativeAuthV2SignUpSubmitCodeCommandResult, NativeAuthV2SignInSubmitCodeCommandResult, @@ -253,12 +255,14 @@ interface NativeAuthV2CommandResult { * The developer must restart the flow with corrected credentials. * Applies to the sign-in start step. */ - data class InvalidCredentials( + data class InvalidCredentials @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val subError: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SignInStartCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.InvalidCredentials(correlationId=$correlationId, error=$error, errorDescription=$errorDescription, subError=$subError)" @@ -272,12 +276,14 @@ interface NativeAuthV2CommandResult { * retry through the state object used for the failed call. * Applies to the submit-password step. */ - data class IncorrectPassword( + data class IncorrectPassword @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val subError: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SubmitPasswordCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.IncorrectPassword(correlationId=$correlationId, error=$error, errorDescription=$errorDescription, subError=$subError)" @@ -291,12 +297,14 @@ interface NativeAuthV2CommandResult { * The developer can retry through the state object used for the failed call. * Applies to the submit-new-password step. */ - data class PasswordNotAccepted( + data class PasswordNotAccepted @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val subError: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SubmitNewPasswordCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.PasswordNotAccepted(correlationId=$correlationId, error=$error, errorDescription=$errorDescription, subError=$subError)" @@ -325,11 +333,13 @@ interface NativeAuthV2CommandResult { * The username provided is not registered in the tenant. * Applies to the start step. */ - data class UserNotFound( + data class UserNotFound @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2ResetPasswordStartCommandResult, NativeAuthV2SignInStartCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.UserNotFound(correlationId=$correlationId, error=$error, errorDescription=$errorDescription)" @@ -364,13 +374,17 @@ interface NativeAuthV2CommandResult { * [continuationState] with corrected values. Applies to the sign-up start and submit-attributes * steps. */ - data class AttributesInvalid( + data class AttributesInvalid @JvmOverloads constructor( override val correlationId: String, val continuationState: NativeAuthV2ContinuationState, val invalidAttributes: List, val error: String, val errorDescription: String, val errorCodes: List? = null, + val subError: String? = null, + val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SignUpStartCommandResult, NativeAuthV2SubmitAttributesCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.AttributesInvalid(correlationId=$correlationId, invalidAttributes=$invalidAttributes, error=$error, errorDescription=$errorDescription)" @@ -383,11 +397,15 @@ interface NativeAuthV2CommandResult { * An account already exists for the identifier supplied to sign-up. * Applies to the sign-up start and submit-attributes steps. */ - data class UserAlreadyExists( + data class UserAlreadyExists @JvmOverloads constructor( override val correlationId: String, val error: String, val errorDescription: String, val errorCodes: List? = null, + val subError: String? = null, + val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : NativeAuthV2SignUpStartCommandResult, NativeAuthV2SubmitAttributesCommandResult { override fun toUnsanitizedString(): String = "NativeAuthV2CommandResult.UserAlreadyExists(correlationId=$correlationId, error=$error, errorDescription=$errorDescription)" diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/ApiErrorResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/ApiErrorResult.kt index f942c8e43e..4e4f4fb66a 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/ApiErrorResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/ApiErrorResult.kt @@ -25,14 +25,21 @@ package com.microsoft.identity.common.java.nativeauth.providers.responses /** * Base class to encapsulate various error response from the Native Auth API. */ -abstract class ApiErrorResult( +abstract class ApiErrorResult @JvmOverloads constructor( open val error: String?, open val subError: String? = null, open val errorDescription: String?, open val errorCodes: List? = null, - override val correlationId: String + override val correlationId: String, + open val attributeValidationDetails: List>? = null ): ApiResult { + /** Unmodified service trace identifier, when supplied by the endpoint. */ + open val traceId: String? get() = null + + /** Unmodified service timestamp; no client-side date conversion is applied. */ + open val timestamp: String? get() = null + companion object { val INVALID_STATE = "invalid_state" } diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResponse.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResponse.kt index 43c7610d5b..eb5d44c3ee 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResponse.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResponse.kt @@ -42,7 +42,7 @@ import com.microsoft.identity.common.java.nativeauth.util.isUserNotFound * Note: mainly used for representing error cases from the /token endpoint. Successful responses are otherwise mapped to MicrosoftStsTokenResponse instead. * @see com.microsoft.identity.common.java.providers.microsoft.microsoftsts.MicrosoftStsTokenResponse */ -class SignInTokenApiResponse( +class SignInTokenApiResponse @JvmOverloads constructor( @Expose override var statusCode: Int, correlationId: String, @SerializedName("continuation_token") override val continuationToken: String?, @@ -51,6 +51,8 @@ class SignInTokenApiResponse( @SerializedName("error_uri") val errorUri: String?, @SerializedName("suberror") val subError: String?, @SerializedName("error_codes") val errorCodes: List?, + @SerializedName("trace_id") val traceId: String? = null, + @SerializedName("timestamp") val timestamp: String? = null, ): INativeAuthApiResponse(statusCode, correlationId, continuationToken, error = error, errorDescription = errorDescription) { override fun toUnsanitizedString(): String { @@ -69,9 +71,12 @@ class SignInTokenApiResponse( /** * Maps potential errors returned from the server response. + * @param diagnosticErrorCodes codes exposed to callers, without changing classification based + * on the original [errorCodes]. V2 may supply codes extracted from the message as a fallback. * @see com.microsoft.identity.common.java.nativeauth.providers.responses.signin.SignInTokenApiResult */ - fun toErrorResult(): SignInTokenApiResult { + @JvmOverloads + fun toErrorResult(diagnosticErrorCodes: List? = errorCodes): SignInTokenApiResult { return when { error.isInvalidRequest() -> { when { @@ -79,7 +84,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -89,7 +97,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = customDescription, - errorCodes = errorCodes, + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -97,7 +108,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes, + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -109,7 +123,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.InvalidCredentials( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes, + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -121,11 +138,16 @@ class SignInTokenApiResponse( return SignInTokenApiResult.UnknownError( error = ApiErrorResult.INVALID_STATE, errorDescription = "oauth/v2.0/token did not return a continuation token", - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ), subError = subError.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -137,11 +159,16 @@ class SignInTokenApiResponse( return SignInTokenApiResult.UnknownError( error = ApiErrorResult.INVALID_STATE, errorDescription = "oauth/v2.0/token did not return a continuation token", - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ), subError = subError.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -149,8 +176,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.CodeIncorrect( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), subError = subError.orEmpty(), + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -158,7 +187,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.InvalidAuthenticationType( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes, + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -166,7 +198,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -176,7 +211,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UserNotFound( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } @@ -184,7 +222,10 @@ class SignInTokenApiResponse( SignInTokenApiResult.UnknownError( error = error.orEmpty(), errorDescription = errorDescription.orEmpty(), - errorCodes = errorCodes.orEmpty(), + errorCodes = diagnosticErrorCodes.orEmpty(), + subError = subError, + traceId = traceId, + timestamp = timestamp, correlationId = correlationId ) } diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResult.kt index 22825cb6a5..ad03a8332b 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/signin/SignInTokenApiResult.kt @@ -33,9 +33,12 @@ import com.microsoft.identity.common.java.providers.microsoft.microsoftsts.Micro */ sealed interface SignInTokenApiResult: ApiResult, ILoggable { - data class Redirect( + data class Redirect @JvmOverloads constructor( override val correlationId: String, - val redirectReason: String + val redirectReason: String, + val errorCodes: List? = null, + val traceId: String? = null, + val timestamp: String? = null ) : SignInTokenApiResult { override fun toUnsanitizedString(): String { return "Redirect(correlationId=$correlationId, redirectReason=$redirectReason)" @@ -55,13 +58,15 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = toUnsanitizedString() } - data class MFARequired( + data class MFARequired @JvmOverloads constructor( override val correlationId: String, val continuationToken: String, override val error: String, override val subError: String, override val errorDescription: String, - override val errorCodes: List + override val errorCodes: List, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -75,13 +80,15 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "MFARequired(correlationId=$correlationId)" } - data class JITRequired( + data class JITRequired @JvmOverloads constructor( override val correlationId: String, val continuationToken: String, override val error: String, override val subError: String, override val errorDescription: String, - override val errorCodes: List + override val errorCodes: List, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -95,15 +102,19 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "JITRequired(correlationId=$correlationId)" } - data class UserNotFound( + data class UserNotFound @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, + override val subError: String? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, errorCodes = errorCodes, + subError = subError, correlationId = correlationId ), SignInTokenApiResult { override fun toUnsanitizedString() = "UserNotFound(correlationId=$correlationId, " + @@ -112,15 +123,19 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "UserNotFound(correlationId=$correlationId)" } - data class InvalidCredentials( + data class InvalidCredentials @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, + override val subError: String? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, errorCodes = errorCodes, + subError = subError, correlationId = correlationId ), SignInTokenApiResult { override fun toUnsanitizedString() = "InvalidCredentials(correlationId=$correlationId, " + @@ -129,12 +144,14 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "InvalidCredentials(correlationId=$correlationId)" } - data class CodeIncorrect( + data class CodeIncorrect @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, override val subError: String, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -148,15 +165,19 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "CodeIncorrect(correlationId=$correlationId)" } - data class InvalidAuthenticationType( + data class InvalidAuthenticationType @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, + override val subError: String? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, errorCodes = errorCodes, + subError = subError, correlationId = correlationId ), SignInTokenApiResult { override fun toUnsanitizedString() = "InvalidAuthenticationType(correlationId=$correlationId, " + @@ -165,15 +186,19 @@ sealed interface SignInTokenApiResult: ApiResult, ILoggable { override fun toString(): String = "InvalidAuthenticationType(correlationId=$correlationId)" } - data class UnknownError( + data class UnknownError @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val errorCodes: List, + override val subError: String? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, errorCodes = errorCodes, + subError = subError, correlationId = correlationId ), SignInTokenApiResult { override fun toUnsanitizedString() = "UnknownError(correlationId=$correlationId, " + diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/AuthorizeChallengeApiResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/AuthorizeChallengeApiResult.kt index 3967e32547..ae18730364 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/AuthorizeChallengeApiResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/AuthorizeChallengeApiResult.kt @@ -59,9 +59,12 @@ sealed interface AuthorizeChallengeApiResult : ApiResult { /** * The server requires the flow to fall back to a web-based (interactive browser) experience. */ - data class Redirect( + data class Redirect @JvmOverloads constructor( override val correlationId: String, - val redirectReason: String + val redirectReason: String, + val errorCodes: List? = null, + val traceId: String? = null, + val timestamp: String? = null ) : AuthorizeChallengeApiResult { override fun toUnsanitizedString(): String = "Redirect(correlationId=$correlationId, redirectReason=$redirectReason)" @@ -72,11 +75,15 @@ sealed interface AuthorizeChallengeApiResult : ApiResult { * An error was returned (or the response shape was otherwise unusable) that this SDK version * does not map to a more specific case. */ - data class UnknownError( + data class UnknownError @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val subError: String? = null, + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponse.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponse.kt index 604d7cb472..1d9c809d57 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponse.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponse.kt @@ -23,6 +23,7 @@ package com.microsoft.identity.common.java.nativeauth.providers.responses.v2 import com.microsoft.identity.common.java.nativeauth.providers.INativeAuthApiResponse +import com.microsoft.identity.common.java.nativeauth.providers.v2.NativeAuthV2ErrorDiagnostics /** * Single wire model for every V2 HAL Native Auth API response body. There are no response @@ -75,16 +76,21 @@ class NativeAuthV2HalApiResponse private constructor( // Per-attribute error details from `error.innerError.details`. Empty when the server sent // no such array. Used to attribute a sign-up failure (for example `userAlreadyExists` or // `passwordPolicyViolation`) to the specific attribute(s) it concerns. - val details: List + val details: List, + val traceId: String? = null, + val timestamp: String? = null, + val errorCodes: List? = null ) /** * A single entry of `error.innerError.details`, pairing an error [code] (for example - * `userAlreadyExists` or `passwordPolicyViolation`) with the [attributeIds] it applies to. + * `userAlreadyExists` or `passwordPolicyViolation`) with the [attributeIds] it applies to + * and the optional, unmodified service [message]. */ data class HalErrorDetail( val code: String?, - val attributeIds: List + val attributeIds: List, + val message: String? = null ) val isWebFallbackRequired: Boolean @@ -328,7 +334,10 @@ class NativeAuthV2HalApiResponse private constructor( message = errorValue[ERROR_MESSAGE_KEY] as? String, innerErrorCode = innerErrorMap?.get(ERROR_CODE_KEY) as? String, correlationId = errorValue[ERROR_CORRELATION_ID_KEY] as? String, - details = extractErrorDetails(innerErrorMap) + details = extractErrorDetails(innerErrorMap), + traceId = errorValue["traceId"] as? String, + timestamp = errorValue["timestamp"] as? String, + errorCodes = NativeAuthV2ErrorDiagnostics.readErrorCodes(errorValue["error_codes"]) ) } @@ -338,7 +347,10 @@ class NativeAuthV2HalApiResponse private constructor( innerErrorCode = null, correlationId = halResource.string(ERROR_CORRELATION_ID_SNAKE_KEY) ?: halResource.string(ERROR_CORRELATION_ID_KEY), - details = emptyList() + details = emptyList(), + traceId = halResource.string("trace_id"), + timestamp = halResource.string("timestamp"), + errorCodes = NativeAuthV2ErrorDiagnostics.readErrorCodes(halResource.properties["error_codes"]) ) else -> null @@ -360,7 +372,8 @@ class NativeAuthV2HalApiResponse private constructor( .orEmpty() HalErrorDetail( code = detailMap[ERROR_CODE_KEY] as? String, - attributeIds = attributeIds + attributeIds = attributeIds, + message = detailMap[ERROR_MESSAGE_KEY] as? String ) } } diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2InteractionApiResult.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2InteractionApiResult.kt index 8288d881d8..3b8e2e9f20 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2InteractionApiResult.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2InteractionApiResult.kt @@ -163,9 +163,12 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * The server requires the flow to fall back to a web-based (interactive browser) experience. */ - data class Redirect( + data class Redirect @JvmOverloads constructor( override val correlationId: String, - val redirectReason: String + val redirectReason: String, + val errorCodes: List? = null, + val traceId: String? = null, + val timestamp: String? = null ) : NativeAuthV2InteractionApiResult { override fun toUnsanitizedString(): String = "Redirect(correlationId=$correlationId, redirectReason=$redirectReason)" @@ -175,11 +178,13 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * No account matches the identifier supplied to reset-password /start. */ - data class UserNotFound( + data class UserNotFound @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -194,12 +199,14 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * The submitted verification code was invalid. */ - data class InvalidCode( + data class InvalidCode @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val subError: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, subError = subError, @@ -215,12 +222,14 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * The submitted password was invalid (for example, too weak). */ - data class InvalidPassword( + data class InvalidPassword @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val subError: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, subError = subError, @@ -236,12 +245,14 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * The submitted username/password combination was rejected by the service. */ - data class InvalidCredentials( + data class InvalidCredentials @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, override val subError: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, subError = subError, @@ -274,11 +285,15 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { /** * An account already exists for the identifier supplied to sign-up. */ - data class UserAlreadyExists( + data class UserAlreadyExists @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val subError: String? = null, + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -295,12 +310,16 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { * wire names of the attributes the server rejected (for example `password` when the value * violated password policy), in server order. */ - data class InvalidAttributes( + data class InvalidAttributes @JvmOverloads constructor( override val correlationId: String, val invalidAttributes: List, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val subError: String? = null, + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, @@ -338,11 +357,15 @@ sealed interface NativeAuthV2InteractionApiResult : ApiResult { * An error was returned (or the response shape was otherwise unusable) that this SDK version * does not map to a more specific case. */ - data class UnknownError( + data class UnknownError @JvmOverloads constructor( override val correlationId: String, override val error: String, override val errorDescription: String, - override val errorCodes: List? = null + override val errorCodes: List? = null, + override val subError: String? = null, + override val attributeValidationDetails: List>? = null, + override val traceId: String? = null, + override val timestamp: String? = null ) : ApiErrorResult( error = error, errorDescription = errorDescription, diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt index c9a2614255..09db930546 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParser.kt @@ -27,6 +27,7 @@ import com.microsoft.identity.common.java.logging.Logger import com.microsoft.identity.common.java.nativeauth.providers.NativeAuthConstants import com.microsoft.identity.common.java.nativeauth.providers.responses.ApiErrorResult import com.microsoft.identity.common.java.nativeauth.providers.v2.NativeAuthV2FlowScenario +import com.microsoft.identity.common.java.nativeauth.providers.v2.NativeAuthV2ErrorDiagnostics import java.util.Locale /** @@ -70,7 +71,10 @@ class NativeAuthV2ResponseParser { return AuthorizeChallengeApiResult.Redirect( correlationId = response.serverError?.correlationId ?.takeUnless { it.isBlank() } ?: response.correlationId, - redirectReason = response.serverError?.code ?: response.state ?: WEB_FALLBACK_REDIRECT_REASON + redirectReason = response.serverError?.code ?: response.state ?: WEB_FALLBACK_REDIRECT_REASON, + traceId = response.serverError?.traceId, + timestamp = response.serverError?.timestamp, + errorCodes = response.serverError?.errorCodes ?: extractAadstsCodes(response.serverError?.message) ) } @@ -84,7 +88,11 @@ class NativeAuthV2ResponseParser { ?.takeUnless { it.isBlank() } ?: response.correlationId, error = serverError.code ?: ApiErrorResult.INVALID_STATE, errorDescription = serverError.message.orEmpty(), - errorCodes = extractAadstsCodes(serverError.message) + errorCodes = serverError.errorCodes ?: extractAadstsCodes(serverError.message), + subError = serverError.innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) } @@ -173,7 +181,10 @@ class NativeAuthV2ResponseParser { if (response.isWebFallbackRequired) { return NativeAuthV2InteractionApiResult.Redirect( correlationId = errorCorrelationId, - redirectReason = response.serverError?.code ?: response.state ?: WEB_FALLBACK_REDIRECT_REASON + redirectReason = response.serverError?.code ?: response.state ?: WEB_FALLBACK_REDIRECT_REASON, + traceId = response.serverError?.traceId, + timestamp = response.serverError?.timestamp, + errorCodes = response.serverError?.errorCodes ?: extractAadstsCodes(response.serverError?.message) ) } @@ -545,7 +556,7 @@ class NativeAuthV2ResponseParser { val code = serverError.code val innerErrorCode = serverError.innerErrorCode val message = serverError.message - val errorCodes = extractAadstsCodes(message) + val errorCodes = serverError.errorCodes ?: extractAadstsCodes(message) return when { code == ERROR_INVALID_GRANT && innerErrorCode == INNER_ERROR_INVALID_ONE_TIME_CODE -> @@ -554,11 +565,13 @@ class NativeAuthV2ResponseParser { error = code.orEmpty(), errorDescription = message.orEmpty(), subError = innerErrorCode.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + traceId = serverError.traceId, + timestamp = serverError.timestamp ) innerErrorCode == INNER_ERROR_INVALID_CONTINUATION_TOKEN -> - unknownInteractionError(correlationId, code, message, errorCodes) + unknownInteractionError(correlationId, serverError, errorCodes) scenario == NativeAuthV2FlowScenario.SIGN_UP && innerErrorCode == INNER_ERROR_ATTRIBUTE_VALIDATION_FAILED -> @@ -568,14 +581,18 @@ class NativeAuthV2ResponseParser { .flatMap { it.attributeIds } .distinct() if (invalidAttributes.isEmpty()) { - unknownInteractionError(correlationId, code, message, errorCodes) + unknownInteractionError(correlationId, serverError, errorCodes) } else { NativeAuthV2InteractionApiResult.InvalidAttributes( correlationId = correlationId, invalidAttributes = invalidAttributes, error = code.orEmpty(), errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + subError = innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) } } @@ -587,7 +604,11 @@ class NativeAuthV2ResponseParser { correlationId = correlationId, error = code.orEmpty(), errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + subError = innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) code == ERROR_INVALID_REQUEST && innerErrorCode in INNER_ERROR_INVALID_PASSWORD -> @@ -596,7 +617,9 @@ class NativeAuthV2ResponseParser { error = code.orEmpty(), errorDescription = message.orEmpty(), subError = innerErrorCode.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + traceId = serverError.traceId, + timestamp = serverError.timestamp ) code == ERROR_INVALID_GRANT && @@ -606,7 +629,9 @@ class NativeAuthV2ResponseParser { error = code.orEmpty(), errorDescription = message.orEmpty(), subError = innerErrorCode.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + traceId = serverError.traceId, + timestamp = serverError.timestamp ) // The account does not exist in the directory. This response carries no inner error @@ -618,25 +643,36 @@ class NativeAuthV2ResponseParser { correlationId = correlationId, error = code.orEmpty(), errorDescription = message.orEmpty(), - errorCodes = errorCodes + errorCodes = errorCodes, + traceId = serverError.traceId, + timestamp = serverError.timestamp ) - else -> unknownInteractionError(correlationId, code, message, errorCodes) + else -> unknownInteractionError(correlationId, serverError, errorCodes) } } private fun unknownInteractionError( correlationId: String, - code: String?, - message: String?, + serverError: NativeAuthV2HalApiResponse.HalServerError, errorCodes: List? ): NativeAuthV2InteractionApiResult.UnknownError = NativeAuthV2InteractionApiResult.UnknownError( correlationId = correlationId, - error = code ?: ApiErrorResult.INVALID_STATE, - errorDescription = message.orEmpty(), - errorCodes = errorCodes + error = serverError.code ?: ApiErrorResult.INVALID_STATE, + errorDescription = serverError.message.orEmpty(), + errorCodes = errorCodes, + subError = serverError.innerErrorCode, + attributeValidationDetails = validationDetails(serverError), + traceId = serverError.traceId, + timestamp = serverError.timestamp ) + private fun validationDetails(error: NativeAuthV2HalApiResponse.HalServerError): List> = + error.details.map { detail -> + val fields = mapOf("code" to detail.code, "attributeIds" to detail.attributeIds) + detail.message?.let { fields + ("message" to it) } ?: fields + } + private fun missingLinkError( correlationId: String, relation: NativeAuthV2LinkRelation @@ -685,19 +721,12 @@ class NativeAuthV2ResponseParser { * surfacing service error codes via [ApiErrorResult.errorCodes]. Returns `null` (rather than * an empty list) when none are present, matching [ApiErrorResult.errorCodes]'s own default. */ - private fun extractAadstsCodes(message: String?): List? { - if (message.isNullOrBlank()) { - return null - } - val codes = AADSTS_CODE_REGEX.findAll(message).mapNotNull { it.groupValues[1].toIntOrNull() }.toList() - return codes.ifEmpty { null } - } + private fun extractAadstsCodes(message: String?): List? = + NativeAuthV2ErrorDiagnostics.codesFromMessage(message) private companion object { private val TAG: String = NativeAuthV2ResponseParser::class.java.simpleName - private val AADSTS_CODE_REGEX = Regex("AADSTS(\\d+)") - private const val STATE_CONTINUE = "continue" private const val WEB_FALLBACK_REDIRECT_REASON = "web_fallback_required" diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ErrorDiagnostics.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ErrorDiagnostics.kt new file mode 100644 index 0000000000..40a3438b36 --- /dev/null +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ErrorDiagnostics.kt @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.microsoft.identity.common.java.nativeauth.providers.v2 + +import java.math.BigDecimal + +/** Shared diagnostic decoding for V2 HAL and OAuth error envelopes. */ +internal object NativeAuthV2ErrorDiagnostics { + private val aadstsCodeRegex = Regex("AADSTS(\\d+)") + + /** A malformed array is rejected as a whole; an explicit empty array remains authoritative. */ + fun readErrorCodes(value: Any?): List? { + val values = value as? List<*> ?: return null + return values.map { + val number = it as? Number ?: return null + try { + BigDecimal(number.toString()).intValueExact() + } catch (e: NumberFormatException) { + return null + } catch (e: ArithmeticException) { + return null + } + } + } + + fun codesFromMessage(message: String?): List? = + message?.let { + aadstsCodeRegex.findAll(it).mapNotNull { match -> + match.groupValues[1].toIntOrNull() + }.toList().ifEmpty { null } + } +} diff --git a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandler.kt b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandler.kt index e7f7c39a31..abf19ce59e 100644 --- a/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandler.kt +++ b/common4j/src/main/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandler.kt @@ -22,6 +22,9 @@ // THE SOFTWARE. package com.microsoft.identity.common.java.nativeauth.providers.v2 +import com.google.gson.JsonArray +import com.google.gson.JsonObject +import com.google.gson.JsonPrimitive import com.microsoft.identity.common.java.AuthenticationConstants import com.microsoft.identity.common.java.exception.ClientException import com.microsoft.identity.common.java.logging.LogSession @@ -175,19 +178,36 @@ class NativeAuthV2ResponseHandler { errorCodes = null ) } else { - ObjectMapper.deserializeJsonStringToObject( + val body = ObjectMapper.deserializeJsonStringToObject( response.body, - SignInTokenApiResponse::class.java + JsonObject::class.java ) ?: return buildTokenErrorResult( statusCode = response.statusCode, correlationId = correlationId, errorCode = NativeAuthResponseHandler.EMPTY_RESPONSE_ERROR, errorMessage = NativeAuthResponseHandler.EMPTY_RESPONSE_ERROR_ERROR_DESCRIPTION ) + // Keep the original numeric representation; Double coercion can hide fractions. + val rawErrorCodes = (body["error_codes"] as? JsonArray)?.map { + (it as? JsonPrimitive)?.takeIf { value -> value.isNumber }?.asNumber + } + SignInTokenApiResponse( + statusCode = response.statusCode, + correlationId = correlationId, + continuationToken = body.string("continuation_token"), + error = body.string("error"), + errorDescription = body.string("error_description"), + errorUri = body.string("error_uri"), + subError = body.string("suberror"), + errorCodes = NativeAuthV2ErrorDiagnostics.readErrorCodes(rawErrorCodes), + traceId = body.string("trace_id"), + timestamp = body.string("timestamp") + ) } - apiResponse.statusCode = response.statusCode - apiResponse.correlationId = correlationId - apiResponse.toErrorResult() + apiResponse.toErrorResult( + diagnosticErrorCodes = apiResponse.errorCodes + ?: NativeAuthV2ErrorDiagnostics.codesFromMessage(apiResponse.errorDescription) + ) } else { val tokenResponse = ObjectMapper.deserializeJsonStringToObject( response.body, @@ -212,6 +232,9 @@ class NativeAuthV2ResponseHandler { } } + private fun JsonObject.string(name: String): String? = + (get(name) as? JsonPrimitive)?.takeIf { it.isString }?.asString + private fun buildTokenErrorResult( statusCode: Int, correlationId: String, diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponseTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponseTest.kt index 82cb52f205..b5e32e9fc1 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponseTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2HalApiResponseTest.kt @@ -30,6 +30,48 @@ import org.junit.Test class NativeAuthV2HalApiResponseTest { + @Test + fun from_preservesAttributeDetailMessagesVerbatim() { + val response = responseFrom( + """{"error":{"code":"invalidRequest","innerError":{"code":"attributeValidationError", + "details":[ + {"code":"attributeValidationFailed","attributeIds":["email"],"message":"Enter a valid value."}, + {"code":"attributeRequired","message":"A \"quoted\" value.\nNext line."}, + {"code":"futureDetail","attributeIds":[],"message":""} + ]}}}""" + ) + + assertEquals( + listOf( + NativeAuthV2HalApiResponse.HalErrorDetail( + "attributeValidationFailed", listOf("email"), "Enter a valid value." + ), + NativeAuthV2HalApiResponse.HalErrorDetail( + "attributeRequired", emptyList(), "A \"quoted\" value.\nNext line." + ), + NativeAuthV2HalApiResponse.HalErrorDetail("futureDetail", emptyList(), "") + ), + response.serverError?.details + ) + } + + @Test + fun from_missingOrMalformedDetailMessagesDoNotDiscardOtherFields() { + for (messageField in listOf("", ""","message":null""", ""","message":42""", + ""","message":{}""", ""","message":[]""", ""","message":false""")) { + val response = responseFrom( + """{"error":{"code":"invalidRequest","innerError":{"details":[ + {"code":"attributeValidationFailed","attributeIds":["email"]$messageField} + ]}}}""" + ) + + assertEquals( + listOf(NativeAuthV2HalApiResponse.HalErrorDetail("attributeValidationFailed", listOf("email"))), + response.serverError?.details + ) + } + } + @Test fun error_buildsClientSideErrorWithoutFlowState() { val response = NativeAuthV2HalApiResponse.error( diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt index 901f7d913f..0ef241b5b2 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2ResponseParserTest.kt @@ -36,6 +36,213 @@ import org.junit.Test class NativeAuthV2ResponseParserTest { private val parser = NativeAuthV2ResponseParser() + @Test + fun parseAuthorizeChallenge_prefersExplicitErrorCodesIncludingEmptyArray() { + for (codes in listOf(listOf(100, 200), emptyList())) { + val result = parser.parseAuthorizeChallenge( + response = responseFrom( + """{"error":"InsufficientAuthorization", + "error_description":"AADSTS500127: No authenticated credentials.", + "error_codes":$codes,"trace_id":"server-trace", + "timestamp":"2026-10-15 11:00:20Z"}""" + ), + entryRelation = NativeAuthV2LinkRelation.SIGN_IN, + scenario = NativeAuthV2FlowScenario.SIGN_IN, + scopes = emptyList() + ) as AuthorizeChallengeApiResult.UnknownError + + assertEquals(codes, result.errorCodes) + assertEquals("server-trace", result.traceId) + assertEquals("2026-10-15 11:00:20Z", result.timestamp) + } + } + + @Test + fun parseErrors_preservesSuppliedPayloadDiagnosticsAcrossScenarios() { + val attributeMessage = "Enter a valid \"email\" value.\nTry again." + val details = listOf( + mapOf( + "code" to "attributeValidationFailed", + "attributeIds" to listOf("email"), + "message" to attributeMessage + ) + ) + val cases = listOf( + Triple( + """{"error":"InsufficientAuthorization", + "error_description":"AADSTS500127: No authenticated credentials.", + "error_codes":[500127],"correlation_id":"service-correlation", + "trace_id":"service-trace","timestamp":"service-time"}""", + null, 500127 + ), + Triple( + """{"error":{"code":"invalidRequest", + "message":"AADSTS1002027: Attribute validation failed.", + "correlationId":"service-correlation","traceId":"service-trace", + "timestamp":"service-time","innerError":{"code":"attributeValidationError", + "details":[{"code":"attributeValidationFailed","attributeIds":["email"], + "message":"Enter a valid \"email\" value.\nTry again."}]}}}""", + "attributeValidationError", 1002027 + ), + Triple( + """{"error":{"code":"invalidRequest", + "message":"AADSTS10040172: User not found.", + "correlationId":"service-correlation","traceId":"service-trace", + "timestamp":"service-time","innerError":{"code":"userNotFound"}}, + "sign_up":"/tenant/api/v0.1/signup/start"}""", + "userNotFound", 10040172 + ) + ) + val scenarios = listOf( + NativeAuthV2FlowScenario.SIGN_IN, + NativeAuthV2FlowScenario.SIGN_UP, + NativeAuthV2FlowScenario.RESET_PASSWORD + ) + for ((json, subError, errorCode) in cases) { + fun assertDiagnostics(error: ApiErrorResult) { + assertEquals( + if (subError == null) "InsufficientAuthorization" else "invalidRequest", + error.error + ) + assertEquals( + when (errorCode) { + 500127 -> "AADSTS500127: No authenticated credentials." + 1002027 -> "AADSTS1002027: Attribute validation failed." + else -> "AADSTS10040172: User not found." + }, + error.errorDescription + ) + assertEquals(listOf(errorCode), error.errorCodes) + assertEquals("service-correlation", error.correlationId) + assertEquals("service-trace", error.traceId) + assertEquals("service-time", error.timestamp) + assertEquals(subError, error.subError) + assertEquals( + if (subError == "attributeValidationError") details else emptyList(), + error.attributeValidationDetails + ) + } + for (scenario in scenarios) { + val response = responseFrom(json) + val authorizeResult = parser.parseAuthorizeChallenge( + response, NativeAuthV2LinkRelation.SIGN_IN, scenario, emptyList() + ) + assertTrue(authorizeResult is AuthorizeChallengeApiResult.UnknownError) + assertDiagnostics(authorizeResult as ApiErrorResult) + + val interactionResult = parser.parseInteraction(response, previousState(scenario)) + if (scenario == NativeAuthV2FlowScenario.SIGN_UP && + subError == "attributeValidationError") { + assertTrue(interactionResult is NativeAuthV2InteractionApiResult.InvalidAttributes) + assertEquals( + listOf("email"), + (interactionResult as NativeAuthV2InteractionApiResult.InvalidAttributes).invalidAttributes + ) + } else { + assertTrue(interactionResult is NativeAuthV2InteractionApiResult.UnknownError) + } + assertDiagnostics(interactionResult as ApiErrorResult) + } + } + } + + @Test + fun parseInteraction_missingOrMalformedDetailMessagesPreservesExistingMapShape() { + for (messageField in listOf("", ""","message":null""", ""","message":42""", + ""","message":{}""", ""","message":[]""", ""","message":false""")) { + val result = parser.parseInteraction( + responseFrom( + """{"error":{"code":"invalidRequest","innerError":{"code":"attributeValidationError", + "details":[{"code":"attributeValidationFailed","attributeIds":["email"]$messageField}]}}}""" + ), + previousState(NativeAuthV2FlowScenario.SIGN_UP) + ) as NativeAuthV2InteractionApiResult.InvalidAttributes + + assertEquals( + listOf(mapOf("code" to "attributeValidationFailed", "attributeIds" to listOf("email"))), + result.attributeValidationDetails + ) + } + } + + @Test + fun parseInteraction_preservesDiagnosticsAcrossTypedAndUnknownErrors() { + val cases = listOf( + Triple("invalidGrant", "invalidOneTimeCode", NativeAuthV2InteractionApiResult.InvalidCode::class.java), + Triple("invalidGrant", "invalidUserNameOrPassword", NativeAuthV2InteractionApiResult.InvalidCredentials::class.java), + Triple("invalidRequest", "passwordTooWeak", NativeAuthV2InteractionApiResult.InvalidPassword::class.java), + Triple("invalidRequest", "attributeValidationError", NativeAuthV2InteractionApiResult.InvalidAttributes::class.java), + Triple("invalidRequest", "userNotFound", NativeAuthV2InteractionApiResult.UnknownError::class.java) + ) + for ((code, innerCode, expectedClass) in cases) { + val result = parser.parseInteraction( + responseFrom( + """{"error":{"code":"$code","message":"AADSTS10040172: Service diagnostic.", + "correlationId":"service-correlation","traceId":"service-trace", + "timestamp":"unmodified-timestamp","innerError":{"code":"$innerCode", + "details":[{"code":"attributeValidationFailed","attributeIds":["email"]}]}}}""" + ), + previousState(NativeAuthV2FlowScenario.SIGN_UP) + ) + + assertEquals(innerCode, expectedClass, result.javaClass) + val error = result as ApiErrorResult + assertEquals("service-trace", error.traceId) + assertEquals("unmodified-timestamp", error.timestamp) + assertEquals("service-correlation", error.correlationId) + assertEquals(listOf(10040172), error.errorCodes) + } + } + + @Test + fun parseAuthorizeChallenge_missingOrMalformedDiagnosticFieldsRemainNull() { + for (json in listOf( + """{"error":"future_error"}""", + """{"error":"future_error","trace_id":123,"timestamp":{}}""", + """{"error":{"code":"future_error","traceId":[],"timestamp":false}}""" + )) { + val result = parser.parseAuthorizeChallenge( + responseFrom(json), NativeAuthV2LinkRelation.SIGN_IN, + NativeAuthV2FlowScenario.SIGN_IN, emptyList() + ) as AuthorizeChallengeApiResult.UnknownError + assertNull(result.traceId) + assertNull(result.timestamp) + assertNull(result.errorCodes) + } + } + + @Test + fun parseAuthorizeChallenge_browserFallbackRetainsDiagnostics() { + val result = parser.parseAuthorizeChallenge( + responseFrom( + """{"error":{"code":"redirect_to_web","message":"AADSTS123: Browser required.", + "traceId":"fallback-trace","timestamp":"service-time"}}""" + ), + NativeAuthV2LinkRelation.SIGN_IN, NativeAuthV2FlowScenario.SIGN_IN, emptyList() + ) as AuthorizeChallengeApiResult.Redirect + assertEquals("fallback-trace", result.traceId) + assertEquals("service-time", result.timestamp) + assertEquals(listOf(123), result.errorCodes) + } + + @Test + fun parseAuthorizeChallenge_invalidErrorCodesFallBackToMessage() { + for (codes in listOf("null", "\"bad\"", "[100,\"200\"]", "[1.5]", "[2147483648]", "[2147483647.0000001]", "[null]")) { + val result = parser.parseAuthorizeChallenge( + response = responseFrom( + """{"error":"InsufficientAuthorization", + "error_description":"AADSTS500127: No authenticated credentials.", + "error_codes":$codes}""" + ), + entryRelation = NativeAuthV2LinkRelation.SIGN_IN, + scenario = NativeAuthV2FlowScenario.SIGN_IN, + scopes = emptyList() + ) as AuthorizeChallengeApiResult.UnknownError + + assertEquals(codes, listOf(500127), result.errorCodes) + } + } + @Test fun parseInteraction_whenActionMissing_returnsUnknownErrorForMissingActionField() { val response = responseFrom("""{"continuationToken":"token"}""") @@ -1138,14 +1345,16 @@ class NativeAuthV2ResponseParserTest { correlationId = CORRELATION_ID ) - private fun previousState(): NativeAuthV2ContinuationState { + private fun previousState( + scenario: NativeAuthV2FlowScenario = NativeAuthV2FlowScenario.RESET_PASSWORD + ): NativeAuthV2ContinuationState { val seedResponse = responseFrom("""{"continuationToken":"seed"}""") return NativeAuthV2ContinuationState.fromAuthorizeChallengeResponse( response = seedResponse, continuationToken = "seed", entryRelation = NativeAuthV2LinkRelation.RESET_PASSWORD, scopes = listOf("User.Read"), - scenario = NativeAuthV2FlowScenario.RESET_PASSWORD + scenario = scenario ) } diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2SignUpResponseParserTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2SignUpResponseParserTest.kt index 79e403ac70..434056d5dd 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2SignUpResponseParserTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/responses/v2/NativeAuthV2SignUpResponseParserTest.kt @@ -129,6 +129,10 @@ class NativeAuthV2SignUpResponseParserTest { ) assertTrue(result is NativeAuthV2InteractionApiResult.UserAlreadyExists) + assertEquals( + "userAlreadyExists", + (result as NativeAuthV2InteractionApiResult.UserAlreadyExists).attributeValidationDetails?.first()?.get("code") + ) } @Test @@ -250,6 +254,34 @@ class NativeAuthV2SignUpResponseParserTest { correlationId = CORRELATION_ID ) + @Test + fun parseInteraction_preservesRuntimeValidatedPolicyAndRequiredDetails() { + val result = parser.parseInteraction( + responseFrom("""{"error":{"code":"invalidRequest","message":"validation","innerError":{ + "code":"attributeValidationError","details":[null,42, + {"code":"passwordPolicyViolation","attributeIds":[42,"PASSWORD"]}, + {"code":"attributeRequired","attributeIds":["city"]}]}}}"""), + signUpState() + ) as NativeAuthV2InteractionApiResult.InvalidAttributes + assertEquals("attributeValidationError", result.subError) + assertEquals(listOf("PASSWORD", "city"), result.invalidAttributes) + assertEquals(2, result.attributeValidationDetails?.size) + assertEquals("passwordPolicyViolation", result.attributeValidationDetails?.first()?.get("code")) + } + + @Test + fun parseInteraction_unknownErrorRetainsSubErrorAndRejectsMalformedDetails() { + val result = parser.parseInteraction( + responseFrom("""{"error":{"code":"futureError","message":"diagnostic","innerError":{ + "code":"futureSubError","details":"bad"}}}"""), + signUpState() + ) as NativeAuthV2InteractionApiResult.UnknownError + assertEquals("futureError", result.error) + assertEquals("diagnostic", result.errorDescription) + assertEquals("futureSubError", result.subError) + assertTrue(result.attributeValidationDetails.orEmpty().isEmpty()) + } + private fun signUpState(): NativeAuthV2ContinuationState = NativeAuthV2ContinuationState.fromAuthorizeChallengeResponse( response = responseFrom("""{"continuationToken":"seed","signUp":"/tenant/signup/start"}"""), diff --git a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandlerTest.kt b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandlerTest.kt index 7e867f43b2..40c403204b 100644 --- a/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandlerTest.kt +++ b/common4j/src/test/com/microsoft/identity/common/java/nativeauth/providers/v2/NativeAuthV2ResponseHandlerTest.kt @@ -36,6 +36,60 @@ import org.junit.Test class NativeAuthV2ResponseHandlerTest { private val handler = NativeAuthV2ResponseHandler() + @Test + fun getTokenApiResponse_explicitErrorCodesIncludingEmptyArrayOverrideMessage() { + for (codes in listOf(emptyList(), listOf(123, 456))) { + val result = handler.getTokenApiResponse( + CORRELATION_ID, + response(400, """{"error":"invalid_grant", + "error_description":"AADSTS50126: Credentials rejected.","error_codes":$codes, + "trace_id":123,"timestamp":{}}""") + ) as SignInTokenApiResult.UnknownError + assertEquals(codes, result.errorCodes) + assertNull(result.traceId) + assertNull(result.timestamp) + } + } + + @Test + fun getTokenApiResponse_preservesDiagnosticsForRecoverableTokenErrors() { + val cases = listOf( + "mfa_required" to SignInTokenApiResult.MFARequired::class.java, + "registration_required" to SignInTokenApiResult.JITRequired::class.java, + "invalid_oob_value" to SignInTokenApiResult.CodeIncorrect::class.java + ) + for ((subError, expectedClass) in cases) { + val result = handler.getTokenApiResponse( + CORRELATION_ID, + response(400, """{"error":"invalid_grant","suberror":"$subError", + "continuation_token":"token","error_description":"AADSTS123: Diagnostic.", + "trace_id":"recoverable-trace","timestamp":"raw-time"}""") + ) + assertEquals(expectedClass, result.javaClass) + val error = result as ApiErrorResult + assertEquals(listOf(123), error.errorCodes) + assertEquals("recoverable-trace", error.traceId) + assertEquals("raw-time", error.timestamp) + } + } + + @Test + fun getTokenApiResponse_invalidErrorCodesFallBackToMessageWithoutChangingClassification() { + for (codes in listOf("null", "\"bad\"", "[100,\"200\"]", "[1.5]", "[2147483648]", "[2147483647.0000001]", "[null]")) { + val result = handler.getTokenApiResponse( + CORRELATION_ID, + response( + 400, + """{"error":"invalid_grant","error_description":"AADSTS50126: Credentials rejected.", + "error_codes":$codes}""" + ) + ) + + assertTrue(codes, result is SignInTokenApiResult.UnknownError) + assertEquals(codes, listOf(50126), (result as ApiErrorResult).errorCodes) + } + } + @Test fun getTokenApiResponse_whenStatusCodeUnavailable_returnsTypedUnknownError() { val result = handler.getTokenApiResponse( @@ -219,6 +273,74 @@ class NativeAuthV2ResponseHandlerTest { assertEquals(CORRELATION_ID, error.correlationId) assertEquals("invalid_request", error.error) assertEquals("Bad request.", error.errorDescription) + assertNull(error.subError) + } + + @Test + fun getTokenApiResponse_preservesSubErrorsAcrossTokenErrorMappings() { + val cases = listOf( + Triple("invalid_request", emptyList(), SignInTokenApiResult.UnknownError::class.java), + Triple("invalid_request", listOf(90000), SignInTokenApiResult.UnknownError::class.java), + Triple("invalid_request", listOf(50142), SignInTokenApiResult.UnknownError::class.java), + Triple("invalid_grant", emptyList(), SignInTokenApiResult.UnknownError::class.java), + Triple("invalid_grant", listOf(50126), SignInTokenApiResult.InvalidCredentials::class.java), + Triple("invalid_grant", listOf(400002), SignInTokenApiResult.InvalidAuthenticationType::class.java), + Triple("user_not_found", listOf(50034), SignInTokenApiResult.UserNotFound::class.java), + Triple("future_error", listOf(90000), SignInTokenApiResult.UnknownError::class.java) + ) + + for ((errorCode, errorCodes, resultClass) in cases) { + for (subError in listOf("FutureServiceSubError", "", null)) { + val context = "$errorCode, $errorCodes, suberror=$subError" + val subErrorJson = subError?.let { "\"$it\"" } ?: "null" + val result = handler.getTokenApiResponse( + requestCorrelationId = CORRELATION_ID, + response = response( + statusCode = 400, + body = """{ + "error":"$errorCode", + "error_description":"Service diagnostic.", + "error_codes":$errorCodes, + "trace_id":"token-trace", + "timestamp":"2026-10-15 11:00:20Z", + "suberror":$subErrorJson + }""" + ) + ) + + assertEquals(context, resultClass, result.javaClass) + val error = result as ApiErrorResult + assertEquals(context, subError, error.subError) + assertEquals(context, "token-trace", error.traceId) + assertEquals(context, "2026-10-15 11:00:20Z", error.timestamp) + assertEquals(context, errorCode, error.error) + assertEquals(context, errorCodes, error.errorCodes) + assertEquals(context, CORRELATION_ID, error.correlationId) + assertTrue(context, error.errorDescription.orEmpty().endsWith("Service diagnostic.")) + } + } + } + + @Test + fun getTokenApiResponse_whenRequiredContinuationTokenIsMissing_preservesSubError() { + for (subError in listOf("mfa_required", "registration_required")) { + val result = handler.getTokenApiResponse( + requestCorrelationId = CORRELATION_ID, + response = response( + statusCode = 400, + body = """{"error":"invalid_grant","suberror":"$subError", + "trace_id":"token-trace","timestamp":"raw-time"}""" + ) + ) + + assertTrue(result is SignInTokenApiResult.UnknownError) + val error = result as ApiErrorResult + assertEquals(subError, error.subError) + assertEquals("token-trace", error.traceId) + assertEquals("raw-time", error.timestamp) + assertEquals(ApiErrorResult.INVALID_STATE, error.error) + assertEquals("oauth/v2.0/token did not return a continuation token", error.errorDescription) + } } @Test