Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

jwoa9545b7be9362d2
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<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,35 +1117,67 @@ 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");
+ List<String> supported = new ArrayList<>();
+ for (String name : allowedFirstAuthFactors(pool)) {
+ if ("PASSWORD".equals(name) || "EMAIL_OTP".equals(name) || "SMS_OTP".equals(name)) {
+ supported.add(name);
+ }
}
- Object configuredFactors = signInPolicy.get("AllowedFirstAuthFactors");
- if (!(configuredFactors instanceof List<?> factors) || factors.isEmpty()) {
+ 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> supported = new ArrayList<>();
+ List<String> names = 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)) {
- supported.add(name);
+ if (factor instanceof String name && !names.contains(name)) {
+ names.add(name);
}
}
- return supported;
+ 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. */
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<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)));
}
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();
}
+ List<String> choiceFactors = managedLoginService.choiceBasedFactors(check.client());
+ String username = formParams.getFirst("username");
if (!csrfTokenMatches(csrfCookie, formParams.getFirst(CSRF_FIELD))) {
- return signInPage(requestContext, request, Response.Status.FORBIDDEN,
- "Your sign-in page expired. Sign in again.");
+ 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 username = formParams.getFirst("username");
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;
}
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<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());
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<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) {
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": "[email protected]"},
+ {"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<String> textValues(JsonNode array) {
List<String> 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("<input type=\"hidden\" name=\"([^\"]*)\" value=\"([^\"]*)\">");
private static final Pattern FORM_ACTION = Pattern.compile("<form method=\"post\" action=\"([^\"]*)\">");
+ 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+\"<b>\"@example.com";
+
+ for (String host : new String[] {null, domain}) {
+ Map<String, String> 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 id=\"username\" name=\"username\" type=\"text\" autocomplete=\"username\" "
+ + "autocapitalize=\"none\" value=\"o&#39;hara+&quot;&lt;b&gt;&quot;@example.com\" required>",
+ input(html, "username"));
+ assertFalse(html.contains("<b>"), 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<String, String> 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("<p role=\"alert\">Invalid verification code provided, please try again.</p>"),
+ 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("<button type=\"submit\" name=\"challenge\" value=\"PASSWORD\">"), choiceHtml);
+ assertTrue(choiceHtml.contains("<button type=\"submit\" name=\"challenge\" value=\"EMAIL_OTP\">"), choiceHtml);
+ Response passwordStep = post(null, choice, Map.of("challenge", "PASSWORD"));
+ String passwordHtml = passwordStep.then().statusCode(200).extract().asString();
+ assertTrue(input(passwordHtml, "username").contains("value=\"" + withPassword.email() + "\""), passwordHtml);
+ Response signedIn = post(null, passwordStep, Map.of("username", withPassword.email(), "password", PASSWORD));
+ redeem(null, withPassword.clientId(), code(signedIn), VERIFIER).then().statusCode(200);
+
+ PasswordlessPool withoutPassword = newPasswordlessPool(List.of("PASSWORD", "EMAIL_OTP"), false);
+ Response noPasswordChoice = post(null, loginPage(null, "/cognito-idp/oauth2/authorize",
+ authorizeRequest(withoutPassword.clientId())), Map.of("username", withoutPassword.email()));
+ String noPasswordChoiceHtml = noPasswordChoice.then().statusCode(200).extract().asString();
+ assertTrue(noPasswordChoiceHtml.contains("<button type=\"submit\" name=\"challenge\" value=\"PASSWORD\">"),
+ noPasswordChoiceHtml);
+ Response refused = post(null, post(null, noPasswordChoice, Map.of("challenge", "PASSWORD")),
+ Map.of("username", withoutPassword.email(), "password", PASSWORD));
+ refused.then().statusCode(400);
+ assertTrue(refused.asString().contains("<p role=\"alert\">" + INCORRECT_CREDENTIALS + "</p>"), refused.asString());
+ Response codeStep = post(null, noPasswordChoice, Map.of("challenge", "EMAIL_OTP"));
+ assertNotNull(input(codeStep.then().statusCode(200).extract().asString(), "code"), codeStep.asString());
+ Response codeSignedIn = post(null, codeStep, Map.of("code", latestEmailCode(withoutPassword.email())));
+ redeem(null, withoutPassword.clientId(), code(codeSignedIn), VERIFIER).then().statusCode(200);
+ }
+
+ /**
+ * The step after the username is the same page for every username, so it cannot tell who has an account,
+ * which factors they have, or whether they can sign in: with PASSWORD and EMAIL_OTP allowed, each is offered
+ * both, and no code is sent before one is chosen.
+ */
+ @Test
+ void everyUsernameIsOfferedTheSameFactors() throws Exception {
+ PasswordlessPool pool = newPasswordlessPool(List.of("PASSWORD", "EMAIL_OTP"), true);
+ List<String> usernames = List.of(pool.email(), addEmailUser(pool.poolId(), false, true),
+ addEmailUser(pool.poolId(), true, false), disabledUser(pool.poolId()),
+ resetRequiredUser(pool.poolId()), "nobody-" + System.nanoTime() + "@example.com");
+
+ String expected = null;
+ for (String username : usernames) {
+ Response choice = post(null, loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId())),
+ Map.of("username", username));
+
+ String html = choice.then().statusCode(200).extract().asString();
+ assertEquals(username, hiddenFields(html).get("username"), html);
+ String page = withoutPerRequestValues(html);
+ if (expected == null) {
+ expected = page;
+ assertTrue(page.contains("<button type=\"submit\" name=\"challenge\" value=\"PASSWORD\">"), page);
+ assertTrue(page.contains("<button type=\"submit\" name=\"challenge\" value=\"EMAIL_OTP\">"), page);
+ }
+ assertEquals(expected, page, username);
+ assertEquals(0, emailsTo(username).size(), username);
+ }
+ }
+
+ /**
+ * With EMAIL_OTP alone, every username goes straight to the same code step, whose session does not name
+ * the user. Only a user who can sign in and has a verified email is sent a code; anyone else is sent
+ * nothing, and every code is wrong for them in the same words as for a user with an account who typed a
+ * wrong one.
+ */
+ @Test
+ void everyUsernameGetsTheCodeStepButOnlyAUserWhoCanSignInIsSentACode() throws Exception {
+ PasswordlessPool pool = newPasswordlessPool(List.of("EMAIL_OTP"), false);
+ List<String> usernames = List.of(pool.email(), addEmailUser(pool.poolId(), false, false),
+ disabledUser(pool.poolId()), resetRequiredUser(pool.poolId()),
+ "nobody-" + System.nanoTime() + "@example.com");
+
+ String expectedCodeStep = null;
+ String expectedRefusal = null;
+ String wrongCode = null;
+ Set<Integer> sessionLengths = new HashSet<>();
+ for (String username : usernames) {
+ Response codeStep = post(null, loginPage(null, "/cognito-idp/oauth2/authorize",
+ authorizeRequest(pool.clientId())), Map.of("username", username));
+ String html = codeStep.then().statusCode(200).extract().asString();
+ assertNotNull(input(html, "code"), username + ": " + html);
+ String session = hiddenFields(html).get("session");
+ String decodedSession = new String(Base64.getDecoder().decode(session), StandardCharsets.UTF_8);
+ assertFalse(decodedSession.contains(username) || decodedSession.contains(pool.sub()),
+ "the session must not name the user: " + decodedSession);
+ sessionLengths.add(session.length());
+ if (username.equals(pool.email())) {
+ wrongCode = differentCode(latestEmailCode(username));
+ expectedCodeStep = withoutPerRequestValues(html);
+ } else {
+ assertEquals(0, emailsTo(username).size(), username);
+ }
+ assertEquals(expectedCodeStep, withoutPerRequestValues(html), username);
+
+ Response refused = post(null, codeStep, Map.of("code", wrongCode));
+
+ String refusedHtml = refused.then().statusCode(400).extract().asString();
+ assertTrue(refusedHtml.contains("<p role=\"alert\">Invalid verification code provided, please try again.</p>"),
+ username + ": " + refusedHtml);
+ if (expectedRefusal == null) {
+ expectedRefusal = withoutPerRequestValues(refusedHtml);
+ }
+ assertEquals(expectedRefusal, withoutPerRequestValues(refusedHtml), username);
+ }
+ assertEquals(1, sessionLengths.size(), "every session is as long as any other: " + sessionLengths);
+ }
+
+ /**
+ * A user who can no longer sign in learns why only from the right code: after the user is disabled, a
+ * wrong code still reads as wrong, and the right one gives the reason, back at the username step since
+ * the code is used up.
+ */
+ @Test
+ void userDisabledAfterTheCodeWasSentLearnsWhyOnlyFromTheRightCode() 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());
+ cognitoAction("AdminDisableUser", """
+ {"UserPoolId":"%s","Username":"%s"}
+ """.formatted(pool.poolId(), pool.email())).then().statusCode(200);
+
+ Response wrong = post(null, codeStep, Map.of("code", differentCode(code)));
+ wrong.then().statusCode(400);
+ assertTrue(wrong.asString().contains("<p role=\"alert\">Invalid verification code provided, please try again.</p>"),
+ wrong.asString());
+
+ Response refused = post(null, wrong, Map.of("code", code));
+
+ String html = refused.then().statusCode(400).extract().asString();
+ assertTrue(html.contains("<p role=\"alert\">User is disabled</p>"), html);
+ assertNull(input(html, "code"), "the code is used up, so the page does not ask for it again");
+ assertTrue(input(html, "username").contains("value=\"" + pool.email() + "\""), html);
+ assertNull(refused.getHeader("Location"));
+ assertNull(setCookie(refused, "cognito"));
+ }
+
+ /**
+ * The right code is used up before PostAuthentication runs, so when the trigger fails the page goes back to
+ * the username with the trigger's error, instead of asking again for a code that can no longer sign in.
+ */
+ @Test
+ void failedPostAuthenticationAfterTheRightCodeGoesBackToTheUsernameStep() throws Exception {
+ PasswordlessPool pool = newPasswordlessPool(List.of("EMAIL_OTP"), false,
+ Map.of("PostAuthentication", POST_AUTHENTICATION_ARN));
+ when(lambdaService.invoke(anyString(), eq(POST_AUTHENTICATION_ARN), any(), any()))
+ .thenReturn(new InvokeResult(200, "Unhandled",
+ MAPPER.writeValueAsBytes(Map.of("errorMessage", "audit log unavailable")), null, "req-id"));
+ Response codeStep = post(null, loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId())),
+ Map.of("username", pool.email()));
+
+ Response failed = post(null, codeStep, Map.of("code", latestEmailCode(pool.email())));
+
+ String html = failed.then().statusCode(400).contentType(startsWith("text/html")).extract().asString();
+ assertTrue(html.contains("<p role=\"alert\">PostAuthentication failed with error audit log unavailable</p>"), html);
+ assertNull(input(html, "code"), "the code is used up, so the page does not ask for it again");
+ assertNull(hiddenFields(html).get("session"), html);
+ assertTrue(input(html, "username").contains("value=\"" + pool.email() + "\""), html);
+ assertNull(failed.getHeader("Location"));
+ assertNull(setCookie(failed, "cognito"));
+ }
+
+ /**
+ * Asking for a code again within the resend limit shows the code step as the first request did, and the code
+ * already sent signs in from it, so the limit cannot tell a username with an account from one without.
+ */
+ @Test
+ void askingForACodeAgainWithinTheResendLimitStillShowsTheCodeStep() throws Exception {
+ PasswordlessPool pool = newPasswordlessPool(List.of("EMAIL_OTP"), false);
+ post(null, loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId())),
+ Map.of("username", pool.email())).then().statusCode(200);
+
+ Response again = post(null, loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId())),
+ Map.of("username", pool.email()));
+
+ assertNotNull(input(again.then().statusCode(200).extract().asString(), "code"), again.asString());
+ Response signedIn = post(null, again, Map.of("code", latestEmailCode(pool.email())));
+ redeem(null, pool.clientId(), code(signedIn), VERIFIER).then().statusCode(200);
+ }
+
+ /** An unknown user is asked for a code like anyone else, so the page does not tell who has an account. */
+ @Test
+ void unknownUserIsAskedForACodeThatNeverSignsIn() throws Exception {
+ PasswordlessPool pool = newPasswordlessPool(List.of("EMAIL_OTP"), false);
+ String nobody = "nobody-" + System.nanoTime() + "@example.com";
+
+ Response codeStep = post(null, loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId())),
+ Map.of("username", nobody));
+ assertNotNull(input(codeStep.then().statusCode(200).extract().asString(), "code"), codeStep.asString());
+ assertEquals(0, emailsTo(nobody).size(), "nothing is sent to an address with no account");
+
+ Response refused = post(null, codeStep, Map.of("code", "123456"));
+
+ refused.then().statusCode(400);
+ assertNull(refused.getHeader("Location"));
+ assertTrue(refused.asString().contains("<p role=\"alert\">Invalid verification code provided, please try again.</p>"),
+ refused.asString());
+ }
+
+ @Test
+ void passwordIsRefusedWhenThePolicyAllowsOnlyEmailCodes() throws Exception {
+ PasswordlessPool pool = newPasswordlessPool(List.of("EMAIL_OTP"), true);
+
+ Response refused = post(null, loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId())),
+ Map.of("username", pool.email(), "password", PASSWORD));
+
+ refused.then().statusCode(400).contentType(startsWith("text/html"));
+ assertNull(refused.getHeader("Location"));
+ assertNull(setCookie(refused, "cognito"));
+ }
+
+ /**
+ * Choice-based sign-in needs EMAIL_OTP in the sign-in policy and USER_AUTH on the client; without
+ * either, the page is the username and password form of before, and it signs in the same way.
+ */
+ @Test
+ void passwordFormStaysWithoutAnEmailCodePolicyOrWithoutUserAuthOnTheClient() throws Exception {
+ PasswordlessPool passwordPolicy = newPasswordlessPool(List.of("PASSWORD"), true);
+ PasswordlessPool withoutUserAuth = newPasswordlessPool(List.of("PASSWORD", "EMAIL_OTP"), true);
+ cognitoAction("UpdateUserPoolClient", """
+ {"UserPoolId":"%s","ClientId":"%s","AllowedOAuthFlowsUserPoolClient":true,"AllowedOAuthFlows":["code"],
+ "AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],
+ "ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]}
+ """.formatted(withoutUserAuth.poolId(), withoutUserAuth.clientId(), CALLBACK)).then().statusCode(200);
+
+ for (PasswordlessPool pool : List.of(passwordPolicy, withoutUserAuth)) {
+ Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()));
+ assertEquals("<input id=\"password\" name=\"password\" type=\"password\" autocomplete=\"current-password\" "
+ + "required>", input(page.asString(), "password"));
+ Response signedIn = submit(null, page, pool.email(), PASSWORD);
+ redeem(null, pool.clientId(), code(signedIn), VERIFIER).then().statusCode(200);
+ }
+ }
+
/** Without a custom domain Host, /login stays S3's path-style bucket route. */
@Test
void loginOnFlocisOwnHostIsNotManagedLogin() {
@@ -823,6 +1159,103 @@ class CognitoManagedLoginIntegrationTest {
return new Pool(poolId, clientId, user.path("Username").asText(), sub);
}
+ /** A pool with email usernames and a sign-in policy, a client that allows USER_AUTH, and a user with a verified email. */
+ private record PasswordlessPool(String poolId, String clientId, String email, String sub) {
+ }
+
+ private static PasswordlessPool newPasswordlessPool(List<String> firstFactors, boolean withPassword)
+ throws Exception {
+ return newPasswordlessPool(firstFactors, withPassword, Map.of());
+ }
+
+ private static PasswordlessPool newPasswordlessPool(List<String> firstFactors, boolean withPassword,
+ Map<String, String> lambdaConfig) throws Exception {
+ String poolId = cognitoJson("CreateUserPool", """
+ {"PoolName":"PasswordlessPool","UsernameAttributes":["email"],
+ "Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":%s}},"LambdaConfig":%s}
+ """.formatted(MAPPER.writeValueAsString(firstFactors), MAPPER.writeValueAsString(lambdaConfig)))
+ .path("UserPool").path("Id").asText();
+ String clientId = cognitoJson("CreateUserPoolClient", """
+ {"UserPoolId":"%s","ClientName":"passwordless","AllowedOAuthFlowsUserPoolClient":true,
+ "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"],
+ "SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_USER_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]}
+ """.formatted(poolId, CALLBACK)).path("UserPoolClient").path("ClientId").asText();
+ String email = addEmailUser(poolId, withPassword, true);
+ JsonNode user = cognitoJson("AdminGetUser", """
+ {"UserPoolId":"%s","Username":"%s"}
+ """.formatted(poolId, email));
+ String sub = null;
+ for (JsonNode attribute : user.path("UserAttributes")) {
+ if ("sub".equals(attribute.path("Name").asText())) {
+ sub = attribute.path("Value").asText();
+ }
+ }
+ return new PasswordlessPool(poolId, clientId, email, sub);
+ }
+
+ /**
+ * Adds a user whose username is a new email address, verified or not, with {@link #PASSWORD} as their
+ * permanent password when {@code withPassword}, and returns the address.
+ */
+ private static String addEmailUser(String poolId, boolean withPassword, boolean emailVerified) throws Exception {
+ String email = "passwordless-" + System.nanoTime() + "@example.com";
+ cognitoAction("AdminCreateUser", """
+ {"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS",
+ "UserAttributes":[{"Name":"email","Value":"%s"},{"Name":"email_verified","Value":"%s"}]}
+ """.formatted(poolId, email, email, emailVerified)).then().statusCode(200);
+ if (withPassword) {
+ cognitoAction("AdminSetUserPassword", """
+ {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
+ """.formatted(poolId, email, PASSWORD)).then().statusCode(200);
+ }
+ return email;
+ }
+
+ /** A user with a password and a verified email who is disabled, and so cannot sign in. */
+ private static String disabledUser(String poolId) throws Exception {
+ String email = addEmailUser(poolId, true, true);
+ cognitoAction("AdminDisableUser", """
+ {"UserPoolId":"%s","Username":"%s"}
+ """.formatted(poolId, email)).then().statusCode(200);
+ return email;
+ }
+
+ /** A user with a verified email whose password an administrator reset, so they cannot sign in until they set one. */
+ private static String resetRequiredUser(String poolId) throws Exception {
+ String email = addEmailUser(poolId, true, true);
+ cognitoAction("AdminResetUserPassword", """
+ {"UserPoolId":"%s","Username":"%s"}
+ """.formatted(poolId, email)).then().statusCode(200);
+ return email;
+ }
+
+ /**
+ * {@code html} with the values that differ from one rendering to the next blanked: the CSRF token, the
+ * username and the USER_AUTH session.
+ */
+ private static String withoutPerRequestValues(String html) {
+ return html.replaceAll("name=\"(_csrf|username|session)\" value=\"[^\"]*\"", "name=\"$1\" value=\"\"");
+ }
+
+ /** The code in the one message Floci's SES holds for {@code email}. */
+ private static String latestEmailCode(String email) throws Exception {
+ JsonNode messages = emailsTo(email);
+ assertEquals(1, messages.size(), messages.toString());
+ Matcher matcher = SIX_DIGIT_CODE.matcher(messages.get(0).path("Body").path("text_part").asText());
+ assertTrue(matcher.find(), messages.toString());
+ return matcher.group(1);
+ }
+
+ private static JsonNode emailsTo(String email) throws Exception {
+ String body = given().queryParam("email", email).when().get("/_aws/ses")
+ .then().statusCode(200).extract().asString();
+ return MAPPER.readTree(body).path("messages");
+ }
+
+ private static String differentCode(String code) {
+ return "000000".equals(code) ? "000001" : "000000";
+ }
+
/** A PKCE authorization request, as a single-page app sends one. */
private static Map<String, String> authorizeRequest(String clientId) {
Map<String, String> query = new LinkedHashMap<>();
@@ -878,6 +1311,20 @@ class CognitoManagedLoginIntegrationTest {
return request.when().post(formAction(html));
}
+ /** Submits a page's form as a browser does: its hidden fields and CSRF cookie, with {@code fields} filled in. */
+ private static Response post(String host, Response page, Map<String, String> fields) {
+ String html = page.asString();
+ Map<String, String> form = new LinkedHashMap<>(hiddenFields(html));
+ form.putAll(fields);
+ RequestSpecification request = given().redirects().follow(false)
+ .cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))
+ .formParams(form);
+ if (host != null) {
+ request.header("Host", host);
+ }
+ return request.when().post(formAction(html));
+ }
+
/** Signs a fresh browser in through the authorize endpoint and returns the redirect to the callback. */
private static Response signIn(String host, Pool pool, Map<String, String> query) {
Response page = loginPage(host, host == null ? "/cognito-idp/oauth2/authorize" : "/oauth2/authorize", query);
@@ -945,6 +1392,12 @@ class CognitoManagedLoginIntegrationTest {
return fields;
}
+ /** The {@code <input>} element with {@code id}, or null when the page has none. */
+ private static String input(String html, String id) {
+ Matcher matcher = Pattern.compile("<input id=\"" + Pattern.quote(id) + "\"[^>]*>").matcher(html);
+ return matcher.find() ? matcher.group() : null;
+ }
+
private static String formAction(String html) {
Matcher matcher = FORM_ACTION.matcher(html);
assertTrue(matcher.find(), html);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java
index e54ece597c..0300573fb2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java
@@ -74,7 +74,7 @@ class CognitoOAuthControllerTest {
.thenReturn("https://provider.example.test/authorize?state=provider-state");
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", "nonce",
- "ExampleOidc", " relying-party-state ", RFC_7636_CHALLENGE, "S256", null);
+ "ExampleOidc", " relying-party-state ", RFC_7636_CHALLENGE, "S256", null, null);
assertEquals(302, response.getStatus());
assertEquals("https://provider.example.test/authorize?state=provider-state", response.getHeaderString("Location"));
@@ -86,7 +86,7 @@ class CognitoOAuthControllerTest {
.thenThrow(new AwsException("ResourceNotFoundException", "Client not found", 400));
Response response = controller.authorize(requestContext(null), "missing-client", CALLBACK_URI, "code", "openid", null,
- "ExampleOidc", null, null, null, null);
+ "ExampleOidc", null, null, null, null, null);
assertOAuthError(response, "invalid_client");
}
@@ -94,7 +94,7 @@ class CognitoOAuthControllerTest {
@Test
void authorizeReturnsInvalidRequestForUnregisteredRedirectUri() {
Response response = controller.authorize(requestContext(null), CLIENT_ID, "https://other.example.test/callback", "code", "openid",
- null, "ExampleOidc", null, null, null, null);
+ null, "ExampleOidc", null, null, null, null, null);
assertOAuthError(response, "invalid_request");
}
@@ -102,7 +102,7 @@ class CognitoOAuthControllerTest {
@Test
void authorizeReturnsUnsupportedResponseTypeForTokenResponse() {
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "token", "openid", null, "ExampleOidc",
- null, null, null, null);
+ null, null, null, null, null);
assertOAuthError(response, "unsupported_response_type");
}
@@ -110,7 +110,7 @@ class CognitoOAuthControllerTest {
@Test
void authorizeWithoutIdentityProviderRedirectsToTheLoginEndpointWithTheRequest() {
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid email",
- "nonce", null, "state & more", RFC_7636_CHALLENGE, "S256", null);
+ "nonce", null, "state & more", RFC_7636_CHALLENGE, "S256", null, null);
assertEquals(302, response.getStatus());
assertEquals("/cognito-idp/login?response_type=code&client_id=" + CLIENT_ID
@@ -120,10 +120,23 @@ class CognitoOAuthControllerTest {
response.getHeaderString("Location"));
}
+ /** AWS: "managed login fills the username field with your hint value", so the redirect carries it. */
+ @Test
+ void authorizeCarriesTheLoginHintToTheLoginEndpoint() {
+ Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid",
+ null, null, "s1", null, null, "[email protected]", null);
+
+ assertEquals(302, response.getStatus());
+ assertEquals("/cognito-idp/login?response_type=code&client_id=" + CLIENT_ID
+ + "&redirect_uri=https%3A%2F%2Fapplication.example.test%2Fcallback&scope=openid&state=s1"
+ + "&login_hint=user%40example.com",
+ response.getHeaderString("Location"));
+ }
+
@Test
void authorizeWithCognitoProviderOnACustomDomainRedirectsToItsLoginPath() {
Response response = controller.authorize(requestContext(POOL_ID), CLIENT_ID, CALLBACK_URI, "code", null, null,
- "COGNITO", null, null, null, null);
+ "COGNITO", null, null, null, null, null);
assertEquals(302, response.getStatus());
assertEquals("/login?response_type=code&client_id=" + CLIENT_ID
@@ -135,7 +148,7 @@ class CognitoOAuthControllerTest {
client.setSupportedIdentityProviders(List.of("ExampleOidc"));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", null,
- null, null, null, null, null);
+ null, null, null, null, null, null);
assertOAuthError(response, "invalid_request");
}
@@ -152,7 +165,7 @@ class CognitoOAuthControllerTest {
void authorizeRejectsUnusablePkceParametersForEitherProvider(String challenge, String method) {
for (String provider : new String[] {null, "ExampleOidc"}) {
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", null,
- provider, null, challenge, method, null);
+ provider, null, challenge, method, null, null);
assertOAuthError(response, "invalid_request");
String description = ((JsonNode) response.getEntity()).path("error_description").asText();
@@ -165,14 +178,14 @@ class CognitoOAuthControllerTest {
void authorizeRedirectsAScopeTheClientIsNotAllowedToTheCallbackForEitherProvider() {
for (String provider : new String[] {null, "COGNITO", "ExampleOidc"}) {
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid phone",
- null, provider, "s1", null, null, null);
+ null, provider, "s1", null, null, null, null);
assertEquals(302, response.getStatus());
assertEquals(CALLBACK_URI + "?error_description=invalid_scope&state=s1&error=invalid_request",
response.getHeaderString("Location"));
}
Response withoutState = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code",
- "aws.cognito.signin.user.admin", null, null, null, null, null, null);
+ "aws.cognito.signin.user.admin", null, null, null, null, null, null, null);
assertEquals(CALLBACK_URI + "?error_description=invalid_scope&error=invalid_request",
withoutState.getHeaderString("Location"));
verify(federationService, never()).beginAuthorization(any(), any(), any(), any(), any(), any(), any(), any(),
@@ -207,7 +220,7 @@ class CognitoOAuthControllerTest {
new CognitoManagedLoginService(cognitoService, stateStore, CLOCK));
String toProvider = federating.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
- "ExampleOidc", "s1", null, null, null).getHeaderString("Location");
+ "ExampleOidc", "s1", null, null, null, null).getHeaderString("Location");
String toCallback = federating.idpResponse(requestContext(null), queryParameter(toProvider, "state"),
"provider-code", null, null).getHeaderString("Location");
@@ -223,9 +236,9 @@ class CognitoOAuthControllerTest {
CLOCK.instant().plusSeconds(60)));
String withoutScope = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
- null, null, null, null, sessionId).getHeaderString("Location");
- String withScope = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "email email",
null, null, null, null, null, sessionId).getHeaderString("Location");
+ String withScope = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "email email",
+ null, null, null, null, null, null, sessionId).getHeaderString("Location");
assertEquals(List.of("openid", "email"), storedCode(withoutScope).scopes());
assertEquals(List.of("email"), storedCode(withScope).scopes());
@@ -238,7 +251,7 @@ class CognitoOAuthControllerTest {
CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", "nonce",
- null, "relying-party-state", RFC_7636_CHALLENGE, "S256", sessionId);
+ null, "relying-party-state", RFC_7636_CHALLENGE, "S256", null, sessionId);
assertEquals(302, response.getStatus());
String location = response.getHeaderString("Location");
@@ -257,7 +270,7 @@ class CognitoOAuthControllerTest {
CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
- null, null, null, null, sessionId);
+ null, null, null, null, null, sessionId);
assertEquals(302, response.getStatus());
assertTrue(response.getHeaderString("Location").startsWith("/cognito-idp/login?"));
@@ -273,7 +286,7 @@ class CognitoOAuthControllerTest {
CLOCK.instant().plusSeconds(60)));
Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,
- null, null, null, null, sessionId);
+ null, null, null, null, null, sessionId);
assertTrue(response.getHeaderString("Location").startsWith("/cognito-idp/login?"));
assertTrue(stateStore.findSession(sessionId).isEmpty());
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
index 6bf6244cbd..b22a1e407a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
@@ -21,6 +21,7 @@ import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
+import io.github.hectorvent.floci.services.cognito.verification.SlowVerificationCodeStore;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
@@ -41,11 +42,13 @@ import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.*;
@@ -57,6 +60,9 @@ import static org.mockito.Mockito.*;
class CognitoServiceTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
+ /** What AWS's DescribeUserPool reports for a pool created without a SignInPolicy. */
+ private static final Map<String, Object> DEFAULT_SIGN_IN_POLICY =
+ Map.of("AllowedFirstAuthFactors", List.of("PASSWORD"));
@Test
void authSessionValiditySurvivesSerializationAndDefaultsForLegacyClients() throws Exception {
@@ -160,7 +166,8 @@ class CognitoServiceTest {
Map<String, Object> expectedPasswordPolicy = new HashMap<>();
expectedPasswordPolicy.put("MinimumLength", 12);
expectedPasswordPolicy.put("TemporaryPasswordValidityDays", 7);
- assertEquals(Map.of("PasswordPolicy", expectedPasswordPolicy), pool.getPolicies());
+ assertEquals(Map.of("PasswordPolicy", expectedPasswordPolicy, "SignInPolicy", DEFAULT_SIGN_IN_POLICY),
+ pool.getPolicies());
assertEquals(List.of("email"), pool.getUsernameAttributes());
}
@@ -657,7 +664,8 @@ class CognitoServiceTest {
Map<String, Object> expectedPasswordPolicy = new HashMap<>();
expectedPasswordPolicy.put("MinimumLength", 7);
expectedPasswordPolicy.put("TemporaryPasswordValidityDays", 7);
- assertEquals(Map.of("PasswordPolicy", expectedPasswordPolicy), pool.getPolicies());
+ assertEquals(Map.of("PasswordPolicy", expectedPasswordPolicy, "SignInPolicy", DEFAULT_SIGN_IN_POLICY),
+ pool.getPolicies());
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "no-requirements-client", false, false, List.of(), List.of());
@@ -687,7 +695,8 @@ class CognitoServiceTest {
expectedPasswordPolicy.put("RequireNumbers", false);
expectedPasswordPolicy.put("RequireSymbols", false);
expectedPasswordPolicy.put("TemporaryPasswordValidityDays", 7);
- assertEquals(Map.of("PasswordPolicy", expectedPasswordPolicy), pool.getPolicies());
+ assertEquals(Map.of("PasswordPolicy", expectedPasswordPolicy, "SignInPolicy", DEFAULT_SIGN_IN_POLICY),
+ pool.getPolicies());
}
@Test
@@ -2750,17 +2759,59 @@ class CognitoServiceTest {
assertEquals("InvalidParameterException", ex.getErrorCode());
}
+ /** A preferred challenge the user has not set up gets the choice of those they have, as AWS answers it. */
@Test
- void initiateAuthWithUserAuthRejectsAnUnavailablePreferredChallenge() {
- // alice has neither a password nor an SRP verifier at this point: not confirmed yet.
+ void initiateAuthWithUserAuthOffersTheChoiceForAPreferredChallengeTheUserHasNotSetUp() {
+ // alice has a temporary password, and this service sends no codes, so EMAIL_OTP is not hers to take.
UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
- UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
+ UserPoolClient client = openClient(service, pool.getId(), "c", false);
service.adminCreateUser(pool.getId(), "alice", Map.of("email", "[email protected]"), "TempPass1!");
- AwsException ex = assertThrows(AwsException.class, () -> service.initiateAuth(
- client.getClientId(), "USER_AUTH",
- Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP")));
- assertEquals("InvalidParameterException", ex.getErrorCode());
+ Map<String, Object> result = service.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP"));
+
+ assertEquals("SELECT_CHALLENGE", result.get("ChallengeName"));
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), result.get("AvailableChallenges"));
+ }
+
+ /** A PREFERRED_CHALLENGE naming no challenge Cognito supports is refused with AWS's message, for any username. */
+ @Test
+ void initiateAuthWithUserAuthRefusesAPreferredChallengeCognitoDoesNotSupport() {
+ UserPool pool = createPoolAndUser();
+ UserPoolClient client = openClient(service, pool.getId(), "c", false);
+ service.describeUserPoolClient(client.getClientId()).setPreventUserExistenceErrors("ENABLED");
+
+ for (String username : List.of("alice", "nobody")) {
+ AwsException ex = assertThrows(AwsException.class, () -> service.initiateAuth(client.getClientId(),
+ "USER_AUTH", Map.of("USERNAME", username, "PREFERRED_CHALLENGE", "BOGUS")));
+ assertEquals("InvalidParameterException", ex.getErrorCode(), username);
+ assertEquals("The preferred challenge must be one of the supported challenges. "
+ + "[PASSWORD, PASSWORD_SRP, SMS_OTP, EMAIL_OTP, WEB_AUTHN]", ex.getMessage(), username);
+ }
+ }
+
+ /**
+ * With user existence errors prevented, an unknown user's PREFERRED_CHALLENGE is answered as a known
+ * user's would be: with that challenge when the sign-in policy allows it, and with the choice of the
+ * policy's factors when it does not.
+ */
+ @Test
+ void initiateAuthWithUserAuthAnswersAnUnknownUsersPreferredChallengeAsAKnownUsers() {
+ UserPool pool = service.createUserPool(Map.of(
+ "PoolName", "TestPool",
+ "Policies", Map.of("SignInPolicy", Map.of(
+ "AllowedFirstAuthFactors", List.of("PASSWORD", "SMS_OTP")))), "us-east-1");
+ UserPoolClient client = openClient(service, pool.getId(), "c", false);
+ service.describeUserPoolClient(client.getClientId()).setPreventUserExistenceErrors("ENABLED");
+
+ Map<String, Object> allowed = service.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "nobody", "PREFERRED_CHALLENGE", "SMS_OTP"));
+ Map<String, Object> disallowed = service.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "nobody", "PREFERRED_CHALLENGE", "EMAIL_OTP"));
+
+ assertEquals("SMS_OTP", allowed.get("ChallengeName"));
+ assertEquals("SELECT_CHALLENGE", disallowed.get("ChallengeName"));
+ assertEquals(List.of("PASSWORD", "SMS_OTP"), disallowed.get("AvailableChallenges"));
}
@Test
@@ -3215,7 +3266,7 @@ class CognitoServiceTest {
mock(TlsCertificateManager.class)
);
- UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "PASSWORD", "EMAIL_OTP");
UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("email", "[email protected]", "email_verified", "true"), "TempPass1!");
@@ -3271,7 +3322,7 @@ class CognitoServiceTest {
mock(TlsCertificateManager.class)
);
- UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "PASSWORD", "SMS_OTP");
UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("phone_number", "+15551234567", "phone_number_verified", "true"), "TempPass1!");
@@ -3329,7 +3380,7 @@ class CognitoServiceTest {
mock(TlsCertificateManager.class)
);
- UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "PASSWORD", "EMAIL_OTP");
UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("email", "[email protected]", "email_verified", "true"), "TempPass1!");
@@ -3345,6 +3396,393 @@ class CognitoServiceTest {
assertEquals("CodeMismatchException", ex.getErrorCode());
}
+ /** AWS, pool policy [PASSWORD]: a user with a password and a verified email gets SELECT_CHALLENGE with PASSWORD_SRP and PASSWORD. */
+ @Test
+ @SuppressWarnings("unchecked")
+ void initiateAuthWithUserAuthOffersOnlyTheFirstFactorsTheSignInPolicyAllows() {
+ CognitoService serviceWithVerification = serviceWithEmailOtpCode("654321");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "PASSWORD");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ createUserWithVerifiedEmail(serviceWithVerification, pool, "Perm1234!");
+
+ Map<String, Object> result = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice"));
+
+ assertEquals("SELECT_CHALLENGE", result.get("ChallengeName"));
+ assertEquals(Set.of("PASSWORD", "PASSWORD_SRP"), Set.copyOf((List<String>) result.get("AvailableChallenges")));
+ }
+
+ @Test
+ void initiateAuthWithUserAuthOffersOnlyEmailOtpWhenThePolicyAllowsOnlyEmailOtp() {
+ CognitoService serviceWithVerification = serviceWithEmailOtpCode("654321");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "EMAIL_OTP");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ createUserWithVerifiedEmail(serviceWithVerification, pool, "Perm1234!");
+
+ Map<String, Object> result = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice"));
+
+ assertEquals("SELECT_CHALLENGE", result.get("ChallengeName"));
+ assertEquals(List.of("EMAIL_OTP"), result.get("AvailableChallenges"));
+ }
+
+ @Test
+ void initiateAuthWithUserAuthOffersNoPasswordChallengeToAUserWithoutAPassword() {
+ CognitoService serviceWithVerification = serviceWithEmailOtpCode("654321");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "PASSWORD", "EMAIL_OTP");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ createUserWithVerifiedEmail(serviceWithVerification, pool, null);
+
+ Map<String, Object> result = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice"));
+
+ assertEquals(List.of("EMAIL_OTP"), result.get("AvailableChallenges"));
+ }
+
+ /** Observed on AWS: a pool created without a SignInPolicy, on any tier, describes it as PASSWORD alone. */
+ @ParameterizedTest
+ @CsvSource({"LITE", "ESSENTIALS", "PLUS"})
+ void createUserPoolDefaultsTheSignInPolicyToPasswordAlone(String tier) {
+ UserPool pool = service.createUserPool(Map.of("PoolName", "TestPool", "UserPoolTier", tier), "us-east-1");
+
+ assertEquals(Map.of("SignInPolicy", DEFAULT_SIGN_IN_POLICY),
+ service.describeUserPool(pool.getId()).getPolicies());
+ }
+
+ /**
+ * UpdateUserPool keeps a pool's policies when the request names none, as it keeps every member it omits,
+ * and a Policies without a SignInPolicy replaces them whole, so the sign-in policy is its default again.
+ */
+ @Test
+ void updateUserPoolKeepsTheSignInPolicyOrPutsTheDefaultBack() {
+ UserPool pool = poolWithFirstFactors(service, "PASSWORD", "EMAIL_OTP");
+
+ service.updateUserPool(Map.of("UserPoolId", pool.getId()), "us-east-1");
+ assertEquals(Map.of("AllowedFirstAuthFactors", List.of("PASSWORD", "EMAIL_OTP")),
+ service.describeUserPool(pool.getId()).getPolicies().get("SignInPolicy"));
+
+ service.updateUserPool(Map.of("UserPoolId", pool.getId(),
+ "Policies", Map.of("PasswordPolicy", Map.of("MinimumLength", 8))), "us-east-1");
+ assertEquals(DEFAULT_SIGN_IN_POLICY, service.describeUserPool(pool.getId()).getPolicies().get("SignInPolicy"));
+ }
+
+ /**
+ * A pool without a SignInPolicy, created so or persisted by a Floci that did not store the default yet,
+ * allows PASSWORD alone, as AWS's default does: a user with a verified email is offered no EMAIL_OTP.
+ */
+ @Test
+ void initiateAuthWithUserAuthOffersOnlyPasswordChallengesWithoutASignInPolicy() {
+ CognitoService serviceWithVerification = serviceWithEmailOtpCode("654321");
+ UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ createUserWithVerifiedEmail(serviceWithVerification, pool, "Perm1234!");
+
+ Map<String, Object> created = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice"));
+ serviceWithVerification.describeUserPool(pool.getId()).setPolicies(null);
+ Map<String, Object> persisted = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice"));
+
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), created.get("AvailableChallenges"));
+ assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), persisted.get("AvailableChallenges"));
+ }
+
+ /**
+ * 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 InitiateAuth without one: SELECT_CHALLENGE and the challenges
+ * they can take. Nothing is sent meanwhile.
+ */
+ @ParameterizedTest
+ @CsvSource({"PASSWORD", "SMS_OTP", "WEB_AUTHN"})
+ void initiateAuthWithUserAuthOffersTheChoiceForAPreferredChallengeTheUserCannotTake(String preferred) {
+ VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
+ CognitoService serviceWithVerification = serviceWithVerification(verificationCodeService);
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "EMAIL_OTP", "SMS_OTP");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ createUserWithVerifiedEmail(serviceWithVerification, pool, "Perm1234!");
+
+ Map<String, Object> result = serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", preferred));
+
+ assertEquals("SELECT_CHALLENGE", result.get("ChallengeName"));
+ assertEquals(List.of("EMAIL_OTP"), result.get("AvailableChallenges"));
+ assertNotNull(result.get("Session"));
+ verify(verificationCodeService, never()).issue(any(), any(), any(), any());
+ }
+
+ /** Only PREFERRED_CHALLENGE falls back: an answer to SELECT_CHALLENGE outside the choice offered is refused. */
+ @Test
+ void respondToSelectChallengeRefusesAnAnswerThePolicyDisallows() {
+ CognitoService serviceWithVerification = serviceWithEmailOtpCode("654321");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "EMAIL_OTP");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ createUserWithVerifiedEmail(serviceWithVerification, pool, "Perm1234!");
+ String session = (String) serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice")).get("Session");
+
+ AwsException answer = assertThrows(AwsException.class, () -> serviceWithVerification.respondToAuthChallenge(
+ client.getClientId(), "SELECT_CHALLENGE", session,
+ Map.of("USERNAME", "alice", "ANSWER", "PASSWORD_SRP", "SRP_A", "ABCDEF1234567890")));
+ assertEquals("InvalidParameterException", answer.getErrorCode());
+ }
+
+ /** Managed login asks again after a wrong code, so the USER_AUTH session must outlive one. */
+ @Test
+ void managedLoginEmailOtpKeepsTheSessionForAnotherTryAfterAWrongCode() {
+ VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
+ when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any()))
+ .thenReturn("654321");
+ doThrow(new VerificationCodeException(VerificationCodeException.Kind.MISMATCH, "nope"))
+ .when(verificationCodeService).consume(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP),
+ eq("000000"));
+ CognitoService serviceWithVerification = serviceWithVerification(verificationCodeService);
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "EMAIL_OTP");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ createUserWithVerifiedEmail(serviceWithVerification, pool, null);
+
+ String session = serviceWithVerification.startManagedLoginEmailOtp(client, "alice");
+ AwsException wrong = assertThrows(AwsException.class,
+ () -> serviceWithVerification.completeManagedLoginEmailOtp(client, session, "000000"));
+ assertEquals("CodeMismatchException", wrong.getErrorCode());
+
+ assertEquals("alice", serviceWithVerification.completeManagedLoginEmailOtp(client, session, "654321")
+ .getUsername());
+ AwsException replayed = assertThrows(AwsException.class,
+ () -> serviceWithVerification.completeManagedLoginEmailOtp(client, session, "654321"));
+ assertEquals("NotAuthorizedException", replayed.getErrorCode(), "a session that signed in is spent");
+ }
+
+ /**
+ * Requests answering one session with its code at the same moment, from the sign-in page or from
+ * RespondToAuthChallenge, sign in once: the code store redeems the code once, and the others find it
+ * used or the session spent. The store reads the code a moment late, so they would all find it unused
+ * if redeeming it were not one step.
+ */
+ @Test
+ void managedLoginEmailOtpSignsInOnceWhenTheSameCodeArrivesConcurrently() throws Exception {
+ AtomicReference<String> sentCode = new AtomicReference<>();
+ CognitoService serviceWithVerification = serviceWithSlowCodeStore(Clock.systemUTC(), sentCode);
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "EMAIL_OTP");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ createUserWithVerifiedEmail(serviceWithVerification, pool, null);
+ int callers = 8;
+ ExecutorService executor = Executors.newFixedThreadPool(callers);
+ try {
+ for (int round = 0; round < 10; round++) {
+ String session = serviceWithVerification.startManagedLoginEmailOtp(client, "alice");
+ String code = sentCode.get();
+ CountDownLatch ready = new CountDownLatch(callers);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<Boolean>> outcomes = new ArrayList<>();
+ for (int caller = 0; caller < callers; caller++) {
+ boolean throughTheApi = caller % 2 == 1;
+ outcomes.add(executor.submit(() -> {
+ ready.countDown();
+ start.await();
+ try {
+ if (throughTheApi) {
+ serviceWithVerification.respondToAuthChallenge(client.getClientId(), "EMAIL_OTP",
+ session, Map.of("USERNAME", "alice", "EMAIL_OTP_CODE", code));
+ } else {
+ serviceWithVerification.completeManagedLoginEmailOtp(client, session, code);
+ }
+ return true;
+ } catch (AwsException e) {
+ assertTrue(Set.of("CodeMismatchException", "NotAuthorizedException")
+ .contains(e.getErrorCode()), e.getErrorCode() + ": " + e.getMessage());
+ return false;
+ }
+ }));
+ }
+ assertTrue(ready.await(10, TimeUnit.SECONDS));
+ start.countDown();
+ int signedIn = 0;
+ for (Future<Boolean> outcome : outcomes) {
+ if (outcome.get(10, TimeUnit.SECONDS)) {
+ signedIn++;
+ }
+ }
+ assertEquals(1, signedIn, "round " + round);
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ /**
+ * Every live EMAIL_OTP or SMS_OTP session of a user takes the user's latest code, so two of them answered
+ * with it at once through RespondToAuthChallenge sign in once: the code store redeems it once. The store
+ * reads the code a moment late, so both would find it unused if redeeming it were not one step.
+ */
+ @ParameterizedTest
+ @CsvSource({"EMAIL_OTP, EMAIL_OTP_CODE, email, [email protected]",
+ "SMS_OTP, SMS_OTP_CODE, phone_number, +15555550100"})
+ void respondToAuthChallengeRedeemsASignInCodeOnceAcrossSessions(String challenge, String codeParameter,
+ String attribute, String destination)
+ throws Exception {
+ MutableClock clock = new MutableClock();
+ AtomicReference<String> sentCode = new AtomicReference<>();
+ CognitoService serviceWithVerification = serviceWithSlowCodeStore(clock, sentCode);
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, challenge);
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ serviceWithVerification.adminCreateUser(pool.getId(), "alice",
+ Map.of(attribute, destination, attribute + "_verified", "true"), null);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ for (int round = 0; round < 10; round++) {
+ List<String> sessions = new ArrayList<>();
+ while (sessions.size() < 2) {
+ sessions.add((String) serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", challenge)).get("Session"));
+ // Past the resend limit, the next session's code replaces this one's, and both take it.
+ clock.advance(Duration.ofSeconds(31));
+ }
+ String code = sentCode.get();
+ CountDownLatch ready = new CountDownLatch(sessions.size());
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<Boolean>> outcomes = new ArrayList<>();
+ for (String session : sessions) {
+ outcomes.add(executor.submit(() -> {
+ ready.countDown();
+ start.await();
+ try {
+ serviceWithVerification.respondToAuthChallenge(client.getClientId(), challenge, session,
+ Map.of("USERNAME", "alice", codeParameter, code));
+ return true;
+ } catch (AwsException e) {
+ assertEquals("CodeMismatchException", e.getErrorCode(), e.getMessage());
+ return false;
+ }
+ }));
+ }
+ assertTrue(ready.await(10, TimeUnit.SECONDS));
+ start.countDown();
+ int signedIn = 0;
+ for (Future<Boolean> outcome : outcomes) {
+ if (outcome.get(10, TimeUnit.SECONDS)) {
+ signedIn++;
+ }
+ }
+ assertEquals(1, signedIn, "round " + round);
+ }
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ /**
+ * Redeeming a code holds up no other user: while one user's code is slow to redeem, from the sign-in page
+ * or from RespondToAuthChallenge, another user starts a USER_AUTH sign-in and answers it with their code.
+ */
+ @ParameterizedTest
+ @CsvSource({"page", "api"})
+ void slowCodeRedemptionForOneUserDoesNotHoldUpAnotherUsersSignIn(String aliceAnswersThrough) throws Exception {
+ VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
+ when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any()))
+ .thenReturn("654321");
+ CountDownLatch aliceRedeeming = new CountDownLatch(1);
+ CountDownLatch releaseAlice = new CountDownLatch(1);
+ doAnswer(invocation -> {
+ aliceRedeeming.countDown();
+ assertTrue(releaseAlice.await(10, TimeUnit.SECONDS));
+ return null;
+ }).when(verificationCodeService).consume(any(), eq("alice"), eq(VerificationCode.Purpose.EMAIL_OTP), any());
+ CognitoService serviceWithVerification = serviceWithVerification(verificationCodeService);
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "EMAIL_OTP");
+ UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
+ for (String username : List.of("alice", "bob")) {
+ serviceWithVerification.adminCreateUser(pool.getId(), username,
+ Map.of("email", username + "@example.com", "email_verified", "true"), null);
+ }
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ String aliceSession = serviceWithVerification.startManagedLoginEmailOtp(client, "alice");
+ Future<Object> alice = executor.submit(() -> "page".equals(aliceAnswersThrough)
+ ? serviceWithVerification.completeManagedLoginEmailOtp(client, aliceSession, "654321")
+ : serviceWithVerification.respondToAuthChallenge(client.getClientId(), "EMAIL_OTP",
+ aliceSession, Map.of("USERNAME", "alice", "EMAIL_OTP_CODE", "654321")));
+ assertTrue(aliceRedeeming.await(10, TimeUnit.SECONDS));
+
+ Future<Map<String, Object>> bob = executor.submit(() -> {
+ String bobSession = (String) serviceWithVerification.initiateAuth(client.getClientId(), "USER_AUTH",
+ Map.of("USERNAME", "bob", "PREFERRED_CHALLENGE", "EMAIL_OTP")).get("Session");
+ return serviceWithVerification.respondToAuthChallenge(client.getClientId(), "EMAIL_OTP", bobSession,
+ Map.of("USERNAME", "bob", "EMAIL_OTP_CODE", "654321"));
+ });
+
+ assertNotNull(bob.get(5, TimeUnit.SECONDS).get("AuthenticationResult"),
+ "bob signs in while alice's code is still being redeemed");
+ releaseAlice.countDown();
+ assertNotNull(alice.get(10, TimeUnit.SECONDS));
+ } finally {
+ releaseAlice.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ /** A service whose EMAIL_OTP code is always {@code code}, with delivery mocked out. */
+ private CognitoService serviceWithEmailOtpCode(String code) {
+ VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
+ when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.EMAIL_OTP), any()))
+ .thenReturn(code);
+ return serviceWithVerification(verificationCodeService);
+ }
+
+ private CognitoService serviceWithVerification(VerificationCodeService verificationCodeService) {
+ return serviceWithVerification(verificationCodeService, mock(CognitoMessageDispatcher.class));
+ }
+
+ private CognitoService serviceWithVerification(VerificationCodeService verificationCodeService,
+ CognitoMessageDispatcher messageDispatcher) {
+ return new CognitoService(
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ "http://localhost:4566",
+ "cloudfront.net",
+ regionResolver,
+ null,
+ acmService,
+ verificationCodeService,
+ messageDispatcher,
+ mock(TlsCertificateManager.class)
+ );
+ }
+
+ /**
+ * A service with the real code store over a {@link SlowVerificationCodeStore}, keeping its codes' time by
+ * {@code clock}, that puts each code it sends in {@code sentCode}.
+ */
+ private CognitoService serviceWithSlowCodeStore(Clock clock, AtomicReference<String> sentCode) {
+ CognitoMessageDispatcher dispatcher = mock(CognitoMessageDispatcher.class);
+ doAnswer(invocation -> {
+ sentCode.set(invocation.getArgument(3));
+ return null;
+ }).when(dispatcher).dispatch(any(), any(), any(), anyString(), any(), any());
+ return serviceWithVerification(new VerificationCodeService(SlowVerificationCodeStore.factory(), clock),
+ dispatcher);
+ }
+
+ private static UserPool poolWithFirstFactors(CognitoService service, String... factors) {
+ return service.createUserPool(Map.of(
+ "PoolName", "TestPool",
+ "Policies", Map.of("SignInPolicy", Map.of("AllowedFirstAuthFactors", List.of(factors)))), "us-east-1");
+ }
+
+ /** Creates alice with a verified email, and with {@code password} as her permanent password unless it is null. */
+ private static void createUserWithVerifiedEmail(CognitoService service, UserPool pool, String password) {
+ service.adminCreateUser(pool.getId(), "alice",
+ Map.of("email", "[email protected]", "email_verified", "true"), null);
+ if (password != null) {
+ service.adminSetUserPassword(pool.getId(), "alice", password, true);
+ }
+ }
+
@Test
void initiateAuthWithUserAuthRejectsMissingSecretHashWhenClientHasSecret() {
UserPool pool = createPoolAndUser();
@@ -3382,7 +3820,7 @@ class CognitoServiceTest {
mock(TlsCertificateManager.class)
);
- UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "PASSWORD", "EMAIL_OTP");
UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("email", "[email protected]", "email_verified", "true"), "TempPass1!");
@@ -3424,7 +3862,7 @@ class CognitoServiceTest {
mock(TlsCertificateManager.class)
);
- UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
+ UserPool pool = poolWithFirstFactors(serviceWithVerification, "PASSWORD", "EMAIL_OTP");
UserPoolClient client = openClient(serviceWithVerification, pool.getId(), "c", false);
serviceWithVerification.adminCreateUser(pool.getId(), "alice",
Map.of("email", "[email protected]", "email_verified", "true"), "TempPass1!");
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/SlowVerificationCodeStore.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/SlowVerificationCodeStore.java
new file mode 100644
index 0000000000..deb9109cd3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/SlowVerificationCodeStore.java
@@ -0,0 +1,56 @@
+package io.github.hectorvent.floci.services.cognito.verification;
+
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+
+import java.util.Optional;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * A verification-code store for concurrency tests. Every read hands back its own copy a moment late, as a
+ * read from disk does, so requests redeeming one code at once all find it unused; and every delete lands a
+ * moment late, after a write another request made meanwhile, so redeeming a code can delete the one a resend
+ * just wrote. Neither happens unless {@link VerificationCodeService} lets one request at a time at a code.
+ */
+public final class SlowVerificationCodeStore extends InMemoryStorage<String, VerificationCode> {
+
+ private SlowVerificationCodeStore() {
+ }
+
+ /** A storage factory that gives a {@link VerificationCodeService} a store of its own like this one. */
+ public static StorageFactory factory() {
+ StorageFactory factory = mock(StorageFactory.class);
+ when(factory.create(anyString(), anyString(), any())).thenAnswer(invocation ->
+ new AccountAwareStorageBackend<>(new SlowVerificationCodeStore(), null, "000000000000"));
+ return factory;
+ }
+
+ @Override
+ public Optional<VerificationCode> get(String key) {
+ Optional<VerificationCode> read = super.get(key).map(code -> new VerificationCode(code.getUserPoolId(),
+ code.getUsername(), code.getPurpose(), code.getCodeHash(), code.getSalt(), code.getIssuedAt(),
+ code.getExpiresAt(), code.getAttemptsRemaining(), code.isConsumed()));
+ pause();
+ return read;
+ }
+
+ @Override
+ public void delete(String key) {
+ pause();
+ super.delete(key);
+ }
+
+ private static void pause() {
+ try {
+ Thread.sleep(20);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Interrupted while waiting on the verification-code store", e);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java
index 71cbb39e5e..88d516b0b2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/VerificationCodeServiceTest.java
@@ -10,6 +10,14 @@ import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -214,6 +222,102 @@ class VerificationCodeServiceTest {
"deleting pool must not invalidate a code issued by pool:child");
}
+ /** A code redeems once: of consumes of it at the same moment, one succeeds and the others find it gone. */
+ @Test
+ void consume_sameCodeConcurrently_redeemsOnce() throws Exception {
+ VerificationCodeService slow = new VerificationCodeService(SlowVerificationCodeStore.factory(), clock);
+ String code = slow.issue("pool", "alice", VerificationCode.Purpose.EMAIL_OTP, Duration.ofMinutes(5));
+
+ List<VerificationCodeException.Kind> outcomes = consumeAtOnce(slow, Collections.nCopies(8, code));
+
+ assertEquals(1, Collections.frequency(outcomes, null), outcomes.toString());
+ assertEquals(7, Collections.frequency(outcomes, VerificationCodeException.Kind.NOT_FOUND),
+ outcomes.toString());
+ }
+
+ /** Wrong codes at the same moment each use up an attempt, so five of them invalidate the code as five in turn do. */
+ @Test
+ void consume_wrongCodesConcurrently_countEveryAttempt() throws Exception {
+ VerificationCodeService slow = new VerificationCodeService(SlowVerificationCodeStore.factory(), clock);
+ String code = slow.issue("pool", "alice", VerificationCode.Purpose.EMAIL_OTP, Duration.ofMinutes(5));
+
+ consumeAtOnce(slow, Collections.nCopies(5, "000000".equals(code) ? "000001" : "000000"));
+
+ VerificationCodeException ex = assertThrows(VerificationCodeException.class,
+ () -> slow.consume("pool", "alice", VerificationCode.Purpose.EMAIL_OTP, code));
+ assertEquals(VerificationCodeException.Kind.NOT_FOUND, ex.getKind());
+ }
+
+ /** A code sent while the one before it is redeemed stays usable: redeeming the old code cannot delete it. */
+ @Test
+ void issue_whilePreviousCodeIsConsumed_leavesTheNewCodeUsable() throws Exception {
+ VerificationCodeService slow = new VerificationCodeService(SlowVerificationCodeStore.factory(), clock);
+ String previous = slow.issue("pool", "alice", VerificationCode.Purpose.EMAIL_OTP, Duration.ofMinutes(5));
+ clock.advance(Duration.ofSeconds(31));
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ CountDownLatch ready = new CountDownLatch(2);
+ CountDownLatch start = new CountDownLatch(1);
+ Future<VerificationCodeException.Kind> redeemed = executor.submit(() -> {
+ ready.countDown();
+ start.await();
+ try {
+ slow.consume("pool", "alice", VerificationCode.Purpose.EMAIL_OTP, previous);
+ return null;
+ } catch (VerificationCodeException e) {
+ return e.getKind();
+ }
+ });
+ Future<String> resent = executor.submit(() -> {
+ ready.countDown();
+ start.await();
+ return slow.issue("pool", "alice", VerificationCode.Purpose.EMAIL_OTP, Duration.ofMinutes(5));
+ });
+ assertTrue(ready.await(10, TimeUnit.SECONDS));
+ start.countDown();
+ VerificationCodeException.Kind previousOutcome = redeemed.get(10, TimeUnit.SECONDS);
+ String code = resent.get(10, TimeUnit.SECONDS);
+
+ assertTrue(previousOutcome == null || previousOutcome == VerificationCodeException.Kind.MISMATCH,
+ "the old code is redeemed, or is wrong once the new one replaced it: " + previousOutcome);
+ assertDoesNotThrow(() -> slow.consume("pool", "alice", VerificationCode.Purpose.EMAIL_OTP, code));
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ /** Consumes each of {@code codes} as alice's EMAIL_OTP at the same moment; null where one succeeded. */
+ private static List<VerificationCodeException.Kind> consumeAtOnce(VerificationCodeService service,
+ List<String> codes) throws Exception {
+ ExecutorService executor = Executors.newFixedThreadPool(codes.size());
+ try {
+ CountDownLatch ready = new CountDownLatch(codes.size());
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<VerificationCodeException.Kind>> futures = new ArrayList<>();
+ for (String code : codes) {
+ futures.add(executor.submit(() -> {
+ ready.countDown();
+ start.await();
+ try {
+ service.consume("pool", "alice", VerificationCode.Purpose.EMAIL_OTP, code);
+ return null;
+ } catch (VerificationCodeException e) {
+ return e.getKind();
+ }
+ }));
+ }
+ assertTrue(ready.await(10, TimeUnit.SECONDS));
+ start.countDown();
+ List<VerificationCodeException.Kind> outcomes = new ArrayList<>();
+ for (Future<VerificationCodeException.Kind> future : futures) {
+ outcomes.add(future.get(10, TimeUnit.SECONDS));
+ }
+ return outcomes;
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
static final class MutableClock extends Clock {
private Instant now;
MutableClock(Instant start) { this.now = start; }