diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 83e1873ab7..7af43da1ce 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -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 | diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java index 9d8b718013..9122667460 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java @@ -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 customDomainConfig = customDomainConfigNode.isObject() + ? objectMapper.convertValue(customDomainConfigNode, new TypeReference>() {}) + : 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 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()); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 3f9c06865f..71603111a5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -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 poolStore; private final StorageBackend clientStore; private final StorageBackend resourceServerStore; + private final StorageBackend domainStore; private final StorageBackend userStore; private final StorageBackend groupStore; private final StorageBackend revokedTokenStore; @@ -128,6 +131,8 @@ public class CognitoService implements ResourceProvider { new TypeReference>() {}), storageFactory.create("cognito", "cognito-resource-servers.json", new TypeReference>() {}), + storageFactory.create("cognito", "cognito-domains.json", + new TypeReference>() {}), storageFactory.create("cognito", "cognito-users.json", new TypeReference>() {}), 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 poolStore, StorageBackend clientStore, StorageBackend resourceServerStore, + StorageBackend domainStore, StorageBackend userStore, StorageBackend groupStore, StorageBackend 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 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 attributes, diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolDomain.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolDomain.java new file mode 100644 index 0000000000..19f9f5df75 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/UserPoolDomain.java @@ -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; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index bb86ab5ea2..df6ac368e6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -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, diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserPoolDomainIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserPoolDomainIntegrationTest.java new file mode 100644 index 0000000000..696caa8188 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserPoolDomainIntegrationTest.java @@ -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); + } +}