diff --git a/compatibility-tests/sdk-test-python/README.md b/compatibility-tests/sdk-test-python/README.md index ce26482b1c..b98b0d7fd6 100644 --- a/compatibility-tests/sdk-test-python/README.md +++ b/compatibility-tests/sdk-test-python/README.md @@ -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 diff --git a/compatibility-tests/sdk-test-python/conftest.py b/compatibility-tests/sdk-test-python/conftest.py index a63b11c6bc..7b1a52474b 100644 --- a/compatibility-tests/sdk-test-python/conftest.py +++ b/compatibility-tests/sdk-test-python/conftest.py @@ -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 # ============================================ diff --git a/compatibility-tests/sdk-test-python/tests/test_acm.py b/compatibility-tests/sdk-test-python/tests/test_acm.py index 19e7be2525..6d78e47ea4 100644 --- a/compatibility-tests/sdk-test-python/tests/test_acm.py +++ b/compatibility-tests/sdk-test-python/tests/test_acm.py @@ -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( diff --git a/compatibility-tests/sdk-test-python/tests/test_elbv2_listener_certificates.py b/compatibility-tests/sdk-test-python/tests/test_elbv2_listener_certificates.py new file mode 100644 index 0000000000..b0b71f512d --- /dev/null +++ b/compatibility-tests/sdk-test-python/tests/test_elbv2_listener_certificates.py @@ -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} diff --git a/docs/services/elb.md b/docs/services/elb.md index b5e204a49a..60be5cfec4 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -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.). diff --git a/src/main/java/io/github/hectorvent/floci/core/common/CertificateReferenceResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/CertificateReferenceResolver.java new file mode 100644 index 0000000000..aa83691e87 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/CertificateReferenceResolver.java @@ -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. + * + *

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. + * + *

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. + * + *

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 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 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 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; + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java index f9d770758e..e569dc5604 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java +++ b/src/main/java/io/github/hectorvent/floci/services/elb/ElbClassicService.java @@ -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> 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. * - *

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. - * - *

This class's own invariants do not ride on this lock. The unique load balancer name is + *

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 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 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 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 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 certificateIdsOf(List listeners) { + List certificateIds = new ArrayList<>(); + for (ClassicListener listener : listeners) { + if (listener.getSslCertificateId() != null) { + certificateIds.add(listener.getSslCertificateId()); + } } + return certificateIds; } private static void validateListener(ClassicListener listener) { diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java index cc650372e8..270813936f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java @@ -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> loadBalancers = new ConcurrentHashMap<>(); private Map> 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 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 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 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. + * + *

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. + * + *

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 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 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) { diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2CertificateDeleteRaceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2CertificateDeleteRaceTest.java new file mode 100644 index 0000000000..6eb3eeb79d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2CertificateDeleteRaceTest.java @@ -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. + * + *

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 prepare, + BiFunction write) throws Exception { + List dangling = new ArrayList<>(); + List 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> 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> racers) throws Exception { + for (Future racer : racers) { + racer.get(); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java new file mode 100644 index 0000000000..5894b74ac7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java @@ -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 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"); + } +}