mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): honour DryRun on the volume and tag calls (#8244)
CreateVolume, DeleteVolume, AttachVolume, DetachVolume, CreateTags and DeleteTags ignored DryRun=true and carried out the request. The AWS EBS CSI driver's controller sends a dry run CreateVolume, tagged CSIVolumeName=IopsLimitDryRun, every time it starts in order to probe the IOPS limits. AWS answers it with DryRunOperation and creates nothing, while Floci created a real 4 GiB volume, with its backing file, on every restart. A dry run DeleteVolume really deleted the volume. Each of these calls now runs the checks its real path makes and then answers DryRunOperation (HTTP 412) without changing anything, the convention ModifyVolume already follows. CreateVolume answers once its parameters and tag specification are read. DeleteVolume first requires the volume to exist and be detached. AttachVolume requires the volume, the instance, its state, the Availability Zone and the device to pass. DetachVolume requires the attachment to match and the root device rules to allow it. CreateTags checks the ids, the keys, the lengths, that each resource exists and the per-resource limit. DeleteTags checks the ids and the keys. No backing device is created, deleted, attached or detached by a dry run. Every handler read of DryRun goes through dryRun(p), which refuses a blank or non-boolean value with InvalidParameterValue, as DeleteSecurityGroup and DeleteLaunchTemplateVersions already did by hand; both now use it, and checkDryRun sits on it. Every DryRunOperation comes from Ec2Service.dryRunOperation(). Tests: a DryRun value that is not a boolean is refused on the six volume and tag calls; under IAM enforcement a dry run needs the caller's current permission. AwsSdkErrors.assertAwsError replaces the copies the route and S3 enforcement tests kept.
This commit is contained in:
1 parent
39c29de635
commit
3ae36eb7be
8 files changed
+436
-69
No files matched your search
@@ -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<Route> 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<Route> 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<Route> 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<Route> 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;
|
||||
|
||||
@@ -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<Volume> 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<Volume> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -250,7 +250,7 @@ class Ec2QueryHandlerTest {
|
||||
assertEquals(200, response.getStatus());
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Tag>> 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<List<Tag>> 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());
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String> 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<String> 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<String> 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<String> volumes() {
|
||||
XmlPath described = ec2("DescribeVolumes");
|
||||
List<String> 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);
|
||||
}
|
||||
}
|
||||
+12
-17
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user