Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(organizations): add CloudFormation resource types (#2495)

William St John Bacon054508df87a2
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 8e57290641..5c66f2add4 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -60,6 +60,7 @@ cross-resource references.
| DynamoDB | `Table`, `GlobalTable` |
| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into) |
| IAM | `Role`, `User`, `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` |
+| Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` |
| SSM | `Parameter` |
| KMS | `Key`, `Alias` |
| Secrets Manager | `Secret`, `SecretTargetAttachment` |
@@ -122,6 +123,34 @@ because their backing services are not implemented. A `SecretId` change is appli
than reproducing CloudFormation's replacement event sequence; failed changes restore affected secret
data and attachment ownership.
+## Organizations
+
+`AWS::Organizations::Organization` uses the stack's calling account as the management account, so
+the rest of the stack's Organizations resources are provisioned into that account's organization.
+`Fn::GetAtt Org.RootId` is the usual way to root the OU tree in the same template. `Organization` is
+the one type in this section where bare `Ref` does not return the resource's own id: per AWS, `Ref`
+returns the management account id, while `Fn::GetAtt Org.Id` returns the organization id.
+
+- `OrganizationalUnit` — `ParentId` is create-only per the registry schema, so an update only
+ renames the OU in place; the physical id survives, keeping every `Ref` to it valid.
+- `Account` — `ParentIds` accepts a single entry and the account is moved there after creation
+ (accounts are always created under the root). Because Floci resolves a 12-digit access key id
+ straight to an account, `Ref`/`Fn::GetAtt AccountId` yields an id you can immediately use as a
+ caller identity against other services. `State` mirrors `Status`, the parameter AWS is retiring
+ it in favour of; Floci does not model the `PENDING_ACTIVATION` or `CLOSED` phases that only
+ `State` can express.
+- `Policy` — `TargetIds` is reconciled on update: targets the template adds are attached and ones
+ it drops are detached. Deleting the resource detaches its remaining targets first, since
+ `DeletePolicy` refuses while a policy is still attached.
+- `ResourcePolicy` — backed by `PutResourcePolicy`, which is already create-or-update.
+
+`Fn::GetAtt OrganizationalUnit.Path` and `Fn::GetAtt Account.Paths` return the organization path —
+`o-<org>/r-<root>/[ou-<ou>/…]<id>/`. An account has one parent and therefore one path, so the
+list-typed `Paths` holds a single entry; read it with `Fn::Select` as you would on AWS.
+
+Deleting the stack removes the resources in dependency order and finally the organization itself.
+Deleting a resource that is already gone is tolerated.
+
## Auto Scaling Launch Template Resolution
`AWS::AutoScaling::AutoScalingGroup` resolves its launch template through any of the shapes AWS
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisioner.java
new file mode 100644
index 0000000000..37a39b04bd
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisioner.java
@@ -0,0 +1,328 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import io.github.hectorvent.floci.services.organizations.model.CreateAccountStatus;
+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.OrganizationPolicy;
+import io.github.hectorvent.floci.services.organizations.model.OrganizationalUnit;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for AWS Organizations: {@code AWS::Organizations::Organization},
+ * {@code OrganizationalUnit}, {@code Account}, {@code Policy} and {@code ResourcePolicy}.
+ *
+ * <p>Attribute names come from the registry schemas in
+ * {@code aws-cloudformation-resource-providers-organizations} ({@code readOnlyProperties}), so
+ * {@code Fn::GetAtt} resolves the same keys AWS publishes.
+ */
+@ApplicationScoped
+public class OrganizationsCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(OrganizationsCfnProvisioner.class);
+
+ private static final String ORGANIZATION = "AWS::Organizations::Organization";
+ private static final String ORGANIZATIONAL_UNIT = "AWS::Organizations::OrganizationalUnit";
+ private static final String ACCOUNT = "AWS::Organizations::Account";
+ private static final String POLICY = "AWS::Organizations::Policy";
+ private static final String RESOURCE_POLICY = "AWS::Organizations::ResourcePolicy";
+
+ private final OrganizationsService organizationsService;
+
+ @Inject
+ public OrganizationsCfnProvisioner(OrganizationsService organizationsService) {
+ this.organizationsService = organizationsService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(ORGANIZATION, ORGANIZATIONAL_UNIT, ACCOUNT, POLICY, RESOURCE_POLICY);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ switch (r.getResourceType()) {
+ case ORGANIZATION -> provisionOrganization(r, props, ctx);
+ case ORGANIZATIONAL_UNIT -> provisionOrganizationalUnit(r, props, ctx);
+ case ACCOUNT -> provisionAccount(r, props, ctx);
+ case POLICY -> provisionPolicy(r, props, ctx);
+ case RESOURCE_POLICY -> provisionResourcePolicy(r, props, ctx);
+ default -> throw new IllegalStateException(
+ "OrganizationsCfnProvisioner cannot handle " + r.getResourceType());
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ // The delete path carries no caller identity, so recover the owning management account
+ // from the resource id. Nothing matching means the resource is already gone.
+ String caller = organizationsService.findManagementAccountForResource(physicalId).orElse(null);
+ if (caller == null) {
+ LOG.debugv("No organization owns {0}; treating {1} as already deleted",
+ physicalId, resourceType);
+ return;
+ }
+ try {
+ switch (resourceType) {
+ case ORGANIZATION -> organizationsService.deleteOrganization(caller);
+ case ORGANIZATIONAL_UNIT -> organizationsService.deleteOrganizationalUnit(caller, physicalId);
+ case ACCOUNT -> organizationsService.removeAccountFromOrganization(caller, physicalId);
+ case POLICY -> deletePolicy(caller, physicalId);
+ case RESOURCE_POLICY -> organizationsService.deleteResourcePolicy(caller);
+ default -> LOG.debugv("No Organizations delete for {0}", resourceType);
+ }
+ } catch (AwsException e) {
+ // Deleting something already gone is tolerated; anything else is a real failure.
+ if (!isNotFound(e)) {
+ throw e;
+ }
+ LOG.debugv(e, "{0} {1} was already deleted", resourceType, physicalId);
+ }
+ }
+
+ // ──────────────────────────── Organization ────────────────────────────
+
+ private void provisionOrganization(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String featureSet = ctx.resolveOptional(props, "FeatureSet");
+ Organization organization;
+ if (r.getPhysicalId() != null) {
+ // UpdateStack re-invokes provision with the previous physical id. FeatureSet is the
+ // only settable property, and the only legal transition is the one-way upgrade to ALL.
+ organization = organizationsService.describeOrganization(ctx.accountId());
+ if ("ALL".equals(featureSet) && !"ALL".equals(organization.getFeatureSet())) {
+ organizationsService.enableAllFeatures(ctx.accountId());
+ organization = organizationsService.describeOrganization(ctx.accountId());
+ }
+ } else {
+ organization = organizationsService.createOrganization(ctx.accountId(), featureSet);
+ }
+
+ // AWS documents Organization as a special case: Ref returns the management account id,
+ // not the organization id. Fn::GetAtt Org.Id below still returns the organization id.
+ r.setPhysicalId(organization.getMasterAccountId());
+ r.getAttributes().put("Id", organization.getId());
+ r.getAttributes().put("Arn", organization.getArn());
+ r.getAttributes().put("ManagementAccountArn", organization.getMasterAccountArn());
+ r.getAttributes().put("ManagementAccountId", organization.getMasterAccountId());
+ r.getAttributes().put("ManagementAccountEmail", organization.getMasterAccountEmail());
+ r.getAttributes().put("RootId", organization.getRoot().getId());
+ }
+
+ // ──────────────────────────── Organizational unit ────────────────────────────
+
+ private void provisionOrganizationalUnit(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String name = ctx.resolveOptional(props, "Name");
+ String parentId = ctx.resolveOptional(props, "ParentId");
+ Map<String, String> tags = resolveTags(props, ctx);
+
+ OrganizationalUnit unit;
+ if (r.getPhysicalId() != null) {
+ // ParentId is createOnly in the registry schema, so an update only renames.
+ unit = organizationsService.updateOrganizationalUnit(ctx.accountId(), r.getPhysicalId(), name);
+ replaceTags(ctx.accountId(), unit.getId(), tags);
+ } else {
+ unit = organizationsService.createOrganizationalUnit(ctx.accountId(), parentId, name, tags);
+ // The OU is real once createOrganizationalUnit returns, so mark it stack-owned before
+ // the Path lookup below gets a chance to throw. CloudFormationService only deletes a
+ // CREATE_FAILED resource that is both marked owned and carries a physical id.
+ r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
+ }
+
+ r.setPhysicalId(unit.getId());
+ r.getAttributes().put("Id", unit.getId());
+ r.getAttributes().put("Arn", unit.getArn());
+ r.getAttributes().put("Path", organizationsService.organizationPath(ctx.accountId(), unit.getId()));
+ }
+
+ // ──────────────────────────── Account ────────────────────────────
+
+ private void provisionAccount(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String accountName = ctx.resolveOptional(props, "AccountName");
+ String email = ctx.resolveOptional(props, "Email");
+ Map<String, String> tags = resolveTags(props, ctx);
+ // ParentIds is a list in the schema but AWS accepts at most one entry.
+ List<String> parentIds = ctx.resolveStringList(props, "ParentIds");
+ String desiredParent = parentIds.isEmpty() ? null : parentIds.get(0);
+
+ OrganizationAccount account;
+ if (r.getPhysicalId() != null) {
+ account = organizationsService.describeAccount(ctx.accountId(), r.getPhysicalId());
+ replaceTags(ctx.accountId(), account.getId(), tags);
+ } else {
+ CreateAccountStatus status =
+ organizationsService.createAccount(ctx.accountId(), email, accountName, tags, false);
+ if (!"SUCCEEDED".equals(status.getState())) {
+ throw new AwsException("ConstraintViolationException",
+ "CreateAccount for " + accountName + " failed: " + status.getFailureReason(), 400);
+ }
+ // CreateAccount has already made this a real member of the organization, so claim it
+ // for the stack before anything else can throw. CloudFormationService only deletes a
+ // CREATE_FAILED resource that is both marked owned and carries a physical id, and the
+ // move below raises DestinationParentNotFoundException whenever ParentIds names an OU
+ // that isn't there — a broken Ref or a stale literal. Recording either marker later
+ // would leave the account behind, unmanaged, after the stack reported its rollback.
+ r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
+ r.setPhysicalId(status.getAccountId());
+ account = organizationsService.describeAccount(ctx.accountId(), status.getAccountId());
+ }
+
+ if (desiredParent != null && !desiredParent.equals(account.getParentId())) {
+ organizationsService.moveAccount(
+ ctx.accountId(), account.getId(), account.getParentId(), desiredParent);
+ account = organizationsService.describeAccount(ctx.accountId(), account.getId());
+ }
+
+ r.getAttributes().put("AccountId", account.getId());
+ r.getAttributes().put("Arn", account.getArn());
+ r.getAttributes().put("Status", account.getStatus());
+ // State supersedes Status in the Organizations API, which retires Status on 2026-09-09.
+ // Floci only ever puts an account in ACTIVE or PENDING_CLOSURE, and both are AccountState
+ // values too, so the two agree; the phases State adds — PENDING_ACTIVATION and CLOSED —
+ // are ones the emulator does not model.
+ r.getAttributes().put("State", account.getStatus());
+ r.getAttributes().put("JoinedMethod", account.getJoinedMethod());
+ if (account.getJoinedTimestamp() != null) {
+ r.getAttributes().put("JoinedTimestamp", account.getJoinedTimestamp().toString());
+ }
+ // Paths is a list in the schema, but an account has exactly one parent and so exactly one
+ // path. Attributes are string-valued, and the engine's Fn::Select splits a comma-delimited
+ // scalar back into a list, so a one-element list round-trips as itself. Read this after the
+ // move above: the path has to name the parent the account actually ended up in.
+ r.getAttributes().put("Paths",
+ organizationsService.organizationPath(ctx.accountId(), account.getId()));
+ }
+
+ // ──────────────────────────── Policy ────────────────────────────
+
+ private void provisionPolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String name = ctx.resolveOptional(props, "Name");
+ String type = ctx.resolveOptional(props, "Type");
+ String description = ctx.resolveOptional(props, "Description");
+ String content = resolveContent(props, ctx);
+ Map<String, String> tags = resolveTags(props, ctx);
+ Set<String> desiredTargets = new LinkedHashSet<>(ctx.resolveStringList(props, "TargetIds"));
+
+ OrganizationPolicy policy;
+ if (r.getPhysicalId() != null) {
+ policy = organizationsService.updatePolicy(
+ ctx.accountId(), r.getPhysicalId(), name, description, content);
+ replaceTags(ctx.accountId(), policy.getId(), tags);
+ } else {
+ policy = organizationsService.createPolicy(ctx.accountId(), content, description, name, type, tags);
+ // As above: the policy is real once createPolicy returns, so mark it stack-owned before
+ // reconcileTargets gets a chance to throw.
+ r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
+ }
+ // Same ordering as provisionAccount: the policy already exists once createPolicy returns,
+ // so claim the id before reconcileTargets, whose attach/detach calls can throw.
+ r.setPhysicalId(policy.getId());
+
+ reconcileTargets(ctx.accountId(), policy, desiredTargets);
+
+ r.getAttributes().put("Id", policy.getId());
+ r.getAttributes().put("Arn", policy.getArn());
+ r.getAttributes().put("AwsManaged", String.valueOf(policy.isAwsManaged()));
+ }
+
+ /** Attaches targets the template added and detaches the ones it dropped. */
+ private void reconcileTargets(String caller, OrganizationPolicy policy, Set<String> desired) {
+ Set<String> current = new LinkedHashSet<>(policy.getTargets());
+ for (String target : desired) {
+ if (!current.contains(target)) {
+ organizationsService.attachPolicy(caller, policy.getId(), target);
+ }
+ }
+ for (String target : current) {
+ if (!desired.contains(target)) {
+ organizationsService.detachPolicy(caller, policy.getId(), target);
+ }
+ }
+ }
+
+ private void deletePolicy(String caller, String policyId) {
+ // DeletePolicy refuses while the policy is still attached, so drop the attachments first.
+ organizationsService.listTargetsForPolicy(caller, policyId)
+ .forEach(target -> organizationsService.detachPolicy(caller, policyId, target.targetId()));
+ organizationsService.deletePolicy(caller, policyId);
+ }
+
+ // ──────────────────────────── Resource policy ────────────────────────────
+
+ private void provisionResourcePolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
+ // PutResourcePolicy is already create-or-update, so the same call serves both paths.
+ OrganizationsService.ResourcePolicyView policy = organizationsService.putResourcePolicy(
+ ctx.accountId(), resolveContent(props, ctx), resolveTags(props, ctx));
+
+ r.setPhysicalId(policy.id());
+ r.getAttributes().put("Id", policy.id());
+ r.getAttributes().put("Arn", policy.arn());
+ }
+
+ // ──────────────────────────── Helpers ────────────────────────────
+
+ /**
+ * {@code Content} is a policy document that templates write either as an inline JSON object or
+ * as a string built with {@code Fn::Sub}/{@code Fn::Join}. Both have to reach the service as
+ * the serialized string it stores.
+ */
+ private String resolveContent(JsonNode props, ProvisionContext ctx) {
+ if (props == null || !props.has("Content") || props.get("Content").isNull()) {
+ return null;
+ }
+ return ctx.engine().resolveJsonAttribute(props.get("Content"));
+ }
+
+ /** CloudFormation tags are a list of {@code {Key, Value}} objects. */
+ private Map<String, String> resolveTags(JsonNode props, ProvisionContext ctx) {
+ if (props == null || !props.has("Tags") || !props.get("Tags").isArray()) {
+ return null;
+ }
+ Map<String, String> tags = new LinkedHashMap<>();
+ for (JsonNode tag : ctx.engine().resolveNode(props.get("Tags"))) {
+ String key = tag.path("Key").asText(null);
+ if (key != null && !key.isBlank()) {
+ tags.put(key, tag.path("Value").asText(""));
+ }
+ }
+ return tags;
+ }
+
+ /**
+ * Makes the stored tags match the template on update: tag keys the template dropped are
+ * removed rather than left behind from the previous revision.
+ */
+ private void replaceTags(String caller, String resourceId, Map<String, String> tags) {
+ if (tags == null) {
+ return;
+ }
+ List<String> stale = organizationsService.listTagsForResource(caller, resourceId).keySet().stream()
+ .filter(key -> !tags.containsKey(key))
+ .toList();
+ if (!stale.isEmpty()) {
+ organizationsService.untagResource(caller, resourceId, stale);
+ }
+ if (!tags.isEmpty()) {
+ organizationsService.tagResource(caller, resourceId, tags);
+ }
+ }
+
+ private static boolean isNotFound(AwsException e) {
+ return switch (e.getErrorCode()) {
+ case "AWSOrganizationsNotInUseException", "AccountNotFoundException",
+ "OrganizationalUnitNotFoundException", "PolicyNotFoundException",
+ "ResourcePolicyNotFoundException" -> true;
+ default -> false;
+ };
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java
index 209039e29c..93e641d1bc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java
@@ -397,6 +397,17 @@ public class OrganizationsService {
return List.of(new ParentRef(parentId, parentType(organization, parentId)));
}
+ /**
+ * The organization path of a root, OU or account:
+ * {@code o-<org>/r-<root>[/ou-<ou>]*[/<accountId>]/}, trailing slash included. This is the
+ * value the Organizations API reports as {@code OrganizationalUnit.Path} and as the single
+ * entry of {@code Account.Paths}, and what {@code Fn::GetAtt} returns for the same keys.
+ */
+ public String organizationPath(String callerAccountId, String resourceId) {
+ Organization organization = requireOrganizationForCaller(callerAccountId);
+ return organization.getId() + "/" + String.join("/", ancestryOf(organization, resourceId)) + "/";
+ }
+
public List<ChildRef> listChildren(String callerAccountId, String parentId, String childType) {
Organization organization = requireOrganizationForCaller(callerAccountId);
requireParent(organization, parentId);
@@ -948,6 +959,12 @@ public class OrganizationsService {
}
organization.setResourcePolicyContent(content);
if (tags != null) {
+ // Put replaces rather than merges: a caller that supplies Tags is stating the full set,
+ // so a key it no longer lists is dropped. The resource policy is not addressable by
+ // TagResource/UntagResource the way accounts, OUs, roots and policies are, so this call
+ // is the only way CloudFormation can converge Tags on an update. Omitting Tags
+ // entirely (null) leaves the existing ones untouched.
+ organization.getResourcePolicyTags().clear();
organization.getResourcePolicyTags().putAll(tags);
}
organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);
@@ -1161,6 +1178,50 @@ public class OrganizationsService {
return organization;
}
+ /**
+ * The management account that owns the given organization, root, OU, account, policy or
+ * resource-policy id, or empty when nothing matches.
+ *
+ * <p>CloudFormation's delete path carries no caller identity — {@code CfnResourceProvisioner}
+ * hands over a physical id and a region only — so the owner has to be recovered from the
+ * resource itself before a management-account-scoped operation can run against it.
+ */
+ public Optional<String> findManagementAccountForResource(String resourceId) {
+ if (resourceId == null || resourceId.isEmpty()) {
+ return Optional.empty();
+ }
+ for (Organization organization : organizations.scanAllAccounts()) {
+ boolean owns = resourceId.equals(organization.getId())
+ || resourceId.equals(organization.getRoot().getId())
+ || resourceId.equals(organization.getResourcePolicyId());
+ if (owns) {
+ return Optional.of(organization.getMasterAccountId());
+ }
+ }
+ if (ACCOUNT_ID_PATTERN.matcher(resourceId).matches()) {
+ return accounts.scanAllAccounts().stream()
+ .filter(account -> resourceId.equals(account.getId()))
+ .findFirst()
+ .flatMap(account -> organizationById(account.getOrganizationId()))
+ .map(Organization::getMasterAccountId);
+ }
+ if (OU_ID_PATTERN.matcher(resourceId).matches()) {
+ return organizationalUnits.scanAllAccounts().stream()
+ .filter(unit -> resourceId.equals(unit.getId()))
+ .findFirst()
+ .flatMap(unit -> organizationById(unit.getOrganizationId()))
+ .map(Organization::getMasterAccountId);
+ }
+ if (POLICY_ID_PATTERN.matcher(resourceId).matches()) {
+ return policies.scanAllAccounts().stream()
+ .filter(policy -> resourceId.equals(policy.getId()))
+ .findFirst()
+ .flatMap(policy -> organizationById(policy.getOrganizationId()))
+ .map(Organization::getMasterAccountId);
+ }
+ return Optional.empty();
+ }
+
private Optional<Organization> findOrganizationForAccount(String accountId) {
for (Organization organization : organizations.scanAllAccounts()) {
if (accountId.equals(organization.getMasterAccountId())) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/OrganizationsCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/OrganizationsCfnIntegrationTest.java
new file mode 100644
index 0000000000..7c6785a893
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/OrganizationsCfnIntegrationTest.java
@@ -0,0 +1,340 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import java.time.Duration;
+import java.util.concurrent.TimeUnit;
+
+import static io.restassured.RestAssured.given;
+import static org.awaitility.Awaitility.await;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.matchesRegex;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.startsWith;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * The {@code AWS::Organizations::*} CloudFormation resource types end to end.
+ *
+ * <p>Every assertion goes through a stack {@code Output} backed by {@code Fn::GetAtt}. That is
+ * deliberate: an unmapped attribute does not fail provisioning, it silently resolves to the
+ * literal string {@code "LogicalId.Attr"}. Asserting {@code CREATE_COMPLETE}, or even that the
+ * underlying resource exists, would pass just as happily with every attribute unwired.
+ *
+ * <p>Runs as its own management account so it never contends with the Organizations service
+ * tests for the default account's organization.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class OrganizationsCfnIntegrationTest {
+
+ private static final String MANAGEMENT_ACCOUNT = "666666666666";
+ private static final String STACK_NAME = "organizations-stack";
+ private static final String ORGANIZATIONS_TARGET = "AWSOrganizationsV20161128.";
+ private static final String JSON_1_1 = "application/x-amz-json-1.1";
+
+ private static final String TEMPLATE = """
+ {
+ "Resources": {
+ "Org": {
+ "Type": "AWS::Organizations::Organization",
+ "Properties": { "FeatureSet": "ALL" }
+ },
+ "Workloads": {
+ "Type": "AWS::Organizations::OrganizationalUnit",
+ "Properties": {
+ "Name": "Workloads",
+ "ParentId": { "Fn::GetAtt": ["Org", "RootId"] },
+ "Tags": [ { "Key": "env", "Value": "test" } ]
+ }
+ },
+ "Dev": {
+ "Type": "AWS::Organizations::Account",
+ "Properties": {
+ "AccountName": "CfnDev",
+ "Email": "[email protected]",
+ "ParentIds": [ { "Ref": "Workloads" } ]
+ }
+ },
+ "Scp": {
+ "Type": "AWS::Organizations::Policy",
+ "Properties": {
+ "Name": "CfnDenyEc2",
+ "Type": "SERVICE_CONTROL_POLICY",
+ "Description": "Deny EC2",
+ "Content": {
+ "Version": "2012-10-17",
+ "Statement": [ { "Effect": "Deny", "Action": "ec2:*", "Resource": "*" } ]
+ },
+ "TargetIds": [ { "Ref": "Workloads" } ]
+ }
+ },
+ "Rp": {
+ "Type": "AWS::Organizations::ResourcePolicy",
+ "Properties": {
+ "Content": {
+ "Version": "2012-10-17",
+ "Statement": [ {
+ "Effect": "Allow",
+ "Principal": { "AWS": "*" },
+ "Action": "organizations:Describe*",
+ "Resource": "*"
+ } ]
+ }
+ }
+ }
+ },
+ "Outputs": {
+ "OrgId": { "Value": { "Fn::GetAtt": ["Org", "Id"] } },
+ "OrgArn": { "Value": { "Fn::GetAtt": ["Org", "Arn"] } },
+ "MgmtAccountId": { "Value": { "Fn::GetAtt": ["Org", "ManagementAccountId"] } },
+ "MgmtAccountArn": { "Value": { "Fn::GetAtt": ["Org", "ManagementAccountArn"] } },
+ "MgmtEmail": { "Value": { "Fn::GetAtt": ["Org", "ManagementAccountEmail"] } },
+ "RootId": { "Value": { "Fn::GetAtt": ["Org", "RootId"] } },
+ "OrgRef": { "Value": { "Ref": "Org" } },
+ "OuId": { "Value": { "Fn::GetAtt": ["Workloads", "Id"] } },
+ "OuArn": { "Value": { "Fn::GetAtt": ["Workloads", "Arn"] } },
+ "OuPath": { "Value": { "Fn::GetAtt": ["Workloads", "Path"] } },
+ "OuRef": { "Value": { "Ref": "Workloads" } },
+ "AccountId": { "Value": { "Fn::GetAtt": ["Dev", "AccountId"] } },
+ "AccountArn": { "Value": { "Fn::GetAtt": ["Dev", "Arn"] } },
+ "AccountStatus": { "Value": { "Fn::GetAtt": ["Dev", "Status"] } },
+ "AccountState": { "Value": { "Fn::GetAtt": ["Dev", "State"] } },
+ "AccountPaths": { "Value": { "Fn::GetAtt": ["Dev", "Paths"] } },
+ "AccountPath0": { "Value": { "Fn::Select": [0, { "Fn::GetAtt": ["Dev", "Paths"] }] } },
+ "AccountJoined": { "Value": { "Fn::GetAtt": ["Dev", "JoinedMethod"] } },
+ "AccountJoinedAt":{ "Value": { "Fn::GetAtt": ["Dev", "JoinedTimestamp"] } },
+ "PolicyId": { "Value": { "Fn::GetAtt": ["Scp", "Id"] } },
+ "PolicyArn": { "Value": { "Fn::GetAtt": ["Scp", "Arn"] } },
+ "PolicyAwsManaged": { "Value": { "Fn::GetAtt": ["Scp", "AwsManaged"] } },
+ "ResourcePolicyId": { "Value": { "Fn::GetAtt": ["Rp", "Id"] } },
+ "ResourcePolicyArn": { "Value": { "Fn::GetAtt": ["Rp", "Arn"] } }
+ }
+ }
+ """;
+
+ private String organizationId;
+ private String rootId;
+ private String ouId;
+ private String memberAccountId;
+ private String policyId;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static String authorization() {
+ return "AWS4-HMAC-SHA256 Credential=" + MANAGEMENT_ACCOUNT
+ + "/20260823/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc";
+ }
+
+ private static Response cloudFormation(String action, String... formParams) {
+ var request = given()
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + MANAGEMENT_ACCOUNT
+ + "/20260823/us-east-1/cloudformation/aws4_request, SignedHeaders=host, Signature=abc")
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", action);
+ for (int i = 0; i < formParams.length; i += 2) {
+ request = request.formParam(formParams[i], formParams[i + 1]);
+ }
+ return request.when().post("/");
+ }
+
+ private static Response organizations(String action, String body) {
+ return given()
+ .header("Authorization", authorization())
+ .header("X-Amz-Target", ORGANIZATIONS_TARGET + action)
+ .contentType(JSON_1_1)
+ .body(body)
+ .when().post("/");
+ }
+
+ private static Response describeStacks() {
+ return cloudFormation("DescribeStacks", "StackName", STACK_NAME);
+ }
+
+ /** Pulls a single {@code OutputValue} out of the DescribeStacks XML by its key. */
+ private static String output(Response response, String key) {
+ return response.xmlPath().getString(
+ "DescribeStacksResponse.DescribeStacksResult.Stacks.member.Outputs.member"
+ + ".find { it.OutputKey == '" + key + "' }.OutputValue");
+ }
+
+ private static void awaitStackStatus(String expected) {
+ await().atMost(Duration.ofSeconds(30)).pollInterval(200, TimeUnit.MILLISECONDS).until(() ->
+ expected.equals(describeStacks().xmlPath().getString(
+ "DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackStatus")));
+ }
+
+ @Test
+ @Order(1)
+ void createStackProvisionsEveryOrganizationsResourceType() {
+ cloudFormation("CreateStack", "StackName", STACK_NAME, "TemplateBody", TEMPLATE)
+ .then().statusCode(200);
+ awaitStackStatus("CREATE_COMPLETE");
+ }
+
+ @Test
+ @Order(2)
+ void organizationAttributesResolve() {
+ Response stacks = describeStacks();
+
+ organizationId = output(stacks, "OrgId");
+ rootId = output(stacks, "RootId");
+
+ assertThat(organizationId, matchesRegex("o-[a-z0-9]{10}"));
+ assertThat(rootId, matchesRegex("r-[a-z0-9]{4}"));
+ assertEquals("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":organization/" + organizationId,
+ output(stacks, "OrgArn"));
+ assertEquals(MANAGEMENT_ACCOUNT, output(stacks, "MgmtAccountId"));
+ assertEquals("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":account/" + organizationId
+ + "/" + MANAGEMENT_ACCOUNT, output(stacks, "MgmtAccountArn"));
+ assertThat(output(stacks, "MgmtEmail"), startsWith("master@"));
+ // Organization is the one AWS type where Ref returns the management account id rather than
+ // the resource's own id; Fn::GetAtt Org.Id above is what returns the organization id.
+ assertEquals(MANAGEMENT_ACCOUNT, output(stacks, "OrgRef"));
+ }
+
+ @Test
+ @Order(3)
+ void organizationalUnitAttributesResolveAndRefIsTheOuId() {
+ Response stacks = describeStacks();
+ ouId = output(stacks, "OuId");
+
+ assertThat(ouId, matchesRegex("ou-[a-z0-9]{4}-[a-z0-9]{8}"));
+ assertEquals("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":ou/" + organizationId + "/" + ouId,
+ output(stacks, "OuArn"));
+ // Path runs from the organization down to and including the OU, trailing slash and all.
+ assertEquals(organizationId + "/" + rootId + "/" + ouId + "/", output(stacks, "OuPath"));
+ // Ref resolves to the physical id, which is what ParentIds/TargetIds referenced.
+ assertEquals(ouId, output(stacks, "OuRef"));
+ }
+
+ @Test
+ @Order(4)
+ void accountAttributesResolve() {
+ Response stacks = describeStacks();
+ memberAccountId = output(stacks, "AccountId");
+
+ assertThat(memberAccountId, matchesRegex("\\d{12}"));
+ assertEquals("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":account/" + organizationId
+ + "/" + memberAccountId, output(stacks, "AccountArn"));
+ assertEquals("ACTIVE", output(stacks, "AccountStatus"));
+ // State is the successor AWS is retiring Status in favour of; both are mapped.
+ assertEquals("ACTIVE", output(stacks, "AccountState"));
+ assertEquals("CREATED", output(stacks, "AccountJoined"));
+ assertThat(output(stacks, "AccountJoinedAt"), matchesRegex("\\d{4}-\\d{2}-\\d{2}T.*Z"));
+
+ // Paths names the OU that ParentIds moved the account into, so it is read after the move
+ // rather than off the freshly created account still sitting under the root.
+ String path = organizationId + "/" + rootId + "/" + ouId + "/" + memberAccountId + "/";
+ assertEquals(path, output(stacks, "AccountPaths"));
+ // Paths is list-typed in the registry schema, and Fn::Select is how a template reads one.
+ assertEquals(path, output(stacks, "AccountPath0"));
+ }
+
+ @Test
+ @Order(5)
+ void policyAndResourcePolicyAttributesResolve() {
+ Response stacks = describeStacks();
+ policyId = output(stacks, "PolicyId");
+
+ assertThat(policyId, matchesRegex("p-[a-z0-9]{8}"));
+ assertEquals("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":policy/" + organizationId
+ + "/service_control_policy/" + policyId, output(stacks, "PolicyArn"));
+ assertEquals("false", output(stacks, "PolicyAwsManaged"));
+
+ assertThat(output(stacks, "ResourcePolicyId"), startsWith("rp-"));
+ assertEquals("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":resourcepolicy/" + organizationId
+ + "/" + output(stacks, "ResourcePolicyId"),
+ output(stacks, "ResourcePolicyArn"));
+ }
+
+ @Test
+ @Order(6)
+ void theProvisionedResourcesAreRealAndWiredTogether() {
+ organizations("DescribeOrganization", "{}")
+ .then().statusCode(200)
+ .body("Organization.Id", equalTo(organizationId))
+ .body("Organization.FeatureSet", equalTo("ALL"));
+
+ // ParentIds moved the account out of the root and into the OU.
+ organizations("ListAccountsForParent", "{\"ParentId\":\"" + ouId + "\"}")
+ .then().statusCode(200)
+ .body("Accounts.Id", hasItem(memberAccountId));
+
+ // TargetIds attached the SCP to the OU.
+ organizations("ListPoliciesForTarget",
+ "{\"TargetId\":\"" + ouId + "\",\"Filter\":\"SERVICE_CONTROL_POLICY\"}")
+ .then().statusCode(200)
+ .body("Policies.Id", hasItem(policyId));
+
+ // Tags on the OU came through the template.
+ organizations("ListTagsForResource", "{\"ResourceId\":\"" + ouId + "\"}")
+ .then().statusCode(200)
+ .body("Tags[0].Key", equalTo("env"))
+ .body("Tags[0].Value", equalTo("test"));
+
+ organizations("DescribeResourcePolicy", "{}")
+ .then().statusCode(200)
+ .body("ResourcePolicy.Content", org.hamcrest.Matchers.containsString("organizations:Describe*"));
+ }
+
+ @Test
+ @Order(7)
+ void updateStackRenamesInPlaceRatherThanRecreating() {
+ String updated = TEMPLATE.replace("\"Name\": \"Workloads\"", "\"Name\": \"Renamed\"");
+
+ cloudFormation("UpdateStack", "StackName", STACK_NAME, "TemplateBody", updated)
+ .then().statusCode(200);
+ awaitStackStatus("UPDATE_COMPLETE");
+
+ // The physical id must survive the update — a recreated OU would orphan the old one and
+ // break every Ref that pointed at it.
+ assertEquals(ouId, output(describeStacks(), "OuId"));
+ organizations("DescribeOrganizationalUnit", "{\"OrganizationalUnitId\":\"" + ouId + "\"}")
+ .then().statusCode(200)
+ .body("OrganizationalUnit.Name", equalTo("Renamed"));
+
+ organizations("ListAccounts", "{}")
+ .then().statusCode(200)
+ .body("Accounts.Id", hasItem(memberAccountId));
+ }
+
+ @Test
+ @Order(8)
+ void deleteStackTearsTheOrganizationDown() {
+ cloudFormation("DeleteStack", "StackName", STACK_NAME).then().statusCode(200);
+
+ await().atMost(Duration.ofSeconds(30)).pollInterval(200, TimeUnit.MILLISECONDS).until(() ->
+ organizations("DescribeOrganization", "{}").statusCode() == 400);
+
+ organizations("DescribeOrganization", "{}")
+ .then().statusCode(400)
+ .body("__type", equalTo("AWSOrganizationsNotInUseException"));
+ }
+
+ @Test
+ @Order(9)
+ void theManagementAccountIsFreeToStartOver() {
+ // The teardown must leave no organization behind for this account, otherwise a second
+ // stack — or a re-run of this test class — would hit AlreadyInOrganizationException.
+ organizations("CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
+ .then().statusCode(200)
+ .body("Organization.Id", not(equalTo(organizationId)));
+
+ organizations("DeleteOrganization", "{}").then().statusCode(200);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/OrganizationsCfnRollbackIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/OrganizationsCfnRollbackIntegrationTest.java
new file mode 100644
index 0000000000..16a2340dcc
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/OrganizationsCfnRollbackIntegrationTest.java
@@ -0,0 +1,132 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInstance;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import static io.restassured.RestAssured.given;
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Rollback of an {@code AWS::Organizations::Account} that fails <em>after</em> it was created.
+ *
+ * <p>{@code CreateAccount} succeeds and makes the account a real member of the organization, then
+ * {@code MoveAccount} raises {@code DestinationParentNotFoundException} because {@code ParentIds}
+ * names an OU that does not exist. Recovering from that needs two things from the provisioner, and
+ * missing either one strands the account: a physical id, and the
+ * {@code CfnRollback.ROLLBACK_OWNED_ATTR} marker. {@code CloudFormationService} only deletes a
+ * CREATE_FAILED resource when it has both, so without them rollback silently walks past the
+ * account, then fails to delete the organization it still belongs to and reports ROLLBACK_FAILED.
+ *
+ * <p>Runs as its own management account so it never contends for an organization with the other
+ * Organizations suites.
+ */
+@QuarkusTest
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+class OrganizationsCfnRollbackIntegrationTest {
+
+ private static final String MANAGEMENT_ACCOUNT = "676767676767";
+ private static final String STACK_NAME = "organizations-rollback-stack";
+ private static final String ORGANIZATIONS_TARGET = "AWSOrganizationsV20161128.";
+ private static final String JSON_1_1 = "application/x-amz-json-1.1";
+
+ /** ParentIds names a well-formed OU id that was never created. */
+ private static final String TEMPLATE = """
+ {
+ "Resources": {
+ "Org": {
+ "Type": "AWS::Organizations::Organization",
+ "Properties": { "FeatureSet": "ALL" }
+ },
+ "Stranded": {
+ "Type": "AWS::Organizations::Account",
+ "DependsOn": "Org",
+ "Properties": {
+ "AccountName": "stranded",
+ "Email": "[email protected]",
+ "ParentIds": [ "ou-zzzz-nosuchou1" ]
+ }
+ }
+ }
+ }
+ """;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static Response cloudFormation(String action, String... formParams) {
+ var request = given()
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + MANAGEMENT_ACCOUNT
+ + "/20260823/us-east-1/cloudformation/aws4_request, SignedHeaders=host, Signature=abc")
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", action);
+ for (int i = 0; i < formParams.length; i += 2) {
+ request = request.formParam(formParams[i], formParams[i + 1]);
+ }
+ return request.when().post("/");
+ }
+
+ private static Response organizations(String action, String body) {
+ return given()
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + MANAGEMENT_ACCOUNT
+ + "/20260823/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc")
+ .header("X-Amz-Target", ORGANIZATIONS_TARGET + action)
+ .contentType(JSON_1_1)
+ .body(body)
+ .when().post("/");
+ }
+
+ private static String stackStatus() {
+ return cloudFormation("DescribeStacks", "StackName", STACK_NAME).xmlPath().getString(
+ "DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackStatus");
+ }
+
+ @Test
+ void anAccountThatCannotBeMovedIsDeletedByRollbackRatherThanStranded() {
+ cloudFormation("CreateStack", "StackName", STACK_NAME, "TemplateBody", TEMPLATE)
+ .then().statusCode(200);
+
+ await().atMost(Duration.ofSeconds(30)).pollInterval(200, TimeUnit.MILLISECONDS)
+ .until(() -> {
+ String status = stackStatus();
+ return status != null && (status.endsWith("_COMPLETE") || status.endsWith("_FAILED"))
+ && !status.endsWith("IN_PROGRESS");
+ });
+
+ // ROLLBACK_FAILED here means rollback could not unwind the attempt — the account survived
+ // and kept the organization alive with it.
+ assertEquals("ROLLBACK_COMPLETE", stackStatus());
+
+ Response events = cloudFormation("DescribeStackEvents", "StackName", STACK_NAME);
+ List<String> strandedStatuses = events.xmlPath().getList(
+ "DescribeStackEventsResponse.DescribeStackEventsResult.StackEvents.member"
+ + ".findAll { it.LogicalResourceId == 'Stranded' }.ResourceStatus");
+ List<String> strandedIds = events.xmlPath().getList(
+ "DescribeStackEventsResponse.DescribeStackEventsResult.StackEvents.member"
+ + ".findAll { it.LogicalResourceId == 'Stranded' }.PhysicalResourceId");
+
+ // The account id has to reach the stack's own records, or rollback has nothing to delete.
+ assertTrue(strandedIds.stream().anyMatch(id -> id != null && id.matches("\\d{12}")),
+ "no account id was recorded for the failed resource: " + strandedIds);
+ // And rollback has to actually act on it rather than walk past a CREATE_FAILED resource.
+ assertTrue(strandedStatuses.contains("DELETE_COMPLETE"),
+ "rollback never deleted the created account; events were " + strandedStatuses);
+
+ // Nothing survives the unwind: no member account, and so the organization deletes cleanly.
+ assertEquals("AWSOrganizationsNotInUseException",
+ organizations("DescribeOrganization", "{}").jsonPath().getString("__type"));
+ assertNull(organizations("ListAccounts", "{}").jsonPath().getString("Accounts"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java
new file mode 100644
index 0000000000..fd7912cb49
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/OrganizationsCfnProvisionerTest.java
@@ -0,0 +1,548 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import io.github.hectorvent.floci.services.organizations.model.CreateAccountStatus;
+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.OrganizationPolicy;
+import io.github.hectorvent.floci.services.organizations.model.OrganizationalUnit;
+import io.github.hectorvent.floci.services.organizations.model.Root;
+import org.junit.jupiter.api.Test;
+import org.mockito.InOrder;
+
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * The Organizations CFN provisioner in isolation, with only {@link OrganizationsService} mocked.
+ *
+ * <p>The assertions name the exact {@code Fn::GetAtt} keys rather than just checking that
+ * provisioning succeeded: an unmapped attribute silently resolves to the literal
+ * {@code "LogicalId.Attr"}, so a status-only assertion cannot tell a wired type from an unwired one.
+ */
+class OrganizationsCfnProvisionerTest {
+
+ private static final String ACCOUNT = "000000000000";
+ private static final String ORG_ID = "o-abcdefghij";
+ private static final String ROOT_ID = "r-ab12";
+ private static final String OU_PATH = ORG_ID + "/" + ROOT_ID + "/ou-ab12-abcd1234/";
+ private static final String ACCOUNT_PATH = ORG_ID + "/" + ROOT_ID + "/123456789012/";
+
+ private final OrganizationsService organizations = mock(OrganizationsService.class);
+ private final OrganizationsCfnProvisioner provisioner = new OrganizationsCfnProvisioner(organizations);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node.isTextual() ? node.asText() : node.toString();
+ });
+ return new ProvisionContext(engine, "us-east-1", ACCOUNT, "my-stack");
+ }
+
+ private StackResource resource(String type, String logicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId(logicalId);
+ r.setResourceType(type);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private Organization organization(String featureSet) {
+ Organization organization = new Organization();
+ organization.setId(ORG_ID);
+ organization.setArn("arn:aws:organizations::" + ACCOUNT + ":organization/" + ORG_ID);
+ organization.setFeatureSet(featureSet);
+ organization.setMasterAccountId(ACCOUNT);
+ organization.setMasterAccountArn("arn:aws:organizations::" + ACCOUNT + ":account/" + ORG_ID + "/" + ACCOUNT);
+ organization.setMasterAccountEmail("[email protected]");
+ Root root = new Root();
+ root.setId(ROOT_ID);
+ root.setArn("arn:aws:organizations::" + ACCOUNT + ":root/" + ORG_ID + "/" + ROOT_ID);
+ organization.setRoot(root);
+ return organization;
+ }
+
+ // ──────────────────────────── Organization ────────────────────────────
+
+ @Test
+ void organizationSetsPhysicalIdAndEveryGetAttAttribute() {
+ when(organizations.createOrganization(ACCOUNT, "ALL")).thenReturn(organization("ALL"));
+ StackResource r = resource("AWS::Organizations::Organization", "Org");
+
+ provisioner.provision(r, mapper.createObjectNode().put("FeatureSet", "ALL"), ctx());
+
+ assertEquals(ACCOUNT, r.getPhysicalId());
+ assertEquals(ORG_ID, r.getAttributes().get("Id"));
+ assertEquals("arn:aws:organizations::" + ACCOUNT + ":organization/" + ORG_ID,
+ r.getAttributes().get("Arn"));
+ assertEquals(ACCOUNT, r.getAttributes().get("ManagementAccountId"));
+ assertEquals("arn:aws:organizations::" + ACCOUNT + ":account/" + ORG_ID + "/" + ACCOUNT,
+ r.getAttributes().get("ManagementAccountArn"));
+ assertEquals("[email protected]", r.getAttributes().get("ManagementAccountEmail"));
+ assertEquals(ROOT_ID, r.getAttributes().get("RootId"));
+ }
+
+ @Test
+ void organizationUpdateUpgradesConsolidatedBillingToAllFeatures() {
+ when(organizations.describeOrganization(ACCOUNT))
+ .thenReturn(organization("CONSOLIDATED_BILLING"), organization("ALL"));
+ StackResource r = resource("AWS::Organizations::Organization", "Org");
+ r.setPhysicalId(ACCOUNT);
+
+ provisioner.provision(r, mapper.createObjectNode().put("FeatureSet", "ALL"), ctx());
+
+ verify(organizations).enableAllFeatures(ACCOUNT);
+ verify(organizations, never()).createOrganization(anyString(), anyString());
+ assertEquals(ACCOUNT, r.getPhysicalId());
+ }
+
+ @Test
+ void organizationUpdateLeavesAnAlreadyUpgradedOrganizationAlone() {
+ when(organizations.describeOrganization(ACCOUNT)).thenReturn(organization("ALL"));
+ StackResource r = resource("AWS::Organizations::Organization", "Org");
+ r.setPhysicalId(ACCOUNT);
+
+ provisioner.provision(r, mapper.createObjectNode().put("FeatureSet", "ALL"), ctx());
+
+ verify(organizations, never()).enableAllFeatures(anyString());
+ }
+
+ // ──────────────────────────── Organizational unit ────────────────────────────
+
+ @Test
+ void organizationalUnitSetsPhysicalIdAndGetAttAttributes() {
+ OrganizationalUnit unit = new OrganizationalUnit();
+ unit.setId("ou-ab12-abcd1234");
+ unit.setArn("arn:aws:organizations::" + ACCOUNT + ":ou/" + ORG_ID + "/ou-ab12-abcd1234");
+ unit.setName("Workloads");
+ when(organizations.createOrganizationalUnit(eq(ACCOUNT), eq(ROOT_ID), eq("Workloads"), any()))
+ .thenReturn(unit);
+ when(organizations.organizationPath(ACCOUNT, "ou-ab12-abcd1234")).thenReturn(OU_PATH);
+
+ StackResource r = resource("AWS::Organizations::OrganizationalUnit", "Ou");
+ ObjectNode props = mapper.createObjectNode().put("Name", "Workloads").put("ParentId", ROOT_ID);
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("ou-ab12-abcd1234", r.getPhysicalId());
+ assertEquals("ou-ab12-abcd1234", r.getAttributes().get("Id"));
+ assertEquals("arn:aws:organizations::" + ACCOUNT + ":ou/" + ORG_ID + "/ou-ab12-abcd1234",
+ r.getAttributes().get("Arn"));
+ assertEquals(OU_PATH, r.getAttributes().get("Path"));
+ }
+
+ @Test
+ void anOuWhosePathLookupFailsStaysOwnedByTheStackForRollback() {
+ OrganizationalUnit unit = new OrganizationalUnit();
+ unit.setId("ou-ab12-abcd1234");
+ when(organizations.createOrganizationalUnit(eq(ACCOUNT), eq(ROOT_ID), eq("Workloads"), any()))
+ .thenReturn(unit);
+ when(organizations.organizationPath(ACCOUNT, "ou-ab12-abcd1234"))
+ .thenThrow(new AwsException("AWSOrganizationsNotInUseException", "gone", 400));
+
+ StackResource r = resource("AWS::Organizations::OrganizationalUnit", "Ou");
+ ObjectNode props = mapper.createObjectNode().put("Name", "Workloads").put("ParentId", ROOT_ID);
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+
+ // The OU is a real member of the organization by then. CloudFormationService only deletes a
+ // CREATE_FAILED resource carrying both markers, so losing either strands the OU.
+ assertEquals("ou-ab12-abcd1234", r.getPhysicalId());
+ assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
+ }
+
+ @Test
+ void organizationalUnitUpdateRenamesInsteadOfCreating() {
+ OrganizationalUnit unit = new OrganizationalUnit();
+ unit.setId("ou-ab12-abcd1234");
+ unit.setArn("arn:aws:organizations::" + ACCOUNT + ":ou/" + ORG_ID + "/ou-ab12-abcd1234");
+ unit.setName("Renamed");
+ when(organizations.updateOrganizationalUnit(ACCOUNT, "ou-ab12-abcd1234", "Renamed")).thenReturn(unit);
+
+ StackResource r = resource("AWS::Organizations::OrganizationalUnit", "Ou");
+ r.setPhysicalId("ou-ab12-abcd1234");
+ ObjectNode props = mapper.createObjectNode().put("Name", "Renamed").put("ParentId", ROOT_ID);
+
+ provisioner.provision(r, props, ctx());
+
+ verify(organizations).updateOrganizationalUnit(ACCOUNT, "ou-ab12-abcd1234", "Renamed");
+ verify(organizations, never()).createOrganizationalUnit(anyString(), anyString(), anyString(), any());
+ assertEquals("ou-ab12-abcd1234", r.getPhysicalId());
+ }
+
+ // ──────────────────────────── Account ────────────────────────────
+
+ private OrganizationAccount account(String parentId) {
+ OrganizationAccount account = new OrganizationAccount();
+ account.setId("123456789012");
+ account.setArn("arn:aws:organizations::" + ACCOUNT + ":account/" + ORG_ID + "/123456789012");
+ account.setName("Dev");
+ account.setEmail("[email protected]");
+ account.setStatus("ACTIVE");
+ account.setJoinedMethod("CREATED");
+ account.setJoinedTimestamp(Instant.parse("2026-08-23T00:00:00Z"));
+ account.setParentId(parentId);
+ return account;
+ }
+
+ @Test
+ void accountSetsPhysicalIdAndEveryGetAttAttribute() {
+ CreateAccountStatus status = new CreateAccountStatus();
+ status.setId("car-abcd1234");
+ status.setState("SUCCEEDED");
+ status.setAccountId("123456789012");
+ when(organizations.createAccount(eq(ACCOUNT), eq("[email protected]"), eq("Dev"), any(), eq(false)))
+ .thenReturn(status);
+ when(organizations.describeAccount(ACCOUNT, "123456789012")).thenReturn(account(ROOT_ID));
+ when(organizations.organizationPath(ACCOUNT, "123456789012")).thenReturn(ACCOUNT_PATH);
+
+ StackResource r = resource("AWS::Organizations::Account", "Dev");
+ ObjectNode props = mapper.createObjectNode()
+ .put("AccountName", "Dev").put("Email", "[email protected]");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("123456789012", r.getPhysicalId());
+ assertEquals("123456789012", r.getAttributes().get("AccountId"));
+ assertEquals("arn:aws:organizations::" + ACCOUNT + ":account/" + ORG_ID + "/123456789012",
+ r.getAttributes().get("Arn"));
+ assertEquals("ACTIVE", r.getAttributes().get("Status"));
+ assertEquals("ACTIVE", r.getAttributes().get("State"));
+ assertEquals("CREATED", r.getAttributes().get("JoinedMethod"));
+ assertEquals("2026-08-23T00:00:00Z", r.getAttributes().get("JoinedTimestamp"));
+ assertEquals(ACCOUNT_PATH, r.getAttributes().get("Paths"));
+ }
+
+ @Test
+ void accountPathsNameTheParentTheAccountWasMovedInto() {
+ CreateAccountStatus status = new CreateAccountStatus();
+ status.setState("SUCCEEDED");
+ status.setAccountId("123456789012");
+ when(organizations.createAccount(eq(ACCOUNT), anyString(), anyString(), any(), eq(false)))
+ .thenReturn(status);
+ when(organizations.describeAccount(ACCOUNT, "123456789012"))
+ .thenReturn(account(ROOT_ID), account("ou-ab12-abcd1234"));
+ when(organizations.organizationPath(ACCOUNT, "123456789012")).thenReturn(OU_PATH + "123456789012/");
+
+ StackResource r = resource("AWS::Organizations::Account", "Dev");
+ ObjectNode props = mapper.createObjectNode()
+ .put("AccountName", "Dev").put("Email", "[email protected]");
+ props.putArray("ParentIds").add("ou-ab12-abcd1234");
+
+ provisioner.provision(r, props, ctx());
+
+ // Accounts are always created under the root and moved afterwards, so reading the path
+ // before the move would publish the root path for an account that no longer lives there.
+ InOrder order = inOrder(organizations);
+ order.verify(organizations).moveAccount(ACCOUNT, "123456789012", ROOT_ID, "ou-ab12-abcd1234");
+ order.verify(organizations).organizationPath(ACCOUNT, "123456789012");
+ assertEquals(OU_PATH + "123456789012/", r.getAttributes().get("Paths"));
+ }
+
+ @Test
+ void accountWithParentIdsIsMovedOutOfTheRoot() {
+ CreateAccountStatus status = new CreateAccountStatus();
+ status.setState("SUCCEEDED");
+ status.setAccountId("123456789012");
+ when(organizations.createAccount(eq(ACCOUNT), anyString(), anyString(), any(), eq(false)))
+ .thenReturn(status);
+ when(organizations.describeAccount(ACCOUNT, "123456789012"))
+ .thenReturn(account(ROOT_ID), account("ou-ab12-abcd1234"));
+
+ StackResource r = resource("AWS::Organizations::Account", "Dev");
+ ObjectNode props = mapper.createObjectNode()
+ .put("AccountName", "Dev").put("Email", "[email protected]");
+ props.putArray("ParentIds").add("ou-ab12-abcd1234");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(organizations).moveAccount(ACCOUNT, "123456789012", ROOT_ID, "ou-ab12-abcd1234");
+ }
+
+ @Test
+ void accountAlreadyInTheRequestedParentIsNotMoved() {
+ CreateAccountStatus status = new CreateAccountStatus();
+ status.setState("SUCCEEDED");
+ status.setAccountId("123456789012");
+ when(organizations.createAccount(eq(ACCOUNT), anyString(), anyString(), any(), eq(false)))
+ .thenReturn(status);
+ when(organizations.describeAccount(ACCOUNT, "123456789012")).thenReturn(account("ou-ab12-abcd1234"));
+
+ StackResource r = resource("AWS::Organizations::Account", "Dev");
+ ObjectNode props = mapper.createObjectNode()
+ .put("AccountName", "Dev").put("Email", "[email protected]");
+ props.putArray("ParentIds").add("ou-ab12-abcd1234");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(organizations, never()).moveAccount(anyString(), anyString(), anyString(), anyString());
+ }
+
+ @Test
+ void anAccountThatFailsToMoveStillCarriesItsPhysicalIdForRollback() {
+ CreateAccountStatus status = new CreateAccountStatus();
+ status.setState("SUCCEEDED");
+ status.setAccountId("123456789012");
+ when(organizations.createAccount(eq(ACCOUNT), anyString(), anyString(), any(), eq(false)))
+ .thenReturn(status);
+ when(organizations.describeAccount(ACCOUNT, "123456789012")).thenReturn(account(ROOT_ID));
+ // A ParentIds entry pointing at an OU that isn't there — a broken Ref or a stale literal.
+ doThrow(new AwsException("DestinationParentNotFoundException", "no such parent", 400))
+ .when(organizations).moveAccount(anyString(), anyString(), anyString(), anyString());
+
+ StackResource r = resource("AWS::Organizations::Account", "Dev");
+ ObjectNode props = mapper.createObjectNode()
+ .put("AccountName", "Dev").put("Email", "[email protected]");
+ props.putArray("ParentIds").add("ou-ab12-missing1");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+
+ // CreateAccount already succeeded, so the account is a real member of the organization.
+ // Without the physical id, CloudFormation's rollback has nothing to call delete() with and
+ // the account is stranded outside the stack.
+ assertEquals("123456789012", r.getPhysicalId());
+ }
+
+ @Test
+ void aPolicyThatFailsToAttachStillCarriesItsPhysicalIdForRollback() {
+ when(organizations.createPolicy(eq(ACCOUNT), anyString(), any(), anyString(), anyString(), any()))
+ .thenReturn(policy());
+ doThrow(new AwsException("TargetNotFoundException", "no such target", 400))
+ .when(organizations).attachPolicy(anyString(), anyString(), anyString());
+
+ StackResource r = resource("AWS::Organizations::Policy", "Scp");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "scp").put("Type", "SERVICE_CONTROL_POLICY").put("Content", "{}");
+ props.putArray("TargetIds").add("ou-ab12-missing1");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+
+ assertEquals("p-abcd1234", r.getPhysicalId());
+ }
+
+ @Test
+ void aFailedCreateAccountFailsTheResource() {
+ CreateAccountStatus status = new CreateAccountStatus();
+ status.setState("FAILED");
+ status.setFailureReason("EMAIL_ALREADY_EXISTS");
+ when(organizations.createAccount(eq(ACCOUNT), anyString(), anyString(), any(), eq(false)))
+ .thenReturn(status);
+
+ StackResource r = resource("AWS::Organizations::Account", "Dev");
+ ObjectNode props = mapper.createObjectNode()
+ .put("AccountName", "Dev").put("Email", "[email protected]");
+
+ AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ assertEquals("ConstraintViolationException", error.getErrorCode());
+ }
+
+ // ──────────────────────────── Policy ────────────────────────────
+
+ private OrganizationPolicy policy(String... targets) {
+ OrganizationPolicy policy = new OrganizationPolicy();
+ policy.setId("p-abcd1234");
+ policy.setArn("arn:aws:organizations::" + ACCOUNT + ":policy/" + ORG_ID
+ + "/service_control_policy/p-abcd1234");
+ policy.setName("DenyEc2");
+ policy.setType("SERVICE_CONTROL_POLICY");
+ policy.getTargets().addAll(List.of(targets));
+ return policy;
+ }
+
+ @Test
+ void policySetsPhysicalIdAndGetAttAttributesAndAttachesTargets() {
+ when(organizations.createPolicy(eq(ACCOUNT), anyString(), any(), eq("DenyEc2"),
+ eq("SERVICE_CONTROL_POLICY"), any())).thenReturn(policy());
+
+ StackResource r = resource("AWS::Organizations::Policy", "Scp");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "DenyEc2").put("Type", "SERVICE_CONTROL_POLICY");
+ props.putObject("Content").put("Version", "2012-10-17");
+ props.putArray("TargetIds").add(ROOT_ID);
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("p-abcd1234", r.getPhysicalId());
+ assertEquals("p-abcd1234", r.getAttributes().get("Id"));
+ assertEquals("arn:aws:organizations::" + ACCOUNT + ":policy/" + ORG_ID
+ + "/service_control_policy/p-abcd1234", r.getAttributes().get("Arn"));
+ assertEquals("false", r.getAttributes().get("AwsManaged"));
+ verify(organizations).attachPolicy(ACCOUNT, "p-abcd1234", ROOT_ID);
+ }
+
+ @Test
+ void policyContentGivenAsAnInlineObjectIsSerializedForTheService() {
+ when(organizations.createPolicy(eq(ACCOUNT), eq("{\"Version\":\"2012-10-17\"}"), any(),
+ anyString(), anyString(), any())).thenReturn(policy());
+
+ StackResource r = resource("AWS::Organizations::Policy", "Scp");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "DenyEc2").put("Type", "SERVICE_CONTROL_POLICY");
+ props.putObject("Content").put("Version", "2012-10-17");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(organizations).createPolicy(ACCOUNT, "{\"Version\":\"2012-10-17\"}", null,
+ "DenyEc2", "SERVICE_CONTROL_POLICY", null);
+ }
+
+ @Test
+ void policyUpdateAttachesNewTargetsAndDetachesDroppedOnes() {
+ when(organizations.updatePolicy(eq(ACCOUNT), eq("p-abcd1234"), anyString(), any(), anyString()))
+ .thenReturn(policy(ROOT_ID, "ou-ab12-stale111"));
+ when(organizations.listTagsForResource(ACCOUNT, "p-abcd1234")).thenReturn(Map.of());
+
+ StackResource r = resource("AWS::Organizations::Policy", "Scp");
+ r.setPhysicalId("p-abcd1234");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "DenyEc2").put("Type", "SERVICE_CONTROL_POLICY");
+ props.putObject("Content").put("Version", "2012-10-17");
+ props.putArray("TargetIds").add(ROOT_ID).add("ou-ab12-newone11");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(organizations).attachPolicy(ACCOUNT, "p-abcd1234", "ou-ab12-newone11");
+ verify(organizations).detachPolicy(ACCOUNT, "p-abcd1234", "ou-ab12-stale111");
+ verify(organizations, never()).attachPolicy(ACCOUNT, "p-abcd1234", ROOT_ID);
+ }
+
+ // ──────────────────────────── Resource policy ────────────────────────────
+
+ @Test
+ void resourcePolicySetsPhysicalIdAndGetAttAttributes() {
+ when(organizations.putResourcePolicy(eq(ACCOUNT), anyString(), any()))
+ .thenReturn(new OrganizationsService.ResourcePolicyView("rp-abcd1234",
+ "arn:aws:organizations::" + ACCOUNT + ":resourcepolicy/" + ORG_ID + "/rp-abcd1234",
+ "{}", Map.of()));
+
+ StackResource r = resource("AWS::Organizations::ResourcePolicy", "Rp");
+ ObjectNode props = mapper.createObjectNode();
+ props.putObject("Content").put("Version", "2012-10-17");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("rp-abcd1234", r.getPhysicalId());
+ assertEquals("rp-abcd1234", r.getAttributes().get("Id"));
+ assertEquals("arn:aws:organizations::" + ACCOUNT + ":resourcepolicy/" + ORG_ID + "/rp-abcd1234",
+ r.getAttributes().get("Arn"));
+ }
+
+ @Test
+ void resourcePolicyUpdatePassesTheFullTagSetSoDroppedKeysAreRemoved() {
+ when(organizations.putResourcePolicy(eq(ACCOUNT), anyString(), any()))
+ .thenReturn(new OrganizationsService.ResourcePolicyView("rp-abcd1234",
+ "arn:aws:organizations::" + ACCOUNT + ":resourcepolicy/" + ORG_ID + "/rp-abcd1234",
+ "{}", Map.of()));
+
+ StackResource r = resource("AWS::Organizations::ResourcePolicy", "Rp");
+ r.setPhysicalId("rp-abcd1234");
+ ObjectNode props = mapper.createObjectNode();
+ props.putObject("Content").put("Version", "2012-10-17");
+ // The previous revision also carried "owner"; this one drops it.
+ props.putArray("Tags").addObject().put("Key", "env").put("Value", "prod");
+
+ provisioner.provision(r, props, ctx());
+
+ // putResourcePolicy replaces the tag map, so handing it exactly the template's set is what
+ // removes the dropped key. The other three types reach the same end via replaceTags, which
+ // cannot be used here because a resource policy is not a TagResource target.
+ verify(organizations).putResourcePolicy(eq(ACCOUNT), anyString(), eq(Map.of("env", "prod")));
+ }
+
+ // ──────────────────────────── Delete ────────────────────────────
+
+ @Test
+ void deleteResolvesTheOwningManagementAccountFromThePhysicalId() {
+ when(organizations.findManagementAccountForResource("ou-ab12-abcd1234"))
+ .thenReturn(Optional.of(ACCOUNT));
+
+ provisioner.delete("AWS::Organizations::OrganizationalUnit", "ou-ab12-abcd1234", "us-east-1");
+
+ verify(organizations).deleteOrganizationalUnit(ACCOUNT, "ou-ab12-abcd1234");
+ }
+
+ @Test
+ void deletingAPolicyDetachesItsTargetsFirst() {
+ when(organizations.findManagementAccountForResource("p-abcd1234")).thenReturn(Optional.of(ACCOUNT));
+ when(organizations.listTargetsForPolicy(ACCOUNT, "p-abcd1234")).thenReturn(List.of(
+ new OrganizationsService.PolicyTarget(ROOT_ID, "arn:root", "Root", "ROOT")));
+
+ provisioner.delete("AWS::Organizations::Policy", "p-abcd1234", "us-east-1");
+
+ verify(organizations).detachPolicy(ACCOUNT, "p-abcd1234", ROOT_ID);
+ verify(organizations).deletePolicy(ACCOUNT, "p-abcd1234");
+ }
+
+ @Test
+ void deletingAnAlreadyGoneResourceIsANoOp() {
+ when(organizations.findManagementAccountForResource("ou-ab12-abcd1234")).thenReturn(Optional.empty());
+
+ provisioner.delete("AWS::Organizations::OrganizationalUnit", "ou-ab12-abcd1234", "us-east-1");
+
+ verify(organizations).findManagementAccountForResource("ou-ab12-abcd1234");
+ verifyNoMoreInteractions(organizations);
+ }
+
+ @Test
+ void deleteToleratesAResourceThatDisappearedBetweenLookupAndDelete() {
+ when(organizations.findManagementAccountForResource("ou-ab12-abcd1234"))
+ .thenReturn(Optional.of(ACCOUNT));
+ org.mockito.Mockito.doThrow(new AwsException("OrganizationalUnitNotFoundException", "gone", 400))
+ .when(organizations).deleteOrganizationalUnit(ACCOUNT, "ou-ab12-abcd1234");
+
+ provisioner.delete("AWS::Organizations::OrganizationalUnit", "ou-ab12-abcd1234", "us-east-1");
+ }
+
+ @Test
+ void deleteRethrowsARealFailure() {
+ when(organizations.findManagementAccountForResource("ou-ab12-abcd1234"))
+ .thenReturn(Optional.of(ACCOUNT));
+ org.mockito.Mockito.doThrow(new AwsException("OrganizationalUnitNotEmptyException", "busy", 400))
+ .when(organizations).deleteOrganizationalUnit(ACCOUNT, "ou-ab12-abcd1234");
+
+ AwsException error = assertThrows(AwsException.class, () -> provisioner.delete(
+ "AWS::Organizations::OrganizationalUnit", "ou-ab12-abcd1234", "us-east-1"));
+ assertEquals("OrganizationalUnitNotEmptyException", error.getErrorCode());
+ }
+
+ @Test
+ void everyRegistrySchemaTypeIsServed() {
+ assertEquals(Set.of(
+ "AWS::Organizations::Organization",
+ "AWS::Organizations::OrganizationalUnit",
+ "AWS::Organizations::Account",
+ "AWS::Organizations::Policy",
+ "AWS::Organizations::ResourcePolicy"),
+ provisioner.resourceTypes());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java
index 0dc38ea7d1..5d531c6382 100644
--- a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java
@@ -127,6 +127,35 @@ class OrganizationsServiceTest {
assertTrue(effective.policyContent().contains("platform"), effective.policyContent());
}
+ @Test
+ void organizationPathsRunFromTheOrganizationDownToTheResourceItself() {
+ Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
+ String rootId = organization.getRoot().getId();
+ OrganizationalUnit parent =
+ service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, rootId, "Parent", null);
+ OrganizationalUnit child =
+ service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, parent.getId(), "Child", null);
+ String accountId =
+ service.createAccount(MANAGEMENT_ACCOUNT, "[email protected]", "Dev", null, false).getAccountId();
+ service.moveAccount(MANAGEMENT_ACCOUNT, accountId, rootId, child.getId());
+
+ String root = organization.getId() + "/" + rootId + "/";
+ assertEquals(root, service.organizationPath(MANAGEMENT_ACCOUNT, rootId));
+ assertEquals(root + parent.getId() + "/",
+ service.organizationPath(MANAGEMENT_ACCOUNT, parent.getId()));
+ assertEquals(root + parent.getId() + "/" + child.getId() + "/",
+ service.organizationPath(MANAGEMENT_ACCOUNT, child.getId()));
+
+ // An account's path names every OU above it and ends with the account, the way ListAccounts
+ // reports Paths — and it tracks the move rather than the parent the account was created in.
+ String accountPath = root + parent.getId() + "/" + child.getId() + "/" + accountId + "/";
+ assertEquals(accountPath, service.organizationPath(MANAGEMENT_ACCOUNT, accountId));
+ // The Path shape AWS publishes for the Organizations API and the registry schemas.
+ assertTrue(accountPath.matches(
+ "^(o-[a-z0-9]{10,32}/r-[0-9a-z]{4,32}(/ou-[0-9a-z]{4,32}-[a-z0-9]{8,32})*(/\\d{12})*)/"),
+ accountPath);
+ }
+
@Test
void effectivePolicyRejectsAccessControlPolicyTypes() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
@@ -196,6 +225,26 @@ class OrganizationsServiceTest {
}
}
+ @Test
+ void putResourcePolicyReplacesTagsRatherThanMergingThem() {
+ service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
+ String content = "{\"Version\":\"2012-10-17\"}";
+
+ service.putResourcePolicy(MANAGEMENT_ACCOUNT, content, Map.of("env", "test", "owner", "platform"));
+ assertEquals(Map.of("env", "test", "owner", "platform"),
+ service.describeResourcePolicy(MANAGEMENT_ACCOUNT).tags());
+
+ // The resource policy is not addressable by TagResource/UntagResource, so Put is the only
+ // way a dropped key can be removed — CloudFormation relies on this to converge on update.
+ service.putResourcePolicy(MANAGEMENT_ACCOUNT, content, Map.of("env", "prod"));
+ assertEquals(Map.of("env", "prod"), service.describeResourcePolicy(MANAGEMENT_ACCOUNT).tags());
+
+ // Omitting Tags entirely is "don't touch", matching how the provisioner treats an absent
+ // Tags property on every other Organizations type.
+ service.putResourcePolicy(MANAGEMENT_ACCOUNT, content, null);
+ assertEquals(Map.of("env", "prod"), service.describeResourcePolicy(MANAGEMENT_ACCOUNT).tags());
+ }
+
@Test
void anAccountOutsideAnyOrganizationGetsNotInUse() {
AwsException error = assertThrows(AwsException.class,