mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
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:
1 parent
e714fd9594
commit
ebdac90574
6 files changed
+447
-37
No files matched your search
+60
@@ -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<String> factors = new HashSet<>();
|
||||
resolved.path("EnabledMfas").forEach(factor -> factors.add(factor.asText()));
|
||||
|
||||
Boolean softwareTokenEnabled = factors.contains("SOFTWARE_TOKEN_MFA") ? Boolean.TRUE : null;
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> target, String key, JsonNode value) {
|
||||
if (value.isTextual()) {
|
||||
target.put(key, value.asText());
|
||||
}
|
||||
}
|
||||
|
||||
private void provisionUserPoolClient(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
|
||||
@@ -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<String> 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<String, Object> 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<Map<String, Object>> customAttributes) {
|
||||
synchronized (poolLock(userPoolId)) {
|
||||
addCustomAttributesUnderPoolLock(userPoolId, customAttributes);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCustomAttributesUnderPoolLock(String userPoolId, List<Map<String, Object>> customAttributes) {
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
List<Map<String, Object>> schema = pool.getSchemaAttributes();
|
||||
if (schema == null) {
|
||||
@@ -810,8 +836,41 @@ public class CognitoService implements ResourceProvider {
|
||||
Map<String, Object> smsMfaConfiguration,
|
||||
Map<String, Object> 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<String, Object> smsMfaConfiguration,
|
||||
Map<String, Object> 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<String, Object> smsMfaConfiguration,
|
||||
Map<String, Object> 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) {
|
||||
|
||||
Reference in new issue
Block a user