fix(organizations): preconfigure the account access role in a new account (#6444)

* fix(organizations): preconfigure the account access role in a new account

CreateAccount was returning a member account with no OrganizationAccountAccessRole, so sts:AssumeRole into it failed on a role that does not exist. The role AWS preconfigures is now created through IAM's own creation, in the new account's namespace: it trusts the management account and carries AdministratorAccess. CreateAccount's RoleName is honored, defaulted to OrganizationAccountAccessRole, and validated with the pattern the reference publishes, including the AWSServiceRoleFor refusal. Invited accounts do not get the role, which is AWS behavior. IAM owns the how behind an interface, the way ScpProvider already decouples IAM's reads of organization policy.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(organizations): answer RoleName errors with their reasons and provision the role as the new account

CreateAccount's InvalidInputException for a bad RoleName now carries the
reference's Reason, INVALID_PATTERN for a pattern violation and
INVALID_ROLE_NAME for the reserved prefix, asserted at the service, the
wire and the SDK levels. The provisioner itself now runs createRole and
attachRolePolicy inside RequestScopes.callAs(memberAccountId), so
validation, ARN minting and storage stay IAM's own and the hand-built
role with its account-aware storage branch is gone. EntityAlreadyExists
is the one error caught, falling back to the role that is there, and
the integration test builds its requests and auth through the
OrganizationsRequests and EnforcementFixtures helpers.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-25 07:31:36 -04:00
1 parent 35b76d2d94
commit 9242c7003a
10 files changed
+560 -3

No files matched your search

@@ -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());
}
@Test
void updateAssumeRolePolicyWithMatchingExpectedIdApplies() {
IamRole role = iamService.createRole("LambdaExec", "/", "{}", null, 3600, null);
@@ -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\":\"member@example.com\",\"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\":\"custom@example.com\",\"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\":\"bad@example.com\",\"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\":\"bad@example.com\",\"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);
}
}
@@ -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, "dev@example.com", "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, "dev@example.com", "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, "dev@example.com", "Dev", null, roleName, false));
assertEquals("InvalidInputException", error.getErrorCode());
assertEquals("INVALID_PATTERN", error.getExtendedData().get("Reason"));
}
AwsException reserved = assertThrows(AwsException.class, () -> service.createAccount(
MANAGEMENT_ACCOUNT, "dev@example.com", "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, "dev@example.com", "Dev", null, null, false);
int provisionedSoFar = provisioner.calls.size();
CreateAccountStatus failed = provisioning.createAccount(
MANAGEMENT_ACCOUNT, "dev@example.com", "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"})