mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(cognito): support SMS and email MFA challenges (#5104)
SetUserPoolMfaConfig validated SmsMfaConfiguration and EmailMfaConfiguration but stored neither, SMSMfaSettings was ignored, and no MFA code was ever sent, so a user who picked SMS or email as a second factor signed in without one. - SetUserPoolMfaConfig stores both configurations, GetUserPoolMfaConfig returns them, and OFF drops them. SmsMfaConfiguration also sets the pool's SmsAuthenticationMessage and SmsConfiguration. - A pool offers SMS MFA once it has an SmsMfaConfiguration or an SmsConfiguration from CreateUserPool or UpdateUserPool, as AWS makes SMS an MFA factor for any pool with an SMS configuration. - SetUserMFAPreference and AdminSetUserMFAPreference store SMSMfaSettings. Turning SMS or email MFA on for a user without a phone_number or email fails with InvalidParameterException. UserMFASettingList and PreferredMfaSetting report SMS_MFA. - After a password or SRP first factor, the user's factors follow the developer guide's MFA logic: with OPTIONAL the factors the user turned on, with ON every factor the pool offers and the user can receive. The preferred factor's challenge follows, the only factor's, or SELECT_MFA_TYPE between several. - SMS_MFA sends a code through SNS with SmsAuthenticationMessage. Email MFA is the EMAIL_OTP challenge, a code through SES with EmailMfaConfiguration's subject and message, which also carry the USER_AUTH EMAIL_OTP sign-in code once set. Both fire the CustomMessage trigger with CustomMessage_Authentication, and a right code marks the phone number or email address verified. - In USER_AUTH, a user with such a factor in an optional-MFA pool is offered only password challenges. Closes #5182
This commit is contained in:
1 parent
db8c441ed4
commit
d0e0af502b
11 files changed
+821
-65
No files matched your search
+46
-16
@@ -47,9 +47,9 @@ format. Validation runs before pool or client lookup.
|
||||
| ListUserPools | Lists local user pools visible in the request region. |
|
||||
| UpdateUserPool | Updates mutable user pool settings and persisted user-pool tags. |
|
||||
| DeleteUserPool | Deletes a local user pool and everything it owns: users, groups, app clients, resource servers, identity providers, revoked tokens and verification codes. Refused with `InvalidParameterException` while `DeletionProtection` is `ACTIVE` (switch it to `INACTIVE` with `UpdateUserPool` first, as on AWS) or while a domain is still configured. |
|
||||
| GetUserPoolMfaConfig | Returns the pool's MFA mode and, once configured, its software-token and passkey (`WebAuthnConfiguration`) settings. |
|
||||
| GetUserPoolMfaConfig | Returns the pool's MFA mode and, once configured, its software-token, SMS and email MFA, and passkey (`WebAuthnConfiguration`) settings. |
|
||||
| AddCustomAttributes | Adds 1 to 25 attributes to a user pool's schema, prefixing each name with `custom:`, or `dev:` for a `DeveloperOnlyAttribute`, and rejecting a name the schema already has. |
|
||||
| SetUserPoolMfaConfig | Sets `MfaConfiguration` (`OFF`/`ON`/`OPTIONAL`) and `SoftwareTokenMfaConfiguration`. An absent `MfaConfiguration` means `OFF`, and turning MFA off drops the factor configuration with it. Validation follows the live service: `OFF` alongside a software-token, email or SMS factor is rejected, and `ON`/`OPTIONAL` with none of those three is rejected, in both cases on the member being present, not on its `Enabled` value. `WebAuthnConfiguration` sits outside both rules, as it does in AWS, and is stored: see [Passkeys](#passkeys). A request without it keeps the stored one. SMS and email configurations are validated and not stored: Floci cannot deliver those factors, so keeping the config would imply a capability it does not have. |
|
||||
| SetUserPoolMfaConfig | Sets `MfaConfiguration` (`OFF`/`ON`/`OPTIONAL`) and `SoftwareTokenMfaConfiguration`. An absent `MfaConfiguration` means `OFF`, and turning MFA off drops the factor configuration with it. Validation follows the live service: `OFF` alongside a software-token, email or SMS factor is rejected, and `ON`/`OPTIONAL` with none of those three is rejected, in both cases on the member being present, not on its `Enabled` value. `WebAuthnConfiguration` sits outside both rules, as it does in AWS, and is stored: see [Passkeys](#passkeys). A request without it keeps the stored one. `SmsMfaConfiguration` and `EmailMfaConfiguration` are stored and offer SMS and email MFA (see [SMS and email MFA](#sms-and-email-mfa)); `SmsMfaConfiguration` also sets the pool's `SmsAuthenticationMessage` and `SmsConfiguration`. |
|
||||
|
||||
Email that Cognito sends to users, such as verification codes, goes through Floci's SES (readable
|
||||
at `/_aws/ses`) from the sender the pool's `EmailConfiguration` names:
|
||||
@@ -239,7 +239,7 @@ further divergences, both deliberate:
|
||||
| AdminDisableUser | Disables a user, whose sign-in then fails with `NotAuthorizedException` (`User is disabled.`). Tokens already issued keep working, where AWS revokes the user's access tokens. |
|
||||
| AdminEnableUser | Re-enables a disabled user. |
|
||||
| AdminResetUserPassword | Clears a user's password and sets the status to `RESET_REQUIRED`, so sign-in fails with `PasswordResetRequiredException`. Floci sends no reset code: finish with `ForgotPassword` and `ConfirmForgotPassword`, or `AdminSetUserPassword`. Refused when the pool's account recovery is `admin_only`. |
|
||||
| AdminSetUserMFAPreference | Sets a user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`, and passkey MFA from `WebAuthnMfaSettings` (see [Passkeys](#passkeys)). SMS settings are accepted but not stored. See [MFA preferences](#mfa-preferences). |
|
||||
| AdminSetUserMFAPreference | Sets a user's SMS, email and software-token MFA preferences from `SMSMfaSettings`, `EmailMfaSettings` and `SoftwareTokenMfaSettings`, and passkey MFA from `WebAuthnMfaSettings` (see [Passkeys](#passkeys)). See [MFA preferences](#mfa-preferences). |
|
||||
| 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. |
|
||||
|
||||
@@ -288,14 +288,14 @@ passwordless pool generates a password. `TemporaryPasswordValidityDays` is not e
|
||||
| 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. |
|
||||
| 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 email and software-token MFA preferences set with `SetUserMFAPreference`. SMS MFA settings are not reported. |
|
||||
| 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. |
|
||||
| VerifyUserAttribute | Verifies an email or phone_number attribute with its issued verification code. |
|
||||
| UpdateUserAttributes | Updates attributes for the authenticated access-token user. |
|
||||
| DeleteUserAttributes | Deletes the named attributes from the authenticated access-token user. |
|
||||
| DeleteUser | Deletes the authenticated access-token user and removes them from their groups. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. |
|
||||
| ChangePassword | Changes the authenticated user's password. |
|
||||
| SetUserMFAPreference | Sets the authenticated access-token user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`, and passkey MFA from `WebAuthnMfaSettings` (see [Passkeys](#passkeys)). SMS settings are accepted but not stored. See [MFA preferences](#mfa-preferences). |
|
||||
| SetUserMFAPreference | Sets the authenticated access-token user's SMS, email and software-token MFA preferences from `SMSMfaSettings`, `EmailMfaSettings` and `SoftwareTokenMfaSettings`, and passkey MFA from `WebAuthnMfaSettings` (see [Passkeys](#passkeys)). See [MFA preferences](#mfa-preferences). |
|
||||
| GlobalSignOut | Revokes the access, ID and refresh tokens issued to the authenticated access-token user. |
|
||||
| StartWebAuthnRegistration | Returns the `CredentialCreationOptions` to register a passkey for the authenticated access-token user. See [Passkeys](#passkeys). |
|
||||
| CompleteWebAuthnRegistration | Verifies the `RegistrationResponseJSON` in `Credential` and registers the passkey. |
|
||||
@@ -353,21 +353,51 @@ then on a successful password or SRP first factor, through `USER_PASSWORD_AUTH`,
|
||||
challenge follows the user's registered authenticator even when the pool later stops offering
|
||||
software-token MFA, which is what AWS documents.
|
||||
|
||||
- Turning software-token MFA on for a user without a verified authenticator fails with
|
||||
`InvalidParameterException` (`User does not have delivery config set to turn on
|
||||
SOFTWARE_TOKEN_MFA`). Turning a factor off is always accepted and drops its preference.
|
||||
- Only one factor is preferred: preferring one clears the preference of the other, and preferring
|
||||
both in one request, or preferring a factor that is off, fails with `InvalidParameterException`.
|
||||
- `UserMFASettingList` lists the factors turned on (`EMAIL_OTP`, `SOFTWARE_TOKEN_MFA`), and
|
||||
- Turning a factor on for a user it cannot reach fails with `InvalidParameterException`
|
||||
(`User does not have delivery config set to turn on <factor>`): SMS MFA without a
|
||||
`phone_number`, email MFA without an `email`, software-token MFA without a verified
|
||||
authenticator. Turning a factor off is always accepted and drops its preference.
|
||||
- Only one factor is preferred: preferring one clears the preference of the others, and preferring
|
||||
two in one request, or preferring a factor that is off, fails with `InvalidParameterException`.
|
||||
- `UserMFASettingList` lists the factors turned on (`SMS_MFA`, `EMAIL_OTP`, `SOFTWARE_TOKEN_MFA`), and
|
||||
`PreferredMfaSetting` the preferred one. Both are omitted when empty. In a pool that requires
|
||||
software-token MFA, a registered authenticator is listed whether or not it was turned on, since
|
||||
every sign-in asks for it.
|
||||
- In `USER_AUTH`, a user with software-token MFA turned on in an optional-MFA pool is offered only
|
||||
`PASSWORD` and `PASSWORD_SRP`, as AWS documents for users with MFA, so the second factor still
|
||||
follows. Email MFA does not restrict the choice, because Floci does not send an email MFA code
|
||||
after a password. A user who also turned passkey MFA on keeps `WEB_AUTHN` (see [Passkeys](#passkeys)).
|
||||
- In `USER_AUTH`, a user with an MFA factor the pool can ask for, turned on in an optional-MFA pool,
|
||||
is offered only `PASSWORD` and `PASSWORD_SRP`, as AWS documents for users with MFA, so the second
|
||||
factor still follows. A user who also turned passkey MFA on keeps `WEB_AUTHN` (see [Passkeys](#passkeys)).
|
||||
|
||||
SMS and email MFA challenges, and managed-login MFA, are not emulated.
|
||||
#### SMS and email MFA
|
||||
|
||||
A pool offers SMS MFA once `SetUserPoolMfaConfig` has set `SmsMfaConfiguration`, or once it has an
|
||||
`SmsConfiguration` from `CreateUserPool` or `UpdateUserPool`, since AWS makes SMS an MFA factor for any
|
||||
pool with an SMS configuration and `CreateUserPool` sets up MFA only that way. It offers email MFA once
|
||||
`SetUserPoolMfaConfig` has set `EmailMfaConfiguration`. After a successful password or SRP first
|
||||
factor:
|
||||
|
||||
- With `MfaConfiguration=OPTIONAL`, the factors that count are the ones the user turned on. With
|
||||
`ON`, every factor the pool offers and the user can receive counts (a phone number for SMS, an
|
||||
email address for email, a registered authenticator for software tokens), since AWS lets users
|
||||
of such a pool choose only the preferred one. A user with no such factor gets `MFA_SETUP` when
|
||||
the pool offers software-token MFA.
|
||||
- The preferred factor's challenge follows; with one factor, that one's; with several and no
|
||||
preference, `SELECT_MFA_TYPE`, whose `MFAS_CAN_CHOOSE` lists them (for example
|
||||
`["SMS_MFA","SOFTWARE_TOKEN_MFA","EMAIL_OTP"]`). Answer it with `ANSWER` set to one of them.
|
||||
- `SMS_MFA` sends a code through SNS (inspect it at `/_aws/sns`) with the pool's
|
||||
`SmsAuthenticationMessage`, and is answered with `SMS_MFA_CODE`. Email MFA is the `EMAIL_OTP`
|
||||
challenge: a code through SES (`/_aws/ses`) with `EmailMfaConfiguration`'s `Subject` and
|
||||
`Message`, answered with `EMAIL_OTP_CODE`. Both carry `CODE_DELIVERY_DELIVERY_MEDIUM` and the
|
||||
masked `CODE_DELIVERY_DESTINATION`, and fire the CustomMessage trigger with
|
||||
`CustomMessage_Authentication`. Once set, `EmailMfaConfiguration`'s `Subject` and `Message` also
|
||||
carry the `USER_AUTH` `EMAIL_OTP` sign-in code, as `SmsAuthenticationMessage` does for `SMS_OTP`.
|
||||
- A wrong code fails with `CodeMismatchException` and leaves the session for another try. After a
|
||||
right one, the phone number or email address the code went to is marked verified, as on AWS.
|
||||
- Signing in again while the last code is still unused and under 30 seconds old answers the new
|
||||
challenge with that code instead of sending another.
|
||||
|
||||
Not emulated: the rule that an attribute used for account recovery cannot also receive MFA codes,
|
||||
`MFA_SETUP` for SMS or email in a pool that requires MFA without offering software tokens (the
|
||||
user signs in without a challenge there), and managed-login MFA.
|
||||
|
||||
### Passkeys
|
||||
|
||||
|
||||
+206
-17
@@ -72,6 +72,7 @@ final class CognitoAuthFlowHandler {
|
||||
private final ConcurrentHashMap<String, SrpSession> srpSessions = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, CustomAuthToken> customAuthSessions = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, TotpSession> totpSessions = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, MfaSession> mfaSessions = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Guards both USER_AUTH session maps and nothing else: no storage I/O or Lambda trigger runs under it,
|
||||
* so one user's sign-in cannot hold up another's. The code store redeems sign-in codes, once, outside it.
|
||||
@@ -92,6 +93,14 @@ final class CognitoAuthFlowHandler {
|
||||
String triggerSource, Instant expiresAt, String secret,
|
||||
AtomicInteger failedAttempts) {}
|
||||
|
||||
/**
|
||||
* A pending SMS_MFA, email MFA (EMAIL_OTP) or SELECT_MFA_TYPE challenge after a first factor.
|
||||
* {@code choices} holds SELECT_MFA_TYPE's MFAS_CAN_CHOOSE.
|
||||
*/
|
||||
private record MfaSession(String userPoolId, String username, String clientId, String challengeName,
|
||||
List<String> choices, Map<String, String> clientMetadata, String triggerSource,
|
||||
Instant expiresAt) {}
|
||||
|
||||
/**
|
||||
* Correlates a USER_AUTH challenge response back to the InitiateAuth/RespondToAuthChallenge
|
||||
* call that issued it, the same way {@link SrpSession} and {@link CustomAuthSession} do for
|
||||
@@ -461,6 +470,17 @@ final class CognitoAuthFlowHandler {
|
||||
rejectSimulatedUser(consumeUserAuthSession(pool, client, session, "PASSWORD_SRP"));
|
||||
return handleUserSrpAuth(pool, client, responses, clientMetadata);
|
||||
}
|
||||
if ("SMS_MFA".equals(challengeName)) {
|
||||
return handleMessageMfaChallenge(pool, client, "SMS_MFA", session, responses, clientMetadata);
|
||||
}
|
||||
// EMAIL_OTP names both the email MFA challenge and USER_AUTH's email first factor; the session tells them apart.
|
||||
if (("EMAIL_OTP".equals(challengeName) || "EMAIL_MFA".equals(challengeName))
|
||||
&& session != null && mfaSessions.containsKey(session)) {
|
||||
return handleMessageMfaChallenge(pool, client, "EMAIL_OTP", session, responses, clientMetadata);
|
||||
}
|
||||
if ("SELECT_MFA_TYPE".equals(challengeName)) {
|
||||
return handleSelectMfaType(pool, client, session, responses, clientMetadata);
|
||||
}
|
||||
if ("EMAIL_OTP".equals(challengeName) || "SMS_OTP".equals(challengeName)) {
|
||||
rejectSimulatedUser(consumeUserAuthSession(pool, client, session, challengeName));
|
||||
return handleOtpChallengeResponse(pool, client, challengeName, responses, clientMetadata);
|
||||
@@ -1252,10 +1272,9 @@ final class CognitoAuthFlowHandler {
|
||||
List<String> allowed = allowedFirstAuthFactors(pool);
|
||||
available.removeIf(challenge -> !allowed.contains("PASSWORD_SRP".equals(challenge) ? "PASSWORD" : challenge));
|
||||
// Where MFA is optional, AWS lets a user who has turned on an MFA factor sign in with a password
|
||||
// only, so that the second factor still follows. Floci asks for software-token codes, not for
|
||||
// email or SMS ones, so only that factor restricts the choice here. A user who turned passkey MFA
|
||||
// on keeps WEB_AUTHN, since a user-verified passkey satisfies MFA on its own.
|
||||
if ("OPTIONAL".equals(pool.getMfaConfiguration()) && CognitoService.softwareTokenMfaEnabled(user)) {
|
||||
// only, so that the second factor still follows. A user who turned passkey MFA on keeps WEB_AUTHN,
|
||||
// since a user-verified passkey satisfies MFA on its own.
|
||||
if ("OPTIONAL".equals(pool.getMfaConfiguration()) && !mfaFactors(pool, user).isEmpty()) {
|
||||
boolean passkeyIsMfa = passkeySatisfiesMfa(pool, user);
|
||||
available.removeIf(challenge -> !"PASSWORD".equals(challenge) && !"PASSWORD_SRP".equals(challenge)
|
||||
&& !(passkeyIsMfa && "WEB_AUTHN".equals(challenge)));
|
||||
@@ -2041,28 +2060,115 @@ final class CognitoAuthFlowHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends a successful first factor with tokens, or with the MFA challenge the pool and user call for.
|
||||
* A pool that requires MFA asks for the user's authenticator, or sets one up when the user has none.
|
||||
* Where MFA is optional, only a user who has turned on software-token MFA with SetUserMFAPreference
|
||||
* is asked for a code. AWS keeps accepting a registered authenticator after the pool stops offering
|
||||
* software-token MFA, so the optional case does not look at the pool's software-token setting.
|
||||
* Ends a successful first factor with tokens, or with the MFA challenge the pool and user call for:
|
||||
* the user's preferred factor, the only one, or SELECT_MFA_TYPE between several. A pool that requires
|
||||
* MFA sets up an authenticator for a user with no factor it can use, when it offers software-token MFA.
|
||||
*/
|
||||
private Map<String, Object> completePrimaryAuth(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
String triggerSource, Map<String, String> clientMetadata) {
|
||||
TotpPhase phase;
|
||||
if ("OPTIONAL".equals(pool.getMfaConfiguration()) && CognitoService.softwareTokenMfaEnabled(user)) {
|
||||
phase = TotpPhase.CODE_REQUIRED;
|
||||
} else if ("ON".equals(pool.getMfaConfiguration()) && Boolean.TRUE.equals(pool.getSoftwareTokenMfaEnabled())) {
|
||||
phase = user.getSoftwareTokenMfaSecret() == null ? TotpPhase.SETUP : TotpPhase.CODE_REQUIRED;
|
||||
} else {
|
||||
String mode = pool.getMfaConfiguration();
|
||||
if (!"ON".equals(mode) && !"OPTIONAL".equals(mode)) {
|
||||
return authenticationResult(pool, client, user, triggerSource, clientMetadata);
|
||||
}
|
||||
Map<String, String> metadata = clientMetadata == null ? Map.of() : Map.copyOf(clientMetadata);
|
||||
List<String> factors = mfaFactors(pool, user);
|
||||
if (factors.isEmpty()) {
|
||||
if ("ON".equals(mode) && Boolean.TRUE.equals(pool.getSoftwareTokenMfaEnabled())) {
|
||||
return totpChallenge(pool, client, user, TotpPhase.SETUP, triggerSource, metadata);
|
||||
}
|
||||
return authenticationResult(pool, client, user, triggerSource, clientMetadata);
|
||||
}
|
||||
String preferred = CognitoService.preferredMfaSetting(pool, user);
|
||||
if (preferred != null && factors.contains(preferred)) {
|
||||
return startMfaChallenge(pool, client, user, preferred, triggerSource, metadata);
|
||||
}
|
||||
if (factors.size() == 1) {
|
||||
return startMfaChallenge(pool, client, user, factors.get(0), triggerSource, metadata);
|
||||
}
|
||||
return selectMfaTypeChallenge(pool, client, user, factors, triggerSource, metadata);
|
||||
}
|
||||
|
||||
/**
|
||||
* The MFA factors a sign-in by {@code user} can be asked for, in the order SELECT_MFA_TYPE lists them.
|
||||
* Where MFA is optional, a factor counts once the user has turned it on with SetUserMFAPreference.
|
||||
* Where it is required, every factor the pool offers and the user can receive counts, since AWS lets
|
||||
* users of such a pool choose only which one is preferred. An SMS factor needs a pool that offers SMS
|
||||
* MFA and the user's phone number; an email factor needs the pool's EmailMfaConfiguration and the
|
||||
* user's email address.
|
||||
*/
|
||||
private List<String> mfaFactors(UserPool pool, CognitoUser user) {
|
||||
boolean required = "ON".equals(pool.getMfaConfiguration());
|
||||
boolean messaging = service.verificationServicesConfigured();
|
||||
List<String> factors = new ArrayList<>();
|
||||
if (messaging && smsMfaOffered(pool) && user.getAttributes().get("phone_number") != null
|
||||
&& (required || (user.getSmsMfaSettings() != null && user.getSmsMfaSettings().isEnabled()))) {
|
||||
factors.add("SMS_MFA");
|
||||
}
|
||||
if (required ? CognitoService.softwareTokenMfaActive(pool, user) : CognitoService.softwareTokenMfaEnabled(user)) {
|
||||
factors.add("SOFTWARE_TOKEN_MFA");
|
||||
}
|
||||
if (messaging && pool.getEmailMfaConfiguration() != null && user.getAttributes().get("email") != null
|
||||
&& (required || (user.getEmailMfaSettings() != null && user.getEmailMfaSettings().isEnabled()))) {
|
||||
factors.add("EMAIL_OTP");
|
||||
}
|
||||
return factors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the pool offers SMS MFA: SetUserPoolMfaConfig set an SmsMfaConfiguration, or the pool has the
|
||||
* SmsConfiguration that CreateUserPool requires alongside MfaConfiguration ON or OPTIONAL. AWS makes SMS
|
||||
* an MFA factor for any pool with an SMS configuration.
|
||||
*/
|
||||
private static boolean smsMfaOffered(UserPool pool) {
|
||||
return pool.getSmsMfaConfiguration() != null
|
||||
|| (pool.getSmsConfiguration() != null && !pool.getSmsConfiguration().isEmpty());
|
||||
}
|
||||
|
||||
private Map<String, Object> startMfaChallenge(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
String factor, String triggerSource,
|
||||
Map<String, String> metadata) {
|
||||
if ("SOFTWARE_TOKEN_MFA".equals(factor)) {
|
||||
return totpChallenge(pool, client, user, TotpPhase.CODE_REQUIRED, triggerSource, metadata);
|
||||
}
|
||||
boolean sms = "SMS_MFA".equals(factor);
|
||||
Map<String, Object> customMessage = fireCustomMessage(pool, client, user, "CustomMessage_Authentication");
|
||||
Map<String, String> parameters = new HashMap<>(service.issueMfaCode(pool, user,
|
||||
sms ? VerificationCode.Purpose.SMS_MFA : VerificationCode.Purpose.EMAIL_MFA,
|
||||
sms ? "phone_number" : "email", sms ? "SMS" : "EMAIL", customMessage));
|
||||
parameters.put("USERNAME", user.getUsername());
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("ChallengeName", factor);
|
||||
result.put("Session", issueMfaSession(pool, client, user, factor, List.of(), triggerSource, metadata));
|
||||
result.put("ChallengeParameters", parameters);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, Object> selectMfaTypeChallenge(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
List<String> factors, String triggerSource,
|
||||
Map<String, String> metadata) {
|
||||
Map<String, String> parameters = new HashMap<>();
|
||||
parameters.put("USERNAME", user.getUsername());
|
||||
try {
|
||||
parameters.put("MFAS_CAN_CHOOSE", MAPPER.writeValueAsString(factors));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("InternalErrorException", "Failed to list the MFA choices", 500);
|
||||
}
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("ChallengeName", "SELECT_MFA_TYPE");
|
||||
result.put("Session", issueMfaSession(pool, client, user, "SELECT_MFA_TYPE", factors, triggerSource,
|
||||
metadata));
|
||||
result.put("ChallengeParameters", parameters);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, Object> totpChallenge(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
TotpPhase phase, String triggerSource, Map<String, String> metadata) {
|
||||
String challengeName = phase == TotpPhase.SETUP ? "MFA_SETUP" : "SOFTWARE_TOKEN_MFA";
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("ChallengeName", challengeName);
|
||||
result.put("Session", issueTotpSession(pool.getId(), user.getUsername(), client.getClientId(),
|
||||
phase, clientMetadata == null ? Map.of() : Map.copyOf(clientMetadata), triggerSource,
|
||||
sessionExpiry(client, clock.instant()), user.getSoftwareTokenMfaSecret()));
|
||||
phase, metadata, triggerSource, sessionExpiry(client, clock.instant()),
|
||||
user.getSoftwareTokenMfaSecret()));
|
||||
Map<String, String> parameters = new HashMap<>();
|
||||
parameters.put("USERNAME", user.getUsername());
|
||||
if (phase == TotpPhase.SETUP) {
|
||||
@@ -2072,6 +2178,89 @@ final class CognitoAuthFlowHandler {
|
||||
return result;
|
||||
}
|
||||
|
||||
private String issueMfaSession(UserPool pool, UserPoolClient client, CognitoUser user, String challengeName,
|
||||
List<String> choices, String triggerSource, Map<String, String> metadata) {
|
||||
purgeExpired(mfaSessions, MfaSession::expiresAt);
|
||||
String token = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId());
|
||||
mfaSessions.put(token, new MfaSession(pool.getId(), user.getUsername(), client.getClientId(), challengeName,
|
||||
List.copyOf(choices), metadata, triggerSource, sessionExpiry(client, clock.instant())));
|
||||
return token;
|
||||
}
|
||||
|
||||
private MfaSession requireMfaSession(UserPool pool, UserPoolClient client, String session,
|
||||
String challengeName, Map<String, String> responses) {
|
||||
MfaSession state = session == null ? null : mfaSessions.get(session);
|
||||
if (state == null || !challengeName.equals(state.challengeName())) {
|
||||
throw new AwsException("NotAuthorizedException", "Session not found", 400);
|
||||
}
|
||||
if (sessionExpired(state.expiresAt())) {
|
||||
mfaSessions.remove(session, state);
|
||||
throw sessionExpiredException();
|
||||
}
|
||||
if (!pool.getId().equals(state.userPoolId()) || !client.getClientId().equals(state.clientId())) {
|
||||
throw new AwsException("NotAuthorizedException", "Session does not match client", 400);
|
||||
}
|
||||
String username = responses.get("USERNAME");
|
||||
if (username == null || !username.equals(state.username())) {
|
||||
throw new AwsException("NotAuthorizedException", "Session does not match user", 400);
|
||||
}
|
||||
validateSecretHash(client, responses, username);
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers an SMS_MFA or email (EMAIL_OTP) MFA challenge with the code sent for it. A wrong code
|
||||
* leaves the session for another try, until the code itself stops working. The phone number or
|
||||
* email address the code went to counts as verified afterwards, as on AWS.
|
||||
*/
|
||||
private Map<String, Object> handleMessageMfaChallenge(UserPool pool, UserPoolClient client, String challengeName,
|
||||
String session, Map<String, String> responses,
|
||||
Map<String, String> clientMetadata) {
|
||||
MfaSession state = requireMfaSession(pool, client, session, challengeName, responses);
|
||||
boolean sms = "SMS_MFA".equals(challengeName);
|
||||
String code = sms ? responses.get("SMS_MFA_CODE")
|
||||
: responses.getOrDefault("EMAIL_OTP_CODE", responses.get("EMAIL_MFA_CODE"));
|
||||
if (code == null) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"USERNAME and " + (sms ? "SMS_MFA_CODE" : "EMAIL_OTP_CODE") + " are required", 400);
|
||||
}
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), state.username());
|
||||
requireSignInEligible(user);
|
||||
service.consumeSignInOtp(pool.getId(), user.getUsername(),
|
||||
sms ? VerificationCode.Purpose.SMS_MFA : VerificationCode.Purpose.EMAIL_MFA, code);
|
||||
if (!mfaSessions.remove(session, state)) {
|
||||
throw new AwsException("NotAuthorizedException", "Session not found", 400);
|
||||
}
|
||||
service.markAttributeVerified(pool.getId(), user.getUsername(), sms ? "phone_number" : "email");
|
||||
user = service.adminGetUser(pool.getId(), user.getUsername());
|
||||
Map<String, String> metadata = clientMetadata != null && !clientMetadata.isEmpty()
|
||||
? clientMetadata : state.clientMetadata();
|
||||
return authenticationResult(pool, client, user, state.triggerSource(), metadata);
|
||||
}
|
||||
|
||||
/** Answers SELECT_MFA_TYPE: {@code ANSWER} names one of {@code MFAS_CAN_CHOOSE}, whose challenge follows. */
|
||||
private Map<String, Object> handleSelectMfaType(UserPool pool, UserPoolClient client, String session,
|
||||
Map<String, String> responses,
|
||||
Map<String, String> clientMetadata) {
|
||||
MfaSession state = requireMfaSession(pool, client, session, "SELECT_MFA_TYPE", responses);
|
||||
String answer = responses.get("ANSWER");
|
||||
if ("EMAIL_MFA".equals(answer)) {
|
||||
answer = "EMAIL_OTP";
|
||||
}
|
||||
if (answer == null || !state.choices().contains(answer)) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"ANSWER must be one of " + state.choices(), 400);
|
||||
}
|
||||
if (!mfaSessions.remove(session, state)) {
|
||||
throw new AwsException("NotAuthorizedException", "Session not found", 400);
|
||||
}
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), state.username());
|
||||
requireSignInEligible(user);
|
||||
Map<String, String> metadata = clientMetadata != null && !clientMetadata.isEmpty()
|
||||
? Map.copyOf(clientMetadata) : state.clientMetadata();
|
||||
return startMfaChallenge(pool, client, user, answer, state.triggerSource(), metadata);
|
||||
}
|
||||
|
||||
private Map<String, Object> authenticationResult(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
String triggerSource, Map<String, String> clientMetadata) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
@@ -230,17 +230,22 @@ public class CognitoJsonHandler {
|
||||
|
||||
private Response handleSetUserPoolMfaConfig(JsonNode request) {
|
||||
JsonNode softwareToken = request.path("SoftwareTokenMfaConfiguration");
|
||||
boolean otherFactorConfigured = request.hasNonNull("EmailMfaConfiguration")
|
||||
|| request.hasNonNull("SmsMfaConfiguration");
|
||||
UserPool pool = service.setUserPoolMfaConfig(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.hasNonNull("MfaConfiguration") ? request.path("MfaConfiguration").asText() : null,
|
||||
softwareToken.hasNonNull("Enabled") ? softwareToken.path("Enabled").asBoolean() : null,
|
||||
otherFactorConfigured,
|
||||
objectMember(request, "SmsMfaConfiguration"),
|
||||
objectMember(request, "EmailMfaConfiguration"),
|
||||
webAuthnConfiguration(request.path("WebAuthnConfiguration")));
|
||||
return Response.ok(buildMfaConfigResponse(pool)).build();
|
||||
}
|
||||
|
||||
private Map<String, Object> objectMember(JsonNode request, String name) {
|
||||
return request.hasNonNull(name)
|
||||
? objectMapper.convertValue(request.path(name), new TypeReference<Map<String, Object>>() {})
|
||||
: null;
|
||||
}
|
||||
|
||||
private static WebAuthnConfiguration webAuthnConfiguration(JsonNode node) {
|
||||
if (!node.isObject()) {
|
||||
return null;
|
||||
@@ -267,6 +272,12 @@ public class CognitoJsonHandler {
|
||||
.put("Enabled", pool.getSoftwareTokenMfaEnabled());
|
||||
}
|
||||
response.put("MfaConfiguration", pool.getMfaConfiguration());
|
||||
if (pool.getSmsMfaConfiguration() != null) {
|
||||
response.set("SmsMfaConfiguration", objectMapper.valueToTree(pool.getSmsMfaConfiguration()));
|
||||
}
|
||||
if (pool.getEmailMfaConfiguration() != null) {
|
||||
response.set("EmailMfaConfiguration", objectMapper.valueToTree(pool.getEmailMfaConfiguration()));
|
||||
}
|
||||
WebAuthnConfiguration webAuthn = pool.getWebAuthnConfiguration();
|
||||
if (webAuthn != null) {
|
||||
ObjectNode node = response.putObject("WebAuthnConfiguration");
|
||||
@@ -1564,6 +1575,7 @@ public class CognitoJsonHandler {
|
||||
service.adminSetUserMFAPreference(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("Username").asText(),
|
||||
mfaSettingsUpdate(request.path("SMSMfaSettings")),
|
||||
mfaSettingsUpdate(request.path("EmailMfaSettings")),
|
||||
mfaSettingsUpdate(request.path("SoftwareTokenMfaSettings")),
|
||||
webAuthnMfaEnabled(request));
|
||||
@@ -1573,6 +1585,7 @@ public class CognitoJsonHandler {
|
||||
private Response handleSetUserMFAPreference(JsonNode request) {
|
||||
service.setUserMFAPreference(
|
||||
request.path("AccessToken").asText(),
|
||||
mfaSettingsUpdate(request.path("SMSMfaSettings")),
|
||||
mfaSettingsUpdate(request.path("EmailMfaSettings")),
|
||||
mfaSettingsUpdate(request.path("SoftwareTokenMfaSettings")),
|
||||
webAuthnMfaEnabled(request));
|
||||
|
||||
@@ -37,6 +37,7 @@ import io.github.hectorvent.floci.services.cognito.model.ManagedLoginBranding;
|
||||
import io.github.hectorvent.floci.services.cognito.model.ResourceServer;
|
||||
import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;
|
||||
import io.github.hectorvent.floci.services.cognito.model.RevokedTokenInfo;
|
||||
import io.github.hectorvent.floci.services.cognito.model.SmsMfaSettings;
|
||||
import io.github.hectorvent.floci.services.cognito.model.SoftwareTokenMfaSettings;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
@@ -759,25 +760,40 @@ public class CognitoService implements ResourceProvider {
|
||||
}
|
||||
|
||||
/**
|
||||
* SetUserPoolMfaConfig. Stores the MFA mode, the software-token setting and the passkey
|
||||
* ({@code WebAuthnConfiguration}) settings, which is what GetUserPoolMfaConfig reports back
|
||||
* and what the Terraform provider reads to detect drift on mfa_configuration /
|
||||
* software_token_mfa_configuration / web_authn_configuration.
|
||||
*
|
||||
* <p>SMS and email MFA are accepted and not stored: Floci has no path to deliver an SMS or
|
||||
* email factor, so retaining the config would claim a capability that does not exist.
|
||||
*
|
||||
* @param otherFactorConfigured whether EmailMfaConfiguration or SmsMfaConfiguration was
|
||||
* present in the request. Both count towards the factor rules below even though
|
||||
* Floci does not deliver either challenge; WebAuthnConfiguration does not, measured
|
||||
* against the live service, which accepts it alongside OFF and does not accept it
|
||||
* as the sole factor for ON or OPTIONAL.
|
||||
* @param otherFactorConfigured whether to configure SMS MFA with an empty SmsMfaConfiguration
|
||||
* @param webAuthnConfiguration the request's WebAuthnConfiguration, or null to keep the stored one
|
||||
*/
|
||||
public UserPool setUserPoolMfaConfig(String id, String mfaConfiguration,
|
||||
Boolean softwareTokenMfaEnabled,
|
||||
boolean otherFactorConfigured,
|
||||
WebAuthnConfiguration webAuthnConfiguration) {
|
||||
return setUserPoolMfaConfig(id, mfaConfiguration, softwareTokenMfaEnabled,
|
||||
otherFactorConfigured ? Map.of() : null, null, webAuthnConfiguration);
|
||||
}
|
||||
|
||||
/**
|
||||
* SetUserPoolMfaConfig. Stores the MFA mode, the software-token setting, the SMS and email MFA
|
||||
* configurations and the passkey ({@code WebAuthnConfiguration}) settings, which is what
|
||||
* GetUserPoolMfaConfig reports back and what the Terraform provider reads to detect drift on
|
||||
* mfa_configuration / software_token_mfa_configuration / web_authn_configuration.
|
||||
*
|
||||
* <p>SMS and email MFA configurations turn those factors on for the pool: Floci delivers their
|
||||
* codes through SNS and SES.
|
||||
*
|
||||
* @param smsMfaConfiguration the request's SmsMfaConfiguration, or null when absent; its
|
||||
* SmsAuthenticationMessage and SmsConfiguration also become the pool's, as on AWS
|
||||
* @param emailMfaConfiguration the request's EmailMfaConfiguration, or null when absent
|
||||
* @param webAuthnConfiguration the request's WebAuthnConfiguration, or null to keep the stored one.
|
||||
* Unlike the SMS and email configurations it does not count towards the factor rules below,
|
||||
* measured against the live service, which accepts it alongside OFF and does not accept it
|
||||
* as the sole factor for ON or OPTIONAL.
|
||||
*/
|
||||
public UserPool setUserPoolMfaConfig(String id, String mfaConfiguration,
|
||||
Boolean softwareTokenMfaEnabled,
|
||||
Map<String, Object> smsMfaConfiguration,
|
||||
Map<String, Object> emailMfaConfiguration,
|
||||
WebAuthnConfiguration webAuthnConfiguration) {
|
||||
boolean otherFactorConfigured = smsMfaConfiguration != null || emailMfaConfiguration != null;
|
||||
UserPool pool = describeUserPool(id);
|
||||
if (webAuthnConfiguration != null) {
|
||||
validateWebAuthnConfiguration(webAuthnConfiguration);
|
||||
@@ -812,8 +828,26 @@ public class CognitoService implements ResourceProvider {
|
||||
// Turning MFA off drops the factor configuration with it: the live service
|
||||
// answers OFF alone afterwards, with no SoftwareTokenMfaConfiguration member.
|
||||
pool.setSoftwareTokenMfaEnabled(null);
|
||||
} else if (softwareTokenMfaEnabled != null) {
|
||||
pool.setSoftwareTokenMfaEnabled(softwareTokenMfaEnabled);
|
||||
pool.setSmsMfaConfiguration(null);
|
||||
pool.setEmailMfaConfiguration(null);
|
||||
} else {
|
||||
if (softwareTokenMfaEnabled != null) {
|
||||
pool.setSoftwareTokenMfaEnabled(softwareTokenMfaEnabled);
|
||||
}
|
||||
if (smsMfaConfiguration != null) {
|
||||
pool.setSmsMfaConfiguration(new LinkedHashMap<>(smsMfaConfiguration));
|
||||
if (smsMfaConfiguration.get("SmsAuthenticationMessage") instanceof String message) {
|
||||
pool.setSmsAuthenticationMessage(message);
|
||||
}
|
||||
if (smsMfaConfiguration.get("SmsConfiguration") instanceof Map<?, ?> smsConfiguration) {
|
||||
Map<String, Object> copy = new LinkedHashMap<>();
|
||||
smsConfiguration.forEach((key, value) -> copy.put(String.valueOf(key), value));
|
||||
pool.setSmsConfiguration(copy);
|
||||
}
|
||||
}
|
||||
if (emailMfaConfiguration != null) {
|
||||
pool.setEmailMfaConfiguration(new LinkedHashMap<>(emailMfaConfiguration));
|
||||
}
|
||||
}
|
||||
if (webAuthnConfiguration != null) {
|
||||
pool.setWebAuthnConfiguration(webAuthnConfiguration);
|
||||
@@ -6135,8 +6169,8 @@ public class CognitoService implements ResourceProvider {
|
||||
return value;
|
||||
}
|
||||
/**
|
||||
* One factor's settings from an MFA preference request ({@code EmailMfaSettings},
|
||||
* {@code SoftwareTokenMfaSettings}). A null member leaves the stored value alone.
|
||||
* One factor's settings from an MFA preference request ({@code SMSMfaSettings},
|
||||
* {@code EmailMfaSettings}, {@code SoftwareTokenMfaSettings}). A null member leaves the stored value alone.
|
||||
*/
|
||||
public record MfaSettingsUpdate(Boolean enabled, Boolean preferredMfa) {
|
||||
public static final MfaSettingsUpdate NONE = new MfaSettingsUpdate(null, null);
|
||||
@@ -6154,9 +6188,17 @@ public class CognitoService implements ResourceProvider {
|
||||
/** @param webAuthnMfaEnabled {@code WebAuthnMfaSettings.Enabled}, or null to leave passkey MFA as it is */
|
||||
public void adminSetUserMFAPreference(String userPoolId, String username, MfaSettingsUpdate email,
|
||||
MfaSettingsUpdate softwareToken, Boolean webAuthnMfaEnabled) {
|
||||
adminSetUserMFAPreference(userPoolId, username, MfaSettingsUpdate.NONE, email, softwareToken,
|
||||
webAuthnMfaEnabled);
|
||||
}
|
||||
|
||||
/** @param webAuthnMfaEnabled {@code WebAuthnMfaSettings.Enabled}, or null to leave passkey MFA as it is */
|
||||
public void adminSetUserMFAPreference(String userPoolId, String username, MfaSettingsUpdate sms,
|
||||
MfaSettingsUpdate email, MfaSettingsUpdate softwareToken,
|
||||
Boolean webAuthnMfaEnabled) {
|
||||
CognitoUser resolvedUser = adminGetUser(userPoolId, username);
|
||||
synchronized (userLock(userPoolId, resolvedUser.getUsername())) {
|
||||
updateMfaPreferenceUnderUserLock(userPoolId, resolvedUser.getUsername(), email, softwareToken,
|
||||
updateMfaPreferenceUnderUserLock(userPoolId, resolvedUser.getUsername(), sms, email, softwareToken,
|
||||
webAuthnMfaEnabled);
|
||||
}
|
||||
}
|
||||
@@ -6168,39 +6210,71 @@ public class CognitoService implements ResourceProvider {
|
||||
/** @param webAuthnMfaEnabled {@code WebAuthnMfaSettings.Enabled}, or null to leave passkey MFA as it is */
|
||||
public void setUserMFAPreference(String accessToken, MfaSettingsUpdate email, MfaSettingsUpdate softwareToken,
|
||||
Boolean webAuthnMfaEnabled) {
|
||||
setUserMFAPreference(accessToken, MfaSettingsUpdate.NONE, email, softwareToken, webAuthnMfaEnabled);
|
||||
}
|
||||
|
||||
/** @param webAuthnMfaEnabled {@code WebAuthnMfaSettings.Enabled}, or null to leave passkey MFA as it is */
|
||||
public void setUserMFAPreference(String accessToken, MfaSettingsUpdate sms, MfaSettingsUpdate email,
|
||||
MfaSettingsUpdate softwareToken, Boolean webAuthnMfaEnabled) {
|
||||
VerifiedAccessToken token = verifyAccessToken(accessToken);
|
||||
requireScope(accessToken, USER_ADMIN_SCOPE);
|
||||
synchronized (userLock(token.poolId(), token.username())) {
|
||||
updateMfaPreferenceUnderUserLock(token.poolId(), token.username(), email, softwareToken,
|
||||
updateMfaPreferenceUnderUserLock(token.poolId(), token.username(), sms, email, softwareToken,
|
||||
webAuthnMfaEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateMfaPreferenceUnderUserLock(String poolId, String username, MfaSettingsUpdate email,
|
||||
MfaSettingsUpdate softwareToken, Boolean webAuthnMfaEnabled) {
|
||||
private void updateMfaPreferenceUnderUserLock(String poolId, String username, MfaSettingsUpdate sms,
|
||||
MfaSettingsUpdate email, MfaSettingsUpdate softwareToken,
|
||||
Boolean webAuthnMfaEnabled) {
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
requirePasskeyMfaAvailable(describeUserPool(poolId), webAuthnMfaEnabled);
|
||||
if (Boolean.TRUE.equals(email.preferredMfa()) && Boolean.TRUE.equals(softwareToken.preferredMfa())) {
|
||||
long preferredCount = List.of(sms, email, softwareToken).stream()
|
||||
.filter(update -> Boolean.TRUE.equals(update.preferredMfa())).count();
|
||||
if (preferredCount > 1) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"Only one MFA method can be set as preferred.", 400);
|
||||
}
|
||||
SmsMfaSettings smsSettings = user.getSmsMfaSettings();
|
||||
EmailMfaSettings emailSettings = user.getEmailMfaSettings();
|
||||
SoftwareTokenMfaSettings tokenSettings = user.getSoftwareTokenMfaSettings();
|
||||
FactorState smsState = resolveMfaSettings(sms, smsSettings == null
|
||||
? FactorState.OFF : new FactorState(smsSettings.isEnabled(), smsSettings.isPreferredMfa()));
|
||||
FactorState emailState = resolveMfaSettings(email, emailSettings == null
|
||||
? FactorState.OFF : new FactorState(emailSettings.isEnabled(), emailSettings.isPreferredMfa()));
|
||||
FactorState tokenState = resolveMfaSettings(softwareToken, tokenSettings == null
|
||||
? FactorState.OFF : new FactorState(tokenSettings.isEnabled(), tokenSettings.isPreferredMfa()));
|
||||
// AWS refuses to turn on TOTP MFA for a user who has not verified an authenticator.
|
||||
// AWS refuses to turn on a factor it has nowhere to deliver: an SMS code without a phone number,
|
||||
// an email code without an email address, TOTP without a verified authenticator.
|
||||
if (Boolean.TRUE.equals(sms.enabled()) && user.getAttributes().get("phone_number") == null) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"User does not have delivery config set to turn on SMS_MFA", 400);
|
||||
}
|
||||
if (Boolean.TRUE.equals(email.enabled()) && user.getAttributes().get("email") == null) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"User does not have delivery config set to turn on EMAIL_OTP", 400);
|
||||
}
|
||||
if (Boolean.TRUE.equals(softwareToken.enabled()) && user.getSoftwareTokenMfaSecret() == null) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"User does not have delivery config set to turn on SOFTWARE_TOKEN_MFA", 400);
|
||||
}
|
||||
// Only one factor is preferred, so preferring one drops the preference of the others.
|
||||
if (Boolean.TRUE.equals(email.preferredMfa())) {
|
||||
if (Boolean.TRUE.equals(sms.preferredMfa())) {
|
||||
emailState = new FactorState(emailState.enabled(), false);
|
||||
tokenState = new FactorState(tokenState.enabled(), false);
|
||||
} else if (Boolean.TRUE.equals(email.preferredMfa())) {
|
||||
smsState = new FactorState(smsState.enabled(), false);
|
||||
tokenState = new FactorState(tokenState.enabled(), false);
|
||||
} else if (Boolean.TRUE.equals(softwareToken.preferredMfa())) {
|
||||
smsState = new FactorState(smsState.enabled(), false);
|
||||
emailState = new FactorState(emailState.enabled(), false);
|
||||
}
|
||||
if (!sms.isEmpty() || smsSettings != null) {
|
||||
SmsMfaSettings settings = smsSettings != null ? smsSettings : new SmsMfaSettings();
|
||||
settings.setEnabled(smsState.enabled());
|
||||
settings.setPreferredMfa(smsState.preferred());
|
||||
user.setSmsMfaSettings(settings);
|
||||
}
|
||||
if (!email.isEmpty() || emailSettings != null) {
|
||||
EmailMfaSettings settings = emailSettings != null ? emailSettings : new EmailMfaSettings();
|
||||
settings.setEnabled(emailState.enabled());
|
||||
@@ -6260,6 +6334,41 @@ public class CognitoService implements ResourceProvider {
|
||||
return new FactorState(enabled, enabled && preferred);
|
||||
}
|
||||
|
||||
/**
|
||||
* The message factor's code for a challenge after a password: a new code, or while one sent
|
||||
* moments ago is still live, that one, since each sign-in asks for a code and the code store
|
||||
* paces new ones. Returns the CODE_DELIVERY challenge parameters.
|
||||
*/
|
||||
Map<String, String> issueMfaCode(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
|
||||
String attributeName, String deliveryMedium,
|
||||
Map<String, Object> customMessageResponse) {
|
||||
try {
|
||||
return issueSignInOtp(pool, user, purpose, attributeName, deliveryMedium, customMessageResponse);
|
||||
} catch (AwsException e) {
|
||||
if (!"LimitExceededException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
String destination = user.getAttributes().get(attributeName);
|
||||
Map<String, String> details = new LinkedHashMap<>();
|
||||
details.put("CODE_DELIVERY_DELIVERY_MEDIUM", deliveryMedium);
|
||||
details.put("CODE_DELIVERY_DESTINATION",
|
||||
"email".equals(attributeName) ? maskEmail(destination) : maskPhoneNumber(destination));
|
||||
return details;
|
||||
}
|
||||
}
|
||||
|
||||
/** After an SMS or email MFA code, AWS marks the attribute it went to as verified. */
|
||||
void markAttributeVerified(String poolId, String username, String attributeName) {
|
||||
synchronized (userLock(poolId, username)) {
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
if (!"true".equals(user.getAttributes().get(attributeName + "_verified"))) {
|
||||
user.getAttributes().put(attributeName + "_verified", "true");
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(poolId, user.getUsername()), user);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the user's newly registered authenticator as their MFA factor, which completing the
|
||||
* {@code MFA_SETUP} challenge does on AWS. It becomes the preferred factor when no other is.
|
||||
@@ -6286,6 +6395,9 @@ public class CognitoService implements ResourceProvider {
|
||||
*/
|
||||
static List<String> userMfaSettingList(UserPool pool, CognitoUser user) {
|
||||
List<String> factors = new ArrayList<>();
|
||||
if (user.getSmsMfaSettings() != null && user.getSmsMfaSettings().isEnabled()) {
|
||||
factors.add("SMS_MFA");
|
||||
}
|
||||
if (user.getEmailMfaSettings() != null && user.getEmailMfaSettings().isEnabled()) {
|
||||
factors.add("EMAIL_OTP");
|
||||
}
|
||||
@@ -6297,6 +6409,10 @@ public class CognitoService implements ResourceProvider {
|
||||
|
||||
/** {@code PreferredMfaSetting}: the user's preferred MFA factor, or null when none is. */
|
||||
static @Nullable String preferredMfaSetting(UserPool pool, CognitoUser user) {
|
||||
SmsMfaSettings sms = user.getSmsMfaSettings();
|
||||
if (sms != null && sms.isEnabled() && sms.isPreferredMfa()) {
|
||||
return "SMS_MFA";
|
||||
}
|
||||
EmailMfaSettings email = user.getEmailMfaSettings();
|
||||
if (email != null && email.isEnabled() && email.isPreferredMfa()) {
|
||||
return "EMAIL_OTP";
|
||||
@@ -6319,7 +6435,7 @@ public class CognitoService implements ResourceProvider {
|
||||
* software-token MFA asks for a registered authenticator at every sign-in, whether or not it was
|
||||
* turned on, and AWS lets users there choose only which factor is preferred.
|
||||
*/
|
||||
private static boolean softwareTokenMfaActive(UserPool pool, CognitoUser user) {
|
||||
static boolean softwareTokenMfaActive(UserPool pool, CognitoUser user) {
|
||||
return softwareTokenMfaEnabled(user)
|
||||
|| (user.getSoftwareTokenMfaSecret() != null && "ON".equals(pool.getMfaConfiguration())
|
||||
&& Boolean.TRUE.equals(pool.getSoftwareTokenMfaEnabled()));
|
||||
|
||||
@@ -27,6 +27,7 @@ public class CognitoUser {
|
||||
private String srpVerifier;
|
||||
private EmailMfaSettings emailMfaSettings;
|
||||
private SoftwareTokenMfaSettings softwareTokenMfaSettings;
|
||||
private SmsMfaSettings smsMfaSettings;
|
||||
private String softwareTokenMfaSecret;
|
||||
private String pendingSoftwareTokenMfaSecret;
|
||||
private Integer pendingSoftwareTokenMfaAttemptsRemaining;
|
||||
@@ -98,6 +99,9 @@ public class CognitoUser {
|
||||
this.emailMfaSettings = emailMfaSettings;
|
||||
}
|
||||
|
||||
public SmsMfaSettings getSmsMfaSettings() { return smsMfaSettings; }
|
||||
public void setSmsMfaSettings(SmsMfaSettings smsMfaSettings) { this.smsMfaSettings = smsMfaSettings; }
|
||||
|
||||
public SoftwareTokenMfaSettings getSoftwareTokenMfaSettings() { return softwareTokenMfaSettings; }
|
||||
public void setSoftwareTokenMfaSettings(SoftwareTokenMfaSettings settings) {
|
||||
this.softwareTokenMfaSettings = settings;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package io.github.hectorvent.floci.services.cognito.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SmsMfaSettings {
|
||||
|
||||
private boolean enabled;
|
||||
private boolean preferredMfa;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public boolean isPreferredMfa() {
|
||||
return preferredMfa;
|
||||
}
|
||||
|
||||
public void setPreferredMfa(boolean preferredMfa) {
|
||||
this.preferredMfa = preferredMfa;
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,8 @@ public class UserPool {
|
||||
/** Null until SetUserPoolMfaConfig sets it; absent from responses while null, as AWS omits it. */
|
||||
private Boolean softwareTokenMfaEnabled;
|
||||
private WebAuthnConfiguration webAuthnConfiguration;
|
||||
private Map<String, Object> smsMfaConfiguration;
|
||||
private Map<String, Object> emailMfaConfiguration;
|
||||
private Map<String, Object> deviceConfiguration = new HashMap<>();
|
||||
private int estimatedNumberOfUsers = 0;
|
||||
private Map<String, Object> emailConfiguration = new HashMap<>();
|
||||
@@ -141,6 +143,18 @@ public class UserPool {
|
||||
this.webAuthnConfiguration = webAuthnConfiguration;
|
||||
}
|
||||
|
||||
/** SetUserPoolMfaConfig's SmsMfaConfiguration; null while SMS MFA is not configured. */
|
||||
public Map<String, Object> getSmsMfaConfiguration() { return smsMfaConfiguration; }
|
||||
public void setSmsMfaConfiguration(Map<String, Object> smsMfaConfiguration) {
|
||||
this.smsMfaConfiguration = smsMfaConfiguration;
|
||||
}
|
||||
|
||||
/** SetUserPoolMfaConfig's EmailMfaConfiguration; null while email MFA is not configured. */
|
||||
public Map<String, Object> getEmailMfaConfiguration() { return emailMfaConfiguration; }
|
||||
public void setEmailMfaConfiguration(Map<String, Object> emailMfaConfiguration) {
|
||||
this.emailMfaConfiguration = emailMfaConfiguration;
|
||||
}
|
||||
|
||||
public Map<String, Object> getDeviceConfiguration() { return deviceConfiguration; }
|
||||
public void setDeviceConfiguration(Map<String, Object> deviceConfiguration) { this.deviceConfiguration = deviceConfiguration; }
|
||||
|
||||
|
||||
+24
-2
@@ -14,6 +14,7 @@ import org.apache.james.mime4j.field.address.ParseException;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
@@ -94,10 +95,15 @@ public final class CognitoMessageDispatcher {
|
||||
|
||||
for (String medium : mediums) {
|
||||
if ("EMAIL".equalsIgnoreCase(medium) && email != null) {
|
||||
// The pool's EmailMfaConfiguration is the template for email MFA codes and, once set, for
|
||||
// USER_AUTH's email sign-in codes too, as SmsAuthenticationMessage is for both SMS ones.
|
||||
Map<String, Object> emailTemplate = purpose == VerificationCode.Purpose.EMAIL_MFA
|
||||
|| (purpose == VerificationCode.Purpose.EMAIL_OTP && pool.getEmailMfaConfiguration() != null)
|
||||
? emailMfaTemplate(pool) : template;
|
||||
String subject = stringOrNull(customMessageResponse, "emailSubject");
|
||||
if (subject == null) subject = stringOr(template.get("EmailSubject"), DEFAULT_EMAIL_SUBJECT);
|
||||
if (subject == null) subject = stringOr(emailTemplate.get("EmailSubject"), DEFAULT_EMAIL_SUBJECT);
|
||||
String rawBody = stringOrNull(customMessageResponse, "emailMessage");
|
||||
if (rawBody == null) rawBody = stringOr(template.get(emailTemplateKey()), DEFAULT_EMAIL_BODY);
|
||||
if (rawBody == null) rawBody = stringOr(emailTemplate.get(emailTemplateKey()), DEFAULT_EMAIL_BODY);
|
||||
sendEmail(pool, region, email, subject, renderTemplate(rawBody, code));
|
||||
} else if ("SMS".equalsIgnoreCase(medium) && phone != null) {
|
||||
String rawBody = stringOrNull(customMessageResponse, "smsMessage");
|
||||
@@ -342,6 +348,22 @@ public final class CognitoMessageDispatcher {
|
||||
private record Sender(String from, String address) {
|
||||
}
|
||||
|
||||
/** The pool's EmailMfaConfiguration as an email template ({@code Subject}, {@code Message}). */
|
||||
private static Map<String, Object> emailMfaTemplate(UserPool pool) {
|
||||
Map<String, Object> configuration = pool.getEmailMfaConfiguration();
|
||||
if (configuration == null) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, Object> template = new HashMap<>();
|
||||
if (configuration.get("Subject") != null) {
|
||||
template.put("EmailSubject", configuration.get("Subject"));
|
||||
}
|
||||
if (configuration.get("Message") != null) {
|
||||
template.put("EmailMessage", configuration.get("Message"));
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
/**
|
||||
* Email template key. Returns the code-based {@code EmailMessage} ({@code {####}}).
|
||||
* TODO: honor the pool's {@code DefaultEmailOption}: when set to {@code CONFIRM_WITH_LINK},
|
||||
|
||||
+3
-1
@@ -26,7 +26,9 @@ public final class VerificationCode {
|
||||
// USER_AUTH choice-based sign-in codes (distinct from SMS_MFA/attribute verification
|
||||
// so a sign-in code can't be replayed against those other purposes' consume() calls).
|
||||
EMAIL_OTP,
|
||||
SMS_OTP
|
||||
SMS_OTP,
|
||||
// An email MFA code after a password, the email twin of SMS_MFA.
|
||||
EMAIL_MFA
|
||||
}
|
||||
|
||||
private final String userPoolId;
|
||||
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** SMS and email message MFA after a password, over the JSON 1.1 wire protocol. */
|
||||
@QuarkusTest
|
||||
class CognitoMessageMfaIntegrationTest {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b");
|
||||
private static final String PASSWORD = "Perm1234!";
|
||||
private static final String SMS_CONFIG = """
|
||||
"SmsMfaConfiguration":{"SmsAuthenticationMessage":"Your MFA code is {####}"}""";
|
||||
private static final String EMAIL_CONFIG = """
|
||||
"EmailMfaConfiguration":{"Message":"Your MFA code is {####}","Subject":"Your MFA code"}""";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void optionalSmsMfaChallengesOnceTurnedOnAndVerifiesThePhone() throws Exception {
|
||||
String poolId = createPool("OPTIONAL", SMS_CONFIG);
|
||||
String clientId = createClient(poolId);
|
||||
User user = createUser(poolId);
|
||||
String accessToken = passwordLogin(clientId, user).path("AuthenticationResult").path("AccessToken").asText();
|
||||
assertFalse(accessToken.isEmpty(), "MFA is optional and not turned on yet");
|
||||
|
||||
cognitoAction("SetUserMFAPreference", """
|
||||
{"AccessToken":"%s","SMSMfaSettings":{"Enabled":true}}
|
||||
""".formatted(accessToken)).then().statusCode(200);
|
||||
cognitoAction("GetUser", """
|
||||
{"AccessToken":"%s"}
|
||||
""".formatted(accessToken))
|
||||
.then().statusCode(200)
|
||||
.body("UserMFASettingList", contains("SMS_MFA"))
|
||||
.body("$", not(hasKey("PreferredMfaSetting")));
|
||||
|
||||
JsonNode challenge = passwordLogin(clientId, user);
|
||||
assertEquals("SMS_MFA", challenge.path("ChallengeName").asText());
|
||||
assertEquals("SMS", challenge.path("ChallengeParameters").path("CODE_DELIVERY_DELIVERY_MEDIUM").asText());
|
||||
assertTrue(challenge.path("ChallengeParameters").path("CODE_DELIVERY_DESTINATION").asText().startsWith("+"));
|
||||
String sms = latestSms(user.phone());
|
||||
assertTrue(sms.startsWith("Your MFA code is "), sms);
|
||||
String code = sixDigitCode(sms);
|
||||
|
||||
String wrongCode = code.equals("000000") ? "000001" : "000000";
|
||||
cognitoAction("RespondToAuthChallenge", respond(clientId, "SMS_MFA", challenge, user,
|
||||
"SMS_MFA_CODE", wrongCode))
|
||||
.then().statusCode(400).body("__type", equalTo("CodeMismatchException"));
|
||||
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond(clientId, "SMS_MFA", challenge, user,
|
||||
"SMS_MFA_CODE", code));
|
||||
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
|
||||
|
||||
JsonNode adminUser = cognitoJson("AdminGetUser", """
|
||||
{"UserPoolId":"%s","Username":"%s"}
|
||||
""".formatted(poolId, user.username()));
|
||||
boolean phoneVerified = false;
|
||||
for (JsonNode attribute : adminUser.path("UserAttributes")) {
|
||||
if ("phone_number_verified".equals(attribute.path("Name").asText())) {
|
||||
phoneVerified = "true".equals(attribute.path("Value").asText());
|
||||
}
|
||||
}
|
||||
assertTrue(phoneVerified, "a completed SMS MFA challenge verifies the phone number");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailMfaUsesThePoolsEmailMfaMessage() throws Exception {
|
||||
String poolId = createPool("OPTIONAL", EMAIL_CONFIG);
|
||||
String clientId = createClient(poolId);
|
||||
User user = createUser(poolId);
|
||||
cognitoAction("AdminSetUserMFAPreference", """
|
||||
{"UserPoolId":"%s","Username":"%s","EmailMfaSettings":{"Enabled":true,"PreferredMfa":true}}
|
||||
""".formatted(poolId, user.username())).then().statusCode(200);
|
||||
|
||||
JsonNode challenge = cognitoJson("AdminInitiateAuth", """
|
||||
{"UserPoolId":"%s","ClientId":"%s","AuthFlow":"ADMIN_USER_PASSWORD_AUTH",
|
||||
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
|
||||
""".formatted(poolId, clientId, user.username(), PASSWORD));
|
||||
assertEquals("EMAIL_OTP", challenge.path("ChallengeName").asText());
|
||||
assertEquals("EMAIL", challenge.path("ChallengeParameters").path("CODE_DELIVERY_DELIVERY_MEDIUM").asText());
|
||||
JsonNode email = latestEmail(user.email());
|
||||
assertEquals("Your MFA code", email.path("Subject").asText());
|
||||
String code = sixDigitCode(email.path("Body").path("text_part").asText());
|
||||
|
||||
JsonNode signedIn = cognitoJson("AdminRespondToAuthChallenge", """
|
||||
{"UserPoolId":"%s","ClientId":"%s","ChallengeName":"EMAIL_OTP","Session":"%s",
|
||||
"ChallengeResponses":{"USERNAME":"%s","EMAIL_OTP_CODE":"%s"}}
|
||||
""".formatted(poolId, clientId, challenge.path("Session").asText(), user.username(), code));
|
||||
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void severalFactorsWithoutAPreferenceAskToChoose() throws Exception {
|
||||
String poolId = createPool("OPTIONAL", SMS_CONFIG + "," + EMAIL_CONFIG);
|
||||
String clientId = createClient(poolId);
|
||||
User user = createUser(poolId);
|
||||
cognitoAction("AdminSetUserMFAPreference", """
|
||||
{"UserPoolId":"%s","Username":"%s","SMSMfaSettings":{"Enabled":true},
|
||||
"EmailMfaSettings":{"Enabled":true}}
|
||||
""".formatted(poolId, user.username())).then().statusCode(200);
|
||||
|
||||
JsonNode select = passwordLogin(clientId, user);
|
||||
assertEquals("SELECT_MFA_TYPE", select.path("ChallengeName").asText());
|
||||
assertEquals("[\"SMS_MFA\",\"EMAIL_OTP\"]",
|
||||
select.path("ChallengeParameters").path("MFAS_CAN_CHOOSE").asText());
|
||||
cognitoAction("RespondToAuthChallenge", respond(clientId, "SELECT_MFA_TYPE", select, user,
|
||||
"ANSWER", "SOFTWARE_TOKEN_MFA"))
|
||||
.then().statusCode(400).body("__type", equalTo("InvalidParameterException"));
|
||||
JsonNode emailChallenge = cognitoJson("RespondToAuthChallenge", respond(clientId, "SELECT_MFA_TYPE", select,
|
||||
user, "ANSWER", "EMAIL_OTP"));
|
||||
assertEquals("EMAIL_OTP", emailChallenge.path("ChallengeName").asText());
|
||||
String code = sixDigitCode(latestEmail(user.email()).path("Body").path("text_part").asText());
|
||||
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond(clientId, "EMAIL_OTP", emailChallenge,
|
||||
user, "EMAIL_OTP_CODE", code));
|
||||
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
|
||||
|
||||
cognitoAction("AdminSetUserMFAPreference", """
|
||||
{"UserPoolId":"%s","Username":"%s","SMSMfaSettings":{"PreferredMfa":true}}
|
||||
""".formatted(poolId, user.username())).then().statusCode(200);
|
||||
assertEquals("SMS_MFA", passwordLogin(clientId, user).path("ChallengeName").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiredMfaSendsAnSmsCodeToAUserWithAPhoneNumber() throws Exception {
|
||||
String poolId = createPool("ON", SMS_CONFIG);
|
||||
String clientId = createClient(poolId);
|
||||
User user = createUser(poolId);
|
||||
|
||||
JsonNode challenge = passwordLogin(clientId, user);
|
||||
assertEquals("SMS_MFA", challenge.path("ChallengeName").asText());
|
||||
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond(clientId, "SMS_MFA", challenge, user,
|
||||
"SMS_MFA_CODE", sixDigitCode(latestSms(user.phone()))));
|
||||
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserPoolSmsConfigurationOffersSmsMfa() throws Exception {
|
||||
String poolId = cognitoJson("CreateUserPool", """
|
||||
{"PoolName":"CreatePoolSmsMfa","MfaConfiguration":"ON",
|
||||
"SmsAuthenticationMessage":"Sign-in code {####}",
|
||||
"SmsConfiguration":{"SnsCallerArn":"arn:aws:iam::000000000000:role/cognito-sms","ExternalId":"floci"}}
|
||||
""").path("UserPool").path("Id").asText();
|
||||
String clientId = createClient(poolId);
|
||||
User user = createUser(poolId);
|
||||
|
||||
JsonNode challenge = passwordLogin(clientId, user);
|
||||
assertEquals("SMS_MFA", challenge.path("ChallengeName").asText());
|
||||
String sms = latestSms(user.phone());
|
||||
assertTrue(sms.startsWith("Sign-in code "), sms);
|
||||
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond(clientId, "SMS_MFA", challenge, user,
|
||||
"SMS_MFA_CODE", sixDigitCode(sms)));
|
||||
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailMfaConfigurationAlsoCarriesTheEmailSignInCode() throws Exception {
|
||||
String poolId = cognitoJson("CreateUserPool", """
|
||||
{"PoolName":"EmailSignInTemplatePool","UserPoolTier":"ESSENTIALS",
|
||||
"Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":["PASSWORD","EMAIL_OTP"]}}}
|
||||
""").path("UserPool").path("Id").asText();
|
||||
cognitoJson("SetUserPoolMfaConfig", """
|
||||
{"UserPoolId":"%s","MfaConfiguration":"OPTIONAL",%s}
|
||||
""".formatted(poolId, EMAIL_CONFIG));
|
||||
String clientId = createClient(poolId);
|
||||
User user = createUser(poolId);
|
||||
cognitoJson("AdminUpdateUserAttributes", """
|
||||
{"UserPoolId":"%s","Username":"%s","UserAttributes":[{"Name":"email_verified","Value":"true"}]}
|
||||
""".formatted(poolId, user.username()));
|
||||
|
||||
JsonNode challenge = cognitoJson("InitiateAuth", """
|
||||
{"ClientId":"%s","AuthFlow":"USER_AUTH",
|
||||
"AuthParameters":{"USERNAME":"%s","PREFERRED_CHALLENGE":"EMAIL_OTP"}}
|
||||
""".formatted(clientId, user.username()));
|
||||
assertEquals("EMAIL_OTP", challenge.path("ChallengeName").asText());
|
||||
JsonNode email = latestEmail(user.email());
|
||||
assertEquals("Your MFA code", email.path("Subject").asText());
|
||||
String body = email.path("Body").path("text_part").asText();
|
||||
assertTrue(body.startsWith("Your MFA code is "), body);
|
||||
JsonNode signedIn = cognitoJson("RespondToAuthChallenge", respond(clientId, "EMAIL_OTP", challenge, user,
|
||||
"EMAIL_OTP_CODE", sixDigitCode(body)));
|
||||
assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageFactorsNeedADestinationAndLimitChoiceBasedSignIn() throws Exception {
|
||||
String poolId = cognitoJson("CreateUserPool", """
|
||||
{"PoolName":"MessageMfaChoicePool","UserPoolTier":"ESSENTIALS",
|
||||
"Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":["PASSWORD","EMAIL_OTP"]}}}
|
||||
""").path("UserPool").path("Id").asText();
|
||||
cognitoJson("SetUserPoolMfaConfig", """
|
||||
{"UserPoolId":"%s","MfaConfiguration":"OPTIONAL",%s}
|
||||
""".formatted(poolId, SMS_CONFIG));
|
||||
cognitoAction("GetUserPoolMfaConfig", """
|
||||
{"UserPoolId":"%s"}
|
||||
""".formatted(poolId))
|
||||
.then().statusCode(200)
|
||||
.body("SmsMfaConfiguration.SmsAuthenticationMessage", equalTo("Your MFA code is {####}"));
|
||||
String clientId = createClient(poolId);
|
||||
String noPhone = "no-phone-" + UUID.randomUUID();
|
||||
cognitoJson("AdminCreateUser", """
|
||||
{"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS",
|
||||
"UserAttributes":[{"Name":"email","Value":"%s@example.com"}]}
|
||||
""".formatted(poolId, noPhone, noPhone));
|
||||
cognitoAction("AdminSetUserMFAPreference", """
|
||||
{"UserPoolId":"%s","Username":"%s","SMSMfaSettings":{"Enabled":true}}
|
||||
""".formatted(poolId, noPhone))
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterException"))
|
||||
.body("message", equalTo("User does not have delivery config set to turn on SMS_MFA"));
|
||||
|
||||
User user = createUser(poolId);
|
||||
cognitoJson("AdminUpdateUserAttributes", """
|
||||
{"UserPoolId":"%s","Username":"%s","UserAttributes":[{"Name":"email_verified","Value":"true"}]}
|
||||
""".formatted(poolId, user.username()));
|
||||
String userAuth = """
|
||||
{"ClientId":"%s","AuthFlow":"USER_AUTH","AuthParameters":{"USERNAME":"%s"}}
|
||||
""".formatted(clientId, user.username());
|
||||
cognitoAction("InitiateAuth", userAuth)
|
||||
.then().statusCode(200)
|
||||
.body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP", "EMAIL_OTP"));
|
||||
cognitoAction("AdminSetUserMFAPreference", """
|
||||
{"UserPoolId":"%s","Username":"%s","SMSMfaSettings":{"Enabled":true}}
|
||||
""".formatted(poolId, user.username())).then().statusCode(200);
|
||||
cognitoAction("InitiateAuth", userAuth)
|
||||
.then().statusCode(200)
|
||||
.body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP"));
|
||||
|
||||
cognitoJson("SetUserPoolMfaConfig", """
|
||||
{"UserPoolId":"%s","MfaConfiguration":"OFF"}
|
||||
""".formatted(poolId));
|
||||
cognitoAction("GetUserPoolMfaConfig", """
|
||||
{"UserPoolId":"%s"}
|
||||
""".formatted(poolId))
|
||||
.then().statusCode(200)
|
||||
.body("$", not(hasKey("SmsMfaConfiguration")));
|
||||
}
|
||||
|
||||
private record User(String username, String phone, String email) {}
|
||||
|
||||
private static User createUser(String poolId) throws Exception {
|
||||
String username = "mfa-" + UUID.randomUUID();
|
||||
String phone = "+1555" + ThreadLocalRandom.current().nextInt(1_000_000, 9_999_999);
|
||||
String email = username + "@example.com";
|
||||
cognitoJson("AdminCreateUser", """
|
||||
{"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS",
|
||||
"UserAttributes":[{"Name":"phone_number","Value":"%s"},{"Name":"email","Value":"%s"}]}
|
||||
""".formatted(poolId, username, phone, email));
|
||||
cognitoJson("AdminSetUserPassword", """
|
||||
{"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
|
||||
""".formatted(poolId, username, PASSWORD));
|
||||
return new User(username, phone, email);
|
||||
}
|
||||
|
||||
private static String createPool(String mfaConfiguration, String factorConfiguration) throws Exception {
|
||||
String poolId = cognitoJson("CreateUserPool", """
|
||||
{"PoolName":"MessageMfaPool"}
|
||||
""").path("UserPool").path("Id").asText();
|
||||
cognitoJson("SetUserPoolMfaConfig", """
|
||||
{"UserPoolId":"%s","MfaConfiguration":"%s",%s}
|
||||
""".formatted(poolId, mfaConfiguration, factorConfiguration));
|
||||
return poolId;
|
||||
}
|
||||
|
||||
private static String createClient(String poolId) throws Exception {
|
||||
return cognitoJson("CreateUserPoolClient", """
|
||||
{"UserPoolId":"%s","ClientName":"message-mfa-client",
|
||||
"ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_USER_AUTH"]}
|
||||
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
|
||||
}
|
||||
|
||||
private static JsonNode passwordLogin(String clientId, User user) throws Exception {
|
||||
return cognitoJson("InitiateAuth", """
|
||||
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
|
||||
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
|
||||
""".formatted(clientId, user.username(), PASSWORD));
|
||||
}
|
||||
|
||||
private static String respond(String clientId, String challengeName, JsonNode challenge, User user,
|
||||
String key, String value) {
|
||||
return """
|
||||
{"ClientId":"%s","ChallengeName":"%s","Session":"%s",
|
||||
"ChallengeResponses":{"USERNAME":"%s","%s":"%s"}}
|
||||
""".formatted(clientId, challengeName, challenge.path("Session").asText(), user.username(), key,
|
||||
value);
|
||||
}
|
||||
|
||||
private static String latestSms(String phone) throws Exception {
|
||||
JsonNode messages = JSON.readTree(given().queryParam("phone", phone).get("/_aws/sns")
|
||||
.then().statusCode(200).extract().asString()).path("messages");
|
||||
assertTrue(messages.isArray() && !messages.isEmpty(), "an SMS should have been sent to " + phone);
|
||||
return messages.get(messages.size() - 1).path("Message").asText();
|
||||
}
|
||||
|
||||
/** The newest message to {@code recipient}: {@code /_aws/ses?email=} filters by sender, so match the recipient here. */
|
||||
private static JsonNode latestEmail(String recipient) throws Exception {
|
||||
JsonNode messages = JSON.readTree(given().get("/_aws/ses")
|
||||
.then().statusCode(200).extract().asString()).path("messages");
|
||||
JsonNode latest = null;
|
||||
for (JsonNode message : messages) {
|
||||
for (JsonNode to : message.path("Destination").path("ToAddresses")) {
|
||||
if (recipient.equals(to.asText())) {
|
||||
latest = message;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertNotNull(latest, "an email should have been sent to " + recipient);
|
||||
return latest;
|
||||
}
|
||||
|
||||
private static String sixDigitCode(String message) {
|
||||
Matcher matcher = SIX_DIGIT_CODE.matcher(message);
|
||||
assertTrue(matcher.find(), "the message should carry a six-digit code: " + message);
|
||||
return matcher.group(1);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -121,7 +121,7 @@ class CognitoOptionalTotpMfaIntegrationTest {
|
||||
.then().statusCode(200)
|
||||
.body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP", "EMAIL_OTP"));
|
||||
|
||||
// Floci sends no email MFA code after a password, so email MFA alone keeps the email code choice.
|
||||
// The pool offers no email MFA, so email MFA turned on alone keeps the email code choice.
|
||||
cognitoJson("SetUserMFAPreference", """
|
||||
{"AccessToken":"%s","EmailMfaSettings":{"Enabled":true}}
|
||||
""".formatted(accessToken));
|
||||
|
||||
Reference in new issue
Block a user