fix(elbv2): reject a listener certificate the account does not have (#5474)

A listener stored whatever certificate ARN it was given. CreateListener,
ModifyListener and AddListenerCertificates each model CertificateNotFound,
and all three took an ARN naming nothing and answered 200, so a listener
could be left serving a certificate that was never uploaded. Only the other
direction worked: ELBv2 reports its references to IAM, so
DeleteServerCertificate already refused with DeleteConflict while a listener
held one.

The error is the one AWS publishes on those three operations and no others:
botocore gives CertificateNotFoundException the code CertificateNotFound,
400, senderFault, and the API reference lists it under
AddListenerCertificates, CreateListener and ModifyListener with one
sentence, "The specified certificate does not exist." That sentence is the
message rather than one naming the ARN, because it is the one the reference
publishes.

The check covers the listener types the member belongs to and no more. The
reference marks Certificates "[HTTPS and TLS listeners]" on CreateListener
and ModifyListener, and describes AddListenerCertificates as adding to the
list "for the specified HTTPS or TLS listener", so a certificate on a
listener of any other protocol is a configuration it does not describe. What
AWS answers there is not CertificateNotFound on any evidence to hand, so
such a request keeps the behaviour it had rather than being refused with a
code read off the wrong case. A test pins each side of that line. The line
follows the protocol the listener ends the call with, not the one it started
with: ModifyListener takes a protocol without taking certificates, so when
none arrive the certificates checked are the ones already on file. An HTTP
listener holding an ARN that resolves to nothing is left alone, and the
request that turns it into an HTTPS one, which is where those certificates
start being served, is refused.

A blank entry is refused the same way, rather than skipped. Certificates is
the list of certificates the listener serves, an empty value in it names one
no better than a value that is no ARN at all, and the Query parser turns an
empty CertificateArn parameter into exactly that entry, so skipping it
stored a certificate the listener cannot serve.

ELB Classic already answered this question in full, resolving an ARN to an
IAM server certificate or an ACM one and holding IAM's certificate lock
across the write. This is the second caller, so the three private methods it
kept, certificateExists, iamServerCertificate and acmCertificateExists, move
to CertificateReferenceResolver in core.common and Classic reads them from
there. Neither referrer owns the lookup: IAM holds server certificates, ACM
holds the rest, and a listener carries only the ARN. Classic's public
constructors are untouched, so its unit tests still build it the same way.

The check alone is not enough, which is why the lock moves with it. A
certificate can be deleted between the check and the write, and the delete
walks the reference providers under IAM's own lock, so every write that
records an IAM certificate runs inside that lock and re-checks there, while
the fail-fast check outside it keeps the error precedence. That covers
CreateListener as much as the two writes to a listener already published:
until the new listener is in the map, nothing the delete walks can see that
it holds the certificate. A race test drives each of them against
DeleteServerCertificate over the wire, and with the lock removed they leave
a listener holding a deleted certificate in 1 of 30 trials for
AddListenerCertificates and 4 of 30 for CreateListener, so the guarantee is
measured rather than asserted.

Where the check sits in ModifyListener is part of the fix. The listener it
modifies is the stored object, and the port, protocol and SSL policy were
set before anything could refuse the request, so a refusal answered 400 over
a listener already moved to the new port: no later read put it back, and the
data plane was never restarted to match. Every refusal now lands before the
first setter.

An absent resolver leaves the old behaviour in place. ElbV2Service is wired
by hand in its unit tests, with no IAM and no ACM, and a listener write
there is the write it was before any certificate existed to check. The
dependency is a field rather than a constructor parameter because that is
how this class takes all six of its others, and converting it would be a
refactor this change does not need.

docs/services/elb.md said listener certificate ARNs are not validated when
they are added, which was true and is the behaviour this removes, so it now
documents the three operations, the protocols they cover, the empty value,
the protocol change, the error and the lock, as the Classic page already
does.

Sixteen integration tests cover a missing IAM certificate, a missing ACM
one, a blank entry, a value that is no ARN at all and an ARN of a service
that serves no certificates, an uploaded certificate and an ACM certificate
being accepted, a listener carrying no certificate, a TLS listener held to
the same check as an HTTPS one and a listener of a protocol with no
certificates left alone, a protocol change refused over the certificate it
already held and allowed over one that exists, a second certificate being
added, a refused change leaving the port and protocol as they were, and the
two writes that must refuse without changing what the listener already
serves. Every certificate and load balancer they make is registered for
cleanup: the account's certificate quota is 20 and the Quarkus instance is
shared, so one left behind fails an unrelated class's upload instead of
anything here.

Three things the reference states about these operations stay open, each
wanting an error code no source here gives: CreateListener and
ModifyListener take "exactly one certificate" and AddListenerCertificates
"one certificate per call", where Floci accepts a list; TooManyCertificates
is modeled on all three and no quota is enforced; and
DescribeListenerCertificates is documented to report the default certificate
alongside the list, with IsDefault telling them apart, which Floci does not
model.

Driven through the standard hashicorp/aws provider against a local instance
as well, which is how the change was checked against a real client rather
than only against the suite: an aws_iam_server_certificate and an
aws_lb_listener serving it apply clean, and a listener naming a certificate
nobody uploaded fails with CertificateNotFound and the reference's sentence.
That failure arrives at the end of the provider's create timeout rather than
at once, because the provider retries this error on all three calls, the
AddListenerCertificates one against a constant named iamPropagationTimeout:
real AWS is eventually consistent about a certificate just imported, so a
client waits it out. Floci's storage is immediately consistent and nothing
here models a propagation delay, so the retry simply ends in the refusal.

The same contract is pinned at the SDK boundary too, as eight boto3 tests in
compatibility-tests: the refusal on each of the three operations, the
accepted cases, and both protocol edges. They run in under a second, where
driving the same thing through Terraform in CI costs about a minute for the
accepted case and nearly two for the refusal, almost all of it the
provider's waiter and the retry above rather than anything Floci does. The
suite had no ELB coverage at all before this. Each test takes its load
balancer back out before its certificates, which is the order that frees
them, and test_acm.py's private certificate builder moves to a conftest
fixture taking the common name rather than being copied, since the new file
needs the same pair.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-11 21:47:38 -05:00
1 parent 6d7d85f0f8
commit 233253334d
10 files changed
+1069 -116

No files matched your search

@@ -0,0 +1,118 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Collection;
import java.util.Optional;
/**
* Whether a certificate another service names exists, and the lock that keeps the answer true for
* the length of a write.
*
* <p>A load balancer listener or a CloudFront distribution serves a certificate it does not own:
* IAM holds server certificates and ACM holds the rest, and the referring service carries only the
* ARN. Both of those lookups and the lock belong to neither referrer, which is why they live here
* rather than in one service's package.
*
* <p>A service that is not present answers for its own certificates: an absent {@link IamService}
* or {@link AcmService} leaves every ARN in its namespace existing rather than missing. That keeps
* a unit test that wires one referrer and no certificate service on the behaviour it had before a
* check existed, which is the same judgement the referrers make about an absent resolver.
*/
@ApplicationScoped
public class CertificateReferenceResolver {
private static final Logger LOG = Logger.getLogger(CertificateReferenceResolver.class);
private final IamService iamService;
private final AcmService acmService;
@Inject
public CertificateReferenceResolver(IamService iamService, AcmService acmService) {
this.iamService = iamService;
this.acmService = acmService;
}
/**
* Whether the ARN names a certificate that exists. Anything that is not an ARN of a service
* that serves certificates does not name one, so it does not exist either.
*/
public boolean exists(String region, String certificateArn) {
if (certificateArn == null || certificateArn.isBlank()
|| !AwsArnUtils.isArn(certificateArn)) {
return false;
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(certificateArn);
return switch (arn.service()) {
case "iam" -> iamService == null || iamServerCertificate(arn, certificateArn).isPresent();
case "acm" -> acmService == null || acmCertificateExists(region, certificateArn);
default -> false;
};
}
/**
* 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.
*/
public void runWhileHeld(Collection<String> certificateArns, Runnable action) {
if (iamService == null || !namesIamCertificate(certificateArns)) {
action.run();
return;
}
iamService.runWithServerCertificatesHeld(action);
}
/** Whether any of these ARNs names a certificate IAM serves, rather than ACM. */
public boolean namesIamCertificate(Collection<String> certificateArns) {
if (certificateArns == null) {
return false;
}
for (String certificateArn : certificateArns) {
if (certificateArn != null && !certificateArn.isBlank()
&& AwsArnUtils.isArn(certificateArn)
&& "iam".equals(AwsArnUtils.parse(certificateArn).service())) {
return true;
}
}
return false;
}
/**
* The certificate the ARN names, by the name it carries. Only the certificate's current ARN
* counts: a rename keeps the former ones for the reference check that
* {@code DeleteServerCertificate} makes, and they do not name a certificate a new listener can
* be given.
*/
private Optional<ServerCertificate> iamServerCertificate(AwsArnUtils.Arn arn,
String certificateArn) {
if (!arn.resource().startsWith("server-certificate/")) {
return Optional.empty();
}
String name = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);
return iamService.findServerCertificate(name)
.filter(certificate -> certificateArn.equals(certificate.getArn()));
}
private boolean acmCertificateExists(String region, String certificateArn) {
try {
return certificateArn.equals(
acmService.describeCertificate(certificateArn, region).getArn());
} catch (AwsException e) {
LOG.debugv("ACM certificate {0} not usable in {1}: {2}", certificateArn, region,
e.getMessage());
return false;
}
}
}
@@ -2,9 +2,9 @@ package io.github.hectorvent.floci.services.elb;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
@@ -18,7 +18,6 @@ import io.github.hectorvent.floci.services.elb.model.ClassicListener;
import io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancer;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.ServerCertificateReferenceProvider;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -32,7 +31,6 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@@ -63,7 +61,7 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final IamService iamService;
private final AcmService acmService;
private final CertificateReferenceResolver certificates;
// region → load balancer name → record
private Map<String, Map<String, ClassicLoadBalancer>> loadBalancers = new ConcurrentHashMap<>();
@@ -100,7 +98,7 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
this.config = config;
this.regionResolver = regionResolver;
this.iamService = iamService;
this.acmService = acmService;
this.certificates = new CertificateReferenceResolver(iamService, acmService);
}
@PostConstruct
@@ -615,81 +613,38 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
}
/**
* Runs a write that records a listener's IAM server certificate while IAM holds the lock
* {@code DeleteServerCertificate} takes, so the certificate 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
* commit.
* 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 commit.
*
* <p>Only for a write that names an IAM certificate. A listener with no certificate, or one
* served by ACM, cannot leave a load balancer holding a deleted IAM certificate, and the
* delete reads a snapshot of the listener list rather than the live one, so an unguarded
* write cannot disturb its walk either. Taking the lock for every write would instead make a
* certificate delete wait on an unrelated load balancer, listener or zone write, and the
* other way round, for writes that cannot affect it.
*
* <p>This class's own invariants do not ride on this lock. The unique load balancer name is
* <p>This class's own invariants do not ride on that lock. The unique load balancer name is
* carried by {@code putIfAbsent} and the listener list by {@link #listenerLock}, both of
* which hold whether or not IAM is present, which is what the unit tests build.
*/
private void whileCertificatesHeld(List<ClassicListener> listeners, Runnable action) {
if (iamService == null || !namesIamCertificate(listeners)) {
action.run();
return;
}
iamService.runWithServerCertificatesHeld(action);
}
/** Whether any of these listeners names a certificate that IAM serves, rather than ACM. */
private static boolean namesIamCertificate(List<ClassicListener> listeners) {
for (ClassicListener listener : listeners) {
String certificate = listener.getSslCertificateId();
if (certificate != null && !certificate.isBlank() && AwsArnUtils.isArn(certificate)
&& "iam".equals(AwsArnUtils.parse(certificate).service())) {
return true;
}
}
return false;
certificates.runWhileHeld(certificateIdsOf(listeners), action);
}
private void requireCertificates(String region, List<ClassicListener> listeners) {
for (ClassicListener listener : listeners) {
String certificateId = listener.getSslCertificateId();
if (certificateId != null && !certificateId.isBlank() && !certificateExists(region, certificateId)) {
if (certificateId != null && !certificateId.isBlank()
&& !certificates.exists(region, certificateId)) {
throw new AwsException("CertificateNotFound",
"Server Certificate not found for the key: " + certificateId, 400);
}
}
}
private boolean certificateExists(String region, String certificateArn) {
if (!AwsArnUtils.isArn(certificateArn)) {
return false;
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(certificateArn);
return switch (arn.service()) {
case "iam" -> iamService == null || iamServerCertificate(arn, certificateArn).isPresent();
case "acm" -> acmService == null || acmCertificateExists(region, certificateArn);
default -> false;
};
}
private Optional<ServerCertificate> iamServerCertificate(AwsArnUtils.Arn arn, String certificateArn) {
if (!arn.resource().startsWith("server-certificate/")) {
return Optional.empty();
}
String name = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);
return iamService.findServerCertificate(name)
.filter(certificate -> certificateArn.equals(certificate.getArn()));
}
private boolean acmCertificateExists(String region, String certificateArn) {
try {
return certificateArn.equals(acmService.describeCertificate(certificateArn, region).getArn());
} catch (AwsException e) {
LOG.debugv("ACM certificate {0} not usable in {1}: {2}", certificateArn, region, e.getMessage());
return false;
private static List<String> certificateIdsOf(List<ClassicListener> listeners) {
List<String> certificateIds = new ArrayList<>();
for (ClassicListener listener : listeners) {
if (listener.getSslCertificateId() != null) {
certificateIds.add(listener.getSslCertificateId());
}
}
return certificateIds;
}
private static void validateListener(ClassicListener listener) {
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SsrfProtection;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
@@ -53,6 +54,14 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
@Inject
EmulatorConfig config;
/**
* Left null by the unit tests, which wire this service without IAM or ACM. A referrer with no
* resolver keeps the behaviour it had before the check existed, rather than refusing every
* certificate because it cannot look one up.
*/
@Inject
CertificateReferenceResolver certificateResolver;
// region → ARN → resource
private Map<String, Map<String, LoadBalancer>> loadBalancers = new ConcurrentHashMap<>();
private Map<String, Map<String, TargetGroup>> targetGroups = new ConcurrentHashMap<>();
@@ -495,6 +504,10 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
"A listener already exists on port " + port + " for this load balancer.", 400);
}
// Fail fast, then again under the guard the listener is published inside: this one keeps
// the error precedence, and only the one holding the lock is atomic with the write.
requireCertificates(region, protocol, certificates);
LoadBalancer lb = requireLoadBalancer(region, lbArn);
String lbType = lb.getType() != null ? lb.getType() : "application";
String typePrefix = lbTypePrefix(lbType);
@@ -512,8 +525,15 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
listener.setDefaultActions(defaultActions != null ? new ArrayList<>(defaultActions) : new ArrayList<>());
listener.setAlpnPolicy(alpnPolicy != null ? new ArrayList<>(alpnPolicy) : new ArrayList<>());
regionListeners.put(listenerArn, listener);
listeners.put(region, regionListeners);
// 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, () -> {
requireCertificates(region, protocol, certificates);
regionListeners.put(listenerArn, listener);
listeners.put(region, regionListeners);
});
lbToListeners.computeIfAbsent(lbArn, k -> new ArrayList<>()).add(listenerArn);
// auto-create the default rule
@@ -590,7 +610,8 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
boolean restartDataPlane = false;
boolean recompileRules = false;
if (port != null && !Objects.equals(listener.getPort(), port)) {
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()
@@ -600,12 +621,32 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
throw new AwsException("DuplicateListener",
"A listener already exists on port " + port + " for this load balancer.", 400);
}
}
// 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();
requireCertificates(region, effectiveProtocol,
certificates != null ? certificates : listener.getCertificates());
if (portChanges) {
listener.setPort(port);
restartDataPlane = true;
}
if (protocol != null) listener.setProtocol(protocol);
if (sslPolicy != null) listener.setSslPolicy(sslPolicy);
if (certificates != null) listener.setCertificates(new ArrayList<>(certificates));
if (certificates != null) {
whileCertificatesHeld(certificates, () -> {
requireCertificates(region, effectiveProtocol, certificates);
listener.setCertificates(new ArrayList<>(certificates));
});
}
if (alpnPolicy != null) listener.setAlpnPolicy(new ArrayList<>(alpnPolicy));
if (defaultActions != null) {
listener.setDefaultActions(new ArrayList<>(defaultActions));
@@ -909,12 +950,16 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
public void addListenerCertificates(String region, String listenerArn, List<String> certArns) {
Listener listener = requireListener(region, listenerArn);
for (String certArn : certArns) {
if (!listener.getCertificates().contains(certArn)) {
listener.getCertificates().add(certArn);
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);
persistRegion(listeners, region);
});
}
public void removeListenerCertificates(String region, String listenerArn, List<String> certArns) {
@@ -930,6 +975,57 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
// ── Helpers ───────────────────────────────────────────────────────────────
/**
* Refuses a certificate the account does not have. {@code CertificateNotFound} is modeled on
* {@code CreateListener}, {@code ModifyListener} and {@code AddListenerCertificates} alone,
* and the reference gives it one sentence, so that sentence is the message rather than one
* naming the ARN.
*
* <p>Only for the listener types the member belongs to. The reference marks {@code
* Certificates} "[HTTPS and TLS listeners]" and the user guide scopes the certificate list to
* an HTTPS listener, so a certificate on a listener of any other protocol is a configuration
* AWS does not describe, and what it answers there is not {@code CertificateNotFound} on any
* evidence here. Such a request keeps the behaviour it had rather than being refused with a
* code read off the wrong case.
*
* <p>A blank entry is refused like any other. {@code Certificates} is a list of the
* certificates the listener serves, and an empty value in it names one no better than a value
* that is no ARN at all, so letting it through would store a certificate the listener cannot
* serve.
*/
private void requireCertificates(String region, String protocol,
List<String> certificateArns) {
if (certificateResolver == null || certificateArns == null || !servesCertificates(protocol)) {
return;
}
for (String certificateArn : certificateArns) {
if (certificateArn == null || certificateArn.isBlank()
|| !certificateResolver.exists(region, certificateArn)) {
throw new AwsException("CertificateNotFound",
"The specified certificate does not exist.", 400);
}
}
}
/** The listener protocols a certificate belongs to, per the reference's own bracket. */
private static boolean servesCertificates(String protocol) {
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;
}
certificateResolver.runWhileHeld(certificateArns, action);
}
private LoadBalancer requireLoadBalancer(String region, String arn) {
LoadBalancer lb = loadBalancers.getOrDefault(region, Map.of()).get(arn);
if (lb == null) {