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

@@ -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 role
@@ -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);
}
}
@@ -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);
}
@@ -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();
@@ -127,6 +127,12 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
private 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, RootAccessOrganization
private final RegionResolver regionResolver;
private final boolean scpEnforcementEnabled;
private final String managementAccountEmail;
private final AccountAccessRoleProvisioner accountAccessRoleProvisioner;
@Inject
public 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, RootAccessOrganization
AccountAwareStorageBackend<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, RootAccessOrganization
this.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, RootAccessOrganization
public 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, RootAccessOrganization
OrganizationAccount 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);
}