mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cognito): implement VerifyUserAttribute (#2018)
* feat(cognito): implement VerifyUserAttribute * fix(cognito): align attribute verification with AWS * fix(cognito): require access-token scope on VerifyUserAttribute verifyUserAttribute() extracted username/pool/jti from the caller's token but never checked token_use or scope, so a valid ID token could reach the same code-consuming, attribute-mutating path as an access token. AWS requires an access token carrying the aws.cognito.signin.user.admin scope for this operation (API_VerifyUserAttribute.html). Adds a token_use check (unconditional) and a scope check that only rejects a token when it explicitly carries a scope list missing the required scope. Most access tokens this simulator issues carry no scope claim at all (scopes are only modeled through the V2 Pre-Token-Generation Lambda override), so treating an absent claim as unrestricted keeps every normal login flow working, while an access token with an explicit, non-conforming scope list is now rejected. Adds unit coverage for all three cases (ID token rejected, access token missing the scope rejected, access token with the scope accepted) plus a wire-level regression for the ID-token case. * fix(cognito): scope consumed-code tombstone to attribute verification VerificationCodeService.consume() retained a consumed-code tombstone for every purpose, so a reused code answers ExpiredCodeException instead of the original CodeMismatchException. That behavior was validated against a real Cognito pool for VerifyUserAttribute, but the service is shared with ConfirmSignUp (SIGNUP_CONFIRMATION) and ConfirmForgotPassword (PASSWORD_RESET), so the same change silently altered their reused-code error too, without the same validation. Scopes the tombstone to EMAIL_ATTRIBUTE_VERIFICATION and PHONE_ATTRIBUTE_VERIFICATION only. SIGNUP_CONFIRMATION and PASSWORD_RESET go back to deleting on consume, restoring their original, previously validated NOT_FOUND/CodeMismatchException behavior on reuse. --------- Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
1 parent
166b13a82f
commit
36c3ee4e22
8 files changed
+689
-61
No files matched your search
+239
@@ -0,0 +1,239 @@
|
||||
package com.floci.test;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.CodeMismatchException;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ExpiredCodeException;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType;
|
||||
import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class CognitoVerifyUserAttributeTest {
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final HttpClient HTTP = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(10))
|
||||
.build();
|
||||
private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b");
|
||||
private static final String PASSWORD = "Verify1234!";
|
||||
|
||||
private static CognitoIdentityProviderClient cognito;
|
||||
|
||||
private String poolId;
|
||||
|
||||
@BeforeAll
|
||||
static void setUpClient() {
|
||||
cognito = TestFixtures.cognitoClient();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void closeClient() {
|
||||
if (cognito != null) {
|
||||
cognito.close();
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deletePool() {
|
||||
if (poolId != null) {
|
||||
cognito.deleteUserPool(b -> b.userPoolId(poolId));
|
||||
poolId = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifiesEmailAndPhoneNumberWithAwsSdk() throws Exception {
|
||||
poolId = cognito.createUserPool(b -> b.poolName("verify-attribute-" + UUID.randomUUID()))
|
||||
.userPool()
|
||||
.id();
|
||||
String clientId = cognito.createUserPoolClient(b -> b
|
||||
.userPoolId(poolId)
|
||||
.clientName("verify-attribute-client")
|
||||
.explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH))
|
||||
.userPoolClient()
|
||||
.clientId();
|
||||
|
||||
String username = "verify-" + UUID.randomUUID();
|
||||
String email = username + "@example.com";
|
||||
String phoneNumber = "+1555" + ThreadLocalRandom.current().nextLong(1_000_000, 10_000_000);
|
||||
|
||||
cognito.adminCreateUser(b -> b
|
||||
.userPoolId(poolId)
|
||||
.username(username)
|
||||
.messageAction(MessageActionType.SUPPRESS)
|
||||
.userAttributes(
|
||||
AttributeType.builder().name("email").value(email).build(),
|
||||
AttributeType.builder().name("phone_number").value(phoneNumber).build()));
|
||||
cognito.adminSetUserPassword(b -> b
|
||||
.userPoolId(poolId)
|
||||
.username(username)
|
||||
.password(PASSWORD)
|
||||
.permanent(true));
|
||||
|
||||
String accessToken = cognito.initiateAuth(b -> b
|
||||
.clientId(clientId)
|
||||
.authFlow(AuthFlowType.USER_PASSWORD_AUTH)
|
||||
.authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD)))
|
||||
.authenticationResult()
|
||||
.accessToken();
|
||||
|
||||
clearInspectionEndpoint("/_aws/ses");
|
||||
clearInspectionEndpoint("/_aws/sns");
|
||||
|
||||
var emailDelivery = cognito.getUserAttributeVerificationCode(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("email"))
|
||||
.codeDeliveryDetails();
|
||||
assertThat(emailDelivery.attributeName()).isEqualTo("email");
|
||||
assertThat(emailDelivery.deliveryMediumAsString()).isEqualTo("EMAIL");
|
||||
assertThat(emailDelivery.destination()).isEqualTo("v***@e***");
|
||||
String emailCode = fetchLatestSesVerificationCode(email);
|
||||
|
||||
var phoneDelivery = cognito.getUserAttributeVerificationCode(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("phone_number"))
|
||||
.codeDeliveryDetails();
|
||||
assertThat(phoneDelivery.attributeName()).isEqualTo("phone_number");
|
||||
assertThat(phoneDelivery.deliveryMediumAsString()).isEqualTo("SMS");
|
||||
assertThat(phoneDelivery.destination()).isEqualTo(maskedPhoneNumber(phoneNumber));
|
||||
String phoneCode = fetchLatestSnsVerificationCode(phoneNumber);
|
||||
|
||||
assertThatThrownBy(() -> cognito.verifyUserAttribute(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("email")
|
||||
.code(differentCode(emailCode))))
|
||||
.isInstanceOf(CodeMismatchException.class);
|
||||
assertThat(userAttribute(username, "email_verified")).isNull();
|
||||
|
||||
cognito.verifyUserAttribute(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("email")
|
||||
.code(emailCode));
|
||||
cognito.verifyUserAttribute(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("phone_number")
|
||||
.code(phoneCode));
|
||||
|
||||
assertThat(userAttribute(username, "email_verified")).isEqualTo("true");
|
||||
assertThat(userAttribute(username, "phone_number_verified")).isEqualTo("true");
|
||||
|
||||
assertThatThrownBy(() -> cognito.verifyUserAttribute(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("email")
|
||||
.code(emailCode)))
|
||||
.isInstanceOfSatisfying(ExpiredCodeException.class,
|
||||
exception -> assertThat(exception.awsErrorDetails().errorMessage())
|
||||
.isEqualTo("Invalid code provided, please request a code again."));
|
||||
|
||||
clearInspectionEndpoint("/_aws/ses");
|
||||
clearInspectionEndpoint("/_aws/sns");
|
||||
|
||||
cognito.getUserAttributeVerificationCode(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("email"));
|
||||
String repeatedEmailCode = fetchLatestSesVerificationCode(email);
|
||||
|
||||
cognito.getUserAttributeVerificationCode(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("phone_number"));
|
||||
String repeatedPhoneCode = fetchLatestSnsVerificationCode(phoneNumber);
|
||||
|
||||
cognito.verifyUserAttribute(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("email")
|
||||
.code(repeatedEmailCode));
|
||||
cognito.verifyUserAttribute(b -> b
|
||||
.accessToken(accessToken)
|
||||
.attributeName("phone_number")
|
||||
.code(repeatedPhoneCode));
|
||||
|
||||
assertThat(userAttribute(username, "email_verified")).isEqualTo("true");
|
||||
assertThat(userAttribute(username, "phone_number_verified")).isEqualTo("true");
|
||||
}
|
||||
|
||||
private String userAttribute(String username, String attributeName) {
|
||||
return cognito.adminGetUser(b -> b.userPoolId(poolId).username(username))
|
||||
.userAttributes()
|
||||
.stream()
|
||||
.filter(attribute -> attributeName.equals(attribute.name()))
|
||||
.map(AttributeType::value)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private static void clearInspectionEndpoint(String path) throws Exception {
|
||||
HttpResponse<String> response = HTTP.send(
|
||||
HttpRequest.newBuilder()
|
||||
.uri(TestFixtures.endpoint().resolve(path))
|
||||
.DELETE()
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
}
|
||||
|
||||
private static String fetchLatestSesVerificationCode(String recipient) throws Exception {
|
||||
URI uri = TestFixtures.endpoint()
|
||||
.resolve("/_aws/ses?email=" + URLEncoder.encode(recipient, StandardCharsets.UTF_8));
|
||||
JsonNode messages = getInspectionMessages(uri);
|
||||
return extractVerificationCode(messages.get(0).path("Body").path("text_part").asText());
|
||||
}
|
||||
|
||||
private static String fetchLatestSnsVerificationCode(String phoneNumber) throws Exception {
|
||||
URI uri = TestFixtures.endpoint()
|
||||
.resolve("/_aws/sns?phone=" + URLEncoder.encode(phoneNumber, StandardCharsets.UTF_8));
|
||||
JsonNode messages = getInspectionMessages(uri);
|
||||
return extractVerificationCode(messages.get(0).path("Message").asText());
|
||||
}
|
||||
|
||||
private static JsonNode getInspectionMessages(URI uri) throws Exception {
|
||||
HttpResponse<String> response = HTTP.send(
|
||||
HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.GET()
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertThat(response.statusCode()).isEqualTo(200);
|
||||
JsonNode messages = JSON.readTree(response.body()).path("messages");
|
||||
assertThat(messages.isArray() && !messages.isEmpty()).isTrue();
|
||||
return messages;
|
||||
}
|
||||
|
||||
private static String extractVerificationCode(String message) {
|
||||
Matcher matcher = SIX_DIGIT_CODE.matcher(message);
|
||||
assertThat(matcher.find()).isTrue();
|
||||
return matcher.group(1);
|
||||
}
|
||||
|
||||
private static String differentCode(String code) {
|
||||
return "000000".equals(code) ? "000001" : "000000";
|
||||
}
|
||||
|
||||
private static String maskedPhoneNumber(String phoneNumber) {
|
||||
return "+" + "*".repeat(phoneNumber.length() - 5)
|
||||
+ phoneNumber.substring(phoneNumber.length() - 4);
|
||||
}
|
||||
}
|
||||
@@ -172,6 +172,7 @@ further divergences, both deliberate:
|
||||
| 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. |
|
||||
| VerifyUserAttribute | Verifies an email or phone_number attribute with its issued verification code. |
|
||||
| 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. |
|
||||
|
||||
@@ -104,6 +104,7 @@ public class CognitoJsonHandler {
|
||||
case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request);
|
||||
case "GetUser" -> handleGetUser(request);
|
||||
case "GetUserAttributeVerificationCode" -> handleGetUserAttributeVerificationCode(request);
|
||||
case "VerifyUserAttribute" -> handleVerifyUserAttribute(request);
|
||||
case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);
|
||||
case "DeleteUserAttributes" -> handleDeleteUserAttributes(request);
|
||||
case "GlobalSignOut" -> handleGlobalSignOut(request);
|
||||
@@ -1018,6 +1019,15 @@ public class CognitoJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleVerifyUserAttribute(JsonNode request) {
|
||||
service.verifyUserAttribute(
|
||||
request.path("AccessToken").asText(),
|
||||
request.path("AttributeName").asText(),
|
||||
request.path("Code").asText()
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).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()));
|
||||
|
||||
@@ -2594,6 +2594,48 @@ public class CognitoService implements ResourceProvider {
|
||||
return response;
|
||||
}
|
||||
|
||||
public void verifyUserAttribute(String accessToken, String attributeName, String code) {
|
||||
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");
|
||||
String username = token.username();
|
||||
String poolId = token.poolId();
|
||||
|
||||
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);
|
||||
if (blankToNull(user.getAttributes().get(attributeName)) == null) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"Unable to verify attribute: " + attributeName + " no value set to verify",
|
||||
400);
|
||||
}
|
||||
|
||||
VerificationCode.Purpose purpose = "email".equals(attributeName)
|
||||
? VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION
|
||||
: VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
|
||||
ensureVerificationWiring();
|
||||
try {
|
||||
verificationCodeService.consume(poolId, user.getUsername(), purpose, code);
|
||||
} catch (VerificationCodeException e) {
|
||||
throw mapVerificationCodeException(e);
|
||||
}
|
||||
|
||||
user.getAttributes().put(attributeName + "_verified", "true");
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(poolId, user.getUsername()), user);
|
||||
}
|
||||
|
||||
public void updateUserAttributes(String accessToken, Map<String, String> attributes) {
|
||||
VerifiedAccessToken token = verifyAccessToken(accessToken);
|
||||
String username = token.username();
|
||||
@@ -3715,6 +3757,43 @@ 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.
|
||||
*/
|
||||
private Set<String> 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<String> scopes = new HashSet<>();
|
||||
for (String s : scope.split(" ")) {
|
||||
if (!s.isBlank()) scopes.add(s);
|
||||
}
|
||||
return scopes;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private void requireScope(String accessToken, String requiredScope) {
|
||||
Set<String> scopes = extractScopesFromToken(accessToken);
|
||||
if (scopes != null && !scopes.contains(requiredScope)) {
|
||||
throw new AwsException("NotAuthorizedException", "Access Token does not have the required scope", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a refresh token has not been revoked, including global user sign-out.
|
||||
* Called from CognitoAuthFlowHandler for the REFRESH_TOKEN_AUTH flow.
|
||||
|
||||
+24
-9
@@ -86,9 +86,15 @@ public final class VerificationCodeService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a code. On success, marks it consumed and removes it. On any
|
||||
* failure, throws {@link VerificationCodeException} with the specific
|
||||
* {@link VerificationCodeException.Kind}.
|
||||
* Validate a code. On success, marks it consumed. For the attribute-verification
|
||||
* purposes, retains the tombstone until it expires or a new code replaces it, so a
|
||||
* reused code answers {@code EXPIRED} rather than {@code NOT_FOUND}, validated against
|
||||
* a real Cognito pool for {@code VerifyUserAttribute} (see CognitoServiceTest /
|
||||
* CognitoAttributeVerificationIntegrationTest). {@link VerificationCode.Purpose#SIGNUP_CONFIRMATION}
|
||||
* and {@link VerificationCode.Purpose#PASSWORD_RESET} keep the original delete-on-consume
|
||||
* behavior instead, since that reuse case was never validated against real Cognito for
|
||||
* {@code ConfirmSignUp} or {@code ConfirmForgotPassword}. On any failure, throws
|
||||
* {@link VerificationCodeException} with the specific {@link VerificationCodeException.Kind}.
|
||||
*
|
||||
* <p>Note: not thread-safe under concurrent {@code consume()} of the same
|
||||
* (poolId, username, purpose) key — two racing wrong-code calls may
|
||||
@@ -101,17 +107,17 @@ public final class VerificationCodeService {
|
||||
VerificationCode vc = store.get(key).orElseThrow(() -> new VerificationCodeException(
|
||||
VerificationCodeException.Kind.NOT_FOUND,
|
||||
"Invalid verification code provided, please try again"));
|
||||
if (vc.isConsumed()) {
|
||||
throw new VerificationCodeException(
|
||||
VerificationCodeException.Kind.NOT_FOUND,
|
||||
"Invalid verification code provided, please try again");
|
||||
}
|
||||
if (vc.isExpired(clock.instant())) {
|
||||
store.delete(key);
|
||||
throw new VerificationCodeException(
|
||||
VerificationCodeException.Kind.EXPIRED,
|
||||
"Invalid code provided, please request a code again");
|
||||
}
|
||||
if (vc.isConsumed()) {
|
||||
throw new VerificationCodeException(
|
||||
VerificationCodeException.Kind.EXPIRED,
|
||||
"Invalid code provided, please request a code again");
|
||||
}
|
||||
if (vc.getAttemptsRemaining() <= 0) {
|
||||
store.delete(key);
|
||||
// AWS returns the generic invalid-code message here too, never the
|
||||
@@ -136,7 +142,16 @@ public final class VerificationCodeService {
|
||||
}
|
||||
|
||||
vc.markConsumed();
|
||||
store.delete(key);
|
||||
if (retainsConsumedTombstone(purpose)) {
|
||||
store.put(key, vc);
|
||||
} else {
|
||||
store.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean retainsConsumedTombstone(VerificationCode.Purpose purpose) {
|
||||
return purpose == VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION
|
||||
|| purpose == VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
|
||||
}
|
||||
|
||||
/** Remove any active code for the (pool, user, purpose). Idempotent. */
|
||||
|
||||
+205
-52
@@ -1,6 +1,7 @@
|
||||
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 org.junit.jupiter.api.BeforeAll;
|
||||
@@ -10,21 +11,31 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
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.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CognitoAttributeVerificationIntegrationTest {
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b");
|
||||
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;
|
||||
private static String idToken;
|
||||
private static String emailVerificationCode;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
@@ -83,11 +94,14 @@ class CognitoAttributeVerificationIntegrationTest {
|
||||
}
|
||||
""".formatted(clientId, USERNAME, PASSWORD));
|
||||
accessToken = auth.path("AuthenticationResult").path("AccessToken").asText();
|
||||
idToken = auth.path("AuthenticationResult").path("IdToken").asText();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void issuesEmailVerificationCode() {
|
||||
void issuesEmailVerificationCode() throws Exception {
|
||||
clearInspectionEndpoint("/_aws/ses");
|
||||
|
||||
cognitoAction("GetUserAttributeVerificationCode", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
@@ -99,10 +113,62 @@ class CognitoAttributeVerificationIntegrationTest {
|
||||
.body("CodeDeliveryDetails.AttributeName", equalTo("email"))
|
||||
.body("CodeDeliveryDetails.DeliveryMedium", equalTo("EMAIL"))
|
||||
.body("CodeDeliveryDetails.Destination", equalTo("v***@e***"));
|
||||
|
||||
emailVerificationCode = fetchLatestSesVerificationCode(USERNAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void rejectsWrongVerificationCodeWithoutUpdatingAttribute() throws Exception {
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
"AttributeName": "email",
|
||||
"Code": "%s"
|
||||
}
|
||||
""".formatted(accessToken, differentCode(emailVerificationCode)))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("CodeMismatchException"));
|
||||
|
||||
assertNull(userAttribute(USERNAME, "email_verified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void verifiesEmailAttribute() throws Exception {
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
"AttributeName": "email",
|
||||
"Code": "%s"
|
||||
}
|
||||
""".formatted(accessToken, emailVerificationCode))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(equalTo("{}"));
|
||||
|
||||
assertEquals("true", userAttribute(USERNAME, "email_verified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void rejectsConsumedVerificationCode() {
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
"AttributeName": "email",
|
||||
"Code": "%s"
|
||||
}
|
||||
""".formatted(accessToken, emailVerificationCode))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ExpiredCodeException"))
|
||||
.body("message", equalTo("Invalid code provided, please request a code again."));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void rejectsInvalidAccessToken() {
|
||||
cognitoAction("GetUserAttributeVerificationCode", """
|
||||
{
|
||||
@@ -117,7 +183,7 @@ class CognitoAttributeVerificationIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
@Order(7)
|
||||
void rejectsUnverifiableAttribute() {
|
||||
cognitoAction("GetUserAttributeVerificationCode", """
|
||||
{
|
||||
@@ -128,11 +194,12 @@ class CognitoAttributeVerificationIntegrationTest {
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"))
|
||||
.body("message", equalTo("Invalid attribute name. Only phone_number and email can be verified."));
|
||||
.body("message", equalTo(
|
||||
"Invalid attribute name. Only phone_number and email can be verified."));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
@Order(8)
|
||||
void rejectsAttributeWithoutValue() {
|
||||
cognitoAction("GetUserAttributeVerificationCode", """
|
||||
{
|
||||
@@ -147,19 +214,20 @@ class CognitoAttributeVerificationIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
@Order(9)
|
||||
void emailAndPhoneCodesAreIndependent() throws Exception {
|
||||
String username = "verify-both+" + UUID.randomUUID() + "@example.com";
|
||||
String phoneNumber = "+15551234567";
|
||||
cognitoAction("AdminCreateUser", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"UserAttributes": [
|
||||
{ "Name": "email", "Value": "%s" },
|
||||
{ "Name": "phone_number", "Value": "+15551234567" }
|
||||
{ "Name": "phone_number", "Value": "%s" }
|
||||
]
|
||||
}
|
||||
""".formatted(poolId, username, username))
|
||||
""".formatted(poolId, username, username, phoneNumber))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
@@ -186,8 +254,9 @@ class CognitoAttributeVerificationIntegrationTest {
|
||||
""".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.
|
||||
clearInspectionEndpoint("/_aws/ses");
|
||||
clearInspectionEndpoint("/_aws/sns");
|
||||
|
||||
cognitoAction("GetUserAttributeVerificationCode", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
@@ -197,6 +266,7 @@ class CognitoAttributeVerificationIntegrationTest {
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CodeDeliveryDetails.DeliveryMedium", equalTo("EMAIL"));
|
||||
String emailCode = fetchLatestSesVerificationCode(username);
|
||||
|
||||
cognitoAction("GetUserAttributeVerificationCode", """
|
||||
{
|
||||
@@ -209,56 +279,139 @@ class CognitoAttributeVerificationIntegrationTest {
|
||||
.body("CodeDeliveryDetails.AttributeName", equalTo("phone_number"))
|
||||
.body("CodeDeliveryDetails.DeliveryMedium", equalTo("SMS"))
|
||||
.body("CodeDeliveryDetails.Destination", equalTo("+*******4567"));
|
||||
String phoneCode = fetchLatestSnsVerificationCode(phoneNumber);
|
||||
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
"AttributeName": "phone_number",
|
||||
"Code": "%s"
|
||||
}
|
||||
""".formatted(token, phoneCode))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
"AttributeName": "email",
|
||||
"Code": "%s"
|
||||
}
|
||||
""".formatted(token, emailCode))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
assertEquals("true", userAttribute(username, "email_verified"));
|
||||
assertEquals("true", userAttribute(username, "phone_number_verified"));
|
||||
}
|
||||
|
||||
@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", """
|
||||
@Order(10)
|
||||
void rejectsUnverifiableAttributeDuringVerification() {
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
"AttributeName": "email"
|
||||
"AttributeName": "given_name",
|
||||
"Code": "123456"
|
||||
}
|
||||
""".formatted(token))
|
||||
""".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(11)
|
||||
void rejectsVerificationForAttributeWithoutValue() {
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
"AttributeName": "phone_number",
|
||||
"Code": "123456"
|
||||
}
|
||||
""".formatted(accessToken))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"))
|
||||
.body("message", equalTo(
|
||||
"Unable to verify attribute: phone_number no value set to verify"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void rejectsIdTokenForVerification() {
|
||||
// VerifyUserAttribute must be authorized with an access token, not an ID token,
|
||||
// even though both carry the same username/pool claims this simulator reads.
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{
|
||||
"AccessToken": "%s",
|
||||
"AttributeName": "email",
|
||||
"Code": "123456"
|
||||
}
|
||||
""".formatted(idToken))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Invalid Access Token"));
|
||||
}
|
||||
|
||||
private static void clearInspectionEndpoint(String path) {
|
||||
given()
|
||||
.delete(path)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static String fetchLatestSesVerificationCode(String recipient) throws Exception {
|
||||
String response = given()
|
||||
.queryParam("email", recipient)
|
||||
.get("/_aws/ses")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CodeDeliveryDetails.AttributeName", equalTo("email"));
|
||||
.extract()
|
||||
.asString();
|
||||
JsonNode messages = JSON.readTree(response).path("messages");
|
||||
assertTrue(messages.isArray() && !messages.isEmpty());
|
||||
return extractVerificationCode(messages.get(0).path("Body").path("text_part").asText());
|
||||
}
|
||||
|
||||
private static String fetchLatestSnsVerificationCode(String phoneNumber) throws Exception {
|
||||
String response = given()
|
||||
.queryParam("phone", phoneNumber)
|
||||
.get("/_aws/sns")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.asString();
|
||||
JsonNode messages = JSON.readTree(response).path("messages");
|
||||
assertTrue(messages.isArray() && !messages.isEmpty());
|
||||
return extractVerificationCode(messages.get(0).path("Message").asText());
|
||||
}
|
||||
|
||||
private static String extractVerificationCode(String message) {
|
||||
Matcher matcher = SIX_DIGIT_CODE.matcher(message);
|
||||
assertTrue(matcher.find());
|
||||
return matcher.group(1);
|
||||
}
|
||||
|
||||
private static String differentCode(String code) {
|
||||
return "000000".equals(code) ? "000001" : "000000";
|
||||
}
|
||||
|
||||
private static String userAttribute(String username, String attributeName) throws Exception {
|
||||
JsonNode user = cognitoJson("AdminGetUser", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s"
|
||||
}
|
||||
""".formatted(poolId, username));
|
||||
for (JsonNode attribute : user.path("UserAttributes")) {
|
||||
if (attributeName.equals(attribute.path("Name").asText())) {
|
||||
return attribute.path("Value").asText();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2983,6 +2983,86 @@ class CognitoServiceTest {
|
||||
}
|
||||
}
|
||||
|
||||
// KenkoGeek review, PR #2018: VerifyUserAttribute must require an access token (not an
|
||||
// ID token) carrying the aws.cognito.signin.user.admin scope.
|
||||
@Nested
|
||||
class VerifyUserAttributeAuthorization {
|
||||
|
||||
private CognitoService svc;
|
||||
private VerificationCodeService verificationCodeService;
|
||||
private UserPool pool;
|
||||
private UserPoolClient client;
|
||||
private CognitoUser user;
|
||||
|
||||
@BeforeEach
|
||||
void setUpVerification() {
|
||||
verificationCodeService = mock(VerificationCodeService.class);
|
||||
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
|
||||
svc = new CognitoService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
"http://localhost:4566",
|
||||
regionResolver,
|
||||
null,
|
||||
acmService,
|
||||
verificationCodeService,
|
||||
messageDispatcher,
|
||||
mock(TlsCertificateManager.class)
|
||||
);
|
||||
pool = svc.createUserPool(Map.of("PoolName", "ScopeTestPool"), "us-east-1");
|
||||
client = svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
svc.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "TempPass1!");
|
||||
svc.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
|
||||
user = svc.adminGetUser(pool.getId(), "alice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsIdTokenEvenThoughItSharesTheSameClaims() {
|
||||
// ID tokens never carry a scope claim (matching real Cognito), so this must be
|
||||
// rejected on token_use alone, before the scope check ever runs.
|
||||
String idToken = svc.generateSignedJwt(user, pool, "id", client, null);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> svc.verifyUserAttribute(idToken, "email", "123456"));
|
||||
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
verify(verificationCodeService, never()).consume(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAccessTokenMissingTheRequiredScope() {
|
||||
// Access tokens carry aws.cognito.signin.user.admin by default (generateSignedJwt),
|
||||
// so building one that lacks it means explicitly suppressing the default and
|
||||
// substituting something else, the way a Pre-Token-Generation V2 Lambda trigger would.
|
||||
String accessToken = svc.generateSignedJwt(user, pool, "access", client,
|
||||
new CognitoService.ClaimsOverride(null, null, null, null,
|
||||
List.of("openid"), List.of("aws.cognito.signin.user.admin"),
|
||||
null, null, null));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> svc.verifyUserAttribute(accessToken, "email", "123456"));
|
||||
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
verify(verificationCodeService, never()).consume(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsDefaultAccessTokenSinceItAlreadyCarriesTheRequiredScope() {
|
||||
String accessToken = svc.generateSignedJwt(user, pool, "access", client, null);
|
||||
|
||||
svc.verifyUserAttribute(accessToken, "email", "123456");
|
||||
|
||||
verify(verificationCodeService).consume(pool.getId(), user.getUsername(),
|
||||
VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, "123456");
|
||||
}
|
||||
}
|
||||
|
||||
// ──────── UsernameAttributes=email: immutable UUID username + mutable email alias ────────
|
||||
|
||||
private UserPool createEmailAliasPool() {
|
||||
|
||||
+51
@@ -50,6 +50,57 @@ class VerificationCodeServiceTest {
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, code));
|
||||
}
|
||||
|
||||
@Test
|
||||
void consume_consumedAttributeVerificationCode_throwsExpired() {
|
||||
String code = service.issue("pool", "alice",
|
||||
VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, Duration.ofHours(24));
|
||||
service.consume("pool", "alice",
|
||||
VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, code);
|
||||
|
||||
VerificationCodeException ex = assertThrows(VerificationCodeException.class,
|
||||
() -> service.consume("pool", "alice",
|
||||
VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, code));
|
||||
|
||||
assertEquals(VerificationCodeException.Kind.EXPIRED, ex.getKind());
|
||||
}
|
||||
|
||||
@Test
|
||||
void consume_consumedSignupOrResetCode_throwsNotFound() {
|
||||
// Unlike the attribute-verification purposes, SIGNUP_CONFIRMATION and
|
||||
// PASSWORD_RESET delete on consume rather than retaining a tombstone: that
|
||||
// reuse behavior was never validated against real Cognito for ConfirmSignUp
|
||||
// or ConfirmForgotPassword, so it stays exactly as it was before this change.
|
||||
String signupCode = service.issue("pool", "alice",
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
|
||||
service.consume("pool", "alice",
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, signupCode);
|
||||
VerificationCodeException signupEx = assertThrows(VerificationCodeException.class,
|
||||
() -> service.consume("pool", "alice",
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, signupCode));
|
||||
assertEquals(VerificationCodeException.Kind.NOT_FOUND, signupEx.getKind());
|
||||
|
||||
String resetCode = service.issue("pool", "bob",
|
||||
VerificationCode.Purpose.PASSWORD_RESET, Duration.ofHours(1));
|
||||
service.consume("pool", "bob",
|
||||
VerificationCode.Purpose.PASSWORD_RESET, resetCode);
|
||||
VerificationCodeException resetEx = assertThrows(VerificationCodeException.class,
|
||||
() -> service.consume("pool", "bob",
|
||||
VerificationCode.Purpose.PASSWORD_RESET, resetCode));
|
||||
assertEquals(VerificationCodeException.Kind.NOT_FOUND, resetEx.getKind());
|
||||
}
|
||||
|
||||
@Test
|
||||
void issue_afterConsumedCode_succeedsImmediately() {
|
||||
String code = service.issue("pool", "alice",
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
|
||||
service.consume("pool", "alice",
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, code);
|
||||
|
||||
assertDoesNotThrow(() ->
|
||||
service.issue("pool", "alice",
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void consume_wrongCode_throwsMismatch() {
|
||||
service.issue("pool", "alice",
|
||||
|
||||
Reference in new issue
Block a user