diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2EbsEncryptionService.java b/src/main/java/io/floci/aws/services/ec2/Ec2EbsEncryptionService.java index bb5223712b..7f0cdf1e9f 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2EbsEncryptionService.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2EbsEncryptionService.java @@ -65,9 +65,20 @@ public class Ec2EbsEncryptionService { } public String modifyEbsDefaultKmsKeyId(String region, String kmsKeyId) { + return modifyEbsDefaultKmsKeyId(region, kmsKeyId, false); + } + + /** + * As above; with {@code dryRun} the request must name a key, and is then answered with + * DryRunOperation, the default key unchanged. + */ + public String modifyEbsDefaultKmsKeyId(String region, String kmsKeyId, boolean dryRun) { if (kmsKeyId == null || kmsKeyId.isBlank()) { throw new AwsException("MissingParameter", "The request must contain the parameter KmsKeyId", 400); } + if (dryRun) { + throw Ec2Service.dryRunOperation(); + } settings.put(key(region, KMS_KEY_SUFFIX), kmsKeyId); LOG.infov("EBS default KMS key in {0} set to {1}", region, kmsKeyId); return kmsKeyId; diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java index adf1b35354..0ca4186a55 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -119,11 +119,11 @@ public class Ec2QueryHandler { case "ModifyInstanceMetadataOptions" -> handleModifyInstanceMetadataOptions(params, region); // EBS encryption defaults case "GetEbsEncryptionByDefault" -> handleGetEbsEncryptionByDefault(region); - case "EnableEbsEncryptionByDefault" -> handleEnableEbsEncryptionByDefault(region); - case "DisableEbsEncryptionByDefault" -> handleDisableEbsEncryptionByDefault(region); + case "EnableEbsEncryptionByDefault" -> handleEnableEbsEncryptionByDefault(params, region); + case "DisableEbsEncryptionByDefault" -> handleDisableEbsEncryptionByDefault(params, region); case "GetEbsDefaultKmsKeyId" -> handleGetEbsDefaultKmsKeyId(region); case "ModifyEbsDefaultKmsKeyId" -> handleModifyEbsDefaultKmsKeyId(params, region); - case "ResetEbsDefaultKmsKeyId" -> handleResetEbsDefaultKmsKeyId(region); + case "ResetEbsDefaultKmsKeyId" -> handleResetEbsDefaultKmsKeyId(params, region); // AMI block public access case "EnableImageBlockPublicAccess" -> handleEnableImageBlockPublicAccess(params, region); case "DisableImageBlockPublicAccess" -> handleDisableImageBlockPublicAccess(params, region); @@ -678,12 +678,14 @@ public class Ec2QueryHandler { ebsEncryptionService.getEbsEncryptionByDefault(region)); } - private Response handleEnableEbsEncryptionByDefault(String region) { + private Response handleEnableEbsEncryptionByDefault(MultivaluedMap p, String region) { + checkDryRun(p); return ebsEncryptionBooleanResponse("EnableEbsEncryptionByDefaultResponse", ebsEncryptionService.enableEbsEncryptionByDefault(region)); } - private Response handleDisableEbsEncryptionByDefault(String region) { + private Response handleDisableEbsEncryptionByDefault(MultivaluedMap p, String region) { + checkDryRun(p); return ebsEncryptionBooleanResponse("DisableEbsEncryptionByDefaultResponse", ebsEncryptionService.disableEbsEncryptionByDefault(region)); } @@ -695,10 +697,11 @@ public class Ec2QueryHandler { private Response handleModifyEbsDefaultKmsKeyId(MultivaluedMap p, String region) { return ebsKmsKeyResponse("ModifyEbsDefaultKmsKeyIdResponse", - ebsEncryptionService.modifyEbsDefaultKmsKeyId(region, p.getFirst("KmsKeyId"))); + ebsEncryptionService.modifyEbsDefaultKmsKeyId(region, p.getFirst("KmsKeyId"), dryRun(p))); } - private Response handleResetEbsDefaultKmsKeyId(String region) { + private Response handleResetEbsDefaultKmsKeyId(MultivaluedMap p, String region) { + checkDryRun(p); return ebsKmsKeyResponse("ResetEbsDefaultKmsKeyIdResponse", ebsEncryptionService.resetEbsDefaultKmsKeyId(region)); } @@ -1511,7 +1514,7 @@ public class Ec2QueryHandler { */ private Response handleMonitoring(MultivaluedMap p, String region, String action, boolean enabled) { - List changed = service.setInstanceMonitoring(region, getList(p, "InstanceId"), enabled); + List changed = service.setInstanceMonitoring(region, getList(p, "InstanceId"), enabled, dryRun(p)); String state = enabled ? "enabled" : "disabled"; XmlBuilder xml = new XmlBuilder() .start(action + "Response", AwsNamespaces.EC2) @@ -1677,16 +1680,16 @@ public class Ec2QueryHandler { // UserData arrives base64-encoded, as on RunInstances; both forms are kept so the attribute // describes back exactly as sent. String userDataEncoded = p.getFirst("UserData.Value"); - if (userDataEncoded != null) { - service.modifyInstanceUserData(region, instanceId, Ec2UserDataDecoder.decode(userDataEncoded), userDataEncoded); - } + String userData = userDataEncoded == null ? null : Ec2UserDataDecoder.decode(userDataEncoded); // Find which attribute is being modified + String attrName = null; + String attrValue = null; for (String attr : List.of("InstanceType.Value", "SourceDestCheck.Value", "EbsOptimized.Value")) { String val = p.getFirst(attr); if (val != null) { - String attrName = attr.replace(".Value", ""); + attrName = attr.replace(".Value", ""); attrName = Character.toLowerCase(attrName.charAt(0)) + attrName.substring(1); - service.modifyInstanceAttribute(region, instanceId, attrName, val); + attrValue = val; break; } } @@ -1699,6 +1702,17 @@ public class Ec2QueryHandler { } groupIds.add(groupId); } + if (dryRun(p)) { + service.checkInstanceAttributeChange(region, instanceId, userDataEncoded != null, attrName != null, + groupIds); + throw Ec2Service.dryRunOperation(); + } + if (userDataEncoded != null) { + service.modifyInstanceUserData(region, instanceId, userData, userDataEncoded); + } + if (attrName != null) { + service.modifyInstanceAttribute(region, instanceId, attrName, attrValue); + } if (!groupIds.isEmpty()) { service.modifyInstanceGroups(region, instanceId, groupIds); } @@ -1710,7 +1724,8 @@ public class Ec2QueryHandler { if (instanceId == null || instanceId.isBlank()) { throw new AwsException("MissingParameter", "The request must contain the parameter InstanceId", 400); } - Instance inst = service.modifyInstanceMetadataOptions(region, instanceId, parseMetadataOptions(p, "")); + Instance inst = service.modifyInstanceMetadataOptions(region, instanceId, parseMetadataOptions(p, ""), + dryRun(p)); XmlBuilder xml = new XmlBuilder() .start("ModifyInstanceMetadataOptionsResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) @@ -7037,7 +7052,7 @@ public class Ec2QueryHandler { List requests = service.requestSpotInstances(region, spotPrice, instanceCount, type, productDescription, imageId, instanceType, keyName, subnetId, securityGroupIds, userData, iamInstanceProfileArn, - spotRequestTags, instanceTags, userDataEncoded); + spotRequestTags, instanceTags, userDataEncoded, dryRun(p)); XmlBuilder xml = new XmlBuilder() .start("RequestSpotInstancesResponse", AwsNamespaces.EC2) @@ -7070,7 +7085,7 @@ public class Ec2QueryHandler { private Response handleCancelSpotInstanceRequests(MultivaluedMap p, String region) { List ids = getList(p, "SpotInstanceRequestId"); - List requests = service.cancelSpotInstanceRequests(region, ids); + List requests = service.cancelSpotInstanceRequests(region, ids, dryRun(p)); XmlBuilder xml = new XmlBuilder() .start("CancelSpotInstanceRequestsResponse", AwsNamespaces.EC2) diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 9ac9cd3f77..e1c5b3c769 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -5350,7 +5350,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * @return the ids that were changed, in request order */ public List setInstanceMonitoring(String region, List instanceIds, boolean enabled) { + return setInstanceMonitoring(region, instanceIds, enabled, false); + } + + /** + * As above; with {@code dryRun} every instance must exist, and the request is then answered with + * DryRunOperation, no instance's monitoring changed. + */ + public List setInstanceMonitoring(String region, List instanceIds, boolean enabled, + boolean dryRun) { ensureDefaultResources(region); + if (dryRun) { + instanceIds.forEach(id -> getRequiredInstance(region, id)); + throw dryRunOperation(); + } List changed = new ArrayList<>(); for (String id : instanceIds) { Instance inst = getRequiredInstance(region, id); @@ -5777,11 +5790,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab public void modifyInstanceUserData(String region, String instanceId, String userData, String encodedUserData) { ensureDefaultResources(region); Instance inst = getRequiredInstance(region, instanceId); - String state = inst.getState() != null ? inst.getState().getName() : null; - if (!"stopped".equals(state)) { - throw new AwsException("IncorrectInstanceState", - "The instance '" + instanceId + "' is not in the 'stopped' state.", 400); - } + requireStoppedForUserData(inst); inst.setUserData(userData); inst.setEncodedUserData(encodedUserData); instances.put(key(region, instanceId), inst); @@ -5873,6 +5882,51 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab inst.getIamInstanceProfileAssociationTime()); } + /** + * ModifyInstanceAttribute's checks for a dry run, in the order the change makes them, changing + * nothing: with any part to change, the instance exists; new user data needs it stopped; each + * security group exists in the instance's VPC. With nothing to change, as for the change, there + * is nothing to check. + */ + public void checkInstanceAttributeChange(String region, String instanceId, boolean userData, + boolean attribute, List groupIds) { + ensureDefaultResources(region); + if (!userData && !attribute && groupIds.isEmpty()) { + return; + } + Instance inst = getRequiredInstance(region, instanceId); + if (userData) { + requireStoppedForUserData(inst); + } + if (!groupIds.isEmpty()) { + synchronized (attachmentTopologyLock(region)) { + instanceVpcGroups(region, inst, groupIds); + } + } + } + + /** New user data needs the instance stopped, as on AWS. */ + private static void requireStoppedForUserData(Instance inst) { + String state = inst.getState() != null ? inst.getState().getName() : null; + if (!"stopped".equals(state)) { + throw new AwsException("IncorrectInstanceState", + "The instance '" + inst.getInstanceId() + "' is not in the 'stopped' state.", 400); + } + } + + /** The security groups {@code groupIds} names, each of which must be in the instance's VPC. */ + private List instanceVpcGroups(String region, Instance inst, List groupIds) { + List groups = new ArrayList<>(); + for (String groupId : groupIds) { + SecurityGroup sg = getRequiredSecurityGroup(region, groupId); + if (!Objects.equals(inst.getVpcId(), sg.getVpcId())) { + throw new AwsException("InvalidGroup.NotFound", "Security group is not in the instance VPC", 400); + } + groups.add(sg); + } + return groups; + } + public void modifyInstanceAttribute(String region, String instanceId, String attribute, String value) { ensureDefaultResources(region); Instance inst = getRequiredInstance(region, instanceId); @@ -5915,11 +5969,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab List identifiers = new ArrayList<>(); List protectedGroups = new ArrayList<>(); synchronized (attachmentTopologyLock(region)) { - for (String groupId : groupIds) { - SecurityGroup sg = getRequiredSecurityGroup(region, groupId); - if (!Objects.equals(inst.getVpcId(), sg.getVpcId())) { - throw new AwsException("InvalidGroup.NotFound", "Security group is not in the instance VPC", 400); - } + for (SecurityGroup sg : instanceVpcGroups(region, inst, groupIds)) { identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName())); protectedGroups.add(callerAccountId() + "::" + key(region, sg.getGroupId())); } @@ -5977,6 +6027,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab */ public Instance modifyInstanceMetadataOptions(String region, String instanceId, LaunchTemplateData.MetadataOptions request) { + return modifyInstanceMetadataOptions(region, instanceId, request, false); + } + + /** + * As above; with {@code dryRun} the options and the instance pass every check the change makes, + * and the request is then answered with DryRunOperation, the options unchanged. + */ + public Instance modifyInstanceMetadataOptions(String region, String instanceId, + LaunchTemplateData.MetadataOptions request, boolean dryRun) { ensureDefaultResources(region); validateMetadataOptions(request); Instance inst = getRequiredInstance(region, instanceId); @@ -5985,6 +6044,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "The instance '" + instanceId + "' is a cluster node and its metadata options cannot be" + " modified through EC2", 400); } + if (dryRun) { + throw dryRunOperation(); + } inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(inst.effectiveMetadataOptions(), request)); instances.put(key(region, instanceId), inst); return inst; @@ -16215,22 +16277,39 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab String keyName, String subnetId, List securityGroupIds, String userData, String iamInstanceProfileArn, List spotRequestTags, List instanceTags, String encodedUserData) { + return requestSpotInstances(region, spotPrice, instanceCount, type, productDescription, imageId, instanceType, + keyName, subnetId, securityGroupIds, userData, iamInstanceProfileArn, spotRequestTags, instanceTags, + encodedUserData, false); + } + + /** + * As above; with {@code dryRun} the request's instances are checked as RunInstances checks a dry + * run of all of them at once, which then answers DryRunOperation: no request is made and no + * instance launched. + */ + public List requestSpotInstances(String region, String spotPrice, Integer instanceCount, + String type, String productDescription, String imageId, String instanceType, + String keyName, String subnetId, List securityGroupIds, + String userData, String iamInstanceProfileArn, + List spotRequestTags, List instanceTags, String encodedUserData, + boolean dryRun) { ensureDefaultResources(region); int count = instanceCount != null ? instanceCount : 1; String finalType = type != null ? type : "one-time"; + if (dryRun) { + runSpotInstances(region, imageId, instanceType, count, keyName, securityGroupIds, subnetId, instanceTags, + userData, iamInstanceProfileArn, encodedUserData, true); + throw dryRunOperation(); + } List requests = new ArrayList<>(); for (int i = 0; i < count; i++) { String spotRequestId = "sir-" + randomHex(8); - Reservation reservation = runInstances(region, imageId, instanceType, 1, 1, keyName, - securityGroupIds, subnetId, null, instanceTags, userData, iamInstanceProfileArn, - /* associatePublicIp */ null, /* networkInterfaceId */ null, - /* networkInterfaceDeviceIndex */ 0, /* availabilityZone */ null, - /* metadataOptions */ null, /* creditSpecificationCpuCredits */ null, encodedUserData, - false, null, null, null, true); + Reservation reservation = runSpotInstances(region, imageId, instanceType, 1, keyName, securityGroupIds, + subnetId, instanceTags, userData, iamInstanceProfileArn, encodedUserData, false); Instance launchedInstance = reservation.getInstances().get(0); @@ -16285,14 +16364,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab List>> filters) { ensureDefaultResources(region); - if (!spotRequestIds.isEmpty()) { - for (String id : spotRequestIds) { - if (spotInstanceRequests.get(key(region, id)).isEmpty()) { - throw new AwsException("InvalidSpotInstanceRequestID.NotFound", - "The spot instance request ID '" + id + "' does not exist", 400); - } - } - } + spotRequestIds.forEach(id -> requireSpotInstanceRequest(region, id)); return spotInstanceRequests.scan(k -> true).stream() .filter(sir -> sir.getRegion().equals(region)) @@ -16301,16 +16373,47 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .collect(Collectors.toList()); } + /** + * RunInstances for {@code count} of a Spot request's instances, as its launch specification gives them; with + * {@code dryRun}, RunInstances' own dry run of all of them. + */ + private Reservation runSpotInstances(String region, String imageId, String instanceType, int count, + String keyName, List securityGroupIds, String subnetId, + List instanceTags, String userData, String iamInstanceProfileArn, + String encodedUserData, boolean dryRun) { + return runInstances(region, imageId, instanceType, count, count, keyName, + securityGroupIds, subnetId, null, instanceTags, userData, iamInstanceProfileArn, + /* associatePublicIp */ null, /* networkInterfaceId */ null, + /* networkInterfaceDeviceIndex */ 0, /* availabilityZone */ null, + /* metadataOptions */ null, /* creditSpecificationCpuCredits */ null, encodedUserData, + dryRun, null, null, null, true); + } + + private SpotInstanceRequest requireSpotInstanceRequest(String region, String id) { + return spotInstanceRequests.get(key(region, id)).orElseThrow(() -> new AwsException( + "InvalidSpotInstanceRequestID.NotFound", + "The spot instance request ID '" + id + "' does not exist", 400)); + } + public List cancelSpotInstanceRequests(String region, List spotRequestIds) { + return cancelSpotInstanceRequests(region, spotRequestIds, false); + } + + /** + * As above; with {@code dryRun} every request must exist, and the call is then answered with + * DryRunOperation, no request cancelled. + */ + public List cancelSpotInstanceRequests(String region, List spotRequestIds, + boolean dryRun) { ensureDefaultResources(region); + if (dryRun) { + spotRequestIds.forEach(id -> requireSpotInstanceRequest(region, id)); + throw dryRunOperation(); + } List result = new ArrayList<>(); for (String id : spotRequestIds) { - SpotInstanceRequest sir = spotInstanceRequests.get(key(region, id)).orElse(null); - if (sir == null) { - throw new AwsException("InvalidSpotInstanceRequestID.NotFound", - "The spot instance request ID '" + id + "' does not exist", 400); - } + SpotInstanceRequest sir = requireSpotInstanceRequest(region, id); sir.setState("cancelled"); sir.setStatusCode("request-canceled-and-instance-running"); diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java index 9db7642a30..ee2f426004 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java @@ -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 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); } } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java index e47fe5afc1..aad7abedda 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceDryRunIntegrationTest.java @@ -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 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("[^<]*", ""); + } + + /** {@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;