From 2749cd6fcdf27429bd6c2029a8fe585e9832d977 Mon Sep 17 00:00:00 2001 From: Mario Toffia Date: Sun, 4 Oct 2026 23:00:35 +0200 Subject: [PATCH] feat(cognito): provision user group attachments (#4806) * feat(cognito): provision user group attachments Serve AWS::Cognito::UserPoolUserToGroupAttachment through a new per-service provisioner. Ref is ||, as measured on AWS. Every property is createOnly, so a change replaces the membership and the old one is removed in cleanup; delete tolerates a membership that is already gone. * test(cognito): read stack outputs with XmlPath * fix(cognito): attach users to groups from their recorded parts, as AWS does * test(cognito): cover pipe group names and alias updates, delete seeded pools * fix(cognito): remove an unrecorded attachment named unambiguously by its id * test(cognito): pin that a failed rollback keeps the replacement's recorded parts * fix(docker): finish a failed tar copy's writer before retrying * test(docker): wait for each attempt's tar writer instead of racing it Restores RetryingTarCopier.copyStreamed to its state on main: joining a failed attempt's writer could block on a writer stalled outside the pipe. * docs(cloudformation): note the no-op delete of a short membership id The class Javadoc said an unrecorded id that does not split into exactly three parts is refused. An id of fewer parts names no membership and its delete does nothing; only more parts is refused. * fix(cloudformation): keep __Floci attributes out of Fn::GetAtt Provisioners keep private state under __Floci attribute keys. Fn::GetAtt and Fn::Sub resolved them like any attribute, so a template could read, for example, an attachment's recorded pool, group and username, while AWS resolves no such attribute. They now resolve as unresolved, like any attribute a type does not have. * docs(cloudformation): note that custom resource Data keys under __Floci are reserved --- ...ationCognitoUserToGroupAttachmentTest.java | 167 ++++++++ docs/services/cloudformation.md | 5 +- .../CloudFormationTemplateEngine.java | 3 +- ...olUserToGroupAttachmentCfnProvisioner.java | 191 ++++++++++ .../common/docker/RetryingTarCopierTest.java | 11 +- .../cloudformation/CfnProvisionerFixture.java | 2 + ...oUserToGroupAttachmentIntegrationTest.java | 253 +++++++++++++ .../CloudFormationTemplateEngineTest.java | 14 + ...erToGroupAttachmentCfnProvisionerTest.java | 358 ++++++++++++++++++ .../supported-resource-types.tsv | 1 + 10 files changed, 999 insertions(+), 6 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserToGroupAttachmentTest.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisioner.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserToGroupAttachmentIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisionerTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserToGroupAttachmentTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserToGroupAttachmentTest.java new file mode 100644 index 0000000000..4ecd11c26a --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserToGroupAttachmentTest.java @@ -0,0 +1,167 @@ +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.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.cognitoidentityprovider.CognitoIdentityProviderClient; +import software.amazon.awssdk.services.cognitoidentityprovider.model.GroupType; +import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType; + +import java.util.List; +import java.util.function.BooleanSupplier; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("CloudFormation AWS::Cognito::UserPoolUserToGroupAttachment") +class CloudFormationCognitoUserToGroupAttachmentTest { + + private static final String USER = "user-one"; + private static final String TEMPLATE = """ + { + "Parameters": { + "PoolId": {"Type": "String"}, + "GroupName": {"Type": "String"}, + "Username": {"Type": "String"} + }, + "Resources": { + "Attach": { + "Type": "AWS::Cognito::UserPoolUserToGroupAttachment", + "Properties": { + "UserPoolId": {"Ref": "PoolId"}, + "GroupName": {"Ref": "GroupName"}, + "Username": {"Ref": "Username"} + } + } + }, + "Outputs": {"AttachRef": {"Value": {"Ref": "Attach"}}} + } + """; + + private static CloudFormationClient cfn; + private static CognitoIdentityProviderClient cognito; + private static String poolId; + private String stackName; + private boolean stackCreated; + + @BeforeAll + static void seed() { + cfn = TestFixtures.cloudFormationClient(); + cognito = TestFixtures.cognitoClient(); + poolId = cognito.createUserPool(r -> r.poolName(TestFixtures.uniqueName("compat-cfn-attach"))) + .userPool().id(); + cognito.adminCreateUser(r -> r.userPoolId(poolId).username(USER) + .messageAction(MessageActionType.SUPPRESS)); + for (String group : List.of("grp-a", "grp-b")) { + cognito.createGroup(r -> r.userPoolId(poolId).groupName(group)); + } + } + + @AfterEach + void cleanup() throws InterruptedException { + deleteStack(); + } + + @AfterAll + static void teardown() { + try { + cognito.deleteUserPool(r -> r.userPoolId(poolId)); + } finally { + cognito.close(); + cfn.close(); + } + } + + @Test + void attachmentAddsMovesAndRemovesTheMembership() throws InterruptedException { + stackName = TestFixtures.uniqueName("compat-cfn-attach"); + + cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameters("grp-a"))); + stackCreated = true; + awaitStatus("CREATE_COMPLETE"); + assertThat(output()).as("Ref is ||") + .isEqualTo(poolId + "|grp-a|" + USER); + assertThat(groups()).containsExactly("grp-a"); + + cfn.updateStack(r -> r.stackName(stackName).templateBody(TEMPLATE).parameters(parameters("grp-b"))); + awaitStatus("UPDATE_COMPLETE"); + assertThat(output()).isEqualTo(poolId + "|grp-b|" + USER); + assertThat(groups()).as("the replaced membership is removed in cleanup").containsExactly("grp-b"); + + deleteStack(); + assertThat(groups()).isEmpty(); + } + + private static List parameters(String groupName) { + return List.of( + Parameter.builder().parameterKey("PoolId").parameterValue(poolId).build(), + Parameter.builder().parameterKey("GroupName").parameterValue(groupName).build(), + Parameter.builder().parameterKey("Username").parameterValue(USER).build()); + } + + private List groups() { + return cognito.adminListGroupsForUser(r -> r.userPoolId(poolId).username(USER)).groups().stream() + .map(GroupType::groupName).toList(); + } + + private String output() { + return cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).outputs().stream() + .filter(o -> "AttachRef".equals(o.outputKey())).map(Output::outputValue) + .findFirst().orElseThrow(); + } + + private void awaitStatus(String expected) throws InterruptedException { + await(() -> { + Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0); + String status = stack.stackStatusAsString(); + if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) { + throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason()); + } + return expected.equals(status); + }, expected); + } + + private void deleteStack() throws InterruptedException { + if (!stackCreated) { + return; + } + cfn.deleteStack(r -> r.stackName(stackName)); + await(() -> { + try { + List stacks = cfn.describeStacks(r -> r.stackName(stackName)).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"); + stackCreated = false; + } + + private void await(BooleanSupplier condition, String expected) throws InterruptedException { + long deadline = System.nanoTime() + 60_000_000_000L; + while (System.nanoTime() < deadline) { + if (condition.getAsBoolean()) { + return; + } + Thread.sleep(100); + } + throw new AssertionError(stackName + " timed out waiting for " + expected); + } +} diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 3cc85769c2..4768eceec6 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -152,7 +152,7 @@ cross-resource references. | CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` | | CodeBuild | `Project` | | Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` | -| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `/`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolUser` | +| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `/`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolUser`, `UserPoolUserToGroupAttachment` | | ACM | `Certificate` | | EventBridge | `Rule`, `EventBus`, `EventBusPolicy`, `Archive` (`KmsKeyIdentifier` is ignored) | | EventBridge Scheduler | `ScheduleGroup` | @@ -409,6 +409,9 @@ Lambda. floci supports two shapes: ResponseURL callback fires. The wait is bounded by an async custom-resource timeout (3 minutes by default); a resource that never completes fails the stack rather than hanging. +The handler's `Data` keys resolve through `Fn::GetAtt`, except keys that begin with `__Floci`. Floci +reserves that prefix for its own resource state, which no template can read. + ## Deleted Stacks A deleted stack is kept for a short window afterwards rather than being forgotten at diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java index 2dc9a2996f..5902997fcc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java @@ -602,7 +602,8 @@ public class CloudFormationTemplateEngine { private String resolveGetAttParts(String logicalId, String attrName) { Map attrs = resourceAttributes.get(logicalId); - if (attrs != null && attrs.containsKey(attrName)) { + // Provisioners keep private state under __Floci keys; AWS resolves no such attribute. + if (attrs != null && attrs.containsKey(attrName) && !attrName.startsWith("__Floci")) { return attrs.get(attrName); } LOG.warnv("Unresolved GetAtt: {0}.{1}", logicalId, attrName); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisioner.java new file mode 100644 index 0000000000..49cd3487a2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisioner.java @@ -0,0 +1,191 @@ +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.ArrayNode; +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; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * CloudFormation provisioning for {@code AWS::Cognito::UserPoolUserToGroupAttachment}. {@code Ref} + * returns {@code ||}, with the Username as the template gives it. + * + *

Every property is createOnly, so any change is a replacement: the new membership is added and + * the old one is removed once the update commits, through {@link ReplacementCleanup}. The parts are + * recorded per physical id, because a group name or username may contain {@code |}, and a membership + * is removed from its recorded parts, as on AWS. Without a record, as for a Cloud Control delete of a + * membership it did not create, the membership is removed from its id when the id splits into exactly + * three parts. An id of fewer parts names no membership, so the delete does nothing, and an id of more + * parts is refused as ambiguous. Adding a user who is already in the group is refused as + * AlreadyExists, and a change that keeps the Ref is refused as a custom-named replacement, as on AWS. + */ +@ApplicationScoped +public class CognitoUserPoolUserToGroupAttachmentCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(CognitoUserPoolUserToGroupAttachmentCfnProvisioner.class); + private static final String TYPE = "AWS::Cognito::UserPoolUserToGroupAttachment"; + /** Physical id to its [UserPoolId, GroupName, Username], because names may contain {@code |}. */ + private static final String MEMBERSHIPS_ATTR = "__FlociCognitoMemberships"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final CognitoService cognitoService; + + @Inject + public CognitoUserPoolUserToGroupAttachmentCfnProvisioner(CognitoService cognitoService) { + this.cognitoService = cognitoService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + String userPoolId = require(props, "UserPoolId", ctx); + String groupName = require(props, "GroupName", ctx); + String username = require(props, "Username", ctx); + + Map attributesBefore = new HashMap<>(r.getAttributes()); + String physicalId = userPoolId + "|" + groupName + "|" + username; + ArrayNode membership = MAPPER.createArrayNode().add(userPoolId).add(groupName).add(username); + if (ctx.reusesPriorEntity(physicalId)) { + JsonNode prior = memberships(attributesBefore).get(physicalId); + if (prior != null && !prior.equals(membership)) { + throw new AwsException("ValidationError", + "CloudFormation cannot update a stack when a custom-named resource requires replacing. Rename " + + physicalId + " and update the stack again.", 400); + } + } else { + String member = cognitoService.adminGetUser(userPoolId, username).getUsername(); + if (cognitoService.getGroup(userPoolId, groupName).getUserNames().contains(member)) { + throw new AwsException("AlreadyExists", + "User with name " + member + " already exists in Group " + groupName + ".", 400); + } + cognitoService.adminAddUserToGroup(userPoolId, groupName, username); + } + r.setPhysicalId(physicalId); + ReplacementCleanup.record(r, ctx, attributesBefore); + recordMembership(r, attributesBefore, membership); + } + + private static String require(JsonNode props, String name, ProvisionContext ctx) { + String value = ctx.resolveOptional(props, name); + if (value == null || value.isBlank()) { + throw new AwsException("ValidationError", TYPE + " requires " + name, 400); + } + return value; + } + + @Override + public void delete(StackResource resource, String region) { + removeMembership(resource.getAttributes(), resource.getPhysicalId()); + } + + @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, (type, physicalId, region) -> + removeMembership(resource.getAttributes(), physicalId)); + } + + @Override + public void clearUpdate(StackResource resource) { + ReplacementCleanup.clear(resource); + } + + @Override + public boolean rollbackUpdate(StackResource resource) { + ReplacementCleanup.rollback(resource, (type, physicalId, region) -> + removeMembership(resource.getAttributes(), physicalId)); + // Every property is createOnly, so without a replacement nothing changed, including an + // update refused as AlreadyExists or as a custom-named replacement. + return true; + } + + private void removeMembership(Map attributes, String physicalId) { + String[] parts = physicalId == null ? null : membershipParts(attributes, physicalId); + if (parts == null) { + return; + } + String userPoolId = parts[0]; + String groupName = parts[1]; + String username = parts[2]; + CfnDeletes.safeDelete("Cognito group membership", physicalId, + () -> cognitoService.adminRemoveUserFromGroup(userPoolId, groupName, username), + "UserNotFoundException", "ResourceNotFoundException"); + } + + /** + * The [UserPoolId, GroupName, Username] of a membership: its recorded parts, else its id split on + * {@code |}. Null when the id is not a membership id; refused when a name holding {@code |} makes + * the split ambiguous. + */ + private static String[] membershipParts(Map attributes, String physicalId) { + JsonNode recorded = memberships(attributes).get(physicalId); + if (recorded != null && recorded.isArray() && recorded.size() == 3) { + return new String[] {recorded.get(0).asText(), recorded.get(1).asText(), recorded.get(2).asText()}; + } + String[] parts = physicalId.split("\\|", -1); + if (parts.length < 3) { + return null; + } + if (parts.length > 3) { + throw new AwsException("InvalidRequest", "Cannot tell the GroupName and Username of " + physicalId + + " apart without the attachment's recorded properties, because one of them holds |.", 400); + } + return parts; + } + + /** + * Keeps the parts of the membership the resource now names and of every membership still owed a + * delete, from this update or an earlier one, so each is removed from its own parts. Every other + * entry is dropped, so the record stays bounded across repeated replacements. Call after + * {@link ReplacementCleanup#record}, so the membership this update displaced is already owed. + */ + private static void recordMembership(StackResource r, Map attributesBefore, ArrayNode membership) { + ObjectNode prior = memberships(attributesBefore); + ObjectNode memberships = MAPPER.createObjectNode(); + for (String owed : ReplacementCleanup.owedPhysicalIds(r)) { + JsonNode parts = prior.get(owed); + if (parts != null) { + memberships.set(owed, parts); + } + } + memberships.set(r.getPhysicalId(), membership); + r.getAttributes().put(MEMBERSHIPS_ATTR, memberships.toString()); + } + + private static ObjectNode memberships(Map attributes) { + String recorded = attributes.get(MEMBERSHIPS_ATTR); + if (recorded != null) { + try { + if (MAPPER.readTree(recorded) instanceof ObjectNode memberships) { + return memberships; + } + } catch (JsonProcessingException e) { + LOG.warnv("Unreadable Cognito group membership record, ignoring it: {0}", e.getMessage()); + } + } + return MAPPER.createObjectNode(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/RetryingTarCopierTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/RetryingTarCopierTest.java index ef69eeb126..a5eaac12af 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/docker/RetryingTarCopierTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/RetryingTarCopierTest.java @@ -15,6 +15,8 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -156,21 +158,22 @@ class RetryingTarCopierTest { } @Test - void copyStreamedInvokesTheWriterFreshlyPerAttempt() { + void copyStreamedInvokesTheWriterFreshlyPerAttempt() throws InterruptedException { DockerClient docker = mock(DockerClient.class); AtomicInteger calls = new AtomicInteger(); failingOnce(docker, calls); - AtomicInteger writes = new AtomicInteger(); + CountDownLatch writes = new CountDownLatch(2); RetryingTarCopier.copyStreamed(docker, "c-1", "/var/task", "fn-code", out -> { - writes.incrementAndGet(); + writes.countDown(); out.write("x".getBytes(StandardCharsets.UTF_8)); }, MAX_ATTEMPTS, 0L); assertEquals(2, calls.get()); - assertEquals(2, writes.get(), "the tar content must be regenerated for every attempt"); + // A failed attempt's writer is never joined, so it may still be starting when copyStreamed returns. + assertTrue(writes.await(5, TimeUnit.SECONDS), "the tar content must be regenerated for every attempt"); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 631fcd1ead..9f35c742b0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -54,6 +54,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatc import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolGroupCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolUserCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolUserToGroupAttachmentCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2LaunchTemplateCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkAclCfnProvisioner; @@ -299,6 +300,7 @@ final class CfnProvisionerFixture { discovered.add(new CognitoCfnProvisioner(cognitoService)); discovered.add(new CognitoUserPoolGroupCfnProvisioner(cognitoService)); discovered.add(new CognitoUserPoolUserCfnProvisioner(cognitoService)); + discovered.add(new CognitoUserPoolUserToGroupAttachmentCfnProvisioner(cognitoService)); } if (cloudFrontService != null) { discovered.add(new CloudFrontCfnProvisioner(cloudFrontService)); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserToGroupAttachmentIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserToGroupAttachmentIntegrationTest.java new file mode 100644 index 0000000000..f41f5bc304 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserToGroupAttachmentIntegrationTest.java @@ -0,0 +1,253 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import io.restassured.config.EncoderConfig; +import io.restassured.http.ContentType; +import io.restassured.parsing.Parser; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * {@code AWS::Cognito::UserPoolUserToGroupAttachment} end to end. The pool, user and groups are + * seeded through the Cognito API and passed in as parameters, so the stack owns only the + * membership, and every assertion reads the membership back from Cognito. Each test deletes the + * pool it seeded. + */ +@QuarkusTest +class CloudFormationCognitoUserToGroupAttachmentIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String USER = "user-one"; + + private static final String TEMPLATE = """ + { + "Parameters": { + "PoolId": { "Type": "String" }, + "GroupName": { "Type": "String" }, + "Username": { "Type": "String" } + }, + "Resources": { + "Attach": { + "Type": "AWS::Cognito::UserPoolUserToGroupAttachment", + "Properties": { + "UserPoolId": { "Ref": "PoolId" }, + "GroupName": { "Ref": "GroupName" }, + "Username": { "Ref": "Username" } + } + } + }, + "Outputs": { + "AttachRef": { "Value": { "Ref": "Attach" } } + } + } + """; + + @BeforeAll + static void registerAwsJsonParser() { + RestAssured.registerParser(COGNITO_CONTENT_TYPE, Parser.JSON); + } + + @Test + void changingTheGroupReplacesTheMembershipAndDeleteToleratesOneRemovedOutOfBand() + throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String poolId = seedPoolUserAndGroups("cfn-attach-" + suffix); + String stackName = "cfn-cognito-attach-" + suffix; + + String stackId = stackCall("CreateStack", stackName, poolId, "grp-a"); + awaitStackStatus(stackId, "CREATE_COMPLETE"); + assertEquals(poolId + "|grp-a|" + USER, outputValue(stackId, "AttachRef")); + groupsOf(poolId).body("Groups.GroupName", contains("grp-a")); + + stackCall("UpdateStack", stackName, poolId, "grp-b"); + awaitStackStatus(stackId, "UPDATE_COMPLETE"); + assertEquals(poolId + "|grp-b|" + USER, outputValue(stackId, "AttachRef")); + groupsOf(poolId).body("Groups.GroupName", contains("grp-b")); + + cognito("AdminRemoveUserFromGroup", """ + {"UserPoolId": "%s", "GroupName": "grp-b", "Username": "%s"} + """.formatted(poolId, USER)).statusCode(200); + deleteStack(stackName); + awaitStackStatus(stackId, "DELETE_COMPLETE"); + groupsOf(poolId).body("Groups", empty()); + deletePool(poolId); + } + + @Test + void deletingTheStackRemovesTheMembership() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String poolId = seedPoolUserAndGroups("cfn-attach-del-" + suffix); + createGroup(poolId, "grp|c"); + String stackName = "cfn-cognito-attach-del-" + suffix; + + String stackId = stackCall("CreateStack", stackName, poolId, "grp|c"); + awaitStackStatus(stackId, "CREATE_COMPLETE"); + assertEquals(poolId + "|grp|c|" + USER, outputValue(stackId, "AttachRef")); + groupsOf(poolId).body("Groups.GroupName", contains("grp|c")); + + deleteStack(stackName); + awaitStackStatus(stackId, "DELETE_COMPLETE"); + groupsOf(poolId).body("Groups", empty()); + deletePool(poolId); + } + + @Test + void anAliasUpdateOfTheSameUserRollsBackAndKeepsTheMembership() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String email = "user-" + suffix + "@example.com"; + String poolId = cognito("CreateUserPool", """ + {"PoolName": "cfn-attach-alias-%s", "AliasAttributes": ["email"]} + """.formatted(suffix)) + .statusCode(200) + .extract().path("UserPool.Id"); + cognito("AdminCreateUser", """ + {"UserPoolId": "%s", "Username": "%s", "MessageAction": "SUPPRESS", + "UserAttributes": [{"Name": "email", "Value": "%s"}, {"Name": "email_verified", "Value": "true"}]} + """.formatted(poolId, USER, email)).statusCode(200); + createGroup(poolId, "grp-a"); + String stackName = "cfn-cognito-attach-alias-" + suffix; + String aliasRef = poolId + "|grp-a|" + email; + + String stackId = stackCall("CreateStack", stackName, poolId, "grp-a", email); + awaitStackStatus(stackId, "CREATE_COMPLETE"); + assertEquals(aliasRef, outputValue(stackId, "AttachRef")); + groupsOf(poolId).body("Groups.GroupName", contains("grp-a")); + + stackCall("UpdateStack", stackName, poolId, "grp-a", USER); + awaitStackStatus(stackId, "UPDATE_ROLLBACK_COMPLETE"); + assertEquals(aliasRef, outputValue(stackId, "AttachRef")); + groupsOf(poolId).body("Groups.GroupName", contains("grp-a")); + + deleteStack(stackName); + awaitStackStatus(stackId, "DELETE_COMPLETE"); + groupsOf(poolId).body("Groups", empty()); + deletePool(poolId); + } + + private String seedPoolUserAndGroups(String poolName) { + String poolId = cognito("CreateUserPool", "{\"PoolName\": \"" + poolName + "\"}") + .statusCode(200) + .extract().path("UserPool.Id"); + cognito("AdminCreateUser", """ + {"UserPoolId": "%s", "Username": "%s", "MessageAction": "SUPPRESS"} + """.formatted(poolId, USER)).statusCode(200); + for (String group : new String[] {"grp-a", "grp-b"}) { + createGroup(poolId, group); + } + return poolId; + } + + private void createGroup(String poolId, String groupName) { + cognito("CreateGroup", """ + {"UserPoolId": "%s", "GroupName": "%s"} + """.formatted(poolId, groupName)).statusCode(200); + } + + private void deletePool(String poolId) { + cognito("DeleteUserPool", """ + {"UserPoolId": "%s"} + """.formatted(poolId)).statusCode(200); + } + + private ValidatableResponse groupsOf(String poolId) { + return cognito("AdminListGroupsForUser", """ + {"UserPoolId": "%s", "Username": "%s"} + """.formatted(poolId, USER)).statusCode(200); + } + + /** CreateStack or UpdateStack with the attachment template for the seeded user; returns the stack id. */ + private static String stackCall(String action, String stackName, String poolId, String groupName) { + return stackCall(action, stackName, poolId, groupName, USER); + } + + /** CreateStack or UpdateStack with the attachment template; returns the stack id. */ + private static String stackCall(String action, String stackName, String poolId, String groupName, + String username) { + String xml = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", action) + .formParam("StackName", stackName) + .formParam("TemplateBody", TEMPLATE) + .formParam("Parameters.member.1.ParameterKey", "PoolId") + .formParam("Parameters.member.1.ParameterValue", poolId) + .formParam("Parameters.member.2.ParameterKey", "GroupName") + .formParam("Parameters.member.2.ParameterValue", groupName) + .formParam("Parameters.member.3.ParameterKey", "Username") + .formParam("Parameters.member.3.ParameterValue", username) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + return XmlPath.from(xml).getString(action + "Response." + action + "Result.StackId"); + } + + private static void deleteStack(String stackName) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static String describeStacks(String stackId) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackId) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + } + + private static void awaitStackStatus(String stackId, String status) throws InterruptedException { + String xml = ""; + long deadline = System.currentTimeMillis() + 10_000; + while (System.currentTimeMillis() < deadline) { + xml = describeStacks(stackId); + if (status.equals(XmlPath.from(xml).getString( + "DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackStatus"))) { + return; + } + Thread.sleep(50); + } + fail("stack " + stackId + " never reached " + status + ": " + xml); + } + + private static String outputValue(String stackId, String key) { + return XmlPath.from(describeStacks(stackId)).getString( + "DescribeStacksResponse.DescribeStacksResult.Stacks.member.Outputs.member.find { it.OutputKey == '" + + key + "' }.OutputValue"); + } + + private ValidatableResponse cognito(String target, String body) { + return given() + .config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig() + .encodeContentTypeAs(COGNITO_CONTENT_TYPE, ContentType.TEXT))) + .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + target) + .contentType(COGNITO_CONTENT_TYPE) + .body(body) + .when() + .post("/") + .then(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java index c2e62d85dd..72940ce79c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java @@ -14,6 +14,7 @@ import java.util.function.Function; import java.util.function.UnaryOperator; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -147,6 +148,19 @@ class CloudFormationTemplateEngineTest { "{\"deadLetterTargetArn\":{\"Fn::GetAtt\":[\"Dlq\",\"Arn\"]}}"))); } + @Test + void getAttDoesNotExposeFlociInternalAttributes() { + CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000", + "us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), + Map.of("Res", Map.of("Arn", "arn:res", "__FlociSecret", "secret-value")), + Map.of(), Map.of(), mapper, (Function) name -> null); + + assertEquals("arn:res", e.resolve(json("{\"Fn::GetAtt\": [\"Res\", \"Arn\"]}"))); + assertEquals("Res.__FlociSecret", + e.resolve(json("{\"Fn::GetAtt\": [\"Res\", \"__FlociSecret\"]}"))); + assertNotEquals("secret-value", e.resolve(json("{\"Fn::Sub\": \"${Res.__FlociSecret}\"}"))); + } + @Test void resolveJsonAttributeReturnsNullForMissingOrNullNode() { assertNull(engine().resolveJsonAttribute(json("null"))); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisionerTest.java new file mode 100644 index 0000000000..a1665b27de --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserToGroupAttachmentCfnProvisionerTest.java @@ -0,0 +1,358 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +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.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cognito.CognitoService; +import io.github.hectorvent.floci.services.cognito.model.CognitoGroup; +import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * {@code AWS::Cognito::UserPoolUserToGroupAttachment} in isolation: Ref is + * {@code ||}, every property is createOnly so any change is a + * replacement, a user already in the group is refused as AlreadyExists, a change that keeps the Ref is + * refused as a custom-named replacement, and delete removes the membership from its recorded parts. + */ +class CognitoUserPoolUserToGroupAttachmentCfnProvisionerTest { + + private static final String TYPE = "AWS::Cognito::UserPoolUserToGroupAttachment"; + private static final String POOL = "us-east-1_pool"; + private static final String ID_A = POOL + "|grp-a|user-one"; + private static final String ID_B = POOL + "|grp-b|user-one"; + + private final CognitoService cognito = mock(CognitoService.class); + private final CognitoUserPoolUserToGroupAttachmentCfnProvisioner provisioner = + new CognitoUserPoolUserToGroupAttachmentCfnProvisioner(cognito); + private final ObjectMapper mapper = new ObjectMapper(); + + @BeforeEach + void everyUserExistsUnderItsOwnNameAndEveryGroupStartsEmpty() { + when(cognito.adminGetUser(any(), any())).thenAnswer(inv -> user(inv.getArgument(1))); + when(cognito.getGroup(any(), any())).thenAnswer(inv -> group(inv.getArgument(1))); + } + + @Test + void servesTheAttachmentType() { + assertEquals(Set.of(TYPE), provisioner.resourceTypes()); + } + + @Test + void createAddsTheUserToTheGroupAndRefIsTheCompositeId() { + StackResource r = resource(null); + + provisioner.provision(r, props(POOL, "grp-a", "user-one"), ctx(null)); + + verify(cognito).adminAddUserToGroup(POOL, "grp-a", "user-one"); + assertEquals(ID_A, r.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + @ParameterizedTest + @ValueSource(strings = {"UserPoolId", "GroupName", "Username"}) + void eachRequiredPropertyIsValidated(String missing) { + ObjectNode props = props(POOL, "grp-a", "user-one"); + props.remove(missing); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(resource(null), props, ctx(null))); + + assertEquals("ValidationError", failure.getErrorCode()); + assertEquals(TYPE + " requires " + missing, failure.getMessage()); + verifyNoInteractions(cognito); + } + + @Test + void anUnchangedUpdateKeepsTheIdAndCallsNothingOnCognito() { + StackResource r = resource(ID_A); + + provisioner.provision(r, props(POOL, "grp-a", "user-one"), ctx(ID_A)); + + assertEquals(ID_A, r.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(r)); + verifyNoInteractions(cognito); + } + + @Test + void createRefusesAUserAlreadyInTheGroupNamingTheCanonicalUser() { + when(cognito.adminGetUser("pool", "alice@example.com")).thenReturn(user("alice")); + when(cognito.getGroup("pool", "g")).thenReturn(group("g", "alice")); + StackResource r = resource(null); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(r, props("pool", "g", "alice@example.com"), ctx(null))); + + assertEquals("AlreadyExists", failure.getErrorCode()); + assertEquals("User with name alice already exists in Group g.", failure.getMessage()); + verify(cognito, never()).adminAddUserToGroup(any(), any(), any()); + } + + @Test + void anAliasToCanonicalReplacementOfAMemberFailsAndItsRollbackRemovesNothing() { + when(cognito.adminGetUser("pool", "alice@example.com")).thenReturn(user("alice")); + StackResource r = created("pool", "g", "alice@example.com"); + String aliasId = "pool|g|alice@example.com"; + when(cognito.getGroup("pool", "g")).thenReturn(group("g", "alice")); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(r, props("pool", "g", "alice"), ctx(aliasId))); + + assertEquals("AlreadyExists", failure.getErrorCode()); + assertEquals("User with name alice already exists in Group g.", failure.getMessage()); + assertEquals(aliasId, r.getPhysicalId()); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(cognito, never()).adminRemoveUserFromGroup(any(), any(), any()); + assertEquals(aliasId, r.getPhysicalId()); + } + + @Test + void aChangeThatKeepsTheRefIsRefusedAsACustomNamedReplacement() { + StackResource r = created("pool", "a", "b|c"); + clearInvocations(cognito); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(r, props("pool", "a|b", "c"), ctx("pool|a|b|c"))); + + assertEquals("ValidationError", failure.getErrorCode()); + assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. " + + "Rename pool|a|b|c and update the stack again.", failure.getMessage()); + assertEquals("pool|a|b|c", r.getPhysicalId()); + verify(cognito, never()).adminAddUserToGroup(any(), any(), any()); + verify(cognito, never()).adminRemoveUserFromGroup(any(), any(), any()); + } + + @Test + void deleteRemovesAMembershipWhoseGroupNameHoldsAPipe() { + StackResource r = created("pool", "a|b", "c"); + + provisioner.delete(r, "us-east-1"); + + verify(cognito).adminRemoveUserFromGroup("pool", "a|b", "c"); + } + + @Test + void aReplacementAwayFromAPipedGroupNameRemovesTheRecordedMembership() { + StackResource r = created("pool", "a|b", "c"); + provisioner.provision(r, props("pool", "x", "c"), ctx("pool|a|b|c")); + + assertTrue(provisioner.completeUpdate(r).complete()); + + verify(cognito).adminRemoveUserFromGroup("pool", "a|b", "c"); + verify(cognito, never()).adminRemoveUserFromGroup("pool", "a", "b|c"); + verify(cognito, never()).adminRemoveUserFromGroup("pool", "x", "c"); + } + + @Test + void theMembershipRecordKeepsOnlyTheCurrentIdAndTheIdsStillOwedADelete() throws Exception { + String idC = POOL + "|grp-c|user-one"; + StackResource r = created(POOL, "grp-a", "user-one"); + provisioner.provision(r, props(POOL, "grp-b", "user-one"), ctx(ID_A)); + assertTrue(provisioner.completeUpdate(r).complete()); + provisioner.clearUpdate(r); + + provisioner.provision(r, props(POOL, "grp-c", "user-one"), ctx(ID_B)); + + assertEquals(Set.of(ID_B, idC), recordedIds(r)); + assertTrue(provisioner.completeUpdate(r).complete()); + provisioner.clearUpdate(r); + verify(cognito).adminRemoveUserFromGroup(POOL, "grp-b", "user-one"); + provisioner.provision(r, props(POOL, "grp-c", "user-one"), ctx(idC)); + assertEquals(Set.of(idC), recordedIds(r)); + } + + @Test + void aGroupNameChangeIsAReplacementWhoseCleanupRemovesOnlyTheOldMembership() { + StackResource r = created(POOL, "grp-a", "user-one"); + + provisioner.provision(r, props(POOL, "grp-b", "user-one"), ctx(ID_A)); + + verify(cognito).adminAddUserToGroup(POOL, "grp-b", "user-one"); + assertEquals(ID_B, r.getPhysicalId()); + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals(ID_A, provisioner.updateCleanupPhysicalId(r)); + + UpdateCleanupResult result = provisioner.completeUpdate(r); + + assertTrue(result.complete()); + verify(cognito).adminRemoveUserFromGroup(POOL, "grp-a", "user-one"); + verify(cognito, never()).adminRemoveUserFromGroup(POOL, "grp-b", "user-one"); + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + @Test + void rollingBackAReplacementRemovesTheNewMembershipAndRestoresThePriorId() { + StackResource r = created(POOL, "grp-a", "user-one"); + provisioner.provision(r, props(POOL, "grp-b", "user-one"), ctx(ID_A)); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(cognito).adminRemoveUserFromGroup(POOL, "grp-b", "user-one"); + verify(cognito, never()).adminRemoveUserFromGroup(POOL, "grp-a", "user-one"); + assertEquals(ID_A, r.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + @Test + void aReplacementWhoseRollbackDeleteFailsIsRemovedFromItsRecordedPartsByTheNextCleanup() { + String priorId = POOL + "|g|alice"; + StackResource r = created(POOL, "g", "alice"); + provisioner.provision(r, props(POOL, "b|c", "alice"), ctx(priorId)); + doThrow(new AwsException("InternalErrorException", "storage unavailable", 500)).doNothing() + .when(cognito).adminRemoveUserFromGroup(POOL, "b|c", "alice"); + + AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + + assertEquals("InternalErrorException", failure.getErrorCode()); + assertEquals(priorId, r.getPhysicalId()); + + assertTrue(provisioner.completeUpdate(r).complete()); + + verify(cognito, times(2)).adminRemoveUserFromGroup(POOL, "b|c", "alice"); + verify(cognito, never()).adminRemoveUserFromGroup(POOL, "g", "alice"); + } + + @Test + void rollingBackAnUpdateThatReplacedNothingIsDone() { + StackResource r = resource(ID_A); + provisioner.provision(r, props(POOL, "grp-a", "user-one"), ctx(ID_A)); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(cognito, never()).adminRemoveUserFromGroup(any(), any(), any()); + assertEquals(ID_A, r.getPhysicalId()); + } + + @Test + void deleteRemovesTheRecordedMembership() { + StackResource r = created(POOL, "grp-a", "user-one"); + + provisioner.delete(r, "us-east-1"); + + verify(cognito).adminRemoveUserFromGroup(POOL, "grp-a", "user-one"); + } + + @ParameterizedTest + @ValueSource(strings = {"UserNotFoundException", "ResourceNotFoundException"}) + void deleteToleratesAMembershipThatIsAlreadyGone(String code) { + StackResource r = created(POOL, "grp-a", "user-one"); + doThrow(new AwsException(code, "gone", 400)) + .when(cognito).adminRemoveUserFromGroup(POOL, "grp-a", "user-one"); + + assertDoesNotThrow(() -> provisioner.delete(r, "us-east-1")); + } + + @Test + void deleteSurfacesAnyOtherFailure() { + StackResource r = created(POOL, "grp-a", "user-one"); + doThrow(new AwsException("InternalFailure", "storage unavailable", 500)) + .when(cognito).adminRemoveUserFromGroup(POOL, "grp-a", "user-one"); + + AwsException thrown = assertThrows(AwsException.class, + () -> provisioner.delete(r, "us-east-1")); + + assertEquals("InternalFailure", thrown.getErrorCode()); + } + + @Test + void deleteOfAnIdNeverRecordedRemovesTheMembershipItNames() { + provisioner.delete(resource(POOL + "|grp|alice"), "us-east-1"); + + verify(cognito).adminRemoveUserFromGroup(POOL, "grp", "alice"); + } + + @Test + void deleteOfAnUnrecordedIdHoldingAnExtraPipeIsRefused() { + StackResource r = resource(POOL + "|a|b|c"); + + AwsException failure = assertThrows(AwsException.class, () -> provisioner.delete(r, "us-east-1")); + + assertEquals("InvalidRequest", failure.getErrorCode()); + verifyNoInteractions(cognito); + } + + @Test + void deleteOfAnIdThatIsNotACompositeCallsNothing() { + assertDoesNotThrow(() -> provisioner.delete(resource("stub-id"), "us-east-1")); + + verifyNoInteractions(cognito); + } + + private StackResource created(String userPoolId, String groupName, String username) { + StackResource r = resource(null); + provisioner.provision(r, props(userPoolId, groupName, username), ctx(null)); + return r; + } + + private Set recordedIds(StackResource r) throws Exception { + Set ids = new HashSet<>(); + mapper.readTree(r.getAttributes().get("__FlociCognitoMemberships")).fieldNames().forEachRemaining(ids::add); + return ids; + } + + private static CognitoUser user(String username) { + CognitoUser user = new CognitoUser(); + user.setUsername(username); + return user; + } + + private static CognitoGroup group(String groupName, String... members) { + CognitoGroup group = new CognitoGroup(); + group.setGroupName(groupName); + group.setUserNames(List.of(members)); + return group; + } + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId); + } + + private ObjectNode props(String userPoolId, String groupName, String username) { + ObjectNode props = mapper.createObjectNode(); + props.put("UserPoolId", userPoolId); + props.put("GroupName", groupName); + props.put("Username", username); + return props; + } + + private static StackResource resource(String physicalId) { + StackResource r = new StackResource(); + r.setLogicalId("Attach"); + r.setResourceType(TYPE); + r.setPhysicalId(physicalId); + r.setAttributes(new HashMap<>()); + return r; + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index aebebb4ad8..b238297192 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -52,6 +52,7 @@ AWS::Cognito::UserPoolClient CognitoCfnProvisioner AWS::Cognito::UserPoolDomain CognitoCfnProvisioner AWS::Cognito::UserPoolGroup CognitoUserPoolGroupCfnProvisioner AWS::Cognito::UserPoolUser CognitoUserPoolUserCfnProvisioner +AWS::Cognito::UserPoolUserToGroupAttachment CognitoUserPoolUserToGroupAttachmentCfnProvisioner AWS::Config::ConfigRule ConfigCfnProvisioner AWS::DynamoDB::GlobalTable DynamoDbCfnProvisioner AWS::DynamoDB::Table DynamoDbCfnProvisioner