fix(cloudformation): apply EnabledMfas on AWS::Cognito::UserPool (#7046)

* fix(cloudformation): apply EnabledMfas on AWS::Cognito::UserPool

* docs(cloudformation): move the EnabledMfas note to the resource-type table source

* fix(cloudformation): drop the MFA factors EnabledMfas no longer lists on update

* fix(cognito): apply EnabledMfas mode and factors in one write

* fix(cloudformation): roll back EnabledMfas with the rest of the user pool

* fix(cognito): serialize whole-pool writes behind a per-pool lock

replaceUserPoolMfaConfig stores a copy of the pool, so a TagResource that
landed between the copy and the write was lost. Tag and untag locked the
pool instance, which the copy replaces, so they did not exclude it.

Every write that reads a pool and stores it back whole now holds a lock
keyed by the pool id and reads the pool inside it.
This commit is contained in:
Vinícius Ribeiro authored and GitHub committed 2026-10-31 05:15:29 -04:00
1 parent e714fd9594
commit ebdac90574
6 files changed
+447 -37

No files matched your search

@@ -15,6 +15,8 @@ import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsAction;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -440,6 +442,187 @@ class CognitoCfnIntegrationTest {
.body("__type", equalTo("ResourceNotFoundException"));
}
/**
* EnabledMfas is not a CreateUserPool member: CloudFormation applies it with
* SetUserPoolMfaConfig, so GetUserPoolMfaConfig reports the factors the template enabled.
*/
@Test
void enabledMfasTurnsOnTheListedFactors() throws Exception {
String stack = "cognito-cfn-enabled-mfas-it";
cloudFormation(stack, "CreateStack", """
{
"Resources": {
"TotpPool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {
"UserPoolName": "cognito-cfn-totp-pool",
"MfaConfiguration": "ON",
"EnabledMfas": ["SOFTWARE_TOKEN_MFA"]
}
},
"SmsEmailPool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {
"UserPoolName": "cognito-cfn-sms-email-pool",
"MfaConfiguration": "OPTIONAL",
"EnabledMfas": ["SMS_MFA", "EMAIL_OTP"],
"SmsAuthenticationMessage": "Your code is {####}",
"SmsConfiguration": {"SnsCallerArn": "arn:aws:iam::000000000000:role/sms", "ExternalId": "ext"},
"EmailAuthenticationMessage": "Your email code is {####}",
"EmailAuthenticationSubject": "Sign-in code"
}
}
},
"Outputs": {
"TotpPoolId": {"Value": {"Ref": "TotpPool"}},
"SmsEmailPoolId": {"Value": {"Ref": "SmsEmailPool"}}
}
}
""");
String stacks = describeStacks(stack, "CREATE_COMPLETE");
cognitoAction("GetUserPoolMfaConfig", "{\"UserPoolId\": \"" + outputValue(stacks, "TotpPoolId") + "\"}")
.then().statusCode(200)
.body("MfaConfiguration", equalTo("ON"))
.body("SoftwareTokenMfaConfiguration.Enabled", equalTo(true));
cognitoAction("GetUserPoolMfaConfig", "{\"UserPoolId\": \"" + outputValue(stacks, "SmsEmailPoolId") + "\"}")
.then().statusCode(200)
.body("MfaConfiguration", equalTo("OPTIONAL"))
.body("SmsMfaConfiguration.SmsAuthenticationMessage", equalTo("Your code is {####}"))
.body("SmsMfaConfiguration.SmsConfiguration.ExternalId", equalTo("ext"))
.body("EmailMfaConfiguration.Message", equalTo("Your email code is {####}"))
.body("EmailMfaConfiguration.Subject", equalTo("Sign-in code"));
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
/** An update leaves exactly the factors the new template lists, as CloudFormation does on AWS. */
@Test
void anUpdateDropsTheFactorsEnabledMfasNoLongerLists() throws Exception {
String stack = "cognito-cfn-enabled-mfas-update-it";
cloudFormation(stack, "CreateStack", enabledMfasTemplate(
"\"MfaConfiguration\": \"ON\", \"EnabledMfas\": [\"SOFTWARE_TOKEN_MFA\"]"));
String poolId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "PoolId");
cloudFormation(stack, "UpdateStack", enabledMfasTemplate(
"\"MfaConfiguration\": \"OPTIONAL\", \"EnabledMfas\": [\"SMS_MFA\"], "
+ "\"SmsConfiguration\": {\"SnsCallerArn\": \"arn:aws:iam::000000000000:role/sms\"}"));
describeStacks(stack, "UPDATE_COMPLETE");
cognitoAction("GetUserPoolMfaConfig", "{\"UserPoolId\": \"" + poolId + "\"}")
.then().statusCode(200)
.body("MfaConfiguration", equalTo("OPTIONAL"))
.body("SoftwareTokenMfaConfiguration", nullValue())
.body("SmsMfaConfiguration.SmsConfiguration.SnsCallerArn", equalTo("arn:aws:iam::000000000000:role/sms"));
cloudFormation(stack, "UpdateStack", enabledMfasTemplate("\"MfaConfiguration\": \"OFF\""));
describeStacks(stack, "UPDATE_COMPLETE");
cognitoAction("GetUserPoolMfaConfig", "{\"UserPoolId\": \"" + poolId + "\"}")
.then().statusCode(200)
.body("MfaConfiguration", equalTo("OFF"))
.body("SoftwareTokenMfaConfiguration", nullValue())
.body("SmsMfaConfiguration", nullValue());
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
/** OFF with a listed factor is refused by SetUserPoolMfaConfig after the pool exists. */
@Test
void aRefusedEnabledMfasOnCreateRemovesThePool() throws Exception {
String stack = "cognito-cfn-mfa-refused-create-it";
String poolName = "cognito-cfn-mfa-refused-create-pool";
cloudFormation(stack, "CreateStack", enabledMfasTemplate(poolName,
"\"MfaConfiguration\": \"OFF\", \"EnabledMfas\": [\"SOFTWARE_TOKEN_MFA\"]", ""));
awaitStackStatus(stack, "ROLLBACK_COMPLETE");
cognitoAction("ListUserPools", "{\"MaxResults\": 60}")
.then().statusCode(200)
.body("UserPools.Name", not(hasItem(poolName)));
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
@Test
void aRefusedEnabledMfasOnUpdatePutsThePoolBack() throws Exception {
String stack = "cognito-cfn-mfa-refused-update-it";
String poolName = "cognito-cfn-mfa-refused-update-pool";
cloudFormation(stack, "CreateStack", enabledMfasTemplate(poolName,
"\"MfaConfiguration\": \"ON\", \"EnabledMfas\": [\"SOFTWARE_TOKEN_MFA\"]", ""));
String poolId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "PoolId");
cloudFormation(stack, "UpdateStack", enabledMfasTemplate(poolName + "-v2",
"\"MfaConfiguration\": \"OFF\", \"EnabledMfas\": [\"SOFTWARE_TOKEN_MFA\"]", ""));
awaitStackStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
cognitoAction("DescribeUserPool", "{\"UserPoolId\": \"" + poolId + "\"}")
.then().statusCode(200)
.body("UserPool.Name", equalTo(poolName));
assertMfa(poolId, "ON", true, false);
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
@Test
void aLaterFailurePutsTheReplacedFactorsBack() throws Exception {
String stack = "cognito-cfn-mfa-later-failure-it";
String poolName = "cognito-cfn-mfa-later-failure-pool";
cloudFormation(stack, "CreateStack", enabledMfasTemplate(poolName,
"\"MfaConfiguration\": \"ON\", \"EnabledMfas\": [\"SOFTWARE_TOKEN_MFA\"]", ""));
String poolId = outputValue(describeStacks(stack, "CREATE_COMPLETE"), "PoolId");
String failingSecret = """
,
"BadSecret": {
"Type": "AWS::SecretsManager::Secret",
"DependsOn": "Pool",
"Properties": {
"Name": "cognito-cfn-mfa-later-failure",
"SecretString": "explicit",
"GenerateSecretString": {"PasswordLength": 32}
}
}""";
cloudFormation(stack, "UpdateStack", enabledMfasTemplate(poolName,
"\"MfaConfiguration\": \"OPTIONAL\", \"EnabledMfas\": [\"SMS_MFA\"], "
+ "\"SmsConfiguration\": {\"SnsCallerArn\": \"arn:aws:iam::000000000000:role/sms\"}",
failingSecret));
awaitStackStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
assertMfa(poolId, "ON", true, false);
cloudFormation(stack, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(stack);
}
private static void assertMfa(String poolId, String mode, boolean softwareToken, boolean sms) {
cognitoAction("GetUserPoolMfaConfig", "{\"UserPoolId\": \"" + poolId + "\"}")
.then().statusCode(200)
.body("MfaConfiguration", equalTo(mode))
.body("SoftwareTokenMfaConfiguration.Enabled", softwareToken ? equalTo(true) : nullValue())
.body("SmsMfaConfiguration", sms ? notNullValue() : nullValue());
}
private static String enabledMfasTemplate(String mfaProperties) {
return enabledMfasTemplate("cognito-cfn-mfa-update-pool", mfaProperties, "");
}
private static String enabledMfasTemplate(String poolName, String mfaProperties, String extraResources) {
return """
{
"Resources": {
"Pool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {"UserPoolName": "%s", %s}
}%s
},
"Outputs": {"PoolId": {"Value": {"Ref": "Pool"}}}
}
""".formatted(poolName, mfaProperties, extraResources);
}
private static String deletionProtectionTemplate(String deletionProtection) {
return """
{
@@ -0,0 +1,104 @@
package io.github.hectorvent.floci.services.cognito;
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.model.UserPool;
import io.github.hectorvent.floci.testing.MutableClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.CyclicBarrier;
import static org.junit.jupiter.api.Assertions.assertEquals;
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;
/**
* replaceUserPoolMfaConfig, the CloudFormation EnabledMfas path: the pool ends up with exactly the
* given factors, and the new settings are stored in one write without touching the pool a
* concurrent sign-in may already be reading.
*/
class CognitoReplaceMfaConfigTest {
private CognitoService service;
private String poolId;
@BeforeEach
void setUp() {
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, new MutableClock());
poolId = service.createUserPool(Map.of("PoolName", "ReplaceMfaPool"), "us-east-1").getId();
service.setUserPoolMfaConfig(poolId, "ON", true, null,
Map.of("Subject", "Code", "Message", "Your code is {####}"), null);
}
@Test
void factorsThatAreNotGivenAreTurnedOff() {
service.replaceUserPoolMfaConfig(poolId, "OPTIONAL", null, Map.of("SmsAuthenticationMessage", "{####}"), null);
UserPool pool = service.describeUserPool(poolId);
assertEquals("OPTIONAL", pool.getMfaConfiguration());
assertNull(pool.getSoftwareTokenMfaEnabled());
assertNull(pool.getEmailMfaConfiguration());
assertNotNull(pool.getSmsMfaConfiguration());
}
@Test
void thePoolAReaderAlreadyHoldsKeepsItsSettings() {
UserPool before = service.describeUserPool(poolId);
service.replaceUserPoolMfaConfig(poolId, "OPTIONAL", null, Map.of(), null);
assertEquals("ON", before.getMfaConfiguration());
assertTrue(before.getSoftwareTokenMfaEnabled());
assertNotNull(before.getEmailMfaConfiguration());
assertEquals("OPTIONAL", service.describeUserPool(poolId).getMfaConfiguration());
}
@Test
void tagsAddedWhileTheMfaSettingsAreReplacedAreKept() throws Exception {
String arn = service.describeUserPool(poolId).getArn();
int tags = 200;
CyclicBarrier start = new CyclicBarrier(2);
Thread tagger = new Thread(() -> {
try {
start.await();
for (int i = 0; i < tags; i++) {
service.tagResource(arn, Map.of("key" + i, "value"));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
});
tagger.start();
start.await();
while (tagger.isAlive()) {
service.replaceUserPoolMfaConfig(poolId, "OPTIONAL", true, null, null);
}
tagger.join();
assertEquals(tags, service.listTagsForResource(arn).size());
}
@Test
void anInvalidConfigurationLeavesThePoolUnchanged() {
AwsException error = assertThrows(AwsException.class,
() -> service.replaceUserPoolMfaConfig(poolId, "ON", null, null, null));
assertEquals("InvalidParameterException", error.getErrorCode());
UserPool pool = service.describeUserPool(poolId);
assertEquals("ON", pool.getMfaConfiguration());
assertTrue(pool.getSoftwareTokenMfaEnabled());
assertNotNull(pool.getEmailMfaConfiguration());
}
}