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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

@@ -0,0 +1,221 @@
package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Function;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A listener and the certificate it names cannot end up disagreeing about whether the certificate
* exists.
*
* <p>The same hazard the Classic suite drives: {@code DeleteServerCertificate} checks the
* reference providers under IAM's own lock, while a listener write checks the certificate and then
* records it. Both writes that record one are driven here, over the wire, because the certificate
* arrives as a request parameter and the check lives behind the handler.
*/
@QuarkusTest
class ElbV2CertificateDeleteRaceTest {
private static final String ELB_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260427/us-east-1/elasticloadbalancing/aws4_request";
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
private static final int TRIALS = 30;
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private static String uploadCertificate(String name) {
CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
"elbv2.race.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
return given().header("Authorization", IAM_AUTH)
.formParam("Action", "UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then().statusCode(200)
.extract().path("UploadServerCertificateResponse.UploadServerCertificateResult"
+ ".ServerCertificateMetadata.Arn");
}
private static String loadBalancer(String name) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateLoadBalancer")
.formParam("Name", name)
.formParam("Type", "application")
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
.formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b"))
.when().post("/").then().statusCode(200)
.extract().path("CreateLoadBalancerResponse.CreateLoadBalancerResult"
+ ".LoadBalancers.member.LoadBalancerArn");
}
/** A listener carrying no certificate yet, so the race is only about the one being added. */
private static String listener(String lbArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", lbArn)
.formParam("Protocol", "HTTPS")
.formParam("Port", "443")
.formParam("DefaultActions.member.1.Type", "fixed-response")
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")
.when().post("/").then().statusCode(200)
.extract().path("CreateListenerResponse.CreateListenerResult.Listeners.member"
+ ".ListenerArn");
}
private static int createListenerWith(String lbArn, String certificateArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", lbArn)
.formParam("Protocol", "HTTPS")
.formParam("Port", "443")
.formParam("DefaultActions.member.1.Type", "fixed-response")
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")
.formParam("Certificates.member.1.CertificateArn", certificateArn)
.when().post("/").then().extract().statusCode();
}
private static int addListenerCertificate(String listenerArn, String certificateArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "AddListenerCertificates")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", certificateArn)
.when().post("/").then().extract().statusCode();
}
private static int deleteCertificate(String name) {
return given().header("Authorization", IAM_AUTH)
.formParam("Action", "DeleteServerCertificate")
.formParam("ServerCertificateName", name)
.when().post("/").then().extract().statusCode();
}
private static boolean certificateExists(String name) {
return given().header("Authorization", IAM_AUTH)
.formParam("Action", "GetServerCertificate")
.formParam("ServerCertificateName", name)
.when().post("/").then().extract().statusCode() == 200;
}
private static void deleteLoadBalancer(String lbArn) {
given().header("Authorization", ELB_AUTH)
.formParam("Action", "DeleteLoadBalancer")
.formParam("LoadBalancerArn", lbArn)
.when().post("/").then().extract().statusCode();
}
@Test
void addingACertificateNeverLeavesAListenerHoldingADeletedOne() throws Exception {
race("the listener it was added to", ElbV2CertificateDeleteRaceTest::listener,
ElbV2CertificateDeleteRaceTest::addListenerCertificate);
}
@Test
void creatingAListenerNeverPublishesOneHoldingADeletedCertificate() throws Exception {
// The certificate is checked before the listener is built, and the listener is not in the
// map until it is published, so without the guard the delete sees nothing referring to
// the certificate and takes it while the listener is on its way in.
race("the listener it was created with", lbArn -> lbArn,
ElbV2CertificateDeleteRaceTest::createListenerWith);
}
/**
* Races one listener write against {@code DeleteServerCertificate} {@value #TRIALS} times.
*
* @param what how to describe the listener in a failure, since the write decides whether one
* already exists.
* @param prepare whatever the write needs in place first, built from the trial's load balancer
* and outside the timed section: the listener for a write that adds to one, the load
* balancer itself for the write that creates it.
* @param write the listener write under test, given what {@code prepare} returned and the
* certificate ARN, answering with its status code.
*/
private void race(String what, Function<String, String> prepare,
BiFunction<String, String, Integer> write) throws Exception {
List<String> dangling = new ArrayList<>();
List<String> unresolved = new ArrayList<>();
for (int trial = 0; trial < TRIALS; trial++) {
String name = "elbv2-race-cert-" + trial + "-" + suffix();
String arn = uploadCertificate(name);
String lbArn = loadBalancer("elbv2-race-" + trial + "-" + suffix());
String target = prepare.apply(lbArn);
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger writeStatus = new AtomicInteger();
AtomicInteger deleteStatus = new AtomicInteger();
try {
List<Future<?>> racers = List.of(pool.submit(() -> {
start.await();
writeStatus.set(write.apply(target, arn));
return null;
}), pool.submit(() -> {
start.await();
deleteStatus.set(deleteCertificate(name));
return null;
}));
start.countDown();
pool.shutdown();
assertTrue(pool.awaitTermination(60, TimeUnit.SECONDS), "trial did not finish");
reportAnythingUnexpected(racers);
int wrote = writeStatus.get();
int delete = deleteStatus.get();
if (wrote == 200 && delete == 200 && !certificateExists(name)) {
dangling.add("trial " + trial + ": " + what
+ " holds deleted certificate " + name);
}
// Exactly one order wins and the loser says why: the certificate is recorded and
// the delete answers DeleteConflict, or the certificate goes and the write is
// refused with CertificateNotFound. Two failures would leave the race untested
// while the trial still looked clean, so they are collected rather than ignored.
if (!(wrote == 200 && delete == 409) && !(wrote == 400 && delete == 200)) {
unresolved.add("trial " + trial + ": write=" + wrote + " delete=" + delete);
}
} finally {
pool.shutdownNow();
deleteLoadBalancer(lbArn);
if (certificateExists(name)) {
deleteCertificate(name);
}
}
}
assertTrue(dangling.isEmpty(), "a listener was left holding a deleted certificate in "
+ dangling.size() + " of " + TRIALS + " trials: " + dangling);
assertTrue(unresolved.isEmpty(),
"every trial must resolve as one order winning and the other being told why, "
+ "these did not: " + unresolved);
}
/**
* Surfaces anything a racing task threw. The throwable otherwise stays in the task's
* {@link Future}, the status stays at its initial zero, and the trial reads as the other
* order having won without the race ever having run.
*/
private static void reportAnythingUnexpected(List<Future<?>> racers) throws Exception {
for (Future<?> racer : racers) {
racer.get();
}
}
}
@@ -0,0 +1,348 @@
package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A listener's certificates are resolved against IAM and ACM on the way in.
* {@code CertificateNotFound} is modeled on {@code CreateListener}, {@code ModifyListener} and
* {@code AddListenerCertificates} alone, and the reference gives it one sentence and a 400.
*/
@QuarkusTest
class ElbV2ListenerCertificateIntegrationTest {
private static final String ELB_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260427/us-east-1/elasticloadbalancing/aws4_request";
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static final String ACM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/acm/aws4_request";
private static final String MISSING_IAM_CERTIFICATE =
"arn:aws:iam::000000000000:server-certificate/never-uploaded";
private static final String MISSING_ACM_CERTIFICATE = "arn:aws:acm:us-east-1:000000000000"
+ ":certificate/00000000-0000-0000-0000-000000000000";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
/**
* Every certificate and load balancer this class makes is taken back out again. The account's
* server certificate quota is 20 and the Quarkus instance is shared, so a certificate left
* behind here fails an unrelated class's upload rather than anything in this one.
*/
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private String uploadCertificate() {
CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
"elbv2.certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
String name = "elbv2-cert-" + suffix();
// Registered before the load balancer's undo so it runs after it: a certificate a
// listener still holds answers DeleteConflict.
cleanup.register(() -> given().header("Authorization", IAM_AUTH)
.formParam("Action", "DeleteServerCertificate")
.formParam("ServerCertificateName", name)
.when().post("/"));
return given().header("Authorization", IAM_AUTH)
.formParam("Action", "UploadServerCertificate")
.formParam("ServerCertificateName", name)
.formParam("CertificateBody", pair.certificatePem())
.formParam("PrivateKey", pair.privateKeyPem())
.when().post("/").then().statusCode(200)
.extract().path("UploadServerCertificateResponse.UploadServerCertificateResult"
+ ".ServerCertificateMetadata.Arn");
}
private static String requestAcmCertificate() {
return given().header("Authorization", ACM_AUTH)
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
.contentType("application/x-amz-json-1.1")
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
.body("{\"DomainName\": \"elbv2-" + suffix()
+ ".example.com\", \"ValidationMethod\": \"DNS\"}")
.when().post("/").then().statusCode(200)
.extract().path("CertificateArn");
}
private String loadBalancer() {
String arn = given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateLoadBalancer")
.formParam("Name", "elbv2-cert-" + suffix())
.formParam("Type", "application")
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
.formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b"))
.when().post("/").then().statusCode(200)
.extract().path("CreateLoadBalancerResponse.CreateLoadBalancerResult"
+ ".LoadBalancers.member.LoadBalancerArn");
// Deleting the load balancer cascades to its listeners, which is what frees the
// certificate for the undo registered above.
cleanup.register(() -> given().header("Authorization", ELB_AUTH)
.formParam("Action", "DeleteLoadBalancer")
.formParam("LoadBalancerArn", arn)
.when().post("/"));
return arn;
}
private ValidatableResponse createListener(String certificateArn) {
return createListener("HTTPS", certificateArn);
}
private ValidatableResponse createListener(String protocol, String certificateArn) {
RequestSpecification request = given().header("Authorization", ELB_AUTH)
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", loadBalancer())
.formParam("Protocol", protocol)
.formParam("Port", "443")
.formParam("DefaultActions.member.1.Type", "fixed-response")
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200");
if (certificateArn != null) {
request = request.formParam("Certificates.member.1.CertificateArn", certificateArn);
}
return request.when().post("/").then();
}
private String listenerServing(String certificateArn) {
return listenerServing("HTTPS", certificateArn);
}
private String listenerServing(String protocol, String certificateArn) {
return createListener(protocol, certificateArn).statusCode(200)
.extract().path("CreateListenerResponse.CreateListenerResult.Listeners.member"
+ ".ListenerArn");
}
private static ValidatableResponse describeListener(String listenerArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "DescribeListeners")
.formParam("ListenerArns.member.1", listenerArn)
.when().post("/").then().statusCode(200);
}
private static String listenerField(String listenerArn, String field) {
return describeListener(listenerArn).extract()
.path("DescribeListenersResponse.DescribeListenersResult.Listeners.member."
+ field).toString();
}
/** Read through {@code getList} so one certificate and several arrive the same shape. */
private static List<String> listenerCertificates(String listenerArn) {
return given().header("Authorization", ELB_AUTH)
.formParam("Action", "DescribeListenerCertificates")
.formParam("ListenerArn", listenerArn)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getList("DescribeListenerCertificatesResponse"
+ ".DescribeListenerCertificatesResult.Certificates.member.CertificateArn");
}
@Test
void createListenerRejectsAnIamCertificateThatDoesNotExist() {
createListener(MISSING_IAM_CERTIFICATE)
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"))
.body("ErrorResponse.Error.Message",
equalTo("The specified certificate does not exist."));
}
@Test
void createListenerRejectsAnAcmCertificateThatDoesNotExist() {
createListener(MISSING_ACM_CERTIFICATE)
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
}
@Test
void createListenerRejectsSomethingThatNamesNoCertificateAtAll() {
createListener("not-an-arn")
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
// An ARN of a service that serves no certificates names one no better.
createListener("arn:aws:s3:::some-bucket")
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
}
@Test
void createListenerAcceptsAnUploadedIamCertificate() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void createListenerAcceptsAnAcmCertificate() {
createListener(requestAcmCertificate()).statusCode(200);
}
@Test
void createListenerWithNoCertificateIsUntouched() {
// Nothing to resolve, so the check has nothing to say: a listener may carry none.
createListener(null).statusCode(200);
}
@Test
void aTlsListenerIsHeldToTheSameCheckAsAnHttpsOne() {
// The reference brackets the member for HTTPS and TLS, so both, not HTTPS alone.
createListener("TLS", MISSING_IAM_CERTIFICATE)
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
}
@Test
void aListenerOfAProtocolWithNoCertificatesIsLeftAlone() {
// The member is bracketed "[HTTPS and TLS listeners]", so a certificate on an HTTP
// listener is a configuration the reference does not describe. What AWS answers there is
// not CertificateNotFound on any evidence to hand, so Floci does not invent one: this
// pins the scope of the check rather than endorsing the request.
createListener("HTTP", MISSING_IAM_CERTIFICATE).statusCode(200);
}
@Test
void modifyListenerRejectsAMissingCertificateAndKeepsTheOneItHad() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", MISSING_IAM_CERTIFICATE)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
// The refusal has to land before the write, or the listener is left serving a
// certificate the account does not have.
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void addListenerCertificatesRejectsAMissingCertificateAndAddsNothing() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "AddListenerCertificates")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", MISSING_IAM_CERTIFICATE)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void createListenerRejectsABlankCertificateArn() {
// An empty value in the list names a certificate no better than "not-an-arn" does, and
// letting it through would leave the listener holding something it cannot serve.
createListener("").statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
}
@Test
void addListenerCertificatesRejectsABlankCertificateArnAndAddsNothing() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "AddListenerCertificates")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", "")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void aRefusedModifyListenerLeavesThePortAndProtocolAsTheyWere() {
String certificateArn = uploadCertificate();
String listenerArn = listenerServing(certificateArn);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", listenerArn)
.formParam("Port", "8443")
.formParam("Protocol", "TLS")
.formParam("Certificates.member.1.CertificateArn", MISSING_IAM_CERTIFICATE)
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
// A refused request must change nothing. The listener being modified is the stored one,
// so a check that ran after the first setter would answer 400 over a listener already
// moved to the new port, which no later read would put back.
assertEquals("443", listenerField(listenerArn, "Port"));
assertEquals("HTTPS", listenerField(listenerArn, "Protocol"));
assertEquals(List.of(certificateArn), listenerCertificates(listenerArn));
}
@Test
void turningAnHttpListenerIntoAnHttpsOneChecksTheCertificateItAlreadyHeld() {
// An HTTP listener may carry a certificate nothing resolves, because the check does not
// cover its protocol. Serving it is what the check covers, and the request that starts
// serving it names no certificate of its own, so the one on file is the one to resolve.
String listenerArn = listenerServing("HTTP", MISSING_IAM_CERTIFICATE);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", listenerArn)
.formParam("Protocol", "HTTPS")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("CertificateNotFound"));
assertEquals("HTTP", listenerField(listenerArn, "Protocol"));
}
@Test
void turningAnHttpListenerIntoAnHttpsOneIsAllowedWhenTheCertificateExists() {
String listenerArn = listenerServing("HTTP", uploadCertificate());
given().header("Authorization", ELB_AUTH)
.formParam("Action", "ModifyListener")
.formParam("ListenerArn", listenerArn)
.formParam("Protocol", "HTTPS")
.when().post("/").then().statusCode(200);
assertEquals("HTTPS", listenerField(listenerArn, "Protocol"));
}
@Test
void addListenerCertificatesAcceptsASecondUploadedCertificate() {
String first = uploadCertificate();
String second = uploadCertificate();
String listenerArn = listenerServing(first);
given().header("Authorization", ELB_AUTH)
.formParam("Action", "AddListenerCertificates")
.formParam("ListenerArn", listenerArn)
.formParam("Certificates.member.1.CertificateArn", second)
.when().post("/").then().statusCode(200);
assertTrue(listenerCertificates(listenerArn).containsAll(List.of(first, second)),
"both certificates should be on the listener");
}
}