diff --git a/docs/services/elb.md b/docs/services/elb.md index 265e3e906f..9920e7d4ac 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -47,8 +47,10 @@ Floci supports Application Load Balancers (ALB) and Network Load Balancers (NLB) HTTPS listeners require a default certificate. Supply one when creating a listener or changing an HTTP listener to HTTPS; an omitted certificate list on an existing HTTPS listener keeps its default. -Listener responses omit `Certificates` when the listener has none. Configured certificates -remain present in create, describe and modify responses. +Listener responses carry the listener's default certificate in `Certificates`, and omit the +member when the listener has none. The certificate list `AddListenerCertificates` builds is +read through `DescribeListenerCertificates` rather than through a listener response, as the +reference describes. Creating an HTTPS or TLS listener without `SslPolicy` selects `ELBSecurityPolicy-2016-08`, matching AWS's default for API, CLI and CloudFormation creation. An explicit policy @@ -151,7 +153,11 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on - 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. - HTTPS and TLS certificate ARNs must refer to existing IAM server certificates or ACM certificates. `CreateListener`, `ModifyListener` and `AddListenerCertificates` reject a blank or unknown ARN with `CertificateNotFound`. When `ModifyListener` changes the protocol to HTTPS or TLS, it checks any inherited certificate ARNs too. An HTTPS listener also needs a default certificate: `CreateListener` and `ModifyListener` reject an absent or empty effective certificate list with `InvalidConfigurationRequest`. A referenced IAM server certificate cannot be deleted: `DeleteServerCertificate` returns `DeleteConflict` until the certificate is removed from the listener. Writes recording a new IAM certificate reference hold IAM's certificate lock, so the certificate cannot be deleted between the check and the write. A refused change preserves the listener's previous port, protocol, policy and certificates. -- `RemoveListenerCertificates` refuses removal of an HTTPS or TLS listener's default certificate with `OperationNotPermitted` (400) and preserves the certificate list. Use `ModifyListener` to replace the default certificate. Additional certificates can still be removed. +- `RemoveListenerCertificates` refuses removal of an HTTPS or TLS listener's default certificate with `OperationNotPermitted` (400) and preserves the certificate list. Use `ModifyListener` to replace the default certificate. Additional certificates can still be removed. A default certificate the certificate list holds as well is refused too: the published sentence, that you cannot remove the default certificate for a listener, names no exception for that case, so the refusal is Floci's reading. +- A listener's default certificate is one certificate. `CreateListener` and `ModifyListener` refuse a `Certificates` list naming more than one with `ValidationError` (400), the reference saying of that member on both operations that you must provide exactly one certificate. No published sentence gives the code a longer list is answered with, so the code is Floci's reading. +- The certificate list is kept apart from the default certificate. A listener created through the API starts with an empty certificate list, and `AddListenerCertificates` adds to it, taking more than one certificate in a call: the API member reads as one certificate per call, while the Application Load Balancers guide adds three in one call of its own, and the guide's example is what Floci takes. `ModifyListener` replaces the default certificate and leaves the certificate list standing, so a default that was added to the list keeps serving SNI after it is replaced. `AddListenerCertificates` answers with the certificate list the add leaves behind rather than with the certificates the call named. +- `DescribeListenerCertificates` names the default certificate with `IsDefault` true and each certificate in the certificate list with `IsDefault` false, so a certificate that is both appears twice. A listener's own `Certificates` member is its default certificate alone and carries no `IsDefault`, which is where the reference puts that member. +- A load balancer's listeners share a certificate quota of 25, counting the certificates in their certificate lists and not their default certificates, which is the published Application Load Balancer quota and the number `DescribeAccountLimits` reports. `AddListenerCertificates` refuses the certificate that would pass it with `TooManyCertificates` (400). A TLS listener on a Network Load Balancer is held to the same ceiling, which is Floci's reading rather than a published number of its own. - `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/floci/aws/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java index 5c9edae642..5e734a6928 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2DataPlane.java @@ -822,10 +822,11 @@ public class ElbV2DataPlane { Set hosts = new LinkedHashSet<>(); List certificates = new ArrayList<>(); if (secure) { - if (listener.getCertificates() == null || listener.getCertificates().isEmpty()) { + List served = listener.servedCertificates(); + if (served.isEmpty()) { throw new IllegalStateException("HTTPS listener has no default certificate"); } - for (String certificateArn : listener.getCertificates()) { + for (String certificateArn : served) { CertificateMaterial certificate = certificateResolver.publishedMaterial( listener.getListenerArn(), region, certificateArn); try { diff --git a/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java index 5ea985c74b..aa5ea9612f 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java @@ -47,7 +47,8 @@ public class ElbV2QueryHandler { ACCOUNT_LIMITS.put("rules-per-application-load-balancer", "100"); ACCOUNT_LIMITS.put("target-groups-per-application-load-balancer", "100"); ACCOUNT_LIMITS.put("targets-per-application-load-balancer", "1000"); - ACCOUNT_LIMITS.put("certificates-per-application-load-balancer", "25"); + ACCOUNT_LIMITS.put("certificates-per-application-load-balancer", + String.valueOf(ElbV2Service.CERTIFICATES_PER_LOAD_BALANCER)); ACCOUNT_LIMITS.put("condition-values-per-alb-rule", "5"); ACCOUNT_LIMITS.put("condition-wildcards-per-alb-rule", "5"); } @@ -775,13 +776,13 @@ public class ElbV2QueryHandler { private Response handleAddListenerCertificates(MultivaluedMap p, String region) { String listenerArn = p.getFirst("ListenerArn"); List certs = parseCertificateList(p, "Certificates"); - service.addListenerCertificates(region, listenerArn, certs); + List certificateList = service.addListenerCertificates(region, listenerArn, certs); XmlBuilder xml = new XmlBuilder() .start("AddListenerCertificatesResponse", AwsNamespaces.ELB_V2) .start("AddListenerCertificatesResult") .start("Certificates"); - for (String c : certs) { + for (String c : certificateList) { xml.start("member").elem("CertificateArn", c).end("member"); } xml.end("Certificates") @@ -800,12 +801,22 @@ public class ElbV2QueryHandler { private Response handleDescribeListenerCertificates(MultivaluedMap p, String region) { String listenerArn = p.getFirst("ListenerArn"); - List certs = service.describeListenerCertificates(region, listenerArn); + List certs = + service.describeListenerCertificates(region, listenerArn); XmlBuilder xml = new XmlBuilder() .start("DescribeListenerCertificatesResponse", AwsNamespaces.ELB_V2) .start("DescribeListenerCertificatesResult"); - appendCertificates(xml, certs); + if (!certs.isEmpty()) { + xml.start("Certificates"); + for (ElbV2Service.ListenerCertificate certificate : certs) { + xml.start("member") + .elem("CertificateArn", certificate.certificateArn()) + .elem("IsDefault", String.valueOf(certificate.isDefault())) + .end("member"); + } + xml.end("Certificates"); + } xml.end("DescribeListenerCertificatesResult") .raw(AwsQueryResponse.responseMetadata()) .end("DescribeListenerCertificatesResponse"); @@ -878,7 +889,8 @@ public class ElbV2QueryHandler { if (l.getPort() != null) xml.elem("Port", String.valueOf(l.getPort())); xml.elem("Protocol", safe(l.getProtocol())); xml.elem("SslPolicy", l.getSslPolicy()); - appendCertificates(xml, l.getCertificates()); + appendCertificates(xml, l.getDefaultCertificate() == null ? List.of() + : List.of(l.getDefaultCertificate())); xml.start("DefaultActions"); for (Action a : l.getDefaultActions()) { xml.start("member").raw(actionXml(a)).end("member"); @@ -892,6 +904,7 @@ public class ElbV2QueryHandler { return xml.build(); } + /** The {@code Certificates} a listener carries, which is its default certificate alone. */ private static void appendCertificates(XmlBuilder xml, List certificates) { if (!certificates.isEmpty()) { xml.start("Certificates"); diff --git a/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java index 0a3409a973..3e50b7860d 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java @@ -48,6 +48,12 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc private static final Logger LOG = Logger.getLogger(ElbV2Service.class); private static final String DEFAULT_SSL_POLICY = "ELBSecurityPolicy-2016-08"; + /** + * "Certificates per Application Load Balancer (excluding default certificates)", the one + * certificate quota the reference publishes a number for, and the number + * {@code DescribeAccountLimits} reports. + */ + public static final int CERTIFICATES_PER_LOAD_BALANCER = 25; /** {@code LoadBalancerTypeEnum}, in the model's order. */ private static final List LOAD_BALANCER_TYPES = List.of("application", "network", "gateway"); @@ -670,6 +676,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc List defaultActions, List alpnPolicy, Map initialTags) { validatePort(port, "port"); + requireOneDefaultCertificate(certificates); requireGatewayListenerSettings(requireLoadBalancer(region, lbArn), protocol, port); Map regionListeners = listeners.computeIfAbsent(region, k -> new ConcurrentHashMap<>()); @@ -701,7 +708,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc listener.setProtocol(protocol != null ? protocol : ("gateway".equals(lbType) ? "GENEVE" : "HTTP")); listener.setSslPolicy(sslPolicy == null && servesCertificates(listener.getProtocol()) ? DEFAULT_SSL_POLICY : sslPolicy); - listener.setCertificates(certificates != null ? new ArrayList<>(certificates) : new ArrayList<>()); + listener.setDefaultCertificate(defaultCertificateOf(certificates)); listener.setDefaultActions(defaultActions != null ? new ArrayList<>(defaultActions) : new ArrayList<>()); listener.setAlpnPolicy(alpnPolicy != null ? new ArrayList<>(alpnPolicy) : new ArrayList<>()); @@ -838,6 +845,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc String sslPolicy, List certificates, List defaultActions, List alpnPolicy) { validatePort(port, "port"); + requireOneDefaultCertificate(certificates); while (true) { Listener initial = requireListener(region, listenerArn); LoadBalancer initialLb = requireLoadBalancer(region, initial.getLoadBalancerArn()); @@ -857,13 +865,14 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc Listener listener = requireListener(region, listenerArn); LoadBalancer lb = requireLoadBalancer(region, listener.getLoadBalancerArn()); ListenerState expected = listenerState(listener, lb); - Listener prospective = prospectiveListener(expected, protocol, port, certificates); + Listener prospective = prospectiveListener(expected, protocol, port, + defaultCertificateOf(certificates), null); boolean clearSecuritySettings = clearsSecuritySettings(expected.protocol(), protocol); requireAvailableListenerPort(listeners.getOrDefault(region, Map.of()), listener.getLoadBalancerArn(), listenerArn, prospective.getPort()); if (!validateExistingListener(region, expected, lb, () -> { requireListenerProtocolTransition(expected.protocol(), protocol, sslPolicy, certificates); - requireListenerCertificates(region, prospective.getProtocol(), prospective.getCertificates()); + requireListenerCertificates(region, prospective.getProtocol(), prospective.servedCertificates()); requireCompatibleListenerProtocol(listenerArn, prospective.getPort(), prospective.getProtocol()); })) { continue; @@ -888,7 +897,13 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc listener.setSslPolicy(sslPolicy); } if (certificates != null || clearSecuritySettings) { - listener.setCertificates(new ArrayList<>(prospective.getCertificates())); + // A default the certificate list holds as well is not counted while it is + // the default, so replacing it starts counting it and the ceiling has to be + // asked about, which is why this operation models TooManyCertificates too. + requireCertificateQuota(region, expected, prospective.getDefaultCertificate(), + prospective.getCertificateList()); + listener.setDefaultCertificate(prospective.getDefaultCertificate()); + listener.setCertificateList(new ArrayList<>(prospective.getCertificateList())); } if (alpnPolicy != null) { listener.setAlpnPolicy(new ArrayList<>(alpnPolicy)); @@ -913,15 +928,15 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc boolean applied = restart ? publishExistingListener(prospective, region, expected, lb, () -> requireCertificates(region, prospective.getProtocol(), - certificates != null ? certificates : prospective.getCertificates()), publication) - : supplyCertificatesHeld(prospective.getCertificates(), () -> { + certificates != null ? certificates : prospective.servedCertificates()), publication) + : supplyCertificatesHeld(prospective.servedCertificates(), () -> { synchronized (lb) { if (!isCurrentListener(region, expected)) { return false; } } - requireCertificates(region, prospective.getProtocol(), prospective.getCertificates()); - requirePublishedCertificates(region, prospective.getProtocol(), prospective.getCertificates()); + requireCertificates(region, prospective.getProtocol(), prospective.servedCertificates()); + requirePublishedCertificates(region, prospective.getProtocol(), prospective.servedCertificates()); return dataPlane.updateListener(expected.port(), publication); }); if (applied) { @@ -1210,7 +1225,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc List references = new ArrayList<>(); for (Map regionListeners : listeners.values()) { for (Listener listener : regionListeners.values()) { - for (String certificate : listener.getCertificates()) { + for (String certificate : listener.servedCertificates()) { references.add(new Reference(certificate, "listener " + listener.getListenerArn())); } } @@ -1218,25 +1233,34 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc return references; } - public void addListenerCertificates(String region, String listenerArn, List certArns) { + /** + * The certificate list as the add leaves it, which is what the operation answers with: "the + * certificates in the certificate list", rather than the certificates the call named. + * + *

The reference's member says one certificate per call, and the Application Load Balancers + * guide adds three in one call of its own, so a list is taken. + */ + public List addListenerCertificates(String region, String listenerArn, List certArns) { Listener initial = requireListener(region, listenerArn); requireCertificates(region, initial.getProtocol(), certArns); - changeListenerCertificates(region, listenerArn, certArns, false); + return changeListenerCertificates(region, listenerArn, certArns, false); } public void removeListenerCertificates(String region, String listenerArn, List certArns) { changeListenerCertificates(region, listenerArn, certArns, true); } - private void changeListenerCertificates(String region, String listenerArn, List requested, boolean remove) { + private List changeListenerCertificates(String region, String listenerArn, + List requested, boolean remove) { while (true) { Listener listener = requireListener(region, listenerArn); LoadBalancer lb = requireLoadBalancer(region, listener.getLoadBalancerArn()); ListenerState expected = listenerState(listener, lb); - List certificates = new ArrayList<>(expected.certificates()); + List certificates = new ArrayList<>(expected.certificateList()); + boolean namesTheDefault = remove && expected.defaultCertificate() != null + && requested.contains(expected.defaultCertificate()); if (remove) { - if (servesCertificates(expected.protocol()) && !certificates.isEmpty() - && requested.contains(certificates.getFirst())) { + if (servesCertificates(expected.protocol()) && namesTheDefault) { throw new AwsException("OperationNotPermitted", "The default listener certificate cannot be removed.", 400); } @@ -1251,11 +1275,16 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc certificates.add(arn); } } + requireCertificateQuota(region, expected, certificates); + } + Listener prospective = prospectiveListener(expected, null, null, null, certificates); + if (namesTheDefault) { + prospective.setDefaultCertificate(null); } - Listener prospective = prospectiveListener(expected, null, null, certificates); if (publishExistingListener(prospective, region, expected, lb, () -> { if (!remove) { requireCertificates(region, expected.protocol(), requested); + requireCertificateQuota(region, expected, certificates); } }, () -> { synchronized (lb) { @@ -1263,28 +1292,109 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc if (!isCurrentListener(region, expected)) { return false; } - listener.setCertificates(certificates); + if (!remove) { + // The ceiling belongs to the load balancer rather than to the listener, so + // it is counted here as well, under the lock every certificate write takes: + // two adds on sibling listeners would otherwise each count the other's list + // as it was before the other wrote and pass the ceiling together. + requireCertificateQuota(region, expected, certificates); + } + listener.setCertificateList(certificates); + if (namesTheDefault) { + // Only a listener of a protocol the member does not describe reaches here, + // the throw above refusing the removal otherwise, and it keeps the + // behaviour this service had before the default was held apart. + listener.setDefaultCertificate(null); + } persistRegion(listeners, region); return true; } })) { - return; + return certificates; } } } - public List describeListenerCertificates(String region, String listenerArn) { + /** + * The quota the reference publishes is per load balancer and excludes the default certificates, + * so a listener's own default is not counted where its certificate list holds it as well, and + * the listeners of one load balancer share the ceiling. The default the count is taken against + * is the one the write leaves behind rather than the one the listener holds now, since + * replacing a default the certificate list also holds starts counting it. The number in hand is + * the Application Load Balancer one; a TLS listener on a Network Load Balancer is held to the + * same ceiling, which is Floci's reading rather than a sentence of its own. + */ + private void requireCertificateQuota(String region, ListenerState expected, List certificateList) { + requireCertificateQuota(region, expected, expected.defaultCertificate(), certificateList); + } + + private void requireCertificateQuota(String region, ListenerState expected, String defaultCertificate, + List certificateList) { + String loadBalancerArn = expected.listener().getLoadBalancerArn(); + String listenerArn = expected.listener().getListenerArn(); + int held = countedCertificates(defaultCertificate, certificateList); + for (Listener other : listeners.getOrDefault(region, Map.of()).values()) { + if (loadBalancerArn.equals(other.getLoadBalancerArn()) + && !listenerArn.equals(other.getListenerArn())) { + held += countedCertificates(other.getDefaultCertificate(), other.getCertificateList()); + } + } + if (held > CERTIFICATES_PER_LOAD_BALANCER) { + throw new AwsException("TooManyCertificates", + "You've reached the limit on the number of certificates per load balancer.", 400); + } + } + + private static int countedCertificates(String defaultCertificate, List certificateList) { + return (int) certificateList.stream().filter(arn -> !arn.equals(defaultCertificate)).count(); + } + + /** + * The default certificate and then the certificate list, a default the list holds as well + * named twice, "once with IsDefault set to true and once with IsDefault set to false". + */ + public List describeListenerCertificates(String region, String listenerArn) { Listener listener = requireListener(region, listenerArn); - return new ArrayList<>(listener.getCertificates()); + List certificates = new ArrayList<>(); + if (listener.getDefaultCertificate() != null) { + certificates.add(new ListenerCertificate(listener.getDefaultCertificate(), true)); + } + for (String certificate : listener.getCertificateList()) { + certificates.add(new ListenerCertificate(certificate, false)); + } + return certificates; + } + + /** A certificate {@code DescribeListenerCertificates} names, and the part it plays. */ + public record ListenerCertificate(String certificateArn, boolean isDefault) {} + + /** + * The member both create and modify read as the listener's default certificate, where the + * reference says "You must provide exactly one certificate." No source gives the code a longer + * list is answered with, so it is the {@code ValidationError} this service answers a request + * shape with, which is Floci's reading. + */ + private static void requireOneDefaultCertificate(List certificates) { + if (certificates != null && certificates.size() > 1) { + throw new AwsException("ValidationError", + "You must provide exactly one certificate.", 400); + } + } + + private static String defaultCertificateOf(List certificates) { + return certificates == null || certificates.isEmpty() ? null : certificates.getFirst(); } // ── Helpers ─────────────────────────────────────────────────────────────── - private record ListenerState(Listener listener, Integer port, String protocol, List certificates) {} + private record ListenerState(Listener listener, Integer port, String protocol, + String defaultCertificate, List certificateList, + List certificates) {} private static ListenerState listenerState(Listener listener) { return new ListenerState(listener, listener.getPort(), listener.getProtocol(), - new ArrayList<>(listener.getCertificates())); + listener.getDefaultCertificate(), new ArrayList<>(listener.getCertificateList()), + listener.servedCertificates()); } private static ListenerState listenerState(Listener listener, LoadBalancer lb) { @@ -1297,18 +1407,23 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc Listener current = listeners.getOrDefault(region, Map.of()).get(expected.listener().getListenerArn()); return current == expected.listener() && Objects.equals(current.getPort(), expected.port()) && Objects.equals(current.getProtocol(), expected.protocol()) - && current.getCertificates().equals(expected.certificates()); + && Objects.equals(current.getDefaultCertificate(), expected.defaultCertificate()) + && current.getCertificateList().equals(expected.certificateList()); } private static Listener prospectiveListener(ListenerState expected, String protocol, Integer port, - List certificates) { + String defaultCertificate, List certificateList) { Listener prospective = new Listener(); prospective.setListenerArn(expected.listener().getListenerArn()); prospective.setLoadBalancerArn(expected.listener().getLoadBalancerArn()); prospective.setPort(port != null ? port : expected.port()); prospective.setProtocol(protocol != null ? protocol : expected.protocol()); - prospective.setCertificates(clearsSecuritySettings(expected.protocol(), protocol) ? new ArrayList<>() - : new ArrayList<>(certificates != null ? certificates : expected.certificates())); + if (!clearsSecuritySettings(expected.protocol(), protocol)) { + prospective.setDefaultCertificate(defaultCertificate != null ? defaultCertificate + : expected.defaultCertificate()); + prospective.setCertificateList(new ArrayList<>(certificateList != null ? certificateList + : expected.certificateList())); + } return prospective; } @@ -1416,7 +1531,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc LoadBalancer lb, Runnable referenceValidation, BooleanSupplier publication) { try { return publishListener(prospective, region, expected.port(), publication, - operation -> supplyCertificatesHeld(prospective.getCertificates(), () -> { + operation -> supplyCertificatesHeld(prospective.servedCertificates(), () -> { synchronized (lb) { if (!isCurrentListener(region, expected) || loadBalancers.getOrDefault(region, Map.of()).get(lb.getLoadBalancerArn()) != lb) { @@ -1424,7 +1539,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc } } referenceValidation.run(); - requirePublishedCertificates(region, prospective.getProtocol(), prospective.getCertificates()); + requirePublishedCertificates(region, prospective.getProtocol(), prospective.servedCertificates()); return operation.get(); })); } catch (AwsException failure) { @@ -1446,7 +1561,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc return; } ListenerState expected = listenerState(listener, lb); - if (publishExistingListener(prospectiveListener(expected, null, null, null), region, expected, lb, + if (publishExistingListener(prospectiveListener(expected, null, null, null, null), region, expected, lb, () -> { }, () -> { synchronized (lb) { return loadBalancers.getOrDefault(region, Map.of()).get(lb.getLoadBalancerArn()) == lb @@ -1527,7 +1642,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc List references = new ArrayList<>(); for (Map regionListeners : listeners.values()) { for (Listener listener : regionListeners.values()) { - for (String certificateArn : listener.getCertificates()) { + for (String certificateArn : listener.servedCertificates()) { references.add(new CertificateReference(certificateArn, listener.getLoadBalancerArn())); } } @@ -1537,7 +1652,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc public void certificateReimported(String certificateArn, String region) { for (Listener listener : listeners.getOrDefault(region, Map.of()).values()) { - if (listener.getCertificates().contains(certificateArn)) { + if (listener.servedCertificates().contains(certificateArn)) { try { restoreListener(region, listener.getListenerArn()); } catch (RuntimeException failure) { diff --git a/src/main/java/io/floci/aws/services/elbv2/model/Listener.java b/src/main/java/io/floci/aws/services/elbv2/model/Listener.java index 88a1463ed0..02707feaff 100644 --- a/src/main/java/io/floci/aws/services/elbv2/model/Listener.java +++ b/src/main/java/io/floci/aws/services/elbv2/model/Listener.java @@ -1,6 +1,7 @@ package io.floci.aws.services.elbv2.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.ArrayList; @@ -16,7 +17,8 @@ public class Listener { private String loadBalancerArn; private Integer port; private String protocol; - private List certificates = new ArrayList<>(); + private String defaultCertificate; + private List certificateList = new ArrayList<>(); private String sslPolicy; private List defaultActions = new ArrayList<>(); private List alpnPolicy = new ArrayList<>(); @@ -36,8 +38,44 @@ public class Listener { public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } - public List getCertificates() { return certificates; } - public void setCertificates(List certificates) { this.certificates = certificates; } + public String getDefaultCertificate() { return defaultCertificate; } + public void setDefaultCertificate(String defaultCertificate) { this.defaultCertificate = defaultCertificate; } + + public List getCertificateList() { return certificateList; } + public void setCertificateList(List certificateList) { this.certificateList = certificateList; } + + /** + * The certificates the listener serves, its default first and then its certificate list, a + * certificate both of them name appearing once. The two are kept apart because the reference + * keeps them apart: the default is what CreateListener and ModifyListener set, one certificate + * at a time, the list is what AddListenerCertificates adds to, and DescribeListenerCertificates + * names a default the list holds as well twice, telling the two apart by IsDefault. + */ + public List servedCertificates() { + List served = new ArrayList<>(); + if (defaultCertificate != null) { + served.add(defaultCertificate); + } + for (String certificate : certificateList) { + if (!served.contains(certificate)) { + served.add(certificate); + } + } + return served; + } + + /** + * Reads a listener saved before the default certificate and the certificate list were kept + * apart, when both sat in one list with the default at its head. Nothing writes this member. + */ + @JsonProperty("certificates") + void setSavedCertificates(List certificates) { + if (certificates == null || certificates.isEmpty()) { + return; + } + this.defaultCertificate = certificates.getFirst(); + this.certificateList = new ArrayList<>(certificates.subList(1, certificates.size())); + } public String getSslPolicy() { return sslPolicy; } public void setSslPolicy(String sslPolicy) { this.sslPolicy = sslPolicy; } diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2CertificatePublicationServiceTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2CertificatePublicationServiceTest.java index bcfedaa632..919e229c97 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2CertificatePublicationServiceTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2CertificatePublicationServiceTest.java @@ -103,12 +103,12 @@ class ElbV2CertificatePublicationServiceTest { AwsException failure = assertThrows(AwsException.class, request::run); assertEquals("CertificateNotFound", failure.getErrorCode()); assertEquals(1, service.describeListeners(REGION, lb, List.of()).size()); - assertEquals(List.of(HELD_CERTIFICATE), existing.getCertificates()); + assertEquals(List.of(HELD_CERTIFICATE), existing.servedCertificates()); issued.set(true); assertDoesNotThrow(request::run); assertEquals("create".equals(operation) ? 2 : 1, service.describeListeners(REGION, lb, List.of()).size()); assertEquals("add".equals(operation) ? List.of(HELD_CERTIFICATE, pending) - : "modify".equals(operation) ? List.of(pending) : List.of(HELD_CERTIFICATE), existing.getCertificates()); + : "modify".equals(operation) ? List.of(pending) : List.of(HELD_CERTIFICATE), existing.servedCertificates()); } @ParameterizedTest @@ -143,7 +143,7 @@ class ElbV2CertificatePublicationServiceTest { null, 9090, null, null, null, null)); assertEquals("HTTP", moved.getProtocol()); assertEquals(9090, moved.getPort()); - assertTrue(moved.getCertificates().isEmpty()); + assertTrue(moved.servedCertificates().isEmpty()); assertNull(moved.getSslPolicy()); assertFalse(first.get()); } @@ -236,7 +236,7 @@ class ElbV2CertificatePublicationServiceTest { assertEquals(Integer.valueOf(443), listener.getPort()); assertEquals("HTTPS", listener.getProtocol()); assertEquals("ELBSecurityPolicy-2016-08", listener.getSslPolicy()); - assertEquals(List.of(HELD_CERTIFICATE), listener.getCertificates()); + assertEquals(List.of(HELD_CERTIFICATE), listener.servedCertificates()); verify(dataPlane, never()).removeListener(anyString(), any(), any()); } diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java index 5d80488d41..8184fb6dfe 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerCertificateIntegrationTest.java @@ -14,18 +14,27 @@ import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +import java.util.ArrayList; import java.util.List; import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; 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. + * + *

The default certificate and the certificate list are read apart here too: the member create + * and modify take is one certificate, the list is what {@code AddListenerCertificates} builds, + * {@code DescribeListenerCertificates} tells the two apart by {@code IsDefault}, and the + * certificates in the lists of one load balancer's listeners share a quota of 25. */ @QuarkusTest class ElbV2ListenerCertificateIntegrationTest { @@ -75,13 +84,19 @@ class ElbV2ListenerCertificateIntegrationTest { } private static String requestAcmCertificate() { + return requestAcmCertificate("RSA_2048"); + } + + /** An elliptic-curve key where a test wants many certificates rather than one. */ + private static String requestAcmCertificate(String keyAlgorithm) { 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\"}") + + ".example.com\", \"ValidationMethod\": \"DNS\", \"KeyAlgorithm\": \"" + + keyAlgorithm + "\"}") .when().post("/").then().statusCode(200) .extract().path("CertificateArn"); } @@ -148,12 +163,56 @@ class ElbV2ListenerCertificateIntegrationTest { /** Read through {@code getList} so one certificate and several arrive the same shape. */ private static List listenerCertificates(String listenerArn) { + return describeListenerCertificates(listenerArn, "CertificateArn"); + } + + /** The {@code IsDefault} flags, in the order the certificates above are named. */ + private static List listenerCertificateDefaults(String listenerArn) { + return describeListenerCertificates(listenerArn, "IsDefault"); + } + + private static List describeListenerCertificates(String listenerArn, String member) { 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"); + + ".DescribeListenerCertificatesResult.Certificates.member." + member); + } + + private static ValidatableResponse addCertificates(String listenerArn, List certificateArns) { + RequestSpecification request = given().header("Authorization", ELB_AUTH) + .formParam("Action", "AddListenerCertificates") + .formParam("ListenerArn", listenerArn); + int member = 1; + for (String certificateArn : certificateArns) { + request = request.formParam("Certificates.member." + member + ".CertificateArn", certificateArn); + member++; + } + return request.when().post("/").then(); + } + + private static List listenersOf(String loadBalancerArn) { + return given().header("Authorization", ELB_AUTH) + .formParam("Action", "DescribeListeners") + .formParam("LoadBalancerArn", loadBalancerArn) + .when().post("/").then().statusCode(200) + .extract().xmlPath().getList("DescribeListenersResponse.DescribeListenersResult" + + ".Listeners.member.ListenerArn"); + } + + private static String httpsListenerOn(String loadBalancerArn, int port, String certificateArn) { + return given().header("Authorization", ELB_AUTH) + .formParam("Action", "CreateListener") + .formParam("LoadBalancerArn", loadBalancerArn) + .formParam("Protocol", "HTTPS") + .formParam("Port", String.valueOf(port)) + .formParam("DefaultActions.member.1.Type", "fixed-response") + .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200") + .formParam("Certificates.member.1.CertificateArn", certificateArn) + .when().post("/").then().statusCode(200) + .extract().path("CreateListenerResponse.CreateListenerResult.Listeners.member" + + ".ListenerArn"); } @Test @@ -206,9 +265,7 @@ class ElbV2ListenerCertificateIntegrationTest { .formParam("DefaultActions.member.1.Type", "fixed-response") .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200") .when().post("/"); - List listeners = given().header("Authorization", ELB_AUTH).formParam("Action", "DescribeListeners") - .formParam("LoadBalancerArn", lb).when().post("/").then().statusCode(200) - .extract().xmlPath().getList("DescribeListenersResponse.DescribeListenersResult.Listeners.member.ListenerArn"); + List listeners = listenersOf(lb); assertAll(() -> assertEquals(400, refused.statusCode()), () -> assertEquals("InvalidConfigurationRequest", refused.xmlPath().getString("ErrorResponse.Error.Code")), () -> assertTrue(listeners.isEmpty(), "rejected request must leave no listener")); @@ -440,4 +497,206 @@ class ElbV2ListenerCertificateIntegrationTest { assertEquals(List.of(additional), listenerCertificates(listener)); } + @Test + void createListenerTakesOneDefaultCertificateAndNoMore() { + // "The default certificate for the listener. You must provide exactly one certificate." + String first = uploadCertificate(); + String second = uploadCertificate(); + String lb = loadBalancer(); + + given().header("Authorization", ELB_AUTH) + .formParam("Action", "CreateListener") + .formParam("LoadBalancerArn", lb) + .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", first) + .formParam("Certificates.member.2.CertificateArn", second) + .when().post("/").then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", + equalTo("You must provide exactly one certificate.")); + + assertTrue(listenersOf(lb).isEmpty(), "a refused create must leave no listener"); + } + + @Test + void modifyListenerTakesOneDefaultCertificateAndNoMore() { + String first = uploadCertificate(); + String second = uploadCertificate(); + String listener = listenerServing(first); + + given().header("Authorization", ELB_AUTH) + .formParam("Action", "ModifyListener") + .formParam("ListenerArn", listener) + .formParam("Certificates.member.1.CertificateArn", first) + .formParam("Certificates.member.2.CertificateArn", second) + .when().post("/").then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")); + + assertEquals(List.of(first), listenerCertificates(listener)); + } + + @Test + void addListenerCertificatesTakesMoreThanOneCertificateInACall() { + // The member reads as one certificate per call, while the Application Load Balancers + // guide adds three in a call of its own, and the guide's example is the one to follow. + String first = uploadCertificate(); + String second = uploadCertificate(); + String third = uploadCertificate(); + String listener = listenerServing(first); + + addCertificates(listener, List.of(second, third)).statusCode(200); + assertEquals(List.of(first, second, third), listenerCertificates(listener)); + + // "Information about the certificates in the certificate list", which the default is not + // in and which is not the call's own member: adding a certificate the list already holds + // answers with the whole list rather than with the one certificate named. + List answered = addCertificates(listener, List.of(third)).statusCode(200) + .extract().xmlPath().getList("AddListenerCertificatesResponse" + + ".AddListenerCertificatesResult.Certificates.member.CertificateArn"); + + assertEquals(List.of(second, third), answered); + } + + @Test + void describeListenerCertificatesTellsTheDefaultApartFromTheList() { + String first = uploadCertificate(); + String second = uploadCertificate(); + String listener = listenerServing(first); + addCertificates(listener, List.of(second)).statusCode(200); + + assertEquals(List.of(first, second), listenerCertificates(listener)); + assertEquals(List.of("true", "false"), listenerCertificateDefaults(listener)); + } + + @Test + void aDefaultCertificateTheListHoldsAsWellIsNamedTwice() { + // "If the default certificate is also in the certificate list, it appears twice in the + // results (once with IsDefault set to true and once with IsDefault set to false)." + String first = uploadCertificate(); + String listener = listenerServing(first); + addCertificates(listener, List.of(first)).statusCode(200); + + assertEquals(List.of(first, first), listenerCertificates(listener)); + assertEquals(List.of("true", "false"), listenerCertificateDefaults(listener)); + } + + @Test + void aListenerCarriesItsDefaultCertificateAloneAndNoIsDefault() { + // The listener's own member is "the default certificate for the listener", and IsDefault + // "is not included in the output when describing a listener". + String first = uploadCertificate(); + String second = uploadCertificate(); + String listener = listenerServing(first); + addCertificates(listener, List.of(second)).statusCode(200); + + describeListener(listener) + .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member" + + ".Certificates.member.CertificateArn", equalTo(first)) + .body(not(containsString("IsDefault"))); + } + + @Test + void replacingTheDefaultLeavesTheCertificateListStanding() { + // "Adding the default certificate to the certificate list ensures that this certificate is + // used with the SNI protocol even if it is replaced as the default certificate." + String first = uploadCertificate(); + String sni = uploadCertificate(); + String replacement = uploadCertificate(); + String listener = listenerServing(first); + addCertificates(listener, List.of(sni)).statusCode(200); + + given().header("Authorization", ELB_AUTH) + .formParam("Action", "ModifyListener") + .formParam("ListenerArn", listener) + .formParam("Certificates.member.1.CertificateArn", replacement) + .when().post("/").then().statusCode(200); + + assertEquals(List.of(replacement, sni), listenerCertificates(listener)); + assertEquals(List.of("true", "false"), listenerCertificateDefaults(listener)); + } + + @Test + void theCertificateQuotaIsSharedByTheListenersAndLeavesTheDefaultsOut() { + // "Certificates per Application Load Balancer (excluding default certificates): 25", so + // the listeners of one load balancer share it and a default is not counted, its own + // certificate list holding it or not. + String loadBalancer = loadBalancer(); + String listener = httpsListenerOn(loadBalancer, 443, requestAcmCertificate("EC_prime256v1")); + List filling = new ArrayList<>(); + for (int i = 0; i < ElbV2Service.CERTIFICATES_PER_LOAD_BALANCER; i++) { + filling.add(requestAcmCertificate("EC_prime256v1")); + } + addCertificates(listener, filling).statusCode(200); + String theDefault = listenerCertificates(listener).getFirst(); + + // The default is excluded from the count, so the list can still take it at the ceiling. + addCertificates(listener, List.of(theDefault)).statusCode(200); + List flags = listenerCertificateDefaults(listener); + assertEquals(ElbV2Service.CERTIFICATES_PER_LOAD_BALANCER + 2, flags.size()); + assertEquals("true", flags.getFirst()); + assertEquals("false", flags.getLast()); + + String overTheQuota = requestAcmCertificate("EC_prime256v1"); + addCertificates(listener, List.of(overTheQuota)).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("TooManyCertificates")) + .body("ErrorResponse.Error.Message", equalTo("You've reached the limit on the " + + "number of certificates per load balancer.")); + assertFalse(listenerCertificates(listener).contains(overTheQuota), + "a refused add must leave the certificate list as it was"); + + // The second listener shares the load balancer's ceiling rather than carrying its own. + String second = httpsListenerOn(loadBalancer, 8443, requestAcmCertificate("EC_prime256v1")); + addCertificates(second, List.of(overTheQuota)).statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("TooManyCertificates")); + assertEquals(1, listenerCertificates(second).size()); + } + + @Test + void replacingADefaultTheCertificateListHoldsIsHeldToTheCeilingToo() { + // A default is not counted while it is the default, so replacing one the certificate list + // holds as well starts counting it, which is why ModifyListener models TooManyCertificates + // as the add does. + String loadBalancer = loadBalancer(); + String theDefault = requestAcmCertificate("EC_prime256v1"); + String listener = httpsListenerOn(loadBalancer, 443, theDefault); + List filling = new ArrayList<>(); + for (int i = 0; i < ElbV2Service.CERTIFICATES_PER_LOAD_BALANCER; i++) { + filling.add(requestAcmCertificate("EC_prime256v1")); + } + addCertificates(listener, filling).statusCode(200); + addCertificates(listener, List.of(theDefault)).statusCode(200); + + given().header("Authorization", ELB_AUTH) + .formParam("Action", "ModifyListener") + .formParam("ListenerArn", listener) + .formParam("Certificates.member.1.CertificateArn", requestAcmCertificate("EC_prime256v1")) + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("TooManyCertificates")); + assertEquals(theDefault, listenerCertificates(listener).getFirst(), + "a refused modify leaves the default as it was"); + } + + @Test + void removingADefaultTheListHoldsAsWellIsRefusedToo() { + // "You can't remove the default certificate for a listener" names no exception for a + // default the certificate list holds as well, so Floci refuses that too. + String first = uploadCertificate(); + String listener = listenerServing(first); + addCertificates(listener, List.of(first)).statusCode(200); + + given().header("Authorization", ELB_AUTH) + .formParam("Action", "RemoveListenerCertificates") + .formParam("ListenerArn", listener) + .formParam("Certificates.member.1.CertificateArn", first) + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("OperationNotPermitted")); + + assertEquals(List.of(first, first), listenerCertificates(listener)); + } + } diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerCertificateModelTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerCertificateModelTest.java new file mode 100644 index 0000000000..cd9cacd670 --- /dev/null +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerCertificateModelTest.java @@ -0,0 +1,56 @@ +package io.floci.aws.services.elbv2; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.elbv2.model.Listener; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The listener's two certificate members, as what is stored reads them. Listeners are persisted + * through a plain {@link ObjectMapper}, which is what these round trips use, and a listener saved + * before the default and the list were kept apart has to come back serving the same certificates. + */ +class ElbV2ListenerCertificateModelTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void aListenerSavedWithOneCertificateListReadsItsHeadAsTheDefault() throws Exception { + Listener restored = MAPPER.readValue("{\"listenerArn\":\"arn:listener\"," + + "\"certificates\":[\"arn:default\",\"arn:sni\"]}", Listener.class); + + assertEquals("arn:default", restored.getDefaultCertificate()); + assertEquals(List.of("arn:sni"), restored.getCertificateList()); + assertEquals(List.of("arn:default", "arn:sni"), restored.servedCertificates()); + } + + @Test + void aListenerSavedWithNoCertificatesCarriesNoDefault() throws Exception { + Listener restored = MAPPER.readValue("{\"certificates\":[]}", Listener.class); + + assertNull(restored.getDefaultCertificate()); + assertTrue(restored.servedCertificates().isEmpty()); + } + + @Test + void aListenerIsSavedWithItsDefaultAndItsListApart() throws Exception { + Listener listener = new Listener(); + listener.setDefaultCertificate("arn:default"); + listener.setCertificateList(List.of("arn:default", "arn:sni")); + + String saved = MAPPER.writeValueAsString(listener); + Listener restored = MAPPER.readValue(saved, Listener.class); + + assertFalse(saved.contains("\"certificates\""), "the one flat list is not written any more"); + assertEquals("arn:default", restored.getDefaultCertificate()); + assertEquals(List.of("arn:default", "arn:sni"), restored.getCertificateList()); + // A default the certificate list holds as well is served once. + assertEquals(List.of("arn:default", "arn:sni"), restored.servedCertificates()); + } +} diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerOwnershipTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerOwnershipTest.java index 3f4322d5d2..7b3e309fb9 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerOwnershipTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ListenerOwnershipTest.java @@ -80,7 +80,7 @@ class ElbV2ListenerOwnershipTest { CertificateMaterial broken = new CertificateMaterial(CERTIFICATE, valid.certificateBody(), other.privateKeyPem(), null); when(fixture.plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(broken); if (emptyDefault) { - listener.setCertificates(List.of()); + listener.setDefaultCertificate(null); } AtomicInteger publications = new AtomicInteger(); try { @@ -89,7 +89,7 @@ class ElbV2ListenerOwnershipTest { assertEquals(0, publications.get()); assertTrue(registry.isEmpty()); assertEquals(0, fixture.creations(8443)); - listener.setCertificates(List.of(CERTIFICATE)); + listener.setDefaultCertificate(CERTIFICATE); when(fixture.plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(valid); assertTrue(fixture.plane.publishListener(listener, REGION, 8443, () -> { publications.incrementAndGet(); return true; }, () -> List.of(rule("retry")), admitted -> admitted.get())); @@ -718,7 +718,7 @@ class ElbV2ListenerOwnershipTest { listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/shared/1"); listener.setPort(port); listener.setProtocol(secure ? "HTTPS" : "HTTP"); - listener.setCertificates(secure ? List.of(CERTIFICATE) : List.of()); + listener.setDefaultCertificate(secure ? CERTIFICATE : null); return listener; } diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ReservedPortTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ReservedPortTest.java index c9a25fca3c..1dcb40d01a 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2ReservedPortTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ReservedPortTest.java @@ -186,7 +186,7 @@ class ElbV2ReservedPortTest { listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/lb/1"); listener.setPort(8443); listener.setProtocol("HTTPS"); - listener.setCertificates(List.of(certificateArn)); + listener.setDefaultCertificate(certificateArn); LoadBalancer loadBalancer = new LoadBalancer(); loadBalancer.setDnsName("tls.example.test"); when(dataPlane.elbV2Service.getLoadBalancer(region, listener.getLoadBalancerArn())).thenReturn(loadBalancer); @@ -252,7 +252,7 @@ class ElbV2ReservedPortTest { listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1"); listener.setPort(8443); listener.setProtocol("HTTPS"); - listener.setCertificates(List.of(certificateArn)); + listener.setDefaultCertificate(certificateArn); LoadBalancer loadBalancer = new LoadBalancer(); loadBalancer.setDnsName(name + ".example.test"); when(dataPlane.elbV2Service.getLoadBalancer("us-west-2", listener.getLoadBalancerArn())) diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java index fe91e2b4cf..096cb1c278 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java @@ -48,6 +48,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import java.util.function.Function; import java.util.function.Supplier; import static io.floci.aws.services.elbv2.ElbV2PublicationTestSupport.allowPublications; @@ -61,6 +63,7 @@ import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -349,7 +352,7 @@ class ElbV2ServiceTest { assertEquals(8080, listener.getPort()); assertEquals("HTTP", listener.getProtocol()); assertNull(listener.getSslPolicy()); - assertTrue(listener.getCertificates().isEmpty()); + assertTrue(listener.servedCertificates().isEmpty()); verifyNoInteractions(dataPlane); } @@ -380,7 +383,7 @@ class ElbV2ServiceTest { assertTrue(service.describeRules(REGION, null, List.of()).isEmpty()); Listener retry = service.createListener(REGION, lb, "HTTPS", 9443, null, List.of(HELD_CERTIFICATE), List.of(), List.of(), Map.of()); - assertEquals(List.of(HELD_CERTIFICATE), retry.getCertificates()); + assertEquals(List.of(HELD_CERTIFICATE), retry.servedCertificates()); } @ParameterizedTest @@ -394,11 +397,11 @@ class ElbV2ServiceTest { assertEquals("InvalidConfigurationRequest", refusal.getErrorCode()); assertEquals("HTTP", listener.getProtocol()); assertEquals(9080, listener.getPort()); - assertEquals(List.of(), listener.getCertificates()); + assertEquals(List.of(), listener.servedCertificates()); service.modifyListener(REGION, listener.getListenerArn(), "HTTPS", 9443, "ELBSecurityPolicy-2016-08", List.of(HELD_CERTIFICATE), null, null); assertEquals("HTTPS", listener.getProtocol()); - assertEquals(List.of(HELD_CERTIFICATE), listener.getCertificates()); + assertEquals(List.of(HELD_CERTIFICATE), listener.servedCertificates()); } @ParameterizedTest @@ -410,20 +413,21 @@ class ElbV2ServiceTest { String first = "arn:aws:iam::000000000000:server-certificate/first"; String additional = "arn:aws:iam::000000000000:server-certificate/additional"; String listenerArn = service.createListener(REGION, lbArn, protocol, 9443, null, - List.of(first, additional), List.of(), List.of(), Map.of()).getListenerArn(); + List.of(first), List.of(), List.of(), Map.of()).getListenerArn(); + service.addListenerCertificates(REGION, listenerArn, List.of(additional)); clearInvocations(dataPlane); AwsException rejected = assertThrows(AwsException.class, () -> service.removeListenerCertificates(REGION, listenerArn, List.of(additional, first))); assertEquals("OperationNotPermitted", rejected.getErrorCode()); - assertEquals(List.of(first, additional), service.describeListenerCertificates(REGION, listenerArn)); + assertEquals(List.of(first, additional), describedCertificates(listenerArn)); verifyNoInteractions(dataPlane); service.removeListenerCertificates(REGION, listenerArn, List.of(additional)); - assertEquals(List.of(first), service.describeListenerCertificates(REGION, listenerArn)); + assertEquals(List.of(first), describedCertificates(listenerArn)); assertThrows(AwsException.class, () -> service.removeListenerCertificates(REGION, listenerArn, List.of(first))); - assertEquals(List.of(first), service.describeListenerCertificates(REGION, listenerArn)); + assertEquals(List.of(first), describedCertificates(listenerArn)); } @ParameterizedTest @@ -453,7 +457,7 @@ class ElbV2ServiceTest { assertEquals("InvalidConfigurationRequest", rejected.getErrorCode()); assertEquals("HTTP", listener.getProtocol()); assertEquals(8080, listener.getPort()); - assertTrue(listener.getCertificates().isEmpty()); + assertTrue(listener.servedCertificates().isEmpty()); verifyNoInteractions(dataPlane); } @@ -464,7 +468,8 @@ class ElbV2ServiceTest { String first = "arn:aws:iam::000000000000:server-certificate/first"; String additional = "arn:aws:iam::000000000000:server-certificate/additional"; String listener = service.createListener(REGION, lbArn, "HTTPS", 9443, null, - List.of(first, additional), List.of(), List.of(), Map.of()).getListenerArn(); + List.of(first), List.of(), List.of(), Map.of()).getListenerArn(); + service.addListenerCertificates(REGION, listener, List.of(additional)); CountDownLatch checkedOriginalDefault = new CountDownLatch(1); CountDownLatch releaseRemoval = new CountDownLatch(1); List requested = new ArrayList<>(List.of(additional)) { @@ -486,16 +491,16 @@ class ElbV2ServiceTest { Future removal = worker.submit(() -> service.removeListenerCertificates(REGION, listener, requested)); assertTrue(checkedOriginalDefault.await(5, TimeUnit.SECONDS), "removal did not check the original default"); service.modifyListener(REGION, listener, null, null, null, List.of(additional), null, null); - assertEquals(List.of(additional), service.describeListenerCertificates(REGION, listener)); + assertEquals(List.of(additional, additional), describedCertificates(listener)); releaseRemoval.countDown(); ExecutionException refused = assertThrows(ExecutionException.class, () -> removal.get(5, TimeUnit.SECONDS)); assertEquals("OperationNotPermitted", ((AwsException) refused.getCause()).getErrorCode()); - assertEquals(List.of(additional), service.describeListenerCertificates(REGION, listener)); + assertEquals(List.of(additional, additional), describedCertificates(listener)); AwsException rejected = assertThrows(AwsException.class, () -> service.removeListenerCertificates(REGION, listener, List.of(additional))); assertEquals("OperationNotPermitted", rejected.getErrorCode()); - assertEquals(List.of(additional), service.describeListenerCertificates(REGION, listener)); + assertEquals(List.of(additional, additional), describedCertificates(listener)); } finally { releaseRemoval.countDown(); worker.shutdownNow(); @@ -503,6 +508,44 @@ class ElbV2ServiceTest { } } + @Test + void parallelAddsCannotPassTheCeilingTheListenersShare() throws Exception { + String lbArn = service.createLoadBalancer(REGION, "shared-ceiling-lb", "internal", "application", "ipv4", + ALB_SUBNETS, List.of("sg-a"), Map.of()).getLoadBalancerArn(); + String first = service.createListener(REGION, lbArn, "HTTPS", 9443, null, + List.of(serverCertificate("first-default")), List.of(), List.of(), Map.of()).getListenerArn(); + String second = service.createListener(REGION, lbArn, "HTTPS", 8443, null, + List.of(serverCertificate("second-default")), List.of(), List.of(), Map.of()).getListenerArn(); + List filling = new ArrayList<>(); + for (int i = 0; i < ElbV2Service.CERTIFICATES_PER_LOAD_BALANCER - 1; i++) { + filling.add(serverCertificate("filling-" + i)); + } + service.addListenerCertificates(REGION, first, filling); + CountDownLatch countedTheCeiling = new CountDownLatch(1); + CountDownLatch releaseTheWrite = new CountDownLatch(1); + pauseWriteAfterCountingTheCeiling(first, countedTheCeiling, releaseTheWrite); + + ExecutorService worker = Executors.newSingleThreadExecutor(); + try { + Future paused = worker.submit(() -> + service.addListenerCertificates(REGION, first, List.of(serverCertificate("first-last")))); + assertTrue(countedTheCeiling.await(5, TimeUnit.SECONDS), "the first add did not reach its write"); + service.addListenerCertificates(REGION, second, List.of(serverCertificate("second-last"))); + releaseTheWrite.countDown(); + + ExecutionException refused = assertThrows(ExecutionException.class, + () -> paused.get(5, TimeUnit.SECONDS)); + assertEquals("TooManyCertificates", ((AwsException) refused.getCause()).getErrorCode()); + assertEquals(ElbV2Service.CERTIFICATES_PER_LOAD_BALANCER, countedCertificates(first, second)); + assertFalse(describedCertificates(first).contains(serverCertificate("first-last")), + "a refused add leaves the certificate list as it was"); + } finally { + releaseTheWrite.countDown(); + worker.shutdownNow(); + assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS)); + } + } + @Test void certificateMetadataOnAnHttpListenerKeepsItsExistingRemovalBehavior() { String lbArn = service.createLoadBalancer(REGION, "http-cert-lb", "internal", "application", "ipv4", @@ -511,7 +554,7 @@ class ElbV2ServiceTest { String listenerArn = service.createListener(REGION, lbArn, "HTTP", 8080, null, List.of(certificate), List.of(), List.of(), Map.of()).getListenerArn(); service.removeListenerCertificates(REGION, listenerArn, List.of(certificate)); - assertEquals(List.of(), service.describeListenerCertificates(REGION, listenerArn)); + assertEquals(List.of(), describedCertificates(listenerArn)); } @Test @@ -532,7 +575,7 @@ class ElbV2ServiceTest { verify(dataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any()); assertEquals("HTTPS", listenerCaptor.getValue().getProtocol()); assertEquals(List.of("arn:aws:acm:us-west-2:000000000000:certificate/first"), - listenerCaptor.getValue().getCertificates()); + listenerCaptor.getValue().servedCertificates()); verify(dataPlane, never()).recompileRules(anyString(), any()); } @@ -548,12 +591,12 @@ class ElbV2ServiceTest { clearInvocations(dataPlane); service.modifyListener(REGION, listenerArn, null, null, null, List.of(replacement), null, null); - assertEquals(List.of(replacement), service.describeListenerCertificates(REGION, listenerArn)); + assertEquals(List.of(replacement), describedCertificates(listenerArn)); verify(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any()); service.modifyListener(REGION, listenerArn, null, null, null, List.of(replacement), null, null); verify(dataPlane, times(2)).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any()); - assertEquals(List.of(replacement), service.describeListenerCertificates(REGION, listenerArn)); + assertEquals(List.of(replacement), describedCertificates(listenerArn)); verify(dataPlane, never()).recompileRules(anyString(), any()); } @@ -575,7 +618,7 @@ class ElbV2ServiceTest { verify(dataPlane, times(2)) .publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any()); assertEquals(List.of(firstCertificate), - service.describeListenerCertificates(REGION, listenerArn)); + describedCertificates(listenerArn)); } @Test @@ -586,15 +629,16 @@ class ElbV2ServiceTest { String first = "arn:aws:acm:us-west-2:000000000000:certificate/default"; String additional = "arn:aws:acm:us-west-2:000000000000:certificate/additional"; String listener = service.createListener(REGION, lbArn, "HTTPS", 9443, null, - List.of(first, additional), List.of(), List.of(), Map.of()).getListenerArn(); + List.of(first), List.of(), List.of(), Map.of()).getListenerArn(); + service.addListenerCertificates(REGION, listener, List.of(additional)); clearInvocations(dataPlane); AwsException rejected = assertThrows(AwsException.class, () -> service.removeListenerCertificates(REGION, listener, List.of(first))); assertEquals("OperationNotPermitted", rejected.getErrorCode()); - assertEquals(List.of(first, additional), service.describeListenerCertificates(REGION, listener)); + assertEquals(List.of(first, additional), describedCertificates(listener)); verifyNoInteractions(dataPlane); service.removeListenerCertificates(REGION, listener, List.of(additional)); - assertEquals(List.of(first), service.describeListenerCertificates(REGION, listener)); + assertEquals(List.of(first), describedCertificates(listener)); verify(dataPlane).publishListener(any(Listener.class), eq(REGION), any(), any(), any(), any()); } @@ -621,7 +665,7 @@ class ElbV2ServiceTest { verify(reloadedDataPlane).publishListener(listenerCaptor.capture(), eq(REGION), any(), any(), any(), any()); assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn()); assertEquals(protocol, listenerCaptor.getValue().getProtocol()); - assertEquals(List.of(certificateArn), listenerCaptor.getValue().getCertificates()); + assertEquals(List.of(certificateArn), listenerCaptor.getValue().servedCertificates()); Listener described = reloaded.describeListeners(REGION, lbArn, List.of(listenerArn)).getFirst(); assertEquals(sslPolicy == null ? "ELBSecurityPolicy-2016-08" : sslPolicy, described.getSslPolicy()); @@ -645,7 +689,7 @@ class ElbV2ServiceTest { Listener plainListener = plainReload.describeListeners(REGION, lb, List.of(arn)).getFirst(); assertEquals(plain, plainListener.getProtocol()); assertNull(plainListener.getSslPolicy()); - assertTrue(plainListener.getCertificates().isEmpty()); + assertTrue(plainListener.servedCertificates().isEmpty()); plainReload.modifyListener(REGION, arn, encrypted, null, "ELBSecurityPolicy-2016-08", List.of(OTHER_CERTIFICATE), null, null); @@ -654,7 +698,7 @@ class ElbV2ServiceTest { Listener encryptedListener = encryptedReload.describeListeners(REGION, lb, List.of(arn)).getFirst(); assertEquals(encrypted, encryptedListener.getProtocol()); assertEquals("ELBSecurityPolicy-2016-08", encryptedListener.getSslPolicy()); - assertEquals(List.of(OTHER_CERTIFICATE), encryptedListener.getCertificates()); + assertEquals(List.of(OTHER_CERTIFICATE), encryptedListener.servedCertificates()); } @Test @@ -1359,6 +1403,56 @@ class ElbV2ServiceTest { List.of(forwardAction(targetGroupArn)), List.of(), Map.of()).getListenerArn(); } + /** The ARNs the describe names, in order; which of them is the default is pinned elsewhere. */ + private static String serverCertificate(String name) { + return "arn:aws:iam::000000000000:server-certificate/" + name; + } + + /** What the load balancer's ceiling counts: every certificate but each listener's default. */ + private int countedCertificates(String... listenerArns) { + int counted = 0; + for (String listenerArn : listenerArns) { + for (ElbV2Service.ListenerCertificate certificate + : service.describeListenerCertificates(REGION, listenerArn)) { + if (!certificate.isDefault()) { + counted++; + } + } + } + return counted; + } + + /** + * Holds one listener's certificate write between the ceiling it counts and the write itself, + * which is where a sibling listener's write lands in the window this closes. + */ + private void pauseWriteAfterCountingTheCeiling(String listenerArn, CountDownLatch reached, + CountDownLatch release) { + doAnswer(call -> { + Function, Boolean> admission = call.getArgument(5); + BooleanSupplier publication = call.getArgument(3); + boolean pause = listenerArn.equals(call.getArgument(0, Listener.class).getListenerArn()) + && reached.getCount() > 0; + return admission.apply(() -> { + if (pause) { + reached.countDown(); + try { + assertTrue(release.await(5, TimeUnit.SECONDS), "the paused write was not released"); + } catch (InterruptedException interruption) { + Thread.currentThread().interrupt(); + throw new AssertionError("the paused write was interrupted", interruption); + } + } + return publication.getAsBoolean(); + }); + }).when(dataPlane).publishListener(any(Listener.class), anyString(), any(), any(), any(), any()); + } + + private List describedCertificates(String listenerArn) { + return service.describeListenerCertificates(REGION, listenerArn).stream() + .map(ElbV2Service.ListenerCertificate::certificateArn).toList(); + } + private static Action forwardAction(String targetGroupArn) { Action action = new Action(); action.setType("forward"); diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2TlsCohortTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2TlsCohortTest.java index a11261a16a..b9ee6c8cc7 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2TlsCohortTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2TlsCohortTest.java @@ -203,7 +203,7 @@ class ElbV2TlsCohortTest { listener.setLoadBalancerArn("arn:aws:elasticloadbalancing:us-west-2:000000000000:loadbalancer/app/" + name + "/1"); listener.setPort(8443); listener.setProtocol("HTTPS"); - listener.setCertificates(List.of(certificateArn)); + listener.setDefaultCertificate(certificateArn); return listener; }