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:
Daniel ZwickerandPriamo Germosen authored and GitHub committed 2026-09-14 11:05:25 -04:00
1 parent 166b13a82f
commit 36c3ee4e22
8 files changed
+689 -61

No files matched your search

@@ -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() {
@@ -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",