Light, fluffy, and always free - The AWS Local Emulator alternative
fix(config): drop a conformance pack's tags when the pack is deleted (#5779)
Allen Sanbornf7240b8ace60
diff --git a/src/main/java/io/github/hectorvent/floci/services/configservice/AwsConfigService.java b/src/main/java/io/github/hectorvent/floci/services/configservice/AwsConfigService.javaindex 98855ebe8d..7c7c6a8800 100644--- a/src/main/java/io/github/hectorvent/floci/services/configservice/AwsConfigService.java+++ b/src/main/java/io/github/hectorvent/floci/services/configservice/AwsConfigService.java@@ -821,33 +821,47 @@ public class AwsConfigService {// --- Conformance Packs ---+ /** Put on an existing pack is a get-then-put, so it runs under the lock delete takes. Unlocked,+ * a delete landing between the get and the put would remove the pack and its tags, and the+ * put would then re-insert it under its old ARN: a successful delete, a pack that survives,+ * and tags silently gone. */public ConformancePack putConformancePack(String region, String packName,String templateS3Uri, String templateBody) {- Map<String, ConformancePack> store = packsFor(region);- ConformancePack existing = store.get(packName);- if (existing != null) {- ConformancePack updated = new ConformancePack(existing.conformancePackName(), existing.conformancePackArn(),- existing.conformancePackId(), templateS3Uri, templateBody);- store.put(packName, updated);+ synchronized (lockFor(conformancePackLockKey(region, packName))) {+ Map<String, ConformancePack> store = packsFor(region);+ ConformancePack existing = store.get(packName);+ if (existing != null) {+ ConformancePack updated = new ConformancePack(existing.conformancePackName(),+ existing.conformancePackArn(), existing.conformancePackId(), templateS3Uri, templateBody);+ store.put(packName, updated);+ persistRegion(conformancePacks, region);+ return updated;+ }+ String packId = "conformance-pack-" + shortId();+ String packArn = AwsArnUtils.Arn.of("config", region, regionResolver.getAccountId(),+ "conformance-pack/" + packName + "/" + packId).toString();+ ConformancePack pack = new ConformancePack(packName, packArn, packId, templateS3Uri, templateBody);+ store.put(packName, pack);persistRegion(conformancePacks, region);- return updated;+ return pack;}- String packId = "conformance-pack-" + shortId();- String packArn = AwsArnUtils.Arn.of("config", region, regionResolver.getAccountId(),- "conformance-pack/" + packName + "/" + packId).toString();- ConformancePack pack = new ConformancePack(packName, packArn, packId, templateS3Uri, templateBody);- store.put(packName, pack);- persistRegion(conformancePacks, region);- return pack;}public void deleteConformancePack(String region, String packName) {- Map<String, ConformancePack> store = packsFor(region);- if (store.remove(packName) == null) {- throw new AwsException("NoSuchConformancePackException",- "Conformance pack '" + packName + "' does not exist.", 400);+ synchronized (lockFor(conformancePackLockKey(region, packName))) {+ Map<String, ConformancePack> store = packsFor(region);+ ConformancePack removed = store.remove(packName);+ if (removed == null) {+ throw new AwsException("NoSuchConformancePackException",+ "Conformance pack '" + packName + "' does not exist.", 400);+ }+ persistRegion(conformancePacks, region);+ tags.remove(removed.conformancePackArn());}- persistRegion(conformancePacks, region);+ }++ private static String conformancePackLockKey(String region, String packName) {+ return "conformance-pack|" + region + "|" + packName;}public List<ConformancePack> describeConformancePacks(String region, List<String> names) {diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServiceAggregationAuthorizationTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServiceAggregationAuthorizationTest.javaindex 4b1d9fa262..be0bfb7c65 100644--- a/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServiceAggregationAuthorizationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/configservice/AwsConfigServiceAggregationAuthorizationTest.java@@ -1,9 +1,16 @@package io.github.hectorvent.floci.services.configservice;+import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.core.storage.WriteProfile;import io.github.hectorvent.floci.services.configservice.model.AggregationAuthorization;+import io.github.hectorvent.floci.services.configservice.model.ConformancePack;+import io.github.hectorvent.floci.testing.ParkingStore;import org.junit.jupiter.api.Test;import java.util.ArrayList;@@ -16,10 +23,13 @@ import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicReference;import java.util.stream.Collectors;+import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertSame;@@ -203,6 +213,71 @@ class AwsConfigServiceAggregationAuthorizationTest {"tags of a deleted authorization must not resurface on the reused ARN");}+ @Test+ void deleteConformancePackDropsItsTags() {+ AwsConfigService service = service();+ String arn = service.putConformancePack(REGION, "pack", "s3://bucket/template.yaml", null)+ .conformancePackArn();+ service.tagResource(arn, List.of(Map.of("Key", "env", "Value", "prod")));++ service.deleteConformancePack(REGION, "pack");++ assertTrue(service.listTagsForResource(arn).isEmpty(),+ "tags of a deleted conformance pack must not outlive it");+ }++ /**+ * Put on an existing pack is a get-then-put. Unlocked, a Delete landing between the get and+ * the put removes the pack and its tags, then the Put re-inserts the pack under its old ARN:+ * Delete reported success, yet the pack survives with its tags silently gone. The window is a+ * few in-memory instructions, so rather than sample it, the Put is parked in its persist,+ * still inside the section the lock guards, and the Delete must be seen waiting on it.+ */+ @Test+ void aPackDeleteWaitsForAnUpdateAlreadyInProgress() throws Exception {+ ParkingStore<Map<String, ConformancePack>> packs = new ParkingStore<>();+ AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, ACCOUNT),+ new StorageFactory(null, null) {+ @Override+ @SuppressWarnings("unchecked")+ public <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,+ TypeReference<Map<String, V>> typeReference, WriteProfile profile) {+ return fileName.equals("config-conformance-packs.json")+ ? new AccountAwareStorageBackend<>((StorageBackend<String, V>) (Object) packs,+ null, ACCOUNT)+ : AccountAwareStorageBackend.inMemory(ACCOUNT);+ }+ });+ service.initializeStorage();+ String arn = service.putConformancePack(REGION, "pack", "s3://bucket/v1.yaml", null)+ .conformancePackArn();+ service.tagResource(arn, List.of(Map.of("Key", "env", "Value", "prod")));++ packs.parkNextWrite();+ ExecutorService pool = Executors.newFixedThreadPool(2);+ try {+ Future<?> put = pool.submit(() -> service.putConformancePack(REGION, "pack", "s3://bucket/v2.yaml", null));+ assertTrue(packs.awaitParked(), "the update must reach its persist");+ AtomicReference<Thread> deleteThread = new AtomicReference<>();+ Future<?> delete = pool.submit(() -> {+ deleteThread.set(Thread.currentThread());+ service.deleteConformancePack(REGION, "pack");+ });+ awaitBlockedOrDone(deleteThread, delete);+ assertFalse(delete.isDone(), "the delete ran while an update of the same pack was mid-write");++ packs.release();+ put.get(2, TimeUnit.SECONDS);+ delete.get(2, TimeUnit.SECONDS);+ } finally {+ pool.shutdownNow();+ }++ assertTrue(service.describeConformancePacks(REGION, null).isEmpty(),+ "a Delete that succeeded left the pack it deleted in the store");+ assertTrue(service.listTagsForResource(arn).isEmpty(), "the deleted pack's tags survived");+ }+@Testvoid rejectsAnAccountIdThatIsNotTwelveDigits() {AwsConfigService service = service();diff --git a/src/test/java/io/github/hectorvent/floci/services/configservice/ConformancePackIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/configservice/ConformancePackIntegrationTest.javaindex 213c77abf9..29f27dc320 100644--- a/src/test/java/io/github/hectorvent/floci/services/configservice/ConformancePackIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/configservice/ConformancePackIntegrationTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.configservice;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Order;@@ -18,6 +19,8 @@ class ConformancePackIntegrationTest {private static final String CONTENT_TYPE = "application/x-amz-json-1.1";private static final String TARGET_PREFIX = "StarlingDoveService.";+ private static String packArn;+@BeforeAllstatic void configureRestAssured() {RestAssuredJsonUtils.configureAwsContentTypes();@@ -26,7 +29,7 @@ class ConformancePackIntegrationTest {@Test@Order(1)void putConformancePack() {- given()+ packArn = given().header("X-Amz-Target", TARGET_PREFIX + "PutConformancePack").contentType(CONTENT_TYPE).body("""@@ -39,7 +42,17 @@ class ConformancePackIntegrationTest {.post("/").then().statusCode(200)- .body("ConformancePackArn", notNullValue());+ .body("ConformancePackArn", notNullValue())+ .extract().path("ConformancePackArn");++ given()+ .header("X-Amz-Target", TARGET_PREFIX + "TagResource")+ .contentType(CONTENT_TYPE)+ .body("{\"ResourceArn\": \"" + packArn + "\", \"Tags\": [{\"Key\": \"env\", \"Value\": \"prod\"}]}")+ .when()+ .post("/")+ .then()+ .statusCode(200);}@Test@@ -83,6 +96,8 @@ class ConformancePackIntegrationTest {@Test@Order(4)void deleteConformancePack() {+ listPackTags().body("Tags", hasSize(1));+given().header("X-Amz-Target", TARGET_PREFIX + "DeleteConformancePack").contentType(CONTENT_TYPE)@@ -93,6 +108,20 @@ class ConformancePackIntegrationTest {.post("/").then().statusCode(200);++ // The pack's tags go with it.+ listPackTags().body("Tags", empty());+ }++ private ValidatableResponse listPackTags() {+ return given()+ .header("X-Amz-Target", TARGET_PREFIX + "ListTagsForResource")+ .contentType(CONTENT_TYPE)+ .body("{\"ResourceArn\": \"" + packArn + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsPolicyAndSandboxEditsTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsPolicyAndSandboxEditsTest.javaindex 110949d385..e3827ab77a 100644--- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsPolicyAndSandboxEditsTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsPolicyAndSandboxEditsTest.java@@ -6,11 +6,11 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;import io.github.hectorvent.floci.services.sns.model.SentSms;import io.github.hectorvent.floci.services.sns.model.SmsSandboxPhoneNumber;import io.github.hectorvent.floci.services.sns.model.Topic;+import io.github.hectorvent.floci.testing.ParkingStore;import org.junit.jupiter.api.Test;import org.mockito.Mockito;import java.util.List;-import java.util.Optional;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -236,40 +236,6 @@ class SnsPolicyAndSandboxEditsTest {return code.group();}- /** A store whose next read, once armed, parks after reading until released. */- private static final class ParkingStore<V> extends InMemoryStorage<String, V> {-- private final AtomicBoolean parkNext = new AtomicBoolean();- private final CountDownLatch parked = new CountDownLatch(1);- private final CountDownLatch released = new CountDownLatch(1);-- void parkNextRead() {- parkNext.set(true);- }-- boolean awaitParked() throws InterruptedException {- return parked.await(2, TimeUnit.SECONDS);- }-- void release() {- released.countDown();- }-- @Override- public Optional<V> get(String key) {- Optional<V> value = super.get(key);- if (parkNext.getAndSet(false)) {- parked.countDown();- try {- released.await();- } catch (InterruptedException e) {- Thread.currentThread().interrupt();- }- }- return value;- }- }-/** Where SNS records the SMS it sends, made to fail on demand. */private static final class FailingTexts extends InMemoryStorage<String, SentSms> {diff --git a/src/test/java/io/github/hectorvent/floci/testing/ParkingStore.java b/src/test/java/io/github/hectorvent/floci/testing/ParkingStore.javanew file mode 100644index 0000000000..e48535150f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/testing/ParkingStore.java@@ -0,0 +1,67 @@+package io.github.hectorvent.floci.testing;++import io.github.hectorvent.floci.core.storage.InMemoryStorage;++import java.util.Optional;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;++/**+ * An in-memory store that, once armed, parks the next read (after reading) or the next write+ * (before writing) until released, so a test can hold one request inside its read-modify-write+ * window while a second one arrives. Parks once per instance. An interrupt, such as the+ * {@code shutdownNow} a test runs in its {@code finally}, releases a parked thread.+ */+public final class ParkingStore<V> extends InMemoryStorage<String, V> {++ private final AtomicBoolean parkNextRead = new AtomicBoolean();+ private final AtomicBoolean parkNextWrite = new AtomicBoolean();+ private final CountDownLatch parked = new CountDownLatch(1);+ private final CountDownLatch released = new CountDownLatch(1);++ /** Parks the next {@code get}, after it has read the value. */+ public void parkNextRead() {+ parkNextRead.set(true);+ }++ /** Parks the next {@code put}, before it writes the value. */+ public void parkNextWrite() {+ parkNextWrite.set(true);+ }++ /** Waits up to two seconds for the armed call to park; false if it never did. */+ public boolean awaitParked() throws InterruptedException {+ return parked.await(2, TimeUnit.SECONDS);+ }++ public void release() {+ released.countDown();+ }++ @Override+ public Optional<V> get(String key) {+ Optional<V> value = super.get(key);+ if (parkNextRead.getAndSet(false)) {+ park();+ }+ return value;+ }++ @Override+ public void put(String key, V value) {+ if (parkNextWrite.getAndSet(false)) {+ park();+ }+ super.put(key, value);+ }++ private void park() {+ parked.countDown();+ try {+ released.await();+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ }+ }+}