diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java index c900f8c891..cfe10d061f 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletionPolicyIntegrationTest.java @@ -1,12 +1,14 @@ package io.floci.aws.services.cloudformation; import io.floci.aws.core.common.XmlParser; +import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.time.Duration; import java.util.ArrayList; @@ -40,6 +42,9 @@ class CloudFormationDeletionPolicyIntegrationTest { private static final String EU_WEST_1_BUCKET = "eu-west-1"; + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + @Test void deletingNestedStacksDoesNotExhaustOperationWorkers() throws InterruptedException { String suffix = Long.toString(System.nanoTime(), 36); @@ -108,6 +113,7 @@ class CloudFormationDeletionPolicyIntegrationTest { """.formatted(bucket); String stackId = createStack(stackName, template); + cleanup.register(() -> deleteBucket(bucket, "object.txt")); given() .contentType("text/plain") @@ -153,6 +159,7 @@ class CloudFormationDeletionPolicyIntegrationTest { """.formatted(bucket); String stackId = createStack(stackName, template); + cleanup.register(() -> deleteBucket(bucket)); deleteStack(stackName); awaitStackStatus(stackId, "DELETE_COMPLETE"); @@ -196,6 +203,8 @@ class CloudFormationDeletionPolicyIntegrationTest { """.formatted(keptBucket, rolledBackBucket, suffix); String stackId = createStack(stackName, template); + cleanup.register(() -> deleteBucket(keptBucket)); + cleanup.register(() -> deleteStack(stackName)); awaitStackStatus(stackId, "ROLLBACK_COMPLETE"); assertBucketExists(keptBucket); @@ -264,6 +273,8 @@ class CloudFormationDeletionPolicyIntegrationTest { """.formatted(bucket1, bucket2); String stackId = createStack(stackName, template1); + cleanup.register(() -> deleteBucket(bucket1)); + cleanup.register(() -> deleteStack(stackName)); awaitStackStatus(stackId, "CREATE_COMPLETE"); String template2 = """ @@ -890,6 +901,7 @@ class CloudFormationDeletionPolicyIntegrationTest { """.formatted(suffix); String parentStackId = createStack(stackName, template); + cleanup.register(() -> deleteBucket(keptBucket)); try { awaitStackStatus(parentStackId, "ROLLBACK_COMPLETE"); cfnQuery("DescribeStacks", stackName + "-ChildStack").then().statusCode(400); @@ -1535,4 +1547,15 @@ class CloudFormationDeletionPolicyIntegrationTest { private static Response bucketRequest(String bucket) { return given().header("Host", bucket + ".localhost").when().get("/"); } + + /** + * Deletes a bucket a retaining policy kept, and the {@code keys} put in it. Every {@code @QuarkusTest} class + * shares one emulator, so a kept bucket would outlive the test. + */ + private static void deleteBucket(String bucket, String... keys) { + for (String key : keys) { + given().header("Host", bucket + ".localhost").when().delete("/" + key).then().statusCode(204); + } + given().header("Host", bucket + ".localhost").when().delete("/").then().statusCode(204); + } } diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java index d182d56f51..5963bc7cb3 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunIntegrationTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.emrserverless; import io.floci.aws.testing.EmrServerlessRequests; import io.floci.aws.testing.MutableClock; +import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.config.JsonConfig; @@ -13,6 +14,7 @@ import io.restassured.specification.RequestSpecification; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.math.BigDecimal; import java.time.Duration; @@ -36,6 +38,9 @@ class EmrServerlessJobRunIntegrationTest { @Inject MutableClock clock; + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -45,18 +50,39 @@ class EmrServerlessJobRunIntegrationTest { return EmrServerlessRequests.emrServerless("us-east-1"); } - private static String createApplication(String extra) { + private String createApplication(String extra) { return createApplicationOn("emr-7.5.0", extra); } - private static String createApplicationOn(String releaseLabel, String extra) { - return givenReq() + /** Creates an application, deleted after the test: every {@code @QuarkusTest} class shares one emulator. */ + private String createApplicationOn(String releaseLabel, String extra) { + String applicationId = givenReq() .body(""" {"name": "jobs-%s", "releaseLabel": "%s", "type": "SPARK", "clientToken": "%s"%s} """.formatted(UUID.randomUUID(), releaseLabel, UUID.randomUUID(), extra)) .when().post("/applications") .then().statusCode(200) .extract().path("applicationId"); + cleanup.register(() -> deleteApplication(applicationId)); + return applicationId; + } + + /** + * Cancels the application's runs still going, which StopApplication requires, then stops and deletes it, unless + * the test deleted it already. + */ + private static void deleteApplication(String applicationId) { + String application = "/applications/" + applicationId; + String state = givenReq().when().get(application).then().statusCode(200).extract().path("application.state"); + if ("TERMINATED".equals(state)) { + return; + } + List going = givenReq().when().get(application + "/jobruns").then().statusCode(200).extract() + .jsonPath().getList("jobRuns.findAll { !['SUCCESS', 'FAILED', 'CANCELLED'].contains(it.state) }.id"); + for (String jobRunId : going) { + givenReq().when().delete(application + "/jobruns/" + jobRunId).then().statusCode(200); + } + EmrServerlessRequests.deleteApplication("us-east-1", applicationId); } private static String sparkRun(String clientToken, String extra) { diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java index f1ecf9b710..7ede69f920 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java @@ -118,6 +118,8 @@ class IamRestRouteEnforcementIntegrationTest { created.then().statusCode(201); String arn = XmlParser.extractFirst(created.asString(), "ARN", null); String etag = created.header("ETag"); + cleanup.register(() -> given().header("Authorization", auth(ADMIN, "cloudfront")).header("If-Match", etag) + .delete("/2020-05-31/key-value-store/" + name).then().statusCode(204)); policy(user, allow("cloudfront:*", "*") + "," + "{\"Effect\":\"Deny\",\"Action\":\"cloudfront:DeleteKeyValueStore\",\"Resource\":\"" + arn + "\"}"); @@ -900,11 +902,15 @@ class IamRestRouteEnforcementIntegrationTest { void accountIsCheckedOnTheMemberAccountOfTheCallersOrganization() { OrganizationsRequests.request(MANAGEMENT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}") .when().post("/").then().statusCode(200); + cleanup.register(() -> OrganizationsRequests.request(MANAGEMENT, "DeleteOrganization", "{}") + .when().post("/").then().statusCode(200)); String organization = OrganizationsRequests.request(MANAGEMENT, "DescribeOrganization", "{}") .when().post("/").then().statusCode(200).extract().path("Organization.Id"); String member = OrganizationsRequests.request(MANAGEMENT, "CreateAccount", "{\"Email\":\"route-contact@example.com\",\"AccountName\":\"RouteContact\"}") .when().post("/").then().statusCode(200).extract().path("CreateAccountStatus.AccountId"); + cleanup.register(() -> OrganizationsRequests.request(MANAGEMENT, "RemoveAccountFromOrganization", + "{\"AccountId\":\"" + member + "\"}").when().post("/").then().statusCode(200)); OrganizationsRequests.request(MANAGEMENT, "EnableAWSServiceAccess", "{\"ServicePrincipal\":\"account.amazonaws.com\"}") .when().post("/").then().statusCode(200); @@ -1019,8 +1025,8 @@ class IamRestRouteEnforcementIntegrationTest { @Test void ramIsCheckedOnTheResourceShareItNamesInItsBodyAndQuery() { - String share = adminOf("ram").body("{\"name\":\"route-share-" + suffix() + "\"}").post("/createresourceshare") - .then().statusCode(200).extract().path("resourceShare.resourceShareArn"); + String share = madeShare(adminOf("ram").body("{\"name\":\"route-share-" + suffix() + "\"}") + .post("/createresourceshare").then()); String other = "arn:aws:ram:us-east-1:" + ACCOUNT + ":resource-share/other"; String user = user("route-ram"); @@ -1249,10 +1255,11 @@ class IamRestRouteEnforcementIntegrationTest { refused(request(user, service, "POST", path, body.apply("red")), action); } - /** A create that got past the check and made a resource share, removed afterwards. */ - private void madeShare(ValidatableResponse response) { + /** A create that got past the check and made a resource share, removed afterwards; returns the share's ARN. */ + private String madeShare(ValidatableResponse response) { String share = response.statusCode(200).extract().path("resourceShare.resourceShareArn"); cleanup.register(() -> adminOf("ram").queryParam("resourceShareArn", share).delete("/deleteresourceshare")); + return share; } /** Refuses a request until the caller holds the action, then lets it past the check. */ diff --git a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest.java index c02f6ebd7e..f77c098f17 100644 --- a/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/redshiftserverless/RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest.java @@ -100,10 +100,9 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest { "Action":"redshift-serverless:GetSnapshot"} ]} """.formatted(CALLER, CALLER); - call(OWNER, "CreateNamespace", Map.of("namespaceName", namespace, "adminUsername", "admin")).statusCode(200); - String arn = call(OWNER, "CreateSnapshot", Map.of("snapshotName", snapshot, "namespaceName", namespace)) - .statusCode(200).extract().path("snapshot.snapshotArn"); - call(OWNER, "CreateSnapshot", Map.of("snapshotName", privateSnapshot, "namespaceName", namespace)).statusCode(200); + createNamespace(OWNER, namespace, Map.of()); + String arn = createSnapshot(snapshot, namespace); + createSnapshot(privateSnapshot, namespace); Map byName = Map.of("snapshotName", snapshot, "ownerAccount", OWNER); Map byArn = Map.of("snapshotArn", arn, "ownerAccount", OWNER); Map list = Map.of("ownerAccount", OWNER); @@ -152,16 +151,11 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest { String unprivilegedKey = user(CALLER, "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + "\"Action\":\"redshift-serverless:GetNamespace\",\"Resource\":\"*\"}]}"); - call(OWNER, "CreateNamespace", Map.of("namespaceName", sourceNamespace, "adminUsername", "admin")) - .statusCode(200); - String snapshotArn = call(OWNER, "CreateSnapshot", - Map.of("snapshotName", snapshot, "namespaceName", sourceNamespace)) - .statusCode(200).extract().path("snapshot.snapshotArn"); + createNamespace(OWNER, sourceNamespace, Map.of()); + String snapshotArn = createSnapshot(snapshot, sourceNamespace); for (String account : List.of(CALLER, STRANGER)) { - call(account, "CreateNamespace", Map.of("namespaceName", namespace, "adminUsername", "admin")) - .statusCode(200); - call(account, "CreateWorkgroup", Map.of("workgroupName", workgroup, "namespaceName", namespace)) - .statusCode(200); + createNamespace(account, namespace, Map.of()); + createWorkgroup(account, workgroup, namespace); } Map byName = Map.of("namespaceName", namespace, "workgroupName", workgroup, "snapshotName", snapshot, "ownerAccount", OWNER); @@ -267,18 +261,40 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest { String workgroup = "kms-wg-" + suffix; String key = kms(OWNER, "CreateKey", Map.of("Description", "snapshot key")).statusCode(200) .extract().path(keyField); - call(OWNER, "CreateNamespace", Map.of("namespaceName", sourceNamespace, "adminUsername", "admin", - "kmsKeyId", key)).statusCode(200); - String snapshotArn = call(OWNER, "CreateSnapshot", - Map.of("snapshotName", snapshot, "namespaceName", sourceNamespace)) - .statusCode(200).extract().path("snapshot.snapshotArn"); - call(restoringAccount, "CreateNamespace", Map.of("namespaceName", namespace, "adminUsername", "admin")) - .statusCode(200); - call(restoringAccount, "CreateWorkgroup", Map.of("workgroupName", workgroup, "namespaceName", namespace)) - .statusCode(200); + cleanup.register(() -> scheduleKeyDeletion(key)); + createNamespace(OWNER, sourceNamespace, Map.of("kmsKeyId", key)); + String snapshotArn = createSnapshot(snapshot, sourceNamespace); + createNamespace(restoringAccount, namespace, Map.of()); + createWorkgroup(restoringAccount, workgroup, namespace); return new EncryptedSnapshot(key, snapshot, snapshotArn, namespace, workgroup); } + /** + * A namespace of {@code account}'s with {@code settings}, deleted after the test as the workgroups and snapshots + * below are: every {@code @QuarkusTest} class shares one emulator. + */ + private void createNamespace(String account, String namespace, Map settings) { + Map request = new HashMap<>(settings); + request.put("namespaceName", namespace); + request.put("adminUsername", "admin"); + call(account, "CreateNamespace", request).statusCode(200); + cleanup.register(() -> call(account, "DeleteNamespace", Map.of("namespaceName", namespace)).statusCode(200)); + } + + private void createWorkgroup(String account, String workgroup, String namespace) { + call(account, "CreateWorkgroup", Map.of("workgroupName", workgroup, "namespaceName", namespace)) + .statusCode(200); + cleanup.register(() -> call(account, "DeleteWorkgroup", Map.of("workgroupName", workgroup)).statusCode(200)); + } + + /** The owner's snapshot of {@code namespace}, deleted after the test; its ARN. */ + private String createSnapshot(String snapshot, String namespace) { + String arn = call(OWNER, "CreateSnapshot", Map.of("snapshotName", snapshot, "namespaceName", namespace)) + .statusCode(200).extract().path("snapshot.snapshotArn"); + cleanup.register(() -> call(OWNER, "DeleteSnapshot", Map.of("snapshotName", snapshot)).statusCode(200)); + return arn; + } + /** An encrypted snapshot, its key as the namespace was given it, and where it is restored. */ private record EncryptedSnapshot(String key, String snapshot, String snapshotArn, String namespace, String workgroup) { @@ -309,6 +325,15 @@ class RedshiftServerlessSnapshotSharingIamEnforcementIntegrationTest { + "\"Action\":\"kms:Decrypt\",\"Resource\":\"*\"" + condition + "}]}"; } + /** Schedules {@code keyId}'s deletion, which is how KMS removes a key, unless a test has scheduled it already. */ + private void scheduleKeyDeletion(String keyId) { + String state = kms(OWNER, "DescribeKey", Map.of("KeyId", keyId)).statusCode(200) + .extract().path("KeyMetadata.KeyState"); + if (!"PendingDeletion".equals(state)) { + kms(OWNER, "ScheduleKeyDeletion", Map.of("KeyId", keyId, "PendingWindowInDays", "7")).statusCode(200); + } + } + private void putKeyPolicy(String keyId, String policy) { kms(OWNER, "PutKeyPolicy", Map.of("KeyId", keyId, "PolicyName", "default", "Policy", policy)) .statusCode(200); diff --git a/src/test/java/io/floci/aws/services/s3/S3LeadingSlashKeyIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3LeadingSlashKeyIntegrationTest.java index c7d796f16d..c32e58db15 100644 --- a/src/test/java/io/floci/aws/services/s3/S3LeadingSlashKeyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3LeadingSlashKeyIntegrationTest.java @@ -3,10 +3,7 @@ package io.floci.aws.services.s3; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; import java.net.URI; import java.net.http.HttpClient; @@ -31,7 +28,6 @@ import static org.junit.jupiter.api.Assertions.*; * because RestAssured normalizes double slashes in URL paths. */ @QuarkusTest -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) class S3LeadingSlashKeyIntegrationTest { private static final String BUCKET = "test-slash-bucket"; @@ -39,34 +35,31 @@ class S3LeadingSlashKeyIntegrationTest { @TestHTTPResource("/") URI baseUri; - /** The slash-only key test's bucket. Every {@code @QuarkusTest} class shares one emulator, so it goes too. */ - private String slashOnlyBucket; + /** The running test's bucket. Every {@code @QuarkusTest} class shares one emulator, so it goes after the test. */ + private String createdBucket; + /** The keys the running test writes to its bucket, deleted before it. */ + private List writtenKeys = List.of(); @AfterEach - void deleteTheSlashOnlyBucket() throws Exception { - if (slashOnlyBucket == null) { + void deleteTheBucket() throws Exception { + if (createdBucket == null) { return; } HttpClient client = HttpClient.newHttpClient(); String base = baseUri.toString().replaceAll("/$", ""); - for (String key : List.of("/", "//")) { - HttpRequest delete = HttpRequest.newBuilder(URI.create(base + "/" + slashOnlyBucket + "/" + key)) + for (String key : writtenKeys) { + HttpRequest delete = HttpRequest.newBuilder(URI.create(base + "/" + createdBucket + "/" + key)) .DELETE().build(); assertEquals(204, client.send(delete, HttpResponse.BodyHandlers.ofString()).statusCode(), key); } - given().when().delete("/" + slashOnlyBucket).then().statusCode(204); + given().when().delete("/" + createdBucket).then().statusCode(204); } - // --- Setup --- - - @Test - @Order(0) - void createBucket() { - given() - .when() - .put("/" + BUCKET) - .then() - .statusCode(200); + /** Creates {@code bucket}, deleted after the test with the {@code keys} the test writes to it. */ + private void createBucket(String bucket, String... keys) { + given().when().put("/" + bucket).then().statusCode(200); + createdBucket = bucket; + writtenKeys = List.of(keys); } // --- Test 1: Distinct Objects --- @@ -75,8 +68,8 @@ class S3LeadingSlashKeyIntegrationTest { // Bug: both map to "file.txt", so content-B overwrites content-A. @Test - @Order(1) void distinctObjects_leadingSlashKeyIsSeparateFromNormalKey() throws Exception { + createBucket(BUCKET, "file.txt", "/file.txt"); HttpClient client = HttpClient.newHttpClient(); String base = baseUri.toString().replaceAll("/$", ""); @@ -126,8 +119,8 @@ class S3LeadingSlashKeyIntegrationTest { // but the key is wrong (leading slash stripped). @Test - @Order(2) void putGetRoundTrip_leadingSlashKeyPreservesContent() throws Exception { + createBucket(BUCKET, "/leading.txt"); HttpClient client = HttpClient.newHttpClient(); String base = baseUri.toString().replaceAll("/$", ""); String content = "leading-slash-content-12345"; @@ -169,8 +162,8 @@ class S3LeadingSlashKeyIntegrationTest { // assert correct Content-Length and Content-Type. @Test - @Order(3) void headLeadingSlashKey_returnsCorrectMetadata() throws Exception { + createBucket(BUCKET, "/meta.txt"); HttpClient client = HttpClient.newHttpClient(); String base = baseUri.toString().replaceAll("/$", ""); String content = "metadata-test-content"; @@ -209,8 +202,8 @@ class S3LeadingSlashKeyIntegrationTest { // Bug: DELETE //data.txt actually deletes "data.txt" (the normal key). @Test - @Order(4) void deleteIsolation_deletingLeadingSlashKeyDoesNotAffectNormalKey() throws Exception { + createBucket(BUCKET, "data.txt", "/data.txt"); HttpClient client = HttpClient.newHttpClient(); String base = baseUri.toString().replaceAll("/$", ""); @@ -255,14 +248,13 @@ class S3LeadingSlashKeyIntegrationTest { // Bug: both map to "file.txt", so list shows only one entry. @Test - @Order(5) void listShowsBoth_leadingSlashAndNormalKeyAppearSeparately() throws Exception { HttpClient client = HttpClient.newHttpClient(); String base = baseUri.toString().replaceAll("/$", ""); // Use a dedicated bucket to avoid interference from other tests String listBucket = "test-slash-list-bucket"; - given().when().put("/" + listBucket).then().statusCode(200); + createBucket(listBucket, "file.txt", "/file.txt"); // PUT to normal key: file.txt HttpRequest putNormal = HttpRequest.newBuilder() @@ -304,12 +296,10 @@ class S3LeadingSlashKeyIntegrationTest { } @Test - @Order(6) void aKeyOfOnlySlashesIsThatObjectNotTheBucket() throws Exception { // "/bucket//" names the key "/" and "/bucket///" the key "//": collapsed, either reads as the bucket. String bucket = "test-slash-only-bucket"; - given().when().put("/" + bucket).then().statusCode(200); - slashOnlyBucket = bucket; + createBucket(bucket, "/", "//"); HttpClient client = HttpClient.newHttpClient(); String base = baseUri.toString().replaceAll("/$", ""); URI oneSlash = URI.create(base + "/" + bucket + "//");