feat(cognito): add verification code subsystem (store, dispatcher, SNS/SES inspection) (#1249)

* chore(fixtures): capture AWS Cognito auth flow fixtures for contract tests

Captures 7 wire-format fixtures against wirebit stg pool for use as ground truth
in floci compatibility tests. Includes capture script with PII sanitization and
best-effort user cleanup.

Empirical findings vs spec:
- No client-side rate-limit observed on back-to-back ResendConfirmationCode
- PreventUserExistenceErrors=LEGACY in wirebit prod/stg (older pools)
- Email Destination masking is aggressive: f***@e***

* feat(cognito): add verification code store, message dispatcher and SNS inspection

Introduces the foundation for full Cognito auth flow emulation:

- VerificationCodeService: 6-digit codes hashed with per-code salt, persisted
  via StorageFactory with TTL + 30s rate-limit + 5-attempt invalidation.
- VerificationCode model: serializable to disk for filesystem storage mode.
- CognitoMessageDispatcher: renders VerificationMessageTemplate ({####}
  placeholder + failsafe), dispatches via SesService (email) or SnsService
  (SMS) honoring DeliveryMediums.
- SnsService: now persists every phone publish() as a SentSms record and
  exposes getSentMessages()/clearSentMessages().
- SnsInspectionController: GET/DELETE /_aws/sns mirroring SesInspectionController.
- FixtureLoader + 7 AWS Cognito fixtures captured against wirebit-stg pool
  (sign-up, confirm-signup error, resend, forgot-password unknown-user, SRP
  unknown-user). Relocated from compatibility-tests/ to src/test/resources/
  so JUnit can load them via classpath.

Not yet wired to any flow — that's PR #2-5 in a stacked series.

Tests: 22 new (9 VerificationCodeService + 6 dispatcher + 4 SNS inspection +
3 FixtureLoader). Full suite 4336 passing (was 4314), ElastiCacheIntegrationTest
excluded due to local port-6379 collision.

* feat(ses): SesInspectionController supports ?email= filter

Symmetric to SnsInspectionController.?phone= (added in the verification
code store commit). Lets test helpers retrieve the latest email sent to
a specific recipient without filtering client-side over the full message
list.

GET /_aws/ses?email=user@example.com → only messages where the address
is in ToAddresses.

* fix(cognito): align verification dispatcher with AWS and current SES API

Adapt the adopted verification-code foundation to current main and AWS:
- update CognitoMessageDispatcher to the 12-arg SesService.sendEmail signature
- source the MFA SMS message from the user pool's top-level SmsAuthenticationMessage
  (it is not part of VerificationMessageTemplate, which only holds SmsMessage)
- match AWS's out-of-the-box default verification message text
- document the 30s resend window and 5-attempt cap as emulation heuristics (not
  AWS-published constants) and add TODOs for DefaultEmailOption, medium preference,
  and per-purpose TTL that the auth-flow wiring must honour

Co-authored-by: Ricardo Medina <34877263+ricardomedina98@users.noreply.github.com>

* refactor(cognito): drop dead code flagged by static analysis

- remove no-op ctorRequest local in scripts/aws-fixtures-capture.mjs
- drop the unused purpose parameter from emailTemplateKey() and its call site

Co-authored-by: Ricardo Medina <34877263+ricardomedina98@users.noreply.github.com>

* chore(cognito): remove the one-off AWS fixture-capture dev script

The captured aws-cognito/*.json fixtures remain (FixtureLoader uses those); the Node capture tool is not needed in the repo.

---------

Co-authored-by: Ricardo Medina <34877263+ricardomedina98@users.noreply.github.com>
This commit is contained in:
Hector VenturaandRicardo Medina authored and GitHub committed 2026-06-11 00:47:33 -05:00
1 parent 92f4ff1ccf
commit d7f9f95873
21 files changed
+1289 -4

No files matched your search

@@ -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 = "no-reply@verificationemail.com";
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;
}
}
@@ -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();
}
}
@@ -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; }
}
@@ -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;
}
}
@@ -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) {
@@ -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();
}
}
@@ -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 SMS
if (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");
}
}
@@ -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; }
}