feat(cognito): user pool domain operations (Create/Describe/DeleteUserPoolDomain) (#2742)

* feat(cognito): user pool domain operations (Create/Describe/DeleteUserPoolDomain)

Adds the domain family Cognito was missing, which blocks any estate using
aws_cognito_user_pool_domain (e.g. an ALB authenticate-cognito listener).
Supports both an Amazon Cognito prefix domain and a custom domain backed by
an ACM certificate ARN, matching the documented request and response shapes.
Domain names are globally unique across pools; a missing domain reports
ResourceNotFoundException on Describe/Delete, consistent with the rest of
the Cognito handler's not-found behavior.

* fix(cognito): refuse DeleteUserPool while a domain is configured

The DeleteUserPool API reference documents this refusal: a pool with a
hosted UI or custom domain answers InvalidParameterException ("User pool
cannot be deleted. It has a domain configured that should be deleted
first.") rather than deleting and stranding the globally-unique domain
name.
This commit is contained in:
lex00 authored and GitHub committed 2026-08-29 23:58:59 -04:00
1 parent fcc606799c
commit ed167135ff
6 files changed
+458 -1

No files matched your search

+8
View File
@@ -55,6 +55,14 @@ Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource`
| ListResourceServers | Lists resource servers for a user pool. |
| DeleteResourceServer | Deletes a resource server from a user pool. |
### User Pool Domains
| Action | Description |
|--------|-------------|
| 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. |
| DeleteUserPoolDomain | Deletes a domain from its user pool. |
### Admin User Management
| Action | Description |
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope;
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.UserPoolClientSecret;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@@ -57,6 +58,9 @@ public class CognitoJsonHandler {
case "ListResourceServers" -> handleListResourceServers(request);
case "UpdateResourceServer" -> handleUpdateResourceServer(request);
case "DeleteResourceServer" -> handleDeleteResourceServer(request);
case "CreateUserPoolDomain" -> handleCreateUserPoolDomain(request);
case "DescribeUserPoolDomain" -> handleDescribeUserPoolDomain(request);
case "DeleteUserPoolDomain" -> handleDeleteUserPoolDomain(request);
case "AdminResetUserPassword" -> handleAdminResetUserPassword(request);
case "AdminCreateUser" -> handleAdminCreateUser(request);
case "AdminGetUser" -> handleAdminGetUser(request);
@@ -341,6 +345,64 @@ public class CognitoJsonHandler {
return Response.ok(objectMapper.createObjectNode()).build();
}
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
);
ObjectNode response = objectMapper.createObjectNode();
if (domain.isCustomDomain()) {
response.put("CloudFrontDomain", domain.getCloudFrontDistribution());
}
if (domain.getManagedLoginVersion() != null) {
response.put("ManagedLoginVersion", domain.getManagedLoginVersion());
}
return Response.ok(response).build();
}
private Response handleDescribeUserPoolDomain(JsonNode request) {
UserPoolDomain domain = service.describeUserPoolDomain(request.path("Domain").asText());
ObjectNode response = objectMapper.createObjectNode();
response.set("DomainDescription", userPoolDomainToNode(domain));
return Response.ok(response).build();
}
private Response handleDeleteUserPoolDomain(JsonNode request) {
service.deleteUserPoolDomain(
request.path("Domain").asText(),
request.path("UserPoolId").asText()
);
return Response.ok(objectMapper.createObjectNode()).build();
}
private ObjectNode userPoolDomainToNode(UserPoolDomain d) {
ObjectNode node = objectMapper.createObjectNode();
node.put("AWSAccountId", d.getAwsAccountId());
if (d.getCloudFrontDistribution() != null) {
node.put("CloudFrontDistribution", d.getCloudFrontDistribution());
}
if (d.isCustomDomain()) {
ObjectNode customDomainConfig = node.putObject("CustomDomainConfig");
customDomainConfig.put("CertificateArn", d.getCertificateArn());
customDomainConfig.put("SecurityPolicy", d.getSecurityPolicy());
}
node.put("Domain", d.getDomain());
if (d.getManagedLoginVersion() != null) {
node.put("ManagedLoginVersion", d.getManagedLoginVersion());
}
node.put("S3Bucket", d.getS3Bucket());
node.put("Status", d.getStatus());
node.put("UserPoolId", d.getUserPoolId());
node.put("Version", d.getVersion());
return node;
}
private Response handleAdminCreateUser(JsonNode request) {
Map<String, String> attrs = new HashMap<>();
request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText()));
@@ -732,6 +794,11 @@ public class CognitoJsonHandler {
return node;
}
@SuppressWarnings("unchecked")
private ObjectNode clientToDescriptionNode(UserPoolClient c) {
ObjectNode node = objectMapper.createObjectNode();
node.put("ClientId", c.getClientId());
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
@@ -23,6 +24,7 @@ import io.github.hectorvent.floci.services.cognito.model.RevokedTokenInfo;
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.UserPoolClientSecret;
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.VerificationCodeException;
@@ -105,6 +107,7 @@ public class CognitoService implements ResourceProvider {
private final StorageBackend<String, UserPool> poolStore;
private final StorageBackend<String, UserPoolClient> clientStore;
private final StorageBackend<String, ResourceServer> resourceServerStore;
private final StorageBackend<String, UserPoolDomain> domainStore;
private final StorageBackend<String, CognitoUser> userStore;
private final StorageBackend<String, CognitoGroup> groupStore;
private final StorageBackend<String, RevokedTokenInfo> revokedTokenStore;
@@ -128,6 +131,8 @@ public class CognitoService implements ResourceProvider {
new TypeReference<Map<String, UserPoolClient>>() {}),
storageFactory.create("cognito", "cognito-resource-servers.json",
new TypeReference<Map<String, ResourceServer>>() {}),
storageFactory.create("cognito", "cognito-domains.json",
new TypeReference<Map<String, UserPoolDomain>>() {}),
storageFactory.create("cognito", "cognito-users.json",
new TypeReference<Map<String, CognitoUser>>() {}),
storageFactory.create("cognito", "cognito-groups.json",
@@ -151,13 +156,15 @@ public class CognitoService implements ResourceProvider {
String baseUrl,
RegionResolver regionResolver,
LambdaService lambdaService) {
this(poolStore, clientStore, resourceServerStore, userStore, groupStore, revokedTokenStore, baseUrl,
this(poolStore, clientStore, resourceServerStore, new InMemoryStorage<>(),
userStore, groupStore, revokedTokenStore, baseUrl,
regionResolver, lambdaService, null, null);
}
CognitoService(StorageBackend<String, UserPool> poolStore,
StorageBackend<String, UserPoolClient> clientStore,
StorageBackend<String, ResourceServer> resourceServerStore,
StorageBackend<String, UserPoolDomain> domainStore,
StorageBackend<String, CognitoUser> userStore,
StorageBackend<String, CognitoGroup> groupStore,
StorageBackend<String, RevokedTokenInfo> revokedTokenStore,
@@ -168,6 +175,7 @@ public class CognitoService implements ResourceProvider {
this.poolStore = poolStore;
this.clientStore = clientStore;
this.resourceServerStore = resourceServerStore;
this.domainStore = domainStore;
this.userStore = userStore;
this.groupStore = groupStore;
this.revokedTokenStore = revokedTokenStore;
@@ -401,6 +409,14 @@ public class CognitoService implements ResourceProvider {
}
public void deleteUserPool(String id) {
// AWS refuses to delete a pool that still has a hosted UI / custom domain; the
// DeleteUserPool API reference documents this exact InvalidParameterException.
boolean hasDomain = domainStore.scan(k -> true).stream()
.anyMatch(d -> id.equals(d.getUserPoolId()));
if (hasDomain) {
throw new AwsException("InvalidParameterException",
"User pool cannot be deleted. It has a domain configured that should be deleted first.", 400);
}
String prefix = id + "::";
groupStore.scan(k -> k.startsWith(prefix))
.forEach(g -> groupStore.delete(groupKey(id, g.getGroupName())));
@@ -821,6 +837,77 @@ public class CognitoService implements ResourceProvider {
resourceServerStore.delete(resourceServerKey(userPoolId, identifier));
}
// ──────────────────────────── User Pool Domains ────────────────────────────
/**
* Creates either an Amazon Cognito prefix domain ({@code customDomainConfig == null})
* or a custom domain fronted by an ACM certificate. Domain names are globally unique
* across pools, matching AWS's shared namespace for hosted UI/managed login domains.
*/
public UserPoolDomain createUserPoolDomain(String domain, String userPoolId,
Map<String, Object> customDomainConfig, Integer managedLoginVersion) {
describeUserPool(userPoolId);
if (domain == null || domain.isBlank()) {
throw new AwsException("InvalidParameterException", "Domain is required", 400);
}
if (domainStore.get(domain).isPresent()) {
throw new AwsException("InvalidParameterException",
"Domain " + domain + " already associated with another user pool", 400);
}
UserPoolDomain userPoolDomain = new UserPoolDomain();
userPoolDomain.setDomain(domain);
userPoolDomain.setUserPoolId(userPoolId);
userPoolDomain.setAwsAccountId(regionResolver.getAccountId());
userPoolDomain.setManagedLoginVersion(managedLoginVersion);
userPoolDomain.setStatus("ACTIVE");
userPoolDomain.setVersion(generateDomainVersion());
userPoolDomain.setS3Bucket("aws-cognito-prod-" + regionResolver.getRegion() + "-assets");
if (customDomainConfig != null) {
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");
userPoolDomain.setSecurityPolicy(securityPolicy != null ? securityPolicy.toString() : "TLS_V1_2_2021");
userPoolDomain.setCloudFrontDistribution(generateCloudFrontDomain());
}
domainStore.put(domain, userPoolDomain);
LOG.infov("Created User Pool Domain: {0} for pool {1}", domain, userPoolId);
return userPoolDomain;
}
public UserPoolDomain describeUserPoolDomain(String domain) {
if (domain == null || domain.isBlank()) {
throw new AwsException("InvalidParameterException", "Domain is required", 400);
}
return domainStore.get(domain)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Domain does not exist", 404));
}
public void deleteUserPoolDomain(String domain, String userPoolId) {
UserPoolDomain userPoolDomain = describeUserPoolDomain(domain);
if (!userPoolDomain.getUserPoolId().equals(userPoolId)) {
throw new AwsException("ResourceNotFoundException", "Domain does not exist", 404);
}
domainStore.delete(domain);
LOG.infov("Deleted User Pool Domain: {0} for pool {1}", domain, userPoolId);
}
private String generateCloudFrontDomain() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 14) + ".cloudfront.net";
}
private String generateDomainVersion() {
return java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
.withZone(java.time.ZoneOffset.UTC)
.format(java.time.Instant.now());
}
// ──────────────────────────── Users ────────────────────────────
public CognitoUser adminCreateUser(String userPoolId, String username, Map<String, String> attributes,
@@ -0,0 +1,68 @@
package io.github.hectorvent.floci.services.cognito.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserPoolDomain {
private String domain;
private String userPoolId;
private String awsAccountId;
private String status = "ACTIVE";
private String version;
private String s3Bucket;
private String cloudFrontDistribution;
private Integer managedLoginVersion;
// Custom-domain-only fields (null for an Amazon Cognito prefix domain).
private String certificateArn;
private String securityPolicy;
private long creationDate;
private long lastModifiedDate;
public UserPoolDomain() {
long now = System.currentTimeMillis() / 1000L;
this.creationDate = now;
this.lastModifiedDate = now;
}
public String getDomain() { return domain; }
public void setDomain(String domain) { this.domain = domain; }
public String getUserPoolId() { return userPoolId; }
public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; }
public String getAwsAccountId() { return awsAccountId; }
public void setAwsAccountId(String awsAccountId) { this.awsAccountId = awsAccountId; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
public String getS3Bucket() { return s3Bucket; }
public void setS3Bucket(String s3Bucket) { this.s3Bucket = s3Bucket; }
public String getCloudFrontDistribution() { return cloudFrontDistribution; }
public void setCloudFrontDistribution(String cloudFrontDistribution) { this.cloudFrontDistribution = cloudFrontDistribution; }
public Integer getManagedLoginVersion() { return managedLoginVersion; }
public void setManagedLoginVersion(Integer managedLoginVersion) { this.managedLoginVersion = managedLoginVersion; }
public String getCertificateArn() { return certificateArn; }
public void setCertificateArn(String certificateArn) { this.certificateArn = certificateArn; }
public String getSecurityPolicy() { return securityPolicy; }
public void setSecurityPolicy(String securityPolicy) { this.securityPolicy = securityPolicy; }
public boolean isCustomDomain() { return certificateArn != null; }
public long getCreationDate() { return creationDate; }
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
public long getLastModifiedDate() { return lastModifiedDate; }
public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }
}
@@ -1212,6 +1212,7 @@ class CognitoServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
@@ -1249,6 +1250,7 @@ class CognitoServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
@@ -2640,6 +2642,7 @@ class CognitoServiceTest {
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
@@ -0,0 +1,224 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.UUID;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Covers CreateUserPoolDomain/DescribeUserPoolDomain/DeleteUserPoolDomain (lex00/floci#63)
* for both an Amazon Cognito prefix domain and a custom domain fronted by an ACM certificate.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CognitoUserPoolDomainIntegrationTest {
private static String poolId;
private static String prefixDomain;
private static String customDomain;
private static final String CERTIFICATE_ARN =
"arn:aws:acm:us-east-1:000000000000:certificate/" + UUID.randomUUID();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createPool() throws Exception {
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
"PoolName": "DomainTestPool"
}
""");
poolId = poolResponse.path("UserPool").path("Id").asText();
prefixDomain = "floci-test-" + UUID.randomUUID().toString().substring(0, 8);
customDomain = "auth-" + UUID.randomUUID().toString().substring(0, 8) + ".example.com";
}
@Test
@Order(2)
void createPrefixDomainSucceeds() throws Exception {
JsonNode response = cognitoJson("CreateUserPoolDomain", """
{
"Domain": "%s",
"UserPoolId": "%s"
}
""".formatted(prefixDomain, poolId));
// AWS returns CloudFrontDomain=null for a prefix domain; floci should not
// fabricate one, so the field is simply absent from the response.
assertNull(response.get("CloudFrontDomain"));
}
@Test
@Order(3)
void describePrefixDomainReturnsMatchingFields() throws Exception {
JsonNode response = cognitoJson("DescribeUserPoolDomain", """
{
"Domain": "%s"
}
""".formatted(prefixDomain));
JsonNode description = response.path("DomainDescription");
assertEquals(prefixDomain, description.path("Domain").asText());
assertEquals(poolId, description.path("UserPoolId").asText());
assertEquals("ACTIVE", description.path("Status").asText());
assertNull(description.get("CustomDomainConfig"));
}
@Test
@Order(4)
void deletePrefixDomainSucceeds() {
cognitoAction("DeleteUserPoolDomain", """
{
"Domain": "%s",
"UserPoolId": "%s"
}
""".formatted(prefixDomain, poolId))
.then()
.statusCode(200);
}
@Test
@Order(5)
void describeDeletedPrefixDomainIsNotFound() {
cognitoAction("DescribeUserPoolDomain", """
{
"Domain": "%s"
}
""".formatted(prefixDomain))
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
@Order(6)
void createCustomDomainReturnsCloudFrontDomain() throws Exception {
JsonNode response = cognitoJson("CreateUserPoolDomain", """
{
"Domain": "%s",
"UserPoolId": "%s",
"CustomDomainConfig": {
"CertificateArn": "%s"
}
}
""".formatted(customDomain, poolId, CERTIFICATE_ARN));
org.junit.jupiter.api.Assertions.assertTrue(response.path("CloudFrontDomain").isTextual());
org.junit.jupiter.api.Assertions.assertFalse(response.path("CloudFrontDomain").asText().isBlank());
}
@Test
@Order(7)
void describeCustomDomainReturnsCertificateArn() throws Exception {
JsonNode response = cognitoJson("DescribeUserPoolDomain", """
{
"Domain": "%s"
}
""".formatted(customDomain));
JsonNode description = response.path("DomainDescription");
assertEquals(customDomain, description.path("Domain").asText());
assertEquals(poolId, description.path("UserPoolId").asText());
assertEquals(CERTIFICATE_ARN, description.path("CustomDomainConfig").path("CertificateArn").asText());
assertEquals("ACTIVE", description.path("Status").asText());
org.junit.jupiter.api.Assertions.assertNotNull(description.path("CloudFrontDistribution").asText(null));
}
@Test
@Order(8)
void createCustomDomainWithoutCertificateArnFails() {
cognitoAction("CreateUserPoolDomain", """
{
"Domain": "%s",
"UserPoolId": "%s",
"CustomDomainConfig": {}
}
""".formatted("bad-" + UUID.randomUUID().toString().substring(0, 8) + ".example.com", poolId))
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"));
}
@Test
@Order(9)
void deleteCustomDomainThenDescribeIsNotFound() {
cognitoAction("DeleteUserPoolDomain", """
{
"Domain": "%s",
"UserPoolId": "%s"
}
""".formatted(customDomain, poolId))
.then()
.statusCode(200);
cognitoAction("DescribeUserPoolDomain", """
{
"Domain": "%s"
}
""".formatted(customDomain))
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
@Order(10)
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);
cognitoJson("CreateUserPoolDomain", """
{
"Domain": "%s",
"UserPoolId": "%s"
}
""".formatted(blockingDomain, poolId));
cognitoAction("DeleteUserPool", """
{
"UserPoolId": "%s"
}
""".formatted(poolId))
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"))
.body("message", equalTo(
"User pool cannot be deleted. It has a domain configured that should be deleted first."));
cognitoAction("DeleteUserPoolDomain", """
{
"Domain": "%s",
"UserPoolId": "%s"
}
""".formatted(blockingDomain, poolId))
.then()
.statusCode(200);
}
@Test
@Order(11)
void deleteUserPoolSucceedsOnceDomainIsGone() {
cognitoAction("DeleteUserPool", """
{
"UserPoolId": "%s"
}
""".formatted(poolId))
.then()
.statusCode(200);
}
}