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

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

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

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

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

Refs #4759

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

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

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

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

Refs #4759

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

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

Refs #4759

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

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

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

Refs #4759

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

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

Refs #4759

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

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

Refs #4759

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

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

Refs #4759

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

No files matched your search

@@ -3270,6 +3270,71 @@ class CognitoIntegrationTest {
.body("message", equalTo("Incorrect username or password"));
}
/**
* Observed on AWS with a sign-in policy of PASSWORD: a PREFERRED_CHALLENGE outside the policy, or one the
* user has not set up, gets SELECT_CHALLENGE and the available list, and a name Cognito does not support
* gets InvalidParameterException.
*/
@Test
@Order(112)
void userAuthOffersTheChoiceForAPreferredChallengeTheUserCannotTakeOverTheWire() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{
"PoolName": "PreferredChallengeWirePool",
"Policies": { "SignInPolicy": { "AllowedFirstAuthFactors": ["PASSWORD"] } }
}
""").path("UserPool").path("Id").asText();
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId": "%s", "ClientName": "preferred-challenge-client", "ExplicitAuthFlows": ["ALLOW_USER_AUTH"]}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", """
{"UserPoolId": "%s", "Username": "wire-user", "MessageAction": "SUPPRESS",
"UserAttributes": [{"Name": "email", "Value": "wire-user@example.com"},
{"Name": "email_verified", "Value": "true"}]}
""".formatted(poolId)).then().statusCode(200);
cognitoAction("AdminSetUserPassword", """
{"UserPoolId": "%s", "Username": "wire-user", "Password": "Perm1234!", "Permanent": true}
""".formatted(poolId)).then().statusCode(200);
for (String preferred : List.of("EMAIL_OTP", "WEB_AUTHN")) {
JsonNode result = cognitoJson("InitiateAuth", """
{"ClientId": "%s", "AuthFlow": "USER_AUTH",
"AuthParameters": {"USERNAME": "wire-user", "PREFERRED_CHALLENGE": "%s"}}
""".formatted(clientId, preferred));
assertEquals("SELECT_CHALLENGE", result.path("ChallengeName").asText(), preferred);
assertEquals(List.of("PASSWORD", "PASSWORD_SRP"), textValues(result.path("AvailableChallenges")),
preferred);
assertFalse(result.path("Session").asText().isBlank(), preferred);
}
cognitoAction("InitiateAuth", """
{"ClientId": "%s", "AuthFlow": "USER_AUTH",
"AuthParameters": {"USERNAME": "wire-user", "PREFERRED_CHALLENGE": "BOGUS"}}
""".formatted(clientId))
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"))
.body("message", equalTo("The preferred challenge must be one of the supported challenges. "
+ "[PASSWORD, PASSWORD_SRP, SMS_OTP, EMAIL_OTP, WEB_AUTHN]"));
}
/** Observed on AWS: DescribeUserPool reports a SignInPolicy of PASSWORD for a pool created without one. */
@Test
@Order(113)
void describeUserPoolReportsAPasswordSignInPolicyForAPoolCreatedWithoutOne() throws Exception {
for (String tier : List.of("LITE", "ESSENTIALS")) {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName": "DefaultSignInPolicyPool", "UserPoolTier": "%s"}
""".formatted(tier)).path("UserPool").path("Id").asText();
JsonNode policies = cognitoJson("DescribeUserPool", """
{"UserPoolId": "%s"}
""".formatted(poolId)).path("UserPool").path("Policies");
assertEquals(List.of("PASSWORD"),
textValues(policies.path("SignInPolicy").path("AllowedFirstAuthFactors")), tier);
}
}
private static List<String> textValues(JsonNode array) {
List<String> values = new ArrayList<>();
for (JsonNode value : array) {
@@ -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);
@@ -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, "user@example.com", 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());
@@ -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", "alice@example.com"), "TempPass1!");
AwsException ex = assertThrows(AwsException.class, () -> service.initiateAuth(
client.getClientId(), "USER_AUTH",
Map.of("USERNAME", "alice", "PREFERRED_CHALLENGE", "EMAIL_OTP")));
assertEquals("InvalidParameterException", ex.getErrorCode());
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", "alice@example.com", "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", "alice@example.com", "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, alice@example.com",
"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", "alice@example.com", "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", "alice@example.com", "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", "alice@example.com", "email_verified", "true"), "TempPass1!");
@@ -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);
}
}
}
@@ -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; }