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

@@ -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) {