mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): make the server certificate reference check atomic with the write (#5368)
DeleteServerCertificate checked the reference providers under its own lock, while a referring service validated the certificate and then saved the resource naming it. Nothing tied the two together, so a delete running between the check and the write saw no reference, removed the certificate, and left a live distribution or listener holding one that was gone. It reproduced in 233 of 400 trials. CloudFront and ELB Classic now perform that check and the write while holding the lock the delete takes, so only the two sensible orders remain: the delete loses and answers DeleteConflict, or it wins and the create is refused. The ordering runs one way only. deleteServerCertificate holds the lock while calling serverCertificateReferences() on each provider, and those are plain reads over the provider's own store that take no provider monitor, so IAM never waits on a provider while a provider waits on IAM. ELBv2 is untouched: it never validates certificate references, so a listener there can name a certificate that was never present, which is a separate gap. Removing a listener needs a lock too, for a different reason than adding one. deleteLoadBalancerListeners removed from the listener list with no lock at all, while the certificate delete walked that same ArrayList, and a structural change to a list being walked ends the walk in ConcurrentModificationException. No mapper covers that, so DeleteServerCertificate answered an unmapped 500 rather than 200 or DeleteConflict. A probe calling the scan exactly as the delete does, against a loop of listener removals, hit it within two seconds. That one is the list's problem rather than the lock's, so the listeners are held in a CopyOnWriteArrayList, as Stack.events and IamUser.groupNames already are, and the walk reads a snapshot of it. Removal then takes only this service's own monitor, which the add shares so that a removal cannot land between the add's look at the port and its decision, and a certificate delete no longer waits on either. A unit test runs the scan against a loop of listener writes: with a plain list it ends in ConcurrentModificationException inside a second, which is how the probe became a test. The two race tests keep their own fixtures and read their own failures. Each trial's certificate, and its load balancer or distribution, now come back out in a finally, so a trial that fails part way through leaves nothing behind in the application the other test classes share, which matters against a 20 certificate quota. The racing tasks' futures are read as well: each catches the AwsException its order expects, and anything else used to stay in the future, leaving the trial looking like the other order had won and the test passing green without the race ever having run. The load balancer name check moves inside the guard too. It was made before the write and nowhere else, so two creates of one name both passed it and both committed, and the first caller was told it had succeeded while holding a load balancer that had been replaced. The check above the guard stays as the fail-fast that keeps AWS's error precedence. Reverting the inner one has the new test report two winners where there should be one. That also showed the guard was not always a lock. Built without IAM, which is how this service's unit tests build it, it ran the action with nothing held, so a re-check there would have been worth no more than the first check. The name is settled by putIfAbsent instead, which holds whether or not IAM is present and needs no lock to carry it. Neither service takes the lock for a write that cannot record an IAM certificate. A distribution that names none, a listener with no certificate or one served by ACM, and a listener removal cannot leave a resource holding a deleted certificate, and the delete reads a copy of the distribution store and a snapshot of each listener list, so an unguarded write cannot disturb its walk either. Holding it for every write would instead have an unrelated load balancer, zone or health check write delay a certificate delete, and the other way round. The race tests stop accepting any AwsException as an order. Each task swallows only the code its own order produces, InvalidViewerCertificate for the create and DeleteConflict for the delete, and rethrows the rest into the future the trial now reads. The load balancer trials record both statuses, and the run asserts every one resolved as one order winning with the other told why, since two failures would otherwise pass as a clean trial with the race untested. The doc paragraph for this behaviour claimed the DeleteConflict refusal was what AWS does, and nothing sources that. DeleteConflict is modeled on the operation, but the API Reference describes it only as attached subordinate entities without saying what counts as one for a certificate, and the operation's own page warns that if Elastic Load Balancing does not detect the deletion of a bound certificate it may continue to use it, which reads as the delete going through. The refusal stays, being the more useful answer to a caller than a dangling reference, and is now recorded as the intentional deviation it is. The ELBv2 note carries its evidence too: CertificateNotFound is modeled on CreateListener, ModifyListener and AddListenerCertificates, and none of the three checks anything. Closes #5087
This commit is contained in:
1 parent
46f9c23c8b
commit
477e3ef813
8 files changed
+754
-51
No files matched your search
+257
@@ -0,0 +1,257 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.ServerCertificateReferenceProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
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.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A distribution and the certificate it names cannot end up disagreeing about whether the
|
||||
* certificate exists.
|
||||
*
|
||||
* <p>{@code DeleteServerCertificate} checks the reference providers under its own lock, and
|
||||
* CloudFront validates the certificate and then saves the distribution. With the two critical
|
||||
* sections unrelated, either order was reachable and so was a third state that neither order
|
||||
* should produce: a saved distribution naming a certificate the delete had already removed. That
|
||||
* reproduced in well over half of the trials below, so this is a tight assertion rather than a
|
||||
* hopeful one.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFrontCertificateDeleteRaceTest {
|
||||
|
||||
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
|
||||
/** The window was wide, so a few dozen trials is already decisive. */
|
||||
private static final int TRIALS = 120;
|
||||
|
||||
private final CloudFrontService cloudFrontService;
|
||||
private final IamService iamService;
|
||||
|
||||
CloudFrontCertificateDeleteRaceTest(CloudFrontService cloudFrontService, IamService iamService) {
|
||||
this.cloudFrontService = cloudFrontService;
|
||||
this.iamService = iamService;
|
||||
}
|
||||
|
||||
private ServerCertificate uploadCertificate(String name) {
|
||||
CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
|
||||
"race.certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
|
||||
return iamService.uploadServerCertificate(name, "/race/", pair.certificatePem(),
|
||||
pair.privateKeyPem(), null, Map.of());
|
||||
}
|
||||
|
||||
private Distribution distributionWithCertificate(String certificateId) {
|
||||
Origin origin = new Origin();
|
||||
origin.setId("race-origin");
|
||||
origin.setDomainName("example.com");
|
||||
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
|
||||
customOriginConfig.put("HTTPPort", "80");
|
||||
customOriginConfig.put("HTTPSPort", "443");
|
||||
customOriginConfig.put("OriginProtocolPolicy", "http-only");
|
||||
origin.setCustomOriginConfig(customOriginConfig);
|
||||
|
||||
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
|
||||
behavior.setTargetOriginId("race-origin");
|
||||
behavior.setViewerProtocolPolicy("allow-all");
|
||||
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(false);
|
||||
config.setComment("certificate-delete-race");
|
||||
config.setOrigins(List.of(origin));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Map<String, String> viewerCertificate = new LinkedHashMap<>();
|
||||
viewerCertificate.put("IAMCertificateId", certificateId);
|
||||
viewerCertificate.put("SSLSupportMethod", "sni-only");
|
||||
config.setViewerCertificate(viewerCertificate);
|
||||
|
||||
Distribution distribution = new Distribution();
|
||||
distribution.setConfig(config);
|
||||
return distribution;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDistributionIsNeverLeftHoldingADeletedCertificate() throws Exception {
|
||||
List<String> dangling = new ArrayList<>();
|
||||
List<ServerCertificateReferenceProvider> providers = List.of(cloudFrontService);
|
||||
|
||||
for (int trial = 0; trial < TRIALS; trial++) {
|
||||
String name = "race-cert-" + trial + "-" + Long.toString(System.nanoTime(), 36);
|
||||
ServerCertificate certificate = uploadCertificate(name);
|
||||
String certificateId = certificate.getServerCertificateId();
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
AtomicReference<Distribution> created = new AtomicReference<>();
|
||||
AtomicBoolean deleted = new AtomicBoolean(false);
|
||||
try {
|
||||
List<Future<?>> racers = List.of(pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
created.set(cloudFrontService.createDistribution(
|
||||
distributionWithCertificate(certificateId), Map.of()));
|
||||
} catch (AwsException e) {
|
||||
// InvalidViewerCertificate when the delete got there first. Any other
|
||||
// code is a real failure, and swallowing it here would read as a lost
|
||||
// race and leave the trial looking clean.
|
||||
if (!"InvalidViewerCertificate".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}), pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
iamService.deleteServerCertificate(name, providers);
|
||||
deleted.set(true);
|
||||
} catch (AwsException e) {
|
||||
// DeleteConflict when the distribution was already saved. Any other code
|
||||
// is a real failure and has to reach the future.
|
||||
if (!"DeleteConflict".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
start.countDown();
|
||||
pool.shutdown();
|
||||
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish");
|
||||
reportAnythingUnexpected(racers);
|
||||
|
||||
if (created.get() != null && deleted.get()
|
||||
&& iamService.findServerCertificateById(certificateId).isEmpty()) {
|
||||
dangling.add("trial " + trial + ": distribution " + created.get().getId()
|
||||
+ " holds deleted certificate " + certificateId);
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
cleanUpTrial(created.get(), name, certificateId);
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(dangling.isEmpty(),
|
||||
"a distribution was left holding a deleted certificate in "
|
||||
+ dangling.size() + " of " + TRIALS + " trials: " + dangling);
|
||||
}
|
||||
|
||||
/** Whichever order wins, the pair stays consistent: both present, or neither. */
|
||||
@Test
|
||||
void oneOfTheTwoOrdersAlwaysWins() throws Exception {
|
||||
List<ServerCertificateReferenceProvider> providers = List.of(cloudFrontService);
|
||||
int createWon = 0;
|
||||
int deleteWon = 0;
|
||||
|
||||
for (int trial = 0; trial < 40; trial++) {
|
||||
String name = "race-order-" + trial + "-" + Long.toString(System.nanoTime(), 36);
|
||||
String certificateId = uploadCertificate(name).getServerCertificateId();
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
AtomicReference<Distribution> created = new AtomicReference<>();
|
||||
AtomicBoolean deleted = new AtomicBoolean(false);
|
||||
try {
|
||||
List<Future<?>> racers = List.of(pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
created.set(cloudFrontService.createDistribution(
|
||||
distributionWithCertificate(certificateId), Map.of()));
|
||||
} catch (AwsException e) {
|
||||
// the delete won; anything else is a failure, not an order
|
||||
if (!"InvalidViewerCertificate".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}), pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
iamService.deleteServerCertificate(name, providers);
|
||||
deleted.set(true);
|
||||
} catch (AwsException e) {
|
||||
// the create won; anything else is a failure, not an order
|
||||
if (!"DeleteConflict".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
start.countDown();
|
||||
pool.shutdown();
|
||||
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "trial did not finish");
|
||||
reportAnythingUnexpected(racers);
|
||||
|
||||
boolean certificateGone =
|
||||
iamService.findServerCertificateById(certificateId).isEmpty();
|
||||
if (created.get() != null) {
|
||||
createWon++;
|
||||
assertTrue(!certificateGone,
|
||||
"trial " + trial + ": the distribution exists so the certificate "
|
||||
+ "must too");
|
||||
} else {
|
||||
deleteWon++;
|
||||
assertTrue(certificateGone || !deleted.get(),
|
||||
"trial " + trial + ": no distribution, so a successful delete must "
|
||||
+ "have removed the certificate");
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
cleanUpTrial(created.get(), name, certificateId);
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(createWon + deleteWon == 40, "every trial must resolve one way or the other");
|
||||
}
|
||||
|
||||
/**
|
||||
* Surfaces anything a racing task threw that it was not written to expect. The throwable
|
||||
* otherwise stays in the task's {@link Future}, the trial reads as the other order having
|
||||
* won, and the test passes without the race it exists to measure ever having run.
|
||||
*/
|
||||
private static void reportAnythingUnexpected(List<Future<?>> racers) throws Exception {
|
||||
for (Future<?> racer : racers) {
|
||||
racer.get();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes the trial's own fixtures back out of the application, whatever happened above. Other
|
||||
* test classes share it, and the account's certificate quota is 20, so a trial that failed
|
||||
* part way through must not leave either resource behind. Nothing is asserted and either
|
||||
* resource may already be gone, since which one survives is exactly what the race decides.
|
||||
*/
|
||||
private void cleanUpTrial(Distribution created, String name, String certificateId) {
|
||||
if (created != null) {
|
||||
try {
|
||||
cloudFrontService.removeDistribution(created.getId());
|
||||
} catch (AwsException ignored) {
|
||||
// Already removed, which is one of the outcomes this test measures.
|
||||
}
|
||||
}
|
||||
if (iamService.findServerCertificateById(certificateId).isPresent()) {
|
||||
try {
|
||||
iamService.deleteServerCertificate(name, List.of());
|
||||
} catch (AwsException ignored) {
|
||||
// Deleted between that check and here by the racing task.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package io.github.hectorvent.floci.services.elb;
|
||||
|
||||
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 static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A Classic load balancer and the certificate its listener names cannot end up disagreeing about
|
||||
* whether the certificate exists.
|
||||
*
|
||||
* <p>Same hazard as the CloudFront one: {@code DeleteServerCertificate} checks the reference
|
||||
* providers under its own lock, while {@code CreateLoadBalancer} checks the certificate and then
|
||||
* commits the load balancer. Driven over the wire here, because the listener's certificate arrives
|
||||
* as a request parameter and the check lives behind the handler.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ElbClassicCertificateDeleteRaceTest {
|
||||
|
||||
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 CLASSIC_VERSION = "2012-06-01";
|
||||
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
|
||||
private static final int TRIALS = 60;
|
||||
|
||||
private static String suffix() {
|
||||
return Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
private static String uploadCertificate(String name) {
|
||||
CertificateGenerator.GeneratedCertificate pair = GENERATOR.generateSelfSignedCertificate(
|
||||
"elb.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 int createLoadBalancer(String lbName, String certificateArn) {
|
||||
return given().header("Authorization", ELB_AUTH)
|
||||
.formParam("Action", "CreateLoadBalancer")
|
||||
.formParam("Version", CLASSIC_VERSION)
|
||||
.formParam("LoadBalancerName", lbName)
|
||||
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
|
||||
.formParam("Listeners.member.1.Protocol", "HTTPS")
|
||||
.formParam("Listeners.member.1.LoadBalancerPort", "443")
|
||||
.formParam("Listeners.member.1.InstanceProtocol", "HTTP")
|
||||
.formParam("Listeners.member.1.InstancePort", "8080")
|
||||
.formParam("Listeners.member.1.SSLCertificateId", 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 int deleteLoadBalancer(String lbName) {
|
||||
return given().header("Authorization", ELB_AUTH)
|
||||
.formParam("Action", "DeleteLoadBalancer")
|
||||
.formParam("Version", CLASSIC_VERSION)
|
||||
.formParam("LoadBalancerName", lbName)
|
||||
.when().post("/").then().extract().statusCode();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLoadBalancerIsNeverLeftHoldingADeletedCertificate() throws Exception {
|
||||
List<String> dangling = new ArrayList<>();
|
||||
List<String> unresolved = new ArrayList<>();
|
||||
|
||||
for (int trial = 0; trial < TRIALS; trial++) {
|
||||
String name = "elb-race-cert-" + trial + "-" + suffix();
|
||||
String arn = uploadCertificate(name);
|
||||
String lbName = "elb-race-" + trial + "-" + suffix();
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
AtomicInteger createStatus = new AtomicInteger();
|
||||
AtomicInteger deleteStatus = new AtomicInteger();
|
||||
try {
|
||||
List<Future<?>> racers = List.of(pool.submit(() -> {
|
||||
start.await();
|
||||
createStatus.set(createLoadBalancer(lbName, 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 create = createStatus.get();
|
||||
int delete = deleteStatus.get();
|
||||
if (create == 200 && delete == 200 && !certificateExists(name)) {
|
||||
dangling.add("trial " + trial + ": load balancer " + lbName
|
||||
+ " holds deleted certificate " + name);
|
||||
}
|
||||
// Exactly one order wins, and the loser says why: the load balancer commits and
|
||||
// the delete answers DeleteConflict, or the certificate goes and the listener 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 (!(create == 200 && delete == 409) && !(create == 400 && delete == 200)) {
|
||||
unresolved.add("trial " + trial + ": create=" + create + " delete=" + delete);
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
cleanUpTrial(createStatus.get() == 200, lbName, name);
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(dangling.isEmpty(),
|
||||
"a load balancer 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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes the trial's own fixtures back out of the application, whatever happened above. Other
|
||||
* test classes share it, and the account's certificate quota is 20, so a trial that failed
|
||||
* part way through must not leave either resource behind. The status codes are ignored: which
|
||||
* of the two is still there is exactly what the race decides.
|
||||
*/
|
||||
private static void cleanUpTrial(boolean created, String lbName, String name) {
|
||||
if (created) {
|
||||
deleteLoadBalancer(lbName);
|
||||
}
|
||||
if (certificateExists(name)) {
|
||||
deleteCertificate(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,13 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
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.AtomicBoolean;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
@@ -147,6 +154,109 @@ class ElbClassicServiceTest {
|
||||
assertEquals("DuplicateLoadBalancerName", e.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* The name check and the write have to be one step. Checked before the write and nothing
|
||||
* else, two creates of one name both pass the check and both commit, and the caller of the
|
||||
* first is told it succeeded while holding a load balancer that was replaced.
|
||||
*/
|
||||
@Test
|
||||
void twoConcurrentCreatesOfOneNameLeaveOnlyOneWinner() throws Exception {
|
||||
for (int attempt = 0; attempt < 8; attempt++) {
|
||||
String name = "concurrent-elb-" + attempt;
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
try {
|
||||
List<Future<?>> creates = List.of(
|
||||
pool.submit(() -> {
|
||||
start.await();
|
||||
// Zones rather than subnets, and no security group, so that nothing
|
||||
// in here reaches a mock from two threads at once.
|
||||
return service.createLoadBalancer(REGION, name,
|
||||
List.of(httpListener()), List.of(REGION + "a"), List.of(),
|
||||
List.of(), null, Map.of());
|
||||
}),
|
||||
pool.submit(() -> {
|
||||
start.await();
|
||||
return service.createLoadBalancer(REGION, name,
|
||||
List.of(httpListener()), List.of(REGION + "a"), List.of(),
|
||||
List.of(), null, Map.of());
|
||||
}));
|
||||
start.countDown();
|
||||
pool.shutdown();
|
||||
assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS), "attempt did not finish");
|
||||
|
||||
int won = 0;
|
||||
int refused = 0;
|
||||
for (Future<?> create : creates) {
|
||||
try {
|
||||
create.get();
|
||||
won++;
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause() instanceof AwsException aws
|
||||
&& "DuplicateLoadBalancerName".equals(aws.getErrorCode()),
|
||||
"the loser must be refused by name, got " + e.getCause());
|
||||
refused++;
|
||||
}
|
||||
}
|
||||
assertEquals(1, won, "exactly one create must succeed for attempt " + attempt);
|
||||
assertEquals(1, refused, "exactly one create must be refused for attempt " + attempt);
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* IAM's {@code DeleteServerCertificate} walks these listener lists while deciding whether the
|
||||
* certificate it is about to remove is still in use. It holds its own lock for that and not
|
||||
* this service's, by design, so listener writes run alongside the walk and the list has to
|
||||
* tolerate them: on a plain list the walk ends in ConcurrentModificationException, which no
|
||||
* mapper covers, and the delete answers an unmapped 500.
|
||||
*/
|
||||
@Test
|
||||
void theCertificateScanSurvivesListenerWritesOnAnotherThread() throws Exception {
|
||||
create("scanned-elb");
|
||||
ClassicListener https = new ClassicListener();
|
||||
https.setProtocol("HTTPS");
|
||||
https.setLoadBalancerPort(443);
|
||||
https.setInstanceProtocol("HTTP");
|
||||
https.setInstancePort(80);
|
||||
https.setSslCertificateId("arn:aws:iam::000000000000:server-certificate/scanned");
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
AtomicBoolean writing = new AtomicBoolean(true);
|
||||
try {
|
||||
Future<?> writer = pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
for (int i = 0; i < 400; i++) {
|
||||
service.createLoadBalancerListeners(REGION, "scanned-elb", List.of(https));
|
||||
service.deleteLoadBalancerListeners(REGION, "scanned-elb", List.of(443));
|
||||
}
|
||||
} finally {
|
||||
writing.set(false);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
Future<Integer> scanner = pool.submit(() -> {
|
||||
start.await();
|
||||
int scans = 0;
|
||||
while (writing.get()) {
|
||||
service.serverCertificateReferences();
|
||||
scans++;
|
||||
}
|
||||
return scans;
|
||||
});
|
||||
start.countDown();
|
||||
|
||||
writer.get(30, TimeUnit.SECONDS);
|
||||
assertTrue(scanner.get(30, TimeUnit.SECONDS) > 0, "the scan never ran");
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadBalancersAreScopedByRegion() {
|
||||
create("my-elb");
|
||||
|
||||
Reference in new issue
Block a user