diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 439db872d8..b63dd68383 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -955,6 +955,12 @@ Floci follows real Cognito semantics for pools created with `UsernameAttributes` the `RespondToAuthChallenge` `SECRET_HASH` is validated against the `USERNAME` sent that round. That `USERNAME` must still resolve to the session's user — the UUID or any of its current aliases — and a value naming a different user is rejected with `NotAuthorizedException`. +- The same holds for the `USERNAME` of the other challenge responses (`NEW_PASSWORD_REQUIRED`, + `MFA_SETUP`, `SOFTWARE_TOKEN_MFA`, and the SMS and email MFA codes): the session keeps the UUID, and the + email or phone number the user signed in with names the same user. The AWS Developer Guide says that with + username attributes "you can use an email address or phone number in place of the username in all APIs + except the ListUsers operation" (Working with user attributes). The one exception is the SRP password + verifier, which has to use the `USER_ID_FOR_SRP` of the challenge, as AWS documents. - `AdminUpdateUserAttributes` can change the email; afterwards sign-in works with the new email and fails with the old one, while `Username`/`sub` stay fixed. - Duplicate email/phone on `AdminCreateUser`: `UsernameExistsException` when the incoming alias is diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java index 47803a6229..f190177e35 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java @@ -446,7 +446,7 @@ final class CognitoAuthFlowHandler { throw new AwsException("NotAuthorizedException", "Session does not match client", 400); } String username = responses.get("USERNAME"); - if (username == null || !service.signInKey(pool, username).equals(service.signInKey(pool, state.username()))) { + if (!isSessionUser(pool, username, state.username())) { throw new AwsException("NotAuthorizedException", "Session does not match user", 400); } validateSecretHash(client, responses, username); @@ -543,14 +543,14 @@ final class CognitoAuthFlowHandler { consumeCustomSession(session, state); state.history.get(state.history.size() - 1).put("challengeResult", true); } - CognitoUser user = applyNewPasswordAttributes(pool, responses); + CognitoUser user = applyNewPasswordAttributes(pool, state.username, responses); return continueCustomSrpAuth(pool, client, user, session, state, clientMetadata); } String username = responses.get("USERNAME"); PasswordChangeSession pending = session == null ? null : passwordChangeSessions.get(session); if (pending == null || sessionExpired(pending.expiresAt()) || !pool.getId().equals(pending.userPoolId()) || !client.getClientId().equals(pending.clientId()) - || !service.signInKey(pool, pending.username()).equals(service.signInKey(pool, username))) { + || !isSessionUser(pool, username, pending.username())) { throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400); } validateSecretHash(client, responses, username); @@ -561,7 +561,7 @@ final class CognitoAuthFlowHandler { changePassword(pool, responses); passwordChangeSessions.remove(session, pending); } - CognitoUser user = applyNewPasswordAttributes(pool, responses); + CognitoUser user = applyNewPasswordAttributes(pool, pending.username(), responses); return completePrimaryAuth(pool, client, user, "TokenGeneration_NewPasswordChallenge", clientMetadata, pending.authEventId()); } @@ -578,8 +578,12 @@ final class CognitoAuthFlowHandler { service.adminSetUserPassword(pool.getId(), username, newPassword, true); } - private CognitoUser applyNewPasswordAttributes(UserPool pool, Map responses) { - String username = responses.get("USERNAME"); + /** + * Applies the attributes of the response, then reads the user back. {@code username} is the user's own username + * from the session: the USERNAME of the response may be an alias such as the email, which stops naming the + * user once the response changes it. + */ + private CognitoUser applyNewPasswordAttributes(UserPool pool, String username, Map responses) { Map attrUpdates = newPasswordAttributes(responses); if (!attrUpdates.isEmpty()) { service.adminUpdateUserAttributes(pool.getId(), username, attrUpdates); @@ -890,6 +894,29 @@ final class CognitoAuthFlowHandler { } } + /** + * Whether {@code supplied}, the USERNAME of a challenge response, names the user a session was issued for. + * The session keeps the user's own username, which in a pool with {@code UsernameAttributes} is the + * {@code sub} and not the email or phone number the user signed in with. AWS documents that an SRP + * response must use that username and not an alias (the SRP paths here stay strict), and documents + * only {@code USERNAME} for the other challenges, without excluding the alias. The custom-auth + * challenges here already resolve the alias to the session's user, so the NEW_PASSWORD_REQUIRED and MFA + * challenges of the other flows do as well. A direct match of the sign-in keys counts, so a pool + * without aliases and its case sensitivity behave as before; only otherwise is the supplied value + * resolved to its user, with a single lookup, because every session holds the username of its user + * already. + */ + private boolean isSessionUser(UserPool pool, String supplied, String sessionUsername) { + if (supplied == null) { + return false; + } + if (service.signInKey(pool, supplied).equals(service.signInKey(pool, sessionUsername))) { + return true; + } + String canonical = resolveToCanonicalUsername(pool, supplied); + return canonical != null && service.signInKey(pool, canonical).equals(service.signInKey(pool, sessionUsername)); + } + // ──────────────────────────── SRP ──────────────────────────── /** @param recordAuthEvent whether this is one of the flows that record a sign-in event, not USER_AUTH's PASSWORD_SRP */ @@ -1598,7 +1625,7 @@ final class CognitoAuthFlowHandler { validateSecretHash(client, responses, suppliedUsername); CognitoUser user = service.adminGetUser(pool.getId(), state.username); - if (!user.getUsername().equals(resolveToCanonicalUsername(pool, suppliedUsername))) { + if (!isSessionUser(pool, suppliedUsername, user.getUsername())) { throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400); } @@ -1738,7 +1765,7 @@ final class CognitoAuthFlowHandler { private void validateCustomUsername(UserPool pool, UserPoolClient client, CustomAuthSession state, Map responses) { String supplied = responses.get("USERNAME"); - if (!state.username.equals(resolveToCanonicalUsername(pool, supplied))) { + if (!isSessionUser(pool, supplied, state.username)) { throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400); } validateSecretHash(client, responses, supplied); @@ -2589,7 +2616,7 @@ final class CognitoAuthFlowHandler { throw new AwsException("NotAuthorizedException", "Session does not match client", 400); } String username = responses.get("USERNAME"); - if (username == null || !service.signInKey(pool, username).equals(service.signInKey(pool, state.username()))) { + if (!isSessionUser(pool, username, state.username())) { throw new AwsException("NotAuthorizedException", "Session does not match user", 400); } validateSecretHash(client, responses, username); diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoAliasMfaIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoAliasMfaIntegrationTest.java new file mode 100644 index 0000000000..bcf97f3f32 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cognito/CognitoAliasMfaIntegrationTest.java @@ -0,0 +1,212 @@ +package io.floci.aws.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.latestSms; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * MFA challenges in a pool created with {@code UsernameAttributes = ["email"]}. The session of such a challenge + * keeps the user's own username (the {@code sub}), while the user signed in with, and answers with, the email: + * the challenge response has to accept that sign-in alias, and only the alias of the session's own user. + */ +@QuarkusTest +class CognitoAliasMfaIntegrationTest { + private static final String PASSWORD = "Perm1234!"; + private static final String TEMPORARY_PASSWORD = "Temp1234!"; + + @Inject + Clock clock; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void totpChallengesAcceptTheEmailTheUserSignedInWith() throws Exception { + String poolId = createAliasPool(""" + {"MfaConfiguration":"ON","SoftwareTokenMfaConfiguration":{"Enabled":true}}"""); + String clientId = createClient(poolId); + String email = createUser(poolId, null); + String otherEmail = createUser(poolId, null); + + String loginRequest = login(clientId, email); + JsonNode challenge = cognitoJson("InitiateAuth", loginRequest); + assertEquals("MFA_SETUP", challenge.path("ChallengeName").asText()); + + JsonNode associated = cognitoJson("AssociateSoftwareToken", """ + {"Session":"%s"} + """.formatted(challenge.path("Session").asText())); + String secret = associated.path("SecretCode").asText(); + String code = CognitoTotp.code(secret, clock.instant()); + JsonNode verified = cognitoJson("VerifySoftwareToken", """ + {"Session":"%s","UserCode":"%s"} + """.formatted(associated.path("Session").asText(), code)); + String setupSession = verified.path("Session").asText(); + + // the email of another user does not name the user of this session + cognitoAction("RespondToAuthChallenge", respond(clientId, "MFA_SETUP", setupSession, otherEmail, "")) + .then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Session does not match user")); + + JsonNode completed = cognitoJson("RespondToAuthChallenge", + respond(clientId, "MFA_SETUP", setupSession, email, "")); + assertFalse(completed.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + + JsonNode later = cognitoJson("InitiateAuth", loginRequest); + assertEquals("SOFTWARE_TOKEN_MFA", later.path("ChallengeName").asText()); + String nextCode = CognitoTotp.code(secret, clock.instant().plusSeconds(30)); + String laterSession = later.path("Session").asText(); + cognitoAction("RespondToAuthChallenge", respond(clientId, "SOFTWARE_TOKEN_MFA", laterSession, otherEmail, + ",\"SOFTWARE_TOKEN_MFA_CODE\":\"" + nextCode + "\"")) + .then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Session does not match user")); + JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond(clientId, "SOFTWARE_TOKEN_MFA", + laterSession, email, ",\"SOFTWARE_TOKEN_MFA_CODE\":\"" + nextCode + "\"")); + assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + } + + @Test + void smsChallengeAcceptsTheEmailTheUserSignedInWith() throws Exception { + String poolId = createAliasPool(""" + {"MfaConfiguration":"ON","SmsMfaConfiguration":{"SmsAuthenticationMessage":"Your MFA code is {####}"}}"""); + String clientId = createClient(poolId); + String phone = "+1555" + ThreadLocalRandom.current().nextInt(1_000_000, 9_999_999); + String email = createUser(poolId, phone); + String otherEmail = createUser(poolId, null); + + JsonNode challenge = cognitoJson("InitiateAuth", login(clientId, email)); + assertEquals("SMS_MFA", challenge.path("ChallengeName").asText()); + String code = CognitoCodes.sixDigitCode(latestSms(phone)); + String codeResponse = ",\"SMS_MFA_CODE\":\"" + code + "\""; + String session = challenge.path("Session").asText(); + + cognitoAction("RespondToAuthChallenge", respond(clientId, "SMS_MFA", session, otherEmail, codeResponse)) + .then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Session does not match user")); + JsonNode result = cognitoJson("RespondToAuthChallenge", + respond(clientId, "SMS_MFA", session, email, codeResponse)); + assertFalse(result.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + } + + @Test + void newPasswordChallengeAcceptsTheEmailTheUserSignedInWith() throws Exception { + String poolId = createAliasPool(""" + {"MfaConfiguration":"OFF"}"""); + String clientId = createClient(poolId); + String email = createUserWithTemporaryPassword(poolId); + String otherEmail = createUserWithTemporaryPassword(poolId); + + JsonNode challenge = cognitoJson("InitiateAuth", login(clientId, email, TEMPORARY_PASSWORD)); + assertEquals("NEW_PASSWORD_REQUIRED", challenge.path("ChallengeName").asText()); + String session = challenge.path("Session").asText(); + String newPassword = ",\"NEW_PASSWORD\":\"" + PASSWORD + "\""; + + cognitoAction("RespondToAuthChallenge", + respond(clientId, "NEW_PASSWORD_REQUIRED", session, otherEmail, newPassword)) + .then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Invalid session for the user.")); + JsonNode result = cognitoJson("RespondToAuthChallenge", + respond(clientId, "NEW_PASSWORD_REQUIRED", session, email, newPassword)); + assertFalse(result.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + } + + @Test + void newPasswordChallengeCompletesWhenTheResponseChangesTheEmail() throws Exception { + String poolId = createAliasPool(""" + {"MfaConfiguration":"OFF"}"""); + String clientId = createClient(poolId); + String email = createUserWithTemporaryPassword(poolId); + String newEmail = "alias-mfa-new-" + UUID.randomUUID() + "@example.com"; + + JsonNode challenge = cognitoJson("InitiateAuth", login(clientId, email, TEMPORARY_PASSWORD)); + assertEquals("NEW_PASSWORD_REQUIRED", challenge.path("ChallengeName").asText()); + String responses = ",\"NEW_PASSWORD\":\"" + PASSWORD + "\",\"userAttributes.email\":\"" + newEmail + "\""; + + JsonNode result = cognitoJson("RespondToAuthChallenge", respond(clientId, "NEW_PASSWORD_REQUIRED", + challenge.path("Session").asText(), email, responses)); + assertFalse(result.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + + JsonNode signedIn = cognitoJson("InitiateAuth", login(clientId, newEmail)); + assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty()); + } + + private static String createAliasPool(String mfaConfiguration) throws Exception { + String poolId = cognitoJson("CreateUserPool", """ + {"PoolName":"AliasMfaPool","UsernameAttributes":["email"]} + """).path("UserPool").path("Id").asText(); + String configuration = mfaConfiguration.substring(1, mfaConfiguration.length() - 1); + cognitoJson("SetUserPoolMfaConfig", """ + {"UserPoolId":"%s",%s} + """.formatted(poolId, configuration)); + return poolId; + } + + private static String createClient(String poolId) throws Exception { + return cognitoJson("CreateUserPoolClient", """ + {"UserPoolId":"%s","ClientName":"alias-mfa-client", + "ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]} + """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText(); + } + + /** Creates a user that signs in with the returned email; {@code phone} is optional. */ + private static String createUser(String poolId, String phone) throws Exception { + String email = "alias-mfa-" + UUID.randomUUID() + "@example.com"; + String phoneAttribute = phone == null ? "" + : ",\"UserAttributes\":[{\"Name\":\"phone_number\",\"Value\":\"" + phone + "\"}]"; + cognitoJson("AdminCreateUser", """ + {"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS"%s} + """.formatted(poolId, email, phoneAttribute)); + cognitoJson("AdminSetUserPassword", """ + {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true} + """.formatted(poolId, email, PASSWORD)); + return email; + } + + /** Creates a user that still has to choose a password, and signs in with the returned email. */ + private static String createUserWithTemporaryPassword(String poolId) throws Exception { + String email = "alias-mfa-" + UUID.randomUUID() + "@example.com"; + cognitoJson("AdminCreateUser", """ + {"UserPoolId":"%s","Username":"%s","TemporaryPassword":"%s","MessageAction":"SUPPRESS"} + """.formatted(poolId, email, TEMPORARY_PASSWORD)); + return email; + } + + private static String login(String clientId, String email) { + return login(clientId, email, PASSWORD); + } + + private static String login(String clientId, String email, String password) { + return """ + {"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH", + "AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}} + """.formatted(clientId, email, password); + } + + /** {@code extraResponses} is appended inside {@code ChallengeResponses}, so it starts with a comma. */ + private static String respond(String clientId, String challengeName, String session, String username, + String extraResponses) { + return """ + {"ClientId":"%s","ChallengeName":"%s","Session":"%s", + "ChallengeResponses":{"USERNAME":"%s"%s}} + """.formatted(clientId, challengeName, session, username, extraResponses); + } +} diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoMessageMfaIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoMessageMfaIntegrationTest.java index 0994669a97..f3517bcccd 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoMessageMfaIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoMessageMfaIntegrationTest.java @@ -15,6 +15,7 @@ import java.util.concurrent.ThreadLocalRandom; import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoAction; import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.latestSms; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -453,13 +454,6 @@ class CognitoMessageMfaIntegrationTest { value); } - private static String latestSms(String phone) throws Exception { - JsonNode messages = JSON.readTree(given().queryParam("phone", phone).get("/_aws/sns") - .then().statusCode(200).extract().asString()).path("messages"); - assertTrue(messages.isArray() && !messages.isEmpty(), "an SMS should have been sent to " + phone); - return messages.get(messages.size() - 1).path("Message").asText(); - } - /** The newest message to {@code recipient}: {@code /_aws/ses?email=} filters by sender, so match the recipient here. */ private static JsonNode latestEmail(String recipient) throws Exception { JsonNode messages = JSON.readTree(given().get("/_aws/ses") diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoRestAssuredUtils.java b/src/test/java/io/floci/aws/services/cognito/CognitoRestAssuredUtils.java index d84eb6c1a8..4d70461e22 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoRestAssuredUtils.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoRestAssuredUtils.java @@ -1,10 +1,16 @@ package io.floci.aws.services.cognito; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.testing.RestAssuredJsonUtils; import io.restassured.response.Response; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class CognitoRestAssuredUtils { + private static final ObjectMapper JSON = new ObjectMapper(); + private CognitoRestAssuredUtils(){} public static Response cognitoAction(String action, String body) { @@ -14,4 +20,11 @@ public class CognitoRestAssuredUtils { public static JsonNode cognitoJson(String action, String body) throws Exception { return RestAssuredJsonUtils.awsActionJson("AWSCognitoIdentityProviderService", action, body); } + + public static String latestSms(String phone) throws Exception { + JsonNode messages = JSON.readTree(given().queryParam("phone", phone).get("/_aws/sns") + .then().statusCode(200).extract().asString()).path("messages"); + assertTrue(messages.isArray() && !messages.isEmpty(), "an SMS should have been sent to " + phone); + return messages.get(messages.size() - 1).path("Message").asText(); + } }