diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java index 53ee06d718..2546f018a4 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java @@ -322,6 +322,27 @@ class CognitoFeaturesTest { .isTrue(); } + // ── Issue #4760: GetUserAuthFactors ────────────────────────────────────── + + @Test + @Order(34) + void getUserAuthFactorsListsPasswordAndVerifiedEmail() { + InitiateAuthResponse resp = cognito.initiateAuth(b -> b + .clientId(clientId) + .authFlow(AuthFlowType.USER_PASSWORD_AUTH) + .authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD))); + String accessToken = resp.authenticationResult().accessToken(); + + GetUserAuthFactorsResponse factors = cognito.getUserAuthFactors(b -> b.accessToken(accessToken)); + + assertThat(factors.username()) + .isEqualTo(cognito.getUser(b -> b.accessToken(accessToken)).username()); + assertThat(factors.configuredUserAuthFactors()) + .containsExactly(AuthFactorType.PASSWORD, AuthFactorType.EMAIL_OTP); + assertThat(factors.preferredMfaSetting()).isNull(); + assertThat(factors.hasUserMFASettingList()).isFalse(); + } + // ── Issue #220 — AdminGetUser accepts sub UUID and email as Username ─────── @Test diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 7df36bba6b..059c3b94bd 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -190,6 +190,7 @@ further divergences, both deliberate: | SignUp | Creates a self-service user for an app client. | | ConfirmSignUp | Confirms a pending self-service signup. | | GetUser | Returns attributes for the authenticated access-token user. | +| GetUserAuthFactors | Returns the authenticated access-token user's sign-in factors: `PASSWORD` when the user has a password, `EMAIL_OTP` and `SMS_OTP` when the email or phone number is verified, whatever the pool's `AllowedFirstAuthFactors` allows, as on AWS, and `SOFTWARE_TOKEN` once `VerifySoftwareToken` has confirmed an authenticator. The access token must carry the `aws.cognito.signin.user.admin` scope. `UserMFASettingList` and `PreferredMfaSetting` report the email MFA preference set with `SetUserMFAPreference`. `WEB_AUTHN` and SMS or software-token MFA settings are not reported. | | GetUserAttributeVerificationCode | Issues a verification code for the authenticated user's email or phone_number attribute. | | VerifyUserAttribute | Verifies an email or phone_number attribute with its issued verification code. | | UpdateUserAttributes | Updates attributes for the authenticated access-token user. | diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java index b64bf480a3..15cafae333 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -1014,25 +1014,57 @@ final class CognitoAuthFlowHandler { /** The set of USER_AUTH challenges this user currently qualifies for. */ private List availableUserAuthChallenges(CognitoUser user) { List available = new ArrayList<>(); - if (user.getPasswordHash() != null) { + if (hasPassword(user)) { available.add("PASSWORD"); } if (user.getSrpVerifier() != null) { available.add("PASSWORD_SRP"); } - Map attrs = user.getAttributes(); - if (attrs != null && service.verificationServicesConfigured()) { - if (Boolean.parseBoolean(attrs.getOrDefault("email_verified", "false")) && attrs.get("email") != null) { + if (service.verificationServicesConfigured()) { + if (hasVerifiedAttribute(user, "email")) { available.add("EMAIL_OTP"); } - if (Boolean.parseBoolean(attrs.getOrDefault("phone_number_verified", "false")) - && attrs.get("phone_number") != null) { + if (hasVerifiedAttribute(user, "phone_number")) { available.add("SMS_OTP"); } } return available; } + /** + * The sign-in factors {@code user} has set up, as GetUserAuthFactors reports them, in the + * {@code AuthFactorType} enum's order. AWS lists what the user holds, not what the pool's + * {@code AllowedFirstAuthFactors} permits, so neither that policy nor Floci's code-delivery + * wiring filters this list. {@code WEB_AUTHN} never appears: Floci stores no passkeys. + */ + List configuredUserAuthFactors(CognitoUser user) { + List factors = new ArrayList<>(); + if (hasPassword(user)) { + factors.add("PASSWORD"); + } + if (hasVerifiedAttribute(user, "email")) { + factors.add("EMAIL_OTP"); + } + if (hasVerifiedAttribute(user, "phone_number")) { + factors.add("SMS_OTP"); + } + if (user.getSoftwareTokenMfaSecret() != null) { + factors.add("SOFTWARE_TOKEN"); + } + return factors; + } + + private static boolean hasPassword(CognitoUser user) { + return user.getPasswordHash() != null; + } + + private static boolean hasVerifiedAttribute(CognitoUser user, String attributeName) { + Map attrs = user.getAttributes(); + return attrs != null + && Boolean.parseBoolean(attrs.getOrDefault(attributeName + "_verified", "false")) + && attrs.get(attributeName) != null; + } + private void requireSignInEligible(CognitoUser user) { if (!user.isEnabled()) { throw new AwsException("UserNotConfirmedException", "User is disabled", 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java index c178a9e264..a011ae93bc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java @@ -105,6 +105,7 @@ public class CognitoJsonHandler { case "ForgotPassword" -> handleForgotPassword(request); case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request); case "GetUser" -> handleGetUser(request); + case "GetUserAuthFactors" -> handleGetUserAuthFactors(request); case "GetUserAttributeVerificationCode" -> handleGetUserAttributeVerificationCode(request); case "VerifyUserAttribute" -> handleVerifyUserAttribute(request); case "UpdateUserAttributes" -> handleUpdateUserAttributes(request); @@ -1023,6 +1024,11 @@ public class CognitoJsonHandler { return Response.ok(objectMapper.valueToTree(result)).build(); } + private Response handleGetUserAuthFactors(JsonNode request) { + Map result = service.getUserAuthFactors(request.path("AccessToken").asText()); + return Response.ok(objectMapper.valueToTree(result)).build(); + } + private Response handleGetUserAttributeVerificationCode(JsonNode request) { Map deliveryDetails = service.getUserAttributeVerificationCode( request.path("AccessToken").asText(), diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 2bb8034126..bf12d155c5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -3091,6 +3091,41 @@ public class CognitoService implements ResourceProvider { return result; } + /** + * GetUserAuthFactors. The MFA members come from the email MFA preference, the one per-user + * MFA setting Floci stores; SetUserMFAPreference accepts SMS and software-token settings + * without keeping them. + */ + public Map getUserAuthFactors(String accessToken) { + VerifiedAccessToken token; + try { + token = verifyAccessToken(accessToken); + } catch (AwsException e) { + if ("NotAuthorizedException".equals(e.getErrorCode()) + && INVALID_ACCESS_TOKEN_MESSAGE.equals(e.getMessage())) { + throw new AwsException("NotAuthorizedException", "Invalid Access Token", 400); + } + throw e; + } + requireScope(accessToken, "aws.cognito.signin.user.admin"); + + CognitoUser user = adminGetUser(token.poolId(), token.username()); + Map result = new LinkedHashMap<>(); + result.put("Username", user.getUsername()); + List factors = authFlowHandler.configuredUserAuthFactors(user); + if (!factors.isEmpty()) { + result.put("ConfiguredUserAuthFactors", factors); + } + EmailMfaSettings emailMfa = user.getEmailMfaSettings(); + if (emailMfa != null && emailMfa.isEnabled()) { + if (emailMfa.isPreferredMfa()) { + result.put("PreferredMfaSetting", "EMAIL_OTP"); + } + result.put("UserMFASettingList", List.of("EMAIL_OTP")); + } + return result; + } + public Map getUserAttributeVerificationCode(String accessToken, String attributeName) { VerifiedAccessToken token; try { @@ -3692,7 +3727,11 @@ public class CognitoService implements ResourceProvider { if (override.scopesToAdd() != null) { for (String s : override.scopesToAdd()) if (!current.contains(s)) current.add(s); } - if (!current.isEmpty()) claims.put("scope", String.join(" ", current)); + if (current.isEmpty()) { + claims.remove("scope"); + } else { + claims.put("scope", String.join(" ", current)); + } } } @@ -4575,39 +4614,40 @@ public class CognitoService implements ResourceProvider { /** - * Extracts the space-separated {@code scope} claim from an already-verified access token - * (call after {@link #verifyAccessToken}). {@code null} means no scope claim at all, which - * every token this simulator currently issues also is not the case for access tokens (see - * {@code generateSignedJwt}, which always sets a default scope) but a caller-suppressed - * scope list still needs to be tolerated as "no restriction modeled" rather than treated the - * same as an empty, restrictive list. + * The scopes in the space-separated {@code scope} claim of an already-verified access token + * (call after {@link #verifyAccessToken}), empty when the claim is absent or blank. Every access + * token Floci mints sets the claim (see {@code generateSignedJwt}); it is missing only when a + * PreTokenGeneration trigger removed it, and such a token grants no scope. */ private Set extractScopesFromToken(String token) { try { String[] parts = token.split("\\.", -1); JsonNode claims = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[1])); String scope = textClaim(claims, "scope"); - if (scope == null || scope.isBlank()) return null; Set scopes = new HashSet<>(); + if (scope == null) { + return scopes; + } for (String s : scope.split(" ")) { if (!s.isBlank()) scopes.add(s); } return scopes; } catch (Exception e) { - return null; + LOG.debug("Could not read the scope claim of an access token", e); + return Set.of(); } } /** * AWS requires an access token carrying the given scope for some operations (for example - * VerifyUserAttribute requires aws.cognito.signin.user.admin). Call after - * {@link #verifyAccessToken}, which already confirms the token is a valid, unexpired access - * token; this only adds the scope check on top. + * VerifyUserAttribute requires aws.cognito.signin.user.admin), and refuses a token with no + * scope claim. Call after {@link #verifyAccessToken}, which already confirms the token is a + * valid, unexpired access token; this only adds the scope check on top. */ void requireScope(String accessToken, String requiredScope) { Set scopes = extractScopesFromToken(accessToken); - if (scopes != null && !scopes.contains(requiredScope)) { - throw new AwsException("NotAuthorizedException", "Access Token does not have the required scope", 400); + if (!scopes.contains(requiredScope)) { + throw new AwsException("NotAuthorizedException", "Access Token does not have required scopes", 400); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoGetUserAuthFactorsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoGetUserAuthFactorsIntegrationTest.java new file mode 100644 index 0000000000..c0a2d0e9bf --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoGetUserAuthFactorsIntegrationTest.java @@ -0,0 +1,376 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.time.Clock; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * GetUserAuthFactors over the JSON 1.1 wire protocol. The pools use email as a username + * attribute, so each user's username is its generated sub, which is what AWS returns as + * {@code Username} for such a pool. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CognitoGetUserAuthFactorsIntegrationTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b"); + private static final String PASSWORD = "Factors1234!"; + + private static String passwordOnlyPoolId; + private static String passwordOnlyClientId; + private static String passwordlessPoolId; + private static String passwordlessClientId; + + @Inject + Clock clock; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void setUpPoolsAndClients() throws Exception { + passwordOnlyPoolId = createPool("AuthFactorsPasswordOnlyPool", "[\"PASSWORD\"]"); + passwordOnlyClientId = createClient(passwordOnlyPoolId); + passwordlessPoolId = createPool("AuthFactorsPasswordlessPool", "[\"PASSWORD\", \"EMAIL_OTP\"]"); + passwordlessClientId = createClient(passwordlessPoolId); + } + + @Test + @Order(2) + void passwordAndVerifiedEmailAreReportedEvenWhenThePoolAllowsOnlyPassword() throws Exception { + String email = uniqueEmail(); + createUserWithPassword(passwordOnlyPoolId, email, """ + { "Name": "email", "Value": "%s" }, + { "Name": "email_verified", "Value": "true" } + """.formatted(email)); + String accessToken = signInWithPassword(passwordOnlyClientId, email); + String username = cognitoJson("GetUser", accessTokenBody(accessToken)).path("Username").asText(); + + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(200) + .body("Username", equalTo(username)) + .body("ConfiguredUserAuthFactors", contains("PASSWORD", "EMAIL_OTP")) + .body("$", not(hasKey("PreferredMfaSetting"))) + .body("$", not(hasKey("UserMFASettingList"))); + assertNotEquals(email, username, "an email-username pool keys the user by its sub"); + } + + @Test + @Order(3) + void unverifiedEmailIsNotAFactor() throws Exception { + String email = uniqueEmail(); + createUserWithPassword(passwordOnlyPoolId, email, """ + { "Name": "email", "Value": "%s" } + """.formatted(email)); + String accessToken = signInWithPassword(passwordOnlyClientId, email); + + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(200) + .body("ConfiguredUserAuthFactors", contains("PASSWORD")); + } + + @Test + @Order(4) + void verifiedPhoneNumberAddsSmsOtpAfterEmailOtp() throws Exception { + String email = uniqueEmail(); + createUserWithPassword(passwordOnlyPoolId, email, """ + { "Name": "email", "Value": "%s" }, + { "Name": "email_verified", "Value": "true" }, + { "Name": "phone_number", "Value": "+15555550123" }, + { "Name": "phone_number_verified", "Value": "true" } + """.formatted(email)); + String accessToken = signInWithPassword(passwordOnlyClientId, email); + + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(200) + .body("ConfiguredUserAuthFactors", contains("PASSWORD", "EMAIL_OTP", "SMS_OTP")); + } + + @Test + @Order(5) + void passwordlessUserSignedInWithEmailOtpHasNoPasswordFactor() throws Exception { + String email = uniqueEmail(); + cognitoAction("AdminCreateUser", """ + { + "UserPoolId": "%s", + "Username": "%s", + "MessageAction": "SUPPRESS", + "UserAttributes": [ + { "Name": "email", "Value": "%s" }, + { "Name": "email_verified", "Value": "true" } + ] + } + """.formatted(passwordlessPoolId, email, email)) + .then() + .statusCode(200); + + given().delete("/_aws/ses").then().statusCode(200); + JsonNode challenge = cognitoJson("InitiateAuth", """ + { + "ClientId": "%s", + "AuthFlow": "USER_AUTH", + "AuthParameters": { "USERNAME": "%s", "PREFERRED_CHALLENGE": "EMAIL_OTP" } + } + """.formatted(passwordlessClientId, email)); + assertEquals("EMAIL_OTP", challenge.path("ChallengeName").asText()); + JsonNode auth = cognitoJson("RespondToAuthChallenge", """ + { + "ClientId": "%s", + "ChallengeName": "EMAIL_OTP", + "Session": "%s", + "ChallengeResponses": { "USERNAME": "%s", "EMAIL_OTP_CODE": "%s" } + } + """.formatted(passwordlessClientId, challenge.path("Session").asText(), + challenge.path("ChallengeParameters").path("USERNAME").asText(), + fetchLatestSesCode(email))); + String accessToken = auth.path("AuthenticationResult").path("AccessToken").asText(); + + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(200) + .body("ConfiguredUserAuthFactors", contains("EMAIL_OTP")); + } + + @Test + @Order(6) + void emailMfaPreferenceIsReportedAsMfaSettings() throws Exception { + String email = uniqueEmail(); + createUserWithPassword(passwordOnlyPoolId, email, """ + { "Name": "email", "Value": "%s" }, + { "Name": "email_verified", "Value": "true" } + """.formatted(email)); + String accessToken = signInWithPassword(passwordOnlyClientId, email); + + cognitoAction("SetUserMFAPreference", """ + { "AccessToken": "%s", "EmailMfaSettings": { "Enabled": true } } + """.formatted(accessToken)) + .then() + .statusCode(200); + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(200) + .body("UserMFASettingList", contains("EMAIL_OTP")) + .body("$", not(hasKey("PreferredMfaSetting"))); + + cognitoAction("SetUserMFAPreference", """ + { "AccessToken": "%s", "EmailMfaSettings": { "Enabled": true, "PreferredMfa": true } } + """.formatted(accessToken)) + .then() + .statusCode(200); + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(200) + .body("ConfiguredUserAuthFactors", contains("PASSWORD", "EMAIL_OTP")) + .body("PreferredMfaSetting", equalTo("EMAIL_OTP")) + .body("UserMFASettingList", contains("EMAIL_OTP")); + } + + @Test + @Order(7) + void invalidAccessTokenIsRejected() { + cognitoAction("GetUserAuthFactors", accessTokenBody("not-a-valid-token")) + .then() + .statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Invalid Access Token")); + } + + @Test + @Order(8) + void globallySignedOutTokenIsRejectedLikeGetUser() throws Exception { + String email = uniqueEmail(); + createUserWithPassword(passwordOnlyPoolId, email, """ + { "Name": "email", "Value": "%s" } + """.formatted(email)); + String accessToken = signInWithPassword(passwordOnlyClientId, email); + cognitoAction("GlobalSignOut", accessTokenBody(accessToken)).then().statusCode(200); + + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Access Token has been revoked")); + cognitoAction("GetUser", accessTokenBody(accessToken)) + .then() + .statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Access Token has been revoked")); + } + + @Test + @Order(9) + void deletedUserTokenIsRejectedLikeGetUser() throws Exception { + String email = uniqueEmail(); + createUserWithPassword(passwordOnlyPoolId, email, """ + { "Name": "email", "Value": "%s" } + """.formatted(email)); + String accessToken = signInWithPassword(passwordOnlyClientId, email); + cognitoAction("AdminDeleteUser", """ + { "UserPoolId": "%s", "Username": "%s" } + """.formatted(passwordOnlyPoolId, email)) + .then() + .statusCode(200); + + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(400) + .body("__type", equalTo("UserNotFoundException")); + cognitoAction("GetUser", accessTokenBody(accessToken)) + .then() + .statusCode(400) + .body("__type", equalTo("UserNotFoundException")); + } + + @Test + @Order(10) + void verifiedSoftwareTokenIsReportedLastButAnUnverifiedOneIsNot() throws Exception { + String poolId = createPool("AuthFactorsTotpPool", "[\"PASSWORD\"]"); + cognitoAction("SetUserPoolMfaConfig", """ + { + "UserPoolId": "%s", + "MfaConfiguration": "OPTIONAL", + "SoftwareTokenMfaConfiguration": { "Enabled": true } + } + """.formatted(poolId)) + .then() + .statusCode(200); + String clientId = createClient(poolId); + String email = uniqueEmail(); + createUserWithPassword(poolId, email, """ + { "Name": "email", "Value": "%s" }, + { "Name": "email_verified", "Value": "true" }, + { "Name": "phone_number", "Value": "+15555550124" }, + { "Name": "phone_number_verified", "Value": "true" } + """.formatted(email)); + String accessToken = signInWithPassword(clientId, email); + + String secret = cognitoJson("AssociateSoftwareToken", accessTokenBody(accessToken)) + .path("SecretCode").asText(); + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(200) + .body("ConfiguredUserAuthFactors", contains("PASSWORD", "EMAIL_OTP", "SMS_OTP")); + + JsonNode verified = cognitoJson("VerifySoftwareToken", """ + { "AccessToken": "%s", "UserCode": "%s" } + """.formatted(accessToken, CognitoTotp.code(secret, clock.instant()))); + assertEquals("SUCCESS", verified.path("Status").asText()); + cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken)) + .then() + .statusCode(200) + .body("ConfiguredUserAuthFactors", + contains("PASSWORD", "EMAIL_OTP", "SMS_OTP", "SOFTWARE_TOKEN")); + } + + private static String createPool(String name, String allowedFirstAuthFactors) throws Exception { + JsonNode response = cognitoJson("CreateUserPool", """ + { + "PoolName": "%s", + "UsernameAttributes": ["email"], + "UserPoolTier": "ESSENTIALS", + "Policies": { "SignInPolicy": { "AllowedFirstAuthFactors": %s } } + } + """.formatted(name, allowedFirstAuthFactors)); + return response.path("UserPool").path("Id").asText(); + } + + private static String createClient(String poolId) throws Exception { + JsonNode response = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "auth-factors-client", + "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_USER_AUTH"] + } + """.formatted(poolId)); + return response.path("UserPoolClient").path("ClientId").asText(); + } + + private static void createUserWithPassword(String poolId, String email, String attributes) { + cognitoAction("AdminCreateUser", """ + { + "UserPoolId": "%s", + "Username": "%s", + "MessageAction": "SUPPRESS", + "UserAttributes": [ %s ] + } + """.formatted(poolId, email, attributes)) + .then() + .statusCode(200); + cognitoAction("AdminSetUserPassword", """ + { + "UserPoolId": "%s", + "Username": "%s", + "Password": "%s", + "Permanent": true + } + """.formatted(poolId, email, PASSWORD)) + .then() + .statusCode(200); + } + + private static String signInWithPassword(String clientId, String email) throws Exception { + JsonNode auth = cognitoJson("InitiateAuth", """ + { + "ClientId": "%s", + "AuthFlow": "USER_PASSWORD_AUTH", + "AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" } + } + """.formatted(clientId, email, PASSWORD)); + return auth.path("AuthenticationResult").path("AccessToken").asText(); + } + + private static String accessTokenBody(String accessToken) { + return """ + { "AccessToken": "%s" } + """.formatted(accessToken); + } + + private static String uniqueEmail() { + return "factors+" + UUID.randomUUID() + "@example.com"; + } + + private static String fetchLatestSesCode(String recipient) throws Exception { + String response = given() + .queryParam("email", recipient) + .get("/_aws/ses") + .then() + .statusCode(200) + .extract() + .asString(); + JsonNode messages = JSON.readTree(response).path("messages"); + assertTrue(messages.isArray() && !messages.isEmpty(), "an EMAIL_OTP code should have been sent"); + Matcher matcher = SIX_DIGIT_CODE.matcher(messages.get(0).path("Body").path("text_part").asText()); + assertTrue(matcher.find(), "the EMAIL_OTP message should carry a six-digit code"); + return matcher.group(1); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java index 534929c2f9..33fc15f3f8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -709,6 +709,25 @@ class CognitoLambdaTriggersTest { assertTrue(!tokens.contains("phone"), "phone dropped by scopesToSuppress"); } + @Test + @SuppressWarnings("unchecked") + void preTokenGenerationV2SuppressingEveryScopeRemovesTheScopeClaim() throws Exception { + UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token")); + seedUser(pool, "alice", "Perm1234!"); + UserPoolClient client = createClient(pool); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any())) + .thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of( + "accessTokenGeneration", Map.of( + "scopesToSuppress", List.of("aws.cognito.signin.user.admin")))))); + + Map result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", + Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")); + String accessToken = (String) ((Map) result.get("AuthenticationResult")).get("AccessToken"); + + Map claims = MAPPER.readValue(decodeJwtPayload(accessToken), new TypeReference<>() {}); + assertFalse(claims.containsKey("scope"), "suppressing the only scope leaves no scope claim: " + claims); + } + @Test @SuppressWarnings("unchecked") void preTokenGenerationV2ResolvesArnFromPreTokenGenerationConfigKey() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java index dcb290d3cb..15aacf359a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java @@ -257,6 +257,75 @@ class CognitoManagedLoginIntegrationTest { "admin/superuser is not in the client's AllowedOAuthScopes, so the trigger never sees it"); } + /** + * GetUserAuthFactors needs {@code aws.cognito.signin.user.admin} in the access token's scope. + * Floci stamps that scope on every code-grant access token whatever the request asked for, so a + * V2 trigger reshapes this token's scope to the {@code openid email} the request named. + */ + @Test + void codeGrantAccessTokenWithoutTheAdminScopeCannotReadAuthFactors() throws Exception { + String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of( + "scopesToAdd", List.of("openid", "email"), + "scopesToSuppress", List.of("aws.cognito.signin.user.admin"))); + assertEquals("openid email", jwtPayload(accessToken).path("scope").asText()); + + cognitoAction("GetUserAuthFactors", """ + {"AccessToken":"%s"} + """.formatted(accessToken)) + .then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Access Token does not have required scopes")); + } + + /** A trigger that suppresses the token's only scope leaves no scope claim, which grants nothing. */ + @Test + void codeGrantAccessTokenWithEveryScopeSuppressedCannotReadAuthFactors() throws Exception { + String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of( + "scopesToSuppress", List.of("aws.cognito.signin.user.admin"))); + assertFalse(jwtPayload(accessToken).has("scope")); + + cognitoAction("GetUserAuthFactors", """ + {"AccessToken":"%s"} + """.formatted(accessToken)) + .then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Access Token does not have required scopes")); + } + + @Test + void codeGrantAccessTokenWithEveryScopeSuppressedCannotVerifyAnAttribute() throws Exception { + String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of( + "scopesToSuppress", List.of("aws.cognito.signin.user.admin"))); + assertFalse(jwtPayload(accessToken).has("scope")); + + cognitoAction("VerifyUserAttribute", """ + {"AccessToken":"%s","AttributeName":"email","Code":"123456"} + """.formatted(accessToken)) + .then().statusCode(400) + .body("__type", equalTo("NotAuthorizedException")) + .body("message", equalTo("Access Token does not have required scopes")); + } + + @Test + void codeGrantAccessTokenWithTheAdminScopeReadsAuthFactors() throws Exception { + String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"ManagedLoginAdminScopePool\"}") + .path("UserPool").path("Id").asText(); + Pool pool = withUser(poolId, + codeClient(poolId, "\"openid\",\"email\",\"aws.cognito.signin.user.admin\""), + "user-" + System.nanoTime()); + Map query = authorizeRequest(pool.clientId()); + query.put("scope", "openid email aws.cognito.signin.user.admin"); + String accessToken = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER) + .path("access_token"); + + cognitoAction("GetUserAuthFactors", """ + {"AccessToken":"%s"} + """.formatted(accessToken)) + .then().statusCode(200) + .body("Username", equalTo(pool.username())) + .body("ConfiguredUserAuthFactors", equalTo(List.of("PASSWORD"))); + } + @Test void codeIsRefusedWithAWrongOrMissingVerifierAndAWrongOneSpendsIt() throws Exception { Pool pool = newPool(); @@ -527,17 +596,35 @@ class CognitoManagedLoginIntegrationTest { return withUser(poolId, codeClient(poolId), "user-" + System.nanoTime()); } + /** + * Signs a new pool's user in through the code grant, with a V2 PreTokenGeneration trigger + * answering {@code accessTokenGeneration}, and returns the access token it mints. + */ + private String codeGrantAccessTokenReshapedByTrigger(Map accessTokenGeneration) throws Exception { + Pool pool = newPoolWithPreTokenGenerationTrigger(); + when(lambdaService.invoke(anyString(), eq(PRE_TOKEN_GENERATION_ARN), any(), any())) + .thenReturn(triggerResponse(Map.of("claimsAndScopeOverrideDetails", + Map.of("accessTokenGeneration", accessTokenGeneration)))); + return redeem(null, pool.clientId(), + code(signIn(null, pool, authorizeRequest(pool.clientId()))), VERIFIER).path("access_token"); + } + /** A successful trigger invocation returning {@code response} as the Lambda's payload. */ private static InvokeResult triggerResponse(Map response) throws Exception { return new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of("response", response)), null, "req-id"); } private static String codeClient(String poolId) throws Exception { + return codeClient(poolId, "\"openid\",\"email\""); + } + + /** {@code allowedScopes} is the body of the AllowedOAuthScopes JSON array. */ + private static String codeClient(String poolId, String allowedScopes) throws Exception { return cognitoJson("CreateUserPoolClient", """ {"UserPoolId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true, - "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"], + "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":[%s],"CallbackURLs":["%s"], "LogoutURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]} - """.formatted(poolId, CALLBACK, SIGNED_OUT)).path("UserPoolClient").path("ClientId").asText(); + """.formatted(poolId, allowedScopes, CALLBACK, SIGNED_OUT)).path("UserPoolClient").path("ClientId").asText(); } private static Pool withUser(String poolId, String clientId, String username) throws Exception { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index bd21ecae6b..6bf6244cbd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -4953,6 +4953,68 @@ class CognitoServiceTest { assertThrows(AwsException.class, () -> service.getUserAttributeVerificationCode(invalid, "email")); assertThrows(AwsException.class, () -> service.globalSignOut(invalid)); assertThrows(AwsException.class, () -> service.setUserMFAPreference(invalid, true, false)); + assertThrows(AwsException.class, () -> service.getUserAuthFactors(invalid)); + } + + @Test + void getUserAuthFactors_userWithoutPassword_omitsPasswordFactor() { + UserPool pool = service.createUserPool(Map.of("PoolName", "PasswordlessPool"), "us-east-1"); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + CognitoUser user = service.adminCreateUser(pool.getId(), "bob", + Map.of("email", "bob@example.com", "email_verified", "true"), null); + String accessToken = service.generateSignedJwt(user, pool, "access", client, null, null); + + Map result = service.getUserAuthFactors(accessToken); + + assertEquals("bob", result.get("Username")); + assertEquals(List.of("EMAIL_OTP"), result.get("ConfiguredUserAuthFactors"), + "a verified email is a factor whether or not Floci's code delivery is wired"); + } + + @Test + void getUserAuthFactors_userWithNoFactors_returnsOnlyUsername() { + UserPool pool = service.createUserPool(Map.of("PoolName", "NoFactorPool"), "us-east-1"); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + CognitoUser user = service.adminCreateUser(pool.getId(), "carol", + Map.of("email", "carol@example.com"), null); + String accessToken = service.generateSignedJwt(user, pool, "access", client, null, null); + + assertEquals(Map.of("Username", "carol"), service.getUserAuthFactors(accessToken)); + } + + @Test + void getUserAuthFactors_accessTokenWithoutAdminScope_isRejected() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + String accessToken = service.generateSignedJwt(user, pool, "access", client, + new CognitoService.ClaimsOverride(null, null, null, null, + List.of("openid", "email"), List.of("aws.cognito.signin.user.admin"), + null, null, null)); + + AwsException ex = assertThrows(AwsException.class, () -> service.getUserAuthFactors(accessToken)); + + assertEquals("NotAuthorizedException", ex.getErrorCode()); + assertEquals("Access Token does not have required scopes", ex.getMessage()); + } + + @Test + void getUserAuthFactors_accessTokenWithNoScopeClaim_isRejected() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "c", false, false, List.of(), List.of()); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + String accessToken = service.generateSignedJwt(user, pool, "access", client, + new CognitoService.ClaimsOverride(null, null, null, List.of("scope"), + null, null, null, null, null)); + + AwsException ex = assertThrows(AwsException.class, () -> service.getUserAuthFactors(accessToken)); + + assertEquals("NotAuthorizedException", ex.getErrorCode()); + assertEquals("Access Token does not have required scopes", ex.getMessage()); } private void assertInvalidAccessToken(String token, String reason) {