fix(ec2): make CreateVolume idempotent on its client token (#8301)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-14 11:12:45 -04:00
1 parent fdb4a811ba
commit 2337c34ef9
12 files changed
+489 -146

No files matched your search

@@ -0,0 +1,67 @@
package io.floci.aws.services.ec2;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.acm.AcmService;
import io.floci.aws.services.ec2.model.ClientVpnEndpoint;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.stream.Stream;
import static io.floci.aws.testing.Ec2ServiceFixtures.ACCOUNT;
import static io.floci.aws.testing.Ec2ServiceFixtures.mockModeService;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.Mockito.mock;
/**
* CreateClientVpnEndpoint's ClientToken: a retry with the token returns the endpoint the first call
* made, and a call with no token, or a blank one, makes an endpoint of its own, as the other EC2
* creates that take a token do.
*/
class Ec2ClientVpnClientTokenTest {
private static final String REGION = "us-east-1";
private final Ec2ClientVpnService vpn = new Ec2ClientVpnService(
AccountAwareStorageBackend.<ClientVpnEndpoint>inMemory(ACCOUNT), mockModeService(), mock(AcmService.class));
@Test
void aRetryWithTheSameTokenReturnsTheFirstEndpoint() {
String first = createEndpoint("4f9a8d0c2b7e41f3");
assertEquals(first, createEndpoint("4f9a8d0c2b7e41f3"));
assertEquals(List.of(first), endpointIds());
}
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = " ")
void aCreateWithoutATokenMakesAnEndpointOfItsOwn(String token) {
String first = createEndpoint(token);
String second = createEndpoint(token);
assertNotEquals(first, second);
assertEquals(Stream.of(first, second).sorted().toList(), endpointIds());
}
/** A certificate-authenticated endpoint with every optional member left to AWS's default. */
private String createEndpoint(String clientToken) {
ClientVpnEndpoint.Authentication certificate = new ClientVpnEndpoint.Authentication();
certificate.setType("certificate-authentication");
certificate.setClientRootCertificateChain("arn:aws:acm:us-east-1:000000000000:certificate/client-root");
Ec2ClientVpnService.EndpointRequest request = new Ec2ClientVpnService.EndpointRequest("172.16.0.0/22",
"arn:aws:acm:us-east-1:000000000000:certificate/server", List.of(certificate), false,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
clientToken);
return vpn.createEndpoint(REGION, request, List.of()).getClientVpnEndpointId();
}
private List<String> endpointIds() {
return vpn.describeEndpoints(REGION, List.of()).stream()
.map(ClientVpnEndpoint::getClientVpnEndpointId).sorted().toList();
}
}
@@ -0,0 +1,172 @@
package io.floci.aws.services.ec2;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.ec2.model.Volume;
import io.floci.aws.testing.InMemoryStorageFactory;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Stream;
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.ok;
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.queryHandler;
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.send;
import static io.floci.aws.testing.Ec2ServiceFixtures.ACCOUNT;
import static io.floci.aws.testing.Ec2ServiceFixtures.mockModeService;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* CreateVolume's ClientToken, sent through the Query handler to a real service, as the EBS CSI
* driver sends it when it retries. A retry with the token and the request the first call made
* returns that call's volume and creates no other; the token with another parameter or other
* creation tags fails with IdempotentParameterMismatch; without a token every call creates a volume.
*/
class Ec2CreateVolumeClientTokenTest {
private static final String TOKEN = "4f9a8d0c2b7e41f3a6c5d8e9b0a1c2d3";
private static final String MISMATCH = "Parameters differ from the previous request with this ClientToken.";
private final Ec2QueryHandler handler = queryHandler(mockModeService());
@Test
void aRetryWithTheSameTokenAndParametersReturnsTheFirstVolume() {
String first = volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1"));
assertEquals(first, volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1")));
assertEquals(List.of(first), describedVolumeIds());
}
@Test
void theSameTokenWithAnotherSizeOrOtherTagsIsAMismatch() {
String first = volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1"));
assertMismatch(createVolume(TOKEN, "us-east-1a", "11", "pvc-1"));
assertMismatch(createVolume(TOKEN, "us-east-1a", "10", "pvc-2"));
assertEquals(List.of(first), describedVolumeIds());
}
@Test
void withoutATokenEveryCallCreatesAVolume() {
String first = volumeId(createVolume(null, "us-east-1a", "10", "pvc-1"));
String second = volumeId(createVolume(null, "us-east-1a", "10", "pvc-1"));
assertNotEquals(first, second);
assertEquals(Stream.of(first, second).sorted().toList(), describedVolumeIds());
}
/** The guide exempts the Availability Zone from the mismatch check: the token is zonal. */
@Test
void theSameTokenInAnotherZoneCreatesThatZonesVolume() {
String first = volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1"));
String other = volumeId(createVolume(TOKEN, "us-east-1b", "10", "pvc-1"));
assertNotEquals(first, other);
assertEquals(Stream.of(first, other).sorted().toList(), describedVolumeIds());
assertEquals(other, volumeId(createVolume(TOKEN, "us-east-1b", "10", "pvc-1")));
}
/** The retry is compared with the first request, not with the volume as it is now. */
@Test
void aRetryStillMatchesAfterTheVolumeWasModifiedAndTagged() {
String first = volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1"));
ok(handler, "ModifyVolume", "VolumeId", first, "Size", "20");
ok(handler, "CreateTags", "ResourceId.1", first, "Tag.1.Key", "Team", "Tag.1.Value", "storage");
assertEquals(first, volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1")));
assertEquals(List.of(first), describedVolumeIds());
}
/** Creates that race with one token are held apart by the token's lock, so one volume is made. */
@Test
void concurrentCreatesWithOneClientTokenMakeOneVolume() throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(8);
try {
for (int round = 0; round < 50; round++) {
Ec2QueryHandler racing = queryHandler(mockModeService());
CountDownLatch go = new CountDownLatch(1);
List<Future<String>> ids = new ArrayList<>();
for (int i = 0; i < 8; i++) {
ids.add(pool.submit(() -> {
go.await();
return volumeId(createVolume(racing, TOKEN, "us-east-1a", "10", "pvc-1"));
}));
}
go.countDown();
Set<String> distinct = ConcurrentHashMap.newKeySet();
for (Future<String> id : ids) {
distinct.add(id.get());
}
assertEquals(1, distinct.size(), "round " + round + ": " + distinct);
assertEquals(List.copyOf(distinct), XmlParser.extractAll(ok(racing, "DescribeVolumes"), "volumeId"));
}
} finally {
pool.shutdownNow();
}
}
/** Without a token there is nothing to replay, so a create does not read the volume store. */
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = " ")
void aCreateWithoutATokenDoesNotScanTheVolumes(String token) {
AccountAwareStorageBackend<Volume> volumes = spy(AccountAwareStorageBackend.<Volume>inMemory(ACCOUNT));
Ec2QueryHandler tokenless = queryHandler(mockModeService(new InMemoryStorageFactory(ACCOUNT)
.withStore("ec2-volumes.json", volumes)));
clearInvocations(volumes);
volumeId(createVolume(tokenless, token, "us-east-1a", "10", "pvc-1"));
verify(volumes, never()).scan(any());
}
private Response createVolume(String token, String zone, String size, String name) {
return createVolume(handler, token, zone, size, name);
}
/** A gp3 CreateVolume tagged with {@code Name}, as the CSI driver sends it; a null token is left out. */
private static Response createVolume(Ec2QueryHandler handler, String token, String zone, String size,
String name) {
List<String> params = new ArrayList<>(List.of("AvailabilityZone", zone, "Size", size, "VolumeType", "gp3",
"TagSpecification.1.ResourceType", "volume",
"TagSpecification.1.Tag.1.Key", "Name", "TagSpecification.1.Tag.1.Value", name));
if (token != null) {
params.addAll(List.of("ClientToken", token));
}
return send(handler, "CreateVolume", params.toArray(String[]::new));
}
private List<String> describedVolumeIds() {
return XmlParser.extractAll(ok(handler, "DescribeVolumes"), "volumeId").stream().sorted().toList();
}
private static String volumeId(Response response) {
String body = String.valueOf(response.getEntity());
assertEquals(200, response.getStatus(), body);
return XmlParser.extractFirst(body, "volumeId", null);
}
private static void assertMismatch(Response response) {
String body = String.valueOf(response.getEntity());
assertEquals(400, response.getStatus(), body);
assertEquals("IdempotentParameterMismatch", XmlParser.extractFirst(body, "Code", null), body);
assertEquals(MISMATCH, XmlParser.extractFirst(body, "Message", null), body);
}
}
@@ -2,13 +2,10 @@ package io.floci.aws.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import io.floci.aws.testing.Ec2QueryHandlerFixtures;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -24,6 +21,7 @@ import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.queryHandler;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -60,9 +58,7 @@ class Ec2RepeatedFilterNamesTest {
Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
service = new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
new AmiImageResolver(imageCatalog), imageCatalog, new Ec2InstanceTypeCatalog(), new MemoryFactory());
handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class), mock(FlowLogService.class),
mock(Ec2EbsEncryptionService.class), mock(Ec2BlockPublicAccessService.class),
mock(Ec2IpamService.class), new RegionResolver(REGION, "000000000000"));
handler = queryHandler(service);
}
/**
@@ -704,14 +700,7 @@ class Ec2RepeatedFilterNamesTest {
}
private String ok(String action, String... params) {
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
for (int i = 0; i < params.length; i += 2) {
form.add(params[i], params[i + 1]);
}
Response response = handler.handle(action, form, REGION);
String body = String.valueOf(response.getEntity());
assertEquals(200, response.getStatus(), action + ": " + body);
return body;
return Ec2QueryHandlerFixtures.ok(handler, action, params);
}
private String first(String xml, String element) {
@@ -3,7 +3,6 @@ package io.floci.aws.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.core.storage.PersistentStorage;
import io.floci.aws.core.storage.StorageBackend;
@@ -35,8 +34,6 @@ import io.floci.aws.services.ec2.model.Volume;
import io.floci.aws.services.ec2.model.Vpc;
import io.floci.aws.services.ec2.model.VpcEndpoint;
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -49,6 +46,9 @@ import java.util.Map;
import static io.floci.aws.services.ec2.Ec2KeyPairFixtures.ED25519_FINGERPRINT;
import static io.floci.aws.services.ec2.Ec2KeyPairFixtures.ED25519_KEY;
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.ok;
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.queryHandler;
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.send;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -765,10 +765,7 @@ class Ec2ServicePersistenceTest {
Map.of("key-type", List.of("ed25519"), "tag:Team", List.of("blue"))).stream()
.map(KeyPair::getKeyName).toList());
String xml = (String) new Ec2QueryHandler(restarted, mock(EmulatorConfig.class), mock(FlowLogService.class),
mock(Ec2EbsEncryptionService.class), mock(Ec2BlockPublicAccessService.class),
mock(Ec2IpamService.class), new RegionResolver(REGION, "000000000000"))
.handle("DescribeKeyPairs", new MultivaluedHashMap<>(), REGION).getEntity();
String xml = (String) send(queryHandler(restarted), "DescribeKeyPairs").getEntity();
assertTrue(xml.contains("<keyType>rsa</keyType>"), xml);
assertTrue(xml.contains("<keyType>ed25519</keyType>"), xml);
assertFalse(xml.contains("<createTime>"), xml);
@@ -787,6 +784,20 @@ class Ec2ServicePersistenceTest {
assertEquals(List.of(keyArn), XmlParser.extractAll(described, "kmsKeyId"), described);
}
/** The token and the request it came with are stored, so a retry after a restart still matches. */
@Test
void volumeClientTokenSurvivesRestart(@TempDir Path dir) {
String[] request = {"AvailabilityZone", "us-east-1a", "Size", "1", "ClientToken", "restart-token",
"TagSpecification.1.ResourceType", "volume",
"TagSpecification.1.Tag.1.Key", "Name", "TagSpecification.1.Tag.1.Value", "pvc-1"};
String volumeId = XmlParser.extractFirst(query(newService(dir), "CreateVolume", request), "volumeId", null);
String retried = query(newService(dir), "CreateVolume", request);
assertEquals(volumeId, XmlParser.extractFirst(retried, "volumeId", null), retried);
assertEquals(List.of(volumeId), XmlParser.extractAll(query(newService(dir), "DescribeVolumes"), "volumeId"));
}
/**
* A volume store as Floci wrote it before a volume kept its KMS key: an encrypted volume
* attached to an instance and an unencrypted one. Both load as they were stored, and
@@ -867,18 +878,7 @@ class Ec2ServicePersistenceTest {
}
private static String query(Ec2Service service, String action, String... params) {
MultivaluedHashMap<String, String> form = new MultivaluedHashMap<>();
for (int i = 0; i < params.length; i += 2) {
form.add(params[i], params[i + 1]);
}
Response response = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class),
mock(Ec2BlockPublicAccessService.class), mock(Ec2IpamService.class),
new RegionResolver(REGION, "000000000000"))
.handle(action, form, REGION);
String body = String.valueOf(response.getEntity());
assertEquals(200, response.getStatus(), action + ": " + body);
return body;
return ok(queryHandler(service), action, params);
}
private static String jsonString(String value) {
@@ -2,14 +2,11 @@ package io.floci.aws.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import io.floci.aws.testing.Ec2QueryHandlerFixtures;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -19,6 +16,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.queryHandler;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.mock;
@@ -55,9 +53,7 @@ class Ec2VolumeKmsKeyIdTest {
Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), new AmiImageResolver(imageCatalog), imageCatalog,
new Ec2InstanceTypeCatalog(), new MemoryFactory());
handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class), mock(FlowLogService.class),
mock(Ec2EbsEncryptionService.class), mock(Ec2BlockPublicAccessService.class),
mock(Ec2IpamService.class), new RegionResolver(REGION, "000000000000"));
handler = queryHandler(service);
}
/** Each form CreateVolume documents for KmsKeyId is kept as the caller gave it. */
@@ -126,14 +122,7 @@ class Ec2VolumeKmsKeyIdTest {
}
private String ok(String action, String... params) {
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
for (int i = 0; i < params.length; i += 2) {
form.add(params[i], params[i + 1]);
}
Response response = handler.handle(action, form, REGION);
String body = String.valueOf(response.getEntity());
assertEquals(200, response.getStatus(), action + ": " + body);
return body;
return Ec2QueryHandlerFixtures.ok(handler, action, params);
}
private static String first(String xml, String element) {
@@ -0,0 +1,52 @@
package io.floci.aws.testing;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.ec2.Ec2BlockPublicAccessService;
import io.floci.aws.services.ec2.Ec2EbsEncryptionService;
import io.floci.aws.services.ec2.Ec2IpamService;
import io.floci.aws.services.ec2.Ec2QueryHandler;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.FlowLogService;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
/**
* EC2 Query requests sent straight to an {@link Ec2QueryHandler} in {@link #REGION}, for unit tests
* that check what a call answers without HTTP. The handler's other services are mocks.
*/
public final class Ec2QueryHandlerFixtures {
public static final String REGION = "us-east-1";
private Ec2QueryHandlerFixtures() {
}
/** A handler over {@code service} for {@link #REGION} and {@link Ec2ServiceFixtures#ACCOUNT}. */
public static Ec2QueryHandler queryHandler(Ec2Service service) {
return new Ec2QueryHandler(service, mock(EmulatorConfig.class), mock(FlowLogService.class),
mock(Ec2EbsEncryptionService.class), mock(Ec2BlockPublicAccessService.class),
mock(Ec2IpamService.class), new RegionResolver(REGION, Ec2ServiceFixtures.ACCOUNT));
}
/** Sends {@code action} with {@code params}, given as name and value pairs, and returns the answer. */
public static Response send(Ec2QueryHandler handler, String action, String... params) {
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
for (int i = 0; i < params.length; i += 2) {
form.add(params[i], params[i + 1]);
}
return handler.handle(action, form, REGION);
}
/** As {@link #send}, asserting that the call succeeds, and returns the response body. */
public static String ok(Ec2QueryHandler handler, String action, String... params) {
Response response = send(handler, action, params);
String body = String.valueOf(response.getEntity());
assertEquals(200, response.getStatus(), action + ": " + body);
return body;
}
}