mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): honour DryRun on the instance start, stop, reboot and terminate calls (#8252)
This commit is contained in:
1 parent
4313fc5fac
commit
fa9190e110
5 files changed
+329
-44
No files matched your search
+29
@@ -654,6 +654,35 @@ class Ec2CapacityReservationAssociationServiceTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A dry-run start admits its stopped instances into their reservation as the real start does,
|
||||
* the whole batch counted, and records nothing: one of two fits the free slot, both do not.
|
||||
*/
|
||||
@Test
|
||||
void aDryRunRestartIsAdmittedAsTheRealOneAndRecordsNothing() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
CapacityReservation capacity = fixture.create(1);
|
||||
Instance first = fixture.launch(capacity.getCapacityReservationId());
|
||||
fixture.service.stopInstances(REGION, List.of(first.getInstanceId()));
|
||||
Instance second = fixture.launch(capacity.getCapacityReservationId());
|
||||
fixture.service.stopInstances(REGION, List.of(second.getInstanceId()));
|
||||
|
||||
assertEquals("DryRunOperation", assertThrows(AwsException.class, () -> fixture.service
|
||||
.startInstances(REGION, List.of(first.getInstanceId()), true)).getErrorCode());
|
||||
AwsException failure = assertThrows(AwsException.class, () -> fixture.service
|
||||
.startInstances(REGION, List.of(first.getInstanceId(), second.getInstanceId()), true));
|
||||
assertEquals("ReservationCapacityExceeded", failure.getErrorCode());
|
||||
assertEquals("The targeted Capacity Reservation has insufficient available capacity.", failure.getMessage());
|
||||
|
||||
assertEquals(List.of(), fixture.describe(capacity).getInstanceIds());
|
||||
assertEquals(1, fixture.describe(capacity).getAvailableInstanceCount());
|
||||
assertEquals(List.of("stopped", "stopped"), fixture.service.describeInstances(REGION,
|
||||
List.of(first.getInstanceId(), second.getInstanceId()), Map.of()).stream()
|
||||
.flatMap(reservation -> reservation.getInstances().stream())
|
||||
.map(instance -> instance.getState().getName()).toList());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reservationOnlyLaunchDoesNotFallBackToOnDemand() {
|
||||
try (Fixture fixture = new Fixture("memory", directory)) {
|
||||
|
||||
@@ -9,19 +9,22 @@ 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.InstanceType;
|
||||
import software.amazon.awssdk.services.ec2.model.Volume;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* A dry run checks the caller's permission and changes nothing else: under IAM enforcement a caller the
|
||||
* policy does not allow gets UnauthorizedOperation for a dry run, as for the real call, and one it allows
|
||||
* gets DryRunOperation, with nothing created or deleted either way.
|
||||
* gets DryRunOperation, with nothing created, deleted or terminated either way.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
@@ -84,4 +87,41 @@ class Ec2DryRunIamIntegrationTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTerminateDryRunNeedsTheCallersCurrentPermission() throws Exception {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*"
|
||||
}]}
|
||||
""";
|
||||
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint);
|
||||
SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "instance-dryrun-allowed-", "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)));
|
||||
|
||||
assertAwsError("DryRunOperation", 412,
|
||||
() -> caller.terminateInstances(r -> r.instanceIds(instanceId).dryRun(true)));
|
||||
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)));
|
||||
|
||||
assertEquals("running", state(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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.testing.QueryRequests;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.ValueSource;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
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.
|
||||
*/
|
||||
@QuarkusTest
|
||||
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 INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item";
|
||||
|
||||
private String account;
|
||||
private String runningId;
|
||||
private String stoppedId;
|
||||
|
||||
@BeforeEach
|
||||
void launchARunningAndAStoppedInstance() {
|
||||
account = Long.toString(ACCOUNTS.incrementAndGet());
|
||||
runningId = launch();
|
||||
stoppedId = launch();
|
||||
ec2("StopInstances", "InstanceId.1", stoppedId);
|
||||
awaitState(stoppedId, "stopped");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void terminateTheInstances() {
|
||||
ec2("TerminateInstances", "InstanceId.1", runningId, "InstanceId.2", stoppedId);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"StartInstances", "StopInstances", "RebootInstances", "TerminateInstances"})
|
||||
void aDryRunIsAnsweredWithDryRunOperationAndChangesNothing(String action) {
|
||||
Map<String, String> before = states();
|
||||
|
||||
request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId)
|
||||
.formParam("DryRun", "true").post("/").then()
|
||||
.statusCode(412)
|
||||
.body("Response.Errors.Error.Code", equalTo("DryRunOperation"))
|
||||
.body("Response.Errors.Error.Message",
|
||||
equalTo("Request would have succeeded, but DryRun flag is set."));
|
||||
|
||||
assertEquals(before, states());
|
||||
}
|
||||
|
||||
/** Every instance is checked before the dry run is answered, so one the call would refuse refuses it. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"StartInstances", "StopInstances", "RebootInstances", "TerminateInstances"})
|
||||
void aDryRunNamingAMissingInstanceKeepsTheRealCallsError(String action) {
|
||||
Map<String, String> before = states();
|
||||
|
||||
request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId,
|
||||
"InstanceId.2", MISSING_INSTANCE).formParam("DryRun", "true").post("/").then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound"));
|
||||
|
||||
assertEquals(before, states());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDryRunStartOfATerminatedInstanceKeepsTheRealCallsError() {
|
||||
ec2("TerminateInstances", "InstanceId.1", runningId);
|
||||
awaitState(runningId, "terminated");
|
||||
Map<String, String> before = states();
|
||||
|
||||
for (String dryRun : List.of("true", "false")) {
|
||||
request("StartInstances", "InstanceId.1", runningId).formParam("DryRun", dryRun).post("/").then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("IncorrectInstanceState"));
|
||||
}
|
||||
|
||||
assertEquals(before, states());
|
||||
}
|
||||
|
||||
/** A DryRun value that is not a boolean is refused as one, and no instance changes. */
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"StartInstances, maybe", "StartInstances, ''",
|
||||
"StopInstances, maybe", "StopInstances, ''",
|
||||
"RebootInstances, maybe", "RebootInstances, ''",
|
||||
"TerminateInstances, maybe", "TerminateInstances, ''"
|
||||
})
|
||||
void aDryRunValueThatIsNotABooleanIsRefused(String action, String value) {
|
||||
Map<String, String> before = states();
|
||||
|
||||
request(action, "InstanceId.1", "StartInstances".equals(action) ? stoppedId : runningId)
|
||||
.formParam("DryRun", value).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, states());
|
||||
}
|
||||
|
||||
private String launch() {
|
||||
String instanceId = ec2("RunInstances", "ImageId", "ami-1234567890abcdef0", "InstanceType", "t3.micro",
|
||||
"MinCount", "1", "MaxCount", "1").getString("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
awaitState(instanceId, "running");
|
||||
return instanceId;
|
||||
}
|
||||
|
||||
private void awaitState(String instanceId, String state) {
|
||||
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() ->
|
||||
assertEquals(state, states().get(instanceId)));
|
||||
}
|
||||
|
||||
/** Every instance of the account with its state, ordered by instance id. */
|
||||
private Map<String, String> states() {
|
||||
XmlPath described = ec2("DescribeInstances");
|
||||
List<String> ids = described.getList(INSTANCE + ".instanceId", String.class);
|
||||
List<String> states = described.getList(INSTANCE + ".instanceState.name", String.class);
|
||||
Map<String, String> byId = new TreeMap<>();
|
||||
for (int i = 0; i < ids.size(); i++) {
|
||||
byId.put(ids.get(i), states.get(i));
|
||||
}
|
||||
return byId;
|
||||
}
|
||||
|
||||
private XmlPath ec2(String action, String... params) {
|
||||
return request(action, params).post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
private RequestSpecification request(String action, String... params) {
|
||||
return QueryRequests.request(account, "ec2", action, params);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user