mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
066e6c904b
commit
7188b3ec9d
24 files changed
+2070
-34
No files matched your search
+308
-1
@@ -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.
|
||||
|
||||
+67
@@ -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<>(),
|
||||
|
||||
+127
@@ -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));
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -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
|
||||
|
||||
+105
@@ -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"));
|
||||
}
|
||||
}
|
||||
+200
@@ -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"));
|
||||
}
|
||||
}
|
||||
+130
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user