Light, fluffy, and always free - The AWS Local Emulator alternative
feat(organizations): add AWS Organizations service (#2489)
William St John Bacon87e804492aaa
diff --git a/README.md b/README.mdindex 6d6b2db87d..679a733754 100644--- a/README.md+++ b/README.md@@ -226,7 +226,7 @@ Floci supports local emulation for application services, data services, eventing| Data, analytics, and AI | Athena, Glue, EMR, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Bedrock Runtime || Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache || Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core |-| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, CloudHSM v2 |+| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, CloudHSM v2, Organizations || Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports || Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |@@ -297,6 +297,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/| AWS Backup | In-process | Vaults, backup plans, selections, simulated job lifecycle, recovery points || AWS FIS | In-process | All 26 management APIs for templates, experiments, target accounts, action and target discovery, safety lever, tagging, and pagination; experiment execution is a safe control-plane simulation and does not inject faults into other services || AWS Config | In-process | Config rules, configuration recorders, delivery channels, conformance packs, tagging |+| Organizations | In-process | Organizations, roots, nested OUs, member accounts, all policy types with `FullAWSAccess` and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable Floci accounts and member accounts can read the organization they belong to || CloudTrail | In-process | Trails, event selectors (S3 data events with bucket/prefix matching), `StartLogging`/`StopLogging`, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits `AccessDenied` records || CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, tagging || WAF v2 | In-process | Web ACLs, IP sets, regex pattern sets, rule groups, logging configs, resource associations, tagging (REGIONAL and CLOUDFRONT scopes) |diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex ad5872292d..c1423503c6 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -213,6 +213,11 @@<groupId>software.amazon.awssdk</groupId><artifactId>cloudhsmv2</artifactId></dependency>+ <!-- Organizations client -->+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>organizations</artifactId>+ </dependency><!-- Cloud Map (servicediscovery) client --><dependency><groupId>software.amazon.awssdk</groupId>diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex 44c8a6d25a..1c5505333d 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -28,6 +28,7 @@ import software.amazon.awssdk.services.neptune.NeptuneClient;import software.amazon.awssdk.services.rds.RdsClient;import software.amazon.awssdk.services.guardduty.GuardDutyClient;import software.amazon.awssdk.services.fis.FisClient;+import software.amazon.awssdk.services.organizations.OrganizationsClient;import software.amazon.awssdk.services.rum.RumClient;import software.amazon.awssdk.services.s3.S3Client;import software.amazon.awssdk.endpoints.Endpoint;@@ -259,6 +260,14 @@ public final class TestFixtures {.build();}+ public static OrganizationsClient organizationsClient() {+ return OrganizationsClient.builder()+ .endpointOverride(ENDPOINT)+ .region(REGION)+ .credentialsProvider(CREDENTIALS)+ .build();+ }+public static SsmClient ssmClient() {return SsmClient.builder().endpointOverride(ENDPOINT)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OrganizationsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OrganizationsTest.javanew file mode 100644index 0000000000..7c89977d5d--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OrganizationsTest.java@@ -0,0 +1,268 @@+package com.floci.test;++import org.junit.jupiter.api.Test;+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;+import software.amazon.awssdk.regions.Region;+import software.amazon.awssdk.services.organizations.OrganizationsClient;+import software.amazon.awssdk.services.organizations.model.Account;+import software.amazon.awssdk.services.organizations.model.AccessDeniedException;+import software.amazon.awssdk.services.organizations.model.AwsOrganizationsNotInUseException;+import software.amazon.awssdk.services.organizations.model.ChildType;+import software.amazon.awssdk.services.organizations.model.ConstraintViolationException;+import software.amazon.awssdk.services.organizations.model.CreateAccountState;+import software.amazon.awssdk.services.organizations.model.CreateAccountStatus;+import software.amazon.awssdk.services.organizations.model.Handshake;+import software.amazon.awssdk.services.organizations.model.HandshakeState;+import software.amazon.awssdk.services.organizations.model.Organization;+import software.amazon.awssdk.services.organizations.model.OrganizationFeatureSet;+import software.amazon.awssdk.services.organizations.model.OrganizationalUnit;+import software.amazon.awssdk.services.organizations.model.OrganizationalUnitNotEmptyException;+import software.amazon.awssdk.services.organizations.model.Policy;+import software.amazon.awssdk.services.organizations.model.PolicyInUseException;+import software.amazon.awssdk.services.organizations.model.PolicyType;+import software.amazon.awssdk.services.organizations.model.Root;+import software.amazon.awssdk.services.organizations.model.TargetType;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++/**+ * Drives the whole Organizations surface through the real AWS SDK, which is the check that+ * matters for wire compatibility: the SDK does its own request marshalling, response parsing,+ * id/ARN validation and typed-exception mapping.+ *+ * <p>The test tears the organization down at the end so it can be re-run against the same+ * Floci instance.+ */+public class OrganizationsTest {++ private static final String SCP_CONTENT =+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"ec2:*\",\"Resource\":\"*\"}]}";+ private static final String TAG_POLICY_CONTENT =+ "{\"tags\":{\"CostCenter\":{\"tag_key\":{\"@@assign\":\"CostCenter\"}}}}";++ private static final String INVITED_ACCOUNT = "987654321098";++ private final OrganizationsClient client = TestFixtures.organizationsClient();++ /** A client whose 12-digit access key id makes Floci treat the caller as that account. */+ private static OrganizationsClient clientFor(String accountId) {+ return OrganizationsClient.builder()+ .endpointOverride(TestFixtures.endpoint())+ .region(Region.US_EAST_1)+ .credentialsProvider(StaticCredentialsProvider.create(+ AwsBasicCredentials.create(accountId, "test")))+ .build();+ }++ @Test+ public void testFullLifecycle() {+ // 1. Create the organization.+ Organization organization = client.createOrganization(r -> r.featureSet(OrganizationFeatureSet.ALL))+ .organization();+ assertThat(organization.id()).matches("o-[a-z0-9]{10}");+ assertThat(organization.featureSet()).isEqualTo(OrganizationFeatureSet.ALL);+ assertThat(organization.arn()).startsWith("arn:aws:organizations::");+ assertThat(organization.masterAccountId()).isNotBlank();++ String managementAccountId = organization.masterAccountId();++ try {+ assertThat(client.describeOrganization().organization().id()).isEqualTo(organization.id());++ // 2. The root exists and carries the AWS-managed FullAWSAccess SCP.+ Root root = client.listRoots().roots().get(0);+ assertThat(root.id()).matches("r-[a-z0-9]{4}");+ assertThat(root.name()).isEqualTo("Root");+ assertThat(root.policyTypes()).anyMatch(p -> p.type() == PolicyType.SERVICE_CONTROL_POLICY);++ assertThat(client.listPoliciesForTarget(r -> r.targetId(root.id())+ .filter(PolicyType.SERVICE_CONTROL_POLICY)).policies())+ .anyMatch(p -> p.id().equals("p-FullAWSAccess") && Boolean.TRUE.equals(p.awsManaged()));++ // 3. Build an OU tree.+ OrganizationalUnit workloads = client.createOrganizationalUnit(r -> r+ .parentId(root.id()).name("Workloads")).organizationalUnit();+ assertThat(workloads.id()).matches("ou-[a-z0-9]{4}-[a-z0-9]{8}");++ OrganizationalUnit production = client.createOrganizationalUnit(r -> r+ .parentId(workloads.id()).name("Production")).organizationalUnit();++ assertThat(client.listOrganizationalUnitsForParent(r -> r.parentId(root.id()))+ .organizationalUnits()).extracting(OrganizationalUnit::id).containsExactly(workloads.id());+ assertThat(client.listChildren(r -> r.parentId(workloads.id())+ .childType(ChildType.ORGANIZATIONAL_UNIT)).children())+ .singleElement().satisfies(child -> assertThat(child.id()).isEqualTo(production.id()));+ assertThat(client.listParents(r -> r.childId(production.id())).parents())+ .singleElement().satisfies(parent -> assertThat(parent.id()).isEqualTo(workloads.id()));++ // 4. Create a member account and move it into the OU.+ CreateAccountStatus status = client.createAccount(r -> r+ .email("[email protected]").accountName("CompatDev")).createAccountStatus();+ assertThat(status.id()).startsWith("car-");+ assertThat(status.state()).isEqualTo(CreateAccountState.SUCCEEDED);+ assertThat(status.accountId()).matches("\\d{12}");++ String memberAccountId = status.accountId();+ assertThat(client.describeCreateAccountStatus(r -> r.createAccountRequestId(status.id()))+ .createAccountStatus().accountId()).isEqualTo(memberAccountId);++ Account member = client.describeAccount(r -> r.accountId(memberAccountId)).account();+ assertThat(member.email()).isEqualTo("[email protected]");+ assertThat(member.name()).isEqualTo("CompatDev");+ assertThat(member.joinedTimestamp()).isNotNull();++ assertThat(client.listAccounts().accounts()).extracting(Account::id)+ .contains(managementAccountId, memberAccountId);++ client.moveAccount(r -> r.accountId(memberAccountId)+ .sourceParentId(root.id()).destinationParentId(workloads.id()));+ assertThat(client.listAccountsForParent(r -> r.parentId(workloads.id())).accounts())+ .extracting(Account::id).containsExactly(memberAccountId);++ assertThatThrownBy(() -> client.deleteOrganizationalUnit(r -> r+ .organizationalUnitId(workloads.id())))+ .isInstanceOf(OrganizationalUnitNotEmptyException.class);++ // 5. Service control policies.+ Policy scp = client.createPolicy(r -> r.name("CompatDenyEc2").description("Deny EC2")+ .type(PolicyType.SERVICE_CONTROL_POLICY).content(SCP_CONTENT)).policy();+ assertThat(scp.policySummary().id()).matches("p-[a-z0-9]{8}");+ assertThat(scp.content()).isEqualTo(SCP_CONTENT);++ String scpId = scp.policySummary().id();+ client.attachPolicy(r -> r.policyId(scpId).targetId(workloads.id()));++ assertThat(client.listTargetsForPolicy(r -> r.policyId(scpId)).targets())+ .singleElement().satisfies(target -> {+ assertThat(target.targetId()).isEqualTo(workloads.id());+ assertThat(target.type()).isEqualTo(TargetType.ORGANIZATIONAL_UNIT);+ assertThat(target.name()).isEqualTo("Workloads");+ });++ assertThatThrownBy(() -> client.deletePolicy(r -> r.policyId(scpId)))+ .isInstanceOf(PolicyInUseException.class);++ client.detachPolicy(r -> r.policyId(scpId).targetId(workloads.id()));+ assertThatThrownBy(() -> client.detachPolicy(r -> r+ .policyId("p-FullAWSAccess").targetId(workloads.id())))+ .isInstanceOf(ConstraintViolationException.class);+ client.deletePolicy(r -> r.policyId(scpId));++ // 6. Tag policies and effective-policy inheritance.+ client.enablePolicyType(r -> r.rootId(root.id()).policyType(PolicyType.TAG_POLICY));+ Policy tagPolicy = client.createPolicy(r -> r.name("CompatCostCenter")+ .type(PolicyType.TAG_POLICY).content(TAG_POLICY_CONTENT)).policy();+ String tagPolicyId = tagPolicy.policySummary().id();+ client.attachPolicy(r -> r.policyId(tagPolicyId).targetId(root.id()));++ assertThat(client.describeEffectivePolicy(r -> r+ .policyType("TAG_POLICY").targetId(memberAccountId)).effectivePolicy())+ .satisfies(effective -> {+ assertThat(effective.policyContent()).isEqualTo(TAG_POLICY_CONTENT);+ assertThat(effective.targetId()).isEqualTo(memberAccountId);+ assertThat(effective.lastUpdatedTimestamp()).isNotNull();+ });++ client.detachPolicy(r -> r.policyId(tagPolicyId).targetId(root.id()));+ client.deletePolicy(r -> r.policyId(tagPolicyId));+ client.disablePolicyType(r -> r.rootId(root.id()).policyType(PolicyType.TAG_POLICY));++ // 7. Tags.+ client.tagResource(r -> r.resourceId(memberAccountId)+ .tags(t -> t.key("team").value("platform")));+ assertThat(client.listTagsForResource(r -> r.resourceId(memberAccountId)).tags())+ .singleElement().satisfies(tag -> {+ assertThat(tag.key()).isEqualTo("team");+ assertThat(tag.value()).isEqualTo("platform");+ });+ client.untagResource(r -> r.resourceId(memberAccountId).tagKeys("team"));+ assertThat(client.listTagsForResource(r -> r.resourceId(memberAccountId)).tags()).isEmpty();++ // 8. Trusted access and delegated administrators.+ client.enableAWSServiceAccess(r -> r.servicePrincipal("config.amazonaws.com"));+ assertThat(client.listAWSServiceAccessForOrganization().enabledServicePrincipals())+ .singleElement().satisfies(principal -> {+ assertThat(principal.servicePrincipal()).isEqualTo("config.amazonaws.com");+ assertThat(principal.dateEnabled()).isNotNull();+ });++ client.registerDelegatedAdministrator(r -> r.accountId(memberAccountId)+ .servicePrincipal("config.amazonaws.com"));+ assertThat(client.listDelegatedAdministrators(r -> r+ .servicePrincipal("config.amazonaws.com")).delegatedAdministrators())+ .singleElement().satisfies(admin -> {+ assertThat(admin.id()).isEqualTo(memberAccountId);+ assertThat(admin.delegationEnabledDate()).isNotNull();+ });+ assertThat(client.listDelegatedServicesForAccount(r -> r.accountId(memberAccountId))+ .delegatedServices()).singleElement()+ .satisfies(svc -> assertThat(svc.servicePrincipal()).isEqualTo("config.amazonaws.com"));++ client.deregisterDelegatedAdministrator(r -> r.accountId(memberAccountId)+ .servicePrincipal("config.amazonaws.com"));+ client.disableAWSServiceAccess(r -> r.servicePrincipal("config.amazonaws.com"));++ // 9. Resource policy.+ String resourcePolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","+ + "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"organizations:Describe*\",\"Resource\":\"*\"}]}";+ assertThat(client.putResourcePolicy(r -> r.content(resourcePolicy)).resourcePolicy())+ .satisfies(policy -> {+ assertThat(policy.resourcePolicySummary().id()).startsWith("rp-");+ assertThat(policy.content()).isEqualTo(resourcePolicy);+ });+ assertThat(client.describeResourcePolicy(r -> { }).resourcePolicy().content())+ .isEqualTo(resourcePolicy);+ client.deleteResourcePolicy(r -> { });++ // 10. The invitation handshake, driven from both sides.+ try (OrganizationsClient invitedClient = clientFor(INVITED_ACCOUNT)) {+ assertThatThrownBy(invitedClient::describeOrganization)+ .isInstanceOf(AwsOrganizationsNotInUseException.class);++ Handshake invitation = client.inviteAccountToOrganization(r -> r+ .target(t -> t.id(INVITED_ACCOUNT).type("ACCOUNT"))+ .notes("compat suite")).handshake();+ assertThat(invitation.state()).isEqualTo(HandshakeState.REQUESTED);+ assertThat(invitation.expirationTimestamp()).isNotNull();++ Handshake accepted = invitedClient.acceptHandshake(r -> r+ .handshakeId(invitation.id())).handshake();+ assertThat(accepted.state()).isEqualTo(HandshakeState.ACCEPTED);++ // The member account can now read the organization it belongs to, but not mutate it.+ assertThat(invitedClient.describeOrganization().organization().id())+ .isEqualTo(organization.id());+ assertThatThrownBy(() -> invitedClient.createOrganizationalUnit(r -> r+ .parentId(root.id()).name("Nope")))+ .isInstanceOf(AccessDeniedException.class);++ assertThat(client.listHandshakesForOrganization().handshakes())+ .extracting(Handshake::id).contains(invitation.id());++ invitedClient.leaveOrganization();+ assertThat(client.listAccounts().accounts())+ .extracting(Account::id).doesNotContain(INVITED_ACCOUNT);+ }++ // 11. Tear the organization down.+ client.removeAccountFromOrganization(r -> r.accountId(memberAccountId));+ client.deleteOrganizationalUnit(r -> r.organizationalUnitId(production.id()));+ client.deleteOrganizationalUnit(r -> r.organizationalUnitId(workloads.id()));+ } finally {+ // Best effort: if an assertion above failed, the organization may still hold accounts+ // or OUs and DeleteOrganization will refuse. Swallowing that here keeps the original+ // assertion failure visible instead of replacing it with a cleanup error.+ try {+ client.deleteOrganization();+ } catch (RuntimeException e) {+ System.err.println("[WARN] Organizations cleanup failed, leaving the organization "+ + "in place: " + e.getMessage());+ }+ }++ assertThatThrownBy(client::describeOrganization)+ .isInstanceOf(AwsOrganizationsNotInUseException.class);+ }+}diff --git a/docs/index.md b/docs/index.mdindex 3cc3033b45..816cad8925 100644--- a/docs/index.md+++ b/docs/index.md@@ -34,6 +34,7 @@ Floci emulates 73 AWS services. See the [Services Overview](services/index.md) f| Step Functions | JSON 1.1 || IAM | Query || STS | Query |+| Organizations | JSON 1.1 || ElastiCache (Redis / Valkey) | Query + RESP proxy || RDS (PostgreSQL / MySQL) | Query + wire proxy || RDS Data API | REST JSON |diff --git a/docs/services/index.md b/docs/services/index.mdindex a79ab8b991..982f3aeba5 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -25,6 +25,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [IAM](iam.md) | `POST /` with `Action=` param | Query | 76 || [STS](sts.md) | `POST /` with `Action=` param | Query | 7 || [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |+| [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 55 || [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 43 || [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 34 || [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 |diff --git a/docs/services/organizations.md b/docs/services/organizations.mdnew file mode 100644index 0000000000..70725faf16--- /dev/null+++ b/docs/services/organizations.md@@ -0,0 +1,113 @@+# Organizations++**Protocol:** JSON 1.1 (`X-Amz-Target: AWSOrganizationsV20161128.*`)+**Endpoint:** `POST http://localhost:4566/`++Floci emulates the full AWS Organizations control plane: the organization and its root,+the organizational-unit tree, member accounts, policies of every type, tags, trusted+service access, delegated administrators, the organization resource policy, and the+invitation/handshake flow.++## Accounts are real Floci accounts++Floci resolves any 12-digit access key id straight to an AWS account, so an account created+by `CreateAccount` is immediately usable as a caller identity against every other service:++```bash+aws --endpoint-url http://localhost:4566 organizations create-organization --feature-set ALL+aws --endpoint-url http://localhost:4566 organizations create-account \+ --email [email protected] --account-name Dev+# ... then call as that account+AWS_ACCESS_KEY_ID=<new-account-id> AWS_SECRET_ACCESS_KEY=x \+ aws --endpoint-url http://localhost:4566 organizations describe-organization+```++## Management account vs member accounts++Authorization mirrors AWS. Every mutating action is restricted to the **management account**+— the account that called `CreateOrganization` — and returns `AccessDeniedException` otherwise.+Member accounts can read the organization they belong to (`DescribeOrganization`, `ListRoots`,+`ListParents`, `DescribeAccount`, `DescribePolicy`), act on handshakes addressed to them, and+call `LeaveOrganization`. An account in no organization gets+`AWSOrganizationsNotInUseException`.++## Behaviour notes++- The AWS-managed `p-FullAWSAccess` SCP is created with the organization and attached to the+ root, every new OU and every new account. Detaching the last service control policy from a+ target is rejected with `ConstraintViolationException`, as on AWS.+- A `CONSOLIDATED_BILLING` organization has no available policy types. `EnableAllFeatures`+ promotes it to `ALL`; with no member accounts the handshake completes immediately. With member+ accounts it stays `REQUESTED` until one of them calls `AcceptHandshake` — AWS requires *every*+ member to approve, which Floci simplifies to the first acceptance.+- `CreateAccount` returns a `CreateAccountStatus` you can poll with+ `DescribeCreateAccountStatus`, matching the asynchronous AWS contract. A duplicate email+ produces `State=FAILED` with `FailureReason=EMAIL_ALREADY_EXISTS` rather than an error.+- `DescribeEffectivePolicy` merges every policy of the requested type down the+ root → OU → target chain, with the closest ancestor winning on conflicting keys. As on AWS,+ the access-control types (`SERVICE_CONTROL_POLICY`, `RESOURCE_CONTROL_POLICY`) are rejected.+- Handshakes expire 15 days after they are created and report `EXPIRED` from then on.+- Organizations ARNs are global and carry no region:+ `arn:aws:organizations::123456789012:organization/o-abc1234567`.++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `CreateOrganization` | Creates an organization with the calling account as the management account. |+| `DescribeOrganization` | Returns information about the organization the calling account belongs to. |+| `DeleteOrganization` | Deletes the organization; only the management account may remain in it. |+| `EnableAllFeatures` | Upgrades a consolidated-billing organization to all features via a handshake. |+| `ListRoots` | Lists the roots defined in the organization. |+| `CreateOrganizationalUnit` | Creates an OU under the specified root or parent OU. |+| `UpdateOrganizationalUnit` | Renames the specified organizational unit. |+| `DeleteOrganizationalUnit` | Deletes an organizational unit that contains no accounts or child OUs. |+| `DescribeOrganizationalUnit` | Returns information about the specified organizational unit. |+| `ListOrganizationalUnitsForParent` | Lists the OUs directly under the specified root or parent OU. |+| `ListParents` | Lists the parent of the specified account or organizational unit. |+| `ListChildren` | Lists the accounts or OUs directly under the specified root or parent OU. |+| `CreateAccount` | Creates a member account in the organization and returns its request status. |+| `CreateGovCloudAccount` | Creates a member account together with a linked AWS GovCloud (US) account. |+| `DescribeCreateAccountStatus` | Returns the status of an account-creation request. |+| `ListCreateAccountStatus` | Lists account-creation requests, optionally filtered by state. |+| `DescribeAccount` | Returns information about the specified member account. |+| `ListAccounts` | Lists every account in the organization. |+| `ListAccountsForParent` | Lists the accounts directly under the specified root or OU. |+| `MoveAccount` | Moves an account from one root or OU to another. |+| `RemoveAccountFromOrganization` | Removes a member account from the organization. |+| `LeaveOrganization` | Removes the calling member account from its organization. |+| `CloseAccount` | Closes a member account, moving it to PENDING_CLOSURE. |+| `CreatePolicy` | Creates a policy of the specified type in the organization. |+| `UpdatePolicy` | Updates the name, description or content of a customer-managed policy. |+| `DeletePolicy` | Deletes a policy that is not attached to any target. |+| `DescribePolicy` | Returns a policy's summary and content. |+| `ListPolicies` | Lists the policies of the specified type in the organization. |+| `AttachPolicy` | Attaches a policy to a root, organizational unit or account. |+| `DetachPolicy` | Detaches a policy from a root, organizational unit or account. |+| `ListPoliciesForTarget` | Lists the policies of a given type attached directly to a target. |+| `ListTargetsForPolicy` | Lists the roots, OUs and accounts a policy is attached to. |+| `EnablePolicyType` | Enables a policy type on the specified root. |+| `DisablePolicyType` | Disables a policy type on the specified root. |+| `DescribeEffectivePolicy` | Returns the merged policy of the given type that applies to a target. |+| `TagResource` | Adds or overwrites tags on a root, OU, account or policy. |+| `UntagResource` | Removes the specified tags from a root, OU, account or policy. |+| `ListTagsForResource` | Lists the tags on a root, OU, account or policy. |+| `EnableAWSServiceAccess` | Enables trusted access for an AWS service principal. |+| `DisableAWSServiceAccess` | Disables trusted access for an AWS service principal. |+| `ListAWSServiceAccessForOrganization` | Lists the service principals with trusted access enabled. |+| `RegisterDelegatedAdministrator` | Registers a member account as a delegated administrator for a service. |+| `DeregisterDelegatedAdministrator` | Removes a member account's delegated administrator role for a service. |+| `ListDelegatedAdministrators` | Lists the delegated administrators in the organization. |+| `ListDelegatedServicesForAccount` | Lists the services a member account is a delegated administrator for. |+| `PutResourcePolicy` | Creates or updates the organization's resource policy. |+| `DescribeResourcePolicy` | Returns the organization's resource policy. |+| `DeleteResourcePolicy` | Deletes the organization's resource policy. |+| `InviteAccountToOrganization` | Sends an invitation handshake to an account or email address. |+| `AcceptHandshake` | Accepts a handshake, joining the organization for an invitation. |+| `DeclineHandshake` | Declines a handshake addressed to the calling account. |+| `CancelHandshake` | Cancels an open handshake the calling account originated. |+| `DescribeHandshake` | Returns information about the specified handshake. |+| `ListHandshakesForAccount` | Lists the handshakes that involve the calling account. |+| `ListHandshakesForOrganization` | Lists the handshakes associated with the organization. |+<!-- floci:actions:end -->diff --git a/mkdocs.yml b/mkdocs.ymlindex cc4925c3d9..a5c9fdc9b6 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -97,6 +97,7 @@ nav:- SWF: services/swf.md- IAM: services/iam.md- STS: services/sts.md+ - Organizations: services/organizations.md- ElastiCache: services/elasticache.md- MemoryDB: services/memorydb.md- RDS: services/rds.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex d6ef0b2241..734958b721 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -634,6 +634,7 @@ public interface EmulatorConfig {IotServiceConfig iot();IotDataServiceConfig iotdata();CloudHsmV2ServiceConfig cloudhsmv2();+ OrganizationsServiceConfig organizations();RumServiceConfig rum();GuardDutyServiceConfig guardduty();EmrServerlessServiceConfig emrserverless();@@ -1205,6 +1206,11 @@ public interface EmulatorConfig {boolean enabled();}+ interface OrganizationsServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface AthenaServiceConfig {@WithDefault("true")boolean enabled();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.javaindex 4f0e470f52..3d368eccf9 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java@@ -40,6 +40,7 @@ import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;import io.github.hectorvent.floci.services.kinesisanalytics.KinesisAnalyticsV2JsonHandler;import io.github.hectorvent.floci.services.kms.KmsJsonHandler;import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;+import io.github.hectorvent.floci.services.organizations.OrganizationsJsonHandler;import io.github.hectorvent.floci.services.ssm.Ec2MessagesJsonHandler;import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;import jakarta.inject.Inject;@@ -105,6 +106,7 @@ public class AwsJson11Controller {private final CloudControlJsonHandler cloudControlJsonHandler;private final ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler;private final CloudHsmV2JsonHandler cloudHsmV2JsonHandler;+ private final OrganizationsJsonHandler organizationsJsonHandler;@Injectpublic AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,@@ -141,7 +143,8 @@ public class AwsJson11Controller {LightsailJsonHandler lightsailJsonHandler,CloudControlJsonHandler cloudControlJsonHandler,ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler,- CloudHsmV2JsonHandler cloudHsmV2JsonHandler){+ CloudHsmV2JsonHandler cloudHsmV2JsonHandler,+ OrganizationsJsonHandler organizationsJsonHandler){this.objectMapper = objectMapper;this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);this.catalog = catalog;@@ -183,6 +186,7 @@ public class AwsJson11Controller {this.cloudControlJsonHandler = cloudControlJsonHandler;this.applicationAutoScalingJsonHandler = applicationAutoScalingJsonHandler;this.cloudHsmV2JsonHandler = cloudHsmV2JsonHandler;+ this.organizationsJsonHandler = organizationsJsonHandler;}@POST@@ -255,6 +259,10 @@ public class AwsJson11Controller {case "lightsail" -> lightsailJsonHandler.handle(action, request, region);case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region);case "cloudhsmv2" -> cloudHsmV2JsonHandler.handle(action, request, region);+ // Organizations is global and account-scoped rather than region-scoped: every+ // action is authorized against the calling account, so pass that instead of region.+ case "organizations" ->+ organizationsJsonHandler.handle(action, request, regionResolver.getAccountId());default -> null;};// catalog.matchTarget is protocol-agnostic: a JSON 1.0 targetdiff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex ca6ee2b7ca..65162ed85b 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -476,6 +476,10 @@ public class ResolvedServiceCatalog {"cloudhsmv2", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,protocols(ServiceProtocol.JSON),Set.of("BaldrApiService."), Set.of("cloudhsm"), Set.of(), Set.of()),+ descriptor("organizations", "organizations", config.services().organizations().enabled(), true,+ "organizations", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,+ protocols(ServiceProtocol.JSON),+ Set.of("AWSOrganizationsV20161128."), Set.of("organizations"), Set.of(), Set.of()),descriptor("rum", "rum", config.services().rum().enabled(), true,"rum", storageMode(config.storage().services().rum().mode(), config.storage().mode()),config.storage().services().rum().flushIntervalMs(), null, ServiceProtocol.REST_JSON,diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsJsonHandler.javanew file mode 100644index 0000000000..fd4ab3926e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsJsonHandler.java@@ -0,0 +1,756 @@+package io.github.hectorvent.floci.services.organizations;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.Pagination;+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.HandshakeParty;+import io.github.hectorvent.floci.services.organizations.model.HandshakeResource;+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.PolicyTypeSummary;+import io.github.hectorvent.floci.services.organizations.model.Root;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import jakarta.ws.rs.core.Response;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.function.Function;++/**+ * AWS Organizations JSON 1.1 handler. Dispatched from+ * {@link io.github.hectorvent.floci.core.common.AwsJson11Controller} under the+ * {@code AWSOrganizationsV20161128.} target prefix.+ *+ * <p>The handler is deliberately thin: it parses the request, delegates to+ * {@link OrganizationsService}, and renders the AWS response shape. All validation and+ * authorization lives in the service.+ */+@ApplicationScoped+public class OrganizationsJsonHandler {++ private static final Logger LOG = Logger.getLogger(OrganizationsJsonHandler.class);++ /** AWS caps MaxResults at 20 across the Organizations list operations. */+ private static final int MAX_PAGE = 20;++ private static final String PAGINATION_ERROR = "InvalidInputException";++ private final OrganizationsService service;+ private final ObjectMapper objectMapper;++ @Inject+ public OrganizationsJsonHandler(OrganizationsService service, ObjectMapper objectMapper) {+ this.service = service;+ this.objectMapper = objectMapper;+ }++ public Response handle(String action, JsonNode request, String callerAccountId) {+ LOG.debugv("Organizations action: {0}", action);+ try {+ return switch (action) {+ case "CreateOrganization" -> createOrganization(request, callerAccountId);+ case "DescribeOrganization" -> describeOrganization(callerAccountId);+ case "DeleteOrganization" -> deleteOrganization(callerAccountId);+ case "EnableAllFeatures" -> enableAllFeatures(callerAccountId);+ case "ListRoots" -> listRoots(request, callerAccountId);+ case "CreateOrganizationalUnit" -> createOrganizationalUnit(request, callerAccountId);+ case "UpdateOrganizationalUnit" -> updateOrganizationalUnit(request, callerAccountId);+ case "DeleteOrganizationalUnit" -> deleteOrganizationalUnit(request, callerAccountId);+ case "DescribeOrganizationalUnit" -> describeOrganizationalUnit(request, callerAccountId);+ case "ListOrganizationalUnitsForParent" -> listOrganizationalUnitsForParent(request, callerAccountId);+ case "ListParents" -> listParents(request, callerAccountId);+ case "ListChildren" -> listChildren(request, callerAccountId);+ case "CreateAccount" -> createAccount(request, callerAccountId, false);+ case "CreateGovCloudAccount" -> createAccount(request, callerAccountId, true);+ case "DescribeCreateAccountStatus" -> describeCreateAccountStatus(request, callerAccountId);+ case "ListCreateAccountStatus" -> listCreateAccountStatus(request, callerAccountId);+ case "DescribeAccount" -> describeAccount(request, callerAccountId);+ case "ListAccounts" -> listAccounts(request, callerAccountId);+ case "ListAccountsForParent" -> listAccountsForParent(request, callerAccountId);+ case "MoveAccount" -> moveAccount(request, callerAccountId);+ case "RemoveAccountFromOrganization" -> removeAccountFromOrganization(request, callerAccountId);+ case "LeaveOrganization" -> leaveOrganization(callerAccountId);+ case "CloseAccount" -> closeAccount(request, callerAccountId);+ case "CreatePolicy" -> createPolicy(request, callerAccountId);+ case "UpdatePolicy" -> updatePolicy(request, callerAccountId);+ case "DeletePolicy" -> deletePolicy(request, callerAccountId);+ case "DescribePolicy" -> describePolicy(request, callerAccountId);+ case "ListPolicies" -> listPolicies(request, callerAccountId);+ case "AttachPolicy" -> attachPolicy(request, callerAccountId);+ case "DetachPolicy" -> detachPolicy(request, callerAccountId);+ case "ListPoliciesForTarget" -> listPoliciesForTarget(request, callerAccountId);+ case "ListTargetsForPolicy" -> listTargetsForPolicy(request, callerAccountId);+ case "EnablePolicyType" -> enablePolicyType(request, callerAccountId);+ case "DisablePolicyType" -> disablePolicyType(request, callerAccountId);+ case "DescribeEffectivePolicy" -> describeEffectivePolicy(request, callerAccountId);+ case "TagResource" -> tagResource(request, callerAccountId);+ case "UntagResource" -> untagResource(request, callerAccountId);+ case "ListTagsForResource" -> listTagsForResource(request, callerAccountId);+ case "EnableAWSServiceAccess" -> enableAwsServiceAccess(request, callerAccountId);+ case "DisableAWSServiceAccess" -> disableAwsServiceAccess(request, callerAccountId);+ case "ListAWSServiceAccessForOrganization" ->+ listAwsServiceAccessForOrganization(request, callerAccountId);+ case "RegisterDelegatedAdministrator" -> registerDelegatedAdministrator(request, callerAccountId);+ case "DeregisterDelegatedAdministrator" -> deregisterDelegatedAdministrator(request, callerAccountId);+ case "ListDelegatedAdministrators" -> listDelegatedAdministrators(request, callerAccountId);+ case "ListDelegatedServicesForAccount" -> listDelegatedServicesForAccount(request, callerAccountId);+ case "PutResourcePolicy" -> putResourcePolicy(request, callerAccountId);+ case "DescribeResourcePolicy" -> describeResourcePolicy(callerAccountId);+ case "DeleteResourcePolicy" -> deleteResourcePolicy(callerAccountId);+ case "InviteAccountToOrganization" -> inviteAccountToOrganization(request, callerAccountId);+ case "AcceptHandshake" -> acceptHandshake(request, callerAccountId);+ case "DeclineHandshake" -> declineHandshake(request, callerAccountId);+ case "CancelHandshake" -> cancelHandshake(request, callerAccountId);+ case "DescribeHandshake" -> describeHandshake(request, callerAccountId);+ case "ListHandshakesForAccount" -> listHandshakesForAccount(request, callerAccountId);+ case "ListHandshakesForOrganization" -> listHandshakesForOrganization(request, callerAccountId);+ default -> JsonErrorResponseUtils.createUnknownOperationErrorResponse(+ "AWSOrganizationsV20161128." + action);+ };+ } catch (AwsException e) {+ return JsonErrorResponseUtils.createErrorResponse(e);+ } catch (Exception e) {+ LOG.errorf(e, "Organizations error processing action %s", action);+ return JsonErrorResponseUtils.createErrorResponse(e);+ }+ }++ // ──────────────────────────── Organization lifecycle ────────────────────────────++ private Response createOrganization(JsonNode request, String caller) {+ Organization organization = service.createOrganization(caller, text(request, "FeatureSet"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Organization", organizationNode(organization));+ return Response.ok(response).build();+ }++ private Response describeOrganization(String caller) {+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Organization", organizationNode(service.describeOrganization(caller)));+ return Response.ok(response).build();+ }++ private Response deleteOrganization(String caller) {+ service.deleteOrganization(caller);+ return empty();+ }++ private Response enableAllFeatures(String caller) {+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Handshake", handshakeNode(service.enableAllFeatures(caller)));+ return Response.ok(response).build();+ }++ private Response listRoots(JsonNode request, String caller) {+ PaginatedResult<Root> page = page(service.listRoots(caller), Root::getId, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode roots = response.putArray("Roots");+ page.items().forEach(root -> roots.add(rootNode(root)));+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ // ──────────────────────────── Organizational units ────────────────────────────++ private Response createOrganizationalUnit(JsonNode request, String caller) {+ OrganizationalUnit unit = service.createOrganizationalUnit(caller,+ text(request, "ParentId"), text(request, "Name"), parseTags(request.path("Tags")));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("OrganizationalUnit", organizationalUnitNode(unit));+ return Response.ok(response).build();+ }++ private Response updateOrganizationalUnit(JsonNode request, String caller) {+ OrganizationalUnit unit = service.updateOrganizationalUnit(caller,+ text(request, "OrganizationalUnitId"), text(request, "Name"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("OrganizationalUnit", organizationalUnitNode(unit));+ return Response.ok(response).build();+ }++ private Response deleteOrganizationalUnit(JsonNode request, String caller) {+ service.deleteOrganizationalUnit(caller, text(request, "OrganizationalUnitId"));+ return empty();+ }++ private Response describeOrganizationalUnit(JsonNode request, String caller) {+ OrganizationalUnit unit = service.describeOrganizationalUnit(caller, text(request, "OrganizationalUnitId"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("OrganizationalUnit", organizationalUnitNode(unit));+ return Response.ok(response).build();+ }++ private Response listOrganizationalUnitsForParent(JsonNode request, String caller) {+ List<OrganizationalUnit> all = service.listOrganizationalUnitsForParent(caller, text(request, "ParentId"));+ PaginatedResult<OrganizationalUnit> page = page(all, OrganizationalUnit::getId, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode units = response.putArray("OrganizationalUnits");+ page.items().forEach(unit -> units.add(organizationalUnitNode(unit)));+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ private Response listParents(JsonNode request, String caller) {+ List<OrganizationsService.ParentRef> all = service.listParents(caller, text(request, "ChildId"));+ PaginatedResult<OrganizationsService.ParentRef> page =+ page(all, OrganizationsService.ParentRef::id, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode parents = response.putArray("Parents");+ page.items().forEach(parent -> {+ ObjectNode node = parents.addObject();+ node.put("Id", parent.id());+ node.put("Type", parent.type());+ });+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ private Response listChildren(JsonNode request, String caller) {+ List<OrganizationsService.ChildRef> all =+ service.listChildren(caller, text(request, "ParentId"), text(request, "ChildType"));+ PaginatedResult<OrganizationsService.ChildRef> page = page(all, OrganizationsService.ChildRef::id, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode children = response.putArray("Children");+ page.items().forEach(child -> {+ ObjectNode node = children.addObject();+ node.put("Id", child.id());+ node.put("Type", child.type());+ });+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ // ──────────────────────────── Accounts ────────────────────────────++ private Response createAccount(JsonNode request, String caller, boolean govCloud) {+ CreateAccountStatus status = service.createAccount(caller,+ text(request, "Email"), text(request, "AccountName"), parseTags(request.path("Tags")), govCloud);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("CreateAccountStatus", createAccountStatusNode(status));+ return Response.ok(response).build();+ }++ private Response describeCreateAccountStatus(JsonNode request, String caller) {+ CreateAccountStatus status =+ service.describeCreateAccountStatus(caller, text(request, "CreateAccountRequestId"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("CreateAccountStatus", createAccountStatusNode(status));+ return Response.ok(response).build();+ }++ private Response listCreateAccountStatus(JsonNode request, String caller) {+ List<CreateAccountStatus> all = service.listCreateAccountStatus(caller, parseStringList(request.path("States")));+ PaginatedResult<CreateAccountStatus> page = page(all, CreateAccountStatus::getId, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode statuses = response.putArray("CreateAccountStatuses");+ page.items().forEach(status -> statuses.add(createAccountStatusNode(status)));+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ private Response describeAccount(JsonNode request, String caller) {+ OrganizationAccount account = service.describeAccount(caller, text(request, "AccountId"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Account", accountNode(account));+ return Response.ok(response).build();+ }++ private Response listAccounts(JsonNode request, String caller) {+ PaginatedResult<OrganizationAccount> page =+ page(service.listAccounts(caller), OrganizationAccount::getId, request);+ return accountsResponse(page);+ }++ private Response listAccountsForParent(JsonNode request, String caller) {+ List<OrganizationAccount> all = service.listAccountsForParent(caller, text(request, "ParentId"));+ return accountsResponse(page(all, OrganizationAccount::getId, request));+ }++ private Response accountsResponse(PaginatedResult<OrganizationAccount> page) {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode accounts = response.putArray("Accounts");+ page.items().forEach(account -> accounts.add(accountNode(account)));+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ private Response moveAccount(JsonNode request, String caller) {+ service.moveAccount(caller, text(request, "AccountId"),+ text(request, "SourceParentId"), text(request, "DestinationParentId"));+ return empty();+ }++ private Response removeAccountFromOrganization(JsonNode request, String caller) {+ service.removeAccountFromOrganization(caller, text(request, "AccountId"));+ return empty();+ }++ private Response leaveOrganization(String caller) {+ service.leaveOrganization(caller);+ return empty();+ }++ private Response closeAccount(JsonNode request, String caller) {+ service.closeAccount(caller, text(request, "AccountId"));+ return empty();+ }++ // ──────────────────────────── Policies ────────────────────────────++ private Response createPolicy(JsonNode request, String caller) {+ OrganizationPolicy policy = service.createPolicy(caller,+ text(request, "Content"), text(request, "Description"), text(request, "Name"),+ text(request, "Type"), parseTags(request.path("Tags")));+ return policyResponse(policy);+ }++ private Response updatePolicy(JsonNode request, String caller) {+ OrganizationPolicy policy = service.updatePolicy(caller, text(request, "PolicyId"),+ text(request, "Name"), text(request, "Description"), text(request, "Content"));+ return policyResponse(policy);+ }++ private Response deletePolicy(JsonNode request, String caller) {+ service.deletePolicy(caller, text(request, "PolicyId"));+ return empty();+ }++ private Response describePolicy(JsonNode request, String caller) {+ return policyResponse(service.describePolicy(caller, text(request, "PolicyId")));+ }++ private Response policyResponse(OrganizationPolicy policy) {+ ObjectNode response = objectMapper.createObjectNode();+ ObjectNode node = response.putObject("Policy");+ node.set("PolicySummary", policySummaryNode(policy));+ node.put("Content", policy.getContent());+ return Response.ok(response).build();+ }++ private Response listPolicies(JsonNode request, String caller) {+ List<OrganizationPolicy> all = service.listPolicies(caller, text(request, "Filter"));+ return policiesResponse(page(all, OrganizationPolicy::getId, request));+ }++ private Response listPoliciesForTarget(JsonNode request, String caller) {+ List<OrganizationPolicy> all =+ service.listPoliciesForTarget(caller, text(request, "TargetId"), text(request, "Filter"));+ return policiesResponse(page(all, OrganizationPolicy::getId, request));+ }++ private Response policiesResponse(PaginatedResult<OrganizationPolicy> page) {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode policies = response.putArray("Policies");+ page.items().forEach(policy -> policies.add(policySummaryNode(policy)));+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ private Response attachPolicy(JsonNode request, String caller) {+ service.attachPolicy(caller, text(request, "PolicyId"), text(request, "TargetId"));+ return empty();+ }++ private Response detachPolicy(JsonNode request, String caller) {+ service.detachPolicy(caller, text(request, "PolicyId"), text(request, "TargetId"));+ return empty();+ }++ private Response listTargetsForPolicy(JsonNode request, String caller) {+ List<OrganizationsService.PolicyTarget> all =+ service.listTargetsForPolicy(caller, text(request, "PolicyId"));+ PaginatedResult<OrganizationsService.PolicyTarget> page =+ page(all, OrganizationsService.PolicyTarget::targetId, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode targets = response.putArray("Targets");+ page.items().forEach(target -> {+ ObjectNode node = targets.addObject();+ node.put("TargetId", target.targetId());+ node.put("Arn", target.arn());+ node.put("Name", target.name());+ node.put("Type", target.type());+ });+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ private Response enablePolicyType(JsonNode request, String caller) {+ Root root = service.enablePolicyType(caller, text(request, "RootId"), text(request, "PolicyType"));+ return rootResponse(root);+ }++ private Response disablePolicyType(JsonNode request, String caller) {+ Root root = service.disablePolicyType(caller, text(request, "RootId"), text(request, "PolicyType"));+ return rootResponse(root);+ }++ private Response rootResponse(Root root) {+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Root", rootNode(root));+ return Response.ok(response).build();+ }++ private Response describeEffectivePolicy(JsonNode request, String caller) {+ OrganizationsService.EffectivePolicy effective =+ service.describeEffectivePolicy(caller, text(request, "PolicyType"), text(request, "TargetId"));+ ObjectNode response = objectMapper.createObjectNode();+ ObjectNode node = response.putObject("EffectivePolicy");+ node.put("PolicyContent", effective.policyContent());+ node.put("PolicyType", effective.policyType());+ node.put("TargetId", effective.targetId());+ putTimestamp(node, "LastUpdatedTimestamp", effective.lastUpdatedTimestamp());+ return Response.ok(response).build();+ }++ // ──────────────────────────── Tags ────────────────────────────++ private Response tagResource(JsonNode request, String caller) {+ service.tagResource(caller, text(request, "ResourceId"), parseTags(request.path("Tags")));+ return empty();+ }++ private Response untagResource(JsonNode request, String caller) {+ service.untagResource(caller, text(request, "ResourceId"), parseStringList(request.path("TagKeys")));+ return empty();+ }++ private Response listTagsForResource(JsonNode request, String caller) {+ Map<String, String> tags = service.listTagsForResource(caller, text(request, "ResourceId"));+ List<Map.Entry<String, String>> entries = new ArrayList<>(tags.entrySet());+ PaginatedResult<Map.Entry<String, String>> page = page(entries, Map.Entry::getKey, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode array = response.putArray("Tags");+ page.items().forEach(entry -> {+ ObjectNode node = array.addObject();+ node.put("Key", entry.getKey());+ node.put("Value", entry.getValue());+ });+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ // ──────────────────────────── Trusted access and delegation ────────────────────────────++ private Response enableAwsServiceAccess(JsonNode request, String caller) {+ service.enableAWSServiceAccess(caller, text(request, "ServicePrincipal"));+ return empty();+ }++ private Response disableAwsServiceAccess(JsonNode request, String caller) {+ service.disableAWSServiceAccess(caller, text(request, "ServicePrincipal"));+ return empty();+ }++ private Response listAwsServiceAccessForOrganization(JsonNode request, String caller) {+ List<OrganizationsService.EnabledServicePrincipal> all =+ service.listAWSServiceAccessForOrganization(caller);+ PaginatedResult<OrganizationsService.EnabledServicePrincipal> page =+ page(all, OrganizationsService.EnabledServicePrincipal::servicePrincipal, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode principals = response.putArray("EnabledServicePrincipals");+ page.items().forEach(principal -> {+ ObjectNode node = principals.addObject();+ node.put("ServicePrincipal", principal.servicePrincipal());+ putTimestamp(node, "DateEnabled", principal.dateEnabled());+ });+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ private Response registerDelegatedAdministrator(JsonNode request, String caller) {+ service.registerDelegatedAdministrator(caller, text(request, "AccountId"), text(request, "ServicePrincipal"));+ return empty();+ }++ private Response deregisterDelegatedAdministrator(JsonNode request, String caller) {+ service.deregisterDelegatedAdministrator(caller, text(request, "AccountId"), text(request, "ServicePrincipal"));+ return empty();+ }++ private Response listDelegatedAdministrators(JsonNode request, String caller) {+ String servicePrincipal = text(request, "ServicePrincipal");+ List<OrganizationAccount> all = service.listDelegatedAdministrators(caller, servicePrincipal);+ PaginatedResult<OrganizationAccount> page = page(all, OrganizationAccount::getId, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode administrators = response.putArray("DelegatedAdministrators");+ page.items().forEach(account -> {+ ObjectNode node = accountNode(account);+ Instant enabled = servicePrincipal != null+ ? account.getDelegatedServices().get(servicePrincipal)+ : account.getDelegatedServices().values().stream().findFirst().orElse(null);+ putTimestamp(node, "DelegationEnabledDate", enabled);+ administrators.add(node);+ });+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ private Response listDelegatedServicesForAccount(JsonNode request, String caller) {+ List<OrganizationsService.DelegatedService> all =+ service.listDelegatedServicesForAccount(caller, text(request, "AccountId"));+ PaginatedResult<OrganizationsService.DelegatedService> page =+ page(all, OrganizationsService.DelegatedService::servicePrincipal, request);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode services = response.putArray("DelegatedServices");+ page.items().forEach(delegated -> {+ ObjectNode node = services.addObject();+ node.put("ServicePrincipal", delegated.servicePrincipal());+ putTimestamp(node, "DelegationEnabledDate", delegated.delegationEnabledDate());+ });+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ // ──────────────────────────── Resource policy ────────────────────────────++ private Response putResourcePolicy(JsonNode request, String caller) {+ OrganizationsService.ResourcePolicyView policy =+ service.putResourcePolicy(caller, text(request, "Content"), parseTags(request.path("Tags")));+ return resourcePolicyResponse(policy);+ }++ private Response describeResourcePolicy(String caller) {+ return resourcePolicyResponse(service.describeResourcePolicy(caller));+ }++ private Response deleteResourcePolicy(String caller) {+ service.deleteResourcePolicy(caller);+ return empty();+ }++ private Response resourcePolicyResponse(OrganizationsService.ResourcePolicyView policy) {+ ObjectNode response = objectMapper.createObjectNode();+ ObjectNode node = response.putObject("ResourcePolicy");+ ObjectNode summary = node.putObject("ResourcePolicySummary");+ summary.put("Id", policy.id());+ summary.put("Arn", policy.arn());+ node.put("Content", policy.content());+ return Response.ok(response).build();+ }++ // ──────────────────────────── Handshakes ────────────────────────────++ private Response inviteAccountToOrganization(JsonNode request, String caller) {+ JsonNode target = request.path("Target");+ Handshake handshake = service.inviteAccountToOrganization(caller,+ text(target, "Id"), text(target, "Type"), text(request, "Notes"));+ return handshakeResponse(handshake);+ }++ private Response acceptHandshake(JsonNode request, String caller) {+ return handshakeResponse(service.acceptHandshake(caller, text(request, "HandshakeId")));+ }++ private Response declineHandshake(JsonNode request, String caller) {+ return handshakeResponse(service.declineHandshake(caller, text(request, "HandshakeId")));+ }++ private Response cancelHandshake(JsonNode request, String caller) {+ return handshakeResponse(service.cancelHandshake(caller, text(request, "HandshakeId")));+ }++ private Response describeHandshake(JsonNode request, String caller) {+ return handshakeResponse(service.describeHandshake(caller, text(request, "HandshakeId")));+ }++ private Response handshakeResponse(Handshake handshake) {+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Handshake", handshakeNode(handshake));+ return Response.ok(response).build();+ }++ private Response listHandshakesForAccount(JsonNode request, String caller) {+ JsonNode filter = request.path("Filter");+ List<Handshake> all = service.listHandshakesForAccount(caller,+ parseStringList(filter.path("States")), text(filter, "ActionType"));+ return handshakesResponse(page(all, Handshake::getId, request));+ }++ private Response listHandshakesForOrganization(JsonNode request, String caller) {+ JsonNode filter = request.path("Filter");+ List<Handshake> all = service.listHandshakesForOrganization(caller,+ parseStringList(filter.path("States")), text(filter, "ActionType"));+ return handshakesResponse(page(all, Handshake::getId, request));+ }++ private Response handshakesResponse(PaginatedResult<Handshake> page) {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode handshakes = response.putArray("Handshakes");+ page.items().forEach(handshake -> handshakes.add(handshakeNode(handshake)));+ putNextToken(response, page.nextToken());+ return Response.ok(response).build();+ }++ // ──────────────────────────── Response shapes ────────────────────────────++ private ObjectNode organizationNode(Organization organization) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Id", organization.getId());+ node.put("Arn", organization.getArn());+ node.put("FeatureSet", organization.getFeatureSet());+ node.put("MasterAccountArn", organization.getMasterAccountArn());+ node.put("MasterAccountId", organization.getMasterAccountId());+ node.put("MasterAccountEmail", organization.getMasterAccountEmail());+ ArrayNode policyTypes = node.putArray("AvailablePolicyTypes");+ organization.getRoot().getPolicyTypes().forEach(summary -> policyTypes.add(policyTypeNode(summary)));+ return node;+ }++ private ObjectNode rootNode(Root root) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Id", root.getId());+ node.put("Arn", root.getArn());+ node.put("Name", root.getName());+ ArrayNode policyTypes = node.putArray("PolicyTypes");+ root.getPolicyTypes().forEach(summary -> policyTypes.add(policyTypeNode(summary)));+ return node;+ }++ private ObjectNode policyTypeNode(PolicyTypeSummary summary) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Type", summary.getType());+ node.put("Status", summary.getStatus());+ return node;+ }++ private ObjectNode organizationalUnitNode(OrganizationalUnit unit) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Id", unit.getId());+ node.put("Arn", unit.getArn());+ node.put("Name", unit.getName());+ return node;+ }++ private ObjectNode accountNode(OrganizationAccount account) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Id", account.getId());+ node.put("Arn", account.getArn());+ node.put("Email", account.getEmail());+ node.put("Name", account.getName());+ node.put("Status", account.getStatus());+ node.put("JoinedMethod", account.getJoinedMethod());+ putTimestamp(node, "JoinedTimestamp", account.getJoinedTimestamp());+ return node;+ }++ private ObjectNode policySummaryNode(OrganizationPolicy policy) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Id", policy.getId());+ node.put("Arn", policy.getArn());+ node.put("Name", policy.getName());+ node.put("Description", policy.getDescription() == null ? "" : policy.getDescription());+ node.put("Type", policy.getType());+ node.put("AwsManaged", policy.isAwsManaged());+ return node;+ }++ private ObjectNode createAccountStatusNode(CreateAccountStatus status) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Id", status.getId());+ node.put("AccountName", status.getAccountName());+ node.put("State", status.getState());+ putTimestamp(node, "RequestedTimestamp", status.getRequestedTimestamp());+ putTimestamp(node, "CompletedTimestamp", status.getCompletedTimestamp());+ if (status.getAccountId() != null) {+ node.put("AccountId", status.getAccountId());+ }+ if (status.getGovCloudAccountId() != null) {+ node.put("GovCloudAccountId", status.getGovCloudAccountId());+ }+ if (status.getFailureReason() != null) {+ node.put("FailureReason", status.getFailureReason());+ }+ return node;+ }++ private ObjectNode handshakeNode(Handshake handshake) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Id", handshake.getId());+ node.put("Arn", handshake.getArn());+ node.put("State", handshake.getState());+ node.put("Action", handshake.getAction());+ putTimestamp(node, "RequestedTimestamp", handshake.getRequestedTimestamp());+ putTimestamp(node, "ExpirationTimestamp", handshake.getExpirationTimestamp());+ ArrayNode parties = node.putArray("Parties");+ for (HandshakeParty party : handshake.getParties()) {+ ObjectNode partyNode = parties.addObject();+ partyNode.put("Id", party.getId());+ partyNode.put("Type", party.getType());+ }+ ArrayNode resources = node.putArray("Resources");+ handshake.getResources().forEach(resource -> resources.add(handshakeResourceNode(resource)));+ return node;+ }++ private ObjectNode handshakeResourceNode(HandshakeResource resource) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Value", resource.getValue());+ node.put("Type", resource.getType());+ if (!resource.getResources().isEmpty()) {+ ArrayNode nested = node.putArray("Resources");+ resource.getResources().forEach(child -> nested.add(handshakeResourceNode(child)));+ }+ return node;+ }++ // ──────────────────────────── Parsing helpers ────────────────────────────++ private <T> PaginatedResult<T> page(List<T> all, Function<T, String> cursorOf, JsonNode request) {+ Integer maxResults = request.hasNonNull("MaxResults") ? request.get("MaxResults").asInt() : null;+ return Pagination.paginate(all, cursorOf, maxResults, text(request, "NextToken"), MAX_PAGE, PAGINATION_ERROR);+ }++ private void putNextToken(ObjectNode response, String nextToken) {+ if (nextToken != null) {+ response.put("NextToken", nextToken);+ }+ }++ private void putTimestamp(ObjectNode node, String field, Instant timestamp) {+ if (timestamp != null) {+ node.put(field, timestamp.toEpochMilli() / 1000.0);+ }+ }++ private Response empty() {+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private static String text(JsonNode node, String field) {+ JsonNode value = node.path(field);+ return value.isMissingNode() || value.isNull() ? null : value.asText();+ }++ /** Organizations sends tags as a list of {@code {Key, Value}} objects, not a map. */+ private static Map<String, String> parseTags(JsonNode node) {+ if (node == null || !node.isArray()) {+ return null;+ }+ Map<String, String> tags = new LinkedHashMap<>();+ node.forEach(entry -> tags.put(entry.path("Key").asText(), entry.path("Value").asText("")));+ return tags;+ }++ private static List<String> parseStringList(JsonNode node) {+ if (node == null || !node.isArray()) {+ return null;+ }+ List<String> values = new ArrayList<>();+ node.forEach(entry -> values.add(entry.asText()));+ return values;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.javanew file mode 100644index 0000000000..346954b096--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java@@ -0,0 +1,1667 @@+package io.github.hectorvent.floci.services.organizations;++import com.fasterxml.jackson.core.type.TypeReference;+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.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+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.HandshakeParty;+import io.github.hectorvent.floci.services.organizations.model.HandshakeResource;+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.PolicyTypeSummary;+import io.github.hectorvent.floci.services.organizations.model.Root;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.security.SecureRandom;+import java.time.Instant;+import java.time.temporal.ChronoUnit;+import java.util.ArrayList;+import java.util.Comparator;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.function.Consumer;+import java.util.regex.Pattern;++/**+ * AWS Organizations service implementation for the local emulator.+ *+ * <p>Organizations is a global, inherently cross-account service, which shapes how state is+ * stored here. Every record lives under the <em>management</em> account's storage prefix via the+ * explicit {@code *ForAccount} methods on {@link AccountAwareStorageBackend}, never via the+ * request-context-derived {@code get}/{@code put}. That is deliberate: a member account calling+ * {@code DescribeOrganization} has a different request account than the one that owns the data,+ * so binding reads to the caller's prefix would make the organization invisible to exactly the+ * callers AWS expects to see it. The caller's account id is used for <em>authorization</em>+ * ({@link #requireManagementAccount} vs {@link #requireOrganizationForCaller}) rather than for+ * addressing storage.+ *+ * @see <a href="https://docs.aws.amazon.com/organizations/latest/APIReference/Welcome.html">AWS Organizations API Reference</a>+ */+@ApplicationScoped+public class OrganizationsService {++ private static final Logger LOG = Logger.getLogger(OrganizationsService.class);++ private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";++ static final String FULL_AWS_ACCESS_POLICY_ID = "p-FullAWSAccess";+ private static final String FULL_AWS_ACCESS_CONTENT =+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";++ static final String SERVICE_CONTROL_POLICY = "SERVICE_CONTROL_POLICY";+ private static final String RESOURCE_CONTROL_POLICY = "RESOURCE_CONTROL_POLICY";++ /**+ * Policy types AWS accepts on CreatePolicy and Enable/DisablePolicyType.+ *+ * <p>Declared as an ordered {@link List} because the validation error message renders it:+ * {@code Set.of}'s iteration order is unspecified and salted per JVM run, so joining a set+ * would make the same rejection read differently from one run to the next. The companion+ * {@code *_SET} keeps membership checks O(1).+ */+ private static final List<String> POLICY_TYPES = List.of(+ SERVICE_CONTROL_POLICY,+ RESOURCE_CONTROL_POLICY,+ "TAG_POLICY",+ "BACKUP_POLICY",+ "AISERVICES_OPT_OUT_POLICY",+ "CHATBOT_POLICY",+ "DECLARATIVE_POLICY_EC2",+ "SECURITYHUB_POLICY");++ private static final Set<String> POLICY_TYPE_SET = Set.copyOf(POLICY_TYPES);++ /**+ * {@code DescribeEffectivePolicy} is defined only for the inheritable policy types. AWS+ * rejects the two access-control types outright — they are evaluated as a deny-by-intersection+ * chain rather than merged into a single effective document, so there is nothing to return.+ */+ private static final List<String> EFFECTIVE_POLICY_TYPES = List.of(+ "TAG_POLICY",+ "BACKUP_POLICY",+ "AISERVICES_OPT_OUT_POLICY",+ "CHATBOT_POLICY",+ "DECLARATIVE_POLICY_EC2",+ "SECURITYHUB_POLICY");++ private static final Set<String> EFFECTIVE_POLICY_TYPE_SET = Set.copyOf(EFFECTIVE_POLICY_TYPES);++ private static final String FEATURE_SET_ALL = "ALL";+ private static final String FEATURE_SET_CONSOLIDATED_BILLING = "CONSOLIDATED_BILLING";++ private static final String STATUS_ACTIVE = "ACTIVE";+ private static final String STATUS_PENDING_CLOSURE = "PENDING_CLOSURE";++ private static final String HANDSHAKE_REQUESTED = "REQUESTED";+ private static final String HANDSHAKE_ACCEPTED = "ACCEPTED";+ private static final String HANDSHAKE_DECLINED = "DECLINED";+ private static final String HANDSHAKE_CANCELED = "CANCELED";+ private static final String HANDSHAKE_EXPIRED = "EXPIRED";+ private static final String HANDSHAKE_INVITE = "INVITE";+ private static final String HANDSHAKE_ENABLE_ALL_FEATURES = "ENABLE_ALL_FEATURES";++ /** AWS holds an unaccepted handshake open for 15 days. */+ private static final int HANDSHAKE_TTL_DAYS = 15;++ private static final Pattern ACCOUNT_ID_PATTERN = Pattern.compile("\\d{12}");+ private static final Pattern ROOT_ID_PATTERN = Pattern.compile("r-[0-9a-z]{4,32}");+ private static final Pattern OU_ID_PATTERN = Pattern.compile("ou-[0-9a-z]{4,32}-[0-9a-z]{8,32}");+ private static final Pattern POLICY_ID_PATTERN = Pattern.compile("p-[0-9a-zA-Z_]{8,128}");+ private static final Pattern EMAIL_PATTERN = Pattern.compile("[^\\s@]+@[^\\s@]+\\.[^\\s@]+");+ private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}");++ private static final int MAX_ACCOUNT_NAME_LENGTH = 50;+ private static final int MAX_OU_NAME_LENGTH = 128;+ private static final int MAX_POLICY_NAME_LENGTH = 128;+ private static final int MAX_POLICY_DESCRIPTION_LENGTH = 512;+ private static final int MAX_TAG_KEY_LENGTH = 128;+ private static final int MAX_TAG_VALUE_LENGTH = 256;++ private final SecureRandom random = new SecureRandom();+ private final ObjectMapper objectMapper;++ private final AccountAwareStorageBackend<Organization> organizations;+ private final AccountAwareStorageBackend<OrganizationAccount> accounts;+ private final AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits;+ private final AccountAwareStorageBackend<OrganizationPolicy> policies;+ private final AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses;+ private final AccountAwareStorageBackend<Handshake> handshakes;++ @Inject+ public OrganizationsService(StorageFactory storageFactory, ObjectMapper objectMapper) {+ this.objectMapper = objectMapper;+ this.organizations = storageFactory.create("organizations", "organizations-organizations.json",+ new TypeReference<Map<String, Organization>>() {});+ this.accounts = storageFactory.create("organizations", "organizations-accounts.json",+ new TypeReference<Map<String, OrganizationAccount>>() {});+ this.organizationalUnits = storageFactory.create("organizations", "organizations-ous.json",+ new TypeReference<Map<String, OrganizationalUnit>>() {});+ this.policies = storageFactory.create("organizations", "organizations-policies.json",+ new TypeReference<Map<String, OrganizationPolicy>>() {});+ this.createAccountStatuses = storageFactory.create("organizations", "organizations-create-account-status.json",+ new TypeReference<Map<String, CreateAccountStatus>>() {});+ this.handshakes = storageFactory.create("organizations", "organizations-handshakes.json",+ new TypeReference<Map<String, Handshake>>() {});+ }++ OrganizationsService(ObjectMapper objectMapper,+ AccountAwareStorageBackend<Organization> organizations,+ AccountAwareStorageBackend<OrganizationAccount> accounts,+ AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,+ AccountAwareStorageBackend<OrganizationPolicy> policies,+ AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses,+ AccountAwareStorageBackend<Handshake> handshakes) {+ this.objectMapper = objectMapper;+ this.organizations = organizations;+ this.accounts = accounts;+ this.organizationalUnits = organizationalUnits;+ this.policies = policies;+ this.createAccountStatuses = createAccountStatuses;+ this.handshakes = handshakes;+ }++ /** A parent reference as returned by {@code ListParents}. */+ public record ParentRef(String id, String type) {}++ /** A child reference as returned by {@code ListChildren}. */+ public record ChildRef(String id, String type) {}++ /** A policy attachment as returned by {@code ListTargetsForPolicy}. */+ public record PolicyTarget(String targetId, String arn, String name, String type) {}++ /** A trusted-access entry as returned by {@code ListAWSServiceAccessForOrganization}. */+ public record EnabledServicePrincipal(String servicePrincipal, Instant dateEnabled) {}++ /** A delegation entry as returned by {@code ListDelegatedServicesForAccount}. */+ public record DelegatedService(String servicePrincipal, Instant delegationEnabledDate) {}++ /** The organization resource policy as returned by {@code PutResourcePolicy}. */+ public record ResourcePolicyView(String id, String arn, String content, Map<String, String> tags) {}++ /** The merged inheritance chain as returned by {@code DescribeEffectivePolicy}. */+ public record EffectivePolicy(String policyContent, String policyType, String targetId,+ Instant lastUpdatedTimestamp) {}++ // ──────────────────────────── Organization lifecycle ────────────────────────────++ public Organization createOrganization(String callerAccountId, String featureSet) {+ String resolvedFeatureSet = featureSet == null || featureSet.isEmpty() ? FEATURE_SET_ALL : featureSet;+ if (!FEATURE_SET_ALL.equals(resolvedFeatureSet)+ && !FEATURE_SET_CONSOLIDATED_BILLING.equals(resolvedFeatureSet)) {+ throw invalidInput("FeatureSet must be ALL or CONSOLIDATED_BILLING.");+ }+ findOrganizationForAccount(callerAccountId).ifPresent(existing -> {+ throw new AwsException("AlreadyInOrganizationException",+ "The provided account is already a member of an organization.", 400);+ });++ String organizationId = "o-" + randomId(10);+ String rootId = "r-" + randomId(4);++ Organization organization = new Organization();+ organization.setId(organizationId);+ organization.setArn(arn(callerAccountId, "organization/" + organizationId));+ organization.setFeatureSet(resolvedFeatureSet);+ organization.setMasterAccountId(callerAccountId);+ organization.setMasterAccountArn(arn(callerAccountId, "account/" + organizationId + "/" + callerAccountId));+ organization.setMasterAccountEmail("master@" + callerAccountId + ".example.com");+ organization.setCreatedTimestamp(Instant.now());++ Root root = new Root();+ root.setId(rootId);+ root.setArn(arn(callerAccountId, "root/" + organizationId + "/" + rootId));+ root.setName("Root");+ if (FEATURE_SET_ALL.equals(resolvedFeatureSet)) {+ root.getPolicyTypes().add(new PolicyTypeSummary(SERVICE_CONTROL_POLICY, "ENABLED"));+ }+ organization.setRoot(root);++ organizations.putForAccount(callerAccountId, organizationId, organization);++ OrganizationAccount master = new OrganizationAccount();+ master.setId(callerAccountId);+ master.setArn(organization.getMasterAccountArn());+ master.setEmail(organization.getMasterAccountEmail());+ master.setName("management-account");+ master.setStatus(STATUS_ACTIVE);+ master.setJoinedMethod("INVITED");+ master.setJoinedTimestamp(organization.getCreatedTimestamp());+ master.setOrganizationId(organizationId);+ master.setParentId(rootId);+ accounts.putForAccount(callerAccountId, callerAccountId, master);++ createFullAwsAccessPolicy(organization, rootId, callerAccountId);++ LOG.infov("Created organization {0} with root {1}", organizationId, rootId);+ return organization;+ }++ public Organization describeOrganization(String callerAccountId) {+ return requireOrganizationForCaller(callerAccountId);+ }++ public void deleteOrganization(String callerAccountId) {+ Organization organization = requireManagementAccount(callerAccountId);+ List<OrganizationAccount> members = accountsIn(organization);+ if (members.size() > 1) {+ throw new AwsException("OrganizationNotEmptyException",+ "The organization still contains accounts other than the management account. "+ + "Remove them before deleting the organization.", 400);+ }+ if (!organizationalUnitsIn(organization).isEmpty()) {+ throw new AwsException("OrganizationNotEmptyException",+ "The organization still contains organizational units. "+ + "Delete them before deleting the organization.", 400);+ }++ String master = organization.getMasterAccountId();+ policiesIn(organization).forEach(policy -> policies.deleteForAccount(master, policy.getId()));+ members.forEach(account -> accounts.deleteForAccount(master, account.getId()));+ handshakesIn(organization).forEach(handshake -> handshakes.deleteForAccount(master, handshake.getId()));+ createAccountStatusesIn(organization)+ .forEach(status -> createAccountStatuses.deleteForAccount(master, status.getId()));+ organizations.deleteForAccount(master, organization.getId());++ LOG.infov("Deleted organization {0}", organization.getId());+ }++ /**+ * Promotes a CONSOLIDATED_BILLING organization to ALL features. AWS models this as a handshake+ * that every member account must approve; with no member accounts the handshake completes+ * immediately, which is the common emulator case.+ */+ public Handshake enableAllFeatures(String callerAccountId) {+ Organization organization = requireManagementAccount(callerAccountId);+ if (FEATURE_SET_ALL.equals(organization.getFeatureSet())) {+ throw new AwsException("HandshakeConstraintViolationException",+ "The organization is already set to support all features.", 400);+ }++ Handshake handshake = newHandshake(organization, HANDSHAKE_ENABLE_ALL_FEATURES);+ handshake.getParties().add(new HandshakeParty(organization.getId(), "ORGANIZATION"));+ handshake.getResources().add(new HandshakeResource(organization.getId(), "ORGANIZATION"));++ boolean hasMembers = accountsIn(organization).size() > 1;+ if (!hasMembers) {+ handshake.setState(HANDSHAKE_ACCEPTED);+ applyEnableAllFeatures(organization);+ }+ handshakes.putForAccount(organization.getMasterAccountId(), handshake.getId(), handshake);+ return handshake;+ }++ public List<Root> listRoots(String callerAccountId) {+ return List.of(requireOrganizationForCaller(callerAccountId).getRoot());+ }++ // ──────────────────────────── Organizational units ────────────────────────────++ public OrganizationalUnit createOrganizationalUnit(String callerAccountId, String parentId, String name,+ Map<String, String> tags) {+ Organization organization = requireManagementAccount(callerAccountId);+ requireParent(organization, parentId);+ validateName(name, "Name", MAX_OU_NAME_LENGTH);+ validateTags(tags);++ boolean duplicate = organizationalUnitsIn(organization).stream()+ .anyMatch(ou -> parentId.equals(ou.getParentId()) && name.equals(ou.getName()));+ if (duplicate) {+ throw new AwsException("DuplicateOrganizationalUnitException",+ "An OU with the name " + name + " already exists under this parent.", 400);+ }++ String rootSuffix = organization.getRoot().getId().substring(2);+ String ouId = "ou-" + rootSuffix + "-" + randomId(8);++ OrganizationalUnit unit = new OrganizationalUnit();+ unit.setId(ouId);+ unit.setArn(arn(organization.getMasterAccountId(), "ou/" + organization.getId() + "/" + ouId));+ unit.setName(name);+ unit.setOrganizationId(organization.getId());+ unit.setParentId(parentId);+ if (tags != null) {+ unit.getTags().putAll(tags);+ }+ organizationalUnits.putForAccount(organization.getMasterAccountId(), ouId, unit);++ attachFullAwsAccess(organization, ouId);+ return unit;+ }++ public OrganizationalUnit updateOrganizationalUnit(String callerAccountId, String ouId, String name) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationalUnit unit = requireOrganizationalUnit(organization, ouId);+ if (name == null) {+ return unit;+ }+ validateName(name, "Name", MAX_OU_NAME_LENGTH);+ boolean duplicate = organizationalUnitsIn(organization).stream()+ .anyMatch(other -> !other.getId().equals(ouId)+ && unit.getParentId().equals(other.getParentId())+ && name.equals(other.getName()));+ if (duplicate) {+ throw new AwsException("DuplicateOrganizationalUnitException",+ "An OU with the name " + name + " already exists under this parent.", 400);+ }+ unit.setName(name);+ organizationalUnits.putForAccount(organization.getMasterAccountId(), ouId, unit);+ return unit;+ }++ public void deleteOrganizationalUnit(String callerAccountId, String ouId) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationalUnit unit = requireOrganizationalUnit(organization, ouId);++ boolean hasChildOus = organizationalUnitsIn(organization).stream()+ .anyMatch(other -> ouId.equals(other.getParentId()));+ boolean hasAccounts = accountsIn(organization).stream()+ .anyMatch(account -> ouId.equals(account.getParentId()));+ if (hasChildOus || hasAccounts) {+ throw new AwsException("OrganizationalUnitNotEmptyException",+ "The organizational unit " + ouId + " still contains accounts or other OUs.", 400);+ }++ detachAllPoliciesFrom(organization, ouId);+ organizationalUnits.deleteForAccount(organization.getMasterAccountId(), unit.getId());+ }++ public OrganizationalUnit describeOrganizationalUnit(String callerAccountId, String ouId) {+ return requireOrganizationalUnit(requireOrganizationForCaller(callerAccountId), ouId);+ }++ public List<OrganizationalUnit> listOrganizationalUnitsForParent(String callerAccountId, String parentId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ requireParent(organization, parentId);+ return organizationalUnitsIn(organization).stream()+ .filter(ou -> parentId.equals(ou.getParentId()))+ .sorted(Comparator.comparing(OrganizationalUnit::getId))+ .toList();+ }++ public List<ParentRef> listParents(String callerAccountId, String childId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ String parentId = parentOf(organization, childId);+ return List.of(new ParentRef(parentId, parentType(organization, parentId)));+ }++ public List<ChildRef> listChildren(String callerAccountId, String parentId, String childType) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ requireParent(organization, parentId);+ if (!"ACCOUNT".equals(childType) && !"ORGANIZATIONAL_UNIT".equals(childType)) {+ throw invalidInput("ChildType must be ACCOUNT or ORGANIZATIONAL_UNIT.");+ }+ if ("ACCOUNT".equals(childType)) {+ return accountsIn(organization).stream()+ .filter(account -> parentId.equals(account.getParentId()))+ .sorted(Comparator.comparing(OrganizationAccount::getId))+ .map(account -> new ChildRef(account.getId(), "ACCOUNT"))+ .toList();+ }+ return organizationalUnitsIn(organization).stream()+ .filter(ou -> parentId.equals(ou.getParentId()))+ .sorted(Comparator.comparing(OrganizationalUnit::getId))+ .map(ou -> new ChildRef(ou.getId(), "ORGANIZATIONAL_UNIT"))+ .toList();+ }++ // ──────────────────────────── Accounts ────────────────────────────++ public CreateAccountStatus createAccount(String callerAccountId, String email, String accountName,+ Map<String, String> tags, boolean govCloud) {+ Organization organization = requireManagementAccount(callerAccountId);+ validateEmail(email);+ validateName(accountName, "AccountName", MAX_ACCOUNT_NAME_LENGTH);+ validateTags(tags);++ boolean emailTaken = accountsIn(organization).stream()+ .anyMatch(account -> email.equalsIgnoreCase(account.getEmail()));++ CreateAccountStatus status = new CreateAccountStatus();+ status.setId("car-" + randomId(8));+ status.setAccountName(accountName);+ status.setRequestedTimestamp(Instant.now());+ status.setOrganizationId(organization.getId());++ if (emailTaken) {+ status.setState("FAILED");+ status.setFailureReason("EMAIL_ALREADY_EXISTS");+ status.setCompletedTimestamp(Instant.now());+ createAccountStatuses.putForAccount(organization.getMasterAccountId(), status.getId(), status);+ return status;+ }++ String newAccountId = allocateAccountId(organization);+ OrganizationAccount account = newMemberAccount(organization, newAccountId, email, accountName, "CREATED");+ accounts.putForAccount(organization.getMasterAccountId(), newAccountId, account);+ attachFullAwsAccess(organization, newAccountId);++ status.setState("SUCCEEDED");+ status.setAccountId(newAccountId);+ status.setCompletedTimestamp(Instant.now());+ if (govCloud) {+ status.setGovCloudAccountId(allocateAccountId(organization));+ }+ createAccountStatuses.putForAccount(organization.getMasterAccountId(), status.getId(), status);++ LOG.infov("Created account {0} ({1}) in organization {2}", newAccountId, accountName, organization.getId());+ return status;+ }++ public CreateAccountStatus describeCreateAccountStatus(String callerAccountId, String requestId) {+ Organization organization = requireManagementAccount(callerAccountId);+ return createAccountStatuses.getForAccount(organization.getMasterAccountId(), requestId)+ .filter(status -> organization.getId().equals(status.getOrganizationId()))+ .orElseThrow(() -> new AwsException("CreateAccountStatusNotFoundException",+ "We can't find a create account request with the id " + requestId + ".", 400));+ }++ public List<CreateAccountStatus> listCreateAccountStatus(String callerAccountId, List<String> states) {+ Organization organization = requireManagementAccount(callerAccountId);+ return createAccountStatusesIn(organization).stream()+ .filter(status -> states == null || states.isEmpty() || states.contains(status.getState()))+ .sorted(Comparator.comparing(CreateAccountStatus::getId))+ .toList();+ }++ public OrganizationAccount describeAccount(String callerAccountId, String accountId) {+ return requireAccount(requireOrganizationForCaller(callerAccountId), accountId);+ }++ public List<OrganizationAccount> listAccounts(String callerAccountId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ return accountsIn(organization).stream()+ .sorted(Comparator.comparing(OrganizationAccount::getId))+ .toList();+ }++ public List<OrganizationAccount> listAccountsForParent(String callerAccountId, String parentId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ requireParent(organization, parentId);+ return accountsIn(organization).stream()+ .filter(account -> parentId.equals(account.getParentId()))+ .sorted(Comparator.comparing(OrganizationAccount::getId))+ .toList();+ }++ public void moveAccount(String callerAccountId, String accountId, String sourceParentId,+ String destinationParentId) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationAccount account = requireAccount(organization, accountId);+ requireParent(organization, sourceParentId);+ if (!accountParentExists(organization, destinationParentId)) {+ throw new AwsException("DestinationParentNotFoundException",+ "We can't find the destination parent " + destinationParentId + ".", 400);+ }+ if (!account.getParentId().equals(sourceParentId)) {+ throw new AwsException("SourceParentNotMatchedException",+ "The account " + accountId + " is not in the source parent " + sourceParentId + ".", 400);+ }+ if (sourceParentId.equals(destinationParentId)) {+ throw new AwsException("DuplicateAccountException",+ "The account " + accountId + " is already in " + destinationParentId + ".", 400);+ }+ account.setParentId(destinationParentId);+ accounts.putForAccount(organization.getMasterAccountId(), accountId, account);+ }++ public void removeAccountFromOrganization(String callerAccountId, String accountId) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationAccount account = requireAccount(organization, accountId);+ if (accountId.equals(organization.getMasterAccountId())) {+ throw new AwsException("MasterCannotLeaveOrganizationException",+ "The management account can't be removed from the organization.", 400);+ }+ detachAllPoliciesFrom(organization, account.getId());+ accounts.deleteForAccount(organization.getMasterAccountId(), account.getId());+ }++ public void leaveOrganization(String callerAccountId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ if (callerAccountId.equals(organization.getMasterAccountId())) {+ throw new AwsException("MasterCannotLeaveOrganizationException",+ "The management account can't leave the organization.", 400);+ }+ OrganizationAccount account = requireAccount(organization, callerAccountId);+ detachAllPoliciesFrom(organization, account.getId());+ accounts.deleteForAccount(organization.getMasterAccountId(), account.getId());+ }++ public OrganizationAccount closeAccount(String callerAccountId, String accountId) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationAccount account = requireAccount(organization, accountId);+ if (accountId.equals(organization.getMasterAccountId())) {+ throw new AwsException("ConstraintViolationException",+ "The management account can't be closed.", 400);+ }+ account.setStatus(STATUS_PENDING_CLOSURE);+ accounts.putForAccount(organization.getMasterAccountId(), accountId, account);+ return account;+ }++ // ──────────────────────────── Policies ────────────────────────────++ public OrganizationPolicy createPolicy(String callerAccountId, String content, String description,+ String name, String type, Map<String, String> tags) {+ Organization organization = requireManagementAccount(callerAccountId);+ validatePolicyType(type);+ requirePolicyTypeEnabled(organization, type);+ validateName(name, "Name", MAX_POLICY_NAME_LENGTH);+ if (content == null || content.isBlank()) {+ throw invalidInput("Content must not be empty.");+ }+ if (description != null && description.length() > MAX_POLICY_DESCRIPTION_LENGTH) {+ throw invalidInput("Description must be " + MAX_POLICY_DESCRIPTION_LENGTH + " characters or fewer.");+ }+ validateTags(tags);++ boolean duplicate = policiesIn(organization).stream()+ .anyMatch(policy -> name.equals(policy.getName()) && type.equals(policy.getType()));+ if (duplicate) {+ throw new AwsException("DuplicatePolicyException",+ "A policy with the name " + name + " already exists.", 400);+ }++ OrganizationPolicy policy = new OrganizationPolicy();+ policy.setId("p-" + randomId(8));+ policy.setName(name);+ policy.setDescription(description);+ policy.setType(type);+ policy.setContent(content);+ policy.setOrganizationId(organization.getId());+ policy.setArn(policyArn(organization, policy.getId(), type));+ if (tags != null) {+ policy.getTags().putAll(tags);+ }+ policies.putForAccount(organization.getMasterAccountId(), policy.getId(), policy);+ return policy;+ }++ public OrganizationPolicy updatePolicy(String callerAccountId, String policyId, String name,+ String description, String content) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationPolicy policy = requirePolicy(organization, policyId);+ requireNotAwsManaged(policy);++ if (name != null) {+ validateName(name, "Name", MAX_POLICY_NAME_LENGTH);+ boolean duplicate = policiesIn(organization).stream()+ .anyMatch(other -> !other.getId().equals(policyId)+ && name.equals(other.getName())+ && policy.getType().equals(other.getType()));+ if (duplicate) {+ throw new AwsException("DuplicatePolicyException",+ "A policy with the name " + name + " already exists.", 400);+ }+ policy.setName(name);+ }+ if (description != null) {+ if (description.length() > MAX_POLICY_DESCRIPTION_LENGTH) {+ throw invalidInput("Description must be " + MAX_POLICY_DESCRIPTION_LENGTH + " characters or fewer.");+ }+ policy.setDescription(description);+ }+ if (content != null) {+ if (content.isBlank()) {+ throw invalidInput("Content must not be empty.");+ }+ policy.setContent(content);+ }+ policies.putForAccount(organization.getMasterAccountId(), policyId, policy);+ return policy;+ }++ public void deletePolicy(String callerAccountId, String policyId) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationPolicy policy = requirePolicy(organization, policyId);+ requireNotAwsManaged(policy);+ if (!policy.getTargets().isEmpty()) {+ throw new AwsException("PolicyInUseException",+ "The policy " + policyId + " is still attached to " + policy.getTargets().size()+ + " target(s). Detach it before deleting.", 400);+ }+ policies.deleteForAccount(organization.getMasterAccountId(), policyId);+ }++ public OrganizationPolicy describePolicy(String callerAccountId, String policyId) {+ return requirePolicy(requireOrganizationForCaller(callerAccountId), policyId);+ }++ public List<OrganizationPolicy> listPolicies(String callerAccountId, String filter) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ validatePolicyType(filter);+ return policiesIn(organization).stream()+ .filter(policy -> filter.equals(policy.getType()))+ .sorted(Comparator.comparing(OrganizationPolicy::getId))+ .toList();+ }++ public void attachPolicy(String callerAccountId, String policyId, String targetId) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationPolicy policy = requirePolicy(organization, policyId);+ requireTarget(organization, targetId);+ requirePolicyTypeEnabled(organization, policy.getType());+ if (!policy.getTargets().add(targetId)) {+ throw new AwsException("DuplicatePolicyAttachmentException",+ "The policy " + policyId + " is already attached to " + targetId + ".", 400);+ }+ policies.putForAccount(organization.getMasterAccountId(), policyId, policy);+ }++ public void detachPolicy(String callerAccountId, String policyId, String targetId) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationPolicy policy = requirePolicy(organization, policyId);+ requireTarget(organization, targetId);+ if (!policy.getTargets().contains(targetId)) {+ throw new AwsException("PolicyNotAttachedException",+ "The policy " + policyId + " is not attached to " + targetId + ".", 400);+ }+ // AWS requires every target to keep at least one SCP; detaching the last one would leave+ // it with no allow statement at all, so the API rejects it rather than silently locking+ // the target out.+ if (SERVICE_CONTROL_POLICY.equals(policy.getType())+ && countAttachedPolicies(organization, targetId, SERVICE_CONTROL_POLICY) <= 1) {+ throw new AwsException("ConstraintViolationException",+ "You can't detach the last service control policy from " + targetId + ".", 400);+ }+ policy.getTargets().remove(targetId);+ policies.putForAccount(organization.getMasterAccountId(), policyId, policy);+ }++ public List<OrganizationPolicy> listPoliciesForTarget(String callerAccountId, String targetId, String filter) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ requireTarget(organization, targetId);+ validatePolicyType(filter);+ return policiesIn(organization).stream()+ .filter(policy -> filter.equals(policy.getType()) && policy.getTargets().contains(targetId))+ .sorted(Comparator.comparing(OrganizationPolicy::getId))+ .toList();+ }++ public List<PolicyTarget> listTargetsForPolicy(String callerAccountId, String policyId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ OrganizationPolicy policy = requirePolicy(organization, policyId);+ List<PolicyTarget> targets = new ArrayList<>();+ for (String targetId : policy.getTargets()) {+ targets.add(describeTarget(organization, targetId));+ }+ targets.sort(Comparator.comparing(PolicyTarget::targetId));+ return targets;+ }++ public Root enablePolicyType(String callerAccountId, String rootId, String policyType) {+ Organization organization = requireManagementAccount(callerAccountId);+ Root root = requireRoot(organization, rootId);+ validatePolicyType(policyType);+ if (!FEATURE_SET_ALL.equals(organization.getFeatureSet())) {+ throw new AwsException("PolicyTypeNotAvailableForOrganizationException",+ "Policy type " + policyType + " requires an organization with all features enabled. "+ + "Call EnableAllFeatures first.", 400);+ }+ Optional<PolicyTypeSummary> existing = findPolicyType(root, policyType);+ if (existing.isPresent() && "ENABLED".equals(existing.get().getStatus())) {+ throw new AwsException("PolicyTypeAlreadyEnabledException",+ "The policy type " + policyType + " is already enabled.", 400);+ }+ if (existing.isPresent()) {+ existing.get().setStatus("ENABLED");+ } else {+ root.getPolicyTypes().add(new PolicyTypeSummary(policyType, "ENABLED"));+ }+ organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);+ return root;+ }++ public Root disablePolicyType(String callerAccountId, String rootId, String policyType) {+ Organization organization = requireManagementAccount(callerAccountId);+ Root root = requireRoot(organization, rootId);+ validatePolicyType(policyType);+ PolicyTypeSummary summary = findPolicyType(root, policyType)+ .filter(entry -> "ENABLED".equals(entry.getStatus()))+ .orElseThrow(() -> new AwsException("PolicyTypeNotEnabledException",+ "The policy type " + policyType + " is not enabled for this root.", 400));+ root.getPolicyTypes().remove(summary);+ organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);+ return root;+ }++ /**+ * Merges every policy of {@code policyType} down the inheritance chain root → OU(s) → target,+ * with the closest ancestor taking precedence on conflicting keys.+ */+ public EffectivePolicy describeEffectivePolicy(String callerAccountId, String policyType, String targetId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ if (policyType == null || !EFFECTIVE_POLICY_TYPE_SET.contains(policyType)) {+ throw invalidInput("PolicyType must be one of " + String.join(", ", EFFECTIVE_POLICY_TYPES) + ".");+ }+ String effectiveTarget = targetId == null || targetId.isEmpty() ? callerAccountId : targetId;+ requireTarget(organization, effectiveTarget);++ List<String> chain = ancestryOf(organization, effectiveTarget);+ ObjectNode merged = objectMapper.createObjectNode();+ boolean found = false;+ for (String node : chain) {+ for (OrganizationPolicy policy : policiesIn(organization)) {+ if (!policyType.equals(policy.getType()) || !policy.getTargets().contains(node)) {+ continue;+ }+ merged = deepMerge(merged, parsePolicyContent(policy));+ found = true;+ }+ }+ if (!found) {+ throw new AwsException("EffectivePolicyNotFoundException",+ "No policy of type " + policyType + " applies to " + effectiveTarget + ".", 400);+ }+ return new EffectivePolicy(merged.toString(), policyType, effectiveTarget, Instant.now());+ }++ // ──────────────────────────── Tags ────────────────────────────++ public Map<String, String> listTagsForResource(String callerAccountId, String resourceId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ return new LinkedHashMap<>(resolveTagOwner(organization, resourceId).tags());+ }++ public void tagResource(String callerAccountId, String resourceId, Map<String, String> tags) {+ Organization organization = requireManagementAccount(callerAccountId);+ validateTags(tags);+ mutateTags(organization, resourceId, target -> {+ if (tags != null) {+ target.putAll(tags);+ }+ });+ }++ public void untagResource(String callerAccountId, String resourceId, List<String> tagKeys) {+ Organization organization = requireManagementAccount(callerAccountId);+ mutateTags(organization, resourceId, target -> {+ if (tagKeys != null) {+ tagKeys.forEach(target::remove);+ }+ });+ }++ // ──────────────────────────── Trusted access and delegation ────────────────────────────++ public void enableAWSServiceAccess(String callerAccountId, String servicePrincipal) {+ Organization organization = requireManagementAccount(callerAccountId);+ validateServicePrincipal(servicePrincipal);+ organization.getEnabledServicePrincipals().putIfAbsent(servicePrincipal, Instant.now());+ organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);+ }++ public void disableAWSServiceAccess(String callerAccountId, String servicePrincipal) {+ Organization organization = requireManagementAccount(callerAccountId);+ validateServicePrincipal(servicePrincipal);+ boolean stillDelegated = accountsIn(organization).stream()+ .anyMatch(account -> account.getDelegatedServices().containsKey(servicePrincipal));+ if (stillDelegated) {+ throw new AwsException("ConstraintViolationException",+ "You must deregister the delegated administrators for " + servicePrincipal+ + " before disabling trusted access.", 400);+ }+ organization.getEnabledServicePrincipals().remove(servicePrincipal);+ organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);+ }++ public List<EnabledServicePrincipal> listAWSServiceAccessForOrganization(String callerAccountId) {+ Organization organization = requireManagementAccount(callerAccountId);+ return organization.getEnabledServicePrincipals().entrySet().stream()+ .map(entry -> new EnabledServicePrincipal(entry.getKey(), entry.getValue()))+ .sorted(Comparator.comparing(EnabledServicePrincipal::servicePrincipal))+ .toList();+ }++ public void registerDelegatedAdministrator(String callerAccountId, String accountId, String servicePrincipal) {+ Organization organization = requireManagementAccount(callerAccountId);+ validateServicePrincipal(servicePrincipal);+ OrganizationAccount account = requireAccount(organization, accountId);+ if (accountId.equals(organization.getMasterAccountId())) {+ throw new AwsException("ConstraintViolationException",+ "The management account can't be registered as a delegated administrator.", 400);+ }+ if (account.getDelegatedServices().containsKey(servicePrincipal)) {+ throw new AwsException("AccountAlreadyRegisteredException",+ "The account " + accountId + " is already a delegated administrator for "+ + servicePrincipal + ".", 400);+ }+ organization.getEnabledServicePrincipals().putIfAbsent(servicePrincipal, Instant.now());+ organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);+ account.getDelegatedServices().put(servicePrincipal, Instant.now());+ accounts.putForAccount(organization.getMasterAccountId(), accountId, account);+ }++ public void deregisterDelegatedAdministrator(String callerAccountId, String accountId, String servicePrincipal) {+ Organization organization = requireManagementAccount(callerAccountId);+ validateServicePrincipal(servicePrincipal);+ OrganizationAccount account = requireAccount(organization, accountId);+ if (account.getDelegatedServices().remove(servicePrincipal) == null) {+ throw new AwsException("AccountNotRegisteredException",+ "The account " + accountId + " is not a delegated administrator for "+ + servicePrincipal + ".", 400);+ }+ accounts.putForAccount(organization.getMasterAccountId(), accountId, account);+ }++ public List<OrganizationAccount> listDelegatedAdministrators(String callerAccountId, String servicePrincipal) {+ Organization organization = requireManagementAccount(callerAccountId);+ if (servicePrincipal != null) {+ validateServicePrincipal(servicePrincipal);+ }+ return accountsIn(organization).stream()+ .filter(account -> servicePrincipal == null+ ? !account.getDelegatedServices().isEmpty()+ : account.getDelegatedServices().containsKey(servicePrincipal))+ .sorted(Comparator.comparing(OrganizationAccount::getId))+ .toList();+ }++ public List<DelegatedService> listDelegatedServicesForAccount(String callerAccountId, String accountId) {+ Organization organization = requireManagementAccount(callerAccountId);+ OrganizationAccount account = requireAccount(organization, accountId);+ if (account.getDelegatedServices().isEmpty()) {+ throw new AwsException("AccountNotRegisteredException",+ "The account " + accountId + " is not a delegated administrator for any service.", 400);+ }+ return account.getDelegatedServices().entrySet().stream()+ .map(entry -> new DelegatedService(entry.getKey(), entry.getValue()))+ .sorted(Comparator.comparing(DelegatedService::servicePrincipal))+ .toList();+ }++ // ──────────────────────────── Resource policy ────────────────────────────++ public ResourcePolicyView putResourcePolicy(String callerAccountId, String content, Map<String, String> tags) {+ Organization organization = requireManagementAccount(callerAccountId);+ if (content == null || content.isBlank()) {+ throw invalidInput("Content must not be empty.");+ }+ validateTags(tags);+ if (organization.getResourcePolicyId() == null) {+ String policyId = "rp-" + randomId(8);+ organization.setResourcePolicyId(policyId);+ organization.setResourcePolicyArn(+ arn(organization.getMasterAccountId(), "resourcepolicy/" + organization.getId() + "/" + policyId));+ }+ organization.setResourcePolicyContent(content);+ if (tags != null) {+ organization.getResourcePolicyTags().putAll(tags);+ }+ organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);+ return resourcePolicyView(organization);+ }++ public ResourcePolicyView describeResourcePolicy(String callerAccountId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ if (organization.getResourcePolicyContent() == null) {+ throw new AwsException("ResourcePolicyNotFoundException",+ "The organization doesn't have a resource policy.", 400);+ }+ return resourcePolicyView(organization);+ }++ public void deleteResourcePolicy(String callerAccountId) {+ Organization organization = requireManagementAccount(callerAccountId);+ if (organization.getResourcePolicyContent() == null) {+ throw new AwsException("ResourcePolicyNotFoundException",+ "The organization doesn't have a resource policy.", 400);+ }+ organization.setResourcePolicyId(null);+ organization.setResourcePolicyArn(null);+ organization.setResourcePolicyContent(null);+ organization.getResourcePolicyTags().clear();+ organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);+ }++ // ──────────────────────────── Handshakes ────────────────────────────++ public Handshake inviteAccountToOrganization(String callerAccountId, String targetId, String targetType,+ String notes) {+ Organization organization = requireManagementAccount(callerAccountId);+ if (targetId == null || targetId.isEmpty()) {+ throw invalidInput("Target.Id is required.");+ }+ String resolvedType = targetType == null || targetType.isEmpty() ? "ACCOUNT" : targetType;+ if (!"ACCOUNT".equals(resolvedType) && !"EMAIL".equals(resolvedType)) {+ throw invalidInput("Target.Type must be ACCOUNT or EMAIL.");+ }++ String invitedAccountId = null;+ String invitedEmail = null;+ if ("ACCOUNT".equals(resolvedType)) {+ if (!ACCOUNT_ID_PATTERN.matcher(targetId).matches()) {+ throw invalidInput("Target.Id must be a 12-digit account id when Target.Type is ACCOUNT.");+ }+ invitedAccountId = targetId;+ if (accountsIn(organization).stream().anyMatch(a -> a.getId().equals(targetId))) {+ throw new AwsException("AccountAlreadyRegisteredException",+ "The account " + targetId + " is already a member of this organization.", 400);+ }+ findOrganizationForAccount(targetId).ifPresent(other -> {+ throw new AwsException("HandshakeConstraintViolationException",+ "The account " + targetId + " is already a member of another organization.", 400);+ });+ } else {+ validateEmail(targetId);+ invitedEmail = targetId;+ }++ String finalInvitedAccountId = invitedAccountId;+ String finalInvitedEmail = invitedEmail;+ boolean duplicate = handshakesIn(organization).stream()+ .filter(existing -> HANDSHAKE_REQUESTED.equals(effectiveState(existing)))+ .anyMatch(existing -> (finalInvitedAccountId != null+ && finalInvitedAccountId.equals(existing.getTargetAccountId()))+ || (finalInvitedEmail != null && finalInvitedEmail.equals(existing.getTargetEmail())));+ if (duplicate) {+ throw new AwsException("DuplicateHandshakeException",+ "An open invitation to " + targetId + " already exists.", 400);+ }++ Handshake handshake = newHandshake(organization, HANDSHAKE_INVITE);+ handshake.setTargetAccountId(invitedAccountId);+ handshake.setTargetEmail(invitedEmail);+ handshake.getParties().add(new HandshakeParty(organization.getId(), "ORGANIZATION"));+ handshake.getParties().add(new HandshakeParty(targetId, resolvedType));++ // MASTER_EMAIL and MASTER_NAME are the two child resources AWS defines on an INVITE's+ // ORGANIZATION resource. HandshakeResourceType is a closed enum, so emitting anything+ // outside it (an account id, say) deserializes as UNKNOWN_TO_SDK_VERSION in the SDK.+ HandshakeResource organizationResource = new HandshakeResource(organization.getId(), "ORGANIZATION");+ organizationResource.getResources()+ .add(new HandshakeResource(organization.getMasterAccountEmail(), "MASTER_EMAIL"));+ organizationResource.getResources()+ .add(new HandshakeResource(managementAccountName(organization), "MASTER_NAME"));+ handshake.getResources().add(organizationResource);+ handshake.getResources().add(new HandshakeResource(targetId, resolvedType));+ if (notes != null && !notes.isEmpty()) {+ handshake.getResources().add(new HandshakeResource(notes, "NOTES"));+ }++ handshakes.putForAccount(organization.getMasterAccountId(), handshake.getId(), handshake);+ return handshake;+ }++ public Handshake acceptHandshake(String callerAccountId, String handshakeId) {+ Handshake handshake = requireHandshake(handshakeId);+ Organization organization = requireOrganizationById(handshake.getOrganizationId());+ requireOpen(handshake);++ if (HANDSHAKE_ENABLE_ALL_FEATURES.equals(handshake.getAction())) {+ requireCallerInOrganization(organization, callerAccountId);+ applyEnableAllFeatures(organization);+ } else {+ requireInvitee(handshake, callerAccountId);+ if (accountsIn(organization).stream().anyMatch(a -> a.getId().equals(callerAccountId))) {+ throw new AwsException("AccountAlreadyRegisteredException",+ "The account " + callerAccountId + " is already a member of this organization.", 400);+ }+ findOrganizationForAccount(callerAccountId).ifPresent(other -> {+ throw new AwsException("HandshakeConstraintViolationException",+ "The account " + callerAccountId + " is already a member of another organization.", 400);+ });+ String email = handshake.getTargetEmail() != null+ ? handshake.getTargetEmail()+ : "account-" + callerAccountId + "@example.com";+ OrganizationAccount account = newMemberAccount(+ organization, callerAccountId, email, "invited-" + callerAccountId, "INVITED");+ accounts.putForAccount(organization.getMasterAccountId(), callerAccountId, account);+ attachFullAwsAccess(organization, callerAccountId);+ handshake.setTargetAccountId(callerAccountId);+ }++ handshake.setState(HANDSHAKE_ACCEPTED);+ handshakes.putForAccount(organization.getMasterAccountId(), handshakeId, handshake);+ return handshake;+ }++ public Handshake declineHandshake(String callerAccountId, String handshakeId) {+ Handshake handshake = requireHandshake(handshakeId);+ Organization organization = requireOrganizationById(handshake.getOrganizationId());+ requireOpen(handshake);+ requireInvitee(handshake, callerAccountId);+ handshake.setState(HANDSHAKE_DECLINED);+ handshakes.putForAccount(organization.getMasterAccountId(), handshakeId, handshake);+ return handshake;+ }++ public Handshake cancelHandshake(String callerAccountId, String handshakeId) {+ Handshake handshake = requireHandshake(handshakeId);+ Organization organization = requireOrganizationById(handshake.getOrganizationId());+ requireOpen(handshake);+ if (!organization.getMasterAccountId().equals(callerAccountId)) {+ throw accessDenied("Only the account that sent the invitation can cancel it.");+ }+ handshake.setState(HANDSHAKE_CANCELED);+ handshakes.putForAccount(organization.getMasterAccountId(), handshakeId, handshake);+ return handshake;+ }++ public Handshake describeHandshake(String callerAccountId, String handshakeId) {+ Handshake handshake = requireHandshake(handshakeId);+ Organization organization = requireOrganizationById(handshake.getOrganizationId());+ // AWS scopes DescribeHandshake to the two parties — the originating account and the+ // recipient — not to the organization at large.+ if (!organization.getMasterAccountId().equals(callerAccountId)+ && !isInvitee(handshake, callerAccountId)) {+ throw accessDenied("You don't have permission to view this handshake.");+ }+ handshake.setState(effectiveState(handshake));+ return handshake;+ }++ public List<Handshake> listHandshakesForAccount(String callerAccountId, List<String> states,+ String actionFilter) {+ // The organizations a handshake could belong to are scanned once, not once per handshake:+ // organizationById is itself a full scan, so calling it in the loop made this quadratic.+ Map<String, String> masterByOrganizationId = new LinkedHashMap<>();+ for (Organization organization : organizations.scanAllAccounts()) {+ masterByOrganizationId.put(organization.getId(), organization.getMasterAccountId());+ }++ List<Handshake> matching = new ArrayList<>();+ for (Handshake handshake : handshakes.scanAllAccounts()) {+ boolean visible = isInvitee(handshake, callerAccountId)+ || callerAccountId.equals(masterByOrganizationId.get(handshake.getOrganizationId()));+ if (visible) {+ matching.add(handshake);+ }+ }+ return filterHandshakes(matching, states, actionFilter);+ }++ public List<Handshake> listHandshakesForOrganization(String callerAccountId, List<String> states,+ String actionFilter) {+ Organization organization = requireManagementAccount(callerAccountId);+ return filterHandshakes(handshakesIn(organization), states, actionFilter);+ }++ // ──────────────────────────── Authorization ────────────────────────────++ /**+ * Resolves the organization the caller belongs to, whether as the management account or as a+ * member. A caller outside any organization gets {@code AWSOrganizationsNotInUseException},+ * which is what the AWS SDK surfaces before {@code CreateOrganization} has been called.+ */+ Organization requireOrganizationForCaller(String callerAccountId) {+ return findOrganizationForAccount(callerAccountId)+ .orElseThrow(() -> new AwsException("AWSOrganizationsNotInUseException",+ "Your account is not a member of an organization.", 400));+ }++ /** Every mutating action is management-account only, matching AWS. */+ Organization requireManagementAccount(String callerAccountId) {+ Organization organization = requireOrganizationForCaller(callerAccountId);+ if (!organization.getMasterAccountId().equals(callerAccountId)) {+ throw accessDenied("This operation can be performed only by the management account of the organization.");+ }+ return organization;+ }++ private Optional<Organization> findOrganizationForAccount(String accountId) {+ for (Organization organization : organizations.scanAllAccounts()) {+ if (accountId.equals(organization.getMasterAccountId())) {+ return Optional.of(organization);+ }+ }+ for (OrganizationAccount account : accounts.scanAllAccounts()) {+ if (accountId.equals(account.getId())) {+ Optional<Organization> organization = organizationById(account.getOrganizationId());+ if (organization.isPresent()) {+ return organization;+ }+ }+ }+ return Optional.empty();+ }++ private Optional<Organization> organizationById(String organizationId) {+ if (organizationId == null) {+ return Optional.empty();+ }+ return organizations.scanAllAccounts().stream()+ .filter(organization -> organizationId.equals(organization.getId()))+ .findFirst();+ }++ private Organization requireOrganizationById(String organizationId) {+ return organizationById(organizationId)+ .orElseThrow(() -> new AwsException("AWSOrganizationsNotInUseException",+ "The organization no longer exists.", 400));+ }++ // ──────────────────────────── Collection helpers ────────────────────────────++ private List<OrganizationAccount> accountsIn(Organization organization) {+ return accounts.scanAllAccounts().stream()+ .filter(account -> organization.getId().equals(account.getOrganizationId()))+ .toList();+ }++ private List<OrganizationalUnit> organizationalUnitsIn(Organization organization) {+ return organizationalUnits.scanAllAccounts().stream()+ .filter(ou -> organization.getId().equals(ou.getOrganizationId()))+ .toList();+ }++ private List<OrganizationPolicy> policiesIn(Organization organization) {+ return policies.scanAllAccounts().stream()+ .filter(policy -> organization.getId().equals(policy.getOrganizationId()))+ .toList();+ }++ private List<Handshake> handshakesIn(Organization organization) {+ return handshakes.scanAllAccounts().stream()+ .filter(handshake -> organization.getId().equals(handshake.getOrganizationId()))+ .toList();+ }++ private List<CreateAccountStatus> createAccountStatusesIn(Organization organization) {+ return createAccountStatuses.scanAllAccounts().stream()+ .filter(status -> organization.getId().equals(status.getOrganizationId()))+ .toList();+ }++ // ──────────────────────────── Lookup helpers ────────────────────────────++ private OrganizationAccount requireAccount(Organization organization, String accountId) {+ if (accountId == null || !ACCOUNT_ID_PATTERN.matcher(accountId).matches()) {+ throw invalidInput("Account id must be 12 digits.");+ }+ return accountsIn(organization).stream()+ .filter(account -> accountId.equals(account.getId()))+ .findFirst()+ .orElseThrow(() -> new AwsException("AccountNotFoundException",+ "We can't find an AWS account with the AccountId " + accountId + ".", 400));+ }++ private OrganizationalUnit requireOrganizationalUnit(Organization organization, String ouId) {+ if (ouId == null || !OU_ID_PATTERN.matcher(ouId).matches()) {+ throw invalidInput("OrganizationalUnitId must match ou-[0-9a-z]{4,32}-[0-9a-z]{8,32}.");+ }+ return organizationalUnitsIn(organization).stream()+ .filter(ou -> ouId.equals(ou.getId()))+ .findFirst()+ .orElseThrow(() -> new AwsException("OrganizationalUnitNotFoundException",+ "We can't find an OU with the OrganizationalUnitId " + ouId + ".", 400));+ }++ private OrganizationPolicy requirePolicy(Organization organization, String policyId) {+ if (policyId == null || !POLICY_ID_PATTERN.matcher(policyId).matches()) {+ throw invalidInput("PolicyId must match p-[0-9a-zA-Z_]{8,128}.");+ }+ return policiesIn(organization).stream()+ .filter(policy -> policyId.equals(policy.getId()))+ .findFirst()+ .orElseThrow(() -> new AwsException("PolicyNotFoundException",+ "We can't find a policy with the PolicyId " + policyId + ".", 400));+ }++ private Root requireRoot(Organization organization, String rootId) {+ if (rootId == null || !ROOT_ID_PATTERN.matcher(rootId).matches()) {+ throw invalidInput("RootId must match r-[0-9a-z]{4,32}.");+ }+ if (!organization.getRoot().getId().equals(rootId)) {+ throw new AwsException("RootNotFoundException",+ "We can't find a root with the RootId " + rootId + ".", 400);+ }+ return organization.getRoot();+ }++ private Handshake requireHandshake(String handshakeId) {+ if (handshakeId == null || handshakeId.isEmpty()) {+ throw invalidInput("HandshakeId is required.");+ }+ return handshakes.scanAllAccounts().stream()+ .filter(handshake -> handshakeId.equals(handshake.getId()))+ .findFirst()+ .orElseThrow(() -> new AwsException("HandshakeNotFoundException",+ "We can't find a handshake with the HandshakeId " + handshakeId + ".", 400));+ }++ /** A parent is the root or an OU; anything else is rejected before it can be used as one. */+ private void requireParent(Organization organization, String parentId) {+ if (parentId == null || parentId.isEmpty()) {+ throw invalidInput("ParentId is required.");+ }+ if (ROOT_ID_PATTERN.matcher(parentId).matches()) {+ requireRoot(organization, parentId);+ return;+ }+ if (OU_ID_PATTERN.matcher(parentId).matches()) {+ requireOrganizationalUnit(organization, parentId);+ return;+ }+ throw new AwsException("ParentNotFoundException",+ "We can't find a parent with the ParentId " + parentId + ".", 400);+ }++ private boolean accountParentExists(Organization organization, String parentId) {+ if (parentId == null) {+ return false;+ }+ if (organization.getRoot().getId().equals(parentId)) {+ return true;+ }+ return organizationalUnitsIn(organization).stream().anyMatch(ou -> parentId.equals(ou.getId()));+ }++ /** A policy target is the root, an OU, or an account. */+ private void requireTarget(Organization organization, String targetId) {+ if (targetId == null || targetId.isEmpty()) {+ throw invalidInput("TargetId is required.");+ }+ if (ACCOUNT_ID_PATTERN.matcher(targetId).matches()) {+ requireAccount(organization, targetId);+ return;+ }+ if (ROOT_ID_PATTERN.matcher(targetId).matches()) {+ requireRoot(organization, targetId);+ return;+ }+ if (OU_ID_PATTERN.matcher(targetId).matches()) {+ requireOrganizationalUnit(organization, targetId);+ return;+ }+ throw new AwsException("TargetNotFoundException",+ "We can't find a target with the TargetId " + targetId + ".", 400);+ }++ private PolicyTarget describeTarget(Organization organization, String targetId) {+ if (ACCOUNT_ID_PATTERN.matcher(targetId).matches()) {+ OrganizationAccount account = requireAccount(organization, targetId);+ return new PolicyTarget(account.getId(), account.getArn(), account.getName(), "ACCOUNT");+ }+ if (organization.getRoot().getId().equals(targetId)) {+ Root root = organization.getRoot();+ return new PolicyTarget(root.getId(), root.getArn(), root.getName(), "ROOT");+ }+ OrganizationalUnit unit = requireOrganizationalUnit(organization, targetId);+ return new PolicyTarget(unit.getId(), unit.getArn(), unit.getName(), "ORGANIZATIONAL_UNIT");+ }++ private String parentOf(Organization organization, String childId) {+ if (childId == null || childId.isEmpty()) {+ throw invalidInput("ChildId is required.");+ }+ if (ACCOUNT_ID_PATTERN.matcher(childId).matches()) {+ return requireAccount(organization, childId).getParentId();+ }+ if (OU_ID_PATTERN.matcher(childId).matches()) {+ return requireOrganizationalUnit(organization, childId).getParentId();+ }+ throw new AwsException("ChildNotFoundException",+ "We can't find a child with the ChildId " + childId + ".", 400);+ }++ private String parentType(Organization organization, String parentId) {+ return organization.getRoot().getId().equals(parentId) ? "ROOT" : "ORGANIZATIONAL_UNIT";+ }++ /** The chain from the root down to (and including) {@code targetId}. */+ private List<String> ancestryOf(Organization organization, String targetId) {+ List<String> chain = new ArrayList<>();+ String current = targetId;+ while (current != null && !organization.getRoot().getId().equals(current)) {+ chain.add(current);+ current = parentOf(organization, current);+ }+ chain.add(organization.getRoot().getId());+ java.util.Collections.reverse(chain);+ return chain;+ }++ // ──────────────────────────── Tag helpers ────────────────────────────++ /** A taggable resource resolved once: its live tag map plus how to write the owner back. */+ private record TagOwner(Map<String, String> tags, Runnable persist) {}++ /**+ * Resolves a taggable resource to the object that actually holds its tags. Resolving and+ * persisting have to work on the same instance — looking the owner up a second time to save it+ * would write back a copy that never saw the mutation under any non-in-memory storage mode.+ */+ private TagOwner resolveTagOwner(Organization organization, String resourceId) {+ if (resourceId == null || resourceId.isEmpty()) {+ throw invalidInput("ResourceId is required.");+ }+ String master = organization.getMasterAccountId();+ if (ACCOUNT_ID_PATTERN.matcher(resourceId).matches()) {+ OrganizationAccount account = requireAccount(organization, resourceId);+ return new TagOwner(account.getTags(),+ () -> accounts.putForAccount(master, resourceId, account));+ }+ if (ROOT_ID_PATTERN.matcher(resourceId).matches()) {+ Root root = requireRoot(organization, resourceId);+ return new TagOwner(root.getTags(),+ () -> organizations.putForAccount(master, organization.getId(), organization));+ }+ if (OU_ID_PATTERN.matcher(resourceId).matches()) {+ OrganizationalUnit unit = requireOrganizationalUnit(organization, resourceId);+ return new TagOwner(unit.getTags(),+ () -> organizationalUnits.putForAccount(master, resourceId, unit));+ }+ if (POLICY_ID_PATTERN.matcher(resourceId).matches()) {+ OrganizationPolicy policy = requirePolicy(organization, resourceId);+ return new TagOwner(policy.getTags(),+ () -> policies.putForAccount(master, resourceId, policy));+ }+ throw new AwsException("TargetNotFoundException",+ "We can't find a resource with the ResourceId " + resourceId + ".", 400);+ }++ private void mutateTags(Organization organization, String resourceId,+ Consumer<Map<String, String>> mutation) {+ TagOwner owner = resolveTagOwner(organization, resourceId);+ mutation.accept(owner.tags());+ owner.persist().run();+ }++ // ──────────────────────────── Internal helpers ────────────────────────────++ private void createFullAwsAccessPolicy(Organization organization, String rootId, String masterAccountId) {+ OrganizationPolicy policy = new OrganizationPolicy();+ policy.setId(FULL_AWS_ACCESS_POLICY_ID);+ policy.setName("FullAWSAccess");+ policy.setDescription("Allows access to every operation");+ policy.setType(SERVICE_CONTROL_POLICY);+ policy.setAwsManaged(true);+ policy.setContent(FULL_AWS_ACCESS_CONTENT);+ policy.setOrganizationId(organization.getId());+ policy.setArn(policyArn(organization, FULL_AWS_ACCESS_POLICY_ID, SERVICE_CONTROL_POLICY));+ policy.getTargets().add(rootId);+ policy.getTargets().add(masterAccountId);+ policies.putForAccount(masterAccountId, FULL_AWS_ACCESS_POLICY_ID, policy);+ }++ /**+ * AWS attaches FullAWSAccess to every new OU and account so the target is not implicitly+ * denied everything the moment it is created.+ */+ private void attachFullAwsAccess(Organization organization, String targetId) {+ policies.getForAccount(organization.getMasterAccountId(), FULL_AWS_ACCESS_POLICY_ID)+ .ifPresent(policy -> {+ policy.getTargets().add(targetId);+ policies.putForAccount(organization.getMasterAccountId(), FULL_AWS_ACCESS_POLICY_ID, policy);+ });+ }++ private void detachAllPoliciesFrom(Organization organization, String targetId) {+ for (OrganizationPolicy policy : policiesIn(organization)) {+ if (policy.getTargets().remove(targetId)) {+ policies.putForAccount(organization.getMasterAccountId(), policy.getId(), policy);+ }+ }+ }++ private int countAttachedPolicies(Organization organization, String targetId, String type) {+ return (int) policiesIn(organization).stream()+ .filter(policy -> type.equals(policy.getType()) && policy.getTargets().contains(targetId))+ .count();+ }++ private OrganizationAccount newMemberAccount(Organization organization, String accountId, String email,+ String name, String joinedMethod) {+ OrganizationAccount account = new OrganizationAccount();+ account.setId(accountId);+ account.setArn(arn(organization.getMasterAccountId(),+ "account/" + organization.getId() + "/" + accountId));+ account.setEmail(email);+ account.setName(name);+ account.setStatus(STATUS_ACTIVE);+ account.setJoinedMethod(joinedMethod);+ account.setJoinedTimestamp(Instant.now());+ account.setOrganizationId(organization.getId());+ account.setParentId(organization.getRoot().getId());+ return account;+ }++ private String allocateAccountId(Organization organization) {+ List<OrganizationAccount> existing = accountsIn(organization);+ for (int attempt = 0; attempt < 100; attempt++) {+ StringBuilder builder = new StringBuilder(12);+ builder.append(1 + random.nextInt(9));+ for (int i = 1; i < 12; i++) {+ builder.append(random.nextInt(10));+ }+ String candidate = builder.toString();+ boolean taken = existing.stream().anyMatch(account -> candidate.equals(account.getId()));+ if (!taken) {+ return candidate;+ }+ }+ throw new AwsException("ConstraintViolationException",+ "Unable to allocate a unique account id.", 400);+ }++ /** The management account's display name, falling back to its id if the record is missing. */+ private String managementAccountName(Organization organization) {+ return accountsIn(organization).stream()+ .filter(account -> account.getId().equals(organization.getMasterAccountId()))+ .map(OrganizationAccount::getName)+ .findFirst()+ .orElse(organization.getMasterAccountId());+ }++ private Handshake newHandshake(Organization organization, String action) {+ Instant now = Instant.now();+ Handshake handshake = new Handshake();+ handshake.setId("h-" + randomId(8));+ handshake.setAction(action);+ handshake.setState(HANDSHAKE_REQUESTED);+ handshake.setRequestedTimestamp(now);+ handshake.setExpirationTimestamp(now.plus(HANDSHAKE_TTL_DAYS, ChronoUnit.DAYS));+ handshake.setOrganizationId(organization.getId());+ handshake.setArn(arn(organization.getMasterAccountId(),+ "handshake/" + organization.getId() + "/" + action.toLowerCase(java.util.Locale.ROOT)+ + "/" + handshake.getId()));+ return handshake;+ }++ private void applyEnableAllFeatures(Organization organization) {+ organization.setFeatureSet(FEATURE_SET_ALL);+ if (findPolicyType(organization.getRoot(), SERVICE_CONTROL_POLICY).isEmpty()) {+ organization.getRoot().getPolicyTypes().add(new PolicyTypeSummary(SERVICE_CONTROL_POLICY, "ENABLED"));+ }+ organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);+ }++ /** A handshake left open past its expiry reports EXPIRED without needing a sweeper. */+ private String effectiveState(Handshake handshake) {+ if (HANDSHAKE_REQUESTED.equals(handshake.getState())+ && handshake.getExpirationTimestamp() != null+ && Instant.now().isAfter(handshake.getExpirationTimestamp())) {+ return HANDSHAKE_EXPIRED;+ }+ return handshake.getState();+ }++ private void requireOpen(Handshake handshake) {+ String state = effectiveState(handshake);+ if (!HANDSHAKE_REQUESTED.equals(state)) {+ throw new AwsException("InvalidHandshakeTransitionException",+ "The handshake " + handshake.getId() + " is in state " + state+ + " and can no longer be acted on.", 400);+ }+ }++ private boolean isInvitee(Handshake handshake, String accountId) {+ return accountId != null && accountId.equals(handshake.getTargetAccountId());+ }++ private void requireInvitee(Handshake handshake, String callerAccountId) {+ // An EMAIL-targeted invitation names no account up front, so any account outside the+ // organization may claim it — which is exactly how the real console flow behaves.+ if (handshake.getTargetAccountId() == null && handshake.getTargetEmail() != null) {+ return;+ }+ if (!isInvitee(handshake, callerAccountId)) {+ throw accessDenied("This handshake was not sent to your account.");+ }+ }++ private boolean isMember(Organization organization, String accountId) {+ return accountsIn(organization).stream().anyMatch(account -> account.getId().equals(accountId));+ }++ private void requireCallerInOrganization(Organization organization, String callerAccountId) {+ if (!isMember(organization, callerAccountId)) {+ throw accessDenied("Your account is not a member of this organization.");+ }+ }++ private List<Handshake> filterHandshakes(List<Handshake> candidates, List<String> states, String actionFilter) {+ for (Handshake handshake : candidates) {+ handshake.setState(effectiveState(handshake));+ }+ return candidates.stream()+ .filter(handshake -> states == null || states.isEmpty() || states.contains(handshake.getState()))+ .filter(handshake -> actionFilter == null || actionFilter.equals(handshake.getAction()))+ .sorted(Comparator.comparing(Handshake::getId))+ .toList();+ }++ private ResourcePolicyView resourcePolicyView(Organization organization) {+ return new ResourcePolicyView(+ organization.getResourcePolicyId(),+ organization.getResourcePolicyArn(),+ organization.getResourcePolicyContent(),+ new LinkedHashMap<>(organization.getResourcePolicyTags()));+ }++ private Optional<PolicyTypeSummary> findPolicyType(Root root, String policyType) {+ return root.getPolicyTypes().stream()+ .filter(entry -> entry.getType().equals(policyType))+ .findFirst();+ }++ private void requirePolicyTypeEnabled(Organization organization, String policyType) {+ boolean enabled = findPolicyType(organization.getRoot(), policyType)+ .map(entry -> "ENABLED".equals(entry.getStatus()))+ .orElse(false);+ if (!enabled) {+ throw new AwsException("PolicyTypeNotEnabledException",+ "The policy type " + policyType + " is not enabled for this organization. "+ + "Call EnablePolicyType on the root first.", 400);+ }+ }++ private void requireNotAwsManaged(OrganizationPolicy policy) {+ if (policy.isAwsManaged()) {+ throw new AwsException("ConstraintViolationException",+ "The policy " + policy.getId() + " is managed by AWS and can't be modified.", 400);+ }+ }++ private ObjectNode parsePolicyContent(OrganizationPolicy policy) {+ try {+ JsonNode parsed = objectMapper.readTree(policy.getContent());+ if (parsed instanceof ObjectNode objectNode) {+ return objectNode;+ }+ } catch (Exception e) {+ LOG.debugv(e, "Policy {0} content is not a JSON object; skipping it in the effective policy",+ policy.getId());+ }+ return objectMapper.createObjectNode();+ }++ /** Child values win, matching how AWS resolves a conflicting key further down the tree. */+ private ObjectNode deepMerge(ObjectNode parent, ObjectNode child) {+ ObjectNode merged = parent.deepCopy();+ child.fields().forEachRemaining(entry -> {+ JsonNode existing = merged.get(entry.getKey());+ if (existing instanceof ObjectNode existingObject && entry.getValue() instanceof ObjectNode childObject) {+ merged.set(entry.getKey(), deepMerge(existingObject, childObject));+ } else {+ merged.set(entry.getKey(), entry.getValue());+ }+ });+ return merged;+ }++ private String policyArn(Organization organization, String policyId, String type) {+ return arn(organization.getMasterAccountId(),+ "policy/" + organization.getId() + "/" + type.toLowerCase(java.util.Locale.ROOT) + "/" + policyId);+ }++ /** Organizations ARNs carry no region, so the region segment is deliberately empty. */+ private String arn(String accountId, String resource) {+ return AwsArnUtils.Arn.of("organizations", "", accountId, resource).toString();+ }++ private String randomId(int length) {+ StringBuilder builder = new StringBuilder(length);+ for (int i = 0; i < length; i++) {+ builder.append(ID_ALPHABET.charAt(random.nextInt(ID_ALPHABET.length())));+ }+ return builder.toString();+ }++ // ──────────────────────────── Validation ────────────────────────────++ private void validatePolicyType(String type) {+ if (type == null || !POLICY_TYPE_SET.contains(type)) {+ throw invalidInput("PolicyType must be one of " + String.join(", ", POLICY_TYPES) + ".");+ }+ }++ private void validateName(String name, String field, int maxLength) {+ if (name == null || name.isEmpty()) {+ throw invalidInput(field + " is required.");+ }+ if (name.length() > maxLength) {+ throw invalidInput(field + " must be " + maxLength + " characters or fewer.");+ }+ }++ private void validateEmail(String email) {+ if (email == null || email.isEmpty()) {+ throw invalidInput("Email is required.");+ }+ if (email.length() < 6 || email.length() > 64 || !EMAIL_PATTERN.matcher(email).matches()) {+ throw invalidInput("Email must be a valid address between 6 and 64 characters.");+ }+ }++ private void validateServicePrincipal(String servicePrincipal) {+ if (servicePrincipal == null || !SERVICE_PRINCIPAL_PATTERN.matcher(servicePrincipal).matches()) {+ throw invalidInput("ServicePrincipal must match [\\w+=,.@-]{1,128}.");+ }+ }++ private void validateTags(Map<String, String> tags) {+ if (tags == null) {+ return;+ }+ tags.forEach((key, value) -> {+ if (key == null || key.isEmpty() || key.length() > MAX_TAG_KEY_LENGTH) {+ throw invalidInput("Tag keys must be between 1 and " + MAX_TAG_KEY_LENGTH + " characters.");+ }+ if (value != null && value.length() > MAX_TAG_VALUE_LENGTH) {+ throw invalidInput("Tag values must be " + MAX_TAG_VALUE_LENGTH + " characters or fewer.");+ }+ });+ }++ private static AwsException invalidInput(String message) {+ return new AwsException("InvalidInputException", message, 400);+ }++ private static AwsException accessDenied(String message) {+ return new AwsException("AccessDeniedException", message, 403);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/CreateAccountStatus.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/CreateAccountStatus.javanew file mode 100644index 0000000000..49f15ed88d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/CreateAccountStatus.java@@ -0,0 +1,98 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;++/**+ * Tracks an asynchronous {@code CreateAccount} or {@code CreateGovCloudAccount} request.+ *+ * <p>AWS returns this in {@code IN_PROGRESS} and the caller polls+ * {@code DescribeCreateAccountStatus}. Floci completes the account synchronously but keeps the+ * record so SDK code written against the real polling contract works unchanged.+ */+@RegisterForReflection+public class CreateAccountStatus {++ private String id;+ private String accountName;+ private String state;+ private Instant requestedTimestamp;+ private Instant completedTimestamp;+ private String accountId;+ private String govCloudAccountId;+ private String failureReason;+ private String organizationId;++ public String getId() {+ return id;+ }++ public void setId(String id) {+ this.id = id;+ }++ public String getAccountName() {+ return accountName;+ }++ public void setAccountName(String accountName) {+ this.accountName = accountName;+ }++ public String getState() {+ return state;+ }++ public void setState(String state) {+ this.state = state;+ }++ public Instant getRequestedTimestamp() {+ return requestedTimestamp;+ }++ public void setRequestedTimestamp(Instant requestedTimestamp) {+ this.requestedTimestamp = requestedTimestamp;+ }++ public Instant getCompletedTimestamp() {+ return completedTimestamp;+ }++ public void setCompletedTimestamp(Instant completedTimestamp) {+ this.completedTimestamp = completedTimestamp;+ }++ public String getAccountId() {+ return accountId;+ }++ public void setAccountId(String accountId) {+ this.accountId = accountId;+ }++ public String getGovCloudAccountId() {+ return govCloudAccountId;+ }++ public void setGovCloudAccountId(String govCloudAccountId) {+ this.govCloudAccountId = govCloudAccountId;+ }++ public String getFailureReason() {+ return failureReason;+ }++ public void setFailureReason(String failureReason) {+ this.failureReason = failureReason;+ }++ public String getOrganizationId() {+ return organizationId;+ }++ public void setOrganizationId(String organizationId) {+ this.organizationId = organizationId;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/Handshake.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/Handshake.javanew file mode 100644index 0000000000..d66bcf7a83--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/Handshake.java@@ -0,0 +1,119 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.ArrayList;+import java.util.List;++/**+ * Domain model for a handshake — the two-party exchange behind+ * {@code InviteAccountToOrganization} and {@code EnableAllFeatures}.+ *+ * <p>{@code targetAccountId} and {@code targetEmail} are Floci bookkeeping, not part of the+ * AWS wire shape: they record which account (or email) the invitation was addressed to so+ * {@code ListHandshakesForAccount} can answer for a caller that has not joined yet.+ */+@RegisterForReflection+public class Handshake {++ private String id;+ private String arn;+ private String state;+ private String action;+ private Instant requestedTimestamp;+ private Instant expirationTimestamp;+ private List<HandshakeParty> parties = new ArrayList<>();+ private List<HandshakeResource> resources = new ArrayList<>();+ private String organizationId;+ private String targetAccountId;+ private String targetEmail;++ public String getId() {+ return id;+ }++ public void setId(String id) {+ this.id = id;+ }++ public String getArn() {+ return arn;+ }++ public void setArn(String arn) {+ this.arn = arn;+ }++ public String getState() {+ return state;+ }++ public void setState(String state) {+ this.state = state;+ }++ public String getAction() {+ return action;+ }++ public void setAction(String action) {+ this.action = action;+ }++ public Instant getRequestedTimestamp() {+ return requestedTimestamp;+ }++ public void setRequestedTimestamp(Instant requestedTimestamp) {+ this.requestedTimestamp = requestedTimestamp;+ }++ public Instant getExpirationTimestamp() {+ return expirationTimestamp;+ }++ public void setExpirationTimestamp(Instant expirationTimestamp) {+ this.expirationTimestamp = expirationTimestamp;+ }++ public List<HandshakeParty> getParties() {+ return parties;+ }++ public void setParties(List<HandshakeParty> parties) {+ this.parties = parties;+ }++ public List<HandshakeResource> getResources() {+ return resources;+ }++ public void setResources(List<HandshakeResource> resources) {+ this.resources = resources;+ }++ public String getOrganizationId() {+ return organizationId;+ }++ public void setOrganizationId(String organizationId) {+ this.organizationId = organizationId;+ }++ public String getTargetAccountId() {+ return targetAccountId;+ }++ public void setTargetAccountId(String targetAccountId) {+ this.targetAccountId = targetAccountId;+ }++ public String getTargetEmail() {+ return targetEmail;+ }++ public void setTargetEmail(String targetEmail) {+ this.targetEmail = targetEmail;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/HandshakeParty.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/HandshakeParty.javanew file mode 100644index 0000000000..040610d605--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/HandshakeParty.java@@ -0,0 +1,38 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * One side of a handshake. {@code type} is {@code ACCOUNT}, {@code ORGANIZATION} or+ * {@code EMAIL}, and {@code id} is interpreted accordingly.+ */+@RegisterForReflection+public class HandshakeParty {++ private String id;+ private String type;++ public HandshakeParty() {+ }++ public HandshakeParty(String id, String type) {+ this.id = id;+ this.type = type;+ }++ public String getId() {+ return id;+ }++ public void setId(String id) {+ this.id = id;+ }++ public String getType() {+ return type;+ }++ public void setType(String type) {+ this.type = type;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/HandshakeResource.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/HandshakeResource.javanew file mode 100644index 0000000000..d36165b7e0--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/HandshakeResource.java@@ -0,0 +1,51 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.List;++/**+ * A piece of information attached to a handshake. AWS nests these — the {@code ORGANIZATION}+ * resource carries {@code MASTER_EMAIL} and {@code MASTER_NAME} children — so the shape is+ * recursive.+ */+@RegisterForReflection+public class HandshakeResource {++ private String value;+ private String type;+ private List<HandshakeResource> resources = new ArrayList<>();++ public HandshakeResource() {+ }++ public HandshakeResource(String value, String type) {+ this.value = value;+ this.type = type;+ }++ public String getValue() {+ return value;+ }++ public void setValue(String value) {+ this.value = value;+ }++ public String getType() {+ return type;+ }++ public void setType(String type) {+ this.type = type;+ }++ public List<HandshakeResource> getResources() {+ return resources;+ }++ public void setResources(List<HandshakeResource> resources) {+ this.resources = resources;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/Organization.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/Organization.javanew file mode 100644index 0000000000..986df98ce0--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/Organization.java@@ -0,0 +1,139 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.Map;++/**+ * Domain model for an AWS Organization.+ *+ * <p>The organization is the anchor for every other Organizations resource: accounts, OUs and+ * policies all carry its id, which is what lets a member account resolve the organization it+ * belongs to without knowing the management account up front.+ */+@RegisterForReflection+public class Organization {++ private String id;+ private String arn;+ private String featureSet;+ private String masterAccountId;+ private String masterAccountArn;+ private String masterAccountEmail;+ private Instant createdTimestamp;+ private Root root = new Root();++ /** Service principal to the timestamp trusted access was enabled, in insertion order. */+ private Map<String, Instant> enabledServicePrincipals = new LinkedHashMap<>();++ private String resourcePolicyId;+ private String resourcePolicyArn;+ private String resourcePolicyContent;+ private Map<String, String> resourcePolicyTags = new LinkedHashMap<>();++ public String getId() {+ return id;+ }++ public void setId(String id) {+ this.id = id;+ }++ public String getArn() {+ return arn;+ }++ public void setArn(String arn) {+ this.arn = arn;+ }++ public String getFeatureSet() {+ return featureSet;+ }++ public void setFeatureSet(String featureSet) {+ this.featureSet = featureSet;+ }++ public String getMasterAccountId() {+ return masterAccountId;+ }++ public void setMasterAccountId(String masterAccountId) {+ this.masterAccountId = masterAccountId;+ }++ public String getMasterAccountArn() {+ return masterAccountArn;+ }++ public void setMasterAccountArn(String masterAccountArn) {+ this.masterAccountArn = masterAccountArn;+ }++ public String getMasterAccountEmail() {+ return masterAccountEmail;+ }++ public void setMasterAccountEmail(String masterAccountEmail) {+ this.masterAccountEmail = masterAccountEmail;+ }++ public Instant getCreatedTimestamp() {+ return createdTimestamp;+ }++ public void setCreatedTimestamp(Instant createdTimestamp) {+ this.createdTimestamp = createdTimestamp;+ }++ public Root getRoot() {+ return root;+ }++ public void setRoot(Root root) {+ this.root = root;+ }++ public Map<String, Instant> getEnabledServicePrincipals() {+ return enabledServicePrincipals;+ }++ public void setEnabledServicePrincipals(Map<String, Instant> enabledServicePrincipals) {+ this.enabledServicePrincipals = enabledServicePrincipals;+ }++ public String getResourcePolicyId() {+ return resourcePolicyId;+ }++ public void setResourcePolicyId(String resourcePolicyId) {+ this.resourcePolicyId = resourcePolicyId;+ }++ public String getResourcePolicyArn() {+ return resourcePolicyArn;+ }++ public void setResourcePolicyArn(String resourcePolicyArn) {+ this.resourcePolicyArn = resourcePolicyArn;+ }++ public String getResourcePolicyContent() {+ return resourcePolicyContent;+ }++ public void setResourcePolicyContent(String resourcePolicyContent) {+ this.resourcePolicyContent = resourcePolicyContent;+ }++ public Map<String, String> getResourcePolicyTags() {+ return resourcePolicyTags;+ }++ public void setResourcePolicyTags(Map<String, String> resourcePolicyTags) {+ this.resourcePolicyTags = resourcePolicyTags;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationAccount.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationAccount.javanew file mode 100644index 0000000000..3961d310ab--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationAccount.java@@ -0,0 +1,120 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.Map;++/**+ * Domain model for an account that belongs to an organization.+ *+ * <p>The account id doubles as a Floci account: {@code AccountResolver} treats any 12-digit+ * access key id as an account, so an account created here can immediately be used as a caller+ * identity against every other Floci service.+ */+@RegisterForReflection+public class OrganizationAccount {++ private String id;+ private String arn;+ private String email;+ private String name;+ private String status;+ private String joinedMethod;+ private Instant joinedTimestamp;+ private String organizationId;+ private String parentId;+ private Map<String, String> tags = new LinkedHashMap<>();++ /** Service principal to the timestamp this account was registered as a delegated admin. */+ private Map<String, Instant> delegatedServices = new LinkedHashMap<>();++ public String getId() {+ return id;+ }++ public void setId(String id) {+ this.id = id;+ }++ public String getArn() {+ return arn;+ }++ public void setArn(String arn) {+ this.arn = arn;+ }++ public String getEmail() {+ return email;+ }++ public void setEmail(String email) {+ this.email = email;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public String getStatus() {+ return status;+ }++ public void setStatus(String status) {+ this.status = status;+ }++ public String getJoinedMethod() {+ return joinedMethod;+ }++ public void setJoinedMethod(String joinedMethod) {+ this.joinedMethod = joinedMethod;+ }++ public Instant getJoinedTimestamp() {+ return joinedTimestamp;+ }++ public void setJoinedTimestamp(Instant joinedTimestamp) {+ this.joinedTimestamp = joinedTimestamp;+ }++ public String getOrganizationId() {+ return organizationId;+ }++ public void setOrganizationId(String organizationId) {+ this.organizationId = organizationId;+ }++ public String getParentId() {+ return parentId;+ }++ public void setParentId(String parentId) {+ this.parentId = parentId;+ }++ public Map<String, String> getTags() {+ return tags;+ }++ public void setTags(Map<String, String> tags) {+ this.tags = tags;+ }++ public Map<String, Instant> getDelegatedServices() {+ return delegatedServices;+ }++ public void setDelegatedServices(Map<String, Instant> delegatedServices) {+ this.delegatedServices = delegatedServices;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationPolicy.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationPolicy.javanew file mode 100644index 0000000000..a02caa3d38--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationPolicy.java@@ -0,0 +1,113 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.Map;+import java.util.Set;++/**+ * Domain model for an organization policy (SCP, tag policy, backup policy, and peers).+ *+ * <p>Attachments are held on the policy rather than on the target so that+ * {@code ListTargetsForPolicy} and {@code DetachPolicy} stay a single lookup; the reverse+ * direction ({@code ListPoliciesForTarget}) scans the org's policies.+ */+@RegisterForReflection+public class OrganizationPolicy {++ private String id;+ private String arn;+ private String name;+ private String description;+ private String type;+ private boolean awsManaged;+ private String content;+ private String organizationId;++ /** Root, OU and account ids this policy is attached to, in attachment order. */+ private Set<String> targets = new LinkedHashSet<>();++ private Map<String, String> tags = new LinkedHashMap<>();++ public String getId() {+ return id;+ }++ public void setId(String id) {+ this.id = id;+ }++ public String getArn() {+ return arn;+ }++ public void setArn(String arn) {+ this.arn = arn;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public String getDescription() {+ return description;+ }++ public void setDescription(String description) {+ this.description = description;+ }++ public String getType() {+ return type;+ }++ public void setType(String type) {+ this.type = type;+ }++ public boolean isAwsManaged() {+ return awsManaged;+ }++ public void setAwsManaged(boolean awsManaged) {+ this.awsManaged = awsManaged;+ }++ public String getContent() {+ return content;+ }++ public void setContent(String content) {+ this.content = content;+ }++ public String getOrganizationId() {+ return organizationId;+ }++ public void setOrganizationId(String organizationId) {+ this.organizationId = organizationId;+ }++ public Set<String> getTargets() {+ return targets;+ }++ public void setTargets(Set<String> targets) {+ this.targets = targets;+ }++ public Map<String, String> getTags() {+ return tags;+ }++ public void setTags(Map<String, String> tags) {+ this.tags = tags;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationalUnit.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationalUnit.javanew file mode 100644index 0000000000..ddec44c67d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/OrganizationalUnit.java@@ -0,0 +1,69 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.LinkedHashMap;+import java.util.Map;++/**+ * Domain model for an organizational unit. {@code parentId} is either the root id or+ * another OU id, which is what makes the hierarchy arbitrarily deep.+ */+@RegisterForReflection+public class OrganizationalUnit {++ private String id;+ private String arn;+ private String name;+ private String organizationId;+ private String parentId;+ private Map<String, String> tags = new LinkedHashMap<>();++ public String getId() {+ return id;+ }++ public void setId(String id) {+ this.id = id;+ }++ public String getArn() {+ return arn;+ }++ public void setArn(String arn) {+ this.arn = arn;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public String getOrganizationId() {+ return organizationId;+ }++ public void setOrganizationId(String organizationId) {+ this.organizationId = organizationId;+ }++ public String getParentId() {+ return parentId;+ }++ public void setParentId(String parentId) {+ this.parentId = parentId;+ }++ public Map<String, String> getTags() {+ return tags;+ }++ public void setTags(Map<String, String> tags) {+ this.tags = tags;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/PolicyTypeSummary.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/PolicyTypeSummary.javanew file mode 100644index 0000000000..0ad7611247--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/PolicyTypeSummary.java@@ -0,0 +1,38 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++/**+ * A policy type and its enablement status on a root, as returned inside+ * {@code ListRoots} and {@code DescribeOrganization}.+ */+@RegisterForReflection+public class PolicyTypeSummary {++ private String type;+ private String status;++ public PolicyTypeSummary() {+ }++ public PolicyTypeSummary(String type, String status) {+ this.type = type;+ this.status = status;+ }++ public String getType() {+ return type;+ }++ public void setType(String type) {+ this.type = type;+ }++ public String getStatus() {+ return status;+ }++ public void setStatus(String status) {+ this.status = status;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/model/Root.java b/src/main/java/io/github/hectorvent/floci/services/organizations/model/Root.javanew file mode 100644index 0000000000..a002d77916--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/model/Root.java@@ -0,0 +1,62 @@+package io.github.hectorvent.floci.services.organizations.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * The root of an organization's OU hierarchy. An organization has exactly one root,+ * so it is stored inside {@link Organization} rather than in its own backend.+ */+@RegisterForReflection+public class Root {++ private String id;+ private String arn;+ private String name = "Root";+ private List<PolicyTypeSummary> policyTypes = new ArrayList<>();+ private Map<String, String> tags = new LinkedHashMap<>();++ public String getId() {+ return id;+ }++ public void setId(String id) {+ this.id = id;+ }++ public String getArn() {+ return arn;+ }++ public void setArn(String arn) {+ this.arn = arn;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public List<PolicyTypeSummary> getPolicyTypes() {+ return policyTypes;+ }++ public void setPolicyTypes(List<PolicyTypeSummary> policyTypes) {+ this.policyTypes = policyTypes;+ }++ public Map<String, String> getTags() {+ return tags;+ }++ public void setTags(Map<String, String> tags) {+ this.tags = tags;+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 110e7158e7..947bdc3357 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -529,6 +529,8 @@ floci:enabled: truecloudhsmv2:enabled: true+ organizations:+ enabled: truerum:enabled: trueguardduty:diff --git a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsCrossAccountIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsCrossAccountIntegrationTest.javanew file mode 100644index 0000000000..7be2140803--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsCrossAccountIntegrationTest.java@@ -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\":\"[email protected]\",\"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);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsFeatureSetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsFeatureSetIntegrationTest.javanew file mode 100644index 0000000000..87f0d3e1af--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsFeatureSetIntegrationTest.java@@ -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);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsIntegrationTest.javanew file mode 100644index 0000000000..280bcdb98a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsIntegrationTest.java@@ -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\":\"[email protected]\",\"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\":\"[email protected]\",\"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("[email protected]"))+ .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("\"", "\\\"") + "\"";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.javanew file mode 100644index 0000000000..5b30282514--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java@@ -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, "[email protected]", "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, "[email protected]", "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());+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex f5b984b689..861e27ae30 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -323,6 +323,8 @@ floci:enabled: truecloudhsmv2:enabled: true+ organizations:+ enabled: truerum:enabled: trueguardduty:diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex 5137da976a..6a7a1e1a78 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -38,6 +38,10 @@ services:doc: docs/services/docdb.mdsources:- { path: src/main/java/io/github/hectorvent/floci/services/docdb/DocDbQueryHandler.java, mode: switch }+ - service: organizations+ doc: docs/services/organizations.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsJsonHandler.java, mode: switch }- service: elasticachedoc: docs/services/elasticache.mdsources: