mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cognito): add GetUserAttributeVerificationCode support (#1898)
* feat(cognito): issue attribute verification codes in CognitoService * feat(cognito): dispatch GetUserAttributeVerificationCode in CognitoJsonHandler * test(cognito): add GetUserAttributeVerificationCode happy path * test(cognito): cover invalid token and unverifiable attribute errors * docs(cognito): document GetUserAttributeVerificationCode * fix(cognito): key attribute verification codes per attribute * fix(cognito): match AWS error messages for GetUserAttributeVerificationCode Real Cognito returns "Invalid Access Token", "Invalid attribute name. Only phone_number and email can be verified.", and attribute-specific "User does not have a valid registered email address" / "...phone number" messages, per AWS-parity comparison in PR #1898 review. * fix(cognito): match AWS destination masking format for verification codes Real Cognito masks as "z***@b***" for email (first char of local part and domain, three asterisks, no TLD retained) and "+********8920" for phone (leading "+", asterisks, last four digits kept), per AWS-parity comparison in PR #1898 review. Applies to both attribute-verification and forgot-password/account-recovery delivery masking, which share these helpers. * test(cognito): assert exact AWS-parity error messages and mask format Tighten GetUserAttributeVerificationCode assertions from loose containsString checks to the exact wording and masking AWS returns, so a regression in either silently drifting from AWS again is caught. * test(cognito): cover re-issuing verification code for a verified attribute AWS permits requesting a fresh GetUserAttributeVerificationCode code for an attribute that is already verified, as long as its value has not changed. Nothing in the current issuance path checks the *_verified flag, so this locks in that AWS-parity behavior. * style(cognito): drop redundant comment in attribute verification test The method name already conveys the AWS behavior being tested, per AGENTS.md's guidance to prefer self-explanatory code over comments.
This commit is contained in:
1 parent
25b46e28ad
commit
24cdabb257
5 files changed
+339
-19
No files matched your search
@@ -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. |
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -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;
|
||||
|
||||
+4
-1
@@ -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;
|
||||
|
||||
+264
@@ -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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user