Light, fluffy, and always free - The AWS Local Emulator alternative
feat(elbv2): terminate HTTPS with ACM and IAM certificates (#5959)
David Phillips0da0c808242e
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2HttpsDataPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2HttpsDataPlaneTest.javanew file mode 100644index 0000000000..726b5b163c--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2HttpsDataPlaneTest.java@@ -0,0 +1,199 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.acm.AcmClient;+import software.amazon.awssdk.services.acm.model.CertificateStatus;+import software.amazon.awssdk.services.acm.model.ResourceInUseException;+import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;+import software.amazon.awssdk.services.elasticloadbalancingv2.model.Action;+import software.amazon.awssdk.services.elasticloadbalancingv2.model.ActionTypeEnum;+import software.amazon.awssdk.services.elasticloadbalancingv2.model.FixedResponseActionConfig;+import software.amazon.awssdk.services.elasticloadbalancingv2.model.Listener;+import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancer;+import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerTypeEnum;+import software.amazon.awssdk.services.elasticloadbalancingv2.model.ProtocolEnum;++import javax.net.ssl.SSLContext;+import javax.net.ssl.TrustManagerFactory;++import java.io.ByteArrayInputStream;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.nio.charset.StandardCharsets;+import java.security.KeyStore;+import java.security.MessageDigest;+import java.security.cert.CertificateFactory;+import java.security.cert.X509Certificate;+import java.time.Duration;+import java.util.HexFormat;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assertions.assertAll;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assumptions.assumeFalse;++@DisplayName("Local ELBv2 HTTPS listeners")+class ElbV2HttpsDataPlaneTest {++ private static final int LISTENER_PORT = 7796;++ private static AcmClient acm;+ private static ElasticLoadBalancingV2Client elb;+ private static String certificateArn;+ private static String loadBalancerArn;+ private static String listenerArn;++ @BeforeAll+ static void setup() {+ assumeFalse(TestFixtures.isRealAws(), "Creates local HTTPS listener fixtures");+ acm = TestFixtures.acmClient();+ elb = TestFixtures.elbV2Client();+ }++ @AfterAll+ static void cleanup() {+ assertAll("Delete every HTTPS fixture resource and close both clients",+ () -> {+ if (listenerArn != null) {+ elb.deleteListener(request -> request.listenerArn(listenerArn));+ }+ },+ () -> {+ if (loadBalancerArn != null) {+ elb.deleteLoadBalancer(request -> request.loadBalancerArn(loadBalancerArn));+ }+ },+ () -> {+ if (certificateArn != null) {+ acm.deleteCertificate(request -> request.certificateArn(certificateArn));+ }+ },+ () -> {+ if (elb != null) {+ elb.close();+ }+ },+ () -> {+ if (acm != null) {+ acm.close();+ }+ });+ }++ @Test+ @DisplayName("Official clients configure an ACM-backed listener that serves HTTPS")+ void officialClientsConfigureAcmBackedHttpsListenerThatTerminatesTls() throws Exception {+ LoadBalancer loadBalancer = elb.createLoadBalancer(request -> request+ .name(TestFixtures.uniqueName("tls"))+ .type(LoadBalancerTypeEnum.APPLICATION))+ .loadBalancers().get(0);+ loadBalancerArn = loadBalancer.loadBalancerArn();+ String dnsName = loadBalancer.dnsName();++ certificateArn = acm.requestCertificate(request -> request.domainName(dnsName)).certificateArn();+ acm.updateCertificateOptions(request -> request.certificateArn(certificateArn)+ .options(options -> options.export("ENABLED")));+ assertThat(acm.describeCertificate(request -> request.certificateArn(certificateArn))+ .certificate().options().exportAsString()).isEqualTo("ENABLED");+ String certificatePem = acm.getCertificate(request -> request.certificateArn(certificateArn)).certificate();++ listenerArn = elb.createListener(request -> request+ .loadBalancerArn(loadBalancerArn)+ .protocol(ProtocolEnum.HTTPS)+ .port(LISTENER_PORT)+ .sslPolicy("ELBSecurityPolicy-TLS13-1-2-2021-06")+ .certificates(certificate -> certificate.certificateArn(certificateArn))+ .defaultActions(Action.builder()+ .type(ActionTypeEnum.FIXED_RESPONSE)+ .fixedResponseConfig(FixedResponseActionConfig.builder()+ .statusCode("200")+ .contentType("text/plain")+ .messageBody("sdk-tls")+ .build())+ .build()))+ .listeners().get(0).listenerArn();++ Listener described = elb.describeListeners(request -> request.listenerArns(listenerArn)).listeners().get(0);+ assertThat(described.protocol()).isEqualTo(ProtocolEnum.HTTPS);+ assertThat(described.port()).isEqualTo(LISTENER_PORT);+ assertThat(described.sslPolicy()).isEqualTo("ELBSecurityPolicy-TLS13-1-2-2021-06");+ assertThat(described.certificates()).extracting(certificate -> certificate.certificateArn())+ .containsExactly(certificateArn);++ X509Certificate expected = parseCertificate(certificatePem);+ HttpClient client = trustedClient(expected);+ HttpResponse<String> result = awaitHttps(client, dnsName);++ assertThat(result.statusCode()).isEqualTo(200);+ assertThat(result.body()).isEqualTo("sdk-tls");+ X509Certificate actual = (X509Certificate) result.sslSession().orElseThrow().getPeerCertificates()[0];+ assertThat(fingerprint(actual)).isEqualTo(fingerprint(expected));+ assertThat(actual.getSubjectAlternativeNames())+ .anySatisfy(san -> assertThat(san.get(1)).isEqualTo(dnsName));++ ResourceInUseException refusal = assertThrows(ResourceInUseException.class,+ () -> acm.revokeCertificate(request -> request.certificateArn(certificateArn)+ .revocationReason("KEY_COMPROMISE")));+ assertThat(refusal.statusCode()).isEqualTo(400);+ assertThat(acm.describeCertificate(request -> request.certificateArn(certificateArn)).certificate().status())+ .isEqualTo(CertificateStatus.ISSUED);+ HttpClient fresh = trustedClient(expected);+ HttpResponse<String> afterRefusal = awaitHttps(fresh, dnsName);+ assertThat(afterRefusal.statusCode()).isEqualTo(200);+ assertThat(afterRefusal.body()).isEqualTo("sdk-tls");+ assertThat(fingerprint((X509Certificate) afterRefusal.sslSession().orElseThrow().getPeerCertificates()[0]))+ .isEqualTo(fingerprint(expected));+ elb.deleteListener(request -> request.listenerArn(listenerArn));+ listenerArn = null;+ acm.revokeCertificate(request -> request.certificateArn(certificateArn).revocationReason("KEY_COMPROMISE"));+ assertThat(acm.describeCertificate(request -> request.certificateArn(certificateArn)).certificate().status())+ .isEqualTo(CertificateStatus.REVOKED);+ }++ private static HttpClient trustedClient(X509Certificate certificate) throws Exception {+ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());+ trustStore.load(null, null);+ trustStore.setCertificateEntry("acm", certificate);+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ trustManagerFactory.init(trustStore);+ SSLContext sslContext = SSLContext.getInstance("TLS");+ sslContext.init(null, trustManagerFactory.getTrustManagers(), null);+ return HttpClient.newBuilder()+ .connectTimeout(Duration.ofSeconds(2))+ .sslContext(sslContext)+ .build();+ }++ private static HttpResponse<String> awaitHttps(HttpClient client, String dnsName) throws Exception {+ long deadline = System.nanoTime() + Duration.ofSeconds(10).toNanos();+ Exception lastFailure = null;+ do {+ try {+ return client.send(+ HttpRequest.newBuilder(URI.create("https://" + dnsName + ":" + LISTENER_PORT + "/"))+ .timeout(Duration.ofSeconds(2))+ .GET()+ .build(),+ HttpResponse.BodyHandlers.ofString());+ } catch (Exception e) {+ lastFailure = e;+ Thread.sleep(100);+ }+ } while (System.nanoTime() < deadline);+ throw lastFailure;+ }++ private static X509Certificate parseCertificate(String pem) throws Exception {+ return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(+ new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));+ }++ private static String fingerprint(X509Certificate certificate) throws Exception {+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded()));+ }+}diff --git a/docs/services/elb.md b/docs/services/elb.mdindex 78064a5a7c..5c800bc513 100644--- a/docs/services/elb.md+++ b/docs/services/elb.md@@ -2,7 +2,7 @@**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter-Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB) through the ELBv2 management API. The control plane is AWS SDK / CLI / Terraform compatible, and HTTP listeners can forward to registered instance targets using the target's reachable local address.+Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB) through the ELBv2 management API. The control plane is AWS SDK / CLI / Terraform compatible, and HTTP and HTTPS listeners can forward to registered instance targets using the target's reachable local address.> Classic (v1) Elastic Load Balancing is a **different API** served from the same endpoint host —> see [ELB Classic (v1)](elb-classic.md). Requests are routed by their `Version` parameter:@@ -86,6 +86,10 @@ HTTPS listeners require a default certificate. Supply one when creating a listen## Behavior Notes+- HTTPS listeners terminate TLS using the configured ACM or IAM server certificates, with SNI certificate selection. When several load balancers share one local HTTPS port, clients must send SNI to identify the certificate they need; a connection without SNI cannot identify a particular load balancer before the TLS handshake.+- ACM certificates must be issued before attaching them. Reimporting an attached ACM certificate refreshes subsequent TLS connections; existing connections keep their negotiated certificate. ACM deletion and revocation are refused while a listener still references the certificate.+- Unusable saved listeners are retained for correction and logged individually so other saved listeners can start.+- Listeners sharing a local port must use the same protocol. Requests select a load balancer by its DNS name, a hostname declared by its rules, or a certificate hostname; ambiguous hostnames return 502.- Load balancer, target group, listener, rule, and tag state is persisted through Floci storage and rebuilt on service startup.- Load balancers are created in `active` state.- EC2 refuses deletion of subnets and VPCs still referenced by load balancers with `DependencyViolation`. These account- and region-scoped dependencies follow persisted load balancer state; changing subnets or deleting the load balancer releases its old references. A CloudFormation update that changes `Subnets` or `SubnetMappings` moves the load balancer the way `SetSubnets` does, and a rolled-back update moves it back. An independent target group does not prevent subnet or VPC deletion.@@ -96,7 +100,7 @@ HTTPS listeners require a default certificate. Supply one when creating a listen- Each `CreateListener` automatically creates an immutable default rule (`priority=default`, `isDefault=true`). This rule cannot be deleted; use `ModifyListener` to change its action.- Rule priorities are unique per listener: `CreateRule` and `SetRulePriorities` only reject a priority held by another rule on the same listener. `SetRulePriorities` is atomic: all priority assignments are validated before any change is committed.- `DeleteTargetGroup` is rejected with `ResourceInUse` while the target group is referenced by any listener or rule.-- An HTTPS or TLS listener's certificates must name existing certificates: an IAM server certificate ARN or an ACM certificate ARN. `CreateListener`, `ModifyListener` and `AddListenerCertificates` reject a missing or empty one with `CertificateNotFound`, the three operations the API reference models it on, and a `ModifyListener` that turns a listener into an HTTPS or TLS one is held to the same check over the certificates it already carried. An IAM server certificate a listener references cannot be deleted: `DeleteServerCertificate` returns `DeleteConflict` until the certificate is removed from the listener. A write that records one runs while IAM holds its certificate lock, so a certificate cannot be deleted between the check and the write, and a `ModifyListener` refused by that check leaves the listener on the port, protocol, policy and certificates it already had.+- HTTPS and TLS certificate ARNs must refer to existing IAM server certificates or ACM certificates. `CreateListener`, `ModifyListener` and `AddListenerCertificates` reject a blank or unknown ARN with `CertificateNotFound`. When `ModifyListener` changes the protocol to HTTPS or TLS, it checks any inherited certificate ARNs too. An HTTPS listener also needs a default certificate: `CreateListener` and `ModifyListener` reject an absent or empty effective certificate list with `InvalidConfigurationRequest`. A referenced IAM server certificate cannot be deleted: `DeleteServerCertificate` returns `DeleteConflict` until the certificate is removed from the listener. Writes recording a new IAM certificate reference hold IAM's certificate lock, so the certificate cannot be deleted between the check and the write. A refused change preserves the listener's previous port, protocol, policy and certificates.- `RemoveListenerCertificates` refuses removal of an HTTPS or TLS listener's default certificate with `OperationNotPermitted` (400) and preserves the certificate list. Use `ModifyListener` to replace the default certificate. Additional certificates can still be removed.- `DeleteRule` is rejected with `OperationNotPermitted` for the default rule.- `DescribeSSLPolicies` returns a pre-seeded list of standard AWS SSL policies (`ELBSecurityPolicy-*`).diff --git a/src/main/java/io/github/hectorvent/floci/core/common/CertificateReferenceResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/CertificateReferenceResolver.javaindex aa83691e87..3f9a4f81ec 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/CertificateReferenceResolver.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/CertificateReferenceResolver.java@@ -1,6 +1,8 @@package io.github.hectorvent.floci.core.common;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.iam.IamService;import io.github.hectorvent.floci.services.iam.model.ServerCertificate;import jakarta.enterprise.context.ApplicationScoped;@@ -9,6 +11,7 @@ import org.jboss.logging.Logger;import java.util.Collection;import java.util.Optional;+import java.util.function.Supplier;/*** Whether a certificate another service names exists, and the lock that keeps the answer true for@@ -55,23 +58,95 @@ public class CertificateReferenceResolver {};}+ /** Detached TLS material for a reference already recorded by a certificate consumer. */+ public record CertificateMaterial(String arn, String certificateBody, String privateKey, String certificateChain) {}+/**- * Runs a write that records an IAM server certificate while IAM holds the lock- * {@code DeleteServerCertificate} takes, so the certificate cannot be deleted between the- * check and the write. A caller re-checks inside the action: a check made before the lock- * says nothing about the moment of the write, while one made outside it keeps the error- * precedence AWS has.- *- * <p>Only for a write that names an IAM certificate. One naming no certificate, or an ACM- * certificate, cannot leave a referrer holding a deleted IAM certificate, and taking the lock- * for every write would make a certificate delete wait on writes that cannot affect it.+ * Reads a published reference in its owner's account. IAM retains former ARNs after a rename,+ * so an existing reference keeps its certificate while new references still pass through+ * {@link #exists}. The returned strings are snapshots; background socket callbacks must not+ * repeat an account-sensitive lookup after the request context has ended.*/+ public CertificateMaterial publishedMaterial(String ownerArn, String region, String certificateArn) {+ AwsArnUtils.Arn owner = AwsArnUtils.parse(ownerArn);+ AwsArnUtils.Arn certificate = AwsArnUtils.parse(certificateArn);+ if (owner.accountId().isBlank() || !owner.accountId().equals(certificate.accountId())+ || !owner.partition().equals(certificate.partition())) {+ throw missingCertificate();+ }+ return RequestScopes.callAs(owner.accountId(), region, () -> {+ if ("iam".equals(certificate.service()) && iamService != null) {+ return iamService.supplyWithServerCertificatesHeld(() -> {+ ServerCertificate stored = iamServerCertificate(certificate, certificateArn)+ .orElseGet(() -> iamService.listServerCertificates(null).stream()+ .filter(value -> value.getFormerArns().contains(certificateArn))+ .findFirst().orElseThrow(CertificateReferenceResolver::missingCertificate));+ return new CertificateMaterial(certificateArn, stored.getCertificateBody(),+ stored.getPrivateKey(), stored.getCertificateChain());+ });+ }+ if ("acm".equals(certificate.service()) && acmService != null && region.equals(certificate.region())) {+ return acmService.supplyWithCertificatesHeld(() -> {+ try {+ Certificate stored = acmService.getCertificate(certificateArn, region);+ if (!certificateArn.equals(stored.getArn()) || stored.getStatus() != CertificateStatus.ISSUED) {+ throw missingCertificate();+ }+ return new CertificateMaterial(certificateArn, stored.getCertificateBody(),+ stored.getPrivateKey(), stored.getCertificateChain());+ } catch (AwsException failure) {+ if ("ResourceNotFoundException".equals(failure.getErrorCode())) {+ throw missingCertificate();+ }+ throw failure;+ }+ });+ }+ throw missingCertificate();+ });+ }++ private static AwsException missingCertificate() {+ return new AwsException("CertificateNotFound", "The specified certificate does not exist.", 400);+ }++ /** Runs reference publication under IAM then ACM guards for the complete effective list. */public void runWhileHeld(Collection<String> certificateArns, Runnable action) {- if (iamService == null || !namesIamCertificate(certificateArns)) {+ supplyWhileHeld(certificateArns, () -> {action.run();- return;+ return null;+ });+ }++ public <T> T supplyWhileHeld(Collection<String> certificateArns, Supplier<T> action) {+ Supplier<T> acmGuard = () -> acmService != null && namesCertificateService(certificateArns, "acm")+ ? acmService.supplyWithCertificatesHeld(action) : action.get();+ return iamService != null && namesIamCertificate(certificateArns)+ ? iamService.supplyWithServerCertificatesHeld(acmGuard) : acmGuard.get();+ }++ /** ELB usability is narrower than existence, which other consumers also query. */+ public boolean isUsableAcmCertificate(String region, String certificateArn) {+ if (certificateArn == null || !AwsArnUtils.isArn(certificateArn)+ || !"acm".equals(AwsArnUtils.parse(certificateArn).service()) || acmService == null) {+ return true;+ }+ try {+ return acmService.supplyWithCertificatesHeld(() -> {+ Certificate certificate = acmService.getCertificate(certificateArn, region);+ return certificateArn.equals(certificate.getArn()) && certificate.getStatus() == CertificateStatus.ISSUED;+ });+ } catch (AwsException failure) {+ if ("ResourceNotFoundException".equals(failure.getErrorCode())) {+ return false;+ }+ throw failure;}- iamService.runWithServerCertificatesHeld(action);+ }++ private boolean namesCertificateService(Collection<String> arns, String service) {+ return arns != null && arns.stream().anyMatch(arn -> arn != null && AwsArnUtils.isArn(arn)+ && service.equals(AwsArnUtils.parse(arn).service()));}/** Whether any of these ARNs names a certificate IAM serves, rather than ACM. */diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmCertificateReferenceProvider.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmCertificateReferenceProvider.javanew file mode 100644index 0000000000..a5bf80e6ef--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmCertificateReferenceProvider.java@@ -0,0 +1,15 @@+package io.github.hectorvent.floci.services.acm;++import java.util.List;++/** Live references and material refreshes for consumers of ACM certificates. */+public interface AcmCertificateReferenceProvider {++ record CertificateReference(String certificateArn, String resourceArn) {}++ /** Reads recorded references without certificate lookups or consumer locks. */+ List<CertificateReference> acmCertificateReferences();++ /** Called after an import commits and releases the ACM write guard. */+ void certificateReimported(String certificateArn, String region);+}diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.javaindex 60a9d27dd8..1582ce8b7f 100644--- a/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java@@ -161,10 +161,11 @@ public class AcmJsonHandler {ListResult result = service.listCertificates(statuses, keyTypes, region, maxItems, nextToken);+ Map<String, List<String>> consumers = service.certificateInUseBy(result.certificates());ObjectNode response = objectMapper.createObjectNode();ArrayNode summaryList = objectMapper.createArrayNode();for (Certificate cert : result.certificates()) {- summaryList.add(buildCertificateSummary(cert));+ summaryList.add(buildCertificateSummary(cert, consumers.get(cert.getArn())));}response.set("CertificateSummaryList", summaryList);if (result.nextToken() != null) {@@ -400,9 +401,7 @@ public class AcmJsonHandler {}ArrayNode inUseBy = objectMapper.createArrayNode();- if (cert.getInUseBy() != null) {- cert.getInUseBy().forEach(inUseBy::add);- }+ service.certificateInUseBy(cert).forEach(inUseBy::add);node.set("InUseBy", inUseBy);if (cert.getDomainValidationOptions() != null && !cert.getDomainValidationOptions().isEmpty()) {@@ -463,7 +462,7 @@ public class AcmJsonHandler {return node;}- private ObjectNode buildCertificateSummary(Certificate cert) {+ private ObjectNode buildCertificateSummary(Certificate cert, List<String> consumers) {ObjectNode node = objectMapper.createObjectNode();node.put("CertificateArn", cert.getArn());node.put("DomainName", cert.getDomainName());@@ -509,7 +508,7 @@ public class AcmJsonHandler {}node.put("RenewalEligibility", "INELIGIBLE");- node.put("InUse", cert.getInUseBy() != null && !cert.getInUseBy().isEmpty());+ node.put("InUse", !consumers.isEmpty());return node;}diff --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 ee31a1b9fb..241ff0c930 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@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.acm.model.ResourceRecord;import io.github.hectorvent.floci.services.acm.model.RevocationReason;import io.github.hectorvent.floci.services.acm.model.ValidationMethod;import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.inject.Instance;import jakarta.inject.Inject;import org.jboss.logging.Logger;@@ -39,6 +40,7 @@ import java.util.Comparator;import java.util.EnumSet;import java.util.HashMap;import java.util.HashSet;+import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;import java.util.Locale;@@ -50,6 +52,7 @@ import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicInteger;+import java.util.function.Supplier;import java.util.stream.Collectors;/**@@ -72,6 +75,9 @@ public class AcmService implements ResourceProvider {/** Key algorithms real ACM accepts for RequestCertificate; the wider enum stays valid for ImportCertificate. */private static final Set<KeyAlgorithm> REQUESTABLE_KEY_ALGORITHMS =EnumSet.of(KeyAlgorithm.RSA_2048, KeyAlgorithm.EC_prime256v1, KeyAlgorithm.EC_secp384r1);+ @Inject+ Instance<AcmCertificateReferenceProvider> referenceProviders;+private final StorageBackend<String, Certificate> store;private final CertificateGenerator certificateGenerator;private final FlociCertificateAuthority certificateAuthority;@@ -243,7 +249,7 @@ public class AcmService implements ResourceProvider {// ============ DescribeCertificate ============- public Certificate describeCertificate(String certificateArn, String region) {+ public synchronized Certificate describeCertificate(String certificateArn, String region) {Certificate cert = getCertificateByArn(certificateArn, region);// Check for expiration@@ -342,12 +348,13 @@ public class AcmService implements ResourceProvider {// ============ DeleteCertificate ============- public void deleteCertificate(String certificateArn, String region) {+ public synchronized void deleteCertificate(String certificateArn, String region) {Certificate cert = getCertificateByArn(certificateArn, region);- if (cert.getInUseBy() != null && !cert.getInUseBy().isEmpty()) {+ List<String> consumers = certificateInUseBy(certificateArn, region);+ if (!consumers.isEmpty()) {throw new AwsException("ResourceInUseException",- "Certificate " + certificateArn + " is in use by: " + String.join(", ", cert.getInUseBy()), 409);+ "Certificate " + certificateArn + " is in use by: " + String.join(", ", consumers), 409);}String storageKey = regionKey(region, cert.extractCertificateId());@@ -361,7 +368,7 @@ public class AcmService implements ResourceProvider {* 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) {+ public synchronized void addInUseBy(String certificateArn, String consumerArn, String region) {Certificate cert = getCertificateByArn(certificateArn, region);if (!cert.getInUseBy().contains(consumerArn)) {cert.getInUseBy().add(consumerArn);@@ -370,7 +377,7 @@ public class AcmService implements ResourceProvider {}/** Releases {@code consumerArn}. A certificate that no longer exists has nothing to release. */- public void removeInUseBy(String certificateArn, String consumerArn, String region) {+ public synchronized void removeInUseBy(String certificateArn, String consumerArn, String region) {Certificate cert;try {cert = getCertificateByArn(certificateArn, region);@@ -386,6 +393,45 @@ public class AcmService implements ResourceProvider {}}+ /** The same bounded guard protects certificate deletion, reimport and reference publication. */+ public synchronized <T> T supplyWithCertificatesHeld(Supplier<T> action) {+ return action.get();+ }++ /** Detached union of persisted consumers and live references; computed uses are never stored. */+ public synchronized List<String> certificateInUseBy(String certificateArn, String region) {+ return certificateInUseBy(getCertificateByArn(certificateArn, region));+ }++ /** A captured list row remains serializable if it is deleted before response encoding. */+ public synchronized List<String> certificateInUseBy(Certificate certificate) {+ return certificateInUseBy(List.of(certificate)).get(certificate.getArn());+ }++ /** One detached live-reference snapshot for a captured response page, including deleted rows. */+ public synchronized Map<String, List<String>> certificateInUseBy(List<Certificate> certificates) {+ Map<String, Set<String>> consumersByArn = new LinkedHashMap<>();+ for (Certificate certificate : certificates) {+ Set<String> consumers = consumersByArn.computeIfAbsent(certificate.getArn(), key -> new LinkedHashSet<>());+ if (certificate.getInUseBy() != null) {+ consumers.addAll(certificate.getInUseBy());+ }+ }+ if (!consumersByArn.isEmpty() && referenceProviders != null) {+ for (AcmCertificateReferenceProvider provider : referenceProviders) {+ for (AcmCertificateReferenceProvider.CertificateReference reference : provider.acmCertificateReferences()) {+ Set<String> consumers = consumersByArn.get(reference.certificateArn());+ if (consumers != null) {+ consumers.add(reference.resourceArn());+ }+ }+ }+ }+ Map<String, List<String>> snapshot = new LinkedHashMap<>();+ consumersByArn.forEach((arn, consumers) -> snapshot.put(arn, List.copyOf(consumers)));+ return Map.copyOf(snapshot);+ }+// ============ ImportCertificate ============public Certificate importCertificate(String certificatePem, String privateKeyPem, String chainPem,@@ -413,46 +459,54 @@ public class AcmService implements ResourceProvider {validateTags(tags);}- String certId;- String arn;-- if (existingArn != null && !existingArn.isEmpty()) {- // Re-import- Certificate existing = getCertificateByArn(existingArn, region);- certId = existing.extractCertificateId();- arn = existingArn;- } else {- certId = UUID.randomUUID().toString();- arn = buildCertificateArn(region, certId);+ Certificate cert;+ synchronized (this) {+ Certificate existing = existingArn != null && !existingArn.isEmpty()+ ? getCertificateByArn(existingArn, region) : null;+ String certId = existing == null ? UUID.randomUUID().toString() : existing.extractCertificateId();+ String arn = existing == null ? buildCertificateArn(region, certId) : existingArn;++ Instant now = Instant.now();+ KeyAlgorithm keyAlg = certificateGenerator.detectKeyAlgorithm(x509Cert.getPublicKey());++ cert = new Certificate();+ cert.setArn(arn);+ cert.setDomainName(extractCommonName(x509Cert));+ cert.setStatus(CertificateStatus.ISSUED);+ cert.setType(CertificateType.IMPORTED);+ cert.setCreatedAt(existingArn == null ? now : null);+ cert.setImportedAt(now);+ cert.setIssuedAt(now);+ cert.setNotBefore(x509Cert.getNotBefore().toInstant());+ cert.setNotAfter(x509Cert.getNotAfter().toInstant());+ cert.setSerial(CertificateGenerator.colonHex(x509Cert.getSerialNumber()));+ cert.setSubject(x509Cert.getSubjectX500Principal().getName());+ cert.setIssuer(x509Cert.getIssuerX500Principal().getName());+ cert.setKeyAlgorithm(keyAlg);+ cert.setSignatureAlgorithm(x509Cert.getSigAlgName().toUpperCase(Locale.ROOT));+ cert.setCertificateBody(certificatePem);+ cert.setPrivateKey(privateKeyPem);+ cert.setCertificateChain(chainPem);+ cert.setTags(tags != null ? new HashMap<>(tags) : new HashMap<>());++ String storageKey = regionKey(region, certId);+ if (existing != null && existing.getInUseBy() != null) {+ cert.setInUseBy(new ArrayList<>(existing.getInUseBy()));+ }+ store.put(storageKey, cert);+ }+ // A consumer may acquire IAM before ACM; never invoke it while holding this guard.+ if (existingArn != null && !existingArn.isEmpty() && referenceProviders != null) {+ for (AcmCertificateReferenceProvider provider : referenceProviders) {+ try {+ provider.certificateReimported(cert.getArn(), region);+ } catch (RuntimeException failure) {+ LOG.warnv("ACM consumer refresh failed for {0} ({1}: {2}); an identical update can retry",+ cert.getArn(), failure.getClass().getSimpleName(), failure.getMessage());+ }+ }}-- Instant now = Instant.now();- KeyAlgorithm keyAlg = certificateGenerator.detectKeyAlgorithm(x509Cert.getPublicKey());-- Certificate cert = new Certificate();- cert.setArn(arn);- cert.setDomainName(extractCommonName(x509Cert));- cert.setStatus(CertificateStatus.ISSUED);- cert.setType(CertificateType.IMPORTED);- cert.setCreatedAt(existingArn == null ? now : null);- cert.setImportedAt(now);- cert.setIssuedAt(now);- cert.setNotBefore(x509Cert.getNotBefore().toInstant());- cert.setNotAfter(x509Cert.getNotAfter().toInstant());- cert.setSerial(CertificateGenerator.colonHex(x509Cert.getSerialNumber()));- cert.setSubject(x509Cert.getSubjectX500Principal().getName());- cert.setIssuer(x509Cert.getIssuerX500Principal().getName());- cert.setKeyAlgorithm(keyAlg);- cert.setSignatureAlgorithm(x509Cert.getSigAlgName().toUpperCase(Locale.ROOT));- cert.setCertificateBody(certificatePem);- cert.setPrivateKey(privateKeyPem);- cert.setCertificateChain(chainPem);- cert.setTags(tags != null ? new HashMap<>(tags) : new HashMap<>());-- String storageKey = regionKey(region, certId);- store.put(storageKey, cert);-- LOG.infov("Imported certificate: {0}", arn);+ LOG.infov("Imported certificate: {0}", cert.getArn());return cert;}@@ -490,7 +544,7 @@ public class AcmService implements ResourceProvider {// ============ Tagging Operations ============- public void addTagsToCertificate(String certificateArn, Map<String, String> tags, String region) {+ public synchronized void addTagsToCertificate(String certificateArn, Map<String, String> tags, String region) {Certificate cert = getCertificateByArn(certificateArn, region);validateTags(tags);@@ -511,7 +565,7 @@ public class AcmService implements ResourceProvider {return cert.getTags() != null ? new HashMap<>(cert.getTags()) : new HashMap<>();}- public void removeTagsFromCertificate(String certificateArn, List<Map<String, String>> tagSpecs, String region) {+ public synchronized void removeTagsFromCertificate(String certificateArn, List<Map<String, String>> tagSpecs, String region) {Certificate cert = getCertificateByArn(certificateArn, region);Map<String, String> currentTags = cert.getTags() != null ? new HashMap<>(cert.getTags()) : new HashMap<>();@@ -572,19 +626,23 @@ public class AcmService implements ResourceProvider {return Set.of(new SupportedResourceType("acm:certificate", "acm", true));}- public Certificate revokeCertificate(String certificateArn, RevocationReason reason, String region) {+ public synchronized Certificate revokeCertificate(String certificateArn, RevocationReason reason, String region) {Certificate cert = getCertificateByArn(certificateArn, region);boolean exportEnabled = cert.getCertOptions() != null && "ENABLED".equals(cert.getCertOptions().export());if (!exportEnabled) {throw new AwsException("ValidationException","Certificate " + certificateArn + " cannot be revoked because it is not export-enabled.", 400);}+ if (!certificateInUseBy(cert).isEmpty()) {+ throw new AwsException("ResourceInUseException",+ "Certificate " + certificateArn + " is in use by another service.", 400);+ }cert.setStatus(CertificateStatus.REVOKED);store.put(regionKey(region, cert.extractCertificateId()), cert);return cert;}- public Certificate renewCertificate(String certificateArn, String region) {+ public synchronized Certificate renewCertificate(String certificateArn, String region) {Certificate cert = getCertificateByArn(certificateArn, region);if (cert.getStatus() == CertificateStatus.PENDING_VALIDATION) {throw new AwsException("RequestInProgressException", "Certificate is pending validation", 400);@@ -601,7 +659,7 @@ public class AcmService implements ResourceProvider {return cert;}- public void updateCertificateOptions(String certificateArn, CertificateOptions options, String region) {+ public synchronized void updateCertificateOptions(String certificateArn, CertificateOptions options, String region) {Certificate cert = getCertificateByArn(certificateArn, region);CertificateOptions current = cert.getCertOptions() != null? cert.getCertOptions() : CertificateOptions.defaultOptions();@@ -615,7 +673,7 @@ public class AcmService implements ResourceProvider {// ============ Helper Methods ============- private Certificate getCertificateByArn(String arn, String region) {+ private synchronized Certificate getCertificateByArn(String arn, String region) {String certId = extractCertificateIdFromArn(arn);String storageKey = regionKey(region, certId);@@ -633,7 +691,13 @@ public class AcmService implements ResourceProvider {* with pending entries. A certificate revoked before it was ever issued keeps its pending* entries. Changes are stored, which is what a client polling ACM observes.*/- private Certificate settleValidation(Certificate cert, String region) {+ private synchronized Certificate settleValidation(Certificate cert, String region) {+ // A list scan may have captured a row before reimport or deletion acquired this guard.+ Certificate current = store.get(regionKey(region, cert.extractCertificateId())).orElse(null);+ if (current == null) {+ return cert;+ }+ cert = current;boolean changed = false;if (cert.getStatus() == CertificateStatus.PENDING_VALIDATION && cert.getCreatedAt() != null&& !Instant.now().isBefore(cert.getCreatedAt().plusSeconds(validationWaitSeconds))) {diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2AcmCertificateReferences.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2AcmCertificateReferences.javanew file mode 100644index 0000000000..b867260536--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2AcmCertificateReferences.java@@ -0,0 +1,28 @@+package io.github.hectorvent.floci.services.elbv2;++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 ElbV2AcmCertificateReferences implements AcmCertificateReferenceProvider {+ private final ElbV2Service service;++ @Inject+ public ElbV2AcmCertificateReferences(ElbV2Service service) {+ this.service = service;+ }++ @Override+ public List<CertificateReference> acmCertificateReferences() {+ return service.acmCertificateReferences();+ }++ @Override+ public void certificateReimported(String certificateArn, String region) {+ service.certificateReimported(certificateArn, region);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.javaindex 5dab19bc89..21847518fa 100644--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java@@ -4,6 +4,9 @@ import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.config.TlsProxyServer;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;+import io.github.hectorvent.floci.core.common.Pem;import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.services.elbv2.model.Action;import io.github.hectorvent.floci.services.elbv2.model.Listener;@@ -15,6 +18,7 @@ import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;import io.github.hectorvent.floci.services.lambda.LambdaService;import io.github.hectorvent.floci.services.lambda.model.InvocationType;import io.github.hectorvent.floci.services.lambda.model.InvokeResult;+import io.vertx.core.Future;import io.vertx.core.MultiMap;import io.vertx.core.Vertx;import io.vertx.core.buffer.Buffer;@@ -28,28 +32,48 @@ import io.vertx.core.http.HttpServerResponse;import io.vertx.core.http.HttpVersion;import io.vertx.core.http.RequestOptions;import io.vertx.core.net.NetSocket;+import io.vertx.core.net.PemKeyCertOptions;+import io.vertx.core.net.SSLOptions;import jakarta.annotation.PostConstruct;import jakarta.annotation.PreDestroy;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;+import javax.naming.InvalidNameException;+import javax.naming.ldap.LdapName;+import javax.naming.ldap.Rdn;++import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.nio.charset.StandardCharsets;+import java.security.cert.CertificateException;+import java.security.cert.CertificateFactory;+import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.Base64;+import java.util.Collection;import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.Objects;+import java.util.Set;import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.ConcurrentMap;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.atomic.AtomicReference;+import java.util.function.BooleanSupplier;+import java.util.function.Function;+import java.util.function.Supplier;import java.util.regex.Pattern;import java.util.stream.Collectors;+import java.util.stream.Stream;@ApplicationScopedpublic class ElbV2DataPlane {@@ -85,14 +109,80 @@ public class ElbV2DataPlane {@InjectEc2Service ec2Service;+ @Inject+ CertificateReferenceResolver certificateResolver;+@InjectObjectMapper objectMapper;private final Map<Integer, HttpServer> servers = new ConcurrentHashMap<>();+ private final Map<Integer, PortState> portStates = new ConcurrentHashMap<>();+ private volatile boolean stopping;++ private static final class PortState {+ private int depth;+ private int closing;+ private long generation;+ private volatile RoutingView routing = new RoutingView(Map.of(), Map.of());+ }++ private <T> T onPort(int port, Function<PortState, T> operation) {+ while (true) {+ PortState state = portStates.computeIfAbsent(port, ignored -> new PortState());+ synchronized (state) {+ if (portStates.get(port) != state) {+ continue;+ }+ state.depth++;+ try {+ return operation.apply(state);+ } finally {+ if (state.depth == 1) {+ refreshRouting(port, state);+ }+ state.depth--;+ retirePortState(port, state);+ }+ }+ }+ }++ private <T> T onPorts(List<Integer> ports, int index, Supplier<T> operation) {+ if (index == ports.size()) {+ return operation.get();+ }+ return onPort(ports.get(index), state -> onPorts(ports, index + 1, operation));+ }++ private void onCurrentPort(int port, PortState state, Runnable operation) {+ synchronized (state) {+ if (stopping || portStates.get(port) != state) {+ return;+ }+ state.depth++;+ try {+ operation.run();+ } finally {+ if (state.depth == 1) {+ refreshRouting(port, state);+ }+ state.depth--;+ retirePortState(port, state);+ }+ }+ }++ private void retirePortState(int port, PortState state) {+ if (state.depth == 0 && state.closing == 0 && !servers.containsKey(port)+ && !listenersByHostAndPort.containsKey(port)) {+ portStates.remove(port, state);+ }+ }+private final java.util.concurrent.atomic.AtomicBoolean releaseHandlerRegistered =new java.util.concurrent.atomic.AtomicBoolean();private final Map<Integer, Map<String, String>> listenersByHostAndPort = new ConcurrentHashMap<>();- private final Map<String, ListenerBinding> listenerBindings = new ConcurrentHashMap<>();+ private final ConcurrentMap<String, ListenerBinding> listenerBindings;private final Map<String, AtomicReference<List<CompiledRule>>> ruleChains = new ConcurrentHashMap<>();private final Map<String, AtomicInteger> rrCounters = new ConcurrentHashMap<>();private final Map<String, String> listenerRegions = new ConcurrentHashMap<>();@@ -100,7 +190,16 @@ public class ElbV2DataPlane {private HttpClient proxyClient;- private record ListenerBinding(int port, String host, String loadBalancerArn) {}+ public ElbV2DataPlane() {+ this(new ConcurrentHashMap<>());+ }++ ElbV2DataPlane(ConcurrentMap<String, ListenerBinding> listenerBindings) {+ this.listenerBindings = listenerBindings;+ }++ record ListenerBinding(int port, String host, String loadBalancerArn,+ boolean secure, Set<String> certificateHosts, List<CertificateMaterial> certificates) {}@PostConstructvoid init() {@@ -112,9 +211,16 @@ public class ElbV2DataPlane {@PreDestroyvoid shutdown() {- for (Map.Entry<Integer, HttpServer> e : servers.entrySet()) {- e.getValue().close();+ stopping = true;+ for (Map.Entry<Integer, PortState> entry : portStates.entrySet()) {+ synchronized (entry.getValue()) {+ HttpServer server = servers.remove(entry.getKey());+ if (server != null) {+ server.close();+ }+ }}+ portStates.clear();servers.clear();listenersByHostAndPort.clear();listenerBindings.clear();@@ -123,68 +229,167 @@ public class ElbV2DataPlane {listenerRegions.clear();}- public void startListener(Listener listener, String region, List<Rule> rules) {- if (config.services().elbv2().mock()) {- return;+ boolean publishListener(Listener listener, String region, Integer previousPort,+ BooleanSupplier publication, Supplier<List<Rule>> rules,+ Function<Supplier<Boolean>, Boolean> admission) {+ boolean live = !config.services().elbv2().mock() && !stopping && listener.getPort() != null;+ // Certificate ownership and material resolution must precede every port gate.+ ListenerBinding prepared = live ? binding(listener, region) : null;+ String arn = listener.getListenerArn();+ ListenerBinding expected = listenerBindings.get(arn);+ Integer runtimePort = expected == null ? previousPort : Integer.valueOf(expected.port());+ List<Integer> ports = Stream.of(previousPort, runtimePort, listener.getPort())+ .filter(Objects::nonNull).distinct().sorted().toList();+ boolean applied = admission.apply(() -> {+ // Recheck snapshots under the certificate guards, before taking any port gate.+ if (prepared != null) {+ for (CertificateMaterial material : prepared.certificates()) {+ if (!material.equals(certificateResolver.publishedMaterial(arn, region, material.arn()))) {+ return false;+ }+ }+ }+ return onPorts(ports, 0, () -> {+ if (listenerBindings.get(arn) != expected) {+ return false;+ }+ if (!live) {+ return publication.getAsBoolean();+ }+ return installBinding(arn, expected, prepared, region,+ () -> compileRules(rules.get()), publication, true);+ });+ });+ if (applied && live && !stopping) {+ ensureReleaseHandlerRegistered();+ onPort(prepared.port(), state -> {+ if (!stopping && listenerBindings.containsKey(arn)) {+ ensurePortServer(prepared.port());+ }+ return null;+ });}- String listenerArn = listener.getListenerArn();- List<CompiledRule> compiled = compileRules(rules);- ruleChains.put(listenerArn, new AtomicReference<>(compiled));- listenerRegions.put(listenerArn, region);- ListenerBinding binding = binding(listener, region);- listenerBindings.put(listenerArn, binding);- Map<String, String> listenersOnPort =- listenersByHostAndPort.computeIfAbsent(binding.port(), ignored -> new ConcurrentHashMap<>());- warnOnSharedPort(binding, listenersOnPort);- listenersOnPort.put(binding.host(), listenerArn);- ensureReleaseHandlerRegistered();- servers.computeIfAbsent(binding.port(), this::startPortServer);+ return applied;}- public void restartListener(Listener listener, String region, List<Rule> rules) {- if (config.services().elbv2().mock()) {- return;+ boolean updateListener(Integer storedPort, BooleanSupplier publication) {+ return storedPort == null ? publication.getAsBoolean()+ : onPort(storedPort, state -> publication.getAsBoolean());+ }++ boolean removeListener(String arn, Integer storedPort, BooleanSupplier publication) {+ ListenerBinding expected = listenerBindings.get(arn);+ Integer runtimePort = expected == null ? storedPort : Integer.valueOf(expected.port());+ List<Integer> ports = Stream.of(storedPort, runtimePort).filter(Objects::nonNull).distinct().sorted().toList();+ return onPorts(ports, 0, () -> {+ if (listenerBindings.get(arn) != expected || !publication.getAsBoolean()) {+ return false;+ }+ if (expected != null) {+ ruleChains.remove(arn);+ listenerRegions.remove(arn);+ listenerBindings.remove(arn, expected);+ removePortBinding(arn, expected);+ }+ return true;+ });+ }++ private boolean installBinding(String arn, ListenerBinding expected, ListenerBinding prepared,+ String region, Supplier<List<CompiledRule>> compiled,+ BooleanSupplier publication, boolean preserveRules) {+ if (stopping) {+ return publication.getAsBoolean();}- String listenerArn = listener.getListenerArn();- ListenerBinding newBinding = binding(listener, region);- ListenerBinding oldBinding = listenerBindings.get(listenerArn);- if (newBinding.equals(oldBinding)) {- ruleChains.put(listenerArn, new AtomicReference<>(compileRules(rules)));- listenerRegions.put(listenerArn, region);- listenersByHostAndPort.computeIfAbsent(newBinding.port(), ignored -> new ConcurrentHashMap<>())- .put(newBinding.host(), listenerArn);- ensureReleaseHandlerRegistered();- servers.computeIfAbsent(newBinding.port(), this::startPortServer);- return;+ if (listenerBindings.get(arn) != expected) {+ return false;}- oldBinding = listenerBindings.remove(listenerArn);- if (oldBinding != null) {- Map<String, String> listenersByHost = listenersByHostAndPort.get(oldBinding.port());- if (listenersByHost != null) {- listenersByHost.remove(oldBinding.host(), listenerArn);- closePortServerIfUnused(oldBinding.port(), listenersByHost);+ requireCompatiblePort(prepared, arn);+ boolean claimed = expected == null+ ? listenerBindings.putIfAbsent(arn, prepared) == null+ : listenerBindings.replace(arn, expected, prepared);+ if (!claimed) {+ return false;+ }+ try {+ if (!publication.getAsBoolean()) {+ restoreReservation(arn, expected, prepared);+ return false;+ }+ } catch (RuntimeException failure) {+ restoreReservation(arn, expected, prepared);+ throw failure;+ }+ if (expected != null) {+ removeHostBindings(arn, expected);+ if (expected.port() != prepared.port()) {+ removePortBinding(arn, expected);+ }+ }+ publishBinding(arn, prepared);+ if (preserveRules) {+ ruleChains.computeIfAbsent(arn, ignored -> new AtomicReference<>(compiled.get()));+ } else {+ ruleChains.put(arn, new AtomicReference<>(compiled.get()));+ }+ listenerRegions.put(arn, region);+ Map<String, String> peers = listenersByHostAndPort.computeIfAbsent(+ prepared.port(), ignored -> new ConcurrentHashMap<>());+ warnOnSharedPort(prepared, peers);+ addHostBindings(arn, prepared);+ if (expected != null && expected.port() == prepared.port() && expected.secure() != prepared.secure()) {+ restartPortServer(prepared.port());+ } else {+ HttpServer server = servers.get(prepared.port());+ if (server == null) {+ ensurePortServer(prepared.port());+ } else if (prepared.secure()) {+ refreshTlsOptions(prepared.port(), server);}}- startListener(listener, region, rules);+ return true;+ }++ private void restoreReservation(String arn, ListenerBinding expected, ListenerBinding prepared) {+ if (expected == null) {+ listenerBindings.remove(arn, prepared);+ } else {+ listenerBindings.replace(arn, prepared, expected);+ }}- public void stopListener(String listenerArn) {- ListenerBinding binding = listenerBindings.remove(listenerArn);- if (binding != null) {- Map<String, String> listenersByHost = listenersByHostAndPort.get(binding.port());- if (listenersByHost != null) {- listenersByHost.remove(binding.host(), listenerArn);- closePortServerIfUnused(binding.port(), listenersByHost);+ private void removePortBinding(String listenerArn, ListenerBinding binding) {+ removeHostBindings(listenerArn, binding);+ Map<String, String> listenersByHost = listenersByHostAndPort.get(binding.port());+ if (listenersByHost == null || listenersByHost.isEmpty()) {+ closePortServerIfUnused(binding.port(), listenersByHost);+ } else if (binding.secure()) {+ HttpServer server = servers.get(binding.port());+ if (server != null) {+ refreshTlsOptions(binding.port(), server);}}- ruleChains.remove(listenerArn);- listenerRegions.remove(listenerArn);}- public void recompileRules(String listenerArn, List<Rule> rules) {- AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);- if (ref != null) {- ref.set(compileRules(rules));+ public void recompileRules(String listenerArn, Supplier<List<Rule>> rules) {+ while (!stopping) {+ ListenerBinding expected = listenerBindings.get(listenerArn);+ if (expected == null) {+ return;+ }+ boolean applied = onPort(expected.port(), state -> {+ if (listenerBindings.get(listenerArn) != expected) {+ return false;+ }+ AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);+ if (ref != null) {+ ref.set(compileRules(rules.get()));+ }+ return true;+ });+ if (applied) {+ return;+ }}}@@ -219,8 +424,13 @@ public class ElbV2DataPlane {* would ever retry the listener, leaving it registered with no data plane and the port free.*/private void bindListenersWaitingOn(int port) {- if (listenersByHostAndPort.containsKey(port)) {- servers.computeIfAbsent(port, this::startPortServer);+ PortState state = portStates.get(port);+ if (state != null) {+ onCurrentPort(port, state, () -> {+ if (listenersByHostAndPort.containsKey(port)) {+ ensurePortServer(port);+ }+ });}}@@ -241,7 +451,15 @@ public class ElbV2DataPlane {}}- private HttpServer startPortServer(int port) {+ private void ensurePortServer(int port) {+ PortState state = portStates.get(port);+ if (!stopping && state != null && state.closing == 0 && !servers.containsKey(port)+ && listenersByHostAndPort.containsKey(port)) {+ startPortServer(port, state);+ }+ }++ private void startPortServer(int port, PortState state) {if (isReservedByFloci(port)) {// Returning null leaves `servers` untouched: computeIfAbsent skips a null mapping.// The emulator's own port cannot be handed over, so the two cases need different@@ -251,43 +469,68 @@ public class ElbV2DataPlane {: "Set floci.tls.aws-https-port=0 (or disable TLS) to free it.";LOG.warnv("ELBv2 listener port {0} is reserved by Floci itself; the listener is "+ "registered but serves no traffic. {1}", String.valueOf(port), remedy);- return null;+ return;}- HttpServer server = vertx.createHttpServer(new HttpServerOptions()+ boolean secure = portIsSecure(port);+ HttpServerOptions options = new HttpServerOptions().setHost("0.0.0.0")- .setPort(port));- server.requestHandler(req -> handleRequest(req, port));- server.listen()- .onSuccess(s -> LOG.infov("ELBv2 listener port started on {0}", String.valueOf(port)))- .onFailure(err -> {- servers.remove(port);- clearPortBindings(port);- server.close();- LOG.warnv("ELBv2 listener port failed to start on {0}: {1}", String.valueOf(port), err.getMessage());- });- return server;+ .setPort(port);+ if (secure) {+ options.setSsl(true)+ .setSni(true)+ .setPemKeyCertOptions(tlsKeyCertOptions(port));+ }+ HttpServer server = vertx.createHttpServer(options);+ long generation = ++state.generation;+ servers.put(port, server);+ try {+ server.requestHandler(req -> handleRequest(req, port));+ server.listen()+ .onSuccess(s -> LOG.infov("ELBv2 {0} listener port started on {1}",+ secure ? "HTTPS" : "HTTP", String.valueOf(port)))+ .onFailure(err -> onCurrentPort(port, state, () -> {+ if (state.generation == generation && servers.remove(port, server)) {+ clearPortBindings(port);+ closeOwnedServer(port, state, server);+ } else {+ server.close();+ }+ LOG.warnv("ELBv2 listener port failed to start on {0}: {1}",+ String.valueOf(port), err.getMessage());+ }));+ } catch (RuntimeException failure) {+ if (state.generation == generation && servers.remove(port, server)) {+ clearPortBindings(port);+ try {+ closeOwnedServer(port, state, server);+ } catch (RuntimeException cleanupFailure) {+ failure.addSuppressed(cleanupFailure);+ }+ }+ throw failure;+ }}private void closePortServerIfUnused(int port, Map<String, String> listenersByHost) {- if (!listenersByHost.isEmpty()) {+ if (listenersByHost != null && !listenersByHost.isEmpty()) {return;}- listenersByHostAndPort.remove(port, listenersByHost);- HttpServer server = servers.remove(port);- if (server != null) {- server.close();+ if (listenersByHost != null) {+ listenersByHostAndPort.remove(port, listenersByHost);}+ restartPortServer(port);}private void clearPortBindings(int port) {- Map<String, String> listenersByHost = listenersByHostAndPort.remove(port);- if (listenersByHost == null) {- return;- }- for (String listenerArn : listenersByHost.values()) {- listenerBindings.remove(listenerArn);- ruleChains.remove(listenerArn);- listenerRegions.remove(listenerArn);+ listenersByHostAndPort.remove(port);+ for (Map.Entry<String, ListenerBinding> entry : listenerBindings.entrySet()) {+ if (entry.getValue().port() == port) {+ // Retain the old binding claim until its metadata is gone. A publisher on+ // another port cannot install the same listener's new metadata in between.+ ruleChains.remove(entry.getKey());+ listenerRegions.remove(entry.getKey());+ listenerBindings.remove(entry.getKey(), entry.getValue());+ }}}@@ -314,93 +557,279 @@ public class ElbV2DataPlane {}}+ private void publishBinding(String listenerArn, ListenerBinding binding) {+ listenerBindings.put(listenerArn, binding);+ if (!binding.secure()) {+ return;+ }+ Map<String, CertificateMaterial> current = new LinkedHashMap<>();+ for (CertificateMaterial certificate : binding.certificates()) {+ current.put(certificate.arn(), certificate);+ }+ listenerBindings.replaceAll((peerArn, peer) -> {+ if (peer.port() != binding.port() || !peer.secure()) {+ return peer;+ }+ List<CertificateMaterial> material = new ArrayList<>();+ Set<String> hosts = new LinkedHashSet<>();+ for (CertificateMaterial certificate : peer.certificates()) {+ CertificateMaterial replacement = current.getOrDefault(certificate.arn(), certificate);+ material.add(replacement);+ addCertificateHosts(hosts, replacement);+ }+ return new ListenerBinding(peer.port(), peer.host(), peer.loadBalancerArn(), true,+ Set.copyOf(hosts), List.copyOf(material));+ });+ }+private ListenerBinding binding(Listener listener, String region) {LoadBalancer loadBalancer = elbV2Service.getLoadBalancer(region, listener.getLoadBalancerArn());String host = loadBalancer != null ? normalizeHost(loadBalancer.getDnsName()) : listener.getLoadBalancerArn();- return new ListenerBinding(listener.getPort(), host, listener.getLoadBalancerArn());+ boolean secure = "HTTPS".equalsIgnoreCase(listener.getProtocol());+ Set<String> hosts = new LinkedHashSet<>();+ List<CertificateMaterial> certificates = new ArrayList<>();+ if (secure) {+ if (listener.getCertificates() == null || listener.getCertificates().isEmpty()) {+ throw new IllegalStateException("HTTPS listener has no default certificate");+ }+ for (String certificateArn : listener.getCertificates()) {+ CertificateMaterial certificate = certificateResolver.publishedMaterial(+ listener.getListenerArn(), region, certificateArn);+ try {+ if (!Pem.isPair(Pem.parsePrivateKey(certificate.privateKey()),+ Pem.parseCertificate(certificate.certificateBody()).getPublicKey())) {+ throw new IllegalArgumentException("Certificate and private key do not match");+ }+ } catch (Exception failure) {+ throw new IllegalStateException("Certificate " + certificateArn + " has unusable TLS material", failure);+ }+ certificates.add(certificate);+ addCertificateHosts(hosts, certificate);+ }+ }+ return new ListenerBinding(listener.getPort(), host, listener.getLoadBalancerArn(),+ secure, Set.copyOf(hosts), List.copyOf(certificates));}- private void handleRequest(io.vertx.core.http.HttpServerRequest req, int port) {- String listenerArn = resolveListenerArn(port, req.host());- if (listenerArn == null) {- req.response().setStatusCode(502).end("No listener for host");+ public void requireCompatibleListenerProtocol(String listenerArn, int port, String protocol) {+ if (config.services().elbv2().mock()) {return;}- String region = listenerRegions.get(listenerArn);- if (region == null) {- req.response().setStatusCode(502).end("No listener region");- return;+ onPort(port, state -> {+ requireCompatiblePort(port, "HTTPS".equalsIgnoreCase(protocol), listenerArn);+ return null;+ });+ }++ private void requireCompatiblePort(ListenerBinding binding, String listenerArn) {+ requireCompatiblePort(binding.port(), binding.secure(), listenerArn);+ }++ private void requireCompatiblePort(int port, boolean secure, String listenerArn) {+ for (Map.Entry<String, ListenerBinding> entry : listenerBindings.entrySet()) {+ ListenerBinding existing = entry.getValue();+ if (!entry.getKey().equals(listenerArn)+ && existing.port() == port+ && existing.secure() != secure) {+ throw new IncompatibleListenerProtocolException(port);+ }+ }+ }++ static final class IncompatibleListenerProtocolException extends IllegalStateException {+ IncompatibleListenerProtocolException(int port) {+ super("ELBv2 listeners sharing port " + port + " must use the same front-end protocol");+ }+ }++ private void addHostBindings(String listenerArn, ListenerBinding binding) {+ listenersByHostAndPort.computeIfAbsent(binding.port(), ignored -> new ConcurrentHashMap<>())+ .put(binding.host(), listenerArn);+ }++ private void removeHostBindings(String listenerArn, ListenerBinding binding) {+ Map<String, String> listenersByHost = listenersByHostAndPort.get(binding.port());+ if (listenersByHost != null) {+ listenersByHost.remove(binding.host(), listenerArn);}- AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);- if (ref == null) {- req.response().setStatusCode(502).end("No rule chain");+ }++ private void refreshTlsOptions(int port, HttpServer server) {+ server.updateSSLOptions(new SSLOptions().setKeyCertOptions(tlsKeyCertOptions(port)), true)+ .onFailure(err -> LOG.warnv("ELBv2 listener TLS certificates failed to refresh on {0}: {1}",+ String.valueOf(port), err.getMessage()));+ }++ private void restartPortServer(int port) {+ PortState state = portStates.get(port);+ HttpServer server = servers.remove(port);+ if (server == null) {+ ensurePortServer(port);return;}- List<CompiledRule> chain = ref.get();- for (CompiledRule compiled : chain) {- if (compiled.matches(req)) {- executeAction(req, compiled.action, region, listenerArn);- return;+ closeOwnedServer(port, state, server);+ }++ private void closeOwnedServer(int port, PortState state, HttpServer server) {+ long generation = ++state.generation;+ state.closing++;+ Future<Void> closed;+ try {+ closed = server.close();+ } catch (RuntimeException failure) {+ state.closing--;+ throw failure;+ }+ closed.onComplete(ignored -> onCurrentPort(port, state, () -> {+ state.closing--;+ if (state.generation == generation) {+ ensurePortServer(port);}- }- req.response().setStatusCode(502).end("No matching rule");+ }));}- /**- * Chooses the listener that serves a request arriving on a shared port.- *- * <p>Real AWS has no such step. Every load balancer gets its own DNS name and addresses, so- * the network picks the load balancer and a {@code host-header} rule only picks a rule inside- * one listener. Floci serves every load balancer from a single socket per port, so the Host- * header has to carry both decisions.- *- * <p>The load balancer's own DNS name wins first. Failing that, a listener whose rules already- * declare the hostname claims it: a deployment that puts two load balancers on port 80 names- * them in host-header conditions anyway, so this reuses what the template already says instead- * of inventing a Floci-only knob. A lone listener on the port still answers anything, so a- * single load balancer needs no hostname at all.- */- private String resolveListenerArn(int port, String hostHeader) {- Map<String, String> listenersByHost = listenersByHostAndPort.get(port);- if (listenersByHost == null || listenersByHost.isEmpty()) {- return null;+ private PemKeyCertOptions tlsKeyCertOptions(int port) {+ Map<String, CertificateMaterial> certificates = new LinkedHashMap<>();+ for (Map.Entry<String, ListenerBinding> entry : listenerBindings.entrySet()) {+ ListenerBinding binding = entry.getValue();+ if (binding.port() != port || !binding.secure()) {+ continue;+ }+ for (CertificateMaterial certificate : binding.certificates()) {+ certificates.putIfAbsent(certificate.arn(), certificate);+ }}- String host = normalizeHost(hostHeader);- String listenerArn = listenersByHost.get(host);- if (listenerArn != null) {- return listenerArn;- }- List<String> declaring = listenersDeclaringHost(listenersByHost, host);- if (declaring.size() == 1) {- return declaring.get(0);- }- if (declaring.size() > 1) {- LOG.debugv("ELBv2 port {0}: {1} listeners declare Host {2} in a host-header condition, "- + "so none of them can claim it", String.valueOf(port),- String.valueOf(declaring.size()), host);- return null;+ if (certificates.isEmpty()) {+ throw new IllegalStateException("HTTPS listener port " + port + " has no certificate");}- if (listenersByHost.size() == 1) {- return listenersByHost.values().iterator().next();+ PemKeyCertOptions options = new PemKeyCertOptions();+ for (CertificateMaterial certificate : certificates.values()) {+ if (certificate.privateKey() == null || certificate.privateKey().isBlank()+ || certificate.certificateBody() == null || certificate.certificateBody().isBlank()) {+ throw new IllegalStateException("Certificate " + certificate.arn()+ + " does not contain TLS key material");+ }+ options.addKeyValue(Buffer.buffer(certificate.privateKey()));+ options.addCertValue(Buffer.buffer(certificatePemChain(certificate)));}- return null;+ return options;}- private List<String> listenersDeclaringHost(Map<String, String> listenersByHost, String host) {- List<String> declaring = new ArrayList<>();- for (String listenerArn : listenersByHost.values()) {- AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);- if (ref == null) {- continue;+ private boolean portIsSecure(int port) {+ return listenerBindings.values().stream()+ .filter(binding -> binding.port() == port)+ .findFirst()+ .map(ListenerBinding::secure)+ .orElse(false);+ }++ private static String certificatePemChain(CertificateMaterial certificate) {+ String body = certificate.certificateBody().stripTrailing();+ String chain = certificate.certificateChain();+ if (chain == null || chain.isBlank()) {+ return body + "\n";+ }+ try {+ CertificateFactory.getInstance("X.509").generateCertificates(+ new ByteArrayInputStream(chain.getBytes(StandardCharsets.US_ASCII)));+ return body + "\n" + chain.strip() + "\n";+ } catch (CertificateException e) {+ LOG.warnv("Certificate {0} has an invalid optional chain; serving its leaf certificate only",+ certificate.arn());+ return body + "\n";+ }+ }++ private static void addCertificateHosts(Set<String> hosts, CertificateMaterial certificate) {+ X509Certificate leaf = Pem.parseCertificate(certificate.certificateBody());+ try {+ Set<String> leafHosts = new LinkedHashSet<>();+ Collection<List<?>> names = leaf.getSubjectAlternativeNames();+ if (names != null) {+ for (List<?> name : names) {+ if (Integer.valueOf(2).equals(name.get(0)) && name.get(1) instanceof String hostname) {+ leafHosts.add(normalizeHost(hostname));+ }+ }}- for (CompiledRule compiled : ref.get()) {- if (compiled.declaresHost(host)) {- declaring.add(listenerArn);- break;+ if (leafHosts.isEmpty()) {+ for (Rdn name : new LdapName(leaf.getSubjectX500Principal().getName()).getRdns()) {+ if ("CN".equalsIgnoreCase(name.getType())) {+ leafHosts.add(normalizeHost(name.getValue().toString()));+ }}}+ hosts.addAll(leafHosts);+ } catch (CertificateException | InvalidNameException failure) {+ throw new IllegalStateException("Unable to read certificate hostnames", failure);+ }+ }++ private record RoutedListener(String arn, String region, List<CompiledRule> chain, Set<String> certificateHosts) {}++ private record RoutingView(Map<String, String> hosts, Map<String, RoutedListener> listeners) {}++ /** Publishes membership, region and compiled chain together after a coordinated write. */+ private void refreshRouting(int port, PortState state) {+ Map<String, String> hosts = listenersByHostAndPort.getOrDefault(port, Map.of());+ Map<String, RoutedListener> routes = new HashMap<>();+ for (String arn : hosts.values()) {+ ListenerBinding binding = listenerBindings.get(arn);+ AtomicReference<List<CompiledRule>> chain = ruleChains.get(arn);+ String region = listenerRegions.get(arn);+ if (binding != null && binding.port() == port && chain != null && region != null) {+ routes.put(arn, new RoutedListener(arn, region, chain.get(), binding.certificateHosts()));+ }}- return declaring;+ state.routing = new RoutingView(Map.copyOf(hosts), Map.copyOf(routes));+ }++ private void handleRequest(HttpServerRequest req, int port) {+ PortState state = portStates.get(port);+ RoutingView routing = state == null ? null : state.routing;+ RoutedListener listener = routing == null ? null : resolveListener(routing, req.host());+ if (listener == null) {+ req.response().setStatusCode(502).end("No listener for host");+ return;+ }+ for (CompiledRule compiled : listener.chain()) {+ if (compiled.matches(req)) {+ executeAction(req, compiled.action, listener.region(), listener.arn());+ return;+ }+ }+ req.response().setStatusCode(502).end("No matching rule");+ }++ /** Floci's shared socket first uses load-balancer DNS, then unique rule or certificate hosts. */+ private RoutedListener resolveListener(RoutingView routing, String hostHeader) {+ String host = normalizeHost(hostHeader);+ String direct = routing.hosts().get(host);+ if (direct != null) {+ return routing.listeners().get(direct);+ }+ List<RoutedListener> declaring = routing.listeners().values().stream()+ .filter(listener -> listener.chain().stream().anyMatch(rule -> rule.declaresHost(host)))+ .toList();+ if (!declaring.isEmpty()) {+ return declaring.size() == 1 ? declaring.getFirst() : null;+ }+ List<RoutedListener> certificates = routing.listeners().values().stream()+ .filter(listener -> listener.certificateHosts().stream()+ .anyMatch(candidate -> candidate.equals(host) || wildcardMatches(candidate, host)))+ .toList();+ if (!certificates.isEmpty()) {+ return certificates.size() == 1 ? certificates.getFirst() : null;+ }+ return routing.hosts().size() == 1+ ? routing.listeners().get(routing.hosts().values().iterator().next()) : null;+ }++ private static boolean wildcardMatches(String candidate, String host) {+ return candidate.startsWith("*.")+ && host.length() > candidate.length() - 1+ && host.endsWith(candidate.substring(1))+ && host.indexOf('.') == host.length() - candidate.length() + 1;}private static String normalizeHost(String host) {diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.javaindex 2c1aeb972c..2a0fe66983 100644--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.resource.ResourceProvider;import io.github.hectorvent.floci.core.resource.SupportedResourceType;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.ec2.Ec2Service;import io.github.hectorvent.floci.services.ec2.VpcDependencyProvider;import io.github.hectorvent.floci.services.ec2.model.Subnet;@@ -22,6 +23,7 @@ import io.github.hectorvent.floci.services.iam.ServerCertificateReferenceProvideimport jakarta.annotation.PostConstruct;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;+import org.jboss.logging.Logger;import java.io.IOException;import java.net.InetAddress;@@ -32,11 +34,17 @@ import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.CopyOnWriteArrayList;+import java.util.function.BooleanSupplier;+import java.util.function.Function;+import java.util.function.Supplier;import java.util.stream.Collectors;@ApplicationScopedpublic class ElbV2Service implements ResourceProvider, ServerCertificateReferenceProvider, VpcDependencyProvider {+ private static final Logger LOG = Logger.getLogger(ElbV2Service.class);+@InjectElbV2DataPlane dataPlane;@@ -148,13 +156,13 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencfor (Map<String, Listener> regionListeners : listeners.values()) {for (Listener listener : regionListeners.values()) {- lbToListeners.computeIfAbsent(listener.getLoadBalancerArn(), k -> new ArrayList<>())+ lbToListeners.computeIfAbsent(listener.getLoadBalancerArn(), k -> new CopyOnWriteArrayList<>()).add(listener.getListenerArn());}}for (Map<String, Rule> regionRules : rules.values()) {for (Rule rule : regionRules.values()) {- listenerToRules.computeIfAbsent(rule.getListenerArn(), k -> new ArrayList<>())+ listenerToRules.computeIfAbsent(rule.getListenerArn(), k -> new CopyOnWriteArrayList<>()).add(rule.getRuleArn());}}@@ -188,7 +196,12 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencfor (Map.Entry<String, Map<String, Listener>> regionEntry : listeners.entrySet()) {String region = regionEntry.getKey();for (Listener listener : regionEntry.getValue().values()) {- dataPlane.startListener(listener, region, getListenerRules(region, listener.getListenerArn()));+ try {+ restoreListener(region, listener.getListenerArn());+ } catch (RuntimeException failure) {+ LOG.warnv("ELBv2 saved listener {0} could not be restored ({1}: {2}); its configuration is retained",+ listener.getListenerArn(), failure.getClass().getSimpleName(), failure.getMessage());+ }}}}@@ -308,25 +321,22 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencif (regionLbs == null) {return; // AWS silently ignores non-existent LBs on delete}- LoadBalancer lb = regionLbs.remove(arn);+ LoadBalancer lb = regionLbs.get(arn);if (lb == null) {return;}- // cascade: listeners → rules- List<String> listenerArns = lbToListeners.remove(arn);- if (listenerArns != null) {- Map<String, Listener> regionListeners = listeners.computeIfAbsent(region, k -> new ConcurrentHashMap<>());- Map<String, Rule> regionRules = rules.computeIfAbsent(region, k -> new ConcurrentHashMap<>());- for (String listenerArn : listenerArns) {- dataPlane.stopListener(listenerArn);- regionListeners.remove(listenerArn);- List<String> ruleArns = listenerToRules.remove(listenerArn);- if (ruleArns != null) {- ruleArns.forEach(regionRules::remove);- }+ List<String> listenerArns;+ synchronized (lb) {+ if (!regionLbs.remove(arn, lb)) {+ return;}- listeners.put(region, regionListeners);- rules.put(region, regionRules);+ listenerArns = listeners.getOrDefault(region, Map.of()).values().stream()+ .filter(listener -> arn.equals(listener.getLoadBalancerArn()))+ .map(Listener::getListenerArn).toList();+ lbToListeners.remove(arn);+ }+ for (String listenerArn : listenerArns) {+ deleteListener(region, listenerArn);}// remove from TG indextgToLbs.values().forEach(lbSet -> lbSet.remove(arn));@@ -559,31 +569,38 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenclistener.setDefaultActions(defaultActions != null ? new ArrayList<>(defaultActions) : new ArrayList<>());listener.setAlpnPolicy(alpnPolicy != null ? new ArrayList<>(alpnPolicy) : new ArrayList<>());- // Published under the guard, re-checking inside it. Until the listener is in the map,- // DeleteServerCertificate walking the reference providers cannot see that it holds the- // certificate, so a delete landing in that window would take the certificate out from- // under a listener that is about to serve it.- whileCertificatesHeld(certificates, () -> {- requireListenerCertificates(region, protocol, certificates);- regionListeners.put(listenerArn, listener);- listeners.put(region, regionListeners);- });- lbToListeners.computeIfAbsent(lbArn, k -> new ArrayList<>()).add(listenerArn);-- // auto-create the default ruleRule defaultRule = buildDefaultRule(region, listenerArn, lb, lbId, listenerId, defaultActions);- Map<String, Rule> regionRules = rules.computeIfAbsent(region, k -> new ConcurrentHashMap<>());- regionRules.put(defaultRule.getRuleArn(), defaultRule);- rules.put(region, regionRules);- listenerToRules.computeIfAbsent(listenerArn, k -> new ArrayList<>()).add(defaultRule.getRuleArn());- for (Action action : defaultRule.getActions()) {- linkTgToLb(action, lbArn);- }-- if (!initialTags.isEmpty()) {- tags.put(listenerArn, new LinkedHashMap<>(initialTags));+ while (true) {+ requireListenerCertificates(region, protocol, certificates);+ requireCompatibleListenerProtocol(listenerArn, port, listener.getProtocol());+ boolean applied = publishListener(listener, region, port, () -> {+ synchronized (lb) {+ requireCanonicalLoadBalancer(region, lb);+ requireAvailableListenerPort(regionListeners, lbArn, listenerArn, port);+ regionListeners.put(listenerArn, listener);+ listeners.put(region, regionListeners);+ lbToListeners.computeIfAbsent(lbArn, ignored -> new CopyOnWriteArrayList<>()).add(listenerArn);+ Map<String, Rule> regionRules = rules.computeIfAbsent(region, ignored -> new ConcurrentHashMap<>());+ regionRules.put(defaultRule.getRuleArn(), defaultRule);+ rules.put(region, regionRules);+ listenerToRules.computeIfAbsent(listenerArn, ignored -> new CopyOnWriteArrayList<>())+ .add(defaultRule.getRuleArn());+ for (Action action : defaultRule.getActions()) {+ linkTgToLb(action, lbArn);+ }+ if (!initialTags.isEmpty()) {+ tags.put(listenerArn, new LinkedHashMap<>(initialTags));+ }+ return true;+ }+ }, operation -> supplyCertificatesHeld(certificates, () -> {+ requireListenerCertificates(region, protocol, certificates);+ return operation.get();+ }));+ if (applied) {+ break;+ }}- dataPlane.startListener(listener, region, getListenerRules(region, listenerArn));return listener;}@@ -615,108 +632,135 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc}public void deleteListener(String region, String listenerArn) {- Map<String, Listener> regionListeners = listeners.get(region);- if (regionListeners == null) {- return;- }- Listener listener = regionListeners.remove(listenerArn);- if (listener == null) {- return;- }- dataPlane.stopListener(listenerArn);- removeFromIndex(lbToListeners, listener.getLoadBalancerArn(), listenerArn);-- Map<String, Rule> regionRules = rules.computeIfAbsent(region, k -> new ConcurrentHashMap<>());- List<String> ruleArns = listenerToRules.remove(listenerArn);- if (ruleArns != null) {- ruleArns.forEach(regionRules::remove);+ while (true) {+ Map<String, Listener> regionListeners = listeners.get(region);+ Listener listener = regionListeners == null ? null : regionListeners.get(listenerArn);+ if (listener == null) {+ return;+ }+ ListenerState expected = listenerState(listener);+ LoadBalancer lb = loadBalancers.getOrDefault(region, Map.of()).get(listener.getLoadBalancerArn());+ BooleanSupplier removal = () -> {+ if (!isCurrentListener(region, expected)) {+ return false;+ }+ regionListeners.remove(listenerArn, listener);+ removeFromIndex(lbToListeners, listener.getLoadBalancerArn(), listenerArn);+ Map<String, Rule> regionRules = rules.computeIfAbsent(region, ignored -> new ConcurrentHashMap<>());+ List<String> ruleArns = listenerToRules.remove(listenerArn);+ if (ruleArns != null) {+ ruleArns.forEach(regionRules::remove);+ }+ listeners.put(region, regionListeners);+ rules.put(region, regionRules);+ tags.remove(listenerArn);+ unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());+ return true;+ };+ boolean removed = dataPlane.removeListener(listenerArn, expected.port(), () -> {+ if (lb == null) {+ return removal.getAsBoolean();+ }+ synchronized (lb) {+ return removal.getAsBoolean();+ }+ });+ if (removed) {+ return;+ }}- listeners.put(region, regionListeners);- rules.put(region, regionRules);- tags.remove(listenerArn);- unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());}public Listener modifyListener(String region, String listenerArn, String protocol, Integer port,String sslPolicy, List<String> certificates,List<Action> defaultActions, List<String> alpnPolicy) {- Listener listener = requireListener(region, listenerArn);- boolean recompileRules = false;-- boolean portChanges = port != null && !Objects.equals(listener.getPort(), port);- if (portChanges) {- // check duplicate port on same LB- Map<String, Listener> regionListeners = listeners.getOrDefault(region, Map.of());- boolean portExists = regionListeners.values().stream()- .filter(l -> l.getLoadBalancerArn().equals(listener.getLoadBalancerArn()) && !l.getListenerArn().equals(listenerArn))- .anyMatch(l -> Objects.equals(l.getPort(), port));- if (portExists) {- throw new AwsException("DuplicateListener",- "A listener already exists on port " + port + " for this load balancer.", 400);+ while (true) {+ Listener initial = requireListener(region, listenerArn);+ LoadBalancer initialLb = requireLoadBalancer(region, initial.getLoadBalancerArn());+ ListenerState initialState = listenerState(initial, initialLb);+ requireAvailableListenerPort(listeners.getOrDefault(region, Map.of()), initial.getLoadBalancerArn(),+ listenerArn, port != null ? port : initialState.port());+ if (validateExistingListener(region, initialState, initialLb, () ->+ requireListenerCertificates(region, protocol != null ? protocol : initialState.protocol(),+ certificates != null ? certificates : initialState.certificates()))) {+ break;}}-- // Both refusals land before the first setter, because the listener being modified is the- // stored one: a request refused after one of them had run would answer 400 and still have- // changed the listener's port, protocol or policy.- //- // The protocol and the certificates checked are the ones the listener ends the call with.- // A request that turns an HTTP listener into an HTTPS one brings the certificate the new- // protocol needs, and one that changes the protocol alone puts the certificates the- // listener already holds into service, where they have to be certificates the account has.- String effectiveProtocol = protocol != null ? protocol : listener.getProtocol();- List<String> effectiveCertificates =- certificates != null ? certificates : listener.getCertificates();- requireListenerCertificates(region, effectiveProtocol, effectiveCertificates);-- // Every setter runs inside the guard, behind the re-check, which is what makes the- // comment above hold for that refusal too: the check made outside the guard says nothing- // about the moment of the write, so a delete landing between the two has to answer 400 on- // a listener that has not moved rather than one already on its new port.- //- // The guard is taken for the certificates the request records, which are the only ones a- // delete can race: a certificate the listener already holds is one- // DeleteServerCertificate finds among the references and refuses to delete. The re-check- // covers the effective list all the same, so the refusal is the same one either way.- whileCertificatesHeld(certificates, () -> {- requireListenerCertificates(region, effectiveProtocol, effectiveCertificates);- if (portChanges) {- listener.setPort(port);- }- if (protocol != null) {- listener.setProtocol(protocol);- }- if (sslPolicy != null) {- listener.setSslPolicy(sslPolicy);+ while (true) {+ Listener listener = requireListener(region, listenerArn);+ LoadBalancer lb = requireLoadBalancer(region, listener.getLoadBalancerArn());+ ListenerState expected = listenerState(listener, lb);+ Listener prospective = prospectiveListener(expected, protocol, port, certificates);+ requireAvailableListenerPort(listeners.getOrDefault(region, Map.of()), listener.getLoadBalancerArn(),+ listenerArn, prospective.getPort());+ if (!validateExistingListener(region, expected, lb, () -> {+ requireListenerCertificates(region, prospective.getProtocol(), prospective.getCertificates());+ requireCompatibleListenerProtocol(listenerArn, prospective.getPort(), prospective.getProtocol());+ })) {+ continue;}- if (certificates != null) {- listener.setCertificates(new ArrayList<>(certificates));+ BooleanSupplier publication = () -> {+ synchronized (lb) {+ requireCanonicalLoadBalancer(region, lb);+ if (!isCurrentListener(region, expected)) {+ return false;+ }+ requireAvailableListenerPort(listeners.getOrDefault(region, Map.of()),+ listener.getLoadBalancerArn(), listenerArn, prospective.getPort());+ if (port != null) {+ listener.setPort(port);+ }+ if (protocol != null) {+ listener.setProtocol(protocol);+ }+ if (sslPolicy != null) {+ listener.setSslPolicy(sslPolicy);+ }+ if (certificates != null) {+ listener.setCertificates(new ArrayList<>(certificates));+ }+ if (alpnPolicy != null) {+ listener.setAlpnPolicy(new ArrayList<>(alpnPolicy));+ }+ if (defaultActions != null) {+ listener.setDefaultActions(new ArrayList<>(defaultActions));+ listenerToRules.getOrDefault(listenerArn, List.of()).stream()+ .map(arn -> rules.getOrDefault(region, Map.of()).get(arn))+ .filter(rule -> rule != null && rule.isDefault())+ .forEach(rule -> rule.setActions(new ArrayList<>(defaultActions)));+ for (Action action : defaultActions) {+ linkTgToLb(action, listener.getLoadBalancerArn());+ }+ unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());+ }+ persistRegion(listeners, region);+ persistRegion(rules, region);+ return true;+ }+ };+ boolean restart = port != null || protocol != null || certificates != null;+ boolean applied = restart+ ? publishExistingListener(prospective, region, expected, lb,+ () -> requireCertificates(region, prospective.getProtocol(),+ certificates != null ? certificates : prospective.getCertificates()), publication)+ : supplyCertificatesHeld(prospective.getCertificates(), () -> {+ synchronized (lb) {+ if (!isCurrentListener(region, expected)) {+ return false;+ }+ }+ requireCertificates(region, prospective.getProtocol(), prospective.getCertificates());+ requirePublishedCertificates(region, prospective.getProtocol(), prospective.getCertificates());+ return dataPlane.updateListener(expected.port(), publication);+ });+ if (applied) {+ break;}- });- if (alpnPolicy != null) {- listener.setAlpnPolicy(new ArrayList<>(alpnPolicy));}if (defaultActions != null) {- listener.setDefaultActions(new ArrayList<>(defaultActions));- // update the default rule's actions- listenerToRules.getOrDefault(listenerArn, List.of()).stream()- .map(ra -> rules.getOrDefault(region, Map.of()).get(ra))- .filter(r -> r != null && r.isDefault())- .forEach(r -> r.setActions(new ArrayList<>(defaultActions)));- for (Action action : defaultActions) {- linkTgToLb(action, listener.getLoadBalancerArn());- }- unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());- recompileRules = true;- }- persistRegion(listeners, region);- persistRegion(rules, region);- if (portChanges) {- dataPlane.restartListener(requireListener(region, listenerArn), region, getListenerRules(region, listenerArn));- } else if (recompileRules) {- dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));+ dataPlane.recompileRules(listenerArn, () -> getListenerRules(region, listenerArn));}- return listener;+ return requireListener(region, listenerArn);}// ── Rules ─────────────────────────────────────────────────────────────────@@ -759,7 +803,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencregionRules.put(ruleArn, rule);rules.put(region, regionRules);- listenerToRules.computeIfAbsent(listenerArn, k -> new ArrayList<>()).add(ruleArn);+ listenerToRules.computeIfAbsent(listenerArn, k -> new CopyOnWriteArrayList<>()).add(ruleArn);// update TG → LB index for all target group actionsfor (Action a : rule.getActions()) {@@ -769,7 +813,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencif (!initialTags.isEmpty()) {tags.put(ruleArn, new LinkedHashMap<>(initialTags));}- dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));+ dataPlane.recompileRules(listenerArn, () -> getListenerRules(region, listenerArn));return rule;}@@ -811,7 +855,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencif (listener != null) {unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());}- dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));+ dataPlane.recompileRules(listenerArn, () -> getListenerRules(region, listenerArn));}public Rule modifyRule(String region, String ruleArn, List<RuleCondition> conditions, List<Action> actions) {@@ -820,7 +864,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencif (conditions != null) rule.setConditions(new ArrayList<>(conditions));if (actions != null) rule.setActions(new ArrayList<>(actions));persistRegion(rules, region);- dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));+ dataPlane.recompileRules(listenerArn, () -> getListenerRules(region, listenerArn));return rule;}@@ -874,7 +918,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencSet<String> affectedListeners = arnToPriority.keySet().stream().map(arn -> regionRules.get(arn).getListenerArn()).collect(Collectors.toSet());- affectedListeners.forEach(la -> dataPlane.recompileRules(la, getListenerRules(region, la)));+ affectedListeners.forEach(la -> dataPlane.recompileRules(la, () -> getListenerRules(region, la)));}// ── Targets ───────────────────────────────────────────────────────────────@@ -997,29 +1041,58 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc}public void addListenerCertificates(String region, String listenerArn, List<String> certArns) {- Listener listener = requireListener(region, listenerArn);- requireCertificates(region, listener.getProtocol(), certArns);- whileCertificatesHeld(certArns, () -> {- requireCertificates(region, listener.getProtocol(), certArns);- for (String certArn : certArns) {- if (!listener.getCertificates().contains(certArn)) {- listener.getCertificates().add(certArn);- }- }- persistRegion(listeners, region);- });+ Listener initial = requireListener(region, listenerArn);+ requireCertificates(region, initial.getProtocol(), certArns);+ changeListenerCertificates(region, listenerArn, certArns, false);}public void removeListenerCertificates(String region, String listenerArn, List<String> certArns) {- Listener listener = requireListener(region, listenerArn);- List<String> certificates = listener.getCertificates();- if (servesCertificates(listener.getProtocol()) && !certificates.isEmpty()- && certArns.contains(certificates.getFirst())) {- throw new AwsException("OperationNotPermitted",- "The default listener certificate cannot be removed.", 400);+ changeListenerCertificates(region, listenerArn, certArns, true);+ }++ private void changeListenerCertificates(String region, String listenerArn, List<String> requested, boolean remove) {+ while (true) {+ Listener listener = requireListener(region, listenerArn);+ LoadBalancer lb = requireLoadBalancer(region, listener.getLoadBalancerArn());+ ListenerState expected = listenerState(listener, lb);+ List<String> certificates = new ArrayList<>(expected.certificates());+ if (remove) {+ if (servesCertificates(expected.protocol()) && !certificates.isEmpty()+ && requested.contains(certificates.getFirst())) {+ throw new AwsException("OperationNotPermitted",+ "The default listener certificate cannot be removed.", 400);+ }+ certificates.removeAll(requested);+ } else {+ if (!validateExistingListener(region, expected, lb,+ () -> requireCertificates(region, expected.protocol(), requested))) {+ continue;+ }+ for (String arn : requested) {+ if (!certificates.contains(arn)) {+ certificates.add(arn);+ }+ }+ }+ Listener prospective = prospectiveListener(expected, null, null, certificates);+ if (publishExistingListener(prospective, region, expected, lb, () -> {+ if (!remove) {+ requireCertificates(region, expected.protocol(), requested);+ }+ }, () -> {+ synchronized (lb) {+ requireCanonicalLoadBalancer(region, lb);+ if (!isCurrentListener(region, expected)) {+ return false;+ }+ listener.setCertificates(certificates);+ persistRegion(listeners, region);+ return true;+ }+ })) {+ return;+ }}- certificates.removeAll(certArns);- persistRegion(listeners, region);}public List<String> describeListenerCertificates(String region, String listenerArn) {@@ -1029,6 +1102,164 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc// ── Helpers ───────────────────────────────────────────────────────────────+ private record ListenerState(Listener listener, Integer port, String protocol, List<String> certificates) {}++ private static ListenerState listenerState(Listener listener) {+ return new ListenerState(listener, listener.getPort(), listener.getProtocol(),+ new ArrayList<>(listener.getCertificates()));+ }++ private static ListenerState listenerState(Listener listener, LoadBalancer lb) {+ synchronized (lb) {+ return listenerState(listener);+ }+ }++ private boolean isCurrentListener(String region, ListenerState expected) {+ Listener current = listeners.getOrDefault(region, Map.of()).get(expected.listener().getListenerArn());+ return current == expected.listener() && Objects.equals(current.getPort(), expected.port())+ && Objects.equals(current.getProtocol(), expected.protocol())+ && current.getCertificates().equals(expected.certificates());+ }++ private static Listener prospectiveListener(ListenerState expected, String protocol, Integer port,+ List<String> certificates) {+ Listener prospective = new Listener();+ prospective.setListenerArn(expected.listener().getListenerArn());+ prospective.setLoadBalancerArn(expected.listener().getLoadBalancerArn());+ prospective.setPort(port != null ? port : expected.port());+ prospective.setProtocol(protocol != null ? protocol : expected.protocol());+ prospective.setCertificates(new ArrayList<>(certificates != null ? certificates : expected.certificates()));+ return prospective;+ }++ private void requireCanonicalLoadBalancer(String region, LoadBalancer lb) {+ if (loadBalancers.getOrDefault(region, Map.of()).get(lb.getLoadBalancerArn()) != lb) {+ throw new AwsException("LoadBalancerNotFound", "One or more load balancers not found.", 400);+ }+ }++ private static void requireAvailableListenerPort(Map<String, Listener> regionListeners, String lbArn,+ String listenerArn, Integer port) {+ if (regionListeners.values().stream().anyMatch(listener -> lbArn.equals(listener.getLoadBalancerArn())+ && !listenerArn.equals(listener.getListenerArn()) && Objects.equals(listener.getPort(), port))) {+ throw new AwsException("DuplicateListener",+ "A listener already exists on port " + port + " for this load balancer.", 400);+ }+ }++ private void requireCompatibleListenerProtocol(String listenerArn, Integer port, String protocol) {+ if (port == null) {+ return;+ }+ try {+ dataPlane.requireCompatibleListenerProtocol(listenerArn, port, protocol);+ } catch (ElbV2DataPlane.IncompatibleListenerProtocolException conflict) {+ throw new ListenerProtocolConflict(conflict);+ }+ }++ private boolean publishListener(Listener prospective, String region, Integer previousPort,+ BooleanSupplier publication, Function<Supplier<Boolean>, Boolean> admission) {+ try {+ return dataPlane.publishListener(prospective, region, previousPort, publication,+ () -> getListenerRules(region, prospective.getListenerArn()), admission);+ } catch (ElbV2DataPlane.IncompatibleListenerProtocolException conflict) {+ throw new ListenerProtocolConflict(conflict);+ }+ }++ private static final class ListenerProtocolConflict extends AwsException {+ private ListenerProtocolConflict(ElbV2DataPlane.IncompatibleListenerProtocolException conflict) {+ super("InvalidConfigurationRequest", conflict.getMessage(), 400);+ }+ }++ private boolean staleListenerPreparation(String region, ListenerState expected, LoadBalancer lb,+ AwsException failure) {+ if (!(failure instanceof ListenerProtocolConflict) && !"CertificateNotFound".equals(failure.getErrorCode())) {+ return false;+ }+ synchronized (lb) {+ return !isCurrentListener(region, expected)+ || loadBalancers.getOrDefault(region, Map.of()).get(lb.getLoadBalancerArn()) != lb;+ }+ }++ private boolean validateExistingListener(String region, ListenerState expected, LoadBalancer lb,+ Runnable validation) {+ try {+ validation.run();+ return true;+ } catch (AwsException failure) {+ if (staleListenerPreparation(region, expected, lb, failure)) {+ return false;+ }+ throw failure;+ }+ }++ private boolean publishExistingListener(Listener prospective, String region, ListenerState expected,+ LoadBalancer lb, Runnable referenceValidation, BooleanSupplier publication) {+ try {+ return publishListener(prospective, region, expected.port(), publication,+ operation -> supplyCertificatesHeld(prospective.getCertificates(), () -> {+ synchronized (lb) {+ if (!isCurrentListener(region, expected)+ || loadBalancers.getOrDefault(region, Map.of()).get(lb.getLoadBalancerArn()) != lb) {+ return false;+ }+ }+ referenceValidation.run();+ requirePublishedCertificates(region, prospective.getProtocol(), prospective.getCertificates());+ return operation.get();+ }));+ } catch (AwsException failure) {+ if (staleListenerPreparation(region, expected, lb, failure)) {+ return false;+ }+ throw failure;+ }+ }++ private void restoreListener(String region, String listenerArn) {+ while (true) {+ Listener listener = listeners.getOrDefault(region, Map.of()).get(listenerArn);+ if (listener == null) {+ return;+ }+ LoadBalancer lb = loadBalancers.getOrDefault(region, Map.of()).get(listener.getLoadBalancerArn());+ if (lb == null) {+ return;+ }+ ListenerState expected = listenerState(listener, lb);+ if (publishExistingListener(prospectiveListener(expected, null, null, null), region, expected, lb,+ () -> { }, () -> {+ synchronized (lb) {+ return loadBalancers.getOrDefault(region, Map.of()).get(lb.getLoadBalancerArn()) == lb+ && isCurrentListener(region, expected);+ }+ })) {+ return;+ }+ }+ }++ private void requirePublishedCertificates(String region, String protocol, List<String> certificateArns) {+ if (certificateResolver != null && certificateArns != null && servesCertificates(protocol)) {+ for (String arn : certificateArns) {+ if (arn != null && AwsArnUtils.isArn(arn) && "acm".equals(AwsArnUtils.parse(arn).service())+ && !certificateResolver.isUsableAcmCertificate(region, arn)) {+ throw new AwsException("CertificateNotFound", "The specified certificate is not available for use.", 400);+ }+ }+ }+ if ("HTTPS".equalsIgnoreCase(protocol) && (certificateArns == null || certificateArns.isEmpty())) {+ throw new AwsException("InvalidConfigurationRequest",+ "An HTTPS listener requires a default certificate.", 400);+ }+ }+/*** Refuses a certificate the account does not have. {@code CertificateNotFound} is modeled on* {@code CreateListener}, {@code ModifyListener} and {@code AddListenerCertificates} alone,@@ -1067,6 +1298,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencthrow new AwsException("InvalidConfigurationRequest","An HTTPS listener requires a default certificate.", 400);}+ requirePublishedCertificates(region, protocol, certificateArns);}/** The listener protocols a certificate belongs to, per the reference's own bracket. */@@ -1074,18 +1306,33 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencreturn "HTTPS".equalsIgnoreCase(protocol) || "TLS".equalsIgnoreCase(protocol);}- /**- * Runs a listener write under {@link CertificateReferenceResolver#runWhileHeld}, so an IAM- * server certificate it records cannot be deleted between the check and the write. The- * callers re-check inside the guard: the fail-fast check above it keeps the error precedence- * AWS has, and only the one under the guard is atomic with the write.- */- private void whileCertificatesHeld(List<String> certificateArns, Runnable action) {- if (certificateResolver == null) {- action.run();- return;+ private <T> T supplyCertificatesHeld(List<String> certificateArns, Supplier<T> action) {+ return certificateResolver == null ? action.get() : certificateResolver.supplyWhileHeld(certificateArns, action);+ }++ public List<CertificateReference> acmCertificateReferences() {+ List<CertificateReference> references = new ArrayList<>();+ for (Map<String, Listener> regionListeners : listeners.values()) {+ for (Listener listener : regionListeners.values()) {+ for (String certificateArn : listener.getCertificates()) {+ references.add(new CertificateReference(certificateArn, listener.getLoadBalancerArn()));+ }+ }+ }+ return references;+ }++ public void certificateReimported(String certificateArn, String region) {+ for (Listener listener : listeners.getOrDefault(region, Map.of()).values()) {+ if (listener.getCertificates().contains(certificateArn)) {+ try {+ restoreListener(region, listener.getListenerArn());+ } catch (RuntimeException failure) {+ LOG.warnv("ELBv2 certificate refresh for listener {0} failed ({1}: {2}); its configuration is retained",+ listener.getListenerArn(), failure.getClass().getSimpleName(), failure.getMessage());+ }+ }}- certificateResolver.runWhileHeld(certificateArns, action);}private LoadBalancer requireLoadBalancer(String region, String arn) {@@ -1225,7 +1472,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferencaction.setTargetGroups(List.of(blueTuple, greenTuple));}defaultRule.setActions(List.of(action));- dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));+ dataPlane.recompileRules(listenerArn, () -> getListenerRules(region, listenerArn));}private List<Rule> getListenerRules(String region, String listenerArn) {diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.javaindex 039dfaa9fa..c8507e70ec 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.java@@ -1,7 +1,10 @@package io.github.hectorvent.floci.services.acm;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.FlociCertificateAuthority;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;import io.github.hectorvent.floci.core.common.Pem;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.InMemoryStorage;@@ -11,13 +14,17 @@ import io.github.hectorvent.floci.services.acm.model.CertificateStatus;import io.github.hectorvent.floci.services.acm.model.CertificateType;import io.github.hectorvent.floci.services.acm.model.DomainValidation;import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.services.acm.model.RevocationReason;import io.github.hectorvent.floci.services.acm.model.ValidationMethod;+import jakarta.enterprise.inject.Instance;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.EnumSource;+import java.lang.management.ManagementFactory;+import java.lang.management.ThreadInfo;import java.math.BigInteger;import java.nio.charset.StandardCharsets;import java.nio.file.Path;@@ -28,18 +35,26 @@ import java.security.cert.TrustAnchor;import java.security.cert.X509Certificate;import java.security.interfaces.ECPublicKey;import java.security.interfaces.RSAPublicKey;+import java.time.Duration;import java.util.ArrayList;import java.util.Base64;+import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;+import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicLong;+import static org.awaitility.Awaitility.await;+import static org.junit.jupiter.api.Assertions.assertAll;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertThrows;@@ -113,6 +128,189 @@ class AcmServiceTest {assertEquals(replacement.privateKeyPem(), service.getCertificate(existing.getArn(), REGION).getPrivateKey());}+ @Test+ void pendingAcmExistsButCannotSupplyAnElbCertificate() {+ AcmService pending = newService(3600);+ Certificate certificate = pending.requestCertificate("pending.example.test", List.of(), ValidationMethod.DNS,+ null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);+ CertificateReferenceResolver resolver = new CertificateReferenceResolver(null, pending);+ assertTrue(resolver.exists(REGION, certificate.getArn()));+ assertEquals(false, resolver.isUsableAcmCertificate(REGION, certificate.getArn()));+ String owner = "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/test/one/two";+ AwsException failure = assertThrows(AwsException.class,+ () -> resolver.publishedMaterial(owner, REGION, certificate.getArn()));+ assertEquals("CertificateNotFound", failure.getErrorCode());+ assertEquals(CertificateStatus.PENDING_VALIDATION, pending.getCertificate(certificate.getArn(), REGION).getStatus());+ }++ @Test+ void attachedExportableCertificateCannotBeRevokedUntilDetached() {+ Certificate certificate = service.requestCertificate("revoke.example.test", List.of(), ValidationMethod.DNS,+ null, KeyAlgorithm.RSA_2048, null, new CertificateOptions(null, "ENABLED"), Map.of(), REGION);+ String owner = "arn:aws:cognito-idp:us-east-1:000000000000:userpool/revoke";+ service.addInUseBy(certificate.getArn(), owner, REGION);+ AwsException failure = assertThrows(AwsException.class,+ () -> service.revokeCertificate(certificate.getArn(), RevocationReason.KEY_COMPROMISE, REGION));+ assertAll(+ () -> assertEquals("ResourceInUseException", failure.getErrorCode()),+ () -> assertEquals(400, failure.getHttpStatus()),+ () -> assertEquals(CertificateStatus.ISSUED, service.getCertificate(certificate.getArn(), REGION).getStatus()),+ () -> assertEquals(List.of(owner), service.certificateInUseBy(certificate)));+ service.removeInUseBy(certificate.getArn(), owner, REGION);+ assertEquals(CertificateStatus.REVOKED,+ service.revokeCertificate(certificate.getArn(), RevocationReason.KEY_COMPROMISE, REGION).getStatus());+ }++ @Test+ void listPageScansLiveConsumersOnceAndRetainsPersistedUses() {+ Certificate first = service.requestCertificate("first.example.test", List.of(), ValidationMethod.DNS,+ null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);+ Certificate second = service.requestCertificate("second.example.test", List.of(), ValidationMethod.DNS,+ null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);+ service.requestCertificate("unused.example.test", List.of(), ValidationMethod.DNS,+ null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);+ service.addInUseBy(first.getArn(), "persisted-owner", REGION);+ AtomicInteger scans = new AtomicInteger();+ AcmCertificateReferenceProvider provider = mock();+ when(provider.acmCertificateReferences()).thenAnswer(call -> {+ scans.incrementAndGet();+ return List.of(new AcmCertificateReferenceProvider.CertificateReference(second.getArn(), "live-owner"));+ });+ Instance<AcmCertificateReferenceProvider> providers = mock();+ when(providers.iterator()).thenAnswer(call -> List.of(provider).iterator());+ service.referenceProviders = providers;+ ObjectMapper mapper = new ObjectMapper();+ AcmJsonHandler handler = new AcmJsonHandler(service, mapper);+ JsonNode response = (JsonNode) handler.handle("ListCertificates", mapper.createObjectNode(), REGION).getEntity();+ Map<String, Boolean> uses = new HashMap<>();+ response.path("CertificateSummaryList").forEach(row -> uses.put(row.path("CertificateArn").asText(),+ row.path("InUse").asBoolean()));+ assertAll(+ () -> assertEquals(1, scans.get()),+ () -> assertEquals(3, uses.size()),+ () -> assertEquals(true, uses.get(first.getArn())),+ () -> assertEquals(true, uses.get(second.getArn())),+ () -> assertEquals(1L, uses.values().stream().filter(value -> !value).count()));+ scans.set(0);+ JsonNode page = (JsonNode) handler.handle("ListCertificates", mapper.createObjectNode().put("MaxItems", 1),+ REGION).getEntity();+ assertEquals(1, page.path("CertificateSummaryList").size());+ assertTrue(page.has("NextToken"));+ assertEquals(1, scans.get());+ }++ @Test+ void capturedCertificateSummarySurvivesDeletion() {+ Certificate certificate = service.requestCertificate("list.example.test", List.of(), ValidationMethod.DNS,+ null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);+ service.deleteCertificate(certificate.getArn(), REGION);+ assertEquals(List.of(), service.certificateInUseBy(certificate));+ Map<String, List<String>> snapshot = service.certificateInUseBy(List.of(certificate));+ assertEquals(List.of(), snapshot.get(certificate.getArn()));+ assertThrows(UnsupportedOperationException.class, () -> snapshot.put("other", List.of()));+ assertThrows(UnsupportedOperationException.class, () -> snapshot.get(certificate.getArn()).add("other"));+ }++ @Test+ void anOlderImportNotificationReadsTheNewestCommittedMaterial() throws Exception {+ CertificateGenerator.GeneratedCertificate original = ca.issueServerCertificate(+ "rotation.example.test", List.of(), KeyAlgorithm.RSA_2048, null);+ Certificate certificate = service.importCertificate(original.certificatePem(), original.privateKeyPem(),+ ca.caPem(), null, Map.of(), REGION);+ CertificateGenerator.GeneratedCertificate first = ca.issueServerCertificate(+ "rotation.example.test", List.of(), KeyAlgorithm.RSA_2048, null);+ CertificateGenerator.GeneratedCertificate second = ca.issueServerCertificate(+ "rotation.example.test", List.of(), KeyAlgorithm.RSA_2048, null);+ CountDownLatch entered = new CountDownLatch(1);+ CountDownLatch release = new CountDownLatch(1);+ AtomicBoolean pause = new AtomicBoolean(true);+ List<String> material = new CopyOnWriteArrayList<>();+ AcmCertificateReferenceProvider consumer = new AcmCertificateReferenceProvider() {+ @Override+ public List<CertificateReference> acmCertificateReferences() { return List.of(); }++ @Override+ public void certificateReimported(String arn, String region) {+ if (pause.getAndSet(false)) {+ entered.countDown();+ try {+ assertTrue(release.await(10, TimeUnit.SECONDS));+ } catch (InterruptedException failure) {+ Thread.currentThread().interrupt();+ throw new AssertionError(failure);+ }+ }+ material.add(service.supplyWithCertificatesHeld(() -> service.getCertificate(arn, region).getCertificateBody()));+ }+ };+ Instance<AcmCertificateReferenceProvider> providers = mock();+ when(providers.iterator()).thenAnswer(call -> List.of(consumer).iterator());+ service.referenceProviders = providers;+ ExecutorService worker = Executors.newSingleThreadExecutor();+ try {+ Future<Certificate> older = worker.submit(() -> service.importCertificate(first.certificatePem(),+ first.privateKeyPem(), ca.caPem(), certificate.getArn(), Map.of(), REGION));+ assertTrue(entered.await(5, TimeUnit.SECONDS));+ service.importCertificate(second.certificatePem(), second.privateKeyPem(), ca.caPem(),+ certificate.getArn(), Map.of(), REGION);+ release.countDown();+ older.get(10, TimeUnit.SECONDS);+ assertEquals(List.of(second.certificatePem(), second.certificatePem()), material);+ } finally {+ release.countDown();+ worker.shutdownNow();+ assertTrue(worker.awaitTermination(10, TimeUnit.SECONDS));+ }+ }++ @Test+ void aDeleteWaitsForReferencePublicationThenObservesTheConsumer() throws Exception {+ Certificate certificate = service.requestCertificate("delete.example.test", List.of(), ValidationMethod.DNS,+ null, KeyAlgorithm.RSA_2048, null, null, Map.of(), REGION);+ String consumer = "arn:aws:cognito-idp:us-east-1:000000000000:userpool/guarded";+ CountDownLatch held = new CountDownLatch(1);+ CountDownLatch release = new CountDownLatch(1);+ CountDownLatch deleting = new CountDownLatch(1);+ AtomicLong holder = new AtomicLong();+ AtomicLong waiter = new AtomicLong();+ ExecutorService workers = Executors.newFixedThreadPool(2);+ try {+ Future<?> publication = workers.submit(() -> service.supplyWithCertificatesHeld(() -> {+ holder.set(Thread.currentThread().threadId());+ held.countDown();+ try {+ assertTrue(release.await(10, TimeUnit.SECONDS));+ } catch (InterruptedException failure) {+ Thread.currentThread().interrupt();+ throw new AssertionError(failure);+ }+ service.addInUseBy(certificate.getArn(), consumer, REGION);+ return null;+ }));+ assertTrue(held.await(5, TimeUnit.SECONDS));+ Future<AwsException> deletion = workers.submit(() -> {+ waiter.set(Thread.currentThread().threadId());+ deleting.countDown();+ return assertThrows(AwsException.class, () -> service.deleteCertificate(certificate.getArn(), REGION));+ });+ assertTrue(deleting.await(5, TimeUnit.SECONDS));+ await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {+ ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(waiter.get());+ assertEquals(Thread.State.BLOCKED, info.getThreadState());+ assertEquals(holder.get(), info.getLockOwnerId());+ });+ release.countDown();+ publication.get(10, TimeUnit.SECONDS);+ assertEquals("ResourceInUseException", deletion.get(10, TimeUnit.SECONDS).getErrorCode());+ service.removeInUseBy(certificate.getArn(), consumer, REGION);+ service.deleteCertificate(certificate.getArn(), REGION);+ } finally {+ release.countDown();+ workers.shutdownNow();+ assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));+ }+ }+private AcmService newService(int validationWaitSeconds) {RegionResolver regionResolver = mock(RegionResolver.class);when(regionResolver.getAccountId()).thenReturn("000000000000");diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2CertificatePublicationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2CertificatePublicationServiceTest.javanew file mode 100644index 0000000000..791570960f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2CertificatePublicationServiceTest.java@@ -0,0 +1,330 @@+package io.github.hectorvent.floci.services.elbv2;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.elbv2.model.Action;+import io.github.hectorvent.floci.services.elbv2.model.Listener;+import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;+import io.github.hectorvent.floci.testutil.LogCapture;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;++import java.lang.management.ManagementFactory;+import java.lang.management.ThreadInfo;+import java.time.Duration;+import java.util.List;+import java.util.Map;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicReference;+import java.util.function.Supplier;+import java.util.logging.LogRecord;++import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.allowPublications;+import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.applyPublication;+import static io.github.hectorvent.floci.services.elbv2.ElbV2ServiceTest.serviceWithStorage;+import static io.github.hectorvent.floci.services.elbv2.ElbV2ServiceTest.sharedStorageFactory;+import static org.awaitility.Awaitility.await;+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyList;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++@ExtendWith(MockitoExtension.class)+class ElbV2CertificatePublicationServiceTest {+ private static final String REGION = "us-west-2";+ private static final List<String> ALB_SUBNETS = List.of("subnet-a", "subnet-b");+ private static final String HELD_CERTIFICATE = "arn:aws:iam::000000000000:server-certificate/held";+ private static final String OTHER_CERTIFICATE = "arn:aws:iam::000000000000:server-certificate/other";++ @Mock+ ElbV2DataPlane dataPlane;++ @Mock+ ElbV2HealthChecker healthChecker;++ private ElbV2Service service;++ @BeforeEach+ void setUp() {+ service = serviceWithStorage(null, dataPlane, healthChecker);+ }++ @ParameterizedTest+ @ValueSource(strings = {"create", "modify", "add"})+ void unavailableAcmCannotBePublishedWithoutALiveTlsRuntime(String operation) {+ String lb = service.createLoadBalancer(REGION, "pending-acm", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ Listener existing = service.createListener(REGION, lb, "HTTPS", 9443, null,+ List.of(HELD_CERTIFICATE), List.of(), List.of(), Map.of());+ String pending = "arn:aws:acm:us-west-2:000000000000:certificate/pending";+ CertificateReferenceResolver resolver = mock(CertificateReferenceResolver.class);+ AtomicBoolean issued = new AtomicBoolean();+ when(resolver.exists(anyString(), anyString())).thenReturn(true);+ when(resolver.isUsableAcmCertificate(REGION, pending)).thenAnswer(call -> issued.get());+ lenient().doAnswer(call -> call.getArgument(1, Supplier.class).get()).when(resolver).supplyWhileHeld(any(), any());+ service.certificateResolver = resolver;+ Runnable request = () -> {+ if ("create".equals(operation)) {+ service.createListener(REGION, lb, "HTTPS", 9444, null, List.of(pending), List.of(), List.of(), Map.of());+ } else if ("modify".equals(operation)) {+ service.modifyListener(REGION, existing.getListenerArn(), null, null, null, List.of(pending), null, null);+ } else {+ service.addListenerCertificates(REGION, existing.getListenerArn(), List.of(pending));+ }+ };+ AwsException failure = assertThrows(AwsException.class, request::run);+ assertEquals("CertificateNotFound", failure.getErrorCode());+ assertEquals(1, service.describeListeners(REGION, lb, List.of()).size());+ assertEquals(List.of(HELD_CERTIFICATE), existing.getCertificates());+ issued.set(true);+ assertDoesNotThrow(request::run);+ assertEquals("create".equals(operation) ? 2 : 1, service.describeListeners(REGION, lb, List.of()).size());+ assertEquals("add".equals(operation) ? List.of(HELD_CERTIFICATE, pending)+ : "modify".equals(operation) ? List.of(pending) : List.of(HELD_CERTIFICATE), existing.getCertificates());+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void portOnlyChangesRetryAProtocolConflictFromAnObsoleteSnapshot(boolean atPublication) {+ LoadBalancer lb = service.createLoadBalancer(REGION, "protocol-retry", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of());+ Listener listener = service.createListener(REGION, lb.getLoadBalancerArn(), "HTTPS", 9443, null,+ List.of(HELD_CERTIFICATE), List.of(), List.of(), Map.of());+ AtomicBoolean first = new AtomicBoolean(true);+ Runnable conflict = () -> {+ if (first.compareAndSet(true, false)) {+ service.modifyListener(REGION, listener.getListenerArn(), "HTTP", null, null, null, null, null);+ throw new ElbV2DataPlane.IncompatibleListenerProtocolException(9090);+ }+ };+ if (atPublication) {+ doAnswer(call -> {+ Listener prospective = call.getArgument(0);+ if (Integer.valueOf(9090).equals(prospective.getPort())) {+ conflict.run();+ }+ return applyPublication(call);+ }).when(dataPlane).publishListener(any(), eq(REGION), any(), any(), any(), any());+ } else {+ doAnswer(call -> {+ conflict.run();+ return null;+ }).when(dataPlane).requireCompatibleListenerProtocol(listener.getListenerArn(), 9090, "HTTPS");+ }+ Listener moved = assertDoesNotThrow(() -> service.modifyListener(REGION, listener.getListenerArn(),+ null, 9090, null, null, null, null));+ assertEquals("HTTP", moved.getProtocol());+ assertEquals(9090, moved.getPort());+ assertEquals(List.of(HELD_CERTIFICATE), moved.getCertificates());+ assertFalse(first.get());+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void unchangedProtocolConflictsRemainTerminal(boolean atPublication) {+ LoadBalancer lb = service.createLoadBalancer(REGION, "protocol-refusal", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of());+ Listener listener = service.createListener(REGION, lb.getLoadBalancerArn(), "HTTPS", 9443, null,+ List.of(HELD_CERTIFICATE), List.of(), List.of(), Map.of());+ AtomicReference<Integer> refusals = new AtomicReference<>(0);+ if (atPublication) {+ doAnswer(call -> {+ refusals.updateAndGet(count -> count + 1);+ throw new ElbV2DataPlane.IncompatibleListenerProtocolException(9090);+ }).when(dataPlane).publishListener(any(), eq(REGION), any(), any(), any(), any());+ } else {+ doAnswer(call -> {+ refusals.updateAndGet(count -> count + 1);+ throw new ElbV2DataPlane.IncompatibleListenerProtocolException(9090);+ }).when(dataPlane).requireCompatibleListenerProtocol(listener.getListenerArn(), 9090, "HTTPS");+ }+ AwsException refusal = assertThrows(AwsException.class, () -> service.modifyListener(REGION,+ listener.getListenerArn(), null, 9090, null, null, null, null));+ assertEquals("InvalidConfigurationRequest", refusal.getErrorCode());+ assertEquals(1, refusals.get());+ assertEquals(9443, listener.getPort());+ assertEquals("HTTPS", listener.getProtocol());+ }++ @Test+ void deletedParentRefusesAListenerWaitingForItsPublicationFence() throws Exception {+ LoadBalancer lb = service.createLoadBalancer(REGION, "parent-fence", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of());+ CountDownLatch publicationEntered = new CountDownLatch(1);+ AtomicReference<Thread> publisher = new AtomicReference<>();+ doAnswer(call -> {+ publisher.set(Thread.currentThread());+ publicationEntered.countDown();+ return applyPublication(call);+ }).when(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());+ ExecutorService worker = Executors.newSingleThreadExecutor();+ try {+ Future<Listener> creation;+ synchronized (lb) {+ creation = worker.submit(() -> service.createListener(REGION, lb.getLoadBalancerArn(), "HTTP", 9090,+ null, List.of(), List.of(), List.of(), Map.of()));+ assertTrue(publicationEntered.await(5, TimeUnit.SECONDS));+ long owner = Thread.currentThread().threadId();+ await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {+ ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(publisher.get().threadId());+ assertNotNull(info);+ assertEquals(Thread.State.BLOCKED, info.getThreadState());+ assertEquals(owner, info.getLockOwnerId());+ });+ service.deleteLoadBalancer(REGION, lb.getLoadBalancerArn());+ }+ ExecutionException refused = assertThrows(ExecutionException.class, () -> creation.get(5, TimeUnit.SECONDS));+ assertEquals("LoadBalancerNotFound", ((AwsException) refused.getCause()).getErrorCode());+ assertTrue(service.describeListeners(REGION, lb.getLoadBalancerArn(), List.of()).isEmpty());+ assertTrue(service.describeRules(REGION, null, List.of()).isEmpty());+ } finally {+ worker.shutdownNow();+ assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));+ }+ }++ @Test+ void modifyListenerRefusedUnderTheCertificateGuardLeavesTheListenerWhereItWas() {+ String lbArn = service.createLoadBalancer(+ REGION, "sample-lb", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ String tgArn = createTargetGroup("sample-tg");+ String listenerArn = service.createListener(+ REGION, lbArn, "HTTPS", 443, "ELBSecurityPolicy-2016-08", List.of(HELD_CERTIFICATE),+ List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn();+ clearInvocations(dataPlane);+ service.certificateResolver = deletedOnTheSecondLook();++ AwsException e = assertThrows(AwsException.class, () -> service.modifyListener(+ REGION, listenerArn, "TLS", 8443, "ELBSecurityPolicy-TLS13-1-2-2021-06",+ List.of(OTHER_CERTIFICATE), null, null));++ assertEquals("CertificateNotFound", e.getErrorCode());+ Listener listener = service.describeListeners(REGION, lbArn, List.of(listenerArn)).getFirst();+ assertEquals(Integer.valueOf(443), listener.getPort());+ assertEquals("HTTPS", listener.getProtocol());+ assertEquals("ELBSecurityPolicy-2016-08", listener.getSslPolicy());+ assertEquals(List.of(HELD_CERTIFICATE), listener.getCertificates());+ verify(dataPlane, never()).removeListener(anyString(), any(), any());+ }++ @Test+ void modifyListenerProtocolAloneTakesTheGuardForTheCertificatesItPutsIntoService() {+ String lbArn = service.createLoadBalancer(+ REGION, "sample-lb", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ String tgArn = createTargetGroup("sample-tg");+ String listenerArn = service.createListener(+ REGION, lbArn, "HTTP", 80, null, List.of(HELD_CERTIFICATE),+ List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn();+ clearInvocations(dataPlane);+ service.certificateResolver = deletedOnTheSecondLook();++ AwsException e = assertThrows(AwsException.class, () -> service.modifyListener(+ REGION, listenerArn, "HTTPS", null, null, null, null, null));++ assertEquals("CertificateNotFound", e.getErrorCode());+ assertEquals("HTTP", service.describeListeners(REGION, lbArn, List.of(listenerArn))+ .getFirst().getProtocol());+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void oneBrokenSavedListenerDoesNotPreventHealthyRestoration(boolean domainFailure) {+ StorageFactory factory = sharedStorageFactory();+ ElbV2Service first = serviceWithStorage(factory, mock(ElbV2DataPlane.class), mock(ElbV2HealthChecker.class));+ String lb = first.createLoadBalancer(REGION, "restore-isolation", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ Listener broken = first.createListener(REGION, lb, "HTTP", 9080, null,+ List.of(), List.of(), List.of(), Map.of());+ Listener healthy = first.createListener(REGION, lb, "HTTP", 9081, null,+ List.of(), List.of(), List.of(), Map.of());+ ElbV2DataPlane runtime = mock(ElbV2DataPlane.class);+ ElbV2Service reloaded = serviceWithStorage(factory, runtime, mock(ElbV2HealthChecker.class));+ AtomicBoolean firstRestore = new AtomicBoolean(true);+ doAnswer(call -> {+ if (firstRestore.getAndSet(false)) {+ if (domainFailure) {+ throw new AwsException("CertificateNotFound", "controlled missing stored material", 400);+ }+ throw new IllegalStateException("controlled unusable stored material");+ }+ return applyPublication(call);+ }).when(runtime).publishListener(any(), eq(REGION), any(), any(), any(), any());+ List<LogRecord> warnings = LogCapture.capture(ElbV2Service.class,+ () -> assertDoesNotThrow(reloaded::restorePersistedRuntime));+ String reason = domainFailure ? "controlled missing stored material" : "controlled unusable stored material";+ assertTrue(warnings.stream().anyMatch(record -> record.getParameters() != null+ && record.getParameters().length == 3+ && reason.equals(record.getParameters()[2])), "restore warning must explain why the listener was skipped");+ ArgumentCaptor<Listener> restored = ArgumentCaptor.captor();+ verify(runtime, times(2)).publishListener(restored.capture(), eq(REGION), any(), any(), any(), any());+ assertEquals(List.of(broken.getListenerArn(), healthy.getListenerArn()).stream().sorted().toList(),+ restored.getAllValues().stream().map(Listener::getListenerArn).sorted().toList());+ assertEquals(2, reloaded.describeListeners(REGION, lb, List.of()).size());+ allowPublications(runtime);+ assertDoesNotThrow(reloaded::restorePersistedRuntime);+ assertEquals(2, reloaded.describeListeners(REGION, lb, List.of()).size());+ }++ /**+ * A resolver that finds the certificate once and not again, which is what a+ * {@code DeleteServerCertificate} landing between the check outside the guard and the one+ * under it looks like from inside the call.+ */+ private static CertificateReferenceResolver deletedOnTheSecondLook() {+ CertificateReferenceResolver resolver = mock(CertificateReferenceResolver.class);+ AtomicBoolean held = new AtomicBoolean();+ when(resolver.exists(anyString(), anyString())).thenAnswer(call -> !held.get());+ doAnswer(invocation -> {+ held.set(true);+ try {+ return invocation.getArgument(1, Supplier.class).get();+ } finally {+ held.set(false);+ }+ }).when(resolver).supplyWhileHeld(any(), any());+ return resolver;+ }++ private String createTargetGroup(String name) {+ return service.createTargetGroup(+ REGION, name, "HTTP", "HTTP1", 9999, "vpc-a", "instance",+ "HTTP", "traffic-port", true, "/v1/ready", 30, 5, 5, 2, "200",+ "ipv4", Map.of()).getTargetGroupArn();+ }++ private static Action forwardAction(String targetGroupArn) {+ Action action = new Action();+ action.setType("forward");+ action.setTargetGroupArn(targetGroupArn);+ return action;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2DefaultAttributesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2DefaultAttributesIntegrationTest.javaindex 19f97a42fa..f6940d360e 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2DefaultAttributesIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2DefaultAttributesIntegrationTest.java@@ -157,6 +157,35 @@ class ElbV2DefaultAttributesIntegrationTest {not(hasItem("idle_timeout.timeout_seconds")));}+ @Test+ void aGatewayListenerRetainsItsControlPlaneWithoutAPort() {+ String arn = createLoadBalancer("attrs-gwlb-listener", "gateway", "10.120.");+ try {+ String listener = given().header("Authorization", AUTH).formParam("Action", "CreateListener")+ .formParam("LoadBalancerArn", arn).formParam("Protocol", "GENEVE")+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .when().post("/").then().statusCode(200).extract()+ .path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");+ given().header("Authorization", AUTH).formParam("Action", "ModifyListener")+ .formParam("ListenerArn", listener)+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "201")+ .when().post("/").then().statusCode(200);+ given().header("Authorization", AUTH).formParam("Action", "DescribeListeners")+ .formParam("ListenerArns.member.1", listener).when().post("/").then().statusCode(200)+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Protocol", equalTo("GENEVE"))+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Port.text()", equalTo(""))+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.DefaultActions.member.FixedResponseConfig.StatusCode",+ equalTo("201"));+ given().header("Authorization", AUTH).formParam("Action", "DeleteListener")+ .formParam("ListenerArn", listener).when().post("/").then().statusCode(200);+ } finally {+ given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", arn).when().post("/").then().statusCode(200);+ }+ }+@Testvoid aModifiedAttributeWinsOverItsDefaultAndTheRestStillReport() {String arn = createLoadBalancer("attrs-modified", "application", "10.99.");diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HttpsDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HttpsDataPlaneIntegrationTest.javanew file mode 100644index 0000000000..9a7453f779--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HttpsDataPlaneIntegrationTest.java@@ -0,0 +1,1783 @@+package io.github.hectorvent.floci.services.elbv2;++import com.sun.net.httpserver.HttpServer;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;+import io.github.hectorvent.floci.services.acm.AcmService;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.Certificate;+import io.github.hectorvent.floci.services.acm.model.CertificateOptions;+import io.github.hectorvent.floci.services.acm.model.CertificateStatus;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.services.acm.model.ValidationMethod;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.arc.ClientProxy;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import io.restassured.response.Response;+import io.restassured.specification.RequestSpecification;+import io.vertx.core.Future;+import io.vertx.core.Vertx;+import io.vertx.core.buffer.Buffer;+import io.vertx.core.http.HttpServerOptions;+import io.vertx.core.net.PemKeyCertOptions;+import io.vertx.core.net.SSLOptions;+import jakarta.inject.Inject;+import org.junit.jupiter.api.AfterAll;+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 javax.net.ssl.SSLContext;+import javax.net.ssl.SSLParameters;+import javax.net.ssl.SSLSession;+import javax.net.ssl.SSLSocket;+import javax.net.ssl.TrustManagerFactory;++import java.io.BufferedReader;+import java.io.ByteArrayInputStream;+import java.io.EOFException;+import java.io.IOException;+import java.io.InputStreamReader;+import java.io.OutputStream;+import java.net.ConnectException;+import java.net.InetSocketAddress;+import java.net.Socket;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.nio.charset.StandardCharsets;+import java.security.KeyStore;+import java.security.MessageDigest;+import java.security.cert.CertificateFactory;+import java.security.cert.X509Certificate;+import java.time.Duration;+import java.util.HexFormat;+import java.util.List;+import java.util.Map;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicReference;+import java.util.function.BooleanSupplier;++import static io.restassured.RestAssured.given;+import static org.awaitility.Awaitility.await;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertAll;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertInstanceOf;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.AdditionalAnswers.delegatesTo;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.mock;++@QuarkusTest+@TestProfile(ElbV2HttpsDataPlaneIntegrationTest.RealElbV2DataPlaneProfile.class)+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class ElbV2HttpsDataPlaneIntegrationTest {++ public static final class RealElbV2DataPlaneProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.elbv2.mock", "false");+ }+ }++ private static final String REGION = "us-east-1";+ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260720/us-east-1/elasticloadbalancing/aws4_request";+ private static final String SHARED_CERTIFICATE_HOST = "shared.elb.localhost.localstack.cloud";+ private static final int HTTPS_PORT = 7794;+ private static final int HTTP_PORT = 7795;++ private static String firstLbArn;+ private static String firstTargetGroupArn;+ private static String firstListenerArn;+ private static String secondLbArn;+ private static String secondListenerArn;+ private static String httpLbArn;+ private static String httpListenerArn;+ private static HttpServer targetServer;++ @Inject+ AcmService acmService;++ @Inject+ ElbV2Service elbV2Service;++ @Inject+ ElbV2DataPlane dataPlane;++ @BeforeAll+ static void startTargetServer() throws IOException {+ RestAssuredJsonUtils.configureAwsContentTypes();+ targetServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ targetServer.createContext("/", exchange -> {+ byte[] response = "target".getBytes(StandardCharsets.UTF_8);+ exchange.getResponseHeaders().set("Content-Type", "text/plain");+ exchange.sendResponseHeaders(200, response.length);+ try (OutputStream output = exchange.getResponseBody()) {+ output.write(response);+ }+ });+ targetServer.start();+ }++ @AfterAll+ static void stopTargetServer() {+ if (targetServer != null) {+ targetServer.stop(0);+ }+ }++ @Test+ @Order(-7)+ void acmAssociationsSurviveReimportUntilTheLastListenerAndPersistedConsumerRelease() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("acm-associations");+ Certificate certificate = requestCertificate(loadBalancer.dnsName());+ String persistedConsumer = "arn:aws:cognito-idp:us-east-1:000000000000:userpool/persisted-consumer";+ boolean persisted = false;+ try {+ createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT, certificate.getArn(), "first");+ String second = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTP_PORT, certificate.getArn(), "second");+ acmService.addInUseBy(certificate.getArn(), persistedConsumer, REGION);+ persisted = true;+ assertAcmConsumers(certificate.getArn(), List.of(loadBalancer.arn(), persistedConsumer));+ assertEquals(List.of(persistedConsumer), acmService.getCertificate(certificate.getArn(), REGION).getInUseBy(),+ "computed load-balancer references must not be stored in ACM");+ assertAcmDeleteInUse(certificate.getArn());+ CertificateGenerator.GeneratedCertificate replacement = new CertificateGenerator().generateSelfSignedCertificate(+ loadBalancer.dnsName(), List.of(), KeyAlgorithm.RSA_2048);+ Certificate current = acmService.importCertificate(replacement.certificatePem(), replacement.privateKeyPem(),+ null, certificate.getArn(), Map.of(), REGION);+ assertAcmConsumers(current.getArn(), List.of(loadBalancer.arn(), persistedConsumer));+ assertEquals(List.of(persistedConsumer), current.getInUseBy());+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "first", current, certificate, current);+ HttpsResult secondWire = awaitHttpsAtPort(loadBalancer.dnsName(), HTTP_PORT, current);+ assertEquals("second", secondWire.body());+ assertPeerCertificate(secondWire.session(), current, loadBalancer.dnsName());+ given().header("Authorization", AUTH).formParam("Action", "DeleteListener")+ .formParam("ListenerArn", second).when().post("/").then().statusCode(200);+ assertAcmConsumers(current.getArn(), List.of(loadBalancer.arn(), persistedConsumer));+ assertAcmDeleteInUse(current.getArn());+ given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", loadBalancer.arn()).when().post("/").then().statusCode(200);+ assertAcmConsumers(current.getArn(), List.of(persistedConsumer));+ assertAcmDeleteInUse(current.getArn());+ acmService.removeInUseBy(current.getArn(), persistedConsumer, REGION);+ persisted = false;+ assertAcmConsumers(current.getArn(), List.of());+ acmRequest()+ .header("Authorization", accountAuthorization("test", "acm"))+ .header("X-Amz-Target", "CertificateManager.DeleteCertificate")+ .body(Map.of("CertificateArn", current.getArn())).when().post("/").then().statusCode(200);+ AwsException missing = assertThrows(AwsException.class, () -> acmService.getCertificate(current.getArn(), REGION));+ assertEquals("ResourceNotFoundException", missing.getErrorCode());+ } finally {+ boolean releasePersisted = persisted;+ assertAll("Clean every association fixture resource",+ () -> given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", loadBalancer.arn()).when().post("/").then().statusCode(200),+ () -> { if (releasePersisted) { acmService.removeInUseBy(certificate.getArn(), persistedConsumer, REGION); } },+ () -> {+ try {+ acmService.deleteCertificate(certificate.getArn(), REGION);+ } catch (AwsException failure) {+ if (!"ResourceNotFoundException".equals(failure.getErrorCode())) { throw failure; }+ }+ });+ }+ }++ private static RequestSpecification acmRequest() {+ return given().contentType("application/x-amz-json-1.1");+ }++ private static void assertAcmDeleteInUse(String arn) {+ acmRequest()+ .header("Authorization", accountAuthorization("test", "acm"))+ .header("X-Amz-Target", "CertificateManager.DeleteCertificate")+ .body(Map.of("CertificateArn", arn)).when().post("/").then().statusCode(409)+ .body("__type", equalTo("ResourceInUseException"));+ }++ private static void assertAcmConsumers(String arn, List<String> expected) {+ List<String> actual = acmRequest()+ .header("Authorization", accountAuthorization("test", "acm"))+ .header("X-Amz-Target", "CertificateManager.DescribeCertificate")+ .body(Map.of("CertificateArn", arn)).when().post("/").then().statusCode(200)+ .extract().path("Certificate.InUseBy");+ assertEquals(expected.stream().sorted().toList(), actual.stream().sorted().toList());+ List<Map<String, Object>> summaries = acmRequest()+ .header("Authorization", accountAuthorization("test", "acm"))+ .header("X-Amz-Target", "CertificateManager.ListCertificates").body(Map.of())+ .when().post("/").then().statusCode(200).extract().path("CertificateSummaryList");+ Map<String, Object> summary = summaries.stream().filter(row -> arn.equals(row.get("CertificateArn")))+ .findFirst().orElseThrow();+ assertEquals(!expected.isEmpty(), summary.get("InUse"));+ }++ @Test+ @Order(-6)+ void controlPublicationDoesNotBlockCommittedTraffic() throws Exception {+ LoadBalancerRef first = createLoadBalancer("publication-traffic");+ LoadBalancerRef unrelated = createLoadBalancer("publication-other");+ ElbV2Service service = ClientProxy.unwrap(elbV2Service);+ ElbV2DataPlane original = service.dataPlane;+ ElbV2DataPlane delegating = mock(ElbV2DataPlane.class, delegatesTo(original));+ CountDownLatch entered = new CountDownLatch(1);+ CountDownLatch release = new CountDownLatch(1);+ ExecutorService worker = Executors.newSingleThreadExecutor();+ try {+ String listener = createFixedResponseListener(first.arn(), "HTTP", HTTP_PORT, null, "old");+ createFixedResponseListener(unrelated.arn(), "HTTP", HTTPS_PORT, null, "unrelated");+ assertPlainResponse(first.dnsName(), HTTP_PORT, "old");+ assertPlainResponse(unrelated.dnsName(), HTTPS_PORT, "unrelated");+ doAnswer(call -> original.updateListener(call.getArgument(0), () -> {+ entered.countDown();+ try {+ assertTrue(release.await(10, TimeUnit.SECONDS));+ } catch (InterruptedException failure) {+ Thread.currentThread().interrupt();+ throw new AssertionError(failure);+ }+ return call.getArgument(1, BooleanSupplier.class).getAsBoolean();+ })).when(delegating).updateListener(eq(HTTP_PORT), any());+ service.dataPlane = delegating;+ CompletableFuture<Response> changing = CompletableFuture.supplyAsync(() -> given()+ .header("Authorization", AUTH).formParam("Action", "ModifyListener")+ .formParam("ListenerArn", listener).formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", "new")+ .when().post("/"), worker);+ assertTrue(entered.await(5, TimeUnit.SECONDS));+ assertAll("Traffic must progress while control publication waits",+ () -> assertPlainResponse(first.dnsName(), HTTP_PORT, "old"),+ () -> assertPlainResponse(unrelated.dnsName(), HTTPS_PORT, "unrelated"));+ release.countDown();+ assertEquals(200, changing.get(10, TimeUnit.SECONDS).statusCode());+ awaitPlainResponse(first.dnsName(), HTTP_PORT, "new");+ } finally {+ release.countDown();+ worker.shutdown();+ try {+ assertTrue(worker.awaitTermination(10, TimeUnit.SECONDS));+ } finally {+ worker.shutdownNow();+ service.dataPlane = original;+ assertAll("Delete both traffic fixtures",+ () -> deleteLoadBalancer(first.arn()),+ () -> deleteLoadBalancer(unrelated.arn()));+ }+ }+ }++ @Test+ @Order(-5)+ void missingHttpsCertificateDoesNotPublishAListenerOrPreventAValidRetry() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("https-missing-create");+ Certificate certificate = requestCertificate(loadBalancer.dnsName());+ try {+ List<String> rulesBefore = given().header("Authorization", AUTH).formParam("Action", "DescribeRules")+ .when().post("/").then().statusCode(200).extract().xmlPath()+ .getList("DescribeRulesResponse.DescribeRulesResult.Rules.member.RuleArn");+ Response rejected = given().header("Authorization", AUTH)+ .formParam("Action", "CreateListener").formParam("LoadBalancerArn", loadBalancer.arn())+ .formParam("Protocol", "HTTPS").formParam("Port", HTTPS_PORT)+ .formParam("Tags.member.1.Key", "missing-certificate")+ .formParam("Tags.member.1.Value", "must-not-publish")+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", "invalid")+ .when().post("/");+ List<String> published = given().header("Authorization", AUTH)+ .formParam("Action", "DescribeListeners").formParam("LoadBalancerArn", loadBalancer.arn())+ .when().post("/").then().statusCode(200).extract().xmlPath()+ .getList("DescribeListenersResponse.DescribeListenersResult.Listeners.member.ListenerArn");+ assertAll("Refuse before publishing listener, default rule, or tags",+ () -> assertEquals(400, rejected.statusCode()),+ () -> assertTrue(published.isEmpty(), "failed create must not leave a visible listener"),+ () -> assertEquals(rulesBefore, given().header("Authorization", AUTH)+ .formParam("Action", "DescribeRules").when().post("/").then().statusCode(200)+ .extract().xmlPath().getList("DescribeRulesResponse.DescribeRulesResult.Rules.member.RuleArn")),+ () -> {+ for (String listener : published) {+ assertTrue(given().header("Authorization", AUTH).formParam("Action", "DescribeRules")+ .formParam("ListenerArn", listener).when().post("/").then().statusCode(200)+ .extract().xmlPath().getList("DescribeRulesResponse.DescribeRulesResult.Rules.member").isEmpty(),+ "failed create must not leave its default rule");+ }+ },+ () -> {+ for (String listener : published) {+ assertTrue(given().header("Authorization", AUTH).formParam("Action", "DescribeTags")+ .formParam("ResourceArns.member.1", listener).when().post("/").then().statusCode(200)+ .extract().xmlPath().getList("DescribeTagsResponse.DescribeTagsResult.TagDescriptions.member.Tags.member").isEmpty(),+ "failed create must not leave its tags");+ }+ });+ createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT, certificate.getArn(), "retry");+ HttpsResult retried = awaitHttps(loadBalancer.dnsName(), certificate);+ assertEquals(200, retried.statusCode());+ assertEquals("retry", retried.body());+ assertPeerCertificate(retried.session(), certificate, loadBalancer.dnsName());+ } finally {+ cleanupMissingCertificateFixture(loadBalancer, certificate);+ }+ }++ @Test+ @Order(-4)+ void missingHttpsCertificatePreservesTheHttpListenerAndItsDefaultRule() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("https-missing-modify");+ Certificate certificate = requestCertificate(loadBalancer.dnsName());+ String listener = null;+ try {+ listener = createFixedResponseListener(loadBalancer.arn(), "HTTP", HTTPS_PORT, null, "original");+ awaitPlainResponse(loadBalancer.dnsName(), HTTPS_PORT, "original");+ Response rejected = given().header("Authorization", AUTH)+ .formParam("Action", "ModifyListener").formParam("ListenerArn", listener)+ .formParam("Protocol", "HTTPS").formParam("SslPolicy", "must-not-publish")+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", "invalid")+ .when().post("/");+ Response described = given().header("Authorization", AUTH)+ .formParam("Action", "DescribeListeners").formParam("ListenerArns.member.1", listener)+ .when().post("/").then().statusCode(200).extract().response();+ String result = "DescribeListenersResponse.DescribeListenersResult.Listeners.member.";+ String ownedListener = listener;+ assertAll("Refused conversion must preserve control and data planes",+ () -> assertEquals(400, rejected.statusCode()),+ () -> assertEquals("HTTP", described.path(result + "Protocol")),+ () -> assertEquals(String.valueOf(HTTPS_PORT), described.path(result + "Port")),+ () -> assertEquals("", described.path(result + "SslPolicy")),+ () -> assertTrue(described.xmlPath().getList(result + "Certificates.member").isEmpty()),+ () -> assertEquals("original", described.path(result+ + "DefaultActions.member.FixedResponseConfig.MessageBody")),+ () -> assertEquals("original", given().header("Authorization", AUTH)+ .formParam("Action", "DescribeRules").formParam("ListenerArn", ownedListener)+ .when().post("/").then().statusCode(200).extract()+ .path("DescribeRulesResponse.DescribeRulesResult.Rules.member.Actions.member.FixedResponseConfig.MessageBody")),+ () -> assertPlainResponse(loadBalancer.dnsName(), HTTPS_PORT, "original"));+ given().header("Authorization", AUTH).formParam("Action", "ModifyListener")+ .formParam("ListenerArn", listener).formParam("Protocol", "HTTPS")+ .formParam("Certificates.member.1.CertificateArn", certificate.getArn())+ .when().post("/").then().statusCode(200);+ HttpsResult retried = awaitHttps(loadBalancer.dnsName(), certificate);+ assertEquals("original", retried.body());+ assertPeerCertificate(retried.session(), certificate, loadBalancer.dnsName());+ } finally {+ cleanupMissingCertificateFixture(loadBalancer, certificate);+ }+ }++ @Test+ @Order(-3)+ void createCannotPublishAfterAConflictingProtocolWinsThePort() throws Exception {+ LoadBalancerRef first = createLoadBalancer("protocol-create-first");+ LoadBalancerRef winner = createLoadBalancer("protocol-create-winner");+ Certificate certificate = requestCertificate(winner.dnsName());+ ElbV2Service service = ClientProxy.unwrap(elbV2Service);+ ElbV2DataPlane original = service.dataPlane;+ CountDownLatch preflight = new CountDownLatch(1);+ CountDownLatch release = new CountDownLatch(1);+ AtomicReference<String> attemptedArn = new AtomicReference<>();+ ExecutorService worker = Executors.newSingleThreadExecutor();+ CompletableFuture<Response> creation = null;+ try {+ service.dataPlane = preflightBarrier(original, "HTTP", preflight, release, attemptedArn);+ creation = CompletableFuture.supplyAsync(() -> given().header("Authorization", AUTH)+ .formParam("Action", "CreateListener").formParam("LoadBalancerArn", first.arn())+ .formParam("Protocol", "HTTP").formParam("Port", HTTPS_PORT)+ .formParam("Tags.member.1.Key", "protocol-loser").formParam("Tags.member.1.Value", "absent")+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", "loser")+ .when().post("/"), worker);+ assertTrue(preflight.await(5, TimeUnit.SECONDS), "first preflight did not complete");+ createFixedResponseListener(first.arn(), "HTTP", HTTP_PORT, null, "unrelated");+ awaitPlainResponse(first.dnsName(), HTTP_PORT, "unrelated");+ String winnerArn = createFixedResponseListener(winner.arn(), "HTTPS", HTTPS_PORT,+ certificate.getArn(), "winner");+ assertEquals("winner", awaitHttps(winner.dnsName(), certificate).body());+ release.countDown();+ Response rejected = creation.get(10, TimeUnit.SECONDS);+ List<String> actualPorts = given().header("Authorization", AUTH)+ .formParam("Action", "DescribeListeners").formParam("LoadBalancerArn", first.arn())+ .when().post("/").then().statusCode(200).extract().xmlPath()+ .getList("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Port");+ assertAll("A stale successful preflight must not publish the losing request",+ () -> assertEquals(400, rejected.statusCode()),+ () -> assertEquals(List.of(String.valueOf(HTTP_PORT)), actualPorts),+ () -> assertTrue(given().header("Authorization", AUTH).formParam("Action", "DescribeRules")+ .formParam("ListenerArn", attemptedArn.get()).when().post("/").then().statusCode(200)+ .extract().xmlPath().getList("DescribeRulesResponse.DescribeRulesResult.Rules.member").isEmpty()),+ () -> assertTrue(given().header("Authorization", AUTH).formParam("Action", "DescribeTags")+ .formParam("ResourceArns.member.1", attemptedArn.get()).when().post("/").then().statusCode(200)+ .extract().xmlPath().getList("DescribeTagsResponse.DescribeTagsResult.TagDescriptions.member.Tags.member").isEmpty()),+ () -> assertEquals("winner", awaitHttps(winner.dnsName(), certificate).body()),+ () -> assertPlainResponse(first.dnsName(), HTTP_PORT, "unrelated"));+ given().header("Authorization", AUTH).formParam("Action", "DeleteListener")+ .formParam("ListenerArn", winnerArn).when().post("/").then().statusCode(200);+ awaitListenerPortClosed();+ createFixedResponseListener(first.arn(), "HTTP", HTTPS_PORT, null, "retry");+ awaitPlainResponse(first.dnsName(), HTTPS_PORT, "retry");+ } finally {+ release.countDown();+ worker.shutdownNow();+ try {+ assertTrue(worker.awaitTermination(10, TimeUnit.SECONDS), "creation worker did not stop");+ } finally {+ service.dataPlane = original;+ cleanupProtocolFixtures(first, winner, certificate);+ }+ }+ }++ @Test+ @Order(-2)+ void modifyCannotPublishAfterAConflictingProtocolWinsTheDestinationPort() throws Exception {+ LoadBalancerRef first = createLoadBalancer("protocol-modify-first");+ LoadBalancerRef winner = createLoadBalancer("protocol-modify-winner");+ Certificate certificate = requestCertificate(first.dnsName());+ ElbV2Service service = ClientProxy.unwrap(elbV2Service);+ ElbV2DataPlane original = service.dataPlane;+ CountDownLatch preflight = new CountDownLatch(1);+ CountDownLatch release = new CountDownLatch(1);+ AtomicReference<String> attemptedArn = new AtomicReference<>();+ ExecutorService worker = Executors.newSingleThreadExecutor();+ try {+ String firstArn = createFixedResponseListener(first.arn(), "HTTP", HTTP_PORT, null, "original");+ awaitPlainResponse(first.dnsName(), HTTP_PORT, "original");+ service.dataPlane = preflightBarrier(original, "HTTPS", preflight, release, attemptedArn);+ CompletableFuture<Response> modification = CompletableFuture.supplyAsync(() ->+ given().header("Authorization", AUTH).formParam("Action", "ModifyListener")+ .formParam("ListenerArn", firstArn).formParam("Protocol", "HTTPS")+ .formParam("Port", HTTPS_PORT).formParam("SslPolicy", "must-not-publish")+ .formParam("Certificates.member.1.CertificateArn", certificate.getArn())+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", "invalid")+ .when().post("/"), worker);+ assertTrue(preflight.await(5, TimeUnit.SECONDS), "modify preflight did not complete");+ assertPlainResponse(first.dnsName(), HTTP_PORT, "original");+ String winnerArn = createFixedResponseListener(winner.arn(), "HTTP", HTTPS_PORT, null, "winner");+ awaitPlainResponse(winner.dnsName(), HTTPS_PORT, "winner");+ release.countDown();+ Response rejected = modification.get(10, TimeUnit.SECONDS);+ Response described = given().header("Authorization", AUTH).formParam("Action", "DescribeListeners")+ .formParam("ListenerArns.member.1", firstArn).when().post("/")+ .then().statusCode(200).extract().response();+ String result = "DescribeListenersResponse.DescribeListenersResult.Listeners.member.";+ assertAll("Refused destination must preserve the original listener and the competing winner",+ () -> assertEquals(400, rejected.statusCode()),+ () -> assertEquals("HTTP", described.path(result + "Protocol")),+ () -> assertEquals(String.valueOf(HTTP_PORT), described.path(result + "Port")),+ () -> assertEquals("", described.path(result + "SslPolicy")),+ () -> assertTrue(described.xmlPath().getList(result + "Certificates.member").isEmpty()),+ () -> assertEquals("original", described.path(result+ + "DefaultActions.member.FixedResponseConfig.MessageBody")),+ () -> assertPlainResponse(first.dnsName(), HTTP_PORT, "original"),+ () -> assertPlainResponse(winner.dnsName(), HTTPS_PORT, "winner"));+ given().header("Authorization", AUTH).formParam("Action", "DeleteListener")+ .formParam("ListenerArn", winnerArn).when().post("/").then().statusCode(200);+ awaitListenerPortClosed();+ given().header("Authorization", AUTH).formParam("Action", "ModifyListener")+ .formParam("ListenerArn", firstArn).formParam("Protocol", "HTTPS").formParam("Port", HTTPS_PORT)+ .formParam("Certificates.member.1.CertificateArn", certificate.getArn())+ .when().post("/").then().statusCode(200);+ assertEquals("original", awaitHttps(first.dnsName(), certificate).body());+ } finally {+ release.countDown();+ worker.shutdownNow();+ try {+ assertTrue(worker.awaitTermination(10, TimeUnit.SECONDS), "modification worker did not stop");+ } finally {+ service.dataPlane = original;+ cleanupProtocolFixtures(first, winner, certificate);+ }+ }+ }++ @Test+ @Order(-1)+ void portOnlyChangesReconcileCertificateChangesDuringMaterialPreparation() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("tls-material-retry");+ LoadBalancerRef unrelated = createLoadBalancer("tls-material-progress");+ ElbV2DataPlane runtime = ClientProxy.unwrap(dataPlane);+ CertificateReferenceResolver original = runtime.certificateResolver;+ ExecutorService worker = Executors.newSingleThreadExecutor();+ AtomicReference<CountDownLatch> entered = new AtomicReference<>(new CountDownLatch(1));+ AtomicReference<CountDownLatch> release = new AtomicReference<>(new CountDownLatch(1));+ AtomicReference<String> pausedCertificate = new AtomicReference<>();+ AtomicBoolean claimedPause = new AtomicBoolean();+ AtomicBoolean refuseUnchanged = new AtomicBoolean(true);+ AtomicBoolean iamPresent = new AtomicBoolean();+ AtomicInteger iamReads = new AtomicInteger();+ String iamName = "tls-material-" + Long.toUnsignedString(System.nanoTime(), 36);+ Certificate first = null;+ Certificate added = null;+ try {+ first = requestCertificate(loadBalancer.dnsName());+ String addedHost = "later-material.elb.localhost.localstack.cloud";+ added = requestCertificate(addedHost);+ CertificateGenerator.GeneratedCertificate pair = new CertificateGenerator().generateSelfSignedCertificate(+ "additional-material.example.test", List.of(), KeyAlgorithm.RSA_2048);+ String iamArn = uploadIamCertificate("test", iamName, pair);+ iamPresent.set(true);+ String listener = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT, first.getArn(), "original");+ given().header("Authorization", AUTH).formParam("Action", "AddListenerCertificates")+ .formParam("ListenerArn", listener).formParam("Certificates.member.1.CertificateArn", iamArn)+ .when().post("/").then().statusCode(200);+ assertEquals("original", awaitHttps(loadBalancer.dnsName(), first).body());+ CertificateReferenceResolver wrapped = mock(CertificateReferenceResolver.class, delegatesTo(original));+ doAnswer(call -> {+ String certificate = call.getArgument(2);+ if (iamArn.equals(certificate)) {+ iamReads.incrementAndGet();+ if (refuseUnchanged.compareAndSet(true, false)) {+ throw new AwsException("CertificateNotFound", "The specified certificate does not exist.", 400);+ }+ }+ if (certificate.equals(pausedCertificate.get()) && claimedPause.compareAndSet(false, true)) {+ entered.get().countDown();+ assertTrue(release.get().await(30, TimeUnit.SECONDS), "material preparation was not released");+ }+ return original.publishedMaterial(call.getArgument(0), call.getArgument(1), certificate);+ }).when(wrapped).publishedMaterial(anyString(), anyString(), anyString());+ runtime.certificateResolver = wrapped;+ given().header("Authorization", AUTH).formParam("Action", "ModifyListener")+ .formParam("ListenerArn", listener).formParam("Port", HTTP_PORT)+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));+ assertEquals(1, iamReads.get(), "an unchanged snapshot must preserve its preparation error");+ given().header("Authorization", AUTH).formParam("Action", "DescribeListeners")+ .formParam("ListenerArns.member.1", listener).when().post("/").then().statusCode(200)+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Port",+ equalTo(String.valueOf(HTTPS_PORT)));+ pausedCertificate.set(iamArn);+ CompletableFuture<Response> moving = CompletableFuture.supplyAsync(() -> given().header("Authorization", AUTH)+ .formParam("Action", "ModifyListener").formParam("ListenerArn", listener)+ .formParam("Port", HTTP_PORT).when().post("/"), worker);+ assertTrue(entered.get().await(5, TimeUnit.SECONDS));+ given().header("Authorization", AUTH).formParam("Action", "RemoveListenerCertificates")+ .formParam("ListenerArn", listener).formParam("Certificates.member.1.CertificateArn", iamArn)+ .when().post("/").then().statusCode(200);+ given().header("Authorization", accountAuthorization("test", "iam"))+ .formParam("Action", "DeleteServerCertificate").formParam("ServerCertificateName", iamName)+ .when().post("/").then().statusCode(200);+ iamPresent.set(false);+ String progress = createFixedResponseListener(unrelated.arn(), "HTTP", HTTP_PORT, null, "progress");+ awaitPlainResponse(unrelated.dnsName(), HTTP_PORT, "progress");+ assertEquals("original", awaitHttps(loadBalancer.dnsName(), first).body());+ given().header("Authorization", AUTH).formParam("Action", "DeleteListener")+ .formParam("ListenerArn", progress).when().post("/").then().statusCode(200);+ awaitListenerPortClosed(HTTP_PORT);+ release.get().countDown();+ assertEquals(200, moving.get(10, TimeUnit.SECONDS).statusCode());+ assertEquals(2, iamReads.get(), "retry must discard the removed, deleted certificate");+ HttpsResult moved = awaitHttpsAtPort(loadBalancer.dnsName(), HTTP_PORT, first);+ assertEquals("original", moved.body());+ assertPeerCertificate(moved.session(), first, loadBalancer.dnsName());+ given().header("Authorization", AUTH).formParam("Action", "DescribeListenerCertificates")+ .formParam("ListenerArn", listener).when().post("/").then().statusCode(200)+ .body("DescribeListenerCertificatesResponse.DescribeListenerCertificatesResult.Certificates.member.CertificateArn",+ equalTo(first.getArn()));+ entered.set(new CountDownLatch(1));+ release.set(new CountDownLatch(1));+ claimedPause.set(false);+ pausedCertificate.set(first.getArn());+ CompletableFuture<Response> movingBack = CompletableFuture.supplyAsync(() -> given().header("Authorization", AUTH)+ .formParam("Action", "ModifyListener").formParam("ListenerArn", listener)+ .formParam("Port", HTTPS_PORT).when().post("/"), worker);+ assertTrue(entered.get().await(5, TimeUnit.SECONDS));+ given().header("Authorization", AUTH).formParam("Action", "AddListenerCertificates")+ .formParam("ListenerArn", listener).formParam("Certificates.member.1.CertificateArn", added.getArn())+ .when().post("/").then().statusCode(200);+ release.get().countDown();+ assertEquals(200, movingBack.get(10, TimeUnit.SECONDS).statusCode());+ given().header("Authorization", AUTH).formParam("Action", "DescribeListenerCertificates")+ .formParam("ListenerArn", listener).when().post("/").then().statusCode(200)+ .body("DescribeListenerCertificatesResponse.DescribeListenerCertificatesResult.Certificates.member.collect { it.CertificateArn.text() }",+ equalTo(List.of(first.getArn(), added.getArn())));+ HttpsResult finalResult = awaitHttps(loadBalancer.dnsName(), first);+ assertEquals("original", finalResult.body());+ assertPeerCertificate(finalResult.session(), first, loadBalancer.dnsName());+ HttpsResult addedResult = awaitHttps(addedHost, added);+ assertEquals(200, addedResult.statusCode());+ assertEquals("original", addedResult.body());+ assertPeerCertificate(addedResult.session(), added, addedHost);+ } finally {+ release.get().countDown();+ worker.shutdown();+ try {+ assertTrue(worker.awaitTermination(10, TimeUnit.SECONDS), "material worker did not stop");+ } finally {+ worker.shutdownNow();+ runtime.certificateResolver = original;+ Certificate ownedFirst = first;+ Certificate ownedAdded = added;+ assertAll("Clean all material-retry resources after success or failure",+ () -> given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", loadBalancer.arn()).when().post("/").then().statusCode(200),+ () -> given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", unrelated.arn()).when().post("/").then().statusCode(200),+ () -> awaitListenerPortClosed(HTTPS_PORT),+ () -> awaitListenerPortClosed(HTTP_PORT),+ () -> {+ if (iamPresent.get()) {+ given().header("Authorization", accountAuthorization("test", "iam"))+ .formParam("Action", "DeleteServerCertificate").formParam("ServerCertificateName", iamName)+ .when().post("/").then().statusCode(200);+ }+ },+ () -> { if (ownedFirst != null) { acmService.deleteCertificate(ownedFirst.getArn(), REGION); } },+ () -> { if (ownedAdded != null) { acmService.deleteCertificate(ownedAdded.getArn(), REGION); } });+ }+ }+ }++ private static ElbV2DataPlane preflightBarrier(ElbV2DataPlane original, String protocol,+ CountDownLatch preflight, CountDownLatch release,+ AtomicReference<String> attemptedArn) {+ ElbV2DataPlane wrapped = mock(ElbV2DataPlane.class, delegatesTo(original));+ doAnswer(invocation -> {+ String arn = invocation.getArgument(0);+ int port = invocation.getArgument(1);+ String actualProtocol = invocation.getArgument(2);+ original.requireCompatibleListenerProtocol(arn, port, actualProtocol);+ if (port == HTTPS_PORT && protocol.equals(actualProtocol) && attemptedArn.compareAndSet(null, arn)) {+ preflight.countDown();+ assertTrue(release.await(30, TimeUnit.SECONDS), "preflight was not released");+ }+ return null;+ }).when(wrapped).requireCompatibleListenerProtocol(anyString(), anyInt(), anyString());+ return wrapped;+ }++ private void cleanupProtocolFixtures(LoadBalancerRef first, LoadBalancerRef winner, Certificate certificate) {+ assertAll("Remove both protocol-race fixtures even when the loser was published",+ () -> given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", first.arn()).when().post("/").then().statusCode(200),+ () -> given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", winner.arn()).when().post("/").then().statusCode(200),+ ElbV2HttpsDataPlaneIntegrationTest::awaitListenerPortClosed,+ () -> acmService.deleteCertificate(certificate.getArn(), REGION));+ }++ private void cleanupMissingCertificateFixture(LoadBalancerRef loadBalancer, Certificate certificate) {+ assertAll("Clean up both successful and partially published listener requests",+ () -> {+ List<String> listeners = given().header("Authorization", AUTH)+ .formParam("Action", "DescribeListeners").formParam("LoadBalancerArn", loadBalancer.arn())+ .when().post("/").then().statusCode(200).extract().xmlPath()+ .getList("DescribeListenersResponse.DescribeListenersResult.Listeners.member.ListenerArn");+ for (String listener : listeners) {+ given().header("Authorization", AUTH).formParam("Action", "DeleteListener")+ .formParam("ListenerArn", listener).when().post("/").then().statusCode(200);+ }+ awaitListenerPortClosed();+ },+ () -> given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", loadBalancer.arn()).when().post("/").then().statusCode(200),+ () -> acmService.deleteCertificate(certificate.getArn(), REGION));+ }++ private static void assertPlainResponse(String host, int port, String body) throws Exception {+ try (HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build()) {+ HttpResponse<String> response = client.send(HttpRequest.newBuilder(+ URI.create("http://" + host + ":" + port + "/"))+ .timeout(Duration.ofSeconds(2)).GET().build(), HttpResponse.BodyHandlers.ofString());+ assertEquals(200, response.statusCode());+ assertEquals(body, response.body());+ }+ }++ private static void awaitPlainResponse(String host, int port, String body) {+ await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() ->+ assertPlainResponse(host, port, body));+ }++ @Test+ @Order(1)+ void terminatesTlsWithSniSelectedAcmCertificatesAndKeepsHttpListenersPlain() throws Exception {+ LoadBalancerRef first = createLoadBalancer("https-first");+ firstLbArn = first.arn();+ Certificate firstCertificate = requestCertificate(first.dnsName());+ firstTargetGroupArn = createHealthyTargetGroup();+ firstListenerArn = createForwardListener(+ first.arn(), HTTPS_PORT, firstCertificate.getArn(), firstTargetGroupArn);++ describeHttpsListener(firstListenerArn, firstCertificate.getArn());+ awaitTargetHealthy(firstTargetGroupArn);+ HttpsResult firstResult = awaitHttps(first.dnsName(), firstCertificate);+ assertEquals(200, firstResult.statusCode());+ assertEquals("target", firstResult.body());+ assertPeerCertificate(firstResult.session(), firstCertificate, first.dnsName());++ LoadBalancerRef second = createLoadBalancer("https-second");+ secondLbArn = second.arn();+ Certificate secondCertificate = requestCertificate(second.dnsName());+ secondListenerArn = createFixedResponseListener(+ second.arn(), "HTTPS", HTTPS_PORT, secondCertificate.getArn(), "second");++ HttpsResult refreshedFirstResult = awaitHttps(first.dnsName(), firstCertificate);+ assertEquals("target", refreshedFirstResult.body());+ assertPeerCertificate(refreshedFirstResult.session(), firstCertificate, first.dnsName());++ HttpsResult secondResult = awaitHttps(second.dnsName(), secondCertificate);+ assertEquals("second", secondResult.body());+ assertPeerCertificate(secondResult.session(), secondCertificate, second.dnsName());+ HttpsResult ambiguous = awaitHttps(SHARED_CERTIFICATE_HOST, firstCertificate, secondCertificate);+ assertEquals(502, ambiguous.statusCode());+ assertEquals("No listener for host", ambiguous.body());++ LoadBalancerRef http = createLoadBalancer("http-control");+ httpLbArn = http.arn();+ httpListenerArn = createFixedResponseListener(http.arn(), "HTTP", HTTP_PORT, null, "plain");+ given()+ .baseUri("http://" + http.dnsName())+ .port(HTTP_PORT)+ .when()+ .get("/")+ .then()+ .statusCode(200)+ .body(equalTo("plain"));++ deleteListener(firstListenerArn);+ firstListenerArn = null;+ assertEquals("second", awaitHttps(second.dnsName(), secondCertificate).body());+ assertEquals("second", awaitHttps(SHARED_CERTIFICATE_HOST, secondCertificate).body());++ deleteListener(secondListenerArn);+ secondListenerArn = null;+ await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {+ Exception failure = assertThrows(Exception.class,+ () -> trustedClient(secondCertificate).send(+ HttpRequest.newBuilder(URI.create("https://" + second.dnsName() + ":" + HTTPS_PORT + "/"))+ .timeout(Duration.ofSeconds(1))+ .GET()+ .build(),+ HttpResponse.BodyHandlers.ofString()));+ assertTrue(hasCause(failure, ConnectException.class), failure.toString());+ });+ }++ @Test+ @Order(2)+ void iamServerCertificateTerminatesTls() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("https-iam");+ String name = "elb-tls-iam-" + Long.toString(System.nanoTime(), 36);+ String listenerArn = null;+ boolean uploaded = false;+ CertificateGenerator.GeneratedCertificate pair = new CertificateGenerator().generateSelfSignedCertificate(+ loadBalancer.dnsName(), List.of(), KeyAlgorithm.RSA_2048);+ try {+ String certificateArn = given()+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260720/us-east-1/iam/aws4_request")+ .formParam("Action", "UploadServerCertificate")+ .formParam("ServerCertificateName", name)+ .formParam("CertificateBody", pair.certificatePem())+ .formParam("PrivateKey", pair.privateKeyPem())+ .when().post("/").then().statusCode(200)+ .extract().path("UploadServerCertificateResponse.UploadServerCertificateResult"+ + ".ServerCertificateMetadata.Arn");+ uploaded = true;+ listenerArn = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT, certificateArn, "iam");+ Certificate expected = new Certificate();+ expected.setCertificateBody(pair.certificatePem());+ HttpsResult result = awaitHttps(loadBalancer.dnsName(), expected);+ assertEquals(200, result.statusCode());+ assertEquals("iam", result.body());+ assertPeerCertificate(result.session(), expected, loadBalancer.dnsName());+ } finally {+ try {+ deleteListener(listenerArn);+ deleteLoadBalancer(loadBalancer.arn());+ } finally {+ if (uploaded) {+ given()+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260720/us-east-1/iam/aws4_request")+ .formParam("Action", "DeleteServerCertificate")+ .formParam("ServerCertificateName", name)+ .when().post("/").then().statusCode(200);+ }+ }+ }+ }++ @Test+ @Order(3)+ void rejectedMixedProtocolChangePreservesBothHttpListeners() {+ LoadBalancerRef first = createLoadBalancer("mixed-before-first");+ LoadBalancerRef second = createLoadBalancer("mixed-before-second");+ Certificate certificate = requestCertificate(first.dnsName());+ String firstListener = null;+ String secondListener = null;+ try {+ firstListener = createFixedResponseListener(first.arn(), "HTTP", HTTP_PORT, null, "first");+ secondListener = createFixedResponseListener(second.arn(), "HTTP", HTTP_PORT, null, "second");+ given().baseUri("http://" + first.dnsName()).port(HTTP_PORT)+ .when().get("/").then().statusCode(200).body(equalTo("first"));+ given().baseUri("http://" + second.dnsName()).port(HTTP_PORT)+ .when().get("/").then().statusCode(200).body(equalTo("second"));+ Response rejected = given().header("Authorization", AUTH)+ .formParam("Action", "ModifyListener").formParam("ListenerArn", firstListener)+ .formParam("Protocol", "HTTPS")+ .formParam("Certificates.member.1.CertificateArn", certificate.getArn())+ .when().post("/");+ assertTrue(rejected.statusCode() >= 400);+ given().header("Authorization", AUTH).formParam("Action", "DescribeListeners")+ .formParam("ListenerArns.member.1", firstListener).when().post("/")+ .then().statusCode(200)+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Protocol", equalTo("HTTP"));+ given().baseUri("http://" + first.dnsName()).port(HTTP_PORT)+ .when().get("/").then().statusCode(200).body(equalTo("first"));+ given().baseUri("http://" + second.dnsName()).port(HTTP_PORT)+ .when().get("/").then().statusCode(200).body(equalTo("second"));+ } finally {+ deleteListener(firstListener);+ deleteListener(secondListener);+ deleteLoadBalancer(first.arn());+ deleteLoadBalancer(second.arn());+ acmService.deleteCertificate(certificate.getArn(), REGION);+ }+ }++ @Test+ @Order(4)+ void rejectedDefaultCertificateRemovalPreservesTlsListener() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("remove-default-before");+ Certificate certificate = requestCertificate(loadBalancer.dnsName());+ String listener = null;+ try {+ listener = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT,+ certificate.getArn(), "retained");+ HttpsResult before = awaitHttps(loadBalancer.dnsName(), certificate);+ assertEquals("retained", before.body());+ assertPeerCertificate(before.session(), certificate, loadBalancer.dnsName());+ Response rejected = given().header("Authorization", AUTH)+ .formParam("Action", "RemoveListenerCertificates").formParam("ListenerArn", listener)+ .formParam("Certificates.member.1.CertificateArn", certificate.getArn())+ .when().post("/");+ assertEquals(400, rejected.statusCode());+ assertEquals("OperationNotPermitted", rejected.xmlPath().getString("ErrorResponse.Error.Code"));+ given().header("Authorization", AUTH).formParam("Action", "DescribeListenerCertificates")+ .formParam("ListenerArn", listener).when().post("/").then().statusCode(200)+ .body("DescribeListenerCertificatesResponse.DescribeListenerCertificatesResult.Certificates.member.CertificateArn",+ equalTo(certificate.getArn()));+ HttpsResult after = awaitHttps(loadBalancer.dnsName(), certificate);+ assertEquals("retained", after.body());+ assertPeerCertificate(after.session(), certificate, loadBalancer.dnsName());+ } finally {+ deleteListener(listener);+ deleteLoadBalancer(loadBalancer.arn());+ acmService.deleteCertificate(certificate.getArn(), REGION);+ }+ }++ @Test+ @Order(5)+ void rejectedMixedProtocolCreationLeavesNoListenerAndCanRetry() throws Exception {+ LoadBalancerRef first = null;+ LoadBalancerRef second = null;+ Certificate certificate = null;+ String firstListener = null;+ String retryListener = null;+ try {+ first = createLoadBalancer("create-mixed-first");+ second = createLoadBalancer("create-mixed-second");+ certificate = requestCertificate(second.dnsName());+ firstListener = createFixedResponseListener(first.arn(), "HTTP", HTTP_PORT, null, "first");+ given().baseUri("http://" + first.dnsName()).port(HTTP_PORT)+ .when().get("/").then().statusCode(200).body(equalTo("first"));+ Response refused = given().header("Authorization", AUTH)+ .formParam("Action", "CreateListener").formParam("LoadBalancerArn", second.arn())+ .formParam("Protocol", "HTTPS").formParam("Port", HTTP_PORT)+ .formParam("Certificates.member.1.CertificateArn", certificate.getArn())+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", "second")+ .when().post("/");+ assertTrue(refused.statusCode() >= 400);+ List<String> remaining = given().header("Authorization", AUTH)+ .formParam("Action", "DescribeListeners").formParam("LoadBalancerArn", second.arn())+ .when().post("/").then().statusCode(200).extract().xmlPath()+ .getList("DescribeListenersResponse.DescribeListenersResult.Listeners.member.ListenerArn");+ assertTrue(remaining.isEmpty());+ given().baseUri("http://" + first.dnsName()).port(HTTP_PORT)+ .when().get("/").then().statusCode(200).body(equalTo("first"));+ retryListener = createFixedResponseListener(second.arn(), "HTTPS", HTTPS_PORT,+ certificate.getArn(), "retry");+ HttpsResult retry = awaitHttps(second.dnsName(), certificate);+ assertEquals("retry", retry.body());+ assertPeerCertificate(retry.session(), certificate, second.dnsName());+ } finally {+ deleteListener(firstListener);+ deleteListener(retryListener);+ if (first != null) {+ deleteLoadBalancer(first.arn());+ }+ if (second != null) {+ deleteLoadBalancer(second.arn());+ }+ if (certificate != null) {+ acmService.deleteCertificate(certificate.getArn(), REGION);+ }+ }+ }++ @Test+ @Order(6)+ void reimportedCertificateUsesOneSnapshotAcrossSharedPortListeners() throws Exception {+ LoadBalancerRef first = null;+ LoadBalancerRef second = null;+ Certificate current = null;+ String firstListener = null;+ String secondListener = null;+ try {+ first = createLoadBalancer("same-material-first");+ second = createLoadBalancer("same-material-second");+ CertificateGenerator generator = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate original = generator.generateSelfSignedCertificate(+ first.dnsName(), List.of(), KeyAlgorithm.RSA_2048);+ current = acmService.importCertificate(original.certificatePem(), original.privateKeyPem(),+ null, null, Map.of(), REGION);+ String arn = current.getArn();+ Certificate originalTrusted = current;+ firstListener = createFixedResponseListener(first.arn(), "HTTPS", HTTPS_PORT, arn, "first");+ HttpsResult initial = awaitHttps(first.dnsName(), current);+ assertEquals("first", initial.body());+ assertPeerCertificate(initial.session(), current, first.dnsName());+ CertificateGenerator.GeneratedCertificate replacement = generator.generateSelfSignedCertificate(+ first.dnsName(), List.of(second.dnsName(), SHARED_CERTIFICATE_HOST), KeyAlgorithm.RSA_2048);+ current = acmService.importCertificate(replacement.certificatePem(), replacement.privateKeyPem(),+ null, arn, Map.of(), REGION);+ assertEquals(arn, current.getArn());+ // A fresh handshake must see replacement material before another ELB publication.+ awaitHttpsMaterial(first.dnsName(), 200, "first", current, current, originalTrusted);+ secondListener = createFixedResponseListener(second.arn(), "HTTPS", HTTPS_PORT, arn, "second");+ awaitHttpsMaterial(first.dnsName(), 200, "first", current, current, originalTrusted);+ HttpsResult shared = awaitHttps(SHARED_CERTIFICATE_HOST, current);+ assertEquals(502, shared.statusCode());+ assertEquals("No listener for host", shared.body());+ assertPeerCertificate(shared.session(), current, SHARED_CERTIFICATE_HOST);+ HttpsResult firstResult = awaitHttps(first.dnsName(), current);+ assertEquals("first", firstResult.body());+ assertPeerCertificate(firstResult.session(), current, first.dnsName());+ HttpsResult secondResult = awaitHttps(second.dnsName(), current);+ assertEquals("second", secondResult.body());+ assertPeerCertificate(secondResult.session(), current, second.dnsName());+ deleteListener(secondListener);+ secondListener = null;+ awaitHttpsMaterial(SHARED_CERTIFICATE_HOST, 200, "first", current, current, originalTrusted);+ } finally {+ deleteListener(firstListener);+ deleteListener(secondListener);+ if (first != null) {+ deleteLoadBalancer(first.arn());+ }+ if (second != null) {+ deleteLoadBalancer(second.arn());+ }+ if (current != null) {+ acmService.deleteCertificate(current.getArn(), REGION);+ }+ }+ }++ @Test+ @Order(7)+ void cnOnlyAdditionalCertificateRoutesAfterASanCertificate() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("https-cn-only");+ Certificate sanCertificate = null;+ Certificate cnCertificate = null;+ Certificate unrelatedCertificate = null;+ LoadBalancerRef unrelated = null;+ String unrelatedListener = null;+ String listenerArn = null;+ String cnHost = "cn-only.elb.localhost.localstack.cloud";+ try {+ CertificateGenerator generator = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate san = generator.generateSelfSignedCertificate(+ loadBalancer.dnsName(), List.of(), KeyAlgorithm.RSA_2048);+ CertificateGenerator.GeneratedCertificate cn = generator.generateCaCertificate(cnHost);+ assertNull(parseCertificate(cn.certificatePem()).getSubjectAlternativeNames());+ assertTrue(parseCertificate(san.certificatePem()).getSubjectAlternativeNames().stream()+ .anyMatch(name -> loadBalancer.dnsName().equals(name.get(1))));+ sanCertificate = acmService.importCertificate(san.certificatePem(), san.privateKeyPem(),+ null, null, Map.of(), REGION);+ cnCertificate = acmService.importCertificate(cn.certificatePem(), cn.privateKeyPem(),+ null, null, Map.of(), REGION);+ listenerArn = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT,+ sanCertificate.getArn(), "cn-route");+ HttpsResult original = awaitHttps(loadBalancer.dnsName(), sanCertificate);+ assertEquals(200, original.statusCode());+ assertEquals("cn-route", original.body());+ assertPeerCertificate(original.session(), sanCertificate, loadBalancer.dnsName());+ unrelated = createLoadBalancer("https-cn-control");+ unrelatedCertificate = requestCertificate(unrelated.dnsName());+ unrelatedListener = createFixedResponseListener(unrelated.arn(), "HTTPS", HTTPS_PORT,+ unrelatedCertificate.getArn(), "unrelated-route");+ HttpsResult unrelatedBefore = awaitHttps(unrelated.dnsName(), unrelatedCertificate);+ assertEquals(200, unrelatedBefore.statusCode());+ assertEquals("unrelated-route", unrelatedBefore.body());+ assertPeerCertificate(unrelatedBefore.session(), unrelatedCertificate, unrelated.dnsName());+ given().header("Authorization", AUTH)+ .formParam("Action", "AddListenerCertificates").formParam("ListenerArn", listenerArn)+ .formParam("Certificates.member.1.CertificateArn", cnCertificate.getArn())+ .when().post("/").then().statusCode(200);++ HttpsResult additional = awaitHttps(cnHost, cnCertificate);+ assertEquals(200, additional.statusCode());+ assertEquals("cn-route", additional.body());+ X509Certificate peer = assertInstanceOf(X509Certificate.class,+ additional.session().getPeerCertificates()[0]);+ assertEquals(fingerprint(parseCertificate(cnCertificate.getCertificateBody())), fingerprint(peer));+ assertNull(peer.getSubjectAlternativeNames());+ HttpsResult retained = awaitHttps(loadBalancer.dnsName(), sanCertificate);+ assertEquals(200, retained.statusCode());+ assertEquals("cn-route", retained.body());+ assertPeerCertificate(retained.session(), sanCertificate, loadBalancer.dnsName());+ HttpsResult unrelatedAfter = awaitHttps(unrelated.dnsName(), unrelatedCertificate);+ assertEquals(200, unrelatedAfter.statusCode());+ assertEquals("unrelated-route", unrelatedAfter.body());+ assertPeerCertificate(unrelatedAfter.session(), unrelatedCertificate, unrelated.dnsName());+ } finally {+ deleteListener(unrelatedListener);+ deleteListener(listenerArn);+ if (unrelated != null) {+ deleteLoadBalancer(unrelated.arn());+ }+ if (unrelatedCertificate != null) {+ acmService.deleteCertificate(unrelatedCertificate.getArn(), REGION);+ }+ deleteLoadBalancer(loadBalancer.arn());+ if (sanCertificate != null) {+ acmService.deleteCertificate(sanCertificate.getArn(), REGION);+ }+ if (cnCertificate != null) {+ acmService.deleteCertificate(cnCertificate.getArn(), REGION);+ }+ }+ }++ @Test+ @Order(8)+ void anEstablishedTlsConnectionSurvivesCertificateReplacement() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("https-keepalive");+ Certificate original = null;+ Certificate replacement = null;+ String listener = null;+ try {+ original = requestCertificate(loadBalancer.dnsName());+ replacement = requestCertificate(loadBalancer.dnsName());+ assertNotEquals(fingerprint(parseCertificate(original.getCertificateBody())),+ fingerprint(parseCertificate(replacement.getCertificateBody())));+ listener = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT,+ original.getArn(), "before");+ HttpsResult before = awaitHttps(loadBalancer.dnsName(), original);+ assertEquals(200, before.statusCode());+ assertEquals("before", before.body());+ assertPeerCertificate(before.session(), original, loadBalancer.dnsName());+ try (HttpClient trust = trustedClient(original, replacement); Socket transport = new Socket()) {+ transport.connect(new InetSocketAddress("127.0.0.1", HTTPS_PORT), 2000);+ try (SSLSocket socket = (SSLSocket) trust.sslContext().getSocketFactory()+ .createSocket(transport, loadBalancer.dnsName(), HTTPS_PORT, true)) {+ socket.setSoTimeout(2000);+ SSLParameters parameters = socket.getSSLParameters();+ parameters.setEndpointIdentificationAlgorithm("HTTPS");+ socket.setSSLParameters(parameters);+ socket.startHandshake();+ assertPeerCertificate(socket.getSession(), original, loadBalancer.dnsName());+ BufferedReader reader = new BufferedReader(new InputStreamReader(+ socket.getInputStream(), StandardCharsets.UTF_8));+ assertPersistentResponse(socket, reader, loadBalancer.dnsName(), "before");+ given().header("Authorization", AUTH)+ .formParam("Action", "ModifyListener").formParam("ListenerArn", listener)+ .formParam("Certificates.member.1.CertificateArn", replacement.getArn())+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.ContentType", "text/plain")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", "after")+ .when().post("/").then().statusCode(200);+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "after", replacement, original, replacement);+ assertPersistentResponse(socket, reader, loadBalancer.dnsName(), "after");+ assertPeerCertificate(socket.getSession(), original, loadBalancer.dnsName());+ assertPersistentResponse(socket, reader, loadBalancer.dnsName(), "after");+ }+ }+ } finally {+ String ownedListener = listener;+ Certificate ownedOriginal = original;+ Certificate ownedReplacement = replacement;+ assertAll("Delete all keep-alive fixture resources",+ () -> {+ if (ownedListener != null) {+ given().header("Authorization", AUTH).formParam("Action", "DeleteListener")+ .formParam("ListenerArn", ownedListener).when().post("/").then().statusCode(200);+ }+ },+ () -> given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", loadBalancer.arn()).when().post("/").then().statusCode(200),+ () -> {+ if (ownedOriginal != null) {+ acmService.deleteCertificate(ownedOriginal.getArn(), REGION);+ }+ },+ () -> {+ if (ownedReplacement != null) {+ acmService.deleteCertificate(ownedReplacement.getArn(), REGION);+ }+ });+ }+ }++ private static void assertPersistentResponse(SSLSocket socket, BufferedReader reader, String host, String body)+ throws IOException {+ String request = "GET / HTTP/1.1\r\nHost: " + host + "\r\nConnection: keep-alive\r\n\r\n";+ socket.getOutputStream().write(request.getBytes(StandardCharsets.US_ASCII));+ socket.getOutputStream().flush();+ String status = reader.readLine();+ assertTrue(status != null && status.startsWith("HTTP/1.1 200 "), "Unexpected HTTP status: " + status);+ int length = -1;+ String header;+ while ((header = reader.readLine()) != null && !header.isEmpty()) {+ String[] parts = header.split(":", 2);+ if (parts.length == 2 && parts[0].equalsIgnoreCase("Content-Length")) {+ length = Integer.parseInt(parts[1].trim());+ }+ }+ assertEquals(body.length(), length, "The fixed ASCII response must be length-delimited");+ char[] received = new char[length];+ int offset = 0;+ while (offset < length) {+ int read = reader.read(received, offset, length - offset);+ if (read < 0) {+ throw new EOFException("Connection closed before the response body completed");+ }+ offset += read;+ }+ assertEquals(body, new String(received));+ }++ @Test+ @Order(9)+ void iamMaterialBelongsToTheListenerAccountAfterTheRequestEnds() throws Exception {+ String owner = "111111111111";+ String foreign = "222222222222";+ String name = "elb-tls-owner-" + Long.toString(System.nanoTime(), 36);+ LoadBalancerRef loadBalancer = null;+ String listener = null;+ String ownerCertificate = null;+ String foreignCertificate = null;+ try {+ Response created = given().header("Authorization", accountAuthorization(owner, "elasticloadbalancing"))+ .formParam("Action", "CreateLoadBalancer").formParam("Name", "https-scoped-iam")+ .formParam("Type", "application").when().post("/").then().statusCode(200).extract().response();+ loadBalancer = new LoadBalancerRef(+ created.xmlPath().getString("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"),+ created.xmlPath().getString("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.DNSName"));+ assertTrue(loadBalancer.arn().contains(":" + owner + ":"));+ CertificateGenerator generator = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate first = generator.generateSelfSignedCertificate(+ loadBalancer.dnsName(), List.of(), KeyAlgorithm.RSA_2048);+ CertificateGenerator.GeneratedCertificate other = generator.generateSelfSignedCertificate(+ loadBalancer.dnsName(), List.of(), KeyAlgorithm.RSA_2048);+ Certificate expected = new Certificate();+ expected.setCertificateBody(first.certificatePem());+ Certificate foreignExpected = new Certificate();+ foreignExpected.setCertificateBody(other.certificatePem());+ assertNotEquals(fingerprint(parseCertificate(first.certificatePem())),+ fingerprint(parseCertificate(other.certificatePem())));+ ownerCertificate = uploadIamCertificate(owner, name, first);+ foreignCertificate = uploadIamCertificate(foreign, name, other);+ assertTrue(ownerCertificate.contains(":" + owner + ":"));+ assertTrue(foreignCertificate.contains(":" + foreign + ":"));+ listener = given().header("Authorization", accountAuthorization(owner, "elasticloadbalancing"))+ .formParam("Action", "CreateListener").formParam("LoadBalancerArn", loadBalancer.arn())+ .formParam("Protocol", "HTTPS").formParam("Port", HTTPS_PORT)+ .formParam("Certificates.member.1.CertificateArn", ownerCertificate)+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.ContentType", "text/plain")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", "scoped")+ .when().post("/").then().statusCode(200).extract()+ .path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");+ assertTrue(listener.contains(":" + owner + ":"));+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "scoped", expected, expected, foreignExpected);+ given().header("Authorization", accountAuthorization(owner, "elasticloadbalancing"))+ .formParam("Action", "ModifyListener").formParam("ListenerArn", listener)+ .formParam("Certificates.member.1.CertificateArn", foreignCertificate)+ .when().post("/").then().statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));+ given().header("Authorization", accountAuthorization(owner, "elasticloadbalancing"))+ .formParam("Action", "DescribeListenerCertificates").formParam("ListenerArn", listener)+ .when().post("/").then().statusCode(200)+ .body("DescribeListenerCertificatesResponse.DescribeListenerCertificatesResult.Certificates.member.CertificateArn",+ equalTo(ownerCertificate));+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "scoped", expected, expected, foreignExpected);+ } finally {+ String ownedListener = listener;+ LoadBalancerRef ownedBalancer = loadBalancer;+ String ownedCertificate = ownerCertificate;+ String otherCertificate = foreignCertificate;+ assertAll("Delete all scoped IAM TLS fixture resources",+ () -> {+ if (ownedListener != null) {+ given().header("Authorization", accountAuthorization(owner, "elasticloadbalancing"))+ .formParam("Action", "DeleteListener").formParam("ListenerArn", ownedListener)+ .when().post("/").then().statusCode(200);+ }+ },+ () -> {+ if (ownedBalancer != null) {+ given().header("Authorization", accountAuthorization(owner, "elasticloadbalancing"))+ .formParam("Action", "DeleteLoadBalancer").formParam("LoadBalancerArn", ownedBalancer.arn())+ .when().post("/").then().statusCode(200);+ }+ },+ () -> {+ if (ownedCertificate != null) {+ given().header("Authorization", accountAuthorization(owner, "iam"))+ .formParam("Action", "DeleteServerCertificate").formParam("ServerCertificateName", name)+ .when().post("/").then().statusCode(200);+ }+ },+ () -> {+ if (otherCertificate != null) {+ given().header("Authorization", accountAuthorization(foreign, "iam"))+ .formParam("Action", "DeleteServerCertificate").formParam("ServerCertificateName", name)+ .when().post("/").then().statusCode(200);+ }+ });+ }+ }++ private static String accountAuthorization(String account, String service) {+ return "AWS4-HMAC-SHA256 Credential=" + account + "/20260720/" + REGION + "/" + service + "/aws4_request";+ }++ private static String uploadIamCertificate(String account, String name, CertificateGenerator.GeneratedCertificate pair) {+ return given().header("Authorization", accountAuthorization(account, "iam"))+ .formParam("Action", "UploadServerCertificate").formParam("ServerCertificateName", name)+ .formParam("CertificateBody", pair.certificatePem()).formParam("PrivateKey", pair.privateKeyPem())+ .when().post("/").then().statusCode(200).extract()+ .path("UploadServerCertificateResponse.UploadServerCertificateResult.ServerCertificateMetadata.Arn");+ }++ @Test+ @Order(Integer.MAX_VALUE - 1)+ void identicalCertificateUpdateRecoversAfterAnActualSslRefreshFailure() throws Exception {+ ElbV2DataPlane runtime = ClientProxy.unwrap(dataPlane);+ Vertx originalVertx = runtime.vertx;+ Vertx delegatingVertx = mock(Vertx.class, delegatesTo(originalVertx));+ AtomicBoolean failOnce = new AtomicBoolean(true);+ AtomicInteger updates = new AtomicInteger();+ AtomicReference<Future<Boolean>> failedUpdate = new AtomicReference<>();+ CountDownLatch failureCompleted = new CountDownLatch(1);+ doAnswer(creation -> {+ // Qualify Vert.x HttpServer to distinguish it from the fixture's JDK HttpServer.+ io.vertx.core.http.HttpServer actual = originalVertx.createHttpServer(+ (HttpServerOptions) creation.getArgument(0));+ io.vertx.core.http.HttpServer wrapped = mock(io.vertx.core.http.HttpServer.class, delegatesTo(actual));+ doAnswer(update -> {+ updates.incrementAndGet();+ if (failOnce.compareAndSet(true, false)) {+ SSLOptions invalid = new SSLOptions().setKeyCertOptions(new PemKeyCertOptions()+ .addKeyValue(Buffer.buffer("not a PEM private key"))+ .addCertValue(Buffer.buffer("not a PEM certificate")));+ Future<Boolean> failure = actual.updateSSLOptions(invalid, true);+ failedUpdate.set(failure);+ failure.onComplete(ignored -> failureCompleted.countDown());+ return failure;+ }+ return actual.updateSSLOptions((SSLOptions) update.getArgument(0), true);+ }).when(wrapped).updateSSLOptions(any(SSLOptions.class), eq(true));+ return wrapped;+ }).when(delegatingVertx).createHttpServer(any(HttpServerOptions.class));+ LoadBalancerRef loadBalancer = createLoadBalancer("https-refresh-retry");+ Certificate original = null;+ Certificate replacement = null;+ String listener = null;+ try {+ runtime.vertx = delegatingVertx;+ original = requestCertificate(loadBalancer.dnsName());+ replacement = requestCertificate(loadBalancer.dnsName());+ assertNotEquals(fingerprint(parseCertificate(original.getCertificateBody())),+ fingerprint(parseCertificate(replacement.getCertificateBody())));+ listener = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT,+ original.getArn(), "retry");+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "retry", original, original, replacement);+ for (int attempt = 0; attempt < 2; attempt++) {+ given().header("Authorization", AUTH).formParam("Action", "ModifyListener")+ .formParam("ListenerArn", listener)+ .formParam("Certificates.member.1.CertificateArn", replacement.getArn())+ .when().post("/").then().statusCode(200);+ if (attempt == 0) {+ assertTrue(failureCompleted.await(5, TimeUnit.SECONDS));+ assertNotNull(failedUpdate.get());+ assertTrue(failedUpdate.get().failed(), "malformed PEM must fail the real SSL update");+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "retry", original, original, replacement);+ } else {+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "retry", replacement, original, replacement);+ }+ }+ assertEquals(2, updates.get(), "identical API retry must retry the real server update");+ } finally {+ runtime.vertx = originalVertx;+ String ownedListener = listener;+ Certificate ownedOriginal = original;+ Certificate ownedReplacement = replacement;+ assertAll("Delete all failed-refresh fixture resources",+ () -> {+ if (ownedListener != null) {+ deleteListener(ownedListener);+ awaitListenerPortClosed();+ }+ },+ () -> deleteLoadBalancer(loadBalancer.arn()),+ () -> {+ if (ownedOriginal != null) {+ acmService.deleteCertificate(ownedOriginal.getArn(), REGION);+ }+ },+ () -> {+ if (ownedReplacement != null) {+ acmService.deleteCertificate(ownedReplacement.getArn(), REGION);+ }+ });+ }+ }++ @Test+ @Order(Integer.MAX_VALUE)+ void storedIamReferencesReapplyFormerThenCurrentMaterial() throws Exception {+ LoadBalancerRef loadBalancer = createLoadBalancer("https-stored-iam");+ String name = "elb-tls-stored-" + Long.toString(System.nanoTime(), 36);+ String renamed = name + "-renamed";+ String originalName = name;+ String originalArn = null;+ String replacementArn = null;+ String listener = null;+ try {+ CertificateGenerator generator = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate first = generator.generateSelfSignedCertificate(+ loadBalancer.dnsName(), List.of(), KeyAlgorithm.RSA_2048);+ CertificateGenerator.GeneratedCertificate second = generator.generateSelfSignedCertificate(+ loadBalancer.dnsName(), List.of(), KeyAlgorithm.RSA_2048);+ Certificate before = new Certificate();+ before.setCertificateBody(first.certificatePem());+ Certificate after = new Certificate();+ after.setCertificateBody(second.certificatePem());+ assertNotEquals(fingerprint(parseCertificate(first.certificatePem())),+ fingerprint(parseCertificate(second.certificatePem())));+ originalArn = uploadIamCertificate("test", name, first);+ listener = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT, originalArn, "stored");+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "stored", before, before, after);+ given().header("Authorization", accountAuthorization("test", "iam"))+ .formParam("Action", "UpdateServerCertificate").formParam("ServerCertificateName", name)+ .formParam("NewServerCertificateName", renamed).when().post("/").then().statusCode(200);+ originalName = renamed;+ // UpdateServerCertificate has no result metadata; read the canonical record explicitly.+ String renamedArn = given().header("Authorization", accountAuthorization("test", "iam"))+ .formParam("Action", "GetServerCertificate").formParam("ServerCertificateName", renamed)+ .when().post("/").then().statusCode(200).extract()+ .path("GetServerCertificateResponse.GetServerCertificateResult.ServerCertificate.ServerCertificateMetadata.Arn");+ assertNotEquals(originalArn, renamedArn);+ given().header("Authorization", AUTH).formParam("Action", "DescribeListenerCertificates")+ .formParam("ListenerArn", listener).when().post("/").then().statusCode(200)+ .body("DescribeListenerCertificatesResponse.DescribeListenerCertificatesResult.Certificates.member.CertificateArn",+ equalTo(originalArn));+ assertTrue(dataPlane.removeListener(listener, HTTPS_PORT, () -> true));+ awaitListenerPortClosed();+ elbV2Service.restorePersistedRuntime();+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "stored", before, before, after);+ replacementArn = uploadIamCertificate("test", name, second);+ assertEquals(originalArn, replacementArn);+ assertTrue(dataPlane.removeListener(listener, HTTPS_PORT, () -> true));+ awaitListenerPortClosed();+ elbV2Service.restorePersistedRuntime();+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "stored", after, before, after);+ given().header("Authorization", AUTH).formParam("Action", "DescribeListenerCertificates")+ .formParam("ListenerArn", listener).when().post("/").then().statusCode(200)+ .body("DescribeListenerCertificatesResponse.DescribeListenerCertificatesResult.Certificates.member.CertificateArn",+ equalTo(originalArn));+ } finally {+ String ownedListener = listener;+ String ownedOriginalName = originalName;+ String ownedOriginal = originalArn;+ String ownedReplacement = replacementArn;+ assertAll("Delete stored IAM TLS fixture resources",+ () -> {+ if (ownedListener != null) {+ given().header("Authorization", AUTH).formParam("Action", "DeleteListener")+ .formParam("ListenerArn", ownedListener).when().post("/").then().statusCode(200);+ }+ },+ () -> given().header("Authorization", AUTH).formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", loadBalancer.arn()).when().post("/").then().statusCode(200),+ () -> {+ if (ownedOriginal != null) {+ given().header("Authorization", accountAuthorization("test", "iam"))+ .formParam("Action", "DeleteServerCertificate").formParam("ServerCertificateName", ownedOriginalName)+ .when().post("/").then().statusCode(200);+ }+ },+ () -> {+ if (ownedReplacement != null) {+ given().header("Authorization", accountAuthorization("test", "iam"))+ .formParam("Action", "DeleteServerCertificate").formParam("ServerCertificateName", name)+ .when().post("/").then().statusCode(200);+ }+ });+ }+ }++ private static void awaitListenerPortClosed() {+ awaitListenerPortClosed(HTTPS_PORT);+ }++ private static void awaitListenerPortClosed(int port) {+ await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {+ try (Socket socket = new Socket()) {+ IOException failure = assertThrows(IOException.class,+ () -> socket.connect(new InetSocketAddress("127.0.0.1", port), 1000));+ assertTrue(hasCause(failure, ConnectException.class), failure.toString());+ }+ });+ }++ @Test+ @Order(Integer.MAX_VALUE - 2)+ void cleanupResources() {+ deleteListener(firstListenerArn);+ deleteListener(secondListenerArn);+ deleteListener(httpListenerArn);+ deleteLoadBalancer(firstLbArn);+ deleteLoadBalancer(secondLbArn);+ deleteLoadBalancer(httpLbArn);+ deleteTargetGroup(firstTargetGroupArn);+ }++ @Test+ @Order(10)+ void attachedExportableCertificateRefusesRevocationWithoutChangingHttps() {+ LoadBalancerRef loadBalancer = createLoadBalancer("tls-revoke-guard");+ Certificate certificate = acmService.requestCertificate(loadBalancer.dnsName(), List.of(), ValidationMethod.DNS,+ null, KeyAlgorithm.RSA_2048, null, new CertificateOptions(null, "ENABLED"), Map.of(), REGION);+ String listener = null;+ try {+ listener = createFixedResponseListener(loadBalancer.arn(), "HTTPS", HTTPS_PORT, certificate.getArn(), "revocation");+ awaitHttpsMaterial(loadBalancer.dnsName(), 200, "revocation", certificate, certificate);+ Response refusal = given().header("X-Amz-Target", "CertificateManager.RevokeCertificate")+ .header("Authorization", AUTH.replace("elasticloadbalancing", "acm"))+ .contentType("application/x-amz-json-1.1")+ .body(Map.of("CertificateArn", certificate.getArn(), "RevocationReason", "KEY_COMPROMISE"))+ .post("/");+ assertAll(+ () -> assertEquals(400, refusal.statusCode()),+ () -> assertTrue(String.valueOf(refusal.jsonPath().getString("__type")).endsWith("ResourceInUseException")),+ () -> assertEquals(CertificateStatus.ISSUED,+ acmService.getCertificate(certificate.getArn(), REGION).getStatus()),+ () -> awaitHttpsMaterial(loadBalancer.dnsName(), 200, "revocation", certificate, certificate));+ deleteListener(listener);+ listener = null;+ given().header("X-Amz-Target", "CertificateManager.RevokeCertificate")+ .header("Authorization", AUTH.replace("elasticloadbalancing", "acm"))+ .contentType("application/x-amz-json-1.1")+ .body(Map.of("CertificateArn", certificate.getArn(), "RevocationReason", "KEY_COMPROMISE"))+ .post("/").then().statusCode(200);+ assertEquals(CertificateStatus.REVOKED,+ acmService.getCertificate(certificate.getArn(), REGION).getStatus());+ } finally {+ deleteListener(listener);+ deleteLoadBalancer(loadBalancer.arn());+ acmService.deleteCertificate(certificate.getArn(), REGION);+ }+ }++ private Certificate requestCertificate(String domainName) {+ return acmService.requestCertificate(+ domainName,+ List.of(SHARED_CERTIFICATE_HOST),+ ValidationMethod.DNS,+ null,+ KeyAlgorithm.RSA_2048,+ null,+ CertificateOptions.defaultOptions(),+ Map.of("purpose", "elb-tls-test"),+ REGION);+ }++ private static LoadBalancerRef createLoadBalancer(String name) {+ Response response = given()+ .formParam("Action", "CreateLoadBalancer")+ .formParam("Name", name)+ .formParam("Type", "application")+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract()+ .response();+ return new LoadBalancerRef(+ response.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"),+ response.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.DNSName"));+ }++ private static String createFixedResponseListener(+ String lbArn, String protocol, int port, String certificateArn, String body) {+ RequestSpecification request = given()+ .formParam("Action", "CreateListener")+ .formParam("LoadBalancerArn", lbArn)+ .formParam("Protocol", protocol)+ .formParam("Port", String.valueOf(port))+ .formParam("DefaultActions.member.1.Type", "fixed-response")+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")+ .formParam("DefaultActions.member.1.FixedResponseConfig.ContentType", "text/plain")+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", body)+ .header("Authorization", AUTH);+ if (certificateArn != null) {+ request.formParam("SslPolicy", "ELBSecurityPolicy-TLS13-1-2-2021-06")+ .formParam("Certificates.member.1.CertificateArn", certificateArn);+ }+ return request+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract()+ .path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");+ }++ private static String createHealthyTargetGroup() {+ int targetPort = targetServer.getAddress().getPort();+ String targetGroupArn = given()+ .formParam("Action", "CreateTargetGroup")+ .formParam("Name", "https-target")+ .formParam("Protocol", "HTTP")+ .formParam("Port", String.valueOf(targetPort))+ .formParam("VpcId", "vpc-tls-test")+ .formParam("TargetType", "ip")+ .formParam("HealthCheckProtocol", "HTTP")+ .formParam("HealthCheckPath", "/")+ .formParam("HealthCheckIntervalSeconds", "5")+ .formParam("HealthyThresholdCount", "1")+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract()+ .path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");++ given()+ .formParam("Action", "RegisterTargets")+ .formParam("TargetGroupArn", targetGroupArn)+ .formParam("Targets.member.1.Id", "127.0.0.1")+ .formParam("Targets.member.1.Port", String.valueOf(targetPort))+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ return targetGroupArn;+ }++ private static String createForwardListener(+ String lbArn, int port, String certificateArn, String targetGroupArn) {+ return given()+ .formParam("Action", "CreateListener")+ .formParam("LoadBalancerArn", lbArn)+ .formParam("Protocol", "HTTPS")+ .formParam("Port", String.valueOf(port))+ .formParam("SslPolicy", "ELBSecurityPolicy-TLS13-1-2-2021-06")+ .formParam("Certificates.member.1.CertificateArn", certificateArn)+ .formParam("DefaultActions.member.1.Type", "forward")+ .formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn)+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract()+ .path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");+ }++ private static void awaitTargetHealthy(String targetGroupArn) {+ await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() ->+ given()+ .formParam("Action", "DescribeTargetHealth")+ .formParam("TargetGroupArn", targetGroupArn)+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member.TargetHealth.State",+ equalTo("healthy")));+ }++ private static void describeHttpsListener(String listenerArn, String certificateArn) {+ given()+ .formParam("Action", "DescribeListeners")+ .formParam("ListenerArns.member.1", listenerArn)+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Protocol", equalTo("HTTPS"))+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Port", equalTo(String.valueOf(HTTPS_PORT)))+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.SslPolicy",+ equalTo("ELBSecurityPolicy-TLS13-1-2-2021-06"))+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Certificates.member.CertificateArn",+ equalTo(certificateArn));+ }++ private static HttpsResult awaitHttps(String host, Certificate... trustedCertificates) {+ return awaitHttpsAtPort(host, HTTPS_PORT, trustedCertificates);+ }++ private static HttpsResult awaitHttpsAtPort(String host, int port, Certificate... trustedCertificates) {+ HttpsResult[] result = new HttpsResult[1];+ await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() -> {+ HttpResponse<String> response;+ try (HttpClient client = trustedClient(trustedCertificates)) {+ try {+ response = client.send(+ HttpRequest.newBuilder(URI.create("https://" + host + ":" + port + "/"))+ .timeout(Duration.ofSeconds(2))+ .GET()+ .build(),+ HttpResponse.BodyHandlers.ofString());+ } catch (IOException failure) {+ throw new IOException("TLS request to " + host + " failed", failure);+ }+ }+ result[0] = new HttpsResult(response.statusCode(), response.body(), response.sslSession().orElseThrow());+ });+ return result[0];+ }++ private static void awaitHttpsMaterial(String host, int status, String body, Certificate expected,+ Certificate... trustedCertificates) {+ await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() -> {+ try (HttpClient client = trustedClient(trustedCertificates)) {+ HttpResponse<String> response;+ try {+ response = client.send(HttpRequest.newBuilder(URI.create("https://" + host + ":" + HTTPS_PORT + "/"))+ .timeout(Duration.ofSeconds(2)).GET().build(), HttpResponse.BodyHandlers.ofString());+ } catch (IOException failure) {+ throw new AssertionError("TLS material has not converged for " + host, failure);+ }+ assertEquals(status, response.statusCode());+ assertEquals(body, response.body());+ assertPeerCertificate(response.sslSession().orElseThrow(), expected, host);+ }+ });+ }++ private static HttpClient trustedClient(Certificate... certificates) throws Exception {+ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());+ trustStore.load(null, null);+ for (int i = 0; i < certificates.length; i++) {+ trustStore.setCertificateEntry("acm-" + i, parseCertificate(certificates[i].getCertificateBody()));+ }+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ trustManagerFactory.init(trustStore);+ SSLContext sslContext = SSLContext.getInstance("TLS");+ sslContext.init(null, trustManagerFactory.getTrustManagers(), null);+ return HttpClient.newBuilder()+ .connectTimeout(Duration.ofSeconds(2))+ .sslContext(sslContext)+ .build();+ }++ private static void assertPeerCertificate(SSLSession session, Certificate expected, String expectedHost)+ throws Exception {+ X509Certificate actual = assertInstanceOf(X509Certificate.class, session.getPeerCertificates()[0]);+ X509Certificate configured = parseCertificate(expected.getCertificateBody());+ assertEquals(fingerprint(configured), fingerprint(actual));+ assertTrue(actual.getSubjectAlternativeNames().stream()+ .anyMatch(san -> expectedHost.equals(san.get(1))));+ }++ private static X509Certificate parseCertificate(String pem) throws Exception {+ return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(+ new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));+ }++ private static String fingerprint(X509Certificate certificate) throws Exception {+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded()));+ }++ private static boolean hasCause(Throwable failure, Class<? extends Throwable> type) {+ for (Throwable current = failure; current != null; current = current.getCause()) {+ if (type.isInstance(current)) {+ return true;+ }+ }+ return false;+ }++ private static void deleteListener(String listenerArn) {+ if (listenerArn == null) {+ return;+ }+ given()+ .formParam("Action", "DeleteListener")+ .formParam("ListenerArn", listenerArn)+ .header("Authorization", AUTH)+ .when()+ .post("/");+ }++ private static void deleteLoadBalancer(String lbArn) {+ if (lbArn == null) {+ return;+ }+ given()+ .formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", lbArn)+ .header("Authorization", AUTH)+ .when()+ .post("/");+ }++ private static void deleteTargetGroup(String targetGroupArn) {+ if (targetGroupArn == null) {+ return;+ }+ given()+ .formParam("Action", "DeleteTargetGroup")+ .formParam("TargetGroupArn", targetGroupArn)+ .header("Authorization", AUTH)+ .when()+ .post("/");+ }++ private record LoadBalancerRef(String arn, String dnsName) {}++ private record HttpsResult(int statusCode, String body, SSLSession session) {}+}diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerCertificateIntegrationTest.javaindex bbe5a1a466..6180105669 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java@@ -241,6 +241,11 @@ class ElbV2ListenerCertificateIntegrationTest {assertEquals(List.of(certificate), listenerCertificates(listener));}+ @Test+ void anHttpListenerStillNeedsNoCertificate() {+ createListener("HTTP", null).statusCode(200);+ }+@Testvoid aTlsListenerIsHeldToTheSameCheckAsAnHttpsOne() {// The reference brackets the member for HTTPS and TLS, so both, not HTTPS alone.diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerOwnershipTest.javanew file mode 100644index 0000000000..32a5318a9d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerOwnershipTest.java@@ -0,0 +1,624 @@+package io.github.hectorvent.floci.services.elbv2;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsProxyServer;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.services.elbv2.model.Action;+import io.github.hectorvent.floci.services.elbv2.model.Listener;+import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;+import io.github.hectorvent.floci.services.elbv2.model.Rule;+import io.vertx.core.Future;+import io.vertx.core.Handler;+import io.vertx.core.Promise;+import io.vertx.core.Vertx;+import io.vertx.core.http.HttpServer;+import io.vertx.core.http.HttpServerOptions;+import io.vertx.core.http.HttpServerRequest;+import io.vertx.core.http.HttpServerResponse;+import io.vertx.core.net.SSLOptions;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;++import java.lang.management.ManagementFactory;+import java.lang.management.ThreadInfo;+import java.net.BindException;+import java.time.Duration;+import java.util.Arrays;+import java.util.List;+import java.util.Map;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicReference;++import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.publishRuntime;+import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.removeRuntime;+import static org.awaitility.Awaitility.await;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.doReturn;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++class ElbV2ListenerOwnershipTest {+ private static final String REGION = "us-west-2";+ private static final String HOST = "shared.example.test";+ private static final String CERTIFICATE = "arn:aws:acm:us-west-2:000000000000:certificate/shared";++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void unusableSavedMaterialCannotClaimAPortOrPublishControlState(boolean emptyDefault) {+ Registry registry = new Registry();+ Fixture fixture = new Fixture(registry);+ Listener listener = listener("unusable", 8443, true);+ CertificateMaterial valid = fixture.plane.certificateResolver.publishedMaterial(listener.getListenerArn(), REGION, CERTIFICATE);+ CertificateGenerator.GeneratedCertificate other = new CertificateGenerator().generateSelfSignedCertificate(+ HOST, List.of(), KeyAlgorithm.RSA_2048);+ CertificateMaterial broken = new CertificateMaterial(CERTIFICATE, valid.certificateBody(), other.privateKeyPem(), null);+ when(fixture.plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(broken);+ if (emptyDefault) {+ listener.setCertificates(List.of());+ }+ AtomicInteger publications = new AtomicInteger();+ try {+ assertThrows(RuntimeException.class, () -> fixture.plane.publishListener(listener, REGION, 8443,+ () -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("unpublished")), admitted -> admitted.get()));+ assertEquals(0, publications.get());+ assertTrue(registry.isEmpty());+ assertEquals(0, fixture.creations(8443));+ listener.setCertificates(List.of(CERTIFICATE));+ when(fixture.plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(valid);+ assertTrue(fixture.plane.publishListener(listener, REGION, 8443,+ () -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("retry")), admitted -> admitted.get()));+ assertEquals(1, publications.get());+ fixture.serves(8443, "retry");+ } finally {+ fixture.plane.shutdown();+ }+ }++ @Test+ void materialChangedBeforeAdmissionCannotPublishAnOlderPreparedSnapshot() {+ Registry registry = new Registry();+ Fixture fixture = new Fixture(registry);+ Listener listener = listener("overtaken", 8443, true);+ CertificateGenerator.GeneratedCertificate newer = new CertificateGenerator().generateSelfSignedCertificate(+ HOST, List.of(), KeyAlgorithm.RSA_2048);+ CertificateMaterial current = new CertificateMaterial(CERTIFICATE, newer.certificatePem(), newer.privateKeyPem(), null);+ AtomicInteger publications = new AtomicInteger();+ try {+ assertFalse(fixture.plane.publishListener(listener, REGION, 8443,+ () -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("stale")), operation -> {+ when(fixture.plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE)))+ .thenReturn(current);+ return operation.get();+ }));+ assertEquals(0, publications.get());+ assertTrue(registry.isEmpty());+ assertEquals(0, fixture.creations(8443));+ assertTrue(fixture.plane.publishListener(listener, REGION, 8443,+ () -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("current")), operation -> operation.get()));+ assertEquals(List.of(current), registry.get(listener.getListenerArn()).certificates());+ assertEquals(1, publications.get());+ fixture.serves(8443, "current");+ } finally {+ fixture.plane.shutdown();+ }+ }++ @ParameterizedTest+ @CsvSource({"false,false", "false,true", "true,false", "true,true"})+ void refusedControlPublicationRestoresTheExactRuntimeReservation(boolean existing, boolean throwsFailure) {+ Registry registry = new Registry();+ Fixture fixture = new Fixture(registry);+ Listener first = listener("publication", 8443, false);+ Listener next = listener("publication", 9443, false);+ try {+ if (existing) {+ publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("old")));+ }+ ElbV2DataPlane.ListenerBinding expected = registry.get(first.getListenerArn());+ AtomicInteger callbacks = new AtomicInteger();+ if (throwsFailure) {+ assertThrows(IllegalArgumentException.class, () -> fixture.plane.publishListener(next, REGION, 8443,+ () -> {+ callbacks.incrementAndGet();+ throw new IllegalArgumentException("refused control publication");+ }, () -> List.of(rule("unpublished")), admitted -> admitted.get()));+ } else {+ assertFalse(fixture.plane.publishListener(next, REGION, 8443, () -> {+ callbacks.incrementAndGet();+ return false;+ }, () -> List.of(rule("unpublished")), admitted -> admitted.get()));+ }+ assertEquals(1, callbacks.get());+ assertSame(expected, registry.get(first.getListenerArn()));+ assertEquals(0, fixture.creations(9443));+ assertEquals(0, fixture.closes(8443));+ if (existing) {+ fixture.serves(8443, "old");+ fixture.plane.recompileRules(first.getListenerArn(), () -> List.of(rule("latest")));+ } else {+ assertTrue(registry.isEmpty());+ }+ assertTrue(fixture.plane.publishListener(next, REGION, 8443, () -> true,+ () -> List.of(rule("initial")), admitted -> admitted.get()));+ fixture.serves(9443, existing ? "latest" : "initial");+ assertEquals(1, fixture.creations(9443));+ } finally {+ fixture.plane.shutdown();+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void noPortControlCallbacksRunWithoutCreatingAGeneveSocket(boolean mockMode) {+ Registry registry = new Registry();+ Fixture fixture = new Fixture(registry);+ when(fixture.plane.config.services().elbv2().mock()).thenReturn(mockMode);+ Listener gateway = listener("gateway", 8443, false);+ gateway.setPort(null);+ gateway.setProtocol("GENEVE");+ AtomicInteger callbacks = new AtomicInteger();+ try {+ assertTrue(fixture.plane.publishListener(gateway, REGION, null, () -> {+ callbacks.incrementAndGet();+ return true;+ }, () -> {+ throw new AssertionError("control-only publication must not initialize socket rules");+ }, admitted -> admitted.get()));+ assertTrue(fixture.plane.updateListener(null, () -> {+ callbacks.incrementAndGet();+ return true;+ }));+ assertTrue(fixture.plane.removeListener(gateway.getListenerArn(), null, () -> {+ callbacks.incrementAndGet();+ return true;+ }));+ assertEquals(3, callbacks.get());+ assertTrue(registry.isEmpty());+ assertTrue(fixture.created.isEmpty());+ } finally {+ fixture.plane.shutdown();+ }+ }++ @Test+ void absentRuntimeAndStoppedRuntimeStillApplyControlCallbacks() {+ Registry registry = new Registry();+ Fixture fixture = new Fixture(registry);+ Listener listener = listener("stopped", 8443, false);+ AtomicInteger callbacks = new AtomicInteger();+ try {+ assertTrue(fixture.plane.removeListener(listener.getListenerArn(), 8443, () -> {+ callbacks.incrementAndGet();+ return true;+ }));+ fixture.plane.shutdown();+ assertTrue(fixture.plane.publishListener(listener, REGION, 8443, () -> {+ callbacks.incrementAndGet();+ return true;+ }, () -> {+ throw new AssertionError("stopped runtime must not compile socket rules");+ }, admitted -> admitted.get()));+ assertEquals(2, callbacks.get());+ assertTrue(registry.isEmpty());+ assertTrue(fixture.created.isEmpty());+ } finally {+ fixture.plane.shutdown();+ }+ }++ @Test+ void delayedRuleRefreshReadsCurrentMembershipInsideThePortGate() throws Exception {+ Registry registry = new Registry();+ Fixture fixture = new Fixture(registry);+ ExecutorService workers = Executors.newFixedThreadPool(2);+ CountDownLatch holding = new CountDownLatch(1);+ CountDownLatch release = new CountDownLatch(1);+ AtomicReference<Thread> owner = new AtomicReference<>();+ AtomicReference<Thread> refresher = new AtomicReference<>();+ AtomicReference<List<Rule>> current = new AtomicReference<>(List.of(rule("old")));+ AtomicInteger reads = new AtomicInteger();+ Listener listener = listener("rules", 8443, false);+ try {+ publishRuntime(fixture.plane, listener, REGION, listener.getPort(), current.get());+ // Qualify the JDK Future to distinguish it from Vert.x Future.+ java.util.concurrent.Future<?> held = workers.submit(() -> fixture.plane.updateListener(8443, () -> {+ owner.set(Thread.currentThread());+ holding.countDown();+ try {+ assertTrue(release.await(10, TimeUnit.SECONDS));+ } catch (InterruptedException interrupted) {+ Thread.currentThread().interrupt();+ throw new AssertionError(interrupted);+ }+ return true;+ }));+ assertTrue(holding.await(5, TimeUnit.SECONDS));+ java.util.concurrent.Future<?> refreshed = workers.submit(() -> {+ refresher.set(Thread.currentThread());+ fixture.plane.recompileRules(listener.getListenerArn(), () -> {+ reads.incrementAndGet();+ return current.get();+ });+ });+ await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {+ assertNotNull(refresher.get());+ ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(refresher.get().threadId(), 30);+ assertNotNull(info);+ assertEquals(Thread.State.BLOCKED, info.getThreadState());+ assertEquals(owner.get().threadId(), info.getLockOwnerId());+ assertTrue(Arrays.stream(info.getStackTrace()).anyMatch(frame -> frame.getMethodName().equals("onPort")));+ });+ assertEquals(0, reads.get(), "rule membership must not be read before acquiring the gate");+ current.set(List.of(rule("added"), rule("old")));+ publishRuntime(fixture.plane, listener("unrelated", 10443, false), REGION, null, List.of(rule("progress")));+ fixture.serves(10443, "progress");+ release.countDown();+ held.get(5, TimeUnit.SECONDS);+ refreshed.get(5, TimeUnit.SECONDS);+ assertEquals(1, reads.get());+ fixture.serves(8443, "added");+ } finally {+ release.countDown();+ workers.shutdownNow();+ try {+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));+ } finally {+ fixture.plane.shutdown();+ }+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void competingInitialClaimsRetryAgainstThePublishedBinding(boolean secure) throws Exception {+ Registry registry = new Registry();+ Fixture fixture = new Fixture(registry);+ ExecutorService workers = Executors.newFixedThreadPool(2);+ Listener first = listener("same", 8443, secure);+ Listener second = listener("same", 9443, secure);+ registry.arn = first.getListenerArn();+ try {+ // Prime release-handler registration before pausing a port gate.+ publishRuntime(fixture.plane, listener("prime", 10443, false), REGION, null, List.of(rule("prime")));+ // Qualify the JDK Future to distinguish it from Vert.x Future.+ java.util.concurrent.Future<?> initial = workers.submit(() -> {+ registry.worker = Thread.currentThread();+ registry.pauseInitial = true;+ publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("first")));+ });+ assertTrue(registry.entered.await(5, TimeUnit.SECONDS));+ workers.submit(() -> publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second"))))+ .get(5, TimeUnit.SECONDS);+ fixture.serves(9443, "second");+ registry.release.countDown();+ initial.get(5, TimeUnit.SECONDS);+ assertEquals(1, registry.failedClaims.get(), "the actual putIfAbsent must lose before retrying");+ fixture.serves(8443, "first");+ assertEquals(1, fixture.closes(9443));+ publishRuntime(fixture.plane, listener("other", 9443, secure), REGION, null, List.of(rule("reused")));+ fixture.serves(9443, "reused");+ verify(fixture.plane.tlsProxyServer, times(1)).onPortReleased(any());+ } finally {+ registry.release.countDown();+ workers.shutdownNow();+ try {+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));+ } finally {+ fixture.plane.shutdown();+ }+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void stopCannotEraseSameArnPublishedOnAnotherPort(boolean secure) throws Exception {+ Registry registry = new Registry();+ Fixture fixture = new Fixture(registry);+ ExecutorService workers = Executors.newFixedThreadPool(2);+ Listener first = listener("same", 8443, secure);+ Listener second = listener("same", 9443, secure);+ registry.arn = first.getListenerArn();+ try {+ publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("first")));+ // Qualify the JDK Future to distinguish it from Vert.x Future.+ java.util.concurrent.Future<?> stopping = workers.submit(() -> {+ registry.worker = Thread.currentThread();+ registry.pauseRemoval = true;+ removeRuntime(fixture.plane, first.getListenerArn(), first.getPort());+ });+ assertTrue(registry.entered.await(5, TimeUnit.SECONDS));+ workers.submit(() -> publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second"))))+ .get(5, TimeUnit.SECONDS);+ fixture.serves(9443, "second");+ registry.release.countDown();+ stopping.get(5, TimeUnit.SECONDS);+ fixture.serves(9443, "second");+ assertEquals(1, fixture.closes(8443));+ assertEquals(0, fixture.closes(9443));+ int creations = fixture.creations(9443);+ publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));+ assertEquals(creations, fixture.creations(9443));+ fixture.serves(9443, "second");+ removeRuntime(fixture.plane, second.getListenerArn(), second.getPort());+ assertEquals(1, fixture.closes(9443));+ publishRuntime(fixture.plane, listener("other", 8443, secure), REGION, null, List.of(rule("reused")));+ fixture.serves(8443, "reused");+ } finally {+ registry.release.countDown();+ workers.shutdownNow();+ try {+ assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));+ } finally {+ fixture.plane.shutdown();+ }+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void aPublisherQueuedOnARetiringPortStateRetriesItsIdentity(boolean failedClose) throws Exception {+ Fixture fixture = new Fixture(new Registry());+ CountDownLatch insideClose = new CountDownLatch(1);+ CountDownLatch releaseClose = new CountDownLatch(1);+ AtomicReference<Throwable> stoppingFailure = new AtomicReference<>();+ AtomicReference<Throwable> publisherFailure = new AtomicReference<>();+ Listener first = listener("first", 8443, false);+ Listener second = listener("second", 8443, false);+ Thread stopping = Thread.ofPlatform().unstarted(() -> {+ try {+ removeRuntime(fixture.plane, first.getListenerArn(), first.getPort());+ } catch (Throwable failure) {+ stoppingFailure.set(failure);+ }+ });+ Thread publishing = Thread.ofPlatform().unstarted(() -> {+ try {+ publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));+ } catch (Throwable failure) {+ publisherFailure.set(failure);+ }+ });+ try {+ publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("first")));+ doAnswer(ignored -> {+ insideClose.countDown();+ assertTrue(releaseClose.await(10, TimeUnit.SECONDS));+ return failedClose ? Future.failedFuture(new IllegalStateException("controlled close failure"))+ : Future.succeededFuture();+ }).when(fixture.servers.get(8443)).close();+ stopping.start();+ assertTrue(insideClose.await(5, TimeUnit.SECONDS));+ publishing.start();+ await().atMost(5, TimeUnit.SECONDS).until(() -> {+ ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(publishing.threadId(), 30);+ return info != null && info.getThreadState() == Thread.State.BLOCKED+ && info.getLockOwnerId() == stopping.threadId()+ && Arrays.stream(info.getStackTrace()).anyMatch(frame ->+ frame.getClassName().equals(ElbV2DataPlane.class.getName())+ && frame.getMethodName().equals("onPort"));+ });+ publishRuntime(fixture.plane, listener("unrelated", 9443, false), REGION, null, List.of(rule("unrelated")));+ fixture.serves(9443, "unrelated");+ releaseClose.countDown();+ stopping.join(5_000);+ publishing.join(5_000);+ assertFalse(stopping.isAlive());+ assertFalse(publishing.isAlive());+ assertNull(stoppingFailure.get());+ assertNull(publisherFailure.get());+ assertEquals(2, fixture.creations(8443), "queued publisher must bind using the current port state");+ fixture.serves(8443, "second");+ fixture.serves(9443, "unrelated");+ } finally {+ releaseClose.countDown();+ stopping.interrupt();+ publishing.interrupt();+ stopping.join(5_000);+ publishing.join(5_000);+ fixture.plane.shutdown();+ }+ }++ @Test+ void failedClosePermitsABoundedBindAttemptAndIdenticalPublicationCanRetry() {+ Fixture fixture = new Fixture(new Registry());+ Promise<Void> close = Promise.promise();+ Listener first = listener("first", 8443, false);+ Listener second = listener("second", 8443, false);+ try {+ publishRuntime(fixture.plane, first, REGION, first.getPort(), List.of(rule("first")));+ doReturn(close.future()).when(fixture.servers.get(8443)).close();+ removeRuntime(fixture.plane, first.getListenerArn(), first.getPort());+ publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));+ assertEquals(1, fixture.creations(8443), "pending close must defer the next bind");+ publishRuntime(fixture.plane, listener("unrelated", 9443, false), REGION, null, List.of(rule("unrelated")));+ fixture.serves(9443, "unrelated");+ // A failed close does not establish that the old physical socket is free.+ fixture.failNextListenPort = 8443;+ close.fail(new IllegalStateException("controlled close failure"));+ assertEquals(2, fixture.creations(8443));+ assertEquals(1, fixture.closes(8443), "failed replacement must be closed");+ publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));+ assertEquals(3, fixture.creations(8443));+ fixture.serves(8443, "second");+ fixture.serves(9443, "unrelated");+ } finally {+ close.tryComplete();+ fixture.plane.shutdown();+ }+ }++ private static final class Registry extends ConcurrentHashMap<String, ElbV2DataPlane.ListenerBinding> {+ private final CountDownLatch entered = new CountDownLatch(1);+ private final CountDownLatch release = new CountDownLatch(1);+ private final AtomicInteger reads = new AtomicInteger();+ private final AtomicInteger failedClaims = new AtomicInteger();+ private final AtomicBoolean paused = new AtomicBoolean();+ private volatile Thread worker;+ private String arn;+ private volatile boolean pauseInitial;+ private volatile boolean pauseRemoval;++ @Override+ public ElbV2DataPlane.ListenerBinding get(Object key) {+ ElbV2DataPlane.ListenerBinding actual = super.get(key);+ // Shared publication first checks its expected binding, then install checks the claim.+ if (Thread.currentThread() == worker && arn.equals(key) && pauseInitial+ && reads.incrementAndGet() == 3 && actual == null) {+ pause();+ }+ return actual;+ }++ @Override+ public ElbV2DataPlane.ListenerBinding putIfAbsent(String key, ElbV2DataPlane.ListenerBinding value) {+ ElbV2DataPlane.ListenerBinding previous = super.putIfAbsent(key, value);+ if (Thread.currentThread() == worker && arn.equals(key) && previous != null) {+ failedClaims.incrementAndGet();+ }+ return previous;+ }++ @Override+ public boolean remove(Object key, Object value) {+ boolean removed = super.remove(key, value);+ if (Thread.currentThread() == worker && arn.equals(key) && pauseRemoval && removed) {+ pause();+ }+ return removed;+ }++ private void pause() {+ if (paused.compareAndSet(false, true)) {+ entered.countDown();+ try {+ assertTrue(release.await(10, TimeUnit.SECONDS), "registry boundary was not released");+ } catch (InterruptedException interrupted) {+ Thread.currentThread().interrupt();+ throw new AssertionError(interrupted);+ }+ }+ }+ }++ private static final class Fixture {+ private final ElbV2DataPlane plane;+ private final Map<Integer, Handler<HttpServerRequest>> handlers = new ConcurrentHashMap<>();+ private final Map<Integer, AtomicInteger> created = new ConcurrentHashMap<>();+ private final Map<Integer, AtomicInteger> closed = new ConcurrentHashMap<>();+ private final Map<Integer, HttpServer> servers = new ConcurrentHashMap<>();+ private volatile int failNextListenPort = -1;++ private Fixture(Registry registry) {+ plane = new ElbV2DataPlane(registry);+ plane.config = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.ElbV2ServiceConfig config = mock(EmulatorConfig.ElbV2ServiceConfig.class);+ when(plane.config.services()).thenReturn(services);+ when(services.elbv2()).thenReturn(config);+ when(config.mock()).thenReturn(false);+ when(plane.config.port()).thenReturn(4566);+ plane.tlsProxyServer = mock(TlsProxyServer.class);+ when(plane.tlsProxyServer.reservesPort(anyInt())).thenReturn(false);+ plane.elbV2Service = mock(ElbV2Service.class);+ LoadBalancer balancer = new LoadBalancer();+ balancer.setDnsName(HOST);+ when(plane.elbV2Service.getLoadBalancer(eq(REGION), anyString())).thenReturn(balancer);+ plane.certificateResolver = mock(CertificateReferenceResolver.class);+ CertificateGenerator.GeneratedCertificate pair = new CertificateGenerator().generateSelfSignedCertificate(+ HOST, List.of(), KeyAlgorithm.RSA_2048);+ CertificateMaterial material = new CertificateMaterial(CERTIFICATE, pair.certificatePem(), pair.privateKeyPem(), null);+ when(plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(material);+ plane.vertx = mock(Vertx.class);+ when(plane.vertx.createHttpServer(any(HttpServerOptions.class))).thenAnswer(call -> {+ int port = ((HttpServerOptions) call.getArgument(0)).getPort();+ created.computeIfAbsent(port, ignored -> new AtomicInteger()).incrementAndGet();+ HttpServer server = mock(HttpServer.class);+ servers.put(port, server);+ when(server.requestHandler(any())).thenAnswer(handler -> {+ handlers.put(port, handler.getArgument(0));+ return server;+ });+ when(server.listen()).thenAnswer(ignored -> {+ if (failNextListenPort == port) {+ failNextListenPort = -1;+ return Future.failedFuture(new BindException("controlled occupied port"));+ }+ return Future.succeededFuture(server);+ });+ when(server.close()).thenAnswer(ignored -> {+ closed.computeIfAbsent(port, key -> new AtomicInteger()).incrementAndGet();+ return Future.succeededFuture();+ });+ when(server.updateSSLOptions(any(SSLOptions.class), eq(true))).thenReturn(Future.succeededFuture(true));+ return server;+ });+ }++ private int creations(int port) {+ AtomicInteger count = created.get(port);+ return count == null ? 0 : count.get();+ }++ private int closes(int port) {+ AtomicInteger count = closed.get(port);+ return count == null ? 0 : count.get();+ }++ private void serves(int port, String body) {+ HttpServerRequest request = mock(HttpServerRequest.class);+ HttpServerResponse response = mock(HttpServerResponse.class);+ when(request.host()).thenReturn(HOST);+ when(request.response()).thenReturn(response);+ when(response.setStatusCode(anyInt())).thenReturn(response);+ handlers.get(port).handle(request);+ verify(response).setStatusCode(200);+ verify(response).end(body);+ }+ }++ private static Listener listener(String name, int port, boolean secure) {+ Listener listener = new Listener();+ listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/shared/1/" + name);+ listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/shared/1");+ listener.setPort(port);+ listener.setProtocol(secure ? "HTTPS" : "HTTP");+ listener.setCertificates(secure ? List.of(CERTIFICATE) : List.of());+ return listener;+ }++ private static Rule rule(String body) {+ Action action = new Action();+ action.setType("fixed-response");+ action.setFixedResponseStatusCode("200");+ action.setFixedResponseMessageBody(body);+ Rule rule = new Rule();+ rule.setDefault(true);+ rule.setActions(List.of(action));+ return rule;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PublicationTestSupport.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PublicationTestSupport.javanew file mode 100644index 0000000000..dbb747b712--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PublicationTestSupport.java@@ -0,0 +1,49 @@+package io.github.hectorvent.floci.services.elbv2;++import io.github.hectorvent.floci.services.elbv2.model.Listener;+import io.github.hectorvent.floci.services.elbv2.model.Rule;+import org.mockito.invocation.InvocationOnMock;++import java.util.List;+import java.util.function.BooleanSupplier;+import java.util.function.Function;+import java.util.function.Supplier;++import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.lenient;++final class ElbV2PublicationTestSupport {+ private ElbV2PublicationTestSupport() { }++ static void publishRuntime(ElbV2DataPlane plane, Listener listener, String region,+ Integer previousPort, List<Rule> rules) {+ while (!plane.publishListener(listener, region, previousPort, () -> {+ plane.recompileRules(listener.getListenerArn(), () -> rules);+ return true;+ }, () -> rules, Supplier::get)) {+ // The service retries a runtime reservation changed by another publisher.+ }+ }++ static void removeRuntime(ElbV2DataPlane plane, String arn, Integer storedPort) {+ while (!plane.removeListener(arn, storedPort, () -> true)) {+ // Retry an identity changed while waiting for its port gate.+ }+ }++ static boolean applyPublication(InvocationOnMock call) {+ Function<Supplier<Boolean>, Boolean> admission = call.getArgument(5);+ return admission.apply(() -> call.getArgument(3, BooleanSupplier.class).getAsBoolean());+ }++ static void allowPublications(ElbV2DataPlane dataPlane) {+ lenient().doAnswer(ElbV2PublicationTestSupport::applyPublication)+ .when(dataPlane).publishListener(any(Listener.class), anyString(), any(), any(), any(), any());+ lenient().doAnswer(call -> call.getArgument(1, BooleanSupplier.class).getAsBoolean())+ .when(dataPlane).updateListener(any(), any());+ lenient().doAnswer(call -> call.getArgument(2, BooleanSupplier.class).getAsBoolean())+ .when(dataPlane).removeListener(anyString(), any(), any());+ }++}diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ReservedPortTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ReservedPortTest.javaindex 3ccf0f3f37..3e0f8293e2 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ReservedPortTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ReservedPortTest.java@@ -2,23 +2,48 @@ package io.github.hectorvent.floci.services.elbv2;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.config.TlsProxyServer;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.services.elbv2.model.Action;import io.github.hectorvent.floci.services.elbv2.model.Listener;+import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;+import io.github.hectorvent.floci.services.elbv2.model.Rule;+import io.vertx.core.Future;+import io.vertx.core.Handler;import io.vertx.core.Promise;import io.vertx.core.Vertx;import io.vertx.core.http.HttpServer;import io.vertx.core.http.HttpServerOptions;+import io.vertx.core.http.HttpServerRequest;+import io.vertx.core.http.HttpServerResponse;+import io.vertx.core.net.PemKeyCertOptions;+import io.vertx.core.net.SSLOptions;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.ArgumentCaptor;import java.util.List;import java.util.function.IntConsumer;+import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.publishRuntime;+import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.removeRuntime;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertInstanceOf;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.argThat;+import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -124,7 +149,7 @@ class ElbV2ReservedPortTest {listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/lb/1");listener.setPort(443);- assertDoesNotThrow(() -> dataPlane.startListener(listener, "us-west-2", List.of()),+ assertDoesNotThrow(() -> publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of()),"the released-port replay re-entered the server map for the key it was computing");verify(vertx, times(1)).createHttpServer(any(HttpServerOptions.class));}@@ -135,4 +160,395 @@ class ElbV2ReservedPortTest {assertFalse(dataPlane.isReservedByFloci(80));assertFalse(dataPlane.isReservedByFloci(8080));}+ @Test+ void identicalRestartRetriesAFailedTlsRefresh() {+ ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);+ EmulatorConfig.ElbV2ServiceConfig elbv2 = mock(EmulatorConfig.ElbV2ServiceConfig.class);+ when(elbv2.mock()).thenReturn(false);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ when(services.elbv2()).thenReturn(elbv2);+ when(dataPlane.config.services()).thenReturn(services);+ dataPlane.vertx = mock(Vertx.class);+ dataPlane.elbV2Service = mock(ElbV2Service.class);+ dataPlane.certificateResolver = mock(CertificateReferenceResolver.class);+ HttpServer server = mock(HttpServer.class);+ when(server.requestHandler(any())).thenReturn(server);+ when(server.listen()).thenReturn(Future.succeededFuture(server));+ when(server.close()).thenReturn(Future.succeededFuture());+ when(server.updateSSLOptions(any(SSLOptions.class), eq(true)))+ .thenReturn(Future.failedFuture(new IllegalStateException("controlled TLS refresh failure")),+ Future.succeededFuture(true));+ when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(server);+ String region = "us-west-2";+ String owner = "arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/lb/1/2";+ String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/current";+ Listener listener = new Listener();+ listener.setListenerArn(owner);+ listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/lb/1");+ listener.setPort(8443);+ listener.setProtocol("HTTPS");+ listener.setCertificates(List.of(certificateArn));+ LoadBalancer loadBalancer = new LoadBalancer();+ loadBalancer.setDnsName("tls.example.test");+ when(dataPlane.elbV2Service.getLoadBalancer(region, listener.getLoadBalancerArn())).thenReturn(loadBalancer);+ CertificateGenerator generator = new CertificateGenerator();+ CertificateGenerator.GeneratedCertificate old = generator.generateSelfSignedCertificate(+ "tls.example.test", List.of(), KeyAlgorithm.RSA_2048);+ CertificateGenerator.GeneratedCertificate replacement = generator.generateSelfSignedCertificate(+ "tls.example.test", List.of(), KeyAlgorithm.RSA_2048);+ CertificateMaterial first = new CertificateMaterial(certificateArn, old.certificatePem(), old.privateKeyPem(), null);+ CertificateMaterial next = new CertificateMaterial(certificateArn,+ replacement.certificatePem(), replacement.privateKeyPem(), null);+ when(dataPlane.certificateResolver.publishedMaterial(owner, region, certificateArn)).thenReturn(first, next, next);+ try {+ publishRuntime(dataPlane, listener, region, listener.getPort(), List.of());+ publishRuntime(dataPlane, listener, region, listener.getPort(), List.of());+ verify(server).updateSSLOptions(any(SSLOptions.class), eq(true));+ publishRuntime(dataPlane, listener, region, listener.getPort(), List.of());+ ArgumentCaptor<SSLOptions> options = ArgumentCaptor.forClass(SSLOptions.class);+ verify(server, times(2)).updateSSLOptions(options.capture(), eq(true));+ for (SSLOptions attempt : options.getAllValues()) {+ PemKeyCertOptions material = assertInstanceOf(PemKeyCertOptions.class, attempt.getKeyCertOptions());+ assertEquals(1, material.getCertValues().size());+ assertEquals(replacement.certificatePem().stripTrailing() + "\n",+ material.getCertValues().getFirst().toString());+ assertEquals(1, material.getKeyValues().size());+ assertEquals(replacement.privateKeyPem(), material.getKeyValues().getFirst().toString());+ }+ } finally {+ dataPlane.shutdown();+ }+ }++ @Test+ void movingSecureListenerRefreshesTheSurvivingOldPort() {+ ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);+ EmulatorConfig.ElbV2ServiceConfig elbv2 = mock(EmulatorConfig.ElbV2ServiceConfig.class);+ when(elbv2.mock()).thenReturn(false);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ when(services.elbv2()).thenReturn(elbv2);+ when(dataPlane.config.services()).thenReturn(services);+ dataPlane.vertx = mock(Vertx.class);+ dataPlane.elbV2Service = mock(ElbV2Service.class);+ dataPlane.certificateResolver = mock(CertificateReferenceResolver.class);+ HttpServer oldServer = mock(HttpServer.class);+ HttpServer newServer = mock(HttpServer.class);+ for (HttpServer server : List.of(oldServer, newServer)) {+ when(server.requestHandler(any())).thenReturn(server);+ when(server.listen()).thenReturn(Future.succeededFuture(server));+ when(server.close()).thenReturn(Future.succeededFuture());+ }+ when(oldServer.updateSSLOptions(any(SSLOptions.class), eq(true)))+ .thenReturn(Future.succeededFuture(true));+ when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class)))+ .thenAnswer(invocation -> ((HttpServerOptions) invocation.getArgument(0)).getPort() == 8443+ ? oldServer : newServer);+ CertificateGenerator generator = new CertificateGenerator();+ Listener survivor = new Listener();+ Listener moved = new Listener();+ CertificateGenerator.GeneratedCertificate survivorCertificate = null;+ for (Listener listener : List.of(survivor, moved)) {+ String name = listener == survivor ? "survivor" : "moved";+ String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/" + name;+ listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");+ listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");+ listener.setPort(8443);+ listener.setProtocol("HTTPS");+ listener.setCertificates(List.of(certificateArn));+ LoadBalancer loadBalancer = new LoadBalancer();+ loadBalancer.setDnsName(name + ".example.test");+ when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))+ .thenReturn(loadBalancer);+ CertificateGenerator.GeneratedCertificate certificate = generator.generateSelfSignedCertificate(+ name + ".example.test", List.of(), KeyAlgorithm.RSA_2048);+ if (listener == survivor) {+ survivorCertificate = certificate;+ }+ when(dataPlane.certificateResolver.publishedMaterial(listener.getListenerArn(), "us-west-2", certificateArn))+ .thenReturn(new CertificateMaterial(certificateArn,+ certificate.certificatePem(), certificate.privateKeyPem(), null));+ }+ try {+ publishRuntime(dataPlane, survivor, "us-west-2", survivor.getPort(), List.of());+ publishRuntime(dataPlane, moved, "us-west-2", moved.getPort(), List.of());+ ArgumentCaptor<SSLOptions> initial = ArgumentCaptor.forClass(SSLOptions.class);+ verify(oldServer).updateSSLOptions(initial.capture(), eq(true));+ assertEquals(2, assertInstanceOf(PemKeyCertOptions.class,+ initial.getValue().getKeyCertOptions()).getCertValues().size());++ moved.setPort(9443);+ publishRuntime(dataPlane, moved, "us-west-2", moved.getPort(), List.of());++ ArgumentCaptor<SSLOptions> refreshed = ArgumentCaptor.forClass(SSLOptions.class);+ verify(oldServer, times(2)).updateSSLOptions(refreshed.capture(), eq(true));+ PemKeyCertOptions retained = assertInstanceOf(PemKeyCertOptions.class,+ refreshed.getAllValues().getLast().getKeyCertOptions());+ assertEquals(List.of(survivorCertificate.certificatePem().stripTrailing() + "\n"),+ retained.getCertValues().stream().map(value -> value.toString()).toList());+ assertEquals(List.of(survivorCertificate.privateKeyPem()),+ retained.getKeyValues().stream().map(value -> value.toString()).toList());+ verify(newServer).listen();+ verify(oldServer, never()).close();+ } finally {+ dataPlane.shutdown();+ }+ }++ @Test+ void lastListenerCloseCompletesBeforeItsPortIsReused() {+ ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);+ EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ when(elb.mock()).thenReturn(false);+ when(services.elbv2()).thenReturn(elb);+ when(dataPlane.config.services()).thenReturn(services);+ dataPlane.vertx = mock(Vertx.class);+ dataPlane.elbV2Service = mock(ElbV2Service.class);+ HttpServer oldServer = mock(HttpServer.class);+ HttpServer replacement = mock(HttpServer.class);+ Promise<Void> close = Promise.promise();+ when(oldServer.close()).thenReturn(close.future());+ when(replacement.close()).thenReturn(Future.succeededFuture());+ for (HttpServer server : List.of(oldServer, replacement)) {+ when(server.requestHandler(any())).thenReturn(server);+ when(server.listen()).thenReturn(Future.succeededFuture(server));+ }+ when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(oldServer, replacement);+ Listener first = new Listener();+ Listener second = new Listener();+ for (Listener listener : List.of(first, second)) {+ String name = listener == first ? "first" : "second";+ listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");+ listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");+ listener.setPort(8443);+ listener.setProtocol("HTTP");+ LoadBalancer loadBalancer = new LoadBalancer();+ loadBalancer.setDnsName(name + ".example.test");+ when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))+ .thenReturn(loadBalancer);+ }+ try {+ publishRuntime(dataPlane, first, "us-west-2", first.getPort(), List.of());+ verify(oldServer).listen();+ removeRuntime(dataPlane, first.getListenerArn(), first.getPort());+ verify(oldServer).close();+ publishRuntime(dataPlane, second, "us-west-2", second.getPort(), List.of());+ verify(replacement, never()).listen();+ close.complete();+ verify(replacement).listen();+ removeRuntime(dataPlane, second.getListenerArn(), second.getPort());+ verify(replacement).close();+ } finally {+ close.tryComplete();+ dataPlane.shutdown();+ }+ }++ @Test+ void pendingOldPortClosePreservesAMovedListenerAndLaterPortReuse() {+ ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);+ EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ when(elb.mock()).thenReturn(false);+ when(services.elbv2()).thenReturn(elb);+ when(dataPlane.config.services()).thenReturn(services);+ dataPlane.vertx = mock(Vertx.class);+ dataPlane.elbV2Service = mock(ElbV2Service.class);+ HttpServer oldServer = mock(HttpServer.class);+ HttpServer movedServer = mock(HttpServer.class);+ HttpServer reusedServer = mock(HttpServer.class);+ Promise<Void> oldClose = Promise.promise();+ for (HttpServer server : List.of(oldServer, movedServer, reusedServer)) {+ when(server.requestHandler(any())).thenReturn(server);+ when(server.listen()).thenReturn(Future.succeededFuture(server));+ when(server.close()).thenReturn(Future.succeededFuture());+ }+ when(oldServer.close()).thenReturn(oldClose.future());+ when(dataPlane.vertx.createHttpServer(argThat(options -> options != null && options.getPort() == 8443)))+ .thenReturn(oldServer, reusedServer);+ when(dataPlane.vertx.createHttpServer(argThat(options -> options != null && options.getPort() == 9443))).thenReturn(movedServer);+ Listener old = new Listener();+ Listener moved = new Listener();+ Listener reused = new Listener();+ for (Listener listener : List.of(old, moved, reused)) {+ String name = listener == old ? "old" : listener == moved ? "moved" : "reused";+ listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");+ listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");+ listener.setPort(8443);+ listener.setProtocol("HTTP");+ LoadBalancer loadBalancer = new LoadBalancer();+ loadBalancer.setDnsName(name + ".example.test");+ when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))+ .thenReturn(loadBalancer);+ }+ try {+ publishRuntime(dataPlane, old, "us-west-2", old.getPort(), List.of(fixedRule("old")));+ assertFixedResponse(oldServer, "old.example.test", "old");+ removeRuntime(dataPlane, old.getListenerArn(), old.getPort());+ verify(oldServer).close();+ publishRuntime(dataPlane, moved, "us-west-2", moved.getPort(), List.of(fixedRule("pending")));+ verify(reusedServer, never()).listen();+ moved.setPort(9443);+ publishRuntime(dataPlane, moved, "us-west-2", moved.getPort(), List.of(fixedRule("moved")));+ verify(movedServer).listen();+ oldClose.complete();+ verify(reusedServer, never()).listen();+ verify(movedServer, never()).close();+ assertFixedResponse(movedServer, "moved.example.test", "moved");+ publishRuntime(dataPlane, reused, "us-west-2", reused.getPort(), List.of(fixedRule("reused")));+ verify(reusedServer).listen();+ assertFixedResponse(reusedServer, "reused.example.test", "reused");+ removeRuntime(dataPlane, reused.getListenerArn(), reused.getPort());+ verify(reusedServer).close();+ verify(movedServer, never()).close();+ removeRuntime(dataPlane, moved.getListenerArn(), moved.getPort());+ verify(movedServer).close();+ } finally {+ oldClose.tryComplete();+ dataPlane.shutdown();+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"factory", "handler", "listen", "failed-future"})+ void identicalStartRecoversFromServerAcquisitionFailure(String stage) {+ ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);+ EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ when(elb.mock()).thenReturn(false);+ when(services.elbv2()).thenReturn(elb);+ when(dataPlane.config.services()).thenReturn(services);+ dataPlane.vertx = mock(Vertx.class);+ dataPlane.elbV2Service = mock(ElbV2Service.class);+ HttpServer failed = mock(HttpServer.class);+ HttpServer replacement = mock(HttpServer.class);+ for (HttpServer server : List.of(failed, replacement)) {+ when(server.requestHandler(any())).thenReturn(server);+ when(server.listen()).thenReturn(Future.succeededFuture(server));+ when(server.close()).thenReturn(Future.succeededFuture());+ }+ IllegalStateException failure = new IllegalStateException("controlled " + stage + " failure");+ when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(failed, replacement);+ switch (stage) {+ case "factory" -> when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class)))+ .thenThrow(failure).thenReturn(replacement);+ case "handler" -> when(failed.requestHandler(any())).thenThrow(failure);+ case "listen" -> when(failed.listen()).thenThrow(failure);+ case "failed-future" -> when(failed.listen()).thenReturn(Future.failedFuture(failure));+ default -> throw new IllegalArgumentException(stage);+ }+ Listener listener = new Listener();+ listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/retry/1/2");+ listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/retry/1");+ listener.setPort(8443);+ listener.setProtocol("HTTP");+ LoadBalancer loadBalancer = new LoadBalancer();+ loadBalancer.setDnsName("retry.example.test");+ when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))+ .thenReturn(loadBalancer);+ try {+ if ("failed-future".equals(stage)) {+ assertDoesNotThrow(() -> publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of(fixedRule("recovered"))));+ } else {+ assertSame(failure, assertThrows(IllegalStateException.class,+ () -> publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of(fixedRule("recovered")))));+ }+ if (!"factory".equals(stage)) {+ verify(failed).close();+ }+ publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of(fixedRule("recovered")));+ verify(replacement).listen();+ assertFixedResponse(replacement, "retry.example.test", "recovered");+ removeRuntime(dataPlane, listener.getListenerArn(), listener.getPort());+ verify(replacement).close();+ verify(dataPlane.vertx, times(2)).createHttpServer(any(HttpServerOptions.class));+ } finally {+ dataPlane.shutdown();+ }+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void obsoleteListenFailureCannotRemoveReplacement(boolean deferClose) {+ ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);+ EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ when(elb.mock()).thenReturn(false);+ when(services.elbv2()).thenReturn(elb);+ when(dataPlane.config.services()).thenReturn(services);+ dataPlane.vertx = mock(Vertx.class);+ dataPlane.elbV2Service = mock(ElbV2Service.class);+ HttpServer oldServer = mock(HttpServer.class);+ HttpServer replacement = mock(HttpServer.class);+ Promise<HttpServer> oldListen = Promise.promise();+ Promise<Void> oldClose = Promise.promise();+ when(oldServer.requestHandler(any())).thenReturn(oldServer);+ when(oldServer.listen()).thenReturn(oldListen.future());+ when(oldServer.close()).thenReturn(deferClose ? oldClose.future() : Future.succeededFuture());+ when(replacement.requestHandler(any())).thenReturn(replacement);+ when(replacement.listen()).thenReturn(Future.succeededFuture(replacement));+ when(replacement.close()).thenReturn(Future.succeededFuture());+ when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenReturn(oldServer, replacement);+ Listener first = new Listener();+ Listener second = new Listener();+ for (Listener listener : List.of(first, second)) {+ String name = listener == first ? "old" : "replacement";+ listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");+ listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");+ listener.setPort(8443);+ listener.setProtocol("HTTP");+ LoadBalancer loadBalancer = new LoadBalancer();+ loadBalancer.setDnsName(name + ".example.test");+ when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn()))+ .thenReturn(loadBalancer);+ }+ try {+ publishRuntime(dataPlane, first, "us-west-2", first.getPort(), List.of());+ verify(oldServer).listen();+ removeRuntime(dataPlane, first.getListenerArn(), first.getPort());+ verify(oldServer).close();+ publishRuntime(dataPlane, second, "us-west-2", second.getPort(), List.of(fixedRule("replacement")));+ if (deferClose) {+ verify(replacement, never()).listen();+ oldClose.complete();+ }+ verify(replacement).listen();+ oldListen.fail(new IllegalStateException("obsolete listen failure"));+ verify(replacement, never()).close();+ assertFixedResponse(replacement, "replacement.example.test", "replacement");+ publishRuntime(dataPlane, second, "us-west-2", second.getPort(), List.of(fixedRule("replacement")));+ verify(dataPlane.vertx, times(2)).createHttpServer(any(HttpServerOptions.class));+ removeRuntime(dataPlane, second.getListenerArn(), second.getPort());+ verify(replacement).close();+ } finally {+ oldClose.tryComplete();+ oldListen.tryFail(new IllegalStateException("test cleanup"));+ dataPlane.shutdown();+ }+ }++ private static Rule fixedRule(String body) {+ Action action = new Action();+ action.setType("fixed-response");+ action.setFixedResponseStatusCode("200");+ action.setFixedResponseMessageBody(body);+ Rule rule = new Rule();+ rule.setDefault(true);+ rule.setActions(List.of(action));+ return rule;+ }++ private static void assertFixedResponse(HttpServer server, String host, String body) {+ ArgumentCaptor<Handler<HttpServerRequest>> handler = ArgumentCaptor.captor();+ verify(server).requestHandler(handler.capture());+ HttpServerRequest request = mock(HttpServerRequest.class);+ HttpServerResponse response = mock(HttpServerResponse.class);+ when(request.host()).thenReturn(host);+ when(request.response()).thenReturn(response);+ when(response.setStatusCode(anyInt())).thenReturn(response);+ handler.getValue().handle(request);+ verify(response).setStatusCode(200);+ verify(response).end(body);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.javaindex 815a3d1733..e71c0340f7 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java@@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsRegionFacts;-import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.InMemoryStorage;@@ -38,12 +37,14 @@ import java.util.List;import java.util.Map;import java.util.Optional;import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.function.Supplier;+import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.allowPublications;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertThrows;@@ -53,10 +54,10 @@ import static org.mockito.ArgumentMatchers.anyList;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.clearInvocations;-import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;@@ -88,6 +89,7 @@ class ElbV2ServiceTest {@BeforeEachvoid setUp() {service = new ElbV2Service();+ allowPublications(dataPlane);service.dataPlane = dataPlane;service.healthChecker = healthChecker;service.regionResolver = new RegionResolver(REGION, "000000000000");@@ -153,6 +155,37 @@ class ElbV2ServiceTest {assertEquals(List.of(first), service.describeListenerCertificates(REGION, listenerArn));}+ @ParameterizedTest+ @NullAndEmptySource+ void missingHttpsDefaultIsRefusedEvenWithoutACertificateResolver(List<String> certificates) {+ String lbArn = service.createLoadBalancer(REGION, "missing-create", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ clearInvocations(dataPlane);+ AwsException rejected = assertThrows(AwsException.class, () -> service.createListener(+ REGION, lbArn, "HTTPS", 9443, null, certificates, List.of(), List.of(), Map.of()));+ assertEquals("InvalidConfigurationRequest", rejected.getErrorCode());+ assertTrue(service.describeListeners(REGION, lbArn, List.of()).isEmpty());+ assertTrue(service.describeRules(REGION, null, List.of()).isEmpty());+ verifyNoInteractions(dataPlane);+ }++ @ParameterizedTest+ @NullAndEmptySource+ void missingEffectiveDefaultCannotChangeAnHttpListener(List<String> certificates) {+ String lbArn = service.createLoadBalancer(REGION, "missing-modify", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ Listener listener = service.createListener(REGION, lbArn, "HTTP", 8080, null,+ List.of(), List.of(), List.of(), Map.of());+ clearInvocations(dataPlane);+ AwsException rejected = assertThrows(AwsException.class, () -> service.modifyListener(+ REGION, listener.getListenerArn(), "HTTPS", 9443, "unchanged", certificates, null, null));+ assertEquals("InvalidConfigurationRequest", rejected.getErrorCode());+ assertEquals("HTTP", listener.getProtocol());+ assertEquals(8080, listener.getPort());+ assertTrue(listener.getCertificates().isEmpty());+ verifyNoInteractions(dataPlane);+ }+@Testvoid removalCannotDeleteADefaultPublishedByConcurrentModification() throws Exception {String lbArn = service.createLoadBalancer(REGION, "default-replacement-lb", "internal", "application", "ipv4",@@ -184,7 +217,9 @@ class ElbV2ServiceTest {service.modifyListener(REGION, listener, null, null, null, List.of(additional), null, null);assertEquals(List.of(additional), service.describeListenerCertificates(REGION, listener));releaseRemoval.countDown();- removal.get(5, TimeUnit.SECONDS);+ ExecutionException refused = assertThrows(ExecutionException.class,+ () -> removal.get(5, TimeUnit.SECONDS));+ assertEquals("OperationNotPermitted", ((AwsException) refused.getCause()).getErrorCode());assertEquals(List.of(additional), service.describeListenerCertificates(REGION, listener));AwsException rejected = assertThrows(AwsException.class,() -> service.removeListenerCertificates(REGION, listener, List.of(additional)));@@ -208,6 +243,114 @@ class ElbV2ServiceTest {assertEquals(List.of(), service.describeListenerCertificates(REGION, listenerArn));}+ @Test+ void modifyListenerProtocolAndCertificateRestartsListener() {+ String lbArn = service.createLoadBalancer(+ REGION, "tls-lb", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ String listenerArn = service.createListener(+ REGION, lbArn, "HTTP", 9443, null, List.of(),+ List.of(), List.of(), Map.of()).getListenerArn();+ clearInvocations(dataPlane);++ service.modifyListener(+ REGION, listenerArn, "HTTPS", null, "ELBSecurityPolicy-TLS13-1-2-2021-06",+ List.of("arn:aws:acm:us-west-2:000000000000:certificate/first"), null, null);++ ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.captor();+ verify(dataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any());+ assertEquals("HTTPS", listenerCaptor.getValue().getProtocol());+ assertEquals(List.of("arn:aws:acm:us-west-2:000000000000:certificate/first"),+ listenerCaptor.getValue().getCertificates());+ verify(dataPlane, never()).recompileRules(anyString(), any());+ }++ @Test+ void identicalExplicitTlsModificationReappliesTheDataPlane() {+ String lbArn = service.createLoadBalancer(+ REGION, "tls-retry-lb", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ String first = "arn:aws:acm:us-west-2:000000000000:certificate/first";+ String replacement = "arn:aws:acm:us-west-2:000000000000:certificate/replacement";+ String listenerArn = service.createListener(REGION, lbArn, "HTTPS", 9443, null,+ List.of(first), List.of(), List.of(), Map.of()).getListenerArn();+ clearInvocations(dataPlane);++ service.modifyListener(REGION, listenerArn, null, null, null, List.of(replacement), null, null);+ assertEquals(List.of(replacement), service.describeListenerCertificates(REGION, listenerArn));+ verify(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());+ service.modifyListener(REGION, listenerArn, null, null, null, List.of(replacement), null, null);++ verify(dataPlane, times(2)).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());+ assertEquals(List.of(replacement), service.describeListenerCertificates(REGION, listenerArn));+ verify(dataPlane, never()).recompileRules(anyString(), any());+ }++ @Test+ void listenerCertificateLifecycleRefreshesDataPlane() {+ String lbArn = service.createLoadBalancer(+ REGION, "certificate-lb", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ String firstCertificate = "arn:aws:acm:us-west-2:000000000000:certificate/first";+ String secondCertificate = "arn:aws:acm:us-west-2:000000000000:certificate/second";+ String listenerArn = service.createListener(+ REGION, lbArn, "HTTPS", 9443, null, List.of(firstCertificate),+ List.of(), List.of(), Map.of()).getListenerArn();+ clearInvocations(dataPlane);++ service.addListenerCertificates(REGION, listenerArn, List.of(secondCertificate));+ service.removeListenerCertificates(REGION, listenerArn, List.of(secondCertificate));++ verify(dataPlane, times(2))+ .publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());+ assertEquals(List.of(firstCertificate),+ service.describeListenerCertificates(REGION, listenerArn));+ }++ @Test+ void defaultRemovalWithAdditionalCertificateDoesNotRefreshAndCanRemoveAdditional() {+ String lbArn = service.createLoadBalancer(+ REGION, "default-certificate-lb", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ String first = "arn:aws:acm:us-west-2:000000000000:certificate/default";+ String additional = "arn:aws:acm:us-west-2:000000000000:certificate/additional";+ String listener = service.createListener(REGION, lbArn, "HTTPS", 9443, null,+ List.of(first, additional), List.of(), List.of(), Map.of()).getListenerArn();+ clearInvocations(dataPlane);+ AwsException rejected = assertThrows(AwsException.class,+ () -> service.removeListenerCertificates(REGION, listener, List.of(first)));+ assertEquals("OperationNotPermitted", rejected.getErrorCode());+ assertEquals(List.of(first, additional), service.describeListenerCertificates(REGION, listener));+ verifyNoInteractions(dataPlane);+ service.removeListenerCertificates(REGION, listener, List.of(additional));+ assertEquals(List.of(first), service.describeListenerCertificates(REGION, listener));+ verify(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());+ }++ @Test+ void initializeStorageRestoresHttpsListenerCertificate() {+ SharedStorageFactory storageFactory = new SharedStorageFactory();+ ElbV2Service first = serviceWithStorage(+ storageFactory, mock(ElbV2DataPlane.class), mock(ElbV2HealthChecker.class));+ String lbArn = first.createLoadBalancer(+ REGION, "persisted-https-lb", "internal", "application", "ipv4",+ ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();+ String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/persisted";+ String listenerArn = first.createListener(+ REGION, lbArn, "HTTPS", 9443, "ELBSecurityPolicy-TLS13-1-2-2021-06",+ List.of(certificateArn), List.of(), List.of(), Map.of()).getListenerArn();++ ElbV2DataPlane reloadedDataPlane = mock(ElbV2DataPlane.class);+ ElbV2Service reloaded = serviceWithStorage(storageFactory, reloadedDataPlane, mock(ElbV2HealthChecker.class));+ reloaded.restorePersistedRuntime();++ ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.captor();+ verify(reloadedDataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any());+ assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn());+ assertEquals("HTTPS", listenerCaptor.getValue().getProtocol());+ assertEquals(List.of(certificateArn), listenerCaptor.getValue().getCertificates());+ }+@Testvoid modifyListenerDefaultActionsRecompilesRulesWithoutRestartingListener() {String lbArn = service.createLoadBalancer(@@ -224,13 +367,12 @@ class ElbV2ServiceTest {REGION, listenerArn, null, null, null, null,List.of(forwardAction(newTgArn)), null);- ArgumentCaptor<List<Rule>> rulesCaptor = ArgumentCaptor.captor();+ ArgumentCaptor<Supplier<List<Rule>>> rulesCaptor = ArgumentCaptor.captor();verify(dataPlane).recompileRules(eq(listenerArn), rulesCaptor.capture());- verify(dataPlane, never()).stopListener(anyString());- verify(dataPlane, never()).startListener(any(Listener.class), anyString(), anyList());- verify(dataPlane, never()).restartListener(any(Listener.class), anyString(), anyList());+ verify(dataPlane, never()).removeListener(anyString(), any(), any());+ verify(dataPlane, never()).publishListener(any(Listener.class), anyString(), any(), any(), any(), any());- Rule defaultRule = rulesCaptor.getValue().stream()+ Rule defaultRule = rulesCaptor.getValue().get().stream().filter(Rule::isDefault).findFirst().orElseThrow();@@ -255,69 +397,8 @@ class ElbV2ServiceTest {service.modifyListener(REGION, listenerArn, null, 10000, null, null, null, null);- verify(dataPlane).restartListener(any(Listener.class), eq(REGION), anyList());- verify(dataPlane, never()).stopListener(anyString());- verify(dataPlane, never()).startListener(any(Listener.class), anyString(), anyList());- }-- @Test- void modifyListenerRefusedUnderTheCertificateGuardLeavesTheListenerWhereItWas() {- String lbArn = service.createLoadBalancer(- REGION, "sample-lb", "internal", "application", "ipv4",- ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();- String tgArn = createTargetGroup("sample-tg");- String listenerArn = service.createListener(- REGION, lbArn, "HTTPS", 443, "ELBSecurityPolicy-2016-08", List.of(HELD_CERTIFICATE),- List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn();- clearInvocations(dataPlane);- service.certificateResolver = deletedOnTheSecondLook();-- AwsException e = assertThrows(AwsException.class, () -> service.modifyListener(- REGION, listenerArn, "TLS", 8443, "ELBSecurityPolicy-TLS13-1-2-2021-06",- List.of(OTHER_CERTIFICATE), null, null));-- assertEquals("CertificateNotFound", e.getErrorCode());- Listener listener = service.describeListeners(REGION, lbArn, List.of(listenerArn)).getFirst();- assertEquals(Integer.valueOf(443), listener.getPort());- assertEquals("HTTPS", listener.getProtocol());- assertEquals("ELBSecurityPolicy-2016-08", listener.getSslPolicy());- assertEquals(List.of(HELD_CERTIFICATE), listener.getCertificates());- verify(dataPlane, never()).restartListener(any(Listener.class), anyString(), anyList());- }-- @Test- void modifyListenerProtocolAloneTakesTheGuardForTheCertificatesItPutsIntoService() {- String lbArn = service.createLoadBalancer(- REGION, "sample-lb", "internal", "application", "ipv4",- ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn();- String tgArn = createTargetGroup("sample-tg");- String listenerArn = service.createListener(- REGION, lbArn, "HTTP", 80, null, List.of(HELD_CERTIFICATE),- List.of(forwardAction(tgArn)), List.of(), Map.of()).getListenerArn();- clearInvocations(dataPlane);- service.certificateResolver = deletedOnTheSecondLook();-- AwsException e = assertThrows(AwsException.class, () -> service.modifyListener(- REGION, listenerArn, "HTTPS", null, null, null, null, null));-- assertEquals("CertificateNotFound", e.getErrorCode());- assertEquals("HTTP", service.describeListeners(REGION, lbArn, List.of(listenerArn))- .getFirst().getProtocol());- }-- /**- * A resolver that finds the certificate once and not again, which is what a- * {@code DeleteServerCertificate} landing between the check outside the guard and the one- * under it looks like from inside the call.- */- private static CertificateReferenceResolver deletedOnTheSecondLook() {- CertificateReferenceResolver resolver = mock(CertificateReferenceResolver.class);- when(resolver.exists(anyString(), anyString())).thenReturn(true, false);- doAnswer(invocation -> {- invocation.getArgument(1, Runnable.class).run();- return null;- }).when(resolver).runWhileHeld(any(), any());- return resolver;+ verify(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());+ verify(dataPlane, never()).removeListener(anyString(), any(), any());}@Test@@ -465,7 +546,7 @@ class ElbV2ServiceTest {verify(reloadedHealthChecker).addTargets(eq(tgArn), targetsCaptor.capture(), any(TargetGroup.class));assertEquals("i-1234567890abcdef0", targetsCaptor.getValue().getFirst().getId());assertEquals(8080, targetsCaptor.getValue().getFirst().getPort());- verify(reloadedDataPlane).startListener(any(Listener.class), eq(REGION), anyList());+ verify(reloadedDataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any());reloaded.removeTags(List.of(rule.getRuleArn()), List.of("env"));ElbV2Service updatedReload = serviceWithStorage(storageFactory, mock(ElbV2DataPlane.class), mock(ElbV2HealthChecker.class));@@ -502,7 +583,7 @@ class ElbV2ServiceTest {reloaded.restorePersistedRuntime();ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.captor();- verify(reloadedDataPlane).startListener(listenerCaptor.capture(), eq(REGION), anyList());+ verify(reloadedDataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any());assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn());verify(reloadedHealthChecker).startMonitoring(any(TargetGroup.class));}@@ -523,7 +604,7 @@ class ElbV2ServiceTest {reloaded.restorePersistedRuntime();ArgumentCaptor<Listener> listenerCaptor = ArgumentCaptor.captor();- verify(reloadedDataPlane).startListener(listenerCaptor.capture(), eq(REGION), anyList());+ verify(reloadedDataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any());assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn());}@@ -621,7 +702,11 @@ class ElbV2ServiceTest {return condition;}- private static ElbV2Service serviceWithStorage(StorageFactory storageFactory,+ static StorageFactory sharedStorageFactory() {+ return new SharedStorageFactory();+ }++ static ElbV2Service serviceWithStorage(StorageFactory storageFactory,ElbV2DataPlane dataPlane,ElbV2HealthChecker healthChecker) {Ec2Service ec2Service = mock(Ec2Service.class);@@ -629,11 +714,12 @@ class ElbV2ServiceTest {return serviceWithStorage(storageFactory, dataPlane, healthChecker, ec2Service);}- private static ElbV2Service serviceWithStorage(StorageFactory storageFactory,+ static ElbV2Service serviceWithStorage(StorageFactory storageFactory,ElbV2DataPlane dataPlane,ElbV2HealthChecker healthChecker,Ec2Service ec2Service) {ElbV2Service service = new ElbV2Service();+ allowPublications(dataPlane);service.dataPlane = dataPlane;service.healthChecker = healthChecker;service.regionResolver = new RegionResolver(REGION, "000000000000");diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TlsCohortTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TlsCohortTest.javanew file mode 100644index 0000000000..4bd81bc1b4--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TlsCohortTest.java@@ -0,0 +1,233 @@+package io.github.hectorvent.floci.services.elbv2;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsProxyServer;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;+import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.services.elbv2.model.Action;+import io.github.hectorvent.floci.services.elbv2.model.Listener;+import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;+import io.github.hectorvent.floci.services.elbv2.model.Rule;+import io.github.hectorvent.floci.testing.InlineMocks;+import io.vertx.core.Future;+import io.vertx.core.Handler;+import io.vertx.core.Vertx;+import io.vertx.core.http.HttpServer;+import io.vertx.core.http.HttpServerOptions;+import io.vertx.core.http.HttpServerRequest;+import io.vertx.core.http.HttpServerResponse;+import io.vertx.core.net.PemKeyCertOptions;+import io.vertx.core.net.SSLOptions;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.ArgumentCaptor;++import java.time.Duration;+import java.util.List;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicReference;++import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.publishRuntime;+import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.removeRuntime;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertInstanceOf;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.atLeastOnce;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++class ElbV2TlsCohortTest {++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void concurrentMaterialPublicationKeepsSharedAliasesAmbiguous(boolean pauseOptionsCapture) throws Exception {+ String region = "us-west-2";+ String certificateArn = "arn:aws:acm:us-west-2:000000000000:certificate/shared";+ String alias = "replacement.example.test";+ ElbV2DataPlane dataPlane = new ElbV2DataPlane();+ dataPlane.config = mock(EmulatorConfig.class);+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);+ EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);+ when(dataPlane.config.services()).thenReturn(services);+ when(services.elbv2()).thenReturn(elb);+ when(elb.mock()).thenReturn(false);+ when(dataPlane.config.port()).thenReturn(4566);+ dataPlane.tlsProxyServer = mock(TlsProxyServer.class);+ when(dataPlane.tlsProxyServer.reservesPort(anyInt())).thenReturn(false);+ dataPlane.vertx = mock(Vertx.class);+ dataPlane.elbV2Service = mock(ElbV2Service.class);+ dataPlane.certificateResolver = mock(CertificateReferenceResolver.class);+ HttpServer server = mock(HttpServer.class);+ HttpServer otherServer = mock(HttpServer.class);+ when(otherServer.requestHandler(any())).thenReturn(otherServer);+ when(otherServer.listen()).thenReturn(Future.succeededFuture(otherServer));+ when(otherServer.close()).thenReturn(Future.succeededFuture());+ when(dataPlane.vertx.createHttpServer(any(HttpServerOptions.class))).thenAnswer(call ->+ ((HttpServerOptions) call.getArgument(0)).getPort() == 9443 ? otherServer : server);+ when(server.requestHandler(any())).thenReturn(server);+ when(server.listen()).thenReturn(Future.succeededFuture(server));+ when(server.close()).thenReturn(Future.succeededFuture());+ when(server.updateSSLOptions(any(SSLOptions.class), eq(true))).thenReturn(Future.succeededFuture(true));+ CertificateGenerator generator = new CertificateGenerator();+ CertificateMaterial seed = material(generator, certificateArn, "seed.example.test");+ CertificateMaterial first = InlineMocks.inlineSpy(material(generator, certificateArn, "old.example.test"));+ CertificateMaterial replacement = material(generator, certificateArn, alias);+ Listener left = listener("left", certificateArn);+ Listener right = listener("right", certificateArn);+ Listener unrelated = listener("unrelated", certificateArn);+ unrelated.setPort(9443);+ AtomicReference<CertificateMaterial> leftMaterial = new AtomicReference<>(seed);+ AtomicReference<CertificateMaterial> rightMaterial = new AtomicReference<>(seed);+ when(dataPlane.certificateResolver.publishedMaterial(left.getListenerArn(), region, certificateArn))+ .thenAnswer(ignored -> leftMaterial.get());+ when(dataPlane.certificateResolver.publishedMaterial(right.getListenerArn(), region, certificateArn))+ .thenAnswer(ignored -> rightMaterial.get());+ when(dataPlane.certificateResolver.publishedMaterial(unrelated.getListenerArn(), region, certificateArn))+ .thenReturn(seed);+ for (Listener listener : List.of(left, right, unrelated)) {+ LoadBalancer loadBalancer = new LoadBalancer();+ loadBalancer.setDnsName(listener == left ? "left.example.test" : "right.example.test");+ when(dataPlane.elbV2Service.getLoadBalancer(region, listener.getLoadBalancerArn())).thenReturn(loadBalancer);+ }+ CountDownLatch insideSecondPeer = new CountDownLatch(1);+ CountDownLatch releaseFirst = new CountDownLatch(1);+ CountDownLatch secondResolved = new CountDownLatch(1);+ AtomicReference<Thread> firstWorker = new AtomicReference<>();+ AtomicInteger reads = new AtomicInteger();+ AtomicInteger keyReads = new AtomicInteger();+ AtomicBoolean paused = new AtomicBoolean();+ // Pair validation reads key/body once before the coordinated cohort/SSL-options reads.+ if (pauseOptionsCapture) {+ doAnswer(invocation -> {+ if (Thread.currentThread() == firstWorker.get() && keyReads.incrementAndGet() == 2+ && paused.compareAndSet(false, true)) {+ insideSecondPeer.countDown();+ assertTrue(releaseFirst.await(10, TimeUnit.SECONDS), "options capture was not released");+ }+ return invocation.callRealMethod();+ }).when(first).privateKey();+ } else {+ doAnswer(invocation -> {+ if (Thread.currentThread() == firstWorker.get() && reads.incrementAndGet() == 4+ && paused.compareAndSet(false, true)) {+ insideSecondPeer.countDown();+ assertTrue(releaseFirst.await(10, TimeUnit.SECONDS), "first publisher was not released");+ }+ return invocation.callRealMethod();+ }).when(first).certificateBody();+ }+ ExecutorService workers = Executors.newFixedThreadPool(3);+ try {+ publishRuntime(dataPlane, left, region, left.getPort(), List.of(fixedRule("left")));+ publishRuntime(dataPlane, right, region, right.getPort(), List.of(fixedRule("right")));+ ArgumentCaptor<Handler<HttpServerRequest>> handler = ArgumentCaptor.captor();+ verify(server).requestHandler(handler.capture());+ leftMaterial.set(first);+ rightMaterial.set(replacement);+ when(dataPlane.certificateResolver.publishedMaterial(right.getListenerArn(), region, certificateArn))+ .thenAnswer(ignored -> {+ secondResolved.countDown();+ return rightMaterial.get();+ });+ // Qualify the JDK Future to distinguish it from Vert.x Future.+ java.util.concurrent.Future<?> firstPublication = workers.submit(() -> {+ firstWorker.set(Thread.currentThread());+ publishRuntime(dataPlane, left, region, left.getPort(), List.of(fixedRule("left")));+ });+ assertTrue(insideSecondPeer.await(5, TimeUnit.SECONDS), "publisher did not reach the controlled cohort boundary");+ java.util.concurrent.Future<?> secondPublication = workers.submit(() ->+ publishRuntime(dataPlane, right, region, right.getPort(), List.of(fixedRule("right"))));+ assertTrue(secondResolved.await(5, TimeUnit.SECONDS), "second publisher did not resolve its material");+ workers.submit(() -> publishRuntime(dataPlane, unrelated, region, unrelated.getPort(), List.of(fixedRule("unrelated"))))+ .get(1, TimeUnit.SECONDS);+ verify(otherServer).listen();+ try {+ secondPublication.get(3, TimeUnit.SECONDS);+ } catch (TimeoutException expected) {+ // A correct port-local coordinator may hold this publisher until the first is released.+ } finally {+ releaseFirst.countDown();+ }+ firstPublication.get(5, TimeUnit.SECONDS);+ secondPublication.get(5, TimeUnit.SECONDS);+ HttpServerRequest request = mock(HttpServerRequest.class);+ HttpServerResponse response = mock(HttpServerResponse.class);+ when(request.host()).thenReturn(alias);+ when(request.response()).thenReturn(response);+ when(response.setStatusCode(anyInt())).thenReturn(response);+ handler.getValue().handle(request);+ verify(response).setStatusCode(502);+ verify(response).end("No listener for host");+ ArgumentCaptor<SSLOptions> updates = ArgumentCaptor.forClass(SSLOptions.class);+ verify(server, atLeastOnce()).updateSSLOptions(updates.capture(), eq(true));+ List<SSLOptions> orderedUpdates = updates.getAllValues();+ PemKeyCertOptions preceding = assertInstanceOf(PemKeyCertOptions.class,+ orderedUpdates.get(orderedUpdates.size() - 2).getKeyCertOptions());+ assertEquals(List.of(first.privateKey()),+ preceding.getKeyValues().stream().map(value -> value.toString()).toList());+ PemKeyCertOptions finalOptions = assertInstanceOf(PemKeyCertOptions.class,+ orderedUpdates.getLast().getKeyCertOptions());+ assertEquals(List.of(replacement.privateKey()),+ finalOptions.getKeyValues().stream().map(value -> value.toString()).toList());+ assertEquals(List.of(replacement.certificateBody().stripTrailing() + "\n"),+ finalOptions.getCertValues().stream().map(value -> value.toString()).toList());+ removeRuntime(dataPlane, right.getListenerArn(), right.getPort());+ HttpServerRequest survivingRequest = mock(HttpServerRequest.class);+ HttpServerResponse survivingResponse = mock(HttpServerResponse.class);+ when(survivingRequest.host()).thenReturn(alias);+ when(survivingRequest.response()).thenReturn(survivingResponse);+ when(survivingResponse.setStatusCode(anyInt())).thenReturn(survivingResponse);+ handler.getValue().handle(survivingRequest);+ verify(survivingResponse).setStatusCode(200);+ verify(survivingResponse).end("left");+ } finally {+ releaseFirst.countDown();+ workers.shutdownNow();+ try {+ assertTrue(workers.awaitTermination(Duration.ofSeconds(5).toMillis(), TimeUnit.MILLISECONDS));+ } finally {+ dataPlane.shutdown();+ }+ }+ }++ private static CertificateMaterial material(CertificateGenerator generator, String arn, String host) {+ CertificateGenerator.GeneratedCertificate pair = generator.generateSelfSignedCertificate(+ host, List.of(), KeyAlgorithm.RSA_2048);+ return new CertificateMaterial(arn, pair.certificatePem(), pair.privateKeyPem(), null);+ }++ private static Listener listener(String name, String certificateArn) {+ Listener listener = new Listener();+ listener.setListenerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/app/" + name + "/1/2");+ listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1");+ listener.setPort(8443);+ listener.setProtocol("HTTPS");+ listener.setCertificates(List.of(certificateArn));+ return listener;+ }++ private static Rule fixedRule(String body) {+ Action action = new Action();+ action.setType("fixed-response");+ action.setFixedResponseStatusCode("200");+ action.setFixedResponseMessageBody(body);+ Rule rule = new Rule();+ rule.setDefault(true);+ rule.setActions(List.of(action));+ return rule;+ }+}