Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cognito): provision user pool users (#4805)

Mario Toffiaae0a591bb190
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolUserTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolUserTest.java
new file mode 100644
index 0000000000..4d75a674e6
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoUserPoolUserTest.java
@@ -0,0 +1,181 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+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.CreateStackRequest;
+import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest;
+import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
+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.UpdateStackRequest;
+import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserResponse;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.UserNotFoundException;
+
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+@DisplayName("CloudFormation AWS::Cognito::UserPoolUser")
+class CloudFormationCognitoUserPoolUserTest {
+
+ private static final Logger LOG = Logger.getLogger(CloudFormationCognitoUserPoolUserTest.class.getName());
+
+ private static final String TEMPLATE = """
+ {
+ "Parameters": {
+ "PoolId": { "Type": "String" },
+ "Username": { "Type": "String" }
+ },
+ "Resources": {
+ "User": {
+ "Type": "AWS::Cognito::UserPoolUser",
+ "Properties": {
+ "UserPoolId": { "Ref": "PoolId" },
+ "Username": { "Ref": "Username" },
+ "MessageAction": "SUPPRESS",
+ "UserAttributes": [
+ { "Name": "email", "Value": "[email protected]" },
+ { "Name": "name", "Value": "One" }
+ ]
+ }
+ }
+ },
+ "Outputs": {
+ "UserRef": { "Value": { "Ref": "User" } }
+ }
+ }
+ """;
+
+ private static CloudFormationClient cloudFormation;
+ private static CognitoIdentityProviderClient cognito;
+ private static String stackName;
+ private static String poolId;
+
+ @BeforeAll
+ static void setup() {
+ cloudFormation = TestFixtures.cloudFormationClient();
+ cognito = TestFixtures.cognitoClient();
+ stackName = TestFixtures.uniqueName("compat-cfn-cognito-user");
+ poolId = cognito.createUserPool(r -> r.poolName(stackName)).userPool().id();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (cloudFormation != null) {
+ try {
+ cloudFormation.deleteStack(DeleteStackRequest.builder().stackName(stackName).build());
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to delete CloudFormation Cognito user test stack: " + stackName, e);
+ }
+ cloudFormation.close();
+ }
+ if (cognito != null) {
+ try {
+ cognito.deleteUserPool(r -> r.userPoolId(poolId));
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to delete Cognito user pool during cleanup: " + poolId, e);
+ }
+ cognito.close();
+ }
+ }
+
+ @Test
+ @DisplayName("Ref is the username, a rename replaces the user and DeleteStack removes it")
+ void createsRenamesAndDeletesUserPoolUserThroughAwsSdk() throws InterruptedException {
+ cloudFormation.createStack(CreateStackRequest.builder()
+ .stackName(stackName)
+ .templateBody(TEMPLATE)
+ .parameters(parameters("user-one"))
+ .build());
+ assertThat(waitForTerminal(stackName, 30)).isEqualTo("CREATE_COMPLETE");
+ assertThat(outputs()).containsEntry("UserRef", "user-one");
+
+ AdminGetUserResponse user = cognito.adminGetUser(r -> r.userPoolId(poolId).username("user-one"));
+ assertThat(user.username()).isEqualTo("user-one");
+ assertThat(attributes(user.userAttributes()))
+ .containsEntry("email", "[email protected]")
+ .containsEntry("name", "One")
+ .containsKey("sub");
+
+ cloudFormation.updateStack(UpdateStackRequest.builder()
+ .stackName(stackName)
+ .templateBody(TEMPLATE)
+ .parameters(parameters("user-one-b"))
+ .build());
+ assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_COMPLETE");
+ assertThat(outputs()).containsEntry("UserRef", "user-one-b");
+ assertThat(cognito.adminGetUser(r -> r.userPoolId(poolId).username("user-one-b")).username())
+ .isEqualTo("user-one-b");
+ assertThatThrownBy(() -> cognito.adminGetUser(r -> r.userPoolId(poolId).username("user-one")))
+ .isInstanceOf(UserNotFoundException.class);
+
+ cloudFormation.deleteStack(DeleteStackRequest.builder().stackName(stackName).build());
+ waitForDeleted(stackName, 30);
+ assertThatThrownBy(() -> cognito.adminGetUser(r -> r.userPoolId(poolId).username("user-one-b")))
+ .isInstanceOf(UserNotFoundException.class);
+ }
+
+ private static List<Parameter> parameters(String username) {
+ return List.of(
+ Parameter.builder().parameterKey("PoolId").parameterValue(poolId).build(),
+ Parameter.builder().parameterKey("Username").parameterValue(username).build());
+ }
+
+ private static Map<String, String> outputs() {
+ return cloudFormation.describeStacks(DescribeStacksRequest.builder().stackName(stackName).build())
+ .stacks().get(0).outputs().stream()
+ .collect(Collectors.toMap(Output::outputKey, Output::outputValue));
+ }
+
+ private static Map<String, String> attributes(List<AttributeType> attributes) {
+ return attributes.stream().collect(Collectors.toMap(AttributeType::name, AttributeType::value));
+ }
+
+ private static String waitForTerminal(String name, int maxSeconds) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
+ while (System.currentTimeMillis() < deadline) {
+ List<Stack> stacks = cloudFormation.describeStacks(
+ DescribeStacksRequest.builder().stackName(name).build()).stacks();
+ if (!stacks.isEmpty()) {
+ String status = stacks.get(0).stackStatusAsString();
+ if (!status.endsWith("_IN_PROGRESS")) {
+ return status;
+ }
+ }
+ Thread.sleep(500);
+ }
+ throw new AssertionError("Stack " + name + " did not reach a terminal state within " + maxSeconds + "s");
+ }
+
+ private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
+ while (System.currentTimeMillis() < deadline) {
+ try {
+ List<Stack> stacks = cloudFormation.describeStacks(
+ DescribeStacksRequest.builder().stackName(name).build()).stacks();
+ if (stacks.isEmpty() || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) {
+ return;
+ }
+ } catch (CloudFormationException e) {
+ if (e.getMessage() != null && e.getMessage().contains("does not exist")) {
+ return;
+ }
+ throw e;
+ }
+ Thread.sleep(500);
+ }
+ throw new AssertionError("Stack " + name + " was not deleted within " + maxSeconds + "s");
+ }
+}
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 6649ba5f40..9ace9753cd 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -151,7 +151,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, `<base-url>/<pool id>`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup` |
+| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolUser` |
| ACM | `Certificate` |
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy` |
| EventBridge Scheduler | `ScheduleGroup` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java
new file mode 100644
index 0000000000..8e65a63ba1
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisioner.java
@@ -0,0 +1,212 @@
+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;
+import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::Cognito::UserPoolUser}. {@code Ref} returns the
+ * username Cognito reports: the template's {@code Username}, a generated name when it has none, or
+ * the user's {@code sub} in an email-as-username pool. Every property is createOnly, so a changed
+ * template replaces the user through {@link ReplacementCleanup}, except that a user with an explicit
+ * {@code Username} that stays the same is refused as a custom-named replacement, as on AWS.
+ */
+@ApplicationScoped
+public class CognitoUserPoolUserCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(CognitoUserPoolUserCfnProvisioner.class);
+ private static final String TYPE = "AWS::Cognito::UserPoolUser";
+ private static final String CREATE_ONLY_ATTR = "__FlociCreateOnly";
+ private static final String CREATE_ONLY_PRIOR_ATTR = "__FlociCreateOnlyPrior";
+ /**
+ * Physical id to pool id for the current user and every user still owed a delete, so a displaced
+ * user is deleted in its own pool, not the current one.
+ */
+ private static final String POOLS_ATTR = "__FlociCognitoUserPools";
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private final CognitoService cognitoService;
+
+ @Inject
+ public CognitoUserPoolUserCfnProvisioner(CognitoService cognitoService) {
+ this.cognitoService = cognitoService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
+ JsonNode resolved = props == null ? MAPPER.createObjectNode() : ctx.engine().resolveNode(props);
+ String userPoolId = text(resolved, "UserPoolId");
+ if (userPoolId == null || userPoolId.isBlank()) {
+ throw new AwsException("ValidationError", "AWS::Cognito::UserPoolUser requires UserPoolId", 400);
+ }
+
+ JsonNode prior = priorCreateOnly(attributesBefore);
+ if (ctx.isUpdate() && resolved.equals(prior)) {
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ return;
+ }
+ String username = text(resolved, "Username");
+ boolean customNamed = username != null && !username.isBlank();
+ if (ctx.isUpdate() && customNamed && prior != null && username.equals(text(prior, "Username"))) {
+ throw new AwsException("ValidationError",
+ "CloudFormation cannot update a stack when a custom-named resource requires "
+ + "replacing. Rename " + username + " and update the stack again.", 400);
+ }
+
+ Map<String, String> userAttributes = new LinkedHashMap<>();
+ for (JsonNode attribute : resolved.path("UserAttributes")) {
+ userAttributes.put(attribute.path("Name").asText(), attribute.path("Value").asText());
+ }
+ // DesiredDeliveryMediums, ValidationData and ClientMetadata only reach a message transport
+ // or a Lambda trigger, neither of which AdminCreateUser drives here, so they only take part
+ // in the createOnly record.
+ String name = customNamed ? username : ctx.generatePhysicalName(r.getLogicalId(), 128, false);
+ String messageAction = text(resolved, "MessageAction");
+ if ("RESEND".equalsIgnoreCase(messageAction)) {
+ // RESEND hands back an existing user the stack never created, and AWS refuses it as a name conflict.
+ CognitoUser existing = cognitoService.adminGetUser(userPoolId, name);
+ throw new AwsException("AlreadyExists", "Resource of type 'AWS::Cognito::UserPoolUser' with identifier '"
+ + userPoolId + "|" + existing.getUsername() + "' already exists.", 400);
+ }
+ CognitoUser user = cognitoService.adminCreateUser(userPoolId, name, userAttributes, null, messageAction,
+ Boolean.parseBoolean(text(resolved, "ForceAliasCreation")));
+
+ r.setPhysicalId(user.getUsername());
+ r.getAttributes().put(CREATE_ONLY_ATTR, resolved.toString());
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ recordPool(r, attributesBefore, userPoolId);
+ if (ctx.isUpdate() && !ctx.priorPhysicalId().equals(r.getPhysicalId())) {
+ r.getAttributes().put(CREATE_ONLY_PRIOR_ATTR, attributesBefore.getOrDefault(CREATE_ONLY_ATTR, ""));
+ }
+ }
+
+ @Override
+ public void delete(StackResource resource, String region) {
+ deleteUser(poolFor(resource.getAttributes(), resource.getPhysicalId()), 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) ->
+ deleteUser(poolFor(resource.getAttributes(), physicalId), physicalId));
+ }
+
+ @Override
+ public void clearUpdate(StackResource resource) {
+ resource.getAttributes().remove(CREATE_ONLY_PRIOR_ATTR);
+ ReplacementCleanup.clear(resource);
+ }
+
+ /**
+ * Deletes the replacement and points the resource back at the prior user, with its createOnly
+ * record. A user is never changed in place, so an update that replaced nothing, including a
+ * refused custom-named one, has nothing to undo.
+ */
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ String prior = resource.getAttributes().remove(CREATE_ONLY_PRIOR_ATTR);
+ if (prior != null) {
+ if (prior.isEmpty()) {
+ resource.getAttributes().remove(CREATE_ONLY_ATTR);
+ } else {
+ resource.getAttributes().put(CREATE_ONLY_ATTR, prior);
+ }
+ }
+ ReplacementCleanup.rollback(resource, (type, physicalId, region) ->
+ deleteUser(poolFor(resource.getAttributes(), physicalId), physicalId));
+ return true;
+ }
+
+ private void deleteUser(String userPoolId, String username) {
+ if (userPoolId == null || userPoolId.isBlank() || username == null || username.isBlank()) {
+ return;
+ }
+ CfnDeletes.safeDelete("Cognito user", username, () -> cognitoService.adminDeleteUser(userPoolId, username),
+ "UserNotFoundException", "ResourceNotFoundException");
+ }
+
+ /**
+ * Keeps the pool of the user the resource now names and of every user still owed a delete, from
+ * this update or an earlier one, so each is deleted in its own pool. Every other entry is
+ * dropped, so the record stays bounded across repeated replacements. Call after
+ * {@link ReplacementCleanup#record}, so the user this update displaced is already owed.
+ */
+ private static void recordPool(StackResource r, Map<String, String> attributesBefore, String userPoolId) {
+ ObjectNode prior = pools(attributesBefore);
+ ObjectNode pools = MAPPER.createObjectNode();
+ for (String owed : ReplacementCleanup.owedPhysicalIds(r)) {
+ JsonNode pool = prior.get(owed);
+ if (pool != null) {
+ pools.set(owed, pool);
+ }
+ }
+ pools.put(r.getPhysicalId(), userPoolId);
+ r.getAttributes().put(POOLS_ATTR, pools.toString());
+ }
+
+ private static String poolFor(Map<String, String> attributes, String physicalId) {
+ JsonNode pool = physicalId == null ? null : pools(attributes).get(physicalId);
+ return pool != null && pool.isTextual() ? pool.textValue() : null;
+ }
+
+ private static ObjectNode pools(Map<String, String> attributes) {
+ String recorded = attributes.get(POOLS_ATTR);
+ if (recorded != null) {
+ try {
+ if (MAPPER.readTree(recorded) instanceof ObjectNode pools) {
+ return pools;
+ }
+ } catch (JsonProcessingException e) {
+ LOG.warnv("Unreadable Cognito user pool record, ignoring it: {0}", e.getMessage());
+ }
+ }
+ return MAPPER.createObjectNode();
+ }
+
+ private static JsonNode priorCreateOnly(Map<String, String> attributesBefore) {
+ String prior = attributesBefore.get(CREATE_ONLY_ATTR);
+ if (prior == null) {
+ return null;
+ }
+ try {
+ return MAPPER.readTree(prior);
+ } catch (JsonProcessingException e) {
+ LOG.warnv("Unreadable Cognito user createOnly record, treating it as absent: {0}", e.getMessage());
+ return null;
+ }
+ }
+
+ private static String text(JsonNode node, String name) {
+ JsonNode value = node.path(name);
+ return value.isMissingNode() || value.isNull() ? null : value.asText();
+ }
+}
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.java
index 9ab3340944..70f37a7218 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
@@ -9,9 +9,11 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.jboss.logging.Logger;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* The replacement lifecycle for provisioners whose replacing update simply creates the new entity
@@ -121,6 +123,22 @@ public final class ReplacementCleanup {
return cleanup != null && cleanup.path("displaced").size() > 0;
}
+ /** The physical ids still owed a delete. */
+ static Set<String> owedPhysicalIds(StackResource r) {
+ Set<String> owed = new HashSet<>();
+ ObjectNode cleanup = read(r);
+ if (cleanup == null) {
+ return owed;
+ }
+ for (JsonNode entry : cleanup.path("displaced")) {
+ String physicalId = entry.path("physicalId").asText(null);
+ if (physicalId != null) {
+ owed.add(physicalId);
+ }
+ }
+ return owed;
+ }
+
/**
* The entity the cleanup is working on, or null when none is owed or {@code UpdateReplacePolicy:
* Retain} keeps it. The engine announces one physical id per resource, so a resource owing more
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 564de84116..774146bae3 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
@@ -52,6 +52,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatc
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchDashboardCfnProvisioner;
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.Ec2LaunchTemplateCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkAclCfnProvisioner;
@@ -293,6 +294,7 @@ final class CfnProvisionerFixture {
if (cognitoService != null) {
discovered.add(new CognitoCfnProvisioner(cognitoService));
discovered.add(new CognitoUserPoolGroupCfnProvisioner(cognitoService));
+ discovered.add(new CognitoUserPoolUserCfnProvisioner(cognitoService));
}
if (cloudFrontService != null) {
discovered.add(new CloudFrontCfnProvisioner(cloudFrontService));
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserPoolUserIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserPoolUserIntegrationTest.java
new file mode 100644
index 0000000000..c171c31442
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCognitoUserPoolUserIntegrationTest.java
@@ -0,0 +1,280 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.matchesPattern;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Provisions {@code AWS::Cognito::UserPoolUser} through CloudFormation stacks and reads the users
+ * back through the Cognito JSON API: Ref is the template username or a generated one, an update that
+ * changes a custom-named user is refused and rolled back with the user untouched, a renamed user is
+ * replaced and the old one deleted once the update commits, DeleteStack removes the users, and in an
+ * email-as-username pool Ref is the user's sub.
+ */
+@QuarkusTest
+class CloudFormationCognitoUserPoolUserIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/cloudformation/aws4_request";
+ private static final String COGNITO = "AWSCognitoIdentityProviderService";
+ private static final String UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void createStackProvisionsUsersWhoseRefIsTheirUsername() {
+ String stack = "cfn-cognito-users-" + Long.toString(System.nanoTime(), 36);
+
+ stackAction(stack, "CreateStack", poolAndUsersTemplate(), Map.of());
+ String outputs = describeStacks(stack, "CREATE_COMPLETE");
+ String poolId = outputValue(outputs, "PoolId");
+ String generated = outputValue(outputs, "GeneratedRef");
+ assertEquals("user-one", outputValue(outputs, "NamedRef"));
+ assertThat(generated, matchesPattern(Pattern.quote(stack) + "-GeneratedUser-[a-z0-9]{12}"));
+ adminGetUser(poolId, "user-one")
+ .statusCode(200)
+ .body("Username", equalTo("user-one"))
+ .body("UserAttributes.find { it.Name == 'email' }.Value", equalTo("[email protected]"))
+ .body("UserAttributes.find { it.Name == 'name' }.Value", equalTo("One"));
+ adminGetUser(poolId, generated).statusCode(200).body("Username", equalTo(generated));
+
+ stackAction(stack, "DeleteStack", null, Map.of());
+ CfnStackWaits.awaitStackDeleted(stack);
+ cognito("DescribeUserPool", "{\"UserPoolId\": \"" + poolId + "\"}")
+ .statusCode(400)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ /**
+ * The pool lives outside the stack, so the update exercises only the users and DeleteStack can
+ * show each user is gone rather than only its pool.
+ */
+ @Test
+ void aChangedCustomNamedUserIsRefusedARenameReplacesItAndDeleteStackRemovesIt() {
+ String stack = "cfn-cognito-users-update-" + Long.toString(System.nanoTime(), 36);
+ String poolId = cognito("CreateUserPool", "{\"PoolName\": \"" + stack + "\"}")
+ .statusCode(200)
+ .extract().path("UserPool.Id");
+
+ stackAction(stack, "CreateStack", usersInExistingPoolTemplate(), userParameters(poolId, "user-one", "[email protected]"));
+ String outputs = describeStacks(stack, "CREATE_COMPLETE");
+ String generated = outputValue(outputs, "GeneratedRef");
+ assertEquals("user-one", outputValue(outputs, "NamedRef"));
+ String sub = adminGetUser(poolId, "user-one")
+ .statusCode(200)
+ .extract().path("UserAttributes.find { it.Name == 'sub' }.Value");
+
+ // Every property is createOnly and the username is explicit, so CloudFormation refuses it.
+ stackAction(stack, "UpdateStack", usersInExistingPoolTemplate(), userParameters(poolId, "user-one", "[email protected]"));
+ describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");
+ assertTrue(XmlParser.extractGroups(describeEvents(stack), "member").stream()
+ .anyMatch(event -> "NamedUser".equals(event.get("LogicalResourceId"))
+ && "UPDATE_FAILED".equals(event.get("ResourceStatus"))
+ && event.getOrDefault("ResourceStatusReason", "")
+ .contains("custom-named resource requires replacing. Rename user-one")),
+ "no refused update event for NamedUser");
+ adminGetUser(poolId, "user-one")
+ .statusCode(200)
+ .body("UserAttributes.find { it.Name == 'email' }.Value", equalTo("[email protected]"))
+ .body("UserAttributes.find { it.Name == 'sub' }.Value", equalTo(sub));
+
+ stackAction(stack, "UpdateStack", usersInExistingPoolTemplate(), userParameters(poolId, "user-one-b", "[email protected]"));
+ outputs = describeStacks(stack, "UPDATE_COMPLETE");
+ assertEquals("user-one-b", outputValue(outputs, "NamedRef"));
+ assertEquals(generated, outputValue(outputs, "GeneratedRef"));
+ adminGetUser(poolId, "user-one-b")
+ .statusCode(200)
+ .body("UserAttributes.find { it.Name == 'email' }.Value", equalTo("[email protected]"));
+ adminGetUser(poolId, "user-one").statusCode(400).body("__type", equalTo("UserNotFoundException"));
+ adminGetUser(poolId, generated).statusCode(200);
+
+ stackAction(stack, "DeleteStack", null, Map.of());
+ CfnStackWaits.awaitStackDeleted(stack);
+ adminGetUser(poolId, "user-one-b").statusCode(400).body("__type", equalTo("UserNotFoundException"));
+ adminGetUser(poolId, generated).statusCode(400).body("__type", equalTo("UserNotFoundException"));
+ cognito("DeleteUserPool", "{\"UserPoolId\": \"" + poolId + "\"}").statusCode(200);
+ }
+
+ @Test
+ void anEmailAsUsernamePoolRefsTheUsersSub() {
+ String stack = "cfn-cognito-users-alias-" + Long.toString(System.nanoTime(), 36);
+
+ stackAction(stack, "CreateStack", emailPoolTemplate(), Map.of());
+ String outputs = describeStacks(stack, "CREATE_COMPLETE");
+ String ref = outputValue(outputs, "UserRef");
+ assertThat(ref, matchesPattern(UUID_PATTERN));
+ adminGetUser(outputValue(outputs, "PoolId"), "[email protected]")
+ .statusCode(200)
+ .body("Username", equalTo(ref))
+ .body("UserAttributes.find { it.Name == 'sub' }.Value", equalTo(ref))
+ .body("UserAttributes.find { it.Name == 'email' }.Value", equalTo("[email protected]"));
+
+ stackAction(stack, "DeleteStack", null, Map.of());
+ CfnStackWaits.awaitStackDeleted(stack);
+ }
+
+ private static void stackAction(String stack, String action, String templateBody, Map<String, String> parameters) {
+ RequestSpecification request = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", action)
+ .formParam("StackName", stack);
+ if (templateBody != null) {
+ request.formParam("TemplateBody", templateBody);
+ }
+ int index = 1;
+ for (Map.Entry<String, String> parameter : parameters.entrySet()) {
+ request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
+ request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
+ index++;
+ }
+ request.when().post("/").then().statusCode(200);
+ }
+
+ private static String describeStacks(String stack, String expectedStatus) {
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack);
+ assertEquals(expectedStatus, state.status(), state.reason());
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stack)
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
+ .extract().asString();
+ }
+
+ private static String describeEvents(String stack) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStackEvents")
+ .formParam("StackName", stack)
+ .when().post("/").then().statusCode(200).extract().asString();
+ }
+
+ private static String outputValue(String xml, String key) {
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
+ }
+
+ private static ValidatableResponse adminGetUser(String poolId, String username) {
+ return cognito("AdminGetUser", "{\"UserPoolId\": \"" + poolId + "\", \"Username\": \"" + username + "\"}");
+ }
+
+ private static ValidatableResponse cognito(String action, String body) {
+ return RestAssuredJsonUtils.awsAction(COGNITO, action, body).then();
+ }
+
+ private static Map<String, String> userParameters(String poolId, String username, String email) {
+ return Map.of("PoolId", poolId, "Username", username, "Email", email);
+ }
+
+ private static String poolAndUsersTemplate() {
+ return """
+ {
+ "Resources": {
+ "Pool": {
+ "Type": "AWS::Cognito::UserPool",
+ "Properties": { "UserPoolName": "cfn-user-pool" }
+ },
+ "NamedUser": {
+ "Type": "AWS::Cognito::UserPoolUser",
+ "Properties": {
+ "UserPoolId": { "Ref": "Pool" },
+ "Username": "user-one",
+ "MessageAction": "SUPPRESS",
+ "UserAttributes": [
+ { "Name": "email", "Value": "[email protected]" },
+ { "Name": "name", "Value": "One" }
+ ]
+ }
+ },
+ "GeneratedUser": {
+ "Type": "AWS::Cognito::UserPoolUser",
+ "Properties": { "UserPoolId": { "Ref": "Pool" }, "MessageAction": "SUPPRESS" }
+ }
+ },
+ "Outputs": {
+ "PoolId": { "Value": { "Ref": "Pool" } },
+ "NamedRef": { "Value": { "Ref": "NamedUser" } },
+ "GeneratedRef": { "Value": { "Ref": "GeneratedUser" } }
+ }
+ }
+ """;
+ }
+
+ private static String usersInExistingPoolTemplate() {
+ return """
+ {
+ "Parameters": {
+ "PoolId": { "Type": "String" },
+ "Username": { "Type": "String" },
+ "Email": { "Type": "String" }
+ },
+ "Resources": {
+ "NamedUser": {
+ "Type": "AWS::Cognito::UserPoolUser",
+ "Properties": {
+ "UserPoolId": { "Ref": "PoolId" },
+ "Username": { "Ref": "Username" },
+ "MessageAction": "SUPPRESS",
+ "UserAttributes": [ { "Name": "email", "Value": { "Ref": "Email" } } ]
+ }
+ },
+ "GeneratedUser": {
+ "Type": "AWS::Cognito::UserPoolUser",
+ "Properties": { "UserPoolId": { "Ref": "PoolId" } }
+ }
+ },
+ "Outputs": {
+ "NamedRef": { "Value": { "Ref": "NamedUser" } },
+ "GeneratedRef": { "Value": { "Ref": "GeneratedUser" } }
+ }
+ }
+ """;
+ }
+
+ private static String emailPoolTemplate() {
+ return """
+ {
+ "Resources": {
+ "EmailPool": {
+ "Type": "AWS::Cognito::UserPool",
+ "Properties": { "UserPoolName": "cfn-email-pool", "UsernameAttributes": ["email"] }
+ },
+ "EmailUser": {
+ "Type": "AWS::Cognito::UserPoolUser",
+ "Properties": {
+ "UserPoolId": { "Ref": "EmailPool" },
+ "Username": "[email protected]",
+ "MessageAction": "SUPPRESS",
+ "UserAttributes": [ { "Name": "email", "Value": "[email protected]" } ]
+ }
+ }
+ },
+ "Outputs": {
+ "PoolId": { "Value": { "Ref": "EmailPool" } },
+ "UserRef": { "Value": { "Ref": "EmailUser" } }
+ }
+ }
+ """;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisionerTest.java
new file mode 100644
index 0000000000..0a682e3249
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CognitoUserPoolUserCfnProvisionerTest.java
@@ -0,0 +1,442 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+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.CognitoUser;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.matchesPattern;
+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;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+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.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * The Cognito user pool user CFN provisioner in isolation, with only CognitoService mocked: Ref is
+ * the username Cognito reports, an unchanged template is a no-op, a changed custom-named user is
+ * refused, any other change replaces the user, and every delete goes to the user's own pool.
+ */
+class CognitoUserPoolUserCfnProvisionerTest {
+
+ private static final String TYPE = "AWS::Cognito::UserPoolUser";
+ private static final String CREATE_ONLY_ATTR = "__FlociCreateOnly";
+ private static final String POOLS_ATTR = "__FlociCognitoUserPools";
+
+ private final CognitoService cognito = mock(CognitoService.class);
+ private final CognitoUserPoolUserCfnProvisioner provisioner = new CognitoUserPoolUserCfnProvisioner(cognito);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ void servesTheUserPoolUserType() {
+ assertEquals(Set.of(TYPE), provisioner.resourceTypes());
+ }
+
+ @Test
+ void createPassesUsernameAttributesAndMessageActionThrough() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one", "MessageAction": "SUPPRESS",
+ "ForceAliasCreation": true, "DesiredDeliveryMediums": ["EMAIL"],
+ "UserAttributes": [{"Name": "email", "Value": "[email protected]"},
+ {"Name": "name", "Value": "One"}]}"""), ctx(null));
+
+ Map<String, String> attributes = new LinkedHashMap<>();
+ attributes.put("email", "[email protected]");
+ attributes.put("name", "One");
+ verify(cognito).adminCreateUser("pool-a", "user-one", attributes, null, "SUPPRESS", true);
+ assertEquals("user-one", r.getPhysicalId(), "Ref must resolve to the username");
+ assertTrue(r.getAttributes().keySet().stream().allMatch(key -> key.startsWith("__Floci")),
+ "AWS::Cognito::UserPoolUser exposes no Fn::GetAtt attribute");
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void anEmailAsUsernamePoolRefsTheCanonicalUsernameCognitoReturns() throws Exception {
+ CognitoUser created = new CognitoUser();
+ created.setUsername("d275a484-c0c1-70b3-46da-d9dafa5205e3");
+ when(cognito.adminCreateUser(anyString(), anyString(), any(), any(), any(), anyBoolean()))
+ .thenReturn(created);
+ StackResource r = resource(null);
+
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "[email protected]",
+ "UserAttributes": [{"Name": "email", "Value": "[email protected]"}]}"""), ctx(null));
+
+ verify(cognito).adminCreateUser("pool-a", "[email protected]",
+ Map.of("email", "[email protected]"), null, null, false);
+ assertEquals("d275a484-c0c1-70b3-46da-d9dafa5205e3", r.getPhysicalId());
+ }
+
+ @Test
+ void aUserWithoutUsernameGetsAGeneratedName() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a"}"""), ctx(null));
+
+ assertThat(r.getPhysicalId(), matchesPattern("my-stack-User-[a-z0-9]{12}"));
+ verify(cognito).adminCreateUser("pool-a", r.getPhysicalId(), Map.of(), null, null, false);
+ }
+
+ @Test
+ void missingUserPoolIdIsAValidationErrorAndCreatesNothing() throws Exception {
+ StackResource r = resource(null);
+
+ AwsException thrown = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, props("""
+ {"Username": "user-one"}"""), ctx(null)));
+
+ assertEquals("ValidationError", thrown.getErrorCode());
+ assertEquals("AWS::Cognito::UserPoolUser requires UserPoolId", thrown.getMessage());
+ verifyNoInteractions(cognito);
+ }
+
+ @Test
+ void resendForAnExistingUserFailsWithoutAdoptingIt() throws Exception {
+ CognitoUser existing = new CognitoUser();
+ existing.setUsername("alice");
+ when(cognito.adminGetUser("pool-a", "alice")).thenReturn(existing);
+ StackResource r = resource(null);
+
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "alice", "MessageAction": "RESEND"}"""), ctx(null)));
+
+ assertEquals("AlreadyExists", thrown.getErrorCode());
+ assertEquals("Resource of type 'AWS::Cognito::UserPoolUser' with identifier 'pool-a|alice' already exists.",
+ thrown.getMessage());
+ verify(cognito, never()).adminCreateUser(any(), any(), any(), any(), any(), anyBoolean());
+ assertNull(r.getPhysicalId());
+ }
+
+ @Test
+ void resendForAMissingUserFailsUserNotFound() throws Exception {
+ when(cognito.adminGetUser("pool-a", "alice"))
+ .thenThrow(new AwsException("UserNotFoundException", "User does not exist.", 400));
+ StackResource r = resource(null);
+
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "alice", "MessageAction": "RESEND"}"""), ctx(null)));
+
+ assertEquals("UserNotFoundException", thrown.getErrorCode());
+ verify(cognito, never()).adminCreateUser(any(), any(), any(), any(), any(), anyBoolean());
+ }
+
+ @Test
+ void anUnchangedTemplateLeavesTheUserAlone() throws Exception {
+ stubCreateEchoingTheUsername();
+ String template = """
+ {"UserPoolId": "pool-a", "Username": "user-one",
+ "UserAttributes": [{"Name": "email", "Value": "[email protected]"}]}""";
+ StackResource r = resource(null);
+ provisioner.provision(r, props(template), ctx(null));
+ clearInvocations(cognito);
+
+ provisioner.provision(r, props(template), ctx("user-one"));
+
+ verifyNoInteractions(cognito);
+ assertEquals("user-one", r.getPhysicalId());
+ assertFalse(provisioner.hasReplacementUpdate(r));
+
+ provisioner.delete(r, "us-east-1");
+ verify(cognito).adminDeleteUser("pool-a", r.getPhysicalId());
+ }
+
+ @Test
+ void changingACustomNamedUserIsRefusedWithoutTouchingIt() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one",
+ "UserAttributes": [{"Name": "email", "Value": "[email protected]"}]}"""), ctx(null));
+ clearInvocations(cognito);
+
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one",
+ "UserAttributes": [{"Name": "email", "Value": "[email protected]"}]}"""), ctx("user-one")));
+
+ assertEquals("ValidationError", thrown.getErrorCode());
+ assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ + "Rename user-one and update the stack again.", thrown.getMessage());
+ verifyNoInteractions(cognito);
+ }
+
+ @Test
+ void renamingTheUserReplacesItAndCleanupDeletesTheOldOne() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one"}"""), ctx(null));
+
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one-b"}"""), ctx("user-one"));
+
+ verify(cognito).adminCreateUser("pool-a", "user-one-b", Map.of(), null, null, false);
+ assertEquals("user-one-b", r.getPhysicalId());
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals("user-one", provisioner.updateCleanupPhysicalId(r));
+
+ UpdateCleanupResult result = provisioner.completeUpdate(r);
+
+ assertTrue(result.complete());
+ verify(cognito).adminDeleteUser("pool-a", "user-one");
+ verify(cognito, never()).adminDeleteUser(any(), eq("user-one-b"));
+ }
+
+ @Test
+ void changingAGeneratedNameUserReplacesItUnderANewGeneratedName() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "UserAttributes": [{"Name": "name", "Value": "One"}]}"""), ctx(null));
+ String first = r.getPhysicalId();
+
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "UserAttributes": [{"Name": "name", "Value": "Two"}]}"""), ctx(first));
+
+ assertNotEquals(first, r.getPhysicalId());
+ assertThat(r.getPhysicalId(), matchesPattern("my-stack-User-[a-z0-9]{12}"));
+ verify(cognito).adminCreateUser("pool-a", r.getPhysicalId(), Map.of("name", "Two"), null, null, false);
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void cleanupDeletesTheDisplacedUserInItsOwnPool() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a"}"""), ctx(null));
+ String first = r.getPhysicalId();
+
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-b"}"""), ctx(first));
+ provisioner.completeUpdate(r);
+
+ verify(cognito).adminDeleteUser("pool-a", first);
+ verify(cognito, never()).adminDeleteUser(eq("pool-b"), any());
+
+ provisioner.delete(r, "us-east-1");
+ verify(cognito).adminDeleteUser("pool-b", r.getPhysicalId());
+ }
+
+ @Test
+ void rollingBackAReplacementDeletesItAndRestoresThePriorUser() throws Exception {
+ stubCreateEchoingTheUsername();
+ String original = """
+ {"UserPoolId": "pool-a", "Username": "user-one"}""";
+ StackResource r = resource(null);
+ provisioner.provision(r, props(original), ctx(null));
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-b", "Username": "user-one-b"}"""), ctx("user-one"));
+ clearInvocations(cognito);
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(cognito).adminDeleteUser("pool-b", "user-one-b");
+ verifyNoMoreInteractions(cognito);
+ assertEquals("user-one", r.getPhysicalId());
+ assertFalse(provisioner.hasReplacementUpdate(r));
+
+ // The createOnly record is the prior one again, so re-applying the original template is a no-op.
+ clearInvocations(cognito);
+ provisioner.provision(r, props(original), ctx("user-one"));
+ verifyNoInteractions(cognito);
+
+ provisioner.delete(r, "us-east-1");
+ verify(cognito).adminDeleteUser("pool-a", r.getPhysicalId());
+ }
+
+ @Test
+ void anOlderUserStillOwedADeleteIsDeletedInItsOwnPool() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-a"}"""), ctx(null));
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-b", "Username": "user-b"}"""), ctx("user-a"));
+ doThrow(new AwsException("InternalFailure", "storage unavailable", 500)).doNothing()
+ .when(cognito).adminDeleteUser("pool-b", "user-b");
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-c", "Username": "user-c"}"""), ctx("user-a"));
+ provisioner.completeUpdate(r);
+
+ verify(cognito, times(2)).adminDeleteUser("pool-b", "user-b");
+ verify(cognito, never()).adminDeleteUser("pool-c", "user-b");
+ verify(cognito).adminDeleteUser("pool-a", "user-a");
+ }
+
+ @Test
+ void poolRecordKeepsOnlyTheCurrentUserAndUsersStillOwedADelete() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "alice"}"""), ctx(null));
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-b", "Username": "bob"}"""), ctx("alice"));
+ provisioner.completeUpdate(r);
+ provisioner.clearUpdate(r);
+ verify(cognito).adminDeleteUser("pool-a", "alice");
+
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-c", "Username": "carol"}"""), ctx("bob"));
+
+ JsonNode pools = mapper.readTree(r.getAttributes().get(POOLS_ATTR));
+ Set<String> recorded = new HashSet<>();
+ pools.fieldNames().forEachRemaining(recorded::add);
+ assertEquals(Set.of("bob", "carol"), recorded, "a user deleted by a committed cleanup must leave the record");
+ assertEquals("pool-b", pools.path("bob").asText());
+ assertEquals("pool-c", pools.path("carol").asText());
+
+ provisioner.completeUpdate(r);
+
+ verify(cognito).adminDeleteUser("pool-b", "bob");
+ verify(cognito, never()).adminDeleteUser(any(), eq("carol"));
+ }
+
+ @Test
+ void reorderedPropertiesOfACustomNamedUserAreNotAChange() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one",
+ "UserAttributes": [{"Name": "email", "Value": "[email protected]"}]}"""), ctx(null));
+ clearInvocations(cognito);
+
+ provisioner.provision(r, props("""
+ {"UserAttributes": [{"Value": "[email protected]", "Name": "email"}],
+ "Username": "user-one", "UserPoolId": "pool-a"}"""), ctx("user-one"));
+
+ verifyNoInteractions(cognito);
+ assertEquals("user-one", r.getPhysicalId());
+ }
+
+ @Test
+ void aRollbackWhoseDeleteFailsStillRestoresThePriorCreateOnlyRecord() throws Exception {
+ stubCreateEchoingTheUsername();
+ String original = """
+ {"UserPoolId": "pool-a", "Username": "user-one"}""";
+ StackResource r = resource(null);
+ provisioner.provision(r, props(original), ctx(null));
+ String priorRecord = r.getAttributes().get(CREATE_ONLY_ATTR);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one-b"}"""), ctx("user-one"));
+ doThrow(new AwsException("InternalFailure", "storage unavailable", 500))
+ .when(cognito).adminDeleteUser("pool-a", "user-one-b");
+
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+
+ assertEquals(priorRecord, r.getAttributes().get(CREATE_ONLY_ATTR));
+ clearInvocations(cognito);
+ provisioner.provision(r, props(original), ctx("user-one"));
+ verifyNoInteractions(cognito);
+ }
+
+ @Test
+ void rollingBackWithoutAReplacementHasNothingToUndo() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one"}"""), ctx(null));
+ clearInvocations(cognito);
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verifyNoInteractions(cognito);
+ assertEquals("user-one", r.getPhysicalId());
+ }
+
+ @Test
+ void deleteUsesTheUsersPoolAndToleratesAUserOrPoolAlreadyGone() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one"}"""), ctx(null));
+ doThrow(new AwsException("UserNotFoundException", "User does not exist.", 400))
+ .doThrow(new AwsException("ResourceNotFoundException", "User pool pool-a does not exist.", 400))
+ .when(cognito).adminDeleteUser("pool-a", "user-one");
+
+ provisioner.delete(r, "us-east-1");
+ provisioner.delete(r, "us-east-1");
+
+ verify(cognito, times(2)).adminDeleteUser("pool-a", "user-one");
+ }
+
+ @Test
+ void deleteSurfacesAFailureThatIsNotAMissingUser() throws Exception {
+ stubCreateEchoingTheUsername();
+ StackResource r = resource(null);
+ provisioner.provision(r, props("""
+ {"UserPoolId": "pool-a", "Username": "user-one"}"""), ctx(null));
+ doThrow(new AwsException("InternalFailure", "storage unavailable", 500))
+ .when(cognito).adminDeleteUser("pool-a", "user-one");
+
+ AwsException thrown = assertThrows(AwsException.class, () -> provisioner.delete(r, "us-east-1"));
+
+ assertEquals("InternalFailure", thrown.getErrorCode());
+ }
+
+ private void stubCreateEchoingTheUsername() {
+ when(cognito.adminCreateUser(anyString(), anyString(), any(), any(), any(), anyBoolean()))
+ .thenAnswer(inv -> {
+ CognitoUser user = new CognitoUser();
+ user.setUsername(inv.getArgument(1));
+ return user;
+ });
+ }
+
+ 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();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null ? null : node.deepCopy();
+ });
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
+ }
+
+ private JsonNode props(String json) throws Exception {
+ return mapper.readTree(json);
+ }
+
+ private static StackResource resource(String physicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId("User");
+ 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 982fe03fdd..d3f277ea66 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -50,6 +50,7 @@ AWS::Cognito::UserPool CognitoCfnProvisioner
AWS::Cognito::UserPoolClient CognitoCfnProvisioner
AWS::Cognito::UserPoolDomain CognitoCfnProvisioner
AWS::Cognito::UserPoolGroup CognitoUserPoolGroupCfnProvisioner
+AWS::Cognito::UserPoolUser CognitoUserPoolUserCfnProvisioner
AWS::Config::ConfigRule ConfigCfnProvisioner
AWS::DynamoDB::GlobalTable DynamoDbCfnProvisioner
AWS::DynamoDB::Table DynamoDbCfnProvisioner