feat(elbv2): terminate HTTPS with ACM and IAM certificates (#5959)

* feat(elbv2): serve HTTPS listeners with ACM and IAM certificates

Route HTTPS traffic with SNI and refresh certificates when they change.

* fix(elbv2): preserve attached ACM certificates

Refuse revocation while a listener uses the certificate and keep
certificate listings responsive when many listeners are configured.
This commit is contained in:
David Phillips authored and GitHub committed 2026-10-19 23:40:17 -04:00
1 parent 73da37b90e
commit 0da0c80824
19 files changed
+5284 -471

No files matched your search

@@ -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()));
}
}
+6 -2
View File
@@ -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-*`).
@@ -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 void runWhileHeld(Collection<String> certificateArns, Runnable action) {
if (iamService == null || !namesIamCertificate(certificateArns)) {
action.run();
return;
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();
}
iamService.runWithServerCertificatesHeld(action);
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) {
supplyWhileHeld(certificateArns, () -> {
action.run();
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;
}
}
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. */
@@ -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);
}
@@ -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;
}
@@ -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;
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;
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);
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);
}
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);
// 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());
}
}
}
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))) {
@@ -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);
}
}
@@ -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;
@ApplicationScoped
public class ElbV2DataPlane {
@@ -85,14 +109,80 @@ public class ElbV2DataPlane {
@Inject
Ec2Service ec2Service;
@Inject
CertificateReferenceResolver certificateResolver;
@Inject
ObjectMapper 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) {}
@PostConstruct
void init() {
@@ -112,9 +211,16 @@ public class ElbV2DataPlane {
@PreDestroy
void 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;
}
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);
}
public void restartListener(Listener listener, String region, List<Rule> rules) {
if (config.services().elbv2().mock()) {
return;
}
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);
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();
servers.computeIfAbsent(newBinding.port(), this::startPortServer);
return;
onPort(prepared.port(), state -> {
if (!stopping && listenerBindings.containsKey(arn)) {
ensurePortServer(prepared.port());
}
return null;
});
}
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);
}
}
startListener(listener, region, rules);
return applied;
}
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);
}
}
ruleChains.remove(listenerArn);
listenerRegions.remove(listenerArn);
boolean updateListener(Integer storedPort, BooleanSupplier publication) {
return storedPort == null ? publication.getAsBoolean()
: onPort(storedPort, state -> publication.getAsBoolean());
}
public void recompileRules(String listenerArn, List<Rule> rules) {
AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);
if (ref != null) {
ref.set(compileRules(rules));
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();
}
if (listenerBindings.get(arn) != expected) {
return false;
}
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);
}
}
return true;
}
private void restoreReservation(String arn, ListenerBinding expected, ListenerBinding prepared) {
if (expected == null) {
listenerBindings.remove(arn, prepared);
} else {
listenerBindings.replace(arn, prepared, expected);
}
}
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);
}
}
}
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) {
public void requireCompatibleListenerProtocol(String listenerArn, int port, String protocol) {
if (config.services().elbv2().mock()) {
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);
}
}
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;
}
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);
}
}));
}
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);
}
}
if (certificates.isEmpty()) {
throw new IllegalStateException("HTTPS listener port " + port + " has no certificate");
}
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 options;
}
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));
}
}
}
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()));
}
}
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;
}
String region = listenerRegions.get(listenerArn);
if (region == null) {
req.response().setStatusCode(502).end("No listener region");
return;
}
AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);
if (ref == null) {
req.response().setStatusCode(502).end("No rule chain");
return;
}
List<CompiledRule> chain = ref.get();
for (CompiledRule compiled : chain) {
for (CompiledRule compiled : listener.chain()) {
if (compiled.matches(req)) {
executeAction(req, compiled.action, region, listenerArn);
executeAction(req, compiled.action, listener.region(), listener.arn());
return;
}
}
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;
}
/** 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 listenerArn = listenersByHost.get(host);
if (listenerArn != null) {
return listenerArn;
String direct = routing.hosts().get(host);
if (direct != null) {
return routing.listeners().get(direct);
}
List<String> declaring = listenersDeclaringHost(listenersByHost, host);
if (declaring.size() == 1) {
return declaring.get(0);
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;
}
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;
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;
}
if (listenersByHost.size() == 1) {
return listenersByHost.values().iterator().next();
}
return null;
return routing.hosts().size() == 1
? routing.listeners().get(routing.hosts().values().iterator().next()) : null;
}
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;
}
for (CompiledRule compiled : ref.get()) {
if (compiled.declaresHost(host)) {
declaring.add(listenerArn);
break;
}
}
}
return declaring;
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) {
@@ -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.ServerCertificateReferenceProvide
import 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;
@ApplicationScoped
public class ElbV2Service implements ResourceProvider, ServerCertificateReferenceProvider, VpcDependencyProvider {
private static final Logger LOG = Logger.getLogger(ElbV2Service.class);
@Inject
ElbV2DataPlane dataPlane;
@@ -148,13 +156,13 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
for (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, ServerCertificateReferenc
for (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, ServerCertificateReferenc
if (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 index
tgToLbs.values().forEach(lbSet -> lbSet.remove(arn));
@@ -559,31 +569,38 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
listener.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 rule
Rule 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);
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;
}
}
if (!initialTags.isEmpty()) {
tags.put(listenerArn, new LinkedHashMap<>(initialTags));
}
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;
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;
}
}
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);
}
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);
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 (protocol != null) {
listener.setProtocol(protocol);
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 (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));
// 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;
dataPlane.recompileRules(listenerArn, () -> getListenerRules(region, listenerArn));
}
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));
}
return listener;
return requireListener(region, listenerArn);
}
// ── Rules ─────────────────────────────────────────────────────────────────
@@ -759,7 +803,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
regionRules.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 actions
for (Action a : rule.getActions()) {
@@ -769,7 +813,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
if (!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, ServerCertificateReferenc
if (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, ServerCertificateReferenc
if (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, ServerCertificateReferenc
Set<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, ServerCertificateReferenc
throw 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, ServerCertificateReferenc
return "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, ServerCertificateReferenc
action.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) {
@@ -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");
@@ -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;
}
}
@@ -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);
}
}
@Test
void aModifiedAttributeWinsOverItsDefaultAndTheRestStillReport() {
String arn = createLoadBalancer("attrs-modified", "application", "10.99.");
@@ -241,6 +241,11 @@ class ElbV2ListenerCertificateIntegrationTest {
assertEquals(List.of(certificate), listenerCertificates(listener));
}
@Test
void anHttpListenerStillNeedsNoCertificate() {
createListener("HTTP", null).statusCode(200);
}
@Test
void aTlsListenerIsHeldToTheSameCheckAsAnHttpsOne() {
// The reference brackets the member for HTTPS and TLS, so both, not HTTPS alone.
@@ -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;
}
}
@@ -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());
}
}
@@ -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);
}
}
@@ -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 {
@BeforeEach
void 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);
}
@Test
void 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());
}
@Test
void 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");
@@ -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;
}
}