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:
Jackson Price authored and GitHub committed 2026-10-26 11:20:10 -04:00
1 parent ec13eda221
commit 986117a45c
4 files changed
+237 -6

No files matched your search

@@ -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));
}
}
}
}
+4 -1
View File
@@ -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`,
@@ -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<>();
@@ -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),