Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): add StackSets with account-aware provisioning (#1551)

Alex Banna058e02630a84
diff --git a/README.md b/README.md
index 3eaa4938ce..8ff903b7f5 100644
--- a/README.md
+++ b/README.md
@@ -253,7 +253,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| Kinesis | In-process | Streams, shards, enhanced fan-out, split and merge |
| Secrets Manager | In-process | Versioning, resource policies, tagging |
| Step Functions | In-process | ASL execution, task tokens, execution history |
-| CloudFormation | In-process | Stacks, change sets, resource provisioning |
+| CloudFormation | In-process | Stacks, change sets, resource provisioning, StackSets (cross-account instances) |
| EventBridge | In-process | Custom buses, rules, SQS, SNS and Lambda targets |
| EventBridge Pipes | In-process | Poller-based integration connecting SQS, Kinesis, DynamoDB, and MSK sources to targets with optional filtering |
| EventBridge Scheduler | In-process | Schedule groups, schedules, flexible time windows, retry policies, DLQs |
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackSetsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackSetsTest.java
new file mode 100644
index 0000000000..d2d9a5d2ec
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackSetsTest.java
@@ -0,0 +1,169 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.*;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
+import software.amazon.awssdk.services.cloudformation.model.*;
+import software.amazon.awssdk.services.sqs.SqsClient;
+import software.amazon.awssdk.services.sqs.model.QueueDoesNotExistException;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.*;
+
+/**
+ * Verifies CloudFormation StackSets through the real AWS SDK: a stack set created in the
+ * administration account provisions instances into target accounts, the management responses
+ * unmarshal cleanly, and the provisioned resources land in each target account's namespace.
+ */
+@DisplayName("CloudFormation StackSets cross-account provisioning")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class CloudFormationStackSetsTest {
+
+ private static final String ACCOUNT_B = "222222222222";
+ private static final String ACCOUNT_C = "333333333333";
+ private static final String REGION = "us-east-1";
+
+ private static CloudFormationClient cfn;
+ private static String stackSetName;
+ private static String queueName;
+
+ @BeforeAll
+ static void setup() {
+ cfn = TestFixtures.cloudFormationClient();
+ stackSetName = TestFixtures.uniqueName("compat-stackset");
+ queueName = TestFixtures.uniqueName("compat-ss-queue");
+ }
+
+ @AfterAll
+ static void teardown() {
+ try {
+ cfn.deleteStackInstances(r -> r.stackSetName(stackSetName)
+ .accounts(ACCOUNT_B, ACCOUNT_C).regions(REGION).retainStacks(false));
+ } catch (Exception e) {
+ System.err.println("teardown: deleteStackInstances for " + stackSetName + " failed: " + e.getMessage());
+ }
+ try {
+ cfn.deleteStackSet(r -> r.stackSetName(stackSetName));
+ } catch (Exception e) {
+ System.err.println("teardown: deleteStackSet for " + stackSetName + " failed: " + e.getMessage());
+ }
+ cfn.close();
+ }
+
+ private static SqsClient sqsFor(String account) {
+ return SqsClient.builder()
+ .endpointOverride(TestFixtures.endpoint())
+ .region(Region.US_EAST_1)
+ .credentialsProvider(StaticCredentialsProvider.create(
+ AwsBasicCredentials.create(account, "test")))
+ .build();
+ }
+
+ private static String queueTemplate(String queue) {
+ return "{\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\","
+ + "\"Properties\":{\"QueueName\":\"" + queue + "\"}}}}";
+ }
+
+ @Test
+ @Order(1)
+ void createStackSet() {
+ CreateStackSetResponse resp = cfn.createStackSet(r -> r
+ .stackSetName(stackSetName)
+ .templateBody(queueTemplate(queueName)));
+ assertThat(resp.stackSetId()).isNotBlank();
+ }
+
+ @Test
+ @Order(2)
+ void describeStackSetReturnsDefinition() {
+ DescribeStackSetResponse resp = cfn.describeStackSet(r -> r.stackSetName(stackSetName));
+ StackSet ss = resp.stackSet();
+ assertThat(ss.stackSetName()).isEqualTo(stackSetName);
+ assertThat(ss.status()).isEqualTo(StackSetStatus.ACTIVE);
+ assertThat(ss.templateBody()).contains(queueName);
+ }
+
+ @Test
+ @Order(3)
+ void createStackInstancesProvisionsIntoTargetAccounts() {
+ CreateStackInstancesResponse resp = cfn.createStackInstances(r -> r
+ .stackSetName(stackSetName)
+ .accounts(ACCOUNT_B, ACCOUNT_C)
+ .regions(REGION));
+ assertThat(resp.operationId()).isNotBlank();
+
+ // The queue materializes in each target account's namespace...
+ try (SqsClient b = sqsFor(ACCOUNT_B); SqsClient c = sqsFor(ACCOUNT_C)) {
+ assertThat(b.getQueueUrl(g -> g.queueName(queueName)).queueUrl())
+ .contains("/" + ACCOUNT_B + "/" + queueName);
+ assertThat(c.getQueueUrl(g -> g.queueName(queueName)).queueUrl())
+ .contains("/" + ACCOUNT_C + "/" + queueName);
+ }
+ // ...and not in the administration account.
+ try (SqsClient admin = TestFixtures.sqsClient()) {
+ assertThatThrownBy(() -> admin.getQueueUrl(g -> g.queueName(queueName)))
+ .isInstanceOf(QueueDoesNotExistException.class);
+ }
+ }
+
+ @Test
+ @Order(4)
+ void listStackInstancesReportsTargets() {
+ List<StackInstanceSummary> summaries = cfn.listStackInstances(r -> r.stackSetName(stackSetName))
+ .summaries();
+ assertThat(summaries).hasSize(2);
+ assertThat(summaries).extracting(StackInstanceSummary::account)
+ .containsExactlyInAnyOrder(ACCOUNT_B, ACCOUNT_C);
+ assertThat(summaries).allSatisfy(s -> assertThat(s.region()).isEqualTo(REGION));
+
+ // DescribeStackInstance (singular) — the operation DPS's state machine actually calls.
+ StackInstance inst = cfn.describeStackInstance(r -> r.stackSetName(stackSetName)
+ .stackInstanceAccount(ACCOUNT_B).stackInstanceRegion(REGION)).stackInstance();
+ assertThat(inst.account()).isEqualTo(ACCOUNT_B);
+ assertThat(inst.region()).isEqualTo(REGION);
+ assertThat(inst.stackId()).isNotBlank();
+ }
+
+ @Test
+ @Order(5)
+ void listStackSetOperationsRecordsCreate() {
+ List<StackSetOperationSummary> ops = cfn.listStackSetOperations(r -> r.stackSetName(stackSetName))
+ .summaries();
+ assertThat(ops).isNotEmpty();
+ assertThat(ops).extracting(StackSetOperationSummary::action)
+ .contains(StackSetOperationAction.CREATE);
+
+ String opId = ops.stream().filter(o -> o.action() == StackSetOperationAction.CREATE)
+ .findFirst().orElseThrow().operationId();
+ StackSetOperation op = cfn.describeStackSetOperation(r -> r.stackSetName(stackSetName)
+ .operationId(opId)).stackSetOperation();
+ assertThat(op.operationId()).isEqualTo(opId);
+ assertThat(op.action()).isEqualTo(StackSetOperationAction.CREATE);
+ assertThat(op.status()).isEqualTo(StackSetOperationStatus.SUCCEEDED);
+ }
+
+ @Test
+ @Order(6)
+ void deleteStackInstancesRemovesResources() {
+ cfn.deleteStackInstances(r -> r.stackSetName(stackSetName)
+ .accounts(ACCOUNT_B, ACCOUNT_C).regions(REGION).retainStacks(false));
+
+ assertThat(cfn.listStackInstances(r -> r.stackSetName(stackSetName)).summaries()).isEmpty();
+
+ try (SqsClient b = sqsFor(ACCOUNT_B)) {
+ assertThatThrownBy(() -> b.getQueueUrl(g -> g.queueName(queueName)))
+ .isInstanceOf(QueueDoesNotExistException.class);
+ }
+ }
+
+ @Test
+ @Order(7)
+ void deleteStackSetSucceedsWhenEmpty() {
+ cfn.deleteStackSet(r -> r.stackSetName(stackSetName));
+ assertThatThrownBy(() -> cfn.describeStackSet(r -> r.stackSetName(stackSetName)))
+ .isInstanceOf(StackSetNotFoundException.class);
+ }
+}
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index de553db356..9f2944a54e 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -25,9 +25,15 @@
| `DeleteChangeSet` | Delete a change set |
| `SetStackPolicy` | Accepted; no-op (stub — stack policies are not enforced) |
| `GetStackPolicy` | Accepted; returns an empty policy (stub) |
-| `ListStackSets` | Accepted; returns an empty result (StackSets not implemented) |
-| `DescribeStackSet` | Accepted; returns an empty result (StackSets not implemented) |
-| `CreateStackSet` | Accepted; returns an empty result (StackSets not implemented) |
+| `CreateStackSet` | Create a stack set from a template |
+| `DescribeStackSet` | Get stack set details |
+| `ListStackSets` | List stack sets |
+| `UpdateStackSet` | Update the stack set and re-apply to existing instances |
+| `DeleteStackSet` | Delete an empty stack set |
+| `CreateStackInstances` | Provision instances into target accounts/regions |
+| `ListStackInstances` | List instances (optionally filtered by account/region) |
+| `DeleteStackInstances` | Remove instances and their resources |
+| `ListStackSetOperations` | List operations performed on a stack set |
## Supported Resource Types
@@ -81,6 +87,51 @@ All other resource types are accepted without error and assigned a synthetic phy
- Replacement-only changes such as `FunctionName` or `PackageType` changes create a replacement function and remove the old one.
- S3-backed code stays linked through `S3Bucket` / `S3Key`, so Lambda's reactive S3 sync continues to work for functions created by CloudFormation or CDK.
+## Account-Aware Provisioning
+
+Resources provisioned by `CreateStack` / `UpdateStack` land in the **caller's account** namespace
+(determined from the request's access key — see [Multi-Account Isolation](../configuration/multi-account.md)).
+Deleting the stack removes them from that same account.
+
+## StackSets
+
+StackSets deploy a single template into many target accounts and regions:
+
+```bash
+export AWS_ENDPOINT_URL=http://localhost:4566
+
+# 1. Create the stack set (in the administration account)
+aws cloudformation create-stack-set \
+ --stack-set-name my-set \
+ --template-body file://template.yml \
+ --endpoint-url $AWS_ENDPOINT_URL
+
+# 2. Create instances in two target accounts
+aws cloudformation create-stack-instances \
+ --stack-set-name my-set \
+ --accounts 222222222222 333333333333 \
+ --regions us-east-1 \
+ --endpoint-url $AWS_ENDPOINT_URL
+
+# 3. The resources materialize in each target account's namespace
+aws cloudformation list-stack-instances \
+ --stack-set-name my-set \
+ --endpoint-url $AWS_ENDPOINT_URL
+```
+
+`CreateStackInstances` drives the single-stack engine once per `(account, region)` pair, provisioning
+each instance's resources into that target account's namespace — so a queue named `orders` deployed
+into accounts `222222222222` and `333333333333` exists independently in each. The stack set, its
+instances, and its operation history are recorded in the administration (caller) account.
+
+`DeleteStackInstances` removes instances and their resources, unless `RetainStacks=true`, which
+detaches the instances from the stack set but leaves their underlying stacks and resources in place.
+A stack set must be empty before `DeleteStackSet`.
+
+A `CreateStackInstances` / `UpdateStackSet` operation reports `FAILED` if any of its instances fails
+to deploy (the instance is marked `INOPERABLE`), so polling `DescribeStackSetOperation` reflects real
+provisioning outcomes rather than always returning `SUCCEEDED`.
+
## Configuration
| Variable | Default | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index db32ddbf3f..6ac7a8820d 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -360,7 +360,10 @@ public class AwsQueryController {
"ListStacks", "ListExports", "GetTemplate", "ValidateTemplate",
"CreateChangeSet", "DeleteChangeSet", "DescribeChangeSet", "ExecuteChangeSet", "ListChangeSets",
"DescribeStackEvents", "DescribeStackResources", "ListStackResources", "DescribeStackResource",
- "SetStackPolicy", "GetStackPolicy", "ListStackSets", "DescribeStackSet", "CreateStackSet"
+ "SetStackPolicy", "GetStackPolicy",
+ "ListStackSets", "DescribeStackSet", "CreateStackSet", "UpdateStackSet", "DeleteStackSet",
+ "CreateStackInstances", "ListStackInstances", "DescribeStackInstance", "DeleteStackInstances",
+ "ListStackSetOperations", "DescribeStackSetOperation"
);
private static final Set<String> SES_ACTIONS = Set.of(
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
index bbfeddb58e..4f44a83411 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
@@ -6,7 +6,10 @@ import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
+import io.github.hectorvent.floci.services.cloudformation.model.StackInstance;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.cloudformation.model.StackSet;
+import io.github.hectorvent.floci.services.cloudformation.model.StackSetOperation;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -32,10 +35,12 @@ public class CloudFormationQueryHandler {
private static final String CF_NS = "http://cloudformation.amazonaws.com/doc/2010-05-15/";
private final CloudFormationService cfnService;
+ private final StackSetService stackSetService;
@Inject
- public CloudFormationQueryHandler(CloudFormationService cfnService) {
+ public CloudFormationQueryHandler(CloudFormationService cfnService, StackSetService stackSetService) {
this.cfnService = cfnService;
+ this.stackSetService = stackSetService;
}
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
@@ -59,8 +64,17 @@ public class CloudFormationQueryHandler {
case "SetStackPolicy" -> Response.ok(emptyResult("SetStackPolicyResponse")).build();
case "GetStackPolicy" -> Response.ok(emptyResult("GetStackPolicyResponse")).build();
case "DescribeStackResource" -> describeStackResource(params, region);
- case "ListStackSets", "DescribeStackSet", "CreateStackSet" ->
- Response.ok(emptyResult(action + "Response")).build();
+ case "CreateStackSet" -> createStackSet(params);
+ case "DescribeStackSet" -> describeStackSet(params);
+ case "ListStackSets" -> listStackSets();
+ case "UpdateStackSet" -> updateStackSet(params);
+ case "DeleteStackSet" -> deleteStackSet(params);
+ case "CreateStackInstances" -> createStackInstances(params, region);
+ case "ListStackInstances" -> listStackInstances(params);
+ case "DescribeStackInstance" -> describeStackInstance(params);
+ case "DeleteStackInstances" -> deleteStackInstances(params);
+ case "ListStackSetOperations" -> listStackSetOperations(params);
+ case "DescribeStackSetOperation" -> describeStackSetOperation(params);
default -> xmlError("UnknownAction", "Action " + action + " is not supported.", 400);
};
}
@@ -565,6 +579,279 @@ public class CloudFormationQueryHandler {
.build();
}
+ // ── StackSets ─────────────────────────────────────────────────────────────
+
+ private Response createStackSet(MultivaluedMap<String, String> params) {
+ try {
+ StackSet ss = stackSetService.createStackSet(
+ params.getFirst("StackSetName"),
+ cfnService.resolveTemplateBody(params.getFirst("TemplateBody"), params.getFirst("TemplateURL")),
+ extractParameters(params),
+ extractList(params, "Capabilities.member."),
+ extractTags(params),
+ params.getFirst("Description"));
+ String xml = new XmlBuilder()
+ .start("CreateStackSetResponse", CF_NS)
+ .start("CreateStackSetResult")
+ .elem("StackSetId", ss.getStackSetId())
+ .end("CreateStackSetResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("CreateStackSetResponse")
+ .build();
+ return Response.ok(xml).type("text/xml").build();
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response describeStackSet(MultivaluedMap<String, String> params) {
+ try {
+ StackSet ss = stackSetService.describeStackSet(params.getFirst("StackSetName"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeStackSetResponse", CF_NS)
+ .start("DescribeStackSetResult")
+ .start("StackSet")
+ .elem("StackSetName", ss.getStackSetName())
+ .elem("StackSetId", ss.getStackSetId())
+ .elem("Status", ss.getStatus())
+ .elem("Description", ss.getDescription())
+ .elem("TemplateBody", ss.getTemplateBody())
+ .elem("PermissionModel", ss.getPermissionModel());
+ appendCapabilities(xml, ss.getCapabilities());
+ appendParameters(xml, ss.getParameters());
+ xml.end("StackSet").end("DescribeStackSetResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("DescribeStackSetResponse");
+ return Response.ok(xml.build()).type("text/xml").build();
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response listStackSets() {
+ XmlBuilder xml = new XmlBuilder()
+ .start("ListStackSetsResponse", CF_NS)
+ .start("ListStackSetsResult")
+ .start("Summaries");
+ for (StackSet ss : stackSetService.listStackSets()) {
+ xml.start("member")
+ .elem("StackSetName", ss.getStackSetName())
+ .elem("StackSetId", ss.getStackSetId())
+ .elem("Status", ss.getStatus())
+ .elem("Description", ss.getDescription())
+ .end("member");
+ }
+ xml.end("Summaries").end("ListStackSetsResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("ListStackSetsResponse");
+ return Response.ok(xml.build()).type("text/xml").build();
+ }
+
+ private Response updateStackSet(MultivaluedMap<String, String> params) {
+ try {
+ StackSetOperation op = stackSetService.updateStackSet(
+ params.getFirst("StackSetName"),
+ cfnService.resolveTemplateBody(params.getFirst("TemplateBody"), params.getFirst("TemplateURL")),
+ extractParameters(params),
+ extractList(params, "Capabilities.member."),
+ extractTags(params),
+ params.getFirst("Description"));
+ return operationResponse("UpdateStackSet", op.getOperationId());
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response deleteStackSet(MultivaluedMap<String, String> params) {
+ try {
+ stackSetService.deleteStackSet(params.getFirst("StackSetName"));
+ return Response.ok(emptyResult("DeleteStackSetResponse")).type("text/xml").build();
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response createStackInstances(MultivaluedMap<String, String> params, String region) {
+ try {
+ StackSetOperation op = stackSetService.createStackInstances(
+ params.getFirst("StackSetName"),
+ extractList(params, "Accounts.member."),
+ resolveRegions(params, region));
+ return operationResponse("CreateStackInstances", op.getOperationId());
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response listStackInstances(MultivaluedMap<String, String> params) {
+ try {
+ List<StackInstance> list = stackSetService.listStackInstances(
+ params.getFirst("StackSetName"),
+ params.getFirst("StackInstanceAccount"),
+ params.getFirst("StackInstanceRegion"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("ListStackInstancesResponse", CF_NS)
+ .start("ListStackInstancesResult")
+ .start("Summaries");
+ for (StackInstance inst : list) {
+ xml.start("member")
+ .elem("StackSetId", inst.getStackSetId())
+ .elem("Account", inst.getAccount())
+ .elem("Region", inst.getRegion())
+ .elem("StackId", inst.getStackId())
+ .elem("Status", inst.getStatus())
+ .start("StackInstanceStatus")
+ .elem("DetailedStatus", inst.getDetailedStatus())
+ .end("StackInstanceStatus")
+ .elem("StatusReason", inst.getStatusReason())
+ .end("member");
+ }
+ xml.end("Summaries").end("ListStackInstancesResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("ListStackInstancesResponse");
+ return Response.ok(xml.build()).type("text/xml").build();
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response describeStackInstance(MultivaluedMap<String, String> params) {
+ try {
+ StackInstance inst = stackSetService.describeStackInstance(
+ params.getFirst("StackSetName"),
+ params.getFirst("StackInstanceAccount"),
+ params.getFirst("StackInstanceRegion"));
+ String xml = new XmlBuilder()
+ .start("DescribeStackInstanceResponse", CF_NS)
+ .start("DescribeStackInstanceResult")
+ .start("StackInstance")
+ .elem("StackSetId", inst.getStackSetId())
+ .elem("Account", inst.getAccount())
+ .elem("Region", inst.getRegion())
+ .elem("StackId", inst.getStackId())
+ .elem("Status", inst.getStatus())
+ .start("StackInstanceStatus")
+ .elem("DetailedStatus", inst.getDetailedStatus())
+ .end("StackInstanceStatus")
+ .elem("StatusReason", inst.getStatusReason())
+ .end("StackInstance")
+ .end("DescribeStackInstanceResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("DescribeStackInstanceResponse")
+ .build();
+ return Response.ok(xml).type("text/xml").build();
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response deleteStackInstances(MultivaluedMap<String, String> params) {
+ try {
+ StackSetOperation op = stackSetService.deleteStackInstances(
+ params.getFirst("StackSetName"),
+ extractList(params, "Accounts.member."),
+ extractList(params, "Regions.member."),
+ Boolean.parseBoolean(params.getFirst("RetainStacks")));
+ return operationResponse("DeleteStackInstances", op.getOperationId());
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response listStackSetOperations(MultivaluedMap<String, String> params) {
+ try {
+ List<StackSetOperation> ops = stackSetService.listStackSetOperations(params.getFirst("StackSetName"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("ListStackSetOperationsResponse", CF_NS)
+ .start("ListStackSetOperationsResult")
+ .start("Summaries");
+ for (StackSetOperation op : ops) {
+ xml.start("member")
+ .elem("OperationId", op.getOperationId())
+ .elem("Action", op.getAction())
+ .elem("Status", op.getStatus())
+ .elem("CreationTimestamp", ISO.format(op.getCreationTimestamp()));
+ if (op.getEndTimestamp() != null) {
+ xml.elem("EndTimestamp", ISO.format(op.getEndTimestamp()));
+ }
+ xml.end("member");
+ }
+ xml.end("Summaries").end("ListStackSetOperationsResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("ListStackSetOperationsResponse");
+ return Response.ok(xml.build()).type("text/xml").build();
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response describeStackSetOperation(MultivaluedMap<String, String> params) {
+ try {
+ StackSetOperation op = stackSetService.describeStackSetOperation(
+ params.getFirst("StackSetName"), params.getFirst("OperationId"));
+ XmlBuilder xml = new XmlBuilder()
+ .start("DescribeStackSetOperationResponse", CF_NS)
+ .start("DescribeStackSetOperationResult")
+ .start("StackSetOperation")
+ .elem("OperationId", op.getOperationId())
+ .elem("Action", op.getAction())
+ .elem("Status", op.getStatus())
+ .elem("CreationTimestamp", ISO.format(op.getCreationTimestamp()));
+ if (op.getEndTimestamp() != null) {
+ xml.elem("EndTimestamp", ISO.format(op.getEndTimestamp()));
+ }
+ xml.end("StackSetOperation").end("DescribeStackSetOperationResult")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end("DescribeStackSetOperationResponse");
+ return Response.ok(xml.build()).type("text/xml").build();
+ } catch (AwsException e) {
+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
+ }
+ }
+
+ private Response operationResponse(String action, String operationId) {
+ String xml = new XmlBuilder()
+ .start(action + "Response", CF_NS)
+ .start(action + "Result")
+ .elem("OperationId", operationId)
+ .end(action + "Result")
+ .raw(AwsQueryResponse.responseMetadata())
+ .end(action + "Response")
+ .build();
+ return Response.ok(xml).type("text/xml").build();
+ }
+
+ /** Falls back to the request region when no explicit Regions are supplied. */
+ private List<String> resolveRegions(MultivaluedMap<String, String> params, String region) {
+ List<String> regions = extractList(params, "Regions.member.");
+ return regions.isEmpty() ? List.of(region) : regions;
+ }
+
+ private void appendCapabilities(XmlBuilder xml, List<String> capabilities) {
+ if (capabilities == null || capabilities.isEmpty()) {
+ return;
+ }
+ xml.start("Capabilities");
+ for (String c : capabilities) {
+ xml.elem("member", c);
+ }
+ xml.end("Capabilities");
+ }
+
+ private void appendParameters(XmlBuilder xml, Map<String, String> parameters) {
+ if (parameters == null || parameters.isEmpty()) {
+ return;
+ }
+ xml.start("Parameters");
+ for (Map.Entry<String, String> e : parameters.entrySet()) {
+ xml.start("member")
+ .elem("ParameterKey", e.getKey())
+ .elem("ParameterValue", e.getValue())
+ .end("member");
+ }
+ xml.end("Parameters");
+ }
+
private void awaitExecution(Future<?> future) {
try {
future.get();
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 75b9b2242e..461b7b8aac 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
@@ -4,7 +4,10 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
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.common.RequestContext;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
+import io.quarkus.arc.Arc;
+import io.quarkus.arc.ManagedContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -27,6 +30,7 @@ import java.time.Instant;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -186,6 +190,18 @@ public class CloudFormationService {
// ── ExecuteChangeSet ──────────────────────────────────────────────────────
public Future<?> executeChangeSet(String stackName, String changeSetName, String region) {
+ return executeChangeSet(stackName, changeSetName, region, regionResolver.getAccountId());
+ }
+
+ /**
+ * Executes a change set, provisioning its resources into {@code accountId}'s namespace.
+ *
+ * <p>Provisioning runs on a background executor thread that has no inherited request scope, so
+ * the downstream service calls would otherwise fall back to the default account. The resources
+ * are materialized under a synthetic request scope bound to {@code accountId} so a single-stack
+ * deployment lands in the caller's account, and a StackSet instance lands in its target account.
+ */
+ public Future<?> executeChangeSet(String stackName, String changeSetName, String region, String accountId) {
Stack stack = getStackOrThrow(stackName, region);
ChangeSet cs = stack.getChangeSets().get(resolveChangeSetName(changeSetName));
if (cs == null) {
@@ -205,8 +221,38 @@ public class CloudFormationService {
String templateBody = cs.getTemplateBody();
Map<String, String> params = cs.getParameters() != null ? cs.getParameters() : Map.of();
- String accountId = regionResolver.getAccountId();
- return executor.submit(() -> executeTemplate(stack, templateBody, params, isCreate, region, accountId));
+ return executor.submit(() -> runUnderAccount(accountId,
+ () -> executeTemplate(stack, templateBody, params, isCreate, region, accountId)));
+ }
+
+ /**
+ * Runs {@code body} under a synthetic CDI request scope whose account is {@code accountId}, so
+ * that account-aware storage in the downstream services namespaces provisioned resources under
+ * the intended account. Mirrors the pattern used by other background workers.
+ */
+ private void runUnderAccount(String accountId, Runnable body) {
+ ManagedContext requestContext = Arc.container().requestContext();
+ boolean alreadyActive = requestContext.isActive();
+ if (!alreadyActive) {
+ requestContext.activate();
+ }
+ // Background workers normally have no active scope, so a fresh one is activated and
+ // terminated below. But if we ran inside an already-active scope, restore its previous
+ // account afterwards so we never leave the overridden account ID behind on a reused thread.
+ RequestContext ctx = Arc.container().instance(RequestContext.class).get();
+ String previousAccountId = alreadyActive ? ctx.getAccountId() : null;
+ try {
+ if (accountId != null) {
+ ctx.setAccountId(accountId);
+ }
+ body.run();
+ } finally {
+ if (!alreadyActive) {
+ requestContext.terminate();
+ } else {
+ ctx.setAccountId(previousAccountId);
+ }
+ }
}
// ── DeleteChangeSet ───────────────────────────────────────────────────────
@@ -226,16 +272,29 @@ public class CloudFormationService {
// ── DeleteStack ───────────────────────────────────────────────────────────
public void deleteStack(String stackName, String region) {
+ deleteStack(stackName, region, regionResolver.getAccountId());
+ }
+
+ /**
+ * Deletes a stack, removing its resources from {@code accountId}'s namespace. The account must
+ * match the one the resources were provisioned into (the caller's account for a single-stack
+ * deployment, or the target account for a StackSet instance).
+ *
+ * @return a future that completes when the resources have been removed; already-gone stacks
+ * complete immediately. Callers that need synchronous deletion (e.g. StackSet instance
+ * removal) can await it.
+ */
+ public Future<?> deleteStack(String stackName, String region, String accountId) {
purgeExpiredDeletedStacks();
Stack stack = resolveStack(stackName, region);
if (stack == null) {
- return; // Already gone — no-op
+ return CompletableFuture.completedFuture(null); // Already gone — no-op
}
stack.setStatus("DELETE_IN_PROGRESS");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
- executor.submit(() -> deleteStackResources(stack, region));
+ return executor.submit(() -> runUnderAccount(accountId, () -> deleteStackResources(stack, region)));
}
// ── GetTemplate ───────────────────────────────────────────────────────────
@@ -706,6 +765,18 @@ public class CloudFormationService {
return "{}";
}
+ /**
+ * Resolves a template body from an inline body or a TemplateURL (fetched from S3), for callers
+ * outside this service such as the StackSets handler. Returns {@code null} when neither is given.
+ */
+ public String resolveTemplateBody(String templateBody, String templateUrl) {
+ if ((templateBody == null || templateBody.isBlank())
+ && (templateUrl == null || templateUrl.isBlank())) {
+ return null;
+ }
+ return resolveTemplate(templateBody, templateUrl);
+ }
+
private String fetchTemplateFromS3(String url) {
// Parse S3 URL — three forms:
// Virtual-hosted AWS: https://bucket.s3[.region].amazonaws.com/key
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java
new file mode 100644
index 0000000000..c9b9a3ae40
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java
@@ -0,0 +1,334 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.cloudformation.model.Stack;
+import io.github.hectorvent.floci.services.cloudformation.model.StackInstance;
+import io.github.hectorvent.floci.services.cloudformation.model.StackSet;
+import io.github.hectorvent.floci.services.cloudformation.model.StackSetOperation;
+import com.fasterxml.jackson.core.type.TypeReference;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.Future;
+
+/**
+ * CloudFormation StackSets — manages stack sets and provisions their instances across target
+ * accounts and regions.
+ *
+ * <p>A StackSet holds a template and configuration; {@code CreateStackInstances} drives the existing
+ * single-stack engine ({@link CloudFormationService}) once per target {@code (account, region)},
+ * provisioning the resources into each target account's namespace. The StackSet, instance and
+ * operation records themselves live in the administration (caller) account's namespace.
+ */
+@ApplicationScoped
+public class StackSetService {
+
+ private static final Logger LOG = Logger.getLogger(StackSetService.class);
+ private static final String INSTANCE_CHANGE_SET = "stackset-instance";
+ private static final String UPDATE_CHANGE_SET = "stackset-update";
+
+ private final CloudFormationService cfnService;
+ private final StorageBackend<String, StackSet> stackSets;
+ private final StorageBackend<String, StackInstance> instances;
+ private final StorageBackend<String, StackSetOperation> operations;
+
+ @Inject
+ public StackSetService(CloudFormationService cfnService, StorageFactory storageFactory) {
+ this.cfnService = cfnService;
+ this.stackSets = storageFactory.create("cloudformation", "cloudformation-stacksets.json",
+ new TypeReference<Map<String, StackSet>>() {});
+ this.instances = storageFactory.create("cloudformation", "cloudformation-stackset-instances.json",
+ new TypeReference<Map<String, StackInstance>>() {});
+ this.operations = storageFactory.create("cloudformation", "cloudformation-stackset-operations.json",
+ new TypeReference<Map<String, StackSetOperation>>() {});
+ }
+
+ // ── StackSet lifecycle ─────────────────────────────────────────────────────
+
+ public StackSet createStackSet(String name, String templateBody, Map<String, String> parameters,
+ List<String> capabilities, Map<String, String> tags, String description) {
+ if (name == null || name.isBlank()) {
+ throw new AwsException("ValidationError", "StackSetName must not be empty", 400);
+ }
+ if (stackSets.get(name).isPresent()) {
+ throw new AwsException("NameAlreadyExistsException",
+ "StackSet already exists: " + name, 409);
+ }
+ // AWS rejects CreateStackSet with no template; the handler resolves TemplateBody/TemplateURL
+ // to null when neither is supplied. Without this guard a later CreateStackInstances would
+ // deploy empty ("{}") stacks into every target account.
+ if (templateBody == null || templateBody.isBlank()) {
+ throw new AwsException("ValidationError",
+ "Either TemplateBody or TemplateURL must be specified", 400);
+ }
+ StackSet ss = new StackSet();
+ ss.setStackSetName(name);
+ ss.setStackSetId(name + ":" + UUID.randomUUID());
+ ss.setTemplateBody(templateBody);
+ ss.setDescription(description);
+ if (parameters != null) {
+ ss.setParameters(new LinkedHashMap<>(parameters));
+ }
+ if (capabilities != null) {
+ ss.getCapabilities().addAll(capabilities);
+ }
+ if (tags != null) {
+ ss.getTags().putAll(tags);
+ }
+ stackSets.put(name, ss);
+ LOG.infov("Created StackSet: {0}", name);
+ return ss;
+ }
+
+ public StackSet describeStackSet(String name) {
+ return getStackSetOrThrow(name);
+ }
+
+ public List<StackSet> listStackSets() {
+ return stackSets.scan(k -> true);
+ }
+
+ public StackSetOperation updateStackSet(String name, String templateBody, Map<String, String> parameters,
+ List<String> capabilities, Map<String, String> tags,
+ String description) {
+ StackSet ss = getStackSetOrThrow(name);
+ if (templateBody != null && !templateBody.isBlank()) {
+ ss.setTemplateBody(templateBody);
+ }
+ if (parameters != null && !parameters.isEmpty()) {
+ ss.setParameters(new LinkedHashMap<>(parameters));
+ }
+ if (capabilities != null && !capabilities.isEmpty()) {
+ ss.getCapabilities().clear();
+ ss.getCapabilities().addAll(capabilities);
+ }
+ if (tags != null && !tags.isEmpty()) {
+ ss.getTags().clear();
+ ss.getTags().putAll(tags);
+ }
+ if (description != null) {
+ ss.setDescription(description);
+ }
+ stackSets.put(name, ss);
+
+ // Re-apply the updated definition to every existing instance, refreshing each record.
+ List<StackInstance> deployed = new ArrayList<>();
+ for (StackInstance inst : listStackInstances(name, null, null)) {
+ StackInstance updated = deployInstance(ss, inst.getAccount(), inst.getRegion(), UPDATE_CHANGE_SET, "UPDATE");
+ instances.put(instanceKey(name, updated.getAccount(), updated.getRegion()), updated);
+ deployed.add(updated);
+ }
+ return recordOperation(name, "UPDATE", deriveOperationStatus(deployed));
+ }
+
+ public void deleteStackSet(String name) {
+ getStackSetOrThrow(name);
+ if (!listStackInstances(name, null, null).isEmpty()) {
+ throw new AwsException("StackSetNotEmptyException",
+ "StackSet is not empty. Delete all stack instances first.", 409);
+ }
+ stackSets.delete(name);
+ LOG.infov("Deleted StackSet: {0}", name);
+ }
+
+ // ── Instances ──────────────────────────────────────────────────────────────
+
+ public StackSetOperation createStackInstances(String name, List<String> accounts, List<String> regions) {
+ StackSet ss = getStackSetOrThrow(name);
+ if (accounts == null || accounts.isEmpty() || regions == null || regions.isEmpty()) {
+ throw new AwsException("ValidationError",
+ "Accounts and Regions must each contain at least one value", 400);
+ }
+ List<StackInstance> deployed = new ArrayList<>();
+ for (String account : accounts) {
+ for (String region : regions) {
+ StackInstance inst = deployInstance(ss, account, region, INSTANCE_CHANGE_SET, "CREATE");
+ instances.put(instanceKey(name, account, region), inst);
+ deployed.add(inst);
+ }
+ }
+ return recordOperation(name, "CREATE", deriveOperationStatus(deployed));
+ }
+
+ public List<StackInstance> listStackInstances(String name, String accountFilter, String regionFilter) {
+ getStackSetOrThrow(name);
+ String prefix = name + ":";
+ return instances.scan(k -> k.startsWith(prefix)).stream()
+ .filter(i -> accountFilter == null || accountFilter.equals(i.getAccount()))
+ .filter(i -> regionFilter == null || regionFilter.equals(i.getRegion()))
+ .toList();
+ }
+
+ public StackInstance describeStackInstance(String name, String account, String region) {
+ getStackSetOrThrow(name);
+ if (account == null || region == null) {
+ throw new AwsException("ValidationError",
+ "StackInstanceAccount and StackInstanceRegion are required", 400);
+ }
+ return instances.get(instanceKey(name, account, region))
+ .orElseThrow(() -> new AwsException("StackInstanceNotFoundException",
+ "Stack instance for [" + account + "/" + region + "] not found in stack set " + name, 404));
+ }
+
+ public StackSetOperation deleteStackInstances(String name, List<String> accounts, List<String> regions,
+ boolean retainStacks) {
+ getStackSetOrThrow(name);
+ if (accounts == null || accounts.isEmpty() || regions == null || regions.isEmpty()) {
+ throw new AwsException("ValidationError",
+ "Accounts and Regions must each contain at least one value", 400);
+ }
+ List<StackInstance> results = new ArrayList<>();
+ for (String account : accounts) {
+ for (String region : regions) {
+ String key = instanceKey(name, account, region);
+ StackInstance inst = instances.get(key).orElse(null);
+ if (inst == null) {
+ continue;
+ }
+ // RetainStacks=true detaches the instance from the StackSet but leaves the
+ // underlying CloudFormation stack and its resources in the target account.
+ if (!retainStacks && !await(cfnService.deleteStack(inst.getStackName(), region, account))) {
+ // The underlying stack delete failed. Match AWS: retain the instance record
+ // (now INOPERABLE) and report the operation as FAILED, rather than silently
+ // dropping the instance and claiming success.
+ inst.setStatus("INOPERABLE");
+ inst.setDetailedStatus("FAILED");
+ inst.setStatusReason("Stack instance deletion failed");
+ instances.put(key, inst);
+ results.add(inst);
+ continue;
+ }
+ inst.setDetailedStatus("SUCCEEDED");
+ instances.delete(key);
+ results.add(inst);
+ }
+ }
+ return recordOperation(name, "DELETE", deriveOperationStatus(results));
+ }
+
+ public List<StackSetOperation> listStackSetOperations(String name) {
+ getStackSetOrThrow(name);
+ String prefix = name + ":";
+ return operations.scan(k -> k.startsWith(prefix)).stream()
+ .sorted((a, b) -> b.getCreationTimestamp().compareTo(a.getCreationTimestamp()))
+ .toList();
+ }
+
+ public StackSetOperation describeStackSetOperation(String name, String operationId) {
+ getStackSetOrThrow(name);
+ if (operationId == null || operationId.isBlank()) {
+ throw new AwsException("ValidationError", "OperationId is required", 400);
+ }
+ return operations.get(name + ":" + operationId)
+ .orElseThrow(() -> new AwsException("OperationNotFoundException",
+ "Operation " + operationId + " not found for stack set " + name, 404));
+ }
+
+ // ── Internal helpers ────────────────────────────────────────────────────────
+
+ /**
+ * Drives the single-stack engine to materialize one instance's resources into the target
+ * account's namespace, then returns a {@link StackInstance} describing it.
+ */
+ private StackInstance deployInstance(StackSet ss, String account, String region,
+ String changeSetName, String changeSetType) {
+ String stackName = instanceStackName(ss.getStackSetName(), account);
+ cfnService.createChangeSet(stackName, changeSetName, changeSetType, ss.getTemplateBody(), null,
+ ss.getParameters(), ss.getCapabilities(), ss.getTags(), region);
+ await(cfnService.executeChangeSet(stackName, changeSetName, region, account));
+
+ StackInstance inst = new StackInstance();
+ inst.setStackSetId(ss.getStackSetId());
+ inst.setStackSetName(ss.getStackSetName());
+ inst.setAccount(account);
+ inst.setRegion(region);
+ inst.setStackName(stackName);
+ inst.setStackId(resolveStackId(stackName, region, account));
+ List<Stack> stacks = cfnService.describeStacks(stackName, region);
+ String stackStatus = stacks.isEmpty() ? null : stacks.get(0).getStatus();
+ // Only a clean create/update is a success. A failed resource rolls the stack back, so its
+ // terminal status is ROLLBACK_COMPLETE (not *_FAILED) — treat anything that is not COMPLETE
+ // as a failed instance so the operation status reflects it.
+ if (!"CREATE_COMPLETE".equals(stackStatus) && !"UPDATE_COMPLETE".equals(stackStatus)) {
+ inst.setStatus("INOPERABLE");
+ inst.setDetailedStatus("FAILED");
+ inst.setStatusReason(stacks.isEmpty() ? null : stacks.get(0).getStatusReason());
+ } else {
+ inst.setDetailedStatus("SUCCEEDED");
+ }
+ return inst;
+ }
+
+ private String resolveStackId(String stackName, String region, String account) {
+ List<Stack> stacks = cfnService.describeStacks(stackName, region);
+ if (!stacks.isEmpty() && stacks.get(0).getStackId() != null) {
+ return stacks.get(0).getStackId();
+ }
+ return AwsArnUtils.Arn.of("cloudformation", region, account, "stack/" + stackName).toString();
+ }
+
+ private StackSetOperation recordOperation(String stackSetName, String action, String status) {
+ StackSetOperation op = new StackSetOperation(UUID.randomUUID().toString(), stackSetName, action);
+ op.setStatus(status);
+ op.setEndTimestamp(Instant.now());
+ operations.put(stackSetName + ":" + op.getOperationId(), op);
+ return op;
+ }
+
+ /**
+ * An operation is FAILED if any of its instances did not deploy cleanly; otherwise SUCCEEDED.
+ * Without this, a failed (INOPERABLE) instance would still report SUCCEEDED to anything polling
+ * {@code DescribeStackSetOperation}.
+ */
+ private static String deriveOperationStatus(List<StackInstance> deployedInstances) {
+ boolean anyFailed = deployedInstances.stream()
+ .anyMatch(i -> "FAILED".equals(i.getDetailedStatus()));
+ return anyFailed ? "FAILED" : "SUCCEEDED";
+ }
+
+ private StackSet getStackSetOrThrow(String name) {
+ return stackSets.get(name)
+ .orElseThrow(() -> new AwsException("StackSetNotFoundException",
+ "StackSet [" + name + "] not found", 404));
+ }
+
+ private static String instanceStackName(String stackSetName, String account) {
+ return "StackSet-" + stackSetName + "-" + account;
+ }
+
+ private static String instanceKey(String stackSetName, String account, String region) {
+ return stackSetName + ":" + account + ":" + region;
+ }
+
+ /**
+ * Waits for an instance operation to complete. Returns {@code true} if it finished cleanly and
+ * {@code false} if it failed (the failure is logged). Callers that must react to a failure —
+ * {@link #deleteStackInstances} cannot drop an instance whose underlying stack delete failed —
+ * inspect the result; fire-and-forget callers can ignore it.
+ */
+ private boolean await(Future<?> future) {
+ try {
+ future.get();
+ return true;
+ } catch (InterruptedException e) {
+ // Restore the interrupt flag so a shutdown signal (e.g. Quarkus interrupting the backing
+ // ExecutorService) propagates instead of being swallowed and letting the thread run on.
+ Thread.currentThread().interrupt();
+ LOG.warnv("StackSet instance execution interrupted: {0}", e.getMessage());
+ return false;
+ } catch (Exception e) {
+ LOG.warnv("StackSet instance execution failed: {0}", e.getMessage());
+ return false;
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackInstance.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackInstance.java
new file mode 100644
index 0000000000..3980c28a2b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackInstance.java
@@ -0,0 +1,40 @@
+package io.github.hectorvent.floci.services.cloudformation.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class StackInstance {
+ private String stackSetId;
+ private String stackSetName;
+ private String account;
+ private String region;
+ /** Name of the backing single stack that materializes this instance's resources. */
+ private String stackName;
+ private String stackId;
+ /** Drift status (CURRENT, OUTDATED, INOPERABLE). */
+ private String status = "CURRENT";
+ /** Last operation status (SUCCEEDED, FAILED, ...) reported under StackInstanceStatus.DetailedStatus. */
+ private String detailedStatus = "SUCCEEDED";
+ private String statusReason;
+
+ public String getStackSetId() { return stackSetId; }
+ public void setStackSetId(String stackSetId) { this.stackSetId = stackSetId; }
+ public String getStackSetName() { return stackSetName; }
+ public void setStackSetName(String stackSetName) { this.stackSetName = stackSetName; }
+ public String getAccount() { return account; }
+ public void setAccount(String account) { this.account = account; }
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+ public String getStackName() { return stackName; }
+ public void setStackName(String stackName) { this.stackName = stackName; }
+ public String getStackId() { return stackId; }
+ public void setStackId(String stackId) { this.stackId = stackId; }
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+ public String getDetailedStatus() { return detailedStatus; }
+ public void setDetailedStatus(String detailedStatus) { this.detailedStatus = detailedStatus; }
+ public String getStatusReason() { return statusReason; }
+ public void setStatusReason(String statusReason) { this.statusReason = statusReason; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSet.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSet.java
new file mode 100644
index 0000000000..97df2be0ee
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSet.java
@@ -0,0 +1,43 @@
+package io.github.hectorvent.floci.services.cloudformation.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class StackSet {
+ private String stackSetId;
+ private String stackSetName;
+ private String description;
+ private String status = "ACTIVE";
+ private String templateBody;
+ private List<String> capabilities = new ArrayList<>();
+ private Map<String, String> parameters = new LinkedHashMap<>();
+ private Map<String, String> tags = new LinkedHashMap<>();
+ /** SELF_MANAGED or SERVICE_MANAGED; Floci only models SELF_MANAGED behavior. */
+ private String permissionModel = "SELF_MANAGED";
+
+ public String getStackSetId() { return stackSetId; }
+ public void setStackSetId(String stackSetId) { this.stackSetId = stackSetId; }
+ public String getStackSetName() { return stackSetName; }
+ public void setStackSetName(String stackSetName) { this.stackSetName = stackSetName; }
+ public String getDescription() { return description; }
+ public void setDescription(String description) { this.description = description; }
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+ public String getTemplateBody() { return templateBody; }
+ public void setTemplateBody(String templateBody) { this.templateBody = templateBody; }
+ public List<String> getCapabilities() { return capabilities; }
+ public void setCapabilities(List<String> capabilities) { this.capabilities = capabilities; }
+ public Map<String, String> getParameters() { return parameters; }
+ public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
+ public Map<String, String> getTags() { return tags; }
+ public void setTags(Map<String, String> tags) { this.tags = tags; }
+ public String getPermissionModel() { return permissionModel; }
+ public void setPermissionModel(String permissionModel) { this.permissionModel = permissionModel; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSetOperation.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSetOperation.java
new file mode 100644
index 0000000000..0e08a45e3a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSetOperation.java
@@ -0,0 +1,39 @@
+package io.github.hectorvent.floci.services.cloudformation.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class StackSetOperation {
+ private String operationId;
+ private String stackSetName;
+ /** CREATE, UPDATE or DELETE. */
+ private String action;
+ private String status = "SUCCEEDED";
+ private Instant creationTimestamp = Instant.now();
+ private Instant endTimestamp;
+
+ public StackSetOperation() {}
+
+ public StackSetOperation(String operationId, String stackSetName, String action) {
+ this.operationId = operationId;
+ this.stackSetName = stackSetName;
+ this.action = action;
+ }
+
+ public String getOperationId() { return operationId; }
+ public void setOperationId(String operationId) { this.operationId = operationId; }
+ public String getStackSetName() { return stackSetName; }
+ public void setStackSetName(String stackSetName) { this.stackSetName = stackSetName; }
+ public String getAction() { return action; }
+ public void setAction(String action) { this.action = action; }
+ public String getStatus() { return status; }
+ public void setStatus(String status) { this.status = status; }
+ public Instant getCreationTimestamp() { return creationTimestamp; }
+ public void setCreationTimestamp(Instant creationTimestamp) { this.creationTimestamp = creationTimestamp; }
+ public Instant getEndTimestamp() { return endTimestamp; }
+ public void setEndTimestamp(Instant endTimestamp) { this.endTimestamp = endTimestamp; }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java
new file mode 100644
index 0000000000..4c0ad7c5a5
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java
@@ -0,0 +1,484 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * Integration tests for cross-account CloudFormation provisioning:
+ * <ul>
+ * <li>single-stack resources land in the caller's account namespace; and</li>
+ * <li>StackSet instances materialize resources in each target account's namespace.</li>
+ * </ul>
+ */
+@QuarkusTest
+class CloudFormationStackSetsIntegrationTest {
+
+ private static final String ADMIN = "111111111111";
+ private static final String ACCOUNT_B = "222222222222";
+ private static final String ACCOUNT_C = "333333333333";
+ private static final String REGION = "us-east-1";
+
+ private static String auth(String account, String service) {
+ return "AWS4-HMAC-SHA256 Credential=" + account + "/20260215/" + REGION + "/" + service
+ + "/aws4_request, SignedHeaders=host, Signature=abc";
+ }
+
+ private static String queueTemplate(String queueName) {
+ return """
+ {"Resources":{"Q":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s"}}}}
+ """.formatted(queueName);
+ }
+
+ private void assertQueueVisible(String account, String queueName) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", queueName)
+ .header("Authorization", auth(account, "sqs"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("/" + account + "/" + queueName));
+ }
+
+ private void assertQueueAbsent(String account, String queueName) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", queueName)
+ .header("Authorization", auth(account, "sqs"))
+ .when().post("/")
+ .then().body(containsString("QueueDoesNotExist"));
+ }
+
+ @Test
+ void stackSetFromTemplateUrlProvisionsAndReportsDetailedStatus() {
+ String setName = "url-set-" + UUID.randomUUID().toString().substring(0, 8);
+ String queue = "url-q-" + UUID.randomUUID().toString().substring(0, 8);
+ String bucket = "tpl-bucket-" + UUID.randomUUID().toString().substring(0, 8);
+ String tkey = "template.json";
+
+ // Stage the template in S3, the way DPS does, then reference it by TemplateURL.
+ given().header("Authorization", auth(ADMIN, "s3")).when().put("/" + bucket)
+ .then().statusCode(200);
+ given().header("Authorization", auth(ADMIN, "s3")).body(queueTemplate(queue))
+ .when().put("/" + bucket + "/" + tkey).then().statusCode(200);
+ String templateUrl = "http://localhost:4566/" + bucket + "/" + tkey;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateURL", templateUrl)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<StackSetId>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // The template fetched from S3 was provisioned into account B.
+ assertQueueVisible(ACCOUNT_B, queue);
+
+ // DescribeStackInstance reports the nested StackInstanceStatus.DetailedStatus DPS polls.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackInstance")
+ .formParam("StackSetName", setName)
+ .formParam("StackInstanceAccount", ACCOUNT_B)
+ .formParam("StackInstanceRegion", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<DetailedStatus>SUCCEEDED</DetailedStatus>"));
+ }
+
+ @Test
+ void singleStackProvisioningLandsInCallerAccount() {
+ String queue = "single-" + UUID.randomUUID().toString().substring(0, 8);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "stack-" + queue)
+ .formParam("TemplateBody", queueTemplate(queue))
+ .header("Authorization", auth(ACCOUNT_B, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // Resource lands in the caller's account, not the default account.
+ assertQueueVisible(ACCOUNT_B, queue);
+ assertQueueAbsent("000000000000", queue);
+ }
+
+ @Test
+ void createStackSetWithoutTemplateIsRejected() {
+ // AWS rejects CreateStackSet when neither TemplateBody nor TemplateURL is supplied; otherwise
+ // a later CreateStackInstances would deploy empty stacks into every target account.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", "set-" + UUID.randomUUID().toString().substring(0, 8))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(400)
+ .body(containsString("ValidationError"));
+ }
+
+ @Test
+ void stackSetProvisionsInstancesIntoTargetAccounts() {
+ String setName = "set-" + UUID.randomUUID().toString().substring(0, 8);
+ String queue = "ss-" + UUID.randomUUID().toString().substring(0, 8);
+
+ // 1. Admin creates the StackSet.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", queueTemplate(queue))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<StackSetId>"));
+
+ // 2. Create instances into accounts B and C.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Accounts.member.2", ACCOUNT_C)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<OperationId>"));
+
+ // 3. The queue materializes in B and C, but not in the admin or default account.
+ assertQueueVisible(ACCOUNT_B, queue);
+ assertQueueVisible(ACCOUNT_C, queue);
+ assertQueueAbsent(ADMIN, queue);
+ assertQueueAbsent("000000000000", queue);
+
+ // 4. DescribeStackSet returns the definition.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackSet")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<StackSetName>" + setName + "</StackSetName>"))
+ .body(containsString("<Status>ACTIVE</Status>"));
+
+ // 5. ListStackInstances shows both target accounts.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListStackInstances")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<Account>" + ACCOUNT_B + "</Account>"))
+ .body(containsString("<Account>" + ACCOUNT_C + "</Account>"));
+
+ // 5b. DescribeStackInstance (singular) returns one target's instance.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackInstance")
+ .formParam("StackSetName", setName)
+ .formParam("StackInstanceAccount", ACCOUNT_B)
+ .formParam("StackInstanceRegion", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<Account>" + ACCOUNT_B + "</Account>"))
+ .body(containsString("<Region>" + REGION + "</Region>"));
+
+ // 6. ListStackSetOperations records the CREATE operation.
+ String operationId = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListStackSetOperations")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<Action>CREATE</Action>"))
+ .extract().path("ListStackSetOperationsResponse.ListStackSetOperationsResult.Summaries.member.OperationId");
+
+ // 6b. DescribeStackSetOperation returns that operation.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackSetOperation")
+ .formParam("StackSetName", setName)
+ .formParam("OperationId", operationId)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<OperationId>" + operationId + "</OperationId>"))
+ .body(containsString("<Status>SUCCEEDED</Status>"));
+
+ // 7. Delete the instances; resources and instance records go away.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Accounts.member.2", ACCOUNT_C)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<OperationId>"));
+
+ assertQueueAbsent(ACCOUNT_B, queue);
+ assertQueueAbsent(ACCOUNT_C, queue);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListStackInstances")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(not(containsString("<Account>" + ACCOUNT_B + "</Account>")));
+
+ // 8. With no instances left, the StackSet can be deleted.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStackSet")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void updateStackSetReappliesToExistingInstances() {
+ String setName = "upd-" + UUID.randomUUID().toString().substring(0, 8);
+ String q1 = "u1-" + UUID.randomUUID().toString().substring(0, 8);
+ String q2 = "u2-" + UUID.randomUUID().toString().substring(0, 8);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", queueTemplate(q1))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ assertQueueVisible(ACCOUNT_B, q1);
+ assertQueueAbsent(ACCOUNT_B, q2);
+
+ // Update the template to add a second queue; existing instances are re-applied.
+ String twoQueues = """
+ {"Resources":{
+ "Q1":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s"}},
+ "Q2":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s"}}}}
+ """.formatted(q1, q2);
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", twoQueues)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<OperationId>"));
+
+ // The newly added resource now exists in the target account.
+ assertQueueVisible(ACCOUNT_B, q2);
+
+ // The operation history records the update.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListStackSetOperations")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<Action>UPDATE</Action>"));
+ }
+
+ @Test
+ void stackSetErrorPaths() {
+ String setName = "errset-" + UUID.randomUUID().toString().substring(0, 8);
+ String queue = "errq-" + UUID.randomUUID().toString().substring(0, 8);
+
+ // Describe a non-existent stack set → StackSetNotFoundException.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackSet")
+ .formParam("StackSetName", "does-not-exist-" + setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(404)
+ .body(containsString("StackSetNotFoundException"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", queueTemplate(queue))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // Duplicate create → NameAlreadyExistsException.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", queueTemplate(queue))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(409)
+ .body(containsString("NameAlreadyExistsException"));
+
+ // Add an instance, then attempt to delete the non-empty set → StackSetNotEmptyException.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStackSet")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(409)
+ .body(containsString("StackSetNotEmptyException"));
+ }
+
+ @Test
+ void deleteStackInstancesWithRetainStacksKeepsUnderlyingResources() {
+ String setName = "retain-" + UUID.randomUUID().toString().substring(0, 8);
+ String queue = "retain-q-" + UUID.randomUUID().toString().substring(0, 8);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", queueTemplate(queue))
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+ assertQueueVisible(ACCOUNT_B, queue);
+
+ // RetainStacks=true (the SDK always sends it) detaches the instance but keeps the stack.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Regions.member.1", REGION)
+ .formParam("RetainStacks", "true")
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<OperationId>"));
+
+ // The instance is no longer part of the StackSet...
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListStackInstances")
+ .formParam("StackSetName", setName)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(not(containsString("<Account>" + ACCOUNT_B + "</Account>")));
+
+ // ...but its underlying resources were retained in the target account.
+ assertQueueVisible(ACCOUNT_B, queue);
+ }
+
+ @Test
+ void operationReportsFailedWhenAnInstanceRollsBack() {
+ String setName = "failset-" + UUID.randomUUID().toString().substring(0, 8);
+ // A nested stack with no TemplateURL fails to provision, rolling the instance stack back.
+ String badTemplate =
+ "{\"Resources\":{\"Nested\":{\"Type\":\"AWS::CloudFormation::Stack\",\"Properties\":{}}}}";
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackSet")
+ .formParam("StackSetName", setName)
+ .formParam("TemplateBody", badTemplate)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200);
+
+ String operationId = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStackInstances")
+ .formParam("StackSetName", setName)
+ .formParam("Accounts.member.1", ACCOUNT_B)
+ .formParam("Regions.member.1", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().path("CreateStackInstancesResponse.CreateStackInstancesResult.OperationId");
+
+ // The rolled-back instance is INOPERABLE / FAILED...
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackInstance")
+ .formParam("StackSetName", setName)
+ .formParam("StackInstanceAccount", ACCOUNT_B)
+ .formParam("StackInstanceRegion", REGION)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<DetailedStatus>FAILED</DetailedStatus>"));
+
+ // ...so the operation reports FAILED rather than a false SUCCEEDED.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStackSetOperation")
+ .formParam("StackSetName", setName)
+ .formParam("OperationId", operationId)
+ .header("Authorization", auth(ADMIN, "cloudformation"))
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<Status>FAILED</Status>"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/StackSetServiceDeleteFailureTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/StackSetServiceDeleteFailureTest.java
new file mode 100644
index 0000000000..ea418fdb0e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/StackSetServiceDeleteFailureTest.java
@@ -0,0 +1,109 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.cloudformation.model.Stack;
+import io.github.hectorvent.floci.services.cloudformation.model.StackInstance;
+import io.github.hectorvent.floci.services.cloudformation.model.StackSetOperation;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Focused coverage for how {@link StackSetService#deleteStackInstances} treats a failing underlying
+ * {@code deleteStack}. A non-retained delete whose stack delete fails must report the operation as
+ * FAILED and retain the instance record (AWS semantics) rather than swallowing the failure, dropping
+ * the instance, and reporting a false SUCCEEDED.
+ */
+class StackSetServiceDeleteFailureTest {
+
+ private static final String SET = "del-set";
+ private static final String ACCOUNT = "222222222222";
+ private static final String REGION = "us-east-1";
+
+ private CloudFormationService cfnService;
+ private StackSetService service;
+
+ @BeforeEach
+ void setUp() {
+ cfnService = mock(CloudFormationService.class);
+ // deployInstance drives the single-stack engine; stub it to a clean CREATE so the seeded
+ // instance starts SUCCEEDED, isolating this test to the delete path.
+ when(cfnService.executeChangeSet(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(CompletableFuture.completedFuture(null));
+ Stack created = new Stack();
+ created.setStackName("StackSet-" + SET + "-" + ACCOUNT);
+ created.setStackId("stack-id");
+ created.setStatus("CREATE_COMPLETE");
+ when(cfnService.describeStacks(anyString(), anyString())).thenReturn(List.of(created));
+
+ service = new StackSetService(cfnService, new InMemoryStorageFactory());
+ service.createStackSet(SET, "{\"Resources\":{}}", null, null, null, null);
+ service.createStackInstances(SET, List.of(ACCOUNT), List.of(REGION));
+ }
+
+ @Test
+ void nonRetainedDeleteFailureReportsFailedAndRetainsInstance() {
+ when(cfnService.deleteStack(anyString(), anyString(), anyString()))
+ .thenReturn(CompletableFuture.failedFuture(new RuntimeException("boom")));
+
+ StackSetOperation op = service.deleteStackInstances(SET, List.of(ACCOUNT), List.of(REGION), false);
+
+ // The operation must surface the failure, not a hardcoded SUCCEEDED.
+ assertEquals("FAILED", op.getStatus());
+ // The instance record is retained (AWS does not detach an instance whose stack delete failed)
+ // and marked INOPERABLE/FAILED.
+ List<StackInstance> remaining = service.listStackInstances(SET, null, null);
+ assertEquals(1, remaining.size(), "failed-delete instance must be retained");
+ assertEquals("INOPERABLE", remaining.get(0).getStatus());
+ assertEquals("FAILED", remaining.get(0).getDetailedStatus());
+ }
+
+ @Test
+ void nonRetainedDeleteSuccessReportsSucceededAndRemovesInstance() {
+ when(cfnService.deleteStack(anyString(), anyString(), anyString()))
+ .thenReturn(CompletableFuture.completedFuture(null));
+
+ StackSetOperation op = service.deleteStackInstances(SET, List.of(ACCOUNT), List.of(REGION), false);
+
+ assertEquals("SUCCEEDED", op.getStatus());
+ assertTrue(service.listStackInstances(SET, null, null).isEmpty(),
+ "successful delete must remove the instance");
+ }
+
+ @Test
+ void retainStacksRemovesInstanceWithoutDeletingStack() {
+ StackSetOperation op = service.deleteStackInstances(SET, List.of(ACCOUNT), List.of(REGION), true);
+
+ assertEquals("SUCCEEDED", op.getStatus());
+ assertTrue(service.listStackInstances(SET, null, null).isEmpty(),
+ "RetainStacks detaches the instance from the StackSet");
+ // RetainStacks=true must never invoke the underlying stack delete.
+ org.mockito.Mockito.verify(cfnService, org.mockito.Mockito.never())
+ .deleteStack(anyString(), anyString(), anyString());
+ }
+
+ private static final class InMemoryStorageFactory extends StorageFactory {
+ private InMemoryStorageFactory() {
+ super(null, null);
+ }
+
+ @Override
+ public <V> StorageBackend<String, V> create(String serviceName,
+ String fileName,
+ TypeReference<Map<String, V>> typeReference) {
+ return new InMemoryStorage<>();
+ }
+ }
+}