fix(cloudformation): replace Cognito user pool groups like CloudFormation (#4841)

* test(cloudformation): cover AWS::Cognito::UserPoolGroup replacement against AWS

* fix(cloudformation): replace Cognito user pool groups on create-only changes

AWS::Cognito::UserPoolGroup left the old group behind on a rename, kept
the explicit name when GroupName was dropped, and tried to update a
group that did not exist when UserPoolId changed.

The provisioner now creates the group whenever a create-only property
changes and hands the displaced group to ReplacementCleanup, which
deletes it once the update commits or deletes the replacement and
restores the prior name and pool when the update rolls back. A pool
move that keeps an explicit name keeps the physical id, so, as on AWS,
nothing is deleted and the old-pool group stays. A generated name is
kept only for an in-place update; a pool move or a dropped explicit
name generates a fresh one. Each provisioned name is recorded with its
pool so a displaced group is deleted from the pool it lives in.

Closes #4836

* test(cloudformation): cover a failed update after moving a named Cognito group against AWS

* fix(cloudformation): roll back named Cognito group pool moves and read legacy name modes

A named pool move keeps the physical id, so it now records a replacement that displaces nothing. A failed update points the group back at the old pool and, as measured on AWS, leaves the new pool's group, and the stack delete reads the pool from UserPoolId. A resource persisted without FlociGroupNameMode reads its name as generated only when it has the generated shape, so dropping an explicit GroupName replaces it.

* test(cloudformation): cover declaring a Cognito group's generated name explicitly against AWS

Measured on AWS (eu-west-1): updating an unnamed group to declare GroupName
equal to its generated name, same pool, fails the Group with UPDATE_FAILED
"CloudFormation cannot update a stack when a custom-named resource requires
replacing. Rename <name> and update the stack again." before anything is
created. The stack ends UPDATE_ROLLBACK_COMPLETE, Ref and the physical id stay
the generated name, and the group keeps its pool, description, precedence and
creation date.

* fix(cloudformation): refuse declaring a Cognito group's generated name explicitly

GroupName is create-only, so declaring an unnamed group's generated name
explicitly in the same pool requires a replacement that keeps both the pool
and the name. Measured on AWS, CloudFormation refuses it before creating
anything: the Group goes UPDATE_FAILED with "CloudFormation cannot update a
stack when a custom-named resource requires replacing. Rename <name> and update
the stack again.", the stack ends UPDATE_ROLLBACK_COMPLETE, and Ref and the
group stay unchanged. Floci updated the group in place and reported
UPDATE_COMPLETE; it now raises the same ValidationError.

* fix(cloudformation): keep only owed and current Cognito groups in the pool record

The group pool record added the prior and current name on every provision and
never dropped one, so it grew with every name the resource ever had. It is now
rebuilt after the replacement record, keeping only the names still owed a
delete, with their recorded pools, plus the current name.

* fix(cloudformation): refuse a declared generated Cognito group name only when the mode was recorded

The refusal of a declared generated name read the prior mode from the name's
shape when no mode was recorded, so a legacy group explicitly named in the
generated shape had a valid in-place update refused. Only a recorded generated
mode refuses now; a legacy record updates in place, as before the mode existed.

* test(cloudformation): read stack outputs with XmlParser

The Cognito group integration test read stack outputs by splitting the
DescribeStacks XML on tag strings. It now uses XmlParser.extractPairs, as the
other CloudFormation integration tests do.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-06 10:24:56 -04:00
1 parent 69b4d17c67
commit e9f2463103
8 files changed
+1224 -14

No files matched your search

@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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;
@@ -8,15 +11,46 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Map;
import java.util.Set;
/**
* Provisions {@code AWS::Cognito::UserPoolGroup}. The physical id and {@code Ref} are the bare group
* name, generated when the template gives none. {@code UserPoolId} and {@code GroupName} are
* create-only: an update that keeps both changes the group in place, and one that changes either,
* or drops an explicit name, creates the new group and leaves the displaced one to the
* {@link ReplacementCleanup} record. A pool move that keeps an explicit name keeps the physical id,
* so, as on AWS, nothing is deleted: a committed move leaves the group in the old pool behind, and
* a rolled-back one points the resource at the old pool's group again and leaves the new one.
* Declaring an unnamed group's generated name explicitly, in the same pool, needs a replacement
* keeping both the pool and the name, which, as on AWS, is refused before anything is created,
* unless the record predates the name mode.
*/
@ApplicationScoped
public class CognitoUserPoolGroupCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(CognitoUserPoolGroupCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
/** Attribute holding the owning pool id, the half of the key the physical id cannot carry. */
static final String USER_POOL_ID_ATTR = "UserPoolId";
/**
* Records whether the name came from the template or was generated, so a later update can tell
* an explicit name being dropped, which replaces the group, from an unnamed group keeping the
* name it was given. A resource without it predates the attribute, and its name reads as
* generated when it has the generated shape.
*/
private static final String NAME_MODE_ATTR = "FlociGroupNameMode";
private static final String NAME_MODE_EXPLICIT = "explicit";
private static final String NAME_MODE_GENERATED = "generated";
/**
* The current group name and every one still owed a delete, mapped to its pool, because the
* replacement cleanup addresses a displaced group by its name alone and a group is deleted by
* pool and name.
*/
// ponytail: keyed by name alone. Two groups of one name are owed deletes together only after a
// group delete failed, and deleteGroup fails only with ResourceNotFoundException, which counts as deleted.
private static final String GROUP_POOLS_ATTR = "__FlociGroupPools";
private final CognitoService cognitoService;
@@ -32,48 +66,159 @@ public class CognitoUserPoolGroupCfnProvisioner implements CfnResourceProvisione
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
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 explicitName = ctx.resolveOptional(props, "GroupName");
if (explicitName != null && explicitName.isBlank()) {
explicitName = null;
}
String priorPoolId = attributesBefore.get(USER_POOL_ID_ATTR);
boolean poolChanged = ctx.isUpdate() && priorPoolId != null && !userPoolId.equals(priorPoolId);
String groupName = groupName(r, ctx, explicitName, poolChanged);
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 {
// ponytail: only a recorded mode refuses. A legacy record's shape cannot tell an explicit
// name from a generated one, so it updates in place as before.
if (explicitName != null && !poolChanged && ctx.reusesPriorEntity(explicitName)
&& NAME_MODE_GENERATED.equals(r.getAttributes().get(NAME_MODE_ATTR))) {
throw new AwsException("ValidationError",
"CloudFormation cannot update a stack when a custom-named resource requires "
+ "replacing. Rename " + explicitName + " and update the stack again.", 400);
}
boolean replaced = poolChanged || !ctx.reusesPriorEntity(groupName);
if (replaced) {
cognitoService.createGroup(userPoolId, groupName, description, precedence, roleArn);
} else {
cognitoService.updateGroup(userPoolId, groupName, description, precedence, roleArn);
}
r.setPhysicalId(groupName);
r.getAttributes().put(USER_POOL_ID_ATTR, userPoolId);
r.getAttributes().put(NAME_MODE_ATTR, explicitName != null ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED);
ReplacementCleanup.record(r, ctx, attributesBefore, replaced);
ObjectNode known = groupPools(r);
if (ctx.isUpdate() && priorPoolId != null) {
known.put(ctx.priorPhysicalId(), priorPoolId);
}
ObjectNode pools = MAPPER.createObjectNode();
for (String owed : ReplacementCleanup.owedPhysicalIds(r)) {
JsonNode pool = known.get(owed);
if (pool != null) {
pools.set(owed, pool);
}
}
pools.put(groupName, userPoolId);
r.getAttributes().put(GROUP_POOLS_ATTR, pools.toString());
}
/**
* The template's name when it gives one; otherwise the generated name the group already has,
* unless the previous name was explicit or the pool changed, since either replaces the group;
* and a fresh generated name failing both.
*/
private static String groupName(StackResource r, ProvisionContext ctx, String explicitName,
boolean poolChanged) {
if (explicitName != null) {
return explicitName;
}
if (ctx.isUpdate() && !poolChanged && priorNameGenerated(r, ctx)) {
return ctx.priorPhysicalId();
}
return ctx.generatePhysicalName(r.getLogicalId(), 128, false);
}
/** Whether the prior name was generated, read from its shape when the mode was never recorded. */
private static boolean priorNameGenerated(StackResource r, ProvisionContext ctx) {
String mode = r.getAttributes().get(NAME_MODE_ATTR);
if (mode == null) {
return ctx.isGeneratedPhysicalName(ctx.priorPhysicalId(), r.getLogicalId(), 128, false);
}
return !NAME_MODE_EXPLICIT.equals(mode);
}
/**
* Deletes the current group from its {@code UserPoolId}, not through the pool map: after a
* rolled-back pool move the map's entry for the name points at the new pool.
*/
@Override
public void delete(StackResource resource, String region) {
String userPoolId = resource.getAttributes().get(USER_POOL_ID_ATTR);
deleteGroup(resource.getAttributes().get(USER_POOL_ID_ATTR), resource.getPhysicalId());
}
/** Deletes a group from the given pool, treating one that is already gone as deleted. */
private void deleteGroup(String userPoolId, String groupName) {
if (userPoolId == null || userPoolId.isBlank()) {
return;
}
try {
cognitoService.deleteGroup(userPoolId, resource.getPhysicalId());
cognitoService.deleteGroup(userPoolId, groupName);
} 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());
LOG.debugv("Cognito group already gone, treating as deleted: {0}", groupName);
}
}
/** Deletes a displaced group from the pool the map recorded for its name. */
private ReplacementCleanup.Deleter displacedDeleter(StackResource resource) {
return (resourceType, groupName, region) -> deleteGroup(
groupPools(resource).path(groupName).asText(resource.getAttributes().get(USER_POOL_ID_ATTR)),
groupName);
}
private static ObjectNode groupPools(StackResource r) {
String raw = r.getAttributes().get(GROUP_POOLS_ATTR);
if (raw != null) {
try {
if (MAPPER.readTree(raw) instanceof ObjectNode pools) {
return pools;
}
} catch (JsonProcessingException e) {
LOG.warnv("Unreadable group pool record on {0}, ignoring it: {1}", r.getLogicalId(), e.getMessage());
}
}
return MAPPER.createObjectNode();
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return ReplacementCleanup.complete(resource, displacedDeleter(resource));
}
@Override
public void clearUpdate(StackResource resource) {
ReplacementCleanup.clear(resource);
}
/**
* A replacement is undone through the cleanup record. A named pool move kept the physical id,
* so its rollback points the resource at the old pool's group again and, as on AWS, leaves the
* new one. Without a record the group was updated in place, and putting that back needs a
* snapshot this provisioner does not keep.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
return ReplacementCleanup.rollback(resource, displacedDeleter(resource));
}
private static Integer parsePrecedence(String value) {
if (value == null || value.isBlank()) {
return null;
@@ -212,6 +212,20 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio
return stale;
}
/**
* Whether {@code name} has the shape {@link #generatePhysicalName} gives this logical id: the
* same prefix and length, ending in a 12-character lowercase hex suffix.
*/
public boolean isGeneratedPhysicalName(String name, String logicalId, int maxLength, boolean lowercase) {
String sample = generatePhysicalName(logicalId, maxLength, lowercase);
if (name == null || name.length() != sample.length()) {
return false;
}
int prefixLength = sample.length() - 12;
return name.startsWith(sample.substring(0, prefixLength))
&& name.substring(prefixLength).matches("[0-9a-f]{12}");
}
/** Generates a CloudFormation-style physical name: {@code <stack>-<logicalId>-<suffix>}. */
public String generatePhysicalName(String logicalId, int maxLength, boolean lowercase) {
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
@@ -57,13 +57,24 @@ public final class ReplacementCleanup {
* because the entity under that id is the one this update created.
*/
static void record(StackResource r, ProvisionContext ctx, Map<String, String> attributesBeforeProvision) {
record(r, ctx, attributesBeforeProvision,
ctx.isUpdate() && !ctx.priorPhysicalId().equals(r.getPhysicalId()));
}
/**
* Records a replacement the provisioner decided on, for a type whose replacement can keep its
* physical id. One that kept it is rolled back by restoring the prior attributes and displaces
* nothing: as on AWS, the old entity is not deleted when the physical id did not change.
*/
static void record(StackResource r, ProvisionContext ctx, Map<String, String> attributesBeforeProvision,
boolean replaced) {
ObjectNode cleanup = readOrEmpty(r);
cleanup.remove("priorPhysicalId");
cleanup.remove("priorAttributes");
cleanup.put("region", ctx.region());
String prior = ctx.priorPhysicalId();
boolean priorIsStub = CfnResourceDispatcher.isStub(prior, attributesBeforeProvision);
if (ctx.isUpdate() && (!prior.equals(r.getPhysicalId()) || priorIsStub)) {
if (ctx.isUpdate() && (replaced || priorIsStub)) {
cleanup.put("priorPhysicalId", prior);
ObjectNode priorAttributes = cleanup.putObject("priorAttributes");
attributesBeforeProvision.forEach((key, value) -> {
@@ -71,7 +82,7 @@ public final class ReplacementCleanup {
priorAttributes.put(key, value);
}
});
if (!priorIsStub) {
if (!priorIsStub && !prior.equals(r.getPhysicalId())) {
addDisplaced(cleanup, prior, r.getResourceType(), ctx.region(), true);
}
}