mirror of
https://github.com/floci-io/floci.git
synced 2026-11-28 16:11:48 -05:00
fix(ec2): keep key pair names unique under concurrent requests (#6635)
* fix(ec2): keep key pair names unique under concurrent requests CreateKeyPair and ImportKeyPair checked that a name was free and stored the new key pair as two separate steps, so two requests for one name at the same moment could both pass the check and both store a key pair. Both got a key pair back, DescribeKeyPairs listed the name twice, and RunInstances injected whichever record it found first, so the other caller's private key did not open the instance. CreateKeyPair generates its key between the two steps, which keeps that window open for as long as key generation takes. Both actions now store through one method that checks the name again and writes under the EC2 service's striped lock for the region and name, so the second request is refused with InvalidKeyPair.Duplicate and the same message as before. The first check stays where it was, so a single request is answered as before, and a taken name is still refused before a key is generated for it. Follow-up to the review of #6112. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep a tag write from restoring a deleted key pair A CreateTags on a key pair reads the record and writes it back with its new tags while holding the key pair's lock, but DeleteKeyPair deleted without that lock. A delete landing between the read and the write was undone: the key pair came back, and if a CreateKeyPair had taken the freed name in between, the name then had two key pairs. DeleteKeyPair now deletes each matching key pair under the lock tag writes take on it, as DeleteEgressOnlyInternetGateway does, so a tag write either finishes before the delete or finds the key pair gone. The EC2 docs now say what CreateKeyPair and ImportKeyPair do with a taken name rather than promising one key pair per name outright. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): pin where the key pair race tests wait, and clean up the SDK test The race tests now let the held write go early only when the waiting request is blocked in storeNewKeyPair or deleteKeyPair on a monitor the held request owns, and otherwise wait for that request to finish, so a change that made it wait anywhere else fails the test instead of quietly skipping the check under the lock. The SDK test waits up to 60 s for its requests to finish before it deletes the name, so a slow request is not left to store a key pair after the cleanup, and it checks the refused requests' error code and status but not their message, which AWS words differently from Floci. The storeNewKeyPair Javadoc also says that the store's own locks, taken inside the name lock, never lead back to an EC2 lock. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): name what the key pair race tests wait for A race test whose request comes to wait anywhere other than the named Ec2Service method now fails with a timeout that says what it waited for, and the helper says why the method is named. The DeleteKeyPair comment says that scan returns a new list rather than copies, and the SDK test's cleanup comment says it waits up to 60 s. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): say what pinning the waiting method guards against The race tests' helper Javadoc no longer says that a wait elsewhere always skips the code under the lock: such a wait may not be at the lock under test, so the tests time out rather than pass without exercising it, and moving that lock into another method means updating the name the tests give. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): park the key pair race tests' writes with ParkingStore Both race tests held a write on a latch in an anonymous store of their own. They now wrap the shared testing ParkingStore in AccountAwareStorageBackend, as the Config tagging tests do, and arm its next write: before the first request in the name race test, and after the key pair is created in the delete test, so the write it parks is the tag write's. The name race test creates ED25519 keys so that key generation stays well inside ParkingStore's two-second wait. Main code is unchanged. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
ec13eda221
commit
986117a45c
4 files changed
+237
-6
No files matched your search
+83
@@ -0,0 +1,83 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
|
||||
import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
|
||||
import software.amazon.awssdk.services.ec2.model.KeyPairInfo;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
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 static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("EC2 key pair names under concurrent CreateKeyPair and ImportKeyPair")
|
||||
class Ec2KeyPairConcurrentNameTest {
|
||||
|
||||
private static final int REQUESTS = 8;
|
||||
|
||||
@Test
|
||||
@DisplayName("Of concurrent requests for one name, one stores a key pair and the others are refused as duplicates")
|
||||
void oneOfConcurrentRequestsForANameGetsIt() throws Exception {
|
||||
String name = TestFixtures.uniqueName("contested-key");
|
||||
String publicKey = "ssh-ed25519 " + Base64.getEncoder().encodeToString(OpenSSHPublicKeyUtil.encodePublicKey(
|
||||
new Ed25519PrivateKeyParameters(new SecureRandom()).generatePublicKey()));
|
||||
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
ExecutorService requests = Executors.newFixedThreadPool(REQUESTS);
|
||||
try {
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
List<Future<String>> results = new ArrayList<>();
|
||||
for (int i = 0; i < REQUESTS; i++) {
|
||||
boolean imported = i % 2 == 1;
|
||||
results.add(requests.submit(() -> {
|
||||
start.await();
|
||||
return imported
|
||||
? ec2.importKeyPair(r -> r.keyName(name)
|
||||
.publicKeyMaterial(SdkBytes.fromUtf8String(publicKey))).keyPairId()
|
||||
: ec2.createKeyPair(r -> r.keyName(name)).keyPairId();
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
|
||||
List<String> stored = new ArrayList<>();
|
||||
List<Throwable> refused = new ArrayList<>();
|
||||
for (Future<String> result : results) {
|
||||
try {
|
||||
stored.add(result.get(60, TimeUnit.SECONDS));
|
||||
} catch (ExecutionException e) {
|
||||
refused.add(e.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(stored).hasSize(1);
|
||||
// The message is not compared: AWS words it differently from Floci.
|
||||
assertThat(refused).hasSize(REQUESTS - 1).allSatisfy(e ->
|
||||
assertThat(e).isInstanceOfSatisfying(Ec2Exception.class, refusal -> {
|
||||
assertThat(refusal.awsErrorDetails().errorCode()).isEqualTo("InvalidKeyPair.Duplicate");
|
||||
assertThat(refusal.statusCode()).isEqualTo(400);
|
||||
}));
|
||||
assertThat(ec2.describeKeyPairs(r -> r.keyNames(name)).keyPairs())
|
||||
.extracting(KeyPairInfo::keyPairId).containsExactlyElementsOf(stored);
|
||||
} finally {
|
||||
// Waits up to 60 s for the requests to finish before the name is deleted, so a slow one
|
||||
// is not left to store a key pair after the cleanup.
|
||||
requests.shutdown();
|
||||
if (!requests.awaitTermination(60, TimeUnit.SECONDS)) {
|
||||
requests.shutdownNow();
|
||||
}
|
||||
ec2.deleteKeyPair(r -> r.keyName(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user