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

@@ -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;