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

+11 -5
View File
@@ -197,12 +197,18 @@ further divergences, both deliberate:
## Supported AuthFlow Values
`InitiateAuth` accepts `USER_PASSWORD_AUTH`, `USER_SRP_AUTH`, `CUSTOM_AUTH`, `REFRESH_TOKEN_AUTH` and
`REFRESH_TOKEN`. `AdminInitiateAuth` accepts `ADMIN_USER_PASSWORD_AUTH`, `ADMIN_NO_SRP_AUTH`,
`ADMIN_USER_SRP_AUTH`, `USER_PASSWORD_AUTH`, `CUSTOM_AUTH`, `REFRESH_TOKEN_AUTH` and `REFRESH_TOKEN`.
`InitiateAuth` accepts `USER_PASSWORD_AUTH`, `USER_SRP_AUTH`, `CUSTOM_AUTH`, `USER_AUTH`,
`REFRESH_TOKEN_AUTH` and `REFRESH_TOKEN`. `AdminInitiateAuth` accepts `ADMIN_USER_PASSWORD_AUTH`,
`ADMIN_NO_SRP_AUTH`, `ADMIN_USER_SRP_AUTH`, `USER_PASSWORD_AUTH`, `CUSTOM_AUTH`, `USER_AUTH`,
`REFRESH_TOKEN_AUTH` and `REFRESH_TOKEN`.
Any other `AuthFlow` value, including the choice-based `USER_AUTH` flow, is rejected with
`InvalidParameterException` and no tokens are issued. `USER_AUTH` is not implemented yet.
`USER_AUTH` is the choice-based flow: with no `PREFERRED_CHALLENGE` it returns
`ChallengeName=SELECT_CHALLENGE` and an `AvailableChallenges` list drawn from what the user has
configured (`PASSWORD`, `PASSWORD_SRP`, `EMAIL_OTP`, `SMS_OTP`); with one, it goes straight to that
challenge. It requires the user pool's tier to be Essentials or higher. `WEB_AUTHN` and the
`ConfirmSignUp` session as a first-factor shortcut are not implemented yet.
Any other `AuthFlow` value is rejected with `InvalidParameterException` and no tokens are issued.
## User Attribute Update Verification
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
@@ -49,11 +50,21 @@ final class CognitoAuthFlowHandler {
private final RegionResolver regionResolver;
private final ConcurrentHashMap<String, SrpSession> srpSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, CustomAuthSession> customAuthSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, UserAuthSession> userAuthSessions = new ConcurrentHashMap<>();
private record SrpSession(String userPoolId, String username, String clientId,
String aHex, String bHex, String bPublicHex,
String secretBlockBase64, Map<String, String> clientMetadata) {}
/**
* Correlates a USER_AUTH challenge response back to the InitiateAuth/RespondToAuthChallenge
* call that issued it, the same way {@link SrpSession} and {@link CustomAuthSession} do for
* their own challenges. Without this, RespondToAuthChallenge would accept any USERNAME and
* factor answer with no session at all, bypassing handleUserAuth's tier gate and letting a
* caller trigger an OTP send without ever starting a flow.
*/
private record UserAuthSession(String userPoolId, String username, String clientId, String challengeName) {}
static final class CustomAuthSession {
final String userPoolId;
final String username;
@@ -88,6 +99,7 @@ final class CognitoAuthFlowHandler {
case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, client, authParameters, clientMetadata);
case "USER_SRP_AUTH" -> handleUserSrpAuth(pool, client, authParameters, clientMetadata);
case "CUSTOM_AUTH" -> handleCustomAuth(pool, client, authParameters, clientMetadata);
case "USER_AUTH" -> handleUserAuth(pool, client, authParameters, clientMetadata);
default -> throw unsupportedAuthFlow(authFlow);
};
}
@@ -116,6 +128,7 @@ final class CognitoAuthFlowHandler {
case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, client, authParameters, clientMetadata);
case "ADMIN_USER_SRP_AUTH" -> handleUserSrpAuth(pool, client, authParameters, clientMetadata);
case "CUSTOM_AUTH" -> handleCustomAuth(pool, client, authParameters, clientMetadata);
case "USER_AUTH" -> handleUserAuth(pool, client, authParameters, clientMetadata);
default -> throw unsupportedAuthFlow(authFlow);
};
}
@@ -148,6 +161,21 @@ final class CognitoAuthFlowHandler {
if ("CUSTOM_CHALLENGE".equals(challengeName)) {
return handleCustomChallenge(pool, client, session, responses, clientMetadata);
}
if ("SELECT_CHALLENGE".equals(challengeName)) {
return handleSelectChallenge(pool, client, session, responses, clientMetadata);
}
if ("PASSWORD".equals(challengeName)) {
consumeUserAuthSession(pool, client, session, "PASSWORD");
return authenticateWithPassword(pool, client, responses, clientMetadata);
}
if ("PASSWORD_SRP".equals(challengeName)) {
consumeUserAuthSession(pool, client, session, "PASSWORD_SRP");
return handleUserSrpAuth(pool, client, responses, clientMetadata);
}
if ("EMAIL_OTP".equals(challengeName) || "SMS_OTP".equals(challengeName)) {
consumeUserAuthSession(pool, client, session, challengeName);
return handleOtpChallengeResponse(pool, client, challengeName, responses, clientMetadata);
}
if ("NEW_PASSWORD_REQUIRED".equals(challengeName)) {
String username = responses.get("USERNAME");
String newPassword = responses.get("NEW_PASSWORD");
@@ -434,6 +462,193 @@ final class CognitoAuthFlowHandler {
return result;
}
// ──────────────────────────── USER_AUTH (choice-based) ────────────────────────────
/**
* Entry point for the {@code USER_AUTH} choice-based flow. {@code PASSWORD} and
* {@code PASSWORD_SRP} reuse {@link #authenticateWithPassword} and {@link #handleUserSrpAuth}
* unchanged rather than reverifying the same credential a second way.
*
* <p>Not implemented: {@code WEB_AUTHN} and the {@code ConfirmSignUp} session as a
* first-factor shortcut (tracked as follow-ups on the issue this was added for).
*/
private Map<String, Object> handleUserAuth(UserPool pool, UserPoolClient client,
Map<String, String> params, Map<String, String> clientMetadata) {
// AWS requires the Essentials tier or higher for USER_AUTH.
if ("LITE".equals(pool.getUserPoolTier())) {
throw new AwsException("InvalidParameterException",
"USER_AUTH requires the user pool to be in the Essentials tier or higher", 400);
}
String username = params.get("USERNAME");
if (username == null) {
throw new AwsException("InvalidParameterException", "USERNAME is required", 400);
}
validateSecretHash(client, params, username);
CognitoUser user = service.adminGetUser(pool.getId(), username);
requireSignInEligible(user);
List<String> available = availableUserAuthChallenges(user);
if (available.isEmpty()) {
throw new AwsException("NotAuthorizedException",
"No USER_AUTH challenge is available for this user", 400);
}
String preferred = params.get("PREFERRED_CHALLENGE");
if (preferred == null) {
return userAuthChallengeResponse(pool, client, user, "SELECT_CHALLENGE", available,
Map.of("USERNAME", user.getUsername()));
}
return startUserAuthChallenge(pool, client, user, preferred, available, params, clientMetadata);
}
/**
* Responds to {@code SELECT_CHALLENGE}: {@code ANSWER} names the chosen factor. If the same
* request already carries that factor's answer ({@code PASSWORD} or {@code SRP_A}), this
* completes in one round trip instead of two.
*/
private Map<String, Object> handleSelectChallenge(UserPool pool, UserPoolClient client, String session,
Map<String, String> responses,
Map<String, String> clientMetadata) {
consumeUserAuthSession(pool, client, session, "SELECT_CHALLENGE");
String username = responses.get("USERNAME");
String answer = responses.get("ANSWER");
if (username == null || answer == null) {
throw new AwsException("InvalidParameterException", "USERNAME and ANSWER are required", 400);
}
validateSecretHash(client, responses, username);
CognitoUser user = service.adminGetUser(pool.getId(), username);
requireSignInEligible(user);
List<String> available = availableUserAuthChallenges(user);
return startUserAuthChallenge(pool, client, user, answer, available, responses, clientMetadata);
}
private Map<String, Object> startUserAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user,
String challenge, List<String> available,
Map<String, String> params, Map<String, String> clientMetadata) {
if (!available.contains(challenge)) {
throw new AwsException("InvalidParameterException",
challenge + " is not an available challenge for this user", 400);
}
return switch (challenge) {
case "PASSWORD" -> params.containsKey("PASSWORD")
? authenticateWithPassword(pool, client, params, clientMetadata)
: userAuthChallengeResponse(pool, client, user, "PASSWORD", available,
Map.of("USERNAME", user.getUsername()));
case "PASSWORD_SRP" -> params.containsKey("SRP_A")
? handleUserSrpAuth(pool, client, params, clientMetadata)
: userAuthChallengeResponse(pool, client, user, "PASSWORD_SRP", available,
Map.of("USERNAME", user.getUsername()));
case "EMAIL_OTP" -> issueOtpChallenge(pool, client, user, "EMAIL_OTP", "email", "EMAIL",
available, clientMetadata);
case "SMS_OTP" -> issueOtpChallenge(pool, client, user, "SMS_OTP", "phone_number", "SMS",
available, clientMetadata);
default -> throw new AwsException("InvalidParameterException",
challenge + " is not a supported challenge", 400);
};
}
private Map<String, Object> issueOtpChallenge(UserPool pool, UserPoolClient client, CognitoUser user,
String challengeName, String attributeName, String deliveryMedium,
List<String> available, Map<String, String> clientMetadata) {
firePreAuthentication(pool, client, user, null, clientMetadata, false);
VerificationCode.Purpose purpose = "EMAIL_OTP".equals(challengeName)
? VerificationCode.Purpose.EMAIL_OTP : VerificationCode.Purpose.SMS_OTP;
Map<String, Object> customMessage = fireCustomMessage(pool, client, user, "CustomMessage_Authentication");
Map<String, String> challengeParams = new HashMap<>(
service.issueSignInOtp(pool, user, purpose, attributeName, deliveryMedium, customMessage));
challengeParams.put("USERNAME", user.getUsername());
return userAuthChallengeResponse(pool, client, user, challengeName, available, challengeParams);
}
private Map<String, Object> handleOtpChallengeResponse(UserPool pool, UserPoolClient client, String challengeName,
Map<String, String> responses,
Map<String, String> clientMetadata) {
String username = responses.get("USERNAME");
boolean isEmail = "EMAIL_OTP".equals(challengeName);
String codeParam = isEmail ? "EMAIL_OTP_CODE" : "SMS_OTP_CODE";
String code = responses.get(codeParam);
if (username == null || code == null) {
throw new AwsException("InvalidParameterException", "USERNAME and " + codeParam + " are required", 400);
}
validateSecretHash(client, responses, username);
CognitoUser user = service.adminGetUser(pool.getId(), username);
requireSignInEligible(user);
service.consumeSignInOtp(pool.getId(), user.getUsername(),
isEmail ? VerificationCode.Purpose.EMAIL_OTP : VerificationCode.Purpose.SMS_OTP, code);
if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {
return buildNewPasswordRequiredChallenge(pool, client, user);
}
Map<String, Object> result = new HashMap<>();
result.put("AuthenticationResult",
issueTokens(pool, client, user, "TokenGeneration_Authentication", clientMetadata));
return result;
}
private Map<String, Object> userAuthChallengeResponse(UserPool pool, UserPoolClient client, CognitoUser user,
String challengeName, List<String> available,
Map<String, String> challengeParameters) {
String session = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId());
userAuthSessions.put(session,
new UserAuthSession(pool.getId(), user.getUsername(), client.getClientId(), challengeName));
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", challengeName);
result.put("Session", session);
result.put("ChallengeParameters", challengeParameters);
result.put("AvailableChallenges", available);
return result;
}
/**
* Validates that {@code session} was issued by {@link #userAuthChallengeResponse} for
* {@code expectedChallenge} against this same pool and client, and consumes it so it cannot
* be replayed against a second RespondToAuthChallenge call.
*/
private void consumeUserAuthSession(UserPool pool, UserPoolClient client, String session,
String expectedChallenge) {
UserAuthSession state = session == null ? null : userAuthSessions.remove(session);
if (state == null || !expectedChallenge.equals(state.challengeName())) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
if (!state.userPoolId().equals(pool.getId()) || !state.clientId().equals(client.getClientId())) {
throw new AwsException("NotAuthorizedException", "Session does not match client", 400);
}
}
/** The set of USER_AUTH challenges this user currently qualifies for. */
private List<String> availableUserAuthChallenges(CognitoUser user) {
List<String> available = new ArrayList<>();
if (user.getPasswordHash() != null) {
available.add("PASSWORD");
}
if (user.getSrpVerifier() != null) {
available.add("PASSWORD_SRP");
}
Map<String, String> attrs = user.getAttributes();
if (attrs != null && service.verificationServicesConfigured()) {
if (Boolean.parseBoolean(attrs.getOrDefault("email_verified", "false")) && attrs.get("email") != null) {
available.add("EMAIL_OTP");
}
if (Boolean.parseBoolean(attrs.getOrDefault("phone_number_verified", "false"))
&& attrs.get("phone_number") != null) {
available.add("SMS_OTP");
}
}
return available;
}
private void requireSignInEligible(CognitoUser user) {
if (!user.isEnabled()) {
throw new AwsException("UserNotConfirmedException", "User is disabled", 400);
}
if ("RESET_REQUIRED".equals(user.getUserStatus())) {
throw new AwsException("PasswordResetRequiredException", "Password reset required", 400);
}
if ("UNCONFIRMED".equals(user.getUserStatus())) {
throw new AwsException("UserNotConfirmedException", "User is not confirmed", 400);
}
}
// ──────────────────────────── CUSTOM_AUTH ────────────────────────────
private Map<String, Object> handleCustomAuth(UserPool pool, UserPoolClient client,
@@ -4447,6 +4447,55 @@ public class CognitoService implements ResourceProvider {
};
}
/** Whether the sign-in verification-code path (EMAIL_OTP/SMS_OTP under USER_AUTH) is wired up. */
boolean verificationServicesConfigured() {
return verificationCodeService != null && messageDispatcher != null;
}
/**
* Issues and delivers a one-time code for a USER_AUTH EMAIL_OTP/SMS_OTP challenge, mirroring
* the SignUp/ForgotPassword code-delivery path. Returns the masked CODE_DELIVERY challenge
* parameters for the InitiateAuth/RespondToAuthChallenge response.
*/
Map<String, String> issueSignInOtp(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
String attributeName, String deliveryMedium, Map<String, Object> customMessageResponse) {
ensureVerificationWiring();
String destination = user.getAttributes().get(attributeName);
String code;
try {
code = verificationCodeService.issue(pool.getId(), user.getUsername(), purpose, Duration.ofMinutes(5));
messageDispatcher.dispatch(pool, user, purpose, code, List.of(deliveryMedium), customMessageResponse);
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
} catch (RuntimeException e) {
// The code was already issued and stored before dispatch failed; invalidate it so
// the rate limiter doesn't block an immediate retry for a code the user never
// received, matching how signUp's rollback treats the same failure shape.
verificationCodeService.invalidatePrevious(pool.getId(), user.getUsername(), purpose);
LOG.warnv(e, "Failed to deliver a USER_AUTH {0} code for pool {1}: {2}",
purpose, pool.getId(), e.getMessage());
// Unlike SignUp/ResendConfirmationCode/ForgotPassword, none of InitiateAuth,
// AdminInitiateAuth, RespondToAuthChallenge or AdminRespondToAuthChallenge declare
// CodeDeliveryFailureException; all four declare InternalErrorException instead.
throw new AwsException("InternalErrorException", "Failed to deliver the message.", 500);
}
String masked = "email".equals(attributeName) ? maskEmail(destination) : maskPhoneNumber(destination);
Map<String, String> details = new LinkedHashMap<>();
details.put("CODE_DELIVERY_DELIVERY_MEDIUM", deliveryMedium);
details.put("CODE_DELIVERY_DESTINATION", masked);
return details;
}
/** Consumes a USER_AUTH EMAIL_OTP/SMS_OTP code, translating a wrong/expired code to the AWS shape. */
void consumeSignInOtp(String userPoolId, String username, VerificationCode.Purpose purpose, String code) {
ensureVerificationWiring();
try {
verificationCodeService.consume(userPoolId, username, purpose, code);
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
}
}
private boolean matchesAliasOrUsernameAttribute(UserPool pool, CognitoUser user,
String username) {
if (username.equals(user.getAttributes().get("sub"))) {
@@ -109,13 +109,14 @@ public final class CognitoMessageDispatcher {
/**
* 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.
* {@code SmsAuthenticationMessage} is a top-level UserPool attribute, NOT part of the
* VerificationMessageTemplate, and per AWS covers both MFA and USER_AUTH's SMS_OTP. 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) {
if (purpose == VerificationCode.Purpose.SMS_MFA || purpose == VerificationCode.Purpose.SMS_OTP) {
return pool.getSmsAuthenticationMessage();
}
Object sms = template.get("SmsMessage");
@@ -22,7 +22,11 @@ public final class VerificationCode {
// Attribute verification is keyed per attribute so email and phone_number codes
// rate-limit and overwrite independently, matching AWS.
EMAIL_ATTRIBUTE_VERIFICATION,
PHONE_ATTRIBUTE_VERIFICATION
PHONE_ATTRIBUTE_VERIFICATION,
// USER_AUTH choice-based sign-in codes (distinct from SMS_MFA/attribute verification
// so a sign-in code can't be replayed against those other purposes' consume() calls).
EMAIL_OTP,
SMS_OTP
}
private final String userPoolId;
@@ -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());