feat(organizations): add AWS Organizations service (#2489)

* feat(organizations): add AWS Organizations service

Implements the AWS Organizations control plane over JSON 1.1
(AWSOrganizationsV20161128.*): organizations and roots, the OU tree,
member accounts, all policy types, tags, trusted service access,
delegated administrators, the organization resource policy, and the
invitation/handshake flow.

Organizations is global and cross-account, so records are addressed
through the explicit *ForAccount methods on AccountAwareStorageBackend
rather than the request-context-derived get/put: a member account
calling DescribeOrganization has a different request account than the
one owning the data. The caller account is used for authorization
instead — mutations are management-account only, members get read
access to their own organization, and outsiders get
AWSOrganizationsNotInUseException.

Because Floci already resolves a 12-digit access key id to an account,
an account created by CreateAccount is immediately usable as a caller
identity against every other service.

* fix(organizations): emit only AWS's handshake resource types

Review feedback on #2489.

The ORGANIZATION resource on an INVITE handshake was carrying a
MASTER_ACCOUNT_ID child. HandshakeResourceType is a closed enum and that
value is not in it, so the AWS SDK deserializes it as
UNKNOWN_TO_SDK_VERSION rather than failing loudly. AWS's documented
children are MASTER_EMAIL and MASTER_NAME; emit those instead. The
javadoc already described the correct pair, so it was the code that
deviated. Adds an integration test pinning the resource types against
the enum so this cannot regress.

Also from review:

- POLICY_TYPES and EFFECTIVE_POLICY_TYPES are rendered into validation
  messages, but Set.of's iteration order is unspecified and salted per
  JVM run, so the same rejection could read differently between runs.
  Declare them as ordered Lists with companion Sets for O(1) membership.
- listHandshakesForAccount called organizationById — itself a full scan —
  once per handshake. Build the orgId to management-account map once.
This commit is contained in:
William St John Bacon authored and GitHub committed 2026-08-23 17:18:42 -04:00
1 parent 56e74d64c6
commit 87e804492a
30 files changed
+5343 -2

No files matched your search

@@ -0,0 +1,388 @@
package io.github.hectorvent.floci.services.organizations;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
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.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
/**
* The invitation/handshake flow and member-account visibility — the behaviour that needs more
* than one AWS account to exercise at all.
*
* <p>Floci resolves a 12-digit access key id straight to an account id, so each request here
* carries a SigV4-shaped {@code Authorization} header whose credential names the calling account.
* The management account is deliberately not the default {@code 000000000000} used by
* {@link OrganizationsIntegrationTest}, so the two classes never contend for the same
* organization inside one shared Quarkus instance.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class OrganizationsCrossAccountIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "AWSOrganizationsV20161128.";
private static final String MANAGEMENT_ACCOUNT = "222222222222";
private static final String INVITED_ACCOUNT = "333333333333";
private static final String OTHER_ACCOUNT = "444444444444";
private String organizationId;
private String inviteHandshakeId;
private String declinedHandshakeId;
private String canceledHandshakeId;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private RequestSpecification organizations(String accountId, String action, String body) {
return given()
.header("Authorization", authorization(accountId))
.header("X-Amz-Target", TARGET_PREFIX + action)
.contentType(CONTENT_TYPE)
.body(body);
}
private static String authorization(String accountId) {
return "AWS4-HMAC-SHA256 Credential=" + accountId
+ "/20260822/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc";
}
@Test
@Order(1)
void createOrganizationAsManagementAccount() {
organizationId = organizations(MANAGEMENT_ACCOUNT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Organization.MasterAccountId", equalTo(MANAGEMENT_ACCOUNT))
.extract().jsonPath().getString("Organization.Id");
}
@Test
@Order(2)
void anAccountOutsideTheOrganizationSeesNothing() {
organizations(INVITED_ACCOUNT, "DescribeOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("AWSOrganizationsNotInUseException"));
}
@Test
@Order(3)
void inviteAccountToOrganization() {
inviteHandshakeId = organizations(MANAGEMENT_ACCOUNT, "InviteAccountToOrganization",
"{\"Target\":{\"Id\":\"" + INVITED_ACCOUNT + "\",\"Type\":\"ACCOUNT\"},\"Notes\":\"join us\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshake.Id", notNullValue())
.body("Handshake.State", equalTo("REQUESTED"))
.body("Handshake.Action", equalTo("INVITE"))
.body("Handshake.Arn",
org.hamcrest.Matchers.startsWith("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":handshake/"))
.body("Handshake.RequestedTimestamp", notNullValue())
.body("Handshake.ExpirationTimestamp", notNullValue())
.body("Handshake.Parties.Id", hasItem(INVITED_ACCOUNT))
.body("Handshake.Resources.Type", hasItem("ORGANIZATION"))
.extract().jsonPath().getString("Handshake.Id");
}
@Test
@Order(4)
void handshakeResourcesUseOnlyTypesFromTheAwsEnum() {
// HandshakeResourceType is a closed enum; a value outside it deserializes as
// UNKNOWN_TO_SDK_VERSION in the SDK rather than failing loudly, so pin the exact types.
organizations(MANAGEMENT_ACCOUNT, "DescribeHandshake", "{\"HandshakeId\":\"" + inviteHandshakeId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshake.Resources.Type", org.hamcrest.Matchers.everyItem(
org.hamcrest.Matchers.in(List.of("ACCOUNT", "ORGANIZATION", "ORGANIZATION_FEATURE_SET",
"EMAIL", "MASTER_EMAIL", "MASTER_NAME", "NOTES", "PARENT_HANDSHAKE"))))
.body("Handshake.Resources.find { it.Type == 'ORGANIZATION' }.Resources.Type",
org.hamcrest.Matchers.containsInAnyOrder("MASTER_EMAIL", "MASTER_NAME"));
}
@Test
@Order(5)
void duplicateInvitationIsRejectedWhileTheFirstIsOpen() {
organizations(MANAGEMENT_ACCOUNT, "InviteAccountToOrganization",
"{\"Target\":{\"Id\":\"" + INVITED_ACCOUNT + "\",\"Type\":\"ACCOUNT\"}}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("DuplicateHandshakeException"));
}
@Test
@Order(6)
void anotherAccountCannotAcceptSomeoneElsesInvitation() {
organizations(OTHER_ACCOUNT, "AcceptHandshake", "{\"HandshakeId\":\"" + inviteHandshakeId + "\"}")
.when()
.post("/")
.then()
.statusCode(403)
.body("__type", equalTo("AccessDeniedException"));
}
@Test
@Order(7)
void theInviteeCanDescribeTheHandshake() {
organizations(INVITED_ACCOUNT, "DescribeHandshake", "{\"HandshakeId\":\"" + inviteHandshakeId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshake.Id", equalTo(inviteHandshakeId))
.body("Handshake.State", equalTo("REQUESTED"));
}
@Test
@Order(8)
void acceptHandshakeJoinsTheOrganization() {
organizations(INVITED_ACCOUNT, "AcceptHandshake", "{\"HandshakeId\":\"" + inviteHandshakeId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshake.State", equalTo("ACCEPTED"));
organizations(MANAGEMENT_ACCOUNT, "ListAccounts", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Accounts.Id", hasItem(INVITED_ACCOUNT))
.body("Accounts.find { it.Id == '" + INVITED_ACCOUNT + "' }.JoinedMethod", equalTo("INVITED"))
.body("Accounts.find { it.Id == '" + INVITED_ACCOUNT + "' }.Status", equalTo("ACTIVE"));
}
@Test
@Order(9)
void aMemberAccountCanReadTheOrganization() {
organizations(INVITED_ACCOUNT, "DescribeOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Organization.Id", equalTo(organizationId))
.body("Organization.MasterAccountId", equalTo(MANAGEMENT_ACCOUNT));
organizations(INVITED_ACCOUNT, "ListRoots", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Roots", hasSize(1));
organizations(INVITED_ACCOUNT, "ListParents", "{\"ChildId\":\"" + INVITED_ACCOUNT + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parents[0].Type", equalTo("ROOT"));
}
@Test
@Order(10)
void aMemberAccountCannotMutateTheOrganization() {
organizations(INVITED_ACCOUNT, "CreateOrganizationalUnit",
"{\"ParentId\":\"r-0000\",\"Name\":\"Nope\"}")
.when()
.post("/")
.then()
.statusCode(403)
.body("__type", equalTo("AccessDeniedException"));
organizations(INVITED_ACCOUNT, "CreateAccount",
"{\"Email\":\"nope@example.com\",\"AccountName\":\"Nope\"}")
.when()
.post("/")
.then()
.statusCode(403)
.body("__type", equalTo("AccessDeniedException"));
}
@Test
@Order(11)
void invitingAnExistingMemberFails() {
organizations(MANAGEMENT_ACCOUNT, "InviteAccountToOrganization",
"{\"Target\":{\"Id\":\"" + INVITED_ACCOUNT + "\",\"Type\":\"ACCOUNT\"}}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("AccountAlreadyRegisteredException"));
}
@Test
@Order(12)
void declineHandshake() {
declinedHandshakeId = organizations(MANAGEMENT_ACCOUNT, "InviteAccountToOrganization",
"{\"Target\":{\"Id\":\"" + OTHER_ACCOUNT + "\",\"Type\":\"ACCOUNT\"}}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath().getString("Handshake.Id");
organizations(OTHER_ACCOUNT, "DeclineHandshake", "{\"HandshakeId\":\"" + declinedHandshakeId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshake.State", equalTo("DECLINED"));
organizations(MANAGEMENT_ACCOUNT, "ListAccounts", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Accounts.Id", not(hasItem(OTHER_ACCOUNT)));
}
@Test
@Order(13)
void cancelHandshake() {
canceledHandshakeId = organizations(MANAGEMENT_ACCOUNT, "InviteAccountToOrganization",
"{\"Target\":{\"Id\":\"" + OTHER_ACCOUNT + "\",\"Type\":\"ACCOUNT\"}}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath().getString("Handshake.Id");
organizations(OTHER_ACCOUNT, "CancelHandshake", "{\"HandshakeId\":\"" + canceledHandshakeId + "\"}")
.when()
.post("/")
.then()
.statusCode(403)
.body("__type", equalTo("AccessDeniedException"));
organizations(MANAGEMENT_ACCOUNT, "CancelHandshake", "{\"HandshakeId\":\"" + canceledHandshakeId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshake.State", equalTo("CANCELED"));
}
@Test
@Order(14)
void actingOnAClosedHandshakeFails() {
organizations(OTHER_ACCOUNT, "AcceptHandshake", "{\"HandshakeId\":\"" + canceledHandshakeId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidHandshakeTransitionException"));
}
@Test
@Order(15)
void listHandshakes() {
organizations(MANAGEMENT_ACCOUNT, "ListHandshakesForOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshakes.Id",
org.hamcrest.Matchers.hasItems(inviteHandshakeId, declinedHandshakeId, canceledHandshakeId));
organizations(MANAGEMENT_ACCOUNT, "ListHandshakesForOrganization",
"{\"Filter\":{\"States\":[\"DECLINED\"]}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshakes", hasSize(1))
.body("Handshakes[0].Id", equalTo(declinedHandshakeId));
organizations(INVITED_ACCOUNT, "ListHandshakesForAccount", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshakes", hasSize(1))
.body("Handshakes[0].Id", equalTo(inviteHandshakeId));
}
@Test
@Order(16)
void listHandshakesForOrganizationIsManagementAccountOnly() {
organizations(INVITED_ACCOUNT, "ListHandshakesForOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(403)
.body("__type", equalTo("AccessDeniedException"));
}
@Test
@Order(17)
void theManagementAccountCannotLeave() {
organizations(MANAGEMENT_ACCOUNT, "LeaveOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("MasterCannotLeaveOrganizationException"));
}
@Test
@Order(18)
void aMemberAccountCanLeave() {
organizations(INVITED_ACCOUNT, "LeaveOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200);
organizations(INVITED_ACCOUNT, "DescribeOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("AWSOrganizationsNotInUseException"));
organizations(MANAGEMENT_ACCOUNT, "ListAccounts", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Accounts.Id", not(hasItem(INVITED_ACCOUNT)));
}
@Test
@Order(19)
void tearDownOrganization() {
organizations(MANAGEMENT_ACCOUNT, "DeleteOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -0,0 +1,131 @@
package io.github.hectorvent.floci.services.organizations;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
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 static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
/**
* The CONSOLIDATED_BILLING → ALL upgrade path, which gates whether policy types can be enabled
* at all. Uses its own management account so it never contends with the other Organizations
* integration tests inside the shared Quarkus instance.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class OrganizationsFeatureSetIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "AWSOrganizationsV20161128.";
private static final String MANAGEMENT_ACCOUNT = "555555555555";
private String rootId;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private RequestSpecification organizations(String action, String body) {
return given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + MANAGEMENT_ACCOUNT
+ "/20260822/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc")
.header("X-Amz-Target", TARGET_PREFIX + action)
.contentType(CONTENT_TYPE)
.body(body);
}
@Test
@Order(1)
void consolidatedBillingOrganizationHasNoAvailablePolicyTypes() {
organizations("CreateOrganization", "{\"FeatureSet\":\"CONSOLIDATED_BILLING\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Organization.FeatureSet", equalTo("CONSOLIDATED_BILLING"))
.body("Organization.AvailablePolicyTypes", empty());
rootId = organizations("ListRoots", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Roots[0].PolicyTypes", empty())
.extract().jsonPath().getString("Roots[0].Id");
}
@Test
@Order(2)
void policyTypesCannotBeEnabledWithoutAllFeatures() {
organizations("EnablePolicyType",
"{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"SERVICE_CONTROL_POLICY\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("PolicyTypeNotAvailableForOrganizationException"));
}
@Test
@Order(3)
void enableAllFeaturesCompletesImmediatelyWithNoMemberAccounts() {
organizations("EnableAllFeatures", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Handshake.Action", equalTo("ENABLE_ALL_FEATURES"))
.body("Handshake.State", equalTo("ACCEPTED"));
organizations("DescribeOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Organization.FeatureSet", equalTo("ALL"))
.body("Organization.AvailablePolicyTypes.Type", hasItem("SERVICE_CONTROL_POLICY"));
}
@Test
@Order(4)
void enableAllFeaturesIsRejectedOnceAlreadyEnabled() {
organizations("EnableAllFeatures", "{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("HandshakeConstraintViolationException"));
}
@Test
@Order(5)
void policyTypesCanBeEnabledAfterUpgrading() {
organizations("EnablePolicyType", "{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"BACKUP_POLICY\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Root.PolicyTypes.Type", hasItem("BACKUP_POLICY"));
}
@Test
@Order(6)
void tearDownOrganization() {
organizations("DeleteOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -0,0 +1,923 @@
package io.github.hectorvent.floci.services.organizations;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
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 static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
/**
* Single-account Organizations flow: the organization itself, the OU tree, accounts, policies,
* tags, trusted access, delegation, the resource policy and effective policies.
*
* <p>Runs entirely as the default account, which becomes the management account. The final test
* tears the organization down so the shared Quarkus instance is left with no organization for
* {@code 000000000000} — {@link OrganizationsCrossAccountIntegrationTest} deliberately uses a
* different management account so the two classes never contend for the same one.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class OrganizationsIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "AWSOrganizationsV20161128.";
private static final String TAG_POLICY_CONTENT =
"{\"tags\":{\"CostCenter\":{\"tag_key\":{\"@@assign\":\"CostCenter\"}}}}";
private static final String SCP_CONTENT =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"ec2:*\",\"Resource\":\"*\"}]}";
private String organizationId;
private String rootId;
private String ouId;
private String nestedOuId;
private String memberAccountId;
private String createAccountRequestId;
private String scpId;
private String tagPolicyId;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private RequestSpecification organizations(String action, String body) {
return given()
.header("X-Amz-Target", TARGET_PREFIX + action)
.contentType(CONTENT_TYPE)
.body(body);
}
// ──────────────────────────── Organization ────────────────────────────
@Test
@Order(1)
void createOrganization() {
organizationId = organizations("CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Organization.Id", matchesPattern("o-[a-z0-9]{10}"))
.body("Organization.Arn", startsWith("arn:aws:organizations::000000000000:organization/o-"))
.body("Organization.FeatureSet", equalTo("ALL"))
.body("Organization.MasterAccountId", equalTo("000000000000"))
.body("Organization.MasterAccountArn", startsWith("arn:aws:organizations::000000000000:account/o-"))
.body("Organization.AvailablePolicyTypes.Type", hasItem("SERVICE_CONTROL_POLICY"))
.extract().jsonPath().getString("Organization.Id");
}
@Test
@Order(2)
void createOrganizationTwiceFails() {
organizations("CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("AlreadyInOrganizationException"));
}
@Test
@Order(3)
void describeOrganization() {
organizations("DescribeOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Organization.Id", equalTo(organizationId))
.body("Organization.MasterAccountId", equalTo("000000000000"));
}
@Test
@Order(4)
void listRootsReturnsRootWithServiceControlPolicyEnabled() {
rootId = organizations("ListRoots", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Roots", hasSize(1))
.body("Roots[0].Id", matchesPattern("r-[a-z0-9]{4}"))
.body("Roots[0].Name", equalTo("Root"))
.body("Roots[0].Arn", startsWith("arn:aws:organizations::000000000000:root/" + organizationId))
.body("Roots[0].PolicyTypes.Type", hasItem("SERVICE_CONTROL_POLICY"))
.body("Roots[0].PolicyTypes.Status", hasItem("ENABLED"))
.extract().jsonPath().getString("Roots[0].Id");
}
@Test
@Order(5)
void fullAwsAccessIsAttachedToTheRoot() {
organizations("ListPoliciesForTarget",
"{\"TargetId\":\"" + rootId + "\",\"Filter\":\"SERVICE_CONTROL_POLICY\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Policies.Id", hasItem("p-FullAWSAccess"))
.body("Policies.find { it.Id == 'p-FullAWSAccess' }.AwsManaged", equalTo(true))
.body("Policies.find { it.Id == 'p-FullAWSAccess' }.Name", equalTo("FullAWSAccess"));
}
// ──────────────────────────── Organizational units ────────────────────────────
@Test
@Order(10)
void createOrganizationalUnit() {
ouId = organizations("CreateOrganizationalUnit",
"{\"ParentId\":\"" + rootId + "\",\"Name\":\"Workloads\","
+ "\"Tags\":[{\"Key\":\"env\",\"Value\":\"test\"}]}")
.when()
.post("/")
.then()
.statusCode(200)
.body("OrganizationalUnit.Id", matchesPattern("ou-[a-z0-9]{4}-[a-z0-9]{8}"))
.body("OrganizationalUnit.Name", equalTo("Workloads"))
.body("OrganizationalUnit.Arn", startsWith("arn:aws:organizations::000000000000:ou/" + organizationId))
.extract().jsonPath().getString("OrganizationalUnit.Id");
}
@Test
@Order(11)
void createDuplicateOrganizationalUnitNameUnderSameParentFails() {
organizations("CreateOrganizationalUnit",
"{\"ParentId\":\"" + rootId + "\",\"Name\":\"Workloads\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("DuplicateOrganizationalUnitException"));
}
@Test
@Order(12)
void createNestedOrganizationalUnit() {
nestedOuId = organizations("CreateOrganizationalUnit",
"{\"ParentId\":\"" + ouId + "\",\"Name\":\"Production\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("OrganizationalUnit.Name", equalTo("Production"))
.extract().jsonPath().getString("OrganizationalUnit.Id");
}
@Test
@Order(13)
void listOrganizationalUnitsForParent() {
organizations("ListOrganizationalUnitsForParent", "{\"ParentId\":\"" + rootId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("OrganizationalUnits", hasSize(1))
.body("OrganizationalUnits[0].Id", equalTo(ouId));
}
@Test
@Order(14)
void listChildrenReturnsNestedOu() {
organizations("ListChildren",
"{\"ParentId\":\"" + ouId + "\",\"ChildType\":\"ORGANIZATIONAL_UNIT\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Children", hasSize(1))
.body("Children[0].Id", equalTo(nestedOuId))
.body("Children[0].Type", equalTo("ORGANIZATIONAL_UNIT"));
}
@Test
@Order(15)
void listParentsWalksUpOneLevel() {
organizations("ListParents", "{\"ChildId\":\"" + nestedOuId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parents", hasSize(1))
.body("Parents[0].Id", equalTo(ouId))
.body("Parents[0].Type", equalTo("ORGANIZATIONAL_UNIT"));
}
@Test
@Order(16)
void updateOrganizationalUnitRenames() {
organizations("UpdateOrganizationalUnit",
"{\"OrganizationalUnitId\":\"" + nestedOuId + "\",\"Name\":\"Prod\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("OrganizationalUnit.Name", equalTo("Prod"));
organizations("DescribeOrganizationalUnit", "{\"OrganizationalUnitId\":\"" + nestedOuId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("OrganizationalUnit.Name", equalTo("Prod"));
}
@Test
@Order(17)
void describeUnknownOrganizationalUnitFails() {
organizations("DescribeOrganizationalUnit", "{\"OrganizationalUnitId\":\"ou-abcd-99999999\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("OrganizationalUnitNotFoundException"));
}
// ──────────────────────────── Accounts ────────────────────────────
@Test
@Order(20)
void createAccount() {
var response = organizations("CreateAccount",
"{\"Email\":\"dev@example.com\",\"AccountName\":\"Dev\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateAccountStatus.Id", startsWith("car-"))
.body("CreateAccountStatus.State", equalTo("SUCCEEDED"))
.body("CreateAccountStatus.AccountName", equalTo("Dev"))
.body("CreateAccountStatus.AccountId", matchesPattern("\\d{12}"))
.body("CreateAccountStatus.RequestedTimestamp", notNullValue())
.body("CreateAccountStatus.CompletedTimestamp", notNullValue())
.extract().jsonPath();
memberAccountId = response.getString("CreateAccountStatus.AccountId");
createAccountRequestId = response.getString("CreateAccountStatus.Id");
}
@Test
@Order(21)
void createAccountWithDuplicateEmailReportsFailure() {
organizations("CreateAccount", "{\"Email\":\"dev@example.com\",\"AccountName\":\"Dev2\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateAccountStatus.State", equalTo("FAILED"))
.body("CreateAccountStatus.FailureReason", equalTo("EMAIL_ALREADY_EXISTS"));
}
@Test
@Order(22)
void createAccountWithInvalidEmailFails() {
organizations("CreateAccount", "{\"Email\":\"not-an-email\",\"AccountName\":\"Bad\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidInputException"));
}
@Test
@Order(23)
void describeCreateAccountStatus() {
organizations("DescribeCreateAccountStatus",
"{\"CreateAccountRequestId\":\"" + createAccountRequestId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateAccountStatus.AccountId", equalTo(memberAccountId));
}
@Test
@Order(24)
void listCreateAccountStatusFiltersByState() {
organizations("ListCreateAccountStatus", "{\"States\":[\"SUCCEEDED\"]}")
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateAccountStatuses.AccountId", hasItem(memberAccountId))
.body("CreateAccountStatuses.State", not(hasItem("FAILED")));
}
@Test
@Order(25)
void describeAccountAndListAccounts() {
organizations("DescribeAccount", "{\"AccountId\":\"" + memberAccountId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Account.Id", equalTo(memberAccountId))
.body("Account.Email", equalTo("dev@example.com"))
.body("Account.Name", equalTo("Dev"))
.body("Account.Status", equalTo("ACTIVE"))
.body("Account.JoinedMethod", equalTo("CREATED"))
.body("Account.Arn", startsWith("arn:aws:organizations::000000000000:account/" + organizationId));
organizations("ListAccounts", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Accounts.Id", hasItems("000000000000", memberAccountId));
}
@Test
@Order(26)
void moveAccountIntoOrganizationalUnit() {
organizations("MoveAccount",
"{\"AccountId\":\"" + memberAccountId + "\",\"SourceParentId\":\"" + rootId
+ "\",\"DestinationParentId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("ListAccountsForParent", "{\"ParentId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Accounts", hasSize(1))
.body("Accounts[0].Id", equalTo(memberAccountId));
}
@Test
@Order(27)
void moveAccountFromWrongSourceParentFails() {
organizations("MoveAccount",
"{\"AccountId\":\"" + memberAccountId + "\",\"SourceParentId\":\"" + rootId
+ "\",\"DestinationParentId\":\"" + nestedOuId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("SourceParentNotMatchedException"));
}
@Test
@Order(28)
void deleteNonEmptyOrganizationalUnitFails() {
organizations("DeleteOrganizationalUnit", "{\"OrganizationalUnitId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("OrganizationalUnitNotEmptyException"));
}
@Test
@Order(29)
void removeManagementAccountFails() {
organizations("RemoveAccountFromOrganization", "{\"AccountId\":\"000000000000\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("MasterCannotLeaveOrganizationException"));
}
// ──────────────────────────── Policies ────────────────────────────
@Test
@Order(30)
void createServiceControlPolicy() {
scpId = organizations("CreatePolicy",
"{\"Name\":\"DenyEc2\",\"Description\":\"Deny EC2\",\"Type\":\"SERVICE_CONTROL_POLICY\","
+ "\"Content\":" + quote(SCP_CONTENT) + "}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Policy.PolicySummary.Id", matchesPattern("p-[a-z0-9]{8}"))
.body("Policy.PolicySummary.Name", equalTo("DenyEc2"))
.body("Policy.PolicySummary.Type", equalTo("SERVICE_CONTROL_POLICY"))
.body("Policy.PolicySummary.AwsManaged", equalTo(false))
.body("Policy.PolicySummary.Arn",
startsWith("arn:aws:organizations::000000000000:policy/" + organizationId
+ "/service_control_policy/"))
.body("Policy.Content", equalTo(SCP_CONTENT))
.extract().jsonPath().getString("Policy.PolicySummary.Id");
}
@Test
@Order(31)
void createDuplicatePolicyNameFails() {
organizations("CreatePolicy",
"{\"Name\":\"DenyEc2\",\"Type\":\"SERVICE_CONTROL_POLICY\",\"Content\":" + quote(SCP_CONTENT) + "}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("DuplicatePolicyException"));
}
@Test
@Order(32)
void attachAndListPolicy() {
organizations("AttachPolicy", "{\"PolicyId\":\"" + scpId + "\",\"TargetId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("ListPoliciesForTarget",
"{\"TargetId\":\"" + ouId + "\",\"Filter\":\"SERVICE_CONTROL_POLICY\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Policies.Id", hasItems("p-FullAWSAccess", scpId));
organizations("ListTargetsForPolicy", "{\"PolicyId\":\"" + scpId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Targets", hasSize(1))
.body("Targets[0].TargetId", equalTo(ouId))
.body("Targets[0].Type", equalTo("ORGANIZATIONAL_UNIT"))
.body("Targets[0].Name", equalTo("Workloads"));
}
@Test
@Order(33)
void attachSamePolicyTwiceFails() {
organizations("AttachPolicy", "{\"PolicyId\":\"" + scpId + "\",\"TargetId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("DuplicatePolicyAttachmentException"));
}
@Test
@Order(34)
void deleteAttachedPolicyFails() {
organizations("DeletePolicy", "{\"PolicyId\":\"" + scpId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("PolicyInUseException"));
}
@Test
@Order(35)
void updatePolicy() {
organizations("UpdatePolicy",
"{\"PolicyId\":\"" + scpId + "\",\"Description\":\"Deny EC2 everywhere\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Policy.PolicySummary.Description", equalTo("Deny EC2 everywhere"));
}
@Test
@Order(36)
void awsManagedPolicyCannotBeModified() {
organizations("UpdatePolicy", "{\"PolicyId\":\"p-FullAWSAccess\",\"Description\":\"nope\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ConstraintViolationException"));
}
@Test
@Order(37)
void detachingTheLastServiceControlPolicyIsRejected() {
organizations("DetachPolicy", "{\"PolicyId\":\"" + scpId + "\",\"TargetId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DetachPolicy", "{\"PolicyId\":\"p-FullAWSAccess\",\"TargetId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ConstraintViolationException"));
}
@Test
@Order(38)
void detachUnattachedPolicyFails() {
organizations("DetachPolicy", "{\"PolicyId\":\"" + scpId + "\",\"TargetId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("PolicyNotAttachedException"));
}
// ──────────────────────────── Policy types and effective policies ────────────────────────────
@Test
@Order(40)
void tagPolicyRequiresItsPolicyTypeEnabled() {
organizations("CreatePolicy",
"{\"Name\":\"CostCenter\",\"Type\":\"TAG_POLICY\",\"Content\":" + quote(TAG_POLICY_CONTENT) + "}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("PolicyTypeNotEnabledException"));
}
@Test
@Order(41)
void enablePolicyType() {
organizations("EnablePolicyType", "{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"TAG_POLICY\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Root.PolicyTypes.Type", hasItems("SERVICE_CONTROL_POLICY", "TAG_POLICY"));
}
@Test
@Order(42)
void enablePolicyTypeTwiceFails() {
organizations("EnablePolicyType", "{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"TAG_POLICY\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("PolicyTypeAlreadyEnabledException"));
}
@Test
@Order(43)
void describeEffectivePolicyMergesTheInheritanceChain() {
tagPolicyId = organizations("CreatePolicy",
"{\"Name\":\"CostCenter\",\"Type\":\"TAG_POLICY\",\"Content\":" + quote(TAG_POLICY_CONTENT) + "}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath().getString("Policy.PolicySummary.Id");
organizations("AttachPolicy", "{\"PolicyId\":\"" + tagPolicyId + "\",\"TargetId\":\"" + rootId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
// The account sits under the OU, which sits under the root, so a policy attached only to
// the root must still reach it.
organizations("DescribeEffectivePolicy",
"{\"PolicyType\":\"TAG_POLICY\",\"TargetId\":\"" + memberAccountId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("EffectivePolicy.PolicyType", equalTo("TAG_POLICY"))
.body("EffectivePolicy.TargetId", equalTo(memberAccountId))
.body("EffectivePolicy.LastUpdatedTimestamp", notNullValue())
.body("EffectivePolicy.PolicyContent", equalTo(TAG_POLICY_CONTENT));
}
@Test
@Order(44)
void describeEffectivePolicyRejectsServiceControlPolicy() {
organizations("DescribeEffectivePolicy",
"{\"PolicyType\":\"SERVICE_CONTROL_POLICY\",\"TargetId\":\"" + memberAccountId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidInputException"));
}
@Test
@Order(45)
void describeEffectivePolicyWithNoMatchingPolicyFails() {
organizations("DescribeEffectivePolicy",
"{\"PolicyType\":\"BACKUP_POLICY\",\"TargetId\":\"" + memberAccountId + "\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("EffectivePolicyNotFoundException"));
}
@Test
@Order(46)
void disablePolicyType() {
organizations("DetachPolicy", "{\"PolicyId\":\"" + tagPolicyId + "\",\"TargetId\":\"" + rootId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DeletePolicy", "{\"PolicyId\":\"" + tagPolicyId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DisablePolicyType", "{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"TAG_POLICY\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Root.PolicyTypes.Type", not(hasItem("TAG_POLICY")));
}
// ──────────────────────────── Tags ────────────────────────────
@Test
@Order(50)
void tagAndUntagResource() {
organizations("ListTagsForResource", "{\"ResourceId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Tags", hasSize(1))
.body("Tags[0].Key", equalTo("env"))
.body("Tags[0].Value", equalTo("test"));
organizations("TagResource",
"{\"ResourceId\":\"" + memberAccountId + "\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"platform\"}]}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("ListTagsForResource", "{\"ResourceId\":\"" + memberAccountId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Tags[0].Key", equalTo("team"))
.body("Tags[0].Value", equalTo("platform"));
organizations("UntagResource",
"{\"ResourceId\":\"" + memberAccountId + "\",\"TagKeys\":[\"team\"]}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("ListTagsForResource", "{\"ResourceId\":\"" + memberAccountId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Tags", hasSize(0));
}
@Test
@Order(51)
void tagUnknownResourceFails() {
organizations("ListTagsForResource", "{\"ResourceId\":\"not-a-resource\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("TargetNotFoundException"));
}
// ──────────────────────────── Trusted access and delegation ────────────────────────────
@Test
@Order(60)
void enableAndListServiceAccess() {
organizations("EnableAWSServiceAccess", "{\"ServicePrincipal\":\"config.amazonaws.com\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("ListAWSServiceAccessForOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("EnabledServicePrincipals.ServicePrincipal", hasItem("config.amazonaws.com"))
.body("EnabledServicePrincipals[0].DateEnabled", notNullValue());
}
@Test
@Order(61)
void registerAndListDelegatedAdministrator() {
organizations("RegisterDelegatedAdministrator",
"{\"AccountId\":\"" + memberAccountId + "\",\"ServicePrincipal\":\"config.amazonaws.com\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("ListDelegatedAdministrators", "{\"ServicePrincipal\":\"config.amazonaws.com\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("DelegatedAdministrators", hasSize(1))
.body("DelegatedAdministrators[0].Id", equalTo(memberAccountId))
.body("DelegatedAdministrators[0].DelegationEnabledDate", notNullValue());
organizations("ListDelegatedServicesForAccount", "{\"AccountId\":\"" + memberAccountId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("DelegatedServices.ServicePrincipal", contains("config.amazonaws.com"));
}
@Test
@Order(62)
void registeringTheSameDelegatedAdministratorTwiceFails() {
organizations("RegisterDelegatedAdministrator",
"{\"AccountId\":\"" + memberAccountId + "\",\"ServicePrincipal\":\"config.amazonaws.com\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("AccountAlreadyRegisteredException"));
}
@Test
@Order(63)
void disablingServiceAccessWithADelegatedAdministratorFails() {
organizations("DisableAWSServiceAccess", "{\"ServicePrincipal\":\"config.amazonaws.com\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ConstraintViolationException"));
}
@Test
@Order(64)
void deregisterDelegatedAdministratorThenDisableServiceAccess() {
organizations("DeregisterDelegatedAdministrator",
"{\"AccountId\":\"" + memberAccountId + "\",\"ServicePrincipal\":\"config.amazonaws.com\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DeregisterDelegatedAdministrator",
"{\"AccountId\":\"" + memberAccountId + "\",\"ServicePrincipal\":\"config.amazonaws.com\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("AccountNotRegisteredException"));
organizations("DisableAWSServiceAccess", "{\"ServicePrincipal\":\"config.amazonaws.com\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("ListAWSServiceAccessForOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("EnabledServicePrincipals", hasSize(0));
}
// ──────────────────────────── Resource policy ────────────────────────────
@Test
@Order(70)
void resourcePolicyLifecycle() {
organizations("DescribeResourcePolicy", "{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourcePolicyNotFoundException"));
String content = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"organizations:Describe*\",\"Resource\":\"*\"}]}";
organizations("PutResourcePolicy", "{\"Content\":" + quote(content) + "}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResourcePolicy.ResourcePolicySummary.Id", startsWith("rp-"))
.body("ResourcePolicy.ResourcePolicySummary.Arn",
startsWith("arn:aws:organizations::000000000000:resourcepolicy/" + organizationId))
.body("ResourcePolicy.Content", equalTo(content));
organizations("DescribeResourcePolicy", "{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ResourcePolicy.Content", equalTo(content));
organizations("DeleteResourcePolicy", "{}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DescribeResourcePolicy", "{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ResourcePolicyNotFoundException"));
}
// ──────────────────────────── Unknown action ────────────────────────────
@Test
@Order(80)
void unknownActionIsRejected() {
organizations("NotARealAction", "{}")
.when()
.post("/")
.then()
.statusCode(404)
.body("__type", equalTo("UnknownOperationException"));
}
// ──────────────────────────── Teardown ────────────────────────────
@Test
@Order(90)
void deleteOrganizationRequiresAnEmptyOrganization() {
organizations("DeleteOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("OrganizationNotEmptyException"));
}
@Test
@Order(91)
void tearDownOrganization() {
organizations("RemoveAccountFromOrganization", "{\"AccountId\":\"" + memberAccountId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DeletePolicy", "{\"PolicyId\":\"" + scpId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DeleteOrganizationalUnit", "{\"OrganizationalUnitId\":\"" + nestedOuId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DeleteOrganizationalUnit", "{\"OrganizationalUnitId\":\"" + ouId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DeleteOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(200);
organizations("DescribeOrganization", "{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("AWSOrganizationsNotInUseException"));
}
private static String quote(String value) {
return "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
}
@@ -0,0 +1,204 @@
package io.github.hectorvent.floci.services.organizations;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.organizations.model.CreateAccountStatus;
import io.github.hectorvent.floci.services.organizations.model.Handshake;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit coverage for the parts of {@link OrganizationsService} that are awkward to pin down over
* the wire: generated id formats, effective-policy merging down the OU chain, and the handshake
* state machine including expiry.
*/
class OrganizationsServiceTest {
private static final String MANAGEMENT_ACCOUNT = "100000000001";
private static final String OUTSIDER_ACCOUNT = "100000000009";
private OrganizationsService service;
private AccountAwareStorageBackend<Handshake> handshakes;
@BeforeEach
void setUp() {
handshakes = AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT);
service = new OrganizationsService(
new ObjectMapper(),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
handshakes);
}
@Test
void generatedIdsMatchTheAwsFormats() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
assertTrue(organization.getId().matches("o-[a-z0-9]{10}"), organization.getId());
assertTrue(organization.getRoot().getId().matches("r-[a-z0-9]{4}"), organization.getRoot().getId());
String rootSuffix = organization.getRoot().getId().substring(2);
OrganizationalUnit unit =
service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, organization.getRoot().getId(), "Unit", null);
assertTrue(unit.getId().matches("ou-" + rootSuffix + "-[a-z0-9]{8}"), unit.getId());
OrganizationPolicy policy = service.createPolicy(MANAGEMENT_ACCOUNT, "{}", null, "Policy",
"SERVICE_CONTROL_POLICY", null);
assertTrue(policy.getId().matches("p-[a-z0-9]{8}"), policy.getId());
CreateAccountStatus status =
service.createAccount(MANAGEMENT_ACCOUNT, "dev@example.com", "Dev", null, false);
assertTrue(status.getId().matches("car-[a-z0-9]{8}"), status.getId());
assertTrue(status.getAccountId().matches("\\d{12}"), status.getAccountId());
}
@Test
void organizationsArnsCarryNoRegion() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
assertEquals("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":organization/" + organization.getId(),
organization.getArn());
assertEquals("arn:aws:organizations::" + MANAGEMENT_ACCOUNT + ":root/" + organization.getId()
+ "/" + organization.getRoot().getId(), organization.getRoot().getArn());
}
@Test
void fullAwsAccessIsAttachedToEveryNewTargetAndCannotBeDetachedAlone() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String rootId = organization.getRoot().getId();
OrganizationalUnit unit = service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, rootId, "Unit", null);
List<OrganizationPolicy> attached = service.listPoliciesForTarget(
MANAGEMENT_ACCOUNT, unit.getId(), "SERVICE_CONTROL_POLICY");
assertEquals(1, attached.size());
assertEquals(OrganizationsService.FULL_AWS_ACCESS_POLICY_ID, attached.get(0).getId());
AwsException error = assertThrows(AwsException.class, () -> service.detachPolicy(
MANAGEMENT_ACCOUNT, OrganizationsService.FULL_AWS_ACCESS_POLICY_ID, unit.getId()));
assertEquals("ConstraintViolationException", error.getErrorCode());
}
@Test
void effectivePolicyMergesDownTheChainWithTheClosestAncestorWinning() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String rootId = organization.getRoot().getId();
service.enablePolicyType(MANAGEMENT_ACCOUNT, rootId, "TAG_POLICY");
OrganizationalUnit unit = service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, rootId, "Unit", null);
String accountId =
service.createAccount(MANAGEMENT_ACCOUNT, "dev@example.com", "Dev", null, false).getAccountId();
service.moveAccount(MANAGEMENT_ACCOUNT, accountId, rootId, unit.getId());
OrganizationPolicy rootPolicy = service.createPolicy(MANAGEMENT_ACCOUNT,
"{\"tags\":{\"cost\":{\"tag_key\":{\"@@assign\":\"from-root\"}},"
+ "\"owner\":{\"tag_key\":{\"@@assign\":\"platform\"}}}}",
null, "RootTags", "TAG_POLICY", null);
OrganizationPolicy unitPolicy = service.createPolicy(MANAGEMENT_ACCOUNT,
"{\"tags\":{\"cost\":{\"tag_key\":{\"@@assign\":\"from-ou\"}}}}",
null, "UnitTags", "TAG_POLICY", null);
service.attachPolicy(MANAGEMENT_ACCOUNT, rootPolicy.getId(), rootId);
service.attachPolicy(MANAGEMENT_ACCOUNT, unitPolicy.getId(), unit.getId());
OrganizationsService.EffectivePolicy effective =
service.describeEffectivePolicy(MANAGEMENT_ACCOUNT, "TAG_POLICY", accountId);
assertEquals(accountId, effective.targetId());
assertTrue(effective.policyContent().contains("from-ou"), effective.policyContent());
assertFalse(effective.policyContent().contains("from-root"), effective.policyContent());
assertTrue(effective.policyContent().contains("platform"), effective.policyContent());
}
@Test
void effectivePolicyRejectsAccessControlPolicyTypes() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
AwsException error = assertThrows(AwsException.class, () -> service.describeEffectivePolicy(
MANAGEMENT_ACCOUNT, "SERVICE_CONTROL_POLICY", organization.getRoot().getId()));
assertEquals("InvalidInputException", error.getErrorCode());
}
@Test
void anExpiredHandshakeReportsExpiredAndCannotBeAccepted() {
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
Handshake handshake = service.inviteAccountToOrganization(
MANAGEMENT_ACCOUNT, OUTSIDER_ACCOUNT, "ACCOUNT", null);
handshake.setExpirationTimestamp(Instant.now().minus(1, ChronoUnit.DAYS));
handshakes.putForAccount(MANAGEMENT_ACCOUNT, handshake.getId(), handshake);
assertEquals("EXPIRED", service.describeHandshake(MANAGEMENT_ACCOUNT, handshake.getId()).getState());
AwsException error = assertThrows(AwsException.class,
() -> service.acceptHandshake(OUTSIDER_ACCOUNT, handshake.getId()));
assertEquals("InvalidHandshakeTransitionException", error.getErrorCode());
}
@Test
void acceptingAnInvitationJoinsTheOrganizationAsAnInvitedMember() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
Handshake handshake = service.inviteAccountToOrganization(
MANAGEMENT_ACCOUNT, OUTSIDER_ACCOUNT, "ACCOUNT", null);
Handshake accepted = service.acceptHandshake(OUTSIDER_ACCOUNT, handshake.getId());
assertEquals("ACCEPTED", accepted.getState());
OrganizationAccount joined = service.describeAccount(OUTSIDER_ACCOUNT, OUTSIDER_ACCOUNT);
assertEquals("INVITED", joined.getJoinedMethod());
assertEquals(organization.getRoot().getId(), joined.getParentId());
assertEquals(organization.getId(), service.describeOrganization(OUTSIDER_ACCOUNT).getId());
}
@Test
void memberAccountsCannotPerformManagementActions() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
Handshake handshake = service.inviteAccountToOrganization(
MANAGEMENT_ACCOUNT, OUTSIDER_ACCOUNT, "ACCOUNT", null);
service.acceptHandshake(OUTSIDER_ACCOUNT, handshake.getId());
AwsException error = assertThrows(AwsException.class, () -> service.createOrganizationalUnit(
OUTSIDER_ACCOUNT, organization.getRoot().getId(), "Unit", null));
assertEquals("AccessDeniedException", error.getErrorCode());
assertEquals(403, error.getHttpStatus());
}
@Test
void tagsRoundTripAcrossEveryTaggableResourceType() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String rootId = organization.getRoot().getId();
OrganizationalUnit unit = service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, rootId, "Unit", null);
OrganizationPolicy policy = service.createPolicy(MANAGEMENT_ACCOUNT, "{}", null, "Policy",
"SERVICE_CONTROL_POLICY", null);
for (String resourceId : List.of(rootId, unit.getId(), policy.getId(), MANAGEMENT_ACCOUNT)) {
service.tagResource(MANAGEMENT_ACCOUNT, resourceId, Map.of("env", "test"));
assertEquals(Map.of("env", "test"), service.listTagsForResource(MANAGEMENT_ACCOUNT, resourceId));
service.untagResource(MANAGEMENT_ACCOUNT, resourceId, List.of("env"));
assertTrue(service.listTagsForResource(MANAGEMENT_ACCOUNT, resourceId).isEmpty());
}
}
@Test
void anAccountOutsideAnyOrganizationGetsNotInUse() {
AwsException error = assertThrows(AwsException.class,
() -> service.describeOrganization(OUTSIDER_ACCOUNT));
assertEquals("AWSOrganizationsNotInUseException", error.getErrorCode());
}
}