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.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-28 08:55:50 -04:00
1 parent 066e6c904b
commit 7188b3ec9d
24 files changed
+2070 -34

No files matched your search

+2
View File
@@ -155,6 +155,8 @@ arn:aws:s3:::my-bucket # S3 ARNs are account-agnostic
All services that use `StorageFactory` participate in account isolation automatically. This covers every service in Floci — SQS, SNS, S3, DynamoDB, Lambda, SSM, Secrets Manager, KMS, Kinesis, EventBridge, Cognito, RDS, ElastiCache, OpenSearch, MSK, and more.
[AWS Organizations](../services/organizations.md) sits on top of this model: the organization's state lives in the management account's namespace, member accounts created with `CreateAccount` are immediately usable as 12-digit access key IDs, and — with IAM enforcement plus `FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED` — service control policies attached in the organization constrain what member-account identities may do.
Background workers (Lambda event-source pollers, DynamoDB TTL sweeper, MSK readiness poller, OpenSearch readiness poller) iterate across all accounts internally and route writes back to the originating account. No cross-account data leaks through these async paths.
## Signature Validation
+120 -5
View File
@@ -41,6 +41,7 @@ type.
|--------|-------------|
| CreateGroup | Creates an IAM group. |
| GetGroup | Returns an IAM group and its users. |
| UpdateGroup | Renames a group and/or changes its path; ARN and stored users move with it. |
| DeleteGroup | Deletes an IAM group from the local IAM store. |
| ListGroups | Lists IAM groups in the local account. |
| AddUserToGroup | Adds a user to an IAM group. |
@@ -312,11 +313,48 @@ environment:
Policy evaluation follows the standard AWS precedence:
1. An explicit **Deny** in any identity, session, or boundary policy → request is denied (HTTP 403 `AccessDeniedException`)
2. An explicit **Allow** in an identity policy creates the base grant
3. If a session policy is present, it must also explicitly allow the request
4. If a permission boundary is present, it must also explicitly allow the request
5. No matching effective allow → implicit deny (HTTP 403)
1. If [SCP enforcement](#service-control-policies-scps) is active, the action must be allowed at **every** organization level (root, OUs on the path, account) and explicitly denied at none — otherwise the request is denied before identity policies are consulted
2. An explicit **Deny** in any identity, session, or boundary policy → request is denied (HTTP 403 `AccessDeniedException`)
3. An explicit **Allow** in an identity policy creates the base grant
4. If a session policy is present, it must also explicitly allow the request
5. If a permission boundary is present, it must also explicitly allow the request
6. No matching effective allow → implicit deny (HTTP 403)
### Service control policies (SCPs)
When the caller's account belongs to an [Organizations](organizations.md) organization,
SCPs attached to the root, the OUs on the account's path, and the account itself can
participate in evaluation. Two flags must both be on:
```yaml
floci:
services:
iam:
enforcement-enabled: true
organizations:
scp-enforcement-enabled: true
```
(env: `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` and
`FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED`)
SCP semantics match AWS: SCPs never grant permissions — they cap what identity policies
may allow; the organization's **management account is exempt**; and an account outside
any organization is unaffected. The `test` credential and unknown access keys are never
SCP-denied.
**The account-root principal is subject to SCPs.** floci's account root is a bare
12-digit account-id access key (the LocalStack multi-account convention). It carries no
registered IAM identity, so it normally takes the unknown-key bypass. But when the access
key equals its own account ID **and** that account has an effective SCP ceiling
(`effectiveScpLevels != null` — i.e. it is a non-management member under a root with the
SCP policy type enabled and at least one attached SCP), floci synthesizes an
allow-everything root identity and evaluates the request against the SCP chain. In that
case **SCPs apply and nothing else does** — no identity policies, permission boundary, or
session policy attaches to the bare account key. If the account has no effective SCP
ceiling (the management account, an account outside any organization, or the SCP type
disabled), the bare key still bypasses enforcement entirely, and unknown `AKIA…` keys
always bypass unconditionally.
### Bypass rules
@@ -329,6 +367,13 @@ These identities always bypass enforcement (backward-compatible defaults):
| No `Authorization` header | Allowed — unauthenticated path (e.g. health checks) |
| Unresolvable IAM action for the request | Allowed — unknown mappings are permissive |
**Exception:** a bare 12-digit account-id key that equals its own account and sits under
an effective SCP ceiling is **not** treated as an unknown key — it is evaluated against
the SCP chain as the account root (see [Service control policies](#service-control-policies-scps)
above). Identity-policy enforcement of a member account still requires an assumable,
account-routable identity such as the `OrganizationAccountAccessRole` session; the bare
account key carries no identity policies of its own.
### Supported policy features
- **Identity-based policies**: inline user/group/role policies and managed attached policies.
@@ -347,6 +392,28 @@ These identities always bypass enforcement (backward-compatible defaults):
- `Bool`, `IpAddress`, `NotIpAddress`, `Null`
- Supports `...IfExists` variants for all operators.
#### Condition keys floci populates
A `Condition` operator can only match a key floci actually places in the request context.
floci populates:
- `s3:prefix`, `s3:delimiter`, `s3:max-keys` — from the S3 request parameters.
- `aws:PrincipalArn` — the caller's ARN, resolved from the signing access key. It is the
IAM-user ARN for a user access key, the assumed-role ARN for an STS session, and
`arn:aws:iam::<account>:root` for the bare account-id key (floci's account-root principal),
matching the ARN shape AWS itself reports for the account root. It is **absent** only for
unknown keys, where nothing about the caller can be resolved.
**Any other condition key is absent from the request context.** A plain (non-`IfExists`)
operator on an absent key makes the whole statement *not apply* — it neither matches nor
blocks. A `DenyRootUser`-style guardrail keyed on `aws:PrincipalArn` therefore fires against
the account root the same way it does on real AWS, consistent with the account root already
being bounded by SCPs (below): both forms of root enforcement now agree.
**Caveat:** `resolveCallerArn` hardcodes the assumed-role session name as `floci-session`,
so `aws:PrincipalArn` for an assumed-role caller will not match a condition that pins a
different session name. This matches what `sts:GetCallerIdentity` already reports.
**Not yet supported**: `NotPrincipal`, resource-based policies (S3 bucket policy, Lambda resource policy).
### Assumed roles
@@ -379,6 +446,54 @@ AWS_ACCESS_KEY_ID=$AKID AWS_SECRET_ACCESS_KEY=$SECRET \
aws s3 ls
```
## Service Control Policies (SCPs)
When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true` and
`FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED=true`, service control policies attached to
the caller account's organization participate in policy evaluation.
The SCP chain is resolved root → OUs on the path → account, and every level must allow the action
for the request to proceed. SCPs never grant permissions on their own — they are a ceiling applied
before identity policies are consulted, exactly as on AWS. Organizations is resolved lazily, so IAM
does not gain a hard dependency on it: with the Organizations service absent or the flag off, the
chain is skipped entirely and evaluation falls back to identity policies alone.
A member account's own bare 12-digit access key is floci's account-root principal. It is not a
registered IAM identity, but like the AWS account root it is still bounded by SCPs, so an SCP `Deny`
(for example a `DenyLeaveOrganization` guardrail) blocks it. What that key does *not* carry is any
identity policy — it behaves as allow-everything bounded only by the SCP ceiling. To exercise
**identity-policy** enforcement, use account-routable credentials for the member instead, most
naturally the `ASIA…` session from assuming its `OrganizationAccountAccessRole`.
Note that `aws:PrincipalArn` is populated for the account-root principal too, as
`arn:aws:iam::<account>:root`, so a principal-scoped guardrail keyed on `aws:PrincipalArn`
(for example a `DenyRootUser` statement matching `arn:aws:iam::*:root`) fires against it —
consistent with the account root already being bounded by SCPs above.
A level containing an SCP document that fails to parse denies every action at that level. The
ceiling cannot tell what an unreadable guardrail would have said, and every target also carries
`FullAWSAccess`, so dropping the bad document would leave the level allowing everything.
The ceiling is attached by the request filter, which is the only producer of SCP levels. Two
evaluation paths therefore run without one and are **not** SCP-bounded: `SimulatePrincipalPolicy`,
and the field-level authorization check on the AppSync GraphQL IAM-auth path (the coarse AppSync
request itself still passes through the filter). Both are deliberate non-goals — bounding them
would require IAM to resolve the caller's organization directly, which is the dependency the
lazily-resolved `ScpProvider` exists to avoid.
## Bypass rules
Enforcement is deliberately permissive in a few cases, so that enabling it does not break workloads
the emulator cannot reason about:
| Case | Behaviour |
| --- | --- |
| Unresolvable action | Allowed. An action the registry cannot resolve is not evaluated. |
| `sts:GetCallerIdentity` | Always allowed — AWS returns caller identity even when a policy denies it. |
| Unknown access key | Allowed. A key that resolves to no IAM identity bypasses enforcement. |
| Bare account-id key with no SCP ceiling | Allowed. With no organization or SCP enforcement off, the account root keeps the historical bypass. |
| Bare account-id key **with** an SCP ceiling | Enforced as the account root, bounded by the SCP chain. |
## Service-linked roles
`CreateServiceLinkedRole` puts a role under `/aws-service-role/<principal>/` and marks it as
+40
View File
@@ -112,3 +112,43 @@ call `LeaveOrganization`. An account in no organization gets
| `ListHandshakesForAccount` | Lists the handshakes that involve the calling account. |
| `ListHandshakesForOrganization` | Lists the handshakes associated with the organization. |
<!-- floci:actions:end -->
## 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)](iam.md#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
```bash
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
```
@@ -1312,6 +1312,9 @@ public interface EmulatorConfig {
interface OrganizationsServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("false")
boolean scpEnforcementEnabled();
}
interface AthenaServiceConfig {
@@ -7,9 +7,11 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
@@ -18,7 +20,10 @@ import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -50,6 +55,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private static final Pattern SERVICE_PATTERN =
Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
/**
* Implicit identity policy for the account-root principal: full access, bounded only by SCPs.
* The account root is not a registered IAM identity, so it has no stored identity policy.
*/
private static final String ROOT_ALLOW_ALL =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
private final EmulatorConfig config;
private final AccountResolver accountResolver;
private final IamService iamService;
@@ -61,6 +73,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private final CloudTrailService cloudTrailService;
private final CurrentVertxRequest currentVertxRequest;
private final ResolvedServiceCatalog catalog;
private final Instance<ScpProvider> scpProvider;
@Inject
public IamEnforcementFilter(EmulatorConfig config,
@@ -73,7 +86,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
IamConditionContextResolver conditionContextResolver,
CloudTrailService cloudTrailService,
CurrentVertxRequest currentVertxRequest,
ResolvedServiceCatalog catalog) {
ResolvedServiceCatalog catalog,
Instance<ScpProvider> scpProvider) {
this.config = config;
this.accountResolver = accountResolver;
this.iamService = iamService;
@@ -85,6 +99,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
this.cloudTrailService = cloudTrailService;
this.currentVertxRequest = currentVertxRequest;
this.catalog = catalog;
this.scpProvider = scpProvider;
}
@Override
@@ -120,18 +135,58 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return; // AWS returns caller identity even when an identity policy explicitly denies it
}
CallerContext caller = iamService.resolveCallerContext(akid);
if (caller == null) {
return; // unknown access key → bypass (backward-compat)
}
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
String accountId = requestContext.getAccountId() == null
? accountResolver.resolve(auth)
: requestContext.getAccountId();
// Service control policies from the caller's organization, when the Organizations
// service is present and SCP enforcement is enabled. Resolved lazily via Instance
// to avoid a hard IAM → Organizations dependency.
//
// Resolved before resolveCallerContext because the account-root branch below needs to
// know whether a ceiling exists in order to decide between enforcing and bypassing. That
// costs an organization lookup on requests that then bypass; both flags are opt-in, and
// effectiveScpLevels returns null immediately when SCP enforcement is off.
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId)
: null;
boolean accountRootPrincipal = false;
CallerContext caller = iamService.resolveCallerContext(akid);
if (caller == null) {
// A bare 12-digit account-id key is floci's account-root principal: not a registered
// IAM identity (resolveCallerContext → null), but in AWS the account root is still
// bounded by SCPs. Enforce them when the account actually has an SCP ceiling; otherwise
// preserve the historical unknown-key bypass.
if (scpLevels == null || !akid.equals(accountId)) {
return; // unknown access key or no SCP ceiling → bypass (backward-compat)
}
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
accountRootPrincipal = true;
}
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
}
String resource = arnBuilder.build(credentialScope, ctx, region, accountId);
Map<String, String> conditionContext = conditionContextResolver.resolve(credentialScope, action, ctx);
// aws:PrincipalArn is populated for every principal this filter can identify — IAM users,
// assumed-role sessions, and now the synthesized account-root principal above, using AWS's
// own root ARN shape (arn:aws:iam::<account>:root). Real AWS populates this key for the
// root user, so a DenyRootUser guardrail keyed on it must fire against floci's account-root
// stand-in the same way it enforces SCPs against it (the account-root SCP change above);
// leaving it absent here would have made the two forms of root enforcement inconsistent.
Optional<String> principalArn = accountRootPrincipal
? Optional.of("arn:aws:iam::" + accountId + ":root")
: iamService.resolveCallerArn(akid);
if (principalArn.isPresent()) {
conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);
conditionContext.put("aws:PrincipalArn", principalArn.get());
}
Decision decision = evaluator.evaluate(caller, null, action, resource, conditionContext);
if (decision == Decision.DENY) {
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
@@ -89,6 +89,14 @@ public class IamPolicyEvaluator {
List<PolicyStatement> boundaryStmts = caller.boundaryPolicyDocument() == null
? null : parseAll(List.of(caller.boundaryPolicyDocument()));
// 0. Service control policies gate everything: the action must be allowed at EVERY
// organization level and explicitly denied at none, before identity policies are
// even consulted. An empty level means FullAWSAccess semantics and is skipped;
// a level holding an unparseable document denies.
if (!scpAllows(caller.scpLevels(), action, resource, ctx)) {
return Decision.DENY;
}
// 1. Explicit deny in ANY policy → DENY immediately
if (anyExplicitDeny(identityStmts, action, resource, ctx)
|| anyExplicitDeny(resourceStmts, action, resource, ctx)
@@ -163,6 +171,39 @@ public class IamPolicyEvaluator {
return SimulationDecision.ALLOWED;
}
/**
* SCP evaluation: at every organization level the action must be explicitly allowed
* and not explicitly denied. {@code null} levels mean SCPs don't apply; a level with
* no documents at all (defensive — the last SCP on a target can't be detached) is
* FullAWSAccess semantics and passes.
*
* <p>A level containing a document that fails to parse denies. The ceiling cannot tell
* what an unreadable guardrail would have said, and every target also carries
* FullAWSAccess, so skipping the bad document would silently leave the level allowing
* everything the operator meant to forbid.</p>
*/
private boolean scpAllows(List<List<String>> scpLevels, String action, String resource,
Map<String, String> ctx) {
if (scpLevels == null) {
return true;
}
for (List<String> level : scpLevels) {
ParsedDocuments parsed = parseAllTracked(level);
if (parsed.anyFailed()) {
return false;
}
List<PolicyStatement> levelStmts = parsed.statements();
if (levelStmts.isEmpty()) {
continue;
}
if (anyExplicitDeny(levelStmts, action, resource, ctx)
|| !anyExplicitAllow(levelStmts, action, resource, ctx)) {
return false;
}
}
return true;
}
// -----------------------------------------------------------------------
// Statement matching
// -----------------------------------------------------------------------
@@ -436,18 +477,32 @@ public class IamPolicyEvaluator {
// -----------------------------------------------------------------------
private List<PolicyStatement> parseAll(List<String> documents) {
return parseAllTracked(documents).statements();
}
/**
* Parses every document, skipping (and logging) any that fails, and reports whether
* any did. Callers that can safely ignore a broken document use {@link #parseAll};
* SCP evaluation reads {@code anyFailed} so the ceiling can fail closed.
*/
private ParsedDocuments parseAllTracked(List<String> documents) {
List<PolicyStatement> result = new ArrayList<>();
if (documents == null) {
return result;
return new ParsedDocuments(result, false);
}
boolean anyFailed = false;
for (String doc : documents) {
try {
result.addAll(parseStatements(doc));
} catch (Exception e) {
anyFailed = true;
LOG.warnv("Failed to parse policy document: {0}", e.getMessage());
}
}
return result;
return new ParsedDocuments(result, anyFailed);
}
private record ParsedDocuments(List<PolicyStatement> statements, boolean anyFailed) {
}
private List<PolicyStatement> parseStatements(String document) throws Exception {
@@ -92,6 +92,7 @@ public class IamQueryHandler {
// Groups
case "CreateGroup" -> handleCreateGroup(params);
case "GetGroup" -> handleGetGroup(params);
case "UpdateGroup" -> handleUpdateGroup(params);
case "DeleteGroup" -> handleDeleteGroup(params);
case "ListGroups" -> handleListGroups(params);
case "AddUserToGroup" -> handleAddUserToGroup(params);
@@ -110,6 +111,8 @@ public class IamQueryHandler {
case "UpdateAssumeRolePolicy" -> handleUpdateAssumeRolePolicy(params);
case "TagRole" -> handleTagRole(params);
case "UntagRole" -> handleUntagRole(params);
case "TagInstanceProfile" -> handleTagInstanceProfile(params);
case "UntagInstanceProfile" -> handleUntagInstanceProfile(params);
case "ListRoleTags" -> handleListRoleTags(params);
// Managed Policies
@@ -168,6 +171,12 @@ public class IamQueryHandler {
case "UpdateAccessKey" -> handleUpdateAccessKey(params);
case "GetAccessKeyLastUsed" -> handleGetAccessKeyLastUsed(params);
case "ListOrganizationsFeatures" -> handleListOrganizationsFeatures(params);
case "EnableOrganizationsRootCredentialsManagement" -> handleEnableOrganizationsRootCredentialsManagement(params);
case "EnableOrganizationsRootSessions" -> handleEnableOrganizationsRootSessions(params);
case "DisableOrganizationsRootCredentialsManagement" -> handleDisableOrganizationsRootCredentialsManagement(params);
case "DisableOrganizationsRootSessions" -> handleDisableOrganizationsRootSessions(params);
// Instance Profiles
case "CreateInstanceProfile" -> handleCreateInstanceProfile(params);
case "GetInstanceProfile" -> handleGetInstanceProfile(params);
@@ -576,6 +585,12 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("GetGroup", AwsNamespaces.IAM, xml.build())).build();
}
private Response handleUpdateGroup(MultivaluedMap<String, String> params) {
iamService.updateGroup(getParam(params, "GroupName"),
getParam(params, "NewGroupName"), getParam(params, "NewPath"));
return Response.ok(AwsQueryResponse.envelopeNoResult("UpdateGroup", AwsNamespaces.IAM)).build();
}
private Response handleDeleteGroup(MultivaluedMap<String, String> params) {
iamService.deleteGroup(getParam(params, "GroupName"));
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteGroup", AwsNamespaces.IAM)).build();
@@ -1023,6 +1038,49 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("GetAccessKeyLastUsed", AwsNamespaces.IAM, result)).build();
}
// =========================================================================
// Centralized root access management (org-scoped, IAM Query endpoint)
// =========================================================================
private Response handleListOrganizationsFeatures(MultivaluedMap<String, String> params) {
return rootFeaturesResponse("ListOrganizationsFeatures", iamService.listOrganizationsFeatures());
}
private Response handleEnableOrganizationsRootCredentialsManagement(MultivaluedMap<String, String> params) {
return rootFeaturesResponse("EnableOrganizationsRootCredentialsManagement",
iamService.enableOrganizationsRootCredentialsManagement());
}
private Response handleEnableOrganizationsRootSessions(MultivaluedMap<String, String> params) {
return rootFeaturesResponse("EnableOrganizationsRootSessions",
iamService.enableOrganizationsRootSessions());
}
private Response handleDisableOrganizationsRootCredentialsManagement(MultivaluedMap<String, String> params) {
return rootFeaturesResponse("DisableOrganizationsRootCredentialsManagement",
iamService.disableOrganizationsRootCredentialsManagement());
}
private Response handleDisableOrganizationsRootSessions(MultivaluedMap<String, String> params) {
return rootFeaturesResponse("DisableOrganizationsRootSessions",
iamService.disableOrganizationsRootSessions());
}
/**
* Builds the shared {@code <EnabledFeatures><member>..</member></EnabledFeatures>} result used by
* both {@code ListOrganizationsFeatures} and the enable/disable ops. The org-scoped
* {@code OrganizationId} is intentionally omitted — LZA's root-user-management module reads only
* the enabled-feature set, and omitting it avoids coupling the IAM endpoint to Organizations.
*/
private Response rootFeaturesResponse(String action, List<String> features) {
XmlBuilder xml = new XmlBuilder().start("EnabledFeatures");
for (String feature : features) {
xml.elem("member", feature);
}
String result = xml.end("EnabledFeatures").build();
return Response.ok(AwsQueryResponse.envelope(action, AwsNamespaces.IAM, result)).build();
}
// =========================================================================
// Instance Profiles
// =========================================================================
@@ -1379,4 +1437,14 @@ public class IamQueryHandler {
if (instant == null) return "";
return DateTimeFormatter.ISO_INSTANT.format(instant);
}
private Response handleTagInstanceProfile(MultivaluedMap<String, String> params) {
iamService.tagInstanceProfile(getParam(params, "InstanceProfileName"), extractTags(params));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagInstanceProfile", AwsNamespaces.IAM)).build();
}
private Response handleUntagInstanceProfile(MultivaluedMap<String, String> params) {
iamService.untagInstanceProfile(getParam(params, "InstanceProfileName"), extractTagKeys(params));
return Response.ok(AwsQueryResponse.envelopeNoResult("UntagInstanceProfile", AwsNamespaces.IAM)).build();
}
}
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
@@ -82,12 +83,26 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final String SERVICE_LINKED_ROLE_PATH = "/aws-service-role/";
private static final String SERVICE_LINKED_ROLE_NAME_PREFIX = "AWSServiceRoleFor";
private static final Map<String, String> SERVICE_LINKED_ROLE_NAMES = Map.of(
"autoscaling.amazonaws.com", "AutoScaling",
"cloud9.amazonaws.com", "AWSCloud9"
);
private static final String AMAZONAWS_DOMAIN = ".amazonaws.com";
/** AWSServiceName as AWS constrains it: 1-128 characters of {@code [\w+=,.@-]}. */
private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}");
/** CustomSuffix as AWS constrains it: 1-64 characters of {@code [\w+=,.@-]}. */
private static final Pattern CUSTOM_SUFFIX_PATTERN = Pattern.compile("[\\w+=,.@-]{1,64}");
private static final int ROLE_NAME_MAX_LENGTH = 64;
/** groupNameType / instanceProfileNameType: 1-128 characters of {@code [\w+=,.@-]}. */
private static final Pattern IAM_RESOURCE_NAME_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}");
/** pathType: a bare slash, or a slash-delimited run of {@code !}-{@code ~}. */
private static final Pattern IAM_PATH_PATTERN = Pattern.compile("(/)|(/[\\x21-\\x7E]+/)");
private static final int IAM_PATH_MAX_LENGTH = 512;
/** {@code tagListType} / {@code tagKeyListType} are both {@code max: 50}. */
private static final int MAX_TAGS_PER_INSTANCE_PROFILE = 50;
private static final String ROOT_FEATURES_KEY = "org-root-features";
public static final String FEATURE_ROOT_CREDENTIALS = "RootCredentialsManagement";
public static final String FEATURE_ROOT_SESSIONS = "RootSessions";
private final StorageBackend<String, IamUser> users;
private final StorageBackend<String, IamGroup> groups;
@@ -116,6 +131,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private final StorageBackend<String, OpenIDConnectProvider> oidcProviders;
/** Deletion is synchronous, so an issued task id is a completed one; the value is its role. */
private final StorageBackend<String, String> serviceLinkedRoleDeletions;
private final StorageBackend<String, OrganizationRootFeatures> orgRootFeatures;
private final RegionResolver regionResolver;
private final boolean seedDeployerPrincipal;
private final String seededAccountAlias;
@@ -141,6 +157,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
storageFactory.create("iam", "iam-password-policy.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-oidc-providers.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-slr-deletions.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-org-root-features.json", new TypeReference<>() {}),
regionResolver,
config.services().iam().seedDeployerPrincipal(),
config.services().iam().accountAlias().orElse(null)
@@ -168,10 +185,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
RegionResolver regionResolver,
boolean seedDeployerPrincipal) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
regionResolver, seedDeployerPrincipal, null);
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, null);
}
// 8-backend constructor (no org-root-features): kept for existing callers/tests;
// delegates with an in-memory root-features backend.
IamService(StorageBackend<String, IamUser> users,
StorageBackend<String, IamGroup> groups,
StorageBackend<String, IamRole> roles,
@@ -186,6 +205,44 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
RegionResolver regionResolver,
boolean seedDeployerPrincipal,
String seededAccountAlias) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
accountAliases, passwordPolicies, oidcProviders, serviceLinkedRoleDeletions,
new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal, seededAccountAlias);
}
// 9-backend constructor (no alias/OIDC/SLR backends): kept for existing callers/tests;
// delegates with in-memory backends for the omitted stores.
IamService(StorageBackend<String, IamUser> users,
StorageBackend<String, IamGroup> groups,
StorageBackend<String, IamRole> roles,
StorageBackend<String, IamPolicy> policies,
StorageBackend<String, AccessKey> accessKeys,
StorageBackend<String, InstanceProfile> instanceProfiles,
StorageBackend<String, SessionCredential> sessions,
StorageBackend<String, AccountPasswordPolicy> passwordPolicies,
StorageBackend<String, OrganizationRootFeatures> orgRootFeatures,
RegionResolver regionResolver,
boolean seedDeployerPrincipal) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
new InMemoryStorage<>(), passwordPolicies, new InMemoryStorage<>(),
new InMemoryStorage<>(), orgRootFeatures, regionResolver, seedDeployerPrincipal, null);
}
IamService(StorageBackend<String, IamUser> users,
StorageBackend<String, IamGroup> groups,
StorageBackend<String, IamRole> roles,
StorageBackend<String, IamPolicy> policies,
StorageBackend<String, AccessKey> accessKeys,
StorageBackend<String, InstanceProfile> instanceProfiles,
StorageBackend<String, SessionCredential> sessions,
StorageBackend<String, String> accountAliases,
StorageBackend<String, AccountPasswordPolicy> passwordPolicies,
StorageBackend<String, OpenIDConnectProvider> oidcProviders,
StorageBackend<String, String> serviceLinkedRoleDeletions,
StorageBackend<String, OrganizationRootFeatures> orgRootFeatures,
RegionResolver regionResolver,
boolean seedDeployerPrincipal,
String seededAccountAlias) {
this.users = users;
this.groups = groups;
this.roles = roles;
@@ -197,6 +254,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this.passwordPolicies = passwordPolicies;
this.oidcProviders = oidcProviders;
this.serviceLinkedRoleDeletions = serviceLinkedRoleDeletions;
this.orgRootFeatures = orgRootFeatures;
this.regionResolver = regionResolver;
this.seedDeployerPrincipal = seedDeployerPrincipal;
this.seededAccountAlias = seededAccountAlias;
@@ -395,6 +453,39 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
"The group with name " + groupName + " cannot be found.", 404));
}
public void updateGroup(String groupName, String newGroupName, String newPath) {
validateIamResourceName(groupName, "GroupName");
if (newGroupName != null) validateIamResourceName(newGroupName, "NewGroupName");
validateIamPath(newPath, "NewPath");
IamGroup group = getGroup(groupName);
if (newGroupName != null && !newGroupName.equals(groupName)) {
if (groups.get(newGroupName).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"Group with name " + newGroupName + " already exists.", 409);
}
groups.delete(groupName);
group.setGroupName(newGroupName);
if (newPath != null) group.setPath(normalizePath(newPath));
group.setArn(iamArn("group", group.getPath(), newGroupName));
groups.put(newGroupName, group);
// Members still carry the old name in their own groupNames list — without this,
// ListGroupsForUser drops the renamed group and its policies stop resolving for them.
for (String memberName : group.getUserNames()) {
users.get(memberName).ifPresent(member -> {
member.getGroupNames().remove(groupName);
member.getGroupNames().add(newGroupName);
users.put(memberName, member);
});
}
} else {
if (newPath != null) {
group.setPath(normalizePath(newPath));
group.setArn(iamArn("group", group.getPath(), groupName));
}
groups.put(groupName, group);
}
}
public void deleteGroup(String groupName) {
IamGroup group = getGroup(groupName);
if (!group.getAttachedPolicyArns().isEmpty() || !group.getInlinePolicies().isEmpty()) {
@@ -599,6 +690,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* roles on AWS, and a config declaring both must not collide on one name here.
*/
private static String derivedServiceName(String awsServiceName) {
String canonicalName = SERVICE_LINKED_ROLE_NAMES.get(awsServiceName);
if (canonicalName != null) {
return canonicalName;
}
String core = awsServiceName == null ? "" : awsServiceName;
if (core.endsWith(AMAZONAWS_DOMAIN)) {
core = core.substring(0, core.length() - AMAZONAWS_DOMAIN.length());
@@ -871,11 +966,29 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Map<String, PolicyVersion> versions = policy.getVersions();
PolicyVersion version;
synchronized (versions) {
int nextVersionNum = versions.size() + 1;
if (nextVersionNum > 5) {
if (versions.size() >= 5) {
throw new AwsException("LimitExceeded",
"A managed policy can have up to 5 versions.", 409);
}
// AWS version ids are monotonic and never reissued after a DeletePolicyVersion.
// The live keys' own max is only a floor, not the source of truth: deleting the
// highest-numbered surviving version would otherwise let a "derive from what's left"
// computation reissue its id. The stored high-water mark is the real counter.
int highestSurviving = versions.keySet().stream()
.mapToInt(id -> Integer.parseInt(id.substring(1)))
.max().orElse(0);
int nextVersionNum;
if (policy.getNextVersionNumber() == null) {
// A policy persisted before this field existed: the live-key floor alone can't
// reveal a version deleted before this field was ever recorded (e.g. v1-v4 live
// after a pre-migration DeletePolicyVersion("v5")). Since a policy can never hold
// more than 5 concurrent versions, no more than 5 stacked deletions could have
// happened at the top between two persists; jump the counter past that worst
// case rather than trust the live keys' max + 1 for an unknown history.
nextVersionNum = highestSurviving + 1 + 5;
} else {
nextVersionNum = Math.max(policy.getNextVersionNumber(), highestSurviving + 1);
}
String versionId = "v" + nextVersionNum;
version = new PolicyVersion(versionId, document, setAsDefault);
if (setAsDefault) {
@@ -883,6 +996,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
policy.setDefaultVersionId(versionId);
}
versions.put(versionId, version);
policy.setNextVersionNumber(nextVersionNum + 1);
}
policy.setUpdateDate(Instant.now());
policies.put(policyArn, policy);
@@ -1221,6 +1335,51 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
accessKeys.put(accessKeyId, key);
}
// =========================================================================
// Centralized root access management (org-scoped, IAM Query endpoint)
// =========================================================================
/** Currently-enabled centralized root features, in enablement order. Empty for a fresh org. */
public List<String> listOrganizationsFeatures() {
return new ArrayList<>(currentRootFeatures().getEnabledFeatures());
}
public List<String> enableOrganizationsRootCredentialsManagement() {
return addRootFeature(FEATURE_ROOT_CREDENTIALS);
}
public List<String> enableOrganizationsRootSessions() {
return addRootFeature(FEATURE_ROOT_SESSIONS);
}
public List<String> disableOrganizationsRootCredentialsManagement() {
return removeRootFeature(FEATURE_ROOT_CREDENTIALS);
}
public List<String> disableOrganizationsRootSessions() {
return removeRootFeature(FEATURE_ROOT_SESSIONS);
}
private OrganizationRootFeatures currentRootFeatures() {
return orgRootFeatures.get(ROOT_FEATURES_KEY).orElseGet(OrganizationRootFeatures::new);
}
private List<String> addRootFeature(String feature) {
OrganizationRootFeatures features = currentRootFeatures();
features.getEnabledFeatures().add(feature);
orgRootFeatures.put(ROOT_FEATURES_KEY, features);
LOG.infov("Enabled centralized root feature {0}", feature);
return new ArrayList<>(features.getEnabledFeatures());
}
private List<String> removeRootFeature(String feature) {
OrganizationRootFeatures features = currentRootFeatures();
features.getEnabledFeatures().remove(feature);
orgRootFeatures.put(ROOT_FEATURES_KEY, features);
LOG.infov("Disabled centralized root feature {0}", feature);
return new ArrayList<>(features.getEnabledFeatures());
}
// =========================================================================
// Instance Profiles
// =========================================================================
@@ -1443,6 +1602,23 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
}
private void validateIamResourceName(String value, String paramName) {
if (value == null || !IAM_RESOURCE_NAME_PATTERN.matcher(value).matches()) {
throw new AwsException("ValidationError",
paramName + " must be 1-128 characters matching [\\w+=,.@-].", 400);
}
}
private void validateIamPath(String value, String paramName) {
if (value == null) return;
if (value.length() > IAM_PATH_MAX_LENGTH || !IAM_PATH_PATTERN.matcher(value).matches()) {
throw new AwsException("ValidationError",
paramName + " must be at most " + IAM_PATH_MAX_LENGTH
+ " characters, either a bare forward slash or a string that begins and ends "
+ "with a forward slash.", 400);
}
}
// OIDC Identity Providers
// =========================================================================
@@ -1650,6 +1826,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return users.get(userName);
}
/**
* Looks up a user by name in a specific account's namespace, without throwing when absent.
* Mirrors {@link #findRole(String, String)} — users are account-namespaced the same way roles
* are, so a caller resolving a user from an ARN must use that ARN's account, not the ambient one.
*/
public Optional<IamUser> findUser(String accountId, String userName) {
if (users instanceof AccountAwareStorageBackend<IamUser> aware) {
return aware.getForAccount(accountId, userName);
}
return users.get(userName);
}
// =========================================================================
// IAM Enforcement — session tracking and policy collection
// =========================================================================
@@ -1923,11 +2111,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
if (principalArn.contains(":user/")) {
String userName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
List<String> identityPolicies = collectUserPolicies(userName);
List<String> identityPolicies = collectUserPolicies(principalArn);
if (identityPolicies == null) {
throw new AwsException("NoSuchEntity", "User " + userName + " cannot be found.", 404);
}
return new CallerContext(identityPolicies, null, resolveUserBoundaryDocument(userName));
return new CallerContext(identityPolicies, null, resolveUserBoundaryDocument(principalArn));
}
if (principalArn.contains(":role/")) {
String roleName = principalArn.substring(principalArn.lastIndexOf('/') + 1);
@@ -1940,8 +2128,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
throw new AwsException("InvalidInput", "PolicySourceArn must identify an IAM user or role.", 400);
}
private String resolveUserBoundaryDocument(String userName) {
return users.get(userName)
private String resolveUserBoundaryDocument(String userArnOrName) {
return userFromArnOrName(userArnOrName)
.map(IamUser::getPermissionsBoundaryArn)
.flatMap(this::resolvePolicy)
.map(IamPolicy::getDefaultDocument)
@@ -1952,8 +2140,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
if (roleArn == null) {
return null;
}
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;
return roles.get(roleName)
return roleFromArnOrName(roleArn)
.map(IamRole::getPermissionsBoundaryArn)
.flatMap(this::resolvePolicy)
.map(IamPolicy::getDefaultDocument)
@@ -2004,8 +2191,37 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
LOG.infov("Deleted permissions boundary for role: {0}", roleName);
}
private List<String> collectUserPolicies(String userName) {
Optional<IamUser> userOpt = users.get(userName);
/**
* Resolves a user for policy collection. Given an ARN, the lookup is scoped to the account the
* ARN itself names: two accounts can hold a same-named user, and evaluating account A's ARN
* against account B's policies is a cross-account authorization bypass. Given a bare name —
* the access-key path, where no ARN exists — the ambient request account still applies.
*/
private Optional<IamUser> userFromArnOrName(String userArnOrName) {
if (userArnOrName == null) {
return Optional.empty();
}
if (!userArnOrName.contains("/")) {
return users.get(userArnOrName);
}
String userName = userArnOrName.substring(userArnOrName.lastIndexOf('/') + 1);
return findUser(AwsArnUtils.accountOrDefault(userArnOrName, regionResolver.getAccountId()), userName);
}
/** Role-side counterpart of {@link #userFromArnOrName(String)}. */
private Optional<IamRole> roleFromArnOrName(String roleArnOrName) {
if (roleArnOrName == null) {
return Optional.empty();
}
if (!roleArnOrName.contains("/")) {
return roles.get(roleArnOrName);
}
String roleName = roleArnOrName.substring(roleArnOrName.lastIndexOf('/') + 1);
return findRole(AwsArnUtils.accountOrDefault(roleArnOrName, regionResolver.getAccountId()), roleName);
}
private List<String> collectUserPolicies(String userArnOrName) {
Optional<IamUser> userOpt = userFromArnOrName(userArnOrName);
if (userOpt.isEmpty()) {
return null;
}
@@ -2043,8 +2259,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
if (roleArn == null) {
return null;
}
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : roleArn;
Optional<IamRole> roleOpt = roles.get(roleName);
Optional<IamRole> roleOpt = roleFromArnOrName(roleArn);
if (roleOpt.isEmpty()) {
return null;
}
@@ -2093,4 +2308,35 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
return sb.toString();
}
public void tagInstanceProfile(String instanceProfileName, Map<String, String> newTags) {
// Request shape before resource lookup, matching untagInstanceProfile and AWS's order.
validateIamResourceName(instanceProfileName, "InstanceProfileName");
if (newTags != null && newTags.size() > MAX_TAGS_PER_INSTANCE_PROFILE) {
throw new AwsException("ValidationError",
"Value at 'tags' failed to satisfy constraint: Member must have length "
+ "less than or equal to " + MAX_TAGS_PER_INSTANCE_PROFILE, 400);
}
InstanceProfile profile = getInstanceProfile(instanceProfileName);
Map<String, String> merged = new LinkedHashMap<>(profile.getTags());
merged.putAll(newTags == null ? Map.of() : newTags);
if (merged.size() > MAX_TAGS_PER_INSTANCE_PROFILE) {
throw new AwsException("LimitExceeded",
"Cannot exceed quota for TagsPerInstanceProfile: " + MAX_TAGS_PER_INSTANCE_PROFILE, 409);
}
profile.getTags().putAll(newTags == null ? Map.of() : newTags);
instanceProfiles.put(instanceProfileName, profile);
}
public void untagInstanceProfile(String instanceProfileName, List<String> tagKeys) {
validateIamResourceName(instanceProfileName, "InstanceProfileName");
if (tagKeys != null && tagKeys.size() > MAX_TAGS_PER_INSTANCE_PROFILE) {
throw new AwsException("ValidationError",
"Value at 'tagKeys' failed to satisfy constraint: Member must have length "
+ "less than or equal to " + MAX_TAGS_PER_INSTANCE_PROFILE, 400);
}
InstanceProfile profile = getInstanceProfile(instanceProfileName);
tagKeys.forEach(profile.getTags()::remove);
instanceProfiles.put(instanceProfileName, profile);
}
}
@@ -0,0 +1,22 @@
package io.github.hectorvent.floci.services.iam;
import java.util.List;
/**
* Supplies the effective service control policies for an account, one list of policy
* documents per organization level (root, each OU on the path, then the account).
*
* <p>Implemented by the Organizations service; consumed lazily by
* {@code IamEnforcementFilter} via {@code Instance<ScpProvider>} so IAM never depends on
* Organizations directly (Organizations already depends on IAM for role provisioning).</p>
*/
public interface ScpProvider {
/**
* @return the effective SCP levels for the account, or {@code null} when SCPs don't
* apply: SCP enforcement is disabled, the account is not in an organization,
* the account is the organization's management account (exempt in AWS), or
* the SCP policy type is not enabled on the root.
*/
List<List<String>> effectiveScpLevels(String accountId);
}
@@ -10,15 +10,32 @@ import java.util.List;
* <li>{@code identityPolicies} — inline + attached policies of the user, role, and groups</li>
* <li>{@code sessionPolicyDocument} — optional inline session policy from AssumeRole (Phase 3)</li>
* <li>{@code boundaryPolicyDocument} — optional permissions boundary document (Phase 3)</li>
* <li>{@code scpLevels} — optional effective service control policies for the caller's
* account, one list of policy documents per organization level (root, each OU on the
* path, account). An action must be allowed at every level and denied at none.
* {@code null} when SCPs don't apply (no organization, management account, or SCP
* enforcement disabled).</li>
* </ul>
*/
public record CallerContext(
List<String> identityPolicies,
String sessionPolicyDocument,
String boundaryPolicyDocument
String boundaryPolicyDocument,
List<List<String>> scpLevels
) {
/** Convenience factory: no session policy, no boundary. */
/** Source-compatible constructor for callers predating SCP support. */
public CallerContext(List<String> identityPolicies, String sessionPolicyDocument,
String boundaryPolicyDocument) {
this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, null);
}
/** Convenience factory: no session policy, no boundary, no SCPs. */
public static CallerContext of(List<String> identityPolicies) {
return new CallerContext(identityPolicies, null, null);
return new CallerContext(identityPolicies, null, null, null);
}
/** Copy of this context with the effective SCP levels attached. */
public CallerContext withScpLevels(List<List<String>> levels) {
return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, levels);
}
}
@@ -20,6 +20,16 @@ public class IamPolicy {
private String description;
private String defaultVersionId = "v1";
private int attachmentCount = 0;
/**
* High-water mark for issued version numbers, so a deleted version's id is never reissued.
* Left null (rather than defaulted) so a policy persisted before this field existed is
* distinguishable from a genuinely fresh one: Jackson leaves an absent JSON field at null,
* while every policy constructed since this field shipped explicitly sets it below. A null
* value is treated at the call site as "true history unknown" and given a defensive margin
* beyond the live keys' own max, since the live keys alone cannot reveal a version deleted
* before this field ever existed on disk.
*/
private Integer nextVersionNumber;
private Instant createDate;
private Instant updateDate;
private Map<String, String> tags = new ConcurrentHashMap<>();
@@ -39,6 +49,7 @@ public class IamPolicy {
this.updateDate = Instant.now();
PolicyVersion v1 = new PolicyVersion("v1", document, true);
this.versions.put("v1", v1);
this.nextVersionNumber = 2;
}
public String getDefaultDocument() {
@@ -67,6 +78,9 @@ public class IamPolicy {
public int getAttachmentCount() { return attachmentCount; }
public void setAttachmentCount(int attachmentCount) { this.attachmentCount = attachmentCount; }
public Integer getNextVersionNumber() { return nextVersionNumber; }
public void setNextVersionNumber(Integer nextVersionNumber) { this.nextVersionNumber = nextVersionNumber; }
public Instant getCreateDate() { return createDate; }
public void setCreateDate(Instant createDate) { this.createDate = createDate; }
@@ -5,6 +5,8 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
@RegisterForReflection
@@ -17,6 +19,7 @@ public class InstanceProfile {
private String arn;
private Instant createDate;
private List<String> roleNames = new CopyOnWriteArrayList<>();
private Map<String, String> tags = new ConcurrentHashMap<>();
public InstanceProfile() {}
@@ -48,4 +51,9 @@ public class InstanceProfile {
public void setRoleNames(List<String> roleNames) {
this.roleNames = new CopyOnWriteArrayList<>(roleNames);
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(tags);
}
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.iam.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Org-wide IAM centralized root access management state.
*
* <p>Backs the IAM {@code ListOrganizationsFeatures} /
* {@code Enable|DisableOrganizationsRootCredentialsManagement} /
* {@code Enable|DisableOrganizationsRootSessions} operations. AWS exposes these on the
* IAM (Query-protocol) endpoint even though the state is organization-scoped; the set of
* currently-enabled features is what {@code ListOrganizationsFeatures} returns.
*
* <p>Recognized feature strings: {@code RootCredentialsManagement}, {@code RootSessions}.
* A {@link LinkedHashSet} keeps enablement order stable and de-duplicates, so repeated
* enable calls are idempotent.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class OrganizationRootFeatures {
private Set<String> enabledFeatures = new LinkedHashSet<>();
public Set<String> getEnabledFeatures() {
return enabledFeatures;
}
public void setEnabledFeatures(Set<String> enabledFeatures) {
this.enabledFeatures = enabledFeatures != null ? enabledFeatures : new LinkedHashSet<>();
}
}
@@ -8,6 +8,8 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.organizations.model.CreateAccountStatus;
import io.github.hectorvent.floci.services.organizations.model.Handshake;
import io.github.hectorvent.floci.services.organizations.model.HandshakeParty;
@@ -51,7 +53,7 @@ import java.util.regex.Pattern;
* @see <a href="https://docs.aws.amazon.com/organizations/latest/APIReference/Welcome.html">AWS Organizations API Reference</a>
*/
@ApplicationScoped
public class OrganizationsService {
public class OrganizationsService implements ScpProvider {
private static final Logger LOG = Logger.getLogger(OrganizationsService.class);
@@ -148,9 +150,12 @@ public class OrganizationsService {
private final AccountAwareStorageBackend<OrganizationPolicy> policies;
private final AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses;
private final AccountAwareStorageBackend<Handshake> handshakes;
private final boolean scpEnforcementEnabled;
@Inject
public OrganizationsService(StorageFactory storageFactory, ObjectMapper objectMapper) {
public OrganizationsService(StorageFactory storageFactory, ObjectMapper objectMapper,
EmulatorConfig config) {
this.scpEnforcementEnabled = config.services().organizations().scpEnforcementEnabled();
this.objectMapper = objectMapper;
this.organizations = storageFactory.create("organizations", "organizations-organizations.json",
new TypeReference<Map<String, Organization>>() {});
@@ -173,6 +178,18 @@ public class OrganizationsService {
AccountAwareStorageBackend<OrganizationPolicy> policies,
AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses,
AccountAwareStorageBackend<Handshake> handshakes) {
this(objectMapper, organizations, accounts, organizationalUnits, policies,
createAccountStatuses, handshakes, true);
}
OrganizationsService(ObjectMapper objectMapper,
AccountAwareStorageBackend<Organization> organizations,
AccountAwareStorageBackend<OrganizationAccount> accounts,
AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,
AccountAwareStorageBackend<OrganizationPolicy> policies,
AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses,
AccountAwareStorageBackend<Handshake> handshakes,
boolean scpEnforcementEnabled) {
this.objectMapper = objectMapper;
this.organizations = organizations;
this.accounts = accounts;
@@ -180,6 +197,7 @@ public class OrganizationsService {
this.policies = policies;
this.createAccountStatuses = createAccountStatuses;
this.handshakes = handshakes;
this.scpEnforcementEnabled = scpEnforcementEnabled;
}
/** A parent reference as returned by {@code ListParents}. */
@@ -872,6 +890,50 @@ public class OrganizationsService {
}
}
// ──────────────────────────── SCP provider ────────────────────────────
/**
* {@inheritDoc}
*
* <p>Levels are ordered root → OUs on the path → account. Only bites when
* {@code floci.services.organizations.scp-enforcement-enabled} is set (and, in practice,
* IAM enforcement too — {@code IamEnforcementFilter} is the only consumer). The management
* account is exempt, matching AWS.</p>
*/
@Override
public List<List<String>> effectiveScpLevels(String accountId) {
if (!scpEnforcementEnabled) {
return null;
}
Organization organization;
try {
organization = requireOrganizationForCaller(accountId);
} catch (AwsException e) {
return null;
}
if (accountId.equals(organization.getMasterAccountId())) {
return null;
}
boolean scpEnabled = organization.getRoot().getPolicyTypes().stream()
.anyMatch(t -> SERVICE_CONTROL_POLICY.equals(t.getType()) && "ENABLED".equals(t.getStatus()));
if (!scpEnabled) {
return null;
}
List<OrganizationPolicy> organizationPolicies = policiesIn(organization);
List<List<String>> levels = new ArrayList<>();
for (String node : ancestryOf(organization, accountId)) {
List<String> documents = organizationPolicies.stream()
.filter(policy -> SERVICE_CONTROL_POLICY.equals(policy.getType())
&& policy.getTargets().contains(node))
.map(OrganizationPolicy::getContent)
.toList();
if (!documents.isEmpty()) {
levels.add(documents);
}
}
return levels.isEmpty() ? null : levels;
}
// ──────────────────────────── Tags ────────────────────────────
public Map<String, String> listTagsForResource(String callerAccountId, String resourceId) {
@@ -1,21 +1,26 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.iam.IamActionRegistry;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.container.ContainerRequestContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -73,12 +78,16 @@ class IamEnforcementFilterTest {
}
private IamEnforcementFilter newFilter() {
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<io.github.hectorvent.floci.services.iam.ScpProvider> scpProvider =
mock(jakarta.enterprise.inject.Instance.class);
when(scpProvider.isResolvable()).thenReturn(false);
return new IamEnforcementFilter(
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
requestContext, conditionContextResolver,
mock(CloudTrailService.class),
mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class),
catalog);
catalog, scpProvider);
}
@Test
@@ -207,6 +216,304 @@ class IamEnforcementFilterTest {
verify(containerRequest).abortWith(any(Response.class));
}
// FullAWSAccess baseline auto-attached to every OU/account when SCP enforcement is on.
private static final String FULL_AWS_ACCESS =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
private static final String DENY_LEAVE_ORG =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\","
+ "\"Action\":\"organizations:LeaveOrganization\",\"Resource\":\"*\"}]}";
/**
* Filter whose SCP provider is resolvable (returns {@code scp}) and whose policy evaluator is
* real, so the SCP deny-ceiling is exercised in-process rather than mocked away.
*/
private IamEnforcementFilter newFilterWithScp(ScpProvider scp) {
@SuppressWarnings("unchecked")
Instance<ScpProvider> scpProvider = mock(Instance.class);
when(scpProvider.isResolvable()).thenReturn(true);
when(scpProvider.get()).thenReturn(scp);
return new IamEnforcementFilter(
config, accountResolver, iamService, new IamPolicyEvaluator(new ObjectMapper()),
actionRegistry, arnBuilder, requestContext, conditionContextResolver,
mock(CloudTrailService.class),
mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class),
catalog, scpProvider);
}
@Test
void scpDeniesLeaveOrganizationForBareAccountRootPrincipal() {
// floci's account-root principal is a bare 12-digit account-id key: resolveCallerContext
// returns null for it, but in AWS the account root is still bounded by SCPs. A workload OU
// carrying a Deny on organizations:LeaveOrganization must therefore block the member.
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
String account = "111122223333";
String auth = "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260629/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc";
requestContext.setAccountId(account);
requestContext.setRegion("us-east-1");
when(accountResolver.extractAccessKeyId(auth)).thenReturn(account);
when(accountResolver.resolve(auth)).thenReturn(account);
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(containerRequest.getMediaType())
.thenReturn(MediaType.valueOf("application/x-amz-json-1.1"));
when(actionRegistry.resolve("organizations", containerRequest))
.thenReturn("organizations:LeaveOrganization");
when(iamService.resolveCallerContext(account)).thenReturn(null); // account root: not an IAM identity
when(arnBuilder.build(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
.thenReturn("*");
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
.thenReturn(null);
ScpProvider scp = mock(ScpProvider.class);
// root(FullAWSAccess) → OU(FullAWSAccess + DenyLeaveOrg) → account(FullAWSAccess)
when(scp.effectiveScpLevels(account)).thenReturn(List.of(
List.of(FULL_AWS_ACCESS),
List.of(FULL_AWS_ACCESS, DENY_LEAVE_ORG),
List.of(FULL_AWS_ACCESS)));
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
newFilterWithScp(scp).filter(containerRequest);
verify(containerRequest).abortWith(captor.capture());
assertEquals(403, captor.getValue().getStatus());
}
@Test
void scpAllowsNonDeniedActionForBareAccountRootPrincipal() {
// Same account root + SCP chain, but an action the SCP does not deny must pass: the
// FullAWSAccess baseline allows it at every level, so we must not over-block.
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
String account = "111122223333";
String auth = "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260629/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc";
requestContext.setAccountId(account);
requestContext.setRegion("us-east-1");
when(accountResolver.extractAccessKeyId(auth)).thenReturn(account);
when(accountResolver.resolve(auth)).thenReturn(account);
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(actionRegistry.resolve("organizations", containerRequest))
.thenReturn("organizations:DescribeOrganization");
when(iamService.resolveCallerContext(account)).thenReturn(null);
when(arnBuilder.build(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
.thenReturn("*");
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
.thenReturn(null);
ScpProvider scp = mock(ScpProvider.class);
when(scp.effectiveScpLevels(account)).thenReturn(List.of(
List.of(FULL_AWS_ACCESS),
List.of(FULL_AWS_ACCESS, DENY_LEAVE_ORG),
List.of(FULL_AWS_ACCESS)));
newFilterWithScp(scp).filter(containerRequest);
verify(containerRequest, never()).abortWith(any());
// Prove the request went THROUGH evaluation rather than taking the unknown-key bypass:
// arnBuilder.build sits after the caller-resolution branch, so it only fires for a request
// that was actually evaluated. Without this, the never()-abort assertion would also pass on
// a bypass, making it no stronger than the pre-fix behavior.
verify(arnBuilder).build(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account));
}
// The realistic baseline guardrail from .temp/org-functional-test.sh: DenyLeaveOrg plus a
// DenyRootUser that fires when aws:PrincipalArn matches the account root. floci now populates
// aws:PrincipalArn as arn:aws:iam::<account>:root for the synthesized account-root principal
// (the same principal SCPs already enforce against), so this guardrail's DenyRootUser
// statement fires for every action the account-root principal takes — not just the one
// DenyLeaveOrg explicitly targets. This test locks in that faithful behavior: a maintainer
// review (pgermosen, PR #2637) flagged the earlier inert-DenyRootUser behavior as an
// inconsistency, since SCPs already treat this principal as root but the condition context
// didn't reflect it.
private static final String WORKLOAD_GUARDRAILS =
"{\"Version\":\"2012-10-17\",\"Statement\":["
+ "{\"Sid\":\"DenyLeaveOrg\",\"Effect\":\"Deny\","
+ "\"Action\":[\"organizations:LeaveOrganization\"],\"Resource\":\"*\"},"
+ "{\"Sid\":\"DenyRootUser\",\"Effect\":\"Deny\",\"Action\":\"*\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringLike\":{\"aws:PrincipalArn\":\"arn:aws:iam::*:root\"}}}]}";
@Test
void workloadGuardrailDenyRootUserFiresForAccountRootPrincipal() {
// A non-DenyLeaveOrg action is now ALSO denied under the two-statement baseline guardrail:
// DenyRootUser's blanket Action:"*" fires because aws:PrincipalArn now matches the
// synthesized account-root ARN.
ContainerRequestContext otherAction = mock(ContainerRequestContext.class);
String account = "111122223333";
String auth = "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260629/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc";
requestContext.setAccountId(account);
requestContext.setRegion("us-east-1");
when(accountResolver.extractAccessKeyId(auth)).thenReturn(account);
when(accountResolver.resolve(auth)).thenReturn(account);
when(otherAction.getHeaderString("Authorization")).thenReturn(auth);
when(otherAction.getMediaType()).thenReturn(MediaType.valueOf("application/x-amz-json-1.1"));
when(actionRegistry.resolve("organizations", otherAction))
.thenReturn("organizations:DescribeOrganization");
when(iamService.resolveCallerContext(account)).thenReturn(null);
when(arnBuilder.build(eq("organizations"), eq(otherAction), eq("us-east-1"), eq(account)))
.thenReturn("*");
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(otherAction)))
.thenReturn(null);
ScpProvider scp = mock(ScpProvider.class);
when(scp.effectiveScpLevels(account)).thenReturn(List.of(
List.of(FULL_AWS_ACCESS),
List.of(FULL_AWS_ACCESS, WORKLOAD_GUARDRAILS)));
ArgumentCaptor<Response> otherCaptor = ArgumentCaptor.forClass(Response.class);
newFilterWithScp(scp).filter(otherAction);
verify(otherAction).abortWith(otherCaptor.capture());
assertEquals(403, otherCaptor.getValue().getStatus());
// ...and the action DenyLeaveOrg explicitly targets is denied too (doubly so now).
ContainerRequestContext denied = mock(ContainerRequestContext.class);
when(denied.getHeaderString("Authorization")).thenReturn(auth);
when(denied.getMediaType()).thenReturn(MediaType.valueOf("application/x-amz-json-1.1"));
when(actionRegistry.resolve("organizations", denied))
.thenReturn("organizations:LeaveOrganization");
when(arnBuilder.build(eq("organizations"), eq(denied), eq("us-east-1"), eq(account)))
.thenReturn("*");
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(denied)))
.thenReturn(null);
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
newFilterWithScp(scp).filter(denied);
verify(denied).abortWith(captor.capture());
assertEquals(403, captor.getValue().getStatus());
}
@Test
void accountRootPrincipalPopulatesRootPrincipalArnInConditionContext() {
// Direct assertion that aws:PrincipalArn is set to the AWS root-ARN shape for the
// synthesized account-root principal: an SCP level that allows everything except an
// action explicitly conditioned on the exact root ARN must deny only that action.
String account = "444455556666";
String rootArnDeny = "{\"Version\":\"2012-10-17\",\"Statement\":["
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:ListBucket\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:PrincipalArn\":\"arn:aws:iam::"
+ account + ":root\"}}}]}";
String auth = "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260629/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=abc";
requestContext.setAccountId(account);
requestContext.setRegion("us-east-1");
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
when(ctx.getHeaderString("Authorization")).thenReturn(auth);
when(ctx.getMediaType()).thenReturn(MediaType.valueOf("application/x-amz-json-1.1"));
when(accountResolver.extractAccessKeyId(auth)).thenReturn(account);
when(accountResolver.resolve(auth)).thenReturn(account);
when(actionRegistry.resolve("s3", ctx)).thenReturn("s3:ListBucket");
when(iamService.resolveCallerContext(account)).thenReturn(null);
when(arnBuilder.build(eq("s3"), eq(ctx), eq("us-east-1"), eq(account))).thenReturn("*");
when(conditionContextResolver.resolve(eq("s3"), anyString(), eq(ctx))).thenReturn(null);
ScpProvider scp = mock(ScpProvider.class);
when(scp.effectiveScpLevels(account)).thenReturn(List.of(
List.of(FULL_AWS_ACCESS), List.of(FULL_AWS_ACCESS, rootArnDeny)));
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
newFilterWithScp(scp).filter(ctx);
verify(ctx).abortWith(captor.capture());
assertEquals(403, captor.getValue().getStatus());
}
// aws:PrincipalArn is populated only for principals whose ARN is known — IAM users and
// assumed-role sessions (IamService.resolveCallerArn). A condition-scoped SCP keyed on the
// principal ARN must therefore fire for a real IAM identity. It stays inert for the bare
// account-root key, whose resolveCallerArn is empty (see the workload-guardrails test above).
private static final String DENY_IAM_USER_PRINCIPAL =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"*\","
+ "\"Resource\":\"*\",\"Condition\":{\"StringLike\":"
+ "{\"aws:PrincipalArn\":\"arn:aws:iam::*:user/*\"}}}]}";
@Test
void scpConditionOnPrincipalArnDeniesRealIamIdentity() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
String account = "111122223333";
String akid = "AKIAALICEEXAMPLE";
String auth = "AWS4-HMAC-SHA256 Credential=" + akid
+ "/20260629/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc";
requestContext.setAccountId(account);
requestContext.setRegion("us-east-1");
when(accountResolver.extractAccessKeyId(auth)).thenReturn(akid);
when(accountResolver.resolve(auth)).thenReturn(account);
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(containerRequest.getMediaType()).thenReturn(MediaType.valueOf("application/x-amz-json-1.1"));
when(actionRegistry.resolve("organizations", containerRequest))
.thenReturn("organizations:DescribeOrganization");
// A real IAM user: full-access identity policy plus a known principal ARN.
when(iamService.resolveCallerContext(akid))
.thenReturn(CallerContext.of(List.of(FULL_AWS_ACCESS)));
when(iamService.resolveCallerArn(akid))
.thenReturn(Optional.of("arn:aws:iam::" + account + ":user/alice"));
when(arnBuilder.build(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
.thenReturn("*");
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
.thenReturn(null);
ScpProvider scp = mock(ScpProvider.class);
when(scp.effectiveScpLevels(account)).thenReturn(List.of(
List.of(FULL_AWS_ACCESS),
List.of(FULL_AWS_ACCESS, DENY_IAM_USER_PRINCIPAL)));
ArgumentCaptor<Response> captor = ArgumentCaptor.forClass(Response.class);
newFilterWithScp(scp).filter(containerRequest);
// aws:PrincipalArn is now populated for the IAM user, so the principal-scoped Deny matches.
verify(containerRequest).abortWith(captor.capture());
assertEquals(403, captor.getValue().getStatus());
}
// Populating aws:PrincipalArn is bidirectional: it lets a principal-scoped Deny fire (above) AND
// lets a principal-scoped Allow match. An identity policy that grants access only when the caller
// is an IAM user must therefore ALLOW a real IAM user. Before aws:PrincipalArn was populated the
// key was absent, the StringLike failed, the sole Allow never matched, and the request was denied
// by default — so stubbing resolveCallerArn empty makes this test RED, proving it is load-bearing.
private static final String ALLOW_IF_IAM_USER_PRINCIPAL =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\","
+ "\"Resource\":\"*\",\"Condition\":{\"StringLike\":"
+ "{\"aws:PrincipalArn\":\"arn:aws:iam::*:user/*\"}}}]}";
@Test
void identityPolicyAllowGatedOnPrincipalArnMatchesRealIamIdentity() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
String account = "111122223333";
String akid = "AKIABOBEXAMPLE";
String auth = "AWS4-HMAC-SHA256 Credential=" + akid
+ "/20260629/us-east-1/organizations/aws4_request, SignedHeaders=host, Signature=abc";
requestContext.setAccountId(account);
requestContext.setRegion("us-east-1");
when(accountResolver.extractAccessKeyId(auth)).thenReturn(akid);
when(accountResolver.resolve(auth)).thenReturn(account);
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(actionRegistry.resolve("organizations", containerRequest))
.thenReturn("organizations:DescribeOrganization");
// A real IAM user whose ONLY grant is conditional on being an IAM-user principal.
when(iamService.resolveCallerContext(akid))
.thenReturn(CallerContext.of(List.of(ALLOW_IF_IAM_USER_PRINCIPAL)));
when(iamService.resolveCallerArn(akid))
.thenReturn(Optional.of("arn:aws:iam::" + account + ":user/bob"));
when(arnBuilder.build(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
.thenReturn("*");
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
.thenReturn(null);
// No SCP ceiling (effectiveScpLevels → null) so the identity-policy Allow is the deciding factor.
ScpProvider scp = mock(ScpProvider.class);
when(scp.effectiveScpLevels(account)).thenReturn(null);
newFilterWithScp(scp).filter(containerRequest);
// aws:PrincipalArn matches arn:aws:iam::*:user/* → the conditional Allow grants access.
verify(containerRequest, never()).abortWith(any());
verify(arnBuilder).build(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account));
}
@Test
void queryProtocolGetsXmlErrorResponse() {
// IAM/STS/EC2/SQS/SNS/RDS/ELBv2/CFN/... — Query protocol, form-encoded body, XML response.
@@ -34,6 +34,7 @@ class IamManagedPolicyAccountScopeTest {
private static final String DEFAULT_ACCT = "000000000000";
private static final String REQUEST_ACCT = "111111111111";
private static final String OTHER_ACCT = "222222222222";
@SuppressWarnings("unchecked")
private static Instance<RequestContext> requestContextFor(String accountId) {
@@ -315,6 +316,72 @@ class IamManagedPolicyAccountScopeTest {
assertEquals("acct-two", otherAccount.getAccountAlias().orElseThrow());
}
/**
* A principal ARN names its own account. Resolving it against the ambient request account
* instead means that when two accounts each hold a same-named role or user, a caller
* presenting account A's ARN can be evaluated against account B's policies — a cross-account
* authorization bypass in either direction.
*/
@Test
void aRoleArnResolvesTheNamedAccountsPoliciesNotTheRequestAccounts() {
String roleName = "app-role";
String docA = "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\"}]}";
String docB = "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\"}]}";
String trust = "{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}}]}";
// The request runs as REQUEST_ACCT; only the ARN says which account owns the role.
AccountAwareStorageBackend<IamRole> roles = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), requestContextFor(REQUEST_ACCT), DEFAULT_ACCT);
IamRole roleA = new IamRole("AROLEA0000000001", roleName, "/",
"arn:aws:iam::" + REQUEST_ACCT + ":role/" + roleName, trust);
roleA.getInlinePolicies().put("inline", docA);
roles.putForAccount(REQUEST_ACCT, roleName, roleA);
IamRole roleB = new IamRole("AROLEB0000000001", roleName, "/",
"arn:aws:iam::" + OTHER_ACCT + ":role/" + roleName, trust);
roleB.getInlinePolicies().put("inline", docB);
roles.putForAccount(OTHER_ACCT, roleName, roleB);
IamService service = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), roles,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", DEFAULT_ACCT));
assertEquals(List.of(docA), service.resolvePrincipalContext(
"arn:aws:iam::" + REQUEST_ACCT + ":role/" + roleName).identityPolicies());
assertEquals(List.of(docB), service.resolvePrincipalContext(
"arn:aws:iam::" + OTHER_ACCT + ":role/" + roleName).identityPolicies());
}
@Test
void aUserArnResolvesTheNamedAccountsPoliciesNotTheRequestAccounts() {
String userName = "alice";
String docA = "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\"}]}";
String docB = "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\"}]}";
AccountAwareStorageBackend<IamUser> users = new AccountAwareStorageBackend<>(
new InMemoryStorage<>(), requestContextFor(REQUEST_ACCT), DEFAULT_ACCT);
IamUser userA = new IamUser("AIDAA00000000001", userName, "/",
"arn:aws:iam::" + REQUEST_ACCT + ":user/" + userName);
userA.getInlinePolicies().put("inline", docA);
users.putForAccount(REQUEST_ACCT, userName, userA);
IamUser userB = new IamUser("AIDAB00000000001", userName, "/",
"arn:aws:iam::" + OTHER_ACCT + ":user/" + userName);
userB.getInlinePolicies().put("inline", docB);
users.putForAccount(OTHER_ACCT, userName, userB);
IamService service = new IamService(
users, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", DEFAULT_ACCT));
assertEquals(List.of(docA), service.resolvePrincipalContext(
"arn:aws:iam::" + REQUEST_ACCT + ":user/" + userName).identityPolicies());
assertEquals(List.of(docB), service.resolvePrincipalContext(
"arn:aws:iam::" + OTHER_ACCT + ":user/" + userName).identityPolicies());
}
private static IamService serviceWithAliases(AccountAwareStorageBackend<String> aliases) {
return new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.iam.model.OrganizationRootFeatures;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* IAM centralized root access management: {@code ListOrganizationsFeatures} +
* enable/disable of {@code RootCredentialsManagement} / {@code RootSessions}.
*
* <p>Consumer contract (LZA v1.16 {@code root-user-management} module,
* {@code aws-iam/root-user-management/index.ts}): the module reads only the enabled-feature
* set from {@code ListOrganizationsFeatures}; a successful call means the service is
* reachable, and each present feature flips the corresponding config flag on. Our config
* enables both, starting from an empty set, so the module calls both enable ops.
*/
class IamOrganizationsRootFeaturesTest {
private static final String ROOT_CREDS = "RootCredentialsManagement";
private static final String ROOT_SESSIONS = "RootSessions";
@Test
void startsWithNoEnabledFeatures() {
IamService svc = newInMemoryService();
assertTrue(svc.listOrganizationsFeatures().isEmpty(),
"a fresh org has no centralized root features enabled");
}
@Test
void enableAddsFeaturesAndIsIdempotent() {
IamService svc = newInMemoryService();
List<String> afterCreds = svc.enableOrganizationsRootCredentialsManagement();
assertTrue(afterCreds.contains(ROOT_CREDS));
assertFalse(afterCreds.contains(ROOT_SESSIONS));
List<String> afterSessions = svc.enableOrganizationsRootSessions();
assertTrue(afterSessions.contains(ROOT_CREDS));
assertTrue(afterSessions.contains(ROOT_SESSIONS));
// Enabling again must not duplicate.
svc.enableOrganizationsRootCredentialsManagement();
svc.enableOrganizationsRootSessions();
assertEquals(2, svc.listOrganizationsFeatures().size());
}
@Test
void disableRemovesFeatures() {
IamService svc = newInMemoryService();
svc.enableOrganizationsRootCredentialsManagement();
svc.enableOrganizationsRootSessions();
List<String> afterDisableSessions = svc.disableOrganizationsRootSessions();
assertTrue(afterDisableSessions.contains(ROOT_CREDS));
assertFalse(afterDisableSessions.contains(ROOT_SESSIONS));
List<String> afterDisableCreds = svc.disableOrganizationsRootCredentialsManagement();
assertTrue(afterDisableCreds.isEmpty());
}
@Test
void enabledFeaturesSurviveRestart(@TempDir Path dir) {
IamService first = newPersistentService(dir);
first.enableOrganizationsRootCredentialsManagement();
first.enableOrganizationsRootSessions();
IamService restarted = newPersistentService(dir);
List<String> loaded = restarted.listOrganizationsFeatures();
assertTrue(loaded.contains(ROOT_CREDS));
assertTrue(loaded.contains(ROOT_SESSIONS));
assertEquals(2, loaded.size());
}
private IamService newInMemoryService() {
return new IamService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"),
false
);
}
private IamService newPersistentService(Path dir) {
return new IamService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
loadRootFeatures(dir),
new RegionResolver("us-east-1", "000000000000"),
false
);
}
private StorageBackend<String, OrganizationRootFeatures> loadRootFeatures(Path dir) {
PersistentStorage<String, OrganizationRootFeatures> backend = new PersistentStorage<>(
dir.resolve("iam-org-root-features.json"),
new TypeReference<Map<String, OrganizationRootFeatures>>() {}
);
backend.load();
return backend;
}
}
@@ -0,0 +1,104 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* SCP semantics in policy evaluation: service control policies gate the decision before
* identity policies, an action must be allowed at every organization level, and a deny
* at any level wins regardless of identity-policy allows.
*/
class IamPolicyEvaluatorTest {
private static final String ALLOW_ALL =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"*\",\"Resource\":\"*\"}]}";
private static final String ALLOW_S3_ONLY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Action\":\"s3:*\",\"Resource\":\"*\"}]}";
private static final String DENY_S3 =
"{\"Version\":\"2012-10-17\",\"Statement\":["
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}";
private static final String MALFORMED = "{\"Version\":\"2012-10-17\",\"Statement\":[";
private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
private static CallerContext adminWithScps(List<List<String>> scpLevels) {
return CallerContext.of(List.of(ALLOW_ALL)).withScpLevels(scpLevels);
}
@Test
void withoutScpLevelsIdentityDecides() {
CallerContext caller = CallerContext.of(List.of(ALLOW_ALL));
assertEquals(Decision.ALLOW,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
}
@Test
void scpDenyWinsOverIdentityAllow() {
CallerContext caller = adminWithScps(List.of(List.of(DENY_S3)));
assertEquals(Decision.DENY,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
assertEquals(Decision.ALLOW,
evaluator.evaluate(caller, null, "ec2:DescribeInstances", "*", null));
}
@Test
void actionMustBeAllowedAtEveryLevel() {
// Root allows everything, the OU level only allows s3.
CallerContext caller = adminWithScps(List.of(List.of(ALLOW_ALL), List.of(ALLOW_S3_ONLY)));
assertEquals(Decision.ALLOW,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
assertEquals(Decision.DENY,
evaluator.evaluate(caller, null, "ec2:DescribeInstances", "*", null));
}
@Test
void scpAllowIsNotAGrant() {
// SCPs permit s3 but the identity has no policy allowing it: still denied.
CallerContext caller = CallerContext.of(List.of())
.withScpLevels(List.of(List.of(ALLOW_ALL)));
assertEquals(Decision.DENY,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
}
@Test
void unparseableScpDeniesEvenWhenTheLevelAlsoHoldsFullAwsAccess() {
// FullAWSAccess is attached to every target, so a level almost always carries it
// alongside the customer's guardrail. Dropping the malformed guardrail would leave
// FullAWSAccess allowing the action — the ceiling has to fail closed instead.
CallerContext caller = adminWithScps(List.of(List.of(MALFORMED, ALLOW_ALL)));
assertEquals(Decision.DENY,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
}
@Test
void allUnparseableScpsInALevelDeny() {
CallerContext caller = adminWithScps(List.of(List.of(MALFORMED)));
assertEquals(Decision.DENY,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
}
@Test
void unparseableIdentityPolicyDoesNotAffectOtherPolicies() {
// Only the SCP ceiling fails closed; identity evaluation keeps skipping bad documents.
CallerContext caller = CallerContext.of(List.of(MALFORMED, ALLOW_ALL));
assertEquals(Decision.ALLOW,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
}
@Test
void emptyLevelIsFullAwsAccessSemantics() {
CallerContext caller = adminWithScps(List.of(List.of(), List.of(ALLOW_ALL)));
assertEquals(Decision.ALLOW,
evaluator.evaluate(caller, null, "s3:GetObject", "*", null));
}
}
@@ -269,7 +269,7 @@ class IamServiceLinkedRoleIntegrationTest {
.then()
.statusCode(200)
.body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName",
equalTo("AWSServiceRoleForAutoscaling_CustomResource"));
equalTo("AWSServiceRoleForAutoScaling_CustomResource"));
}
/** AWS constrains AWSServiceName to [\w+=,.@-]{1,128}; anything else must not reach storage. */
@@ -586,4 +586,22 @@ class IamServiceLinkedRoleIntegrationTest {
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
}
@Test
@Order(24)
void cloud9UsesTheAwsCanonicalRoleName() {
given()
.formParam("Action", "CreateServiceLinkedRole")
.formParam("AWSServiceName", "cloud9.amazonaws.com")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName",
equalTo("AWSServiceRoleForAWSCloud9"))
.body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.Arn",
equalTo("arn:aws:iam::000000000000:role/aws-service-role/cloud9.amazonaws.com/"
+ "AWSServiceRoleForAWSCloud9"));
}
}
@@ -217,6 +217,28 @@ class IamServiceTest {
// Roles
// =========================================================================
@Test
void createServiceLinkedRoleForEc2AutoScalingUsesAwsCanonicalName() {
IamRole role = iamService.createServiceLinkedRole(
"autoscaling.amazonaws.com", null, "EC2 Auto Scaling SLR");
assertEquals("AWSServiceRoleForAutoScaling", role.getRoleName());
assertEquals(
"arn:aws:iam::000000000000:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling",
role.getArn());
}
@Test
void createServiceLinkedRoleForCloud9UsesAwsCanonicalName() {
IamRole role = iamService.createServiceLinkedRole(
"cloud9.amazonaws.com", null, "Cloud9 SLR");
assertEquals("AWSServiceRoleForAWSCloud9", role.getRoleName());
assertEquals(
"arn:aws:iam::000000000000:role/aws-service-role/cloud9.amazonaws.com/AWSServiceRoleForAWSCloud9",
role.getArn());
}
@Test
void createAndGetRole() {
String trustPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
@@ -267,6 +289,28 @@ class IamServiceTest {
"rejected update must not have changed the role's trust policy");
}
@Test
void createServiceLinkedRoleForAccessAnalyzer() {
IamRole role = iamService.createServiceLinkedRole(
"access-analyzer.amazonaws.com", null, "Access Analyzer SLR");
assertEquals("AWSServiceRoleForAccessAnalyzer", role.getRoleName());
assertEquals("/aws-service-role/access-analyzer.amazonaws.com/", role.getPath());
assertTrue(role.getRoleId().startsWith("AROA"));
assertEquals(
"arn:aws:iam::000000000000:role/aws-service-role/access-analyzer.amazonaws.com/AWSServiceRoleForAccessAnalyzer",
role.getArn());
assertTrue(role.getAssumeRolePolicyDocument().contains("access-analyzer.amazonaws.com"),
"trust policy should allow the service principal");
}
@Test
void createServiceLinkedRoleWithCustomSuffix() {
IamRole role = iamService.createServiceLinkedRole(
"access-analyzer.amazonaws.com", "myapp", null);
assertEquals("AWSServiceRoleForAccessAnalyzer_myapp", role.getRoleName());
}
@Test
void deleteRoleWithAttachedPolicyFails() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
@@ -339,6 +383,100 @@ class IamServiceTest {
() -> iamService.createPolicyVersion(arn, "{\"v\":6}", false));
}
@Test
void createPolicyVersionAfterDeletionDoesNotReuseVersionIds() {
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
String arn = policy.getArn();
for (int i = 2; i <= 5; i++) {
iamService.createPolicyVersion(arn, "{\"v\":" + i + "}", true);
}
// Prune the oldest non-default version (what CloudFormation does at the cap) and
// create another. AWS version ids are monotonic — a deleted id is never reissued,
// so the new version must be v6, not a rewrite of the surviving v5.
iamService.deletePolicyVersion(arn, "v1");
PolicyVersion next = iamService.createPolicyVersion(arn, "{\"v\":6}", true);
assertEquals("v6", next.getVersionId());
assertEquals("{\"v\":5}", iamService.getPolicyVersion(arn, "v5").getDocument());
}
@Test
void createPolicyVersionAfterDeletingHighestSurvivingIdDoesNotReuseIt() {
// Deleting the HIGHEST surviving version (not the oldest, as above) is the case that
// breaks a "derive from the live keys" implementation: with v5 gone, the live max is v4,
// so a naive next-id computation reissues v5 rather than advancing to v6.
IamPolicy policy = iamService.createPolicy("P", "/", null, "{}", null);
String arn = policy.getArn();
for (int i = 2; i <= 5; i++) {
iamService.createPolicyVersion(arn, "{\"v\":" + i + "}", false);
}
iamService.deletePolicyVersion(arn, "v5");
PolicyVersion next = iamService.createPolicyVersion(arn, "{\"v\":6}", false);
assertEquals("v6", next.getVersionId());
assertEquals("{\"v\":4}", iamService.getPolicyVersion(arn, "v4").getDocument());
}
@Test
void createPolicyVersionOnLegacyRehydratedPolicyDoesNotReuseADeletedTopVersion() {
// Simulates a policy persisted by a Floci version that predates nextVersionNumber: the
// field is absent from the old JSON, so it rehydrates at the class's fresh-policy default
// (2) regardless of how many versions actually existed historically. Here we seed the
// versions map directly (bypassing createPolicyVersion, which is the only path that would
// have kept nextVersionNumber honest) to reproduce exactly that rehydrated shape: v1-v4
// live, as if v5 had been created and deleted before this field ever existed on disk.
IamPolicy policy = iamService.createPolicy("LegacyP", "/", null, "{\"v\":1}", null);
String arn = policy.getArn();
for (int i = 2; i <= 4; i++) {
policy.getVersions().put("v" + i,
new io.github.hectorvent.floci.services.iam.model.PolicyVersion(
"v" + i, "{\"v\":" + i + "}", false));
}
policy.setNextVersionNumber(null); // Jackson leaves this null when absent from old JSON
PolicyVersion next = iamService.createPolicyVersion(arn, "{\"v\":next}", false);
assertNotEquals("v5", next.getVersionId(),
"a legacy-rehydrated policy must not reissue the id of a version deleted before upgrade");
}
@Test
void updateGroupMalformedNewGroupNameIsRejected() {
iamService.createGroup("orig-group", "/");
assertThrows(AwsException.class,
() -> iamService.updateGroup("orig-group", "not a valid name!", null));
}
@Test
void groupRenamePreservesPolicyResolutionForExistingMembers() {
iamService.createGroup("g-rename", "/");
iamService.putGroupPolicy("g-rename", "p",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}");
iamService.createUser("member-user", "/");
iamService.addUserToGroup("g-rename", "member-user");
AccessKey key = iamService.createAccessKey("member-user");
iamService.updateGroup("g-rename", "g-renamed", null);
List<String> policies = iamService.resolveCallerPolicies(key.getAccessKeyId());
assertNotNull(policies);
assertTrue(policies.stream().anyMatch(doc -> doc.contains("\"Resource\":\"*\"")),
"group policy should still resolve for the member after the group is renamed");
assertTrue(iamService.listGroupsForUser("member-user").stream()
.anyMatch(g -> g.getGroupName().equals("g-renamed")),
"ListGroupsForUser should reflect the new group name");
}
@Test
void instanceProfileSetTagsRejectsNullAndDefensivelyCopies() {
InstanceProfile profile = new InstanceProfile("AIPAX", "p", "/", "arn:aws:iam::111111111111:instance-profile/p");
profile.setTags(null);
assertNotNull(profile.getTags());
assertTrue(profile.getTags().isEmpty());
Map<String, String> source = new java.util.HashMap<>(Map.of("k", "v"));
profile.setTags(source);
source.put("k2", "v2");
assertFalse(profile.getTags().containsKey("k2"),
"setTags should defensively copy, not alias the caller's map");
}
@Test
void deletePolicyWithAttachmentsFails() {
iamService.createUser("alice", "/");
@@ -767,6 +905,28 @@ class IamServiceTest {
IamPolicy bedrockReadOnly = iamService.getPolicy("arn:aws:iam::aws:policy/AmazonBedrockReadOnly");
assertEquals("AmazonBedrockReadOnly", bedrockReadOnly.getPolicyName());
assertEquals("/", bedrockReadOnly.getPath());
// LZA's OperationsStack attaches these to its AWS Backup service roles.
IamPolicy backup = iamService.getPolicy(
"arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup");
assertEquals("AWSBackupServiceRolePolicyForBackup", backup.getPolicyName());
assertEquals("/service-role/", backup.getPath());
IamPolicy restore = iamService.getPolicy(
"arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores");
assertEquals("AWSBackupServiceRolePolicyForRestores", restore.getPolicyName());
assertEquals("/service-role/", restore.getPath());
// The S3 variants live at the root path in real AWS, not /service-role/.
IamPolicy s3Backup = iamService.getPolicy(
"arn:aws:iam::aws:policy/AWSBackupServiceRolePolicyForS3Backup");
assertEquals("AWSBackupServiceRolePolicyForS3Backup", s3Backup.getPolicyName());
assertEquals("/", s3Backup.getPath());
IamPolicy s3Restore = iamService.getPolicy(
"arn:aws:iam::aws:policy/AWSBackupServiceRolePolicyForS3Restore");
assertEquals("AWSBackupServiceRolePolicyForS3Restore", s3Restore.getPolicyName());
assertEquals("/", s3Restore.getPath());
}
@Test
@@ -0,0 +1,105 @@
package io.github.hectorvent.floci.services.iam;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* Wire-level tests for {@code UpdateGroup}.
*
* <p>New class, not appended to {@code IamIntegrationTest} (which shares mutable
* state across {@code @Order}-sequenced tests), so falsifiability isolates per
* operation (CS-001).
*/
@QuarkusTest
class IamUpdateGroupConsumerTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static Response call(String action, String... formParams) {
var request = given().formParam("Action", action).header("Authorization", AUTH_HEADER);
for (int i = 0; i < formParams.length; i += 2) {
request = request.formParam(formParams[i], formParams[i + 1]);
}
return request.when().post("/");
}
private static void createGroup(String name) {
call("CreateGroup", "GroupName", name).then().statusCode(200);
}
@Test
void updateGroup_renamesGroup() {
createGroup("ab-update-group-before");
call("UpdateGroup", "GroupName", "ab-update-group-before", "NewGroupName", "ab-update-group-after")
.then()
.statusCode(200);
call("GetGroup", "GroupName", "ab-update-group-after")
.then()
.statusCode(200)
.body("GetGroupResponse.GetGroupResult.Group.GroupName", equalTo("ab-update-group-after"));
call("GetGroup", "GroupName", "ab-update-group-before")
.then()
.statusCode(404);
}
@Test
void updateGroup_changesPath() {
createGroup("ab-update-group-path");
call("UpdateGroup", "GroupName", "ab-update-group-path", "NewPath", "/custom/")
.then()
.statusCode(200);
call("GetGroup", "GroupName", "ab-update-group-path")
.then()
.statusCode(200)
.body("GetGroupResponse.GetGroupResult.Group.Path", equalTo("/custom/"))
.body("GetGroupResponse.GetGroupResult.Group.Arn", containsString(":group/custom/"));
}
@Test
void updateGroup_newNameAlreadyExists_returnsEntityAlreadyExists() {
createGroup("ab-update-group-existing-1");
createGroup("ab-update-group-existing-2");
call("UpdateGroup", "GroupName", "ab-update-group-existing-1",
"NewGroupName", "ab-update-group-existing-2")
.then()
.statusCode(409)
.body(containsString("EntityAlreadyExists"));
}
@Test
void updateGroup_unknownGroup_returnsNoSuchEntity() {
call("UpdateGroup", "GroupName", "ab-update-group-doesnotexist", "NewPath", "/x/")
.then()
.statusCode(404);
}
@Test
void updateGroup_malformedGroupName_returnsValidationError() {
call("UpdateGroup", "GroupName", "not a valid name!", "NewPath", "/x/")
.then()
.statusCode(400)
.body(containsString("ValidationError"));
}
@Test
void updateGroup_malformedNewPath_returnsValidationError() {
createGroup("ab-update-group-bad-path");
call("UpdateGroup", "GroupName", "ab-update-group-bad-path", "NewPath", "no-leading-slash")
.then()
.statusCode(400)
.body(containsString("ValidationError"));
}
}
@@ -0,0 +1,200 @@
package io.github.hectorvent.floci.services.iam;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
/**
* Verifies TagInstanceProfile and UntagInstanceProfile wire compatibility:
* successful tagging/untagging returns 200 XML, and tagging a nonexistent
* profile returns NoSuchEntity (404).
*/
@QuarkusTest
class InstanceProfileTagsIntegrationTest {
private static final String ACCOUNT = "111111111111";
private static String auth(String account, String service) {
return "AWS4-HMAC-SHA256 Credential=" + account + "/20260215/us-east-1/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
private static void createProfile(String name) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateInstanceProfile")
.formParam("InstanceProfileName", name)
.header("Authorization", auth(ACCOUNT, "iam"))
.when().post("/")
.then().statusCode(200);
}
@Test
void tagInstanceProfileReturns200() {
String profile = "tag-test-" + UUID.randomUUID().toString().substring(0, 8);
createProfile(profile);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "TagInstanceProfile")
.formParam("InstanceProfileName", profile)
.formParam("Tags.member.1.Key", "team")
.formParam("Tags.member.1.Value", "platform")
.header("Authorization", auth(ACCOUNT, "iam"))
.when().post("/")
.then().statusCode(200);
}
@Test
void untagInstanceProfileReturns200() {
String profile = "untag-test-" + UUID.randomUUID().toString().substring(0, 8);
createProfile(profile);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UntagInstanceProfile")
.formParam("InstanceProfileName", profile)
.formParam("TagKeys.member.1", "team")
.header("Authorization", auth(ACCOUNT, "iam"))
.when().post("/")
.then().statusCode(200);
}
private static io.restassured.specification.RequestSpecification tagRequest(String profile,
int from, int to) {
var request = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "TagInstanceProfile")
.formParam("InstanceProfileName", profile)
.header("Authorization", auth(ACCOUNT, "iam"));
for (int i = from; i <= to; i++) {
request.formParam("Tags.member." + (i - from + 1) + ".Key", "key" + i)
.formParam("Tags.member." + (i - from + 1) + ".Value", "value" + i);
}
return request;
}
/**
* {@code tagListType} is {@code max: 50}, so a request carrying more than 50 tags is a
* request-shape failure, checked before the profile is even resolved. Without it the extra
* tags landed in the profile's stored tag map and GetInstanceProfile reported a resource
* AWS could never have produced.
*/
@Test
void tagInstanceProfileBeyondFiftyTagsInOneRequestReturnsValidationError() {
String profile = "tag-limit-" + UUID.randomUUID().toString().substring(0, 8);
createProfile(profile);
tagRequest(profile, 1, 51)
.when().post("/")
.then().statusCode(400)
.body(containsString("ValidationError"));
// Nothing was stored: the profile still reports no tags.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetInstanceProfile")
.formParam("InstanceProfileName", profile)
.header("Authorization", auth(ACCOUNT, "iam"))
.when().post("/")
.then().statusCode(200)
.body(org.hamcrest.Matchers.not(containsString("key1")));
}
/**
* The 50-tag cap is a per-resource quota, so two in-shape requests that together exceed it
* are rejected as LimitExceeded rather than silently over-filling the stored tag map.
*/
@Test
void tagInstanceProfileBeyondFiftyTagsAcrossRequestsReturnsLimitExceeded() {
String profile = "tag-quota-" + UUID.randomUUID().toString().substring(0, 8);
createProfile(profile);
tagRequest(profile, 1, 30).when().post("/").then().statusCode(200);
tagRequest(profile, 31, 60)
.when().post("/")
.then().statusCode(409)
.body(containsString("LimitExceeded"));
// The second request was rejected whole: none of its keys landed.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetInstanceProfile")
.formParam("InstanceProfileName", profile)
.header("Authorization", auth(ACCOUNT, "iam"))
.when().post("/")
.then().statusCode(200)
.body(org.hamcrest.Matchers.not(containsString("key60")));
}
/** {@code tagKeyListType} is {@code max: 50} on the request itself. */
@Test
void untagInstanceProfileBeyondFiftyKeysReturnsValidationError() {
String profile = "untag-limit-" + UUID.randomUUID().toString().substring(0, 8);
createProfile(profile);
var request = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UntagInstanceProfile")
.formParam("InstanceProfileName", profile)
.header("Authorization", auth(ACCOUNT, "iam"));
for (int i = 1; i <= 51; i++) {
request.formParam("TagKeys.member." + i, "key" + i);
}
request.when().post("/")
.then().statusCode(400)
.body(containsString("ValidationError"));
}
@Test
void untagInstanceProfileMalformedNameReturnsValidationError() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UntagInstanceProfile")
.formParam("InstanceProfileName", "not a valid name!")
.formParam("TagKeys.member.1", "team")
.header("Authorization", auth(ACCOUNT, "iam"))
.when().post("/")
.then().statusCode(400)
.body(containsString("ValidationError"));
}
@Test
void tagNonexistentProfileReturnsNoSuchEntity() {
String profile = "no-such-" + UUID.randomUUID().toString().substring(0, 8);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "TagInstanceProfile")
.formParam("InstanceProfileName", profile)
.formParam("Tags.member.1.Key", "team")
.formParam("Tags.member.1.Value", "platform")
.header("Authorization", auth(ACCOUNT, "iam"))
.when().post("/")
.then().statusCode(404)
.body(containsString("NoSuchEntity"));
}
/**
* {@code instanceProfileNameType} is {@code [\w+=,.@-]{1,128}}, so a name outside that shape
* is a request-shape failure, checked before the profile is resolved — otherwise a malformed
* name would surface as NoSuchEntity instead of the ValidationError AWS returns.
*/
@Test
void tagInstanceProfileMalformedNameReturnsValidationError() {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "TagInstanceProfile")
.formParam("InstanceProfileName", "not a valid name!")
.formParam("Tags.member.1.Key", "team")
.formParam("Tags.member.1.Value", "platform")
.header("Authorization", auth(ACCOUNT, "iam"))
.when().post("/")
.then().statusCode(400)
.body(containsString("ValidationError"));
}
}
@@ -0,0 +1,130 @@
package io.github.hectorvent.floci.services.iam;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.config;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
/**
* End-to-end proof that a service control policy actually denies a member account's action once
* both IAM enforcement and SCP enforcement are on.
*
* <p>floci's account-root principal is a bare 12-digit account-id access key. That principal has no
* registered IAM identity, so before the {@link IamEnforcementFilter} account-root fix it slipped
* past enforcement entirely — a {@code DenyLeaveOrganization} SCP attached to a workload OU did not
* stop the member from leaving. This test drives the full Organizations control plane over HTTP
* (management sets up org + OU + deny-SCP + member) and asserts that the member's
* {@code LeaveOrganization} is denied with 403 while a non-denied action still succeeds.</p>
*/
@QuarkusTest
@TestProfile(ScpEnforcementLeaveOrganizationIntegrationTest.ScpEnforcementProfile.class)
class ScpEnforcementLeaveOrganizationIntegrationTest {
private static final String MGMT = "000000000000";
private static final String REGION = "us-east-1";
private static final String DENY_LEAVE_ORG_SCP = """
{"Version":"2012-10-17","Statement":[
{"Sid":"DenyLeaveOrg","Effect":"Deny",
"Action":"organizations:LeaveOrganization","Resource":"*"}]}""";
@Test
void scpDeniesMemberLeaveOrganizationButAllowsOtherActions() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
// --- management sets up the organization -----------------------------------------------
org(MGMT, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}").then().statusCode(200);
// FeatureSet=ALL already enables the SERVICE_CONTROL_POLICY type on the root and seeds
// FullAWSAccess, so no explicit EnablePolicyType is needed for SCPs to participate.
String rootId = JsonPath.from(org(MGMT, "ListRoots", "{}").asString()).getString("Roots[0].Id");
String policyId = JsonPath.from(org(MGMT, "CreatePolicy",
"{\"Name\":\"deny-leave-" + suffix + "\",\"Type\":\"SERVICE_CONTROL_POLICY\","
+ "\"Description\":\"deny leave org\",\"Content\":"
+ jsonString(DENY_LEAVE_ORG_SCP) + "}").asString())
.getString("Policy.PolicySummary.Id");
String ouId = JsonPath.from(org(MGMT, "CreateOrganizationalUnit",
"{\"ParentId\":\"" + rootId + "\",\"Name\":\"Denied-" + suffix + "\"}").asString())
.getString("OrganizationalUnit.Id");
org(MGMT, "AttachPolicy",
"{\"PolicyId\":\"" + policyId + "\",\"TargetId\":\"" + ouId + "\"}")
.then().statusCode(200);
// CreateAccount is synchronous in floci: the account id is present on the returned status.
String memberId = JsonPath.from(org(MGMT, "CreateAccount",
"{\"AccountName\":\"member-" + suffix + "\",\"Email\":\"member-" + suffix + "@floci.test\"}")
.asString()).getString("CreateAccountStatus.AccountId");
org(MGMT, "MoveAccount",
"{\"AccountId\":\"" + memberId + "\",\"SourceParentId\":\"" + rootId
+ "\",\"DestinationParentId\":\"" + ouId + "\"}")
.then().statusCode(200);
// --- the member is now bounded by the OU's deny SCP ------------------------------------
org(memberId, "LeaveOrganization", "{}")
.then()
.statusCode(403)
.body(containsString("AccessDeniedException"));
// An action the SCP does not deny must still succeed (FullAWSAccess baseline holds).
org(memberId, "DescribeOrganization", "{}")
.then()
.statusCode(200);
}
private static Response org(String account, String action, String body) {
return given()
.config(config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.JSON)))
.header("Authorization", auth(account))
.header("X-Amz-Target", "AWSOrganizationsV20161128." + action)
.contentType("application/x-amz-json-1.1")
.body(body)
.when()
.post("/");
}
private static String auth(String accountId) {
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260629/" + REGION
+ "/organizations/aws4_request, SignedHeaders=host, Signature=abc";
}
/** Serializes {@code value} as a JSON string literal (quoted, escaped). */
private static String jsonString(String value) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '"' -> sb.append("\\\"");
case '\\' -> sb.append("\\\\");
case '\n' -> sb.append("\\n");
case '\r' -> sb.append("\\r");
case '\t' -> sb.append("\\t");
default -> sb.append(c);
}
}
return sb.append('"').toString();
}
public static final class ScpEnforcementProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.iam.enforcement-enabled", "true",
"floci.services.organizations.scp-enforcement-enabled", "true");
}
}
}
@@ -20,6 +20,8 @@ import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -251,6 +253,7 @@ class OrganizationsServiceTest {
() -> service.describeOrganization(OUTSIDER_ACCOUNT));
assertEquals("AWSOrganizationsNotInUseException", error.getErrorCode());
}
@Test
void controlTowerGuardrailsReconcileRegisteredAndSecurityOusIdempotently() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
@@ -275,4 +278,78 @@ class OrganizationsServiceTest {
assertFalse(service.listPoliciesForTarget(MANAGEMENT_ACCOUNT, unrelated, "SERVICE_CONTROL_POLICY")
.stream().anyMatch(policy -> policy.getName().startsWith("aws-guardrails-")));
}
// ──────────────────────────── effective SCP levels ────────────────────────────
private static final String DENY_S3 =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\","
+ "\"Action\":\"s3:*\",\"Resource\":\"*\"}]}";
@Test
void effectiveScpLevelsWalkRootOuAccountChain() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String rootId = organization.getRoot().getId();
String ouId = service.createOrganizationalUnit(MANAGEMENT_ACCOUNT, rootId, "workloads", null).getId();
String member = service.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member", null, false)
.getAccountId();
service.moveAccount(MANAGEMENT_ACCOUNT, member, rootId, ouId);
// FullAWSAccess sits on root, OU, and account: three levels.
List<List<String>> levels = service.effectiveScpLevels(member);
assertEquals(3, levels.size());
assertTrue(levels.get(0).get(0).contains("\"Allow\""));
// A deny-s3 SCP attached to the OU shows up on the middle level.
String policyId = service.createPolicy(MANAGEMENT_ACCOUNT, DENY_S3, null,
"deny-s3", "SERVICE_CONTROL_POLICY", null).getId();
service.attachPolicy(MANAGEMENT_ACCOUNT, policyId, ouId);
levels = service.effectiveScpLevels(member);
assertEquals(2, levels.get(1).size());
}
@Test
void theManagementAccountIsExemptFromScps() {
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String member = service.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member", null, false)
.getAccountId();
// The member is under the same root and does get a ceiling, so the exemption is what
// separates the two — not an organization-wide absence of SCPs.
assertNotNull(service.effectiveScpLevels(member));
assertNull(service.effectiveScpLevels(MANAGEMENT_ACCOUNT));
}
@Test
void anAccountOutsideAnyOrganizationHasNoScpCeiling() {
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
assertNull(service.effectiveScpLevels(OUTSIDER_ACCOUNT));
}
@Test
void disablingTheScpPolicyTypeOnTheRootRemovesTheCeiling() {
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String member = service.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member", null, false)
.getAccountId();
assertNotNull(service.effectiveScpLevels(member));
service.disablePolicyType(MANAGEMENT_ACCOUNT, organization.getRoot().getId(), "SERVICE_CONTROL_POLICY");
assertNull(service.effectiveScpLevels(member));
}
@Test
void effectiveScpLevelsAreNullWhenEnforcementDisabled() {
OrganizationsService disabled = new OrganizationsService(
new ObjectMapper(),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
false);
disabled.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String member = disabled.createAccount(MANAGEMENT_ACCOUNT, "member@example.com", "Member", null, false)
.getAccountId();
assertNull(disabled.effectiveScpLevels(member));
}
}