Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

shrimptails-f5e6bcca401f9
diff --git a/compatibility-tests/sdk-test-node/tests/cognito.test.ts b/compatibility-tests/sdk-test-node/tests/cognito.test.ts
index 891d55099b..f5ff589f38 100644
--- a/compatibility-tests/sdk-test-node/tests/cognito.test.ts
+++ b/compatibility-tests/sdk-test-node/tests/cognito.test.ts
@@ -23,7 +23,7 @@ import {
AdminRemoveUserFromGroupCommand,
AdminListGroupsForUserCommand,
} from '@aws-sdk/client-cognito-identity-provider';
-import { makeClient, uniqueName, ENDPOINT } from './setup';
+import { makeClient, uniqueName, ENDPOINT, fetchLatestSesVerificationCode } from './setup';
describe('Cognito', () => {
let cognito: CognitoIdentityProviderClient;
@@ -46,7 +46,10 @@ describe('Cognito', () => {
it('should create user pool', async () => {
const response = await cognito.send(
- new CreateUserPoolCommand({ PoolName: `test-pool-${uniqueName()}` })
+ new CreateUserPoolCommand({
+ PoolName: `test-pool-${uniqueName()}`,
+ AutoVerifiedAttributes: ['email'],
+ })
);
poolId = response.UserPool!.Id!;
expect(poolId).toBeTruthy();
@@ -111,19 +114,21 @@ describe('Cognito', () => {
});
it('should sign up and confirm user', async () => {
+ const email = '[email protected]';
await cognito.send(
new SignUpCommand({
ClientId: clientId,
Username: 'testuser2',
Password: 'Pass789!',
- UserAttributes: [{ Name: 'email', Value: '[email protected]' }],
+ UserAttributes: [{ Name: 'email', Value: email }],
})
);
+ const confirmationCode = await fetchLatestSesVerificationCode(email);
await cognito.send(
new ConfirmSignUpCommand({
ClientId: clientId,
Username: 'testuser2',
- ConfirmationCode: '123456',
+ ConfirmationCode: confirmationCode,
})
);
});
diff --git a/compatibility-tests/sdk-test-node/tests/setup.ts b/compatibility-tests/sdk-test-node/tests/setup.ts
index 74cb636a7e..d25a88585b 100644
--- a/compatibility-tests/sdk-test-node/tests/setup.ts
+++ b/compatibility-tests/sdk-test-node/tests/setup.ts
@@ -38,6 +38,31 @@ export function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
+const SIX_DIGIT_CODE = /\b(\d{6})\b/;
+
+export async function fetchLatestSesVerificationCode(recipient: string): Promise<string> {
+ const response = await fetch(
+ `${ENDPOINT}/_aws/ses?email=${encodeURIComponent(recipient)}`
+ );
+ if (!response.ok) {
+ throw new Error(`failed to fetch SES messages: ${response.status}`);
+ }
+
+ const payload = (await response.json()) as {
+ messages?: Array<{ Body?: { text_part?: string } }>;
+ };
+ const firstMessage = payload.messages?.[0];
+ const body =
+ firstMessage?.Body?.text_part ??
+ (firstMessage?.Body as { html_part?: string } | undefined)?.html_part ??
+ '';
+ const match = body.match(SIX_DIGIT_CODE);
+ if (!match) {
+ throw new Error('verification code email should contain a 6-digit code');
+ }
+ return match[1];
+}
+
// Build a minimal ZIP file for Lambda functions
export function buildMinimalZip(filename: string, content: Buffer): Buffer {
const filenameBytes = Buffer.from(filename);
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.java
index 75b1df3b54..789afd1cfe 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
@@ -526,17 +526,23 @@ public class CognitoJsonHandler {
ObjectNode response = objectMapper.createObjectNode();
response.put("UserConfirmed", "CONFIRMED".equals(user.getUserStatus()));
response.put("UserSub", user.getAttributes().get("sub"));
- ObjectNode delivery = response.putObject("CodeDeliveryDetails");
- delivery.put("AttributeName", "email");
- delivery.put("DeliveryMedium", "EMAIL");
- delivery.put("Destination", user.getAttributes().getOrDefault("email", "****"));
+ if (!"CONFIRMED".equals(user.getUserStatus())) {
+ Map<String, String> deliveryDetails = service.signUpCodeDeliveryDetails(user);
+ if (!deliveryDetails.isEmpty()) {
+ ObjectNode delivery = response.putObject("CodeDeliveryDetails");
+ delivery.put("AttributeName", deliveryDetails.get("AttributeName"));
+ delivery.put("DeliveryMedium", deliveryDetails.get("DeliveryMedium"));
+ delivery.put("Destination", deliveryDetails.get("Destination"));
+ }
+ }
return Response.ok(response).build();
}
private Response handleConfirmSignUp(JsonNode request) {
service.confirmSignUp(
request.path("ClientId").asText(),
- request.path("Username").asText()
+ request.path("Username").asText(),
+ request.path("ConfirmationCode").asText()
);
return Response.ok(objectMapper.createObjectNode()).build();
}
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.java
index 07c28ba803..cd48b5fc12 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
@@ -74,24 +74,25 @@ public class CognitoService {
public CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig,
RegionResolver regionResolver, LambdaService lambdaService, SesService sesService,
SnsService snsService, Clock clock) {
- this.poolStore = storageFactory.create("cognito", "cognito-pools.json",
- new TypeReference<Map<String, UserPool>>() {});
- this.clientStore = storageFactory.create("cognito", "cognito-clients.json",
- new TypeReference<Map<String, UserPoolClient>>() {});
- this.resourceServerStore = storageFactory.create("cognito", "cognito-resource-servers.json",
- new TypeReference<Map<String, ResourceServer>>() {});
- this.userStore = storageFactory.create("cognito", "cognito-users.json",
- new TypeReference<Map<String, CognitoUser>>() {});
- this.groupStore = storageFactory.create("cognito", "cognito-groups.json",
- new TypeReference<Map<String, CognitoGroup>>() {});
- this.revokedTokenStore = storageFactory.create("cognito", "cognito-revoked-tokens.json",
- new TypeReference<Map<String, RevokedTokenInfo>>() {});
- this.baseUrl = trimTrailingSlash(emulatorConfig.baseUrl());
- this.regionResolver = regionResolver;
- this.lambdaService = lambdaService;
- this.verificationCodeService = new VerificationCodeService(storageFactory, clock);
- this.messageDispatcher = new CognitoMessageDispatcher(sesService, snsService);
- this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver);
+ this(
+ storageFactory.create("cognito", "cognito-pools.json",
+ new TypeReference<Map<String, UserPool>>() {}),
+ storageFactory.create("cognito", "cognito-clients.json",
+ new TypeReference<Map<String, UserPoolClient>>() {}),
+ storageFactory.create("cognito", "cognito-resource-servers.json",
+ new TypeReference<Map<String, ResourceServer>>() {}),
+ storageFactory.create("cognito", "cognito-users.json",
+ new TypeReference<Map<String, CognitoUser>>() {}),
+ storageFactory.create("cognito", "cognito-groups.json",
+ new TypeReference<Map<String, CognitoGroup>>() {}),
+ storageFactory.create("cognito", "cognito-revoked-tokens.json",
+ new TypeReference<Map<String, RevokedTokenInfo>>() {}),
+ trimTrailingSlash(emulatorConfig.baseUrl()),
+ regionResolver,
+ lambdaService,
+ new VerificationCodeService(storageFactory, clock),
+ new CognitoMessageDispatcher(sesService, snsService)
+ );
}
CognitoService(StorageBackend<String, UserPool> poolStore,
@@ -103,6 +104,20 @@ public class CognitoService {
String baseUrl,
RegionResolver regionResolver,
LambdaService lambdaService) {
+ this(poolStore, clientStore, resourceServerStore, userStore, groupStore, revokedTokenStore, baseUrl,
+ regionResolver, lambdaService, null, null);
+ }
+
+ CognitoService(StorageBackend<String, UserPool> poolStore,
+ StorageBackend<String, UserPoolClient> clientStore,
+ StorageBackend<String, ResourceServer> resourceServerStore,
+ StorageBackend<String, CognitoUser> userStore,
+ StorageBackend<String, CognitoGroup> groupStore,
+ StorageBackend<String, RevokedTokenInfo> revokedTokenStore,
+ String baseUrl,
+ RegionResolver regionResolver, LambdaService lambdaService,
+ VerificationCodeService verificationCodeService,
+ CognitoMessageDispatcher messageDispatcher) {
this.poolStore = poolStore;
this.clientStore = clientStore;
this.resourceServerStore = resourceServerStore;
@@ -112,8 +127,8 @@ public class CognitoService {
this.baseUrl = baseUrl;
this.regionResolver = regionResolver;
this.lambdaService = lambdaService;
- this.verificationCodeService = null;
- this.messageDispatcher = null;
+ this.verificationCodeService = verificationCodeService;
+ this.messageDispatcher = messageDispatcher;
this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver);
}
@@ -1034,7 +1049,8 @@ public class CognitoService {
public CognitoUser signUp(String clientId, String username, String password, Map<String, String> attributes) {
UserPoolClient client = clientStore.get(clientId)
- .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found",
+ 400));
String userPoolId = client.getUserPoolId();
UserPool pool = describeUserPool(userPoolId);
@@ -1071,10 +1087,38 @@ public class CognitoService {
user.getAttributes().put("phone_number_verified", "true");
}
+ DeliveryTarget deliveryTarget = null;
+ boolean requiresConfirmationCode =
+ !preSignUp.autoConfirmUser() && verificationCodeService != null
+ && messageDispatcher != null && isSignUpConfirmationEnabled(pool);
+ if (requiresConfirmationCode) {
+ deliveryTarget = resolveSignUpDeliveryTarget(pool, user);
+ if (deliveryTarget == null) {
+ throw new AwsException("InvalidParameterException",
+ "Cannot confirm user because email or phone_number is missing", 400);
+ }
+ }
+
userStore.put(key, user);
LOG.infov("Signed up user {0} in pool {1} (status={2})",
username, userPoolId, user.getUserStatus());
+ if (requiresConfirmationCode) {
+ try {
+ String code = verificationCodeService.issue(pool.getId(), user.getUsername(),
+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
+ messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
+ code, List.of(deliveryTarget.deliveryMedium()));
+ } catch (VerificationCodeException e) {
+ rollbackSignUpConfirmationArtifacts(pool.getId(), user.getUsername(), key);
+ throw mapVerificationCodeException(e);
+ } catch (RuntimeException e) {
+ rollbackSignUpConfirmationArtifacts(pool.getId(), user.getUsername(), key);
+ throw new AwsException("CodeDeliveryFailureException",
+ "Failed to deliver the message.", 400);
+ }
+ }
+
// When PreSignUp auto-confirms, AWS Cognito also fires PostConfirmation.
// See: docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html
if (preSignUp.autoConfirmUser()) {
@@ -1084,18 +1128,45 @@ public class CognitoService {
}
public void confirmSignUp(String clientId, String username) {
+ confirmSignUp(clientId, username, null);
+ }
+
+ public void confirmSignUp(String clientId, String username, String confirmationCode) {
UserPoolClient client = clientStore.get(clientId)
- .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found",
+ 400));
+ UserPool pool = poolStore.get(client.getUserPoolId())
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",
+ "User pool not found", 400));
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
+ if (verificationCodeService != null && isSignUpConfirmationEnabled(pool)) {
+ try {
+ verificationCodeService.consume(client.getUserPoolId(), user.getUsername(),
+ VerificationCode.Purpose.SIGNUP_CONFIRMATION,
+ confirmationCode == null ? "" : confirmationCode);
+ } catch (VerificationCodeException e) {
+ throw mapVerificationCodeException(e);
+ }
+ }
user.setUserStatus("CONFIRMED");
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(client.getUserPoolId(), user.getUsername()), user);
-
- UserPool pool = poolStore.get(client.getUserPoolId())
- .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 404));
authFlowHandler.firePostConfirmation(pool, client, user, Map.of(), "PostConfirmation_ConfirmSignUp");
}
+ Map<String, String> signUpCodeDeliveryDetails(CognitoUser user) {
+ UserPool pool = describeUserPool(user.getUserPoolId());
+ if (!isSignUpConfirmationEnabled(pool)) {
+ return Map.of();
+ }
+ DeliveryTarget deliveryTarget = resolveSignUpDeliveryTarget(pool, user);
+ if (deliveryTarget == null) {
+ return Map.of();
+ }
+ return Map.of("AttributeName", deliveryTarget.attributeName(), "DeliveryMedium",
+ deliveryTarget.deliveryMedium(), "Destination", deliveryTarget.destination());
+ }
+
public void adminConfirmSignUp(String userPoolId, String username) {
CognitoUser user = adminGetUser(userPoolId, username);
user.setUserStatus("CONFIRMED");
@@ -2270,6 +2341,43 @@ public class CognitoService {
400);
}
+ private boolean isSignUpConfirmationEnabled(UserPool pool) {
+ return pool.getAutoVerifiedAttributes() != null
+ && !pool.getAutoVerifiedAttributes().isEmpty();
+ }
+
+ private DeliveryTarget resolveSignUpDeliveryTarget(UserPool pool, CognitoUser user) {
+ Map<String, String> attributes = user.getAttributes();
+ List<String> autoVerifiedAttributes =
+ pool.getAutoVerifiedAttributes() != null ? pool.getAutoVerifiedAttributes()
+ : List.of();
+ for (String attribute : autoVerifiedAttributes) {
+ if ("email".equals(attribute)) {
+ String email = blankToNull(attributes.get("email"));
+ if (email != null) {
+ return new DeliveryTarget("email", "EMAIL", maskEmail(email));
+ }
+ }
+ if ("phone_number".equals(attribute)) {
+ String phoneNumber = blankToNull(attributes.get("phone_number"));
+ if (phoneNumber != null) {
+ return new DeliveryTarget("phone_number", "SMS", maskPhoneNumber(phoneNumber));
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private void rollbackSignUpConfirmationArtifacts(String userPoolId, String username,
+ String userKey) {
+ userStore.delete(userKey);
+ if (verificationCodeService != null) {
+ verificationCodeService.invalidatePrevious(userPoolId, username,
+ VerificationCode.Purpose.SIGNUP_CONFIRMATION);
+ }
+ }
+
private AwsException mapVerificationCodeException(VerificationCodeException e) {
return switch (e.getKind()) {
case MISMATCH, NOT_FOUND -> new AwsException("CodeMismatchException",
@@ -2348,7 +2456,7 @@ public class CognitoService {
return value;
}
- private String trimTrailingSlash(String value) {
+ private static String trimTrailingSlash(String value) {
if (value.endsWith("/")) {
return value.substring(0, value.length() - 1);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
index c926d909b1..080f4711de 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java
@@ -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) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
index 3efcdcf353..c2d515ddc3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
@@ -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", "[email protected]")));
+ 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", "[email protected]")));
+ 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() {