mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(organizations): add CloudFormation resource types (#2495)
* feat(organizations): add CloudFormation resource types Adds OrganizationsCfnProvisioner covering AWS::Organizations::Organization, OrganizationalUnit, Account, Policy and ResourcePolicy. Attribute names are taken from the registry schemas' readOnlyProperties so Fn::GetAtt resolves the keys AWS publishes. CloudFormation's delete path hands over a physical id and a region but no caller identity, and every Organizations mutation is management-account scoped. Rather than injecting a second collaborator into the provisioner, OrganizationsService gains findManagementAccountForResource, which recovers the owning account from the resource id — so the provisioner keeps to the one-injected-service convention the other provisioners follow. provision serves create and update: an OU is renamed in place rather than recreated (ParentId is create-only in the schema), a Policy's TargetIds are reconciled in both directions, and an Account is moved to its ParentIds entry after creation. The integration test asserts through stack Outputs backed by Fn::GetAtt: an unmapped attribute does not fail provisioning, it silently resolves to the literal "LogicalId.Attr", so asserting CREATE_COMPLETE would pass with every attribute unwired. * fix(organizations): converge CFN provisioning on partial failure and tag drops Set the physical id as soon as the create call succeeds in provisionAccount and provisionPolicy, before moveAccount and reconcileTargets respectively. Both can throw once the resource already exists — a ParentIds entry pointing at a missing OU raises DestinationParentNotFoundException, and attachPolicy can fail on a bad target — and without an id CloudFormation's rollback has nothing to call delete() with, leaving the account or policy a real member of the organization but unmanaged by the stack. Make putResourcePolicy replace its tag map rather than merge into it, so a key dropped from a template is removed on update instead of lingering. A resource policy is not a TagResource target, so resolveTagOwner rejects rp- ids and the provisioner cannot reach it through replaceTags the way the other types do; Put is the only call that can converge those tags. Supplying Tags states the full set, while omitting them leaves the existing ones untouched, matching how an absent Tags property behaves for every other Organizations type. * fix(organizations): mark created accounts and policies as rollback-owned CloudFormationService.rollbackCreatedResources deletes a CREATE_FAILED resource only when it carries both a physical id and the CfnRollback.ROLLBACK_OWNED_ATTR marker. The provisioner set the id but not the marker, so rollback walked straight past an account whose MoveAccount failed after CreateAccount had already made it a member of the organization. The account survived, the organization could not be deleted while it still contained one, and the stack reported ROLLBACK_FAILED instead of unwinding. Set the marker as soon as the create call returns, the way IamRoleCfnProvisioner does, so the create and the ownership record cannot drift apart. OrganizationsCfnRollbackIntegrationTest drives a real stack whose ParentIds names an OU that does not exist and asserts the account id reaches the stack events, that rollback emits DELETE_COMPLETE for it, and that neither the account nor the organization is left behind. * feat(organizations): map OU Path and Account State/Paths The published registry schemas declare three readOnly properties the provisioner did not map: OrganizationalUnit Path, and Account State and Paths. An unmapped key does not fail provisioning — CloudFormationTemplateEngine resolves it to the literal string "LogicalId.Attr" — so a template asking for Fn::GetAtt Dev.State silently got back "Dev.State". Path and Paths are the organization path, o-<org>/r-<root>[/ou-<ou>]*[/<id>]/, which needs a walk from the resource up to the root. OrganizationsService owns that hierarchy and already computes the chain for effective-policy merging, so it exposes it as organizationPath rather than the provisioner rebuilding it. The account path is read after the move: accounts are always created under the root, so reading it earlier would publish a path the account no longer lives at. State is the parameter AWS is retiring Status in favour of on 2026-09-09. Floci only ever puts an account in ACTIVE or PENDING_CLOSURE, both of which are also AccountState values, so the two agree; PENDING_ACTIVATION and CLOSED are phases the emulator does not model. Paths is list-typed in the schema, but an account has exactly one parent and so exactly one path, and the engine's Fn::Select splits a comma-delimited scalar back into a list, so the string-valued attribute map carries it without loss. Adding the Path lookup to provisionOrganizationalUnit opens the same window that stranded accounts before: a call that can throw once the OU is already a real member of the organization. Mark the OU stack-owned as soon as the create returns, matching the account and policy paths, so rollback can still delete it. * fix(organizations): Ref on Organization returns the management account id AWS documents Organization as the one Organizations type where bare Ref returns the management account id rather than the resource's own id; Fn::GetAtt Org.Id already returned the organization id correctly. Adds an OrgRef stack output/assertion covering the case, since the existing integration test only ever exercised Fn::GetAtt on Org.
This commit is contained in:
1 parent
45240998ac
commit
054508df87
7 files changed
+1487
No files matched your search
+340
@@ -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": "cfn-dev@example.com",
|
||||
"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);
|
||||
}
|
||||
}
|
||||
+132
@@ -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": "stranded@example.com",
|
||||
"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"));
|
||||
}
|
||||
}
|
||||
+548
@@ -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("master@example.com");
|
||||
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("master@example.com", 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("dev@example.com");
|
||||
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("dev@example.com"), 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", "dev@example.com");
|
||||
|
||||
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", "dev@example.com");
|
||||
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", "dev@example.com");
|
||||
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", "dev@example.com");
|
||||
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", "dev@example.com");
|
||||
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", "dev@example.com");
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
+49
@@ -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, "dev@example.com", "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,
|
||||
|
||||
Reference in new issue
Block a user