Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): add verification code subsystem (store, dispatcher, SNS/SES inspection) (#1249)
Hector Venturad7f9f958732e
diff --git a/.gitignore b/.gitignoreindex ea3eabe25b..fc7348525f 100644--- a/.gitignore+++ b/.gitignore@@ -29,3 +29,5 @@ test-results.xml*.logtest-results++scripts/node_modules/diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.javanew file mode 100644index 0000000000..774c7897dd--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java@@ -0,0 +1,126 @@+package io.github.hectorvent.floci.services.cognito.verification;++import io.github.hectorvent.floci.services.cognito.model.CognitoUser;+import io.github.hectorvent.floci.services.cognito.model.UserPool;+import io.github.hectorvent.floci.services.ses.SesService;+import io.github.hectorvent.floci.services.sns.SnsService;++import java.util.List;+import java.util.Map;++/**+ * Routes a verification code through SES (email) or SNS (SMS) according to+ * {@link UserPool#getVerificationMessageTemplate()} and the requested delivery+ * mediums. Renders the {@code {####}} placeholder; appends a failsafe line if+ * the template lacks the placeholder.+ */+public final class CognitoMessageDispatcher {++ // Defaults match AWS Cognito's out-of-the-box verification messages (used only when the+ // user pool configures no VerificationMessageTemplate).+ private static final String DEFAULT_EMAIL_SUBJECT = "Your verification code";+ private static final String DEFAULT_EMAIL_BODY = "Your verification code is {####}.";+ private static final String DEFAULT_SMS_BODY = "Your verification code is {####}.";+ private static final String DEFAULT_FROM = "[email protected]";+ private static final String DEFAULT_REGION = "us-east-1";+ private static final String CODE_PLACEHOLDER = "{####}";++ private final SesService ses;+ private final SnsService sns;++ public CognitoMessageDispatcher(SesService ses, SnsService sns) {+ this.ses = ses;+ this.sns = sns;+ }++ public void dispatch(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,+ String code, List<String> deliveryMediums) {++ Map<String, Object> template = pool.getVerificationMessageTemplate();+ if (template == null) template = Map.of();+ String email = user.getAttributes().get("email");+ String phone = user.getAttributes().get("phone_number");++ List<String> mediums = resolveDeliveryMediums(deliveryMediums, email, phone);++ for (String medium : mediums) {+ if ("EMAIL".equalsIgnoreCase(medium) && email != null) {+ String subject = stringOr(template.get("EmailSubject"), DEFAULT_EMAIL_SUBJECT);+ String body = renderTemplate(stringOr(template.get(emailTemplateKey()), DEFAULT_EMAIL_BODY), code);+ ses.sendEmail(+ DEFAULT_FROM,+ List.of(email),+ List.of(), List.of(), List.of(),+ subject,+ body,+ null, // bodyHtml+ null, // configurationSetName+ List.of(), // emailTags+ List.of(), // additionalHeaders+ DEFAULT_REGION+ );+ } else if ("SMS".equalsIgnoreCase(medium) && phone != null) {+ String body = renderTemplate(stringOr(resolveSmsTemplate(pool, template, purpose), DEFAULT_SMS_BODY), code);+ sns.publish(+ null, null,+ phone,+ body,+ null,+ null,+ DEFAULT_REGION+ );+ }+ }+ }++ /**+ * Email template key. Returns the code-based {@code EmailMessage} ({@code {####}}).+ * TODO: honor the pool's {@code DefaultEmailOption}: when set to {@code CONFIRM_WITH_LINK},+ * AWS uses {@code EmailMessageByLink}/{@code EmailSubjectByLink} ({@code {##Verify Email##}})+ * instead of the code template. Code-only is sufficient for the current foundation scope.+ */+ private String emailTemplateKey() {+ return "EmailMessage";+ }++ /**+ * Resolves the raw SMS template from the correct AWS source for the purpose.+ * {@code SmsAuthenticationMessage} (MFA) is a top-level UserPool attribute, NOT part of+ * the VerificationMessageTemplate. For verification/signup codes, the template's+ * {@code SmsMessage} takes precedence over the legacy top-level SmsVerificationMessage.+ */+ private String resolveSmsTemplate(UserPool pool, Map<String, Object> template,+ VerificationCode.Purpose purpose) {+ if (purpose == VerificationCode.Purpose.SMS_MFA) {+ return pool.getSmsAuthenticationMessage();+ }+ Object sms = template.get("SmsMessage");+ if (sms != null && !sms.toString().isEmpty()) {+ return sms.toString();+ }+ return pool.getSmsVerificationMessage();+ }++ // TODO: when no medium is explicitly requested, the choice should come from the pool's+ // AutoVerifiedAttributes config. In AWS's "SMS if phone available, otherwise email" mode,+ // Cognito prefers the phone number when both contacts are present; this fallback prefers email.+ private List<String> resolveDeliveryMediums(List<String> requested, String email, String phone) {+ if (requested != null && !requested.isEmpty()) return requested;+ if (email != null) return List.of("EMAIL");+ if (phone != null) return List.of("SMS");+ return List.of();+ }++ private String stringOr(Object value, String fallback) {+ if (value == null) return fallback;+ String s = value.toString();+ return s.isEmpty() ? fallback : s;+ }++ private String renderTemplate(String template, String code) {+ if (template.contains(CODE_PLACEHOLDER)) {+ return template.replace(CODE_PLACEHOLDER, code);+ }+ return template + "\nCode: " + code;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCode.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCode.javanew file mode 100644index 0000000000..6353e3a9b0--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCode.java@@ -0,0 +1,82 @@+package io.github.hectorvent.floci.services.cognito.verification;++import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;++import java.time.Instant;++/**+ * Stored representation of a Cognito verification code (signup confirmation,+ * password reset, MFA SMS, attribute verification). The actual code is hashed+ * with a per-code salt so dumps and storage snapshots cannot reveal valid codes.+ */+public final class VerificationCode {++ public enum Purpose {+ SIGNUP_CONFIRMATION,+ PASSWORD_RESET,+ SMS_MFA,+ ATTRIBUTE_VERIFICATION+ }++ private final String userPoolId;+ private final String username;+ private final Purpose purpose;+ private final String codeHash;+ private final String salt;+ private final Instant issuedAt;+ private final Instant expiresAt;+ private int attemptsRemaining;+ private boolean consumed;++ @JsonCreator+ public VerificationCode(+ @JsonProperty("userPoolId") String userPoolId,+ @JsonProperty("username") String username,+ @JsonProperty("purpose") Purpose purpose,+ @JsonProperty("codeHash") String codeHash,+ @JsonProperty("salt") String salt,+ @JsonProperty("issuedAt") Instant issuedAt,+ @JsonProperty("expiresAt") Instant expiresAt,+ @JsonProperty("attemptsRemaining") int attemptsRemaining,+ @JsonProperty("consumed") boolean consumed) {+ this.userPoolId = userPoolId;+ this.username = username;+ this.purpose = purpose;+ this.codeHash = codeHash;+ this.salt = salt;+ this.issuedAt = issuedAt;+ this.expiresAt = expiresAt;+ this.attemptsRemaining = attemptsRemaining;+ this.consumed = consumed;+ }++ public VerificationCode(String userPoolId, String username, Purpose purpose,+ String codeHash, String salt, Instant issuedAt,+ Instant expiresAt, int attemptsRemaining) {+ this(userPoolId, username, purpose, codeHash, salt, issuedAt, expiresAt, attemptsRemaining, false);+ }++ public String getUserPoolId() { return userPoolId; }+ public String getUsername() { return username; }+ public Purpose getPurpose() { return purpose; }+ public String getCodeHash() { return codeHash; }+ public String getSalt() { return salt; }+ public Instant getIssuedAt() { return issuedAt; }+ public Instant getExpiresAt() { return expiresAt; }+ public int getAttemptsRemaining() { return attemptsRemaining; }+ public boolean isConsumed() { return consumed; }++ public void decrementAttempts() { this.attemptsRemaining--; }+ public void markConsumed() { this.consumed = true; }++ public boolean isExpired(Instant now) { return now.isAfter(expiresAt); }++ public static String storageKey(String userPoolId, String username, Purpose purpose) {+ // Assumes username does not contain ':'. Cognito usernames are emails,+ // phone numbers, or UUID-like sub strings in typical usage — none of+ // which contain ':'. External-IdP federated usernames could in theory,+ // but Cognito sanitizes them at sign-up.+ return userPoolId + ":" + username + ":" + purpose.name();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeException.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeException.javanew file mode 100644index 0000000000..9d871db45f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeException.java@@ -0,0 +1,21 @@+package io.github.hectorvent.floci.services.cognito.verification;++/**+ * Thrown by {@link VerificationCodeService} for code-validation failures.+ * The caller in {@code CognitoService} translates each {@link Kind} into the+ * corresponding AWS Cognito exception name ({@code CodeMismatchException},+ * {@code ExpiredCodeException}, {@code LimitExceededException}).+ */+public final class VerificationCodeException extends RuntimeException {++ public enum Kind { MISMATCH, EXPIRED, RATE_LIMIT, NOT_FOUND }++ private final Kind kind;++ public VerificationCodeException(Kind kind, String message) {+ super(message);+ this.kind = kind;+ }++ public Kind getKind() { return kind; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.javanew file mode 100644index 0000000000..2f510b7ef1--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java@@ -0,0 +1,169 @@+package io.github.hectorvent.floci.services.cognito.verification;++import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;++import java.nio.charset.StandardCharsets;+import java.security.MessageDigest;+import java.security.NoSuchAlgorithmException;+import java.security.SecureRandom;+import java.time.Clock;+import java.time.Duration;+import java.time.Instant;+import java.util.HexFormat;+import java.util.Map;+import java.util.Optional;++/**+ * Generates, persists, and validates Cognito verification codes used for+ * SignUp confirmation, password reset, MFA SMS, and attribute verification.+ *+ * <p>Codes are stored as SHA-256(code + per-code salt) so even a storage dump+ * cannot reveal a valid code. The plaintext code is returned to the caller+ * once (at {@code issue}) and never persisted.+ *+ * <p>Rate-limiting: re-issuing for the same (poolId, username, purpose) within+ * {@link #RATE_LIMIT_WINDOW} throws {@link VerificationCodeException.Kind#RATE_LIMIT}.+ * Attempts: after {@link #MAX_ATTEMPTS} failed {@code consume} calls the code+ * is invalidated.+ *+ * <p>The {@code ttl} is caller-supplied (per AWS the sign-up confirmation code is valid+ * 24h; the forgot-password code expires sooner, ~1h) — wiring layers must pass the right+ * value per purpose. {@link #RATE_LIMIT_WINDOW} (30s) and {@link #MAX_ATTEMPTS} (5) are+ * emulation heuristics: AWS throttles resends and invalidates after repeated failures, but+ * does not publish the exact thresholds.+ */+public final class VerificationCodeService {++ // Emulation heuristics (not AWS-documented constants): AWS throttles resend frequency and+ // invalidates a code after repeated wrong attempts, but the exact values are not published.+ private static final Duration RATE_LIMIT_WINDOW = Duration.ofSeconds(30);+ private static final int MAX_ATTEMPTS = 5;+ private static final int SALT_BYTES = 16;++ private final StorageBackend<String, VerificationCode> store;+ private final Clock clock;+ private final SecureRandom random;++ public VerificationCodeService(StorageFactory storageFactory, Clock clock) {+ this.store = storageFactory.create(+ "cognito",+ "cognito-verification-codes.json",+ new TypeReference<Map<String, VerificationCode>>() {}+ );+ this.clock = clock;+ this.random = new SecureRandom();+ }++ /**+ * Issue a new code for the given user/purpose. Returns the plaintext code+ * (caller must dispatch via SES/SNS). Subject to {@link #RATE_LIMIT_WINDOW}.+ */+ public String issue(String userPoolId, String username,+ VerificationCode.Purpose purpose, Duration ttl) {+ String key = VerificationCode.storageKey(userPoolId, username, purpose);+ Optional<VerificationCode> existing = store.get(key);+ if (existing.isPresent() && !existing.get().isConsumed()) {+ Duration since = Duration.between(existing.get().getIssuedAt(), clock.instant());+ if (since.compareTo(RATE_LIMIT_WINDOW) < 0) {+ throw new VerificationCodeException(+ VerificationCodeException.Kind.RATE_LIMIT,+ "Attempt limit exceeded, please try again later");+ }+ }++ String code = String.format("%06d", random.nextInt(1_000_000));+ String salt = HexFormat.of().formatHex(randomBytes(SALT_BYTES));+ String hash = sha256(code + salt);+ Instant now = clock.instant();++ VerificationCode vc = new VerificationCode(+ userPoolId, username, purpose, hash, salt, now, now.plus(ttl), MAX_ATTEMPTS+ );+ store.put(key, vc);+ return code;+ }++ /**+ * Validate a code. On success, marks it consumed and removes it. 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+ * decrement the attempts counter by 1 instead of 2. Acceptable for the+ * single-user local-dev profile; revisit if floci grows multi-tenant.+ */+ public void consume(String userPoolId, String username,+ VerificationCode.Purpose purpose, String code) {+ String key = VerificationCode.storageKey(userPoolId, username, purpose);+ 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.getAttemptsRemaining() <= 0) {+ store.delete(key);+ // AWS returns the generic invalid-code message here too, never the+ // attempt counter (anti-enumeration). Matches the spec's+ // observation: same message as a wrong-code below.+ throw new VerificationCodeException(+ VerificationCodeException.Kind.MISMATCH,+ "Invalid verification code provided, please try again");+ }++ String expectedHash = sha256(code + vc.getSalt());+ if (!constantTimeEquals(expectedHash, vc.getCodeHash())) {+ vc.decrementAttempts();+ if (vc.getAttemptsRemaining() <= 0) {+ store.delete(key); // exhausted — invalidate so even the real code fails+ } else {+ store.put(key, vc);+ }+ throw new VerificationCodeException(+ VerificationCodeException.Kind.MISMATCH,+ "Invalid verification code provided, please try again");+ }++ vc.markConsumed();+ store.delete(key);+ }++ /** Remove any active code for the (pool, user, purpose). Idempotent. */+ public void invalidatePrevious(String userPoolId, String username,+ VerificationCode.Purpose purpose) {+ store.delete(VerificationCode.storageKey(userPoolId, username, purpose));+ }++ private byte[] randomBytes(int n) {+ byte[] b = new byte[n];+ random.nextBytes(b);+ return b;+ }++ private String sha256(String s) {+ try {+ MessageDigest md = MessageDigest.getInstance("SHA-256");+ return HexFormat.of().formatHex(md.digest(s.getBytes(StandardCharsets.UTF_8)));+ } catch (NoSuchAlgorithmException e) {+ throw new IllegalStateException(e);+ }+ }++ private boolean constantTimeEquals(String a, String b) {+ if (a.length() != b.length()) return false;+ int r = 0;+ for (int i = 0; i < a.length(); i++) r |= a.charAt(i) ^ b.charAt(i);+ return r == 0;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.javaindex e94ea64b3d..475813d4d6 100644--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesInspectionController.java@@ -33,7 +33,8 @@ public class SesInspectionController {}@GET- public Response getEmails(@QueryParam("id") String messageId) {+ public Response getEmails(@QueryParam("id") String messageId,+ @QueryParam("email") String recipient) {List<SentEmail> emails = sesService.getEmails();ArrayNode messages = objectMapper.createArrayNode();@@ -41,6 +42,10 @@ public class SesInspectionController {if (messageId != null && !messageId.equals(email.getMessageId())) {continue;}+ if (recipient != null && (email.getToAddresses() == null+ || !email.getToAddresses().contains(recipient))) {+ continue;+ }ObjectNode node = objectMapper.createObjectNode();node.put("Id", email.getMessageId());if (email.getRegion() != null) {diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsInspectionController.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsInspectionController.javanew file mode 100644index 0000000000..269c5ba28d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsInspectionController.java@@ -0,0 +1,81 @@+package io.github.hectorvent.floci.services.sns;++import io.github.hectorvent.floci.services.sns.model.SentSms;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import jakarta.inject.Inject;+import jakarta.ws.rs.DELETE;+import jakarta.ws.rs.GET;+import jakarta.ws.rs.Path;+import jakarta.ws.rs.Produces;+import jakarta.ws.rs.QueryParam;+import jakarta.ws.rs.core.MediaType;+import jakarta.ws.rs.core.Response;++import java.util.List;++/**+ * LocalStack-compatible REST endpoint for inspecting published SNS SMS+ * messages. Mirrors {@code SesInspectionController} so test helpers can+ * retrieve verification codes sent via SMS.+ *+ * <p>GET /_aws/sns — all published SMS+ * <p>GET /_aws/sns?phone=X — filter by phone number (URL-encoded)+ * <p>GET /_aws/sns?id=X — filter by message ID+ * <p>DELETE /_aws/sns — clear all stored SMS+ */+@Path("/_aws/sns")+@Produces(MediaType.APPLICATION_JSON)+public class SnsInspectionController {++ private final SnsService snsService;+ private final ObjectMapper objectMapper;++ @Inject+ public SnsInspectionController(SnsService snsService, ObjectMapper objectMapper) {+ this.snsService = snsService;+ this.objectMapper = objectMapper;+ }++ @GET+ public Response getMessages(@QueryParam("phone") String phone,+ @QueryParam("id") String messageId) {+ List<SentSms> messages = snsService.getSentMessages();++ ArrayNode arr = objectMapper.createArrayNode();+ for (SentSms sms : messages) {+ if (phone != null && !phone.equals(sms.getPhoneNumber())) continue;+ if (messageId != null && !messageId.equals(sms.getMessageId())) continue;++ ObjectNode node = objectMapper.createObjectNode();+ node.put("Id", sms.getMessageId());+ if (sms.getRegion() != null) {+ node.put("Region", sms.getRegion());+ } else {+ node.putNull("Region");+ }+ node.put("PhoneNumber", sms.getPhoneNumber());+ node.put("Message", sms.getMessage());+ if (sms.getSubject() != null) {+ node.put("Subject", sms.getSubject());+ } else {+ node.putNull("Subject");+ }+ if (sms.getSentAt() != null) {+ node.put("Timestamp", sms.getSentAt().toString());+ }+ arr.add(node);+ }++ ObjectNode result = objectMapper.createObjectNode();+ result.set("messages", arr);+ return Response.ok(result).build();+ }++ @DELETE+ public Response clearMessages() {+ snsService.clearSentMessages();+ return Response.ok().build();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.javaindex dc95765a1e..62f1c94fa1 100644--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java@@ -8,9 +8,11 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.lambda.LambdaService;import io.github.hectorvent.floci.services.lambda.model.InvocationType;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.services.sns.model.PlatformApplication;import io.github.hectorvent.floci.services.sns.model.PlatformEndpoint;import io.github.hectorvent.floci.services.sns.model.PushNotification;+import io.github.hectorvent.floci.services.sns.model.SentSms;import io.github.hectorvent.floci.services.sns.model.Subscription;import io.github.hectorvent.floci.services.sns.model.Topic;import io.github.hectorvent.floci.services.sqs.SqsService;@@ -67,6 +69,7 @@ public class SnsService {private final StorageBackend<String, PlatformApplication> platformAppStore;private final StorageBackend<String, PlatformEndpoint> platformEndpointStore;private final Deque<PushNotification> pushCapture = new ConcurrentLinkedDeque<>();+ private final StorageBackend<String, SentSms> smsStore;private final RegionResolver regionResolver;private final SqsService sqsService;private final LambdaService lambdaService;@@ -93,6 +96,9 @@ public class SnsService {storageFactory.create("sns", "sns-platform-endpoints.json",new TypeReference<Map<String, PlatformEndpoint>>() {}),+ storageFactory.create("sns", "sns-sms.json",+ new TypeReference<Map<String, SentSms>>() {+ }),regionResolver,sqsService,lambdaService,@@ -109,8 +115,8 @@ public class SnsService {RegionResolver regionResolver, SqsService sqsService,LambdaService lambdaService) {this(topicStore, subscriptionStore,- new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(),- new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(),+ new InMemoryStorage<>(),+ new InMemoryStorage<>(),regionResolver, sqsService, lambdaService);}@@ -124,6 +130,7 @@ public class SnsService {this.subscriptionStore = subscriptionStore;this.platformAppStore = platformAppStore;this.platformEndpointStore = platformEndpointStore;+ this.smsStore = new InMemoryStorage<>();this.regionResolver = regionResolver;this.sqsService = sqsService;this.lambdaService = lambdaService;@@ -136,12 +143,14 @@ public class SnsService {StorageBackend<String, Subscription> subscriptionStore,StorageBackend<String, PlatformApplication> platformAppStore,StorageBackend<String, PlatformEndpoint> platformEndpointStore,+ StorageBackend<String, SentSms> smsStore,RegionResolver regionResolver, SqsService sqsService,LambdaService lambdaService, String baseUrl, ObjectMapper objectMapper) {this.topicStore = topicStore;this.subscriptionStore = subscriptionStore;this.platformAppStore = platformAppStore;this.platformEndpointStore = platformEndpointStore;+ this.smsStore = smsStore;this.regionResolver = regionResolver;this.sqsService = sqsService;this.lambdaService = lambdaService;@@ -357,7 +366,13 @@ public class SnsService {// Send SMSif (phoneNumber != null) {- return UUID.randomUUID().toString();+ String messageId = UUID.randomUUID().toString();+ String effectiveRegion = region != null ? region : "us-east-1";+ SentSms sms = new SentSms(messageId, effectiveRegion, phoneNumber,+ message, subject, Instant.now());+ smsStore.put("sms::" + effectiveRegion + "::" + messageId, sms);+ LOG.infov("SNS SMS published: messageId={0} phone={1}", messageId, phoneNumber);+ return messageId;}// Send a message to topic or directly to a target ARN@@ -1502,4 +1517,19 @@ public class SnsService {private static String subKey(String region, String subscriptionArn) {return "sub::" + region + "::" + subscriptionArn;}++ /** All SMS messages published since last clear. Used by SnsInspectionController. */+ public List<SentSms> getSentMessages() {+ return smsStore.scan(k -> k.startsWith("sms::"));+ }++ /** Drop all stored SMS records. Used by SnsInspectionController. */+ public void clearSentMessages() {+ for (String key : smsStore.keys()) {+ if (key.startsWith("sms::")) {+ smsStore.delete(key);+ }+ }+ LOG.info("Cleared all SNS SMS records");+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/model/SentSms.java b/src/main/java/io/github/hectorvent/floci/services/sns/model/SentSms.javanew file mode 100644index 0000000000..9b202551c2--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/sns/model/SentSms.java@@ -0,0 +1,65 @@+package io.github.hectorvent.floci.services.sns.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;++/**+ * Record of an SMS published via {@code SnsService.publish(...)} with a phone+ * number. Stored so test helpers and local clients can inspect SMS content+ * via {@code GET /_aws/sns} (mirrors the SES inspection pattern).+ */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class SentSms {++ @JsonProperty("MessageId")+ private String messageId;++ @JsonProperty("Region")+ private String region;++ @JsonProperty("PhoneNumber")+ private String phoneNumber;++ @JsonProperty("Message")+ private String message;++ @JsonProperty("Subject")+ private String subject;++ @JsonProperty("SentAt")+ private Instant sentAt;++ public SentSms() {}++ public SentSms(String messageId, String region, String phoneNumber,+ String message, String subject, Instant sentAt) {+ this.messageId = messageId;+ this.region = region;+ this.phoneNumber = phoneNumber;+ this.message = message;+ this.subject = subject;+ this.sentAt = sentAt;+ }++ public String getMessageId() { return messageId; }+ public void setMessageId(String messageId) { this.messageId = messageId; }++ public String getRegion() { return region; }+ public void setRegion(String region) { this.region = region; }++ public String getPhoneNumber() { return phoneNumber; }+ public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }++ public String getMessage() { return message; }+ public void setMessage(String message) { this.message = message; }++ public String getSubject() { return subject; }+ public void setSubject(String subject) { this.subject = subject; }++ public Instant getSentAt() { return sentAt; }+ public void setSentAt(Instant sentAt) { this.sentAt = sentAt; }+}diff --git a/src/test/java/io/github/hectorvent/floci/compat/FixtureLoader.java b/src/test/java/io/github/hectorvent/floci/compat/FixtureLoader.javanew file mode 100644index 0000000000..ef75e54756--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/compat/FixtureLoader.java@@ -0,0 +1,79 @@+package io.github.hectorvent.floci.compat;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;++import java.io.IOException;+import java.io.InputStream;+import java.util.Iterator;+import java.util.List;+import java.util.Set;++/**+ * Loads AWS API fixtures captured against real AWS endpoints. Each fixture is+ * the canonical wire-format response that floci must replicate (or, for error+ * fixtures, the canonical exception name + HTTP status code).+ *+ * <p>Fixtures live in {@code src/test/resources/fixtures/<service>/<name>.json}+ * and follow this structure:+ * <pre>{@code+ * {+ * "name": "sign-up.happy",+ * "capturedAt": "...",+ * "request": { ... raw AWS SDK request body ... },+ * "response": { ... raw AWS SDK response body, or null if error ... },+ * "error": { "name": "...", "message": "...", "$metadata": {...} } // null if success+ * }+ * }</pre>+ *+ * <p>Use {@link #normalize(JsonNode)} before equality comparisons to strip+ * volatile fields (RequestId, UserSub, timestamps, opaque Session tokens).+ */+public final class FixtureLoader {++ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final Set<String> VOLATILE_FIELDS = Set.of(+ "requestId", "RequestId", "x-amzn-RequestId",+ "UserSub",+ "Session",+ "Timestamp", "SentAt", "capturedAt",+ "$metadata"+ );++ private FixtureLoader() {}++ /** Load a fixture by name (without the .json extension). */+ public static JsonNode load(String name) throws IOException {+ String path = "/fixtures/aws-cognito/" + name + ".json";+ try (InputStream in = FixtureLoader.class.getResourceAsStream(path)) {+ if (in == null) {+ throw new IOException("Fixture not found on classpath: " + path);+ }+ return MAPPER.readTree(in);+ }+ }++ /**+ * Recursively remove volatile fields (RequestId, UserSub, timestamps, Session)+ * so two responses can be structurally compared without false negatives.+ */+ public static JsonNode normalize(JsonNode node) {+ if (node == null || node.isNull() || node.isValueNode()) return node;+ if (node.isArray()) {+ for (JsonNode child : node) normalize(child);+ return node;+ }+ if (node instanceof ObjectNode obj) {+ Iterator<String> fields = obj.fieldNames();+ List<String> toRemove = new java.util.ArrayList<>();+ while (fields.hasNext()) {+ String f = fields.next();+ if (VOLATILE_FIELDS.contains(f)) toRemove.add(f);+ }+ toRemove.forEach(obj::remove);+ obj.fieldNames().forEachRemaining(f -> normalize(obj.get(f)));+ }+ return node;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/compat/FixtureLoaderTest.java b/src/test/java/io/github/hectorvent/floci/compat/FixtureLoaderTest.javanew file mode 100644index 0000000000..3e7915b93c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/compat/FixtureLoaderTest.java@@ -0,0 +1,52 @@+package io.github.hectorvent.floci.compat;++import com.fasterxml.jackson.databind.JsonNode;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++class FixtureLoaderTest {++ @Test+ void load_signUpHappy_returnsCanonicalShape() throws Exception {+ JsonNode fixture = FixtureLoader.load("sign-up.happy");++ assertEquals("sign-up.happy", fixture.path("name").asText());+ JsonNode response = fixture.path("response");+ assertFalse(response.isMissingNode(), "response present");+ assertFalse(response.path("UserConfirmed").asBoolean(true), "UserConfirmed=false on real AWS");+ JsonNode cdd = response.path("CodeDeliveryDetails");+ assertEquals("EMAIL", cdd.path("DeliveryMedium").asText());+ assertEquals("email", cdd.path("AttributeName").asText());+ assertTrue(cdd.path("Destination").asText().contains("@"), "destination is masked email");+ }++ @Test+ void load_codeMismatchError_returnsErrorShape() throws Exception {+ JsonNode fixture = FixtureLoader.load("confirm-sign-up.error.code-mismatch");++ JsonNode error = fixture.path("error");+ assertFalse(error.isMissingNode());+ assertEquals("CodeMismatchException", error.path("name").asText());+ assertEquals(400, error.path("$metadata").path("httpStatusCode").asInt());+ }++ @Test+ void normalize_stripsVolatileFields() throws Exception {+ JsonNode fixture = FixtureLoader.load("sign-up.happy");+ JsonNode response = fixture.path("response");+ assertNotNull(response.get("$metadata"));++ FixtureLoader.normalize(response);++ // Volatile fields removed from the response+ assertTrue(response.path("$metadata").isMissingNode(), "$metadata removed");+ assertTrue(response.path("UserSub").isMissingNode(), "UserSub removed");+ // Structural fields preserved+ assertFalse(response.path("CodeDeliveryDetails").isMissingNode(), "CDD preserved");+ assertFalse(response.path("UserConfirmed").isMissingNode(), "UserConfirmed preserved");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.javanew file mode 100644index 0000000000..db28add75a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java@@ -0,0 +1,167 @@+package io.github.hectorvent.floci.services.cognito.verification;++import io.github.hectorvent.floci.services.cognito.model.CognitoUser;+import io.github.hectorvent.floci.services.cognito.model.UserPool;+import io.github.hectorvent.floci.services.ses.SesService;+import io.github.hectorvent.floci.services.sns.SnsService;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.HashMap;+import java.util.List;+import java.util.Map;++import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.ArgumentMatchers.isNull;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;++class CognitoMessageDispatcherTest {++ private SesService ses;+ private SnsService sns;+ private CognitoMessageDispatcher dispatcher;++ @BeforeEach+ void setUp() {+ ses = mock(SesService.class);+ sns = mock(SnsService.class);+ dispatcher = new CognitoMessageDispatcher(ses, sns);+ }++ @Test+ void dispatch_emailFlow_callsSesWithRenderedTemplate() {+ UserPool pool = pool(Map.of(+ "EmailSubject", "Verify your account",+ "EmailMessage", "Hi! Your code is {####}."+ ));+ CognitoUser user = user("[email protected]", null);++ dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,+ "123456", List.of("EMAIL"));++ verify(ses).sendEmail(+ anyString(),+ eq(List.of("[email protected]")),+ eq(List.of()), eq(List.of()), eq(List.of()),+ eq("Verify your account"),+ eq("Hi! Your code is 123456."),+ isNull(), isNull(), eq(List.of()), eq(List.of()),+ eq("us-east-1"));+ verifyNoInteractions(sns);+ }++ @Test+ void dispatch_smsSignupFlow_usesSmsMessageTemplate() {+ UserPool pool = pool(Map.of(+ "SmsMessage", "Signup: {####}",+ "SmsAuthenticationMessage", "MFA: {####}"+ ));+ CognitoUser user = user("[email protected]", "+5215551234567");++ dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,+ "654321", List.of("SMS"));++ verify(sns).publish(+ isNull(), isNull(),+ eq("+5215551234567"),+ eq("Signup: 654321"),+ isNull(), isNull(), eq("us-east-1"));+ verifyNoInteractions(ses);+ }++ @Test+ void dispatch_smsMfaFlow_usesSmsAuthenticationMessageTemplate() {+ // SmsAuthenticationMessage is a top-level UserPool attribute, not part of+ // VerificationMessageTemplate (which only holds SmsMessage for verification codes).+ UserPool pool = pool(Map.of("SmsMessage", "Signup: {####}"));+ pool.setSmsAuthenticationMessage("MFA: {####}");+ CognitoUser user = user("[email protected]", "+5215551234567");++ dispatcher.dispatch(pool, user, VerificationCode.Purpose.SMS_MFA,+ "654321", List.of("SMS"));++ verify(sns).publish(+ isNull(), isNull(),+ eq("+5215551234567"),+ eq("MFA: 654321"),+ isNull(), isNull(), eq("us-east-1"));+ verifyNoInteractions(ses);+ }++ @Test+ void dispatch_emptyTemplate_usesDefaults() {+ UserPool pool = pool(Map.of());+ CognitoUser user = user("[email protected]", null);++ dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,+ "111222", List.of("EMAIL"));++ verify(ses).sendEmail(+ anyString(), eq(List.of("[email protected]")),+ eq(List.of()), eq(List.of()), eq(List.of()),+ eq("Your verification code"),+ eq("Your verification code is 111222."),+ isNull(), isNull(), eq(List.of()), eq(List.of()), eq("us-east-1"));+ }++ @Test+ void dispatch_templateWithoutPlaceholder_appendsFailsafe() {+ UserPool pool = pool(Map.of("EmailMessage", "Welcome, please verify."));+ CognitoUser user = user("[email protected]", null);++ dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,+ "999000", List.of("EMAIL"));++ verify(ses).sendEmail(+ anyString(), eq(List.of("[email protected]")),+ eq(List.of()), eq(List.of()), eq(List.of()),+ anyString(),+ eq("Welcome, please verify.\nCode: 999000"),+ isNull(), isNull(), eq(List.of()), eq(List.of()), eq("us-east-1"));+ }++ @Test+ void dispatch_missingDeliveryMediums_emailFallbackWhenEmailPresent() {+ UserPool pool = pool(Map.of());+ CognitoUser user = user("[email protected]", "+5215551234567");++ dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,+ "444555", List.of());++ verify(ses).sendEmail(anyString(), eq(List.of("[email protected]")),+ any(), any(), any(), anyString(), anyString(), isNull(), isNull(), any(), any(), anyString());+ verifyNoInteractions(sns);+ }++ @Test+ void dispatch_missingDeliveryMediums_smsFallbackWhenOnlyPhone() {+ UserPool pool = pool(Map.of());+ CognitoUser user = user(null, "+5215551234567");++ dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,+ "777888", List.of());++ verify(sns).publish(isNull(), isNull(), eq("+5215551234567"),+ anyString(), isNull(), isNull(), anyString());+ verifyNoInteractions(ses);+ }++ private UserPool pool(Map<String, Object> template) {+ UserPool p = new UserPool();+ p.setVerificationMessageTemplate(new HashMap<>(template));+ return p;+ }++ private CognitoUser user(String email, String phone) {+ CognitoUser u = new CognitoUser();+ Map<String, String> attrs = new HashMap<>();+ if (email != null) attrs.put("email", email);+ if (phone != null) attrs.put("phone_number", phone);+ u.setAttributes(attrs);+ return u;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.javanew file mode 100644index 0000000000..7fd8afcb05--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java@@ -0,0 +1,143 @@+package io.github.hectorvent.floci.services.cognito.verification;++import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.time.Clock;+import java.time.Duration;+import java.time.Instant;+import java.time.ZoneId;+import java.time.ZoneOffset;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++class VerificationCodeServiceTest {++ private VerificationCodeService service;+ private MutableClock clock;++ @BeforeEach+ void setUp() {+ clock = new MutableClock(Instant.parse("2026-05-15T12:00:00Z"));+ StorageFactory storageFactory = mock(StorageFactory.class);+ when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> new InMemoryStorage<>());+ service = new VerificationCodeService(storageFactory, clock);+ }++ @Test+ void issue_generatesSixDigitCode() {+ String code = service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));+ assertEquals(6, code.length(), "code length");+ assertTrue(code.matches("\\d{6}"), "code is digits");+ }++ @Test+ void consume_validCode_succeeds() {+ String code = service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));+ assertDoesNotThrow(() -> service.consume("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, code));+ }++ @Test+ void consume_wrongCode_throwsMismatch() {+ service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));+ VerificationCodeException ex = assertThrows(VerificationCodeException.class,+ () -> service.consume("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, "000000"));+ assertEquals(VerificationCodeException.Kind.MISMATCH, ex.getKind());+ }++ @Test+ void consume_afterTtl_throwsExpired() {+ String code = service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofMinutes(15));+ clock.advance(Duration.ofMinutes(16));+ VerificationCodeException ex = assertThrows(VerificationCodeException.class,+ () -> service.consume("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, code));+ assertEquals(VerificationCodeException.Kind.EXPIRED, ex.getKind());+ }++ @Test+ void consume_attemptsExhausted_invalidatesCode() {+ String code = service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));+ for (int i = 0; i < 5; i++) {+ assertThrows(VerificationCodeException.class,+ () -> service.consume("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, "000000"));+ }+ // Even the real code should now fail — store entry was invalidated.+ VerificationCodeException ex = assertThrows(VerificationCodeException.class,+ () -> service.consume("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, code));+ assertEquals(VerificationCodeException.Kind.NOT_FOUND, ex.getKind());+ }++ @Test+ void invalidatePrevious_removesActiveCode() {+ service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));+ service.invalidatePrevious("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION);+ // Issuing a new code right after invalidate should not hit rate-limit+ assertDoesNotThrow(() ->+ service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24)));+ }++ @Test+ void issue_twiceWithin30s_throwsRateLimit() {+ service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));+ VerificationCodeException ex = assertThrows(VerificationCodeException.class,+ () -> service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24)));+ assertEquals(VerificationCodeException.Kind.RATE_LIMIT, ex.getKind());+ }++ @Test+ void issue_after30s_succeeds() {+ service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));+ clock.advance(Duration.ofSeconds(31));+ assertDoesNotThrow(() ->+ service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24)));+ }++ @Test+ void codesForDifferentPurposes_independent() {+ String signupCode = service.issue("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));+ String resetCode = service.issue("pool", "alice",+ VerificationCode.Purpose.PASSWORD_RESET, Duration.ofHours(1));+ assertNotEquals(signupCode, resetCode);+ assertDoesNotThrow(() -> service.consume("pool", "alice",+ VerificationCode.Purpose.SIGNUP_CONFIRMATION, signupCode));+ assertDoesNotThrow(() -> service.consume("pool", "alice",+ VerificationCode.Purpose.PASSWORD_RESET, resetCode));+ }++ static final class MutableClock extends Clock {+ private Instant now;+ MutableClock(Instant start) { this.now = start; }+ void advance(Duration d) { now = now.plus(d); }+ @Override public ZoneId getZone() { return ZoneOffset.UTC; }+ @Override public Clock withZone(ZoneId zone) { return this; }+ @Override public Instant instant() { return now; }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsInspectionControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsInspectionControllerIntegrationTest.javanew file mode 100644index 0000000000..779f9ea57f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsInspectionControllerIntegrationTest.java@@ -0,0 +1,84 @@+package io.github.hectorvent.floci.services.sns;++import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasSize;++@QuarkusTest+class SnsInspectionControllerIntegrationTest {++ @Inject+ SnsService snsService;++ @BeforeEach+ void clear() {+ snsService.clearSentMessages();+ }++ @Test+ @DisplayName("GET /_aws/sns returns empty when no SMS published")+ void emptyWhenNoMessages() {+ given()+ .when().get("/_aws/sns")+ .then()+ .statusCode(200)+ .body("messages", hasSize(0));+ }++ @Test+ @DisplayName("publishing SMS makes it inspectable via GET /_aws/sns")+ void publishedSmsIsInspectable() {+ snsService.publish(null, null, "+5215551234567",+ "Your code is 123456", null, null, "us-east-1");++ given()+ .when().get("/_aws/sns")+ .then()+ .statusCode(200)+ .body("messages", hasSize(1))+ .body("messages[0].PhoneNumber", equalTo("+5215551234567"))+ .body("messages[0].Message", equalTo("Your code is 123456"))+ .body("messages[0].Region", equalTo("us-east-1"));+ }++ @Test+ @DisplayName("GET /_aws/sns?phone= filters by phone number")+ void filtersByPhoneNumber() {+ snsService.publish(null, null, "+5215551111111",+ "first", null, null, "us-east-1");+ snsService.publish(null, null, "+5215552222222",+ "second", null, null, "us-east-1");+ snsService.publish(null, null, "+5215553333333",+ "third", null, null, "us-east-1");++ given().queryParam("phone", "+5215552222222")+ .when().get("/_aws/sns")+ .then()+ .statusCode(200)+ .body("messages", hasSize(1))+ .body("messages[0].Message", equalTo("second"));+ }++ @Test+ @DisplayName("DELETE /_aws/sns clears all stored SMS")+ void deleteClearsAll() {+ snsService.publish(null, null, "+5215551234567",+ "to clear", null, null, "us-east-1");++ given()+ .when().delete("/_aws/sns")+ .then().statusCode(200);++ given()+ .when().get("/_aws/sns")+ .then()+ .statusCode(200)+ .body("messages", hasSize(0));+ }+}diff --git a/src/test/resources/fixtures/aws-cognito/confirm-sign-up.error.code-mismatch.json b/src/test/resources/fixtures/aws-cognito/confirm-sign-up.error.code-mismatch.jsonnew file mode 100644index 0000000000..73decd4029--- /dev/null+++ b/src/test/resources/fixtures/aws-cognito/confirm-sign-up.error.code-mismatch.json@@ -0,0 +1,18 @@+{+ "name": "confirm-sign-up.error.code-mismatch",+ "capturedAt": "2026-05-16T05:10:20.553Z",+ "request": {+ "ClientId": "6h89qn2bfglbmvfebq9aaknqk0",+ "Username": "[email protected]",+ "ConfirmationCode": "000000"+ },+ "response": null,+ "error": {+ "name": "CodeMismatchException",+ "message": "Invalid verification code provided, please try again.",+ "$metadata": {+ "httpStatusCode": 400,+ "requestId": "73626b75-683d-4630-99c1-05f736ed86f7"+ }+ }+}\ No newline at end of filediff --git a/src/test/resources/fixtures/aws-cognito/forgot-password.unknown-user.json b/src/test/resources/fixtures/aws-cognito/forgot-password.unknown-user.jsonnew file mode 100644index 0000000000..af6cc18047--- /dev/null+++ b/src/test/resources/fixtures/aws-cognito/forgot-password.unknown-user.json@@ -0,0 +1,17 @@+{+ "name": "forgot-password.unknown-user",+ "capturedAt": "2026-05-16T05:10:22.859Z",+ "request": {+ "ClientId": "6h89qn2bfglbmvfebq9aaknqk0",+ "Username": "[email protected]"+ },+ "response": null,+ "error": {+ "name": "UserNotFoundException",+ "message": "Username/client id combination not found.",+ "$metadata": {+ "httpStatusCode": 400,+ "requestId": "4587537a-5573-4ef5-90b7-7291133ab18d"+ }+ }+}\ No newline at end of filediff --git a/src/test/resources/fixtures/aws-cognito/initiate-auth.srp.unknown-user.json b/src/test/resources/fixtures/aws-cognito/initiate-auth.srp.unknown-user.jsonnew file mode 100644index 0000000000..5ef5e56bd0--- /dev/null+++ b/src/test/resources/fixtures/aws-cognito/initiate-auth.srp.unknown-user.json@@ -0,0 +1,21 @@+{+ "name": "initiate-auth.srp.unknown-user",+ "capturedAt": "2026-05-16T05:10:23.019Z",+ "request": {+ "AuthFlow": "USER_SRP_AUTH",+ "ClientId": "6h89qn2bfglbmvfebq9aaknqk0",+ "AuthParameters": {+ "USERNAME": "[email protected]",+ "SRP_A": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ }+ },+ "response": null,+ "error": {+ "name": "UserNotFoundException",+ "message": "User does not exist.",+ "$metadata": {+ "httpStatusCode": 400,+ "requestId": "c4459718-f2a4-48f8-8377-d56a06828f46"+ }+ }+}\ No newline at end of filediff --git a/src/test/resources/fixtures/aws-cognito/resend-confirmation.error.rate-limit.json b/src/test/resources/fixtures/aws-cognito/resend-confirmation.error.rate-limit.jsonnew file mode 100644index 0000000000..c974ecd97d--- /dev/null+++ b/src/test/resources/fixtures/aws-cognito/resend-confirmation.error.rate-limit.json@@ -0,0 +1,22 @@+{+ "name": "resend-confirmation.error.rate-limit",+ "capturedAt": "2026-05-16T05:10:22.703Z",+ "request": {+ "ClientId": "6h89qn2bfglbmvfebq9aaknqk0",+ "Username": "[email protected]"+ },+ "response": {+ "CodeDeliveryDetails": {+ "Destination": "f***@e***",+ "DeliveryMedium": "EMAIL",+ "AttributeName": "email"+ },+ "$metadata": {+ "httpStatusCode": 200,+ "requestId": "845f89fd-de84-46b3-8de3-fa85980d4a8f",+ "attempts": 1,+ "totalRetryDelay": 0+ }+ },+ "error": null+}\ No newline at end of filediff --git a/src/test/resources/fixtures/aws-cognito/resend-confirmation.happy.json b/src/test/resources/fixtures/aws-cognito/resend-confirmation.happy.jsonnew file mode 100644index 0000000000..92a5923bd3--- /dev/null+++ b/src/test/resources/fixtures/aws-cognito/resend-confirmation.happy.json@@ -0,0 +1,22 @@+{+ "name": "resend-confirmation.happy",+ "capturedAt": "2026-05-16T05:10:21.597Z",+ "request": {+ "ClientId": "6h89qn2bfglbmvfebq9aaknqk0",+ "Username": "[email protected]"+ },+ "response": {+ "CodeDeliveryDetails": {+ "Destination": "f***@e***",+ "DeliveryMedium": "EMAIL",+ "AttributeName": "email"+ },+ "$metadata": {+ "httpStatusCode": 200,+ "requestId": "30b85e7f-621c-413c-a294-25393a2964c6",+ "attempts": 1,+ "totalRetryDelay": 0+ }+ },+ "error": null+}\ No newline at end of filediff --git a/src/test/resources/fixtures/aws-cognito/sign-up.error.username-exists.json b/src/test/resources/fixtures/aws-cognito/sign-up.error.username-exists.jsonnew file mode 100644index 0000000000..b241569051--- /dev/null+++ b/src/test/resources/fixtures/aws-cognito/sign-up.error.username-exists.json@@ -0,0 +1,36 @@+{+ "name": "sign-up.error.username-exists",+ "capturedAt": "2026-05-16T05:10:19.745Z",+ "request": {+ "ClientId": "6h89qn2bfglbmvfebq9aaknqk0",+ "Username": "[email protected]",+ "Password": "Fixture1!Aa",+ "UserAttributes": [+ {+ "Name": "email",+ "Value": "[email protected]"+ },+ {+ "Name": "phone_number",+ "Value": "+5215555555555"+ },+ {+ "Name": "given_name",+ "Value": "Fixture"+ },+ {+ "Name": "family_name",+ "Value": "User"+ }+ ]+ },+ "response": null,+ "error": {+ "name": "UsernameExistsException",+ "message": "User already exists",+ "$metadata": {+ "httpStatusCode": 400,+ "requestId": "b3434b0c-42dd-42fc-82a6-995412164d66"+ }+ }+}\ No newline at end of filediff --git a/src/test/resources/fixtures/aws-cognito/sign-up.happy.json b/src/test/resources/fixtures/aws-cognito/sign-up.happy.jsonnew file mode 100644index 0000000000..66ddc7d369--- /dev/null+++ b/src/test/resources/fixtures/aws-cognito/sign-up.happy.json@@ -0,0 +1,43 @@+{+ "name": "sign-up.happy",+ "capturedAt": "2026-05-16T05:10:18.457Z",+ "request": {+ "ClientId": "6h89qn2bfglbmvfebq9aaknqk0",+ "Username": "[email protected]",+ "Password": "Fixture1!Aa",+ "UserAttributes": [+ {+ "Name": "email",+ "Value": "[email protected]"+ },+ {+ "Name": "phone_number",+ "Value": "+5215555555555"+ },+ {+ "Name": "given_name",+ "Value": "Fixture"+ },+ {+ "Name": "family_name",+ "Value": "User"+ }+ ]+ },+ "response": {+ "UserConfirmed": false,+ "UserSub": "34c84488-e0e1-70ae-d2ee-991ad1a898c8",+ "CodeDeliveryDetails": {+ "Destination": "f***@e***",+ "DeliveryMedium": "EMAIL",+ "AttributeName": "email"+ },+ "$metadata": {+ "httpStatusCode": 200,+ "requestId": "e2953a5e-cd31-49f9-a9e0-fac9c689740d",+ "attempts": 1,+ "totalRetryDelay": 0+ }+ },+ "error": null+}\ No newline at end of file