feat(cognito): offer an email code on managed login (#4765)

* feat(cognito): offer an email code on managed login

Managed login could not sign in a user of a passwordless pool: /login was
a username and password form only. When the pool's SignInPolicy allows
EMAIL_OTP and the client allows USER_AUTH, the page now asks for the
username first, offers the factors that user has (PASSWORD and
EMAIL_OTP), and for EMAIL_OTP sends a code through the USER_AUTH
EMAIL_OTP challenge, so it arrives in Floci's SES. A correct code signs
the user in as the password does: a session cookie and a redirect to the
callback with code and state, redeemed at /oauth2/token with PKCE. The
USER_AUTH session travels in a hidden field. A wrong code shows the code
field again and keeps the session for another try. An unknown user is
asked for a code like anyone else, but nothing is sent and no code signs
them in. Pools and clients without choice-based sign-in keep the
password form unchanged.

USER_AUTH ignored the sign-in policy for existing users, so a pool that
allowed only EMAIL_OTP still offered PASSWORD and PASSWORD_SRP. The
available challenges are now narrowed to AllowedFirstAuthFactors, whose
PASSWORD covers both password challenges, and a PREFERRED_CHALLENGE or
SELECT_CHALLENGE answer outside it is refused as an unavailable one is.
A pool with no sign-in policy is not narrowed.

/oauth2/authorize now carries login_hint to /login, on Floci's host and
on a custom domain, and /login fills the username field with it, as AWS
documents.

Refs #4759

* fix(cognito): harden the managed login email-code step

The step after the username told accounts apart. The page looked each
user up, so a user with one factor skipped the choice others got, a user
who could not sign in was told why, and the USER_AUTH session in the code
form named the user it was for. The page now offers the policy's factors
to every username, and a user who is unknown, cannot sign in, or has no
verified email gets the same code field, with no message sent. Why a user
cannot sign in shows only after a correct code. Asking again within the
resend limit shows the code field for the code already sent, instead of
an error only a real user could get. USER_AUTH session tokens no longer
carry the username.

The same code could sign in twice: requests answering one session with
its code at once could all pass the check before any removed the
session. The code is now checked and the session spent under the lock
that every read and removal of a session takes, RespondToAuthChallenge's
included, so one request signs in and the others find the session spent.

A correct code spends the session, so a failure after it, such as a
failing PostAuthentication trigger or a user who cannot sign in, now goes
back to the username step with the reason, instead of showing a code
field that can no longer work.

Refs #4759

* fix(cognito): redeem an email or SMS sign-in code once across sessions

Every live EMAIL_OTP or SMS_OTP session of a user takes the user's one
sign-in code, and the code store reads a code before it deletes it. Two
of a user's sessions answered with the code at once through
RespondToAuthChallenge could both pass the check and both sign in. Such
a second session is easier to come by now that asking the sign-in page
for a code again within the resend limit opens one. RespondToAuthChallenge
now checks the code under the lock the sign-in page checks it under, so
one session signs in and the other gets CodeMismatchException. Nothing
held under that lock calls a Lambda trigger.

Refs #4759

* fix(cognito): redeem verification codes under a per-user lock

Redeeming an email or SMS sign-in code held the lock shared by every
USER_AUTH session while the code store read and wrote the code, which in
persistent storage mode is a disk write, so one user's slow redemption
held up other users' sign-ins. That lock now guards the session maps
alone.

The code store now redeems a code once by itself: consume() takes a lock
striped by the code's pool, user and purpose, and calls nothing but the
store under it, so no trigger runs and no other lock is taken there.
Sign-up, password reset and attribute verification codes gain the same:
each is redeemed once and every wrong attempt counts, where concurrent
requests could redeem one twice or undercount its attempts before. Of
several requests answering a user's sessions with one code at once, one
signs in and the rest get CodeMismatchException. The sign-in page looks
its session up, redeems the code, then removes the session, and still
signs in if RespondToAuthChallenge spent the session meanwhile, since
only one of them can have redeemed the code.

Refs #4759

* fix(cognito): issue and invalidate verification codes in turn with redemption

Only consume() took the code store's per-key lock, so redeeming the old
code could read it, let a resend write the new one, and then delete the
new one, leaving the user a code that never works. issue() and the two
invalidations now take the same stripe, so each of them and consume()
see the code as the one before left it.

Refs #4759

* fix(cognito): offer the choice for a preferred challenge the user cannot take

USER_AUTH refused a PREFERRED_CHALLENGE that the sign-in policy leaves
out or the user has not set up with InvalidParameterException. AWS
answers it as it answers InitiateAuth without one: SELECT_CHALLENGE and
the challenges the user can take, which is what clients expect on the
main sign-in path. Floci now does the same, and refuses only a name
Cognito does not support, with AWS's message listing the ones it does.
An unknown user whose client prevents user existence errors gets the
same answer as a known user: the preferred challenge when the policy
allows it, and the choice when it does not. A SELECT_CHALLENGE answer
outside the choice is still refused.

Refs #4759

* fix(cognito): default a pool's sign-in policy to PASSWORD alone

AWS's DescribeUserPool reports a SignInPolicy of
{"AllowedFirstAuthFactors": ["PASSWORD"]} for a pool created without one,
on any tier, and USER_AUTH offers that pool's users password challenges
alone. Floci stored no policy and did not narrow such a pool, so it
offered EMAIL_OTP and SMS_OTP that AWS would not. CreateUserPool now
stores the default, UpdateUserPool keeps the policy when the request
omits Policies and puts the default back when its Policies has no
SignInPolicy, and a pool persisted without one is treated as PASSWORD
alone.

Refs #4759

* test(cognito): pass login_hint in the scope tests from main
This commit is contained in:
jwoa95 authored and GitHub committed 2026-10-01 16:40:31 -04:00
1 parent f1d718cae2
commit 45b7be9362
12 files changed
+1714 -104

No files matched your search

@@ -55,6 +55,12 @@ final class CognitoAuthFlowHandler {
/** The message of a wrong password, which managed login also shows for an unknown user. */
static final String INCORRECT_CREDENTIALS = "Incorrect username or password";
static final int MAX_USER_AUTH_SESSIONS_PER_PARTITION = 4_096;
/** The challenges a USER_AUTH PREFERRED_CHALLENGE may name, in the order AWS lists them when refusing another. */
private static final List<String> PREFERRED_CHALLENGES =
List.of("PASSWORD", "PASSWORD_SRP", "SMS_OTP", "EMAIL_OTP", "WEB_AUTHN");
private static final String CODE_MISMATCH = "Invalid verification code provided, please try again.";
private static final String MANAGED_LOGIN_NEW_PASSWORD = "This user must set a new password, which this "
+ "sign-in page does not support. Set a permanent password with AdminSetUserPassword.";
private final CognitoService service;
private final LambdaService lambdaService;
@@ -63,6 +69,10 @@ final class CognitoAuthFlowHandler {
private final ConcurrentHashMap<String, SrpSession> srpSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, CustomAuthToken> customAuthSessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, TotpSession> totpSessions = new ConcurrentHashMap<>();
/**
* Guards both USER_AUTH session maps and nothing else: no storage I/O or Lambda trigger runs under it,
* so one user's sign-in cannot hold up another's. The code store redeems sign-in codes, once, outside it.
*/
private final Object userAuthSessionLock = new Object();
private final LinkedHashMap<String, UserAuthSession> userAuthSessions = new LinkedHashMap<>();
private final LinkedHashMap<String, UserAuthSession> simulatedUserAuthSessions = new LinkedHashMap<>();
@@ -500,8 +510,99 @@ final class CognitoAuthFlowHandler {
CognitoUser authenticateManagedLogin(UserPool pool, UserPoolClient client, String username, String password) {
CognitoUser user = verifyPassword(pool, client, username, password, Map.of());
if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {
throw new AwsException("NotAuthorizedException", "This user must set a new password, which this "
+ "sign-in page does not support. Set a permanent password with AdminSetUserPassword.", 400);
throw new AwsException("NotAuthorizedException", MANAGED_LOGIN_NEW_PASSWORD, 400);
}
firePostAuthentication(pool, client, user, Map.of(), false);
return user;
}
/**
* The first factors in the pool's sign-in policy when the client can use USER_AUTH, which is what
* managed login's choice-based sign-in may offer. Empty for a Lite pool or a client without
* {@code ALLOW_USER_AUTH}.
*/
List<String> managedLoginFirstFactors(UserPool pool, UserPoolClient client) {
if ("LITE".equals(pool.getUserPoolTier()) || !enabledAuthFlows(client).contains("ALLOW_USER_AUTH")) {
return List.of();
}
return allowedFirstAuthFactors(pool);
}
/**
* Emails {@code username} a code, as answering SELECT_CHALLENGE with EMAIL_OTP does, and returns
* the USER_AUTH session that {@link #completeManagedLoginEmailOtp} answers. A user who is unknown,
* cannot sign in, or has no verified email gets a session that no code completes, and no message,
* so the page answers every username alike. Asking again before a new code may be sent gets a
* session for the code already sent.
*/
String startManagedLoginEmailOtp(UserPool pool, UserPoolClient client, String username) {
CognitoUser user = emailOtpRecipient(pool, username);
if (user == null) {
return (String) userAuthChallengeResponse(pool, client, username, "EMAIL_OTP", null,
Map.of("USERNAME", username), false).get("Session");
}
try {
return (String) startUserAuthChallenge(pool, client, user, "EMAIL_OTP",
allowedUserAuthChallenges(pool, user), false, Map.of(), Map.of()).get("Session");
} catch (AwsException exception) {
if (!"LimitExceededException".equals(exception.getErrorCode())) {
throw exception;
}
// The code sent moments ago is still live, and this session takes it. Refusing would tell
// this user from an unknown one, who is never sent a code and so never reaches the limit.
return (String) userAuthChallengeResponse(pool, client, user, "EMAIL_OTP", null,
Map.of("USERNAME", user.getUsername())).get("Session");
}
}
/**
* The user {@code username} names when an emailed code may sign them in, or null for a user who is
* unknown, cannot sign in, or has no verified email.
*/
private CognitoUser emailOtpRecipient(UserPool pool, String username) {
CognitoUser user;
try {
user = service.adminGetUser(pool.getId(), username);
} catch (AwsException exception) {
if (!"UserNotFoundException".equals(exception.getErrorCode())) {
throw exception;
}
return null;
}
try {
requireSignInEligible(user);
} catch (AwsException expected) {
// Why a user cannot sign in shows only after a correct code, which this user is not sent.
return null;
}
return allowedUserAuthChallenges(pool, user).contains("EMAIL_OTP") ? user : null;
}
/**
* Managed login's answer to its EMAIL_OTP challenge: checks the code and returns the signed-in
* user, issuing no tokens, as {@link #authenticateManagedLogin} does for a password. Unlike
* RespondToAuthChallenge, a wrong or expired code ({@code CodeMismatchException} or
* {@code ExpiredCodeException}) leaves the session for another try, since the page asks again; the
* code itself stops working after too many wrong ones. After any other failure the session is spent
* or gone. Why a user cannot sign in shows only after a correct code.
*/
CognitoUser completeManagedLoginEmailOtp(UserPool pool, UserPoolClient client, String session, String code) {
UserAuthSession state = findUserAuthSession(pool, client, session, "EMAIL_OTP");
if (!state.userExists()) {
throw new AwsException("CodeMismatchException", CODE_MISMATCH, 400);
}
// The code store redeems a code once, so of the requests answering this session, or another of the
// user's sessions, with the code at once, one gets past here and the rest get CodeMismatchException.
service.consumeSignInOtp(pool.getId(), state.username(), VerificationCode.Purpose.EMAIL_OTP, code);
// RespondToAuthChallenge may have spent the session since it was found. The code is what signs in;
// removing the session only stops it being answered again.
synchronized (userAuthSessionLock) {
userAuthSessions.remove(session, state);
}
CognitoUser user = service.adminGetUser(pool.getId(), state.username());
requireSignInEligible(user);
if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {
throw new AwsException("NotAuthorizedException", MANAGED_LOGIN_NEW_PASSWORD, 400);
}
firePostAuthentication(pool, client, user, Map.of(), false);
return user;
@@ -616,6 +717,15 @@ final class CognitoAuthFlowHandler {
return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
/**
* A USER_AUTH session token. Unlike {@link #buildSessionToken} it does not carry the username, or a
* simulated challenge's token would tell an unknown or ineligible user from one who can sign in.
*/
private static String userAuthSessionToken(String poolId, String clientId) {
String raw = poolId + "|" + clientId + "|" + UUID.randomUUID();
return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
private void validateSecretHash(UserPoolClient client, Map<String, String> params, String username) {
String secret = client.getClientSecret();
if (secret == null || secret.isBlank()) return;
@@ -791,6 +901,11 @@ final class CognitoAuthFlowHandler {
throw new AwsException("InvalidParameterException", "USERNAME is required", 400);
}
validateSecretHash(client, params, username);
String preferred = params.get("PREFERRED_CHALLENGE");
if (preferred != null && !PREFERRED_CHALLENGES.contains(preferred)) {
throw new AwsException("InvalidParameterException",
"The preferred challenge must be one of the supported challenges. " + PREFERRED_CHALLENGES, 400);
}
CognitoUser user;
try {
user = service.adminGetUser(pool.getId(), username);
@@ -799,18 +914,19 @@ final class CognitoAuthFlowHandler {
|| !"ENABLED".equals(client.getPreventUserExistenceErrors())) {
throw exception;
}
return simulatedUserAuthChallenge(pool, client, username);
return simulatedUserAuthChallenge(pool, client, username, preferred);
}
requireSignInEligible(user);
List<String> available = availableUserAuthChallenges(user);
List<String> available = allowedUserAuthChallenges(pool, 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) {
// AWS answers a preferred challenge the user cannot take, because the sign-in policy leaves it out
// or the user has not set it up, as it answers none: with the choice of those they can take.
if (preferred == null || !available.contains(preferred)) {
return userAuthChallengeResponse(pool, client, user, "SELECT_CHALLENGE", available,
Map.of("USERNAME", user.getUsername()));
}
@@ -834,7 +950,7 @@ final class CognitoAuthFlowHandler {
validateSecretHash(client, responses, username);
CognitoUser user = service.adminGetUser(pool.getId(), username);
requireSignInEligible(user);
List<String> available = availableUserAuthChallenges(user);
List<String> available = allowedUserAuthChallenges(pool, user);
return startUserAuthChallenge(pool, client, user, answer, available, false, responses, clientMetadata);
}
@@ -922,7 +1038,7 @@ final class CognitoAuthFlowHandler {
String challengeName, List<String> available,
Map<String, String> challengeParameters,
boolean userExists) {
String session = buildSessionToken(pool.getId(), username, client.getClientId());
String session = userAuthSessionToken(pool.getId(), client.getClientId());
synchronized (userAuthSessionLock) {
Instant issuedAt = clock.instant();
// Each entry uses its own client's lifetime, even after a clock rollback.
@@ -962,6 +1078,27 @@ final class CognitoAuthFlowHandler {
state = simulatedUserAuthSessions.remove(session);
}
}
return checkUserAuthSession(pool, client, state, expectedChallenge);
}
/**
* As {@link #consumeUserAuthSession}, but leaves the session in place, for a caller that removes it only
* once its answer is right.
*/
private UserAuthSession findUserAuthSession(UserPool pool, UserPoolClient client, String session,
String expectedChallenge) {
UserAuthSession state;
synchronized (userAuthSessionLock) {
state = session == null ? null : userAuthSessions.get(session);
if (state == null && session != null) {
state = simulatedUserAuthSessions.get(session);
}
}
return checkUserAuthSession(pool, client, state, expectedChallenge);
}
private UserAuthSession checkUserAuthSession(UserPool pool, UserPoolClient client, UserAuthSession state,
String expectedChallenge) {
if (state == null || !expectedChallenge.equals(state.challengeName())) {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
@@ -980,37 +1117,69 @@ final class CognitoAuthFlowHandler {
}
}
private Map<String, Object> simulatedUserAuthChallenge(UserPool pool, UserPoolClient client, String username) {
/**
* The challenge an unknown user gets when the client prevents user existence errors, from the pool's
* allowed factors. A PREFERRED_CHALLENGE is answered as a known user's is: with that challenge when the
* policy allows it, and with SELECT_CHALLENGE when not. Without one, the challenge is picked at random.
*/
private Map<String, Object> simulatedUserAuthChallenge(UserPool pool, UserPoolClient client, String username,
String preferred) {
List<String> available = configuredUserAuthChallenges(pool);
if (available.isEmpty()) {
throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400);
}
String challenge = available.get(ThreadLocalRandom.current().nextInt(available.size()));
String challenge;
if (preferred == null) {
challenge = available.get(ThreadLocalRandom.current().nextInt(available.size()));
} else {
challenge = available.contains(preferred) ? preferred : "SELECT_CHALLENGE";
}
return userAuthChallengeResponse(pool, client, username, challenge, available,
Map.of("USERNAME", username), false);
}
private List<String> configuredUserAuthChallenges(UserPool pool) {
Map<String, Object> policies = pool.getPolicies();
if (policies == null || !(policies.get("SignInPolicy") instanceof Map<?, ?> signInPolicy)) {
return List.of("PASSWORD");
}
Object configuredFactors = signInPolicy.get("AllowedFirstAuthFactors");
if (!(configuredFactors instanceof List<?> factors) || factors.isEmpty()) {
return List.of("PASSWORD");
}
List<String> supported = new ArrayList<>();
for (Object factor : factors) {
if (factor instanceof String name
&& ("PASSWORD".equals(name) || "EMAIL_OTP".equals(name) || "SMS_OTP".equals(name))
&& !supported.contains(name)) {
for (String name : allowedFirstAuthFactors(pool)) {
if ("PASSWORD".equals(name) || "EMAIL_OTP".equals(name) || "SMS_OTP".equals(name)) {
supported.add(name);
}
}
return supported;
}
/**
* The pool's {@code SignInPolicy.AllowedFirstAuthFactors} without duplicates, or {@code PASSWORD} alone
* when it names none: AWS's DescribeUserPool reports {@code ["PASSWORD"]} for a pool created without a
* sign-in policy. Floci now stores that default too, but a pool it persisted earlier may have none.
*/
private static List<String> allowedFirstAuthFactors(UserPool pool) {
Map<String, Object> policies = pool.getPolicies();
if (policies == null || !(policies.get("SignInPolicy") instanceof Map<?, ?> signInPolicy)
|| !(signInPolicy.get("AllowedFirstAuthFactors") instanceof List<?> factors) || factors.isEmpty()) {
return List.of("PASSWORD");
}
List<String> names = new ArrayList<>();
for (Object factor : factors) {
if (factor instanceof String name && !names.contains(name)) {
names.add(name);
}
}
return names;
}
/**
* The USER_AUTH challenges this user qualifies for that the pool's sign-in policy allows. The
* policy's {@code PASSWORD} covers both PASSWORD and PASSWORD_SRP, and a pool with no policy
* allows PASSWORD alone, as AWS's default does.
*/
private List<String> allowedUserAuthChallenges(UserPool pool, CognitoUser user) {
List<String> available = availableUserAuthChallenges(user);
List<String> allowed = allowedFirstAuthFactors(pool);
available.removeIf(challenge -> !allowed.contains("PASSWORD_SRP".equals(challenge) ? "PASSWORD" : challenge));
return available;
}
/** The set of USER_AUTH challenges this user currently qualifies for. */
private List<String> availableUserAuthChallenges(CognitoUser user) {
List<String> available = new ArrayList<>();
@@ -15,8 +15,8 @@ import java.util.List;
import java.util.Optional;
/**
* Managed login for a pool's own users: signs a user in with their password, keeps the browser's
* session, and issues the authorization codes that {@code /oauth2/token} redeems.
* Managed login for a pool's own users: signs a user in with their password or an emailed code, keeps
* the browser's session, and issues the authorization codes that {@code /oauth2/token} redeems.
* {@link CognitoFederationService} does the same for users of an external identity provider.
*/
@ApplicationScoped
@@ -26,6 +26,8 @@ public class CognitoManagedLoginService {
private static final Duration AUTHORIZATION_CODE_LIFETIME = Duration.ofMinutes(5);
/** How long AWS keeps a managed login session. */
static final Duration SESSION_LIFETIME = Duration.ofHours(1);
/** The first factors of choice-based sign-in that the sign-in page offers, in the order it lists them. */
private static final List<String> CHOICE_BASED_FACTORS = List.of("PASSWORD", "EMAIL_OTP");
private static final Logger LOG = Logger.getLogger(CognitoManagedLoginService.class);
@@ -48,7 +50,48 @@ public class CognitoManagedLoginService {
* @throws AwsException when the user cannot sign in, with the reason in its message
*/
public String signIn(UserPoolClient client, String username, String password) {
CognitoUser user = cognitoService.authenticateManagedLogin(client, username, password);
return openSession(client, cognitoService.authenticateManagedLogin(client, username, password));
}
/**
* The factors the sign-in page offers after the username, the same for every username, or an empty
* list when the page is the plain username and password form. Choice-based sign-in applies when the
* pool's sign-in policy allows EMAIL_OTP and the client allows USER_AUTH; the page offers the
* policy's PASSWORD and EMAIL_OTP.
*/
public List<String> choiceBasedFactors(UserPoolClient client) {
List<String> allowed = cognitoService.managedLoginFirstFactors(client);
if (!allowed.contains("EMAIL_OTP")) {
return List.of();
}
return CHOICE_BASED_FACTORS.stream().filter(allowed::contains).toList();
}
/**
* Emails the user a sign-in code through the USER_AUTH EMAIL_OTP challenge. A username that no code
* can sign in, because it is unknown, cannot sign in, or has no verified email, is sent nothing but
* gets a session all the same.
*
* @return the USER_AUTH session that {@link #signInWithEmailCode} answers
*/
public String sendEmailCode(UserPoolClient client, String username) {
return cognitoService.startManagedLoginEmailOtp(client, username);
}
/**
* Signs the user of a USER_AUTH EMAIL_OTP session in with the code they were sent, and opens a
* session for them. Only a wrong or expired code ({@code CodeMismatchException} or
* {@code ExpiredCodeException}) leaves the USER_AUTH session for another try; after any other
* failure it is spent or gone.
*
* @return the session's id, the value of the browser's session cookie
* @throws AwsException when the code is wrong or the user cannot sign in, with the reason in its message
*/
public String signInWithEmailCode(UserPoolClient client, String userAuthSession, String code) {
return openSession(client, cognitoService.completeManagedLoginEmailOtp(client, userAuthSession, code));
}
private String openSession(UserPoolClient client, CognitoUser user) {
return stateStore.putSession(new CognitoManagedLoginSession(
client.getUserPoolId(), user.getUsername(), clock.instant().plus(SESSION_LIFETIME)));
}
@@ -94,9 +94,10 @@ public class CognitoOAuthController {
@QueryParam("state") String relyingPartyState,
@QueryParam("code_challenge") String codeChallenge,
@QueryParam("code_challenge_method") String codeChallengeMethod,
@QueryParam("login_hint") String loginHint,
@CookieParam(SESSION_COOKIE) String sessionId) {
AuthorizationRequest request = new AuthorizationRequest(responseType, clientId, redirectUri, scope,
relyingPartyState, nonce, codeChallenge, codeChallengeMethod);
relyingPartyState, nonce, codeChallenge, codeChallengeMethod, loginHint);
String provider = trimToNull(providerName);
if (provider == null || COGNITO_PROVIDER.equals(provider)) {
return authorizeWithManagedLogin(requestContext, request, sessionId);
@@ -147,19 +148,22 @@ public class CognitoOAuthController {
@QueryParam("nonce") String nonce,
@QueryParam("state") String state,
@QueryParam("code_challenge") String codeChallenge,
@QueryParam("code_challenge_method") String codeChallengeMethod) {
@QueryParam("code_challenge_method") String codeChallengeMethod,
@QueryParam("login_hint") String loginHint) {
AuthorizationRequest request = new AuthorizationRequest(responseType, clientId, redirectUri, scope, state,
nonce, codeChallenge, codeChallengeMethod);
nonce, codeChallenge, codeChallengeMethod, loginHint);
AuthorizationCheck check = checkManagedLoginRequest(requestContext, request);
if (check.error() != null) {
return check.error();
}
return signInPage(requestContext, request, Response.Status.OK, null);
return firstPage(requestContext, request, !managedLoginService.choiceBasedFactors(check.client()).isEmpty(),
Response.Status.OK, null, null);
}
/**
* Signs the user in and redirects to the callback with a code. A failed sign-in shows the form
* again with the reason; a missing or wrong CSRF token shows it with a fresh token instead.
* again with the reason; a missing or wrong CSRF token shows it with a fresh token instead. With
* choice-based sign-in, a post without a password is one step of it instead.
*/
@POST
@Path("/cognito-idp/login")
@@ -176,27 +180,110 @@ public class CognitoOAuthController {
if (check.error() != null) {
return check.error();
}
if (!csrfTokenMatches(csrfCookie, formParams.getFirst(CSRF_FIELD))) {
return signInPage(requestContext, request, Response.Status.FORBIDDEN,
"Your sign-in page expired. Sign in again.");
}
List<String> choiceFactors = managedLoginService.choiceBasedFactors(check.client());
String username = formParams.getFirst("username");
if (!csrfTokenMatches(csrfCookie, formParams.getFirst(CSRF_FIELD))) {
return firstPage(requestContext, request, !choiceFactors.isEmpty(), Response.Status.FORBIDDEN,
"Your sign-in page expired. Sign in again.", username);
}
if (!choiceFactors.isEmpty() && !formParams.containsKey("password")) {
return continueChoiceBasedSignIn(requestContext, request, check.client(), choiceFactors, username,
formParams);
}
String password = formParams.getFirst("password");
if (trimToNull(username) == null || password == null || password.isEmpty()) {
return signInPage(requestContext, request, Response.Status.BAD_REQUEST,
"Enter your username and password.");
return passwordPage(requestContext, request, Response.Status.BAD_REQUEST,
"Enter your username and password.", username);
}
if (!choiceFactors.isEmpty() && !choiceFactors.contains("PASSWORD")) {
return usernamePage(requestContext, request, Response.Status.BAD_REQUEST,
"This user pool does not allow sign-in with a password.", username);
}
String sessionId;
try {
sessionId = managedLoginService.signIn(check.client(), username, password);
} catch (AwsException e) {
return signInPage(requestContext, request, Response.Status.BAD_REQUEST, signInError(e));
return passwordPage(requestContext, request, Response.Status.BAD_REQUEST, signInError(e), username);
}
Optional<String> code = issueAuthorizationCode(sessionId, check.client(), request);
return completeSignIn(requestContext, request, check.client(), !choiceFactors.isEmpty(), sessionId, username);
}
/**
* One step of choice-based sign-in, which takes the username, then the factor when the policy offers
* more than one, then the password or the emailed code. Every username gets the same steps, so they
* do not tell who has an account, which factors they have, or whether they can sign in. The username
* travels between the steps in a hidden field, and the code step's USER_AUTH session with it.
*/
private Response continueChoiceBasedSignIn(ContainerRequestContext requestContext, AuthorizationRequest request,
UserPoolClient client, List<String> factors, String username,
MultivaluedMap<String, String> formParams) {
if (trimToNull(username) == null) {
return usernamePage(requestContext, request, Response.Status.BAD_REQUEST, "Enter your username.", null);
}
if (formParams.containsKey("code")) {
return signInWithEmailCode(requestContext, request, client, username, formParams.getFirst("session"),
formParams.getFirst("code"));
}
String factor = formParams.getFirst("challenge");
if (factor == null && factors.size() == 1) {
factor = factors.get(0);
}
if (factor == null) {
return factorPage(requestContext, request, Response.Status.OK, null, username, factors);
}
if (!factors.contains(factor)) {
return factorPage(requestContext, request, Response.Status.BAD_REQUEST, "Choose how to sign in.",
username, factors);
}
if ("PASSWORD".equals(factor)) {
return passwordPage(requestContext, request, Response.Status.OK, null, username);
}
String userAuthSession;
try {
userAuthSession = managedLoginService.sendEmailCode(client, username);
} catch (AwsException e) {
return usernamePage(requestContext, request, Response.Status.BAD_REQUEST, signInError(e), username);
}
return codePage(requestContext, request, Response.Status.OK, null, username, userAuthSession);
}
/**
* The code step of choice-based sign-in. A wrong or expired code shows the code form again with the
* same session. Any other failure sends the user back to the username: the session is gone or expired,
* or the code was right and has spent it, as when the user cannot sign in or PostAuthentication fails.
*/
private Response signInWithEmailCode(ContainerRequestContext requestContext, AuthorizationRequest request,
UserPoolClient client, String username, String userAuthSession,
String code) {
if (trimToNull(userAuthSession) == null) {
return usernamePage(requestContext, request, Response.Status.BAD_REQUEST,
"Your sign-in page expired. Sign in again.", username);
}
if (trimToNull(code) == null) {
return codePage(requestContext, request, Response.Status.BAD_REQUEST, "Enter the code from your email.",
username, userAuthSession);
}
String sessionId;
try {
sessionId = managedLoginService.signInWithEmailCode(client, userAuthSession, code.trim());
} catch (AwsException e) {
if ("CodeMismatchException".equals(e.getErrorCode()) || "ExpiredCodeException".equals(e.getErrorCode())) {
return codePage(requestContext, request, Response.Status.BAD_REQUEST, e.getMessage(), username,
userAuthSession);
}
return usernamePage(requestContext, request, Response.Status.BAD_REQUEST, signInError(e), username);
}
return completeSignIn(requestContext, request, client, true, sessionId, username);
}
/** Redirects a signed-in user to the callback with a code, and sets the session cookie that skips the form. */
private Response completeSignIn(ContainerRequestContext requestContext, AuthorizationRequest request,
UserPoolClient client, boolean choiceBased, String sessionId, String username) {
Optional<String> code = issueAuthorizationCode(sessionId, client, request);
if (code.isEmpty()) {
return signInPage(requestContext, request, Response.Status.BAD_REQUEST,
CognitoAuthFlowHandler.INCORRECT_CREDENTIALS);
return firstPage(requestContext, request, choiceBased, Response.Status.BAD_REQUEST,
CognitoAuthFlowHandler.INCORRECT_CREDENTIALS, username);
}
return Response.fromResponse(redirectWithCode(request, code.get()))
.header(HttpHeaders.SET_COOKIE, cookie(SESSION_COOKIE, sessionId,
@@ -240,7 +327,7 @@ public class CognitoOAuthController {
redirect = Response.status(Response.Status.FOUND).location(URI.create(logoutUri)).build();
} else if (trimToNull(redirectUri) != null) {
AuthorizationRequest request = new AuthorizationRequest(responseType, clientId, redirectUri, scope,
state, nonce, codeChallenge, codeChallengeMethod);
state, nonce, codeChallenge, codeChallengeMethod, null);
AuthorizationCheck check = checkManagedLoginRequest(requestContext, request);
if (check.error() != null) {
return check.error();
@@ -615,16 +702,85 @@ public class CognitoOAuthController {
}
/**
* The sign-in form, deliberately plain: a username, a password, and the authorization request in
* hidden fields. Each rendering sets a fresh CSRF token cookie that the form echoes back.
* The first page of the sign-in: the username and password form, or, with choice-based sign-in,
* the username alone.
*/
private Response firstPage(ContainerRequestContext requestContext, AuthorizationRequest request,
boolean choiceBased, Response.Status status, String error, String username) {
return choiceBased
? usernamePage(requestContext, request, status, error, username)
: passwordPage(requestContext, request, status, error, username);
}
private Response passwordPage(ContainerRequestContext requestContext, AuthorizationRequest request,
Response.Status status, String error, String username) {
return signInPage(requestContext, request, status, error, List.of(
"<label for=\"username\">Username</label>",
usernameInput(request, username),
"<label for=\"password\">Password</label>",
"<input id=\"password\" name=\"password\" type=\"password\" autocomplete=\"current-password\""
+ " required>",
"<button type=\"submit\">Sign in</button>"));
}
private Response usernamePage(ContainerRequestContext requestContext, AuthorizationRequest request,
Response.Status status, String error, String username) {
return signInPage(requestContext, request, status, error, List.of(
"<label for=\"username\">Username</label>",
usernameInput(request, username),
"<button type=\"submit\">Next</button>"));
}
/** One button per factor, each posting its name as {@code challenge}. */
private Response factorPage(ContainerRequestContext requestContext, AuthorizationRequest request,
Response.Status status, String error, String username, List<String> factors) {
List<String> fields = new ArrayList<>();
fields.add(hiddenField("username", username));
for (String factor : factors) {
String label = "PASSWORD".equals(factor) ? "Sign in with your password" : "Email me a sign-in code";
fields.add("<button type=\"submit\" name=\"challenge\" value=\"" + escapeHtml(factor) + "\">"
+ label + "</button>");
}
return signInPage(requestContext, request, status, error, fields);
}
private Response codePage(ContainerRequestContext requestContext, AuthorizationRequest request,
Response.Status status, String error, String username, String userAuthSession) {
return signInPage(requestContext, request, status, error, List.of(
hiddenField("username", username),
hiddenField("session", userAuthSession),
"<p>Enter the code we sent to your email address.</p>",
"<label for=\"code\">Code</label>",
"<input id=\"code\" name=\"code\" type=\"text\" inputmode=\"numeric\""
+ " autocomplete=\"one-time-code\" required>",
"<button type=\"submit\">Sign in</button>"));
}
/** The username input, filled with the username given so far, or else with the request's {@code login_hint}. */
private static String usernameInput(AuthorizationRequest request, String username) {
String value = username != null ? username : request.loginHint();
return "<input id=\"username\" name=\"username\" type=\"text\" autocomplete=\"username\""
+ " autocapitalize=\"none\"" + (value == null ? "" : " value=\"" + escapeHtml(value) + "\"")
+ " required>";
}
private static String hiddenField(String name, String value) {
return "<input type=\"hidden\" name=\"" + escapeHtml(name) + "\" value=\"" + escapeHtml(value) + "\">";
}
/**
* A sign-in page, deliberately plain: {@code fields}, and the authorization request in hidden
* fields. Each rendering sets a fresh CSRF token cookie that the form echoes back.
*/
private Response signInPage(ContainerRequestContext requestContext, AuthorizationRequest request,
Response.Status status, String error) {
Response.Status status, String error, List<String> fields) {
String csrfToken = stateStore.generateOpaqueKey();
List<String> hiddenFields = new ArrayList<>();
List<String> formFields = new ArrayList<>();
for (Map.Entry<String, String> parameter : request.parameters().entrySet()) {
hiddenFields.add(" <input type=\"hidden\" name=\"" + escapeHtml(parameter.getKey())
+ "\" value=\"" + escapeHtml(parameter.getValue()) + "\">");
formFields.add(" " + hiddenField(parameter.getKey(), parameter.getValue()));
}
for (String field : fields) {
formFields.add(" " + field);
}
String page = """
<!doctype html>
@@ -641,18 +797,13 @@ public class CognitoOAuthController {
<form method="post" action="%s">
<input type="hidden" name="%s" value="%s">
%s
<label for="username">Username</label>
<input id="username" name="username" type="text" autocomplete="username" autocapitalize="none" required>
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required>
<button type="submit">Sign in</button>
</form>
</main>
</body>
</html>
""".formatted(error == null ? "" : " <p role=\"alert\">" + escapeHtml(error) + "</p>",
escapeHtml(loginPath(requestContext)), CSRF_FIELD, escapeHtml(csrfToken),
String.join("\n", hiddenFields));
String.join("\n", formFields));
// No form-action directive: browsers apply it to the redirect after the form is submitted,
// which goes to the client's callback on another origin.
return Response.status(status)
@@ -791,13 +942,13 @@ public class CognitoOAuthController {
/** The authorization request that managed login carries from the authorize endpoint to the sign-in form and back. */
private record AuthorizationRequest(String responseType, String clientId, String redirectUri, String scope,
String state, String nonce, String codeChallenge,
String codeChallengeMethod) {
String codeChallengeMethod, String loginHint) {
static AuthorizationRequest from(MultivaluedMap<String, String> parameters) {
return new AuthorizationRequest(parameters.getFirst("response_type"), parameters.getFirst("client_id"),
parameters.getFirst("redirect_uri"), parameters.getFirst("scope"), parameters.getFirst("state"),
parameters.getFirst("nonce"), parameters.getFirst("code_challenge"),
parameters.getFirst("code_challenge_method"));
parameters.getFirst("code_challenge_method"), parameters.getFirst("login_hint"));
}
/** The parameters the request carried, in the order of AWS's redirect to the login endpoint. */
@@ -811,6 +962,7 @@ public class CognitoOAuthController {
putIfPresent(parameters, "nonce", nonce);
putIfPresent(parameters, "code_challenge", codeChallenge);
putIfPresent(parameters, "code_challenge_method", codeChallengeMethod);
putIfPresent(parameters, "login_hint", loginHint);
return parameters;
}
@@ -437,6 +437,21 @@ public class CognitoService implements ResourceProvider {
pool.setPolicies(normalized);
}
/**
* Gives a pool without a {@code SignInPolicy} AWS's default, {@code PASSWORD} alone. DescribeUserPool on
* AWS reports {@code {"AllowedFirstAuthFactors": ["PASSWORD"]}} for a pool created without one, on any
* tier. Unlike {@link #normalizePasswordPolicy}, defaulting this one enforces nothing new: a pool with no
* sign-in policy already offers only password challenges.
*/
private static void defaultSignInPolicy(UserPool pool) {
Map<String, Object> policies = pool.getPolicies() == null ? new HashMap<>() : new HashMap<>(pool.getPolicies());
if (policies.get("SignInPolicy") instanceof Map<?, ?>) {
return;
}
policies.put("SignInPolicy", Map.of("AllowedFirstAuthFactors", List.of("PASSWORD")));
pool.setPolicies(policies);
}
private void validatePasswordPolicy(Map<String, Object> passwordPolicy) {
Object minLengthVal = passwordPolicy.get("MinimumLength");
if (minLengthVal == null) {
@@ -537,6 +552,7 @@ public class CognitoService implements ResourceProvider {
pool.setPolicies((Map<String, Object>) request.get("Policies"));
normalizePasswordPolicy(pool);
}
defaultSignInPolicy(pool);
if (request.containsKey("DeletionProtection")) pool.setDeletionProtection((String) request.get("DeletionProtection"));
if (request.containsKey("LambdaConfig")) pool.setLambdaConfig((Map<String, Object>) request.get("LambdaConfig"));
if (request.containsKey("Schema")) pool.setSchemaAttributes(prefixCustomSchemaAttributes((List<Map<String, Object>>) request.get("Schema")));
@@ -2942,6 +2958,22 @@ public class CognitoService implements ResourceProvider {
username, password);
}
/** Managed login's choice-based sign-in; see {@link CognitoAuthFlowHandler#managedLoginFirstFactors}. */
List<String> managedLoginFirstFactors(UserPoolClient client) {
return authFlowHandler.managedLoginFirstFactors(describeUserPool(client.getUserPoolId()), client);
}
/** See {@link CognitoAuthFlowHandler#startManagedLoginEmailOtp}. */
String startManagedLoginEmailOtp(UserPoolClient client, String username) {
return authFlowHandler.startManagedLoginEmailOtp(describeUserPool(client.getUserPoolId()), client, username);
}
/** See {@link CognitoAuthFlowHandler#completeManagedLoginEmailOtp}. */
CognitoUser completeManagedLoginEmailOtp(UserPoolClient client, String session, String code) {
return authFlowHandler.completeManagedLoginEmailOtp(describeUserPool(client.getUserPoolId()), client,
session, code);
}
public Map<String, Object> respondToAuthChallenge(String clientId, String challengeName,
String session, Map<String, String> responses) {
return authFlowHandler.respondToAuthChallenge(clientId, challengeName, session, responses, Map.of());
@@ -41,10 +41,18 @@ public final class VerificationCodeService {
private static final Duration RATE_LIMIT_WINDOW = Duration.ofSeconds(30);
private static final int MAX_ATTEMPTS = 5;
private static final int SALT_BYTES = 16;
private static final int CODE_LOCK_STRIPES = 256;
private final StorageBackend<String, VerificationCode> store;
private final Clock clock;
private final SecureRandom random;
/**
* Stripes, by storage key, that make issuing, consuming and invalidating a code one step each: only
* codes whose keys share a stripe wait on each other. Nothing but this service's store is called under
* one, never a Lambda trigger or a Cognito lock, so no lock a caller holds around these methods can form
* a cycle with it.
*/
private final Object[] codeLocks = newCodeLocks();
public VerificationCodeService(StorageFactory storageFactory, Clock clock) {
this.store = storageFactory.create(
@@ -58,11 +66,20 @@ public final class VerificationCodeService {
/**
* Issue a new code for the given user/purpose. Returns the plaintext code
* (caller must dispatch via SES/SNS). Subject to {@link #RATE_LIMIT_WINDOW}.
* (caller must dispatch via SES/SNS). Subject to {@link #RATE_LIMIT_WINDOW}. Takes turns
* with {@link #consume} for the same key, so redeeming the previous code cannot delete
* this one.
*/
public String issue(String userPoolId, String username,
VerificationCode.Purpose purpose, Duration ttl) {
String key = VerificationCode.storageKey(userPoolId, username, purpose);
synchronized (lockFor(key)) {
return issueUnderLock(key, userPoolId, username, purpose, ttl);
}
}
private String issueUnderLock(String key, String userPoolId, String username,
VerificationCode.Purpose purpose, Duration ttl) {
Optional<VerificationCode> existing = store.get(key);
if (existing.isPresent() && !existing.get().isConsumed()) {
Duration since = Duration.between(existing.get().getIssuedAt(), clock.instant());
@@ -96,14 +113,19 @@ public final class VerificationCodeService {
* {@code ConfirmSignUp} or {@code ConfirmForgotPassword}. On any failure, throws
* {@link VerificationCodeException} with the specific {@link VerificationCodeException.Kind}.
*
* <p>Note: not thread-safe under concurrent {@code consume()} of the same
* (poolId, username, purpose) key — two racing wrong-code calls may
* decrement the attempts counter by 1 instead of 2. Acceptable for the
* single-user local-dev profile; revisit if floci grows multi-tenant.
* <p>Concurrent calls for the same (poolId, username, purpose) key take turns, so a code
* is redeemed once however many requests present it at the same moment, and every wrong
* attempt counts.
*/
public void consume(String userPoolId, String username,
VerificationCode.Purpose purpose, String code) {
String key = VerificationCode.storageKey(userPoolId, username, purpose);
synchronized (lockFor(key)) {
consumeUnderLock(key, purpose, code);
}
}
private void consumeUnderLock(String key, VerificationCode.Purpose purpose, String code) {
VerificationCode vc = store.get(key).orElseThrow(() -> new VerificationCodeException(
VerificationCodeException.Kind.NOT_FOUND,
"Invalid verification code provided, please try again"));
@@ -157,7 +179,7 @@ public final class VerificationCodeService {
/** Remove any active code for the (pool, user, purpose). Idempotent. */
public void invalidatePrevious(String userPoolId, String username,
VerificationCode.Purpose purpose) {
store.delete(VerificationCode.storageKey(userPoolId, username, purpose));
invalidate(VerificationCode.storageKey(userPoolId, username, purpose));
}
/**
@@ -172,7 +194,26 @@ public final class VerificationCodeService {
.filter(k -> k.startsWith(prefix))
.filter(k -> store.get(k).map(c -> userPoolId.equals(c.getUserPoolId())).orElse(false))
.toList()
.forEach(store::delete);
.forEach(this::invalidate);
}
/** Deletes a code in turn with {@link #consume}, which could otherwise write a wrong attempt back after it. */
private void invalidate(String key) {
synchronized (lockFor(key)) {
store.delete(key);
}
}
private Object lockFor(String key) {
return codeLocks[Math.floorMod(key.hashCode(), CODE_LOCK_STRIPES)];
}
private static Object[] newCodeLocks() {
Object[] locks = new Object[CODE_LOCK_STRIPES];
for (int i = 0; i < locks.length; i++) {
locks[i] = new Object();
}
return locks;
}
private byte[] randomBytes(int n) {