Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): support service-managed stacksets (#3055)
Franklin G. Mendoza41022d09fb7a
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.javaindex d2d9a5d2ec..99c7cf689b 100644--- 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@@ -84,6 +84,7 @@ class CloudFormationStackSetsTest {assertThat(ss.stackSetName()).isEqualTo(stackSetName);assertThat(ss.status()).isEqualTo(StackSetStatus.ACTIVE);assertThat(ss.templateBody()).contains(queueName);+ assertThat(ss.autoDeployment()).isNull();}@Testdiff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 75d8894a2c..a0e8bd0845 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -29,6 +29,8 @@| `SetStackPolicy` | Accepted; no-op (stub — stack policies are not enforced) || `GetStackPolicy` | Accepted; returns an empty policy (stub) || `DescribeStackResource` | Get a specific stack resource |+| `DescribeOrganizationsAccess` | - |+| `ActivateOrganizationsAccess` | - || `CreateStackSet` | Create a stack set from a template || `DescribeStackSet` | Get stack set details || `ListStackSets` | List stack sets |@@ -40,8 +42,17 @@| `DeleteStackInstances` | Remove instances and their resources || `ListStackSetOperations` | List operations performed on a stack set || `DescribeStackSetOperation` | - |+| `ListStackSetAutoDeploymentTargets` | - |<!-- floci:actions:end -->+## StackSets compatibility++StackSets support both `SELF_MANAGED` and the Cloud Launchpad `SERVICE_MANAGED` workflow. `ActivateOrganizationsAccess` requires an Organizations management account with all features enabled and enables trusted access for `stacksets.cloudformation.amazonaws.com`. Service-managed organizational-unit deployment targets are resolved from the caller's actual Organizations state rather than converted into synthetic account IDs. Targeting an OU includes eligible accounts directly in that OU and in all descendant OUs, while excluding the organization management account, matching AWS StackSets targeting semantics.++`CreateStackInstances` and `UpdateStackSet` execute the backing CloudFormation stacks in each target account. A failed resource can therefore drive the backing stack through rollback and leave the stack instance `INOPERABLE` with detailed status `FAILED`; the StackSet operation is reported as `FAILED` instead of being forced to success.++Operation IDs are recorded and validated. Duplicate IDs return `OperationIdAlreadyExistsException`, missing stack sets return `StackSetNotFoundException`, and missing operation IDs return `OperationNotFoundException`. Invalid targets and request shapes use the CloudFormation query-protocol validation errors. Operations complete locally, so `OperationInProgressException` is only reachable when local operation state actually overlaps; Floci does not inject concurrency failures solely to exercise an error code.+## Supported Resource TypesResource types provisioned during `CreateStack` / `UpdateStack` / `DeleteStack`. Each delegates todiff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.javaindex bf9f7a9f2e..c2ab571a4d 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@@ -9,6 +9,7 @@ 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.StackSetAutoDeploymentTarget;import io.github.hectorvent.floci.services.cloudformation.model.StackSetOperation;import io.github.hectorvent.floci.services.cloudformation.model.TemplateSummary;import jakarta.enterprise.context.ApplicationScoped;@@ -67,6 +68,8 @@ public class CloudFormationQueryHandler {case "SetStackPolicy" -> Response.ok(emptyResult("SetStackPolicyResponse")).build();case "GetStackPolicy" -> Response.ok(emptyResult("GetStackPolicyResponse")).build();case "DescribeStackResource" -> describeStackResource(params, region);+ case "DescribeOrganizationsAccess" -> describeOrganizationsAccess();+ case "ActivateOrganizationsAccess" -> activateOrganizationsAccess();case "CreateStackSet" -> createStackSet(params);case "DescribeStackSet" -> describeStackSet(params);case "ListStackSets" -> listStackSets();@@ -78,6 +81,7 @@ public class CloudFormationQueryHandler {case "DeleteStackInstances" -> deleteStackInstances(params);case "ListStackSetOperations" -> listStackSetOperations(params);case "DescribeStackSetOperation" -> describeStackSetOperation(params);+ case "ListStackSetAutoDeploymentTargets" -> listStackSetAutoDeploymentTargets(params);default -> xmlError("UnknownAction", "Action " + action + " is not supported.", 400);};}@@ -724,6 +728,46 @@ public class CloudFormationQueryHandler {// ── StackSets ─────────────────────────────────────────────────────────────+ private Response describeOrganizationsAccess() {+ String xml = new XmlBuilder().start("DescribeOrganizationsAccessResponse", CF_NS)+ .start("DescribeOrganizationsAccessResult")+ .elem("Status", stackSetService.isOrganizationsAccessEnabled() ? "ENABLED" : "DISABLED")+ .end("DescribeOrganizationsAccessResult").raw(AwsQueryResponse.responseMetadata())+ .end("DescribeOrganizationsAccessResponse").build();+ return Response.ok(xml).type("text/xml").build();+ }++ private Response activateOrganizationsAccess() {+ try {+ stackSetService.activateOrganizationsAccess();+ String xml = new XmlBuilder().start("ActivateOrganizationsAccessResponse", CF_NS)+ .start("ActivateOrganizationsAccessResult").end("ActivateOrganizationsAccessResult")+ .raw(AwsQueryResponse.responseMetadata()).end("ActivateOrganizationsAccessResponse").build();+ return Response.ok(xml).type("text/xml").build();+ } catch (AwsException e) {+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());+ }+ }++ private Response listStackSetAutoDeploymentTargets(MultivaluedMap<String, String> params) {+ try {+ List<StackSetAutoDeploymentTarget> targets =+ stackSetService.listStackSetAutoDeploymentTargets(params.getFirst("StackSetName"));+ XmlBuilder xml = new XmlBuilder().start("ListStackSetAutoDeploymentTargetsResponse", CF_NS)+ .start("ListStackSetAutoDeploymentTargetsResult").start("Summaries");+ for (StackSetAutoDeploymentTarget target : targets) {+ xml.start("member").elem("OrganizationalUnitId", target.getOrganizationalUnitId()).start("Regions");+ for (String region : target.getRegions()) xml.elem("member", region);+ xml.end("Regions").end("member");+ }+ xml.end("Summaries").end("ListStackSetAutoDeploymentTargetsResult")+ .raw(AwsQueryResponse.responseMetadata()).end("ListStackSetAutoDeploymentTargetsResponse");+ return Response.ok(xml.build()).type("text/xml").build();+ } catch (AwsException e) {+ return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());+ }+ }+private Response createStackSet(MultivaluedMap<String, String> params) {try {StackSet ss = stackSetService.createStackSet(@@ -732,7 +776,11 @@ public class CloudFormationQueryHandler {extractParameters(params),extractList(params, "Capabilities.member."),extractTags(params),- params.getFirst("Description"));+ params.getFirst("Description"),+ params.getFirst("PermissionModel"),+ Boolean.parseBoolean(params.getFirst("AutoDeployment.Enabled")),+ Boolean.parseBoolean(params.getFirst("AutoDeployment.RetainStacksOnAccountRemoval")),+ Boolean.parseBoolean(params.getFirst("ManagedExecution.Active")));String xml = new XmlBuilder().start("CreateStackSetResponse", CF_NS).start("CreateStackSetResult")@@ -760,6 +808,15 @@ public class CloudFormationQueryHandler {.elem("Description", ss.getDescription()).elem("TemplateBody", ss.getTemplateBody()).elem("PermissionModel", ss.getPermissionModel());+ if ("SERVICE_MANAGED".equals(ss.getPermissionModel())) {+ xml.start("AutoDeployment")+ .elem("Enabled", Boolean.toString(ss.isAutoDeploymentEnabled()))+ .elem("RetainStacksOnAccountRemoval", Boolean.toString(ss.isRetainStacksOnAccountRemoval()))+ .end("AutoDeployment");+ }+ xml.start("ManagedExecution")+ .elem("Active", Boolean.toString(ss.isManagedExecutionActive()))+ .end("ManagedExecution");appendCapabilities(xml, ss.getCapabilities());appendParameters(xml, ss.getParameters());xml.end("StackSet").end("DescribeStackSetResult")@@ -800,7 +857,14 @@ public class CloudFormationQueryHandler {extractParameters(params, previousParameters),extractList(params, "Capabilities.member."),extractTags(params),- params.getFirst("Description"));+ params.getFirst("Description"),+ params.getFirst("OperationId"),+ params.containsKey("AutoDeployment.Enabled")+ ? Boolean.parseBoolean(params.getFirst("AutoDeployment.Enabled")) : null,+ params.containsKey("AutoDeployment.RetainStacksOnAccountRemoval")+ ? Boolean.parseBoolean(params.getFirst("AutoDeployment.RetainStacksOnAccountRemoval")) : null,+ params.containsKey("ManagedExecution.Active")+ ? Boolean.parseBoolean(params.getFirst("ManagedExecution.Active")) : null);return operationResponse("UpdateStackSet", op.getOperationId());} catch (AwsException e) {return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());@@ -821,7 +885,9 @@ public class CloudFormationQueryHandler {StackSetOperation op = stackSetService.createStackInstances(params.getFirst("StackSetName"),extractList(params, "Accounts.member."),- resolveRegions(params, region));+ resolveRegions(params, region),+ extractList(params, "DeploymentTargets.OrganizationalUnitIds.member."),+ params.getFirst("OperationId"));return operationResponse("CreateStackInstances", op.getOperationId());} catch (AwsException e) {return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());@@ -843,6 +909,7 @@ public class CloudFormationQueryHandler {.elem("StackSetId", inst.getStackSetId()).elem("Account", inst.getAccount()).elem("Region", inst.getRegion())+ .elem("OrganizationalUnitId", inst.getOrganizationalUnitId()).elem("StackId", inst.getStackId()).elem("Status", inst.getStatus()).start("StackInstanceStatus")@@ -896,6 +963,7 @@ public class CloudFormationQueryHandler {params.getFirst("StackSetName"),extractList(params, "Accounts.member."),extractList(params, "Regions.member."),+ extractList(params, "DeploymentTargets.OrganizationalUnitIds.member."),Boolean.parseBoolean(params.getFirst("RetainStacks")));return operationResponse("DeleteStackInstances", op.getOperationId());} catch (AwsException e) {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.javaindex eb6007987c..3896e79ca1 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java@@ -2,12 +2,18 @@ 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.common.RegionResolver;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.StackSetAutoDeploymentTarget;import io.github.hectorvent.floci.services.cloudformation.model.StackSetOperation;+import io.github.hectorvent.floci.services.organizations.OrganizationsService;+import io.github.hectorvent.floci.services.organizations.model.Organization;+import io.github.hectorvent.floci.services.organizations.model.OrganizationAccount;+import io.github.hectorvent.floci.services.organizations.model.OrganizationalUnit;import com.fasterxml.jackson.core.type.TypeReference;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;@@ -16,10 +22,13 @@ import org.jboss.logging.Logger;import java.time.Instant;import java.util.ArrayList;import java.util.LinkedHashMap;+import java.util.LinkedHashSet;import java.util.List;import java.util.Map;+import java.util.Set;import java.util.UUID;import java.util.concurrent.Future;+import java.util.regex.Pattern;/*** CloudFormation StackSets — manages stack sets and provisions their instances across target@@ -34,16 +43,32 @@ import java.util.concurrent.Future;public class StackSetService {private static final Logger LOG = Logger.getLogger(StackSetService.class);+ private static final String STACKSETS_SERVICE_PRINCIPAL = "stacksets.cloudformation.amazonaws.com";private static final String INSTANCE_CHANGE_SET = "stackset-instance";private static final String UPDATE_CHANGE_SET = "stackset-update";+ private static final String ORGANIZATIONS_ACCESS_KEY = "organizations-access";+ private static final int STACK_SET_LIMIT = 1000;+ private static final Pattern STACK_SET_NAME = Pattern.compile("[A-Za-z][A-Za-z0-9-]{0,127}");+ private static final Pattern OPERATION_ID = Pattern.compile("[A-Za-z0-9][-A-Za-z0-9]{0,127}");+ private static final Pattern OU_OR_ROOT_ID = Pattern.compile("(?:ou-[a-z0-9]{4,32}-[a-z0-9]{8,32}|r-[a-z0-9]{4,32})");+ private static final Pattern REGION_PATTERN = Pattern.compile("[A-Za-z0-9-]{1,128}");private final CloudFormationService cfnService;private final StorageBackend<String, StackSet> stackSets;private final StorageBackend<String, StackInstance> instances;private final StorageBackend<String, StackSetOperation> operations;+ private final StorageBackend<String, String> organizationsAccess;+ private final StorageBackend<String, StackSetAutoDeploymentTarget> autoDeploymentTargets;+ private final OrganizationsService organizationsService;+ private final RegionResolver regionResolver;++ StackSetService(CloudFormationService cfnService, StorageFactory storageFactory) {+ this(cfnService, storageFactory, null, new RegionResolver("us-east-1", "000000000000"));+ }@Inject- public StackSetService(CloudFormationService cfnService, StorageFactory storageFactory) {+ public StackSetService(CloudFormationService cfnService, StorageFactory storageFactory,+ OrganizationsService organizationsService, RegionResolver regionResolver) {this.cfnService = cfnService;this.stackSets = storageFactory.create("cloudformation", "cloudformation-stacksets.json",new TypeReference<Map<String, StackSet>>() {});@@ -51,45 +76,100 @@ public class StackSetService {new TypeReference<Map<String, StackInstance>>() {});this.operations = storageFactory.create("cloudformation", "cloudformation-stackset-operations.json",new TypeReference<Map<String, StackSetOperation>>() {});+ this.organizationsAccess = storageFactory.create("cloudformation", "cloudformation-organizations-access.json",+ new TypeReference<Map<String, String>>() {});+ this.autoDeploymentTargets = storageFactory.create("cloudformation", "cloudformation-stackset-auto-targets.json",+ new TypeReference<Map<String, StackSetAutoDeploymentTarget>>() {});+ this.organizationsService = organizationsService;+ this.regionResolver = regionResolver;}// ── 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);- }+ return createStackSet(name, templateBody, parameters, capabilities, tags, description,+ "SELF_MANAGED", false, false, false);+ }++ public synchronized StackSet createStackSet(String name, String templateBody, Map<String, String> parameters,+ List<String> capabilities, Map<String, String> tags, String description,+ String permissionModel, boolean autoDeploymentEnabled,+ boolean retainStacksOnAccountRemoval, boolean managedExecutionActive) {+ validateStackSetName(name);if (stackSets.get(name).isPresent()) {- throw new AwsException("NameAlreadyExistsException",- "StackSet already exists: " + name, 409);+ throw new AwsException("NameAlreadyExistsException", "StackSet already exists: " + name, 409);+ }+ if (stackSets.scan(key -> true).size() >= STACK_SET_LIMIT) {+ throw new AwsException("LimitExceededException", "The StackSet quota has been reached.", 400);}- // 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);+ }+ if (templateBody.length() > 51_200) {+ throw new AwsException("ValidationError", "TemplateBody must be no larger than 51200 bytes.", 400);+ }+ if (description != null && (description.isBlank() || description.length() > 1024)) {+ throw new AwsException("ValidationError", "Description must be between 1 and 1024 characters.", 400);+ }+ if (tags != null && tags.size() > 50) {+ throw new AwsException("ValidationError", "A StackSet can have at most 50 tags.", 400);+ }+ String resolvedPermissionModel = permissionModel == null || permissionModel.isBlank()+ ? "SELF_MANAGED" : permissionModel;+ if (!Set.of("SELF_MANAGED", "SERVICE_MANAGED").contains(resolvedPermissionModel)) {+ throw new AwsException("ValidationError", "PermissionModel must be SELF_MANAGED or SERVICE_MANAGED.", 400);+ }+ if ("SERVICE_MANAGED".equals(resolvedPermissionModel) && !isOrganizationsAccessEnabled()) {throw new AwsException("ValidationError",- "Either TemplateBody or TemplateURL must be specified", 400);+ "Activate trusted access with AWS Organizations before creating a service-managed StackSet.", 400);+ }+ if ("SELF_MANAGED".equals(resolvedPermissionModel) && (autoDeploymentEnabled || retainStacksOnAccountRemoval)) {+ throw new AwsException("ValidationError", "AutoDeployment is valid only for SERVICE_MANAGED StackSets.", 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);- }+ ss.setPermissionModel(resolvedPermissionModel);+ ss.setAutoDeploymentEnabled(autoDeploymentEnabled);+ ss.setRetainStacksOnAccountRemoval(retainStacksOnAccountRemoval);+ ss.setManagedExecutionActive(managedExecutionActive);+ 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 boolean isOrganizationsAccessEnabled() {+ return "ENABLED".equals(organizationsAccess.get(ORGANIZATIONS_ACCESS_KEY).orElse("DISABLED"));+ }++ public synchronized void activateOrganizationsAccess() {+ String caller = regionResolver.getAccountId();+ try {+ Organization organization = organizationsService.describeOrganization(caller);+ if (!caller.equals(organization.getMasterAccountId())) {+ throw new AwsException("InvalidOperationException",+ "Only the organization management account can activate trusted access.", 400);+ }+ if (!"ALL".equals(organization.getFeatureSet())) {+ throw new AwsException("InvalidOperationException",+ "AWS Organizations must have all features enabled before activating trusted access.", 400);+ }+ organizationsService.enableAWSServiceAccess(caller, STACKSETS_SERVICE_PRINCIPAL);+ } catch (AwsException e) {+ if ("InvalidOperationException".equals(e.getErrorCode())) throw e;+ throw new AwsException("InvalidOperationException",+ "The calling account must be the management account of an AWS Organization.", 400);+ }+ organizationsAccess.put(ORGANIZATIONS_ACCESS_KEY, "ENABLED");+ }+public StackSet describeStackSet(String name) {return getStackSetOrThrow(name);}@@ -101,7 +181,19 @@ public class StackSetService {public StackSetOperation updateStackSet(String name, String templateBody, Map<String, String> parameters,List<String> capabilities, Map<String, String> tags,String description) {+ return updateStackSet(name, templateBody, parameters, capabilities, tags, description,+ null, null, null, null);+ }++ public synchronized StackSetOperation updateStackSet(String name, String templateBody,+ Map<String, String> parameters,+ List<String> capabilities, Map<String, String> tags,+ String description, String requestedOperationId,+ Boolean autoDeploymentEnabled,+ Boolean retainStacksOnAccountRemoval,+ Boolean managedExecutionActive) {StackSet ss = getStackSetOrThrow(name);+ String operationId = reserveOperation(name, "UPDATE", requestedOperationId).getOperationId();if (templateBody != null && !templateBody.isBlank()) {ss.setTemplateBody(templateBody);}@@ -119,33 +211,49 @@ public class StackSetService {if (description != null) {ss.setDescription(description);}+ if (autoDeploymentEnabled != null) {+ if (!"SERVICE_MANAGED".equals(ss.getPermissionModel())) {+ completeOperation(name, operationId, "FAILED");+ throw new AwsException("InvalidOperationException",+ "AutoDeployment is valid only for SERVICE_MANAGED StackSets.", 400);+ }+ ss.setAutoDeploymentEnabled(autoDeploymentEnabled);+ }+ if (retainStacksOnAccountRemoval != null) ss.setRetainStacksOnAccountRemoval(retainStacksOnAccountRemoval);+ if (managedExecutionActive != null) ss.setManagedExecutionActive(managedExecutionActive);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)) {- // An instance whose stack is terminal - a failed create that rolled back, or a phase- // some earlier operation abandoned - is one the single-stack engine refuses to update.- // That is one instance failing, not a malformed request: AWS leaves such an instance- // INOPERABLE, updates the rest, and reports the operation FAILED. Deploying into it- // anyway would raise the refusal out of here and fail the whole UpdateStackSet call- // with a 400, updating no instance at all.- String stackStatus = cfnService.stackStatus(inst.getStackName(), inst.getRegion());- if (CloudFormationService.refusesUpdate(stackStatus)) {- inst.setStatus("INOPERABLE");- inst.setDetailedStatus("FAILED");- inst.setStatusReason("Stack instance is in " + stackStatus- + " state and can not be updated");- instances.put(instanceKey(name, inst.getAccount(), inst.getRegion()), inst);- deployed.add(inst);- continue;+ try {+ for (StackInstance inst : listStackInstances(name, null, null)) {+ // An instance whose stack is terminal - a failed create that rolled back, or a phase+ // some earlier operation abandoned - is one the single-stack engine refuses to update.+ // That is one instance failing, not a malformed request: AWS leaves such an instance+ // INOPERABLE, updates the rest, and reports the operation FAILED. Deploying into it+ // anyway would raise the refusal out of here and fail the whole UpdateStackSet call+ // with a 400, updating no instance at all.+ String stackStatus = cfnService.stackStatus(inst.getStackName(), inst.getRegion());+ if (CloudFormationService.refusesUpdate(stackStatus)) {+ inst.setStatus("INOPERABLE");+ inst.setDetailedStatus("FAILED");+ inst.setStatusReason("Stack instance is in " + stackStatus+ + " state and can not be updated");+ instances.put(instanceKey(name, inst.getAccount(), inst.getRegion()), inst);+ deployed.add(inst);+ continue;+ }+ StackInstance updated =+ deployInstance(ss, inst.getAccount(), inst.getRegion(), UPDATE_CHANGE_SET, "UPDATE");+ applyDeploymentTargets(updated, deploymentTargetsFor(inst));+ instances.put(instanceKey(name, updated.getAccount(), updated.getRegion()), updated);+ deployed.add(updated);}- StackInstance updated =- deployInstance(ss, inst.getAccount(), inst.getRegion(), UPDATE_CHANGE_SET, "UPDATE");- instances.put(instanceKey(name, updated.getAccount(), updated.getRegion()), updated);- deployed.add(updated);+ completeOperation(name, operationId, deriveOperationStatus(deployed));+ return describeStackSetOperation(name, operationId);+ } catch (RuntimeException e) {+ completeOperation(name, operationId, "FAILED");+ throw e;}- return recordOperation(name, "UPDATE", deriveOperationStatus(deployed));}public void deleteStackSet(String name) {@@ -161,29 +269,84 @@ public class StackSetService {// ── Instances ──────────────────────────────────────────────────────────────public StackSetOperation createStackInstances(String name, List<String> accounts, List<String> regions) {+ return createStackInstances(name, accounts, regions, List.of(), null);+ }++ public StackSetOperation createStackInstances(String name, List<String> accounts, List<String> regions,+ List<String> organizationalUnits) {+ return createStackInstances(name, accounts, regions, organizationalUnits, null);+ }++ public synchronized StackSetOperation createStackInstances(String name, List<String> accounts, List<String> regions,+ List<String> organizationalUnits, String requestedOperationId) {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);+ validateRegions(regions);+ List<String> directAccounts = accounts == null ? List.of() : accounts;+ List<String> targetOus = organizationalUnits == null ? List.of() : organizationalUnits;+ if (!directAccounts.isEmpty() && !targetOus.isEmpty()) {+ throw new AwsException("InvalidOperationException",+ "Specify Accounts or DeploymentTargets, but not both.", 400);+ }+ if (directAccounts.isEmpty() && targetOus.isEmpty()) {+ throw new AwsException("ValidationError", "Accounts or DeploymentTargets must contain at least one value.", 400);+ }+ if (!targetOus.isEmpty() && !"SERVICE_MANAGED".equals(ss.getPermissionModel())) {+ throw new AwsException("InvalidOperationException",+ "DeploymentTargets can be used only with SERVICE_MANAGED StackSets.", 400);+ }+ if (!directAccounts.isEmpty() && "SERVICE_MANAGED".equals(ss.getPermissionModel())) {+ throw new AwsException("InvalidOperationException",+ "Accounts can be used only with SELF_MANAGED StackSets. Use DeploymentTargets for SERVICE_MANAGED StackSets.", 400);}- if (accounts.stream().anyMatch(account -> account == null || !account.matches("[0-9]{12}"))) {+ if (directAccounts.stream().anyMatch(account -> account == null || !account.matches("[0-9]{12}"))) {throw new AwsException("ValidationError",- "1 validation error detected: Value '" + accounts+ "1 validation error detected: Value '" + directAccounts+ "' at 'accounts' failed to satisfy constraint: Member must satisfy constraint: "+ "[Member must have length less than or equal to 12, Member must have length "+ "greater than or equal to 12, Member must satisfy regular expression pattern: "- + "^[0-9]{12}$]",- 400);+ + "^[0-9]{12}$]", 400);}+ for (String ou : targetOus) validateOuOrRoot(ou);++ String operationId = reserveOperation(name, "CREATE", requestedOperationId).getOperationId();+ List<TargetAccount> targets = !directAccounts.isEmpty()+ ? directAccounts.stream().map(account -> new TargetAccount(account, Set.of())).toList()+ : resolveOrganizationTargets(targetOus, regions, name);+List<StackInstance> deployed = new ArrayList<>();- for (String account : accounts) {+ for (TargetAccount target : targets) {for (String region : regions) {- StackInstance inst = deployInstance(ss, account, region, INSTANCE_CHANGE_SET, "CREATE");- instances.put(instanceKey(name, account, region), inst);+ String instanceKey = instanceKey(name, target.accountId(), region);+ StackInstance existing = instances.get(instanceKey).orElse(null);+ if (existing != null && !"OUTDATED".equals(existing.getStatus())) {+ if (!target.organizationalUnitIds().isEmpty()) {+ Set<String> associations = deploymentTargetsFor(existing);+ if (associations.addAll(target.organizationalUnitIds())) {+ applyDeploymentTargets(existing, associations);+ instances.put(instanceKey, existing);+ }+ }+ continue;+ }+ StackInstance inst = deployInstance(ss, target.accountId(), region, INSTANCE_CHANGE_SET, "CREATE");+ Set<String> associations = existing == null+ ? new LinkedHashSet<>() : deploymentTargetsFor(existing);+ associations.addAll(target.organizationalUnitIds());+ applyDeploymentTargets(inst, associations);+ instances.put(instanceKey, inst);deployed.add(inst);}}- return recordOperation(name, "CREATE", deriveOperationStatus(deployed));+ completeOperation(name, operationId, deriveOperationStatus(deployed));+ return describeStackSetOperation(name, operationId);+ }++ public List<StackSetAutoDeploymentTarget> listStackSetAutoDeploymentTargets(String name) {+ getStackSetOrThrow(name);+ String prefix = name + "::";+ return autoDeploymentTargets.scan(key -> key.startsWith(prefix)).stream()+ .sorted(java.util.Comparator.comparing(StackSetAutoDeploymentTarget::getOrganizationalUnitId))+ .toList();}public List<StackInstance> listStackInstances(String name, String accountFilter, String regionFilter) {@@ -208,38 +371,87 @@ public class StackSetService {public StackSetOperation deleteStackInstances(String name, List<String> accounts, List<String> regions,boolean retainStacks) {- getStackSetOrThrow(name);- if (accounts == null || accounts.isEmpty() || regions == null || regions.isEmpty()) {+ return deleteStackInstances(name, accounts, regions, List.of(), retainStacks);+ }++ public StackSetOperation deleteStackInstances(String name, List<String> accounts, List<String> regions,+ List<String> organizationalUnits, boolean retainStacks) {+ StackSet stackSet = getStackSetOrThrow(name);+ validateRegions(regions);+ List<String> directAccounts = accounts == null ? List.of() : accounts;+ List<String> targetOus = organizationalUnits == null ? List.of() : organizationalUnits;+ if (!directAccounts.isEmpty() && !targetOus.isEmpty()) {+ throw new AwsException("InvalidOperationException",+ "Specify Accounts or DeploymentTargets, but not both.", 400);+ }+ if (directAccounts.isEmpty() && targetOus.isEmpty()) {throw new AwsException("ValidationError",- "Accounts and Regions must each contain at least one value", 400);+ "Accounts or DeploymentTargets must contain at least one value.", 400);+ }+ if (!targetOus.isEmpty() && !"SERVICE_MANAGED".equals(stackSet.getPermissionModel())) {+ throw new AwsException("InvalidOperationException",+ "DeploymentTargets can be used only with SERVICE_MANAGED StackSets.", 400);+ }+ if (!directAccounts.isEmpty() && "SERVICE_MANAGED".equals(stackSet.getPermissionModel())) {+ throw new AwsException("InvalidOperationException",+ "Accounts can be used only with SELF_MANAGED StackSets. Use DeploymentTargets for SERVICE_MANAGED StackSets.", 400);+ }+ for (String account : directAccounts) {+ validateAccountId(account);}+ for (String ou : targetOus) {+ validateOuOrRoot(ou);+ }++ Set<String> requestedRegions = Set.copyOf(regions);+ Set<String> requestedAccounts = Set.copyOf(directAccounts);+ Set<String> requestedDeploymentTargets = Set.copyOf(targetOus);+ List<StackInstance> targetInstances = listStackInstances(name, null, null).stream()+ .filter(inst -> requestedRegions.contains(inst.getRegion()))+ .filter(inst -> !requestedAccounts.isEmpty()+ ? requestedAccounts.contains(inst.getAccount())+ : deploymentTargetsFor(inst).stream().anyMatch(requestedDeploymentTargets::contains))+ .toList();+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");+ for (StackInstance inst : targetInstances) {+ String account = inst.getAccount();+ String region = inst.getRegion();+ String key = instanceKey(name, account, region);+ // Service-managed instances can be covered by multiple DeploymentTargets when a+ // parent OU and one of its descendants are both targeted. Removing one target must not+ // tear down the backing stack while another recorded target still covers the instance.+ if (!requestedDeploymentTargets.isEmpty()) {+ Set<String> remainingTargets = deploymentTargetsFor(inst);+ remainingTargets.removeAll(requestedDeploymentTargets);+ if (!remainingTargets.isEmpty()) {+ applyDeploymentTargets(inst, remainingTargets);instances.put(key, inst);+ inst.setDetailedStatus("SUCCEEDED");results.add(inst);continue;}- inst.setDetailedStatus("SUCCEEDED");- instances.delete(key);+ }+ 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));+ String operationStatus = deriveOperationStatus(results);+ if ("SUCCEEDED".equals(operationStatus) && !requestedDeploymentTargets.isEmpty()) {+ removeDeploymentTargetRegions(name, requestedDeploymentTargets, requestedRegions);+ }+ return recordOperation(name, "DELETE", operationStatus);}public List<StackSetOperation> listStackSetOperations(String name) {@@ -262,6 +474,150 @@ public class StackSetService {// ── Internal helpers ────────────────────────────────────────────────────────+ private void removeDeploymentTargetRegions(String stackSetName, Set<String> organizationalUnits,+ Set<String> regions) {+ for (String organizationalUnit : organizationalUnits) {+ String key = stackSetName + "::" + organizationalUnit;+ StackSetAutoDeploymentTarget target = autoDeploymentTargets.get(key).orElse(null);+ if (target == null) {+ continue;+ }+ List<String> remainingRegions = target.getRegions().stream()+ .filter(region -> !regions.contains(region))+ .toList();+ if (remainingRegions.isEmpty()) {+ autoDeploymentTargets.delete(key);+ } else {+ target.setRegions(remainingRegions);+ autoDeploymentTargets.put(key, target);+ }+ }+ }++ private List<TargetAccount> resolveOrganizationTargets(List<String> organizationalUnits,+ List<String> regions, String stackSetName) {+ return resolveOrganizationTargets(organizationalUnits, regions, stackSetName, true);+ }++ private List<TargetAccount> resolveOrganizationTargets(List<String> organizationalUnits,+ List<String> regions, String stackSetName,+ boolean persistTargets) {+ String caller = regionResolver.getAccountId();+ Organization organization;+ try {+ organization = organizationsService.describeOrganization(caller);+ } catch (AwsException e) {+ throw new AwsException("InvalidOperationException",+ "SERVICE_MANAGED StackSets require an AWS Organization.", 400);+ }+ LinkedHashMap<String, TargetAccount> targets = new LinkedHashMap<>();+ for (String ou : organizationalUnits) {+ collectOrganizationTargets(caller, organization, ou, ou, targets);+ if (persistTargets) {+ autoDeploymentTargets.put(stackSetName + "::" + ou,+ new StackSetAutoDeploymentTarget(stackSetName, ou, regions));+ }+ }+ return new ArrayList<>(targets.values());+ }++ private void collectOrganizationTargets(String caller, Organization organization, String parentId,+ String requestedTargetId,+ LinkedHashMap<String, TargetAccount> targets) {+ for (OrganizationAccount account : organizationsService.listAccountsForParent(caller, parentId)) {+ if (!organization.getMasterAccountId().equals(account.getId()) && "ACTIVE".equals(account.getStatus())) {+ targets.compute(account.getId(), (ignored, existing) -> {+ Set<String> associations = existing == null+ ? new LinkedHashSet<>() : new LinkedHashSet<>(existing.organizationalUnitIds());+ associations.add(requestedTargetId);+ return new TargetAccount(account.getId(), associations);+ });+ }+ }+ for (OrganizationalUnit child : organizationsService.listOrganizationalUnitsForParent(caller, parentId)) {+ collectOrganizationTargets(caller, organization, child.getId(), requestedTargetId, targets);+ }+ }++ private StackSetOperation reserveOperation(String stackSetName, String action, String requestedOperationId) {+ String operationId = requestedOperationId == null || requestedOperationId.isBlank()+ ? UUID.randomUUID().toString() : requestedOperationId;+ if (!OPERATION_ID.matcher(operationId).matches()) {+ throw new AwsException("ValidationError", "OperationId is invalid.", 400);+ }+ if (operations.get(stackSetName + ":" + operationId).isPresent()) {+ throw new AwsException("OperationIdAlreadyExistsException",+ "OperationId " + operationId + " already exists for StackSet " + stackSetName + ".", 409);+ }+ boolean running = operations.scan(key -> key.startsWith(stackSetName + ":")).stream()+ .anyMatch(operation -> "RUNNING".equals(operation.getStatus()));+ if (running) {+ throw new AwsException("OperationInProgressException",+ "Another operation is currently in progress for StackSet " + stackSetName + ".", 409);+ }+ StackSetOperation operation = new StackSetOperation(operationId, stackSetName, action);+ operation.setStatus("RUNNING");+ operation.setEndTimestamp(null);+ operations.put(stackSetName + ":" + operationId, operation);+ return operation;+ }++ private void completeOperation(String stackSetName, String operationId, String status) {+ StackSetOperation operation = operations.get(stackSetName + ":" + operationId)+ .orElseThrow(() -> new AwsException("OperationNotFoundException",+ "Operation " + operationId + " not found for stack set " + stackSetName, 404));+ operation.setStatus(status);+ operation.setEndTimestamp(Instant.now());+ operations.put(stackSetName + ":" + operationId, operation);+ }++ private static void validateStackSetName(String name) {+ if (name == null || !STACK_SET_NAME.matcher(name).matches()) {+ throw new AwsException("ValidationError",+ "StackSetName must start with a letter, contain only alphanumeric characters and hyphens, and be at most 128 characters.", 400);+ }+ }++ private static void validateAccountId(String account) {+ if (account == null || !account.matches("[0-9]{12}")) {+ throw new AwsException("ValidationError", "Accounts must contain 12 digit account IDs.", 400);+ }+ }++ private static void validateOuOrRoot(String value) {+ if (value == null || !OU_OR_ROOT_ID.matcher(value).matches()) {+ throw new AwsException("ValidationError", "DeploymentTargets contains an invalid organizational unit or root ID.", 400);+ }+ }++ private static void validateRegions(List<String> regions) {+ if (regions == null || regions.isEmpty()) {+ throw new AwsException("ValidationError", "Regions must contain at least one value.", 400);+ }+ if (regions.stream().anyMatch(region -> region == null || !REGION_PATTERN.matcher(region).matches())) {+ throw new AwsException("ValidationError", "Regions contains an invalid region name.", 400);+ }+ }++ private static Set<String> deploymentTargetsFor(StackInstance instance) {+ LinkedHashSet<String> targets = new LinkedHashSet<>();+ if (instance.getDeploymentTargetIds() != null) {+ targets.addAll(instance.getDeploymentTargetIds());+ }+ if (targets.isEmpty() && instance.getOrganizationalUnitId() != null) {+ targets.add(instance.getOrganizationalUnitId());+ }+ return targets;+ }++ private static void applyDeploymentTargets(StackInstance instance, Set<String> targets) {+ List<String> orderedTargets = new ArrayList<>(targets);+ instance.setDeploymentTargetIds(orderedTargets);+ instance.setOrganizationalUnitId(orderedTargets.isEmpty() ? null : orderedTargets.getFirst());+ }++ private record TargetAccount(String accountId, Set<String> organizationalUnitIds) {}+/*** Drives the single-stack engine to materialize one instance's resources into the target* account's namespace, then returns a {@link StackInstance} describing it.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.javaindex 3980c28a2b..52c810d065 100644--- 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@@ -3,6 +3,9 @@ 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.List;+@RegisterForReflection@JsonIgnoreProperties(ignoreUnknown = true)public class StackInstance {@@ -18,6 +21,16 @@ public class StackInstance {/** Last operation status (SUCCEEDED, FAILED, ...) reported under StackInstanceStatus.DetailedStatus. */private String detailedStatus = "SUCCEEDED";private String statusReason;+ private String organizationalUnitId;+ /**+ * Service-managed DeploymentTargets that currently cover this instance.+ *+ * <p>A single account/Region stack instance can be covered by more than one requested OU,+ * for example when both a parent OU and one of its descendants are StackSet targets. AWS+ * still exposes one {@code OrganizationalUnitId} on the public StackInstance shape, so this+ * list is emulator-internal persistence used to preserve all target associations.</p>+ */+ private List<String> deploymentTargetIds = new ArrayList<>();public String getStackSetId() { return stackSetId; }public void setStackSetId(String stackSetId) { this.stackSetId = stackSetId; }@@ -37,4 +50,10 @@ public class StackInstance {public void setDetailedStatus(String detailedStatus) { this.detailedStatus = detailedStatus; }public String getStatusReason() { return statusReason; }public void setStatusReason(String statusReason) { this.statusReason = statusReason; }+ public String getOrganizationalUnitId() { return organizationalUnitId; }+ public void setOrganizationalUnitId(String organizationalUnitId) { this.organizationalUnitId = organizationalUnitId; }+ public List<String> getDeploymentTargetIds() { return deploymentTargetIds; }+ public void setDeploymentTargetIds(List<String> deploymentTargetIds) {+ this.deploymentTargetIds = deploymentTargetIds == null ? new ArrayList<>() : new ArrayList<>(deploymentTargetIds);+ }}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.javaindex 97df2be0ee..c20609cc44 100644--- 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@@ -21,6 +21,9 @@ public class StackSet {private Map<String, String> tags = new LinkedHashMap<>();/** SELF_MANAGED or SERVICE_MANAGED; Floci only models SELF_MANAGED behavior. */private String permissionModel = "SELF_MANAGED";+ private boolean autoDeploymentEnabled;+ private boolean retainStacksOnAccountRemoval;+ private boolean managedExecutionActive;public String getStackSetId() { return stackSetId; }public void setStackSetId(String stackSetId) { this.stackSetId = stackSetId; }@@ -40,4 +43,10 @@ public class StackSet {public void setTags(Map<String, String> tags) { this.tags = tags; }public String getPermissionModel() { return permissionModel; }public void setPermissionModel(String permissionModel) { this.permissionModel = permissionModel; }+ public boolean isAutoDeploymentEnabled() { return autoDeploymentEnabled; }+ public void setAutoDeploymentEnabled(boolean value) { this.autoDeploymentEnabled = value; }+ public boolean isRetainStacksOnAccountRemoval() { return retainStacksOnAccountRemoval; }+ public void setRetainStacksOnAccountRemoval(boolean value) { this.retainStacksOnAccountRemoval = value; }+ public boolean isManagedExecutionActive() { return managedExecutionActive; }+ public void setManagedExecutionActive(boolean value) { this.managedExecutionActive = value; }}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSetAutoDeploymentTarget.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSetAutoDeploymentTarget.javanew file mode 100644index 0000000000..3e1fbb1e5d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/StackSetAutoDeploymentTarget.java@@ -0,0 +1,30 @@+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.List;++@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class StackSetAutoDeploymentTarget {+ private String stackSetName;+ private String organizationalUnitId;+ private List<String> regions = new ArrayList<>();++ public StackSetAutoDeploymentTarget() {}++ public StackSetAutoDeploymentTarget(String stackSetName, String organizationalUnitId, List<String> regions) {+ this.stackSetName = stackSetName;+ this.organizationalUnitId = organizationalUnitId;+ this.regions = regions == null ? new ArrayList<>() : new ArrayList<>(regions);+ }++ public String getStackSetName() { return stackSetName; }+ public void setStackSetName(String stackSetName) { this.stackSetName = stackSetName; }+ public String getOrganizationalUnitId() { return organizationalUnitId; }+ public void setOrganizationalUnitId(String organizationalUnitId) { this.organizationalUnitId = organizationalUnitId; }+ public List<String> getRegions() { return regions; }+ public void setRegions(List<String> regions) { this.regions = regions == null ? new ArrayList<>() : new ArrayList<>(regions); }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceManagedStackSetsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceManagedStackSetsIntegrationTest.javanew file mode 100644index 0000000000..6de0324a36--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceManagedStackSetsIntegrationTest.java@@ -0,0 +1,458 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.path.json.JsonPath;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.BeforeAll;+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.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.not;++/** AWS Organizations semantics required by service-managed CloudFormation StackSets. */+@QuarkusTest+class CloudFormationServiceManagedStackSetsIntegrationTest {+ private static final String MANAGEMENT = "555555555555";+ private static final String REGION = "us-east-1";+ private static final String ORG_TARGET = "AWSOrganizationsV20161128.";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void serviceManagedStackSetUsesTrustedAccessAndRecursesIntoChildOus() {+ organizations("CreateOrganization", "{\"FeatureSet\":\"ALL\"}")+ .post("/").then().statusCode(200);+ String rootId = organizations("ListRoots", "{}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("Roots[0].Id");++ String parentOu = organizations("CreateOrganizationalUnit",+ "{\"ParentId\":\"" + rootId + "\",\"Name\":\"StackSetsParent\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("OrganizationalUnit.Id");+ String childOu = organizations("CreateOrganizationalUnit",+ "{\"ParentId\":\"" + parentOu + "\",\"Name\":\"StackSetsChild\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("OrganizationalUnit.Id");++ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String directAccount = createAccount("stacksets-direct-" + suffix + "@example.com", "StackSetsDirect");+ String nestedAccount = createAccount("stacksets-nested-" + suffix + "@example.com", "StackSetsNested");+ moveAccount(directAccount, rootId, parentOu);+ moveAccount(nestedAccount, rootId, childOu);++ cloudFormation("ActivateOrganizationsAccess")+ .post("/").then().statusCode(200);++ organizations("ListAWSServiceAccessForOrganization", "{}")+ .post("/").then().statusCode(200)+ .body("EnabledServicePrincipals.ServicePrincipal",+ hasItem("stacksets.cloudformation.amazonaws.com"));++ cloudFormation("DescribeOrganizationsAccess")+ .post("/").then().statusCode(200)+ .body(containsString("<Status>ENABLED</Status>"));++ String stackSet = "nested-ou-" + suffix;+ String queue = "nested-ou-q-" + suffix;+ cloudFormation("CreateStackSet")+ .formParam("StackSetName", stackSet)+ .formParam("TemplateBody", queueTemplate(queue))+ .formParam("PermissionModel", "SERVICE_MANAGED")+ .formParam("AutoDeployment.Enabled", "true")+ .post("/").then().statusCode(200);++ cloudFormation("CreateStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", parentOu)+ .formParam("Regions.member.1", REGION)+ .post("/").then().statusCode(200)+ .body(containsString("<OperationId>"));++ assertQueueVisible(directAccount, queue);+ assertQueueVisible(nestedAccount, queue);++ cloudFormation("ListStackSetAutoDeploymentTargets")+ .formParam("StackSetName", stackSet)+ .post("/").then().statusCode(200)+ .body(containsString("<OrganizationalUnitId>" + parentOu + "</OrganizationalUnitId>"))+ .body(containsString("<member>" + REGION + "</member>"));++ cloudFormation("ListStackInstances")+ .formParam("StackSetName", stackSet)+ .post("/").then().statusCode(200)+ .body(containsString("<Account>" + directAccount + "</Account>"))+ .body(containsString("<Account>" + nestedAccount + "</Account>"))+ .body(containsString("<OrganizationalUnitId>" + parentOu + "</OrganizationalUnitId>"));+ }++ @Test+ void serviceManagedStackSetRejectsTopLevelAccounts() {+ String management = "777777777777";+ String targetAccount = "999999999999";+ organizations(management, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")+ .post("/").then().statusCode(200);+ cloudFormation(management, "ActivateOrganizationsAccess")+ .post("/").then().statusCode(200);++ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String stackSet = "reject-accounts-" + suffix;+ String queue = "reject-accounts-q-" + suffix;+ cloudFormation(management, "CreateStackSet")+ .formParam("StackSetName", stackSet)+ .formParam("TemplateBody", queueTemplate(queue))+ .formParam("PermissionModel", "SERVICE_MANAGED")+ .post("/").then().statusCode(200);++ cloudFormation(management, "CreateStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("Accounts.member.1", targetAccount)+ .formParam("Regions.member.1", REGION)+ .post("/").then().statusCode(400)+ .body(containsString("InvalidOperationException"));++ assertQueueAbsent(targetAccount, queue);+ }++ @Test+ void createServiceManagedStackSetWithoutTrustedAccessUsesValidationError() {+ String management = "888888888888";+ organizations(management, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")+ .post("/").then().statusCode(200);++ cloudFormation(management, "CreateStackSet")+ .formParam("StackSetName", "no-access-" + UUID.randomUUID().toString().substring(0, 8))+ .formParam("TemplateBody", queueTemplate("unused"))+ .formParam("PermissionModel", "SERVICE_MANAGED")+ .post("/").then().statusCode(400)+ .body(containsString("ValidationError"))+ .body(not(containsString("InvalidOperationException")));+ }++ @Test+ void describeSelfManagedStackSetOmitsAutoDeployment() {+ String stackSet = "self-managed-" + UUID.randomUUID().toString().substring(0, 8);+ cloudFormation("CreateStackSet")+ .formParam("StackSetName", stackSet)+ .formParam("TemplateBody", queueTemplate("unused"))+ .post("/").then().statusCode(200);++ cloudFormation("DescribeStackSet")+ .formParam("StackSetName", stackSet)+ .post("/").then().statusCode(200)+ .body(containsString("<PermissionModel>SELF_MANAGED</PermissionModel>"))+ .body(not(containsString("<AutoDeployment>")));+ }++ @Test+ void serviceManagedDeleteRequiresDeploymentTargets() {+ String management = "909090909090";+ organizations(management, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")+ .post("/").then().statusCode(200);+ String rootId = organizations(management, "ListRoots", "{}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("Roots[0].Id");+ String targetOu = organizations(management, "CreateOrganizationalUnit",+ "{\"ParentId\":\"" + rootId + "\",\"Name\":\"DeleteTarget\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("OrganizationalUnit.Id");+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String targetAccount = organizations(management, "CreateAccount",+ "{\"Email\":\"delete-target-" + suffix + "@example.com\",\"AccountName\":\"DeleteTarget\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("CreateAccountStatus.AccountId");+ organizations(management, "MoveAccount",+ "{\"AccountId\":\"" + targetAccount + "\",\"SourceParentId\":\"" + rootId+ + "\",\"DestinationParentId\":\"" + targetOu + "\"}")+ .post("/").then().statusCode(200);+ cloudFormation(management, "ActivateOrganizationsAccess")+ .post("/").then().statusCode(200);++ String stackSet = "delete-targets-" + suffix;+ String queue = "delete-targets-q-" + suffix;+ cloudFormation(management, "CreateStackSet")+ .formParam("StackSetName", stackSet)+ .formParam("TemplateBody", queueTemplate(queue))+ .formParam("PermissionModel", "SERVICE_MANAGED")+ .formParam("AutoDeployment.Enabled", "true")+ .post("/").then().statusCode(200);+ cloudFormation(management, "CreateStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", targetOu)+ .formParam("Regions.member.1", REGION)+ .formParam("Regions.member.2", "us-west-2")+ .post("/").then().statusCode(200);+ assertQueueVisible(targetAccount, queue);++ cloudFormation(management, "DeleteStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("Accounts.member.1", targetAccount)+ .formParam("Regions.member.1", REGION)+ .formParam("RetainStacks", "false")+ .post("/").then().statusCode(400)+ .body(containsString("InvalidOperationException"));+ assertQueueVisible(targetAccount, queue);++ cloudFormation(management, "DeleteStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", targetOu)+ .formParam("Regions.member.1", REGION)+ .formParam("RetainStacks", "false")+ .post("/").then().statusCode(200);+ assertQueueAbsent(targetAccount, queue);+ cloudFormation(management, "ListStackSetAutoDeploymentTargets")+ .formParam("StackSetName", stackSet)+ .post("/").then().statusCode(200)+ .body(containsString("<OrganizationalUnitId>" + targetOu + "</OrganizationalUnitId>"))+ .body(not(containsString("<member>" + REGION + "</member>")))+ .body(containsString("<member>us-west-2</member>"));++ cloudFormation(management, "DeleteStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", targetOu)+ .formParam("Regions.member.1", "us-west-2")+ .formParam("RetainStacks", "false")+ .post("/").then().statusCode(200);+ cloudFormation(management, "ListStackSetAutoDeploymentTargets")+ .formParam("StackSetName", stackSet)+ .post("/").then().statusCode(200)+ .body(not(containsString("<OrganizationalUnitId>" + targetOu + "</OrganizationalUnitId>")));+ }++ @Test+ void serviceManagedDeleteUsesPersistedOuAssociationAfterAccountMoves() {+ String management = "919191919191";+ organizations(management, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")+ .post("/").then().statusCode(200);+ String rootId = organizations(management, "ListRoots", "{}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("Roots[0].Id");+ String firstOu = organizations(management, "CreateOrganizationalUnit",+ "{\"ParentId\":\"" + rootId + "\",\"Name\":\"PersistedTargetA\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("OrganizationalUnit.Id");+ String secondOu = organizations(management, "CreateOrganizationalUnit",+ "{\"ParentId\":\"" + rootId + "\",\"Name\":\"PersistedTargetB\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("OrganizationalUnit.Id");+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String firstAccount = organizations(management, "CreateAccount",+ "{\"Email\":\"persisted-a-" + suffix + "@example.com\",\"AccountName\":\"PersistedA\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("CreateAccountStatus.AccountId");+ String secondAccount = organizations(management, "CreateAccount",+ "{\"Email\":\"persisted-b-" + suffix + "@example.com\",\"AccountName\":\"PersistedB\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("CreateAccountStatus.AccountId");+ organizations(management, "MoveAccount",+ "{\"AccountId\":\"" + firstAccount + "\",\"SourceParentId\":\"" + rootId+ + "\",\"DestinationParentId\":\"" + firstOu + "\"}")+ .post("/").then().statusCode(200);+ organizations(management, "MoveAccount",+ "{\"AccountId\":\"" + secondAccount + "\",\"SourceParentId\":\"" + rootId+ + "\",\"DestinationParentId\":\"" + secondOu + "\"}")+ .post("/").then().statusCode(200);+ cloudFormation(management, "ActivateOrganizationsAccess")+ .post("/").then().statusCode(200);++ String stackSet = "persisted-ou-" + suffix;+ String queue = "persisted-ou-q-" + suffix;+ cloudFormation(management, "CreateStackSet")+ .formParam("StackSetName", stackSet)+ .formParam("TemplateBody", queueTemplate(queue))+ .formParam("PermissionModel", "SERVICE_MANAGED")+ .post("/").then().statusCode(200);+ cloudFormation(management, "CreateStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", firstOu)+ .formParam("Regions.member.1", REGION)+ .post("/").then().statusCode(200);+ cloudFormation(management, "CreateStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", secondOu)+ .formParam("Regions.member.1", REGION)+ .post("/").then().statusCode(200);+ assertQueueVisible(firstAccount, queue);+ assertQueueVisible(secondAccount, queue);++ organizations(management, "MoveAccount",+ "{\"AccountId\":\"" + firstAccount + "\",\"SourceParentId\":\"" + firstOu+ + "\",\"DestinationParentId\":\"" + secondOu + "\"}")+ .post("/").then().statusCode(200);+ organizations(management, "MoveAccount",+ "{\"AccountId\":\"" + secondAccount + "\",\"SourceParentId\":\"" + secondOu+ + "\",\"DestinationParentId\":\"" + firstOu + "\"}")+ .post("/").then().statusCode(200);++ cloudFormation(management, "DeleteStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", firstOu)+ .formParam("Regions.member.1", REGION)+ .formParam("RetainStacks", "false")+ .post("/").then().statusCode(200);+ assertQueueAbsent(firstAccount, queue);+ assertQueueVisible(secondAccount, queue);++ cloudFormation(management, "DeleteStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", secondOu)+ .formParam("Regions.member.1", REGION)+ .formParam("RetainStacks", "false")+ .post("/").then().statusCode(200);+ assertQueueAbsent(secondAccount, queue);+ }++ @Test+ void overlappingOuTargetsKeepInstanceUntilLastAssociationIsDeleted() {+ String management = "929292929292";+ organizations(management, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")+ .post("/").then().statusCode(200);+ String rootId = organizations(management, "ListRoots", "{}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("Roots[0].Id");+ String parentOu = organizations(management, "CreateOrganizationalUnit",+ "{\"ParentId\":\"" + rootId + "\",\"Name\":\"OverlapParent\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("OrganizationalUnit.Id");+ String childOu = organizations(management, "CreateOrganizationalUnit",+ "{\"ParentId\":\"" + parentOu + "\",\"Name\":\"OverlapChild\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("OrganizationalUnit.Id");+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String account = organizations(management, "CreateAccount",+ "{\"Email\":\"overlap-" + suffix + "@example.com\",\"AccountName\":\"Overlap\"}")+ .post("/").then().statusCode(200)+ .extract().jsonPath().getString("CreateAccountStatus.AccountId");+ organizations(management, "MoveAccount",+ "{\"AccountId\":\"" + account + "\",\"SourceParentId\":\"" + rootId+ + "\",\"DestinationParentId\":\"" + childOu + "\"}")+ .post("/").then().statusCode(200);+ cloudFormation(management, "ActivateOrganizationsAccess")+ .post("/").then().statusCode(200);++ String stackSet = "overlap-ou-" + suffix;+ String queue = "overlap-ou-q-" + suffix;+ cloudFormation(management, "CreateStackSet")+ .formParam("StackSetName", stackSet)+ .formParam("TemplateBody", queueTemplate(queue))+ .formParam("PermissionModel", "SERVICE_MANAGED")+ .post("/").then().statusCode(200);+ cloudFormation(management, "CreateStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", parentOu)+ .formParam("Regions.member.1", REGION)+ .post("/").then().statusCode(200);+ cloudFormation(management, "CreateStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", childOu)+ .formParam("Regions.member.1", REGION)+ .post("/").then().statusCode(200);+ assertQueueVisible(account, queue);++ cloudFormation(management, "DeleteStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", parentOu)+ .formParam("Regions.member.1", REGION)+ .formParam("RetainStacks", "false")+ .post("/").then().statusCode(200);+ assertQueueVisible(account, queue);++ cloudFormation(management, "DeleteStackInstances")+ .formParam("StackSetName", stackSet)+ .formParam("DeploymentTargets.OrganizationalUnitIds.member.1", childOu)+ .formParam("Regions.member.1", REGION)+ .formParam("RetainStacks", "false")+ .post("/").then().statusCode(200);+ assertQueueAbsent(account, queue);+ }++ @Test+ void activateOrganizationsAccessRequiresAllFeatures() {+ String management = "666666666666";+ organizations(management, "CreateOrganization", "{\"FeatureSet\":\"CONSOLIDATED_BILLING\"}")+ .post("/").then().statusCode(200);++ cloudFormation(management, "ActivateOrganizationsAccess")+ .post("/").then().statusCode(400)+ .body(containsString("InvalidOperationException"))+ .body(containsString("all features"));+ }++ private String createAccount(String email, String name) {+ JsonPath response = organizations("CreateAccount",+ "{\"Email\":\"" + email + "\",\"AccountName\":\"" + name + "\"}")+ .post("/").then().statusCode(200)+ .body("CreateAccountStatus.State", equalTo("SUCCEEDED"))+ .extract().jsonPath();+ return response.getString("CreateAccountStatus.AccountId");+ }++ private void moveAccount(String accountId, String sourceParent, String destinationParent) {+ organizations("MoveAccount",+ "{\"AccountId\":\"" + accountId + "\",\"SourceParentId\":\"" + sourceParent+ + "\",\"DestinationParentId\":\"" + destinationParent + "\"}")+ .post("/").then().statusCode(200);+ }++ private RequestSpecification organizations(String action, String body) {+ return organizations(MANAGEMENT, action, body);+ }++ private RequestSpecification organizations(String account, String action, String body) {+ return given()+ .header("Authorization", auth(account, "organizations"))+ .header("X-Amz-Target", ORG_TARGET + action)+ .contentType("application/x-amz-json-1.1")+ .body(body);+ }++ private RequestSpecification cloudFormation(String action) {+ return cloudFormation(MANAGEMENT, action);+ }++ private RequestSpecification cloudFormation(String account, String action) {+ return given()+ .header("Authorization", auth(account, "cloudformation"))+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", action);+ }++ private void assertQueueVisible(String account, String queueName) {+ given()+ .header("Authorization", auth(account, "sqs"))+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetQueueUrl")+ .formParam("QueueName", queueName)+ .post("/").then().statusCode(200)+ .body(containsString("/" + account + "/" + queueName));+ }++ private void assertQueueAbsent(String account, String queueName) {+ given()+ .header("Authorization", auth(account, "sqs"))+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetQueueUrl")+ .formParam("QueueName", queueName)+ .post("/").then().statusCode(400)+ .body(containsString("AWS.SimpleQueueService.NonExistentQueue"));+ }++ private static String queueTemplate(String queueName) {+ return "{\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\",\"Properties\":{\"QueueName\":\""+ + queueName + "\"}}}}";+ }++ private static String auth(String account, String service) {+ return "AWS4-HMAC-SHA256 Credential=" + account + "/20260904/" + REGION + "/" + service+ + "/aws4_request, SignedHeaders=host, Signature=abc";+ }+}