Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): add GetUserAttributeVerificationCode support (#1898)
Feyikemi Ogunsanya24cdabb257c3
diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex 4c24becffd..229e7774b6 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -73,6 +73,7 @@ Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource`| 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. |+| GetUserAttributeVerificationCode | Issues a verification code for the authenticated user's email or phone_number attribute. || UpdateUserAttributes | Updates attributes for the authenticated access-token user. || ChangePassword | Changes the authenticated user's password. || ForgotPassword | Starts the local forgot-password flow for a user. |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.javaindex 4b9dea6812..dfe8a05225 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@@ -81,6 +81,7 @@ public class CognitoJsonHandler {case "ForgotPassword" -> handleForgotPassword(request);case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request);case "GetUser" -> handleGetUser(request);+ case "GetUserAttributeVerificationCode" -> handleGetUserAttributeVerificationCode(request);case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);case "DeleteUserAttributes" -> handleDeleteUserAttributes(request);case "GlobalSignOut" -> handleGlobalSignOut(request);@@ -629,6 +630,19 @@ public class CognitoJsonHandler {return Response.ok(objectMapper.valueToTree(result)).build();}+ private Response handleGetUserAttributeVerificationCode(JsonNode request) {+ Map<String, Object> deliveryDetails = service.getUserAttributeVerificationCode(+ request.path("AccessToken").asText(),+ request.path("AttributeName").asText()+ );+ ObjectNode response = objectMapper.createObjectNode();+ ObjectNode delivery = response.putObject("CodeDeliveryDetails");+ delivery.put("AttributeName", (String) deliveryDetails.get("AttributeName"));+ delivery.put("DeliveryMedium", (String) deliveryDetails.get("DeliveryMedium"));+ delivery.put("Destination", (String) deliveryDetails.get("Destination"));+ return Response.ok(response).build();+ }+private Response handleUpdateUserAttributes(JsonNode request) {Map<String, String> attrs = new HashMap<>();request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").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.javaindex 10a3f4f162..d9560c8f75 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@@ -1565,6 +1565,57 @@ public class CognitoService {return result;}+ public Map<String, Object> getUserAttributeVerificationCode(String accessToken, String attributeName) {+ String username = extractUsernameFromToken(accessToken);+ String poolId = extractPoolIdFromToken(accessToken);+ String jti = extractJtiFromToken(accessToken);++ if (username == null || poolId == null || jti == null) {+ throw new AwsException("NotAuthorizedException", "Invalid Access Token", 400);+ }++ validateTokenNotRevoked(jti, poolId, "access");+ validateOriginJtiNotRevoked(accessToken, poolId);+ Long iat = extractIatFromToken(accessToken);+ validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);++ if (!"email".equals(attributeName) && !"phone_number".equals(attributeName)) {+ throw new AwsException("InvalidParameterException",+ "Invalid attribute name. Only phone_number and email can be verified.", 400);+ }++ CognitoUser user = adminGetUser(poolId, username);+ UserPool pool = describeUserPool(poolId);+ String destination = blankToNull(user.getAttributes().get(attributeName));+ if (destination == null) {+ throw new AwsException("InvalidParameterException",+ "email".equals(attributeName)+ ? "User does not have a valid registered email address"+ : "User does not have a valid registered phone number",+ 400);+ }++ String deliveryMedium = "email".equals(attributeName) ? "EMAIL" : "SMS";+ VerificationCode.Purpose purpose = "email".equals(attributeName)+ ? VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION+ : VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;+ ensureVerificationWiring();+ try {+ String code = verificationCodeService.issue(poolId, user.getUsername(),+ purpose, Duration.ofHours(24));+ messageDispatcher.dispatch(pool, user, purpose, code, List.of(deliveryMedium));+ } catch (VerificationCodeException e) {+ throw mapVerificationCodeException(e);+ }++ Map<String, Object> response = new LinkedHashMap<>();+ response.put("AttributeName", attributeName);+ response.put("DeliveryMedium", deliveryMedium);+ response.put("Destination",+ "email".equals(attributeName) ? maskEmail(destination) : maskPhoneNumber(destination));+ return response;+ }+public void updateUserAttributes(String accessToken, Map<String, String> attributes) {String username = extractUsernameFromToken(accessToken);String poolId = extractPoolIdFromToken(accessToken);@@ -2802,34 +2853,21 @@ public class CognitoService {if (at <= 0 || at == email.length() - 1) {return "****";}- String local = email.substring(0, at);- String domain = email.substring(at + 1);- return maskSegment(local) + "@" + maskDomain(domain);+ return email.charAt(0) + "***@" + email.charAt(at + 1) + "***";}private String maskPhoneNumber(String phoneNumber) {if (phoneNumber.length() <= 4) {return "*".repeat(phoneNumber.length());}+ if (phoneNumber.charAt(0) == '+') {+ return "+" + "*".repeat(Math.max(0, phoneNumber.length() - 5))+ + phoneNumber.substring(phoneNumber.length() - 4);+ }return "*".repeat(phoneNumber.length() - 4)+ phoneNumber.substring(phoneNumber.length() - 4);}- private String maskDomain(String domain) {- int dot = domain.lastIndexOf('.');- if (dot <= 0 || dot == domain.length() - 1) {- return maskSegment(domain);- }- return maskSegment(domain.substring(0, dot)) + domain.substring(dot);- }-- private String maskSegment(String value) {- if (value.length() <= 1) {- return "*";- }- return value.charAt(0) + "*".repeat(Math.max(1, value.length() - 1));- }-private String blankToNull(String value) {if (value == null || value.isBlank()) {return null;diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCode.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCode.javaindex 4e4a8134f0..5a5ecfe819 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCode.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCode.java@@ -19,7 +19,10 @@ public final class VerificationCode {SIGNUP_CONFIRMATION,PASSWORD_RESET,SMS_MFA,- ATTRIBUTE_VERIFICATION+ // Attribute verification is keyed per attribute so email and phone_number codes+ // rate-limit and overwrite independently, matching AWS.+ EMAIL_ATTRIBUTE_VERIFICATION,+ PHONE_ATTRIBUTE_VERIFICATION}private final String userPoolId;diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationIntegrationTest.javanew file mode 100644index 0000000000..a105c514a2--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoAttributeVerificationIntegrationTest.java@@ -0,0 +1,264 @@+package io.github.hectorvent.floci.services.cognito;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+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.util.UUID;++import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;+import static org.hamcrest.Matchers.equalTo;++@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class CognitoAttributeVerificationIntegrationTest {++ private static final String USERNAME = "verify+" + UUID.randomUUID() + "@example.com";+ private static final String PASSWORD = "Verify1234!";++ private static String poolId;+ private static String clientId;+ private static String accessToken;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ @Order(1)+ void setUpPoolClientUserAndToken() throws Exception {+ JsonNode poolResponse = cognitoJson("CreateUserPool", """+ {+ "PoolName": "AttributeVerificationPool"+ }+ """);+ poolId = poolResponse.path("UserPool").path("Id").asText();++ JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """+ {+ "UserPoolId": "%s",+ "ClientName": "attribute-verification-client"+ }+ """.formatted(poolId));+ clientId = clientResponse.path("UserPoolClient").path("ClientId").asText();++ cognitoAction("AdminCreateUser", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "UserAttributes": [+ { "Name": "email", "Value": "%s" }+ ]+ }+ """.formatted(poolId, USERNAME, USERNAME))+ .then()+ .statusCode(200);++ cognitoAction("AdminSetUserPassword", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "Password": "%s",+ "Permanent": true+ }+ """.formatted(poolId, USERNAME, PASSWORD))+ .then()+ .statusCode(200);++ JsonNode auth = cognitoJson("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {+ "USERNAME": "%s",+ "PASSWORD": "%s"+ }+ }+ """.formatted(clientId, USERNAME, PASSWORD));+ accessToken = auth.path("AuthenticationResult").path("AccessToken").asText();+ }++ @Test+ @Order(2)+ void issuesEmailVerificationCode() {+ cognitoAction("GetUserAttributeVerificationCode", """+ {+ "AccessToken": "%s",+ "AttributeName": "email"+ }+ """.formatted(accessToken))+ .then()+ .statusCode(200)+ .body("CodeDeliveryDetails.AttributeName", equalTo("email"))+ .body("CodeDeliveryDetails.DeliveryMedium", equalTo("EMAIL"))+ .body("CodeDeliveryDetails.Destination", equalTo("v***@e***"));+ }++ @Test+ @Order(3)+ void rejectsInvalidAccessToken() {+ cognitoAction("GetUserAttributeVerificationCode", """+ {+ "AccessToken": "not-a-valid-token",+ "AttributeName": "email"+ }+ """)+ .then()+ .statusCode(400)+ .body("__type", equalTo("NotAuthorizedException"))+ .body("message", equalTo("Invalid Access Token"));+ }++ @Test+ @Order(4)+ void rejectsUnverifiableAttribute() {+ cognitoAction("GetUserAttributeVerificationCode", """+ {+ "AccessToken": "%s",+ "AttributeName": "given_name"+ }+ """.formatted(accessToken))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo("Invalid attribute name. Only phone_number and email can be verified."));+ }++ @Test+ @Order(5)+ void rejectsAttributeWithoutValue() {+ cognitoAction("GetUserAttributeVerificationCode", """+ {+ "AccessToken": "%s",+ "AttributeName": "phone_number"+ }+ """.formatted(accessToken))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo("User does not have a valid registered phone number"));+ }++ @Test+ @Order(6)+ void emailAndPhoneCodesAreIndependent() throws Exception {+ String username = "verify-both+" + UUID.randomUUID() + "@example.com";+ cognitoAction("AdminCreateUser", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "UserAttributes": [+ { "Name": "email", "Value": "%s" },+ { "Name": "phone_number", "Value": "+15551234567" }+ ]+ }+ """.formatted(poolId, username, username))+ .then()+ .statusCode(200);++ cognitoAction("AdminSetUserPassword", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "Password": "%s",+ "Permanent": true+ }+ """.formatted(poolId, username, PASSWORD))+ .then()+ .statusCode(200);++ JsonNode auth = cognitoJson("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {+ "USERNAME": "%s",+ "PASSWORD": "%s"+ }+ }+ """.formatted(clientId, username, PASSWORD));+ String token = auth.path("AuthenticationResult").path("AccessToken").asText();++ // Back-to-back requests for different attributes must not trip the shared+ // rate limit or overwrite each other: each attribute has its own code slot.+ cognitoAction("GetUserAttributeVerificationCode", """+ {+ "AccessToken": "%s",+ "AttributeName": "email"+ }+ """.formatted(token))+ .then()+ .statusCode(200)+ .body("CodeDeliveryDetails.DeliveryMedium", equalTo("EMAIL"));++ cognitoAction("GetUserAttributeVerificationCode", """+ {+ "AccessToken": "%s",+ "AttributeName": "phone_number"+ }+ """.formatted(token))+ .then()+ .statusCode(200)+ .body("CodeDeliveryDetails.AttributeName", equalTo("phone_number"))+ .body("CodeDeliveryDetails.DeliveryMedium", equalTo("SMS"))+ .body("CodeDeliveryDetails.Destination", equalTo("+*******4567"));+ }++ @Test+ @Order(7)+ void allowsFreshCodeForAlreadyVerifiedAttribute() throws Exception {+ String username = "verify-already+" + UUID.randomUUID() + "@example.com";+ cognitoAction("AdminCreateUser", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "UserAttributes": [+ { "Name": "email", "Value": "%s" },+ { "Name": "email_verified", "Value": "true" }+ ]+ }+ """.formatted(poolId, username, username))+ .then()+ .statusCode(200);++ cognitoAction("AdminSetUserPassword", """+ {+ "UserPoolId": "%s",+ "Username": "%s",+ "Password": "%s",+ "Permanent": true+ }+ """.formatted(poolId, username, PASSWORD))+ .then()+ .statusCode(200);++ JsonNode auth = cognitoJson("InitiateAuth", """+ {+ "ClientId": "%s",+ "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {+ "USERNAME": "%s",+ "PASSWORD": "%s"+ }+ }+ """.formatted(clientId, username, PASSWORD));+ String token = auth.path("AuthenticationResult").path("AccessToken").asText();++ cognitoAction("GetUserAttributeVerificationCode", """+ {+ "AccessToken": "%s",+ "AttributeName": "email"+ }+ """.formatted(token))+ .then()+ .statusCode(200)+ .body("CodeDeliveryDetails.AttributeName", equalTo("email"));+ }+}