diff --git a/src/main/java/io/github/hectorvent/floci/config/ClockProducer.java b/src/main/java/io/github/hectorvent/floci/config/ClockProducer.java new file mode 100644 index 0000000000..66d12eb282 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/config/ClockProducer.java @@ -0,0 +1,16 @@ +package io.github.hectorvent.floci.config; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Produces; + +import java.time.Clock; + +@ApplicationScoped +public class ClockProducer { + + @Produces + @ApplicationScoped + public Clock clock() { + return Clock.systemUTC(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index a2933258bd..017ca0c285 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -577,6 +577,9 @@ public interface EmulatorConfig { interface CloudFormationServiceConfig { @WithDefault("true") boolean enabled(); + + @WithDefault("30") + long deletedStackRetentionSeconds(); } interface AcmServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 7a35d80fff..28dbe11a22 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -17,6 +17,7 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.net.URI; +import java.time.Clock; import java.time.Instant; import java.util.*; import java.util.regex.Matcher; @@ -35,6 +36,7 @@ public class CloudFormationService { private static final Logger LOG = Logger.getLogger(CloudFormationService.class); private final ConcurrentHashMap stacks = new ConcurrentHashMap<>(); + private final ConcurrentHashMap deletedStacks = new ConcurrentHashMap<>(); // Global exports registry: region:exportName -> exportValue private final ConcurrentHashMap exports = new ConcurrentHashMap<>(); private final ExecutorService executor = Executors.newCachedThreadPool(); @@ -44,23 +46,25 @@ public class CloudFormationService { private final ObjectMapper objectMapper; private final EmulatorConfig config; private final RegionResolver regionResolver; + private final Clock clock; @Inject public CloudFormationService(CloudFormationResourceProvisioner provisioner, S3Service s3Service, ObjectMapper objectMapper, EmulatorConfig config, - RegionResolver regionResolver) { + RegionResolver regionResolver, Clock clock) { this.provisioner = provisioner; this.s3Service = s3Service; this.objectMapper = objectMapper; this.config = config; this.regionResolver = regionResolver; + this.clock = clock; } // ── DescribeStacks ──────────────────────────────────────────────────────── public List describeStacks(String stackName, String region) { if (stackName != null && !stackName.isBlank()) { - Stack stack = resolveStack(stackName, region); + Stack stack = resolveStackForDescribe(stackName, region); if (stack == null) { throw new AwsException("ValidationError", "Stack with id " + stackName + " does not exist", 400); @@ -129,7 +133,7 @@ public class CloudFormationService { "CREATE_IN_PROGRESS".equals(stack.getStatus()); stack.setStatus(isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS"); - stack.setLastUpdatedTime(Instant.now()); + stack.setLastUpdatedTime(now()); addEvent(stack, stack.getStackName(), stack.getStackId(), "AWS::CloudFormation::Stack", isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null); @@ -156,6 +160,7 @@ public class CloudFormationService { // ── DeleteStack ─────────────────────────────────────────────────────────── public void deleteStack(String stackName, String region) { + purgeExpiredDeletedStacks(); Stack stack = resolveStack(stackName, region); if (stack == null) { return; // Already gone — no-op @@ -177,7 +182,11 @@ public class CloudFormationService { // ── DescribeStackEvents ─────────────────────────────────────────────────── public List describeStackEvents(String stackName, String region) { - Stack stack = getStackOrThrow(stackName, region); + Stack stack = resolveStackForDescribe(stackName, region); + if (stack == null) { + throw new AwsException("ValidationError", + "Stack with id " + stackName + " does not exist", 400); + } List events = new ArrayList<>(stack.getEvents()); Collections.reverse(events); return events; @@ -370,7 +379,7 @@ public class CloudFormationService { String completeStatus = isCreate ? "CREATE_COMPLETE" : "UPDATE_COMPLETE"; stack.setStatus(completeStatus); - stack.setLastUpdatedTime(Instant.now()); + stack.setLastUpdatedTime(now()); addEvent(stack, stack.getStackName(), stack.getStackId(), "AWS::CloudFormation::Stack", completeStatus, null); LOG.infov("Stack {0} execution complete: {1}", stack.getStackName(), completeStatus); @@ -406,6 +415,9 @@ public class CloudFormationService { "AWS::CloudFormation::Stack", "DELETE_COMPLETE", null); removeStackExports(stack, region); stacks.remove(key(stack.getStackName(), region)); + deletedStacks.put(stack.getStackId(), new DeletedStackEntry( + stack, + now().plusSeconds(config.services().cloudformation().deletedStackRetentionSeconds()))); LOG.infov("Stack {0} deleted", stack.getStackName()); } catch (Exception e) { @@ -618,7 +630,7 @@ public class CloudFormationService { stack.setStatus("REVIEW_IN_PROGRESS"); String stackId = AwsArnUtils.Arn.of("cloudformation", region, regionResolver.getAccountId(), "stack/" + stackName + "/" + UUID.randomUUID()).toString(); stack.setStackId(stackId); - stack.setCreationTime(Instant.now()); + stack.setCreationTime(now()); return stack; } @@ -644,6 +656,41 @@ public class CloudFormationService { return stack; } + private Stack resolveStackForDescribe(String stackNameOrArn, String region) { + Stack stack = resolveStack(stackNameOrArn, region); + if (stack != null) { + return stack; + } + if (stackNameOrArn != null && stackNameOrArn.startsWith("arn:")) { + DeletedStackEntry deleted = deletedStacks.get(stackNameOrArn); + if (deleted != null) { + if (deleted.isExpired(now())) { + deletedStacks.remove(stackNameOrArn, deleted); + return null; + } + if (region.equals(deleted.stack().getRegion())) { + return deleted.stack(); + } + } + } + return null; + } + + private Instant now() { + return Instant.now(clock); + } + + private void purgeExpiredDeletedStacks() { + Instant current = now(); + deletedStacks.entrySet().removeIf(entry -> entry.getValue().isExpired(current)); + } + + private record DeletedStackEntry(Stack stack, Instant expiresAt) { + private boolean isExpired(Instant now) { + return now.isAfter(expiresAt); + } + } + /** * Resolves a changeset name from either a short name or a full ARN. * The AWS CLI passes the full ARN (arn:aws:cloudformation:…:changeSet//) diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index e79dab78bf..b71764360d 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -194,6 +194,7 @@ floci: enabled: true cloudformation: enabled: true + deleted-stack-retention-seconds: 30 acm: enabled: true validation-wait-seconds: 0 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java index 3f84e50713..f800c437ea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java @@ -1,8 +1,11 @@ package io.github.hectorvent.floci.services.cloudformation; +import io.github.hectorvent.floci.testing.MutableClock; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.fasterxml.jackson.databind.JsonNode; @@ -10,6 +13,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.Base64; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -33,11 +37,19 @@ class CloudFormationIntegrationTest { private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + @Inject + MutableClock clock; + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); } + @BeforeEach + void resetClock() { + clock.reset(); + } + private static byte[] buildHandlerZip() { try { var baos = new ByteArrayOutputStream(); @@ -999,6 +1011,170 @@ class CloudFormationIntegrationTest { .body(containsString("arn-events-stack")); } + @Test + void describeDeletedStackEvents_byArn_returnsDeleteCompleteEvents() throws Exception { + String template = """ + { + "Resources": { + "MyBucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "deleted-arn-events-test-bucket" + } + } + } + } + """; + + String createResponse = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "deleted-arn-events-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")) + .extract().asString(); + + String stackArn = createResponse.substring( + createResponse.indexOf("") + "".length(), + createResponse.indexOf("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", "deleted-arn-events-stack") + .when() + .post("/") + .then() + .statusCode(200); + + String deletedEventsXml = null; + long deadline = System.currentTimeMillis() + 10_000; + while (System.currentTimeMillis() < deadline) { + deletedEventsXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackEvents") + .formParam("StackName", stackArn) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + if (deletedEventsXml.contains("DELETE_COMPLETE")) { + break; + } + Thread.sleep(200); + } + + assertThat(deletedEventsXml, containsString("" + stackArn + "")); + assertThat(deletedEventsXml, containsString("DELETE_COMPLETE")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackArn) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("DELETE_COMPLETE")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "deleted-arn-events-stack") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("does not exist")); + } + + @Test + void describeDeletedStack_byArn_expiresAfterRetentionWindow() throws Exception { + String template = """ + { + "Resources": { + "MyBucket": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketName": "deleted-arn-expiry-test-bucket" + } + } + } + } + """; + + String createResponse = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "deleted-arn-expiry-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")) + .extract().asString(); + + String stackArn = createResponse.substring( + createResponse.indexOf("") + "".length(), + createResponse.indexOf("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", "deleted-arn-expiry-stack") + .when() + .post("/") + .then() + .statusCode(200); + + long readyDeadline = System.currentTimeMillis() + 10_000; + while (System.currentTimeMillis() < readyDeadline) { + String deletedEventsXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackEvents") + .formParam("StackName", stackArn) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + if (deletedEventsXml.contains("DELETE_COMPLETE")) { + break; + } + Thread.sleep(200); + } + + clock.advance(Duration.ofSeconds(31)); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackEvents") + .formParam("StackName", stackArn) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("does not exist")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackArn) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("does not exist")); + } + @Test void deleteChangeSet_nonExistentChangeSet_returnsError() { String template = """ diff --git a/src/test/java/io/github/hectorvent/floci/testing/MutableClock.java b/src/test/java/io/github/hectorvent/floci/testing/MutableClock.java new file mode 100644 index 0000000000..5985a3c744 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/MutableClock.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.testing; + +import jakarta.annotation.Priority; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Alternative; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.concurrent.atomic.AtomicReference; + +@Alternative +@Priority(1) +@ApplicationScoped +public class MutableClock extends Clock { + + private static final Instant DEFAULT_INSTANT = Instant.parse("2026-01-01T00:00:00Z"); + + private final AtomicReference current = new AtomicReference<>(DEFAULT_INSTANT); + private final ZoneId zone = ZoneOffset.UTC; + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return current.getAndUpdate(now -> now.plusMillis(1)); + } + + public void reset() { + current.set(DEFAULT_INSTANT); + } + + public void advance(Duration duration) { + current.updateAndGet(now -> now.plus(duration)); + } +}