diff --git a/docs/services/acm.md b/docs/services/acm.md index f453d94a1d..a3ce659377 100644 --- a/docs/services/acm.md +++ b/docs/services/acm.md @@ -38,7 +38,7 @@ - **Certificate Types:** `AMAZON_ISSUED` (default) and `PRIVATE` (when `CertificateAuthorityArn` is provided) - **Imported keys:** `ImportCertificate` requires a private key that matches the certificate. A rejected import leaves an existing certificate unchanged. - **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 each CloudFront distribution whose `ViewerCertificate.ACMCertificateArn` names it, 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. +- **In use:** `DescribeCertificate` lists under `InUseBy` the CloudFront distribution of each Cognito custom domain that uses the certificate, each CloudFront distribution whose `ViewerCertificate.ACMCertificateArn` names it, and each ELBv2 or Classic load balancer whose listener serves it. `DeleteCertificate` refuses with `ResourceInUseException` while that list is not empty. Other consumers, such as API Gateway domain names, are not tracked yet. ## Configuration diff --git a/docs/services/elb-classic.md b/docs/services/elb-classic.md index e692ee2f7c..d6f93646a2 100644 --- a/docs/services/elb-classic.md +++ b/docs/services/elb-classic.md @@ -86,8 +86,11 @@ opened and no traffic is forwarded. Only the control plane and health checking a satisfied. - A listener's `SSLCertificateId` must name an existing certificate: an IAM server certificate ARN or an ACM certificate ARN. `CreateLoadBalancer` and `CreateLoadBalancerListeners` reject a - missing one with `CertificateNotFound`. An IAM server certificate a listener references cannot - be deleted: `DeleteServerCertificate` returns `DeleteConflict` until the listener is removed. + missing one with `CertificateNotFound`, and a blank one on an HTTPS or SSL listener; an HTTP or + TCP listener may carry a blank one, as Terraform sends. A certificate a listener references cannot be + deleted until the listener is removed: `DeleteServerCertificate` returns `DeleteConflict`, and + ACM's `DeleteCertificate` returns `ResourceInUseException` and lists the load balancer under + `InUseBy`. ## Configuration diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicAcmCertificateReferences.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicAcmCertificateReferences.java new file mode 100644 index 0000000000..744fc4da6f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicAcmCertificateReferences.java @@ -0,0 +1,28 @@ +package io.github.hectorvent.floci.services.elb; + +import io.github.hectorvent.floci.services.acm.AcmCertificateReferenceProvider; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; + +/** ACM discovers this consumer lazily, after the load-balancer service has initialized. */ +@ApplicationScoped +public class ElbClassicAcmCertificateReferences implements AcmCertificateReferenceProvider { + private final ElbClassicService service; + + @Inject + public ElbClassicAcmCertificateReferences(ElbClassicService service) { + this.service = service; + } + + @Override + public List acmCertificateReferences() { + return service.acmCertificateReferences(); + } + + /** A Classic listener serves no TLS of its own, so a reimported certificate has nothing to refresh. */ + @Override + public void certificateReimported(String certificateArn, String region) { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java index dbfdf7b969..714a30ce20 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java +++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.elb; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsRegionFacts; import io.github.hectorvent.floci.core.common.CertificateReferenceResolver; @@ -10,6 +11,7 @@ import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackedMap; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.acm.AcmCertificateReferenceProvider.CertificateReference; import io.github.hectorvent.floci.services.acm.AcmService; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.SecurityGroup; @@ -635,18 +637,46 @@ public class ElbClassicService implements ServerCertificateReferenceProvider { @Override public List serverCertificateReferences() { List references = new ArrayList<>(); + for (ListenerCertificate served : listenerCertificates()) { + references.add(new Reference(served.certificateId(), + "load balancer " + served.loadBalancer().getLoadBalancerName())); + } + return references; + } + + /** + * The ACM certificates the listeners serve, each held by its load balancer, so ACM lists the load + * balancer in {@code InUseBy} and refuses to delete the certificate. Like + * {@link #serverCertificateReferences} it takes no monitor of this service. + */ + public List acmCertificateReferences() { + List references = new ArrayList<>(); + for (ListenerCertificate served : listenerCertificates()) { + ClassicLoadBalancer lb = served.loadBalancer(); + String loadBalancerArn = AwsArnUtils.Arn.of("elasticloadbalancing", lb.getRegion(), + lb.getAccountId(), "loadbalancer/" + lb.getLoadBalancerName()).toString(); + references.add(new CertificateReference(served.certificateId(), loadBalancerArn)); + } + return references; + } + + private record ListenerCertificate(ClassicLoadBalancer loadBalancer, String certificateId) { + } + + /** Every certificate a listener names, skipping the empty id Terraform sends for a plain listener. */ + private List listenerCertificates() { + List served = new ArrayList<>(); for (Map regionLbs : loadBalancers.values()) { for (ClassicLoadBalancer lb : regionLbs.values()) { for (ClassicListener listener : lb.getListeners()) { - String certificate = listener.getSslCertificateId(); - if (certificate != null && !certificate.isBlank()) { - references.add(new Reference(certificate, - "load balancer " + lb.getLoadBalancerName())); + String certificateId = listener.getSslCertificateId(); + if (certificateId != null && !certificateId.isBlank()) { + served.add(new ListenerCertificate(lb, certificateId)); } } } } - return references; + return served; } private static AwsException duplicateLoadBalancerName(String name) { @@ -672,14 +702,20 @@ public class ElbClassicService implements ServerCertificateReferenceProvider { private void requireCertificates(String region, List listeners) { for (ClassicListener listener : listeners) { String certificateId = listener.getSslCertificateId(); - if (certificateId != null && !certificateId.isBlank() - && !certificates.exists(region, certificateId)) { + if (certificateId == null || (certificateId.isBlank() && !terminatesTls(listener))) { + continue; + } + if (!certificates.exists(region, certificateId)) { throw new AwsException("CertificateNotFound", "Server Certificate not found for the key: " + certificateId, 400); } } } + private static boolean terminatesTls(ClassicListener listener) { + return "HTTPS".equalsIgnoreCase(listener.getProtocol()) || "SSL".equalsIgnoreCase(listener.getProtocol()); + } + private static List certificateIdsOf(List listeners) { List certificateIds = new ArrayList<>(); for (ClassicListener listener : listeners) { diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java index 0d8e0c9756..6695b100ec 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java @@ -42,7 +42,7 @@ class PartitionCrossServiceSmokeIntegrationTest { "aps", "autoscaling", "backup", "batch", "bcmdataexports", "bedrock", "bedrockagentcorecontrol", "ce", "cloudfront", "cloudmap", "cloudwatch", "codebuild", "codedeploy", "codepipeline", "cognito", "configservice", "connect", "controlcatalog", "controltower", "datasync", "dlm", "dms", "dsql", "dynamodb", "ec2", - "ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elbv2", "emr", "emrserverless", + "ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elb", "elbv2", "emr", "emrserverless", "eventbridge", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda", "lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations", "pipes", "ram", "rds", "redshift", "redshiftserverless", "resourceexplorer2", "resourcegroups", "route53resolver", @@ -167,6 +167,40 @@ class PartitionCrossServiceSmokeIntegrationTest { PartitionMatrix.assertArnIn(partitionCase, arn); } + @ParameterizedTest + @MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES) + void elbClassicLoadBalancerArnInAcmInUseBy(PartitionCase partitionCase) { + String region = offered(partitionCase, "acm"); + offered(partitionCase, "elasticloadbalancing"); + String certificateArn = json11(region, "acm", "CertificateManager.RequestCertificate", + "{\"DomainName\":\"" + unique("smoke-elb", partitionCase) + ".example.com\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("CertificateArn"); + cleanup.register(() -> json11(region, "acm", "CertificateManager.DeleteCertificate", + "{\"CertificateArn\":\"" + certificateArn + "\"}").when().post("/")); + String name = unique("elb", partitionCase); + signed(region, "elasticloadbalancing") + .formParam("Action", "CreateLoadBalancer") + .formParam("Version", "2012-06-01") + .formParam("LoadBalancerName", name) + .formParam("AvailabilityZones.member.1", region + "a") + .formParam("Listeners.member.1.Protocol", "HTTPS") + .formParam("Listeners.member.1.LoadBalancerPort", "443") + .formParam("Listeners.member.1.InstancePort", "8080") + .formParam("Listeners.member.1.SSLCertificateId", certificateArn) + .when().post("/").then().statusCode(200); + cleanup.register(() -> signed(region, "elasticloadbalancing") + .formParam("Action", "DeleteLoadBalancer") + .formParam("Version", "2012-06-01") + .formParam("LoadBalancerName", name) + .when().post("/")); + String arn = json11(region, "acm", "CertificateManager.DescribeCertificate", + "{\"CertificateArn\":\"" + certificateArn + "\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("Certificate.InUseBy[0]"); + PartitionMatrix.assertArnIn(partitionCase, arn); + } + @ParameterizedTest @MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES) void glueSchemaRegistryArn(PartitionCase partitionCase) { diff --git a/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServerCertificateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServerCertificateIntegrationTest.java index cf7a07ef85..fb3afe9bad 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServerCertificateIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elb/ElbClassicServerCertificateIntegrationTest.java @@ -7,12 +7,14 @@ import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; import io.restassured.config.EncoderConfig; import io.restassured.http.ContentType; +import io.restassured.parsing.Parser; import io.restassured.response.ValidatableResponse; import org.junit.jupiter.api.Test; import java.util.List; import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -58,6 +60,14 @@ class ElbClassicServerCertificateIntegrationTest { .extract().path("CertificateArn"); } + private static ValidatableResponse acm(String target, String certificateArn) { + return given().header("Authorization", ACM_AUTH) + .header("X-Amz-Target", "CertificateManager." + target) + .contentType("application/x-amz-json-1.1").config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig().encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT))) + .body("{\"CertificateArn\": \"" + certificateArn + "\"}") + .when().post("/").then().using().defaultParser(Parser.JSON); + } + private static ValidatableResponse deleteCertificate(String name) { return given().header("Authorization", IAM_AUTH) .formParam("Action", "DeleteServerCertificate") @@ -145,6 +155,52 @@ class ElbClassicServerCertificateIntegrationTest { deleteCertificate(certName).statusCode(200); } + @Test + void createLoadBalancerRejectsABlankCertificateId() { + createLoadBalancer("elb-cert-blank-" + suffix(), "") + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("CertificateNotFound")); + } + + @Test + void createLoadBalancerAcceptsAnHttpListenerWithAnEmptyCertificateId() { + given().header("Authorization", ELB_AUTH) + .formParam("Action", "CreateLoadBalancer") + .formParam("Version", CLASSIC_VERSION) + .formParam("LoadBalancerName", "elb-cert-http-" + suffix()) + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Listeners.member.1.Protocol", "HTTP") + .formParam("Listeners.member.1.LoadBalancerPort", "80") + .formParam("Listeners.member.1.InstanceProtocol", "HTTP") + .formParam("Listeners.member.1.InstancePort", "8080") + .formParam("Listeners.member.1.SSLCertificateId", "") + .when().post("/").then().statusCode(200); + } + + @Test + void acmCertificateInUseCannotBeDeletedUntilTheListenerIsGone() { + String lb = "elb-acm-in-use-" + suffix(); + String arn = requestAcmCertificate(); + createLoadBalancer(lb, arn).statusCode(200); + + acm("DescribeCertificate", arn) + .statusCode(200) + .body("Certificate.InUseBy", + contains("arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/" + lb)); + acm("DeleteCertificate", arn) + .statusCode(400) + .body("__type", equalTo("ResourceInUseException")); + + given().header("Authorization", ELB_AUTH) + .formParam("Action", "DeleteLoadBalancerListeners") + .formParam("Version", CLASSIC_VERSION) + .formParam("LoadBalancerName", lb) + .formParam("LoadBalancerPorts.member.1", "443") + .when().post("/").then().statusCode(200); + + acm("DeleteCertificate", arn).statusCode(200); + } + @Test void createLoadBalancerAcceptsAnAcmCertificateOfItsOwnRegionAndAccount() { createLoadBalancer("elb-acm-ok-" + suffix(), requestAcmCertificate()).statusCode(200);