fix(elbv2): hold a listener's default certificate apart from its list (#8240)

A listener kept one certificate list with its default at the head, which left
four readings of the reference unanswered. DescribeListenerCertificates names
"the default certificate and the certificate list", telling them apart by
IsDefault and naming a default the list holds as well twice, "once with
IsDefault set to true and once with IsDefault set to false", where Floci
answered one flat list and no IsDefault at all. A listener's own Certificates
member is "the default certificate for the listener", and IsDefault "is not
included in the output when describing a listener", where Floci named every
certificate the listener held there. ModifyListener replaces the default alone,
the Application Load Balancers guide saying of a default added to the
certificate list that it "is used with the SNI protocol even if it is replaced
as the default certificate", where Floci dropped the list with the replacement.
And a listener made through the API starts with an empty certificate list,
which the same guide says of every listener not made in the console.

The default and the list are two members of the listener now, with the served
set, the default first and the list behind it, derived for the data plane and
for the certificate references. A listener saved before this reads the head of
its one list as the default and the rest as its certificate list.

The member create and modify take is held to one certificate, the reference
saying of it on both operations "You must provide exactly one certificate." No
published sentence gives the code a longer list is answered with, so it is the
ValidationError this service answers a request shape with, which is Floci's
reading rather than a sentence of AWS's.

AddListenerCertificates is left taking a list. Its member reads "You can
specify one certificate per call", while the Application Load Balancers guide
adds three certificates in one call of its own, so the sentence and the example
disagree and the example is the behaviour to keep. The operation answers with
the certificate list the add leaves behind now, which is what its output member
describes, rather than with the certificates the call named.

TooManyCertificates is answered for the first time. The published quota is
"Certificates per Application Load Balancer (excluding default certificates):
25", the number DescribeAccountLimits has been reporting all along, so the
listeners of one load balancer share that ceiling, their default certificates
are left out of the count, and the add that would pass it is refused. The
ceiling is the load balancer's rather than the listener's, so it is counted
where the write is made, under the lock a listener's certificate write takes:
two adds on sibling listeners would otherwise each count the other's list as it
stood before the other wrote and pass it together. Create reaches no quota, a
default certificate not being counted, and modify reaches it through its
default alone, a default the certificate list holds as well not being counted
while it is the default, so replacing it starts counting that entry. The number
in hand is the Application Load Balancer one, and 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.

Removing a default certificate the certificate list holds as well stays
refused: "You can't remove the default certificate for a listener" names no
exception for that case.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-13 22:40:59 -04:00
1 parent 58930c9278
commit ea4427ca58
12 files changed
+666 -84

No files matched your search

@@ -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());
}
@@ -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.
*
* <p>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<String> listenerCertificates(String listenerArn) {
return describeListenerCertificates(listenerArn, "CertificateArn");
}
/** The {@code IsDefault} flags, in the order the certificates above are named. */
private static List<String> listenerCertificateDefaults(String listenerArn) {
return describeListenerCertificates(listenerArn, "IsDefault");
}
private static List<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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));
}
}
@@ -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());
}
}
@@ -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;
}
@@ -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()))
@@ -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<String> 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<String> 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<Supplier<Boolean>, 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<String> 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");
@@ -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;
}