fix(cloudformation): provision Cognito user pool groups (#3695)

* fix(cloudformation): provision Cognito user pool groups

Create and reconcile user pool groups, and namespace custom schema attributes while preserving standard attributes.

* fix(cloudformation): keep a generated Cognito group name across updates

GroupName is optional, and provision generated a fresh stand-in on every call. Because
provision is also the update path, the second UpdateStack derived a different name, took
the create branch and left the group the stack already owned orphaned behind it.

Use ProvisionContext.stablePhysicalName so the prior physical id is reused when the
template does not name the group, and reusesPriorEntity for the create-or-update choice,
which is the pairing that keeps a stable name from turning an update into a duplicate
create.
This commit is contained in:
Chris Jovanovski authored and GitHub committed 2026-09-19 20:06:58 -05:00
1 parent 91de9e452e
commit d9a4db0290
10 files changed
+699 -8

No files matched your search

@@ -0,0 +1,88 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cognito.CognitoService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Set;
@ApplicationScoped
public class CognitoUserPoolGroupCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(CognitoUserPoolGroupCfnProvisioner.class);
/** Attribute holding the owning pool id, the half of the key the physical id cannot carry. */
static final String USER_POOL_ID_ATTR = "UserPoolId";
private final CognitoService cognitoService;
@Inject
public CognitoUserPoolGroupCfnProvisioner(CognitoService cognitoService) {
this.cognitoService = cognitoService;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::Cognito::UserPoolGroup");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
String userPoolId = ctx.resolveOptional(props, "UserPoolId");
if (userPoolId == null || userPoolId.isBlank()) {
throw new IllegalArgumentException("UserPoolId is required for AWS::Cognito::UserPoolGroup");
}
// GroupName is optional, and the generated stand-in has to stay put: generating a fresh one
// on each UpdateStack would create a second group and orphan the one the stack already owns.
String groupName = ctx.stablePhysicalName(
ctx.resolveOptional(props, "GroupName"), r.getLogicalId(), 128, false);
String description = ctx.resolveOptional(props, "Description");
Integer precedence = parsePrecedence(ctx.resolveOptional(props, "Precedence"));
String roleArn = ctx.resolveOptional(props, "RoleArn");
// provision is also the update path. A group is addressed by its name, so a renamed group
// has nothing to update under the new name: that is a replacement on AWS too.
if (ctx.reusesPriorEntity(groupName)) {
cognitoService.updateGroup(userPoolId, groupName, description, precedence, roleArn);
} else {
cognitoService.createGroup(userPoolId, groupName, description, precedence, roleArn);
}
r.setPhysicalId(groupName);
r.getAttributes().put(USER_POOL_ID_ATTR, userPoolId);
}
@Override
public void delete(StackResource resource, String region) {
String userPoolId = resource.getAttributes().get(USER_POOL_ID_ATTR);
if (userPoolId == null || userPoolId.isBlank()) {
return;
}
try {
cognitoService.deleteGroup(userPoolId, resource.getPhysicalId());
} catch (AwsException e) {
// An already-deleted group is the one failure that genuinely means "done". Anything
// else is a real error worth surfacing rather than hiding behind a debug line.
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Cognito group already gone, treating as deleted: {0}", resource.getPhysicalId());
}
}
private static Integer parsePrecedence(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.valueOf(value.trim());
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Precedence must be an integer for AWS::Cognito::UserPoolGroup, got: " + value, e);
}
}
}
@@ -311,11 +311,7 @@ public class CognitoService implements ResourceProvider {
throw new AwsException("InvalidParameterException", "Attribute name contains invalid characters.", 400);
}
boolean developerOnly = Boolean.TRUE.equals(attr.get("DeveloperOnlyAttribute"));
String prefix = developerOnly ? "dev:" : "custom:";
if (!name.startsWith("custom:") && !name.startsWith("dev:")) {
attr.put("Name", prefix + name);
}
attr.put("Name", prefixedAttributeName(name, Boolean.TRUE.equals(attr.get("DeveloperOnlyAttribute"))));
String finalName = (String) attr.get("Name");
boolean exists = schema.stream().anyMatch(existing -> finalName.equals(existing.get("Name")));
@@ -366,12 +362,37 @@ public class CognitoService implements ResourceProvider {
pool.setPolicies(normalized);
}
private static String prefixedAttributeName(String name, boolean developerOnly) {
if (name.startsWith("custom:") || name.startsWith("dev:")) {
return name;
}
return (developerOnly ? "dev:" : "custom:") + name;
}
private static List<Map<String, Object>> prefixCustomSchemaAttributes(List<Map<String, Object>> schema) {
if (schema == null) {
return null;
}
List<Map<String, Object>> prefixed = new ArrayList<>(schema.size());
for (Map<String, Object> attr : schema) {
String name = attr == null ? null : (String) attr.get("Name");
if (name == null || name.isBlank() || CognitoStandardAttributes.isStandard(name)) {
prefixed.add(attr);
continue;
}
Map<String, Object> copy = new HashMap<>(attr);
copy.put("Name", prefixedAttributeName(name, Boolean.TRUE.equals(attr.get("DeveloperOnlyAttribute"))));
prefixed.add(copy);
}
return prefixed;
}
@SuppressWarnings("unchecked")
private void populateUserPool(UserPool pool, Map<String, Object> request) {
if (request.containsKey("Policies")) pool.setPolicies((Map<String, Object>) request.get("Policies"));
if (request.containsKey("DeletionProtection")) pool.setDeletionProtection((String) request.get("DeletionProtection"));
if (request.containsKey("LambdaConfig")) pool.setLambdaConfig((Map<String, Object>) request.get("LambdaConfig"));
if (request.containsKey("Schema")) pool.setSchemaAttributes((List<Map<String, Object>>) request.get("Schema"));
if (request.containsKey("Schema")) pool.setSchemaAttributes(prefixCustomSchemaAttributes((List<Map<String, Object>>) request.get("Schema")));
if (request.containsKey("AutoVerifiedAttributes")) pool.setAutoVerifiedAttributes((List<String>) request.get("AutoVerifiedAttributes"));
if (request.containsKey("AliasAttributes")) pool.setAliasAttributes((List<String>) request.get("AliasAttributes"));
if (request.containsKey("UsernameAttributes")) pool.setUsernameAttributes((List<String>) request.get("UsernameAttributes"));
@@ -4,6 +4,8 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
final class CognitoStandardAttributes {
@@ -71,6 +73,15 @@ final class CognitoStandardAttributes {
return attr;
}
private static final Set<String> DEFAULT_NAMES = DEFAULTS.stream()
.map(attr -> (String) attr.get("Name"))
.collect(Collectors.toUnmodifiableSet());
/** True when {@code name} is one of the standard OIDC attributes every pool carries. */
static boolean isStandard(String name) {
return name != null && DEFAULT_NAMES.contains(name);
}
/**
* Merges standard attributes with any pool-defined schema.
* Custom attributes (name starts with "custom:") are appended after standard ones.