Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cognito): implement SetUserPoolMfaConfig (#2831)

Brian Taylor906717a510c7
diff --git a/compatibility-tests/sdk-test-node/tests/cognito.test.ts b/compatibility-tests/sdk-test-node/tests/cognito.test.ts
index f5ff589f38..9502cca4fb 100644
--- a/compatibility-tests/sdk-test-node/tests/cognito.test.ts
+++ b/compatibility-tests/sdk-test-node/tests/cognito.test.ts
@@ -22,6 +22,8 @@ import {
AdminAddUserToGroupCommand,
AdminRemoveUserFromGroupCommand,
AdminListGroupsForUserCommand,
+ SetUserPoolMfaConfigCommand,
+ GetUserPoolMfaConfigCommand,
} from '@aws-sdk/client-cognito-identity-provider';
import { makeClient, uniqueName, ENDPOINT, fetchLatestSesVerificationCode } from './setup';
@@ -243,3 +245,60 @@ describe('Cognito', () => {
poolId = '';
});
});
+
+describe('Cognito MFA configuration', () => {
+ let cognito: CognitoIdentityProviderClient;
+ let poolId: string;
+
+ beforeAll(async () => {
+ cognito = makeClient(CognitoIdentityProviderClient);
+ const pool = await cognito.send(
+ new CreateUserPoolCommand({ PoolName: `mfa-${uniqueName()}` })
+ );
+ poolId = pool.UserPool!.Id!;
+ });
+
+ afterAll(async () => {
+ if (poolId) {
+ await cognito
+ .send(new DeleteUserPoolCommand({ UserPoolId: poolId }))
+ .catch((error) => console.warn(`failed to delete MFA test pool ${poolId}`, error));
+ }
+ });
+
+ it('should report OFF and omit software-token config before it is set', async () => {
+ const config = await cognito.send(new GetUserPoolMfaConfigCommand({ UserPoolId: poolId }));
+ expect(config.MfaConfiguration).toBe('OFF');
+ // The live service returns only the factors that have been configured.
+ expect(config.SoftwareTokenMfaConfiguration).toBeUndefined();
+ });
+
+ it('should set and round-trip MFA configuration', async () => {
+ const set = await cognito.send(
+ new SetUserPoolMfaConfigCommand({
+ UserPoolId: poolId,
+ MfaConfiguration: 'OPTIONAL',
+ SoftwareTokenMfaConfiguration: { Enabled: true },
+ })
+ );
+ expect(set.MfaConfiguration).toBe('OPTIONAL');
+ expect(set.SoftwareTokenMfaConfiguration?.Enabled).toBe(true);
+
+ // What the Terraform provider reads back to decide whether
+ // mfa_configuration / software_token_mfa_configuration have drifted.
+ const got = await cognito.send(new GetUserPoolMfaConfigCommand({ UserPoolId: poolId }));
+ expect(got.MfaConfiguration).toBe('OPTIONAL');
+ expect(got.SoftwareTokenMfaConfiguration?.Enabled).toBe(true);
+ });
+
+ it('should reject an invalid MfaConfiguration', async () => {
+ await expect(
+ cognito.send(
+ new SetUserPoolMfaConfigCommand({
+ UserPoolId: poolId,
+ MfaConfiguration: 'SOMETIMES' as never,
+ })
+ )
+ ).rejects.toThrow();
+ });
+});
diff --git a/docs/services/cognito.md b/docs/services/cognito.md
index 80090fc840..9b3603bcb2 100644
--- a/docs/services/cognito.md
+++ b/docs/services/cognito.md
@@ -30,6 +30,8 @@ An action given a user pool ID that does not resolve returns `ResourceNotFoundEx
| ListUserPools | Lists local user pools visible in the request region. |
| UpdateUserPool | Updates mutable user pool settings and persisted user-pool tags. |
| DeleteUserPool | Deletes a local user pool and its related state. |
+| GetUserPoolMfaConfig | Returns the pool's MFA mode and, once configured, its software-token setting. |
+| SetUserPoolMfaConfig | Sets `MfaConfiguration` (`OFF`/`ON`/`OPTIONAL`) and `SoftwareTokenMfaConfiguration`. An absent `MfaConfiguration` means `OFF`, and turning MFA off drops the factor configuration with it. Validation follows the live service: `OFF` alongside a software-token, email or SMS factor is rejected, and `ON`/`OPTIONAL` with none of those three is rejected, in both cases on the member being present, not on its `Enabled` value. `WebAuthnConfiguration` sits outside both rules, as it does in AWS. SMS, email and WebAuthn configurations are validated and not stored: Floci cannot deliver those factors, so keeping the config would imply a capability it does not have. |
### User Pool Tags
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 8a4b4af260..86892d031e 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
@@ -51,6 +51,7 @@ public class CognitoJsonHandler {
case "UntagResource" -> handleUntagResource(request);
case "ListTagsForResource" -> handleListTagsForResource(request);
case "GetUserPoolMfaConfig" -> handleGetUserPoolMfaConfig(request);
+ case "SetUserPoolMfaConfig" -> handleSetUserPoolMfaConfig(request);
case "DeleteUserPool" -> handleDeleteUserPool(request);
case "CreateUserPoolClient" -> handleCreateUserPoolClient(request);
case "DescribeUserPoolClient" -> handleDescribeUserPoolClient(request);
@@ -197,9 +198,34 @@ public class CognitoJsonHandler {
private Response handleGetUserPoolMfaConfig(JsonNode request) {
UserPool pool = service.describeUserPool(request.path("UserPoolId").asText());
+ return Response.ok(buildMfaConfigResponse(pool)).build();
+ }
+
+ 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);
+ return Response.ok(buildMfaConfigResponse(pool)).build();
+ }
+
+ /**
+ * Shared by Get and Set, which answer with the same members. SoftwareTokenMfaConfiguration
+ * is omitted while unset, matching the live service, which returns only the factors that
+ * have been configured.
+ */
+ private ObjectNode buildMfaConfigResponse(UserPool pool) {
ObjectNode response = objectMapper.createObjectNode();
+ if (pool.getSoftwareTokenMfaEnabled() != null) {
+ response.putObject("SoftwareTokenMfaConfiguration")
+ .put("Enabled", pool.getSoftwareTokenMfaEnabled());
+ }
response.put("MfaConfiguration", pool.getMfaConfiguration());
- return Response.ok(response).build();
+ return response;
}
private Response handleDeleteUserPool(JsonNode request) {
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 fc0f8d3190..df63186512 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
@@ -368,6 +368,63 @@ public class CognitoService implements ResourceProvider {
return pool;
}
+ /**
+ * SetUserPoolMfaConfig. Stores the MFA mode and the software-token setting, which is
+ * what GetUserPoolMfaConfig reports back and what the Terraform provider reads to
+ * detect drift on mfa_configuration / software_token_mfa_configuration.
+ *
+ * <p>SMS, email and WebAuthn 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.
+ */
+ public UserPool setUserPoolMfaConfig(String id, String mfaConfiguration,
+ Boolean softwareTokenMfaEnabled,
+ boolean otherFactorConfigured) {
+ UserPool pool = describeUserPool(id);
+ // An absent MfaConfiguration means OFF, not "leave the current mode alone":
+ // measured against the live service, which resets a pool that was OPTIONAL back
+ // to OFF when the member is omitted.
+ String mode = mfaConfiguration != null ? mfaConfiguration : "OFF";
+ if (!List.of("OPTIONAL", "OFF", "ON").contains(mode)) {
+ throw new AwsException("InvalidParameterException",
+ "1 validation error detected: Value '" + mode
+ + "' at 'mfaConfiguration' failed to satisfy constraint: "
+ + "Member must satisfy enum value set: [OPTIONAL, OFF, ON]", 400);
+ }
+ // Presence, not value: the live service rejects OFF alongside
+ // SoftwareTokenMfaConfiguration{Enabled:false} just as it does Enabled:true, and
+ // conversely accepts ON alongside Enabled:false, so the member being there is what
+ // counts, despite the "must be enabled" wording of the second message.
+ boolean anyFactorConfigured = softwareTokenMfaEnabled != null || otherFactorConfigured;
+ if ("OFF".equals(mode) && anyFactorConfigured) {
+ throw new AwsException("InvalidParameterException",
+ "Invalid MFA configuration given, can't turn off MFA and configure an "
+ + "MFA together.", 400);
+ }
+ if (!"OFF".equals(mode) && !anyFactorConfigured) {
+ throw new AwsException("InvalidParameterException",
+ "Invalid MFA Configuration given. SMS MFA, Email MFA, or Software Token "
+ + "MFA must be enabled.", 400);
+ }
+ pool.setMfaConfiguration(mode);
+ if ("OFF".equals(mode)) {
+ // 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);
+ }
+ poolStore.put(id, pool);
+ return pool;
+ }
+
public List<UserPool> listUserPools() {
return poolStore.scan(k -> true);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
index 29153230cd..0c3165eac3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPool.java
@@ -35,6 +35,8 @@ public class UserPool {
private Map<String, Object> verificationMessageTemplate = new HashMap<>();
private String smsAuthenticationMessage;
private String mfaConfiguration = "OFF";
+ /** Null until SetUserPoolMfaConfig sets it; absent from responses while null, as AWS omits it. */
+ private Boolean softwareTokenMfaEnabled;
private Map<String, Object> deviceConfiguration = new HashMap<>();
private int estimatedNumberOfUsers = 0;
private Map<String, Object> emailConfiguration = new HashMap<>();
@@ -125,6 +127,10 @@ public class UserPool {
public void setSmsAuthenticationMessage(String smsAuthenticationMessage) { this.smsAuthenticationMessage = smsAuthenticationMessage; }
public String getMfaConfiguration() { return mfaConfiguration; }
+ public Boolean getSoftwareTokenMfaEnabled() { return softwareTokenMfaEnabled; }
+ public void setSoftwareTokenMfaEnabled(Boolean softwareTokenMfaEnabled) {
+ this.softwareTokenMfaEnabled = softwareTokenMfaEnabled;
+ }
public void setMfaConfiguration(String mfaConfiguration) { this.mfaConfiguration = mfaConfiguration; }
public Map<String, Object> getDeviceConfiguration() { return deviceConfiguration; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSetUserPoolMfaConfigIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSetUserPoolMfaConfigIntegrationTest.java
new file mode 100644
index 0000000000..39deb886d2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSetUserPoolMfaConfigIntegrationTest.java
@@ -0,0 +1,224 @@
+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 org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * SetUserPoolMfaConfig, and the round trip through GetUserPoolMfaConfig.
+ *
+ * <p>The response shape was measured against the live service, which returns only the
+ * factors that have been configured: a pool with software-token MFA answers
+ * {@code {"SoftwareTokenMfaConfiguration":{"Enabled":true},"MfaConfiguration":"OPTIONAL"}}
+ * and omits the SMS, email and WebAuthn members entirely.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class CognitoSetUserPoolMfaConfigIntegrationTest {
+
+ private static String poolId;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ @Order(1)
+ void createPool() throws Exception {
+ JsonNode pool = cognitoJson("CreateUserPool", """
+ {"PoolName":"MfaConfigTestPool"}
+ """);
+ poolId = pool.path("UserPool").path("Id").asText();
+ assertTrue(!poolId.isEmpty(), "pool id");
+ }
+
+ @Test
+ @Order(2)
+ void softwareTokenConfigurationIsOmittedUntilItIsSet() throws Exception {
+ // Measured: the live service returns only configured factors, so an untouched
+ // pool carries no SoftwareTokenMfaConfiguration member at all.
+ JsonNode config = cognitoJson("GetUserPoolMfaConfig",
+ """
+ {"UserPoolId":"%s"}
+ """.formatted(poolId));
+ assertEquals("OFF", config.path("MfaConfiguration").asText());
+ assertTrue(config.path("SoftwareTokenMfaConfiguration").isMissingNode(),
+ "SoftwareTokenMfaConfiguration should be absent before it is configured");
+ }
+
+ @Test
+ @Order(3)
+ void setsMfaConfigurationAndSoftwareTokenAndReturnsThem() throws Exception {
+ JsonNode set = cognitoJson("SetUserPoolMfaConfig", """
+ {
+ "UserPoolId":"%s",
+ "MfaConfiguration":"OPTIONAL",
+ "SoftwareTokenMfaConfiguration":{"Enabled":true}
+ }
+ """.formatted(poolId));
+ assertEquals("OPTIONAL", set.path("MfaConfiguration").asText());
+ assertTrue(set.path("SoftwareTokenMfaConfiguration").path("Enabled").asBoolean());
+
+ // The round trip is what the Terraform provider reads to decide whether
+ // mfa_configuration / software_token_mfa_configuration have drifted.
+ JsonNode got = cognitoJson("GetUserPoolMfaConfig", """
+ {"UserPoolId":"%s"}
+ """.formatted(poolId));
+ assertEquals("OPTIONAL", got.path("MfaConfiguration").asText());
+ assertTrue(got.path("SoftwareTokenMfaConfiguration").path("Enabled").asBoolean());
+ }
+
+ @Test
+ @Order(4)
+ void describeUserPoolReflectsTheNewMfaMode() throws Exception {
+ cognitoJson("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"ON",
+ "SoftwareTokenMfaConfiguration":{"Enabled":true}}
+ """.formatted(poolId));
+
+ JsonNode pool = cognitoJson("DescribeUserPool", """
+ {"UserPoolId":"%s"}
+ """.formatted(poolId));
+ assertEquals("ON", pool.path("UserPool").path("MfaConfiguration").asText());
+ }
+
+ @Test
+ @Order(5)
+ void omittingMfaConfigurationWithAFactorIsRejected() {
+ // Measured: an absent MfaConfiguration means OFF, not "leave the mode alone", so
+ // sending a factor alongside it is turning MFA off and configuring it at once.
+ String body = cognitoAction("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","SoftwareTokenMfaConfiguration":{"Enabled":false}}
+ """.formatted(poolId))
+ .then().statusCode(400).extract().asString();
+ assertTrue(body.contains("InvalidParameterException"), body);
+ assertTrue(body.contains("can't turn off MFA and configure an MFA together"), body);
+ }
+
+ @Test
+ @Order(6)
+ void turningMfaOffAlongsideEmailOrSmsIsRejected() {
+ // Measured: the rule covers EmailMfaConfiguration and SmsMfaConfiguration too, not
+ // just the software token, and it fires on the member being present rather than on
+ // its value.
+ for (String factor : new String[] {
+ "\"EmailMfaConfiguration\":{\"Message\":\"code {####}\",\"Subject\":\"code\"}",
+ "\"SmsMfaConfiguration\":{\"SmsAuthenticationMessage\":\"code {####}\"}"}) {
+ String body = cognitoAction("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"OFF",%s}
+ """.formatted(poolId, factor))
+ .then().statusCode(400).extract().asString();
+ assertTrue(body.contains("InvalidParameterException"), body);
+ assertTrue(body.contains("can't turn off MFA and configure an MFA together"), body);
+ }
+ }
+
+ @Test
+ @Order(7)
+ void enablingMfaWithNoFactorAtAllIsRejected() {
+ for (String mode : new String[] {"ON", "OPTIONAL"}) {
+ String body = cognitoAction("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"%s"}
+ """.formatted(poolId, mode))
+ .then().statusCode(400).extract().asString();
+ assertTrue(body.contains("InvalidParameterException"), body);
+ assertTrue(body.contains("SMS MFA, Email MFA, or Software Token MFA must be enabled"),
+ body);
+ }
+ }
+
+ @Test
+ @Order(8)
+ void omittingMfaConfigurationEntirelyResetsThePoolToOff() throws Exception {
+ // The pool is ON with a software-token factor at this point. Sending only the
+ // pool id resets it: the live service answers OFF and drops the factor member.
+ JsonNode set = cognitoJson("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s"}
+ """.formatted(poolId));
+ assertEquals("OFF", set.path("MfaConfiguration").asText());
+ assertTrue(set.path("SoftwareTokenMfaConfiguration").isMissingNode(),
+ "turning MFA off drops the factor configuration with it");
+
+ JsonNode got = cognitoJson("GetUserPoolMfaConfig", """
+ {"UserPoolId":"%s"}
+ """.formatted(poolId));
+ assertEquals("OFF", got.path("MfaConfiguration").asText());
+ assertTrue(got.path("SoftwareTokenMfaConfiguration").isMissingNode());
+ }
+
+ @Test
+ @Order(9)
+ void aDisabledFactorStillCountsAsConfigured() throws Exception {
+ // The message says "must be enabled", but the live service accepts ON alongside
+ // SoftwareTokenMfaConfiguration{Enabled:false}: presence is what it checks.
+ JsonNode set = cognitoJson("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"ON",
+ "SoftwareTokenMfaConfiguration":{"Enabled":false}}
+ """.formatted(poolId));
+ assertEquals("ON", set.path("MfaConfiguration").asText());
+ assertEquals(false, set.path("SoftwareTokenMfaConfiguration").path("Enabled").asBoolean());
+ }
+
+ @Test
+ @Order(10)
+ void webAuthnIsOutsideTheFactorRulesInBothDirections() throws Exception {
+ // Measured: WebAuthnConfiguration is accepted alongside OFF, where every other
+ // factor is rejected, and it does not satisfy the "must be enabled" rule either:
+ // OPTIONAL with WebAuthn alone is refused.
+ JsonNode off = cognitoJson("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"OFF",
+ "WebAuthnConfiguration":{"RelyingPartyId":"example.com",
+ "UserVerification":"preferred"}}
+ """.formatted(poolId));
+ assertEquals("OFF", off.path("MfaConfiguration").asText());
+
+ String body = cognitoAction("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"OPTIONAL",
+ "WebAuthnConfiguration":{"RelyingPartyId":"example.com",
+ "UserVerification":"preferred"}}
+ """.formatted(poolId))
+ .then().statusCode(400).extract().asString();
+ assertTrue(body.contains("SMS MFA, Email MFA, or Software Token MFA must be enabled"), body);
+ }
+
+ @Test
+ @Order(11)
+ void invalidMfaConfigurationIsRejected() {
+ String body = cognitoAction("SetUserPoolMfaConfig", """
+ {"UserPoolId":"%s","MfaConfiguration":"SOMETIMES"}
+ """.formatted(poolId))
+ .then().statusCode(400).extract().asString();
+ assertTrue(body.contains("InvalidParameterException"), body);
+ assertTrue(body.contains("Member must satisfy enum value set: [OPTIONAL, OFF, ON]"), body);
+ }
+
+ @Test
+ @Order(12)
+ void unknownPoolIsResourceNotFound() {
+ String body = cognitoAction("SetUserPoolMfaConfig", """
+ {"UserPoolId":"ap-southeast-1_nosuchpool","MfaConfiguration":"OFF"}
+ """)
+ .then().statusCode(400).extract().asString();
+ assertTrue(body.contains("ResourceNotFoundException"), body);
+ }
+
+ @Test
+ @Order(13)
+ void cleanup_deletePool() {
+ cognitoAction("DeleteUserPool", """
+ {"UserPoolId":"%s"}
+ """.formatted(poolId))
+ .then().statusCode(200);
+ }
+}