Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): check the custom domain certificate in ACM and mark it in use (#3035)
Mario Toffiad771783afb47
diff --git a/docs/services/acm.md b/docs/services/acm.mdindex 5e279df653..64e0e9c063 100644--- a/docs/services/acm.md+++ b/docs/services/acm.md@@ -33,6 +33,7 @@- **Key Algorithms:** Supports `RSA_2048`, `RSA_3072`, `RSA_4096`, `EC_prime256v1`, `EC_secp384r1`, `EC_secp521r1`- **Certificate Types:** `AMAZON_ISSUED` (default) and `PRIVATE` (when `CertificateAuthorityArn` is provided)- **Export:** Only `PRIVATE` type certificates can be exported with their private key+- **In use:** `DescribeCertificate` lists under `InUseBy` the CloudFront distribution of each Cognito custom domain that uses the certificate, and `DeleteCertificate` refuses with `ResourceInUseException` while that list is not empty. Other consumers, such as load balancers and API Gateway domain names, are not tracked yet.## Configurationdiff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex 4a68b913c3..24ad1d36b1 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -96,9 +96,9 @@ always returns it.| Action | Description ||--------|-------------|-| CreateUserPoolDomain | Creates a Cognito prefix domain, or a custom domain when `CustomDomainConfig.CertificateArn` is given. |+| CreateUserPoolDomain | Creates a Cognito prefix domain, or a custom domain when `CustomDomainConfig.CertificateArn` is given. As on AWS, the certificate must exist in ACM in us-east-1 with status `ISSUED`; the domain is listed under the certificate's `InUseBy` until it is deleted. || 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`. |+| UpdateUserPoolDomain | Replaces a custom domain's certificate or changes the managed login version in place. The domain keeps its `CloudFrontDistribution`, and its `InUseBy` entry moves to the new certificate. || DeleteUserPoolDomain | Deletes a domain from its user pool. |### Log Deliverydiff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.javaindex fad547b8a8..16eacb1952 100644--- a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java+++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java@@ -322,6 +322,37 @@ public class AcmService implements ResourceProvider {LOG.infov("Deleted certificate: {0}", certificateArn);}+ // ============ InUseBy ============++ /**+ * Records {@code consumerArn} as a user of the certificate, so DeleteCertificate refuses with+ * ResourceInUseException until it is released. Registering the same consumer twice is a no-op.+ */+ public void addInUseBy(String certificateArn, String consumerArn, String region) {+ Certificate cert = getCertificateByArn(certificateArn, region);+ if (!cert.getInUseBy().contains(consumerArn)) {+ cert.getInUseBy().add(consumerArn);+ store.put(regionKey(region, cert.extractCertificateId()), cert);+ }+ }++ /** Releases {@code consumerArn}. A certificate that no longer exists has nothing to release. */+ public void removeInUseBy(String certificateArn, String consumerArn, String region) {+ Certificate cert;+ try {+ cert = getCertificateByArn(certificateArn, region);+ } catch (AwsException e) {+ if (!"ResourceNotFoundException".equals(e.getErrorCode())) {+ throw e;+ }+ LOG.debugv("Certificate {0} is gone, nothing to release for {1}", certificateArn, consumerArn);+ return;+ }+ if (cert.getInUseBy().remove(consumerArn)) {+ store.put(regionKey(region, cert.extractCertificateId()), cert);+ }+ }+// ============ ImportCertificate ============public Certificate importCertificate(String certificatePem, String privateKeyPem, String chainPem,diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.javaindex c0c0d842d5..7867677521 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java@@ -1740,10 +1740,42 @@ public class CloudFormationService implements ResourceProvider {return failures;}+ /**+ * The stack's resources in the order the current template creates them, for a delete that walks+ * them backwards. The resource map keeps insertion order, and a resource added by a later+ * update sits after the resources that depend on it, so reversing the map would delete it+ * first: a certificate still used by a user pool domain, for one. Resources the template no+ * longer names, left behind by a failed cleanup, sort first here so they are deleted last,+ * after anything that might still use them. Insertion order is the fallback when the template+ * cannot be read.+ */+ private List<StackResource> resourcesInCreationOrder(Stack stack, String region) {+ List<StackResource> ordered = new ArrayList<>(stack.getResources().values());+ try {+ JsonNode template = parseTemplate(stack.getTemplateBody());+ JsonNode resources = template.path("Resources");+ if (!resources.isObject()) {+ return ordered;+ }+ Map<String, Boolean> conditions = resolveConditions(+ template, stack.getParameters(), stack, region, regionResolver.getAccountId());+ List<String> creationOrder = topologicalSort(resources, conditions);+ Map<String, Integer> rank = new HashMap<>();+ for (int i = 0; i < creationOrder.size(); i++) {+ rank.put(creationOrder.get(i), i);+ }+ ordered.sort(Comparator.comparingInt(r -> rank.getOrDefault(r.getLogicalId(), -1)));+ } catch (Exception e) {+ LOG.debugv("Deleting stack {0} in insertion order, its template could not be ordered: {1}",+ stack.getStackName(), e.getMessage());+ }+ return ordered;+ }+private void deleteStackResources(Stack stack, String region) {try {- List<StackResource> resources = new ArrayList<>(stack.getResources().values());- Collections.reverse(resources); // Delete in reverse order+ List<StackResource> resources = resourcesInCreationOrder(stack, region);+ Collections.reverse(resources); // Dependents go before what they depend onList<String> failedResources = new ArrayList<>();for (StackResource resource : resources) {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.javaindex cca2f4274b..b932ec573f 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@@ -17,6 +17,9 @@ import io.github.hectorvent.floci.core.resource.ResourceProvider;import io.github.hectorvent.floci.core.resource.SupportedResourceType;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.acm.AcmService;+import io.github.hectorvent.floci.services.acm.model.Certificate;+import io.github.hectorvent.floci.services.acm.model.CertificateStatus;import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;import io.github.hectorvent.floci.services.cognito.model.CognitoUser;import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;@@ -67,6 +70,7 @@ import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;import java.util.Locale;+import java.util.Objects;import java.util.Map;import java.util.Optional;import java.util.Set;@@ -121,6 +125,7 @@ public class CognitoService implements ResourceProvider {private final String baseUrl;private final RegionResolver regionResolver;private final LambdaService lambdaService;+ private final AcmService acmService;private final VerificationCodeService verificationCodeService;private final CognitoMessageDispatcher messageDispatcher;@@ -129,8 +134,8 @@ public class CognitoService implements ResourceProvider {@Injectpublic CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig,- RegionResolver regionResolver, LambdaService lambdaService, SesService sesService,- SnsService snsService, Clock clock) {+ RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService,+ SesService sesService, SnsService snsService, Clock clock) {this(storageFactory.create("cognito", "cognito-pools.json",new TypeReference<Map<String, UserPool>>() {}),@@ -151,6 +156,7 @@ public class CognitoService implements ResourceProvider {trimTrailingSlash(emulatorConfig.effectiveBaseUrl()),regionResolver,lambdaService,+ acmService,new VerificationCodeService(storageFactory, clock),new CognitoMessageDispatcher(sesService, snsService));@@ -164,10 +170,11 @@ public class CognitoService implements ResourceProvider {StorageBackend<String, RevokedTokenInfo> revokedTokenStore,String baseUrl,RegionResolver regionResolver,- LambdaService lambdaService) {+ LambdaService lambdaService,+ AcmService acmService) {this(poolStore, clientStore, resourceServerStore, new InMemoryStorage<>(),new InMemoryStorage<>(), userStore, groupStore, revokedTokenStore, baseUrl,- regionResolver, lambdaService, null, null);+ regionResolver, lambdaService, acmService, null, null);}CognitoService(StorageBackend<String, UserPool> poolStore,@@ -179,7 +186,7 @@ public class CognitoService implements ResourceProvider {StorageBackend<String, CognitoGroup> groupStore,StorageBackend<String, RevokedTokenInfo> revokedTokenStore,String baseUrl,- RegionResolver regionResolver, LambdaService lambdaService,+ RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService,VerificationCodeService verificationCodeService,CognitoMessageDispatcher messageDispatcher) {this.poolStore = poolStore;@@ -193,6 +200,7 @@ public class CognitoService implements ResourceProvider {this.baseUrl = baseUrl;this.regionResolver = regionResolver;this.lambdaService = lambdaService;+ this.acmService = acmService;this.verificationCodeService = verificationCodeService;this.messageDispatcher = messageDispatcher;this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver);@@ -1073,6 +1081,10 @@ public class CognitoService implements ResourceProvider {// ──────────────────────────── User Pool Domains ────────────────────────────+ private static final String CERTIFICATE_REGION = "us-east-1";+ private static final String CERTIFICATE_NOT_USABLE = "The specified SSL certificate doesn't exist, "+ + "isn't in us-east-1 region, isn't valid, or doesn't include a valid certificate chain.";+/*** Creates either an Amazon Cognito prefix domain ({@code customDomainConfig == null})* or a custom domain fronted by an ACM certificate. Domain names are globally unique@@ -1104,12 +1116,16 @@ public class CognitoService implements ResourceProvider {throw new AwsException("InvalidParameterException","CertificateArn is required in CustomDomainConfig", 400);}+ requireUsableCertificate(certificateArn);userPoolDomain.setCertificateArn(certificateArn);Object securityPolicy = customDomainConfig.get("SecurityPolicy");userPoolDomain.setSecurityPolicy(securityPolicy != null ? securityPolicy.toString() : "TLS_V1_2_2021");userPoolDomain.setCloudFrontDistribution(generateCloudFrontDomain());}+ if (userPoolDomain.isCustomDomain()) {+ registerCertificateUse(userPoolDomain.getCertificateArn(), userPoolDomain);+ }domainStore.put(domain, userPoolDomain);LOG.infov("Created User Pool Domain: {0} for pool {1}", domain, userPoolId);return userPoolDomain;@@ -1135,16 +1151,27 @@ public class CognitoService implements ResourceProvider {if (!userPoolDomain.getUserPoolId().equals(userPoolId)) {throw new AwsException("ResourceNotFoundException", "Domain does not exist", 404);}+ String previousCertificateArn = userPoolDomain.getCertificateArn();+ String certificateArn = previousCertificateArn;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");+ certificateArn = (String) customDomainConfig.get("CertificateArn");if (certificateArn == null || certificateArn.isBlank()) {throw new AwsException("InvalidParameterException","CertificateArn is required in CustomDomainConfig", 400);}+ }+ // A new certificate is checked and registered before anything changes, so a failure leaves+ // the domain on its current certificate.+ boolean certificateChanged = !Objects.equals(certificateArn, previousCertificateArn);+ if (certificateChanged) {+ requireUsableCertificate(certificateArn);+ registerCertificateUse(certificateArn, userPoolDomain);+ }+ if (customDomainConfig != null) {userPoolDomain.setCertificateArn(certificateArn);Object securityPolicy = customDomainConfig.get("SecurityPolicy");if (securityPolicy != null) {@@ -1156,6 +1183,10 @@ public class CognitoService implements ResourceProvider {}userPoolDomain.setLastModifiedDate(System.currentTimeMillis() / 1000L);domainStore.put(domain, userPoolDomain);+ if (certificateChanged) {+ acmService.removeInUseBy(previousCertificateArn,+ cloudFrontDistributionArn(userPoolDomain), CERTIFICATE_REGION);+ }LOG.infov("Updated User Pool Domain: {0} for pool {1}", domain, userPoolId);return userPoolDomain;}@@ -1166,9 +1197,68 @@ public class CognitoService implements ResourceProvider {throw new AwsException("ResourceNotFoundException", "Domain does not exist", 404);}domainStore.delete(domain);+ if (userPoolDomain.isCustomDomain()) {+ acmService.removeInUseBy(userPoolDomain.getCertificateArn(),+ cloudFrontDistributionArn(userPoolDomain), CERTIFICATE_REGION);+ }LOG.infov("Deleted User Pool Domain: {0} for pool {1}", domain, userPoolId);}+ /**+ * Registers the domain on its certificate before the domain is stored or changed, so a+ * certificate that disappears between the check and the registration leaves nothing behind.+ */+ private void registerCertificateUse(String certificateArn, UserPoolDomain userPoolDomain) {+ try {+ acmService.addInUseBy(certificateArn, cloudFrontDistributionArn(userPoolDomain), CERTIFICATE_REGION);+ } catch (AwsException e) {+ if (!"ResourceNotFoundException".equals(e.getErrorCode())) {+ throw e;+ }+ throw new AwsException("InvalidParameterException", CERTIFICATE_NOT_USABLE, 400);+ }+ }++ /**+ * AWS accepts only an issued ACM certificate from us-east-1 behind a custom domain, and answers+ * anything else with this one message.+ */+ private void requireUsableCertificate(String certificateArn) {+ AwsArnUtils.Arn arn;+ try {+ arn = AwsArnUtils.parse(certificateArn);+ } catch (IllegalArgumentException e) {+ throw new AwsException("InvalidParameterException", CERTIFICATE_NOT_USABLE, 400);+ }+ if (!"acm".equals(arn.service()) || !CERTIFICATE_REGION.equals(arn.region())+ || !arn.resource().startsWith("certificate/")) {+ throw new AwsException("InvalidParameterException", CERTIFICATE_NOT_USABLE, 400);+ }+ Certificate certificate;+ try {+ certificate = acmService.describeCertificate(certificateArn, CERTIFICATE_REGION);+ } catch (AwsException e) {+ if (!"ResourceNotFoundException".equals(e.getErrorCode())) {+ throw e;+ }+ throw new AwsException("InvalidParameterException", CERTIFICATE_NOT_USABLE, 400);+ }+ if (certificate.getStatus() != CertificateStatus.ISSUED) {+ throw new AwsException("InvalidParameterException", CERTIFICATE_NOT_USABLE, 400);+ }+ }++ /**+ * What a custom domain registers on its certificate: the CloudFront distribution that serves+ * it, which is what ACM lists on AWS. Floci has no distribution object, so the id is the label+ * of the generated CloudFront name.+ */+ private static String cloudFrontDistributionArn(UserPoolDomain userPoolDomain) {+ String name = userPoolDomain.getCloudFrontDistribution();+ String id = name.substring(0, name.indexOf('.')).toUpperCase(Locale.ROOT);+ return "arn:aws:cloudfront::" + userPoolDomain.getAwsAccountId() + ":distribution/" + id;+ }+private String generateCloudFrontDomain() {return UUID.randomUUID().toString().replace("-", "").substring(0, 14) + ".cloudfront.net";}diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmInUseByTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmInUseByTest.javanew file mode 100644index 0000000000..7068fc106d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmInUseByTest.java@@ -0,0 +1,99 @@+package io.github.hectorvent.floci.services.acm;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.services.acm.model.ValidationMethod;+import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.security.Security;+import java.util.List;+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.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * The {@code InUseBy} bookkeeping other services drive: a registered consumer blocks+ * {@code DeleteCertificate} with {@code ResourceInUseException}, as on AWS, until it is released.+ */+class AcmInUseByTest {++ private static final String REGION = "us-east-1";+ private static final String CONSUMER = "arn:aws:cloudfront::000000000000:distribution/E1234567890ABC";+ private static final String MISSING = "arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-0000-000000000000";++ private static CertificateGenerator generator;+ private AcmService service;++ @BeforeAll+ static void registerProvider() {+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ generator = new CertificateGenerator();+ }++ @BeforeEach+ void setUp() {+ RegionResolver regionResolver = mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");+ service = new AcmService(new InMemoryStorage<>(), generator, regionResolver, 0);+ }++ private String requestCertificate() {+ return service.requestCertificate("auth.example.com", List.of(), ValidationMethod.DNS, null,+ KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION).getArn();+ }++ @Test+ void addInUseByRecordsTheConsumerOnce() {+ String arn = requestCertificate();++ service.addInUseBy(arn, CONSUMER, REGION);+ service.addInUseBy(arn, CONSUMER, REGION);++ assertEquals(List.of(CONSUMER), service.describeCertificate(arn, REGION).getInUseBy());+ }++ @Test+ void aCertificateInUseCannotBeDeleted() {+ String arn = requestCertificate();+ service.addInUseBy(arn, CONSUMER, REGION);++ AwsException failure = assertThrows(AwsException.class, () -> service.deleteCertificate(arn, REGION));++ assertEquals("ResourceInUseException", failure.getErrorCode());+ assertEquals(List.of(CONSUMER), service.describeCertificate(arn, REGION).getInUseBy());+ }++ @Test+ void removeInUseByReleasesTheCertificateForDeletion() {+ String arn = requestCertificate();+ service.addInUseBy(arn, CONSUMER, REGION);++ service.removeInUseBy(arn, CONSUMER, REGION);++ assertEquals(List.of(), service.describeCertificate(arn, REGION).getInUseBy());+ assertDoesNotThrow(() -> service.deleteCertificate(arn, REGION));+ }++ @Test+ void removeInUseByOnAMissingCertificateIsANoOp() {+ assertDoesNotThrow(() -> service.removeInUseBy(MISSING, CONSUMER, REGION));+ }++ @Test+ void addInUseByOnAMissingCertificateIsNotFound() {+ AwsException failure = assertThrows(AwsException.class, () -> service.addInUseBy(MISSING, CONSUMER, REGION));++ assertEquals("ResourceNotFoundException", failure.getErrorCode());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.javaindex d1ba53a28d..2f4c538875 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoCfnIntegrationTest.java@@ -28,7 +28,8 @@ import static org.junit.jupiter.api.Assertions.fail;* {@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+ * that deleting the stack removes the domain before the pool that owns it and the certificate after+ * the domain that uses it. A prefix domain, which* has no distribution of its own, resolves the attribute to an empty string rather than the literal.*/@QuarkusTest@@ -139,6 +140,7 @@ class CognitoCfnIntegrationTest {assertTrue(certificateArn.startsWith("arn:aws:acm:us-east-1:"),"the certificate must be provisioned rather than stubbed: " + certificateArn);assertCertificateStatus(certificateArn, "ISSUED");+ assertCertificateConsumers(certificateArn, 1);JsonNode description = describeDomain(DOMAIN);assertEquals(poolId, description.path("UserPoolId").asText());@@ -159,6 +161,7 @@ class CognitoCfnIntegrationTest {assertEquals(aliasTarget, description.path("CloudFrontDistribution").asText(),"a certificate change must keep the CloudFront distribution the alias record points at");assertCertificateIsGone(certificateArn);+ assertCertificateConsumers(renewedCertificateArn, 1);// Domain is createOnly: a new name is a replacement, created before the old domain goes.cloudFormation(CUSTOM_STACK, "UpdateStack", customDomainTemplate(REPLACEMENT_DOMAIN, "RenewedCert"));@@ -265,6 +268,13 @@ class CognitoCfnIntegrationTest {.body("Certificate.Status", equalTo(status));}+ private static void assertCertificateConsumers(String certificateArn, int count) {+ awsAction("CertificateManager", "DescribeCertificate", "{\"CertificateArn\": \"" + certificateArn + "\"}")+ .then()+ .statusCode(200)+ .body("Certificate.InUseBy.size()", equalTo(count));+ }+private static void assertCertificateIsGone(String certificateArn) {awsAction("CertificateManager", "DescribeCertificate", "{\"CertificateArn\": \"" + certificateArn + "\"}").then()diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.javaindex 91c918e132..0a47b2e1d5 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java@@ -8,6 +8,7 @@ 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.services.acm.AcmService;import jakarta.ws.rs.core.Response;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -19,6 +20,7 @@ import java.util.stream.Collectors;import java.util.stream.StreamSupport;import static org.junit.jupiter.api.Assertions.*;+import static org.mockito.Mockito.mock;class CognitoJsonHandlerTest {@@ -37,7 +39,8 @@ class CognitoJsonHandlerTest {new InMemoryStorage<>(), // revokedTokenStore"http://localhost:4566",regionResolver,- null+ null,+ mock(AcmService.class));handler = new CognitoJsonHandler(service, mapper);}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.javaindex 0f531de57a..18c7e6b4db 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.acm.AcmService;import io.github.hectorvent.floci.services.cognito.model.CognitoUser;import io.github.hectorvent.floci.services.cognito.model.UserPool;import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;@@ -57,7 +58,7 @@ class CognitoLambdaTriggersTest {new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), // revokedTokenStore- "http://localhost:4566", regionResolver, lambdaService);+ "http://localhost:4566", regionResolver, lambdaService, mock(AcmService.class));}private UserPool createPoolWithLambdaConfig(Map<String, Object> lambdaConfig) {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.javaindex acfbc86e21..717dae4cc8 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@@ -7,6 +7,9 @@ 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.services.acm.AcmService;+import io.github.hectorvent.floci.services.acm.model.Certificate;+import io.github.hectorvent.floci.services.acm.model.CertificateStatus;import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;import io.github.hectorvent.floci.services.cognito.model.CognitoUser;import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;@@ -27,11 +30,13 @@ import java.util.ArrayList;import java.util.Base64;import java.util.HashMap;import java.util.List;+import java.util.Locale;import java.util.Map;import java.util.function.Function;import static org.junit.jupiter.api.Assertions.*;import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.*;@@ -43,12 +48,17 @@ class CognitoServiceTest {private InMemoryStorage<String, CognitoUser> userStore;private InMemoryStorage<String, CognitoGroup> groupStore;private RegionResolver regionResolver;+ private AcmService acmService;@BeforeEachvoid setUp() {userStore = new InMemoryStorage<>();groupStore = new InMemoryStorage<>();regionResolver = new RegionResolver("us-east-1", "000000000000");+ acmService = mock(AcmService.class);+ // Every certificate exists and is issued unless a test says otherwise.+ when(acmService.describeCertificate(anyString(), eq("us-east-1")))+ .thenAnswer(inv -> issuedCertificate(inv.getArgument(0)));service = new CognitoService(new InMemoryStorage<>(),new InMemoryStorage<>(),@@ -58,7 +68,8 @@ class CognitoServiceTest {new InMemoryStorage<>(), // revokedTokenStore"http://localhost:4566",regionResolver,- null+ null,+ acmService);}@@ -1391,6 +1402,7 @@ class CognitoServiceTest {"http://localhost:4566",regionResolver,null,+ acmService,verificationCodeService,messageDispatcher);@@ -1430,6 +1442,7 @@ class CognitoServiceTest {"http://localhost:4566",regionResolver,null,+ acmService,verificationCodeService,messageDispatcher);@@ -2900,6 +2913,7 @@ class CognitoServiceTest {"http://localhost:4566",regionResolver,null,+ acmService,verificationCodeService,messageDispatcher);@@ -3269,6 +3283,173 @@ class CognitoServiceTest {return pool;}+ private static final String AWS_CERTIFICATE_MESSAGE = "The specified SSL certificate doesn't exist, "+ + "isn't in us-east-1 region, isn't valid, or doesn't include a valid certificate chain.";++ private static Certificate issuedCertificate(String arn) {+ Certificate certificate = new Certificate();+ certificate.setArn(arn);+ certificate.setStatus(CertificateStatus.ISSUED);+ return certificate;+ }++ /** The ARN a domain registers on its certificate: the CloudFront distribution serving it. */+ private String consumerArn(String domain) {+ String distribution = service.describeUserPoolDomain(domain).getCloudFrontDistribution();+ return "arn:aws:cloudfront::000000000000:distribution/"+ + distribution.substring(0, distribution.indexOf('.')).toUpperCase(Locale.ROOT);+ }++ @Test+ void createUserPoolDomainRejectsACertificateAcmDoesNotKnow() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");+ when(acmService.describeCertificate(CERTIFICATE_ARN, "us-east-1")).thenThrow(+ new AwsException("ResourceNotFoundException", "The certificate " + CERTIFICATE_ARN + " does not exist.", 404));++ AwsException failure = assertThrows(AwsException.class, () -> service.createUserPoolDomain(+ "auth.example.com", pool.getId(), Map.of("CertificateArn", CERTIFICATE_ARN), null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ assertEquals(AWS_CERTIFICATE_MESSAGE, failure.getMessage());+ assertThrows(AwsException.class, () -> service.describeUserPoolDomain("auth.example.com"));+ verify(acmService, never()).addInUseBy(any(), any(), any());+ }++ @Test+ void createUserPoolDomainRejectsACertificateOutsideUsEast1() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");+ String elsewhere = "arn:aws:acm:eu-west-1:000000000000:certificate/11111111-2222-3333-4444-555555555555";++ AwsException failure = assertThrows(AwsException.class, () -> service.createUserPoolDomain(+ "auth.example.com", pool.getId(), Map.of("CertificateArn", elsewhere), null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ assertEquals(AWS_CERTIFICATE_MESSAGE, failure.getMessage());+ verify(acmService, never()).describeCertificate(any(), any());+ }++ @Test+ void createUserPoolDomainRejectsACertificateThatIsNotIssued() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");+ Certificate pending = issuedCertificate(CERTIFICATE_ARN);+ pending.setStatus(CertificateStatus.PENDING_VALIDATION);+ when(acmService.describeCertificate(CERTIFICATE_ARN, "us-east-1")).thenReturn(pending);++ AwsException failure = assertThrows(AwsException.class, () -> service.createUserPoolDomain(+ "auth.example.com", pool.getId(), Map.of("CertificateArn", CERTIFICATE_ARN), null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ assertEquals(AWS_CERTIFICATE_MESSAGE, failure.getMessage());+ }++ @Test+ void createUserPoolDomainRejectsAnAcmArnThatIsNotACertificate() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");+ String notACertificate = "arn:aws:acm:us-east-1:000000000000:certificate-authority/11111111-2222-3333-4444-555555555555";++ AwsException failure = assertThrows(AwsException.class, () -> service.createUserPoolDomain(+ "auth.example.com", pool.getId(), Map.of("CertificateArn", notACertificate), null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ assertEquals(AWS_CERTIFICATE_MESSAGE, failure.getMessage());+ verify(acmService, never()).describeCertificate(any(), any());+ }++ @Test+ void createUserPoolDomainRejectsAMalformedCertificateArn() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");++ AwsException failure = assertThrows(AwsException.class, () -> service.createUserPoolDomain(+ "auth.example.com", pool.getId(), Map.of("CertificateArn", "not-an-arn"), null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ verify(acmService, never()).describeCertificate(any(), any());+ }++ @Test+ void createUserPoolDomainStoresNothingWhenTheCertificateVanishesBeforeRegistration() {+ UserPool pool = service.createUserPool(Map.of("PoolName", "DomainPool"), "us-east-1");+ doThrow(new AwsException("ResourceNotFoundException", "gone", 404))+ .when(acmService).addInUseBy(eq(CERTIFICATE_ARN), any(), eq("us-east-1"));++ AwsException failure = assertThrows(AwsException.class, () -> service.createUserPoolDomain(+ "auth.example.com", pool.getId(), Map.of("CertificateArn", CERTIFICATE_ARN), null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ assertEquals(AWS_CERTIFICATE_MESSAGE, failure.getMessage());+ assertThrows(AwsException.class, () -> service.describeUserPoolDomain("auth.example.com"));+ }++ @Test+ void updateUserPoolDomainKeepsTheCurrentCertificateWhenTheNewOneVanishesBeforeRegistration() {+ UserPool pool = createPoolWithCustomDomain("auth.example.com");+ doThrow(new AwsException("ResourceNotFoundException", "gone", 404))+ .when(acmService).addInUseBy(eq(RENEWED_CERTIFICATE_ARN), any(), eq("us-east-1"));++ AwsException failure = assertThrows(AwsException.class, () -> service.updateUserPoolDomain(+ "auth.example.com", pool.getId(), Map.of("CertificateArn", RENEWED_CERTIFICATE_ARN), 2));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ UserPoolDomain stored = service.describeUserPoolDomain("auth.example.com");+ assertEquals(CERTIFICATE_ARN, stored.getCertificateArn());+ assertEquals(1, stored.getManagedLoginVersion());+ verify(acmService, never()).removeInUseBy(any(), any(), any());+ }++ @Test+ void createUserPoolDomainRegistersTheDomainAsACertificateConsumer() {+ createPoolWithCustomDomain("auth.example.com");++ verify(acmService).addInUseBy(CERTIFICATE_ARN, consumerArn("auth.example.com"), "us-east-1");+ }++ @Test+ void updateUserPoolDomainMovesTheRegistrationToTheNewCertificate() {+ UserPool pool = createPoolWithCustomDomain("auth.example.com");+ String consumer = consumerArn("auth.example.com");++ service.updateUserPoolDomain("auth.example.com", pool.getId(),+ Map.of("CertificateArn", RENEWED_CERTIFICATE_ARN), null);++ verify(acmService).removeInUseBy(CERTIFICATE_ARN, consumer, "us-east-1");+ verify(acmService).addInUseBy(RENEWED_CERTIFICATE_ARN, consumer, "us-east-1");+ }++ @Test+ void updateUserPoolDomainWithTheSameCertificateKeepsTheRegistration() {+ UserPool pool = createPoolWithCustomDomain("auth.example.com");++ service.updateUserPoolDomain("auth.example.com", pool.getId(),+ Map.of("CertificateArn", CERTIFICATE_ARN), 2);++ verify(acmService, never()).removeInUseBy(any(), any(), any());+ verify(acmService, times(1)).addInUseBy(any(), any(), any());+ }++ @Test+ void updateUserPoolDomainRejectsAnUnknownCertificateAndKeepsTheCurrentOne() {+ UserPool pool = createPoolWithCustomDomain("auth.example.com");+ when(acmService.describeCertificate(RENEWED_CERTIFICATE_ARN, "us-east-1")).thenThrow(+ new AwsException("ResourceNotFoundException", "does not exist", 404));++ AwsException failure = assertThrows(AwsException.class, () -> service.updateUserPoolDomain(+ "auth.example.com", pool.getId(), Map.of("CertificateArn", RENEWED_CERTIFICATE_ARN), null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ assertEquals(CERTIFICATE_ARN, service.describeUserPoolDomain("auth.example.com").getCertificateArn());+ verify(acmService, never()).removeInUseBy(any(), any(), any());+ }++ @Test+ void deleteUserPoolDomainReleasesTheCertificate() {+ UserPool pool = createPoolWithCustomDomain("auth.example.com");+ String consumer = consumerArn("auth.example.com");++ service.deleteUserPoolDomain("auth.example.com", pool.getId());++ verify(acmService).removeInUseBy(CERTIFICATE_ARN, consumer, "us-east-1");+ }+@Testvoid updateUserPoolDomainReplacesTheCertificateAndKeepsTheCloudFrontDistribution() {UserPool pool = createPoolWithCustomDomain("auth.example.com");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.javaindex f315b76355..788a99a7a0 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserPoolDomainIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoUserPoolDomainIntegrationTest.java@@ -14,12 +14,14 @@ 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.hamcrest.Matchers.startsWith;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNull;/*** Covers CreateUserPoolDomain/DescribeUserPoolDomain/UpdateUserPoolDomain/DeleteUserPoolDomain (lex00/floci#63)- * for both an Amazon Cognito prefix domain and a custom domain fronted by an ACM certificate.+ * for both an Amazon Cognito prefix domain and a custom domain fronted by an ACM certificate, including+ * the certificate's InUseBy bookkeeping in ACM.*/@QuarkusTest@TestMethodOrder(MethodOrderer.OrderAnnotation.class)@@ -28,10 +30,10 @@ 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();- private static final String RENEWED_CERTIFICATE_ARN =- "arn:aws:acm:us-east-1:000000000000:certificate/" + UUID.randomUUID();+ private static String CERTIFICATE_ARN;+ private static String RENEWED_CERTIFICATE_ARN;+ private static final String AWS_CERTIFICATE_MESSAGE = "The specified SSL certificate doesn't exist, "+ + "isn't in us-east-1 region, isn't valid, or doesn't include a valid certificate chain.";@BeforeAllstatic void configureRestAssured() {@@ -49,6 +51,25 @@ class CognitoUserPoolDomainIntegrationTest {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";+ CERTIFICATE_ARN = requestCertificate(customDomain);+ RENEWED_CERTIFICATE_ARN = requestCertificate(customDomain);+ }++ private static String requestCertificate(String domainName) throws Exception {+ return RestAssuredJsonUtils.awsActionJson("CertificateManager", "RequestCertificate", """+ {+ "DomainName": "%s",+ "ValidationMethod": "DNS"+ }+ """.formatted(domainName)).path("CertificateArn").asText();+ }++ private static io.restassured.response.Response acm(String action, String certificateArn) {+ return RestAssuredJsonUtils.awsAction("CertificateManager", action, """+ {+ "CertificateArn": "%s"+ }+ """.formatted(certificateArn));}@Test@@ -144,6 +165,21 @@ class CognitoUserPoolDomainIntegrationTest {@Test@Order(8)+ void certificateInUseByTheDomainCannotBeDeleted() {+ acm("DescribeCertificate", CERTIFICATE_ARN)+ .then()+ .statusCode(200)+ .body("Certificate.InUseBy.size()", equalTo(1))+ .body("Certificate.InUseBy[0]", startsWith("arn:aws:cloudfront::"));++ acm("DeleteCertificate", CERTIFICATE_ARN)+ .then()+ .statusCode(409)+ .body("__type", equalTo("ResourceInUseException"));+ }++ @Test+ @Order(9)void updateCustomDomainReplacesTheCertificateAndKeepsTheCloudFrontDistribution() throws Exception {String cloudFront = cognitoJson("DescribeUserPoolDomain", """{@@ -177,7 +213,20 @@ class CognitoUserPoolDomainIntegrationTest {}@Test- @Order(9)+ @Order(10)+ void updateMovesTheRegistrationToTheRenewedCertificate() {+ acm("DescribeCertificate", CERTIFICATE_ARN)+ .then()+ .statusCode(200)+ .body("Certificate.InUseBy.size()", equalTo(0));+ acm("DescribeCertificate", RENEWED_CERTIFICATE_ARN)+ .then()+ .statusCode(200)+ .body("Certificate.InUseBy.size()", equalTo(1));+ }++ @Test+ @Order(11)void updateDomainOfAnotherPoolIsNotFound() {cognitoAction("UpdateUserPoolDomain", """{@@ -193,7 +242,7 @@ class CognitoUserPoolDomainIntegrationTest {}@Test- @Order(10)+ @Order(12)void createCustomDomainWithoutCertificateArnFails() {cognitoAction("CreateUserPoolDomain", """{@@ -208,7 +257,25 @@ class CognitoUserPoolDomainIntegrationTest {}@Test- @Order(11)+ @Order(13)+ void createCustomDomainWithUnknownCertificateFails() {+ cognitoAction("CreateUserPoolDomain", """+ {+ "Domain": "%s",+ "UserPoolId": "%s",+ "CustomDomainConfig": {+ "CertificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/%s"+ }+ }+ """.formatted("unknown-" + UUID.randomUUID().toString().substring(0, 8) + ".example.com", poolId, UUID.randomUUID()))+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterException"))+ .body("message", equalTo(AWS_CERTIFICATE_MESSAGE));+ }++ @Test+ @Order(14)void deleteCustomDomainThenDescribeIsNotFound() {cognitoAction("DeleteUserPoolDomain", """{@@ -230,7 +297,20 @@ class CognitoUserPoolDomainIntegrationTest {}@Test- @Order(12)+ @Order(15)+ void deletingTheDomainReleasesTheCertificate() {+ acm("DescribeCertificate", RENEWED_CERTIFICATE_ARN)+ .then()+ .statusCode(200)+ .body("Certificate.InUseBy.size()", equalTo(0));++ acm("DeleteCertificate", RENEWED_CERTIFICATE_ARN)+ .then()+ .statusCode(200);+ }++ @Test+ @Order(16)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);@@ -263,7 +343,7 @@ class CognitoUserPoolDomainIntegrationTest {}@Test- @Order(13)+ @Order(17)void deleteUserPoolSucceedsOnceDomainIsGone() {cognitoAction("DeleteUserPool", """{