fix(cognito): align sign-up confirmation with AWS behavior (#1488)

* fix(cognito): align sign-up confirmation with AWS behavior

* fix(cognito): centralize constructor initialization

* fix(cognito): use issued sign-up confirmation code in node compatibility test

* fix(cognito): align signup confirmation tests with issued codes
This commit is contained in:
shrimptails-f authored and GitHub committed 2026-06-24 22:35:57 -05:00
1 parent 03f1e44e27
commit 5e6bcca401
6 files changed
+440 -40

No files matched your search

@@ -20,6 +20,8 @@ import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.RSAPublicKeySpec;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Base64;
import java.util.List;
import java.util.Spliterators;
@@ -40,6 +42,7 @@ class CognitoIntegrationTest {
private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b");
private static String poolId;
private static String clientId;
@@ -291,6 +294,126 @@ class CognitoIntegrationTest {
@Test
@Order(7)
void confirmSignUpRequiresValidConfirmationCode() throws Exception {
given().delete("/_aws/ses").then().statusCode(200);
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
"PoolName": "ConfirmSignUpCodePool",
"AutoVerifiedAttributes": ["email"]
}
""");
String signUpPoolId = poolResponse.path("UserPool").path("Id").asText();
JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """
{
"UserPoolId": "%s",
"ClientName": "confirm-sign-up-client"
}
""".formatted(signUpPoolId));
String signUpClientId = clientResponse.path("UserPoolClient").path("ClientId").asText();
String signUpUsername = "signup+" + UUID.randomUUID() + "@example.com";
cognitoAction("SignUp", """
{
"ClientId": "%s",
"Username": "%s",
"Password": "Passw0rd!",
"UserAttributes": [
{ "Name": "email", "Value": "%s" }
]
}
""".formatted(signUpClientId, signUpUsername, signUpUsername))
.then()
.statusCode(200);
JsonNode unconfirmedUser = cognitoJson("AdminGetUser", """
{
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(signUpPoolId, signUpUsername));
assertEquals("UNCONFIRMED", unconfirmedUser.path("UserStatus").asText());
cognitoAction("ConfirmSignUp", """
{
"ClientId": "%s",
"Username": "%s",
"ConfirmationCode": "000000"
}
""".formatted(signUpClientId, signUpUsername))
.then()
.statusCode(400)
.body("__type", org.hamcrest.Matchers.equalTo("CodeMismatchException"))
.body("message", org.hamcrest.Matchers.equalTo("Invalid verification code provided, please try again."));
JsonNode stillUnconfirmedUser = cognitoJson("AdminGetUser", """
{
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(signUpPoolId, signUpUsername));
assertEquals("UNCONFIRMED", stillUnconfirmedUser.path("UserStatus").asText());
}
@Test
@Order(8)
void confirmSignUpAcceptsIssuedConfirmationCode() throws Exception {
given().delete("/_aws/ses").then().statusCode(200);
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
"PoolName": "ConfirmSignUpSuccessPool",
"AutoVerifiedAttributes": ["email"]
}
""");
String signUpPoolId = poolResponse.path("UserPool").path("Id").asText();
JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """
{
"UserPoolId": "%s",
"ClientName": "confirm-sign-up-success-client"
}
""".formatted(signUpPoolId));
String signUpClientId = clientResponse.path("UserPoolClient").path("ClientId").asText();
String signUpUsername = "signup+" + UUID.randomUUID() + "@example.com";
cognitoAction("SignUp", """
{
"ClientId": "%s",
"Username": "%s",
"Password": "Passw0rd!",
"UserAttributes": [
{ "Name": "email", "Value": "%s" }
]
}
""".formatted(signUpClientId, signUpUsername, signUpUsername))
.then()
.statusCode(200);
String confirmationCode = fetchLatestSesVerificationCode(signUpUsername);
cognitoAction("ConfirmSignUp", """
{
"ClientId": "%s",
"Username": "%s",
"ConfirmationCode": "%s"
}
""".formatted(signUpClientId, signUpUsername, confirmationCode))
.then()
.statusCode(200);
JsonNode confirmedUser = cognitoJson("AdminGetUser", """
{
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(signUpPoolId, signUpUsername));
assertEquals("CONFIRMED", confirmedUser.path("UserStatus").asText());
}
@Test
@Order(8)
void forgotPasswordRequiresVerifiedRecoveryDestination() throws Exception {
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
@@ -1354,15 +1477,33 @@ class CognitoIntegrationTest {
@Test
@Order(91)
void adminConfirmSignUp() throws Exception {
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
"PoolName": "AdminConfirmSignUpPool"
}
""");
String localPoolId = poolResponse.path("UserPool").path("Id").asText();
JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """
{
"UserPoolId": "%s",
"ClientName": "admin-confirm-sign-up-client"
}
""".formatted(localPoolId));
String localClientId = clientResponse.path("UserPoolClient").path("ClientId").asText();
String testUser = "unconfirmed+" + UUID.randomUUID() + "@example.com";
// SignUp user - initially UNCONFIRMED
cognitoJson("SignUp", """
{
"ClientId": "%s",
"Username": "%s",
"Password": "%s"
"Password": "%s",
"UserAttributes": [
{ "Name": "email", "Value": "%s" }
]
}
""".formatted(clientId, testUser, password));
""".formatted(localClientId, testUser, password, testUser));
// Get user details to verify user status is UNCONFIRMED
JsonNode userResp = cognitoJson("AdminGetUser", """
@@ -1370,7 +1511,7 @@ class CognitoIntegrationTest {
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(poolId, testUser));
""".formatted(localPoolId, testUser));
assertEquals("UNCONFIRMED", userResp.path("UserStatus").asText());
// Admin confirms user
@@ -1379,7 +1520,7 @@ class CognitoIntegrationTest {
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(poolId, testUser))
""".formatted(localPoolId, testUser))
.then()
.statusCode(200);
@@ -1389,7 +1530,7 @@ class CognitoIntegrationTest {
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(poolId, testUser));
""".formatted(localPoolId, testUser));
assertEquals("CONFIRMED", userRespConfirmed.path("UserStatus").asText());
}
@@ -2072,6 +2213,22 @@ class CognitoIntegrationTest {
return auth.path("AuthenticationResult").path("AccessToken").asText();
}
private static String fetchLatestSesVerificationCode(String recipient) throws Exception {
String response = given()
.queryParam("email", recipient)
.when()
.get("/_aws/ses")
.then()
.statusCode(200)
.extract()
.asString();
JsonNode payload = OBJECT_MAPPER.readTree(response);
String body = payload.path("messages").get(0).path("Body").path("text_part").asText();
Matcher matcher = SIX_DIGIT_CODE.matcher(body);
assertTrue(matcher.find(), "verification code email should contain a 6-digit code");
return matcher.group(1);
}
private static String padBase64(String value) {
int remainder = value.length() % 4;
if (remainder == 0) {
@@ -8,6 +8,9 @@ import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -20,6 +23,12 @@ import java.util.Map;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class CognitoServiceTest {
@@ -1048,6 +1057,96 @@ class CognitoServiceTest {
assertFalse(user.getAttributes().get("sub").isBlank());
}
@Test
void signUpWithoutDeliveryTargetFailsBeforePersistingUser() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
verificationCodeService,
messageDispatcher
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
pool.setAutoVerifiedAttributes(List.of("email"));
UserPoolClient client = serviceWithVerification.createUserPoolClient(pool.getId(), "test-client",
false, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class, () ->
serviceWithVerification.signUp(client.getClientId(), "carol", "Pass1234!", Map.of()));
assertEquals("InvalidParameterException", ex.getErrorCode());
AwsException lookupEx = assertThrows(AwsException.class, () ->
serviceWithVerification.adminGetUser(pool.getId(), "carol"));
assertEquals("UserNotFoundException", lookupEx.getErrorCode());
}
@Test
void signUpRollsBackUserWhenDispatchFails() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any()))
.thenReturn("123456");
doThrow(new RuntimeException("SES unavailable")).when(messageDispatcher)
.dispatch(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), eq("123456"), any());
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
verificationCodeService,
messageDispatcher
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
pool.setAutoVerifiedAttributes(List.of("email"));
UserPoolClient client = serviceWithVerification.createUserPoolClient(pool.getId(), "test-client",
false, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class, () ->
serviceWithVerification.signUp(client.getClientId(), "carol", "Pass1234!",
Map.of("email", "carol@example.com")));
assertEquals("CodeDeliveryFailureException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertEquals("Failed to deliver the message.", ex.getMessage());
AwsException lookupEx = assertThrows(AwsException.class, () ->
serviceWithVerification.adminGetUser(pool.getId(), "carol"));
assertEquals("UserNotFoundException", lookupEx.getErrorCode());
verify(verificationCodeService).invalidatePrevious(pool.getId(), "carol",
VerificationCode.Purpose.SIGNUP_CONFIRMATION);
}
@Test
void signUpReturnsResourceNotFoundAsBadRequestWhenClientMissing() {
AwsException ex = assertThrows(AwsException.class, () ->
service.signUp("missing-client", "carol", "Pass1234!", Map.of("email", "carol@example.com")));
assertEquals("ResourceNotFoundException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void confirmSignUpReturnsResourceNotFoundAsBadRequestWhenClientMissing() {
AwsException ex = assertThrows(AwsException.class, () ->
service.confirmSignUp("missing-client", "carol", "123456"));
assertEquals("ResourceNotFoundException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
@SuppressWarnings("unchecked")
void jwtSubMatchesStoredSubAttribute() {