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 3e51c72214..cd4524910d 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -947,7 +947,7 @@ public class Ec2QueryHandler { Reservation res = service.runInstances(region, imageId, instanceType, minCount, maxCount, keyName, sgIds, subnetId, clientToken, instanceTags, userData, iamInstanceProfileArn, associatePublicIp, networkInterfaceId, networkInterfaceDeviceIndex, null, metadataOptions, - creditSpecificationCpuCredits, userDataEncoded, Boolean.parseBoolean(p.getFirst("DryRun")), + creditSpecificationCpuCredits, userDataEncoded, dryRun(p), p.getFirst("Placement.HostId"), p.getFirst("Placement.Tenancy"), blockDeviceMappings, "spot".equals(marketType), privateIpAddress, capacitySpecification); @@ -2361,11 +2361,20 @@ public class Ec2QueryHandler { } private void checkDryRun(MultivaluedMap params) { - if (Boolean.parseBoolean(params.getFirst("DryRun"))) { - throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412); + if (dryRun(params)) { + throw Ec2Service.dryRunOperation(); } } + /** The request's DryRun flag. A blank or non-boolean value is refused rather than read as false. */ + private boolean dryRun(MultivaluedMap params) { + String value = params.getFirst("DryRun"); + if (value != null && value.isBlank()) { + throw new AwsException("InvalidParameterValue", "DryRun is not a valid boolean.", 400); + } + return Boolean.TRUE.equals(parseOptionalBoolean(value, "DryRun")); + } + private Response handleModifyIpam(MultivaluedMap p, String region) { checkDryRun(p); List addOperatingRegions = new ArrayList<>(); @@ -3649,12 +3658,8 @@ public class Ec2QueryHandler { } private Response handleDeleteSecurityGroup(MultivaluedMap p, String region) { - String dryRun = p.getFirst("DryRun"); - if (dryRun != null && dryRun.isBlank()) { - throw new AwsException("InvalidParameterValue", "DryRun is not a valid boolean.", 400); - } String groupId = service.deleteSecurityGroup(region, p.getFirst("GroupId"), p.getFirst("GroupName"), - Boolean.TRUE.equals(parseOptionalBoolean(dryRun, "DryRun"))); + dryRun(p)); return xmlResponse(new XmlBuilder().start("DeleteSecurityGroupResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()).elem("return", "true") .elem("groupId", groupId).end("DeleteSecurityGroupResponse").build()); @@ -4206,7 +4211,7 @@ public class Ec2QueryHandler { String v = p.getFirst("Tag." + i + ".Value"); tagList.add(creationTag(k, v)); } - service.createTags(region, resourceIds, tagList); + service.createTags(region, resourceIds, tagList, dryRun(p)); return booleanResponse("CreateTags"); } @@ -4219,7 +4224,7 @@ public class Ec2QueryHandler { String v = p.getFirst("Tag." + i + ".Value"); tagList.add(new Tag(k, v)); } - service.deleteTags(region, resourceIds, tagList); + service.deleteTags(region, resourceIds, tagList, dryRun(p)); return booleanResponse("DeleteTags"); } @@ -4403,7 +4408,7 @@ public class Ec2QueryHandler { } service.replaceRoute(region, rtId, dest, destIpv6, destPrefixList, gwId, natGwId, pcxId, instanceId, networkInterfaceId, - Boolean.parseBoolean(p.getFirst("DryRun"))); + dryRun(p)); return booleanResponse("ReplaceRoute"); } @@ -4652,7 +4657,7 @@ public class Ec2QueryHandler { InstanceConnectEndpoint endpoint = service.createInstanceConnectEndpoint(region, p.getFirst("SubnetId"), getList(p, "SecurityGroupId"), preserve == null ? null : Boolean.parseBoolean(preserve), p.getFirst("IpAddressType"), parseTagsForResource(p, "instance-connect-endpoint"), - p.getFirst("ClientToken"), Boolean.parseBoolean(p.getFirst("DryRun"))); + p.getFirst("ClientToken"), dryRun(p)); XmlBuilder xml = new XmlBuilder() .start("CreateInstanceConnectEndpointResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) @@ -5271,7 +5276,7 @@ public class Ec2QueryHandler { p.getFirst("LaunchTemplateId"), p.getFirst("LaunchTemplateName"), firstPresent(p, "SetDefaultVersion", "DefaultVersion"), - Boolean.parseBoolean(p.getFirst("DryRun"))); + dryRun(p)); XmlBuilder xml = new XmlBuilder() .start("ModifyLaunchTemplateResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) @@ -5292,13 +5297,9 @@ public class Ec2QueryHandler { } private Response handleDeleteLaunchTemplateVersions(MultivaluedMap p, String region) { - String dryRun = p.getFirst("DryRun"); - if (dryRun != null && dryRun.isBlank()) { - throw new AwsException("InvalidParameterValue", "DryRun is not a valid boolean.", 400); - } List results = service.deleteLaunchTemplateVersions( region, p.getFirst("LaunchTemplateId"), p.getFirst("LaunchTemplateName"), - getList(p, "LaunchTemplateVersion"), Boolean.TRUE.equals(parseOptionalBoolean(dryRun, "DryRun"))); + getList(p, "LaunchTemplateVersion"), dryRun(p)); XmlBuilder xml = new XmlBuilder().start("DeleteLaunchTemplateVersionsResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()); for (boolean success : List.of(true, false)) { @@ -6769,6 +6770,9 @@ public class Ec2QueryHandler { String kmsKeyId = p.getFirst("KmsKeyId"); List volumeTags = parseTagsForResource(p, "volume"); + // Answered once the parameters and tags are read, everything a real create checks, so a + // dry run stores no volume and creates no backing file. + checkDryRun(p); Volume vol = service.createVolume(region, availabilityZone, volumeType, size, encrypted, kmsKeyId, iops, throughput, snapshotId, volumeTags); @@ -6798,7 +6802,7 @@ public class Ec2QueryHandler { } private Response handleDeleteVolume(MultivaluedMap p, String region) { - service.deleteVolume(region, p.getFirst("VolumeId")); + service.deleteVolume(region, p.getFirst("VolumeId"), dryRun(p)); return booleanResponse("DeleteVolume"); } @@ -6814,9 +6818,8 @@ public class Ec2QueryHandler { Boolean multiAttachEnabled = p.getFirst("MultiAttachEnabled") != null ? Boolean.parseBoolean(p.getFirst("MultiAttachEnabled")) : null; - boolean dryRun = Boolean.parseBoolean(p.getFirst("DryRun")); VolumeModification mod = service.modifyVolume(region, volumeId, size, volumeType, - iops, throughput, multiAttachEnabled, dryRun); + iops, throughput, multiAttachEnabled, dryRun(p)); XmlBuilder xml = new XmlBuilder() .start("ModifyVolumeResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) @@ -6895,7 +6898,8 @@ public class Ec2QueryHandler { String volumeId = p.getFirst("VolumeId"); String instanceId = p.getFirst("InstanceId"); String device = p.getFirst("Device"); - VolumeAttachment attachment = service.attachVolume(region, volumeId, instanceId, device); + VolumeAttachment attachment = service.attachVolume(region, volumeId, instanceId, device, + dryRun(p)); return volumeAttachmentResponse("AttachVolume", attachment, "attaching"); } @@ -6904,7 +6908,8 @@ public class Ec2QueryHandler { String instanceId = p.getFirst("InstanceId"); String device = p.getFirst("Device"); boolean force = "true".equalsIgnoreCase(p.getFirst("Force")); - VolumeAttachment attachment = service.detachVolume(region, volumeId, instanceId, device, force); + VolumeAttachment attachment = service.detachVolume(region, volumeId, instanceId, device, force, + dryRun(p)); return volumeAttachmentResponse("DetachVolume", attachment, "detaching"); } 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 b819b52cfe..6db94422ac 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -4157,7 +4157,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } if (dryRun) { - throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412); + throw dryRunOperation(); } synchronized (attachmentTopologyLock(region)) { if (finalSubnetId != null) { @@ -7988,8 +7988,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "The security group '" + selectedId + "' has a dependent object", 400); } if (dryRun) { - throw new AwsException("DryRunOperation", - "Request would have succeeded, but DryRun flag is set.", 412); + throw dryRunOperation(); } securityGroups.delete(key(region, selectedId)); removeTags(region, selectedId); @@ -9910,7 +9909,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab nextDefault = String.valueOf(requested); } if (dryRun) { - throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412); + throw dryRunOperation(); } launchTemplate.setDefaultVersionNumber(nextDefault); launchTemplates.put(key(region, launchTemplate.getLaunchTemplateId()), launchTemplate); @@ -10076,8 +10075,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab synchronized (template) { ensureLaunchTemplatePresent(region, template, id); if (dryRun) { - throw new AwsException("DryRunOperation", - "Request would have succeeded, but DryRun flag is set.", 412); + throw dryRunOperation(); } ensureLaunchTemplateVersions(template); int lastIssued = lastIssuedLaunchTemplateVersion(template); @@ -10468,9 +10466,25 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return IamPolicyEvaluator.caseSensitiveGlobMatches(pattern, value); } + /** + * What EC2 answers a dry run with once the request has passed every check the real call makes: + * DryRunOperation, HTTP 412, nothing changed. + */ + static AwsException dryRunOperation() { + return new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412); + } + // ─── Tags ────────────────────────────────────────────────────────────────── public void createTags(String region, List resourceIds, List tagList) { + createTags(region, resourceIds, tagList, false); + } + + /** + * As above; with {@code dryRun} the request passes every check a write makes, the + * per-resource limit included, and is then answered with DryRunOperation, nothing written. + */ + public void createTags(String region, List resourceIds, List tagList, boolean dryRun) { validateTagTargets(region, resourceIds); validateUserTagKeys(tagList); validateTagLengths(tagList); @@ -10484,6 +10498,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab for (String resourceId : resourceIds) { requireWithinTagLimit(region, resourceId, tagList); } + if (dryRun) { + throw dryRunOperation(); + } createSystemTags(region, resourceIds, tagList); }); } @@ -10712,8 +10729,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public void deleteTags(String region, List resourceIds, List tagList) { + deleteTags(region, resourceIds, tagList, false); + } + + /** As above; with {@code dryRun} the request is validated and then answered with DryRunOperation. */ + public void deleteTags(String region, List resourceIds, List tagList, boolean dryRun) { validateTagTargets(region, resourceIds); validateUserTagKeys(tagList); + if (dryRun) { + throw dryRunOperation(); + } deleteResourceTags(region, resourceIds, tagList); } @@ -12251,8 +12276,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab : null; if (dryRun) { - throw new AwsException("DryRunOperation", - "Request would have succeeded, but DryRun flag is set.", 412); + throw dryRunOperation(); } // The target the request does not name is cleared rather than carried over from the @@ -13119,7 +13143,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } if (dryRun) { - throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412); + throw dryRunOperation(); } String token = clientToken != null && !clientToken.isBlank() ? clientToken : null; if (token != null) { @@ -14850,6 +14874,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public void deleteVolume(String region, String volumeId) { + deleteVolume(region, volumeId, false); + } + + /** + * As above; with {@code dryRun} the volume must still exist and be detached, and the request + * is then answered with DryRunOperation, the volume and its backing storage left in place. + */ + public void deleteVolume(String region, String volumeId, boolean dryRun) { if (volumeId == null || volumeId.isBlank()) { throw new AwsException("MissingParameter", "The parameter VolumeId is missing", 400); } @@ -14862,6 +14894,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab throw new AwsException("VolumeInUse", "Volume " + volumeId + " is currently attached to an instance", 400); } + if (dryRun) { + throw dryRunOperation(); + } if (volumeBlockDeviceManager != null && volumeBlockDeviceManager.isAvailable()) { if (!volumeBlockDeviceManager.deleteVolume(volumeId)) { throw new AwsException("InternalError", @@ -15008,7 +15043,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } if (dryRun) { - throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412); + throw dryRunOperation(); } Integer originalSize = volume.getSize(); @@ -15147,6 +15182,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public VolumeAttachment attachVolume(String region, String volumeId, String instanceId, String device) { + return attachVolume(region, volumeId, instanceId, device, false); + } + + /** + * As above; with {@code dryRun} the volume, the instance and the device pass every check an + * attachment makes, and the request is then answered with DryRunOperation, nothing attached. + */ + public VolumeAttachment attachVolume(String region, String volumeId, String instanceId, String device, + boolean dryRun) { ensureDefaultResources(region); if (volumeId == null || volumeId.isEmpty()) { throw new AwsException("MissingParameter", @@ -15172,14 +15216,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "The device '" + device + "' is already in use by an attachment in progress", 400); } try { - return attachVolumeToInstance(region, volumeId, instanceId, device); + return attachVolumeToInstance(region, volumeId, instanceId, device, dryRun); } finally { pendingVolumeAttachments.remove(target); } }); } - private VolumeAttachment attachVolumeToInstance(String region, String volumeId, String instanceId, String device) { + private VolumeAttachment attachVolumeToInstance(String region, String volumeId, String instanceId, String device, + boolean dryRun) { Volume volume = getRequiredVolume(region, volumeId); Instance inst = getRequiredInstance(region, instanceId); if (!List.of("running", "stopped").contains(inst.getState().getName())) { @@ -15215,6 +15260,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } } + if (dryRun) { + throw dryRunOperation(); + } if (volumeBlockDeviceManager != null) { volumeBlockDeviceManager.attachVolume(volume, inst, device); @@ -15236,6 +15284,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public VolumeAttachment detachVolume(String region, String volumeId, String instanceId, String device, boolean force) { + return detachVolume(region, volumeId, instanceId, device, force, false); + } + + /** + * As above; with {@code dryRun} the attachment passes every check a detach makes, and the + * request is then answered with DryRunOperation, the volume left attached. + */ + public VolumeAttachment detachVolume(String region, String volumeId, String instanceId, String device, + boolean force, boolean dryRun) { if (volumeId == null || volumeId.isEmpty()) { throw new AwsException("MissingParameter", "The parameter VolumeId is missing", 400); } @@ -15265,6 +15322,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "Device " + inst.getRootDeviceName() + " has the root partition on it. Detaching it will damage the " + "filesystem/partition tables. To force detachment, use the force parameter", 400); } + if (dryRun) { + throw dryRunOperation(); + } target.setState("detached"); volume.getAttachments().clear(); volume.setState("available"); diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2CreateRouteDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2CreateRouteDryRunIntegrationTest.java index 307c16c983..33800a26b7 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2CreateRouteDryRunIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2CreateRouteDryRunIntegrationTest.java @@ -17,6 +17,7 @@ import java.net.URI; import java.util.List; import java.util.Map; +import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -34,7 +35,7 @@ class Ec2CreateRouteDryRunIntegrationTest { RouteFixture fixture = new RouteFixture(client)) { List before = fixture.routes(); CreateRouteRequest request = fixture.request().gatewayId(fixture.gatewayId).dryRun(true).build(); - assertError("DryRunOperation", 412, () -> client.createRoute(request)); + assertAwsError("DryRunOperation", 412, () -> client.createRoute(request)); assertEquals(before, fixture.routes()); assertTrue(client.createRoute(request.toBuilder().dryRun(false).build()).returnValue()); assertEquals(before.size() + 1, fixture.routes().size()); @@ -46,7 +47,7 @@ class Ec2CreateRouteDryRunIntegrationTest { try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint); RouteFixture fixture = new RouteFixture(client)) { List before = fixture.routes(); - assertError("DryRunOperation", 412, () -> client.createRoute(fixture.request() + assertAwsError("DryRunOperation", 412, () -> client.createRoute(fixture.request() .natGatewayId("nat-0123456789abcdef0").dryRun(true).build())); assertEquals(before, fixture.routes()); } @@ -60,10 +61,8 @@ class Ec2CreateRouteDryRunIntegrationTest { List before = fixture.routes(); try (Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(), user.secretAccessKey(), Region.US_EAST_1, endpoint)) { - Ec2Exception error = assertThrows(Ec2Exception.class, () -> caller.createRoute(fixture.request() + assertAwsError("UnauthorizedOperation", 403, () -> caller.createRoute(fixture.request() .gatewayId(fixture.gatewayId).dryRun(true).build())); - assertEquals(403, error.statusCode()); - assertEquals("UnauthorizedOperation", error.awsErrorDetails().errorCode()); } assertEquals(before, fixture.routes()); } @@ -101,22 +100,14 @@ class Ec2CreateRouteDryRunIntegrationTest { user.secretAccessKey(), Region.US_EAST_1, endpoint)) { List before = fixture.routes(); CreateRouteRequest request = fixture.request().gatewayId(fixture.gatewayId).dryRun(true).build(); - assertError("DryRunOperation", 412, () -> caller.createRoute(request)); + assertAwsError("DryRunOperation", 412, () -> caller.createRoute(request)); SignedIamUsers.iam(endpoint, "DeleteUserPolicy", Map.of("UserName", user.name(), "PolicyName", "route")) .then().statusCode(200); - Ec2Exception denied = assertThrows(Ec2Exception.class, () -> caller.createRoute(request)); - assertEquals(403, denied.statusCode()); - assertEquals("UnauthorizedOperation", denied.awsErrorDetails().errorCode()); + assertAwsError("UnauthorizedOperation", 403, () -> caller.createRoute(request)); assertEquals(before, fixture.routes()); } } - private static void assertError(String code, int status, Runnable request) { - Ec2Exception error = assertThrows(Ec2Exception.class, request::run); - assertEquals(status, error.statusCode()); - assertEquals(code, error.awsErrorDetails().errorCode()); - } - private static final class RouteFixture implements AutoCloseable { private final Ec2Client client; private final String vpcId; diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java new file mode 100644 index 0000000000..29281ddcf0 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java @@ -0,0 +1,87 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.SignedIamEnforcementProfile; +import io.floci.aws.testing.SignedIamUsers; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +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.Volume; + +import java.net.URI; +import java.util.List; +import java.util.Map; + +import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; +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. + */ +@QuarkusTest +@TestProfile(SignedIamEnforcementProfile.class) +class Ec2DryRunIamIntegrationTest { + + private static final String ZONE = "us-east-1a"; + + @TestHTTPResource("/") + URI endpoint; + + @Test + void aCallerWithoutPermissionCannotUseAVolumeDryRunToGetPastIt() throws Exception { + try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint); + SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "volume-dryrun-denied-"); + Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(), + user.secretAccessKey(), Region.US_EAST_1, endpoint)) { + String volumeId = admin.createVolume(r -> r.availabilityZone(ZONE).size(1)).volumeId(); + try { + List before = admin.describeVolumes().volumes(); + + assertAwsError("UnauthorizedOperation", 403, + () -> caller.createVolume(r -> r.availabilityZone(ZONE).size(1).dryRun(true))); + assertAwsError("UnauthorizedOperation", 403, + () -> caller.deleteVolume(r -> r.volumeId(volumeId).dryRun(true))); + + assertEquals(before, admin.describeVolumes().volumes()); + } finally { + admin.deleteVolume(r -> r.volumeId(volumeId)); + } + } + } + + @Test + void aVolumeDryRunNeedsTheCallersCurrentPermission() throws Exception { + String policy = """ + {"Version":"2012-10-17","Statement":[{ + "Effect":"Allow","Action":["ec2:CreateVolume","ec2:DeleteVolume"],"Resource":"*" + }]} + """; + try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint); + SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "volume-dryrun-allowed-", "volumes", + policy); + Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(), + user.secretAccessKey(), Region.US_EAST_1, endpoint)) { + String volumeId = admin.createVolume(r -> r.availabilityZone(ZONE).size(1)).volumeId(); + try { + List before = admin.describeVolumes().volumes(); + + assertAwsError("DryRunOperation", 412, + () -> caller.createVolume(r -> r.availabilityZone(ZONE).size(1).dryRun(true))); + assertAwsError("DryRunOperation", 412, () -> caller.deleteVolume(r -> r.volumeId(volumeId).dryRun(true))); + SignedIamUsers.iam(endpoint, "DeleteUserPolicy", Map.of("UserName", user.name(), "PolicyName", "volumes")) + .then().statusCode(200); + assertAwsError("UnauthorizedOperation", 403, + () -> caller.deleteVolume(r -> r.volumeId(volumeId).dryRun(true))); + + assertEquals(before, admin.describeVolumes().volumes()); + } finally { + admin.deleteVolume(r -> r.volumeId(volumeId)); + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2QueryHandlerTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2QueryHandlerTest.java index 9d7f5a30bb..ca5e83f73c 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2QueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2QueryHandlerTest.java @@ -250,7 +250,7 @@ class Ec2QueryHandlerTest { assertEquals(200, response.getStatus()); @SuppressWarnings("unchecked") ArgumentCaptor> tags = ArgumentCaptor.forClass(List.class); - verify(service).createTags(eq("us-east-1"), eq(List.of("vpc-test")), tags.capture()); + verify(service).createTags(eq("us-east-1"), eq(List.of("vpc-test")), tags.capture(), eq(false)); assertEquals(List.of("", "", "present"), tags.getValue().stream().map(Tag::getValue).toList()); } @@ -267,7 +267,7 @@ class Ec2QueryHandlerTest { assertEquals(200, response.getStatus()); @SuppressWarnings("unchecked") ArgumentCaptor> tags = ArgumentCaptor.forClass(List.class); - verify(service).deleteTags(eq("us-east-1"), eq(List.of("vpc-test")), tags.capture()); + verify(service).deleteTags(eq("us-east-1"), eq(List.of("vpc-test")), tags.capture(), eq(false)); assertNull(tags.getValue().getFirst().getValue()); } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2VolumeDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2VolumeDryRunIntegrationTest.java new file mode 100644 index 0000000000..0d3d311eed --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2VolumeDryRunIntegrationTest.java @@ -0,0 +1,207 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.QueryRequests; +import io.quarkus.test.InjectMock; +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.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +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; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +/** + * DryRun on the volume and tag calls the EBS CSI driver makes is answered with DryRunOperation and + * HTTP 412 once the request has passed every check the real call makes, and it changes nothing: no + * volume is created or deleted, no attachment made or ended, no tag written or removed, and no + * backing device touched. The driver's controller sends a dry run CreateVolume each time it starts. + */ +@QuarkusTest +class Ec2VolumeDryRunIntegrationTest { + + /** Each test works in an account of its own, so DescribeVolumes lists only the fixture's volumes. */ + private static final AtomicLong ACCOUNTS = new AtomicLong(726100000000L); + private static final String MISSING_VOLUME = "vol-0123456789abcdef0"; + private static final String VOLUME = "DescribeVolumesResponse.volumeSet.item"; + private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item"; + + @InjectMock + Ec2VolumeBlockDeviceManager blockDevices; + + private String account; + private String instanceId; + private String zone; + /** Attached to the instance at /dev/xvdf. */ + private String attachedVolumeId; + /** Not attached, tagged team=storage. */ + private String availableVolumeId; + + @BeforeEach + void launchAnInstanceWithAnAttachedAndAnAvailableVolume() { + account = Long.toString(ACCOUNTS.incrementAndGet()); + XmlPath launched = ec2("RunInstances", "ImageId", "ami-1234567890abcdef0", "InstanceType", "t3.micro", + "MinCount", "1", "MaxCount", "1"); + instanceId = launched.getString("RunInstancesResponse.instancesSet.item.instanceId"); + zone = launched.getString("RunInstancesResponse.instancesSet.item.placement.availabilityZone"); + await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).untilAsserted(() -> + assertEquals("running", ec2("DescribeInstances", "InstanceId.1", instanceId) + .getString(INSTANCE + ".instanceState.name"))); + + attachedVolumeId = createVolume(); + ec2("AttachVolume", "VolumeId", attachedVolumeId, "InstanceId", instanceId, "Device", "/dev/xvdf"); + availableVolumeId = createVolume(); + ec2("CreateTags", "ResourceId.1", availableVolumeId, "Tag.1.Key", "team", "Tag.1.Value", "storage"); + clearInvocations(blockDevices); + } + + @AfterEach + void terminateTheInstance() { + ec2("TerminateInstances", "InstanceId.1", instanceId); + } + + @ParameterizedTest + @ValueSource(strings = {"CreateVolume", "DeleteVolume", "AttachVolume", "DetachVolume", "CreateTags", "DeleteTags"}) + void aDryRunIsAnsweredWithDryRunOperationAndChangesNothing(String action) { + List before = volumes(); + + dryRunnable(action).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, volumes()); + verify(blockDevices, never()).createVolume(anyString(), anyInt()); + verify(blockDevices, never()).deleteVolume(anyString()); + verify(blockDevices, never()).attachVolume(any(), any(), anyString()); + verify(blockDevices, never()).detachVolume(any(), any(), anyString()); + } + + /** A dry run the real call would refuse keeps the real call's error, and changes nothing either. */ + @ParameterizedTest + @CsvSource({ + "delete-attached-volume, VolumeInUse", + "delete-missing-volume, InvalidVolume.NotFound", + "attach-volume-in-use, VolumeInUse", + "detach-available-volume, InvalidVolume.NotAttached", + "create-volume-with-reserved-tag, InvalidParameterValue", + "tag-missing-volume, InvalidVolume.NotFound", + "untag-reserved-key, InvalidParameterValue" + }) + void aDryRunTheRealCallWouldRefuseKeepsItsError(String request, String errorCode) { + List before = volumes(); + + refused(request).formParam("DryRun", "true").post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo(errorCode)); + refused(request).post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo(errorCode)); + + assertEquals(before, volumes()); + } + + /** A DryRun value that is not a boolean is refused as one, and the request changes nothing. */ + @ParameterizedTest + @CsvSource({ + "CreateVolume, maybe", "CreateVolume, ''", + "DeleteVolume, maybe", "DeleteVolume, ''", + "AttachVolume, maybe", "AttachVolume, ''", + "DetachVolume, maybe", "DetachVolume, ''", + "CreateTags, maybe", "CreateTags, ''", + "DeleteTags, maybe", "DeleteTags, ''" + }) + void aDryRunValueThatIsNotABooleanIsRefused(String action, String value) { + List before = volumes(); + + dryRunnable(action).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, volumes()); + } + + /** A request for {@code action} that would succeed against the fixture. */ + private RequestSpecification dryRunnable(String action) { + return switch (action) { + // Like the EBS CSI driver's IOPS limit probe, which tags its 4 GiB volume this way. + case "CreateVolume" -> request(action, "AvailabilityZone", zone, "VolumeType", "io2", "Size", "4", + "Iops", "64000", "TagSpecification.1.ResourceType", "volume", + "TagSpecification.1.Tag.1.Key", "CSIVolumeName", + "TagSpecification.1.Tag.1.Value", "IopsLimitDryRun"); + case "DeleteVolume" -> request(action, "VolumeId", availableVolumeId); + case "AttachVolume" -> request(action, "VolumeId", availableVolumeId, "InstanceId", instanceId, + "Device", "/dev/xvdg"); + case "DetachVolume" -> request(action, "VolumeId", attachedVolumeId, "InstanceId", instanceId); + case "CreateTags" -> request(action, "ResourceId.1", availableVolumeId, + "Tag.1.Key", "team", "Tag.1.Value", "compute", "Tag.2.Key", "owner", "Tag.2.Value", "csi"); + case "DeleteTags" -> request(action, "ResourceId.1", availableVolumeId, "Tag.1.Key", "team"); + default -> throw new IllegalArgumentException(action); + }; + } + + /** The request named by {@code request}, which the real call refuses. */ + private RequestSpecification refused(String request) { + return switch (request) { + case "delete-attached-volume" -> request("DeleteVolume", "VolumeId", attachedVolumeId); + case "delete-missing-volume" -> request("DeleteVolume", "VolumeId", MISSING_VOLUME); + case "attach-volume-in-use" -> request("AttachVolume", "VolumeId", attachedVolumeId, + "InstanceId", instanceId, "Device", "/dev/xvdh"); + case "detach-available-volume" -> request("DetachVolume", "VolumeId", availableVolumeId); + case "create-volume-with-reserved-tag" -> request("CreateVolume", "AvailabilityZone", zone, "Size", "4", + "TagSpecification.1.ResourceType", "volume", + "TagSpecification.1.Tag.1.Key", "aws:reserved", "TagSpecification.1.Tag.1.Value", "x"); + case "tag-missing-volume" -> request("CreateTags", "ResourceId.1", MISSING_VOLUME, + "Tag.1.Key", "team", "Tag.1.Value", "compute"); + case "untag-reserved-key" -> request("DeleteTags", "ResourceId.1", availableVolumeId, + "Tag.1.Key", "aws:reserved"); + default -> throw new IllegalArgumentException(request); + }; + } + + /** Every volume of the account with its state, attachments and tags, ordered by volume id. */ + private List volumes() { + XmlPath described = ec2("DescribeVolumes"); + List volumes = new ArrayList<>(); + for (String volumeId : described.getList(VOLUME + ".volumeId", String.class)) { + String volume = VOLUME + ".find { it.volumeId == '" + volumeId + "' }"; + volumes.add(volumeId + " " + described.getString(volume + ".status") + + " attachments " + described.getList(volume + ".attachmentSet.item.collect { " + + "it.instanceId.text() + ' ' + it.device.text() + ' ' + it.status.text() }", String.class) + + " tags " + described.getList(volume + ".tagSet.item.collect { " + + "it.key.text() + '=' + it.value.text() }", String.class)); + } + volumes.sort(null); + return volumes; + } + + private String createVolume() { + return ec2("CreateVolume", "AvailabilityZone", zone, "Size", "1") + .getString("CreateVolumeResponse.volumeId"); + } + + 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); + } +} diff --git a/src/test/java/io/floci/aws/services/s3/S3BucketCollisionIamEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3BucketCollisionIamEnforcementIntegrationTest.java index 42f4f3e1ec..4f3b55fd8b 100644 --- a/src/test/java/io/floci/aws/services/s3/S3BucketCollisionIamEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3BucketCollisionIamEnforcementIntegrationTest.java @@ -23,6 +23,7 @@ import software.amazon.awssdk.services.s3.model.S3Exception; import java.net.URI; import java.util.UUID; +import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; import static io.floci.aws.testing.EnforcementFixtures.auth; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -61,10 +62,10 @@ class S3BucketCollisionIamEnforcementIntegrationTest { assertEquals(403, assertThrows(S3Exception.class, () -> caller.headBucket(request -> request.bucket(bucket))).statusCode()); } - assertError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket))); - assertError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket) + assertAwsError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket))); + assertAwsError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket) .toBuilder().objectOwnership(ObjectOwnership.OBJECT_WRITER).build())); - assertError("BucketAlreadyOwnedByYou", 409, () -> owner.createBucket(createRequest(bucket))); + assertAwsError("BucketAlreadyOwnedByYou", 409, () -> owner.createBucket(createRequest(bucket))); assertEquals(ObjectOwnership.BUCKET_OWNER_ENFORCED, owner.getBucketOwnershipControls( request -> request.bucket(bucket)).ownershipControls().rules().getFirst().objectOwnership()); assertTrue(caller.listBuckets().buckets().stream().noneMatch(value -> bucket.equals(value.name()))); @@ -89,7 +90,7 @@ class S3BucketCollisionIamEnforcementIntegrationTest { String bucket = createBucket(owner, ownerKeys); owner.putBucketPolicy(request -> request.bucket(bucket).policy(bucketPolicy(bucket, "Allow"))); caller.headBucket(request -> request.bucket(bucket)); - assertError("AccessDenied", 403, () -> caller.createBucket(createRequest(bucket))); + assertAwsError("AccessDenied", 403, () -> caller.createBucket(createRequest(bucket))); owner.headBucket(request -> request.bucket(bucket)); } } @@ -110,18 +111,18 @@ class S3BucketCollisionIamEnforcementIntegrationTest { () -> owner.headBucket(request -> request.bucket(bucket))).statusCode()); assertEquals(403, assertThrows(S3Exception.class, () -> caller.headBucket(request -> request.bucket(bucket))).statusCode()); - assertError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket))); - assertError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket) + assertAwsError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket))); + assertAwsError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket) .toBuilder().objectOwnership(ObjectOwnership.OBJECT_WRITER).build())); - assertError("AccessDenied", 403, () -> owner.createBucket(createRequest(bucket))); - assertError("AccessDenied", 403, () -> owner.createBucket(createRequest(bucket) + assertAwsError("AccessDenied", 403, () -> owner.createBucket(createRequest(bucket))); + assertAwsError("AccessDenied", 403, () -> owner.createBucket(createRequest(bucket) .toBuilder().objectOwnership(ObjectOwnership.OBJECT_WRITER).build())); assertEquals(ObjectOwnership.BUCKET_OWNER_ENFORCED, owner.getBucketOwnershipControls( request -> request.bucket(bucket)).ownershipControls().rules().getFirst().objectOwnership()); } finally { owner.deleteBucketPolicy(request -> request.bucket(bucket)); } - assertError("BucketAlreadyOwnedByYou", 409, () -> owner.createBucket(createRequest(bucket))); + assertAwsError("BucketAlreadyOwnedByYou", 409, () -> owner.createBucket(createRequest(bucket))); } } @@ -135,8 +136,8 @@ class S3BucketCollisionIamEnforcementIntegrationTest { try (S3Client owner = client(ownerKeys); S3Client caller = client(callerKeys)) { String bucket = createBucket(owner, ownerKeys); owner.putBucketPolicy(request -> request.bucket(bucket).policy(bucketPolicy(bucket, "Allow"))); - assertError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket))); - assertError("AccessDenied", 403, () -> caller.createBucket(createRequest(bucket) + assertAwsError("BucketAlreadyExists", 409, () -> caller.createBucket(createRequest(bucket))); + assertAwsError("AccessDenied", 403, () -> caller.createBucket(createRequest(bucket) .toBuilder().objectOwnership(ObjectOwnership.OBJECT_WRITER).build())); owner.headBucket(request -> request.bucket(bucket)); } @@ -178,10 +179,4 @@ class S3BucketCollisionIamEnforcementIntegrationTest { "Resource":["arn:aws:s3:::%s","arn:aws:s3:::%s/*"]}]} """.formatted(effect, CALLER, bucket, bucket); } - - private static void assertError(String code, int status, Runnable request) { - S3Exception error = assertThrows(S3Exception.class, request::run); - assertEquals(code, error.awsErrorDetails().errorCode()); - assertEquals(status, error.statusCode()); - } } diff --git a/src/test/java/io/floci/aws/testing/AwsSdkErrors.java b/src/test/java/io/floci/aws/testing/AwsSdkErrors.java new file mode 100644 index 0000000000..21a2d95074 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/AwsSdkErrors.java @@ -0,0 +1,22 @@ +package io.floci.aws.testing; + +import org.junit.jupiter.api.function.Executable; +import software.amazon.awssdk.awscore.exception.AwsServiceException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** Assertions on the errors an AWS SDK client throws. */ +public final class AwsSdkErrors { + + private AwsSdkErrors() { + } + + /** Asserts that {@code call} fails with the AWS error {@code code} at HTTP {@code status}, and returns it. */ + public static AwsServiceException assertAwsError(String code, int status, Executable call) { + AwsServiceException error = assertThrows(AwsServiceException.class, call); + assertEquals(code, error.awsErrorDetails().errorCode()); + assertEquals(status, error.statusCode()); + return error; + } +}