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,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;
}
}
@@ -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");
}
}
@@ -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("alice@example.com", null);
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"));
verify(ses).sendEmail(
anyString(),
eq(List.of("alice@example.com")),
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("alice@example.com", "+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("alice@example.com", "+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("alice@example.com", null);
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"111222", List.of("EMAIL"));
verify(ses).sendEmail(
anyString(), eq(List.of("alice@example.com")),
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("alice@example.com", null);
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"999000", List.of("EMAIL"));
verify(ses).sendEmail(
anyString(), eq(List.of("alice@example.com")),
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("alice@example.com", "+5215551234567");
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"444555", List.of());
verify(ses).sendEmail(anyString(), eq(List.of("alice@example.com")),
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;
}
}
@@ -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; }
}
}
@@ -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));
}
}