From 45b7be9362d2e50211e22f8aeaee4f416d569b93 Mon Sep 17 00:00:00 2001 From: jwoa95 <88512616+jwoa95@users.noreply.github.com> Date: Thu, 1 Oct 2026 21:40:31 +0100 Subject: [PATCH] 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 --- docs/services/cognito.md | 62 ++- .../cognito/CognitoAuthFlowHandler.java | 215 +++++++- .../cognito/CognitoManagedLoginService.java | 49 +- .../cognito/CognitoOAuthController.java | 212 ++++++-- .../services/cognito/CognitoService.java | 32 ++ .../verification/VerificationCodeService.java | 55 +- .../cognito/CognitoIntegrationTest.java | 65 +++ .../CognitoManagedLoginIntegrationTest.java | 455 ++++++++++++++++- .../cognito/CognitoOAuthControllerTest.java | 45 +- .../services/cognito/CognitoServiceTest.java | 468 +++++++++++++++++- .../SlowVerificationCodeStore.java | 56 +++ .../VerificationCodeServiceTest.java | 104 ++++ 12 files changed, 1714 insertions(+), 104 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/verification/SlowVerificationCodeStore.java diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 800efe5437..dd92681f8e 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -247,8 +247,18 @@ preferences, SMS/email MFA challenges, and managed-login MFA are not emulated. `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. +challenge. The list keeps only the first factors the pool's +`Policies.SignInPolicy.AllowedFirstAuthFactors` allows: its `PASSWORD` covers both `PASSWORD` and +`PASSWORD_SRP`, so a pool that allows only `EMAIL_OTP` offers `["EMAIL_OTP"]`, and a user with no +password is never offered a password challenge. A pool created without a `SignInPolicy` gets +`{"AllowedFirstAuthFactors": ["PASSWORD"]}`, on any tier, as `DescribeUserPool` reports on AWS, so it +offers password challenges alone. `UpdateUserPool` keeps the policy when the request omits `Policies`, +and puts the default back when its `Policies` has no `SignInPolicy`. A `PREFERRED_CHALLENGE` outside +the list, because the policy leaves it out or the user has not set it up, gets `SELECT_CHALLENGE` and +the list, as on AWS; one that names no challenge Cognito supports fails with +`InvalidParameterException`. A `SELECT_CHALLENGE` answer outside the list fails with +`InvalidParameterException`. 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. @@ -377,12 +387,15 @@ the callback in `CallbackURLs`. No domain is needed; on a custom domain the same `/oauth2/authorize`, `/login` and `/logout`. 1. `GET /cognito-idp/oauth2/authorize` redirects to `/cognito-idp/login` with the request's - parameters. If the browser already has a managed login session in the pool, it skips the - form and redirects straight to the callback with a code, as AWS does. A `scope` the client's - `AllowedOAuthScopes` does not include is refused first, as on AWS, with a redirect to the - callback carrying `error=invalid_request`, `error_description=invalid_scope` and the `state`. -2. `GET /cognito-idp/login` renders a plain username and password form. The form carries the - request in hidden fields and a CSRF token that must match the `XSRF-TOKEN` cookie set with it. + parameters, `login_hint` included. If the browser already has a managed login session in the + pool, it skips the form and redirects straight to the callback with a code, as AWS does. A + `scope` the client's `AllowedOAuthScopes` does not include is refused first, as on AWS, with a + redirect to the callback carrying `error=invalid_request`, `error_description=invalid_scope` + and the `state`. +2. `GET /cognito-idp/login` renders a plain username and password form, with the username filled + in from `login_hint` when the request has one. The form carries the request in hidden fields and + a CSRF token that must match the `XSRF-TOKEN` cookie set with it. With choice-based sign-in + (below), it asks for the username alone. 3. `POST /cognito-idp/login` checks the password as `USER_PASSWORD_AUTH` does, including sign-in aliases and the pre and post authentication and user migration triggers, but without the client's `ExplicitAuthFlows`. On success it sets a `cognito` session cookie @@ -402,6 +415,36 @@ the callback in `CallbackURLs`. No domain is needed; on a custom domain the same `response_type=code` instead of `logout_uri`, it ends the session and redirects to the sign-in form for that request. +Choice-based sign-in applies when the pool's `SignInPolicy.AllowedFirstAuthFactors` includes +`EMAIL_OTP` and the client's `ExplicitAuthFlows` includes `ALLOW_USER_AUTH` (on a pool above the +Lite tier). The page then takes one step per `POST /cognito-idp/login`. Up to the password or the +code, every username gets the same pages, so they do not tell who has an account, which factors +they have, or whether they can sign in: + +1. The username. +2. The factor, as buttons that post `challenge=PASSWORD` or `challenge=EMAIL_OTP`, when the policy + allows both. When it allows only `EMAIL_OTP`, every username goes straight to the code. +3. For `PASSWORD`, the username and password form, where a user without a password fails as a + wrong password does. For `EMAIL_OTP`, the page sends a code through the `USER_AUTH` `EMAIL_OTP` + challenge, so it arrives in Floci's SES (readable at `/_aws/ses`), and shows a code field. The + username and the challenge's `Session` travel in hidden fields. A correct code signs the user + in as the password does: the session cookie, and a redirect to the callback with `code` and + `state`. A wrong code shows the code field again with + `Invalid verification code provided, please try again.` and the same session, so the user can + try again until the session (the client's `AuthSessionValidity`) or the code runs out. + +Only a user who can sign in and has a verified email is sent a code. Anyone else, an unknown user +included, gets the same code field, but no message is sent and every code is wrong. Asking again +within 30 seconds, before Floci sends another code, shows the code field for the code already +sent. Why a user cannot sign in (disabled, unconfirmed, a password reset or a new password +required) shows only after a correct code. A correct code uses up the session, so when the user +cannot sign in or the post authentication trigger fails, the page goes back to the username with +the reason. A code signs in once: of several requests that answer with it at once, from one session +or several, one signs in and the others are told the code is wrong, or go back to the username if +their session is already spent. A password posted to a pool whose policy leaves out `PASSWORD` is +refused. Without choice-based sign-in, the page is the username and password form above, whatever +the policy says. + PKCE follows AWS: `code_challenge_method` must be `S256`, and discovery advertises `code_challenge_methods_supported: ["S256"]`. A code issued with a `code_challenge` is redeemed only with the matching `code_verifier`, so a public client (no secret) can use it @@ -413,7 +456,8 @@ Differences from AWS: - **No challenge pages.** A user who must change or reset their password, or who is not confirmed, sees an error on the form instead. Sign-up, forgot-password, MFA and passkey - pages are not served, and `prompt`, `login_hint`, `lang` and `idp_identifier` are ignored. + pages are not served, choice-based sign-in offers no `SMS_OTP` or `WEB_AUTHN` factor, and + `prompt`, `lang` and `idp_identifier` are ignored. - **Errors are JSON.** An authorization request error returns `400` with an OAuth error body, even after `redirect_uri` is validated, where AWS redirects the error to the callback. The exception is an unallowed `scope`, which is redirected as on AWS. diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java index c649c8794b..0a53da69a7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java @@ -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 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 srpSessions = new ConcurrentHashMap<>(); private final ConcurrentHashMap customAuthSessions = new ConcurrentHashMap<>(); private final ConcurrentHashMap 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 userAuthSessions = new LinkedHashMap<>(); private final LinkedHashMap 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 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 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 available = availableUserAuthChallenges(user); + List 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 available = availableUserAuthChallenges(user); + List available = allowedUserAuthChallenges(pool, user); return startUserAuthChallenge(pool, client, user, answer, available, false, responses, clientMetadata); } @@ -922,7 +1038,7 @@ final class CognitoAuthFlowHandler { String challengeName, List available, Map 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 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 simulatedUserAuthChallenge(UserPool pool, UserPoolClient client, String username, + String preferred) { List 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 configuredUserAuthChallenges(UserPool pool) { - Map 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 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 allowedFirstAuthFactors(UserPool pool) { + Map 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 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 allowedUserAuthChallenges(UserPool pool, CognitoUser user) { + List available = availableUserAuthChallenges(user); + List 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 availableUserAuthChallenges(CognitoUser user) { List available = new ArrayList<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java index 7c3083a71d..65de449199 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java @@ -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 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 choiceBasedFactors(UserPoolClient client) { + List 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))); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java index 6ef0b62f44..cff9d69a26 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java @@ -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 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 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 factors, String username, + MultivaluedMap 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 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( + "", + usernameInput(request, username), + "", + "", + "")); + } + + private Response usernamePage(ContainerRequestContext requestContext, AuthorizationRequest request, + Response.Status status, String error, String username) { + return signInPage(requestContext, request, status, error, List.of( + "", + usernameInput(request, username), + "")); + } + + /** 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 factors) { + List 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(""); + } + 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), + "

Enter the code we sent to your email address.

", + "", + "", + "")); + } + + /** 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 ""; + } + + private static String hiddenField(String name, String value) { + return ""; + } + + /** + * 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 fields) { String csrfToken = stateStore.generateOpaqueKey(); - List hiddenFields = new ArrayList<>(); + List formFields = new ArrayList<>(); for (Map.Entry parameter : request.parameters().entrySet()) { - hiddenFields.add(" "); + formFields.add(" " + hiddenField(parameter.getKey(), parameter.getValue())); + } + for (String field : fields) { + formFields.add(" " + field); } String page = """ @@ -641,18 +797,13 @@ public class CognitoOAuthController {
%s - - - - -
""".formatted(error == null ? "" : "

" + escapeHtml(error) + "

", 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 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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 4208e774c0..23472db181 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -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 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 passwordPolicy) { Object minLengthVal = passwordPolicy.get("MinimumLength"); if (minLengthVal == null) { @@ -537,6 +552,7 @@ public class CognitoService implements ResourceProvider { pool.setPolicies((Map) request.get("Policies")); normalizePasswordPolicy(pool); } + defaultSignInPolicy(pool); if (request.containsKey("DeletionProtection")) pool.setDeletionProtection((String) request.get("DeletionProtection")); if (request.containsKey("LambdaConfig")) pool.setLambdaConfig((Map) request.get("LambdaConfig")); if (request.containsKey("Schema")) pool.setSchemaAttributes(prefixCustomSchemaAttributes((List>) 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 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 respondToAuthChallenge(String clientId, String challengeName, String session, Map responses) { return authFlowHandler.respondToAuthChallenge(clientId, challengeName, session, responses, Map.of()); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java index f1c04e4295..f482e9d93a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeService.java @@ -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 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 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}. * - *

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. + *

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) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java index 5eb03d6ba1..8c70f63df9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java @@ -3270,6 +3270,71 @@ class CognitoIntegrationTest { .body("message", equalTo("Incorrect username or password")); } + /** + * Observed on AWS with a sign-in policy of PASSWORD: a PREFERRED_CHALLENGE outside the policy, or one the + * user has not set up, gets SELECT_CHALLENGE and the available list, and a name Cognito does not support + * gets InvalidParameterException. + */ + @Test + @Order(112) + void userAuthOffersTheChoiceForAPreferredChallengeTheUserCannotTakeOverTheWire() throws Exception { + String poolId = cognitoJson("CreateUserPool", """ + { + "PoolName": "PreferredChallengeWirePool", + "Policies": { "SignInPolicy": { "AllowedFirstAuthFactors": ["PASSWORD"] } } + } + """).path("UserPool").path("Id").asText(); + String clientId = cognitoJson("CreateUserPoolClient", """ + {"UserPoolId": "%s", "ClientName": "preferred-challenge-client", "ExplicitAuthFlows": ["ALLOW_USER_AUTH"]} + """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText(); + cognitoAction("AdminCreateUser", """ + {"UserPoolId": "%s", "Username": "wire-user", "MessageAction": "SUPPRESS", + "UserAttributes": [{"Name": "email", "Value": "wire-user@example.com"}, + {"Name": "email_verified", "Value": "true"}]} + """.formatted(poolId)).then().statusCode(200); + cognitoAction("AdminSetUserPassword", """ + {"UserPoolId": "%s", "Username": "wire-user", "Password": "Perm1234!", "Permanent": true} + """.formatted(poolId)).then().statusCode(200); + + for (String preferred : List.of("EMAIL_OTP", "WEB_AUTHN")) { + JsonNode result = cognitoJson("InitiateAuth", """ + {"ClientId": "%s", "AuthFlow": "USER_AUTH", + "AuthParameters": {"USERNAME": "wire-user", "PREFERRED_CHALLENGE": "%s"}} + """.formatted(clientId, preferred)); + assertEquals("SELECT_CHALLENGE", result.path("ChallengeName").asText(), preferred); + assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), textValues(result.path("AvailableChallenges")), + preferred); + assertFalse(result.path("Session").asText().isBlank(), preferred); + } + cognitoAction("InitiateAuth", """ + {"ClientId": "%s", "AuthFlow": "USER_AUTH", + "AuthParameters": {"USERNAME": "wire-user", "PREFERRED_CHALLENGE": "BOGUS"}} + """.formatted(clientId)) + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")) + .body("message", equalTo("The preferred challenge must be one of the supported challenges. " + + "[PASSWORD, PASSWORD_SRP, SMS_OTP, EMAIL_OTP, WEB_AUTHN]")); + } + + /** Observed on AWS: DescribeUserPool reports a SignInPolicy of PASSWORD for a pool created without one. */ + @Test + @Order(113) + void describeUserPoolReportsAPasswordSignInPolicyForAPoolCreatedWithoutOne() throws Exception { + for (String tier : List.of("LITE", "ESSENTIALS")) { + String poolId = cognitoJson("CreateUserPool", """ + {"PoolName": "DefaultSignInPolicyPool", "UserPoolTier": "%s"} + """.formatted(tier)).path("UserPool").path("Id").asText(); + + JsonNode policies = cognitoJson("DescribeUserPool", """ + {"UserPoolId": "%s"} + """.formatted(poolId)).path("UserPool").path("Policies"); + + assertEquals(List.of("PASSWORD"), + textValues(policies.path("SignInPolicy").path("AllowedFirstAuthFactors")), tier); + } + } + private static List textValues(JsonNode array) { List values = new ArrayList<>(); for (JsonNode value : array) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java index da1a0c44cc..e76d922753 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java @@ -16,6 +16,7 @@ import org.mockito.ArgumentCaptor; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; +import java.util.Base64; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -63,11 +64,16 @@ class CognitoManagedLoginIntegrationTest { private static final String INCORRECT_CREDENTIALS = "Incorrect username or password"; private static final Pattern HIDDEN_FIELD = Pattern.compile(""); private static final Pattern FORM_ACTION = Pattern.compile("

"); + private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b"); private static final String PRE_TOKEN_GENERATION_ARN = "arn:aws:lambda:::pre-token-generation"; private static final String ADMIN_SCOPE = "aws.cognito.signin.user.admin"; + private static final String POST_AUTHENTICATION_ARN = "arn:aws:lambda:::post-authentication"; private static final ObjectMapper MAPPER = new ObjectMapper(); - /** Only the PreTokenGeneration trigger is configured on any pool here, so nothing else invokes it. */ + /** + * Only the PreTokenGeneration and PostAuthentication triggers are configured on any pool here, each by + * the tests that stub it, so nothing else invokes it. + */ @InjectMock LambdaService lambdaService; @@ -724,6 +730,336 @@ class CognitoManagedLoginIntegrationTest { queryOf(refused)); } + /** + * AWS: with {@code login_hint}, "managed login fills the username field with your hint value", on + * {@code /oauth2/authorize} and on {@code /login}. The hint is escaped like the rest of the page. + */ + @Test + void loginHintReachesTheLoginPageAndFillsTheUsernameOnEitherHost() throws Exception { + Pool pool = newPool(); + String domain = "login-hint-" + System.nanoTime() + ".teos.localhost.floci.io"; + cognitoJson("CreateUserPoolDomain", customDomain(domain, pool.poolId(), requestCertificate(domain))); + String hint = "o'hara+\"\"@example.com"; + + for (String host : new String[] {null, domain}) { + Map query = authorizeRequest(pool.clientId()); + query.put("login_hint", hint); + String location = browserGet(host, host == null ? "/cognito-idp/oauth2/authorize" : "/oauth2/authorize", + query, null).then().statusCode(302).extract().header("Location"); + assertEquals(hint, queryOf(location).get("login_hint"), location); + + String html = follow(host, location).then().statusCode(200).extract().asString(); + assertEquals("", + input(html, "username")); + assertFalse(html.contains(""), html); + assertTrue(html.contains("name=\"password\""), "a pool without a sign-in policy keeps the password form"); + } + } + + /** + * The issue's pool: email usernames, a sign-in policy of EMAIL_OTP alone, and a client that allows + * USER_AUTH. The page asks for the username, emails a code through Floci's SES, and signs in with it + * exactly as the password form does: a code and the state on the callback, redeemed with PKCE. + */ + @Test + void choiceBasedSignInAsksForTheUsernameThenSignsInWithAnEmailedCode() throws Exception { + PasswordlessPool pool = newPasswordlessPool(List.of("EMAIL_OTP"), true); + JsonNode userAuth = cognitoJson("InitiateAuth", """ + {"ClientId":"%s","AuthFlow":"USER_AUTH","AuthParameters":{"USERNAME":"%s"}} + """.formatted(pool.clientId(), pool.email())); + assertEquals(List.of("EMAIL_OTP"), MAPPER.convertValue(userAuth.path("AvailableChallenges"), List.class)); + Map query = authorizeRequest(pool.clientId()); + query.put("login_hint", pool.email()); + + Response usernameStep = loginPage(null, "/cognito-idp/oauth2/authorize", query); + String usernameHtml = usernameStep.asString(); + assertTrue(input(usernameHtml, "username").contains("value=\"" + pool.email() + "\""), usernameHtml); + assertNull(input(usernameHtml, "password"), "no password field for a pool that allows only email codes"); + + Response codeStep = post(null, usernameStep, Map.of("username", pool.email())); + codeStep.then().statusCode(200).contentType(startsWith("text/html")); + String codeHtml = codeStep.asString(); + assertNotNull(input(codeHtml, "code"), codeHtml); + assertNull(input(codeHtml, "password"), codeHtml); + assertNull(setCookie(codeStep, "cognito")); + assertNotNull(hiddenFields(codeHtml).get("session"), "the USER_AUTH session travels in the form"); + + Response signedIn = post(null, codeStep, Map.of("code", latestEmailCode(pool.email()))); + + signedIn.then().statusCode(302); + String location = signedIn.getHeader("Location"); + assertTrue(location.startsWith(CALLBACK + "?code="), location); + assertEquals("client-state", queryOf(location).get("state")); + assertNotNull(setCookie(signedIn, "cognito")); + JsonNode idToken = jwtPayload(redeem(null, pool.clientId(), code(signedIn), VERIFIER) + .then().statusCode(200).extract().path("id_token")); + assertEquals(pool.sub(), idToken.path("sub").asText()); + assertEquals(pool.email(), idToken.path("email").asText()); + assertEquals("client-nonce", idToken.path("nonce").asText()); + } + + @Test + void wrongEmailCodeShowsTheCodeFormAgainAndTheRightCodeStillSignsIn() throws Exception { + PasswordlessPool pool = newPasswordlessPool(List.of("EMAIL_OTP"), false); + Response codeStep = post(null, loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId())), + Map.of("username", pool.email())); + String code = latestEmailCode(pool.email()); + + Response wrong = post(null, codeStep, Map.of("code", differentCode(code))); + + wrong.then().statusCode(400).contentType(startsWith("text/html")); + assertNull(wrong.getHeader("Location")); + assertNull(setCookie(wrong, "cognito")); + assertTrue(wrong.asString().contains("

Invalid verification code provided, please try again.

"), + wrong.asString()); + assertNotNull(input(wrong.asString(), "code"), "the code form is shown again"); + + Response signedIn = post(null, wrong, Map.of("code", code)); + redeem(null, pool.clientId(), code(signedIn), VERIFIER).then().statusCode(200); + } + + /** + * With PASSWORD and EMAIL_OTP allowed, every user chooses between them, password or not: a user with a + * password signs in with it, and one without fails it as a wrong password does and signs in with a code. + */ + @Test + void everyUserChoosesAFactorWhetherOrNotTheyHaveAPassword() throws Exception { + PasswordlessPool withPassword = newPasswordlessPool(List.of("PASSWORD", "EMAIL_OTP"), true); + + Response choice = post(null, loginPage(null, "/cognito-idp/oauth2/authorize", + authorizeRequest(withPassword.clientId())), Map.of("username", withPassword.email())); + choice.then().statusCode(200); + String choiceHtml = choice.asString(); + assertTrue(choiceHtml.contains("