Files
floci/docs/services/organizations.md
T
Sam Fakhreddine 7188b3ec9d feat(iam): enforce SCPs and populate aws:PrincipalArn during policy evaluation (#2637)
* feat(iam): enforce service control policies during policy evaluation

Service control policies from the caller's organization now gate IAM
policy evaluation. CallerContext carries an optional list of SCP levels
(root, each OU on the account's path, then the account); the evaluator
requires an explicit allow and no explicit deny at every level before
identity policies are consulted. SCPs never grant permissions on their
own.

The ceiling applies to evaluate() only. IamEnforcementFilter is the
single producer of SCP levels, so simulatePrincipalPolicy and the
AppSync GraphQL IAM-auth path (IamAuthValidator) evaluate without one.
Both are explicit non-goals rather than oversights: giving them a
ceiling would require IAM to resolve the principal's organization,
which is the dependency ScpProvider exists to avoid. The coarse AppSync
request is still bounded by the filter ahead of the resource; only the
field-level check runs outside it.

The new ScpProvider interface keeps the dependency direction clean:
OrganizationsService implements it and IamEnforcementFilter resolves it
lazily via Instance, so IAM never depends on Organizations while
Organizations keeps using IamService for role provisioning.

Enforcement is doubly opt-in — FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED
plus FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED — and the
management account is exempt, matching AWS.

* fix(iam): apply service control policies to the account-root principal

floci's account-root principal is a bare 12-digit account-id access key
(LocalStack multi-account convention). IamService.resolveCallerContext
returns null for it, so IamEnforcementFilter took the unknown-key bypass
and returned before SCP levels were ever consulted. Effect: a
DenyLeaveOrganization SCP attached to a workload OU did not stop a member
account from leaving — SCPs never applied to floci's primary
multi-account principal, unlike the AWS account root which is fully
bounded by SCPs.

Fix: when the caller has no registered identity but the account actually
has an effective SCP ceiling and the access key is the account root
(akid == accountId), synthesize an implicit full-access identity
(ROOT_ALLOW_ALL) and evaluate it against the SCP levels. Accounts with no
effective SCPs, and unknown AKIA keys, keep the historical bypass.

Strictly more enforcement, gated behind two opt-in flags
(iam.enforcement-enabled + organizations.scp-enforcement-enabled, both
default off), so the LZA campaign and existing bare-account behavior are
unaffected.

Known flag-flip caveats (both are correct SCP semantics, documented here
for operators enabling enforcement):
- A level that carries SCPs but no FullAWSAccess denies everything for
  the account root, since scpAllows requires an explicit allow at each
  non-empty level. Auto-attached FullAWSAccess covers the normal path.
- Condition-scoped guardrails keyed on aws:PrincipalArn (e.g. a
  DenyRootUser "Deny * when aws:PrincipalArn like *:root") are inert:
  IamConditionContextResolver never populates aws:PrincipalArn, so a
  plain StringLike on that absent key fails the condition block and the
  statement does not apply. A regression test locks this in.

Tests: unit coverage in IamEnforcementFilterTest (bare-account deny,
non-denied allow proven via arnBuilder invocation, and the realistic
two-statement workload-guardrails doc) plus an end-to-end
ScpEnforcementLeaveOrganizationIntegrationTest driving the Organizations
control plane over HTTP.

* feat(iam): populate aws:PrincipalArn for real identities in policy conditions

IamEnforcementFilter built the condition context only from
IamConditionContextResolver, which populates s3:prefix/delimiter/max-keys
and nothing else. aws:PrincipalArn was therefore never set, so every
policy condition keyed on it was inert across all policy layers (SCPs,
identity, session, permissions boundary): a principal-scoped Deny never
fired and a principal-scoped Allow never matched.

Fix: after resolving the condition context, look up the caller's ARN via
IamService.resolveCallerArn(akid) and, when present, set aws:PrincipalArn.
The lookup returns the user ARN for IAM-user access keys and the
assumed-role ARN for STS sessions, and Optional.empty() for the bare
account-id key (floci's account root) and unknown keys. So the key is
populated for real, identifiable principals and stays absent for the
account root — which is exactly why a DenyRootUser guardrail keyed on
aws:PrincipalArn continues not to fire against the account root, per the
account-root SCP change in the preceding commit.

Effect is bidirectional and applies to every policy layer that
evaluate() consults: a principal-scoped Deny can now deny, and a
principal-scoped Allow can now grant. Both remain gated behind the two
opt-in enforcement flags (iam.enforcement-enabled +
organizations.scp-enforcement-enabled, both default off).

IamEnforcementFilter is the sole caller of the condition-aware
IamPolicyEvaluator.evaluate overload and the sole user of
IamConditionContextResolver, so there is no second evaluation path where
the key would be absent and the same policy would behave differently.

Known caveat (pre-existing, surfaced here for operators): resolveCallerArn
hardcodes the assumed-role session name as "floci-session", so
aws:PrincipalArn for assumed-role callers will not match a condition that
pins a specific session name. This matches what STS GetCallerIdentity
already reports.

Tests: two conditional cases in IamEnforcementFilterTest exercise both
directions against a real IamPolicyEvaluator — a principal-scoped SCP
Deny that fires for an IAM user, and an identity-policy Allow gated on an
IAM-user principal that grants access. Both were confirmed RED with the
population disabled.

* docs(iam,organizations): document account-root SCP handling and condition keys

Clarify how SCP enforcement treats the bare account-id key (subject to the
SCP chain as the account root, but carrying no identity policy), the
condition keys floci populates (s3:prefix/delimiter/max-keys,
aws:PrincipalArn), and the absent-key rule that keeps aws:PrincipalArn
guardrails inert against the account root.

* feat(iam): organization support ops for LZA bootstrap

Add ListOrganizationsFeatures and the root-credentials-management and
root-sessions enable/disable pairs, backed by OrganizationRootFeatures.
LZA custom resources call these during the Prepare/Accounts stages
(EnableAllFeatures), alongside CreateServiceLinkedRole for the Access
Analyzer role, which the emulator already implements — the tests here
cover the service-linked role names those stages depend on.

* fix(iam): register OrganizationRootFeatures for reflection

PersistedModelReflectionTest asserts every type reachable from persisted
storage carries @RegisterForReflection -- without it, native-image
persistence breaks on restart. OrganizationRootFeatures was added in
e60e8abd (organization support ops) without the annotation, so the test
has been red since.

Adds @RegisterForReflection plus @JsonIgnoreProperties(ignoreUnknown =
true), matching the convention of every sibling model in the package
(InstanceProfile, IamPolicy, IamGroup).

* feat(iam): tag and untag instance profiles

Adds a tags map to InstanceProfile and wires TagInstanceProfile /
UntagInstanceProfile through the query handler, with an integration test
covering the tag round trip.

* feat(iam): add UpdateGroup

Net-new operation modeled on the existing updateUser: rename and/or
change a group's path, with the ARN and stored users moving with it.
Same EntityAlreadyExists/NoSuchEntity exception shape as updateUser.

* docs(iam): document SCP enforcement where it is implemented

The Organizations page described SCP participation in policy evaluation and
linked to iam.md#service-control-policies-scps and iam.md#bypass-rules, neither
of which existed anywhere. The behaviour belongs to the IAM enforcement layer —
IamEnforcementFilter resolves the chain via effectiveScpLevels — so document it
there, including the account-root and bypass cases, and restore the
cross-reference now that both anchors resolve.

* fix: use canonical IAM service-linked role names

* feat(iam): seed AWS Backup service-role managed policies

LZA's OperationsStack attaches AWSBackupServiceRolePolicyForBackup and
AWSBackupServiceRolePolicyForRestores to its backup service roles; without
catalog entries AttachRolePolicy fails with NoSuchEntity and the stack
rolls back.

* feat(iam): seed AWS Backup S3 service-role managed policies

LZA's OperationsStack backup role also references
AWSBackupServiceRolePolicyForS3Backup / ForS3Restore, which live at the
root path in real AWS rather than /service-role/. Without them the role
create fails with NoSuchEntity and the stack rolls back.

* fix(iam): deny when a service control policy fails to parse

The SCP ceiling skipped any document it could not parse and evaluated
whatever else the level held. Since FullAWSAccess is attached to every
target, a level almost always carries it alongside the customer's
guardrail: a malformed guardrail dropped out, FullAWSAccess supplied the
required explicit allow, and the restriction vanished with only a WARN
line to show for it. A security control must not fail open.

parseAll now reports whether any document failed, and a level holding an
unparseable document denies. Only SCP evaluation reads that signal —
identity, resource, session and boundary policies keep skipping bad
documents as before.

* perf(organizations): scan the policy store once per SCP resolution

effectiveScpLevels called policiesIn(organization) inside the loop over
the account's ancestry, and policiesIn scans every account's policy
store. A root -> OU -> account chain therefore did three full scans on
an authenticated request path. Hoist the scan above the loop and keep
the per-node target filter inside it.

Also record why the SCP levels are resolved before resolveCallerContext
in IamEnforcementFilter: the account-root branch needs to know whether a
ceiling exists before it can choose between enforcing and bypassing.

* test(organizations): cover each reason effectiveScpLevels returns null

The management-account exemption, the account-outside-any-organization
case, and the SCP-policy-type-disabled case were only asserted as three
lines inside the walk-the-chain test, where a name never says what broke
and an earlier failure hides them. Give each its own test, and assert a
member account does get a ceiling in the same setup so the exemption
cases cannot pass for the trivial reason that no SCPs exist at all.

* fix(iam): never reissue deleted policy version ids

CreatePolicyVersion derived the next version id from the version count,
so deleting a non-default version and creating a new one silently
rewrote the highest surviving version. AWS ids are monotonic; derive
the next id from the highest existing one and cap on the live count.

* fix(iam): resolve principal policies in the account the ARN names

collectUserPolicies, collectRolePolicies, resolveUserBoundaryDocument
and resolveRoleBoundaryDocument stripped a bare name out of the given
principal ARN and looked it up in ambient request-context storage. When
two accounts each hold a same-named user or role, presenting account
A's ARN resolved whichever account the request happened to run as — a
cross-account authorization bypass in either direction, and one that
also silently applied the wrong permissions boundary.

Each lookup now scopes to the account segment of the ARN it was given,
via the existing findRole(accountId, roleName) and a new symmetric
findUser(accountId, userName). resolvePrincipalContext passes the full
ARN to the user-side helpers instead of pre-stripping it to a name.

Callers that legitimately have no ARN — resolveCallerContext, reached
from a long-term access key — still resolve through the ambient account,
so account-routed access keys keep working.

* fix(iam): enforce the modeled password-policy bounds and instance-profile tag limits

UpdateAccountPasswordPolicy stored whatever numbers arrived, so a policy with
MinimumPasswordLength outside 6-128, MaxPasswordAge outside 1-1095 or
PasswordReusePrevention outside 1-24 persisted and was read straight back by
GetAccountPasswordPolicy as if AWS had accepted it. Reject with ValidationError,
the code the service already raises for shape-constraint failures.

TagInstanceProfile merged the tag map with no cardinality check and
UntagInstanceProfile accepted an unbounded TagKeys list, though both shapes are
max 50. Tagging past the quota now raises LimitExceeded, matching the other
per-resource quota guards; an over-long TagKeys request raises ValidationError.

* fix(iam): check the instance-profile tag list shape before resolving the profile

Separates the two constraints the previous commit conflated: a request carrying
more than 50 tags fails the tagListType shape and is now rejected with
ValidationError before the profile lookup, matching untagInstanceProfile's order
and AWS's; exceeding the 50-tag per-resource quota across requests stays
LimitExceeded.

* fix(iam): validate GroupName/NewPath and InstanceProfileName shape before mutation

UpdateGroup read GroupName and NewPath with getParam and passed them straight
into IamService.updateGroup with no pattern/length check, and TagInstanceProfile
did the same for InstanceProfileName before reaching IamService.tagInstanceProfile.
botocore's iam/2010-05-08 model constrains groupNameType/instanceProfileNameType
to [\w+=,.@-]{1,128} and pathType to 512 chars matching a bare slash or a
slash-delimited run of !-~; a malformed value previously surfaced as
NoSuchEntity/200 instead of the ValidationError AWS returns.

* fix(iam): never reissue a policy version id after deleting the highest surviving version

CreatePolicyVersion derived the next id from the max of the currently-live version keys, so
deleting the highest-numbered surviving version (as opposed to an older one) and creating a
new one silently reissued the deleted id — e.g. deleting v5 while v4 survives makes the next
version v5 again, violating IAM's monotonic version-id contract. IamPolicy now tracks a
persisted next-version high-water mark, taken as the max of itself and the live-key floor so a
policy rehydrated from before this field existed is never regressed below what it already has
on disk.

* fix(iam): defensively copy InstanceProfile tags and reject a null map

setTags assigned the incoming map directly and allowed null. A persisted "tags": null on
rehydration, or a caller mutating the map it passed in after the call, could NPE at
new LinkedHashMap<>(profile.getTags()) in tagInstanceProfile or silently mutate the profile's
stored tags out from under it. Now defensively copies into a fresh ConcurrentHashMap, or an
empty one for null, matching how getTags()/setTags() are used elsewhere on this model.

* fix(iam): validate UpdateGroup's NewGroupName and keep member policies resolving across a rename

NewGroupName reached storage with no pattern/length check (the same groupNameType gap already
closed on GroupName/NewPath), and UntagInstanceProfile's InstanceProfileName had the same gap
UpdateGroup's tag-sibling TagInstanceProfile already closed. Also: renaming a group rekeyed
only the group record, leaving each member's own groupNames list pointing at the deleted old
name, so ListGroupsForUser dropped the renamed group and collectUserPolicies silently stopped
resolving its inline/attached policies for those members. updateGroup now updates every
member's groupNames symmetrically with addUserToGroup/removeUserFromGroup.

* fix(iam): guard against reissuing a version id deleted before nextVersionNumber existed

nextVersionNumber previously defaulted to 2 in its field initializer, so a policy persisted by a
pre-migration Floci version rehydrated with the same value a genuinely fresh policy would have,
regardless of how many versions it actually held historically. If such a policy's then-highest
version had been deleted (e.g. v1-v4 live after a pre-migration DeletePolicyVersion("v5")), the
live-key floor alone could not reveal that v5 was already used, and CreatePolicyVersion reissued
it. The field is now left null (unset) unless a policy explicitly sets it, so Jackson leaves a
legacy record's value null instead of masquerading as fresh; CreatePolicyVersion treats null as
"true history unknown" and jumps the counter past the live-key max by 5 (a policy can never hold
more than 5 concurrent versions, so no more than 5 stacked deletions could sit above the live max
between two persists).

* fix(iam): populate aws:PrincipalArn as the account root for the synthesized root principal

Maintainer review on #2637 (pgermosen): SCPs already treat floci's bare account-id key as the
account root (enforced), but aws:PrincipalArn was left absent for it, so a common DenyRootUser
guardrail keyed on aws:PrincipalArn (StringLike arn:aws:iam::*:root) could never fire against it
even though the same principal is otherwise bounded as root — an internal inconsistency between
the two forms of root enforcement. IamEnforcementFilter now populates aws:PrincipalArn as
arn:aws:iam::<account>:root right where the root identity is synthesized, matching AWS's own
root ARN shape. Inverts the IamEnforcementFilterTest that pinned the old inert behavior (a
DenyRootUser guardrail now correctly denies the account root's other actions too, not just the
one an accompanying statement explicitly targets) and adds a direct assertion that the exact
root ARN is what's populated. Docs updated to match.
2026-08-28 08:55:50 -04:00

9.8 KiB

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:

aws --endpoint-url http://localhost:4566 organizations create-organization --feature-set ALL
aws --endpoint-url http://localhost:4566 organizations create-account \
    --email dev@example.com --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

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.
ListAccountsWithInvalidEffectivePolicy Always returns an empty list; effective-policy validation is not modeled.
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.

Configuration

Environment variable Default Description
FLOCI_SERVICES_ORGANIZATIONS_ENABLED true Enables the service
FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED false When true (and IAM enforcement is enabled), attached service control policies participate in IAM policy evaluation
FLOCI_SERVICES_ORGANIZATIONS_MANAGEMENT_ACCOUNT_EMAIL unset Email reported for the organization's management account (DescribeOrganization master account, ListAccounts). Unset falls back to the built-in default
FLOCI_STORAGE_SERVICES_ORGANIZATIONS_MODE inherits FLOCI_STORAGE_MODE Storage mode override
FLOCI_STORAGE_SERVICES_ORGANIZATIONS_FLUSH_INTERVAL_MS 5000 Hybrid/WAL flush interval

SCP enforcement

With FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true and FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED=true, service control policies attached to the root, OUs, and accounts participate in IAM policy evaluation: an action must be allowed at every level of the account's chain, before the caller's identity policies are consulted. SCPs never grant permissions on their own. See Service Control Policies (SCPs) for the evaluation order, the account-root behaviour, and the cases that bypass enforcement.

The evaluation itself lives in the IAM enforcement layer — this service stores the policies and resolves the chain, but with IAM enforcement off the flag has no effect.

Example

aws --endpoint-url http://localhost:4566 organizations create-organization --feature-set ALL

ROOT_ID=$(aws --endpoint-url http://localhost:4566 organizations list-roots \
  --query 'Roots[0].Id' --output text)

aws --endpoint-url http://localhost:4566 organizations create-organizational-unit \
  --parent-id "$ROOT_ID" --name workloads

aws --endpoint-url http://localhost:4566 organizations create-account \
  --email member@example.com --account-name "workload-account"

aws --endpoint-url http://localhost:4566 organizations list-accounts