fix(ec2): honour DryRun on the rest of the instance calls (#8289)

* fix(ec2): honour DryRun on the rest of the instance calls
* refactor(ec2): launch a Spot request's instances and check its dry run through one call
* test(ec2): compare instance snapshots with their reservation ids, now stable on main
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-14 10:56:30 -04:00
1 parent b2bdb2bbe9
commit c407c82f8f
5 files changed
+334 -63

No files matched your search

@@ -9,13 +9,17 @@ import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.AttributeValue;
import software.amazon.awssdk.services.ec2.model.Instance;
import software.amazon.awssdk.services.ec2.model.InstanceType;
import software.amazon.awssdk.services.ec2.model.Volume;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.BiConsumer;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static org.awaitility.Awaitility.await;
@@ -90,38 +94,53 @@ class Ec2DryRunIamIntegrationTest {
@Test
void aTerminateDryRunNeedsTheCallersCurrentPermission() throws Exception {
assertAnInstanceDryRunNeedsTheCallersCurrentPermission("TerminateInstances",
(caller, instanceId) -> caller.terminateInstances(r -> r.instanceIds(instanceId).dryRun(true)));
}
@Test
void aModifyInstanceAttributeDryRunNeedsTheCallersCurrentPermission() throws Exception {
assertAnInstanceDryRunNeedsTheCallersCurrentPermission("ModifyInstanceAttribute",
(caller, instanceId) -> caller.modifyInstanceAttribute(r -> r.instanceId(instanceId)
.instanceType(AttributeValue.builder().value("t3.small").build()).dryRun(true)));
}
/**
* A caller the policy allows {@code action} gets DryRunOperation for {@code dryRun} on a running instance,
* and UnauthorizedOperation once the policy is removed; the instance is unchanged either way.
*/
private void assertAnInstanceDryRunNeedsTheCallersCurrentPermission(String action,
BiConsumer<Ec2Client, String> dryRun) throws Exception {
String policy = """
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*"
"Effect":"Allow","Action":"ec2:%s","Resource":"*"
}]}
""";
""".formatted(action);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint);
SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "instance-dryrun-allowed-", "instances",
policy);
SignedIamUsers.User user = SignedIamUsers.createUser(endpoint,
"dryrun-" + action.toLowerCase(Locale.ROOT) + "-", "instances", policy);
Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(),
user.secretAccessKey(), Region.US_EAST_1, endpoint)) {
String instanceId = admin.runInstances(r -> r.imageId("ami-1234567890abcdef0")
.instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1)).instances().get(0).instanceId();
try {
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100))
.untilAsserted(() -> assertEquals("running", state(admin, instanceId)));
.untilAsserted(() -> assertEquals("running", instance(admin, instanceId).state().nameAsString()));
Instance before = instance(admin, instanceId);
assertAwsError("DryRunOperation", 412,
() -> caller.terminateInstances(r -> r.instanceIds(instanceId).dryRun(true)));
assertAwsError("DryRunOperation", 412, () -> dryRun.accept(caller, instanceId));
SignedIamUsers.iam(endpoint, "DeleteUserPolicy", Map.of("UserName", user.name(), "PolicyName", "instances"))
.then().statusCode(200);
assertAwsError("UnauthorizedOperation", 403,
() -> caller.terminateInstances(r -> r.instanceIds(instanceId).dryRun(true)));
assertAwsError("UnauthorizedOperation", 403, () -> dryRun.accept(caller, instanceId));
assertEquals("running", state(admin, instanceId));
assertEquals(before, instance(admin, instanceId));
} finally {
admin.terminateInstances(r -> r.instanceIds(instanceId));
}
}
}
private static String state(Ec2Client client, String instanceId) {
return client.describeInstances(r -> r.instanceIds(instanceId)).reservations().get(0).instances().get(0)
.state().nameAsString();
private static Instance instance(Ec2Client client, String instanceId) {
return client.describeInstances(r -> r.instanceIds(instanceId)).reservations().get(0).instances().get(0);
}
}
@@ -9,6 +9,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Duration;
@@ -16,16 +17,18 @@ import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Stream;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* DryRun on StartInstances, StopInstances, RebootInstances and TerminateInstances is answered with
* DryRunOperation and HTTP 412 once every instance it names has passed the checks the real call makes, and
* it changes no instance's state. A dry run naming an instance the real call would refuse keeps that call's
* error, even when it also names one it would accept.
* DryRun on the instance calls is answered with DryRunOperation and HTTP 412 once the request has passed
* the checks the real call makes, and changes nothing: StartInstances, StopInstances, RebootInstances and
* TerminateInstances, monitoring, metadata options and attributes, the EBS encryption defaults, and Spot
* requests. A dry run the real call would refuse keeps that call's error, even when it also names an
* instance it would accept.
*/
@QuarkusTest
class Ec2InstanceDryRunIntegrationTest {
@@ -33,6 +36,8 @@ class Ec2InstanceDryRunIntegrationTest {
/** Each test works in an account of its own, so DescribeInstances lists only the fixture's instances. */
private static final AtomicLong ACCOUNTS = new AtomicLong(726200000000L);
private static final String MISSING_INSTANCE = "i-0123456789abcdef0";
private static final String IMAGE = "ami-1234567890abcdef0";
private static final String USER_DATA = "IyEvYmluL3NoCg==";
private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item";
private String account;
@@ -117,8 +122,126 @@ class Ec2InstanceDryRunIntegrationTest {
assertEquals(before, states());
}
/** Requests the real call accepts, for the instance calls other than start, stop, reboot and terminate. */
static Stream<String[]> otherInstanceCalls() {
return Stream.of(
new String[] {"MonitorInstances", "InstanceId.1={running}"},
new String[] {"UnmonitorInstances", "InstanceId.1={running}"},
new String[] {"ModifyInstanceMetadataOptions", "InstanceId={running} HttpTokens=required"},
new String[] {"ModifyInstanceAttribute", "InstanceId={stopped} InstanceType.Value=t3.small"},
new String[] {"ModifyInstanceAttribute", "InstanceId={stopped} UserData.Value=" + USER_DATA},
new String[] {"ModifyInstanceAttribute", "InstanceId={running} SourceDestCheck.Value=false"},
new String[] {"EnableEbsEncryptionByDefault", ""},
new String[] {"DisableEbsEncryptionByDefault", ""},
new String[] {"ModifyEbsDefaultKmsKeyId", "KmsKeyId=alias/dry-run"},
new String[] {"ResetEbsDefaultKmsKeyId", ""},
new String[] {"RequestSpotInstances", "InstanceCount=2 LaunchSpecification.ImageId=" + IMAGE
+ " LaunchSpecification.InstanceType=t3.micro"});
}
@ParameterizedTest
@MethodSource("otherInstanceCalls")
void aDryRunOfAnotherInstanceCallIsAnsweredWithDryRunOperationAndChangesNothing(String action, String params) {
String before = snapshot();
request(action, params(params)).formParam("DryRun", "true").post("/").then()
.statusCode(412)
.body("Response.Errors.Error.Code", equalTo("DryRunOperation"));
assertEquals(before, snapshot());
}
@ParameterizedTest
@MethodSource("otherInstanceCalls")
void aDryRunValueThatIsNotABooleanIsRefusedByTheOtherInstanceCalls(String action, String params) {
String before = snapshot();
request(action, params(params)).formParam("DryRun", "maybe").post("/").then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"))
.body("Response.Errors.Error.Message", equalTo("DryRun is not a valid boolean."));
assertEquals(before, snapshot());
}
/** The real call refuses each of these; its dry run keeps the same error, and neither changes anything. */
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"MonitorInstances | InstanceId.1=" + MISSING_INSTANCE + " | InvalidInstanceID.NotFound",
"ModifyInstanceMetadataOptions | InstanceId={running} HttpTokens=sometimes | InvalidParameterValue",
"ModifyInstanceAttribute | InstanceId={running} UserData.Value=" + USER_DATA + " | IncorrectInstanceState",
"ModifyInstanceAttribute | InstanceId={stopped} UserData.Value=%%% | InvalidParameterValue",
"ModifyInstanceAttribute | InstanceId={stopped} GroupId.1=sg-0123456789abcdef0 | InvalidGroup.NotFound",
"ModifyEbsDefaultKmsKeyId | | MissingParameter",
"CancelSpotInstanceRequests | SpotInstanceRequestId.1=sir-01234567 | InvalidSpotInstanceRequestID.NotFound"
})
void aDryRunTheRealCallWouldRefuseKeepsItsError(String action, String params, String code) {
String before = snapshot();
for (String dryRun : List.of("true", "false")) {
request(action, params(params)).formParam("DryRun", dryRun).post("/").then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo(code));
}
assertEquals(before, snapshot());
}
@Test
void aDryRunCancelOfASpotRequestCancelsNothing() {
XmlPath requested = ec2("RequestSpotInstances", "LaunchSpecification.ImageId", IMAGE,
"LaunchSpecification.InstanceType", "t3.micro");
String request = "RequestSpotInstancesResponse.spotInstanceRequestSet.item";
String requestId = requested.getString(request + ".spotInstanceRequestId");
String instanceId = requested.getString(request + ".instanceId");
try {
awaitState(instanceId, "running");
String before = snapshot();
request("CancelSpotInstanceRequests", "SpotInstanceRequestId.1", requestId)
.formParam("DryRun", "true").post("/").then()
.statusCode(412)
.body("Response.Errors.Error.Code", equalTo("DryRunOperation"));
assertEquals(before, snapshot());
} finally {
ec2("CancelSpotInstanceRequests", "SpotInstanceRequestId.1", requestId);
ec2("TerminateInstances", "InstanceId.1", instanceId);
}
}
/**
* Everything the instance calls can change in the test's account, as the describe calls report it:
* the instances, the stopped instance's user data, the EBS encryption defaults and the Spot requests.
*/
private String snapshot() {
return String.join("\n",
body("DescribeInstances"),
body("DescribeInstanceAttribute", "InstanceId", stoppedId, "Attribute", "userData"),
body("GetEbsEncryptionByDefault"),
body("GetEbsDefaultKmsKeyId"),
body("DescribeSpotInstanceRequests"));
}
/** A describe call's answer without the request id, the one part that differs on every call. */
private String body(String action, String... params) {
return request(action, params).post("/").then().statusCode(200).extract().asString()
.replaceAll("<requestId>[^<]*</requestId>", "");
}
/** {@code Key=Value} pairs separated by spaces, with {running} and {stopped} standing for the fixture's ids. */
private String[] params(String spec) {
if (spec == null || spec.isBlank()) {
return new String[0];
}
return Stream.of(spec.trim().split(" +"))
.flatMap(pair -> Stream.of(pair.split("=", 2)))
.map(part -> part.replace("{running}", runningId).replace("{stopped}", stoppedId))
.toArray(String[]::new);
}
private String launch() {
String instanceId = ec2("RunInstances", "ImageId", "ami-1234567890abcdef0", "InstanceType", "t3.micro",
String instanceId = ec2("RunInstances", "ImageId", IMAGE, "InstanceType", "t3.micro",
"MinCount", "1", "MaxCount", "1").getString("RunInstancesResponse.instancesSet.item.instanceId");
awaitState(instanceId, "running");
return instanceId;