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

@@ -22,6 +22,7 @@ Compatibility tests for [Floci](https://github.com/hectorvent/floci) using **bot
| `cloudwatch-metrics` | PutMetricData, ListMetrics, GetMetricStatistics, alarms |
| `cloudformation-naming` | Auto physical name generation, explicit name precedence, cross-reference |
| `cognito` | User pools, clients, AdminCreateUser, InitiateAuth, GetUser |
| `elbv2` | Listener certificates resolved against IAM and ACM |
## Requirements
@@ -1,5 +1,6 @@
"""Shared fixtures for AWS service integration tests."""
import datetime
import os
import uuid
import io
@@ -11,6 +12,10 @@ import boto3
import pytest
from botocore.config import Config
from botocore.exceptions import ClientError
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
logger = logging.getLogger(__name__)
@@ -211,6 +216,18 @@ def iot_jobs_data_client(aws_config, client_config):
return boto3.client("iot-jobs-data", config=client_config, **aws_config)
@pytest.fixture
def ec2_client(aws_config, client_config):
"""Create EC2 client."""
return boto3.client("ec2", config=client_config, **aws_config)
@pytest.fixture
def elbv2_client(aws_config, client_config):
"""Create Elastic Load Balancing v2 client."""
return boto3.client("elbv2", config=client_config, **aws_config)
# ============================================
# Utility Fixtures
# ============================================
@@ -238,6 +255,42 @@ def minimal_lambda_zip():
return buf.getvalue()
@pytest.fixture
def make_self_signed_certificate():
"""Return a factory for a self-signed certificate and its private key.
The factory takes the common name and returns a tuple of (cert_pem, key_pem) bytes.
"""
def _make(common_name="test.example.com"):
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
subject = issuer = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, common_name)]
)
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.now(datetime.timezone.utc))
.not_valid_after(
datetime.datetime.now(datetime.timezone.utc)
+ datetime.timedelta(days=365)
)
.sign(key, hashes.SHA256())
)
cert_pem = cert.public_bytes(serialization.Encoding.PEM)
key_pem = key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption(),
)
return cert_pem, key_pem
return _make
# ============================================
# Resource Fixtures with Cleanup
# ============================================
@@ -1,14 +1,12 @@
"""ACM integration tests."""
import datetime
import re
import pytest
from botocore.exceptions import ClientError
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec, rsa
from cryptography.x509.oid import NameOID
FAKE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-0000-000000000000"
@@ -109,41 +107,9 @@ class TestACMCertificateLifecycle:
class TestACMImportExport:
"""Test ACM import and export operations."""
@staticmethod
def _generate_self_signed_cert():
"""Generate a self-signed certificate and private key.
Returns:
Tuple of (cert_pem_bytes, key_pem_bytes).
"""
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
subject = issuer = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, "test.example.com")]
)
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.now(datetime.timezone.utc))
.not_valid_after(
datetime.datetime.now(datetime.timezone.utc)
+ datetime.timedelta(days=365)
)
.sign(key, hashes.SHA256())
)
cert_pem = cert.public_bytes(serialization.Encoding.PEM)
key_pem = key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption(),
)
return cert_pem, key_pem
def test_import_certificate(self, acm_client):
def test_import_certificate(self, acm_client, make_self_signed_certificate):
"""Test ImportCertificate with self-signed cert returns ARN."""
cert_pem, key_pem = self._generate_self_signed_cert()
cert_pem, key_pem = make_self_signed_certificate()
response = acm_client.import_certificate(
Certificate=cert_pem, PrivateKey=key_pem
@@ -156,9 +122,9 @@ class TestACMImportExport:
finally:
acm_client.delete_certificate(CertificateArn=arn)
def test_import_certificate_with_chain(self, acm_client):
def test_import_certificate_with_chain(self, acm_client, make_self_signed_certificate):
"""Test ImportCertificate with certificate chain returns ARN."""
cert_pem, key_pem = self._generate_self_signed_cert()
cert_pem, key_pem = make_self_signed_certificate()
response = acm_client.import_certificate(
Certificate=cert_pem,
@@ -173,9 +139,9 @@ class TestACMImportExport:
finally:
acm_client.delete_certificate(CertificateArn=arn)
def test_get_imported_certificate(self, acm_client):
def test_get_imported_certificate(self, acm_client, make_self_signed_certificate):
"""Test GetCertificate on imported cert returns matching body."""
cert_pem, key_pem = self._generate_self_signed_cert()
cert_pem, key_pem = make_self_signed_certificate()
import_response = acm_client.import_certificate(
Certificate=cert_pem, PrivateKey=key_pem
@@ -189,9 +155,9 @@ class TestACMImportExport:
finally:
acm_client.delete_certificate(CertificateArn=arn)
def test_export_certificate(self, acm_client):
def test_export_certificate(self, acm_client, make_self_signed_certificate):
"""Test ExportCertificate returns the imported key, encrypted under the passphrase."""
cert_pem, key_pem = self._generate_self_signed_cert()
cert_pem, key_pem = make_self_signed_certificate()
passphrase = b"test-passphrase"
import_response = acm_client.import_certificate(
@@ -0,0 +1,195 @@
"""ELBv2 listener certificate tests.
CreateListener, ModifyListener and AddListenerCertificates resolve every certificate they are
given against IAM and ACM, and answer CertificateNotFound when one of them does not exist.
Those three are the only operations the reference models that error on.
"""
import logging
import pytest
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
MISSING_IAM_CERTIFICATE = "arn:aws:iam::000000000000:server-certificate/never-uploaded"
MISSING_ACM_CERTIFICATE = (
"arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-0000-000000000000"
)
class ListenerFixtures:
"""A load balancer to hang listeners on, with IAM server certificates on demand."""
def __init__(self, elbv2_client, iam_client, ec2_client, make_certificate, name):
self._elbv2_client = elbv2_client
self._iam_client = iam_client
self._make_certificate = make_certificate
self._name = name
self._certificate_names = []
self._next_port = 443
# A load balancer needs subnets in two availability zones and at most one in each, so
# pick by zone rather than taking the first two the account happens to list.
zones = {}
for subnet in ec2_client.describe_subnets()["Subnets"]:
zones.setdefault(subnet["AvailabilityZone"], subnet["SubnetId"])
subnets = [zones[zone] for zone in sorted(zones)[:2]]
response = elbv2_client.create_load_balancer(
Name=name, Type="application", Subnets=subnets
)
self.load_balancer_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
def upload_certificate(self):
"""Upload a self-signed certificate to IAM and return its ARN."""
certificate_name = f"{self._name}-{len(self._certificate_names)}"
certificate_pem, key_pem = self._make_certificate(f"{certificate_name}.example.com")
response = self._iam_client.upload_server_certificate(
ServerCertificateName=certificate_name,
CertificateBody=certificate_pem.decode(),
PrivateKey=key_pem.decode(),
)
self._certificate_names.append(certificate_name)
return response["ServerCertificateMetadata"]["Arn"]
def create_listener(self, certificate_arn=None, protocol="HTTPS"):
"""CreateListener on the load balancer, each on a port of its own."""
request = {
"LoadBalancerArn": self.load_balancer_arn,
"Protocol": protocol,
"Port": self._next_port,
"DefaultActions": [
{"Type": "fixed-response", "FixedResponseConfig": {"StatusCode": "200"}}
],
}
self._next_port += 1
if certificate_arn is not None:
request["Certificates"] = [{"CertificateArn": certificate_arn}]
return self._elbv2_client.create_listener(**request)["Listeners"][0]["ListenerArn"]
def certificates_on(self, listener_arn):
"""The certificate ARNs the listener is serving."""
response = self._elbv2_client.describe_listener_certificates(ListenerArn=listener_arn)
return {certificate["CertificateArn"] for certificate in response["Certificates"]}
def clean_up(self):
"""Take everything back out, load balancer first.
Deleting it cascades to its listeners, which is what frees the certificates: one a
listener still holds answers DeleteConflict, and the account's quota is 20 for the
whole run.
"""
try:
self._elbv2_client.delete_load_balancer(LoadBalancerArn=self.load_balancer_arn)
except ClientError as e:
logger.warning("Failed to clean up load balancer %s: %s", self.load_balancer_arn, e)
for certificate_name in self._certificate_names:
try:
self._iam_client.delete_server_certificate(
ServerCertificateName=certificate_name
)
except ClientError as e:
logger.warning(
"Failed to clean up server certificate %s: %s", certificate_name, e
)
@pytest.fixture
def listeners(
elbv2_client, iam_client, ec2_client, make_self_signed_certificate, unique_name
):
"""Create and clean up one load balancer and the certificates a test puts on it."""
fixtures = ListenerFixtures(
elbv2_client, iam_client, ec2_client, make_self_signed_certificate, unique_name
)
yield fixtures
fixtures.clean_up()
class TestELBv2ListenerCertificates:
"""Test that a certificate named on a listener has to exist."""
def test_create_listener_rejects_missing_iam_certificate(self, listeners):
"""Test CreateListener with an unknown IAM certificate raises CertificateNotFound."""
with pytest.raises(ClientError) as exc_info:
listeners.create_listener(MISSING_IAM_CERTIFICATE)
response = exc_info.value.response
assert response["Error"]["Code"] == "CertificateNotFound"
assert response["Error"]["Message"] == "The specified certificate does not exist."
assert response["ResponseMetadata"]["HTTPStatusCode"] == 400
def test_create_listener_rejects_missing_acm_certificate(self, listeners):
"""Test CreateListener with an unknown ACM certificate raises CertificateNotFound."""
with pytest.raises(ClientError) as exc_info:
listeners.create_listener(MISSING_ACM_CERTIFICATE)
assert exc_info.value.response["Error"]["Code"] == "CertificateNotFound"
def test_create_listener_accepts_uploaded_iam_certificate(self, listeners):
"""Test CreateListener accepts a certificate the account has uploaded to IAM."""
certificate_arn = listeners.upload_certificate()
listener_arn = listeners.create_listener(certificate_arn)
assert listeners.certificates_on(listener_arn) == {certificate_arn}
def test_create_listener_without_certificates_is_untouched(self, listeners):
"""Test CreateListener with no certificates at all is accepted."""
assert listeners.create_listener()
def test_http_listener_is_left_alone(self, listeners):
"""Test the check covers the protocols the Certificates member is bracketed for.
The reference brackets it for HTTPS and TLS listeners, so a certificate on an HTTP
listener is a configuration it does not describe. This pins the scope of the check
rather than endorsing the request.
"""
assert listeners.create_listener(MISSING_IAM_CERTIFICATE, protocol="HTTP")
def test_modify_listener_rejects_missing_certificate(self, listeners, elbv2_client):
"""Test ModifyListener refuses an unknown certificate and keeps the one it had."""
certificate_arn = listeners.upload_certificate()
listener_arn = listeners.create_listener(certificate_arn)
with pytest.raises(ClientError) as exc_info:
elbv2_client.modify_listener(
ListenerArn=listener_arn,
Certificates=[{"CertificateArn": MISSING_IAM_CERTIFICATE}],
)
assert exc_info.value.response["Error"]["Code"] == "CertificateNotFound"
# The refusal has to land before the write, or the listener is left serving a
# certificate the account does not have.
assert listeners.certificates_on(listener_arn) == {certificate_arn}
def test_add_listener_certificates_rejects_missing_certificate(
self, listeners, elbv2_client
):
"""Test AddListenerCertificates refuses an unknown certificate and adds nothing."""
certificate_arn = listeners.upload_certificate()
listener_arn = listeners.create_listener(certificate_arn)
with pytest.raises(ClientError) as exc_info:
elbv2_client.add_listener_certificates(
ListenerArn=listener_arn,
Certificates=[{"CertificateArn": MISSING_IAM_CERTIFICATE}],
)
assert exc_info.value.response["Error"]["Code"] == "CertificateNotFound"
assert listeners.certificates_on(listener_arn) == {certificate_arn}
def test_add_listener_certificates_accepts_second_certificate(
self, listeners, elbv2_client
):
"""Test AddListenerCertificates puts a second uploaded certificate on the listener."""
first = listeners.upload_certificate()
second = listeners.upload_certificate()
listener_arn = listeners.create_listener(first)
elbv2_client.add_listener_certificates(
ListenerArn=listener_arn, Certificates=[{"CertificateArn": second}]
)
assert listeners.certificates_on(listener_arn) == {first, second}
+1 -1
View File
@@ -93,7 +93,7 @@ Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB)
- Each `CreateListener` automatically creates an immutable default rule (`priority=default`, `isDefault=true`). This rule cannot be deleted; use `ModifyListener` to change its action.
- Rule priorities are unique per listener: `CreateRule` and `SetRulePriorities` only reject a priority held by another rule on the same listener. `SetRulePriorities` is atomic: all priority assignments are validated before any change is committed.
- `DeleteTargetGroup` is rejected with `ResourceInUse` while the target group is referenced by any listener or rule.
- `DeleteServerCertificate` is rejected with `DeleteConflict` while an IAM server certificate is named by a listener. Listener certificate ARNs are not validated when they are added.
- An HTTPS or TLS listener's certificates must name existing certificates: an IAM server certificate ARN or an ACM certificate ARN. `CreateListener`, `ModifyListener` and `AddListenerCertificates` reject a missing or empty one with `CertificateNotFound`, the three operations the API reference models it on, and a `ModifyListener` that turns a listener into an HTTPS or TLS one is held to the same check over the certificates it already carried. An IAM server certificate a listener references cannot be deleted: `DeleteServerCertificate` returns `DeleteConflict` until the certificate is removed from the listener. A write that records one runs while IAM holds its certificate lock, so a certificate cannot be deleted between the check and the write.
- `DeleteRule` is rejected with `OperationNotPermitted` for the default rule.
- `DescribeSSLPolicies` returns a pre-seeded list of standard AWS SSL policies (`ELBSecurityPolicy-*`).
- `DescribeAccountLimits` returns standard default limits (e.g., 50 load balancers per region, 100 target groups, etc.).
@@ -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) {
@@ -0,0 +1,221 @@
package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A listener and the certificate it names cannot end up disagreeing about whether the certificate
* exists.
*
* <p>The same hazard the Classic suite drives: {@code DeleteServerCertificate} checks the
* reference providers under IAM's own lock, while a listener write checks the certificate and then
* records it. Both writes that record one are driven here, over the wire, because the certificate
* arrives as a request parameter and the check lives behind the handler.
*/
@QuarkusTest
class ElbV2CertificateDeleteRaceTest {
private static final String ELB_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260427/us-east-1/elasticloadbalancing/aws4_request";
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
private static final int TRIALS = 30;
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private static String uploadCertificate(String name) {
CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
"elbv2.race.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
return given().header("Authorization", IAM_AUTH)
.formParam("Action", "UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then().statusCode(200)
.extract().path("UploadServerCertificateResponse.UploadServerCertificateResult"
+ ".ServerCertificateMetadata.Arn");
}
private static String loadBalancer(String name) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateLoadBalancer")
.formParam("Name", name)
.formParam("Type", "application")
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
.formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b"))
.when().post("/").then().statusCode(200)
.extract().path("CreateLoadBalancerResponse.CreateLoadBalancerResult"
+ ".LoadBalancers.member.LoadBalancerArn");
}
/** A listener carrying no certificate yet, so the race is only about the one being added. */
private static String listener(String lbArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", lbArn)
.formParam("Protocol", "HTTPS")
.formParam("Port", "443")
.formParam("DefaultActions.member.1.Type", "fixed-response")
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")
.when().post("/").then().statusCode(200)
.extract().path("CreateListenerResponse.CreateListenerResult.Listeners.member"
+ ".ListenerArn");
}
private static int createListenerWith(String lbArn, String certificateArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", lbArn)
.formParam("Protocol", "HTTPS")
.formParam("Port", "443")
.formParam("DefaultActions.member.1.Type", "fixed-response")
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")
.formParam("Certificates.member.1.CertificateArn", certificateArn)
.when().post("/").then().extract().statusCode();
}
private static int addListenerCertificate(String listenerArn, String certificateArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "AddListenerCertificates")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", certificateArn)
.when().post("/").then().extract().statusCode();
}
private static int deleteCertificate(String name) {
return given().header("Authorization", IAM_AUTH)
.formParam("Action", "DeleteServerCertificate")
.formParam("ServerCertificateName", name)
.when().post("/").then().extract().statusCode();
}
private static boolean certificateExists(String name) {
return given().header("Authorization", IAM_AUTH)
.formParam("Action", "GetServerCertificate")
.formParam("ServerCertificateName", name)
.when().post("/").then().extract().statusCode() == 200;
}
private static void deleteLoadBalancer(String lbArn) {
given().header("Authorization", ELB_AUTH)
.formParam("Action", "DeleteLoadBalancer")
.formParam("LoadBalancerArn", lbArn)
.when().post("/").then().extract().statusCode();
}
@Test
void addingACertificateNeverLeavesAListenerHoldingADeletedOne() throws Exception {
race("the listener it was added to", ElbV2CertificateDeleteRaceTest::listener,
ElbV2CertificateDeleteRaceTest::addListenerCertificate);
}
@Test
void creatingAListenerNeverPublishesOneHoldingADeletedCertificate() throws Exception {
// The certificate is checked before the listener is built, and the listener is not in the
// map until it is published, so without the guard the delete sees nothing referring to
// the certificate and takes it while the listener is on its way in.
race("the listener it was created with", lbArn -> lbArn,
ElbV2CertificateDeleteRaceTest::createListenerWith);
}
/**
* Races one listener write against {@code DeleteServerCertificate} {@value #TRIALS} times.
*
* @param what how to describe the listener in a failure, since the write decides whether one
* already exists.
* @param prepare whatever the write needs in place first, built from the trial's load balancer
* and outside the timed section: the listener for a write that adds to one, the load
* balancer itself for the write that creates it.
* @param write the listener write under test, given what {@code prepare} returned and the
* certificate ARN, answering with its status code.
*/
private void race(String what, Function<String, String> prepare,
BiFunction<String, String, Integer> write) throws Exception {
List<String> dangling = new ArrayList<>();
List<String> unresolved = new ArrayList<>();
for (int trial = 0; trial < TRIALS; trial++) {
String name = "elbv2-race-cert-" + trial + "-" + suffix();
String arn = uploadCertificate(name);
String lbArn = loadBalancer("elbv2-race-" + trial + "-" + suffix());
String target = prepare.apply(lbArn);
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger writeStatus = new AtomicInteger();
AtomicInteger deleteStatus = new AtomicInteger();
try {
List<Future<?>> racers = List.of(pool.submit(() -> {
start.await();
writeStatus.set(write.apply(target, arn));
return null;
}), pool.submit(() -> {
start.await();
deleteStatus.set(deleteCertificate(name));
return null;
}));
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(60, TimeUnit.SECONDS), "trial did not finish");
reportAnythingUnexpected(racers);
int wrote = writeStatus.get();
int delete = deleteStatus.get();
if (wrote == 200 && delete == 200 && !certificateExists(name)) {
dangling.add("trial " + trial + ": " + what
+ " holds deleted certificate " + name);
}
// Exactly one order wins and the loser says why: the certificate is recorded and
// the delete answers DeleteConflict, or the certificate goes and the write is
// refused with CertificateNotFound. Two failures would leave the race untested
// while the trial still looked clean, so they are collected rather than ignored.
if (!(wrote == 200 && delete == 409) && !(wrote == 400 && delete == 200)) {
unresolved.add("trial " + trial + ": write=" + wrote + " delete=" + delete);
}
} finally {
pool.shutdownNow();
deleteLoadBalancer(lbArn);
if (certificateExists(name)) {
deleteCertificate(name);
}
}
}
assertTrue(dangling.isEmpty(), "a listener was left holding a deleted certificate in "
+ dangling.size() + " of " + TRIALS + " trials: " + dangling);
assertTrue(unresolved.isEmpty(),
"every trial must resolve as one order winning and the other being told why, "
+ "these did not: " + unresolved);
}
/**
* Surfaces anything a racing task threw. The throwable otherwise stays in the task's
* {@link Future}, the status stays at its initial zero, and the trial reads as the other
* order having won without the race ever having run.
*/
private static void reportAnythingUnexpected(List<Future<?>> racers) throws Exception {
for (Future<?> racer : racers) {
racer.get();
}
}
}
@@ -0,0 +1,348 @@
package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A listener's certificates are resolved against IAM and ACM on the way in.
* {@code CertificateNotFound} is modeled on {@code CreateListener}, {@code ModifyListener} and
* {@code AddListenerCertificates} alone, and the reference gives it one sentence and a 400.
*/
@QuarkusTest
class ElbV2ListenerCertificateIntegrationTest {
private static final String ELB_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260427/us-east-1/elasticloadbalancing/aws4_request";
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static final String ACM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/acm/aws4_request";
private static final String MISSING_IAM_CERTIFICATE =
"arn:aws:iam::000000000000:server-certificate/never-uploaded";
private static final String MISSING_ACM_CERTIFICATE = "arn:aws:acm:us-east-1:000000000000"
+ ":certificate/00000000-0000-0000-0000-000000000000";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
/**
* Every certificate and load balancer this class makes is taken back out again. The account's
* server certificate quota is 20 and the Quarkus instance is shared, so a certificate left
* behind here fails an unrelated class's upload rather than anything in this one.
*/
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private String uploadCertificate() {
CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
"elbv2.certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
String name = "elbv2-cert-" + suffix();
// Registered before the load balancer's undo so it runs after it: a certificate a
// listener still holds answers DeleteConflict.
cleanup.register(() -> given().header("Authorization", IAM_AUTH)
.formParam("Action", "DeleteServerCertificate")
.formParam("ServerCertificateName", name)
.when().post("/"));
return given().header("Authorization", IAM_AUTH)
.formParam("Action", "UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then().statusCode(200)
.extract().path("UploadServerCertificateResponse.UploadServerCertificateResult"
+ ".ServerCertificateMetadata.Arn");
}
private static String requestAcmCertificate() {
return given().header("Authorization", ACM_AUTH)
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
.contentType("application/x-amz-json-1.1")
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
.body("{\"DomainName\": \"elbv2-" + suffix()
+ ".example.com\", \"ValidationMethod\": \"DNS\"}")
.when().post("/").then().statusCode(200)
.extract().path("CertificateArn");
}
private String loadBalancer() {
String arn = given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateLoadBalancer")
.formParam("Name", "elbv2-cert-" + suffix())
.formParam("Type", "application")
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
.formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b"))
.when().post("/").then().statusCode(200)
.extract().path("CreateLoadBalancerResponse.CreateLoadBalancerResult"
+ ".LoadBalancers.member.LoadBalancerArn");
// Deleting the load balancer cascades to its listeners, which is what frees the
// certificate for the undo registered above.
cleanup.register(() -> given().header("Authorization", ELB_AUTH)
.formParam("Action", "DeleteLoadBalancer")
.formParam("LoadBalancerArn", arn)
.when().post("/"));
return arn;
}
private ValidatableResponse createListener(String certificateArn) {
return createListener("HTTPS", certificateArn);
}
private ValidatableResponse createListener(String protocol, String certificateArn) {
RequestSpecification request = given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", loadBalancer())
.formParam("Protocol", protocol)
.formParam("Port", "443")
.formParam("DefaultActions.member.1.Type", "fixed-response")
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200");
if (certificateArn != null) {
request = request.formParam("Certificates.member.1.CertificateArn", certificateArn);
}
return request.when().post("/").then();
}
private String listenerServing(String certificateArn) {
return listenerServing("HTTPS", certificateArn);
}
private String listenerServing(String protocol, String certificateArn) {
return createListener(protocol, certificateArn).statusCode(200)
.extract().path("CreateListenerResponse.CreateListenerResult.Listeners.member"
+ ".ListenerArn");
}
private static ValidatableResponse describeListener(String listenerArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "DescribeListeners")
.formParam("ListenerArns.member.1", listenerArn)
.when().post("/").then().statusCode(200);
}
private static String listenerField(String listenerArn, String field) {
return describeListener(listenerArn).extract()
.path("DescribeListenersResponse.DescribeListenersResult.Listeners.member."
+ field).toString();
}
/** Read through {@code getList} so one certificate and several arrive the same shape. */
private static List<String> listenerCertificates(String listenerArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "DescribeListenerCertificates")
.formParam("ListenerArn", listenerArn)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getList("DescribeListenerCertificatesResponse"
+ ".DescribeListenerCertificatesResult.Certificates.member.CertificateArn");
}
@Test
void createListenerRejectsAnIamCertificateThatDoesNotExist() {
createListener(MISSING_IAM_CERTIFICATE)
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"))
.body("ErrorResponse.Error.Message",
equalTo("The specified certificate does not exist."));
}
@Test
void createListenerRejectsAnAcmCertificateThatDoesNotExist() {
createListener(MISSING_ACM_CERTIFICATE)
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
}
@Test
void createListenerRejectsSomethingThatNamesNoCertificateAtAll() {
createListener("not-an-arn")
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
// An ARN of a service that serves no certificates names one no better.
createListener("arn:aws:s3:::some-bucket")
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
}
@Test
void createListenerAcceptsAnUploadedIamCertificate() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void createListenerAcceptsAnAcmCertificate() {
createListener(requestAcmCertificate()).statusCode(200);
}
@Test
void createListenerWithNoCertificateIsUntouched() {
// Nothing to resolve, so the check has nothing to say: a listener may carry none.
createListener(null).statusCode(200);
}
@Test
void aTlsListenerIsHeldToTheSameCheckAsAnHttpsOne() {
// The reference brackets the member for HTTPS and TLS, so both, not HTTPS alone.
createListener("TLS", MISSING_IAM_CERTIFICATE)
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
}
@Test
void aListenerOfAProtocolWithNoCertificatesIsLeftAlone() {
// The member is bracketed "[HTTPS and TLS listeners]", so a certificate on an HTTP
// listener is a configuration the reference does not describe. What AWS answers there is
// not CertificateNotFound on any evidence to hand, so Floci does not invent one: this
// pins the scope of the check rather than endorsing the request.
createListener("HTTP", MISSING_IAM_CERTIFICATE).statusCode(200);
}
@Test
void modifyListenerRejectsAMissingCertificateAndKeepsTheOneItHad() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", MISSING_IAM_CERTIFICATE)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
// The refusal has to land before the write, or the listener is left serving a
// certificate the account does not have.
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void addListenerCertificatesRejectsAMissingCertificateAndAddsNothing() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "AddListenerCertificates")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", MISSING_IAM_CERTIFICATE)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void createListenerRejectsABlankCertificateArn() {
// An empty value in the list names a certificate no better than "not-an-arn" does, and
// letting it through would leave the listener holding something it cannot serve.
createListener("").statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
}
@Test
void addListenerCertificatesRejectsABlankCertificateArnAndAddsNothing() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "AddListenerCertificates")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void aRefusedModifyListenerLeavesThePortAndProtocolAsTheyWere() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", listenerArn)
.formParam("Port", "8443")
.formParam("Protocol", "TLS")
.formParam("Certificates.member.1.CertificateArn", MISSING_IAM_CERTIFICATE)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
// A refused request must change nothing. The listener being modified is the stored one,
// so a check that ran after the first setter would answer 400 over a listener already
// moved to the new port, which no later read would put back.
assertEquals("443", listenerField(listenerArn, "Port"));
assertEquals("HTTPS", listenerField(listenerArn, "Protocol"));
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void turningAnHttpListenerIntoAnHttpsOneChecksTheCertificateItAlreadyHeld() {
// An HTTP listener may carry a certificate nothing resolves, because the check does not
// cover its protocol. Serving it is what the check covers, and the request that starts
// serving it names no certificate of its own, so the one on file is the one to resolve.
String listenerArn = listenerServing("HTTP", MISSING_IAM_CERTIFICATE);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", listenerArn)
.formParam("Protocol", "HTTPS")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
assertEquals("HTTP", listenerField(listenerArn, "Protocol"));
}
@Test
void turningAnHttpListenerIntoAnHttpsOneIsAllowedWhenTheCertificateExists() {
String listenerArn = listenerServing("HTTP", uploadCertificate());
given().header("Authorization", ELB_AUTH)
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", listenerArn)
.formParam("Protocol", "HTTPS")
.when().post("/").then().statusCode(200);
assertEquals("HTTPS", listenerField(listenerArn, "Protocol"));
}
@Test
void addListenerCertificatesAcceptsASecondUploadedCertificate() {
String first = uploadCertificate();
String second = uploadCertificate();
String listenerArn = listenerServing(first);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "AddListenerCertificates")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", second)
.when().post("/").then().statusCode(200);
assertTrue(listenerCertificates(listenerArn).containsAll(List.of(first, second)),
"both certificates should be on the listener");
}
}