mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cognito): send the AdminCreateUser invitation with a temporary password (#5155)
AdminCreateUser without TemporaryPassword created a CONFIRMED user with no
password and sent nothing. It now follows the AdminCreateUser reference:
- Without TemporaryPassword a password meeting the pool's policy is
generated and the user starts in FORCE_CHANGE_PASSWORD. A pool offering
EMAIL_OTP or SMS_OTP (above Lite) creates a CONFIRMED user without one,
which needs an email or phone_number for an offered factor and every
attribute the schema marks as required.
- Without MessageAction the invitation goes to each of
DesiredDeliveryMediums (default SMS) the user can be reached on, through
the dispatcher's SES/SNS path and the pool's EmailConfiguration sender.
The text comes from the CustomMessage_AdminCreateUser trigger, the pool's
InviteMessageTemplate, or AWS's default. A message without {####} is not
delivered to a user with a password.
- SUPPRESS sends nothing. RESEND sets a new temporary password, the
requested one or a generated one, and sends the invitation again.
- The invitation is sent before anything is stored, so a failed delivery
(CodeDeliveryFailureException) creates no user, keeps a resent user's
previous password and leaves a ForceAliasCreation alias in place.
- MessageAction and DesiredDeliveryMediums outside their enums are refused
with InvalidParameterException.
- AWS::Cognito::UserPoolUser passes DesiredDeliveryMediums, ValidationData
and ClientMetadata through.
Closes #5144
This commit is contained in:
1 parent
e77710d32d
commit
641bf980d0
11 files changed
+1042
-72
No files matched your search
@@ -221,7 +221,7 @@ further divergences, both deliberate:
|
||||
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| AdminCreateUser | Creates or resends setup for a user in a user pool. Creating a user invokes the pre sign-up trigger with triggerSource `PreSignUp_AdminCreateUser`, the request's `ValidationData` and `ClientMetadata`, and `callerContext.clientId` `CLIENT_ID_NOT_APPLICABLE`. A trigger error refuses the user with `UserLambdaValidationException`, and its `autoConfirmUser`, `autoVerifyEmail` and `autoVerifyPhone` are ignored, as on AWS. |
|
||||
| AdminCreateUser | Creates a user and sends the invitation, or with `MessageAction` `RESEND` gives an existing `FORCE_CHANGE_PASSWORD` user a new temporary password and sends the invitation again. See [AdminCreateUser invitations](#admincreateuser-invitations). Creating a user invokes the pre sign-up trigger with triggerSource `PreSignUp_AdminCreateUser`, the request's `ValidationData` and `ClientMetadata`, and `callerContext.clientId` `CLIENT_ID_NOT_APPLICABLE`. A trigger error refuses the user with `UserLambdaValidationException`, and its `autoConfirmUser`, `autoVerifyEmail` and `autoVerifyPhone` are ignored, as on AWS. |
|
||||
| AdminGetUser | Returns a user's stored attributes and status, and the MFA settings (`UserMFASettingList`, `PreferredMfaSetting`) once any is turned on. |
|
||||
| AdminDeleteUser | Deletes a user from a user pool. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. |
|
||||
| AdminSetUserPassword | Sets a user's password and permanent-password status. |
|
||||
@@ -235,6 +235,43 @@ further divergences, both deliberate:
|
||||
| AdminUserGlobalSignOut | Revokes the access, ID and refresh tokens issued to a user. |
|
||||
| AdminLinkProviderForUser | Links an external IdP identity to an existing user's `identities` attribute. |
|
||||
|
||||
#### AdminCreateUser invitations
|
||||
|
||||
- **Temporary password:** without `TemporaryPassword`, Floci generates one that meets the pool's
|
||||
password policy, and the user starts in `FORCE_CHANGE_PASSWORD`, as on AWS. In a pool whose
|
||||
`SignInPolicy.AllowedFirstAuthFactors` offers `EMAIL_OTP` or `SMS_OTP` (above the Lite tier), no
|
||||
password is generated: the user is created `CONFIRMED` without one, and must have an `email` for
|
||||
`EMAIL_OTP` or a `phone_number` for `SMS_OTP`, and a value for every attribute the pool's schema
|
||||
marks as required, or the request fails with `InvalidParameterException`. A user with a password
|
||||
may leave required attributes out, as on AWS. A passkey does not make a pool passwordless here,
|
||||
as on AWS.
|
||||
- **Invitation:** without `MessageAction`, the invitation goes to each of `DesiredDeliveryMediums`
|
||||
(`SMS`, the default, or `EMAIL`; any other value is refused) that the user has an `email` or
|
||||
`phone_number` for. Email goes through Floci's SES (readable at `/_aws/ses`) from the pool's
|
||||
`EmailConfiguration` sender, like the other Cognito messages, and SMS through its SNS.
|
||||
- **Text:** the `CustomMessage` trigger's response, when one is configured and answers. It is
|
||||
invoked with triggerSource `CustomMessage_AdminCreateUser`, `usernameParameter` `{username}`,
|
||||
`codeParameter` `{####}` and the request's `ClientMetadata`. Otherwise the pool's
|
||||
`AdminCreateUserConfig.InviteMessageTemplate` (`EmailSubject`, `EmailMessage`, `SMSMessage`), or
|
||||
AWS's default, `Your username is {username} and temporary password is {####}.` under the subject
|
||||
`Your temporary password`. `{username}` and `{####}` (the temporary password) are filled in. A
|
||||
user without a password gets `Your username is {username}.` by default. As on AWS, a message
|
||||
without `{####}` is not delivered to a user with a password.
|
||||
- **`SUPPRESS`** sends nothing. **`RESEND`** sets the request's `TemporaryPassword`, or a
|
||||
generated one, and sends the invitation again.
|
||||
- **Delivery failure** returns `CodeDeliveryFailureException`, as `SignUp` does. The invitation is
|
||||
sent before anything is stored, so a failed one creates no user, leaves a resent user's previous
|
||||
temporary password working, and leaves a `ForceAliasCreation` alias with its holder. When one
|
||||
medium fails and another delivers, the request succeeds.
|
||||
- **CloudFormation:** `AWS::Cognito::UserPoolUser` has no `TemporaryPassword`, so its user gets a
|
||||
generated one, and the template's `DesiredDeliveryMediums`, `ValidationData` and `ClientMetadata`
|
||||
are passed on.
|
||||
|
||||
Where AWS documents no outcome, Floci picks one: a requested medium the user has no attribute for is
|
||||
skipped, since AWS requires the attribute but documents no error for its absence; a template's
|
||||
`{####}` is left empty for a user without a password; and `RESEND` without `TemporaryPassword` in a
|
||||
passwordless pool generates a password. `TemporaryPasswordValidityDays` is not enforced.
|
||||
|
||||
### User Operations
|
||||
|
||||
| Action | Description |
|
||||
|
||||
+20
-8
@@ -12,8 +12,10 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -72,13 +74,7 @@ public class CognitoUserPoolUserCfnProvisioner implements CfnResourceProvisioner
|
||||
+ "replacing. Rename " + username + " and update the stack again.", 400);
|
||||
}
|
||||
|
||||
Map<String, String> userAttributes = new LinkedHashMap<>();
|
||||
for (JsonNode attribute : resolved.path("UserAttributes")) {
|
||||
userAttributes.put(attribute.path("Name").asText(), attribute.path("Value").asText());
|
||||
}
|
||||
// DesiredDeliveryMediums only reaches a message transport, which AdminCreateUser does not
|
||||
// drive here. ValidationData and ClientMetadata are not passed to the PreSignUp trigger,
|
||||
// which sees empty maps. All three only take part in the createOnly record.
|
||||
Map<String, String> userAttributes = attributeMap(resolved.path("UserAttributes"));
|
||||
String name = customNamed ? username : ctx.generatePhysicalName(r.getLogicalId(), 128, false);
|
||||
String messageAction = text(resolved, "MessageAction");
|
||||
if ("RESEND".equalsIgnoreCase(messageAction)) {
|
||||
@@ -87,8 +83,15 @@ public class CognitoUserPoolUserCfnProvisioner implements CfnResourceProvisioner
|
||||
throw new AwsException("AlreadyExists", "Resource of type 'AWS::Cognito::UserPoolUser' with identifier '"
|
||||
+ userPoolId + "|" + existing.getUsername() + "' already exists.", 400);
|
||||
}
|
||||
Map<String, String> clientMetadata = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, JsonNode> entry : resolved.path("ClientMetadata").properties()) {
|
||||
clientMetadata.put(entry.getKey(), entry.getValue().asText());
|
||||
}
|
||||
List<String> desiredDeliveryMediums = new ArrayList<>();
|
||||
resolved.path("DesiredDeliveryMediums").forEach(medium -> desiredDeliveryMediums.add(medium.asText()));
|
||||
CognitoUser user = cognitoService.adminCreateUser(userPoolId, name, userAttributes, null, messageAction,
|
||||
Boolean.parseBoolean(text(resolved, "ForceAliasCreation")));
|
||||
Boolean.parseBoolean(text(resolved, "ForceAliasCreation")), desiredDeliveryMediums,
|
||||
attributeMap(resolved.path("ValidationData")), clientMetadata);
|
||||
|
||||
r.setPhysicalId(user.getUsername());
|
||||
r.getAttributes().put(CREATE_ONLY_ATTR, resolved.toString());
|
||||
@@ -205,6 +208,15 @@ public class CognitoUserPoolUserCfnProvisioner implements CfnResourceProvisioner
|
||||
}
|
||||
}
|
||||
|
||||
/** An {@code AttributeType} list, {@code [{"Name": ..., "Value": ...}]}, as a map. */
|
||||
private static Map<String, String> attributeMap(JsonNode attributes) {
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
for (JsonNode attribute : attributes) {
|
||||
map.put(attribute.path("Name").asText(), attribute.path("Value").asText());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String name) {
|
||||
JsonNode value = node.path(name);
|
||||
return value.isMissingNode() || value.isNull() ? null : value.asText();
|
||||
|
||||
+21
-1
@@ -52,6 +52,7 @@ final class CognitoAuthFlowHandler {
|
||||
private static final Logger LOG = Logger.getLogger(CognitoAuthFlowHandler.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String CUSTOM_MESSAGE_CODE_PARAMETER = "{####}";
|
||||
private static final String CUSTOM_MESSAGE_USERNAME_PARAMETER = "{username}";
|
||||
/** The {@code callerContext.clientId} AWS sends for an admin action, which names no app client. */
|
||||
private static final String CLIENT_ID_NOT_APPLICABLE = "CLIENT_ID_NOT_APPLICABLE";
|
||||
/** The message of a wrong password, which managed login also shows for an unknown user. */
|
||||
@@ -1841,7 +1842,26 @@ final class CognitoAuthFlowHandler {
|
||||
req.put("codeParameter", CUSTOM_MESSAGE_CODE_PARAMETER);
|
||||
req.put("usernameParameter", user.getUsername());
|
||||
req.put("clientMetadata", Map.of());
|
||||
TriggerResult result = invokeTrigger(pool, client, user, "CustomMessage", triggerSource, req);
|
||||
return customMessageResponse(pool, client, user, triggerSource, req);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires the CustomMessage trigger for an AdminCreateUser invitation. The request carries the
|
||||
* {@code {username}} and {@code {####}} placeholders, which Cognito fills in after the function
|
||||
* returns, and the request's {@code ClientMetadata}. Non-blocking, as for the other sources.
|
||||
*/
|
||||
Map<String, Object> fireCustomMessageForAdminCreateUser(UserPool pool, CognitoUser user,
|
||||
Map<String, String> clientMetadata) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("codeParameter", CUSTOM_MESSAGE_CODE_PARAMETER);
|
||||
req.put("usernameParameter", CUSTOM_MESSAGE_USERNAME_PARAMETER);
|
||||
req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata);
|
||||
return customMessageResponse(pool, null, user, "CustomMessage_AdminCreateUser", req);
|
||||
}
|
||||
|
||||
private Map<String, Object> customMessageResponse(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
String triggerSource, Map<String, Object> request) {
|
||||
TriggerResult result = invokeTrigger(pool, client, user, "CustomMessage", triggerSource, request);
|
||||
if (!result.configured()) return null;
|
||||
if (result.errored()) {
|
||||
LOG.warnv("CustomMessage trigger failed for pool {0} (source {1}): {2}",
|
||||
|
||||
@@ -646,6 +646,8 @@ public class CognitoJsonHandler {
|
||||
Map<String, String> validationData = new HashMap<>();
|
||||
request.path("ValidationData").forEach(a -> validationData.put(a.path("Name").asText(), a.path("Value").asText()));
|
||||
Map<String, String> clientMetadata = clientMetadata(request);
|
||||
List<String> desiredDeliveryMediums = new ArrayList<>();
|
||||
request.path("DesiredDeliveryMediums").forEach(m -> desiredDeliveryMediums.add(m.asText()));
|
||||
|
||||
CognitoUser user = service.adminCreateUser(
|
||||
request.path("UserPoolId").asText(),
|
||||
@@ -654,6 +656,7 @@ public class CognitoJsonHandler {
|
||||
tempPassword,
|
||||
messageAction,
|
||||
request.path("ForceAliasCreation").asBoolean(false),
|
||||
desiredDeliveryMediums,
|
||||
validationData,
|
||||
clientMetadata
|
||||
);
|
||||
|
||||
@@ -46,6 +46,7 @@ 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;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.RandomPasswordGenerator;
|
||||
import io.github.hectorvent.floci.services.ses.SesService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -99,6 +100,9 @@ public class CognitoService implements ResourceProvider {
|
||||
List.of("ALLOW_REFRESH_TOKEN_AUTH", "ALLOW_USER_SRP_AUTH", "ALLOW_CUSTOM_AUTH");
|
||||
private static final String COGNITO_PASSWORD_SYMBOLS =
|
||||
"^$*.[]{}()?\"!@#%&/\\,><':;|_~`=+-";
|
||||
private static final int GENERATED_PASSWORD_MINIMUM_LENGTH = 8;
|
||||
private static final List<String> MESSAGE_ACTIONS = List.of("RESEND", "SUPPRESS");
|
||||
private static final List<String> DELIVERY_MEDIUMS = List.of("SMS", "EMAIL");
|
||||
// JVM-local stripes bound lock memory without retaining one lock for every user key.
|
||||
private static final int USER_LOCK_STRIPES = 512;
|
||||
/**
|
||||
@@ -2087,10 +2091,13 @@ public class CognitoService implements ResourceProvider {
|
||||
/**
|
||||
* AdminCreateUser with optional MessageAction.
|
||||
*
|
||||
* <p>{@code messageAction = "RESEND"} resends the invitation for an existing
|
||||
* user in {@code FORCE_CHANGE_PASSWORD} status without recreating it; floci
|
||||
* has no email transport, so this only refreshes {@code lastModifiedDate}.
|
||||
* {@code "SUPPRESS"} or {@code null} retain the default create behavior.</p>
|
||||
* <p>Without a {@code temporaryPassword}, Cognito generates one, unless the pool offers
|
||||
* passwordless sign-in, where the user is created {@code CONFIRMED} with no password. A user
|
||||
* with a password starts in {@code FORCE_CHANGE_PASSWORD}.</p>
|
||||
*
|
||||
* <p>{@code messageAction = null} sends the invitation; {@code "SUPPRESS"} sends nothing.
|
||||
* {@code "RESEND"} gives an existing {@code FORCE_CHANGE_PASSWORD} user a new temporary
|
||||
* password, the requested one or a generated one, and sends the invitation again.</p>
|
||||
*/
|
||||
public CognitoUser adminCreateUser(String userPoolId,
|
||||
String username,
|
||||
@@ -2107,12 +2114,13 @@ public class CognitoService implements ResourceProvider {
|
||||
String messageAction,
|
||||
boolean forceAliasCreation) {
|
||||
return adminCreateUser(userPoolId, username, attributes, temporaryPassword, messageAction,
|
||||
forceAliasCreation, Map.of(), Map.of());
|
||||
forceAliasCreation, List.of(), Map.of(), Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* AdminCreateUser with the request's {@code ValidationData} and {@code ClientMetadata}, which
|
||||
* reach only the PreSignUp trigger and are never stored.
|
||||
* AdminCreateUser with the request's {@code DesiredDeliveryMediums} for the invitation, where an
|
||||
* empty list means AWS's default, {@code SMS}, and its {@code ValidationData} and
|
||||
* {@code ClientMetadata}, which reach only the Lambda triggers and are never stored.
|
||||
*/
|
||||
public CognitoUser adminCreateUser(String userPoolId,
|
||||
String username,
|
||||
@@ -2120,22 +2128,23 @@ public class CognitoService implements ResourceProvider {
|
||||
String temporaryPassword,
|
||||
String messageAction,
|
||||
boolean forceAliasCreation,
|
||||
List<String> desiredDeliveryMediums,
|
||||
Map<String, String> validationData,
|
||||
Map<String, String> clientMetadata) {
|
||||
validateMessageAction(messageAction);
|
||||
List<String> deliveryMediums = invitationDeliveryMediums(desiredDeliveryMediums);
|
||||
// Locked on the requested username/alias (not yet resolved to a canonical id, since
|
||||
// an alias pool doesn't have one until creation), so two concurrent requests for the
|
||||
// same identifier can't both pass the existence/alias check and create duplicates.
|
||||
Object lock = userLock(userPoolId, username);
|
||||
if ("RESEND".equalsIgnoreCase(messageAction)) {
|
||||
synchronized (lock) {
|
||||
return resendInvitationUnderUserLock(userPoolId, username);
|
||||
}
|
||||
if ("RESEND".equals(messageAction)) {
|
||||
return resendInvitation(userPoolId, username, temporaryPassword, clientMetadata, deliveryMediums, lock);
|
||||
}
|
||||
|
||||
// The PreSignUp trigger runs with no lock held: its function can call back into the pool,
|
||||
// and a call that needs the same lock stripe would wait until the invocation timed out.
|
||||
// A taken username or alias is refused before the trigger sees the request, and checked
|
||||
// again under the lock once the trigger accepts, since users can change while it runs.
|
||||
// The PreSignUp and CustomMessage triggers run with no lock held: a function can call back
|
||||
// into the pool, and a call that needs the same lock stripe would wait until the invocation
|
||||
// timed out. A taken username or alias is refused before the triggers see the request, and
|
||||
// checked again under the lock once they return, since users can change while they run.
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
// Claimed before the username is checked, so an overlapping request for it is refused here
|
||||
// rather than passing the check while this one is in its trigger and invoking the trigger
|
||||
@@ -2146,25 +2155,85 @@ public class CognitoService implements ResourceProvider {
|
||||
}
|
||||
try {
|
||||
aliasHolderToMove(pool, username, forceAliasCreation);
|
||||
CognitoUser user = newAdminCreatedUser(pool, username, attributes, temporaryPassword);
|
||||
String password = initialPassword(pool, temporaryPassword);
|
||||
CognitoUser user = newAdminCreatedUser(pool, username, attributes, password);
|
||||
|
||||
// Before anything is stored, so a trigger that refuses the user leaves the pool unchanged,
|
||||
// including the alias a ForceAliasCreation request would move.
|
||||
authFlowHandler.firePreSignUpForAdminCreateUser(pool, user, validationData, clientMetadata);
|
||||
Invitation invitation = "SUPPRESS".equals(messageAction) ? null : new Invitation(password,
|
||||
deliveryMediums, invitationCustomMessage(pool, user, deliveryMediums, clientMetadata));
|
||||
|
||||
synchronized (lock) {
|
||||
return storeAdminCreatedUserUnderUserLock(userPoolId, username, forceAliasCreation, user);
|
||||
return storeAdminCreatedUserUnderUserLock(userPoolId, username, forceAliasCreation, user,
|
||||
invitation);
|
||||
}
|
||||
} finally {
|
||||
adminCreatesInFlight.remove(inFlightKey);
|
||||
}
|
||||
}
|
||||
|
||||
private CognitoUser resendInvitationUnderUserLock(String userPoolId, String username) {
|
||||
private static void validateMessageAction(String messageAction) {
|
||||
if (messageAction != null && !MESSAGE_ACTIONS.contains(messageAction)) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"1 validation error detected: Value '" + messageAction + "' at 'messageAction' failed to "
|
||||
+ "satisfy constraint: Member must satisfy enum value set: [RESEND, SUPPRESS]", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** The request's {@code DesiredDeliveryMediums}, or {@code SMS}, AWS's default, when it names none. */
|
||||
private static List<String> invitationDeliveryMediums(List<String> requested) {
|
||||
if (requested == null || requested.isEmpty()) {
|
||||
return List.of("SMS");
|
||||
}
|
||||
if (!DELIVERY_MEDIUMS.containsAll(requested)) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"1 validation error detected: Value '" + requested + "' at 'desiredDeliveryMediums' failed to "
|
||||
+ "satisfy constraint: Member must satisfy constraint: "
|
||||
+ "[Member must satisfy enum value set: [SMS, EMAIL]]", 400);
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
|
||||
private CognitoUser resendInvitation(String userPoolId, String username, String temporaryPassword,
|
||||
Map<String, String> clientMetadata, List<String> deliveryMediums,
|
||||
Object lock) {
|
||||
// The CustomMessage trigger runs with no lock held, as on create; the user is read again
|
||||
// under the lock before anything changes.
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
CognitoUser existing = userStore.get(userKey(userPoolId, username)).orElse(null);
|
||||
CognitoUser target = resendTarget(pool, username);
|
||||
Map<String, Object> customMessage = invitationCustomMessage(pool, target, deliveryMediums, clientMetadata);
|
||||
synchronized (lock) {
|
||||
return resendInvitationUnderUserLock(userPoolId, username, temporaryPassword, deliveryMediums,
|
||||
customMessage);
|
||||
}
|
||||
}
|
||||
|
||||
private CognitoUser resendInvitationUnderUserLock(String userPoolId, String username, String temporaryPassword,
|
||||
List<String> deliveryMediums,
|
||||
Map<String, Object> customMessage) {
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
CognitoUser existing = resendTarget(pool, username);
|
||||
// "RESEND ... to reset the temporary-password duration with a new temporary password".
|
||||
String password = temporaryPassword != null && !temporaryPassword.isEmpty()
|
||||
? temporaryPassword : generateTemporaryPassword(pool);
|
||||
// Checked and sent before the stored user changes, so a refused password or a failed
|
||||
// delivery leaves the user's current temporary password working.
|
||||
validatePasswordAgainstPolicy(pool, existing, password);
|
||||
deliverInvitation(pool, existing, new Invitation(password, deliveryMediums, customMessage));
|
||||
updateUserPassword(existing, password);
|
||||
existing.setTemporaryPassword(true);
|
||||
existing.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(userPoolId, existing.getUsername()), existing);
|
||||
LOG.infov("Resent invitation for user {0} in pool {1}", existing.getUsername(), userPoolId);
|
||||
return existing;
|
||||
}
|
||||
|
||||
/** The user a RESEND for {@code username} names, refused unless it awaits its first sign-in. */
|
||||
private CognitoUser resendTarget(UserPool pool, String username) {
|
||||
CognitoUser existing = userStore.get(userKey(pool.getId(), username)).orElse(null);
|
||||
if (usesAliasUsernames(pool) && existing == null) {
|
||||
existing = findUserByAlias(userPoolId, aliasAttributeForValue(pool, username), username);
|
||||
existing = findUserByAlias(pool.getId(), aliasAttributeForValue(pool, username), username);
|
||||
}
|
||||
if (existing == null) {
|
||||
throw new AwsException("UserNotFoundException", "User not found", 400);
|
||||
@@ -2175,9 +2244,6 @@ public class CognitoService implements ResourceProvider {
|
||||
""".formatted(existing.getUserStatus());
|
||||
throw new AwsException("UnsupportedUserStateException", userStateExceptionMessage, 400);
|
||||
}
|
||||
existing.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(userPoolId, existing.getUsername()), existing);
|
||||
LOG.infov("Resent invitation for user {0} in pool {1}", existing.getUsername(), userPoolId);
|
||||
return existing;
|
||||
}
|
||||
|
||||
@@ -2209,8 +2275,49 @@ public class CognitoService implements ResourceProvider {
|
||||
return existing;
|
||||
}
|
||||
|
||||
/**
|
||||
* The new user's password: the requested one, or a generated one unless the pool offers
|
||||
* passwordless sign-in, where the user gets none. "If you don't specify a value, Amazon Cognito
|
||||
* generates one for you unless you have passwordless options active for your user pool."
|
||||
*/
|
||||
private String initialPassword(UserPool pool, String temporaryPassword) {
|
||||
if (temporaryPassword != null && !temporaryPassword.isEmpty()) {
|
||||
return temporaryPassword;
|
||||
}
|
||||
return passwordlessFactors(pool).isEmpty() ? generateTemporaryPassword(pool) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The passwordless first factors the pool offers, an email or SMS one-time password. A passkey
|
||||
* does not count: AWS still needs a password for a user whose only factors are a password and
|
||||
* a passkey. As in USER_AUTH, a Lite pool offers none.
|
||||
*/
|
||||
private static List<String> passwordlessFactors(UserPool pool) {
|
||||
if ("LITE".equals(pool.getUserPoolTier())) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> factors = new ArrayList<>(CognitoAuthFlowHandler.allowedFirstAuthFactors(pool));
|
||||
factors.retainAll(List.of("EMAIL_OTP", "SMS_OTP"));
|
||||
return factors;
|
||||
}
|
||||
|
||||
/**
|
||||
* A temporary password that meets any password policy: the policy's minimum length, and at
|
||||
* least eight characters, with an uppercase and a lowercase letter, a digit and a symbol.
|
||||
* Secrets Manager's punctuation is the same set as Cognito's password symbols.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private String generateTemporaryPassword(UserPool pool) {
|
||||
int minimumLength = 0;
|
||||
if (pool.getPolicies() != null && pool.getPolicies().get("PasswordPolicy") instanceof Map<?, ?> policy) {
|
||||
minimumLength = policyInt((Map<String, Object>) policy, "MinimumLength");
|
||||
}
|
||||
return RandomPasswordGenerator.generate(MAPPER.createObjectNode()
|
||||
.put("PasswordLength", Math.max(GENERATED_PASSWORD_MINIMUM_LENGTH, minimumLength)));
|
||||
}
|
||||
|
||||
private CognitoUser newAdminCreatedUser(UserPool pool, String username, Map<String, String> attributes,
|
||||
String temporaryPassword) {
|
||||
String password) {
|
||||
Map<String, String> resolvedAttributes = attributes == null
|
||||
? new HashMap<>() : new HashMap<>(attributes);
|
||||
|
||||
@@ -2231,22 +2338,97 @@ public class CognitoService implements ResourceProvider {
|
||||
user.getAttributes().put("sub", UUID.randomUUID().toString());
|
||||
}
|
||||
|
||||
if (temporaryPassword != null && !temporaryPassword.isEmpty()) {
|
||||
updateUserPassword(user, temporaryPassword);
|
||||
if (password != null) {
|
||||
updateUserPassword(user, password);
|
||||
user.setTemporaryPassword(true);
|
||||
user.setUserStatus("FORCE_CHANGE_PASSWORD");
|
||||
} else {
|
||||
requirePasswordlessSignInAttribute(pool, user);
|
||||
requireSchemaRequiredAttributes(pool, user);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* "To create a user without a password, you must provide attribute values for an available
|
||||
* passwordless sign-in factor": an email address for EMAIL_OTP, a phone number for SMS_OTP.
|
||||
*/
|
||||
private void requirePasswordlessSignInAttribute(UserPool pool, CognitoUser user) {
|
||||
List<String> attributes = new ArrayList<>();
|
||||
for (String factor : passwordlessFactors(pool)) {
|
||||
attributes.add("EMAIL_OTP".equals(factor) ? "email" : "phone_number");
|
||||
}
|
||||
if (attributes.stream().noneMatch(attribute -> user.getAttributes().get(attribute) != null)) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"A user without a password needs a value for " + String.join(" or ", attributes) + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "When you create a user without a password, your request only succeeds if the user provides
|
||||
* values for all attributes that you have marked as required in your user pool." A user with a
|
||||
* temporary password may leave them out and supply them at the NEW_PASSWORD_REQUIRED challenge.
|
||||
*/
|
||||
private static void requireSchemaRequiredAttributes(UserPool pool, CognitoUser user) {
|
||||
List<String> missing = new ArrayList<>();
|
||||
for (Map<String, Object> attribute : CognitoStandardAttributes.merge(pool.getSchemaAttributes())) {
|
||||
String name = String.valueOf(attribute.get("Name"));
|
||||
String value = user.getAttributes().get(name);
|
||||
boolean required = Boolean.parseBoolean(String.valueOf(attribute.get("Required")));
|
||||
if (required && (value == null || value.isEmpty())) {
|
||||
missing.add(name + ": The attribute is required");
|
||||
}
|
||||
}
|
||||
if (!missing.isEmpty()) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"Attributes did not conform to the schema: " + String.join(", ", missing), 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the invitation for a new or resent user needs: the temporary password it carries,
|
||||
* {@code null} for a user without one, the mediums it goes to, and the CustomMessage trigger's
|
||||
* response, {@code null} when the trigger is not configured or failed.
|
||||
*/
|
||||
private record Invitation(String temporaryPassword, List<String> deliveryMediums,
|
||||
Map<String, Object> customMessage) {
|
||||
}
|
||||
|
||||
/** The CustomMessage trigger's response, fired only when the invitation has somewhere to go. */
|
||||
private Map<String, Object> invitationCustomMessage(UserPool pool, CognitoUser user, List<String> deliveryMediums,
|
||||
Map<String, String> clientMetadata) {
|
||||
if (messageDispatcher == null || !CognitoMessageDispatcher.hasInvitationRecipient(user, deliveryMediums)) {
|
||||
return null;
|
||||
}
|
||||
return authFlowHandler.fireCustomMessageForAdminCreateUser(pool, user, clientMetadata);
|
||||
}
|
||||
|
||||
private void deliverInvitation(UserPool pool, CognitoUser user, Invitation invitation) {
|
||||
if (invitation == null || messageDispatcher == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
messageDispatcher.dispatchInvitation(pool, user, invitation.temporaryPassword(),
|
||||
invitation.deliveryMediums(), invitation.customMessage());
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Failed to deliver the invitation for user {0} in pool {1}",
|
||||
user.getUsername(), pool.getId());
|
||||
throw new AwsException("CodeDeliveryFailureException", "Failed to deliver the message.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private CognitoUser storeAdminCreatedUserUnderUserLock(String userPoolId, String username,
|
||||
boolean forceAliasCreation, CognitoUser user) {
|
||||
// Read again under the lock rather than reused from before the trigger: while it ran, the
|
||||
boolean forceAliasCreation, CognitoUser user,
|
||||
Invitation invitation) {
|
||||
// Read again under the lock rather than reused from before the triggers: while they ran, the
|
||||
// pool may have been deleted, another request may have taken the username or alias, and
|
||||
// the alias holder may have been updated or deleted, which writing back an earlier read
|
||||
// would undo.
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
CognitoUser aliasHolder = aliasHolderToMove(pool, username, forceAliasCreation);
|
||||
// Sent once nothing else can refuse the request and before anything is stored, so a failed
|
||||
// delivery leaves no user behind and the alias where it was.
|
||||
deliverInvitation(pool, user, invitation);
|
||||
if (aliasHolder != null) {
|
||||
String aliasAttribute = aliasAttributeForValue(pool, username);
|
||||
aliasHolder.getAttributes().remove(aliasAttribute);
|
||||
|
||||
+142
-20
@@ -13,9 +13,12 @@ import org.apache.james.mime4j.field.address.DefaultAddressParser;
|
||||
import org.apache.james.mime4j.field.address.ParseException;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Routes a verification code through SES (email) or SNS (SMS) according to
|
||||
@@ -27,6 +30,8 @@ import java.util.Map;
|
||||
* whose {@code emailSubject}/{@code emailMessage}/{@code smsMessage} take precedence
|
||||
* over the pool's own template.
|
||||
*
|
||||
* AdminCreateUser invitations go out the same way, from {@link UserPool#getAdminCreateUserConfig()}.
|
||||
*
|
||||
* Email is sent from the address the pool's {@code EmailConfiguration} names when SES has verified
|
||||
* it for the pool's account, or from {@code no-reply@verificationemail.com} otherwise.
|
||||
*/
|
||||
@@ -44,6 +49,13 @@ public final class CognitoMessageDispatcher {
|
||||
private static final String DEVELOPER_SENDING_ACCOUNT = "DEVELOPER";
|
||||
private static final String SES_IDENTITY_RESOURCE_PREFIX = "identity/";
|
||||
private static final String CODE_PLACEHOLDER = "{####}";
|
||||
private static final String USERNAME_PLACEHOLDER = "{username}";
|
||||
private static final Pattern INVITE_PLACEHOLDERS = Pattern.compile("\\{username}|\\{####}");
|
||||
// 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";
|
||||
private static final String DEFAULT_INVITE_BODY = "Your username is {username} and temporary password is {####}.";
|
||||
private static final String DEFAULT_PASSWORDLESS_INVITE_BODY = "Your username is {username}.";
|
||||
|
||||
private final SesService ses;
|
||||
private final SnsService sns;
|
||||
@@ -86,33 +98,143 @@ public final class CognitoMessageDispatcher {
|
||||
if (subject == null) subject = stringOr(template.get("EmailSubject"), DEFAULT_EMAIL_SUBJECT);
|
||||
String rawBody = stringOrNull(customMessageResponse, "emailMessage");
|
||||
if (rawBody == null) rawBody = stringOr(template.get(emailTemplateKey()), DEFAULT_EMAIL_BODY);
|
||||
String body = renderTemplate(rawBody, code);
|
||||
Sender sender = sender(pool, region);
|
||||
ses.sendEmail(SendEmailRequest.builder()
|
||||
.source(sender.from())
|
||||
// SES takes Source as the default return path, the envelope sender it records
|
||||
// and hands to the SMTP relay, which takes a bare address.
|
||||
.returnPath(sender.from().equals(sender.address()) ? null : sender.address())
|
||||
.toAddresses(List.of(email))
|
||||
.region(region)
|
||||
.content(new EmailContent.Simple(subject, body, null, List.of()))
|
||||
.build());
|
||||
sendEmail(pool, region, email, subject, renderTemplate(rawBody, code));
|
||||
} else if ("SMS".equalsIgnoreCase(medium) && phone != null) {
|
||||
String rawBody = stringOrNull(customMessageResponse, "smsMessage");
|
||||
if (rawBody == null) rawBody = stringOr(resolveSmsTemplate(pool, template, purpose), DEFAULT_SMS_BODY);
|
||||
String body = renderTemplate(rawBody, code);
|
||||
sns.publish(
|
||||
null, null,
|
||||
phone,
|
||||
body,
|
||||
null,
|
||||
null,
|
||||
region
|
||||
);
|
||||
sendSms(region, phone, renderTemplate(rawBody, code));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the AdminCreateUser invitation to each of {@code deliveryMediums} that the user has an
|
||||
* {@code email} or {@code phone_number} for. The text is the CustomMessage trigger's response
|
||||
* when it gave one, else the pool's {@code AdminCreateUserConfig.InviteMessageTemplate}, else
|
||||
* AWS's default, with {@code {username}} and {@code {####}} (the temporary password) filled in.
|
||||
*
|
||||
* <p>{@code temporaryPassword} is {@code null} for a user created without a password, whose
|
||||
* default message names only the username and whose template's {@code {####}} is left empty. As
|
||||
* on AWS, a message without {@code {####}} is not delivered to a user who has a password, since
|
||||
* it could not tell them the password.</p>
|
||||
*
|
||||
* <p>A failed send is rethrown only when no message reached the user, so a caller that stores
|
||||
* the user once this returns never leaves a delivered invitation naming an account it did not
|
||||
* create.</p>
|
||||
*/
|
||||
public void dispatchInvitation(UserPool pool, CognitoUser user, String temporaryPassword,
|
||||
List<String> deliveryMediums, Map<String, Object> customMessageResponse) {
|
||||
Map<String, Object> template = inviteMessageTemplate(pool);
|
||||
String defaultBody = temporaryPassword == null ? DEFAULT_PASSWORDLESS_INVITE_BODY : DEFAULT_INVITE_BODY;
|
||||
String email = invitationRecipient(user, deliveryMediums, "EMAIL");
|
||||
String phone = invitationRecipient(user, deliveryMediums, "SMS");
|
||||
String region = AwsArnUtils.regionOrDefault(pool.getArn(), defaultRegion);
|
||||
|
||||
List<Runnable> sends = new ArrayList<>();
|
||||
if (email != null) {
|
||||
String body = renderInvitation(firstNonNull(stringOrNull(customMessageResponse, "emailMessage"),
|
||||
stringOrNull(template, "EmailMessage"), defaultBody), user.getUsername(), temporaryPassword);
|
||||
String subject = firstNonNull(stringOrNull(customMessageResponse, "emailSubject"),
|
||||
stringOrNull(template, "EmailSubject"), DEFAULT_INVITE_SUBJECT);
|
||||
if (body != null) {
|
||||
sends.add(() -> sendEmail(pool, region, email, subject, body));
|
||||
}
|
||||
}
|
||||
if (phone != null) {
|
||||
String body = renderInvitation(firstNonNull(stringOrNull(customMessageResponse, "smsMessage"),
|
||||
stringOrNull(template, "SMSMessage"), defaultBody), user.getUsername(), temporaryPassword);
|
||||
if (body != null) {
|
||||
sends.add(() -> sendSms(region, phone, body));
|
||||
}
|
||||
}
|
||||
|
||||
RuntimeException failure = null;
|
||||
boolean delivered = false;
|
||||
for (Runnable send : sends) {
|
||||
try {
|
||||
send.run();
|
||||
delivered = true;
|
||||
} catch (RuntimeException e) {
|
||||
if (failure == null) {
|
||||
failure = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure != null && !delivered) {
|
||||
throw failure;
|
||||
}
|
||||
if (failure != null) {
|
||||
LOG.warnv(failure, "An invitation for user {0} in pool {1} failed on one medium and went out on another",
|
||||
user.getUsername(), pool.getId());
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether any of {@code deliveryMediums} can reach the user, so an invitation has somewhere to go. */
|
||||
public static boolean hasInvitationRecipient(CognitoUser user, List<String> deliveryMediums) {
|
||||
return invitationRecipient(user, deliveryMediums, "EMAIL") != null
|
||||
|| invitationRecipient(user, deliveryMediums, "SMS") != null;
|
||||
}
|
||||
|
||||
/** The user's {@code email} for {@code EMAIL} or {@code phone_number} for {@code SMS}, when requested. */
|
||||
private static String invitationRecipient(CognitoUser user, List<String> deliveryMediums, String medium) {
|
||||
if (!deliveryMediums.contains(medium)) {
|
||||
return null;
|
||||
}
|
||||
return user.getAttributes().get("EMAIL".equals(medium) ? "email" : "phone_number");
|
||||
}
|
||||
|
||||
private void sendEmail(UserPool pool, String region, String email, String subject, String body) {
|
||||
Sender sender = sender(pool, region);
|
||||
ses.sendEmail(SendEmailRequest.builder()
|
||||
.source(sender.from())
|
||||
// SES takes Source as the default return path, the envelope sender it records
|
||||
// and hands to the SMTP relay, which takes a bare address.
|
||||
.returnPath(sender.from().equals(sender.address()) ? null : sender.address())
|
||||
.toAddresses(List.of(email))
|
||||
.region(region)
|
||||
.content(new EmailContent.Simple(subject, body, null, List.of()))
|
||||
.build());
|
||||
}
|
||||
|
||||
private void sendSms(String region, String phone, String body) {
|
||||
sns.publish(
|
||||
null, null,
|
||||
phone,
|
||||
body,
|
||||
null,
|
||||
null,
|
||||
region
|
||||
);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> inviteMessageTemplate(UserPool pool) {
|
||||
Map<String, Object> config = pool.getAdminCreateUserConfig();
|
||||
return config != null && config.get("InviteMessageTemplate") instanceof Map<?, ?> template
|
||||
? (Map<String, Object>) template : Map.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* The invitation text, or {@code null} when it has no {@code {####}} to carry the user's
|
||||
* temporary password. Both placeholders are filled in one pass, so neither a username nor a
|
||||
* password that happens to contain the other placeholder is substituted twice.
|
||||
*/
|
||||
private static String renderInvitation(String template, String username, String temporaryPassword) {
|
||||
if (temporaryPassword != null && !template.contains(CODE_PLACEHOLDER)) {
|
||||
return null;
|
||||
}
|
||||
return INVITE_PLACEHOLDERS.matcher(template).replaceAll(match -> Matcher.quoteReplacement(
|
||||
USERNAME_PLACEHOLDER.equals(match.group()) ? username
|
||||
: temporaryPassword == null ? "" : temporaryPassword));
|
||||
}
|
||||
|
||||
private static String firstNonNull(String first, String second, String fallback) {
|
||||
if (first != null) {
|
||||
return first;
|
||||
}
|
||||
return second != null ? second : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sender for the pool's {@code EmailConfiguration} (EmailConfigurationType):
|
||||
* <ul>
|
||||
|
||||
+20
-12
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -58,20 +59,23 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPassesUsernameAttributesAndMessageActionThrough() throws Exception {
|
||||
void createPassesEveryAdminCreateUserPropertyThrough() throws Exception {
|
||||
stubCreateEchoingTheUsername();
|
||||
StackResource r = resource(null);
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{"UserPoolId": "pool-a", "Username": "user-one", "MessageAction": "SUPPRESS",
|
||||
"ForceAliasCreation": true, "DesiredDeliveryMediums": ["EMAIL"],
|
||||
"ForceAliasCreation": true, "DesiredDeliveryMediums": ["EMAIL", "SMS"],
|
||||
"UserAttributes": [{"Name": "email", "Value": "one@example.com"},
|
||||
{"Name": "name", "Value": "One"}]}"""), ctx(null));
|
||||
{"Name": "name", "Value": "One"}],
|
||||
"ValidationData": [{"Name": "invite", "Value": "abc"}],
|
||||
"ClientMetadata": {"source": "stack"}}"""), ctx(null));
|
||||
|
||||
Map<String, String> attributes = new LinkedHashMap<>();
|
||||
attributes.put("email", "one@example.com");
|
||||
attributes.put("name", "One");
|
||||
verify(cognito).adminCreateUser("pool-a", "user-one", attributes, null, "SUPPRESS", true);
|
||||
verify(cognito).adminCreateUser("pool-a", "user-one", attributes, null, "SUPPRESS", true,
|
||||
List.of("EMAIL", "SMS"), Map.of("invite", "abc"), Map.of("source", "stack"));
|
||||
assertEquals("user-one", r.getPhysicalId(), "Ref must resolve to the username");
|
||||
assertTrue(r.getAttributes().keySet().stream().allMatch(key -> key.startsWith("__Floci")),
|
||||
"AWS::Cognito::UserPoolUser exposes no Fn::GetAtt attribute");
|
||||
@@ -82,7 +86,7 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
void anEmailAsUsernamePoolRefsTheCanonicalUsernameCognitoReturns() throws Exception {
|
||||
CognitoUser created = new CognitoUser();
|
||||
created.setUsername("d275a484-c0c1-70b3-46da-d9dafa5205e3");
|
||||
when(cognito.adminCreateUser(anyString(), anyString(), any(), any(), any(), anyBoolean()))
|
||||
when(cognito.adminCreateUser(anyString(), anyString(), any(), any(), any(), anyBoolean(), any(), any(), any()))
|
||||
.thenReturn(created);
|
||||
StackResource r = resource(null);
|
||||
|
||||
@@ -91,7 +95,8 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
"UserAttributes": [{"Name": "email", "Value": "alias.user@example.com"}]}"""), ctx(null));
|
||||
|
||||
verify(cognito).adminCreateUser("pool-a", "alias.user@example.com",
|
||||
Map.of("email", "alias.user@example.com"), null, null, false);
|
||||
Map.of("email", "alias.user@example.com"), null, null, false,
|
||||
List.of(), Map.of(), Map.of());
|
||||
assertEquals("d275a484-c0c1-70b3-46da-d9dafa5205e3", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@@ -104,7 +109,8 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
{"UserPoolId": "pool-a"}"""), ctx(null));
|
||||
|
||||
assertThat(r.getPhysicalId(), matchesPattern("my-stack-User-[a-z0-9]{12}"));
|
||||
verify(cognito).adminCreateUser("pool-a", r.getPhysicalId(), Map.of(), null, null, false);
|
||||
verify(cognito).adminCreateUser("pool-a", r.getPhysicalId(), Map.of(), null, null, false,
|
||||
List.of(), Map.of(), Map.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -133,7 +139,7 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
assertEquals("AlreadyExists", thrown.getErrorCode());
|
||||
assertEquals("Resource of type 'AWS::Cognito::UserPoolUser' with identifier 'pool-a|alice' already exists.",
|
||||
thrown.getMessage());
|
||||
verify(cognito, never()).adminCreateUser(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(cognito, never()).adminCreateUser(any(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
|
||||
assertNull(r.getPhysicalId());
|
||||
}
|
||||
|
||||
@@ -147,7 +153,7 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
{"UserPoolId": "pool-a", "Username": "alice", "MessageAction": "RESEND"}"""), ctx(null)));
|
||||
|
||||
assertEquals("UserNotFoundException", thrown.getErrorCode());
|
||||
verify(cognito, never()).adminCreateUser(any(), any(), any(), any(), any(), anyBoolean());
|
||||
verify(cognito, never()).adminCreateUser(any(), any(), any(), any(), any(), anyBoolean(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -199,7 +205,8 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
provisioner.provision(r, props("""
|
||||
{"UserPoolId": "pool-a", "Username": "user-one-b"}"""), ctx("user-one"));
|
||||
|
||||
verify(cognito).adminCreateUser("pool-a", "user-one-b", Map.of(), null, null, false);
|
||||
verify(cognito).adminCreateUser("pool-a", "user-one-b", Map.of(), null, null, false,
|
||||
List.of(), Map.of(), Map.of());
|
||||
assertEquals("user-one-b", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
assertEquals("user-one", provisioner.updateCleanupPhysicalId(r));
|
||||
@@ -224,7 +231,8 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
|
||||
assertNotEquals(first, r.getPhysicalId());
|
||||
assertThat(r.getPhysicalId(), matchesPattern("my-stack-User-[a-z0-9]{12}"));
|
||||
verify(cognito).adminCreateUser("pool-a", r.getPhysicalId(), Map.of("name", "Two"), null, null, false);
|
||||
verify(cognito).adminCreateUser("pool-a", r.getPhysicalId(), Map.of("name", "Two"), null, null, false,
|
||||
List.of(), Map.of(), Map.of());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@@ -406,7 +414,7 @@ class CognitoUserPoolUserCfnProvisionerTest {
|
||||
}
|
||||
|
||||
private void stubCreateEchoingTheUsername() {
|
||||
when(cognito.adminCreateUser(anyString(), anyString(), any(), any(), any(), anyBoolean()))
|
||||
when(cognito.adminCreateUser(anyString(), anyString(), any(), any(), any(), anyBoolean(), any(), any(), any()))
|
||||
.thenAnswer(inv -> {
|
||||
CognitoUser user = new CognitoUser();
|
||||
user.setUsername(inv.getArgument(1));
|
||||
|
||||
+102
@@ -768,6 +768,108 @@ class CognitoIntegrationTest {
|
||||
equalTo("no-reply@verificationemail.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminCreateUserEmailsAnInvitationWithAWorkingTemporaryPassword() throws Exception {
|
||||
String invitePoolId = cognitoJson("CreateUserPool", """
|
||||
{ "PoolName": "InvitationPool" }
|
||||
""").path("UserPool").path("Id").asText();
|
||||
String inviteClientId = cognitoJson("CreateUserPoolClient", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"ClientName": "invitation-client",
|
||||
"ExplicitAuthFlows": ["ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]
|
||||
}
|
||||
""".formatted(invitePoolId)).path("UserPoolClient").path("ClientId").asText();
|
||||
String invitee = "invited+" + UUID.randomUUID() + "@example.com";
|
||||
|
||||
cognitoAction("AdminCreateUser", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"UserAttributes": [{ "Name": "email", "Value": "%s" }],
|
||||
"DesiredDeliveryMediums": ["EMAIL"]
|
||||
}
|
||||
""".formatted(invitePoolId, invitee, invitee))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("User.UserStatus", equalTo("FORCE_CHANGE_PASSWORD"));
|
||||
|
||||
String toInvitee = "messages.findAll { it.Destination?.ToAddresses?.contains('" + invitee + "') }";
|
||||
String body = given()
|
||||
.when()
|
||||
.get("/_aws/ses")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(toInvitee, hasSize(1))
|
||||
.body(toInvitee + "[0].Subject", equalTo("Your temporary password"))
|
||||
.extract()
|
||||
.path(toInvitee + "[0].Body.text_part");
|
||||
Matcher invitation = Pattern.compile("^Your username is (\\S+) and temporary password is (\\S+)\\.$")
|
||||
.matcher(body);
|
||||
assertTrue(invitation.find(), body);
|
||||
assertEquals(invitee, invitation.group(1));
|
||||
|
||||
cognitoAction("AdminInitiateAuth", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"ClientId": "%s",
|
||||
"AuthFlow": "ADMIN_USER_PASSWORD_AUTH",
|
||||
"AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" }
|
||||
}
|
||||
""".formatted(invitePoolId, inviteClientId, invitee, invitation.group(2)))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ChallengeName", equalTo("NEW_PASSWORD_REQUIRED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminCreateUserWithSuppressSendsNoInvitation() throws Exception {
|
||||
String suppressPoolId = cognitoJson("CreateUserPool", """
|
||||
{ "PoolName": "SuppressedInvitationPool" }
|
||||
""").path("UserPool").path("Id").asText();
|
||||
String invitee = "suppressed+" + UUID.randomUUID() + "@example.com";
|
||||
|
||||
cognitoAction("AdminCreateUser", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"UserAttributes": [{ "Name": "email", "Value": "%s" }],
|
||||
"DesiredDeliveryMediums": ["EMAIL"],
|
||||
"MessageAction": "SUPPRESS"
|
||||
}
|
||||
""".formatted(suppressPoolId, invitee, invitee))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("User.UserStatus", equalTo("FORCE_CHANGE_PASSWORD"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/_aws/ses")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("messages.findAll { it.Destination?.ToAddresses?.contains('" + invitee + "') }", hasSize(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminCreateUserRefusesAnUnknownDeliveryMedium() throws Exception {
|
||||
String mediumPoolId = cognitoJson("CreateUserPool", """
|
||||
{ "PoolName": "UnknownMediumPool" }
|
||||
""").path("UserPool").path("Id").asText();
|
||||
|
||||
cognitoAction("AdminCreateUser", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "medium-user",
|
||||
"UserAttributes": [{ "Name": "email", "Value": "medium@example.com" }],
|
||||
"DesiredDeliveryMediums": ["VOICE"]
|
||||
}
|
||||
""".formatted(mediumPoolId))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"))
|
||||
.body("message", containsString("'desiredDeliveryMediums'"));
|
||||
}
|
||||
|
||||
/** Creates a pool with {@code emailConfiguration}, signs a new user up to it and returns the username. */
|
||||
private static String signUpWithEmailConfiguration(String poolName, String emailConfiguration) throws Exception {
|
||||
JsonNode poolResponse = cognitoJson("CreateUserPool", """
|
||||
|
||||
+59
@@ -2294,4 +2294,63 @@ class CognitoLambdaTriggersTest {
|
||||
Map<String, Object> event = MAPPER.readValue(payloadCaptor.getValue(), new TypeReference<>() {});
|
||||
assertEquals("CustomMessage_ForgotPassword", event.get("triggerSource"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void customMessageOverridesTheAdminCreateUserInvitation() {
|
||||
SesService ses = mock(SesService.class);
|
||||
CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class),
|
||||
mock(VerificationCodeService.class));
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1");
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::custom-message"),
|
||||
any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(ok(Map.of(
|
||||
"emailSubject", "Welcome",
|
||||
"emailMessage", "Sign in as {username} with {####}")));
|
||||
|
||||
svc.adminCreateUser(pool.getId(), "spike", Map.of("email", "spike@example.com"), "Spike@Test1", null,
|
||||
false, List.of("EMAIL"), Map.of(), Map.of());
|
||||
|
||||
assertVerificationEmail(ses, "spike@example.com", "Welcome", "Sign in as spike with Spike@Test1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void customMessageAdminCreateUserTriggerReceivesPlaceholdersAndClientMetadata() throws Exception {
|
||||
CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class),
|
||||
mock(VerificationCodeService.class));
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1");
|
||||
ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::custom-message"),
|
||||
payloadCaptor.capture(), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(ok(Map.of()));
|
||||
|
||||
svc.adminCreateUser(pool.getId(), "spike", Map.of("email", "spike@example.com"), "Spike@Test1", null,
|
||||
false, List.of("EMAIL"), Map.of(), Map.of("source", "admin"));
|
||||
|
||||
Map<String, Object> event = MAPPER.readValue(payloadCaptor.getValue(), new TypeReference<>() {});
|
||||
assertEquals("CustomMessage_AdminCreateUser", event.get("triggerSource"));
|
||||
assertEquals("CLIENT_ID_NOT_APPLICABLE", ((Map<String, Object>) event.get("callerContext")).get("clientId"));
|
||||
Map<String, Object> request = (Map<String, Object>) event.get("request");
|
||||
assertEquals("{####}", request.get("codeParameter"));
|
||||
assertEquals("{username}", request.get("usernameParameter"));
|
||||
assertEquals(Map.of("source", "admin"), request.get("clientMetadata"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void customMessageDoesNotFireForAnInvitationWithNowhereToGo() {
|
||||
CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class),
|
||||
mock(VerificationCodeService.class));
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1");
|
||||
|
||||
// SMS, the default medium, and no phone number.
|
||||
svc.adminCreateUser(pool.getId(), "spike", Map.of("email", "spike@example.com"), "Spike@Test1");
|
||||
|
||||
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any());
|
||||
}
|
||||
}
|
||||
@@ -5734,7 +5734,10 @@ class CognitoServiceTest {
|
||||
|
||||
@Test
|
||||
void getUserAuthFactors_userWithoutPassword_omitsPasswordFactor() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "PasswordlessPool"), "us-east-1");
|
||||
// AdminCreateUser leaves a user without a password only where passwordless sign-in is offered.
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "PasswordlessPool",
|
||||
"Policies", Map.of("SignInPolicy", Map.of("AllowedFirstAuthFactors", List.of("PASSWORD", "EMAIL_OTP")))),
|
||||
"us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "bob",
|
||||
@@ -5750,7 +5753,9 @@ class CognitoServiceTest {
|
||||
|
||||
@Test
|
||||
void getUserAuthFactors_userWithNoFactors_returnsOnlyUsername() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "NoFactorPool"), "us-east-1");
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "NoFactorPool",
|
||||
"Policies", Map.of("SignInPolicy", Map.of("AllowedFirstAuthFactors", List.of("PASSWORD", "EMAIL_OTP")))),
|
||||
"us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "carol",
|
||||
@@ -6456,4 +6461,278 @@ class CognitoServiceTest {
|
||||
segment += "=".repeat(pad);
|
||||
return new String(Base64.getUrlDecoder().decode(segment), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class AdminCreateUserInvitation {
|
||||
|
||||
private CognitoService svc;
|
||||
private CognitoMessageDispatcher messageDispatcher;
|
||||
|
||||
@BeforeEach
|
||||
void setUpMessaging() {
|
||||
messageDispatcher = mock(CognitoMessageDispatcher.class);
|
||||
svc = new CognitoService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
"http://localhost:4566",
|
||||
regionResolver,
|
||||
null,
|
||||
acmService,
|
||||
mock(VerificationCodeService.class),
|
||||
messageDispatcher,
|
||||
mock(TlsCertificateManager.class)
|
||||
);
|
||||
}
|
||||
|
||||
private CognitoUser create(UserPool pool, String username, Map<String, String> attributes,
|
||||
String temporaryPassword, String messageAction, List<String> mediums) {
|
||||
return svc.adminCreateUser(pool.getId(), username, attributes, temporaryPassword, messageAction,
|
||||
false, mediums, Map.of(), Map.of());
|
||||
}
|
||||
|
||||
private String sentPassword() {
|
||||
ArgumentCaptor<String> password = ArgumentCaptor.forClass(String.class);
|
||||
verify(messageDispatcher).dispatchInvitation(any(), any(), password.capture(), any(), any());
|
||||
return password.getValue();
|
||||
}
|
||||
|
||||
private UserPool passwordlessPool(List<String> firstAuthFactors) {
|
||||
return svc.createUserPool(Map.of(
|
||||
"PoolName", "PasswordlessInvitePool",
|
||||
"Policies", Map.of("SignInPolicy", Map.of("AllowedFirstAuthFactors", firstAuthFactors))),
|
||||
"us-east-1");
|
||||
}
|
||||
|
||||
private void failDelivery() {
|
||||
doThrow(new RuntimeException("SES down"))
|
||||
.when(messageDispatcher).dispatchInvitation(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutTemporaryPassword_generatesOneThatMeetsThePasswordPolicy() {
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "GeneratedPasswordPool",
|
||||
"Policies", Map.of("PasswordPolicy", Map.of(
|
||||
"MinimumLength", 14,
|
||||
"RequireUppercase", true,
|
||||
"RequireLowercase", true,
|
||||
"RequireNumbers", true,
|
||||
"RequireSymbols", true))), "us-east-1");
|
||||
|
||||
CognitoUser user = create(pool, "alice", Map.of("email", "alice@example.com"), null, null,
|
||||
List.of("EMAIL"));
|
||||
|
||||
assertEquals("FORCE_CHANGE_PASSWORD", user.getUserStatus());
|
||||
assertNotNull(user.getPasswordHash());
|
||||
String password = sentPassword();
|
||||
assertTrue(password.length() >= 14, password);
|
||||
assertTrue(password.chars().anyMatch(Character::isUpperCase), password);
|
||||
assertTrue(password.chars().anyMatch(Character::isLowerCase), password);
|
||||
assertTrue(password.chars().anyMatch(Character::isDigit), password);
|
||||
assertTrue(password.chars().anyMatch(c -> !Character.isLetterOrDigit(c)), password);
|
||||
// The pool's own policy check accepts the generated password.
|
||||
assertDoesNotThrow(() -> svc.adminSetUserPassword(pool.getId(), "alice", password, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutMessageAction_sendsTheInvitationThroughTheRequestedMediums() {
|
||||
UserPool pool = svc.createUserPool(Map.of("PoolName", "InvitePool"), "us-east-1");
|
||||
|
||||
CognitoUser user = create(pool, "alice", Map.of("email", "alice@example.com"), "Temp1234!", null,
|
||||
List.of("EMAIL"));
|
||||
|
||||
verify(messageDispatcher).dispatchInvitation(any(), eq(user), eq("Temp1234!"), eq(List.of("EMAIL")),
|
||||
isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutDesiredDeliveryMediums_sendsBySms() {
|
||||
UserPool pool = svc.createUserPool(Map.of("PoolName", "SmsDefaultPool"), "us-east-1");
|
||||
|
||||
create(pool, "alice", Map.of("phone_number", "+5215551234567"), "Temp1234!", null, List.of());
|
||||
|
||||
verify(messageDispatcher).dispatchInvitation(any(), any(), eq("Temp1234!"), eq(List.of("SMS")), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownDeliveryMedium_isRefusedAndCreatesNoUser() {
|
||||
UserPool pool = svc.createUserPool(Map.of("PoolName", "BadMediumPool"), "us-east-1");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> create(pool, "alice",
|
||||
Map.of("email", "alice@example.com"), "Temp1234!", null, List.of("EMAIL", "VOICE")));
|
||||
|
||||
assertEquals("InvalidParameterException", failure.getErrorCode());
|
||||
assertEquals("1 validation error detected: Value '[EMAIL, VOICE]' at 'desiredDeliveryMediums' failed "
|
||||
+ "to satisfy constraint: Member must satisfy constraint: [Member must satisfy enum value set: "
|
||||
+ "[SMS, EMAIL]]", failure.getMessage());
|
||||
assertEquals("UserNotFoundException",
|
||||
assertThrows(AwsException.class, () -> svc.adminGetUser(pool.getId(), "alice")).getErrorCode());
|
||||
verifyNoInteractions(messageDispatcher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownMessageAction_isRefused() {
|
||||
UserPool pool = svc.createUserPool(Map.of("PoolName", "BadActionPool"), "us-east-1");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> create(pool, "alice",
|
||||
Map.of("email", "alice@example.com"), "Temp1234!", "suppress", List.of("EMAIL")));
|
||||
|
||||
assertEquals("InvalidParameterException", failure.getErrorCode());
|
||||
assertEquals("1 validation error detected: Value 'suppress' at 'messageAction' failed to satisfy "
|
||||
+ "constraint: Member must satisfy enum value set: [RESEND, SUPPRESS]", failure.getMessage());
|
||||
verifyNoInteractions(messageDispatcher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void suppress_sendsNoInvitationButStillGeneratesAPassword() {
|
||||
UserPool pool = svc.createUserPool(Map.of("PoolName", "SuppressPool"), "us-east-1");
|
||||
|
||||
CognitoUser user = create(pool, "alice", Map.of("email", "alice@example.com"), null, "SUPPRESS",
|
||||
List.of("EMAIL"));
|
||||
|
||||
assertEquals("FORCE_CHANGE_PASSWORD", user.getUserStatus());
|
||||
assertNotNull(user.getPasswordHash());
|
||||
verify(messageDispatcher, never()).dispatchInvitation(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordlessPool_withoutTemporaryPassword_createsAConfirmedUserWithoutAPassword() {
|
||||
UserPool pool = passwordlessPool(List.of("PASSWORD", "EMAIL_OTP"));
|
||||
|
||||
CognitoUser user = create(pool, "alice", Map.of("email", "alice@example.com"), null, null,
|
||||
List.of("EMAIL"));
|
||||
|
||||
assertEquals("CONFIRMED", user.getUserStatus());
|
||||
assertNull(user.getPasswordHash());
|
||||
assertNull(sentPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordlessPool_withoutAnAttributeForAPasswordlessFactor_isRefused() {
|
||||
UserPool pool = passwordlessPool(List.of("PASSWORD", "EMAIL_OTP"));
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> create(pool, "alice",
|
||||
Map.of("phone_number", "+5215551234567"), null, null, List.of("SMS")));
|
||||
|
||||
assertEquals("InvalidParameterException", failure.getErrorCode());
|
||||
assertEquals("UserNotFoundException",
|
||||
assertThrows(AwsException.class, () -> svc.adminGetUser(pool.getId(), "alice")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordlessPool_withoutARequiredAttribute_isRefused() {
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "RequiredAttributePool",
|
||||
"Schema", List.of(Map.of("Name", "name", "AttributeDataType", "String",
|
||||
"Mutable", true, "Required", true)),
|
||||
"Policies", Map.of("SignInPolicy", Map.of("AllowedFirstAuthFactors",
|
||||
List.of("PASSWORD", "EMAIL_OTP")))), "us-east-1");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> create(pool, "alice",
|
||||
Map.of("email", "alice@example.com"), null, null, List.of("EMAIL")));
|
||||
|
||||
assertEquals("InvalidParameterException", failure.getErrorCode());
|
||||
assertEquals("Attributes did not conform to the schema: name: The attribute is required",
|
||||
failure.getMessage());
|
||||
// "Administrators can omit values for required attributes when they create users with
|
||||
// temporary passwords."
|
||||
assertEquals("FORCE_CHANGE_PASSWORD", create(pool, "bob", Map.of("email", "bob@example.com"),
|
||||
"Temp1234!", null, List.of("EMAIL")).getUserStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void passkeyPool_withoutTemporaryPassword_stillGeneratesOne() {
|
||||
// "If the only authentication flows available to new users require a password, for example
|
||||
// passkey or username-password, you must create or generate a temporary password".
|
||||
UserPool pool = passwordlessPool(List.of("PASSWORD", "WEB_AUTHN"));
|
||||
|
||||
CognitoUser user = create(pool, "alice", Map.of("email", "alice@example.com"), null, null,
|
||||
List.of("EMAIL"));
|
||||
|
||||
assertEquals("FORCE_CHANGE_PASSWORD", user.getUserStatus());
|
||||
assertNotNull(sentPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resend_givesANewTemporaryPasswordAndSendsTheInvitationAgain() {
|
||||
UserPool pool = svc.createUserPool(Map.of("PoolName", "ResendPool"), "us-east-1");
|
||||
String firstHash = create(pool, "alice", Map.of("email", "alice@example.com"), "Temp1234!",
|
||||
"SUPPRESS", List.of("EMAIL")).getPasswordHash();
|
||||
|
||||
CognitoUser resent = create(pool, "alice", Map.of(), null, "RESEND", List.of("EMAIL"));
|
||||
|
||||
String password = sentPassword();
|
||||
assertNotEquals("Temp1234!", password);
|
||||
assertNotEquals(firstHash, resent.getPasswordHash());
|
||||
assertEquals("FORCE_CHANGE_PASSWORD", resent.getUserStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resend_failedDelivery_keepsThePreviousTemporaryPassword() {
|
||||
UserPool pool = svc.createUserPool(Map.of("PoolName", "FailedResendPool"), "us-east-1");
|
||||
String firstHash = create(pool, "alice", Map.of("email", "alice@example.com"), "Temp1234!",
|
||||
"SUPPRESS", List.of("EMAIL")).getPasswordHash();
|
||||
failDelivery();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> create(pool, "alice", Map.of(),
|
||||
"Other1234!", "RESEND", List.of("EMAIL")));
|
||||
|
||||
assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
|
||||
assertEquals(firstHash, svc.adminGetUser(pool.getId(), "alice").getPasswordHash());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resend_passwordOutsideThePolicy_isRefusedBeforeAnythingIsSent() {
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "ResendPolicyPool",
|
||||
"Policies", Map.of("PasswordPolicy", Map.of("MinimumLength", 12))), "us-east-1");
|
||||
create(pool, "alice", Map.of("email", "alice@example.com"), "LongEnough1234!", "SUPPRESS",
|
||||
List.of("EMAIL"));
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> create(pool, "alice", Map.of(),
|
||||
"Short1!", "RESEND", List.of("EMAIL")));
|
||||
|
||||
assertEquals("InvalidPasswordException", failure.getErrorCode());
|
||||
verify(messageDispatcher, never()).dispatchInvitation(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInvitationDelivery_isCodeDeliveryFailureAndCreatesNoUser() {
|
||||
UserPool pool = svc.createUserPool(Map.of("PoolName", "FailedDeliveryPool"), "us-east-1");
|
||||
failDelivery();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> create(pool, "alice",
|
||||
Map.of("email", "alice@example.com"), null, null, List.of("EMAIL")));
|
||||
|
||||
assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
|
||||
AwsException lookup = assertThrows(AwsException.class, () -> svc.adminGetUser(pool.getId(), "alice"));
|
||||
assertEquals("UserNotFoundException", lookup.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInvitationDelivery_withForceAliasCreation_leavesTheAliasWithItsHolder() {
|
||||
Map<String, Object> poolRequest = Map.of("PoolName", "AliasInvitePool",
|
||||
"UsernameAttributes", List.of("email"));
|
||||
UserPool pool = svc.createUserPool(poolRequest, "us-east-1");
|
||||
CognitoUser holder = create(pool, "alice@example.com", Map.of("email_verified", "true"), "Temp1234!",
|
||||
"SUPPRESS", List.of("EMAIL"));
|
||||
failDelivery();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> svc.adminCreateUser(pool.getId(),
|
||||
"alice@example.com", Map.of("email_verified", "true"), null, null, true, List.of("EMAIL"),
|
||||
Map.of(), Map.of()));
|
||||
|
||||
assertEquals("CodeDeliveryFailureException", failure.getErrorCode());
|
||||
CognitoUser after = svc.adminGetUser(pool.getId(), holder.getUsername());
|
||||
assertEquals("alice@example.com", after.getAttributes().get("email"));
|
||||
assertEquals("true", after.getAttributes().get("email_verified"));
|
||||
assertEquals(holder.getUsername(), svc.adminGetUser(pool.getId(), "alice@example.com").getUsername());
|
||||
}
|
||||
}
|
||||
}
|
||||
+146
@@ -14,9 +14,12 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
@@ -451,6 +454,137 @@ class CognitoMessageDispatcherTest {
|
||||
assertEquals("noreply@repro.example", sentEmail().source());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_withoutTemplate_emailsAwsDefaultInvitation() {
|
||||
dispatcher.dispatchInvitation(pool(Map.of()), invitee("alice@example.com", null), "Temp1234!",
|
||||
List.of("EMAIL"), null);
|
||||
|
||||
assertEquals(SendEmailRequest.builder()
|
||||
.source("no-reply@verificationemail.com")
|
||||
.toAddresses(List.of("alice@example.com"))
|
||||
.region("us-east-1")
|
||||
.content(new EmailContent.Simple("Your temporary password",
|
||||
"Your username is alice and temporary password is Temp1234!.", null, List.of()))
|
||||
.build(), sentEmail());
|
||||
verifyNoInteractions(sns);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_rendersThePoolsInviteMessageTemplateOnBothMediums() {
|
||||
UserPool pool = invitePool(Map.of(
|
||||
"EmailSubject", "Welcome to Repro",
|
||||
"EmailMessage", "Hi {username}, sign in with {####}",
|
||||
"SMSMessage", "{username} / {####}"));
|
||||
|
||||
dispatcher.dispatchInvitation(pool, invitee("alice@example.com", "+5215551234567"), "Temp1234!",
|
||||
List.of("EMAIL", "SMS"), null);
|
||||
|
||||
SendEmailRequest sent = sentEmail();
|
||||
assertEquals("Welcome to Repro", subject(sent));
|
||||
assertEquals("Hi alice, sign in with Temp1234!", bodyText(sent));
|
||||
verify(sns).publish(isNull(), isNull(), eq("+5215551234567"), eq("alice / Temp1234!"),
|
||||
isNull(), isNull(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_sendsOnlyThroughTheRequestedMedium() {
|
||||
dispatcher.dispatchInvitation(pool(Map.of()), invitee("alice@example.com", "+5215551234567"), "Temp1234!",
|
||||
List.of("SMS"), null);
|
||||
|
||||
verify(sns).publish(isNull(), isNull(), eq("+5215551234567"),
|
||||
eq("Your username is alice and temporary password is Temp1234!."), isNull(), isNull(), eq("us-east-1"));
|
||||
verifyNoInteractions(ses);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_customMessageResponse_overridesThePoolsTemplate() {
|
||||
UserPool pool = invitePool(Map.of("EmailSubject", "Pool subject", "EmailMessage", "Pool {####}"));
|
||||
|
||||
dispatcher.dispatchInvitation(pool, invitee("alice@example.com", null), "Temp1234!", List.of("EMAIL"),
|
||||
Map.of("emailSubject", "Trigger subject", "emailMessage", "Trigger {username} {####}"));
|
||||
|
||||
SendEmailRequest sent = sentEmail();
|
||||
assertEquals("Trigger subject", subject(sent));
|
||||
assertEquals("Trigger alice Temp1234!", bodyText(sent));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_sendsFromThePoolsEmailConfigurationSender() {
|
||||
verified("noreply@repro.example", "us-east-1");
|
||||
UserPool pool = emailConfiguredPool(Map.of(
|
||||
"EmailSendingAccount", "DEVELOPER",
|
||||
"SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/noreply@repro.example",
|
||||
"From", "Repro App <noreply@repro.example>"));
|
||||
|
||||
dispatcher.dispatchInvitation(pool, invitee("alice@example.com", null), "Temp1234!", List.of("EMAIL"), null);
|
||||
|
||||
SendEmailRequest sent = sentEmail();
|
||||
assertEquals("Repro App <noreply@repro.example>", sent.source());
|
||||
assertEquals("noreply@repro.example", sent.returnPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_templateWithoutPasswordPlaceholder_isNotDelivered() {
|
||||
// "If your template doesn't have this placeholder, Amazon Cognito doesn't deliver the invitation message."
|
||||
UserPool pool = invitePool(Map.of("EmailMessage", "Welcome {username}"));
|
||||
|
||||
dispatcher.dispatchInvitation(pool, invitee("alice@example.com", null), "Temp1234!", List.of("EMAIL"), null);
|
||||
|
||||
verifyNoInteractions(ses);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_passwordlessUser_getsTheUsernameOnly() {
|
||||
dispatcher.dispatchInvitation(pool(Map.of()), invitee("alice@example.com", null), null, List.of("EMAIL"), null);
|
||||
|
||||
assertEquals("Your username is alice.", bodyText(sentEmail()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_passwordlessUser_leavesTheTemplatesPasswordPlaceholderEmpty() {
|
||||
UserPool pool = invitePool(Map.of("EmailMessage", "Hi {username}, your password: {####}"));
|
||||
|
||||
dispatcher.dispatchInvitation(pool, invitee("alice@example.com", null), null, List.of("EMAIL"), null);
|
||||
|
||||
assertEquals("Hi alice, your password: ", bodyText(sentEmail()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_fillsBothPlaceholdersInOnePass() {
|
||||
CognitoUser user = invitee("alice@example.com", null);
|
||||
user.setUsername("{####}");
|
||||
|
||||
dispatcher.dispatchInvitation(pool(Map.of()), user, "pw{username}1A!", List.of("EMAIL"), null);
|
||||
|
||||
assertEquals("Your username is {####} and temporary password is pw{username}1A!.", bodyText(sentEmail()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_failureOnTheOnlyMedium_isRethrown() {
|
||||
when(ses.sendEmail(any())).thenThrow(new IllegalStateException("SES down"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> dispatcher.dispatchInvitation(pool(Map.of()),
|
||||
invitee("alice@example.com", null), "Temp1234!", List.of("EMAIL"), null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_failureAfterAnotherMediumDelivered_isNotRethrown() {
|
||||
when(sns.publish(any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("SNS down"));
|
||||
|
||||
assertDoesNotThrow(() -> dispatcher.dispatchInvitation(pool(Map.of()),
|
||||
invitee("alice@example.com", "+5215551234567"), "Temp1234!", List.of("EMAIL", "SMS"), null));
|
||||
assertEquals("alice@example.com", sentEmail().toAddresses().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dispatchInvitation_userWithoutTheRequestedAttribute_sendsNothing() {
|
||||
assertDoesNotThrow(() -> dispatcher.dispatchInvitation(pool(Map.of()), invitee("alice@example.com", null),
|
||||
"Temp1234!", List.of("SMS"), null));
|
||||
|
||||
verifyNoInteractions(ses, sns);
|
||||
}
|
||||
|
||||
private SendEmailRequest sentEmail() {
|
||||
ArgumentCaptor<SendEmailRequest> captor = ArgumentCaptor.forClass(SendEmailRequest.class);
|
||||
verify(ses).sendEmail(captor.capture());
|
||||
@@ -476,6 +610,18 @@ class CognitoMessageDispatcherTest {
|
||||
return p;
|
||||
}
|
||||
|
||||
private UserPool invitePool(Map<String, Object> inviteMessageTemplate) {
|
||||
UserPool p = pool(Map.of());
|
||||
p.setAdminCreateUserConfig(Map.of("InviteMessageTemplate", inviteMessageTemplate));
|
||||
return p;
|
||||
}
|
||||
|
||||
private CognitoUser invitee(String email, String phone) {
|
||||
CognitoUser u = user(email, phone);
|
||||
u.setUsername("alice");
|
||||
return u;
|
||||
}
|
||||
|
||||
private UserPool pool(Map<String, Object> template) {
|
||||
UserPool p = new UserPool();
|
||||
p.setVerificationMessageTemplate(new HashMap<>(template));
|
||||
|
||||
Reference in new issue
Block a user