feat(cognito): support the USER_AUTH choice-based auth flow (#3930)

Implements InitiateAuth/AdminInitiateAuth AuthFlow=USER_AUTH (#3926):
USERNAME plus optional PREFERRED_CHALLENGE, offering PASSWORD,
PASSWORD_SRP, EMAIL_OTP and SMS_OTP depending on what the user has
(password hash, SRP verifier, verified email, verified phone). With
no PREFERRED_CHALLENGE, the response carries AvailableChallenges and
ChallengeName=SELECT_CHALLENGE; with one, it goes straight to that
challenge. RespondToAuthChallenge handles SELECT_CHALLENGE (ANSWER
names the chosen factor, and may already carry that factor's own
answer to complete in one round trip), PASSWORD, PASSWORD_SRP, and
EMAIL_OTP/SMS_OTP.

PASSWORD and PASSWORD_SRP reuse authenticateWithPassword and
handleUserSrpAuth unchanged rather than reimplementing verification:
a USER_AUTH client responding with PASSWORD/SRP_A needs exactly the
same checks those flows already perform, so PASSWORD_SRP hands off to
the existing PASSWORD_VERIFIER challenge with zero new SRP logic.
EMAIL_OTP/SMS_OTP reuse the existing VerificationCodeService/
CognitoMessageDispatcher pair already used for SignUp/ForgotPassword
codes, adding EMAIL_OTP/SMS_OTP as new VerificationCode.Purpose
values distinct from SMS_MFA so a sign-in code can't be replayed
against another purpose's consume() call.

Also gates USER_AUTH on the pool's tier: AWS requires Essentials or
higher, and UserPool.userPoolTier already models this (defaulting to
ESSENTIALS), so a LITE-tier pool is rejected. SMS_OTP uses
SmsAuthenticationMessage, the template AWS documents for "SMS OTP and
MFA authentication" (CreateUserPool docs), not the signup/
verification template.

Security and correctness fixes found in review:
- handleUserAuth now validates SECRET_HASH before looking up the user
  or issuing a challenge, closing a hole where a caller with no
  secret could trigger a real OTP send and read the masked
  destination without proving it holds the client secret.
- issueSignInOtp now maps VerificationCodeException through
  mapVerificationCodeException (so a rate-limited retry surfaces as
  LimitExceededException, not a generic CodeDeliveryFailureException
  that hid the real cause), and invalidates the just-issued code
  before reporting a real dispatch failure, so the rate limiter
  doesn't lock out a retry for a code the user never received,
  matching signUp's existing rollback pattern.

Deliberately not implemented, tracked as follow-ups:
- WEB_AUTHN (passkeys): a much bigger piece per the issue's own
  scoping note, no credential storage/ceremony exists in floci yet.
- The Session from ConfirmSignUp accepted as a first-factor shortcut:
  needs ConfirmSignUp to start minting a redeemable session, a
  separate mechanism from the challenge flow this PR adds.
- Pool-level sign-in policy (AllowedFirstAuthFactors): floci does not
  model per-pool factor restrictions at all today; availability here
  is purely per-user (does the user have this factor configured).
- Session is not looked up on RespondToAuthChallenge: each handler
  independently reverifies its own factor from the request body, the
  same shape the existing NEW_PASSWORD_REQUIRED handler already uses,
  so there is no bypass, just an opaque correlation token rather than
  server-held state.

Verified against botocore's cognito-idp service-2.json (AuthFlowType,
ChallengeNameType, AvailableChallengeListType, the AuthParameters
documentation for USER_AUTH) and the real InitiateAuth/CreateUserPool
API reference pages, including InitiateAuth's worked examples and
CreateUserPool's SmsAuthenticationMessage description.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-20 09:11:01 -05:00
1 parent 3958be1d0e
commit 803d0ed0ed
8 files changed
+935 -10

No files matched your search

@@ -22,6 +22,7 @@ import java.security.Signature;
import java.security.spec.RSAPublicKeySpec;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Spliterators;
@@ -2667,6 +2668,153 @@ class CognitoIntegrationTest {
.statusCode(200);
}
// ── Issue #3926: USER_AUTH choice-based flow ────────────────────────
// Self-contained pool/user rather than the suite's shared USERNAME: by this point in the
// ordered sequence several earlier tests have changed alice's password, so PASSWORD no
// longer matches what AdminSetUserPassword set up in @BeforeAll.
@Test
@Order(105)
void initiateAuthWithUserAuthNoPreferredChallengeReturnsSelectChallengeOverTheWire() throws Exception {
String userAuthPoolId = cognitoJson("CreateUserPool", """
{ "PoolName": "UserAuthWirePool" }
""").path("UserPool").path("Id").asText();
String userAuthClientId = cognitoJson("CreateUserPoolClient", """
{ "UserPoolId": "%s", "ClientName": "user-auth-client" }
""".formatted(userAuthPoolId)).path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", """
{ "UserPoolId": "%s", "Username": "dana",
"UserAttributes": [{ "Name": "email", "Value": "dana@example.com" }] }
""".formatted(userAuthPoolId))
.then().statusCode(200);
cognitoAction("AdminSetUserPassword", """
{ "UserPoolId": "%s", "Username": "dana", "Password": "Dana1234!", "Permanent": true }
""".formatted(userAuthPoolId))
.then().statusCode(200);
JsonNode result = cognitoJson("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "USER_AUTH",
"AuthParameters": { "USERNAME": "dana" }
}
""".formatted(userAuthClientId));
assertEquals("SELECT_CHALLENGE", result.path("ChallengeName").asText());
assertFalse(result.path("Session").asText().isBlank());
List<String> available = new ArrayList<>();
result.path("AvailableChallenges").forEach(n -> available.add(n.asText()));
assertTrue(available.contains("PASSWORD"), "expected PASSWORD in " + available);
}
@Test
@Order(106)
void initiateAuthWithUserAuthPreferredChallengePasswordCompletesOverTheWire() throws Exception {
String userAuthPoolId = cognitoJson("CreateUserPool", """
{ "PoolName": "UserAuthWirePasswordPool" }
""").path("UserPool").path("Id").asText();
String userAuthClientId = cognitoJson("CreateUserPoolClient", """
{ "UserPoolId": "%s", "ClientName": "user-auth-client" }
""".formatted(userAuthPoolId)).path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", """
{ "UserPoolId": "%s", "Username": "erin",
"UserAttributes": [{ "Name": "email", "Value": "erin@example.com" }] }
""".formatted(userAuthPoolId))
.then().statusCode(200);
cognitoAction("AdminSetUserPassword", """
{ "UserPoolId": "%s", "Username": "erin", "Password": "Erin1234!", "Permanent": true }
""".formatted(userAuthPoolId))
.then().statusCode(200);
JsonNode challenge = cognitoJson("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "USER_AUTH",
"AuthParameters": { "USERNAME": "erin", "PREFERRED_CHALLENGE": "PASSWORD" }
}
""".formatted(userAuthClientId));
assertEquals("PASSWORD", challenge.path("ChallengeName").asText());
String session = challenge.path("Session").asText();
JsonNode result = cognitoJson("RespondToAuthChallenge", """
{
"ClientId": "%s",
"ChallengeName": "PASSWORD",
"Session": "%s",
"ChallengeResponses": { "USERNAME": "erin", "PASSWORD": "Erin1234!" }
}
""".formatted(userAuthClientId, session));
assertFalse(result.path("AuthenticationResult").path("AccessToken").asText().isBlank(),
"responding to the PASSWORD challenge with the right password should issue tokens");
}
@Test
@Order(107)
void initiateAuthWithUserAuthRejectsALiteTierPoolOverTheWire() throws Exception {
String liteTierPoolId = cognitoJson("CreateUserPool", """
{ "PoolName": "UserAuthLiteTierPool", "UserPoolTier": "LITE" }
""").path("UserPool").path("Id").asText();
String liteTierClientId = cognitoJson("CreateUserPoolClient", """
{ "UserPoolId": "%s", "ClientName": "user-auth-client" }
""".formatted(liteTierPoolId)).path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", """
{ "UserPoolId": "%s", "Username": "finn",
"UserAttributes": [{ "Name": "email", "Value": "finn@example.com" }] }
""".formatted(liteTierPoolId))
.then().statusCode(200);
cognitoAction("AdminSetUserPassword", """
{ "UserPoolId": "%s", "Username": "finn", "Password": "Finn1234!", "Permanent": true }
""".formatted(liteTierPoolId))
.then().statusCode(200);
cognitoAction("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "USER_AUTH",
"AuthParameters": { "USERNAME": "finn" }
}
""".formatted(liteTierClientId))
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
}
@Test
@Order(108)
void respondToAuthChallengeRejectsPasswordWithNoSessionOverTheWire() throws Exception {
// Reproduces the bypass reported on #3930: without session tracking, RespondToAuthChallenge
// would accept a bare USERNAME/PASSWORD pair with ChallengeName=PASSWORD and sign the user
// in without InitiateAuth ever running, skipping the tier gate entirely.
String userAuthPoolId = cognitoJson("CreateUserPool", """
{ "PoolName": "UserAuthWireNoSessionPool" }
""").path("UserPool").path("Id").asText();
String userAuthClientId = cognitoJson("CreateUserPoolClient", """
{ "UserPoolId": "%s", "ClientName": "user-auth-client" }
""".formatted(userAuthPoolId)).path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", """
{ "UserPoolId": "%s", "Username": "gale",
"UserAttributes": [{ "Name": "email", "Value": "gale@example.com" }] }
""".formatted(userAuthPoolId))
.then().statusCode(200);
cognitoAction("AdminSetUserPassword", """
{ "UserPoolId": "%s", "Username": "gale", "Password": "Gale1234!", "Permanent": true }
""".formatted(userAuthPoolId))
.then().statusCode(200);
cognitoAction("RespondToAuthChallenge", """
{
"ClientId": "%s",
"ChallengeName": "PASSWORD",
"Session": "no-such-session",
"ChallengeResponses": { "USERNAME": "gale", "PASSWORD": "Gale1234!" }
}
""".formatted(userAuthClientId))
.then()
.statusCode(400)
.body("__type", equalTo("NotAuthorizedException"));
}
private static JsonNode decodeJwtPayload(String token) throws Exception {
return decodeJwtPart(token, 1);
}
@@ -2147,6 +2147,490 @@ class CognitoServiceTest {
assertEquals("NotAuthorizedException", ex.getErrorCode());
}
// =========================================================================
// USER_AUTH (choice-based) flow
// =========================================================================
@Test
@SuppressWarnings("unchecked")
void initiateAuthWithUserAuthNoPreferredChallengeReturnsSelectChallenge() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
Map<String, Object> result = service.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice"));
assertEquals("SELECT_CHALLENGE", result.get("ChallengeName"));
assertNotNull(result.get("Session"));
List<String> available = (List<String>) result.get("AvailableChallenges");
assertTrue(available.contains("PASSWORD"), "PASSWORD should be available: " + available);
assertTrue(available.contains("PASSWORD_SRP"), "PASSWORD_SRP should be available: " + available);
assertFalse(available.contains("EMAIL_OTP"),
"EMAIL_OTP should not be offered when verification services are not configured");
}
@Test
void initiateAuthWithUserAuthRejectsMissingUsername() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class,
() -> service.initiateAuth(client.getClientId(), "USER_AUTH", Map.of()));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void initiateAuthWithUserAuthRejectsLiteTier() {
UserPool pool = createPoolAndUser();
pool.setUserPoolTier("LITE");
poolStore.put(pool.getId(), pool);
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class, () -> service.initiateAuth(
client.getClientId(), "USER_AUTH", Map.of("USERNAME", "alice")));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void initiateAuthWithUserAuthRejectsAnUnavailablePreferredChallenge() {
// alice has neither a password nor an SRP verifier at this point: not confirmed yet.
UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
service.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "TempPass1!");
AwsException ex = assertThrows(AwsException.class, () -> service.initiateAuth(
client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP")));
assertEquals("InvalidParameterException", ex.getErrorCode());
}
@Test
void initiateAuthWithUserAuthPreferredChallengePasswordThenRespondCompletesAuth() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
assertEquals("PASSWORD", initResult.get("ChallengeName"));
String session = (String) initResult.get("Session");
assertNotNull(session);
Map<String, Object> result = service.respondToAuthChallenge(client.getClientId(), "PASSWORD", session,
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
assertNotNull(result.get("AuthenticationResult"),
"responding to the PASSWORD challenge with the right password should issue tokens");
}
@Test
void initiateAuthWithUserAuthPreferredChallengePasswordSrpThenRespondReturnsPasswordVerifier() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD_SRP"));
assertEquals("PASSWORD_SRP", initResult.get("ChallengeName"));
String session = (String) initResult.get("Session");
Map<String, Object> result = service.respondToAuthChallenge(client.getClientId(), "PASSWORD_SRP", session,
Map.of("USERNAME", "alice", "SRP_A", "ABCDEF1234567890"));
assertEquals("PASSWORD_VERIFIER", result.get("ChallengeName"),
"responding to PASSWORD_SRP with SRP_A should hand off to the existing SRP flow");
}
@Test
@SuppressWarnings("unchecked")
void selectChallengeWithPasswordAnswerAndPasswordCompletesInOneRoundTrip() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice"));
String session = (String) initResult.get("Session");
Map<String, Object> result = service.respondToAuthChallenge(client.getClientId(), "SELECT_CHALLENGE",
session, Map.of("USERNAME", "alice", "ANSWER", "PASSWORD", "PASSWORD", "Perm1234!"));
assertNotNull(result.get("AuthenticationResult"),
"selecting PASSWORD with the password already attached should complete sign-in immediately");
}
@Test
void selectChallengeWithPasswordSrpAnswerAndSrpAReturnsPasswordVerifier() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice"));
String session = (String) initResult.get("Session");
Map<String, Object> result = service.respondToAuthChallenge(client.getClientId(), "SELECT_CHALLENGE",
session, Map.of("USERNAME", "alice", "ANSWER", "PASSWORD_SRP", "SRP_A", "ABCDEF1234567890"));
assertEquals("PASSWORD_VERIFIER", result.get("ChallengeName"));
}
@Test
void respondToAuthChallengeRejectsPasswordWithNoSessionEverIssued() {
// This is the bypass hectorvent flagged: without a tracked session, RespondToAuthChallenge
// would accept any USERNAME/PASSWORD pair with ChallengeName=PASSWORD and never run
// handleUserAuth's tier gate or availability check at all.
UserPool pool = createPoolAndUser();
pool.setUserPoolTier("LITE");
poolStore.put(pool.getId(), pool);
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(
client.getClientId(), "PASSWORD", "made-up-session",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("NotAuthorizedException", ex.getErrorCode());
}
@Test
void respondToAuthChallengeRejectsPasswordWithNullSession() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(
client.getClientId(), "PASSWORD", null,
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("NotAuthorizedException", ex.getErrorCode());
}
@Test
void respondToAuthChallengeRejectsSelectChallengeWithNoSessionEverIssued() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(
client.getClientId(), "SELECT_CHALLENGE", "made-up-session",
Map.of("USERNAME", "alice", "ANSWER", "PASSWORD", "PASSWORD", "Perm1234!")));
assertEquals("NotAuthorizedException", ex.getErrorCode());
}
@Test
void respondToAuthChallengeRejectsASessionIssuedForADifferentChallenge() {
// A session minted for SELECT_CHALLENGE must not be redeemable against PASSWORD directly;
// that would let a caller answer PASSWORD without ever going through SELECT_CHALLENGE's
// requireSignInEligible/availableUserAuthChallenges checks.
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice"));
assertEquals("SELECT_CHALLENGE", initResult.get("ChallengeName"));
String session = (String) initResult.get("Session");
AwsException ex = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(
client.getClientId(), "PASSWORD", session,
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("NotAuthorizedException", ex.getErrorCode());
}
@Test
void respondToAuthChallengeRejectsASessionAlreadyConsumed() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
String session = (String) initResult.get("Session");
Map<String, Object> first = service.respondToAuthChallenge(client.getClientId(), "PASSWORD", session,
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
assertNotNull(first.get("AuthenticationResult"));
AwsException ex = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(
client.getClientId(), "PASSWORD", session,
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("NotAuthorizedException", ex.getErrorCode(), "a consumed session must not be replayable");
}
@Test
void respondToAuthChallengeRejectsASessionRedeemedAgainstADifferentClient() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
UserPoolClient otherClient = service.createUserPoolClient(pool.getId(), "other", false, false,
List.of(), List.of());
Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
String session = (String) initResult.get("Session");
AwsException ex = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(
otherClient.getClientId(), "PASSWORD", session,
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("NotAuthorizedException", ex.getErrorCode());
}
@Test
void adminInitiateAuthWithUserAuthPreferredChallengePasswordWorks() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
Map<String, Object> initResult = service.adminInitiateAuth(pool.getId(), client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "PASSWORD"));
assertEquals("PASSWORD", initResult.get("ChallengeName"));
String session = (String) initResult.get("Session");
Map<String, Object> result = service.adminRespondToAuthChallenge(pool.getId(), client.getClientId(),
"PASSWORD", session, Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
assertNotNull(result.get("AuthenticationResult"));
}
@Test
@SuppressWarnings("unchecked")
void initiateAuthWithUserAuthOffersEmailOtpWhenVerificationIsConfiguredAndEmailVerified() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any()))
.thenReturn("654321");
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
acmService,
verificationCodeService,
messageDispatcher,
mock(TlsCertificateManager.class)
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
UserPoolClient client = serviceWithVerification.createUserPoolClient(pool.getId(), "c",
false, false, List.of(), List.of());
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("email", "alice@example.com", "email_verified", "true"), "TempPass1!");
serviceWithVerification.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
Map<String, Object> initResult = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice"));
List<String> available = (List<String>) initResult.get("AvailableChallenges");
assertTrue(available.contains("EMAIL_OTP"), "EMAIL_OTP should be offered for a verified email: " + available);
Map<String, Object> challenge = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP"));
assertEquals("EMAIL_OTP", challenge.get("ChallengeName"));
Map<String, String> params = (Map<String, String>) challenge.get("ChallengeParameters");
assertEquals("EMAIL", params.get("CODE_DELIVERY_DELIVERY_MEDIUM"));
assertTrue(params.get("CODE_DELIVERY_DESTINATION").contains("***"),
"the destination email should be masked: " + params.get("CODE_DELIVERY_DESTINATION"));
verify(messageDispatcher).dispatch(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP),
eq("654321"), eq(List.of("EMAIL")), any());
String session = (String) challenge.get("Session");
Map<String, Object> result = serviceWithVerification.respondToAuthChallenge(
client.getClientId(), "EMAIL_OTP", session,
Map.of("USERNAME", "alice", "EMAIL_OTP_CODE", "654321"));
assertNotNull(result.get("AuthenticationResult"),
"responding with the correct EMAIL_OTP_CODE should issue tokens");
verify(verificationCodeService).consume(pool.getId(), "alice", VerificationCode.Purpose.EMAIL_OTP, "654321");
}
@Test
@SuppressWarnings("unchecked")
void initiateAuthWithUserAuthOffersSmsOtpWhenVerificationIsConfiguredAndPhoneVerified() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SMS_OTP), any()))
.thenReturn("135790");
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
acmService,
verificationCodeService,
messageDispatcher,
mock(TlsCertificateManager.class)
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
UserPoolClient client = serviceWithVerification.createUserPoolClient(pool.getId(), "c",
false, false, List.of(), List.of());
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("phone_number", "+15551234567", "phone_number_verified", "true"), "TempPass1!");
serviceWithVerification.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
Map<String, Object> initResult = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice"));
List<String> available = (List<String>) initResult.get("AvailableChallenges");
assertTrue(available.contains("SMS_OTP"), "SMS_OTP should be offered for a verified phone: " + available);
Map<String, Object> challenge = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "SMS_OTP"));
assertEquals("SMS_OTP", challenge.get("ChallengeName"));
Map<String, String> params = (Map<String, String>) challenge.get("ChallengeParameters");
assertEquals("SMS", params.get("CODE_DELIVERY_DELIVERY_MEDIUM"));
assertTrue(params.get("CODE_DELIVERY_DESTINATION").contains("***"),
"the destination phone number should be masked: " + params.get("CODE_DELIVERY_DESTINATION"));
verify(messageDispatcher).dispatch(any(), any(), eq(VerificationCode.Purpose.SMS_OTP),
eq("135790"), eq(List.of("SMS")), any());
String session = (String) challenge.get("Session");
Map<String, Object> result = serviceWithVerification.respondToAuthChallenge(
client.getClientId(), "SMS_OTP", session,
Map.of("USERNAME", "alice", "SMS_OTP_CODE", "135790"));
assertNotNull(result.get("AuthenticationResult"),
"responding with the correct SMS_OTP_CODE should issue tokens");
verify(verificationCodeService).consume(pool.getId(), "alice", VerificationCode.Purpose.SMS_OTP, "135790");
}
@Test
void respondToEmailOtpChallengeRejectsWrongCode() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any()))
.thenReturn("654321");
doThrow(new VerificationCodeException(VerificationCodeException.Kind.MISMATCH, "nope"))
.when(verificationCodeService).consume(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP),
eq("000000"));
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
acmService,
verificationCodeService,
messageDispatcher,
mock(TlsCertificateManager.class)
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
UserPoolClient client = serviceWithVerification.createUserPoolClient(pool.getId(), "c",
false, false, List.of(), List.of());
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("email", "alice@example.com", "email_verified", "true"), "TempPass1!");
serviceWithVerification.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
Map<String, Object> challenge = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP"));
String session = (String) challenge.get("Session");
AwsException ex = assertThrows(AwsException.class, () -> serviceWithVerification.respondToAuthChallenge(
client.getClientId(), "EMAIL_OTP", session,
Map.of("USERNAME", "alice", "EMAIL_OTP_CODE", "000000")));
assertEquals("CodeMismatchException", ex.getErrorCode());
}
@Test
void initiateAuthWithUserAuthRejectsMissingSecretHashWhenClientHasSecret() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "c", true, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class, () -> service.initiateAuth(
client.getClientId(), "USER_AUTH", Map.of("USERNAME", "alice")));
assertEquals("InvalidParameterException", ex.getErrorCode());
assertTrue(ex.getMessage().contains("SECRET_HASH"));
}
@Test
void issueOtpChallengeSurfacesRateLimitInsteadOfAGenericDeliveryFailure() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any()))
.thenThrow(new VerificationCodeException(
VerificationCodeException.Kind.RATE_LIMIT, "Attempt limit exceeded"));
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
acmService,
verificationCodeService,
messageDispatcher,
mock(TlsCertificateManager.class)
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
UserPoolClient client = serviceWithVerification.createUserPoolClient(pool.getId(), "c",
false, false, List.of(), List.of());
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("email", "alice@example.com", "email_verified", "true"), "TempPass1!");
serviceWithVerification.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
AwsException ex = assertThrows(AwsException.class, () -> serviceWithVerification.initiateAuth(
client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP")));
assertEquals("LimitExceededException", ex.getErrorCode(),
"a rate-limited code issue must surface as LimitExceededException, not a generic "
+ "InternalErrorException that hides the real cause");
verify(messageDispatcher, never()).dispatch(any(), any(), any(), any(), any(), any());
}
@Test
void issueOtpChallengeInvalidatesTheIssuedCodeWhenDispatchFails() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any()))
.thenReturn("777888");
doThrow(new RuntimeException("SES unavailable")).when(messageDispatcher)
.dispatch(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), eq("777888"), any(), any());
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
acmService,
verificationCodeService,
messageDispatcher,
mock(TlsCertificateManager.class)
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
UserPoolClient client = serviceWithVerification.createUserPoolClient(pool.getId(), "c",
false, false, List.of(), List.of());
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("email", "alice@example.com", "email_verified", "true"), "TempPass1!");
serviceWithVerification.adminSetUserPassword(pool.getId(), "alice", "Perm1234!", true);
AwsException ex = assertThrows(AwsException.class, () -> serviceWithVerification.initiateAuth(
client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP")));
assertEquals("InternalErrorException", ex.getErrorCode());
// The stored code must be invalidated, or the rate limiter would block a retry for a
// code the user never actually received.
verify(verificationCodeService).invalidatePrevious(pool.getId(), "alice", VerificationCode.Purpose.EMAIL_OTP);
}
// =========================================================================
// Issue #228 — AccessToken contains client_id claim
// =========================================================================
@@ -92,6 +92,24 @@ class CognitoMessageDispatcherTest {
verifyNoInteractions(ses);
}
@Test
void dispatch_smsOtpFlow_usesSmsAuthenticationMessageTemplate() {
// Per AWS: SmsAuthenticationMessage covers "SMS OTP and MFA authentication", not just MFA.
UserPool pool = pool(Map.of("SmsMessage", "Signup: {####}"));
pool.setSmsAuthenticationMessage("Auth code: {####}");
CognitoUser user = user("alice@example.com", "+5215551234567");
dispatcher.dispatch(pool, user, VerificationCode.Purpose.SMS_OTP,
"654321", List.of("SMS"));
verify(sns).publish(
isNull(), isNull(),
eq("+5215551234567"),
eq("Auth code: 654321"),
isNull(), isNull(), eq("us-east-1"));
verifyNoInteractions(ses);
}
@Test
void dispatch_emptyTemplate_usesDefaults() {
UserPool pool = pool(Map.of());