Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ec2): keep key pair names unique under concurrent requests (#6635)

Jackson Price986117a45c9c
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2KeyPairConcurrentNameTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2KeyPairConcurrentNameTest.java
new file mode 100644
index 0000000000..0447675e0b
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2KeyPairConcurrentNameTest.java
@@ -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));
+ }
+ }
+ }
+}
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index 675fdf5b12..54587c7585 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -353,7 +353,10 @@ whose blob is incomplete, has bytes after its key or declares another type, and
more than one key line are refused with `InvalidKey.Format`. The key is stored as one OpenSSH line,
which is what `RunInstances` copies into `authorized_keys`. `CreateKeyPair` and `ImportKeyPair`
take a `KeyName` of up to 255 ASCII characters with no leading or trailing space; a missing or
-blank one is `MissingParameter`, and they answer any other with `InvalidParameterValue`.
+blank one is `MissingParameter`, and they answer any other with `InvalidParameterValue`. Either
+action refuses a name that a key pair in the account and region already has with
+`InvalidKeyPair.Duplicate`, and of two that ask for a free name at the same moment, one stores its
+key pair and the other gets that error.
`DescribeKeyPairs` returns each key pair's `keyType` and `createTime`. It filters by `key-pair-id`,
`key-name`, `fingerprint`, `tag-key` and `tag:<key>`, as AWS documents, and also by `key-type`,
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index 11c5917f27..e8f13a3101 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -8139,7 +8139,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
kp.setKeyType(type);
kp.setCreateTime(Instant.now());
kp.setRegion(region);
- keyPairs.put(key(region, keyPairId), kp);
+ storeNewKeyPair(region, kp);
return kp;
}
@@ -8223,14 +8223,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public KeyPair deleteKeyPair(String region, String keyName, String keyPairId) {
ensureDefaultResources(region);
boolean byId = keyPairId != null && !keyPairId.isEmpty();
- // scan() returns detached copies, so each match is resolved to its store key and deleted
- // through the backend; mutating the scan result does not touch the store.
+ // scan() returns a new list, so each match is resolved to its store key and deleted through
+ // the backend; removing it from the list would not touch the store. Each delete holds
+ // the lock tag writes take on the key pair, so a tag write that has read the key pair cannot
+ // write it back once it is deleted.
List<KeyPair> matches = keyPairs.scan(k -> true).stream()
.filter(k -> region.equals(k.getRegion()))
.filter(k -> byId ? keyPairId.equals(k.getKeyPairId()) : keyName != null && keyName.equals(k.getKeyName()))
.toList();
for (KeyPair match : matches) {
- keyPairs.delete(key(region, match.getKeyPairId()));
+ String storeKey = key(region, match.getKeyPairId());
+ synchronized (lockFor(storeKey)) {
+ keyPairs.delete(storeKey);
+ }
}
return matches.isEmpty() ? null : matches.getFirst();
}
@@ -8256,7 +8261,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
kp.setPublicKey(imported.openSshPublicKey());
kp.setCreateTime(Instant.now());
kp.setRegion(region);
- keyPairs.put(key(region, keyPairId), kp);
+ storeNewKeyPair(region, kp);
return kp;
}
@@ -8344,6 +8349,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
+ /**
+ * Stores a key pair CreateKeyPair or ImportKeyPair built, unless its name was taken after they
+ * checked it. The check and the write run under one lock on the region and name, so of two requests
+ * for one name only one stores a key pair and the other is refused as a duplicate. No other lock of
+ * this service is taken while it is held; the store's own locks, taken inside it, never lead back to
+ * one. The callers' own earlier check still refuses a taken name before a key is generated for it.
+ */
+ private void storeNewKeyPair(String region, KeyPair keyPair) {
+ synchronized (lockFor(key(region, "key-name:" + keyPair.getKeyName()))) {
+ rejectDuplicateKeyName(region, keyPair.getKeyName());
+ keyPairs.put(key(region, keyPair.getKeyPairId()), keyPair);
+ }
+ }
+
/** KeyType and KeyFormat take only the values AWS's model lists; each other value is reported. */
private static void requireKeyTypeAndFormat(String keyType, String keyFormat) {
List<String> violations = new ArrayList<>();
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
index 0003dc1844..5fe05fa960 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java
@@ -61,6 +61,7 @@ import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
import io.github.hectorvent.floci.services.ec2.model.VpcEndpointSubnetConfiguration;
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
+import io.github.hectorvent.floci.testing.ParkingStore;
import jakarta.ws.rs.core.MultivaluedHashMap;
import org.awaitility.Awaitility;
import org.bouncycastle.openssl.PEMKeyPair;
@@ -78,6 +79,8 @@ import org.mockito.MockedStatic;
import java.io.IOException;
import java.io.StringReader;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadInfo;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
@@ -98,6 +101,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
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;
@@ -120,6 +124,7 @@ import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.TRUNCAT
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -4810,6 +4815,127 @@ class Ec2ServiceTest {
assertEquals("InvalidKeyPair.Duplicate", error.getErrorCode());
}
+ /**
+ * A second CreateKeyPair or ImportKeyPair for a name, arriving after the first has found the name
+ * free but before its key pair is stored, is refused as a duplicate. The store parks the first
+ * request's write until the second has finished or waits on a lock the first holds, which forces
+ * that interleaving on every run.
+ */
+ @ParameterizedTest
+ @CsvSource({"create, create", "import, import", "create, import", "import, create"})
+ void secondRequestForAKeyPairNameBeingStoredIsRefused(String first, String second) throws Exception {
+ ParkingStore<KeyPair> parking = new ParkingStore<>();
+ AccountAwareStorageBackend<KeyPair> keyPairStore = new AccountAwareStorageBackend<>(parking, null, "000000000000");
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class),
+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
+ new InMemoryStorageFactory(Map.of("ec2-key-pairs.json", keyPairStore)));
+ String publicKey = Ec2KeyMaterial.generateRsa().openSshPublicKey();
+ Function<String, KeyPair> request = action -> "create".equals(action)
+ ? service.createKeyPair("us-east-1", "contested", "ed25519", null)
+ : service.importKeyPair("us-east-1", "contested", publicKey);
+ AtomicReference<Thread> firstWorker = new AtomicReference<>();
+ AtomicReference<Thread> secondWorker = new AtomicReference<>();
+ parking.parkNextWrite();
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ try {
+ Future<KeyPair> firstResult = workers.submit(() -> {
+ firstWorker.set(Thread.currentThread());
+ return request.apply(first);
+ });
+ assertTrue(parking.awaitParked(), "the first request never stored its key pair");
+ Future<KeyPair> secondResult = workers.submit(() -> {
+ secondWorker.set(Thread.currentThread());
+ return request.apply(second);
+ });
+ Awaitility.await("the second request to finish or to wait in storeNewKeyPair")
+ .atMost(Duration.ofSeconds(30)).until(() -> secondResult.isDone()
+ || isBlockedIn(secondWorker.get(), "storeNewKeyPair", firstWorker.get()));
+ parking.release();
+
+ KeyPair stored = firstResult.get(30, TimeUnit.SECONDS);
+ ExecutionException refusal = assertThrows(ExecutionException.class,
+ () -> secondResult.get(30, TimeUnit.SECONDS), "both requests got the name");
+ AwsException duplicate = assertInstanceOf(AwsException.class, refusal.getCause());
+ assertEquals("InvalidKeyPair.Duplicate", duplicate.getErrorCode());
+ assertEquals("The keypair 'contested' already exists", duplicate.getMessage());
+ assertEquals(400, duplicate.getHttpStatus());
+ assertEquals(List.of(stored.getKeyPairId()), service.describeKeyPairs("us-east-1", List.of(), List.of())
+ .stream().map(KeyPair::getKeyPairId).toList());
+ } finally {
+ parking.release();
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ /**
+ * A DeleteKeyPair arriving while a tag write has read the key pair and not yet written it back
+ * waits for that write, so the tag write cannot put back the key pair the delete removes, and the
+ * freed name then goes to one new key pair. Armed once the key pair is created, the store parks the
+ * next write, which is the tag write's, until the delete has finished or waits on a lock the tag
+ * write holds.
+ */
+ @Test
+ void deleteKeyPairWaitsForATagWriteOnTheKeyPair() throws Exception {
+ ParkingStore<KeyPair> parking = new ParkingStore<>();
+ AccountAwareStorageBackend<KeyPair> keyPairStore = new AccountAwareStorageBackend<>(parking, null, "000000000000");
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class),
+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
+ new InMemoryStorageFactory(Map.of("ec2-key-pairs.json", keyPairStore)));
+ KeyPair original = service.createKeyPair("us-east-1", "retagged", "ed25519", null);
+ parking.parkNextWrite();
+ AtomicReference<Thread> tagWorker = new AtomicReference<>();
+ AtomicReference<Thread> deleteWorker = new AtomicReference<>();
+ ExecutorService workers = Executors.newFixedThreadPool(2);
+ try {
+ Future<?> tagging = workers.submit(() -> {
+ tagWorker.set(Thread.currentThread());
+ service.createTags("us-east-1", List.of(original.getKeyPairId()), List.of(new Tag("Team", "blue")));
+ });
+ assertTrue(parking.awaitParked(), "the tag write never stored the key pair");
+ Future<KeyPair> deleting = workers.submit(() -> {
+ deleteWorker.set(Thread.currentThread());
+ return service.deleteKeyPair("us-east-1", "retagged", null);
+ });
+ Awaitility.await("the delete to finish or to wait in deleteKeyPair")
+ .atMost(Duration.ofSeconds(30)).until(() -> deleting.isDone()
+ || isBlockedIn(deleteWorker.get(), "deleteKeyPair", tagWorker.get()));
+ parking.release();
+ tagging.get(30, TimeUnit.SECONDS);
+
+ assertEquals(original.getKeyPairId(), deleting.get(30, TimeUnit.SECONDS).getKeyPairId());
+ assertTrue(service.describeKeyPairs("us-east-1", List.of(), List.of()).isEmpty(),
+ "the tag write put the deleted key pair back");
+ KeyPair recreated = service.createKeyPair("us-east-1", "retagged", "ed25519", null);
+ assertEquals(List.of(recreated.getKeyPairId()), service.describeKeyPairs("us-east-1", List.of(), List.of())
+ .stream().map(KeyPair::getKeyPairId).toList());
+ } finally {
+ parking.release();
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ /**
+ * Whether {@code waiter} waits, in the named Ec2Service method, to enter a monitor {@code owner}
+ * holds. The method is named on purpose: a wait anywhere else may not be at the lock under test, so
+ * the race tests time out rather than pass without exercising it. Moving that lock into another
+ * method means updating the name here.
+ */
+ private static boolean isBlockedIn(Thread waiter, String method, Thread owner) {
+ if (waiter == null) {
+ return false;
+ }
+ ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(waiter.threadId(), 1);
+ return info != null && info.getThreadState() == Thread.State.BLOCKED
+ && info.getLockOwnerId() == owner.threadId()
+ && info.getStackTrace().length == 1
+ && Ec2Service.class.getName().equals(info.getStackTrace()[0].getClassName())
+ && method.equals(info.getStackTrace()[0].getMethodName());
+ }
+
@Test
void describeKeyPairsThrowsNotFoundForMissingName() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),