From ebdac905743519d075a095e01c145e5f44652a10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ribeiro?= <9574254+vinirib@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:15:29 -0300 Subject: [PATCH] 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. --- docs/services/cloudformation.md | 2 +- .../provisioners/CognitoCfnProvisioner.java | 60 ++++++ .../services/cognito/CognitoService.java | 133 +++++++++---- .../CognitoCfnIntegrationTest.java | 183 ++++++++++++++++++ .../cognito/CognitoReplaceMfaConfigTest.java | 104 ++++++++++ tools/docs/cfn_resource_types.yaml | 2 +- 6 files changed, 447 insertions(+), 37 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/CognitoReplaceMfaConfigTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index def9ae044e..888b9b6715 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -203,7 +203,7 @@ cross-resource references. | CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` | | CodeBuild | `Project` | | Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` | -| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `/`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` | +| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `/`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` | | ACM | `Certificate` | | EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `ApiDestination`, `Archive` (`KmsKeyIdentifier` is ignored) | | EventBridge Scheduler | `Schedule`, `ScheduleGroup` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisioner.java index e191d27ac7..807987b1f3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoCfnProvisioner.java @@ -15,6 +15,7 @@ import org.jboss.logging.Logger; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -228,10 +229,16 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner { req.put("UserPoolTags", tags); } + boolean enabledMfasManaged = declaresEnabledMfas(props, ctx) || ctx.previouslyDeclared("EnabledMfas"); UserPool pool; if (ctx.isUpdate()) { req.put("UserPoolId", ctx.priorPhysicalId()); snapshot(r, cognitoService.userPoolSettings(ctx.priorPhysicalId())); + if (enabledMfasManaged) { + // The MFA mode goes out together with its factors in applyEnabledMfas, so the pool + // never pairs the new mode with the old factors. + req.remove("MfaConfiguration"); + } pool = cognitoService.updateUserPool(req, ctx.region()); } else { pool = cognitoService.createUserPool(req, ctx.region()); @@ -245,6 +252,59 @@ public class CognitoCfnProvisioner implements CfnResourceProvisioner { // mints tokens with, so a template wiring it into a JWT authorizer validates locally. r.getAttributes().put("ProviderName", AwsEndpoints.host("cognito-idp", ctx.region()) + "/" + pool.getId()); r.getAttributes().put("ProviderURL", cognitoService.getIssuer(pool.getId())); + if (enabledMfasManaged) { + // The pool is already created or updated here, so a refused MFA configuration has to + // undo that: a new pool is deleted, an updated one gets its snapshot back. + String poolId = pool.getId(); + CfnRollback.guarded(r, ctx, !ctx.isUpdate(), + () -> delete(USER_POOL, poolId, ctx.region()), + () -> rollbackUpdate(r), + () -> applyEnabledMfas(poolId, props, ctx)); + } + } + + private static boolean declaresEnabledMfas(JsonNode props, ProvisionContext ctx) { + JsonNode enabledMfas = props != null ? ctx.engine().resolveNode(props).path("EnabledMfas") : null; + return enabledMfas != null && enabledMfas.isArray() && !enabledMfas.isEmpty(); + } + + /** + * EnabledMfas only exists in CloudFormation: CreateUserPool and UpdateUserPool have no such + * member, so CloudFormation turns it into SetUserPoolMfaConfig. The pool ends up with exactly + * the listed factors, together with the template's MfaConfiguration. SMS_MFA takes the pool's + * SmsAuthenticationMessage and SmsConfiguration, EMAIL_OTP its EmailAuthenticationMessage and + * EmailAuthenticationSubject. + */ + private void applyEnabledMfas(String poolId, JsonNode props, ProvisionContext ctx) { + JsonNode resolved = props != null ? ctx.engine().resolveNode(props) : MAPPER.createObjectNode(); + Set factors = new HashSet<>(); + resolved.path("EnabledMfas").forEach(factor -> factors.add(factor.asText())); + + Boolean softwareTokenEnabled = factors.contains("SOFTWARE_TOKEN_MFA") ? Boolean.TRUE : null; + Map smsMfaConfiguration = null; + if (factors.contains("SMS_MFA")) { + smsMfaConfiguration = new LinkedHashMap<>(); + putIfText(smsMfaConfiguration, "SmsAuthenticationMessage", resolved.path("SmsAuthenticationMessage")); + if (resolved.path("SmsConfiguration").isObject()) { + smsMfaConfiguration.put("SmsConfiguration", jsonObjectToMap(resolved.path("SmsConfiguration"))); + } + } + Map emailMfaConfiguration = null; + if (factors.contains("EMAIL_OTP")) { + emailMfaConfiguration = new LinkedHashMap<>(); + putIfText(emailMfaConfiguration, "Message", resolved.path("EmailAuthenticationMessage")); + putIfText(emailMfaConfiguration, "Subject", resolved.path("EmailAuthenticationSubject")); + } + String mfaConfiguration = resolved.path("MfaConfiguration").isTextual() + ? resolved.path("MfaConfiguration").asText() : null; + cognitoService.replaceUserPoolMfaConfig(poolId, mfaConfiguration, softwareTokenEnabled, + smsMfaConfiguration, emailMfaConfiguration); + } + + private static void putIfText(Map target, String key, JsonNode value) { + if (value.isTextual()) { + target.put(key, value.asText()); + } } private void provisionUserPoolClient(StackResource r, JsonNode props, ProvisionContext ctx) { 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 a2f79f9841..a7aa207d5e 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 @@ -191,6 +191,7 @@ public class CognitoService implements ResourceProvider { private final TlsCertificateManager certificateManager; private final boolean enforceTokenValidityLimits; private final Object[] userLocks = newUserLockStripes(); + private final Object[] poolLocks = newUserLockStripes(); // Reserve names per account through registration callbacks, without blocking their admin requests. private final Set userCreatesInFlight = ConcurrentHashMap.newKeySet(); @@ -211,6 +212,15 @@ public class CognitoService implements ResourceProvider { return userLocks[Math.floorMod(key.hashCode(), USER_LOCK_STRIPES)]; } + /** + * Held by every write that reads a pool and stores it back whole, so one write never stores a + * pool read before another write landed. The lock is per pool id, not per instance, since some + * of these writes store a new copy in place of the instance another write is holding. + */ + private Object poolLock(String poolId) { + return poolLocks[Math.floorMod(poolId.hashCode(), USER_LOCK_STRIPES)]; + } + @Inject public CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig, RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService, @@ -446,21 +456,23 @@ public class CognitoService implements ResourceProvider { public UserPool updateUserPool(Map request, String region) { String id = (String) request.get("UserPoolId"); - UserPool pool = describeUserPool(id); - UserPool updatedPool = MAPPER.convertValue(pool, UserPool.class); + synchronized (poolLock(id)) { + UserPool pool = describeUserPool(id); + UserPool updatedPool = MAPPER.convertValue(pool, UserPool.class); - populateUserPool(updatedPool, request); - if (request.containsKey("LambdaConfig")) { - requireCustomSenderKey(updatedPool, false, region); - } - if (request.get("PoolName") instanceof String poolName && !poolName.isBlank()) { - updatedPool.setName(poolName); - } + populateUserPool(updatedPool, request); + if (request.containsKey("LambdaConfig")) { + requireCustomSenderKey(updatedPool, false, region); + } + if (request.get("PoolName") instanceof String poolName && !poolName.isBlank()) { + updatedPool.setName(poolName); + } - updatedPool.setLastModifiedDate(System.currentTimeMillis() / 1000L); - poolStore.put(id, updatedPool); - LOG.infov("Updated User Pool: {0}", id); - return updatedPool; + updatedPool.setLastModifiedDate(System.currentTimeMillis() / 1000L); + poolStore.put(id, updatedPool); + LOG.infov("Updated User Pool: {0}", id); + return updatedPool; + } } /** @@ -481,16 +493,21 @@ public class CognitoService implements ResourceProvider { * Everything else on the pool, its users and signing keys among them, stays as it is now. */ public UserPool restoreUserPoolSettings(UserPool settings) { - UserPool pool = describeUserPool(settings.getId()); - UserPool restored = MAPPER.convertValue(pool, UserPool.class); - copyUserPoolSettings(MAPPER.convertValue(settings, UserPool.class), restored); - restored.setLastModifiedDate(System.currentTimeMillis() / 1000L); - poolStore.put(restored.getId(), restored); - LOG.infov("Restored User Pool settings: {0}", restored.getId()); - return restored; + synchronized (poolLock(settings.getId())) { + UserPool pool = describeUserPool(settings.getId()); + UserPool restored = MAPPER.convertValue(pool, UserPool.class); + copyUserPoolSettings(MAPPER.convertValue(settings, UserPool.class), restored); + restored.setLastModifiedDate(System.currentTimeMillis() / 1000L); + poolStore.put(restored.getId(), restored); + LOG.infov("Restored User Pool settings: {0}", restored.getId()); + return restored; + } } - /** The name and every field {@code populateUserPool} sets, which is what an update can change. */ + /** + * The name, every field {@code populateUserPool} sets and the MFA factors, which is what an + * update can change: CloudFormation sets the factors of a pool's EnabledMfas. + */ private static void copyUserPoolSettings(UserPool from, UserPool to) { to.setName(from.getName()); to.setPolicies(from.getPolicies()); @@ -506,6 +523,9 @@ public class CognitoService implements ResourceProvider { to.setVerificationMessageTemplate(from.getVerificationMessageTemplate()); to.setSmsAuthenticationMessage(from.getSmsAuthenticationMessage()); to.setMfaConfiguration(from.getMfaConfiguration()); + to.setSoftwareTokenMfaEnabled(from.getSoftwareTokenMfaEnabled()); + to.setSmsMfaConfiguration(from.getSmsMfaConfiguration()); + to.setEmailMfaConfiguration(from.getEmailMfaConfiguration()); to.setDeviceConfiguration(from.getDeviceConfiguration()); to.setEmailConfiguration(from.getEmailConfiguration()); to.setSmsConfiguration(from.getSmsConfiguration()); @@ -519,6 +539,12 @@ public class CognitoService implements ResourceProvider { } public void addCustomAttributes(String userPoolId, List> customAttributes) { + synchronized (poolLock(userPoolId)) { + addCustomAttributesUnderPoolLock(userPoolId, customAttributes); + } + } + + private void addCustomAttributesUnderPoolLock(String userPoolId, List> customAttributes) { UserPool pool = describeUserPool(userPoolId); List> schema = pool.getSchemaAttributes(); if (schema == null) { @@ -810,8 +836,41 @@ public class CognitoService implements ResourceProvider { Map smsMfaConfiguration, Map emailMfaConfiguration, WebAuthnConfiguration webAuthnConfiguration) { + synchronized (poolLock(id)) { + UserPool pool = describeUserPool(id); + applyMfaConfig(pool, mfaConfiguration, softwareTokenMfaEnabled, smsMfaConfiguration, + emailMfaConfiguration, webAuthnConfiguration, false); + poolStore.put(id, pool); + return pool; + } + } + + /** + * SetUserPoolMfaConfig where a factor that is not given is turned off instead of kept, which is + * how CloudFormation applies a user pool's EnabledMfas. The settings are built on a copy and + * stored in one write, so a concurrent sign-in never reads the pool between its old and new + * MFA settings, and under the pool lock, so a concurrent tag or update is kept. + */ + public UserPool replaceUserPoolMfaConfig(String id, String mfaConfiguration, + Boolean softwareTokenMfaEnabled, + Map smsMfaConfiguration, + Map emailMfaConfiguration) { + synchronized (poolLock(id)) { + UserPool pool = MAPPER.convertValue(describeUserPool(id), UserPool.class); + applyMfaConfig(pool, mfaConfiguration, softwareTokenMfaEnabled, smsMfaConfiguration, + emailMfaConfiguration, null, true); + poolStore.put(id, pool); + return pool; + } + } + + private void applyMfaConfig(UserPool pool, String mfaConfiguration, + Boolean softwareTokenMfaEnabled, + Map smsMfaConfiguration, + Map emailMfaConfiguration, + WebAuthnConfiguration webAuthnConfiguration, + boolean replaceFactors) { boolean otherFactorConfigured = smsMfaConfiguration != null || emailMfaConfiguration != null; - UserPool pool = describeUserPool(id); if (webAuthnConfiguration != null) { validateWebAuthnConfiguration(webAuthnConfiguration); } @@ -848,9 +907,12 @@ public class CognitoService implements ResourceProvider { pool.setSmsMfaConfiguration(null); pool.setEmailMfaConfiguration(null); } else { - if (softwareTokenMfaEnabled != null) { + if (softwareTokenMfaEnabled != null || replaceFactors) { pool.setSoftwareTokenMfaEnabled(softwareTokenMfaEnabled); } + if (smsMfaConfiguration == null && replaceFactors) { + pool.setSmsMfaConfiguration(null); + } if (smsMfaConfiguration != null) { pool.setSmsMfaConfiguration(new LinkedHashMap<>(smsMfaConfiguration)); if (smsMfaConfiguration.get("SmsAuthenticationMessage") instanceof String message) { @@ -862,15 +924,14 @@ public class CognitoService implements ResourceProvider { pool.setSmsConfiguration(copy); } } - if (emailMfaConfiguration != null) { - pool.setEmailMfaConfiguration(new LinkedHashMap<>(emailMfaConfiguration)); + if (emailMfaConfiguration != null || replaceFactors) { + pool.setEmailMfaConfiguration(emailMfaConfiguration != null + ? new LinkedHashMap<>(emailMfaConfiguration) : null); } } if (webAuthnConfiguration != null) { pool.setWebAuthnConfiguration(webAuthnConfiguration); } - poolStore.put(id, pool); - return pool; } private static void validateWebAuthnConfiguration(WebAuthnConfiguration configuration) { @@ -989,8 +1050,8 @@ public class CognitoService implements ResourceProvider { throw new AwsException("InvalidParameterException", "Tags are required", 400); } ReservedTags.rejectReservedTagsOnUpdate(tags); - UserPool pool = describeUserPoolByArn(resourceArn); - synchronized (pool) { + synchronized (poolLock(extractUserPoolIdFromArn(resourceArn))) { + UserPool pool = describeUserPoolByArn(resourceArn); pool.setUserPoolTags(mergeUserPoolTags(pool.getUserPoolTags(), tags)); pool.setLastModifiedDate(System.currentTimeMillis() / 1000L); poolStore.put(pool.getId(), pool); @@ -1001,8 +1062,8 @@ public class CognitoService implements ResourceProvider { if (tagKeys == null || tagKeys.isEmpty()) { throw new AwsException("InvalidParameterException", "TagKeys are required", 400); } - UserPool pool = describeUserPoolByArn(resourceArn); - synchronized (pool) { + synchronized (poolLock(extractUserPoolIdFromArn(resourceArn))) { + UserPool pool = describeUserPoolByArn(resourceArn); pool.setUserPoolTags(removeUserPoolTags(pool.getUserPoolTags(), tagKeys)); pool.setLastModifiedDate(System.currentTimeMillis() / 1000L); poolStore.put(pool.getId(), pool); @@ -2015,10 +2076,12 @@ public class CognitoService implements ResourceProvider { validateLogConfigurations(logConfigurations); rejectUnusableEventSources(logConfigurations); - UserPool pool = describeUserPool(userPoolId); - pool.setLogConfigurations(new ArrayList<>(logConfigurations)); - poolStore.put(userPoolId, pool); - return pool; + synchronized (poolLock(userPoolId)) { + UserPool pool = describeUserPool(userPoolId); + pool.setLogConfigurations(new ArrayList<>(logConfigurations)); + poolStore.put(userPoolId, pool); + return pool; + } } public UserPool getLogDeliveryConfiguration(String userPoolId) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java index 6812b93329..982a7374b0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java @@ -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 """ { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoReplaceMfaConfigTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoReplaceMfaConfigTest.java new file mode 100644 index 0000000000..6e2c71b0f5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoReplaceMfaConfigTest.java @@ -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()); + } +} diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index d83cde40a1..3ef05feb98 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -210,7 +210,7 @@ notes: AWS::Route53::RecordSetGroup: 'written in one change batch, so a record set that cannot be written leaves the zone unchanged; every record set must be in the group''s hosted zone' Custom::DynamoDBReplica: applied natively against DynamoDB, not via a provider Lambda AWS::DynamoDB::Table: '`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one' - AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `/`' + AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `/`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS' AWS::SES::EmailIdentity: 'BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS''s region- and identity-specific zone assignment' AWS::SES::ReceiptRule: 'stored in an existing SES receipt rule set; Ref and RuleName return the rule name; management plane only, with no inbound mail delivery' AWS::Events::Archive: '`KmsKeyIdentifier` is ignored'