Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): replace Cognito user pool groups like CloudFormation (#4841)
Mario Toffiae9f24631034d
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolGroupTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolGroupTest.javanew file mode 100644index 0000000000..a7fea3ffe4--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolGroupTest.java@@ -0,0 +1,446 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;+import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;+import software.amazon.awssdk.services.cloudformation.model.Output;+import software.amazon.awssdk.services.cloudformation.model.Parameter;+import software.amazon.awssdk.services.cloudformation.model.Stack;+import software.amazon.awssdk.services.cloudformation.model.StackEvent;+import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;+import software.amazon.awssdk.services.cognitoidentityprovider.model.GroupType;+import software.amazon.awssdk.services.cognitoidentityprovider.model.ResourceNotFoundException;++import java.util.List;+import java.util.function.BooleanSupplier;+import java.util.stream.Collectors;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++/**+ * Drives an {@code AWS::Cognito::UserPoolGroup} through in-place and replacing updates and reads+ * the groups back through the Cognito SDK. The group's create-only properties are+ * {@code UserPoolId} and {@code GroupName}; {@code Ref} and the physical id are the bare group name.+ * The pools are created outside the stack, so the groups left in them stay observable and a+ * rolled-back update touches only the groups.+ */+@DisplayName("CloudFormation AWS::Cognito::UserPoolGroup")+class CloudFormationCognitoUserPoolGroupTest {++ private static final long TIMEOUT_NANOS = 300_000_000_000L;++ private static final String TEMPLATE = """+ {+ "Parameters": {+ "GroupName": {"Type": "String", "Default": ""},+ "UserPoolId": {"Type": "String"},+ "Description": {"Type": "String"},+ "Precedence": {"Type": "Number"},+ "Fail": {"Type": "String", "Default": "false"}+ },+ "Conditions": {+ "Named": {"Fn::Not": [{"Fn::Equals": [{"Ref": "GroupName"}, ""]}]},+ "Fail": {"Fn::Equals": [{"Ref": "Fail"}, "true"]}+ },+ "Resources": {+ "Group": {+ "Type": "AWS::Cognito::UserPoolGroup",+ "Properties": {+ "UserPoolId": {"Ref": "UserPoolId"},+ "GroupName": {"Fn::If": ["Named", {"Ref": "GroupName"}, {"Ref": "AWS::NoValue"}]},+ "Description": {"Ref": "Description"},+ "Precedence": {"Ref": "Precedence"}+ }+ },+ "Duplicate": {+ "Type": "AWS::Cognito::UserPoolGroup",+ "Condition": "Fail",+ "DependsOn": "Group",+ "Properties": {"UserPoolId": {"Ref": "UserPoolId"}, "GroupName": {"Ref": "GroupName"}}+ }+ },+ "Outputs": {+ "GroupRef": {"Value": {"Ref": "Group"}}+ }+ }+ """;++ private static CloudFormationClient cfn;+ private static CognitoIdentityProviderClient cognito;++ private String stackName;+ private String stackId;+ private String p1;+ private String p2;++ @BeforeAll+ static void clients() {+ cfn = TestFixtures.cloudFormationClient();+ cognito = TestFixtures.cognitoClient();+ }++ @BeforeEach+ void setup() {+ stackName = TestFixtures.uniqueName("compat-cfn-cug");+ p1 = cognito.createUserPool(r -> r.poolName(stackName + "-p1")).userPool().id();+ p2 = cognito.createUserPool(r -> r.poolName(stackName + "-p2")).userPool().id();+ }++ @AfterEach+ void cleanup() throws InterruptedException {+ try {+ deleteStack();+ } finally {+ for (String pool : new String[] {p1, p2}) {+ if (pool == null) {+ continue;+ }+ try {+ cognito.deleteUserPool(r -> r.userPoolId(pool));+ } catch (ResourceNotFoundException expected) {+ // The pool never finished creating or was already removed.+ }+ }+ p1 = null;+ p2 = null;+ }+ }++ @AfterAll+ static void closeClients() {+ cfn.close();+ cognito.close();+ }++ @Test+ @DisplayName("Description and Precedence update the named group in place, and the stack delete removes it")+ void inPlaceUpdateKeepsTheNamedGroupAndStackDeletionRemovesIt() throws InterruptedException {+ String name = stackName + "-n1";+ createStack(parameters(name, p1, "d1", 1, false));+ assertIdentity(name);+ GroupType created = group(p1, name);+ assertGroup(created, p1, "d1", 1);+ assertThat(groupNames(p1)).containsExactly(name);+ assertThat(groupNames(p2)).isEmpty();++ updateStack(parameters(name, p1, "d2", 2, false), "UPDATE_COMPLETE");+ assertIdentity(name);+ GroupType updated = group(p1, name);+ assertGroup(updated, p1, "d2", 2);+ assertThat(updated.creationDate()).as("an in-place update keeps the group").isEqualTo(created.creationDate());+ assertThat(groupNames(p1)).containsExactly(name);+ assertThat(groupNames(p2)).isEmpty();++ deleteStack();+ assertThat(groupNames(p1)).as("the stack delete removes the group from the retained pool").isEmpty();+ assertThat(groupNames(p2)).isEmpty();+ }++ @Test+ @DisplayName("Renaming the group replaces it and deletes the group under the old name")+ void renamingTheGroupReplacesItAndDeletesTheOldName() throws InterruptedException {+ String original = stackName + "-n1";+ String renamed = stackName + "-n2";+ createStack(parameters(original, p1, "d1", 1, false));+ assertIdentity(original);++ updateStack(parameters(renamed, p1, "d1", 1, false), "UPDATE_COMPLETE");+ assertIdentity(renamed);+ assertGroup(group(p1, renamed), p1, "d1", 1);+ assertGroupNotFound(p1, original);+ assertThat(groupNames(p1)).containsExactly(renamed);+ assertThat(groupNames(p2)).isEmpty();++ deleteStack();+ assertThat(groupNames(p1)).isEmpty();+ assertThat(groupNames(p2)).isEmpty();+ }++ @Test+ @DisplayName("Moving a named group to another pool creates it there and leaves the old group behind")+ void movingANamedGroupToAnotherPoolCreatesItThereAndLeavesTheOldGroupBehind() throws InterruptedException {+ String name = stackName + "-n1";+ createStack(parameters(name, p1, "d1", 1, false));+ assertIdentity(name);+ GroupType original = group(p1, name);++ updateStack(parameters(name, p2, "d1", 1, false), "UPDATE_COMPLETE");+ assertIdentity(name);+ assertGroup(group(p2, name), p2, "d1", 1);+ assertThat(groupNames(p2)).containsExactly(name);+ assertThat(groupNames(p1))+ .as("AWS replaces the group but skips deleting the old one: its physical id, the bare"+ + " group name, did not change")+ .containsExactly(name);+ assertThat(group(p1, name).creationDate()).isEqualTo(original.creationDate());++ deleteStack();+ assertThat(groupNames(p2)).as("the stack delete removes the group it owns").isEmpty();+ assertThat(groupNames(p1)).as("the group left in the old pool is no longer owned by the stack")+ .containsExactly(name);+ }++ @Test+ @DisplayName("Declaring a generated group's name explicitly is refused as a custom-named replacement and rolls back")+ void declaringAGeneratedGroupNameExplicitlyIsRefusedAndRollsBack() throws InterruptedException {+ createStack(parameters("", p1, "d1", 1, false));+ String generated = output("GroupRef");+ assertGeneratedName(generated);+ assertIdentity(generated);+ GroupType created = group(p1, generated);++ // GroupName is create-only, so declaring it requires a replacement, but the replacement+ // would claim the same pool and name: CloudFormation refuses it before creating anything.+ updateStack(parameters(generated, p1, "d1", 1, false), "UPDATE_ROLLBACK_COMPLETE");+ List<String> failures = groupEvents().stream()+ .filter(event -> "UPDATE_FAILED".equals(event.resourceStatusAsString()))+ .map(StackEvent::resourceStatusReason)+ .toList();+ assertThat(failures).hasSize(1);+ assertThat(failures.get(0)).contains("CloudFormation cannot update a stack when a custom-named resource"+ + " requires replacing. Rename " + generated + " and update the stack again.");+ assertIdentity(generated);+ GroupType kept = group(p1, generated);+ assertGroup(kept, p1, "d1", 1);+ assertThat(kept.creationDate()).isEqualTo(created.creationDate());+ assertThat(groupNames(p1)).containsExactly(generated);+ assertThat(groupNames(p2)).isEmpty();++ deleteStack();+ assertThat(groupNames(p1)).isEmpty();+ assertThat(groupNames(p2)).isEmpty();+ }++ @Test+ @DisplayName("Removing GroupName replaces the named group with a generated one and deletes the named group")+ void removingTheGroupNameReplacesTheGroupWithAGeneratedName() throws InterruptedException {+ String name = stackName + "-n1";+ createStack(parameters(name, p1, "d1", 1, false));+ assertIdentity(name);++ updateStack(parameters("", p1, "d1", 1, false), "UPDATE_COMPLETE");+ String generated = output("GroupRef");+ assertGeneratedName(generated);+ assertThat(generated).isNotEqualTo(name);+ assertIdentity(generated);+ assertGroup(group(p1, generated), p1, "d1", 1);+ assertGroupNotFound(p1, name);+ assertThat(groupNames(p1)).containsExactly(generated);+ assertThat(groupNames(p2)).isEmpty();++ deleteStack();+ assertThat(groupNames(p1)).isEmpty();+ assertThat(groupNames(p2)).isEmpty();+ }++ @Test+ @DisplayName("Moving a generated group to another pool replaces it under a new generated name")+ void movingAGeneratedGroupToAnotherPoolReplacesItUnderANewGeneratedName() throws InterruptedException {+ createStack(parameters("", p1, "d1", 1, false));+ String original = output("GroupRef");+ assertGeneratedName(original);+ assertIdentity(original);+ assertGroup(group(p1, original), p1, "d1", 1);++ updateStack(parameters("", p2, "d1", 1, false), "UPDATE_COMPLETE");+ String replacement = output("GroupRef");+ assertGeneratedName(replacement);+ assertThat(replacement).as("the replacement gets a freshly generated name").isNotEqualTo(original);+ assertIdentity(replacement);+ assertGroup(group(p2, replacement), p2, "d1", 1);+ assertThat(groupNames(p2)).containsExactly(replacement);+ assertThat(groupNames(p1)).as("the generated group in the old pool is deleted").isEmpty();++ deleteStack();+ assertThat(groupNames(p1)).isEmpty();+ assertThat(groupNames(p2)).isEmpty();+ }++ @Test+ @DisplayName("A failed update after a rename deletes the new group and keeps the old one")+ void failedUpdateAfterARenameDeletesTheNewGroupAndKeepsTheOldOne() throws InterruptedException {+ String original = stackName + "-n1";+ String renamed = stackName + "-n2";+ createStack(parameters(original, p1, "d1", 1, false));+ assertIdentity(original);+ GroupType created = group(p1, original);++ // Duplicate depends on Group and claims the same pool and name, so it fails after the+ // replacement group exists and the update rolls back.+ updateStack(parameters(renamed, p1, "d1", 1, true), "UPDATE_ROLLBACK_COMPLETE");+ assertIdentity(original);+ GroupType kept = group(p1, original);+ assertGroup(kept, p1, "d1", 1);+ assertThat(kept.creationDate()).isEqualTo(created.creationDate());+ assertGroupNotFound(p1, renamed);+ assertThat(groupNames(p1)).containsExactly(original);+ assertThat(groupNames(p2)).isEmpty();++ deleteStack();+ assertThat(groupNames(p1)).isEmpty();+ assertThat(groupNames(p2)).isEmpty();+ }++ @Test+ @DisplayName("A failed update after moving a named group keeps the old pool's group and leaves the new one behind")+ void failedUpdateAfterMovingANamedGroupKeepsTheOldPoolGroupAndLeavesTheNewOneBehind()+ throws InterruptedException {+ String name = stackName + "-n1";+ createStack(parameters(name, p1, "d1", 1, false));+ assertIdentity(name);+ GroupType created = group(p1, name);++ // Duplicate depends on Group and claims the new pool and the same name, so it fails after+ // the group exists in the new pool and the update rolls back.+ updateStack(parameters(name, p2, "d1", 1, true), "UPDATE_ROLLBACK_COMPLETE");+ assertIdentity(name);+ GroupType kept = group(p1, name);+ assertGroup(kept, p1, "d1", 1);+ assertThat(kept.creationDate()).isEqualTo(created.creationDate());+ assertThat(groupNames(p1)).containsExactly(name);+ assertThat(groupNames(p2))+ .as("the rollback skips deleting the group the failed update created: its physical id,"+ + " the bare group name, did not change")+ .containsExactly(name);++ deleteStack();+ assertThat(groupNames(p1)).as("the stack delete removes the group it owns again").isEmpty();+ assertThat(groupNames(p2)).as("the group left in the new pool is not owned by the stack")+ .containsExactly(name);+ }++ private static List<Parameter> parameters(String groupName, String userPoolId, String description,+ int precedence, boolean fail) {+ return List.of(+ parameter("GroupName", groupName),+ parameter("UserPoolId", userPoolId),+ parameter("Description", description),+ parameter("Precedence", String.valueOf(precedence)),+ parameter("Fail", String.valueOf(fail)));+ }++ private static Parameter parameter(String key, String value) {+ return Parameter.builder().parameterKey(key).parameterValue(value).build();+ }++ private void createStack(List<Parameter> parameters) throws InterruptedException {+ stackId = cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameters))+ .stackId();+ awaitStatus("CREATE_COMPLETE");+ }++ private void updateStack(List<Parameter> parameters, String expected) throws InterruptedException {+ cfn.updateStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameters));+ awaitStatus(expected);+ }++ private String output(String key) {+ return cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0).outputs().stream()+ .filter(o -> key.equals(o.outputKey())).map(Output::outputValue)+ .findFirst().orElseThrow();+ }++ private void assertIdentity(String groupName) {+ assertThat(output("GroupRef")).as("Ref is the group name").isEqualTo(groupName);+ assertThat(cfn.describeStackResource(r -> r.stackName(stackId).logicalResourceId("Group"))+ .stackResourceDetail().physicalResourceId())+ .as("the physical id is the bare group name").isEqualTo(groupName);+ }++ private static void assertGeneratedName(String name) {+ assertThat(name).isNotEmpty().contains("Group").hasSizeLessThanOrEqualTo(128);+ }++ private GroupType group(String pool, String name) {+ return cognito.getGroup(r -> r.userPoolId(pool).groupName(name)).group();+ }++ private static void assertGroup(GroupType group, String pool, String description, int precedence) {+ assertThat(group.userPoolId()).isEqualTo(pool);+ assertThat(group.description()).isEqualTo(description);+ assertThat(group.precedence()).isEqualTo(precedence);+ }++ private void assertGroupNotFound(String pool, String name) {+ assertThatThrownBy(() -> group(pool, name)).isInstanceOf(ResourceNotFoundException.class);+ }++ private List<String> groupNames(String pool) {+ return cognito.listGroupsPaginator(r -> r.userPoolId(pool)).groups().stream()+ .map(GroupType::groupName).sorted().toList();+ }++ private void awaitStatus(String expected) throws InterruptedException {+ await(() -> {+ Stack stack = cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0);+ String status = stack.stackStatusAsString();+ if (expected.equals(status)) {+ return true;+ }+ if (!status.endsWith("_IN_PROGRESS") && (status.contains("FAILED") || status.contains("ROLLBACK"))) {+ throw new AssertionError(stackName + " reached " + status + " instead of " + expected + ": "+ + stack.stackStatusReason() + failedEvents());+ }+ return false;+ }, expected);+ }++ private List<StackEvent> groupEvents() {+ return cfn.describeStackEvents(r -> r.stackName(stackId)).stackEvents().stream()+ .filter(event -> "Group".equals(event.logicalResourceId()))+ .toList();+ }++ private String failedEvents() {+ return cfn.describeStackEvents(r -> r.stackName(stackId)).stackEvents().stream()+ .filter(event -> event.resourceStatusAsString().endsWith("_FAILED"))+ .map(event -> event.logicalResourceId() + " " + event.resourceStatusAsString() + ": "+ + event.resourceStatusReason())+ .collect(Collectors.joining("; ", " [", "]"));+ }++ private void deleteStack() throws InterruptedException {+ if (stackId == null) {+ return;+ }+ cfn.deleteStack(r -> r.stackName(stackId));+ await(() -> {+ try {+ List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackId)).stacks();+ if (stacks.isEmpty()) {+ return true;+ }+ Stack stack = stacks.get(0);+ if ("DELETE_FAILED".equals(stack.stackStatusAsString())) {+ throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason());+ }+ return "DELETE_COMPLETE".equals(stack.stackStatusAsString());+ } catch (CloudFormationException e) {+ if ("ValidationError".equals(e.awsErrorDetails().errorCode())+ && e.getMessage().contains("does not exist")) {+ return true;+ }+ throw e;+ }+ }, "stack deletion");+ stackId = null;+ }++ private void await(BooleanSupplier condition, String expected) throws InterruptedException {+ long pollMillis = TestFixtures.isRealAws() ? 2_000 : 100;+ long deadline = System.nanoTime() + TIMEOUT_NANOS;+ while (System.nanoTime() < deadline) {+ if (condition.getAsBoolean()) {+ return;+ }+ Thread.sleep(pollMillis);+ }+ throw new AssertionError(stackName + " timed out waiting for " + expected);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisioner.javaindex 5f5e6c3c70..2bcd49e0d8 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisioner.java@@ -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.+ */@ApplicationScopedpublic 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@Overridepublic 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.+ */@Overridepublic 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;diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.javaindex 411ec92e7a..4ae55d9678 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java@@ -212,6 +212,20 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regioreturn 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);diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.javaindex bbfd067915..101785cc10 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java@@ -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);}}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserPoolGroupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserPoolGroupIntegrationTest.javaindex 7650a6a762..52be27fcc5 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserPoolGroupIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserPoolGroupIntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.cloudformation;+import io.github.hectorvent.floci.core.common.XmlParser;import io.quarkus.test.junit.QuarkusTest;import io.restassured.RestAssured;import io.restassured.config.EncoderConfig;@@ -8,13 +9,19 @@ import io.restassured.parsing.Parser;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import java.util.List;+import static io.restassured.RestAssured.given;+import static org.hamcrest.MatcherAssert.assertThat;+import static org.hamcrest.Matchers.contains;import static org.hamcrest.Matchers.containsInAnyOrder;import static org.hamcrest.Matchers.containsString;import static org.hamcrest.Matchers.equalTo;import static org.hamcrest.Matchers.hasSize;import static org.hamcrest.Matchers.not;import static org.hamcrest.Matchers.nullValue;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;@QuarkusTestclass CloudFormationCognitoUserPoolGroupIntegrationTest {@@ -142,6 +149,155 @@ class CloudFormationCognitoUserPoolGroupIntegrationTest {.statusCode(200);}+ @Test+ void renamingAGroupReplacesItAndDeletesTheGroupUnderTheOldName() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-cognito-group-rename-" + suffix;++ String poolId = createStack(stackName, poolAndGroupsTemplate("admin", 0));++ updateStack(stackName, poolAndGroupsTemplate("operators", 0));++ String describeXml = describeStack(stackName);+ assertThat(describeXml, containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"));+ assertEquals("operators", output(describeXml, "AdminGroupName"));+ cognito("ListGroups", "{\"UserPoolId\": \"" + poolId + "\"}")+ .statusCode(200)+ .body("Groups.GroupName", containsInAnyOrder("operators", "readers"));+ cognito("GetGroup", "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"admin\"}")+ .statusCode(400)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ @Test+ void movingAnUnnamedGroupToAnotherPoolReplacesItUnderANewGeneratedName() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-cognito-group-move-" + suffix;++ String firstPool = createStack(stackName, twoPoolsAndUnnamedGroupTemplate("FirstPool"));+ String describeXml = describeStack(stackName);+ String secondPool = output(describeXml, "SecondPoolId");+ String original = output(describeXml, "GroupName");++ updateStack(stackName, twoPoolsAndUnnamedGroupTemplate("SecondPool"));++ describeXml = describeStack(stackName);+ assertThat(describeXml, containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"));+ String replacement = output(describeXml, "GroupName");+ assertNotEquals(original, replacement, "a pool move replaces the group under a fresh name");+ cognito("ListGroups", "{\"UserPoolId\": \"" + secondPool + "\"}")+ .statusCode(200)+ .body("Groups.GroupName", contains(replacement));+ cognito("ListGroups", "{\"UserPoolId\": \"" + firstPool + "\"}")+ .statusCode(200)+ .body("Groups", hasSize(0));+ }++ @Test+ void aFailedUpdateAfterMovingANamedGroupKeepsTheOldPoolGroupAndLeavesTheNewOneBehind() {+ // Measured on AWS: the group's physical id, the bare name, does not change, so the rollback+ // points the resource at the old pool's group again and skips deleting the new pool's group.+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-cognito-group-move-rollback-" + suffix;+ String name = "movers-" + suffix;+ String firstPool = createPool(stackName + "-p1");+ String secondPool = createPool(stackName + "-p2");++ createStackAndWait(stackName, namedGroupTemplate(firstPool, name, false));++ // Duplicate depends on Group and claims the new pool and the same name, so it fails after+ // the group exists in the new pool and the update rolls back.+ updateStack(stackName, namedGroupTemplate(secondPool, name, true));++ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);+ assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());+ assertEquals(name, output(describeStack(stackName), "GroupRef"));+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStackResource")+ .formParam("StackName", stackName)+ .formParam("LogicalResourceId", "Group")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<PhysicalResourceId>" + name + "</PhysicalResourceId>"));+ cognito("GetGroup", "{\"UserPoolId\": \"" + firstPool + "\", \"GroupName\": \"" + name + "\"}")+ .statusCode(200)+ .body("Group.Description", equalTo("d1"))+ .body("Group.Precedence", equalTo(1));+ cognito("ListGroups", "{\"UserPoolId\": \"" + firstPool + "\"}")+ .statusCode(200)+ .body("Groups.GroupName", contains(name));+ cognito("ListGroups", "{\"UserPoolId\": \"" + secondPool + "\"}")+ .statusCode(200)+ .body("Groups.GroupName", contains(name));++ deleteStackAndWait(stackName);++ cognito("ListGroups", "{\"UserPoolId\": \"" + firstPool + "\"}")+ .statusCode(200)+ .body("Groups", hasSize(0));+ cognito("ListGroups", "{\"UserPoolId\": \"" + secondPool + "\"}")+ .statusCode(200)+ .body("Groups.GroupName", contains(name));+ }++ @Test+ void declaringAGeneratedGroupNameExplicitlyIsRefusedAndRollsBack() {+ // Measured on AWS: GroupName is create-only, so declaring the generated name requires a+ // replacement keeping the same pool and name, which is refused before anything is created.+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-cognito-group-declare-" + suffix;+ String poolId = createPool(stackName);++ createStackAndWait(stackName, unnamedGroupTemplate(poolId));+ String generated = output(describeStack(stackName), "GroupRef");+ Object createdAt = cognito("GetGroup",+ "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"" + generated + "\"}")+ .statusCode(200)+ .extract().path("Group.CreationDate");++ updateStack(stackName, namedGroupTemplate(poolId, generated, false));++ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);+ assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());+ List<String> failures = XmlParser.extractGroups(describeEvents(stackName), "member").stream()+ .filter(event -> "Group".equals(event.get("LogicalResourceId"))+ && "UPDATE_FAILED".equals(event.get("ResourceStatus")))+ .map(event -> event.get("ResourceStatusReason"))+ .toList();+ assertThat(failures, contains(containsString("CloudFormation cannot update a stack when a custom-named"+ + " resource requires replacing. Rename " + generated + " and update the stack again.")));+ assertEquals(generated, output(describeStack(stackName), "GroupRef"));+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStackResource")+ .formParam("StackName", stackName)+ .formParam("LogicalResourceId", "Group")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<PhysicalResourceId>" + generated + "</PhysicalResourceId>"));+ cognito("GetGroup", "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"" + generated + "\"}")+ .statusCode(200)+ .body("Group.Description", equalTo("d1"))+ .body("Group.Precedence", equalTo(1))+ .body("Group.CreationDate", equalTo(createdAt));+ cognito("ListGroups", "{\"UserPoolId\": \"" + poolId + "\"}")+ .statusCode(200)+ .body("Groups.GroupName", contains(generated));++ deleteStackAndWait(stackName);++ cognito("ListGroups", "{\"UserPoolId\": \"" + poolId + "\"}")+ .statusCode(200)+ .body("Groups", hasSize(0));+ }+@Testvoid poolSchemaCustomAttributesAreNamespacedAndStandardOnesAreNot() {String suffix = Long.toString(System.nanoTime(), 36);@@ -190,6 +346,84 @@ class CloudFormationCognitoUserPoolGroupIntegrationTest {.split("<OutputValue>")[1].split("</OutputValue>")[0];}+ private void updateStack(String stackName, String template) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "UpdateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ /** Creates the stack and waits for CREATE_COMPLETE, for templates without a PoolId output. */+ private void createStackAndWait(String stackName, String template) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);+ assertEquals("CREATE_COMPLETE", state.status(), state.reason());+ }++ private void deleteStackAndWait(String stackName) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ CfnStackWaits.awaitStackDeleted(stackName);+ }++ private String createPool(String poolName) {+ return cognito("CreateUserPool", "{\"PoolName\": \"" + poolName + "\"}")+ .statusCode(200)+ .extract().path("UserPool.Id");+ }++ private String describeStack(String stackName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ }++ private String describeEvents(String stackName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStackEvents")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ }++ private static String output(String describeXml, String key) {+ return XmlParser.extractPairs(describeXml, "Outputs", "OutputKey", "OutputValue").get(key);+ }+private io.restassured.response.ValidatableResponse cognito(String target, String body) {return given().config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()@@ -241,6 +475,90 @@ class CloudFormationCognitoUserPoolGroupIntegrationTest {""".formatted(adminGroupName, adminPrecedence);}+ /** Two pools and a group without a GroupName, placed in the pool named by {@code poolLogicalId}. */+ private static String twoPoolsAndUnnamedGroupTemplate(String poolLogicalId) {+ return """+ {+ "Resources": {+ "FirstPool": {+ "Type": "AWS::Cognito::UserPool",+ "Properties": { "UserPoolName": "cfn-group-pool-first" }+ },+ "SecondPool": {+ "Type": "AWS::Cognito::UserPool",+ "Properties": { "UserPoolName": "cfn-group-pool-second" }+ },+ "Group": {+ "Type": "AWS::Cognito::UserPoolGroup",+ "Properties": {+ "UserPoolId": { "Ref": "%s" },+ "Description": "moves between pools"+ }+ }+ },+ "Outputs": {+ "PoolId": { "Value": { "Ref": "FirstPool" } },+ "SecondPoolId": { "Value": { "Ref": "SecondPool" } },+ "GroupName": { "Value": { "Ref": "Group" } }+ }+ }+ """.formatted(poolLogicalId);+ }++ /**+ * A named group in a pool created outside the stack. With {@code duplicate}, a second group of+ * the same pool and name depends on it and fails with GroupExistsException once it exists.+ */+ private static String namedGroupTemplate(String poolId, String groupName, boolean duplicate) {+ String duplicateResource = !duplicate ? "" : """+ ,+ "Duplicate": {+ "Type": "AWS::Cognito::UserPoolGroup",+ "DependsOn": "Group",+ "Properties": { "UserPoolId": "%s", "GroupName": "%s" }+ }+ """.formatted(poolId, groupName);+ return """+ {+ "Resources": {+ "Group": {+ "Type": "AWS::Cognito::UserPoolGroup",+ "Properties": {+ "UserPoolId": "%s",+ "GroupName": "%s",+ "Description": "d1",+ "Precedence": 1+ }+ }%s+ },+ "Outputs": {+ "GroupRef": { "Value": { "Ref": "Group" } }+ }+ }+ """.formatted(poolId, groupName, duplicateResource);+ }++ /** The named group's template without a GroupName, so CloudFormation generates one. */+ private static String unnamedGroupTemplate(String poolId) {+ return """+ {+ "Resources": {+ "Group": {+ "Type": "AWS::Cognito::UserPoolGroup",+ "Properties": {+ "UserPoolId": "%s",+ "Description": "d1",+ "Precedence": 1+ }+ }+ },+ "Outputs": {+ "GroupRef": { "Value": { "Ref": "Group" } }+ }+ }+ """.formatted(poolId);+ }+private static String poolAndStudentGroupOnlyTemplate() {return """{diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisionerTest.javaindex 5e43e1b302..0c52afedb3 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolGroupCfnProvisionerTest.java@@ -14,6 +14,9 @@ import java.util.Map;import java.util.Set;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+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.ArgumentMatchers.any;@@ -144,6 +147,220 @@ class CognitoUserPoolGroupCfnProvisionerTest {assertEquals("operators", r.getPhysicalId());}+ @Test+ void renamingReplacesTheGroupAndTheCleanupDeletesTheOldNameInItsPool() {+ StackResource r = resource(null);+ provisioner.provision(r, props("us-east-1_a", "admin"), ctx());++ provisioner.provision(r, props("us-east-1_a", "operators"), ctx("admin"));++ verify(cognito).createGroup("us-east-1_a", "operators", null, null, null);+ assertEquals("operators", r.getPhysicalId());+ assertTrue(provisioner.hasReplacementUpdate(r));+ assertEquals("admin", provisioner.updateCleanupPhysicalId(r));+ verify(cognito, never()).deleteGroup(any(), any());++ UpdateCleanupResult result = provisioner.completeUpdate(r);++ assertTrue(result.complete());+ verify(cognito).deleteGroup("us-east-1_a", "admin");+ verify(cognito, never()).deleteGroup("us-east-1_a", "operators");+ }++ @Test+ void thePoolRecordKeepsOnlyTheCurrentGroupOnceNoDeleteIsOwed() {+ StackResource r = resource(null);+ provisioner.provision(r, props("us-east-1_a", "admin"), ctx());+ provisioner.provision(r, props("us-east-1_a", "ops"), ctx("admin"));+ provisioner.completeUpdate(r);+ provisioner.provision(r, props("us-east-1_a", "staff"), ctx("ops"));+ provisioner.completeUpdate(r);++ provisioner.provision(r, props("us-east-1_a", "staff"), ctx("staff"));++ assertEquals("{\"staff\":\"us-east-1_a\"}", r.getAttributes().get("__FlociGroupPools"));+ }++ @Test+ void movingANamedGroupToAnotherPoolCreatesItThereAndOwesNoDelete() {+ // AWS replaces the group but deletes nothing: the physical id, the bare name, is unchanged.+ StackResource r = resource(null);+ provisioner.provision(r, props("us-east-1_a", "admin"), ctx());++ provisioner.provision(r, props("us-east-1_b", "admin"), ctx("admin"));++ verify(cognito).createGroup("us-east-1_b", "admin", null, null, null);+ verify(cognito, never()).updateGroup(any(), any(), any(), any(), any());+ assertEquals("admin", r.getPhysicalId());+ assertEquals("us-east-1_b", r.getAttributes().get("UserPoolId"));+ assertFalse(provisioner.hasReplacementUpdate(r));+ assertNull(provisioner.updateCleanupPhysicalId(r));+ UpdateCleanupResult result = provisioner.completeUpdate(r);+ assertTrue(result.complete());+ assertNull(result.previousPhysicalId());+ verify(cognito, never()).deleteGroup(any(), any());+ }++ @Test+ void rollingBackANamedPoolMovePointsAtTheOldPoolGroupAndLeavesTheNewOne() {+ // Measured on AWS: the physical id did not change, so the rollback deletes nothing.+ StackResource r = resource(null);+ provisioner.provision(r, props("us-east-1_a", "admin"), ctx());+ provisioner.provision(r, props("us-east-1_b", "admin"), ctx("admin"));++ assertTrue(provisioner.rollbackUpdate(r));++ verify(cognito, never()).deleteGroup(any(), any());+ assertEquals("admin", r.getPhysicalId());+ assertEquals("us-east-1_a", r.getAttributes().get("UserPoolId"));+ assertFalse(provisioner.hasReplacementUpdate(r));++ provisioner.delete(r, "us-east-1");++ verify(cognito).deleteGroup("us-east-1_a", "admin");+ verify(cognito, never()).deleteGroup(eq("us-east-1_b"), any());+ }++ @Test+ void aLegacyResourceWithAnExplicitLookingNameIsReplacedWhenTheNameIsDropped() {+ // Persisted before the name mode was recorded: a name without the generated shape was explicit.+ StackResource r = resource("admin");+ r.setAttributes(new HashMap<>(Map.of("UserPoolId", "us-east-1_a")));++ provisioner.provision(r, props("us-east-1_a", null), ctx("admin"));++ String generated = r.getPhysicalId();+ assertTrue(generated.startsWith("my-stack-AdminGroup-"), generated);+ verify(cognito).createGroup("us-east-1_a", generated, null, null, null);+ verify(cognito, never()).updateGroup(any(), any(), any(), any(), any());+ assertEquals("admin", provisioner.updateCleanupPhysicalId(r));+ }++ @Test+ void aLegacyResourceWithAGeneratedNameKeepsItAndUpdatesInPlace() {+ String legacy = ctx().generatePhysicalName("AdminGroup", 128, false);+ StackResource r = resource(legacy);+ r.setAttributes(new HashMap<>(Map.of("UserPoolId", "us-east-1_a")));++ provisioner.provision(r, props("us-east-1_a", null), ctx(legacy));++ assertEquals(legacy, r.getPhysicalId());+ verify(cognito).updateGroup("us-east-1_a", legacy, null, null, null);+ verify(cognito, never()).createGroup(any(), any(), any(), any(), any());+ assertFalse(provisioner.hasReplacementUpdate(r));+ }++ @Test+ void aLegacyResourceWithAGeneratedLookingExplicitNameUpdatesInPlace() {+ // Persisted before the name mode was recorded: the shape cannot tell an explicit name from+ // a generated one, so declaring the same name keeps the pre-mode in-place update.+ StackResource r = resource("my-stack-AdminGroup-0123456789ab");+ r.setAttributes(new HashMap<>(Map.of("UserPoolId", "us-east-1_a")));++ provisioner.provision(r, props("us-east-1_a", "my-stack-AdminGroup-0123456789ab"),+ ctx("my-stack-AdminGroup-0123456789ab"));++ verify(cognito).updateGroup("us-east-1_a", "my-stack-AdminGroup-0123456789ab", null, null, null);+ verify(cognito, never()).createGroup(any(), any(), any(), any(), any());+ }++ @Test+ void droppingTheExplicitNameReplacesTheGroupUnderAGeneratedNameAndDeletesTheNamedOne() {+ StackResource r = resource(null);+ provisioner.provision(r, props("us-east-1_a", "admin"), ctx());++ provisioner.provision(r, props("us-east-1_a", null), ctx("admin"));++ String generated = r.getPhysicalId();+ assertTrue(generated.startsWith("my-stack-AdminGroup-"), generated);+ verify(cognito).createGroup("us-east-1_a", generated, null, null, null);+ assertEquals("admin", provisioner.updateCleanupPhysicalId(r));++ provisioner.completeUpdate(r);++ verify(cognito).deleteGroup("us-east-1_a", "admin");+ }++ @Test+ void declaringTheGeneratedNameExplicitlyIsRefusedAsACustomNamedReplacement() {+ // Measured on AWS: GroupName is create-only, so declaring it replaces the group, and a+ // replacement keeping the same pool and name is refused before anything is created.+ StackResource r = resource(null);+ provisioner.provision(r, props("us-east-1_a", null), ctx());+ String generated = r.getPhysicalId();++ AwsException thrown = assertThrows(AwsException.class,+ () -> provisioner.provision(r, props("us-east-1_a", generated), ctx(generated)));++ assertEquals("ValidationError", thrown.getErrorCode());+ assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "+ + "Rename " + generated + " and update the stack again.", thrown.getMessage());+ verify(cognito, times(1)).createGroup(any(), any(), any(), any(), any());+ verify(cognito, never()).updateGroup(any(), any(), any(), any(), any());+ }++ @Test+ void movingAGeneratedGroupToAnotherPoolGeneratesANewNameAndDeletesTheOldOneFromTheOldPool() {+ StackResource r = resource(null);+ provisioner.provision(r, props("us-east-1_a", null), ctx());+ String original = r.getPhysicalId();++ provisioner.provision(r, props("us-east-1_b", null), ctx(original));++ String replacement = r.getPhysicalId();+ assertNotEquals(original, replacement);+ assertTrue(replacement.startsWith("my-stack-AdminGroup-"), replacement);+ verify(cognito).createGroup("us-east-1_b", replacement, null, null, null);+ assertEquals(original, provisioner.updateCleanupPhysicalId(r));++ provisioner.completeUpdate(r);++ verify(cognito).deleteGroup("us-east-1_a", original);+ verify(cognito, never()).deleteGroup(eq("us-east-1_b"), any());+ }++ @Test+ void anInPlaceUpdateChangesTheGroupAndOwesNoCleanup() {+ StackResource named = resource(null);+ provisioner.provision(named, props("us-east-1_a", "admin"), ctx());+ StackResource unnamed = resource(null);+ provisioner.provision(unnamed, props("us-east-1_a", null), ctx());+ String generated = unnamed.getPhysicalId();++ ObjectNode namedUpdate = props("us-east-1_a", "admin");+ namedUpdate.put("Description", "d2");+ namedUpdate.put("Precedence", 2);+ provisioner.provision(named, namedUpdate, ctx("admin"));+ provisioner.provision(unnamed, props("us-east-1_a", null), ctx(generated));++ verify(cognito).updateGroup("us-east-1_a", "admin", "d2", 2, null);+ verify(cognito).updateGroup("us-east-1_a", generated, null, null, null);+ verify(cognito, times(2)).createGroup(any(), any(), any(), any(), any());+ assertEquals("admin", named.getPhysicalId());+ assertEquals(generated, unnamed.getPhysicalId());+ assertFalse(provisioner.hasReplacementUpdate(named));+ assertFalse(provisioner.hasReplacementUpdate(unnamed));+ }++ @Test+ void rollingBackARenameDeletesTheReplacementAndRestoresThePriorNameAndPool() {+ StackResource r = resource(null);+ provisioner.provision(r, props("us-east-1_a", "admin"), ctx());+ provisioner.provision(r, props("us-east-1_b", "operators"), ctx("admin"));++ assertTrue(provisioner.rollbackUpdate(r));++ verify(cognito).deleteGroup("us-east-1_b", "operators");+ verify(cognito, never()).deleteGroup(any(), eq("admin"));+ assertEquals("admin", r.getPhysicalId());+ assertEquals("us-east-1_a", r.getAttributes().get("UserPoolId"));+ assertFalse(provisioner.hasReplacementUpdate(r));++ provisioner.delete(r, "us-east-1");++ verify(cognito).deleteGroup("us-east-1_a", "admin");+ }+@Testvoid missingUserPoolIdFailsTheResourceRatherThanStubbingIt() {StackResource r = resource(null);diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.javaindex 79fcd341f1..12a344e79d 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java@@ -205,6 +205,27 @@ class ProvisionContextTest {"a replacing update derives a different name and must still create");}+ @Test+ void isGeneratedPhysicalNameRecognisesOnlyWhatGeneratePhysicalNameProducesForTheLogicalId() {+ ProvisionContext ctx = context(null);+ String generated = ctx.generatePhysicalName("AdminGroup", 128, false);+ assertTrue(ctx.isGeneratedPhysicalName(generated, "AdminGroup", 128, false), generated);++ ProvisionContext longStack = new ProvisionContext(engine, "us-east-1", "000000000000",+ "a-stack-name-long-enough-to-force-truncation", null);+ String longLogicalId = "AVeryLongLogicalIdThatPushesTheGeneratedNamePastItsLimit";+ String truncated = longStack.generatePhysicalName(longLogicalId, 64, false);+ assertEquals(64, truncated.length(), truncated);+ assertTrue(longStack.isGeneratedPhysicalName(truncated, longLogicalId, 64, false), truncated);++ assertFalse(ctx.isGeneratedPhysicalName("admin", "AdminGroup", 128, false), "an explicit name");+ assertFalse(ctx.isGeneratedPhysicalName(ctx.generatePhysicalName("OtherGroup", 128, false),+ "AdminGroup", 128, false), "another logical id's name");+ assertFalse(ctx.isGeneratedPhysicalName("my-stack-AdminGroup-0123456789zz", "AdminGroup", 128, false),+ "a suffix that is not hex");+ assertFalse(ctx.isGeneratedPhysicalName(null, "AdminGroup", 128, false));+ }+/*** The whole property node is handed to {@code engine.resolveStringList}, so a list-valueddiff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanupTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanupTest.javaindex 36eaaff955..9b04445d4d 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanupTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanupTest.java@@ -198,4 +198,42 @@ class ReplacementCleanupTest {assertNull(previous.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR));}++ @Test+ void aReplacementThatKeptItsPhysicalIdRollsBackWithoutADeleteAndDisplacesNothing() {+ StackResource r = resource("subnet-1");+ r.getAttributes().put("VpcId", "vpc-new");+ List<String> deleted = new ArrayList<>();++ ReplacementCleanup.record(r, update("subnet-1"), Map.of("VpcId", "vpc-old"), true);++ assertFalse(ReplacementCleanup.hasReplacement(r));+ assertNull(ReplacementCleanup.cleanupPhysicalId(r));+ assertTrue(ReplacementCleanup.rollback(r, (type, id, region) -> deleted.add(id)));+ assertEquals("subnet-1", r.getPhysicalId());+ assertEquals("vpc-old", r.getAttributes().get("VpcId"));+ assertEquals(List.of(), deleted);+ assertNull(r.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR));+ }++ @Test+ void theThreeArgumentRecordStillKeysTheReplacementOnAChangedPhysicalId() {+ StackResource inPlace = resource("subnet-1");+ ReplacementCleanup.record(inPlace, update("subnet-1"), Map.of("VpcId", "vpc-old"));+ assertNull(inPlace.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR));+ assertFalse(ReplacementCleanup.rollback(inPlace, (type, id, region) -> { }));++ StackResource replaced = resource("subnet-2");+ List<String> deleted = new ArrayList<>();+ ReplacementCleanup.record(replaced, update("subnet-1"), Map.of("VpcId", "vpc-old"));+ assertTrue(ReplacementCleanup.hasReplacement(replaced));+ assertEquals("subnet-1", ReplacementCleanup.cleanupPhysicalId(replaced));+ assertTrue(ReplacementCleanup.rollback(replaced, (type, id, region) -> deleted.add(id)));+ assertEquals("subnet-1", replaced.getPhysicalId());+ assertEquals(List.of("subnet-2"), deleted);+ }++ private static ProvisionContext update(String priorPhysicalId) {+ return new ProvisionContext(null, "us-east-1", "000000000000", "my-stack", priorPhysicalId);+ }}