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

@@ -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) {