Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cognito): support TOTP MFA when MFA is optional (#5101)

outofplacea5db3975c45c
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoOptionalTotpMfaTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoOptionalTotpMfaTest.java
new file mode 100644
index 0000000000..16af1b7e70
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoOptionalTotpMfaTest.java
@@ -0,0 +1,122 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeNameType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.GetUserResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.InitiateAuthResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.InvalidParameterException;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.RespondToAuthChallengeResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolMfaType;
+
+import java.nio.ByteBuffer;
+import java.time.Instant;
+import java.util.Locale;
+import java.util.Map;
+import java.util.UUID;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class CognitoOptionalTotpMfaTest {
+ private static final String USERNAME = "optional-totp-sdk-user";
+ private static final String PASSWORD = "SdkTotp123!";
+
+ @Test
+ @DisplayName("optional MFA challenges a user only after SetUserMFAPreference turns TOTP on")
+ void sdkTurnsOnSoftwareTokenMfaInAnOptionalPool() throws Exception {
+ try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
+ String poolId = cognito.createUserPool(b -> b.poolName("optional-totp-sdk-" + UUID.randomUUID()))
+ .userPool().id();
+ try {
+ cognito.setUserPoolMfaConfig(b -> b.userPoolId(poolId)
+ .mfaConfiguration(UserPoolMfaType.OPTIONAL)
+ .softwareTokenMfaConfiguration(m -> m.enabled(true)));
+ String clientId = cognito.createUserPoolClient(b -> b.userPoolId(poolId)
+ .clientName("optional-totp-sdk-client")
+ .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH))
+ .userPoolClient().clientId();
+ cognito.adminCreateUser(b -> b.userPoolId(poolId).username(USERNAME)
+ .messageAction(MessageActionType.SUPPRESS));
+ cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username(USERNAME)
+ .password(PASSWORD).permanent(true));
+
+ String accessToken = passwordLogin(cognito, clientId).authenticationResult().accessToken();
+ assertThatThrownBy(() -> cognito.setUserMFAPreference(b -> b.accessToken(accessToken)
+ .softwareTokenMfaSettings(s -> s.enabled(true).preferredMfa(true))))
+ .isInstanceOf(InvalidParameterException.class);
+
+ String secret = cognito.associateSoftwareToken(b -> b.accessToken(accessToken)).secretCode();
+ String setupCode = totp(secret, Instant.now());
+ cognito.verifySoftwareToken(b -> b.accessToken(accessToken).userCode(setupCode));
+ assertThat(passwordLogin(cognito, clientId).authenticationResult()).isNotNull();
+
+ cognito.setUserMFAPreference(b -> b.accessToken(accessToken)
+ .softwareTokenMfaSettings(s -> s.enabled(true).preferredMfa(true)));
+ GetUserResponse user = cognito.getUser(b -> b.accessToken(accessToken));
+ assertThat(user.userMFASettingList()).containsExactly("SOFTWARE_TOKEN_MFA");
+ assertThat(user.preferredMfaSetting()).isEqualTo("SOFTWARE_TOKEN_MFA");
+ AdminGetUserResponse adminUser = cognito.adminGetUser(b -> b.userPoolId(poolId).username(USERNAME));
+ assertThat(adminUser.userMFASettingList()).containsExactly("SOFTWARE_TOKEN_MFA");
+ assertThat(adminUser.preferredMfaSetting()).isEqualTo("SOFTWARE_TOKEN_MFA");
+
+ InitiateAuthResponse challenged = passwordLogin(cognito, clientId);
+ assertThat(challenged.challengeName()).isEqualTo(ChallengeNameType.SOFTWARE_TOKEN_MFA);
+ assertThat(challenged.authenticationResult()).isNull();
+ String signInCode = totp(secret, Instant.now());
+ RespondToAuthChallengeResponse signedIn = cognito.respondToAuthChallenge(b -> b
+ .clientId(clientId).challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA)
+ .session(challenged.session())
+ .challengeResponses(Map.of("USERNAME", USERNAME,
+ "SOFTWARE_TOKEN_MFA_CODE", signInCode)));
+ assertThat(signedIn.authenticationResult().accessToken()).isNotBlank();
+
+ cognito.adminSetUserMFAPreference(b -> b.userPoolId(poolId).username(USERNAME)
+ .softwareTokenMfaSettings(s -> s.enabled(false)));
+ assertThat(passwordLogin(cognito, clientId).authenticationResult()).isNotNull();
+ assertThat(cognito.adminGetUser(b -> b.userPoolId(poolId).username(USERNAME))
+ .hasUserMFASettingList()).isFalse();
+ } finally {
+ cognito.deleteUserPool(b -> b.userPoolId(poolId));
+ }
+ }
+ }
+
+ private static InitiateAuthResponse passwordLogin(CognitoIdentityProviderClient cognito, String clientId) {
+ return cognito.initiateAuth(b -> b.clientId(clientId)
+ .authFlow(AuthFlowType.USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD)));
+ }
+
+ private static String totp(String secret, Instant now) throws Exception {
+ byte[] key = new byte[secret.length() * 5 / 8];
+ int buffer = 0;
+ int bits = 0;
+ int index = 0;
+ for (int i = 0; i < secret.length(); i++) {
+ buffer = (buffer << 5) | "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(secret.charAt(i));
+ bits += 5;
+ if (bits >= 8) {
+ key[index++] = (byte) (buffer >>> (bits - 8));
+ bits -= 8;
+ }
+ }
+ Mac mac = Mac.getInstance("HmacSHA1");
+ mac.init(new SecretKeySpec(key, "HmacSHA1"));
+ byte[] digest = mac.doFinal(ByteBuffer.allocate(Long.BYTES)
+ .putLong(now.getEpochSecond() / 30).array());
+ int offset = digest[digest.length - 1] & 15;
+ int binary = ((digest[offset] & 127) << 24)
+ | ((digest[offset + 1] & 255) << 16)
+ | ((digest[offset + 2] & 255) << 8)
+ | (digest[offset + 3] & 255);
+ return String.format(Locale.ROOT, "%06d", binary % 1_000_000);
+ }
+}
diff --git a/docs/services/cognito.md b/docs/services/cognito.md
index 93bb95c58e..cd6711b283 100644
--- a/docs/services/cognito.md
+++ b/docs/services/cognito.md
@@ -208,7 +208,7 @@ further divergences, both deliberate:
| Action | Description |
|--------|-------------|
| AdminCreateUser | Creates or resends setup for a user in a user pool. Creating a user invokes the pre sign-up trigger with triggerSource `PreSignUp_AdminCreateUser`, the request's `ValidationData` and `ClientMetadata`, and `callerContext.clientId` `CLIENT_ID_NOT_APPLICABLE`. A trigger error refuses the user with `UserLambdaValidationException`, and its `autoConfirmUser`, `autoVerifyEmail` and `autoVerifyPhone` are ignored, as on AWS. |
-| AdminGetUser | Returns a user's stored attributes and status. |
+| AdminGetUser | Returns a user's stored attributes and status, and the MFA settings (`UserMFASettingList`, `PreferredMfaSetting`) once any is turned on. |
| AdminDeleteUser | Deletes a user from a user pool. An API Gateway Cognito authorizer rejects the user's existing tokens afterwards. |
| AdminSetUserPassword | Sets a user's password and permanent-password status. |
| AdminUpdateUserAttributes | Updates attributes for a user in a user pool. |
@@ -217,7 +217,7 @@ further divergences, both deliberate:
| AdminDisableUser | Disables a user, who can no longer sign in. 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 MFA preference from `EmailMfaSettings`. SMS and software-token settings are accepted but not stored. |
+| AdminSetUserMFAPreference | Sets a user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`. SMS settings are accepted but not stored. 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. |
@@ -228,15 +228,15 @@ further divergences, both deliberate:
| SignUp | Creates a self-service user for an app client. |
| 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. |
-| 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, 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 MFA preference set with `SetUserMFAPreference`. `WEB_AUTHN` and SMS or software-token MFA settings are not reported. |
+| 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, 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`. `WEB_AUTHN` and SMS MFA settings are not reported. |
| 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 MFA preference from `EmailMfaSettings`. SMS and software-token settings are accepted but not stored. |
+| SetUserMFAPreference | Sets the authenticated access-token user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`. SMS settings are accepted but not stored. See [MFA preferences](#mfa-preferences). |
| GlobalSignOut | Revokes the access, ID and refresh tokens issued to the authenticated access-token user. |
| ForgotPassword | Starts the local forgot-password flow for a user. |
| ConfirmForgotPassword | Completes the forgot-password flow by setting a replacement password. |
@@ -264,7 +264,7 @@ which a pre token generation trigger leaves when it suppresses every scope.
| GetTokensFromRefreshToken | Issues new access and ID tokens from a refresh token. A client's `RefreshTokenRotation` setting is stored but not applied, so no new refresh token is issued. |
| RevokeToken | Revokes a refresh token. The client must have token revocation enabled and, when it has a secret, present it. Only refresh tokens can be revoked. |
| AssociateSoftwareToken | Creates a TOTP secret for a user identified by an MFA setup session or access token. |
-| VerifySoftwareToken | Verifies the TOTP code and enables the user's software token. |
+| VerifySoftwareToken | Verifies the TOTP code and registers the user's authenticator. |
With `MfaConfiguration=ON` and software-token MFA enabled, a successful password or SRP
first factor returns `MFA_SETUP` instead of tokens for a user without a verified token.
@@ -275,8 +275,36 @@ requires a fresh code in `SOFTWARE_TOKEN_MFA_CODE`. Both token-management action
also accept an access token for an already authenticated user. Sessions expire with
the app client's `AuthSessionValidity` and cannot be replayed after completion.
-This flow currently covers software-token MFA required by a pool. Optional MFA
-preferences, SMS/email MFA challenges, and managed-login MFA are not emulated.
+Completing `MFA_SETUP` turns software-token MFA on for the user and, when no other factor is
+preferred, makes it the preferred one, so `GetUser` and `AdminGetUser` report it.
+
+#### MFA preferences
+
+With `MfaConfiguration=OPTIONAL`, a verified authenticator alone does not change sign-in: as on
+AWS, the user is asked for a code only once software-token MFA is turned on with
+`SetUserMFAPreference` or `AdminSetUserMFAPreference` (`SoftwareTokenMfaSettings.Enabled`). From
+then on a successful password or SRP first factor, through `USER_PASSWORD_AUTH`,
+`ADMIN_USER_PASSWORD_AUTH`, `USER_SRP_AUTH` or the `PASSWORD` and `PASSWORD_SRP` challenges of
+`USER_AUTH`, returns `SOFTWARE_TOKEN_MFA`, answered with `RespondToAuthChallenge` or
+`AdminRespondToAuthChallenge`. Turning it off again signs the user in without a challenge. The
+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
+ `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.
+
+SMS and email MFA challenges, and managed-login MFA, are not emulated.
### User Listing
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
index 4d632ef257..2b5e6676b1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
@@ -429,6 +429,9 @@ final class CognitoAuthFlowHandler {
throw new AwsException("NotAuthorizedException", "Session not found", 400);
}
}
+ if (phase == TotpPhase.VERIFIED) {
+ service.activateSoftwareTokenMfaAfterSetup(pool.getId(), user.getUsername());
+ }
Map<String, String> metadata = clientMetadata != null && !clientMetadata.isEmpty()
? clientMetadata : state.clientMetadata();
return authenticationResult(pool, client, user, state.triggerSource(), metadata);
@@ -1179,6 +1182,12 @@ final class CognitoAuthFlowHandler {
List<String> available = availableUserAuthChallenges(user);
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.
+ if ("OPTIONAL".equals(pool.getMfaConfiguration()) && CognitoService.softwareTokenMfaEnabled(user)) {
+ available.removeIf(challenge -> !"PASSWORD".equals(challenge) && !"PASSWORD_SRP".equals(challenge));
+ }
return available;
}
@@ -1918,14 +1927,23 @@ 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.
+ */
private Map<String, Object> completePrimaryAuth(UserPool pool, UserPoolClient client, CognitoUser user,
String triggerSource, Map<String, String> clientMetadata) {
- if (!"ON".equals(pool.getMfaConfiguration())
- || !Boolean.TRUE.equals(pool.getSoftwareTokenMfaEnabled())) {
+ 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 {
return authenticationResult(pool, client, user, triggerSource, clientMetadata);
}
- TotpPhase phase = user.getSoftwareTokenMfaSecret() == null
- ? TotpPhase.SETUP : TotpPhase.CODE_REQUIRED;
String challengeName = phase == TotpPhase.SETUP ? "MFA_SETUP" : "SOFTWARE_TOKEN_MFA";
Map<String, Object> result = new HashMap<>();
result.put("ChallengeName", challengeName);
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
index b05ac041c3..8d510cc711 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java
@@ -648,6 +648,9 @@ public class CognitoJsonHandler {
attr.put("Name", k);
attr.put("Value", v);
});
+ Map<String, Object> mfaSettings = new LinkedHashMap<>();
+ CognitoService.putMfaSettings(mfaSettings, service.describeUserPool(request.path("UserPoolId").asText()), user);
+ response.setAll(objectMapper.<ObjectNode>valueToTree(mfaSettings));
return Response.ok(response).build();
}
@@ -1509,47 +1512,26 @@ public class CognitoJsonHandler {
return node;
}
private Response handleAdminSetUserMFAPreference(JsonNode request) {
- String userPoolId = request.path("UserPoolId").asText();
- String username = request.path("Username").asText();
-
- JsonNode emailSettings = request.path("EmailMfaSettings");
-
- Boolean enabled = emailSettings.has("Enabled")
- ? emailSettings.path("Enabled").asBoolean()
- : null;
-
- Boolean preferredMfa = emailSettings.has("PreferredMfa")
- ? emailSettings.path("PreferredMfa").asBoolean()
- : null;
-
service.adminSetUserMFAPreference(
- userPoolId,
- username,
- enabled,
- preferredMfa
- );
-
+ request.path("UserPoolId").asText(),
+ request.path("Username").asText(),
+ mfaSettingsUpdate(request.path("EmailMfaSettings")),
+ mfaSettingsUpdate(request.path("SoftwareTokenMfaSettings")));
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleSetUserMFAPreference(JsonNode request) {
- JsonNode emailSettings = request.path("EmailMfaSettings");
-
- Boolean enabled = emailSettings.has("Enabled")
- ? emailSettings.path("Enabled").asBoolean()
- : null;
-
- Boolean preferredMfa = emailSettings.has("PreferredMfa")
- ? emailSettings.path("PreferredMfa").asBoolean()
- : null;
-
service.setUserMFAPreference(
request.path("AccessToken").asText(),
- enabled,
- preferredMfa
- );
-
+ mfaSettingsUpdate(request.path("EmailMfaSettings")),
+ mfaSettingsUpdate(request.path("SoftwareTokenMfaSettings")));
return Response.ok(objectMapper.createObjectNode()).build();
}
+ private static CognitoService.MfaSettingsUpdate mfaSettingsUpdate(JsonNode settings) {
+ return new CognitoService.MfaSettingsUpdate(
+ settings.has("Enabled") ? settings.path("Enabled").asBoolean() : null,
+ settings.has("PreferredMfa") ? settings.path("PreferredMfa").asBoolean() : null);
+ }
+
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
index 5c3696c716..7c7822703a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
@@ -28,6 +28,7 @@ import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
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.SoftwareTokenMfaSettings;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClientSecret;
@@ -3386,13 +3387,13 @@ public class CognitoService implements ResourceProvider {
List<Map<String, String>> attrs = new ArrayList<>();
user.getAttributes().forEach((k, v) -> attrs.add(Map.of("Name", k, "Value", v)));
result.put("UserAttributes", attrs);
+ putMfaSettings(result, describeUserPool(token.poolId()), user);
return result;
}
/**
- * GetUserAuthFactors. The MFA members come from the email MFA preference, the one per-user
- * MFA setting Floci stores; SetUserMFAPreference accepts SMS and software-token settings
- * without keeping them.
+ * GetUserAuthFactors. The MFA members come from the email and software-token MFA preferences;
+ * SetUserMFAPreference accepts SMS settings without keeping them.
*/
public Map<String, Object> getUserAuthFactors(String accessToken) {
VerifiedAccessToken token;
@@ -3414,13 +3415,7 @@ public class CognitoService implements ResourceProvider {
if (!factors.isEmpty()) {
result.put("ConfiguredUserAuthFactors", factors);
}
- EmailMfaSettings emailMfa = user.getEmailMfaSettings();
- if (emailMfa != null && emailMfa.isEnabled()) {
- if (emailMfa.isPreferredMfa()) {
- result.put("PreferredMfaSetting", "EMAIL_OTP");
- }
- result.put("UserMFASettingList", List.of("EMAIL_OTP"));
- }
+ putMfaSettings(result, describeUserPool(token.poolId()), user);
return result;
}
@@ -5486,101 +5481,169 @@ public class CognitoService implements ResourceProvider {
}
return value;
}
- public void adminSetUserMFAPreference(
- String userPoolId,
- String username,
- Boolean emailEnabled,
- Boolean emailPreferred) {
+ /**
+ * One factor's settings from an MFA preference request ({@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);
- CognitoUser resolvedUser = adminGetUser(userPoolId, username);
- synchronized (userLock(userPoolId, resolvedUser.getUsername())) {
- adminSetUserMFAPreferenceUnderUserLock(
- userPoolId, resolvedUser.getUsername(), emailEnabled, emailPreferred);
+ boolean isEmpty() {
+ return enabled == null && preferredMfa == null;
}
}
- private void adminSetUserMFAPreferenceUnderUserLock(
- String userPoolId,
- String username,
- Boolean emailEnabled,
- Boolean emailPreferred) {
-
- CognitoUser user = adminGetUser(userPoolId, username);
-
- updateEmailMfaPreference(user, emailEnabled, emailPreferred);
-
- user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
-
- userStore.put(userKey(userPoolId, user.getUsername()), user);
+ public void adminSetUserMFAPreference(String userPoolId, String username,
+ MfaSettingsUpdate email, MfaSettingsUpdate softwareToken) {
+ CognitoUser resolvedUser = adminGetUser(userPoolId, username);
+ synchronized (userLock(userPoolId, resolvedUser.getUsername())) {
+ updateMfaPreferenceUnderUserLock(userPoolId, resolvedUser.getUsername(), email, softwareToken);
+ }
}
- public void setUserMFAPreference(
- String accessToken,
- Boolean emailEnabled,
- Boolean emailPreferred) {
-
+ public void setUserMFAPreference(String accessToken, MfaSettingsUpdate email, MfaSettingsUpdate softwareToken) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
requireScope(accessToken, USER_ADMIN_SCOPE);
synchronized (userLock(token.poolId(), token.username())) {
- setUserMFAPreferenceUnderUserLock(
- token.poolId(), token.username(), emailEnabled, emailPreferred);
+ updateMfaPreferenceUnderUserLock(token.poolId(), token.username(), email, softwareToken);
}
}
- private void setUserMFAPreferenceUnderUserLock(
- String poolId,
- String username,
- Boolean emailEnabled,
- Boolean emailPreferred) {
-
+ private void updateMfaPreferenceUnderUserLock(String poolId, String username,
+ MfaSettingsUpdate email, MfaSettingsUpdate softwareToken) {
CognitoUser user = adminGetUser(poolId, username);
-
- updateEmailMfaPreference(user, emailEnabled, emailPreferred);
-
+ if (Boolean.TRUE.equals(email.preferredMfa()) && Boolean.TRUE.equals(softwareToken.preferredMfa())) {
+ throw new AwsException("InvalidParameterException",
+ "Only one MFA method can be set as preferred.", 400);
+ }
+ EmailMfaSettings emailSettings = user.getEmailMfaSettings();
+ SoftwareTokenMfaSettings tokenSettings = user.getSoftwareTokenMfaSettings();
+ 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.
+ 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())) {
+ tokenState = new FactorState(tokenState.enabled(), false);
+ } else if (Boolean.TRUE.equals(softwareToken.preferredMfa())) {
+ emailState = new FactorState(emailState.enabled(), false);
+ }
+ if (!email.isEmpty() || emailSettings != null) {
+ EmailMfaSettings settings = emailSettings != null ? emailSettings : new EmailMfaSettings();
+ settings.setEnabled(emailState.enabled());
+ settings.setPreferredMfa(emailState.preferred());
+ user.setEmailMfaSettings(settings);
+ }
+ if (!softwareToken.isEmpty() || tokenSettings != null) {
+ SoftwareTokenMfaSettings settings = tokenSettings != null ? tokenSettings : new SoftwareTokenMfaSettings();
+ settings.setEnabled(tokenState.enabled());
+ settings.setPreferredMfa(tokenState.preferred());
+ user.setSoftwareTokenMfaSettings(settings);
+ }
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
-
userStore.put(userKey(poolId, user.getUsername()), user);
}
- private void updateEmailMfaPreference(
- CognitoUser user,
- Boolean enabled,
- Boolean preferredMfa) {
+ private record FactorState(boolean enabled, boolean preferred) {
+ static final FactorState OFF = new FactorState(false, false);
+ }
- if (enabled == null && preferredMfa == null) {
- return;
+ /**
+ * The state a factor ends up in after {@code update}. Disabling a factor drops its preference,
+ * and preferring a disabled one is refused.
+ */
+ private static FactorState resolveMfaSettings(MfaSettingsUpdate update, FactorState current) {
+ boolean enabled = update.enabled() != null ? update.enabled() : current.enabled();
+ boolean preferred = update.preferredMfa() != null ? update.preferredMfa() : current.preferred();
+ if (!enabled && Boolean.TRUE.equals(update.preferredMfa())) {
+ throw new AwsException("InvalidParameterException",
+ "Preferred MFA setting cannot be enabled when the MFA method is disabled.", 400);
}
+ return new FactorState(enabled, enabled && preferred);
+ }
- EmailMfaSettings current = user.getEmailMfaSettings();
-
- boolean newEnabled = enabled != null
- ? enabled
- : current != null && current.isEnabled();
+ /**
+ * 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.
+ */
+ void activateSoftwareTokenMfaAfterSetup(String poolId, String username) {
+ synchronized (userLock(poolId, username)) {
+ CognitoUser user = adminGetUser(poolId, username);
+ SoftwareTokenMfaSettings settings = user.getSoftwareTokenMfaSettings() != null
+ ? user.getSoftwareTokenMfaSettings() : new SoftwareTokenMfaSettings();
+ settings.setEnabled(true);
+ if (preferredMfaSetting(describeUserPool(poolId), user) == null) {
+ settings.setPreferredMfa(true);
+ }
+ user.setSoftwareTokenMfaSettings(settings);
+ user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
+ userStore.put(userKey(poolId, user.getUsername()), user);
+ }
+ }
- boolean newPreferredMfa = preferredMfa != null
- ? preferredMfa
- : current != null && current.isPreferredMfa();
- if (!newEnabled && Boolean.TRUE.equals(preferredMfa)) {
- throw new AwsException(
- "InvalidParameterException",
- "Preferred MFA setting cannot be enabled when the MFA method is disabled.",
- 400
- );
+ /**
+ * {@code UserMFASettingList}: the MFA factors activated for the user, in the order the API
+ * reference lists them. Software-token MFA counts once the user has a verified authenticator
+ * that is turned on, or that a pool requiring software-token MFA asks for at every sign-in.
+ */
+ static List<String> userMfaSettingList(UserPool pool, CognitoUser user) {
+ List<String> factors = new ArrayList<>();
+ if (user.getEmailMfaSettings() != null && user.getEmailMfaSettings().isEnabled()) {
+ factors.add("EMAIL_OTP");
+ }
+ if (softwareTokenMfaActive(pool, user)) {
+ factors.add("SOFTWARE_TOKEN_MFA");
}
+ return factors;
+ }
- if (!newEnabled) {
- newPreferredMfa = false;
+ /** {@code PreferredMfaSetting}: the user's preferred MFA factor, or null when none is. */
+ static @Nullable String preferredMfaSetting(UserPool pool, CognitoUser user) {
+ EmailMfaSettings email = user.getEmailMfaSettings();
+ if (email != null && email.isEnabled() && email.isPreferredMfa()) {
+ return "EMAIL_OTP";
+ }
+ SoftwareTokenMfaSettings token = user.getSoftwareTokenMfaSettings();
+ if (token != null && token.isPreferredMfa() && softwareTokenMfaActive(pool, user)) {
+ return "SOFTWARE_TOKEN_MFA";
}
+ return null;
+ }
- EmailMfaSettings settings = current != null
- ? current
- : new EmailMfaSettings();
+ /** Whether the user has turned on software-token MFA for a verified authenticator. */
+ static boolean softwareTokenMfaEnabled(CognitoUser user) {
+ SoftwareTokenMfaSettings settings = user.getSoftwareTokenMfaSettings();
+ return settings != null && settings.isEnabled() && user.getSoftwareTokenMfaSecret() != null;
+ }
- settings.setEnabled(newEnabled);
- settings.setPreferredMfa(newPreferredMfa);
+ /**
+ * Whether software-token MFA is active for the user: turned on, or required. A pool that requires
+ * 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) {
+ return softwareTokenMfaEnabled(user)
+ || (user.getSoftwareTokenMfaSecret() != null && "ON".equals(pool.getMfaConfiguration())
+ && Boolean.TRUE.equals(pool.getSoftwareTokenMfaEnabled()));
+ }
- user.setEmailMfaSettings(settings);
+ /** Adds {@code UserMFASettingList} and {@code PreferredMfaSetting} to a user response, when set. */
+ static void putMfaSettings(Map<String, Object> response, UserPool pool, CognitoUser user) {
+ String preferred = preferredMfaSetting(pool, user);
+ if (preferred != null) {
+ response.put("PreferredMfaSetting", preferred);
+ }
+ List<String> factors = userMfaSettingList(pool, user);
+ if (!factors.isEmpty()) {
+ response.put("UserMFASettingList", factors);
+ }
}
+
private record DeliveryTarget(String attributeName, String deliveryMedium, String destination) {
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
index 554f89955f..2620777d3c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java
@@ -26,6 +26,7 @@ public class CognitoUser {
private String srpSalt;
private String srpVerifier;
private EmailMfaSettings emailMfaSettings;
+ private SoftwareTokenMfaSettings softwareTokenMfaSettings;
private String softwareTokenMfaSecret;
private String pendingSoftwareTokenMfaSecret;
private Integer pendingSoftwareTokenMfaAttemptsRemaining;
@@ -95,6 +96,11 @@ public class CognitoUser {
this.emailMfaSettings = emailMfaSettings;
}
+ public SoftwareTokenMfaSettings getSoftwareTokenMfaSettings() { return softwareTokenMfaSettings; }
+ public void setSoftwareTokenMfaSettings(SoftwareTokenMfaSettings settings) {
+ this.softwareTokenMfaSettings = settings;
+ }
+
public String getSoftwareTokenMfaSecret() { return softwareTokenMfaSecret; }
public void setSoftwareTokenMfaSecret(String secret) { this.softwareTokenMfaSecret = secret; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/SoftwareTokenMfaSettings.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/SoftwareTokenMfaSettings.java
new file mode 100644
index 0000000000..2e4b00e48c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/SoftwareTokenMfaSettings.java
@@ -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 SoftwareTokenMfaSettings {
+
+ 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;
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java
new file mode 100644
index 0000000000..63702a10c2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaIntegrationTest.java
@@ -0,0 +1,188 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.util.UUID;
+
+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
+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.assertTrue;
+
+@QuarkusTest
+class CognitoOptionalTotpMfaIntegrationTest {
+ private static final String PASSWORD = "Perm1234!";
+
+ @Inject
+ Clock clock;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void optionalPoolChallengesOnlyUsersWhoTurnedTotpOn() throws Exception {
+ String poolId = createOptionalPool();
+ String clientId = createClient(poolId);
+ String username = "optional-" + UUID.randomUUID();
+ createUser(poolId, username);
+ String loginRequest = """
+ {"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
+ "AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
+ """.formatted(clientId, username, PASSWORD);
+
+ String accessToken = cognitoJson("InitiateAuth", loginRequest)
+ .path("AuthenticationResult").path("AccessToken").asText();
+ cognitoAction("SetUserMFAPreference", """
+ {"AccessToken":"%s","SoftwareTokenMfaSettings":{"Enabled":true,"PreferredMfa":true}}
+ """.formatted(accessToken))
+ .then().statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"))
+ .body("message", equalTo("User does not have delivery config set to turn on SOFTWARE_TOKEN_MFA"));
+
+ String secret = cognitoJson("AssociateSoftwareToken", """
+ {"AccessToken":"%s"}
+ """.formatted(accessToken)).path("SecretCode").asText();
+ assertEquals("SUCCESS", cognitoJson("VerifySoftwareToken", """
+ {"AccessToken":"%s","UserCode":"%s"}
+ """.formatted(accessToken, CognitoTotp.code(secret, clock.instant()))).path("Status").asText());
+ assertFalse(cognitoJson("InitiateAuth", loginRequest)
+ .path("AuthenticationResult").path("AccessToken").asText().isEmpty());
+ cognitoAction("GetUser", accessTokenBody(accessToken))
+ .then().statusCode(200)
+ .body("$", not(hasKey("UserMFASettingList")))
+ .body("$", not(hasKey("PreferredMfaSetting")));
+
+ cognitoAction("SetUserMFAPreference", """
+ {"AccessToken":"%s","SoftwareTokenMfaSettings":{"Enabled":true,"PreferredMfa":true}}
+ """.formatted(accessToken))
+ .then().statusCode(200);
+ cognitoAction("GetUser", accessTokenBody(accessToken))
+ .then().statusCode(200)
+ .body("UserMFASettingList", contains("SOFTWARE_TOKEN_MFA"))
+ .body("PreferredMfaSetting", equalTo("SOFTWARE_TOKEN_MFA"));
+ cognitoAction("AdminGetUser", """
+ {"UserPoolId":"%s","Username":"%s"}
+ """.formatted(poolId, username))
+ .then().statusCode(200)
+ .body("UserMFASettingList", contains("SOFTWARE_TOKEN_MFA"))
+ .body("PreferredMfaSetting", equalTo("SOFTWARE_TOKEN_MFA"));
+
+ JsonNode challenged = cognitoJson("InitiateAuth", loginRequest);
+ assertEquals("SOFTWARE_TOKEN_MFA", challenged.path("ChallengeName").asText());
+ assertTrue(challenged.path("AuthenticationResult").isMissingNode());
+ JsonNode signedIn = cognitoJson("RespondToAuthChallenge", """
+ {"ClientId":"%s","ChallengeName":"SOFTWARE_TOKEN_MFA","Session":"%s",
+ "ChallengeResponses":{"USERNAME":"%s","SOFTWARE_TOKEN_MFA_CODE":"%s"}}
+ """.formatted(clientId, challenged.path("Session").asText(), username,
+ CognitoTotp.code(secret, clock.instant())));
+ assertFalse(signedIn.path("AuthenticationResult").path("AccessToken").asText().isEmpty());
+
+ cognitoAction("AdminSetUserMFAPreference", """
+ {"UserPoolId":"%s","Username":"%s","SoftwareTokenMfaSettings":{"Enabled":false}}
+ """.formatted(poolId, username))
+ .then().statusCode(200);
+ assertFalse(cognitoJson("InitiateAuth", loginRequest)
+ .path("AuthenticationResult").path("AccessToken").asText().isEmpty());
+ cognitoAction("AdminGetUser", """
+ {"UserPoolId":"%s","Username":"%s"}
+ """.formatted(poolId, username))
+ .then().statusCode(200)
+ .body("$", not(hasKey("UserMFASettingList")))
+ .body("$", not(hasKey("PreferredMfaSetting")));
+ }
+
+ @Test
+ void choiceBasedSignInOffersOnlyPasswordToAUserWithMfa() throws Exception {
+ String poolId = createOptionalPool();
+ String clientId = createClient(poolId);
+ String username = "choice-" + UUID.randomUUID();
+ createUser(poolId, username);
+ String accessToken = cognitoJson("InitiateAuth", """
+ {"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
+ "AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
+ """.formatted(clientId, username, PASSWORD)).path("AuthenticationResult").path("AccessToken").asText();
+ String userAuthRequest = """
+ {"ClientId":"%s","AuthFlow":"USER_AUTH","AuthParameters":{"USERNAME":"%s"}}
+ """.formatted(clientId, username);
+ cognitoAction("InitiateAuth", userAuthRequest)
+ .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.
+ cognitoJson("SetUserMFAPreference", """
+ {"AccessToken":"%s","EmailMfaSettings":{"Enabled":true}}
+ """.formatted(accessToken));
+ cognitoAction("InitiateAuth", userAuthRequest)
+ .then().statusCode(200)
+ .body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP", "EMAIL_OTP"));
+
+ String secret = cognitoJson("AssociateSoftwareToken", accessTokenBody(accessToken))
+ .path("SecretCode").asText();
+ cognitoJson("VerifySoftwareToken", """
+ {"AccessToken":"%s","UserCode":"%s"}
+ """.formatted(accessToken, CognitoTotp.code(secret, clock.instant())));
+ cognitoJson("SetUserMFAPreference", """
+ {"AccessToken":"%s","SoftwareTokenMfaSettings":{"Enabled":true}}
+ """.formatted(accessToken));
+
+ cognitoAction("InitiateAuth", userAuthRequest)
+ .then().statusCode(200)
+ .body("ChallengeName", equalTo("SELECT_CHALLENGE"))
+ .body("AvailableChallenges", contains("PASSWORD", "PASSWORD_SRP"));
+ JsonNode challenged = cognitoJson("InitiateAuth", """
+ {"ClientId":"%s","AuthFlow":"USER_AUTH",
+ "AuthParameters":{"USERNAME":"%s","PREFERRED_CHALLENGE":"PASSWORD","PASSWORD":"%s"}}
+ """.formatted(clientId, username, PASSWORD));
+ assertEquals("SOFTWARE_TOKEN_MFA", challenged.path("ChallengeName").asText());
+ assertTrue(challenged.path("AuthenticationResult").isMissingNode());
+ }
+
+ private static String createOptionalPool() throws Exception {
+ String poolId = cognitoJson("CreateUserPool", """
+ {"PoolName":"OptionalTotpPool","UserPoolTier":"ESSENTIALS",
+ "Policies":{"SignInPolicy":{"AllowedFirstAuthFactors":["PASSWORD","EMAIL_OTP"]}}}
+ """).path("UserPool").path("Id").asText();
+ cognitoJson("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"OPTIONAL",
+ "SoftwareTokenMfaConfiguration":{"Enabled":true}}
+ """.formatted(poolId));
+ return poolId;
+ }
+
+ private static String createClient(String poolId) throws Exception {
+ return cognitoJson("CreateUserPoolClient", """
+ {"UserPoolId":"%s","ClientName":"optional-totp-client",
+ "ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_USER_AUTH"]}
+ """.formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
+ }
+
+ private static void createUser(String poolId, String username) throws Exception {
+ cognitoJson("AdminCreateUser", """
+ {"UserPoolId":"%s","Username":"%s","MessageAction":"SUPPRESS",
+ "UserAttributes":[{"Name":"email","Value":"%[email protected]"},
+ {"Name":"email_verified","Value":"true"}]}
+ """.formatted(poolId, username, username));
+ cognitoJson("AdminSetUserPassword", """
+ {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
+ """.formatted(poolId, username, PASSWORD));
+ }
+
+ private static String accessTokenBody(String accessToken) {
+ return """
+ {"AccessToken":"%s"}
+ """.formatted(accessToken);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaTest.java
new file mode 100644
index 0000000000..5e9dae1c53
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOptionalTotpMfaTest.java
@@ -0,0 +1,286 @@
+package io.github.hectorvent.floci.services.cognito;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.acm.AcmService;
+import io.github.hectorvent.floci.services.cognito.CognitoService.MfaSettingsUpdate;
+import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
+import io.github.hectorvent.floci.services.cognito.model.UserPool;
+import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
+import io.github.hectorvent.floci.testing.MutableClock;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+
+/** Software-token MFA in a pool where MFA is optional, turned on per user with the MFA preference actions. */
+class CognitoOptionalTotpMfaTest {
+ private static final String USERNAME = "alice";
+ private static final String PASSWORD = "Perm1234!";
+ private static final MfaSettingsUpdate TOTP_PREFERRED = new MfaSettingsUpdate(true, true);
+
+ private CognitoService service;
+ private MutableClock clock;
+ private UserPool pool;
+ private UserPoolClient client;
+
+ @BeforeEach
+ void setUp() {
+ clock = new MutableClock();
+ service = new CognitoService(new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ "http://localhost:4566", "cloudfront.net",
+ new RegionResolver("us-east-1", "000000000000"), null, mock(AcmService.class),
+ null, null, null, clock);
+ pool = service.createUserPool(Map.of("PoolName", "OptionalTotpPool"), "us-east-1");
+ service.adminCreateUser(pool.getId(), USERNAME, Map.of("email", "[email protected]"), null);
+ service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, true);
+ client = service.createUserPoolClient(pool.getId(), "optional-totp-client", false, false,
+ List.of(), List.of());
+ client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_USER_SRP_AUTH",
+ "ALLOW_ADMIN_USER_PASSWORD_AUTH"));
+ service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false);
+ }
+
+ @Test
+ void verifiedAuthenticatorIsNotChallengedUntilTurnedOn() {
+ String secret = registerAuthenticator();
+ assertNotNull(passwordLogin().get("AuthenticationResult"));
+
+ service.setUserMFAPreference(accessToken(), MfaSettingsUpdate.NONE, TOTP_PREFERRED);
+ Map<String, Object> challenged = passwordLogin();
+ assertEquals("SOFTWARE_TOKEN_MFA", challenged.get("ChallengeName"));
+ assertFalse(challenged.containsKey("AuthenticationResult"));
+
+ Map<String, Object> signedIn = service.respondToAuthChallenge(client.getClientId(), "SOFTWARE_TOKEN_MFA",
+ (String) challenged.get("Session"),
+ Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", CognitoTotp.code(secret, clock.instant())));
+ assertNotNull(((Map<?, ?>) signedIn.get("AuthenticationResult")).get("AccessToken"));
+ }
+
+ @Test
+ void turningTotpOffSignsInWithoutAChallengeAgain() {
+ registerAuthenticator();
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, MfaSettingsUpdate.NONE, TOTP_PREFERRED);
+ assertEquals("SOFTWARE_TOKEN_MFA", passwordLogin().get("ChallengeName"));
+
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, MfaSettingsUpdate.NONE,
+ new MfaSettingsUpdate(false, null));
+
+ assertNotNull(passwordLogin().get("AuthenticationResult"));
+ CognitoUser user = service.adminGetUser(pool.getId(), USERNAME);
+ assertTrue(mfaSettingList(user).isEmpty());
+ assertNull(preferredMfaSetting(user));
+ }
+
+ @Test
+ void turningTotpOnRequiresAVerifiedAuthenticator() {
+ String accessToken = accessToken();
+ AwsException noToken = assertThrows(AwsException.class,
+ () -> service.setUserMFAPreference(accessToken, MfaSettingsUpdate.NONE, TOTP_PREFERRED));
+ assertEquals("InvalidParameterException", noToken.getErrorCode());
+
+ service.associateSoftwareToken(accessToken, null);
+ AwsException unverified = assertThrows(AwsException.class, () -> service.adminSetUserMFAPreference(
+ pool.getId(), USERNAME, MfaSettingsUpdate.NONE, TOTP_PREFERRED));
+ assertEquals("InvalidParameterException", unverified.getErrorCode());
+ assertNull(service.adminGetUser(pool.getId(), USERNAME).getSoftwareTokenMfaSettings());
+ assertNotNull(passwordLogin().get("AuthenticationResult"));
+ }
+
+ @Test
+ void adminPasswordAuthAndAdminChallengeResponseUseTheAuthenticator() {
+ String secret = registerAuthenticator();
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, MfaSettingsUpdate.NONE,
+ new MfaSettingsUpdate(true, null));
+
+ Map<String, Object> challenged = service.adminInitiateAuth(pool.getId(), client.getClientId(),
+ "ADMIN_USER_PASSWORD_AUTH", Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD), Map.of());
+ assertEquals("SOFTWARE_TOKEN_MFA", challenged.get("ChallengeName"));
+
+ String code = CognitoTotp.code(secret, clock.instant());
+ String wrongCode = code.equals("000000") ? "000001" : "000000";
+ assertEquals("CodeMismatchException", assertThrows(AwsException.class,
+ () -> service.adminRespondToAuthChallenge(pool.getId(), client.getClientId(), "SOFTWARE_TOKEN_MFA",
+ (String) challenged.get("Session"),
+ Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", wrongCode), Map.of()))
+ .getErrorCode());
+ Map<String, Object> signedIn = service.adminRespondToAuthChallenge(pool.getId(), client.getClientId(),
+ "SOFTWARE_TOKEN_MFA", (String) challenged.get("Session"),
+ Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", code), Map.of());
+ assertNotNull(((Map<?, ?>) signedIn.get("AuthenticationResult")).get("AccessToken"));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void srpProofContinuesToTheSoftwareTokenChallenge() throws Exception {
+ registerAuthenticator();
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, MfaSettingsUpdate.NONE, TOTP_PREFERRED);
+
+ BigInteger privateA = new BigInteger("123456789abcdef123456789abcdef", 16);
+ BigInteger publicA = CognitoSrpHelper.G.modPow(privateA, CognitoSrpHelper.N);
+ Map<String, Object> started = service.initiateAuth(client.getClientId(), "USER_SRP_AUTH",
+ Map.of("USERNAME", USERNAME, "SRP_A", publicA.toString(16)));
+ Map<String, String> params = (Map<String, String>) started.get("ChallengeParameters");
+ String timestamp = "Wed Apr 8 12:00:00 UTC 2026";
+ byte[] sessionKey = clientSrpSessionKey(privateA, publicA,
+ new BigInteger(params.get("SRP_B"), 16), params.get("SALT"));
+ String signature = Base64.getEncoder().encodeToString(CognitoSrpHelper.computeSignature(sessionKey,
+ pool.getId(), USERNAME, Base64.getDecoder().decode(params.get("SECRET_BLOCK")), timestamp));
+
+ Map<String, Object> verified = service.respondToAuthChallenge(client.getClientId(),
+ "PASSWORD_VERIFIER", (String) started.get("Session"), Map.of(
+ "USERNAME", USERNAME,
+ "PASSWORD_CLAIM_SECRET_BLOCK", params.get("SECRET_BLOCK"),
+ "PASSWORD_CLAIM_SIGNATURE", signature,
+ "TIMESTAMP", timestamp));
+ assertEquals("SOFTWARE_TOKEN_MFA", verified.get("ChallengeName"));
+ assertFalse(verified.containsKey("AuthenticationResult"));
+ }
+
+ @Test
+ void preferringOneFactorDropsThePreferenceOfTheOther() {
+ registerAuthenticator();
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, new MfaSettingsUpdate(true, true),
+ MfaSettingsUpdate.NONE);
+ CognitoUser emailPreferred = service.adminGetUser(pool.getId(), USERNAME);
+ assertEquals("EMAIL_OTP", preferredMfaSetting(emailPreferred));
+
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, MfaSettingsUpdate.NONE, TOTP_PREFERRED);
+ CognitoUser totpPreferred = service.adminGetUser(pool.getId(), USERNAME);
+ assertEquals("SOFTWARE_TOKEN_MFA", preferredMfaSetting(totpPreferred));
+ assertEquals(List.of("EMAIL_OTP", "SOFTWARE_TOKEN_MFA"), mfaSettingList(totpPreferred));
+ assertTrue(totpPreferred.getEmailMfaSettings().isEnabled());
+ assertFalse(totpPreferred.getEmailMfaSettings().isPreferredMfa());
+
+ AwsException both = assertThrows(AwsException.class, () -> service.adminSetUserMFAPreference(
+ pool.getId(), USERNAME, new MfaSettingsUpdate(true, true), TOTP_PREFERRED));
+ assertEquals("InvalidParameterException", both.getErrorCode());
+ assertEquals("SOFTWARE_TOKEN_MFA",
+ preferredMfaSetting(service.adminGetUser(pool.getId(), USERNAME)));
+ }
+
+ @Test
+ void preferringADisabledFactorIsRefused() {
+ registerAuthenticator();
+ AwsException refused = assertThrows(AwsException.class, () -> service.adminSetUserMFAPreference(
+ pool.getId(), USERNAME, MfaSettingsUpdate.NONE, new MfaSettingsUpdate(false, true)));
+ assertEquals("InvalidParameterException", refused.getErrorCode());
+ }
+
+ @Test
+ void completingRequiredMfaSetupTurnsTheAuthenticatorOn() {
+ service.setUserPoolMfaConfig(pool.getId(), "ON", true, false);
+ Map<String, Object> login = passwordLogin();
+ assertEquals("MFA_SETUP", login.get("ChallengeName"));
+ Map<String, Object> associated = service.associateSoftwareToken(null, (String) login.get("Session"));
+ String code = CognitoTotp.code((String) associated.get("SecretCode"), clock.instant());
+ String verifiedSession = (String) service.verifySoftwareToken(null,
+ (String) associated.get("Session"), code).get("Session");
+ service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP", verifiedSession,
+ Map.of("USERNAME", USERNAME));
+
+ CognitoUser user = service.adminGetUser(pool.getId(), USERNAME);
+ assertEquals(List.of("SOFTWARE_TOKEN_MFA"), mfaSettingList(user));
+ assertEquals("SOFTWARE_TOKEN_MFA", preferredMfaSetting(user));
+
+ service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false);
+ assertEquals("SOFTWARE_TOKEN_MFA", passwordLogin().get("ChallengeName"));
+ }
+
+ @Test
+ void mfaSettingsSurviveUserSerialization() throws Exception {
+ registerAuthenticator();
+ service.adminSetUserMFAPreference(pool.getId(), USERNAME, MfaSettingsUpdate.NONE, TOTP_PREFERRED);
+
+ ObjectMapper mapper = new ObjectMapper();
+ CognitoUser restored = mapper.readValue(
+ mapper.writeValueAsBytes(service.adminGetUser(pool.getId(), USERNAME)), CognitoUser.class);
+ assertEquals(List.of("SOFTWARE_TOKEN_MFA"), mfaSettingList(restored));
+ assertEquals("SOFTWARE_TOKEN_MFA", preferredMfaSetting(restored));
+ }
+
+ @Test
+ void requiredPoolReportsTheAuthenticatorItAsksFor() {
+ service.setUserPoolMfaConfig(pool.getId(), "OFF", null, false);
+ String accessToken = accessToken();
+ service.setUserPoolMfaConfig(pool.getId(), "ON", true, false);
+ String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
+ service.verifySoftwareToken(accessToken, null, CognitoTotp.code(secret, clock.instant()));
+
+ assertEquals("SOFTWARE_TOKEN_MFA", passwordLogin().get("ChallengeName"));
+ CognitoUser user = service.adminGetUser(pool.getId(), USERNAME);
+ assertEquals(List.of("SOFTWARE_TOKEN_MFA"), mfaSettingList(user));
+ assertNull(preferredMfaSetting(user));
+
+ service.setUserPoolMfaConfig(pool.getId(), "OPTIONAL", true, false);
+ assertTrue(mfaSettingList(user).isEmpty());
+ assertNotNull(passwordLogin().get("AuthenticationResult"));
+ }
+
+ private List<String> mfaSettingList(CognitoUser user) {
+ return CognitoService.userMfaSettingList(service.describeUserPool(pool.getId()), user);
+ }
+
+ private String preferredMfaSetting(CognitoUser user) {
+ return CognitoService.preferredMfaSetting(service.describeUserPool(pool.getId()), user);
+ }
+
+ private String registerAuthenticator() {
+ String accessToken = accessToken();
+ String secret = (String) service.associateSoftwareToken(accessToken, null).get("SecretCode");
+ assertEquals("SUCCESS", service.verifySoftwareToken(accessToken, null,
+ CognitoTotp.code(secret, clock.instant())).get("Status"));
+ return secret;
+ }
+
+ private String accessToken() {
+ return (String) ((Map<?, ?>) passwordLogin().get("AuthenticationResult")).get("AccessToken");
+ }
+
+ private Map<String, Object> passwordLogin() {
+ return service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
+ Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD));
+ }
+
+ private byte[] clientSrpSessionKey(BigInteger privateA, BigInteger publicA,
+ BigInteger publicB, String saltHex) throws Exception {
+ MessageDigest hash = MessageDigest.getInstance("SHA-256");
+ hash.update((CognitoSrpHelper.extractPoolName(pool.getId()) + USERNAME + ":" + PASSWORD)
+ .getBytes(StandardCharsets.UTF_8));
+ byte[] inner = hash.digest();
+ hash.update(new BigInteger(saltHex, 16).toByteArray());
+ BigInteger x = new BigInteger(1, hash.digest(inner));
+ hash.update(publicA.toByteArray());
+ BigInteger u = new BigInteger(1, hash.digest(publicB.toByteArray()));
+ BigInteger base = publicB.subtract(CognitoSrpHelper.K.multiply(
+ CognitoSrpHelper.G.modPow(x, CognitoSrpHelper.N))).mod(CognitoSrpHelper.N);
+ BigInteger shared = base.modPow(privateA.add(u.multiply(x)), CognitoSrpHelper.N);
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(new SecretKeySpec(u.toByteArray(), "HmacSHA256"));
+ byte[] prk = mac.doFinal(shared.toByteArray());
+ mac.init(new SecretKeySpec(prk, "HmacSHA256"));
+ mac.update("Caldera Derived Key".getBytes(StandardCharsets.UTF_8));
+ mac.update((byte) 1);
+ return Arrays.copyOf(mac.doFinal(), 16);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
index 2923963aaf..399da092b1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java
@@ -5533,7 +5533,8 @@ class CognitoServiceTest {
assertThrows(AwsException.class, () -> service.deleteUserAttributes(invalid, List.of("email")));
assertThrows(AwsException.class, () -> service.getUserAttributeVerificationCode(invalid, "email"));
assertThrows(AwsException.class, () -> service.globalSignOut(invalid));
- assertThrows(AwsException.class, () -> service.setUserMFAPreference(invalid, true, false));
+ assertThrows(AwsException.class, () -> service.setUserMFAPreference(invalid,
+ new CognitoService.MfaSettingsUpdate(true, false), CognitoService.MfaSettingsUpdate.NONE));
assertThrows(AwsException.class, () -> service.getUserAuthFactors(invalid));
}
@@ -5765,7 +5766,8 @@ class CognitoServiceTest {
void adminSetUserMFAPreferenceUpdatesEmailMfaSettings() {
UserPool pool = createPoolAndUser();
- service.adminSetUserMFAPreference(pool.getId(), "alice", true, true);
+ service.adminSetUserMFAPreference(pool.getId(), "alice",
+ new CognitoService.MfaSettingsUpdate(true, true), CognitoService.MfaSettingsUpdate.NONE);
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
@@ -5778,10 +5780,12 @@ class CognitoServiceTest {
void adminSetUserMFAPreferenceDoesNotMutateOnInvalidUpdate() {
UserPool pool = createPoolAndUser();
- service.adminSetUserMFAPreference(pool.getId(), "alice", true, true);
+ service.adminSetUserMFAPreference(pool.getId(), "alice",
+ new CognitoService.MfaSettingsUpdate(true, true), CognitoService.MfaSettingsUpdate.NONE);
assertThrows(AwsException.class, () ->
- service.adminSetUserMFAPreference(pool.getId(), "alice", false, true));
+ service.adminSetUserMFAPreference(pool.getId(), "alice",
+ new CognitoService.MfaSettingsUpdate(false, true), CognitoService.MfaSettingsUpdate.NONE));
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
@@ -5792,9 +5796,11 @@ class CognitoServiceTest {
void adminSetUserMFAPreferenceDisablingEmailMfaClearsPreferredMfa() {
UserPool pool = createPoolAndUser();
- service.adminSetUserMFAPreference(pool.getId(), "alice", true, true);
+ service.adminSetUserMFAPreference(pool.getId(), "alice",
+ new CognitoService.MfaSettingsUpdate(true, true), CognitoService.MfaSettingsUpdate.NONE);
- service.adminSetUserMFAPreference(pool.getId(), "alice", false, null);
+ service.adminSetUserMFAPreference(pool.getId(), "alice",
+ new CognitoService.MfaSettingsUpdate(false, null), CognitoService.MfaSettingsUpdate.NONE);
CognitoUser user = service.adminGetUser(pool.getId(), "alice");