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 <UserPoolId>|<GroupName>|<Username>, 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
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-04 17:00:35 -04:00
1 parent 99a6b4050c
commit 2749cd6fcd
10 files changed
+999 -6

No files matched your search

@@ -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
@@ -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));
@@ -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();
}
}
@@ -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<String, String>) 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")));
@@ -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 <UserPoolId>|<GroupName>|<Username>}, 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<String> recordedIds(StackResource r) throws Exception {
Set<String> 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;
}
}