mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cognito): provision AWS::Cognito::UserPoolDomain (#3005)
* feat(cognito): provision AWS::Cognito::UserPoolDomain The type was a stub: the stack turned green, but Fn::GetAtt CloudFrontDistribution resolved to the literal LogicalId.CloudFrontDistribution, so a Route 53 alias record for a custom domain pointed at that text. CognitoCfnProvisioner creates the domain through the existing CreateUserPoolDomain. Ref is the domain name and CloudFrontDistribution is the CloudFront name DescribeUserPoolDomain reports. A changed Domain or UserPoolId replaces the domain; any other change is applied in place through the new UpdateUserPoolDomain operation, so the distribution a DNS alias points at survives a certificate change, as on AWS. Delete uses the pool id recorded at create time and tolerates an already deleted domain. UpdateUserPoolDomain is also exposed on the Cognito API, with the same response shape as CreateUserPoolDomain. * feat(cognito): treat null domain settings as absent and pin the same-name replacement failure Review follow-ups for AWS::Cognito::UserPoolDomain: - A JSON null inside CustomDomainConfig was copied as the text "null", which would have passed for a certificate ARN. Null values are now skipped, so the service rejects the missing ARN as it should. - ManagedLoginVersion on CreateUserPoolDomain and UpdateUserPoolDomain treated an explicit null as 0, overwriting the stored version. Null now counts as omitted, and a value of another JSON type is a SerializationException, as on AWS. - Moving an unchanged domain to another pool fails on the create, because domain names are unique across pools and the replacement is created before the original is deleted, exactly as on AWS. The unit test that mocked this path as a success is replaced by one that pins the failure and checks the original domain is left in place. * test(cognito): cover domain replacement, prefix domains and SecurityPolicy updates The stack test now also renames the domain through UpdateStack, asserting the old domain is gone and the new one has its own distribution, and a second stack proves a prefix domain resolves Fn::GetAtt CloudFrontDistribution to an empty string rather than the literal attribute name. The service test covers a SecurityPolicy change and that an omitted policy is kept. The in-place check reads ctx.reusesPriorEntity(domain), as the sibling provisioners do. * test(cognito): provision the stack test's certificate through AWS::CertificateManager::Certificate With the ACM provisioner merged, the stack test now declares the certificate as a resource and references it with Fn::GetAtt, the way CDK does. Rotating to a new certificate resource updates the domain in place and removes the old certificate once nothing references it. A wildcard name keeps a domain rename from replacing the certificate.
This commit is contained in:
1 parent
71c7836da1
commit
f3c251ef20
12 files changed
+1020
-12
No files matched your search
@@ -79,7 +79,7 @@ cross-resource references.
|
||||
| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
|
||||
| CodeBuild | `Project` |
|
||||
| Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |
|
||||
| Cognito | `UserPool`, `UserPoolClient` |
|
||||
| Cognito | `UserPool`, `UserPoolClient`, `UserPoolDomain` |
|
||||
| ACM | `Certificate` |
|
||||
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy` |
|
||||
| EventBridge Scheduler | `ScheduleGroup` |
|
||||
|
||||
@@ -98,6 +98,7 @@ always returns it.
|
||||
|--------|-------------|
|
||||
| CreateUserPoolDomain | Creates a Cognito prefix domain, or a custom domain when `CustomDomainConfig.CertificateArn` is given. |
|
||||
| DescribeUserPoolDomain | Returns a domain's description, including `CloudFrontDistribution` for custom domains. |
|
||||
| UpdateUserPoolDomain | Replaces a custom domain's certificate or changes the managed login version in place. The domain keeps its `CloudFrontDistribution`. |
|
||||
| DeleteUserPoolDomain | Deletes a domain from its user pool. |
|
||||
|
||||
### Log Delivery
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
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 io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::Cognito::UserPoolDomain}. The physical id is the domain name, as in AWS,
|
||||
* and {@code Fn::GetAtt CloudFrontDistribution} is the CloudFront name a custom domain's DNS alias
|
||||
* points at. A prefix domain has no distribution of its own in Floci, so for one the attribute is
|
||||
* empty rather than the literal {@code LogicalId.CloudFrontDistribution} an unset attribute yields.
|
||||
*
|
||||
* <p>{@code Routing} (regional failover) is accepted and ignored; nothing in the emulator fails
|
||||
* over. {@code AWS::Cognito::UserPool} and {@code UserPoolClient} still live in the legacy switch.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CognitoCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CognitoCfnProvisioner.class);
|
||||
private static final String NOT_FOUND = "ResourceNotFoundException";
|
||||
|
||||
private final CognitoService cognitoService;
|
||||
|
||||
public CognitoCfnProvisioner(CognitoService cognitoService) {
|
||||
this.cognitoService = cognitoService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of("AWS::Cognito::UserPoolDomain");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String domain = ctx.resolveOptional(props, "Domain");
|
||||
String userPoolId = ctx.resolveOptional(props, "UserPoolId");
|
||||
if (domain == null || domain.isBlank() || userPoolId == null || userPoolId.isBlank()) {
|
||||
throw new IllegalArgumentException("AWS::Cognito::UserPoolDomain requires Domain and UserPoolId");
|
||||
}
|
||||
Map<String, Object> customDomainConfig = resolveCustomDomainConfig(props, ctx);
|
||||
Integer managedLoginVersion = resolveManagedLoginVersion(props, ctx);
|
||||
|
||||
// Domain and UserPoolId are createOnly in the schema: a change to either replaces the
|
||||
// domain, and the prior one is removed once the new one exists. Domain names are unique
|
||||
// across pools, so a change to UserPoolId alone fails on the create, as it does on AWS,
|
||||
// where CloudFormation also creates the replacement before deleting the original. Anything
|
||||
// else, a renewed certificate or another managed login version, is applied in place so the
|
||||
// CloudFront distribution a DNS alias points at survives, as on AWS.
|
||||
UserPoolDomain existing = ctx.isUpdate() ? findExisting(ctx.priorPhysicalId()) : null;
|
||||
UserPoolDomain provisioned;
|
||||
if (existing != null && ctx.reusesPriorEntity(domain) && userPoolId.equals(existing.getUserPoolId())) {
|
||||
provisioned = cognitoService.updateUserPoolDomain(domain, userPoolId, customDomainConfig, managedLoginVersion);
|
||||
} else {
|
||||
provisioned = cognitoService.createUserPoolDomain(domain, userPoolId, customDomainConfig, managedLoginVersion);
|
||||
if (existing != null) {
|
||||
deleteDomain(existing.getDomain(), existing.getUserPoolId());
|
||||
}
|
||||
}
|
||||
r.setPhysicalId(domain);
|
||||
// Recorded so delete can name the owning pool: DeleteUserPoolDomain needs both.
|
||||
r.getAttributes().put("UserPoolId", userPoolId);
|
||||
r.getAttributes().put("CloudFrontDistribution",
|
||||
provisioned.getCloudFrontDistribution() == null ? "" : provisioned.getCloudFrontDistribution());
|
||||
}
|
||||
|
||||
/** Deletes the domain from the pool recorded at create time; without that record, looks the pool up. */
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
String userPoolId = resource.getAttributes() == null ? null : resource.getAttributes().get("UserPoolId");
|
||||
if (userPoolId == null || userPoolId.isBlank()) {
|
||||
delete(resource.getResourceType(), resource.getPhysicalId(), region);
|
||||
return;
|
||||
}
|
||||
deleteDomain(resource.getPhysicalId(), userPoolId);
|
||||
}
|
||||
|
||||
/** Only the domain itself can say which pool owns it here; one that is already gone needs nothing. */
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
UserPoolDomain existing = findExisting(physicalId);
|
||||
if (existing != null) {
|
||||
deleteDomain(physicalId, existing.getUserPoolId());
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteDomain(String domain, String userPoolId) {
|
||||
CfnDeletes.safeDelete("user pool domain", domain,
|
||||
() -> cognitoService.deleteUserPoolDomain(domain, userPoolId), NOT_FOUND);
|
||||
}
|
||||
|
||||
private UserPoolDomain findExisting(String domain) {
|
||||
try {
|
||||
return cognitoService.describeUserPoolDomain(domain);
|
||||
} catch (AwsException e) {
|
||||
if (!NOT_FOUND.equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("User pool domain {0} is gone", domain);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> resolveCustomDomainConfig(JsonNode props, ProvisionContext ctx) {
|
||||
if (props == null || !props.hasNonNull("CustomDomainConfig")) {
|
||||
return null;
|
||||
}
|
||||
JsonNode resolved = ctx.engine().resolveNode(props.get("CustomDomainConfig"));
|
||||
if (resolved == null || !resolved.isObject()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> config = new LinkedHashMap<>();
|
||||
resolved.fields().forEachRemaining(field -> {
|
||||
// A JSON null is an absent value, not the text "null" that asText() would make of it.
|
||||
if (!field.getValue().isNull()) {
|
||||
config.put(field.getKey(), field.getValue().asText());
|
||||
}
|
||||
});
|
||||
return config;
|
||||
}
|
||||
|
||||
private static Integer resolveManagedLoginVersion(JsonNode props, ProvisionContext ctx) {
|
||||
String value = ctx.resolveOptional(props, "ManagedLoginVersion");
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.valueOf(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"AWS::Cognito::UserPoolDomain ManagedLoginVersion must be an integer, got: " + value, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,7 @@ public class CognitoJsonHandler {
|
||||
case "DeleteIdentityProvider" -> handleDeleteIdentityProvider(request);
|
||||
case "CreateUserPoolDomain" -> handleCreateUserPoolDomain(request);
|
||||
case "DescribeUserPoolDomain" -> handleDescribeUserPoolDomain(request);
|
||||
case "UpdateUserPoolDomain" -> handleUpdateUserPoolDomain(request);
|
||||
case "DeleteUserPoolDomain" -> handleDeleteUserPoolDomain(request);
|
||||
case "SetLogDeliveryConfiguration" -> handleSetLogDeliveryConfiguration(request);
|
||||
case "GetLogDeliveryConfiguration" -> handleGetLogDeliveryConfiguration(request);
|
||||
@@ -443,16 +444,46 @@ public class CognitoJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleCreateUserPoolDomain(JsonNode request) {
|
||||
JsonNode customDomainConfigNode = request.path("CustomDomainConfig");
|
||||
Map<String, Object> customDomainConfig = customDomainConfigNode.isObject()
|
||||
? objectMapper.convertValue(customDomainConfigNode, new TypeReference<Map<String, Object>>() {})
|
||||
: null;
|
||||
UserPoolDomain domain = service.createUserPoolDomain(
|
||||
request.path("Domain").asText(),
|
||||
request.path("UserPoolId").asText(),
|
||||
customDomainConfig,
|
||||
request.has("ManagedLoginVersion") ? request.path("ManagedLoginVersion").asInt() : null
|
||||
customDomainConfig(request),
|
||||
managedLoginVersion(request)
|
||||
);
|
||||
return Response.ok(userPoolDomainResultToNode(domain)).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateUserPoolDomain(JsonNode request) {
|
||||
UserPoolDomain domain = service.updateUserPoolDomain(
|
||||
request.path("Domain").asText(),
|
||||
request.path("UserPoolId").asText(),
|
||||
customDomainConfig(request),
|
||||
managedLoginVersion(request)
|
||||
);
|
||||
return Response.ok(userPoolDomainResultToNode(domain)).build();
|
||||
}
|
||||
|
||||
private Map<String, Object> customDomainConfig(JsonNode request) {
|
||||
JsonNode node = request.path("CustomDomainConfig");
|
||||
return node.isObject()
|
||||
? objectMapper.convertValue(node, new TypeReference<Map<String, Object>>() {})
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Absent or null yields null; a value of another JSON type is a SerializationException, as on AWS. */
|
||||
private static Integer managedLoginVersion(JsonNode request) {
|
||||
JsonNode node = request.get("ManagedLoginVersion");
|
||||
if (node == null || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isIntegralNumber()) {
|
||||
throw new AwsException("SerializationException", "Expected integer or null", 400);
|
||||
}
|
||||
return node.intValue();
|
||||
}
|
||||
|
||||
/** CreateUserPoolDomain and UpdateUserPoolDomain share this result shape. */
|
||||
private ObjectNode userPoolDomainResultToNode(UserPoolDomain domain) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
if (domain.isCustomDomain()) {
|
||||
response.put("CloudFrontDomain", domain.getCloudFrontDistribution());
|
||||
@@ -460,7 +491,7 @@ public class CognitoJsonHandler {
|
||||
if (domain.getManagedLoginVersion() != null) {
|
||||
response.put("ManagedLoginVersion", domain.getManagedLoginVersion());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
return response;
|
||||
}
|
||||
|
||||
private Response handleDescribeUserPoolDomain(JsonNode request) {
|
||||
|
||||
@@ -1123,6 +1123,43 @@ public class CognitoService implements ResourceProvider {
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Domain does not exist", 404));
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes a domain in place: the certificate behind a custom domain ({@code CustomDomainConfig})
|
||||
* or the managed login version. As on AWS the domain keeps its CloudFront distribution, so a
|
||||
* DNS alias pointing at it stays valid. A setting the request omits is left unchanged.
|
||||
*/
|
||||
public UserPoolDomain updateUserPoolDomain(String domain, String userPoolId,
|
||||
Map<String, Object> customDomainConfig, Integer managedLoginVersion) {
|
||||
describeUserPool(userPoolId);
|
||||
UserPoolDomain userPoolDomain = describeUserPoolDomain(domain);
|
||||
if (!userPoolDomain.getUserPoolId().equals(userPoolId)) {
|
||||
throw new AwsException("ResourceNotFoundException", "Domain does not exist", 404);
|
||||
}
|
||||
if (customDomainConfig != null) {
|
||||
if (!userPoolDomain.isCustomDomain()) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"CustomDomainConfig cannot be set on an Amazon Cognito prefix domain", 400);
|
||||
}
|
||||
String certificateArn = (String) customDomainConfig.get("CertificateArn");
|
||||
if (certificateArn == null || certificateArn.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"CertificateArn is required in CustomDomainConfig", 400);
|
||||
}
|
||||
userPoolDomain.setCertificateArn(certificateArn);
|
||||
Object securityPolicy = customDomainConfig.get("SecurityPolicy");
|
||||
if (securityPolicy != null) {
|
||||
userPoolDomain.setSecurityPolicy(securityPolicy.toString());
|
||||
}
|
||||
}
|
||||
if (managedLoginVersion != null) {
|
||||
userPoolDomain.setManagedLoginVersion(managedLoginVersion);
|
||||
}
|
||||
userPoolDomain.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
domainStore.put(domain, userPoolDomain);
|
||||
LOG.infov("Updated User Pool Domain: {0} for pool {1}", domain, userPoolId);
|
||||
return userPoolDomain;
|
||||
}
|
||||
|
||||
public void deleteUserPoolDomain(String domain, String userPoolId) {
|
||||
UserPoolDomain userPoolDomain = describeUserPoolDomain(domain);
|
||||
if (!userPoolDomain.getUserPoolId().equals(userPoolId)) {
|
||||
|
||||
+4
@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2LaunchTemplateCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkAclCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupRuleCfnProvisioner;
|
||||
@@ -206,6 +207,9 @@ final class CfnProvisionerFixture {
|
||||
if (pipesService != null) {
|
||||
discovered.add(new PipesCfnProvisioner(pipesService));
|
||||
}
|
||||
if (cognitoService != null) {
|
||||
discovered.add(new CognitoCfnProvisioner(cognitoService));
|
||||
}
|
||||
if (firehoseService != null) {
|
||||
discovered.add(new FirehoseCfnProvisioner(firehoseService));
|
||||
}
|
||||
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
|
||||
import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsAction;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
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.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Provisions an {@code AWS::Cognito::UserPoolDomain} through a CloudFormation stack, laid out the
|
||||
* way CDK emits a custom domain: a user pool, an {@code AWS::CertificateManager::Certificate}, the
|
||||
* domain referencing the certificate, and a Route 53 alias record whose target is
|
||||
* {@code Fn::GetAtt CloudFrontDistribution}. Asserts that the attribute is the CloudFront name
|
||||
* {@code DescribeUserPoolDomain} reports rather than the literal {@code Domain.CloudFrontDistribution}
|
||||
* the stub arm would leave in the record, that rotating to a new certificate resource updates the
|
||||
* domain in place so the alias target survives, that a changed domain name replaces the domain, and
|
||||
* that deleting the stack removes the domain before the pool that owns it. A prefix domain, which
|
||||
* has no distribution of its own, resolves the attribute to an empty string rather than the literal.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CognitoCfnIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/cloudformation/aws4_request";
|
||||
private static final String CUSTOM_STACK = "cognito-cfn-it";
|
||||
private static final String PREFIX_STACK = "cognito-cfn-prefix-it";
|
||||
private static final String DOMAIN = "auth.cognito-cfn-it.example.com";
|
||||
private static final String REPLACEMENT_DOMAIN = "login.cognito-cfn-it.example.com";
|
||||
private static final String PREFIX_DOMAIN = "cognito-cfn-it-prefix";
|
||||
|
||||
/**
|
||||
* The certificate carries the logical id so a rotation can add a new certificate resource and
|
||||
* drop the old one, which is how a certificate is replaced without a moment where the domain
|
||||
* points at a certificate that is being deleted. A wildcard name keeps a domain rename from
|
||||
* replacing the certificate as well.
|
||||
*/
|
||||
private static String customDomainTemplate(String domain, String certificateLogicalId) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Pool": {
|
||||
"Type": "AWS::Cognito::UserPool",
|
||||
"Properties": {"UserPoolName": "cognito-cfn-it-pool"}
|
||||
},
|
||||
"%1$s": {
|
||||
"Type": "AWS::CertificateManager::Certificate",
|
||||
"Properties": {"DomainName": "*.cognito-cfn-it.example.com", "ValidationMethod": "DNS"}
|
||||
},
|
||||
"Domain": {
|
||||
"Type": "AWS::Cognito::UserPoolDomain",
|
||||
"Properties": {
|
||||
"Domain": "%2$s",
|
||||
"UserPoolId": {"Ref": "Pool"},
|
||||
"CustomDomainConfig": {"CertificateArn": {"Fn::GetAtt": ["%1$s", "CertificateArn"]}},
|
||||
"ManagedLoginVersion": 2
|
||||
}
|
||||
},
|
||||
"Zone": {
|
||||
"Type": "AWS::Route53::HostedZone",
|
||||
"Properties": {"Name": "cognito-cfn-it.example.com"}
|
||||
},
|
||||
"AuthAlias": {
|
||||
"Type": "AWS::Route53::RecordSet",
|
||||
"Properties": {
|
||||
"HostedZoneId": {"Ref": "Zone"},
|
||||
"Name": "%2$s",
|
||||
"Type": "A",
|
||||
"AliasTarget": {
|
||||
"DNSName": {"Fn::GetAtt": ["Domain", "CloudFrontDistribution"]},
|
||||
"HostedZoneId": "Z2FDTNDATAQYW2"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"PoolId": {"Value": {"Ref": "Pool"}},
|
||||
"DomainRef": {"Value": {"Ref": "Domain"}},
|
||||
"CertArn": {"Value": {"Fn::GetAtt": ["%1$s", "CertificateArn"]}},
|
||||
"AliasTarget": {"Value": {"Fn::GetAtt": ["Domain", "CloudFrontDistribution"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(certificateLogicalId, domain);
|
||||
}
|
||||
|
||||
private static final String PREFIX_DOMAIN_TEMPLATE = """
|
||||
{
|
||||
"Resources": {
|
||||
"Pool": {
|
||||
"Type": "AWS::Cognito::UserPool",
|
||||
"Properties": {"UserPoolName": "cognito-cfn-prefix-it-pool"}
|
||||
},
|
||||
"Domain": {
|
||||
"Type": "AWS::Cognito::UserPoolDomain",
|
||||
"Properties": {
|
||||
"Domain": "%s",
|
||||
"UserPoolId": {"Ref": "Pool"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"PoolId": {"Value": {"Ref": "Pool"}},
|
||||
"DomainRef": {"Value": {"Ref": "Domain"}},
|
||||
"CloudFront": {"Value": {"Fn::GetAtt": ["Domain", "CloudFrontDistribution"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(PREFIX_DOMAIN);
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void customDomainStackExposesTheCloudFrontNameRotatesTheCertificateReplacesOnRenameAndDeletesBeforeThePool()
|
||||
throws Exception {
|
||||
cloudFormation(CUSTOM_STACK, "CreateStack", customDomainTemplate(DOMAIN, "Cert"));
|
||||
|
||||
String stacks = describeStacks(CUSTOM_STACK, "CREATE_COMPLETE");
|
||||
String poolId = outputValue(stacks, "PoolId");
|
||||
String aliasTarget = outputValue(stacks, "AliasTarget");
|
||||
String certificateArn = outputValue(stacks, "CertArn");
|
||||
assertEquals(DOMAIN, outputValue(stacks, "DomainRef"));
|
||||
assertTrue(aliasTarget.endsWith(".cloudfront.net"),
|
||||
"Fn::GetAtt CloudFrontDistribution must be a CloudFront name: " + aliasTarget);
|
||||
assertTrue(certificateArn.startsWith("arn:aws:acm:us-east-1:"),
|
||||
"the certificate must be provisioned rather than stubbed: " + certificateArn);
|
||||
assertCertificateStatus(certificateArn, "ISSUED");
|
||||
|
||||
JsonNode description = describeDomain(DOMAIN);
|
||||
assertEquals(poolId, description.path("UserPoolId").asText());
|
||||
assertEquals(aliasTarget, description.path("CloudFrontDistribution").asText());
|
||||
assertEquals(certificateArn, description.path("CustomDomainConfig").path("CertificateArn").asText());
|
||||
assertEquals(2, description.path("ManagedLoginVersion").asInt());
|
||||
|
||||
// Rotation: a new certificate resource takes over and the old one leaves the template. The
|
||||
// domain moves to the new certificate in place, and the old certificate is removed once
|
||||
// nothing references it.
|
||||
cloudFormation(CUSTOM_STACK, "UpdateStack", customDomainTemplate(DOMAIN, "RenewedCert"));
|
||||
|
||||
stacks = describeStacks(CUSTOM_STACK, "UPDATE_COMPLETE");
|
||||
String renewedCertificateArn = outputValue(stacks, "CertArn");
|
||||
assertNotEquals(certificateArn, renewedCertificateArn);
|
||||
description = describeDomain(DOMAIN);
|
||||
assertEquals(renewedCertificateArn, description.path("CustomDomainConfig").path("CertificateArn").asText());
|
||||
assertEquals(aliasTarget, description.path("CloudFrontDistribution").asText(),
|
||||
"a certificate change must keep the CloudFront distribution the alias record points at");
|
||||
assertCertificateIsGone(certificateArn);
|
||||
|
||||
// Domain is createOnly: a new name is a replacement, created before the old domain goes.
|
||||
cloudFormation(CUSTOM_STACK, "UpdateStack", customDomainTemplate(REPLACEMENT_DOMAIN, "RenewedCert"));
|
||||
|
||||
stacks = describeStacks(CUSTOM_STACK, "UPDATE_COMPLETE");
|
||||
assertEquals(REPLACEMENT_DOMAIN, outputValue(stacks, "DomainRef"));
|
||||
String replacementTarget = outputValue(stacks, "AliasTarget");
|
||||
assertTrue(replacementTarget.endsWith(".cloudfront.net"), replacementTarget);
|
||||
assertNotEquals(aliasTarget, replacementTarget, "the replacement is a new domain with its own distribution");
|
||||
assertDomainIsGone(DOMAIN);
|
||||
description = describeDomain(REPLACEMENT_DOMAIN);
|
||||
assertEquals(poolId, description.path("UserPoolId").asText());
|
||||
assertEquals(replacementTarget, description.path("CloudFrontDistribution").asText());
|
||||
assertEquals(renewedCertificateArn, description.path("CustomDomainConfig").path("CertificateArn").asText());
|
||||
|
||||
cloudFormation(CUSTOM_STACK, "DeleteStack", null);
|
||||
awaitStackDeleted(CUSTOM_STACK);
|
||||
|
||||
assertDomainIsGone(REPLACEMENT_DOMAIN);
|
||||
assertCertificateIsGone(renewedCertificateArn);
|
||||
cognitoAction("DescribeUserPool", "{\"UserPoolId\": \"" + poolId + "\"}")
|
||||
.then()
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void prefixDomainStackResolvesAnEmptyCloudFrontDistribution() throws Exception {
|
||||
cloudFormation(PREFIX_STACK, "CreateStack", PREFIX_DOMAIN_TEMPLATE);
|
||||
|
||||
String stacks = describeStacks(PREFIX_STACK, "CREATE_COMPLETE");
|
||||
assertEquals(PREFIX_DOMAIN, outputValue(stacks, "DomainRef"));
|
||||
assertEquals("", outputValue(stacks, "CloudFront"),
|
||||
"a prefix domain has no distribution of its own, and must not resolve to the literal attribute name");
|
||||
|
||||
JsonNode description = describeDomain(PREFIX_DOMAIN);
|
||||
assertEquals(outputValue(stacks, "PoolId"), description.path("UserPoolId").asText());
|
||||
assertFalse(description.has("CloudFrontDistribution"));
|
||||
assertFalse(description.has("CustomDomainConfig"));
|
||||
|
||||
cloudFormation(PREFIX_STACK, "DeleteStack", null);
|
||||
awaitStackDeleted(PREFIX_STACK);
|
||||
|
||||
assertDomainIsGone(PREFIX_DOMAIN);
|
||||
}
|
||||
|
||||
private static void cloudFormation(String stack, String action, String templateBody) {
|
||||
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);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String stack, String expectedStatus) {
|
||||
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();
|
||||
}
|
||||
|
||||
/** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
|
||||
private static void awaitStackDeleted(String stack) throws InterruptedException {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
String body = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().extract().asString();
|
||||
if (body.contains("does not exist")) {
|
||||
return;
|
||||
}
|
||||
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
|
||||
fail("stack delete failed: " + body);
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("stack " + stack + " was not deleted within the timeout");
|
||||
}
|
||||
|
||||
private static JsonNode describeDomain(String domain) throws Exception {
|
||||
return cognitoJson("DescribeUserPoolDomain", "{\"Domain\": \"" + domain + "\"}").path("DomainDescription");
|
||||
}
|
||||
|
||||
private static void assertDomainIsGone(String domain) {
|
||||
cognitoAction("DescribeUserPoolDomain", "{\"Domain\": \"" + domain + "\"}")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
private static void assertCertificateStatus(String certificateArn, String status) {
|
||||
awsAction("CertificateManager", "DescribeCertificate", "{\"CertificateArn\": \"" + certificateArn + "\"}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Certificate.Status", equalTo(status));
|
||||
}
|
||||
|
||||
private static void assertCertificateIsGone(String certificateArn) {
|
||||
awsAction("CertificateManager", "DescribeCertificate", "{\"CertificateArn\": \"" + certificateArn + "\"}")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
private static String outputValue(String xml, String key) {
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
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.UserPoolDomain;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The Cognito CFN provisioner in isolation: one mocked service. Every case asserts the exact
|
||||
* physical id and the exact {@code Fn::GetAtt} attribute keys, since an unmapped type still
|
||||
* reports CREATE_COMPLETE through the dispatcher's stub arm.
|
||||
*/
|
||||
class CognitoCfnProvisionerTest {
|
||||
|
||||
private static final String TYPE = "AWS::Cognito::UserPoolDomain";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String POOL_ID = "us-east-1_AbCdEfGhI";
|
||||
private static final String DOMAIN = "auth.example.com";
|
||||
private static final String CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555";
|
||||
private static final String RENEWED_CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/99999999-2222-3333-4444-555555555555";
|
||||
private static final String CLOUDFRONT = "d1234567890abc.cloudfront.net";
|
||||
|
||||
private final CognitoService cognito = mock(CognitoService.class);
|
||||
private final CognitoCfnProvisioner provisioner = new CognitoCfnProvisioner(cognito);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
return ctx(null);
|
||||
}
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private static StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Domain");
|
||||
r.setResourceType(TYPE);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private static StackResource resource(String physicalId, Map<String, String> attributes) {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId(physicalId);
|
||||
r.setAttributes(new HashMap<>(attributes));
|
||||
return r;
|
||||
}
|
||||
|
||||
private static UserPoolDomain domain(String domain, String userPoolId, String cloudFront) {
|
||||
UserPoolDomain d = new UserPoolDomain();
|
||||
d.setDomain(domain);
|
||||
d.setUserPoolId(userPoolId);
|
||||
d.setCloudFrontDistribution(cloudFront);
|
||||
return d;
|
||||
}
|
||||
|
||||
private ObjectNode customDomainProps(String certificateArn) {
|
||||
ObjectNode props = mapper.createObjectNode()
|
||||
.put("Domain", DOMAIN)
|
||||
.put("UserPoolId", POOL_ID)
|
||||
.put("ManagedLoginVersion", 2);
|
||||
props.putObject("CustomDomainConfig").put("CertificateArn", certificateArn);
|
||||
return props;
|
||||
}
|
||||
|
||||
@Test
|
||||
void customDomainSetsDomainAsPhysicalIdAndCloudFrontAttribute() {
|
||||
when(cognito.createUserPoolDomain(DOMAIN, POOL_ID, Map.of("CertificateArn", CERTIFICATE_ARN), 2))
|
||||
.thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(CERTIFICATE_ARN), ctx());
|
||||
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
assertEquals(Map.of("UserPoolId", POOL_ID, "CloudFrontDistribution", CLOUDFRONT), r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void prefixDomainHasAnEmptyCloudFrontDistribution() {
|
||||
when(cognito.createUserPoolDomain(eq("my-prefix"), eq(POOL_ID), isNull(), isNull()))
|
||||
.thenReturn(domain("my-prefix", POOL_ID, null));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("Domain", "my-prefix").put("UserPoolId", POOL_ID), ctx());
|
||||
|
||||
assertEquals("my-prefix", r.getPhysicalId());
|
||||
assertEquals(Map.of("UserPoolId", POOL_ID, "CloudFrontDistribution", ""), r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void customDomainConfigPassesEveryFieldThrough() {
|
||||
when(cognito.createUserPoolDomain(any(), any(), any(), any())).thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
ObjectNode props = mapper.createObjectNode().put("Domain", DOMAIN).put("UserPoolId", POOL_ID);
|
||||
props.putObject("CustomDomainConfig")
|
||||
.put("CertificateArn", CERTIFICATE_ARN)
|
||||
.put("SecurityPolicy", "TLS_V1_2_2021");
|
||||
|
||||
provisioner.provision(resource(), props, ctx());
|
||||
|
||||
verify(cognito).createUserPoolDomain(DOMAIN, POOL_ID,
|
||||
Map.of("CertificateArn", CERTIFICATE_ARN, "SecurityPolicy", "TLS_V1_2_2021"), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void customDomainConfigSkipsNullValues() {
|
||||
// A JSON null must not reach the service as the text "null", where it would pass for an ARN.
|
||||
when(cognito.createUserPoolDomain(any(), any(), any(), any())).thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
ObjectNode props = mapper.createObjectNode().put("Domain", DOMAIN).put("UserPoolId", POOL_ID);
|
||||
props.putObject("CustomDomainConfig")
|
||||
.putNull("CertificateArn")
|
||||
.put("SecurityPolicy", "TLS_V1_2_2021");
|
||||
|
||||
provisioner.provision(resource(), props, ctx());
|
||||
|
||||
verify(cognito).createUserPoolDomain(DOMAIN, POOL_ID, Map.of("SecurityPolicy", "TLS_V1_2_2021"), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiresDomainAndUserPoolId() {
|
||||
assertThrows(IllegalArgumentException.class, () -> provisioner.provision(
|
||||
resource(), mapper.createObjectNode().put("UserPoolId", POOL_ID), ctx()));
|
||||
assertThrows(IllegalArgumentException.class, () -> provisioner.provision(
|
||||
resource(), mapper.createObjectNode().put("Domain", DOMAIN), ctx()));
|
||||
|
||||
verify(cognito, never()).createUserPoolDomain(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsANonIntegerManagedLoginVersion() {
|
||||
ObjectNode props = customDomainProps(CERTIFICATE_ARN).put("ManagedLoginVersion", "two");
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> provisioner.provision(resource(), props, ctx()));
|
||||
|
||||
verify(cognito, never()).createUserPoolDomain(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWithUnchangedDomainAndPoolUpdatesInPlace() {
|
||||
when(cognito.describeUserPoolDomain(DOMAIN)).thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
when(cognito.updateUserPoolDomain(DOMAIN, POOL_ID, Map.of("CertificateArn", RENEWED_CERTIFICATE_ARN), 2))
|
||||
.thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
StackResource r = resource(DOMAIN, Map.of("UserPoolId", POOL_ID, "CloudFrontDistribution", CLOUDFRONT));
|
||||
|
||||
provisioner.provision(r, customDomainProps(RENEWED_CERTIFICATE_ARN), ctx(DOMAIN));
|
||||
|
||||
verify(cognito, never()).createUserPoolDomain(any(), any(), any(), any());
|
||||
verify(cognito, never()).deleteUserPoolDomain(any(), any());
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
assertEquals(Map.of("UserPoolId", POOL_ID, "CloudFrontDistribution", CLOUDFRONT), r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWithChangedDomainReplacesTheDomain() {
|
||||
when(cognito.describeUserPoolDomain("old.example.com"))
|
||||
.thenReturn(domain("old.example.com", POOL_ID, "dold.cloudfront.net"));
|
||||
when(cognito.createUserPoolDomain(DOMAIN, POOL_ID, Map.of("CertificateArn", CERTIFICATE_ARN), 2))
|
||||
.thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
StackResource r = resource("old.example.com",
|
||||
Map.of("UserPoolId", POOL_ID, "CloudFrontDistribution", "dold.cloudfront.net"));
|
||||
|
||||
provisioner.provision(r, customDomainProps(CERTIFICATE_ARN), ctx("old.example.com"));
|
||||
|
||||
verify(cognito, never()).updateUserPoolDomain(any(), any(), any(), any());
|
||||
verify(cognito).deleteUserPoolDomain("old.example.com", POOL_ID);
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
assertEquals(Map.of("UserPoolId", POOL_ID, "CloudFrontDistribution", CLOUDFRONT), r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWithChangedUserPoolFailsWhileTheDomainNameIsTaken() {
|
||||
// CloudFormation creates the replacement before deleting the original, and domain names are
|
||||
// unique across pools, so moving an unchanged domain to another pool fails on AWS too. The
|
||||
// original is left untouched for the rollback.
|
||||
String otherPool = "us-east-1_ZzZzZzZzZ";
|
||||
when(cognito.describeUserPoolDomain(DOMAIN)).thenReturn(domain(DOMAIN, otherPool, CLOUDFRONT));
|
||||
when(cognito.createUserPoolDomain(DOMAIN, POOL_ID, Map.of("CertificateArn", CERTIFICATE_ARN), 2))
|
||||
.thenThrow(new AwsException("InvalidParameterException",
|
||||
"Domain " + DOMAIN + " already associated with another user pool", 400));
|
||||
StackResource r = resource(DOMAIN, Map.of("UserPoolId", otherPool, "CloudFrontDistribution", CLOUDFRONT));
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, customDomainProps(CERTIFICATE_ARN), ctx(DOMAIN)));
|
||||
|
||||
assertEquals("InvalidParameterException", failure.getErrorCode());
|
||||
verify(cognito, never()).updateUserPoolDomain(any(), any(), any(), any());
|
||||
verify(cognito, never()).deleteUserPoolDomain(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWhosePriorDomainIsGoneCreatesItAgain() {
|
||||
when(cognito.describeUserPoolDomain(DOMAIN))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "Domain does not exist", 404));
|
||||
when(cognito.createUserPoolDomain(DOMAIN, POOL_ID, Map.of("CertificateArn", CERTIFICATE_ARN), 2))
|
||||
.thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
StackResource r = resource(DOMAIN, Map.of("UserPoolId", POOL_ID, "CloudFrontDistribution", CLOUDFRONT));
|
||||
|
||||
provisioner.provision(r, customDomainProps(CERTIFICATE_ARN), ctx(DOMAIN));
|
||||
|
||||
verify(cognito, never()).updateUserPoolDomain(any(), any(), any(), any());
|
||||
verify(cognito, never()).deleteUserPoolDomain(any(), any());
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementToleratesAPriorDomainThatIsAlreadyGone() {
|
||||
when(cognito.describeUserPoolDomain("old.example.com"))
|
||||
.thenReturn(domain("old.example.com", POOL_ID, "dold.cloudfront.net"));
|
||||
when(cognito.createUserPoolDomain(any(), any(), any(), any())).thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
doThrow(new AwsException("ResourceNotFoundException", "Domain does not exist", 404))
|
||||
.when(cognito).deleteUserPoolDomain("old.example.com", POOL_ID);
|
||||
StackResource r = resource("old.example.com", Map.of("UserPoolId", POOL_ID));
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.provision(r, customDomainProps(CERTIFICATE_ARN), ctx("old.example.com")));
|
||||
assertEquals(DOMAIN, r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteUsesTheRecordedUserPoolId() {
|
||||
provisioner.delete(resource(DOMAIN, Map.of("UserPoolId", POOL_ID, "CloudFrontDistribution", CLOUDFRONT)), REGION);
|
||||
|
||||
verify(cognito).deleteUserPoolDomain(DOMAIN, POOL_ID);
|
||||
verify(cognito, never()).describeUserPoolDomain(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesAnAlreadyDeletedDomain() {
|
||||
doThrow(new AwsException("ResourceNotFoundException", "Domain does not exist", 404))
|
||||
.when(cognito).deleteUserPoolDomain(DOMAIN, POOL_ID);
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(resource(DOMAIN, Map.of("UserPoolId", POOL_ID)), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePropagatesOtherFailures() {
|
||||
doThrow(new AwsException("InvalidParameterException", "Domain is required", 400))
|
||||
.when(cognito).deleteUserPoolDomain(DOMAIN, POOL_ID);
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(resource(DOMAIN, Map.of("UserPoolId", POOL_ID)), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWithoutARecordedUserPoolIdLooksTheDomainUp() {
|
||||
when(cognito.describeUserPoolDomain(DOMAIN)).thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
|
||||
provisioner.delete(resource(DOMAIN, Map.of()), REGION);
|
||||
|
||||
verify(cognito).deleteUserPoolDomain(DOMAIN, POOL_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWithoutARecordedUserPoolIdOfAMissingDomainIsANoOp() {
|
||||
when(cognito.describeUserPoolDomain(DOMAIN))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "Domain does not exist", 404));
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(resource(DOMAIN, Map.of()), REGION));
|
||||
verify(cognito, never()).deleteUserPoolDomain(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteByIdAloneLooksTheDomainUp() {
|
||||
when(cognito.describeUserPoolDomain(DOMAIN)).thenReturn(domain(DOMAIN, POOL_ID, CLOUDFRONT));
|
||||
|
||||
provisioner.delete(TYPE, DOMAIN, REGION);
|
||||
|
||||
verify(cognito).deleteUserPoolDomain(DOMAIN, POOL_ID);
|
||||
}
|
||||
}
|
||||
@@ -492,4 +492,46 @@ class CognitoJsonHandlerTest {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private String createPoolWithPrefixDomain(String domain) {
|
||||
ObjectNode poolReq = mapper.createObjectNode().put("PoolName", "domain-pool");
|
||||
String poolId = ((JsonNode) handler.handle("CreateUserPool", poolReq, "us-east-1").getEntity())
|
||||
.get("UserPool").get("Id").asText();
|
||||
ObjectNode domainReq = mapper.createObjectNode()
|
||||
.put("Domain", domain)
|
||||
.put("UserPoolId", poolId)
|
||||
.put("ManagedLoginVersion", 1);
|
||||
handler.handle("CreateUserPoolDomain", domainReq, "us-east-1");
|
||||
return poolId;
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainTreatsANullManagedLoginVersionAsAbsent() {
|
||||
String poolId = createPoolWithPrefixDomain("null-version");
|
||||
ObjectNode updateReq = mapper.createObjectNode().put("Domain", "null-version").put("UserPoolId", poolId);
|
||||
updateReq.putNull("ManagedLoginVersion");
|
||||
|
||||
JsonNode updated = (JsonNode) handler.handle("UpdateUserPoolDomain", updateReq, "us-east-1").getEntity();
|
||||
|
||||
assertEquals(1, updated.get("ManagedLoginVersion").asInt());
|
||||
JsonNode described = (JsonNode) handler.handle("DescribeUserPoolDomain",
|
||||
mapper.createObjectNode().put("Domain", "null-version"), "us-east-1").getEntity();
|
||||
assertEquals(1, described.get("DomainDescription").get("ManagedLoginVersion").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userPoolDomainRejectsAManagedLoginVersionThatIsNotAnInteger() {
|
||||
String poolId = createPoolWithPrefixDomain("typed-version");
|
||||
ObjectNode updateReq = mapper.createObjectNode()
|
||||
.put("Domain", "typed-version")
|
||||
.put("UserPoolId", poolId)
|
||||
.put("ManagedLoginVersion", "two");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateUserPoolDomain", updateReq, "us-east-1"));
|
||||
|
||||
assertEquals("SerializationException", failure.getErrorCode());
|
||||
JsonNode described = (JsonNode) handler.handle("DescribeUserPoolDomain",
|
||||
mapper.createObjectNode().put("Domain", "typed-version"), "us-east-1").getEntity();
|
||||
assertEquals(1, described.get("DomainDescription").get("ManagedLoginVersion").asInt());
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
|
||||
import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
|
||||
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
|
||||
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
|
||||
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
|
||||
@@ -3255,6 +3256,129 @@ class CognitoServiceTest {
|
||||
assertFalse(user.getEmailMfaSettings().isEnabled());
|
||||
assertFalse(user.getEmailMfaSettings().isPreferredMfa());
|
||||
}
|
||||
// ──────────────────────────── User Pool Domains ────────────────────────────
|
||||
|
||||
private static final String CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555";
|
||||
private static final String RENEWED_CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/99999999-2222-3333-4444-555555555555";
|
||||
|
||||
private UserPool createPoolWithCustomDomain(String domain) {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");
|
||||
service.createUserPoolDomain(domain, pool.getId(), Map.of("CertificateArn", CERTIFICATE_ARN), 1);
|
||||
return pool;
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainReplacesTheCertificateAndKeepsTheCloudFrontDistribution() {
|
||||
UserPool pool = createPoolWithCustomDomain("auth.example.com");
|
||||
String cloudFront = service.describeUserPoolDomain("auth.example.com").getCloudFrontDistribution();
|
||||
|
||||
UserPoolDomain updated = service.updateUserPoolDomain("auth.example.com", pool.getId(),
|
||||
Map.of("CertificateArn", RENEWED_CERTIFICATE_ARN), 2);
|
||||
|
||||
assertEquals(RENEWED_CERTIFICATE_ARN, updated.getCertificateArn());
|
||||
assertEquals(cloudFront, updated.getCloudFrontDistribution());
|
||||
assertEquals(2, updated.getManagedLoginVersion());
|
||||
UserPoolDomain stored = service.describeUserPoolDomain("auth.example.com");
|
||||
assertEquals(RENEWED_CERTIFICATE_ARN, stored.getCertificateArn());
|
||||
assertEquals(2, stored.getManagedLoginVersion());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainLeavesOmittedSettingsUnchanged() {
|
||||
UserPool pool = createPoolWithCustomDomain("auth.example.com");
|
||||
|
||||
service.updateUserPoolDomain("auth.example.com", pool.getId(), null, null);
|
||||
|
||||
UserPoolDomain stored = service.describeUserPoolDomain("auth.example.com");
|
||||
assertEquals(CERTIFICATE_ARN, stored.getCertificateArn());
|
||||
assertEquals(1, stored.getManagedLoginVersion());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainSetsTheManagedLoginVersionOfAPrefixDomain() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");
|
||||
service.createUserPoolDomain("my-prefix", pool.getId(), null, null);
|
||||
|
||||
UserPoolDomain updated = service.updateUserPoolDomain("my-prefix", pool.getId(), null, 2);
|
||||
|
||||
assertEquals(2, updated.getManagedLoginVersion());
|
||||
assertFalse(updated.isCustomDomain());
|
||||
assertNull(updated.getCloudFrontDistribution());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainRejectsACustomDomainConfigOnAPrefixDomain() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");
|
||||
service.createUserPoolDomain("my-prefix", pool.getId(), null, null);
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> service.updateUserPoolDomain(
|
||||
"my-prefix", pool.getId(), Map.of("CertificateArn", CERTIFICATE_ARN), null));
|
||||
|
||||
assertEquals("InvalidParameterException", failure.getErrorCode());
|
||||
assertFalse(service.describeUserPoolDomain("my-prefix").isCustomDomain());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainRequiresACertificateArnInTheCustomDomainConfig() {
|
||||
UserPool pool = createPoolWithCustomDomain("auth.example.com");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> service.updateUserPoolDomain(
|
||||
"auth.example.com", pool.getId(), Map.of(), 2));
|
||||
|
||||
assertEquals("InvalidParameterException", failure.getErrorCode());
|
||||
assertEquals(CERTIFICATE_ARN, service.describeUserPoolDomain("auth.example.com").getCertificateArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainOfAnotherPoolsDomainIsNotFound() {
|
||||
createPoolWithCustomDomain("auth.example.com");
|
||||
UserPool otherPool = service.createUserPool(Map.of("PoolName", "OtherPool"), "us-east-1");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> service.updateUserPoolDomain(
|
||||
"auth.example.com", otherPool.getId(), Map.of("CertificateArn", RENEWED_CERTIFICATE_ARN), null));
|
||||
|
||||
assertEquals("ResourceNotFoundException", failure.getErrorCode());
|
||||
assertEquals(CERTIFICATE_ARN, service.describeUserPoolDomain("auth.example.com").getCertificateArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainOfAnUnknownDomainIsNotFound() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> service.updateUserPoolDomain(
|
||||
"nobody.example.com", pool.getId(), Map.of("CertificateArn", CERTIFICATE_ARN), null));
|
||||
|
||||
assertEquals("ResourceNotFoundException", failure.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainReplacesTheSecurityPolicyAndKeepsItWhenOmitted() {
|
||||
UserPool pool = createPoolWithCustomDomain("auth.example.com");
|
||||
assertEquals("TLS_V1_2_2021", service.describeUserPoolDomain("auth.example.com").getSecurityPolicy());
|
||||
|
||||
service.updateUserPoolDomain("auth.example.com", pool.getId(),
|
||||
Map.of("CertificateArn", RENEWED_CERTIFICATE_ARN, "SecurityPolicy", "TLS_V1_2_2019"), null);
|
||||
assertEquals("TLS_V1_2_2019", service.describeUserPoolDomain("auth.example.com").getSecurityPolicy());
|
||||
|
||||
service.updateUserPoolDomain("auth.example.com", pool.getId(), Map.of("CertificateArn", CERTIFICATE_ARN), null);
|
||||
|
||||
UserPoolDomain stored = service.describeUserPoolDomain("auth.example.com");
|
||||
assertEquals("TLS_V1_2_2019", stored.getSecurityPolicy());
|
||||
assertEquals(CERTIFICATE_ARN, stored.getCertificateArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserPoolDomainOfAnUnknownPoolIsNotFound() {
|
||||
createPoolWithCustomDomain("auth.example.com");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> service.updateUserPoolDomain(
|
||||
"auth.example.com", "us-east-1_missing", Map.of("CertificateArn", CERTIFICATE_ARN), null));
|
||||
|
||||
assertEquals("ResourceNotFoundException", failure.getErrorCode());
|
||||
}
|
||||
|
||||
private static String jwtPayload(String token) {
|
||||
String segment = token.split("\\.")[1];
|
||||
int pad = (4 - segment.length() % 4) % 4;
|
||||
|
||||
+56
-4
@@ -18,7 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* Covers CreateUserPoolDomain/DescribeUserPoolDomain/DeleteUserPoolDomain (lex00/floci#63)
|
||||
* Covers CreateUserPoolDomain/DescribeUserPoolDomain/UpdateUserPoolDomain/DeleteUserPoolDomain (lex00/floci#63)
|
||||
* for both an Amazon Cognito prefix domain and a custom domain fronted by an ACM certificate.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@@ -30,6 +30,8 @@ class CognitoUserPoolDomainIntegrationTest {
|
||||
private static String customDomain;
|
||||
private static final String CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/" + UUID.randomUUID();
|
||||
private static final String RENEWED_CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/" + UUID.randomUUID();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
@@ -142,6 +144,56 @@ class CognitoUserPoolDomainIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void updateCustomDomainReplacesTheCertificateAndKeepsTheCloudFrontDistribution() throws Exception {
|
||||
String cloudFront = cognitoJson("DescribeUserPoolDomain", """
|
||||
{
|
||||
"Domain": "%s"
|
||||
}
|
||||
""".formatted(customDomain)).path("DomainDescription").path("CloudFrontDistribution").asText();
|
||||
|
||||
JsonNode response = cognitoJson("UpdateUserPoolDomain", """
|
||||
{
|
||||
"Domain": "%s",
|
||||
"UserPoolId": "%s",
|
||||
"CustomDomainConfig": {
|
||||
"CertificateArn": "%s"
|
||||
},
|
||||
"ManagedLoginVersion": 2
|
||||
}
|
||||
""".formatted(customDomain, poolId, RENEWED_CERTIFICATE_ARN));
|
||||
|
||||
// As on AWS, the distribution survives a certificate change, so a DNS alias stays valid.
|
||||
assertEquals(cloudFront, response.path("CloudFrontDomain").asText());
|
||||
assertEquals(2, response.path("ManagedLoginVersion").asInt());
|
||||
|
||||
JsonNode description = cognitoJson("DescribeUserPoolDomain", """
|
||||
{
|
||||
"Domain": "%s"
|
||||
}
|
||||
""".formatted(customDomain)).path("DomainDescription");
|
||||
assertEquals(RENEWED_CERTIFICATE_ARN, description.path("CustomDomainConfig").path("CertificateArn").asText());
|
||||
assertEquals(cloudFront, description.path("CloudFrontDistribution").asText());
|
||||
assertEquals(2, description.path("ManagedLoginVersion").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void updateDomainOfAnotherPoolIsNotFound() {
|
||||
cognitoAction("UpdateUserPoolDomain", """
|
||||
{
|
||||
"Domain": "%s",
|
||||
"UserPoolId": "us-east-1_missing",
|
||||
"CustomDomainConfig": {
|
||||
"CertificateArn": "%s"
|
||||
}
|
||||
}
|
||||
""".formatted(customDomain, CERTIFICATE_ARN))
|
||||
.then()
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void createCustomDomainWithoutCertificateArnFails() {
|
||||
cognitoAction("CreateUserPoolDomain", """
|
||||
{
|
||||
@@ -156,7 +208,7 @@ class CognitoUserPoolDomainIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
@Order(11)
|
||||
void deleteCustomDomainThenDescribeIsNotFound() {
|
||||
cognitoAction("DeleteUserPoolDomain", """
|
||||
{
|
||||
@@ -178,7 +230,7 @@ class CognitoUserPoolDomainIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
@Order(12)
|
||||
void deleteUserPoolWithDomainIsRejected() throws Exception {
|
||||
// The DeleteUserPool API reference's own example documents this refusal verbatim.
|
||||
String blockingDomain = "floci-block-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
@@ -211,7 +263,7 @@ class CognitoUserPoolDomainIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
@Order(13)
|
||||
void deleteUserPoolSucceedsOnceDomainIsGone() {
|
||||
cognitoAction("DeleteUserPool", """
|
||||
{
|
||||
|
||||
@@ -28,6 +28,7 @@ AWS::CodePipeline::Pipeline CodePipelineCfnProvisioner
|
||||
AWS::CodePipeline::Webhook CodePipelineCfnProvisioner
|
||||
AWS::Cognito::UserPool LEGACY_SWITCH
|
||||
AWS::Cognito::UserPoolClient LEGACY_SWITCH
|
||||
AWS::Cognito::UserPoolDomain CognitoCfnProvisioner
|
||||
AWS::Config::ConfigRule ConfigCfnProvisioner
|
||||
AWS::DynamoDB::GlobalTable LEGACY_SWITCH
|
||||
AWS::DynamoDB::Table LEGACY_SWITCH
|
||||
|
||||
|
Reference in new issue
Block a user