feat(cognito): send signup confirmation links for CONFIRM_WITH_LINK (#7660)

SignUp and ResendConfirmationCode use EmailMessageByLink and
EmailSubjectByLink when DefaultEmailOption is CONFIRM_WITH_LINK, and
replace {##link text##} with a link to /cognito-idp/confirmUser, or to
/confirmUser on a custom domain. Opening the link confirms the user.
Password reset, attribute verification, sign-in codes and SMS stay on
the code template.

The link is built only when that email places it in the body, so code
and SMS deliveries never scan the stored domains. A shared-host
confirmUser request carries no AWS credential, so it confirms in the
account that owns the client id, while a custom domain keeps the
account it pins.

Cognito HTML escaping goes through one helper, CognitoHtml, and the
tests read another account's SES mail through SesMailbox, signed with
EnforcementFixtures.auth.

Closes #5662
This commit is contained in:
XuJian authored and GitHub committed 2026-11-14 21:19:54 -04:00
1 parent 0ac1760155
commit 68f5510ce8
12 files changed
+936 -45

No files matched your search

+19 -5
View File
@@ -217,6 +217,7 @@ POST https://auth.example.localhost.floci.io/oauth2/userInfo
GET https://auth.example.localhost.floci.io/login
POST https://auth.example.localhost.floci.io/login
GET https://auth.example.localhost.floci.io/logout
GET https://auth.example.localhost.floci.io/confirmUser
```
Requests are matched on the `Host` header, so the name must resolve to Floci (any
@@ -225,8 +226,9 @@ the account that created it, since these requests carry no AWS credential: a `cl
another pool is refused with `invalid_client`, and an access token issued by another pool with
`invalid_token`. Domain names are unique across all accounts, as on AWS. The pool's `openid-configuration` advertises the custom-domain
URLs when one exists. Prefix domains (`<prefix>.auth.<region>.amazoncognito.com`) are stored but not
routed, since that hostname never reaches Floci. `/login` and `/logout` are served at the root only
on a custom-domain host; on Floci's own host they are `/cognito-idp/login` and `/cognito-idp/logout`.
routed, since that hostname never reaches Floci. `/login`, `/logout` and `/confirmUser` are served at
the root only on a custom-domain host; on Floci's own host they are `/cognito-idp/login`,
`/cognito-idp/logout` and `/cognito-idp/confirmUser`.
On a custom-domain host, any other path under `/oauth2/` is answered with AWS's JSON 404, and a
served path called with a method it does not serve with an empty 405 whose `Allow` header lists
the methods it does serve. HEAD is answered as GET, as on AWS, except on `/logout`, which AWS
@@ -335,9 +337,9 @@ passwordless pool generates a password. `TemporaryPasswordValidityDays` is not e
| Action | Description |
|--------|-------------|
| SignUp | Creates a self-service user for an app client. |
| SignUp | Creates a self-service user for an app client. With `VerificationMessageTemplate.DefaultEmailOption` of `CONFIRM_WITH_LINK`, the confirmation email carries a link instead of a code. |
| ConfirmSignUp | Confirms a pending self-service signup. |
| ResendConfirmationCode | Issues a new sign-up confirmation code to an unconfirmed user, replacing the previous one, and returns where it was sent. |
| ResendConfirmationCode | Issues a new sign-up confirmation to an unconfirmed user, replacing the previous one, and returns where it was sent. A `CONFIRM_WITH_LINK` pool sends another confirmation link. |
| GetUser | Returns attributes for the authenticated access-token user, and the MFA settings (`UserMFASettingList`, `PreferredMfaSetting`) once any is turned on. |
| GetUserAuthFactors | Returns the authenticated access-token user's sign-in factors: `PASSWORD` when the user has a password, `EMAIL_OTP` and `SMS_OTP` when the email or phone number is verified, whatever the pool's `AllowedFirstAuthFactors` allows, as on AWS, `WEB_AUTHN` once the user has registered a passkey, and `SOFTWARE_TOKEN` once `VerifySoftwareToken` has confirmed an authenticator. The access token must carry the `aws.cognito.signin.user.admin` scope. `UserMFASettingList` and `PreferredMfaSetting` report the SMS, email and software-token MFA preferences set with `SetUserMFAPreference`. |
| GetUserAttributeVerificationCode | Issues a verification code for the authenticated user's email or phone_number attribute. The CustomMessage trigger shapes its message, with triggerSource `CustomMessage_VerifyUserAttribute` and the request's `ClientMetadata`. |
@@ -352,9 +354,20 @@ passwordless pool generates a password. `TemporaryPasswordValidityDays` is not e
| CompleteWebAuthnRegistration | Verifies the `RegistrationResponseJSON` in `Credential` and registers the passkey. |
| ListWebAuthnCredentials | Lists the authenticated access-token user's passkeys, oldest first, up to 20 per page. `NextToken` is a cursor on the last passkey listed, so deleting a passkey between two pages skips none. |
| DeleteWebAuthnCredential | Deletes one of the authenticated access-token user's passkeys. |
| ForgotPassword | Starts the local forgot-password flow for a user. |
| ForgotPassword | Starts the local forgot-password flow for a user. The message stays a code even when the pool's verification type is `CONFIRM_WITH_LINK`. |
| ConfirmForgotPassword | Completes the forgot-password flow by setting a replacement password. |
When `VerificationMessageTemplate.DefaultEmailOption` is `CONFIRM_WITH_LINK`, `SignUp` and
`ResendConfirmationCode` email `EmailSubjectByLink` and `EmailMessageByLink` (or Cognito's default
link message when those are unset). The `{##link text##}` placeholder becomes a link to
`/cognito-idp/confirmUser?client_id&user_name&confirmation_code`, or to `/confirmUser` on a custom
domain. Opening it confirms the user. A shared-host link carries no AWS credential, so the client
id is resolved across accounts and the user is confirmed in the account that owns the client. A
custom domain still confirms in the account that owns the domain. A prefix domain is not used in
the link, because Floci does not serve that hostname. `CONFIRM_WITH_CODE`, and a pool with no verification type, keep the
`{####}` code template. Password reset, attribute verification and sign-in codes stay on that code
template either way. SMS stays a code.
As on AWS, every operation authorized by the user's access token (`GetUser`,
`GetUserAuthFactors`, `UpdateUserAttributes`, `DeleteUserAttributes`, `DeleteUser`,
`ChangePassword`, `GetUserAttributeVerificationCode`, `VerifyUserAttribute`,
@@ -717,6 +730,7 @@ plain, so branding is stored and returned rather than rendered. Two divergences
| `GET /cognito-idp/oauth2/idpresponse` | OIDC provider callback endpoint |
| `GET`, `POST /cognito-idp/login` | Managed login sign-in form |
| `GET /cognito-idp/logout` | Managed login sign-out |
| `GET /cognito-idp/confirmUser` | Confirms a sign-up from a `CONFIRM_WITH_LINK` email |
| `POST /cognito-idp/oauth2/token` | OAuth code, refresh-token and client-credentials token endpoint |
| `POST /cognito-idp/oauth2/revoke` | OAuth refresh token revocation endpoint |
| `GET`, `POST /cognito-idp/oauth2/userInfo` | OIDC userInfo endpoint, for a user's access token |
@@ -0,0 +1,73 @@
package io.floci.aws.services.cognito;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cognito.model.UserPoolClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.Map;
/**
* The page a {@code CONFIRM_WITH_LINK} sign-up email links to. On AWS this is the hosted UI
* {@code /confirmUser} endpoint: it confirms the user with the code in the query string and shows
* the result. A custom domain is rewritten onto this path by {@link CognitoCustomDomainFilter},
* which pins that domain's account. A shared-host link carries no AWS credential, so the client
* id is resolved across accounts and the user is confirmed in the account that owns the client.
*/
@ApplicationScoped
@Path("/")
public class CognitoConfirmUserController {
private final CognitoService cognitoService;
@Inject
public CognitoConfirmUserController(CognitoService cognitoService) {
this.cognitoService = cognitoService;
}
@GET
@Path("/cognito-idp/confirmUser")
@Produces(MediaType.TEXT_HTML)
public Response confirmUser(@Context ContainerRequestContext requestContext,
@QueryParam("client_id") String clientId,
@QueryParam("user_name") String username,
@QueryParam("confirmation_code") String confirmationCode) {
if (isBlank(clientId) || isBlank(username) || isBlank(confirmationCode)) {
return page(400, "Confirmation failed",
"client_id, user_name, and confirmation_code are required.");
}
try {
String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY);
if (domainPoolId != null) {
UserPoolClient client = cognitoService.findClientById(clientId);
if (!domainPoolId.equals(client.getUserPoolId())) {
return page(400, "Confirmation failed", "Client not found.");
}
cognitoService.confirmSignUp(clientId, username, confirmationCode, Map.of());
} else {
cognitoService.confirmSignUpFromSharedHost(clientId, username, confirmationCode);
}
return page(200, "Account confirmed", "Your account has been confirmed.");
} catch (AwsException e) {
return page(400, "Confirmation failed", e.getMessage());
}
}
private static Response page(int status, String title, String message) {
String html = "<!DOCTYPE html><html><head><title>" + CognitoHtml.escape(title) + "</title></head><body><h1>"
+ CognitoHtml.escape(title) + "</h1><p>" + CognitoHtml.escape(message) + "</p></body></html>";
return Response.status(status).type(MediaType.TEXT_HTML_TYPE.withCharset("UTF-8")).entity(html).build();
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
}
@@ -26,8 +26,9 @@ import java.util.Set;
/**
* Routes Cognito custom-domain requests by Host. On AWS a custom domain serves
* {@code https://<domain>/oauth2/token}, {@code /oauth2/revoke}, {@code /oauth2/userInfo},
* {@code /oauth2/authorize}, {@code /oauth2/idpresponse}, and managed login's {@code /login} and
* {@code /logout}; Floci maps those onto the {@code /cognito-idp/...} handlers and pins the pool and
* {@code /oauth2/authorize}, {@code /oauth2/idpresponse}, managed login's {@code /login} and
* {@code /logout}, and the sign-up confirmation page {@code /confirmUser}; Floci maps those onto
* the {@code /cognito-idp/...} handlers and pins the pool and
* the account that own the domain, since the request itself carries no AWS credential. Any other
* path under {@code /oauth2/} is answered here with AWS's JSON 404, and a served path called with a
* method it does not serve with an empty 405, so neither reaches S3 as a key of a bucket named
@@ -49,6 +50,7 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(CognitoCustomDomainFilter.class);
private static final String OAUTH_PREFIX = "/oauth2/";
private static final Set<String> MANAGED_LOGIN_PATHS = Set.of("/login", "/logout");
private static final String CONFIRM_USER_PATH = "/confirmUser";
private static final String TARGET_PREFIX = "/cognito-idp";
/** The paths the Cognito handlers serve on a custom domain, and their methods. */
private static final Map<String, List<String>> SERVED_ROUTES = Map.of(
@@ -59,7 +61,8 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {
"/oauth2/userInfo", List.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST),
"/login", List.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST),
// AWS refuses a HEAD here rather than sign the browser out.
"/logout", List.of(HttpMethod.GET));
"/logout", List.of(HttpMethod.GET),
"/confirmUser", List.of(HttpMethod.GET, HttpMethod.HEAD));
/** AWS's answer to a path under /oauth2/ that its authorization server does not serve. */
private static final String NOT_FOUND_BODY = "{\"error\":\"This URL doesn't exist on the authorization server.\"}";
@@ -89,7 +92,9 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {
if (domain.isEmpty()) {
return;
}
List<String> methods = SERVED_ROUTES.get(path);
// AWS documents the link with and without a trailing slash. Both hit the same handler.
String routePath = isConfirmUser(path) ? CONFIRM_USER_PATH : path;
List<String> methods = SERVED_ROUTES.get(routePath);
if (methods == null) {
requestContext.abortWith(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8"))
@@ -112,7 +117,7 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {
}
URI newUri = UriBuilder.fromUri(originalUri)
.replacePath(TARGET_PREFIX + path)
.replacePath(TARGET_PREFIX + routePath)
.build();
LOG.debugv("Cognito custom domain routing: {0}{1} -> {2}", host, path, newUri.getPath());
requestContext.setProperty(POOL_PROPERTY, domain.get().getUserPoolId());
@@ -121,7 +126,18 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {
}
private static boolean mayServe(String path) {
return path.startsWith(OAUTH_PREFIX) || MANAGED_LOGIN_PATHS.contains(path);
return path.startsWith(OAUTH_PREFIX) || MANAGED_LOGIN_PATHS.contains(path) || isConfirmUser(path);
}
private static boolean isConfirmUser(String path) {
return CONFIRM_USER_PATH.equals(stripTrailingSlash(path));
}
private static String stripTrailingSlash(String path) {
if (path.length() > 1 && path.endsWith("/")) {
return path.substring(0, path.length() - 1);
}
return path;
}
private static String stripPort(String host) {
@@ -0,0 +1,23 @@
package io.floci.aws.services.cognito;
/**
* Escapes text placed in Cognito HTML: managed login, the sign-up confirmation page, and the
* HTML part of a confirmation-link email. Apostrophes are escaped too, so the rules stay the
* same for every one of those pages.
*/
public final class CognitoHtml {
private CognitoHtml() {
}
public static String escape(String value) {
if (value == null) {
return "";
}
return value.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#39;");
}
}
@@ -949,7 +949,7 @@ public class CognitoOAuthController {
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) + "\">"
fields.add("<button type=\"submit\" name=\"challenge\" value=\"" + CognitoHtml.escape(factor) + "\">"
+ label + "</button>");
}
return signInPage(requestContext, request, status, error, fields);
@@ -971,12 +971,12 @@ public class CognitoOAuthController {
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) + "\"")
+ " autocapitalize=\"none\"" + (value == null ? "" : " value=\"" + CognitoHtml.escape(value) + "\"")
+ " required>";
}
private static String hiddenField(String name, String value) {
return "<input type=\"hidden\" name=\"" + escapeHtml(name) + "\" value=\"" + escapeHtml(value) + "\">";
return "<input type=\"hidden\" name=\"" + CognitoHtml.escape(name) + "\" value=\"" + CognitoHtml.escape(value) + "\">";
}
/**
@@ -998,8 +998,8 @@ public class CognitoOAuthController {
}
Map<String, String> parameters = new LinkedHashMap<>(request.parameters());
parameters.put("identity_provider", provider);
providerLinks.add(" <p><a href=\"" + escapeHtml(authorizePath + "?" + formEncode(parameters))
+ "\">Sign in with " + escapeHtml(provider) + "</a></p>");
providerLinks.add(" <p><a href=\"" + CognitoHtml.escape(authorizePath + "?" + formEncode(parameters))
+ "\">Sign in with " + CognitoHtml.escape(provider) + "</a></p>");
}
String csrfToken = stateStore.generateOpaqueKey();
List<String> formFields = new ArrayList<>();
@@ -1014,7 +1014,7 @@ public class CognitoOAuthController {
<input type="hidden" name="%s" value="%s">
%s
</form>
""".formatted(escapeHtml(loginPath(requestContext)), CSRF_FIELD, escapeHtml(csrfToken),
""".formatted(CognitoHtml.escape(loginPath(requestContext)), CSRF_FIELD, CognitoHtml.escape(csrfToken),
String.join("\n", formFields)) : "";
String page = """
<!doctype html>
@@ -1033,7 +1033,7 @@ public class CognitoOAuthController {
</main>
</body>
</html>
""".formatted(error == null ? "" : " <p role=\"alert\">" + escapeHtml(error) + "</p>",
""".formatted(error == null ? "" : " <p role=\"alert\">" + CognitoHtml.escape(error) + "</p>",
String.join("\n", providerLinks), form);
// 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.
@@ -1084,14 +1084,6 @@ public class CognitoOAuthController {
return "https".equalsIgnoreCase(requestContext.getUriInfo().getRequestUri().getScheme());
}
private static String escapeHtml(String value) {
return value.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#39;");
}
private boolean secretsEqual(String expected, String actual) {
if (expected == null || actual == null) {
return expected == actual;
@@ -19,6 +19,7 @@ import io.floci.aws.core.common.EpochSeconds;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.ReservedTags;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.resource.ExplorerResource;
@@ -68,6 +69,7 @@ import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
@@ -3634,7 +3636,8 @@ public class CognitoService implements ResourceProvider {
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
pool, client, triggerUser, "CustomMessage_SignUp", clientMetadata);
messageDispatcher.dispatch(pool, triggerUser, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
code, List.of(deliveryTarget.deliveryMedium()), customMessage,
() -> signUpConfirmationLink(client, triggerUser, code));
}
} catch (VerificationCodeException e) {
rollbackSignUpConfirmationArtifacts(user);
@@ -3693,6 +3696,24 @@ public class CognitoService implements ResourceProvider {
clientMetadata, "PostConfirmation_ConfirmSignUp");
}
/**
* Confirms a sign-up opened from a shared-host link. The request carries no AWS credential,
* so it arrives in the default account. The client id is unique across accounts, and the
* confirmation runs in the account that owns that client. A custom domain pins its account
* before the controller calls {@link #confirmSignUp} instead of this method.
*/
void confirmSignUpFromSharedHost(String clientId, String username, String confirmationCode) {
if (clientStore instanceof AccountAwareStorageBackend<UserPoolClient> aware) {
String accountId = aware.findAnyAccountEntry(clientId)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400))
.account();
RequestScopes.runAs(accountId, () ->
confirmSignUp(clientId, username, confirmationCode, Map.of()));
return;
}
confirmSignUp(clientId, username, confirmationCode, Map.of());
}
private CognitoUser confirmSignUpUnderUserLock(UserPoolClient client, UserPool pool, String username,
String confirmationCode) {
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
@@ -3772,7 +3793,8 @@ public class CognitoService implements ResourceProvider {
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
pool, client, user, "CustomMessage_ResendCode", clientMetadata);
messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
code, List.of(deliveryTarget.deliveryMedium()), customMessage,
() -> signUpConfirmationLink(client, user, code));
}
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
@@ -4861,6 +4883,24 @@ public class CognitoService implements ResourceProvider {
.orElse(baseUrl + "/cognito-idp/oauth2/" + operation);
}
/**
* The URL in a {@code CONFIRM_WITH_LINK} sign-up or resend email. A custom domain serves
* {@code /confirmUser}. Otherwise the link is on Floci's own host. A prefix domain is stored
* but not served, so it is not used here.
*/
private String signUpConfirmationLink(UserPoolClient client, CognitoUser user, String code) {
String query = "client_id=" + urlEncode(client.getClientId())
+ "&user_name=" + urlEncode(user.getUsername())
+ "&confirmation_code=" + urlEncode(code);
return findCustomDomainForPool(client.getUserPoolId())
.map(domain -> "https://" + domain.getDomain() + "/confirmUser?" + query)
.orElse(baseUrl + "/cognito-idp/confirmUser?" + query);
}
private static String urlEncode(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}
// ──────────────────────────── Private helpers ────────────────────────────
private static AwsException userPoolNotFound(String userPoolId) {
@@ -2,6 +2,7 @@ package io.floci.aws.services.cognito.verification;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.DomainNames;
import io.floci.aws.services.cognito.CognitoHtml;
import io.floci.aws.services.cognito.model.CognitoUser;
import io.floci.aws.services.cognito.model.UserPool;
import io.floci.aws.services.ses.SesService;
@@ -18,6 +19,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -27,6 +29,11 @@ import java.util.regex.Pattern;
* mediums. Renders the {@code {####}} placeholder; appends a failsafe line if
* the template lacks the placeholder.
*
* Sign-up and resend emails use {@code EmailMessageByLink} and {@code EmailSubjectByLink}
* when the pool's {@code DefaultEmailOption} is {@code CONFIRM_WITH_LINK}, and the
* {@code {##link text##}} placeholder becomes a confirmation link. Password reset,
* attribute verification and sign-in codes stay on the code template.
*
* The caller may supply the response of a CustomMessage Lambda trigger invocation,
* whose {@code emailSubject}/{@code emailMessage}/{@code smsMessage} take precedence
* over the pool's own template.
@@ -44,6 +51,9 @@ public final class CognitoMessageDispatcher {
// user pool configures no VerificationMessageTemplate).
private static final String DEFAULT_EMAIL_SUBJECT = "Your verification code";
private static final String DEFAULT_EMAIL_BODY = "Your verification code is {####}.";
private static final String DEFAULT_LINK_EMAIL_SUBJECT = "Your verification link";
private static final String DEFAULT_LINK_EMAIL_BODY =
"Please click the link below to verify your email address. {##Verify Email##}";
private static final String DEFAULT_SMS_BODY = "Your verification code is {####}.";
private static final String DEFAULT_FROM = "no-reply@verificationemail.com";
private static final Sender DEFAULT_SENDER = new Sender(DEFAULT_FROM, DEFAULT_FROM);
@@ -52,6 +62,11 @@ public final class CognitoMessageDispatcher {
private static final String CODE_PLACEHOLDER = "{####}";
private static final String USERNAME_PLACEHOLDER = "{username}";
private static final Pattern INVITE_PLACEHOLDERS = Pattern.compile("\\{username}|\\{####}");
/**
* {@code {##link text##}}, the placeholder Cognito replaces with a confirmation link.
* The text is non-empty, so the code placeholder {@code {####}} is not a link.
*/
private static final Pattern LINK_PLACEHOLDER = Pattern.compile("\\{##([^#]+)##}");
// AdminCreateUser invitation defaults, used when neither a CustomMessage trigger nor the pool's
// AdminCreateUserConfig.InviteMessageTemplate supplies the text.
private static final String DEFAULT_INVITE_SUBJECT = "Your temporary password";
@@ -84,6 +99,30 @@ public final class CognitoMessageDispatcher {
public void dispatch(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
String code, List<String> deliveryMediums,
Map<String, Object> customMessageResponse) {
dispatch(pool, user, purpose, code, deliveryMediums, customMessageResponse, (Supplier<String>) null);
}
/**
* Same as {@link #dispatch(UserPool, CognitoUser, VerificationCode.Purpose, String, List, Map, Supplier)},
* with a confirmation URL that is already built.
*/
public void dispatch(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
String code, List<String> deliveryMediums,
Map<String, Object> customMessageResponse, String confirmationLink) {
Supplier<String> link = confirmationLink == null ? null : () -> confirmationLink;
dispatch(pool, user, purpose, code, deliveryMediums, customMessageResponse, link);
}
/**
* Same as {@link #dispatch(UserPool, CognitoUser, VerificationCode.Purpose, String, List, Map)},
* with the sign-up confirmation link {@code SignUp} and {@code ResendConfirmationCode} can build.
* The supplier is read only when an email for a {@code CONFIRM_WITH_LINK} sign-up confirmation
* actually places the URL in the message. A code email, including one on that same pool, and
* every SMS leave it unread. Password reset and attribute verification stay on the code template.
*/
public void dispatch(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
String code, List<String> deliveryMediums,
Map<String, Object> customMessageResponse, Supplier<String> confirmationLink) {
Map<String, Object> template = pool.getVerificationMessageTemplate();
if (template == null) template = Map.of();
@@ -100,11 +139,19 @@ public final class CognitoMessageDispatcher {
Map<String, Object> emailTemplate = purpose == VerificationCode.Purpose.EMAIL_MFA
|| (purpose == VerificationCode.Purpose.EMAIL_OTP && pool.getEmailMfaConfiguration() != null)
? emailMfaTemplate(pool) : template;
boolean linkEmail = confirmWithLink(emailTemplate, purpose) && confirmationLink != null;
String subject = stringOrNull(customMessageResponse, "emailSubject");
if (subject == null) subject = stringOr(emailTemplate.get("EmailSubject"), DEFAULT_EMAIL_SUBJECT);
if (subject == null) {
subject = stringOr(emailTemplate.get(linkEmail ? "EmailSubjectByLink" : "EmailSubject"),
linkEmail ? DEFAULT_LINK_EMAIL_SUBJECT : DEFAULT_EMAIL_SUBJECT);
}
String rawBody = stringOrNull(customMessageResponse, "emailMessage");
if (rawBody == null) rawBody = stringOr(emailTemplate.get(emailTemplateKey()), DEFAULT_EMAIL_BODY);
sendEmail(pool, region, email, subject, renderTemplate(rawBody, code));
if (rawBody == null) {
rawBody = stringOr(emailTemplate.get(linkEmail ? "EmailMessageByLink" : "EmailMessage"),
linkEmail ? DEFAULT_LINK_EMAIL_BODY : DEFAULT_EMAIL_BODY);
}
RenderedEmail rendered = renderEmail(rawBody, code, linkEmail, confirmationLink);
sendEmail(pool, region, email, subject, rendered.text(), rendered.html());
} else if ("SMS".equalsIgnoreCase(medium) && phone != null) {
String rawBody = stringOrNull(customMessageResponse, "smsMessage");
if (rawBody == null) rawBody = stringOr(resolveSmsTemplate(pool, template, purpose), DEFAULT_SMS_BODY);
@@ -190,6 +237,11 @@ public final class CognitoMessageDispatcher {
}
private void sendEmail(UserPool pool, String region, String email, String subject, String body) {
sendEmail(pool, region, email, subject, body, null);
}
private void sendEmail(UserPool pool, String region, String email, String subject, String body,
String bodyHtml) {
Sender sender = sender(pool, region);
ses.sendServiceEmail(SendEmailRequest.builder()
.source(sender.from())
@@ -198,7 +250,7 @@ public final class CognitoMessageDispatcher {
.returnPath(sender.from().equals(sender.address()) ? null : sender.address())
.toAddresses(List.of(email))
.region(region)
.content(new EmailContent.Simple(subject, body, null, List.of()))
.content(new EmailContent.Simple(subject, body, bodyHtml, List.of()))
.build());
}
@@ -365,13 +417,67 @@ public final class CognitoMessageDispatcher {
}
/**
* Email template key. Returns the code-based {@code EmailMessage} ({@code {####}}).
* TODO: honor the pool's {@code DefaultEmailOption}: when set to {@code CONFIRM_WITH_LINK},
* AWS uses {@code EmailMessageByLink}/{@code EmailSubjectByLink} ({@code {##Verify Email##}})
* instead of the code template. Code-only is sufficient for the current foundation scope.
* Sign-up and resend confirmation emails use the link template only when the pool asks for
* one. SMS, and every other email purpose, stay on the code. Whether a URL was supplied is
* the caller's separate check, so this does not build the link.
*/
private String emailTemplateKey() {
return "EmailMessage";
private static boolean confirmWithLink(Map<String, Object> template, VerificationCode.Purpose purpose) {
if (purpose != VerificationCode.Purpose.SIGNUP_CONFIRMATION) {
return false;
}
Object option = template.get("DefaultEmailOption");
return option != null && "CONFIRM_WITH_LINK".equals(option.toString());
}
/**
* A code email is text, with {@code {####}} filled in. A link email is text plus HTML: the
* {@code {##link text##}} placeholder becomes the confirmation URL in the text part and an
* anchor in the HTML part. A link template with neither placeholder gets the URL appended,
* the same failsafe the code template applies to a missing {@code {####}}. A custom message
* that supplies {@code {####}} and no link placeholder is delivered as a code, which is the
* message the trigger wrote. The supplier is read once, and only on those two link paths.
*/
private static RenderedEmail renderEmail(String template, String code, boolean link,
Supplier<String> confirmationLink) {
if (!link) {
return new RenderedEmail(renderTemplate(template, code), null);
}
if (LINK_PLACEHOLDER.matcher(template).find()) {
String url = confirmationLink.get();
String text = replaceCode(replaceLink(template, url, false), code);
String html = replaceCode(replaceLink(template, url, true), code);
return new RenderedEmail(text, html);
}
if (template.contains(CODE_PLACEHOLDER)) {
return new RenderedEmail(template.replace(CODE_PLACEHOLDER, code), null);
}
String url = confirmationLink.get();
return new RenderedEmail(template + "\n" + url,
template + "<br><a href=\"" + CognitoHtml.escape(url) + "\">Verify Email</a>");
}
private static String replaceLink(String template, String url, boolean html) {
Matcher matcher = LINK_PLACEHOLDER.matcher(template);
StringBuilder rendered = new StringBuilder();
while (matcher.find()) {
String replacement = html
? "<a href=\"" + CognitoHtml.escape(url) + "\">" + CognitoHtml.escape(matcher.group(1)) + "</a>"
: url;
matcher.appendReplacement(rendered, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(rendered);
return rendered.toString();
}
private static String replaceCode(String template, String code) {
if (!template.contains(CODE_PLACEHOLDER)) {
return template;
}
return template.replace(CODE_PLACEHOLDER, code);
}
/** The text part of an email, and the HTML part when the message is a confirmation link. */
private record RenderedEmail(String text, String html) {
}
/**
@@ -417,7 +523,7 @@ public final class CognitoMessageDispatcher {
return s.isEmpty() ? null : s;
}
private String renderTemplate(String template, String code) {
private static String renderTemplate(String template, String code) {
if (template.contains(CODE_PLACEHOLDER)) {
return template.replace(CODE_PLACEHOLDER, code);
}
@@ -117,7 +117,7 @@ class CognitoCustomDomainFilterTest {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
for (String route : new String[] {"POST /oauth2/token", "POST /oauth2/revoke", "GET /oauth2/authorize",
"GET /oauth2/idpresponse", "GET /oauth2/userInfo", "POST /oauth2/userInfo", "GET /login",
"POST /login", "GET /logout"}) {
"POST /login", "GET /logout", "GET /confirmUser"}) {
String[] parts = route.split(" ");
ContainerRequestContext request = request(parts[0], "https://" + DOMAIN + parts[1], DOMAIN);
@@ -163,7 +163,8 @@ class CognitoCustomDomainFilterTest {
for (String route : new String[] {"GET /oauth2/token POST", "GET /oauth2/revoke POST",
"HEAD /oauth2/revoke POST", "DELETE /oauth2/token POST", "POST /oauth2/authorize GET, HEAD",
"POST /oauth2/idpresponse GET, HEAD", "DELETE /oauth2/userInfo GET, HEAD, POST",
"PUT /login GET, HEAD, POST", "POST /logout GET", "HEAD /logout GET"}) {
"PUT /login GET, HEAD, POST", "POST /logout GET", "HEAD /logout GET",
"POST /confirmUser GET, HEAD"}) {
String[] parts = route.split(" ", 3);
ContainerRequestContext request = request(parts[0], "https://" + DOMAIN + parts[1], DOMAIN);
@@ -178,11 +179,24 @@ class CognitoCustomDomainFilterTest {
}
}
@Test
void rewritesConfirmUserWithATrailingSlashOntoTheSameHandler() {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
String query = "?client_id=c&user_name=a%40b.com&confirmation_code=123456";
ContainerRequestContext request = request("GET", "https://" + DOMAIN + "/confirmUser/" + query, DOMAIN);
filter.filter(request);
verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp/confirmUser" + query));
verify(request, never()).abortWith(any());
}
/** AWS answers HEAD as GET on these paths, so the filter serves it with the GET handler. */
@Test
void servesAHeadWithTheGetHandler() {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
for (String path : new String[] {"/oauth2/authorize", "/oauth2/idpresponse", "/oauth2/userInfo", "/login"}) {
for (String path : new String[] {"/oauth2/authorize", "/oauth2/idpresponse", "/oauth2/userInfo", "/login",
"/confirmUser"}) {
ContainerRequestContext request = request("HEAD", "https://" + DOMAIN + path, DOMAIN);
filter.filter(request);
@@ -2,6 +2,7 @@ package io.floci.aws.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testutil.SesMailbox;
import io.quarkus.test.junit.QuarkusTest;
@@ -1013,6 +1014,266 @@ class CognitoIntegrationTest {
.body("__type", Matchers.equalTo("NotAuthorizedException"));
}
@Test
void confirmWithLinkSignUpAndResendSendALinkThatConfirmsTheUser() throws Exception {
given().delete("/_aws/ses").then().statusCode(200);
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
"PoolName": "ConfirmWithLinkPool",
"AutoVerifiedAttributes": ["email"],
"VerificationMessageTemplate": {
"DefaultEmailOption": "CONFIRM_WITH_LINK",
"EmailSubject": "Code subject",
"EmailMessage": "CODE {####}",
"EmailSubjectByLink": "Confirm your account",
"EmailMessageByLink": "Welcome. {##Click here##} to finish."
}
}
""");
String linkPoolId = poolResponse.path("UserPool").path("Id").asText();
String linkClientId = cognitoJson("CreateUserPoolClient", """
{
"UserPoolId": "%s",
"ClientName": "confirm-with-link-client"
}
""".formatted(linkPoolId)).path("UserPoolClient").path("ClientId").asText();
String username = "link+" + UUID.randomUUID() + "@example.com";
cognitoAction("SignUp", """
{
"ClientId": "%s",
"Username": "%s",
"Password": "Passw0rd!",
"UserAttributes": [
{ "Name": "email", "Value": "%s" }
]
}
""".formatted(linkClientId, username, username))
.then()
.statusCode(200);
JsonNode signupEmail = latestEmailTo(username);
assertEquals("Confirm your account", signupEmail.path("Subject").asText());
String signupText = signupEmail.path("Body").path("text_part").asText();
assertThat(signupText, containsString("Welcome."));
assertThat(signupText, containsString("to finish."));
assertFalse(signupText.contains("CODE "));
String signupLink = confirmUserPath(signupText);
String originalCode = confirmationCode(signupLink);
given().delete("/_aws/ses").then().statusCode(200);
cognitoAction("ResendConfirmationCode", """
{
"ClientId": "%s",
"Username": "%s"
}
""".formatted(linkClientId, username))
.then()
.statusCode(200);
JsonNode resendEmail = latestEmailTo(username);
assertEquals("Confirm your account", resendEmail.path("Subject").asText());
String resendText = resendEmail.path("Body").path("text_part").asText();
String resendHtml = resendEmail.path("Body").path("html_part").asText();
String resendLink = confirmUserPath(resendText);
String replacementCode = confirmationCode(resendLink);
assertNotEquals(originalCode, replacementCode);
assertThat(resendHtml, containsString("<a href=\""));
assertThat(resendHtml, containsString(">Click here</a>"));
assertThat(resendHtml, containsString("&amp;"));
cognitoAction("ConfirmSignUp", """
{
"ClientId": "%s",
"Username": "%s",
"ConfirmationCode": "%s"
}
""".formatted(linkClientId, username, originalCode))
.then()
.statusCode(400)
.body("__type", Matchers.equalTo("CodeMismatchException"));
given().urlEncodingEnabled(false)
.get(resendLink)
.then()
.statusCode(200)
.body(containsString("Your account has been confirmed."));
JsonNode confirmed = cognitoJson("AdminGetUser", """
{
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(linkPoolId, username));
assertEquals("CONFIRMED", confirmed.path("UserStatus").asText());
assertEquals("true", attributeValue(confirmed, "email_verified"));
given().delete("/_aws/ses").then().statusCode(200);
cognitoAction("ForgotPassword", """
{
"ClientId": "%s",
"Username": "%s"
}
""".formatted(linkClientId, username))
.then()
.statusCode(200);
JsonNode resetEmail = latestEmailTo(username);
assertEquals("Code subject", resetEmail.path("Subject").asText());
String resetText = resetEmail.path("Body").path("text_part").asText();
assertThat(resetText, containsString("CODE "));
assertFalse(resetText.contains("confirmUser"));
assertTrue(resetEmail.path("Body").path("html_part").isNull());
}
@Test
void confirmWithCodeKeepsTheCodeTemplateWhenALinkTemplateIsAlsoSet() throws Exception {
given().delete("/_aws/ses").then().statusCode(200);
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
"PoolName": "ConfirmWithCodePool",
"AutoVerifiedAttributes": ["email"],
"VerificationMessageTemplate": {
"DefaultEmailOption": "CONFIRM_WITH_CODE",
"EmailSubject": "Code subject",
"EmailMessage": "CODE {####}",
"EmailSubjectByLink": "Confirm your account",
"EmailMessageByLink": "Welcome. {##Click here##}"
}
}
""");
String codePoolId = poolResponse.path("UserPool").path("Id").asText();
String codeClientId = cognitoJson("CreateUserPoolClient", """
{
"UserPoolId": "%s",
"ClientName": "confirm-with-code-client"
}
""".formatted(codePoolId)).path("UserPoolClient").path("ClientId").asText();
String username = "code+" + UUID.randomUUID() + "@example.com";
cognitoAction("SignUp", """
{
"ClientId": "%s",
"Username": "%s",
"Password": "Passw0rd!",
"UserAttributes": [
{ "Name": "email", "Value": "%s" }
]
}
""".formatted(codeClientId, username, username))
.then()
.statusCode(200);
JsonNode email = latestEmailTo(username);
assertEquals("Code subject", email.path("Subject").asText());
String text = email.path("Body").path("text_part").asText();
assertThat(text, containsString("CODE "));
assertFalse(text.contains("confirmUser"));
assertTrue(email.path("Body").path("html_part").isNull());
String signupCode = fetchLatestSesVerificationCode(username);
given().delete("/_aws/ses").then().statusCode(200);
cognitoAction("ResendConfirmationCode", """
{
"ClientId": "%s",
"Username": "%s"
}
""".formatted(codeClientId, username))
.then()
.statusCode(200);
JsonNode resend = latestEmailTo(username);
assertEquals("Code subject", resend.path("Subject").asText());
String resendText = resend.path("Body").path("text_part").asText();
assertThat(resendText, containsString("CODE "));
assertFalse(resendText.contains("confirmUser"));
assertTrue(resend.path("Body").path("html_part").isNull());
String resendCode = fetchLatestSesVerificationCode(username);
assertNotEquals(signupCode, resendCode);
cognitoAction("ConfirmSignUp", """
{
"ClientId": "%s",
"Username": "%s",
"ConfirmationCode": "%s"
}
""".formatted(codeClientId, username, resendCode))
.then()
.statusCode(200);
}
@Test
void confirmWithLinkOnASharedHostConfirmsAUserOutsideTheDefaultAccount() throws Exception {
String accountId = "111122223333";
clearSes(accountId);
JsonNode poolResponse = CognitoCustomDomainFixtures.awsJsonAs(accountId,
CognitoCustomDomainFixtures.COGNITO, "CreateUserPool", """
{
"PoolName": "OtherAccountLinkPool",
"AutoVerifiedAttributes": ["email"],
"VerificationMessageTemplate": {
"DefaultEmailOption": "CONFIRM_WITH_LINK",
"EmailSubjectByLink": "Confirm your account",
"EmailMessageByLink": "Welcome. {##Click here##}"
}
}
""");
String poolId = poolResponse.path("UserPool").path("Id").asText();
String clientId = CognitoCustomDomainFixtures.awsJsonAs(accountId, CognitoCustomDomainFixtures.COGNITO,
"CreateUserPoolClient", """
{
"UserPoolId": "%s",
"ClientName": "other-account-link-client"
}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
String username = "other+" + UUID.randomUUID() + "@example.com";
CognitoCustomDomainFixtures.awsActionAs(accountId, CognitoCustomDomainFixtures.COGNITO, "SignUp", """
{
"ClientId": "%s",
"Username": "%s",
"Password": "Passw0rd!",
"UserAttributes": [
{ "Name": "email", "Value": "%s" }
]
}
""".formatted(clientId, username, username))
.then()
.statusCode(200);
JsonNode email = latestEmailTo(accountId, username);
String link = confirmUserPath(email.path("Body").path("text_part").asText());
given()
.urlEncodingEnabled(false)
.get(link)
.then()
.statusCode(200)
.body(containsString("Your account has been confirmed."));
cognitoAction("AdminGetUser", """
{
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(poolId, username))
.then()
.statusCode(400);
JsonNode confirmed = CognitoCustomDomainFixtures.awsJsonAs(accountId, CognitoCustomDomainFixtures.COGNITO,
"AdminGetUser", """
{
"UserPoolId": "%s",
"Username": "%s"
}
""".formatted(poolId, username));
assertEquals("CONFIRMED", confirmed.path("UserStatus").asText());
assertEquals("true", attributeValue(confirmed, "email_verified"));
}
@Test
@Order(8)
void forgotPasswordRequiresVerifiedRecoveryDestination() throws Exception {
@@ -3650,6 +3911,55 @@ class CognitoIntegrationTest {
""").path("UserPool").path("Id").asText();
}
private static final Pattern CONFIRM_USER_LINK =
Pattern.compile("https?://[^\\s\"<>]+(/cognito-idp/confirmUser\\?[^\\s\"<>]+)");
private static final Pattern CONFIRMATION_CODE_PARAM = Pattern.compile("confirmation_code=(\\d+)");
private static JsonNode latestEmailTo(String recipient) {
return latestEmail(SesMailbox.messagesTo(recipient), "expected an email to " + recipient);
}
/** SES stores the message in the account that sent it, which a credential-free read cannot see. */
private static JsonNode latestEmailTo(String accountId, String recipient) {
return latestEmail(SesMailbox.messagesTo(accountId, recipient),
"expected an email to " + recipient + " in account " + accountId);
}
private static JsonNode latestEmail(JsonNode messages, String failure) {
assertTrue(messages.size() > 0, failure);
return messages.get(messages.size() - 1);
}
private static void clearSes(String accountId) {
given()
.header("Authorization", EnforcementFixtures.auth(accountId, "email"))
.when()
.delete("/_aws/ses")
.then()
.statusCode(200);
}
private static String confirmUserPath(String body) {
Matcher matcher = CONFIRM_USER_LINK.matcher(body);
assertTrue(matcher.find(), body);
return matcher.group(1);
}
private static String confirmationCode(String link) {
Matcher matcher = CONFIRMATION_CODE_PARAM.matcher(link);
assertTrue(matcher.find(), link);
return matcher.group(1);
}
private static String attributeValue(JsonNode user, String name) {
for (JsonNode attribute : user.path("UserAttributes")) {
if (name.equals(attribute.path("Name").asText())) {
return attribute.path("Value").asText();
}
}
return null;
}
private static String fetchLatestSesVerificationCode(String recipient) throws Exception {
return CognitoCodes.sixDigitCode(
SesMailbox.messagesTo(recipient).get(0).path("Body").path("text_part").asText());
@@ -38,6 +38,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
@@ -66,6 +67,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Supplier;
import static io.floci.aws.services.cognito.CognitoSecretHashTestHelper.secretHash;
import static io.floci.aws.testing.InlineMocks.inlineMock;
@@ -2415,7 +2417,8 @@ class CognitoServiceTest {
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any()))
.thenReturn("123456");
doThrow(new RuntimeException("SES unavailable")).when(messageDispatcher)
.dispatch(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), eq("123456"), any(), any());
.dispatch(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), eq("123456"), any(), any(),
ArgumentMatchers.<Supplier<String>>any());
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
@@ -13,11 +13,14 @@ import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -154,6 +157,287 @@ class CognitoMessageDispatcherTest {
.build(), sent);
}
@Test
void dispatch_confirmWithLink_usesLinkSubjectAndBody() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailSubject", "Code subject",
"EmailMessage", "Your code is {####}.",
"EmailSubjectByLink", "Confirm your account",
"EmailMessageByLink", "Welcome. {##Click here##} to finish."
));
String link = "http://localhost/cognito-idp/confirmUser?client_id=abc"
+ "&user_name=alice%40example.com&confirmation_code=123456";
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"), null, link);
SendEmailRequest sent = sentEmail();
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sent.content());
assertEquals("Confirm your account", content.subject());
assertEquals("Welcome. " + link + " to finish.", content.bodyText());
assertEquals("Welcome. <a href=\"" + link.replace("&", "&amp;") + "\">Click here</a> to finish.",
content.bodyHtml());
verifyNoInteractions(sns);
}
@Test
void dispatch_confirmWithLinkWithoutCustomTemplates_usesAwsDefaults() {
UserPool pool = pool(Map.of("DefaultEmailOption", "CONFIRM_WITH_LINK"));
String link = "http://localhost/cognito-idp/confirmUser?confirmation_code=111222";
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"111222", List.of("EMAIL"), null, link);
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Your verification link", content.subject());
assertEquals("Please click the link below to verify your email address. " + link, content.bodyText());
assertEquals("Please click the link below to verify your email address. "
+ "<a href=\"" + link + "\">Verify Email</a>", content.bodyHtml());
}
@Test
void dispatch_confirmWithLinkTemplateMissingPlaceholder_appendsTheLink() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailMessageByLink", "Welcome, please verify."
));
String link = "http://localhost/cognito-idp/confirmUser?confirmation_code=999000";
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"999000", List.of("EMAIL"), null, link);
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Welcome, please verify.\n" + link, content.bodyText());
assertEquals("Welcome, please verify.<br><a href=\"" + link + "\">Verify Email</a>", content.bodyHtml());
}
@Test
void dispatch_confirmWithCode_keepsTheCodeTemplateWhenALinkTemplateIsAlsoSet() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_CODE",
"EmailSubject", "Code subject",
"EmailMessage", "Your code is {####}.",
"EmailSubjectByLink", "Confirm your account",
"EmailMessageByLink", "Welcome. {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"), null, "http://localhost/confirmUser?confirmation_code=123456");
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Code subject", content.subject());
assertEquals("Your code is 123456.", content.bodyText());
assertNull(content.bodyHtml());
}
@Test
void dispatch_confirmWithLink_passwordResetStaysOnTheCodeTemplate() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailSubject", "Reset subject",
"EmailMessage", "Reset code {####}.",
"EmailSubjectByLink", "Confirm your account",
"EmailMessageByLink", "Welcome. {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.PASSWORD_RESET,
"654321", List.of("EMAIL"), null, "http://localhost/confirmUser?confirmation_code=654321");
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Reset subject", content.subject());
assertEquals("Reset code 654321.", content.bodyText());
assertNull(content.bodyHtml());
}
@Test
void dispatch_confirmWithLink_attributeVerificationStaysOnTheCodeTemplate() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailSubject", "Attribute subject",
"EmailMessage", "Attribute code {####}.",
"EmailSubjectByLink", "Confirm your account",
"EmailMessageByLink", "Welcome. {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", null),
VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION,
"246810", List.of("EMAIL"), null, "http://localhost/confirmUser?confirmation_code=246810");
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Attribute subject", content.subject());
assertEquals("Attribute code 246810.", content.bodyText());
assertNull(content.bodyHtml());
}
@Test
void dispatch_confirmWithLink_signInCodeStaysOnTheCodeTemplate() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailMessage", "Sign-in code {####}.",
"EmailMessageByLink", "Welcome. {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.EMAIL_OTP,
"135790", List.of("EMAIL"), null, "http://localhost/confirmUser?confirmation_code=135790");
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Sign-in code 135790.", content.bodyText());
assertNull(content.bodyHtml());
}
@Test
void dispatch_confirmWithLink_emailMfaStaysOnTheMfaTemplate() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailMessageByLink", "Welcome. {##Click here##}"
));
pool.setEmailMfaConfiguration(Map.of("Subject", "MFA subject", "Message", "MFA code {####}."));
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.EMAIL_MFA,
"112233", List.of("EMAIL"), null, "http://localhost/confirmUser?confirmation_code=112233");
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("MFA subject", content.subject());
assertEquals("MFA code 112233.", content.bodyText());
assertNull(content.bodyHtml());
}
@Test
void dispatch_confirmWithLink_smsStaysOnTheCodeTemplate() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"SmsMessage", "Signup: {####}",
"EmailMessageByLink", "Welcome. {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", "+5215551234567"),
VerificationCode.Purpose.SIGNUP_CONFIRMATION, "654321", List.of("SMS"), null,
"http://localhost/confirmUser?confirmation_code=654321");
verify(sns).publish(isNull(), isNull(), eq("+5215551234567"), eq("Signup: 654321"),
isNull(), isNull(), eq("us-east-1"));
verifyNoInteractions(ses);
}
@Test
void dispatch_confirmWithLink_customMessageRendersTheLinkPlaceholder() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailSubjectByLink", "Pool link subject",
"EmailMessageByLink", "Pool link {##Click here##}"
));
String link = "http://localhost/cognito-idp/confirmUser?confirmation_code=123456";
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"),
Map.of("emailSubject", "Custom link", "emailMessage", "Open {##here & now##}"), link);
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Custom link", content.subject());
assertEquals("Open " + link, content.bodyText());
assertEquals("Open <a href=\"" + link + "\">here &amp; now</a>", content.bodyHtml());
}
@Test
void dispatch_confirmWithLink_customCodeMessageStaysACode() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailSubjectByLink", "Pool link subject",
"EmailMessageByLink", "Pool link {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"),
Map.of("emailSubject", "Custom code", "emailMessage", "code {####}"),
"http://localhost/cognito-idp/confirmUser?confirmation_code=123456");
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Custom code", content.subject());
assertEquals("code 123456", content.bodyText());
assertNull(content.bodyHtml());
}
@Test
void dispatch_confirmWithCode_doesNotBuildTheConfirmationLink() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_CODE",
"EmailMessage", "Your code is {####}.",
"EmailMessageByLink", "Welcome. {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"), null, linkThatMustNotBeBuilt());
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Your code is 123456.", content.bodyText());
assertNull(content.bodyHtml());
}
@Test
void dispatch_confirmWithLink_smsDoesNotBuildTheConfirmationLink() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"SmsMessage", "Signup: {####}",
"EmailMessageByLink", "Welcome. {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", "+5215551234567"),
VerificationCode.Purpose.SIGNUP_CONFIRMATION, "654321", List.of("SMS"), null,
linkThatMustNotBeBuilt());
verify(sns).publish(isNull(), isNull(), eq("+5215551234567"), eq("Signup: 654321"),
isNull(), isNull(), eq("us-east-1"));
verifyNoInteractions(ses);
}
@Test
void dispatch_confirmWithLink_customCodeMessageDoesNotBuildTheConfirmationLink() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailMessageByLink", "Pool link {##Click here##}"
));
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"),
Map.of("emailSubject", "Custom code", "emailMessage", "code {####}"),
linkThatMustNotBeBuilt());
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("code 123456", content.bodyText());
assertNull(content.bodyHtml());
}
@Test
void dispatch_confirmWithLink_buildsTheConfirmationLinkOnce() {
UserPool pool = pool(Map.of(
"DefaultEmailOption", "CONFIRM_WITH_LINK",
"EmailMessageByLink", "Go {##O'Hara & <friends>##}"
));
String link = "http://localhost/confirmUser?user_name=a'b&c=\"d\"";
AtomicInteger builds = new AtomicInteger();
Supplier<String> confirmationLink = () -> {
builds.incrementAndGet();
return link;
};
dispatcher.dispatch(pool, user("alice@example.com", null), VerificationCode.Purpose.SIGNUP_CONFIRMATION,
"123456", List.of("EMAIL"), null, confirmationLink);
assertEquals(1, builds.get());
EmailContent.Simple content = assertInstanceOf(EmailContent.Simple.class, sentEmail().content());
assertEquals("Go " + link, content.bodyText());
assertEquals("Go <a href=\"http://localhost/confirmUser?user_name=a&#39;b&amp;c=&quot;d&quot;\">"
+ "O&#39;Hara &amp; &lt;friends&gt;</a>", content.bodyHtml());
}
/** A link builder that fails the test if a code or SMS delivery reads it. */
private static Supplier<String> linkThatMustNotBeBuilt() {
return () -> {
throw new AssertionError("confirmation link was built");
};
}
@Test
void dispatch_missingDeliveryMediums_emailFallbackWhenEmailPresent() {
UserPool pool = pool(Map.of());
@@ -4,13 +4,16 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.floci.aws.testing.EnforcementFixtures;
import io.restassured.specification.RequestSpecification;
import static io.restassured.RestAssured.given;
/**
* Reads Floci's SES inspection mailbox, {@code GET /_aws/ses}, for one recipient. The endpoint's
* {@code email} parameter filters by message source, as on LocalStack, so the messages sent to an
* address are picked out here.
* address are picked out here. Pass an account to read mail stored under that account: a
* credential-free read only sees the default account.
*/
public final class SesMailbox {
@@ -21,7 +24,20 @@ public final class SesMailbox {
/** The captured messages whose To addresses include {@code recipient}, oldest first. */
public static ArrayNode messagesTo(String recipient) {
String body = given().when().get("/_aws/ses").then().statusCode(200).extract().asString();
return messages(given(), recipient);
}
/**
* The captured messages in {@code accountId} whose To addresses include {@code recipient},
* oldest first. The account is the SigV4 access key, which is how the account filter selects
* the mailbox.
*/
public static ArrayNode messagesTo(String accountId, String recipient) {
return messages(given().header("Authorization", EnforcementFixtures.auth(accountId, "email")), recipient);
}
private static ArrayNode messages(RequestSpecification request, String recipient) {
String body = request.when().get("/_aws/ses").then().statusCode(200).extract().asString();
JsonNode messages;
try {
messages = MAPPER.readTree(body).path("messages");