mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): provision Cognito user pool groups (#3695)
* fix(cloudformation): provision Cognito user pool groups Create and reconcile user pool groups, and namespace custom schema attributes while preserving standard attributes. * fix(cloudformation): keep a generated Cognito group name across updates GroupName is optional, and provision generated a fresh stand-in on every call. Because provision is also the update path, the second UpdateStack derived a different name, took the create branch and left the group the stack already owned orphaned behind it. Use ProvisionContext.stablePhysicalName so the prior physical id is reused when the template does not name the group, and reusesPriorEntity for the create-or-update choice, which is the pairing that keeps a stable name from turning an update into a duplicate create.
This commit is contained in:
1 parent
91de9e452e
commit
d9a4db0290
10 files changed
+699
-8
No files matched your search
@@ -150,7 +150,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` |
|
||||
| Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `<base-url>/<pool id>`), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup` |
|
||||
| ACM | `Certificate` |
|
||||
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy` |
|
||||
| EventBridge Scheduler | `ScheduleGroup` |
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoUserPoolGroupCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CognitoUserPoolGroupCfnProvisioner.class);
|
||||
|
||||
/** Attribute holding the owning pool id, the half of the key the physical id cannot carry. */
|
||||
static final String USER_POOL_ID_ATTR = "UserPoolId";
|
||||
|
||||
private final CognitoService cognitoService;
|
||||
|
||||
@Inject
|
||||
public CognitoUserPoolGroupCfnProvisioner(CognitoService cognitoService) {
|
||||
this.cognitoService = cognitoService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of("AWS::Cognito::UserPoolGroup");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String userPoolId = ctx.resolveOptional(props, "UserPoolId");
|
||||
if (userPoolId == null || userPoolId.isBlank()) {
|
||||
throw new IllegalArgumentException("UserPoolId is required for AWS::Cognito::UserPoolGroup");
|
||||
}
|
||||
// GroupName is optional, and the generated stand-in has to stay put: generating a fresh one
|
||||
// on each UpdateStack would create a second group and orphan the one the stack already owns.
|
||||
String groupName = ctx.stablePhysicalName(
|
||||
ctx.resolveOptional(props, "GroupName"), r.getLogicalId(), 128, false);
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
Integer precedence = parsePrecedence(ctx.resolveOptional(props, "Precedence"));
|
||||
String roleArn = ctx.resolveOptional(props, "RoleArn");
|
||||
|
||||
// provision is also the update path. A group is addressed by its name, so a renamed group
|
||||
// has nothing to update under the new name: that is a replacement on AWS too.
|
||||
if (ctx.reusesPriorEntity(groupName)) {
|
||||
cognitoService.updateGroup(userPoolId, groupName, description, precedence, roleArn);
|
||||
} else {
|
||||
cognitoService.createGroup(userPoolId, groupName, description, precedence, roleArn);
|
||||
}
|
||||
|
||||
r.setPhysicalId(groupName);
|
||||
r.getAttributes().put(USER_POOL_ID_ATTR, userPoolId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
String userPoolId = resource.getAttributes().get(USER_POOL_ID_ATTR);
|
||||
if (userPoolId == null || userPoolId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
cognitoService.deleteGroup(userPoolId, resource.getPhysicalId());
|
||||
} catch (AwsException e) {
|
||||
// An already-deleted group is the one failure that genuinely means "done". Anything
|
||||
// else is a real error worth surfacing rather than hiding behind a debug line.
|
||||
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("Cognito group already gone, treating as deleted: {0}", resource.getPhysicalId());
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer parsePrecedence(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.valueOf(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Precedence must be an integer for AWS::Cognito::UserPoolGroup, got: " + value, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,11 +311,7 @@ public class CognitoService implements ResourceProvider {
|
||||
throw new AwsException("InvalidParameterException", "Attribute name contains invalid characters.", 400);
|
||||
}
|
||||
|
||||
boolean developerOnly = Boolean.TRUE.equals(attr.get("DeveloperOnlyAttribute"));
|
||||
String prefix = developerOnly ? "dev:" : "custom:";
|
||||
if (!name.startsWith("custom:") && !name.startsWith("dev:")) {
|
||||
attr.put("Name", prefix + name);
|
||||
}
|
||||
attr.put("Name", prefixedAttributeName(name, Boolean.TRUE.equals(attr.get("DeveloperOnlyAttribute"))));
|
||||
|
||||
String finalName = (String) attr.get("Name");
|
||||
boolean exists = schema.stream().anyMatch(existing -> finalName.equals(existing.get("Name")));
|
||||
@@ -366,12 +362,37 @@ public class CognitoService implements ResourceProvider {
|
||||
pool.setPolicies(normalized);
|
||||
}
|
||||
|
||||
private static String prefixedAttributeName(String name, boolean developerOnly) {
|
||||
if (name.startsWith("custom:") || name.startsWith("dev:")) {
|
||||
return name;
|
||||
}
|
||||
return (developerOnly ? "dev:" : "custom:") + name;
|
||||
}
|
||||
|
||||
private static List<Map<String, Object>> prefixCustomSchemaAttributes(List<Map<String, Object>> schema) {
|
||||
if (schema == null) {
|
||||
return null;
|
||||
}
|
||||
List<Map<String, Object>> prefixed = new ArrayList<>(schema.size());
|
||||
for (Map<String, Object> attr : schema) {
|
||||
String name = attr == null ? null : (String) attr.get("Name");
|
||||
if (name == null || name.isBlank() || CognitoStandardAttributes.isStandard(name)) {
|
||||
prefixed.add(attr);
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> copy = new HashMap<>(attr);
|
||||
copy.put("Name", prefixedAttributeName(name, Boolean.TRUE.equals(attr.get("DeveloperOnlyAttribute"))));
|
||||
prefixed.add(copy);
|
||||
}
|
||||
return prefixed;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void populateUserPool(UserPool pool, Map<String, Object> request) {
|
||||
if (request.containsKey("Policies")) pool.setPolicies((Map<String, Object>) request.get("Policies"));
|
||||
if (request.containsKey("DeletionProtection")) pool.setDeletionProtection((String) request.get("DeletionProtection"));
|
||||
if (request.containsKey("LambdaConfig")) pool.setLambdaConfig((Map<String, Object>) request.get("LambdaConfig"));
|
||||
if (request.containsKey("Schema")) pool.setSchemaAttributes((List<Map<String, Object>>) request.get("Schema"));
|
||||
if (request.containsKey("Schema")) pool.setSchemaAttributes(prefixCustomSchemaAttributes((List<Map<String, Object>>) request.get("Schema")));
|
||||
if (request.containsKey("AutoVerifiedAttributes")) pool.setAutoVerifiedAttributes((List<String>) request.get("AutoVerifiedAttributes"));
|
||||
if (request.containsKey("AliasAttributes")) pool.setAliasAttributes((List<String>) request.get("AliasAttributes"));
|
||||
if (request.containsKey("UsernameAttributes")) pool.setUsernameAttributes((List<String>) request.get("UsernameAttributes"));
|
||||
|
||||
+11
@@ -4,6 +4,8 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
final class CognitoStandardAttributes {
|
||||
|
||||
@@ -71,6 +73,15 @@ final class CognitoStandardAttributes {
|
||||
return attr;
|
||||
}
|
||||
|
||||
private static final Set<String> DEFAULT_NAMES = DEFAULTS.stream()
|
||||
.map(attr -> (String) attr.get("Name"))
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
|
||||
/** True when {@code name} is one of the standard OIDC attributes every pool carries. */
|
||||
static boolean isStandard(String name) {
|
||||
return name != null && DEFAULT_NAMES.contains(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges standard attributes with any pool-defined schema.
|
||||
* Custom attributes (name starts with "custom:") are appended after standard ones.
|
||||
|
||||
+2
@@ -46,6 +46,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrai
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
|
||||
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.Ec2LaunchTemplateCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkAclCfnProvisioner;
|
||||
@@ -267,6 +268,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (cognitoService != null) {
|
||||
discovered.add(new CognitoCfnProvisioner(cognitoService));
|
||||
discovered.add(new CognitoUserPoolGroupCfnProvisioner(cognitoService));
|
||||
}
|
||||
if (cloudFrontService != null) {
|
||||
discovered.add(new CloudFrontCfnProvisioner(cloudFrontService));
|
||||
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
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 org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationCognitoUserPoolGroupIntegrationTest {
|
||||
|
||||
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";
|
||||
|
||||
@BeforeAll
|
||||
static void registerAwsJsonParser() {
|
||||
RestAssured.registerParser(COGNITO_CONTENT_TYPE, Parser.JSON);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackProvisionsGroupsVisibleToCognito() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-cognito-groups-" + suffix;
|
||||
|
||||
String poolId = createStack(stackName, poolAndGroupsTemplate("admin", 0));
|
||||
|
||||
// Both declared groups exist, and only those two.
|
||||
cognito("ListGroups", "{\"UserPoolId\": \"" + poolId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Groups", hasSize(2))
|
||||
.body("Groups.GroupName", containsInAnyOrder("admin", "readers"));
|
||||
|
||||
cognito("GetGroup", "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"admin\"}")
|
||||
.statusCode(200)
|
||||
.body("Group.Description", equalTo("Back office operators"))
|
||||
.body("Group.Precedence", equalTo(0));
|
||||
|
||||
// The matched negative: a group the template never declared is genuinely absent, through
|
||||
// the same call against the same pool. Without it, a lookup that answered "present" for
|
||||
// anything would look identical to a working provisioner.
|
||||
cognito("GetGroup", "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"admins\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupRefResolvesToTheGroupName() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-cognito-group-ref-" + suffix;
|
||||
|
||||
createStack(stackName, poolAndGroupsTemplate("admin", 0));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<OutputKey>AdminGroupName</OutputKey>"))
|
||||
.body(containsString("<OutputValue>admin</OutputValue>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackReconcilesExistingGroupInsteadOfFailing() {
|
||||
// provision() re-runs for every resource on every UpdateStack whether or not its
|
||||
// properties changed, so a group left alone between deploys must reconcile rather than
|
||||
// call CreateGroup again and roll the stack back with GroupExistsException.
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-cognito-group-update-" + suffix;
|
||||
|
||||
String poolId = createStack(stackName, poolAndGroupsTemplate("admin", 0));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", poolAndGroupsTemplate("admin", 7))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
|
||||
.body(not(containsString("ROLLBACK")));
|
||||
|
||||
cognito("ListGroups", "{\"UserPoolId\": \"" + poolId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Groups", hasSize(2));
|
||||
|
||||
cognito("GetGroup", "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"admin\"}")
|
||||
.statusCode(200)
|
||||
.body("Group.Precedence", equalTo(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingAGroupFromTheTemplateDeletesOnlyThatGroup() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-cognito-group-delete-" + suffix;
|
||||
|
||||
String poolId = createStack(stackName, poolAndGroupsTemplate("admin", 0));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", poolAndStudentGroupOnlyTemplate())
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
cognito("GetGroup", "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"admin\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
cognito("GetGroup", "{\"UserPoolId\": \"" + poolId + "\", \"GroupName\": \"readers\"}")
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void poolSchemaCustomAttributesAreNamespacedAndStandardOnesAreNot() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-cognito-schema-" + suffix;
|
||||
|
||||
String poolId = createStack(stackName, poolAndGroupsTemplate("admin", 0));
|
||||
|
||||
cognito("DescribeUserPool", "{\"UserPoolId\": \"" + poolId + "\"}")
|
||||
.statusCode(200)
|
||||
// The template declares EmployeeId unprefixed, as CloudFormation and the SDKs do.
|
||||
.body("UserPool.SchemaAttributes.find { it.Name == 'custom:EmployeeId' }.AttributeDataType",
|
||||
equalTo("String"))
|
||||
.body("UserPool.SchemaAttributes.find { it.Name == 'EmployeeId' }", nullValue())
|
||||
// A standard attribute in the same list overrides its default rather than becoming a
|
||||
// custom one, so email stays bare and keeps the Required the template asked for.
|
||||
.body("UserPool.SchemaAttributes.find { it.Name == 'email' }.Required", equalTo(true))
|
||||
.body("UserPool.SchemaAttributes.find { it.Name == 'custom:email' }", nullValue());
|
||||
}
|
||||
|
||||
/** Creates the stack, asserts it completed, and returns the pool id from its outputs. */
|
||||
private String createStack(String stackName, String template) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String describeXml = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.extract().asString();
|
||||
|
||||
return describeXml.split("<OutputKey>PoolId</OutputKey>")[1]
|
||||
.split("<OutputValue>")[1].split("</OutputValue>")[0];
|
||||
}
|
||||
|
||||
private io.restassured.response.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();
|
||||
}
|
||||
|
||||
private static String poolAndGroupsTemplate(String adminGroupName, int adminPrecedence) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"UserPool": {
|
||||
"Type": "AWS::Cognito::UserPool",
|
||||
"Properties": {
|
||||
"UserPoolName": "cfn-group-pool",
|
||||
"Schema": [
|
||||
{ "Name": "EmployeeId", "AttributeDataType": "String", "Mutable": true },
|
||||
{ "Name": "email", "AttributeDataType": "String", "Required": true }
|
||||
]
|
||||
}
|
||||
},
|
||||
"AdminGroup": {
|
||||
"Type": "AWS::Cognito::UserPoolGroup",
|
||||
"Properties": {
|
||||
"UserPoolId": { "Ref": "UserPool" },
|
||||
"GroupName": "%s",
|
||||
"Description": "Back office operators",
|
||||
"Precedence": %d
|
||||
}
|
||||
},
|
||||
"StudentGroup": {
|
||||
"Type": "AWS::Cognito::UserPoolGroup",
|
||||
"Properties": {
|
||||
"UserPoolId": { "Ref": "UserPool" },
|
||||
"GroupName": "readers"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"PoolId": { "Value": { "Ref": "UserPool" } },
|
||||
"AdminGroupName": { "Value": { "Ref": "AdminGroup" } }
|
||||
}
|
||||
}
|
||||
""".formatted(adminGroupName, adminPrecedence);
|
||||
}
|
||||
|
||||
private static String poolAndStudentGroupOnlyTemplate() {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"UserPool": {
|
||||
"Type": "AWS::Cognito::UserPool",
|
||||
"Properties": {
|
||||
"UserPoolName": "cfn-group-pool",
|
||||
"Schema": [
|
||||
{ "Name": "EmployeeId", "AttributeDataType": "String", "Mutable": true },
|
||||
{ "Name": "email", "AttributeDataType": "String", "Required": true }
|
||||
]
|
||||
}
|
||||
},
|
||||
"StudentGroup": {
|
||||
"Type": "AWS::Cognito::UserPoolGroup",
|
||||
"Properties": {
|
||||
"UserPoolId": { "Ref": "UserPool" },
|
||||
"GroupName": "readers"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"PoolId": { "Value": { "Ref": "UserPool" } }
|
||||
}
|
||||
}
|
||||
""";
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
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 org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
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;
|
||||
|
||||
/** The Cognito user pool group CFN provisioner in isolation, with only CognitoService mocked. */
|
||||
class CognitoUserPoolGroupCfnProvisionerTest {
|
||||
|
||||
private final CognitoService cognito = mock(CognitoService.class);
|
||||
private final CognitoUserPoolGroupCfnProvisioner provisioner =
|
||||
new CognitoUserPoolGroupCfnProvisioner(cognito);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
return ctx(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* CloudFormation hands a provisioner the prior physical id through the context, so an update
|
||||
* has to be modelled there and not only on the resource.
|
||||
*/
|
||||
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) {
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
if (userPoolId != null) {
|
||||
props.put("UserPoolId", userPoolId);
|
||||
}
|
||||
if (groupName != null) {
|
||||
props.put("GroupName", groupName);
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
private StackResource resource(String physicalId) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("AdminGroup");
|
||||
r.setResourceType("AWS::Cognito::UserPoolGroup");
|
||||
r.setPhysicalId(physicalId);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesTheUserPoolGroupType() {
|
||||
assertEquals(Set.of("AWS::Cognito::UserPoolGroup"), provisioner.resourceTypes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsTheGroupAndRefResolvesToItsName() {
|
||||
ObjectNode props = props("us-east-1_pool", "admin");
|
||||
props.put("Description", "Back office");
|
||||
props.put("Precedence", 7);
|
||||
props.put("RoleArn", "arn:aws:iam::000000000000:role/admins");
|
||||
StackResource r = resource(null);
|
||||
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
verify(cognito).createGroup("us-east-1_pool", "admin", "Back office", 7,
|
||||
"arn:aws:iam::000000000000:role/admins");
|
||||
assertEquals("admin", r.getPhysicalId(), "Ref must resolve to the group name");
|
||||
assertEquals("us-east-1_pool", r.getAttributes().get("UserPoolId"),
|
||||
"delete needs the pool id, which the physical id cannot carry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatesAPhysicalNameWhenGroupNameIsAbsent() {
|
||||
StackResource r = resource(null);
|
||||
|
||||
provisioner.provision(r, props("us-east-1_pool", null), ctx());
|
||||
|
||||
assertTrue(r.getPhysicalId().startsWith("my-stack-AdminGroup-"), r.getPhysicalId());
|
||||
verify(cognito).createGroup(eq("us-east-1_pool"), eq(r.getPhysicalId()), isNull(), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnnamedGroupKeepsItsGeneratedNameAcrossUpdates() {
|
||||
// GroupName is optional and CloudFormation generates one. Generating a fresh name on every
|
||||
// UpdateStack would create a second group and orphan the first, so the generated name has
|
||||
// to survive the update.
|
||||
StackResource created = resource(null);
|
||||
provisioner.provision(created, props("us-east-1_pool", null), ctx());
|
||||
String generated = created.getPhysicalId();
|
||||
|
||||
StackResource updated = resource(generated);
|
||||
provisioner.provision(updated, props("us-east-1_pool", null), ctx(generated));
|
||||
|
||||
assertEquals(generated, updated.getPhysicalId(),
|
||||
"an unnamed group must keep its generated name across updates");
|
||||
verify(cognito).updateGroup("us-east-1_pool", generated, null, null, null);
|
||||
verify(cognito, times(1)).createGroup(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reProvisioningTheSameGroupUpdatesInPlace() {
|
||||
// UpdateStack re-provisions every resource whether or not its properties changed, so an
|
||||
// unchanged group must reconcile rather than call CreateGroup again and fail the stack.
|
||||
StackResource r = resource("admin");
|
||||
|
||||
provisioner.provision(r, props("us-east-1_pool", "admin"), ctx("admin"));
|
||||
|
||||
verify(cognito).updateGroup("us-east-1_pool", "admin", null, null, null);
|
||||
verify(cognito, never()).createGroup(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renamingTheGroupCreatesUnderTheNewName() {
|
||||
StackResource r = resource("admin");
|
||||
|
||||
provisioner.provision(r, props("us-east-1_pool", "operators"), ctx("admin"));
|
||||
|
||||
verify(cognito).createGroup("us-east-1_pool", "operators", null, null, null);
|
||||
assertEquals("operators", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingUserPoolIdFailsTheResourceRatherThanStubbingIt() {
|
||||
StackResource r = resource(null);
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> provisioner.provision(r, props(null, "admin"), ctx()));
|
||||
verifyNoInteractions(cognito);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonIntegerPrecedenceFailsTheResourceRatherThanBeingDropped() {
|
||||
ObjectNode props = props("us-east-1_pool", "admin");
|
||||
props.put("Precedence", "not-a-number");
|
||||
StackResource r = resource(null);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> provisioner.provision(r, props, ctx()));
|
||||
verifyNoInteractions(cognito);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteUsesTheStoredPoolIdAndTheGroupName() {
|
||||
StackResource r = resource("admin");
|
||||
r.setAttributes(new HashMap<>(Map.of("UserPoolId", "us-east-1_pool")));
|
||||
|
||||
provisioner.delete(r, "us-east-1");
|
||||
|
||||
verify(cognito).deleteGroup("us-east-1_pool", "admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWithoutAStoredPoolIdIsANoOp() {
|
||||
// The CREATE-rollback shape: nothing was provisioned, so there is nothing to address.
|
||||
provisioner.delete(resource("admin"), "us-east-1");
|
||||
|
||||
verifyNoInteractions(cognito);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAGroupThatIsAlreadyGoneIsTolerated() {
|
||||
StackResource r = resource("admin");
|
||||
r.setAttributes(new HashMap<>(Map.of("UserPoolId", "us-east-1_pool")));
|
||||
doThrow(new AwsException("ResourceNotFoundException", "Group not found: admin", 400))
|
||||
.when(cognito).deleteGroup("us-east-1_pool", "admin");
|
||||
|
||||
provisioner.delete(r, "us-east-1");
|
||||
|
||||
verify(cognito).deleteGroup("us-east-1_pool", "admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSurfacesAFailureThatIsNotAMissingGroup() {
|
||||
StackResource r = resource("admin");
|
||||
r.setAttributes(new HashMap<>(Map.of("UserPoolId", "us-east-1_pool")));
|
||||
doThrow(new AwsException("InternalFailure", "storage unavailable", 500))
|
||||
.when(cognito).deleteGroup("us-east-1_pool", "admin");
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.delete(r, "us-east-1"));
|
||||
|
||||
assertEquals("InternalFailure", thrown.getErrorCode());
|
||||
}
|
||||
}
|
||||
@@ -132,7 +132,10 @@ class CognitoServiceTest {
|
||||
assertNotNull(pool.getId());
|
||||
assertEquals("FullConfigPool", pool.getName());
|
||||
assertEquals("arn:aws:cognito-idp:us-east-1:000000000000:userpool/" + pool.getId(), pool.getArn());
|
||||
assertEquals(schema, pool.getSchemaAttributes());
|
||||
assertEquals(
|
||||
List.of(Map.of("Name", "custom:my-attr", "AttributeDataType", "String")),
|
||||
pool.getSchemaAttributes(),
|
||||
"a non-standard Schema attribute is stored under the custom: namespace");
|
||||
// A supplied PasswordPolicy is normalized with AWS's defaults for the fields left unset
|
||||
// (MinimumLength here was explicit; the rest were not), matching what DescribeUserPool
|
||||
// returns on real Cognito for a policy submitted this way.
|
||||
@@ -333,6 +336,83 @@ class CognitoServiceTest {
|
||||
"email", "bob@example.com", "phone_number", "+4915112345679")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserPoolNamespacesNonStandardSchemaAttributes() {
|
||||
// The Schema property carries custom attributes unprefixed - it is what CloudFormation
|
||||
// and the SDKs send - and AWS files them under custom: on the way in. A pool that stored
|
||||
// the bare name answered DescribeUserPool with an attribute no client ever asks for.
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("PoolName", "CustomAttrPool");
|
||||
request.put("Schema", List.of(
|
||||
Map.of("Name", "EmployeeId", "AttributeDataType", "String", "Mutable", true),
|
||||
Map.of("Name", "Seniority", "AttributeDataType", "Number")));
|
||||
|
||||
UserPool pool = service.createUserPool(request, "us-east-1");
|
||||
|
||||
assertEquals(List.of("custom:EmployeeId", "custom:Seniority"), schemaNames(pool));
|
||||
assertEquals(Boolean.TRUE, findSchemaAttribute(pool, "custom:EmployeeId").get("Mutable"),
|
||||
"the rest of the attribute definition is carried through unchanged");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserPoolLeavesStandardSchemaAttributesUnprefixed() {
|
||||
// A standard attribute travels in the same list to override its default, typically to make
|
||||
// email required. Namespacing it would file a second, custom attribute and leave the
|
||||
// non-required default in force.
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("PoolName", "StandardOverridePool");
|
||||
request.put("Schema", List.of(
|
||||
Map.of("Name", "email", "AttributeDataType", "String", "Required", true),
|
||||
Map.of("Name", "Department", "AttributeDataType", "String")));
|
||||
|
||||
UserPool pool = service.createUserPool(request, "us-east-1");
|
||||
|
||||
assertEquals(List.of("email", "custom:Department"), schemaNames(pool));
|
||||
assertEquals(Boolean.TRUE, findSchemaAttribute(pool, "email").get("Required"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserPoolLeavesAlreadyNamespacedSchemaAttributesAlone() {
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("PoolName", "PrefixedAttrPool");
|
||||
request.put("Schema", List.of(
|
||||
Map.of("Name", "custom:tenant_id", "AttributeDataType", "String"),
|
||||
Map.of("Name", "internal", "AttributeDataType", "String",
|
||||
"DeveloperOnlyAttribute", true)));
|
||||
|
||||
UserPool pool = service.createUserPool(request, "us-east-1");
|
||||
|
||||
assertEquals(List.of("custom:tenant_id", "dev:internal"), schemaNames(pool));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolResendingTheSameSchemaDoesNotPrefixTwice() {
|
||||
// CloudFormation re-sends the whole template on every UpdateStack, so the same Schema
|
||||
// arrives again through updateUserPool. A second pass must be a no-op, not custom:custom:.
|
||||
Map<String, Object> create = new HashMap<>();
|
||||
create.put("PoolName", "ReappliedSchemaPool");
|
||||
create.put("Schema", List.of(Map.of("Name", "EmployeeId", "AttributeDataType", "String")));
|
||||
UserPool pool = service.createUserPool(create, "us-east-1");
|
||||
|
||||
Map<String, Object> update = new HashMap<>();
|
||||
update.put("UserPoolId", pool.getId());
|
||||
update.put("Schema", pool.getSchemaAttributes());
|
||||
UserPool updated = service.updateUserPool(update, "us-east-1");
|
||||
|
||||
assertEquals(List.of("custom:EmployeeId"), schemaNames(updated));
|
||||
}
|
||||
|
||||
private static List<String> schemaNames(UserPool pool) {
|
||||
return pool.getSchemaAttributes().stream().map(attr -> (String) attr.get("Name")).toList();
|
||||
}
|
||||
|
||||
private static Map<String, Object> findSchemaAttribute(UserPool pool, String name) {
|
||||
return pool.getSchemaAttributes().stream()
|
||||
.filter(attr -> name.equals(attr.get("Name")))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AssertionError("no schema attribute named " + name));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserPoolWithOverrideIdUsesProvidedId() {
|
||||
UserPool pool = service.createUserPool(
|
||||
|
||||
+9
@@ -24,6 +24,15 @@ class CognitoStandardAttributesTest {
|
||||
assertEquals(EXPECTED_NAMES, names);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isStandardRecognisesEveryDefaultAndNothingElse() {
|
||||
EXPECTED_NAMES.forEach(name ->
|
||||
assertTrue(CognitoStandardAttributes.isStandard(name), name + " is a standard attribute"));
|
||||
assertFalse(CognitoStandardAttributes.isStandard("EmployeeId"));
|
||||
assertFalse(CognitoStandardAttributes.isStandard("custom:email"));
|
||||
assertFalse(CognitoStandardAttributes.isStandard(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void subIsRequiredAndImmutable() {
|
||||
Map<String, Object> sub = findByName(CognitoStandardAttributes.DEFAULTS, "sub");
|
||||
|
||||
@@ -49,6 +49,7 @@ AWS::CodePipeline::Webhook CodePipelineCfnProvisioner
|
||||
AWS::Cognito::UserPool CognitoCfnProvisioner
|
||||
AWS::Cognito::UserPoolClient CognitoCfnProvisioner
|
||||
AWS::Cognito::UserPoolDomain CognitoCfnProvisioner
|
||||
AWS::Cognito::UserPoolGroup CognitoUserPoolGroupCfnProvisioner
|
||||
AWS::Config::ConfigRule ConfigCfnProvisioner
|
||||
AWS::DynamoDB::GlobalTable DynamoDbCfnProvisioner
|
||||
AWS::DynamoDB::Table DynamoDbCfnProvisioner
|
||||
|
||||
|
Reference in new issue
Block a user