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:
outofplace authored and GitHub committed 2026-10-15 23:38:41 -04:00
1 parent db8c441ed4
commit d0e0af502b
11 files changed
+821 -65

No files matched your search

@@ -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; }
@@ -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},
@@ -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;