Light, fluffy, and always free - The AWS Local Emulator alternative
fix(organizations): preconfigure the account access role in a new account (#6444)
Matheus Oliveira9242c7003a9a
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.javaindex 3bb59028ce..d215355071 100644--- 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.java@@ -11,6 +11,8 @@ 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.InvalidInputException;+import software.amazon.awssdk.services.organizations.model.InvalidInputExceptionReason;import software.amazon.awssdk.services.organizations.model.Organization;import software.amazon.awssdk.services.organizations.model.OrganizationFeatureSet;import software.amazon.awssdk.services.organizations.model.OrganizationalUnit;@@ -20,6 +22,8 @@ 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 software.amazon.awssdk.services.sts.StsClient;+import software.amazon.awssdk.services.sts.model.Credentials;import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;@@ -101,6 +105,38 @@ public class OrganizationsTest {assertThat(client.describeCreateAccountStatus(r -> r.createAccountRequestId(status.id())).createAccountStatus().accountId()).isEqualTo(memberAccountId);+ // 4b. The account access role AWS preconfigures in the new account: the management+ // account can assume it right away, and a RoleName renames it.+ try (StsClient sts = TestFixtures.stsClient()) {+ Credentials accessRoleCredentials = sts.assumeRole(r -> r+ .roleArn(TestFixtures.globalArn("iam", memberAccountId,+ "role/OrganizationAccountAccessRole"))+ .roleSessionName("compat-access-role"))+ .credentials();+ assertThat(accessRoleCredentials.accessKeyId()).startsWith("ASIA");+ assertThat(accessRoleCredentials.sessionToken()).isNotBlank();+ }++ CreateAccountStatus customRoleAccount = client.createAccount(r -> r+ .email("[email protected]").accountName("CompatRole")+ .roleName("CompatAccessRole")).createAccountStatus();+ assertThat(customRoleAccount.state()).isEqualTo(CreateAccountState.SUCCEEDED);+ try (StsClient sts = TestFixtures.stsClient()) {+ assertThat(sts.assumeRole(r -> r+ .roleArn(TestFixtures.globalArn("iam", customRoleAccount.accountId(),+ "role/CompatAccessRole"))+ .roleSessionName("compat-access-role"))+ .credentials().accessKeyId()).startsWith("ASIA");+ }++ // 4c. The RoleName the reference refuses, with the Reason member an SDK caller reads.+ assertThatThrownBy(() -> client.createAccount(r -> r+ .email("[email protected]").accountName("CompatBad")+ .roleName("AWSServiceRoleForOrganizations")))+ .isInstanceOfSatisfying(InvalidInputException.class, error ->+ assertThat(error.reason())+ .isEqualTo(InvalidInputExceptionReason.INVALID_ROLE_NAME));+Account member = client.describeAccount(r -> r.accountId(memberAccountId)).account();assertThat(member.email()).isEqualTo("[email protected]");assertThat(member.name()).isEqualTo("CompatDev");@@ -242,6 +278,7 @@ public class OrganizationsTest {// 11. Tear the organization down.client.removeAccountFromOrganization(r -> r.accountId(memberAccountId));+ client.removeAccountFromOrganization(r -> r.accountId(customRoleAccount.accountId()));client.deleteOrganizationalUnit(r -> r.organizationalUnitId(production.id()));client.deleteOrganizationalUnit(r -> r.organizationalUnitId(workloads.id()));} finally {diff --git a/docs/services/organizations.md b/docs/services/organizations.mdindex b29435af10..41f4fb2853 100644--- a/docs/services/organizations.md+++ b/docs/services/organizations.md@@ -59,6 +59,15 @@ call `LeaveOrganization`. An account in no organization gets- `CreateAccount` returns a `CreateAccountStatus` you can poll with`DescribeCreateAccountStatus`, matching the asynchronous AWS contract. A duplicate emailproduces `State=FAILED` with `FailureReason=EMAIL_ALREADY_EXISTS` rather than an error.+- As on AWS, `CreateAccount` preconfigures the account access role in the new member account:+ the optional `RoleName` parameter names it, defaulting to `OrganizationAccountAccessRole`.+ The role exists in the new account, its trust policy allows the management account+ (`arn:<partition>:iam::<management-account-id>:root` to `sts:AssumeRole`), and it carries the+ `AdministratorAccess` AWS-managed policy, so the management account can assume it immediately.+ Accounts that join through `InviteAccountToOrganization` do not get the role, matching AWS.+ A `RoleName` off the published pattern answers `InvalidInputException` with the reference's+ `Reason` member (`INVALID_PATTERN`, or `INVALID_ROLE_NAME` for the reserved+ `AWSServiceRoleFor` prefix), so SDK callers can read the cause.- `DescribeEffectivePolicy` merges every policy of the requested type down theroot → 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.diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex 0fdec56b01..f3197b2c27 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.CertificateMaterialException;import io.github.hectorvent.floci.core.common.Pem;import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.RequestScopes;import io.github.hectorvent.floci.core.common.ServicePrincipals;import io.github.hectorvent.floci.core.common.SessionAccountLookup;import io.github.hectorvent.floci.core.common.SmithyValidationErrors;@@ -1221,6 +1222,44 @@ public class IamService implements SessionAccountLookup, ResourceProvider {return roles.get(roleName);}+ /**+ * Creates the account access role AWS Organizations preconfigures in a member account it+ * just created ({@code CreateAccount}'s {@code RoleName}, default+ * {@code OrganizationAccountAccessRole}), in that account's own namespace: the+ * management account is the caller here, so the whole creation runs inside+ * {@link RequestScopes#callAs(String, Supplier)} as the new account, and+ * {@link #createRole} and {@link #attachRolePolicy} validate the name, mint the ARN+ * and store the role the way every other IAM role goes.+ *+ * <p>The role matches the one AWS creates: it trusts the management account, through the+ * account-root principal AWS's generated trust policy names, and carries the+ * {@code AdministratorAccess} AWS-managed policy. The account is fresh, so the name+ * cannot collide; a role that is there anyway is returned rather than failing an account+ * creation AWS would have completed: {@link #createRole} answers+ * {@code EntityAlreadyExists} for it, that one error is caught here, and anything+ * else propagates.+ */+ public IamRole provisionAccountAccessRole(String accountId, String roleName, String managementAccountId) {+ String trustPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","+ + "\"Principal\":{\"AWS\":\"" + regionResolver.buildGlobalArn("iam", managementAccountId, "root")+ + "\"},\"Action\":\"sts:AssumeRole\"}]}";+ String administratorAccess = AwsManagedPolicies.arnPrefix(regionResolver.getPartition())+ + "/AdministratorAccess";+ return RequestScopes.callAs(accountId, () -> {+ try {+ IamRole role = createRole(roleName, "/", trustPolicy, null, 0, null);+ attachRolePolicy(roleName, administratorAccess);+ LOG.infov("Created account access role {0} in account {1}", roleName, accountId);+ return role;+ } catch (AwsException alreadyExists) {+ if (!"EntityAlreadyExists".equals(alreadyExists.getErrorCode())) {+ throw alreadyExists;+ }+ return getRole(roleName);+ }+ });+ }+/*** roleDescriptionType: at most 1000 characters of the set AWS publishes, which admits tab,* newline and carriage return and no other control character. Enforced wherever a rolediff --git a/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccountAccessRoleProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccountAccessRoleProvisioner.javanew file mode 100644index 0000000000..5f1ed102b1--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccountAccessRoleProvisioner.java@@ -0,0 +1,27 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.services.organizations.AccountAccessRoleProvisioner;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++/**+ * Creates the account access role Organizations preconfigures in each member account, through+ * IAM's own role creation so storage, validation and ARN minting stay identical to+ * {@code CreateRole}'s. {@code OrganizationsService} depends only on the interface, the way+ * IAM's reads of organization policy depend only on {@code ScpProvider}.+ */+@ApplicationScoped+public class OrganizationsAccountAccessRoleProvisioner implements AccountAccessRoleProvisioner {++ private final IamService iamService;++ @Inject+ public OrganizationsAccountAccessRoleProvisioner(IamService iamService) {+ this.iamService = iamService;+ }++ @Override+ public void provision(String memberAccountId, String roleName, String managementAccountId) {+ iamService.provisionAccountAccessRole(memberAccountId, roleName, managementAccountId);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/organizations/AccountAccessRoleProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/organizations/AccountAccessRoleProvisioner.javanew file mode 100644index 0000000000..68808fb279--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/AccountAccessRoleProvisioner.java@@ -0,0 +1,27 @@+package io.github.hectorvent.floci.services.organizations;++/**+ * Creates the IAM role AWS Organizations preconfigures in each member account it creates:+ * {@code CreateAccount}'s {@code RoleName} parameter, defaulting to+ * {@code OrganizationAccountAccessRole}, trusting the management account (Organizations+ * User Guide, "Creating a member account in your organization").+ *+ * <p>Organizations says what the new account gets; IAM owns how the role is created, so the+ * implementation lives with IAM and the role is stored and its ARN minted the way every other+ * IAM role is. The interface keeps the two services decoupled the way+ * {@code ScpProvider} decouples IAM's reads of organization policy from Organizations.+ */+public interface AccountAccessRoleProvisioner {++ /** A provisioner that creates nothing, for callers that only exercise the service shape. */+ AccountAccessRoleProvisioner NOOP = (memberAccountId, roleName, managementAccountId) -> { };++ /**+ * Creates {@code roleName} in {@code memberAccountId}, trusting {@code managementAccountId}.+ *+ * @param memberAccountId the account CreateAccount just created, which owns the role+ * @param roleName the role name to create, already defaulted and validated by the caller+ * @param managementAccountId the organization's management account, the trusted principal+ */+ void provision(String memberAccountId, String roleName, String managementAccountId);+}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.javaindex 328fa06653..25be75a66f 100644--- a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsJsonHandler.java@@ -247,7 +247,8 @@ public class OrganizationsJsonHandler {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);+ text(request, "Email"), text(request, "AccountName"), parseTags(request.path("Tags")),+ text(request, "RoleName"), govCloud);ObjectNode response = objectMapper.createObjectNode();response.set("CreateAccountStatus", createAccountStatusNode(status));return Response.ok(response).build();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.javaindex ec8eb101bb..38b8f10e3d 100644--- a/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/organizations/OrganizationsService.java@@ -127,6 +127,12 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganizationprivate static final String STATUS_ACTIVE = "ACTIVE";private static final String STATUS_PENDING_CLOSURE = "PENDING_CLOSURE";+ /** CreateAccount's RoleName default, the role AWS preconfigures in every account it creates. */+ private static final String DEFAULT_ACCOUNT_ACCESS_ROLE_NAME = "OrganizationAccountAccessRole";+ /** The RoleName pattern CreateAccount publishes, which also refuses the reserved prefix. */+ private static final Pattern ACCOUNT_ACCESS_ROLE_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]{1,64}");+ private static final String AWS_SERVICE_ROLE_PREFIX = "AWSServiceRoleFor";+private static final String HANDSHAKE_REQUESTED = "REQUESTED";private static final String HANDSHAKE_ACCEPTED = "ACCEPTED";private static final String HANDSHAKE_DECLINED = "DECLINED";@@ -164,10 +170,12 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganizationprivate final RegionResolver regionResolver;private final boolean scpEnforcementEnabled;private final String managementAccountEmail;+ private final AccountAccessRoleProvisioner accountAccessRoleProvisioner;@Injectpublic OrganizationsService(StorageFactory storageFactory, ObjectMapper objectMapper,- EmulatorConfig config, RegionResolver regionResolver) {+ EmulatorConfig config, RegionResolver regionResolver,+ AccountAccessRoleProvisioner accountAccessRoleProvisioner) {EmulatorConfig.OrganizationsServiceConfig organizationsConfig = config.services().organizations();this.scpEnforcementEnabled = organizationsConfig.scpEnforcementEnabled();this.managementAccountEmail = organizationsConfig.managementAccountEmail()@@ -175,6 +183,7 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization.orElse(null);this.objectMapper = objectMapper;this.regionResolver = regionResolver;+ this.accountAccessRoleProvisioner = accountAccessRoleProvisioner;this.organizations = storageFactory.create("organizations", "organizations-organizations.json",new TypeReference<Map<String, Organization>>() {});this.accounts = storageFactory.create("organizations", "organizations-accounts.json",@@ -224,6 +233,22 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganizationAccountAwareStorageBackend<Handshake> handshakes,boolean scpEnforcementEnabled,String managementAccountEmail) {+ this(objectMapper, regionResolver, organizations, accounts, organizationalUnits, policies,+ createAccountStatuses, handshakes, scpEnforcementEnabled, managementAccountEmail,+ AccountAccessRoleProvisioner.NOOP);+ }++ OrganizationsService(ObjectMapper objectMapper,+ RegionResolver regionResolver,+ AccountAwareStorageBackend<Organization> organizations,+ AccountAwareStorageBackend<OrganizationAccount> accounts,+ AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,+ AccountAwareStorageBackend<OrganizationPolicy> policies,+ AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses,+ AccountAwareStorageBackend<Handshake> handshakes,+ boolean scpEnforcementEnabled,+ String managementAccountEmail,+ AccountAccessRoleProvisioner accountAccessRoleProvisioner) {this.objectMapper = objectMapper;this.regionResolver = regionResolver;this.organizations = organizations;@@ -236,6 +261,7 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganizationthis.managementAccountEmail = managementAccountEmail == null? null: requireValidConfiguredEmail(managementAccountEmail);+ this.accountAccessRoleProvisioner = accountAccessRoleProvisioner;}/** A parent reference as returned by {@code ListParents}. */@@ -574,10 +600,22 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganizationpublic CreateAccountStatus createAccount(String callerAccountId, String email, String accountName,Map<String, String> tags, boolean govCloud) {+ return createAccount(callerAccountId, email, accountName, tags, null, govCloud);+ }++ /**+ * Creates a member account and preconfigures its access role, the way AWS does+ * (CreateAccount reference): the role, named by {@code roleName} or defaulted, exists in+ * the new account, trusts the management account and carries administrator permissions,+ * so the management account can assume it with {@code sts:AssumeRole}.+ */+ public CreateAccountStatus createAccount(String callerAccountId, String email, String accountName,+ Map<String, String> tags, String roleName, boolean govCloud) {Organization organization = requireManagementAccount(callerAccountId);validateEmail(email);validateName(accountName, "AccountName", MAX_ACCOUNT_NAME_LENGTH);validateTags(tags);+ validateAccountAccessRoleName(roleName);boolean emailTaken = accountsIn(organization).stream().anyMatch(account -> email.equalsIgnoreCase(account.getEmail()));@@ -600,6 +638,9 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganizationOrganizationAccount account = newMemberAccount(organization, newAccountId, email, accountName, "CREATED");accounts.putForAccount(organization.getMasterAccountId(), newAccountId, account);attachFullAwsAccess(organization, newAccountId);+ accountAccessRoleProvisioner.provision(newAccountId,+ roleName == null ? DEFAULT_ACCOUNT_ACCESS_ROLE_NAME : roleName,+ organization.getMasterAccountId());status.setState("SUCCEEDED");status.setAccountId(newAccountId);@@ -2048,10 +2089,39 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization});}+ /**+ * CreateAccount's optional RoleName, when sent: the pattern the reference publishes+ * ({@code [\w+=,.@-]{1,64}}) plus the reserved prefix its InvalidInputException reasons+ * list refuses (INVALID_ROLE_NAME: a role name can't begin with AWSServiceRoleFor). An+ * absent name is the caller saying "default", so it passes and is defaulted later. The+ * reference answers a value off the pattern with INVALID_PATTERN, and both reasons ride+ * the error's Reason member, which the SDKs read off InvalidInputException.+ */+ private void validateAccountAccessRoleName(String roleName) {+ if (roleName == null) {+ return;+ }+ if (!ACCOUNT_ACCESS_ROLE_NAME_PATTERN.matcher(roleName).matches()) {+ throw invalidInput("RoleName must be 1-64 characters matching [\\w+=,.@-].", "INVALID_PATTERN");+ }+ if (roleName.startsWith(AWS_SERVICE_ROLE_PREFIX)) {+ throw invalidInput("RoleName can't begin with the reserved prefix AWSServiceRoleFor.",+ "INVALID_ROLE_NAME");+ }+ }+private static AwsException invalidInput(String message) {return new AwsException("InvalidInputException", message, 400);}+ /**+ * {@link #invalidInput(String)} carrying a Reason member, the way CreateAccount's+ * reference reports its InvalidInputException causes.+ */+ private static AwsException invalidInput(String message, String reason) {+ return new AwsException("InvalidInputException", message, 400, Map.of("Reason", reason));+ }+private static AwsException accessDenied(String message) {return new AwsException("AccessDeniedException", message, 400);}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.javaindex 79a9b5775d..92e1a9c31a 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java@@ -1569,6 +1569,30 @@ class IamServiceTest {assertEquals(409, error.getHttpStatus());}+ @Test+ void provisionAccountAccessRoleCreatesTheRoleTrustedByTheManagementAccount() {+ IamRole role = iamService.provisionAccountAccessRole(+ "111111111111", "OrganizationAccountAccessRole", "000000000000");++ assertEquals("OrganizationAccountAccessRole", role.getRoleName());+ assertEquals("arn:aws:iam::000000000000:role/OrganizationAccountAccessRole", role.getArn());+ assertTrue(role.getAssumeRolePolicyDocument()+ .contains("\"Principal\":{\"AWS\":\"arn:aws:iam::000000000000:root\"}"));+ assertTrue(role.getAssumeRolePolicyDocument().contains("sts:AssumeRole"));+ assertEquals(List.of("arn:aws:iam::aws:policy/AdministratorAccess"),+ iamService.getRole("OrganizationAccountAccessRole").getAttachedPolicyArns());+ }++ @Test+ void provisionAccountAccessRoleReturnsTheRoleThatIsAlreadyThere() {+ IamRole existing = iamService.createRole("OrganizationAccountAccessRole", "/", "{}", null, 3600, null);++ IamRole role = iamService.provisionAccountAccessRole(+ "000000000000", "OrganizationAccountAccessRole", "000000000000");++ assertEquals(existing.getRoleId(), role.getRoleId());+ }+@Testvoid updateAssumeRolePolicyWithMatchingExpectedIdApplies() {IamRole role = iamService.createRole("LambdaExec", "/", "{}", null, 3600, null);diff --git a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsAccountAccessRoleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsAccountAccessRoleIntegrationTest.javanew file mode 100644index 0000000000..441897ad44--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsAccountAccessRoleIntegrationTest.java@@ -0,0 +1,238 @@+package io.github.hectorvent.floci.services.organizations;++import io.github.hectorvent.floci.testing.EnforcementFixtures;+import io.github.hectorvent.floci.testing.OrganizationsRequests;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.path.json.JsonPath;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.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.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.matchesPattern;+import static org.hamcrest.Matchers.notNullValue;++/**+ * The account access role CreateAccount preconfigures in each member account, end to end as+ * the issue reports it: create the organization, create the account, then assume the new+ * account's OrganizationAccountAccessRole with STS.+ *+ * <p>Runs as its own management account, like {@link OrganizationsCrossAccountIntegrationTest},+ * so it never contends for one with the other Organizations suites.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+@TestInstance(TestInstance.Lifecycle.PER_CLASS)+class OrganizationsAccountAccessRoleIntegrationTest {++ private static final String MANAGEMENT_ACCOUNT = "666666666666";++ private String memberAccountId;+ private String createAccountRequestId;+ private String customRoleAccountId;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ private RequestSpecification sts(String roleArn) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", EnforcementFixtures.auth(MANAGEMENT_ACCOUNT, "sts"))+ .formParam("Action", "AssumeRole")+ .formParam("RoleArn", roleArn)+ .formParam("RoleSessionName", "management-check");+ }++ private RequestSpecification iamAsMember(String accountId, String action, String roleName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", EnforcementFixtures.auth(accountId, "iam"))+ .formParam("Action", action)+ .formParam("RoleName", roleName);+ }++ @Test+ @Order(1)+ void createOrganizationAsManagementAccount() {+ OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Organization.MasterAccountId", equalTo(MANAGEMENT_ACCOUNT));+ }++ @Test+ @Order(2)+ void createAccountReportsSuccess() {+ JsonPath response = OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "CreateAccount",+ "{\"Email\":\"[email protected]\",\"AccountName\":\"Member\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("CreateAccountStatus.State", equalTo("SUCCEEDED"))+ .body("CreateAccountStatus.AccountId", matchesPattern("\\d{12}"))+ .extract().jsonPath();++ memberAccountId = response.getString("CreateAccountStatus.AccountId");+ createAccountRequestId = response.getString("CreateAccountStatus.Id");+ }++ @Test+ @Order(3)+ void describeCreateAccountStatusStillReportsSucceeded() {+ OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "DescribeCreateAccountStatus",+ "{\"CreateAccountRequestId\":\"" + createAccountRequestId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("CreateAccountStatus.State", equalTo("SUCCEEDED"))+ .body("CreateAccountStatus.AccountId", equalTo(memberAccountId));+ }++ @Test+ @Order(4)+ void theManagementAccountCanAssumeThePreconfiguredRole() {+ sts("arn:aws:iam::" + memberAccountId + ":role/OrganizationAccountAccessRole")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", notNullValue())+ .body("AssumeRoleResponse.AssumeRoleResult.Credentials.SecretAccessKey", notNullValue())+ .body("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken", notNullValue())+ .body("AssumeRoleResponse.AssumeRoleResult.Credentials.Expiration", notNullValue())+ .body("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn",+ equalTo("arn:aws:sts::" + memberAccountId+ + ":assumed-role/OrganizationAccountAccessRole/management-check"));+ }++ @Test+ @Order(5)+ void theRoleLivesInTheMemberAccountAndTrustsTheManagementAccount() {+ iamAsMember(memberAccountId, "GetRole", "OrganizationAccountAccessRole")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetRoleResponse.GetRoleResult.Role.Arn",+ equalTo("arn:aws:iam::" + memberAccountId + ":role/OrganizationAccountAccessRole"))+ .body("GetRoleResponse.GetRoleResult.Role.AssumeRolePolicyDocument",+ containsString("\"Principal\":{\"AWS\":\"arn:aws:iam::" + MANAGEMENT_ACCOUNT + ":root\"}"))+ .body("GetRoleResponse.GetRoleResult.Role.AssumeRolePolicyDocument",+ containsString("sts:AssumeRole"));++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", EnforcementFixtures.auth(memberAccountId, "iam"))+ .formParam("Action", "ListAttachedRolePolicies")+ .formParam("RoleName", "OrganizationAccountAccessRole")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("ListAttachedRolePoliciesResponse.ListAttachedRolePoliciesResult"+ + ".AttachedPolicies.member.PolicyName", equalTo("AdministratorAccess"))+ .body("ListAttachedRolePoliciesResponse.ListAttachedRolePoliciesResult"+ + ".AttachedPolicies.member.PolicyArn",+ equalTo("arn:aws:iam::aws:policy/AdministratorAccess"));++ iamAsMember(MANAGEMENT_ACCOUNT, "GetRole", "OrganizationAccountAccessRole")+ .when()+ .post("/")+ .then()+ .statusCode(404)+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));+ }++ @Test+ @Order(6)+ void createAccountWithACustomRoleNameProvisionsThatName() {+ customRoleAccountId = OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "CreateAccount",+ "{\"Email\":\"[email protected]\",\"AccountName\":\"Custom\",\"RoleName\":\"TeamAccessRole\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("CreateAccountStatus.State", equalTo("SUCCEEDED"))+ .extract().jsonPath().getString("CreateAccountStatus.AccountId");++ iamAsMember(customRoleAccountId, "GetRole", "TeamAccessRole")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("GetRoleResponse.GetRoleResult.Role.Arn",+ equalTo("arn:aws:iam::" + customRoleAccountId + ":role/TeamAccessRole"));++ sts("arn:aws:iam::" + customRoleAccountId + ":role/TeamAccessRole")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("AssumeRoleResponse.AssumeRoleResult.AssumedRoleUser.Arn",+ equalTo("arn:aws:sts::" + customRoleAccountId+ + ":assumed-role/TeamAccessRole/management-check"));+ }++ @Test+ @Order(7)+ void aRoleNameWithTheReservedPrefixIsRejectedWithItsReason() {+ OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "CreateAccount",+ "{\"Email\":\"[email protected]\",\"AccountName\":\"Bad\",\"RoleName\":\"AWSServiceRoleForOrganizations\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidInputException"))+ .body("Reason", equalTo("INVALID_ROLE_NAME"));+ }++ @Test+ @Order(8)+ void aRoleNameOffThePatternIsRejectedWithItsReason() {+ OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "CreateAccount",+ "{\"Email\":\"[email protected]\",\"AccountName\":\"Bad\",\"RoleName\":\"bad name\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidInputException"))+ .body("Reason", equalTo("INVALID_PATTERN"));+ }++ @Test+ @Order(90)+ void tearDownOrganization() {+ OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "RemoveAccountFromOrganization",+ "{\"AccountId\":\"" + memberAccountId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "RemoveAccountFromOrganization",+ "{\"AccountId\":\"" + customRoleAccountId + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ OrganizationsRequests.request(MANAGEMENT_ACCOUNT, "DeleteOrganization", "{}")+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }+}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.javaindex 1f506fea35..36bb7c8a1b 100644--- a/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/organizations/OrganizationsServiceTest.java@@ -17,6 +17,7 @@ import org.junit.jupiter.params.provider.ValueSource;import java.time.Instant;import java.time.temporal.ChronoUnit;+import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set;@@ -61,7 +62,7 @@ class OrganizationsServiceTest {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());+ assertTrue(organization.getRoot().getId().matches("r-[0-9a-z]{4}"), organization.getRoot().getId());String rootSuffix = organization.getRoot().getId().substring(2);OrganizationalUnit unit =@@ -79,6 +80,90 @@ class OrganizationsServiceTest {assertTrue(status.getAccountId().matches("\\d{12}"), status.getAccountId());}+ /** The (member account, role name, management account) triples a provisioner received. */+ private static final class RecordedProvisions implements AccountAccessRoleProvisioner {+ final List<String> calls = new ArrayList<>();++ @Override+ public void provision(String memberAccountId, String roleName, String managementAccountId) {+ calls.add(memberAccountId + "|" + roleName + "|" + managementAccountId);+ }+ }++ private OrganizationsService serviceWithProvisioner(RecordedProvisions provisioner) {+ return new OrganizationsService(+ new ObjectMapper(),+ REGION_RESOLVER,+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),+ true,+ null,+ provisioner);+ }++ @Test+ void createAccountProvisionsTheDefaultAccountAccessRole() {+ RecordedProvisions provisioner = new RecordedProvisions();+ OrganizationsService provisioning = serviceWithProvisioner(provisioner);+ provisioning.createOrganization(MANAGEMENT_ACCOUNT, "ALL");++ CreateAccountStatus status = provisioning.createAccount(+ MANAGEMENT_ACCOUNT, "[email protected]", "Dev", null, null, false);++ assertEquals("SUCCEEDED", status.getState());+ assertEquals(List.of(status.getAccountId() + "|OrganizationAccountAccessRole|" + MANAGEMENT_ACCOUNT),+ provisioner.calls);+ }++ @Test+ void createAccountWithARoleNameProvisionsThatName() {+ RecordedProvisions provisioner = new RecordedProvisions();+ OrganizationsService provisioning = serviceWithProvisioner(provisioner);+ provisioning.createOrganization(MANAGEMENT_ACCOUNT, "ALL");++ CreateAccountStatus status = provisioning.createAccount(+ MANAGEMENT_ACCOUNT, "[email protected]", "Dev", null, "CustomAccessRole", false);++ assertEquals(status.getAccountId() + "|CustomAccessRole|" + MANAGEMENT_ACCOUNT,+ provisioner.calls.get(0));+ }++ @Test+ void createAccountWithAnInvalidRoleNameIsRejected() {+ service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");++ for (String roleName : List.of("bad name", "", "x".repeat(65))) {+ AwsException error = assertThrows(AwsException.class, () -> service.createAccount(+ MANAGEMENT_ACCOUNT, "[email protected]", "Dev", null, roleName, false));+ assertEquals("InvalidInputException", error.getErrorCode());+ assertEquals("INVALID_PATTERN", error.getExtendedData().get("Reason"));+ }++ AwsException reserved = assertThrows(AwsException.class, () -> service.createAccount(+ MANAGEMENT_ACCOUNT, "[email protected]", "Dev", null, "AWSServiceRoleForOrganizations", false));+ assertEquals("InvalidInputException", reserved.getErrorCode());+ assertEquals("INVALID_ROLE_NAME", reserved.getExtendedData().get("Reason"));+ }++ @Test+ void createAccountWithADuplicateEmailProvisionsNoRole() {+ RecordedProvisions provisioner = new RecordedProvisions();+ OrganizationsService provisioning = serviceWithProvisioner(provisioner);+ provisioning.createOrganization(MANAGEMENT_ACCOUNT, "ALL");+ provisioning.createAccount(MANAGEMENT_ACCOUNT, "[email protected]", "Dev", null, null, false);+ int provisionedSoFar = provisioner.calls.size();++ CreateAccountStatus failed = provisioning.createAccount(+ MANAGEMENT_ACCOUNT, "[email protected]", "Dev2", null, null, false);++ assertEquals("FAILED", failed.getState());+ assertEquals(provisionedSoFar, provisioner.calls.size());+ }+@ParameterizedTest@ValueSource(strings = {"INSPECTOR_POLICY", "UPGRADE_ROLLOUT_POLICY", "BEDROCK_POLICY","S3_POLICY", "NETWORK_SECURITY_DIRECTOR_POLICY", "GUARDDUTY_POLICY"})