mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -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
+47
-24
@@ -48,6 +48,7 @@ import java.util.SequencedSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -191,20 +192,22 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
validateOriginCustomHeaders(dist.getConfig());
|
||||
validateResponseHeadersPolicyReferences(dist.getConfig(), null);
|
||||
validateTrustedKeyGroups(dist.getConfig());
|
||||
validateViewerCertificate(dist.getConfig());
|
||||
String id = generateDistributionId();
|
||||
dist.setId(id);
|
||||
dist.setArn(arn("distribution/" + id));
|
||||
dist.setDomainName(domainNameFor(id));
|
||||
dist.setStatus("Deployed");
|
||||
dist.setLastModifiedTime(Instant.now());
|
||||
dist.setEtag(UUID.randomUUID().toString());
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
dist.setTags(tags);
|
||||
tagStore.put("distribution/" + id, tags);
|
||||
}
|
||||
distStore.put(id, dist);
|
||||
return dist;
|
||||
return whileCertificatesHeld(dist.getConfig(), () -> {
|
||||
validateViewerCertificate(dist.getConfig());
|
||||
String id = generateDistributionId();
|
||||
dist.setId(id);
|
||||
dist.setArn(arn("distribution/" + id));
|
||||
dist.setDomainName(domainNameFor(id));
|
||||
dist.setStatus("Deployed");
|
||||
dist.setLastModifiedTime(Instant.now());
|
||||
dist.setEtag(UUID.randomUUID().toString());
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
dist.setTags(tags);
|
||||
tagStore.put("distribution/" + id, tags);
|
||||
}
|
||||
distStore.put(id, dist);
|
||||
return dist;
|
||||
});
|
||||
}
|
||||
|
||||
public Distribution getDistribution(String id) {
|
||||
@@ -222,16 +225,18 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
validateOriginCustomHeaders(updated.getConfig());
|
||||
validateResponseHeadersPolicyReferences(updated.getConfig(), id);
|
||||
validateTrustedKeyGroups(updated.getConfig());
|
||||
validateViewerCertificate(updated.getConfig());
|
||||
updated.setId(id);
|
||||
updated.setArn(existing.getArn());
|
||||
updated.setDomainName(existing.getDomainName());
|
||||
updated.setStatus("Deployed");
|
||||
updated.setLastModifiedTime(Instant.now());
|
||||
updated.setEtag(UUID.randomUUID().toString());
|
||||
updated.setTags(existing.getTags());
|
||||
distStore.put(id, updated);
|
||||
return updated;
|
||||
return whileCertificatesHeld(updated.getConfig(), () -> {
|
||||
validateViewerCertificate(updated.getConfig());
|
||||
updated.setId(id);
|
||||
updated.setArn(existing.getArn());
|
||||
updated.setDomainName(existing.getDomainName());
|
||||
updated.setStatus("Deployed");
|
||||
updated.setLastModifiedTime(Instant.now());
|
||||
updated.setEtag(UUID.randomUUID().toString());
|
||||
updated.setTags(existing.getTags());
|
||||
distStore.put(id, updated);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -264,6 +269,24 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a write that may record an IAM server certificate reference while IAM holds the lock
|
||||
* {@code DeleteServerCertificate} takes, so the certificate cannot be deleted between
|
||||
* {@link #validateViewerCertificate} and the store write. Without the guard the delete sees no
|
||||
* reference, because the distribution is not saved yet, and the distribution is left holding a
|
||||
* certificate that is gone.
|
||||
*/
|
||||
private <T> T whileCertificatesHeld(DistributionConfig config, Supplier<T> action) {
|
||||
if (iamService == null || iamCertificateId(config) == null) {
|
||||
// Nothing to order. A distribution that names no IAM certificate cannot be left
|
||||
// holding one, and the scan reads a copy of the store rather than a live collection,
|
||||
// so this write cannot disturb it either. Taking the lock anyway would make every
|
||||
// distribution write wait on a certificate delete, and the other way round.
|
||||
return action.get();
|
||||
}
|
||||
return iamService.supplyWithServerCertificatesHeld(action);
|
||||
}
|
||||
|
||||
private static void validateOriginCustomHeaders(DistributionConfig config) {
|
||||
if (config == null || config.getOrigins() == null) {
|
||||
return;
|
||||
|
||||
@@ -68,6 +68,9 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
|
||||
// region → load balancer name → record
|
||||
private Map<String, Map<String, ClassicLoadBalancer>> loadBalancers = new ConcurrentHashMap<>();
|
||||
|
||||
/** Serializes listener writes against each other; see {@link #createLoadBalancerListeners}. */
|
||||
private final Object listenerLock = new Object();
|
||||
|
||||
public ElbClassicService(Ec2Service ec2Service,
|
||||
ElbClassicHealthChecker healthChecker,
|
||||
StorageFactory storageFactory,
|
||||
@@ -165,9 +168,7 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
|
||||
Map<String, ClassicLoadBalancer> regionLbs =
|
||||
loadBalancers.computeIfAbsent(region, k -> new ConcurrentHashMap<>());
|
||||
if (regionLbs.containsKey(name)) {
|
||||
throw new AwsException("DuplicateLoadBalancerName",
|
||||
"Load balancer named " + name + " already exists and is not compatible with the "
|
||||
+ "requested configuration.", 400);
|
||||
throw duplicateLoadBalancerName(name);
|
||||
}
|
||||
|
||||
String id = randomHex();
|
||||
@@ -204,8 +205,18 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
|
||||
lb.setAvailabilityZones(new ArrayList<>(availabilityZones));
|
||||
}
|
||||
|
||||
regionLbs.put(name, lb);
|
||||
loadBalancers.put(region, regionLbs);
|
||||
whileCertificatesHeld(listeners, () -> {
|
||||
// The certificate check again, and this is the one that counts. The one above it
|
||||
// fails fast and keeps AWS's error precedence, but a check made before the lock says
|
||||
// nothing about the moment of the write. The unique name is a separate problem that
|
||||
// putIfAbsent settles on its own, lock or no lock: checked and then written as two
|
||||
// steps, two creates of one name both pass and only the second survives.
|
||||
requireCertificates(region, listeners);
|
||||
if (regionLbs.putIfAbsent(name, lb) != null) {
|
||||
throw duplicateLoadBalancerName(name);
|
||||
}
|
||||
loadBalancers.put(region, regionLbs);
|
||||
});
|
||||
healthChecker.startMonitoring(lb);
|
||||
return lb;
|
||||
}
|
||||
@@ -282,31 +293,46 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
|
||||
validateListener(listener);
|
||||
}
|
||||
requireCertificates(region, listeners);
|
||||
for (ClassicListener listener : listeners) {
|
||||
ClassicListener existing = lb.getListeners().stream()
|
||||
.filter(l -> l.getLoadBalancerPort().equals(listener.getLoadBalancerPort()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (existing != null) {
|
||||
// AWS accepts a repeat of an identical listener and rejects a conflicting one.
|
||||
if (!sameListener(existing, listener)) {
|
||||
throw new AwsException("DuplicateListener",
|
||||
"A listener already exists for " + name + " with LoadBalancerPort "
|
||||
+ listener.getLoadBalancerPort()
|
||||
+ ", but with a different InstancePort, Protocol, or "
|
||||
+ "SSLCertificateId", 400);
|
||||
whileCertificatesHeld(listeners, () -> {
|
||||
requireCertificates(region, listeners);
|
||||
// The port of an existing listener decides whether this one is added, so the walk and
|
||||
// the add are one step. Two threads adding the same port would otherwise both find it
|
||||
// absent and both add it, and a removal landing in between would drop a listener this
|
||||
// call has already decided to keep.
|
||||
synchronized (listenerLock) {
|
||||
for (ClassicListener listener : listeners) {
|
||||
ClassicListener existing = lb.getListeners().stream()
|
||||
.filter(l -> l.getLoadBalancerPort().equals(listener.getLoadBalancerPort()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (existing != null) {
|
||||
// AWS accepts a repeat of an identical listener and rejects a conflicting one.
|
||||
if (!sameListener(existing, listener)) {
|
||||
throw new AwsException("DuplicateListener",
|
||||
"A listener already exists for " + name + " with LoadBalancerPort "
|
||||
+ listener.getLoadBalancerPort()
|
||||
+ ", but with a different InstancePort, Protocol, or "
|
||||
+ "SSLCertificateId", 400);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
lb.getListeners().add(listener);
|
||||
}
|
||||
continue;
|
||||
persist(region);
|
||||
}
|
||||
lb.getListeners().add(listener);
|
||||
}
|
||||
persist(region);
|
||||
});
|
||||
}
|
||||
|
||||
public void deleteLoadBalancerListeners(String region, String name, List<Integer> loadBalancerPorts) {
|
||||
ClassicLoadBalancer lb = requireLoadBalancer(region, name);
|
||||
lb.getListeners().removeIf(l -> loadBalancerPorts.contains(l.getLoadBalancerPort()));
|
||||
persist(region);
|
||||
// Under the same monitor as the add, so a removal cannot land between that method's look
|
||||
// at the port and its decision. No certificate lock: removing a listener can only drop a
|
||||
// reference to a certificate, never record one, and a delete that reads the list while
|
||||
// this runs reads a snapshot of it.
|
||||
synchronized (listenerLock) {
|
||||
lb.getListeners().removeIf(l -> loadBalancerPorts.contains(l.getLoadBalancerPort()));
|
||||
persist(region);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Health ────────────────────────────────────────────────────────────────
|
||||
@@ -558,6 +584,13 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* <p>Takes no monitor of this service, which is what keeps the ordering with IAM one way: the
|
||||
* delete calls this while holding its certificate lock. Safe without one because both maps
|
||||
* walked here are concurrent and the listener list iterates a snapshot.
|
||||
*/
|
||||
@Override
|
||||
public List<Reference> serverCertificateReferences() {
|
||||
List<Reference> references = new ArrayList<>();
|
||||
@@ -575,6 +608,50 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
|
||||
return references;
|
||||
}
|
||||
|
||||
private static AwsException duplicateLoadBalancerName(String name) {
|
||||
return new AwsException("DuplicateLoadBalancerName",
|
||||
"Load balancer named " + name + " already exists and is not compatible with the "
|
||||
+ "requested configuration.", 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a write that records a listener's IAM server certificate while IAM holds the lock
|
||||
* {@code DeleteServerCertificate} takes, so the certificate cannot be deleted between the
|
||||
* check and the write. The callers re-check inside the guard: the fail-fast check above it
|
||||
* keeps the error precedence AWS has, and only the one under the guard is atomic with the
|
||||
* commit.
|
||||
*
|
||||
* <p>Only for a write that names an IAM certificate. A listener with no certificate, or one
|
||||
* served by ACM, cannot leave a load balancer holding a deleted IAM certificate, and the
|
||||
* delete reads a snapshot of the listener list rather than the live one, so an unguarded
|
||||
* write cannot disturb its walk either. Taking the lock for every write would instead make a
|
||||
* certificate delete wait on an unrelated load balancer, listener or zone write, and the
|
||||
* other way round, for writes that cannot affect it.
|
||||
*
|
||||
* <p>This class's own invariants do not ride on this lock. The unique load balancer name is
|
||||
* carried by {@code putIfAbsent} and the listener list by {@link #listenerLock}, both of
|
||||
* which hold whether or not IAM is present, which is what the unit tests build.
|
||||
*/
|
||||
private void whileCertificatesHeld(List<ClassicListener> listeners, Runnable action) {
|
||||
if (iamService == null || !namesIamCertificate(listeners)) {
|
||||
action.run();
|
||||
return;
|
||||
}
|
||||
iamService.runWithServerCertificatesHeld(action);
|
||||
}
|
||||
|
||||
/** Whether any of these listeners names a certificate that IAM serves, rather than ACM. */
|
||||
private static boolean namesIamCertificate(List<ClassicListener> listeners) {
|
||||
for (ClassicListener listener : listeners) {
|
||||
String certificate = listener.getSslCertificateId();
|
||||
if (certificate != null && !certificate.isBlank() && AwsArnUtils.isArn(certificate)
|
||||
&& "iam".equals(AwsArnUtils.parse(certificate).service())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void requireCertificates(String region, List<ClassicListener> listeners) {
|
||||
for (ClassicListener listener : listeners) {
|
||||
String certificateId = listener.getSslCertificateId();
|
||||
|
||||
+13
-2
@@ -8,6 +8,7 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* A Classic (2012-06-01) load balancer — the {@code LoadBalancerDescription} shape.
|
||||
@@ -30,7 +31,15 @@ public class ClassicLoadBalancer {
|
||||
private String accountId;
|
||||
private Instant createdTime;
|
||||
|
||||
private List<ClassicListener> listeners = new ArrayList<>();
|
||||
/**
|
||||
* Copy on write because IAM reads it from another thread. {@code DeleteServerCertificate}
|
||||
* walks the listeners of every load balancer, through
|
||||
* {@code ElbClassicService.serverCertificateReferences()}, looking for the certificate it is
|
||||
* about to remove, and a listener write may be changing this list while it does. A plain list
|
||||
* ends that walk in {@link java.util.ConcurrentModificationException}; iterating this one
|
||||
* reads a snapshot, which also keeps the response renderer and Jackson off the live list.
|
||||
*/
|
||||
private List<ClassicListener> listeners = new CopyOnWriteArrayList<>();
|
||||
private List<String> availabilityZones = new ArrayList<>();
|
||||
private List<String> subnets = new ArrayList<>();
|
||||
private List<String> securityGroups = new ArrayList<>();
|
||||
@@ -73,7 +82,9 @@ public class ClassicLoadBalancer {
|
||||
public void setCreatedTime(Instant v) { this.createdTime = v; }
|
||||
|
||||
public List<ClassicListener> getListeners() { return listeners; }
|
||||
public void setListeners(List<ClassicListener> v) { this.listeners = v; }
|
||||
public void setListeners(List<ClassicListener> v) {
|
||||
this.listeners = new CopyOnWriteArrayList<>(v != null ? v : List.of());
|
||||
}
|
||||
|
||||
public List<String> getAvailabilityZones() { return availabilityZones; }
|
||||
public void setAvailabilityZones(List<String> v) { this.availabilityZones = v; }
|
||||
|
||||
@@ -81,6 +81,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
@@ -2698,6 +2699,32 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
deleteServerCertificate(name, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs an action that checks a server certificate and then records a reference to it, holding
|
||||
* the lock {@link #deleteServerCertificate} takes so the certificate cannot be deleted in
|
||||
* between. Without it the check and the write straddle the delete: the delete sees no
|
||||
* reference because the referring resource is not saved yet, removes the certificate, and the
|
||||
* resource is then saved pointing at something that is gone.
|
||||
*
|
||||
* <p>Safe to call from inside a provider's own monitor, because the ordering only ever runs
|
||||
* one way. {@code deleteServerCertificate} holds this lock while calling
|
||||
* {@link ServerCertificateReferenceProvider#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.
|
||||
*/
|
||||
public <T> T supplyWithServerCertificatesHeld(Supplier<T> action) {
|
||||
synchronized (serverCertificateLock) {
|
||||
return action.get();
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link #supplyWithServerCertificatesHeld} for an action with no result. */
|
||||
public void runWithServerCertificatesHeld(Runnable action) {
|
||||
synchronized (serverCertificateLock) {
|
||||
action.run();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a server certificate unless one of the providers reports it in use, in which case
|
||||
* AWS answers {@code DeleteConflict} and the certificate stays.
|
||||
|
||||
Reference in new issue
Block a user