Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): match a resource policy's Principal by the kind of caller it names (#4839)
Priamo Germosen2bdfe45207d7
diff --git a/docs/services/iam.md b/docs/services/iam.mdindex 07994e7e1b..b71d920191 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -649,7 +649,7 @@ the route's rule miss.When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` is active, Floci also queries registered `ResourcePolicyProvider` SPI implementations (such as S3 bucket policies) during request authorization:-- Resource policy statements are matched against the caller's principal ARN (`Principal` and `NotPrincipal` clauses), supporting wildcard, user, role, account root, and service principals.+- Resource policy statements are matched against the caller (`Principal` and `NotPrincipal` clauses), each principal type naming only its own kind of caller, as on AWS: `"*"` matches anyone; `{"AWS": "*"}` matches IAM identities and AWS services; any other `AWS` entry (a user, role, account id or account root) matches IAM identities only, and a role session matches a `Principal` naming its role through the role's own ARN, path included; `{"Service": "<name>"}` matches that service exactly. `{"Service": "*"}`, which AWS does not accept, matches nothing, and `Federated` and `CanonicalUser` entries never match an IAM caller.- An explicit **Deny** in a resource policy overrides any allows.- In cross-account scenarios or resource-controlled access, an explicit **Allow** in a resource policy grants access to the principal.- For detailed S3 bucket policy behavior and configuration, see [S3 Bucket Policy Enforcement](s3.md#bucket-policy-enforcement).diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.javaindex 11c724a680..362bcc96cd 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyimport io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.iam.IamService.CallerArns;import io.github.hectorvent.floci.services.iam.IamService.PresignedScope;+import io.github.hectorvent.floci.services.iam.RequestPrincipal;import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;import io.github.hectorvent.floci.services.iam.ScpProvider;@@ -412,7 +413,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {targetContexts.add(targetContext);}- if (abortIfDenied(ctx, caller, action, credentialScope, resources, targetContexts,+ RequestPrincipal principal = requestPrincipal(callerArns.orElse(null));+ if (abortIfDenied(ctx, caller, principal, action, credentialScope, resources, targetContexts,region, accountId, akid)) {return;}@@ -424,7 +426,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {// succeeds, and with no GetObject at all it is denied. If-None-Match needs no such// permission.if ("s3:PutObject".equals(action) && ctx.getHeaderString("If-Match") != null) {- abortIfDenied(ctx, caller, "s3:GetObject", credentialScope, resources,+ abortIfDenied(ctx, caller, principal, "s3:GetObject", credentialScope, resources,withoutObjectTags(targetContexts), region, accountId, akid);}// A DeleteObject conditioned on an ETag reveals whether the object still has it, and the@@ -432,7 +434,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {// needs just s3:DeleteObject. The read is checked the way the PutObject case above is.if ("s3:DeleteObject".equals(action) && isPlainDeleteObject(ctx)&& isETagCondition(ctx.getHeaderString("If-Match"))) {- abortIfDenied(ctx, caller, "s3:GetObject", credentialScope, resources,+ abortIfDenied(ctx, caller, principal, "s3:GetObject", credentialScope, resources,withoutObjectTags(targetContexts), region, accountId, akid);}}@@ -510,6 +512,20 @@ public class IamEnforcementFilter implements ContainerRequestFilter {private record ResolvedAuthorization(String credentialScope, String action) {}+ /**+ * The caller as a resource policy's {@code Principal} sees it. A role session is matched by its+ * session ARN and by the ARN of the role it assumed, path included, which a {@code Principal}+ * naming the role identifies; the session ARN alone names the role without its path.+ */+ private static RequestPrincipal requestPrincipal(CallerArns callerArns) {+ if (callerArns == null) {+ return RequestPrincipal.anonymous();+ }+ return callerArns.callerArn().equals(callerArns.principalArn())+ ? RequestPrincipal.iam(callerArns.callerArn())+ : RequestPrincipal.roleSession(callerArns.callerArn(), callerArns.principalArn());+ }+/** Floci's account-root principal, which is both the caller and the request's aws:PrincipalArn. */private CallerArns accountRootArns(String accountId) {String rootArn = AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "root").toString();@@ -520,8 +536,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {* Evaluates one action against every resource and target context, aborting the request with* AccessDenied on the first DENY. Returns true when the request was aborted.*/- private boolean abortIfDenied(ContainerRequestContext ctx, CallerContext caller, String action,- String credentialScope, List<String> resources,+ private boolean abortIfDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal,+ String action, String credentialScope, List<String> resources,List<Map<String, List<String>>> targetContexts,String region, String accountId, String akid) {for (String resource : resources) {@@ -541,8 +557,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {for (Map<String, List<String>> targetContext : targetContexts) {Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(targetContext, resource, region, accountId, resourceOwnerAccountId);- ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicy(- effectiveResourcePolicies, caller.principalArn(), action, resource, effectiveContext);+ ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicyFor(+ effectiveResourcePolicies, principal, action, resource, effectiveContext);Decision decision = evaluator.evaluateResolvedResourcePolicy(caller, resourcePolicyDecision, accountRelationship, action, resource, effectiveContext);if (decision != Decision.DENY) {@@ -761,9 +777,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(conditionContext, resource, region, accountId, effectiveOwnerAccountId);if (effectiveDecision == null) {- effectiveDecision = evaluator.evaluateResourcePolicy(+ effectiveDecision = evaluator.evaluateResourcePolicyFor(policyDocs.isEmpty() ? null : policyDocs,- caller.principalArn(), action, resource, effectiveContext);+ requestPrincipal(callerArns.orElse(null)), action, resource, effectiveContext);}ResourceAccountRelationship accountRelationship = effectiveOwnerAccountId == nulldiff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.javaindex ba8127e5d2..61ca7e979b 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsServiceNamespaces;+import io.github.hectorvent.floci.core.common.ServicePrincipals;import io.github.hectorvent.floci.services.iam.model.CallerContext;import io.github.hectorvent.floci.services.iam.model.PolicyStatement;import jakarta.enterprise.context.ApplicationScoped;@@ -173,8 +174,9 @@ public class IamPolicyEvaluator {}/**- * Evaluates a resource-based policy standalone for a given caller principal, action,- * and resource.+ * Evaluates a resource-based policy standalone for an IAM caller identified by its ARN. With no+ * ARN, the request's {@code aws:PrincipalArn} stands in for it, which is IAM-only too: the key+ * names IAM users, roles, federated users and the account root, never a service.*/public ResourcePolicyDecision evaluateResourcePolicy(List<String> resourcePolicies,@@ -182,30 +184,66 @@ public class IamPolicyEvaluator {String action,String resource,Map<String, List<String>> conditionCtx) {+ String callerArn = principalArn;+ if (callerArn == null) {+ List<String> principalArns = normalizeConditionContext(conditionCtx).get("aws:principalarn");+ if (principalArns != null && !principalArns.isEmpty()) {+ callerArn = principalArns.getFirst();+ }+ }+ RequestPrincipal principal = callerArn == null+ ? RequestPrincipal.anonymous()+ : RequestPrincipal.iam(callerArn);+ return evaluateResourcePolicyFor(resourcePolicies, principal, action, resource, conditionCtx);+ }++ /**+ * Evaluates a resource-based policy standalone for a typed caller. Each principal type in the+ * policy matches only the callers it can name: {@code AWS} an IAM identity, {@code Service} a+ * service by its exact name, {@code "*"} anyone. Named apart from the String form so a call+ * passing a literal null caller to that one stays unambiguous.+ */+ public ResourcePolicyDecision evaluateResourcePolicyFor(+ List<String> resourcePolicies,+ RequestPrincipal principal,+ String action,+ String resource,+ Map<String, List<String>> conditionCtx) {if (resourcePolicies == null || resourcePolicies.isEmpty()) {return ResourcePolicyDecision.NEUTRAL;}Map<String, List<String>> ctx = normalizeConditionContext(conditionCtx);- if (principalArn == null && ctx.containsKey("aws:principalarn")) {- List<String> principalArns = ctx.get("aws:principalarn");- if (principalArns != null && !principalArns.isEmpty()) {- principalArn = principalArns.getFirst();- }- }String loweredAction = lowercase(action);List<PolicyStatement> stmts = parseAll(resourcePolicies);- if (anyResourceExplicitDeny(stmts, principalArn, loweredAction, resource, ctx)) {+ if (anyResourceExplicitDeny(stmts, principal, loweredAction, resource, ctx)) {return ResourcePolicyDecision.EXPLICIT_DENY;}- if (anyResourceDirectIamUserAllow(stmts, principalArn, loweredAction, resource, ctx)) {+ if (anyResourceDirectIamUserAllow(stmts, principal, loweredAction, resource, ctx)) {return ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER;}- if (anyResourceExplicitAllow(stmts, principalArn, loweredAction, resource, ctx)) {+ if (anyResourceExplicitAllow(stmts, principal, loweredAction, resource, ctx)) {return ResourcePolicyDecision.ALLOW;}return ResourcePolicyDecision.NEUTRAL;}+ /**+ * Decides a call an AWS service makes on its own behalf, such as SNS delivering to a queue. The+ * resource policy decides alone: a service principal carries no identity, session or boundary+ * policy, and SCPs apply only to the IAM users and roles of an organization's accounts. An+ * explicit Deny denies, an Allow allows, and a policy that says nothing denies.+ */+ public Decision evaluateServicePrincipal(+ List<String> resourcePolicies,+ String servicePrincipal,+ String action,+ String resource,+ Map<String, List<String>> conditionCtx) {+ ResourcePolicyDecision decision = evaluateResourcePolicyFor(+ resourcePolicies, RequestPrincipal.service(servicePrincipal), action, resource, conditionCtx);+ return decision == ResourcePolicyDecision.ALLOW ? Decision.ALLOW : Decision.DENY;+ }+private Decision evaluateParsed(CallerContext caller,List<PolicyStatement> identityStmts,@@ -570,41 +608,43 @@ public class IamPolicyEvaluator {return false;}- private boolean anyResourceExplicitDeny(List<PolicyStatement> stmts, String principalArn,+ private boolean anyResourceExplicitDeny(List<PolicyStatement> stmts, RequestPrincipal principal,String action, String resource, Map<String, List<String>> ctx) {for (PolicyStatement stmt : stmts) {- if (stmt.isDeny() && matchesResourceStatement(stmt, principalArn, action, resource, ctx)) {+ if (stmt.isDeny() && matchesResourceStatement(stmt, principal, action, resource, ctx)) {return true;}}return false;}- private boolean anyResourceExplicitAllow(List<PolicyStatement> stmts, String principalArn,+ private boolean anyResourceExplicitAllow(List<PolicyStatement> stmts, RequestPrincipal principal,String action, String resource, Map<String, List<String>> ctx) {for (PolicyStatement stmt : stmts) {- if (stmt.isAllow() && matchesResourceStatement(stmt, principalArn, action, resource, ctx)) {+ if (stmt.isAllow() && matchesResourceStatement(stmt, principal, action, resource, ctx)) {return true;}}return false;}- private boolean anyResourceDirectIamUserAllow(List<PolicyStatement> stmts, String principalArn,+ private boolean anyResourceDirectIamUserAllow(List<PolicyStatement> stmts, RequestPrincipal principal,String action, String resource, Map<String, List<String>> ctx) {for (PolicyStatement stmt : stmts) {- if (stmt.isAllow() && matchesDirectIamUserStatement(stmt, principalArn, action, resource, ctx)) {+ if (stmt.isAllow() && matchesDirectIamUserStatement(stmt, principal, action, resource, ctx)) {return true;}}return false;}- private boolean matchesDirectIamUserStatement(PolicyStatement stmt, String principalArn,+ private boolean matchesDirectIamUserStatement(PolicyStatement stmt, RequestPrincipal principal,String action, String resource, Map<String, List<String>> ctx) {- if (principalArn == null || !principalArn.contains(":user/")) {+ if (principal.type() != RequestPrincipal.Type.IAM+ || principal.arn() == null || !principal.arn().contains(":user/")) {return false;}+ String principalArn = principal.arn();if (stmt.getPrincipals() == null) {return false;}@@ -662,13 +702,13 @@ public class IamPolicyEvaluator {return false;}- private boolean matchesResourceStatement(PolicyStatement stmt, String principalArn,+ private boolean matchesResourceStatement(PolicyStatement stmt, RequestPrincipal principal,String action, String resource, Map<String, List<String>> ctx) {// A resource-policy statement with no Principal matches nothing (per AWS specification)if (stmt.getPrincipals() == null && stmt.getNotPrincipals() == null) {return false;}- if (!matchesPrincipal(stmt, principalArn)) {+ if (!matchesPrincipal(stmt, principal)) {return false;}return matchesAction(stmt, action)@@ -676,17 +716,27 @@ public class IamPolicyEvaluator {&& matchesConditions(stmt.getConditions(), ctx);}- private boolean matchesPrincipal(PolicyStatement stmt, String principalArn) {+ private boolean matchesPrincipal(PolicyStatement stmt, RequestPrincipal principal) {if (stmt.getPrincipals() != null) {- return matchesAnyPrincipal(stmt.getPrincipals(), principalArn);+ return matchesAnyPrincipal(stmt.getPrincipals(), principal);}if (stmt.getNotPrincipals() != null) {- return !matchesAnyPrincipal(stmt.getNotPrincipals(), principalArn);+ return !matchesAnyPrincipal(stmt.getNotPrincipals(), principal);}return false;}- private boolean matchesAnyPrincipal(Map<String, List<String>> principals, String principalArn) {+ /**+ * Matches a statement's {@code Principal} (or {@code NotPrincipal}) map against a typed caller.+ * {@code "*"} matches anyone. {@code {"AWS": "*"}} matches IAM identities and services alike,+ * which policies AWS writes itself rely on (an FIS Deny pausing DynamoDB replication names the+ * replication service that way). Any other {@code AWS} entry names IAM identities only, and a+ * role session matches the role it assumed through that role's own ARN, path included.+ * {@code Service} names one service exactly; {@code {"Service": "*"}} is not a form AWS accepts+ * and matches nothing. {@code Federated}, {@code CanonicalUser} and any other type name callers+ * this evaluator never sees, and so match nothing, rather than being compared with an IAM ARN.+ */+ private boolean matchesAnyPrincipal(Map<String, List<String>> principals, RequestPrincipal principal) {for (Map.Entry<String, List<String>> entry : principals.entrySet()) {String type = entry.getKey();List<String> patterns = entry.getValue();@@ -698,44 +748,56 @@ public class IamPolicyEvaluator {if ("*".equals(pattern)) {return true;}- if (principalArn != null && globMatches(pattern, principalArn)) {+ if (principal.type() == RequestPrincipal.Type.IAM && principal.arn() != null+ && globMatches(pattern, principal.arn())) {return true;}}} else if ("AWS".equalsIgnoreCase(type)) {- if (principalArn == null) {- continue;+ if (patterns.contains("*") && principal.type() != RequestPrincipal.Type.ANONYMOUS) {+ return true;}- String accountId = extractAccountId(principalArn);- String roleArn = extractRoleArnFromAssumedRole(principalArn);- for (String pattern : patterns) {- if ("*".equals(pattern)) {- return true;- }- if (pattern.matches("\\d{12}")) {- if (pattern.equals(accountId)) {- return true;- }- } else if (ROOT_PRINCIPAL_ARN.matcher(pattern).matches()) {- // An account id is scoped to its partition: arn:aws-cn:iam::123:root names- // the China account 123, which is not the commercial account 123.- AwsArnUtils.Arn root = AwsArnUtils.parse(pattern);- if (root.accountId().equals(accountId)- && root.partition().equals(AwsArnUtils.parse(principalArn).partition())) {+ if (principal.type() == RequestPrincipal.Type.IAM && principal.arn() != null+ && matchesAwsPrincipal(patterns, principal)) {+ return true;+ }+ } else if ("Service".equalsIgnoreCase(type)) {+ if (principal.type() == RequestPrincipal.Type.SERVICE && principal.servicePrincipal() != null) {+ String wanted = ServicePrincipals.canonical(principal.servicePrincipal());+ for (String pattern : patterns) {+ if (!"*".equals(pattern) && ServicePrincipals.canonical(pattern).equals(wanted)) {return true;}- } else if (globMatches(pattern, principalArn)) {- return true;- } else if (roleArn != null && globMatches(pattern, roleArn)) {- return true;}}- } else if (principalArn != null) {- for (String pattern : patterns) {- if ("*".equals(pattern) || globMatches(pattern, principalArn)) {- return true;- }+ }+ }+ return false;+ }++ private boolean matchesAwsPrincipal(List<String> patterns, RequestPrincipal principal) {+ String principalArn = principal.arn();+ String accountId = extractAccountId(principalArn);+ String roleArn = principal.roleArn() != null+ ? principal.roleArn()+ : extractRoleArnFromAssumedRole(principalArn);+ for (String pattern : patterns) {+ if (pattern.matches("\\d{12}")) {+ if (pattern.equals(accountId)) {+ return true;+ }+ } else if (ROOT_PRINCIPAL_ARN.matcher(pattern).matches()) {+ // An account id is scoped to its partition: arn:aws-cn:iam::123:root names+ // the China account 123, which is not the commercial account 123.+ AwsArnUtils.Arn root = AwsArnUtils.parse(pattern);+ if (root.accountId().equals(accountId)+ && root.partition().equals(AwsArnUtils.parse(principalArn).partition())) {+ return true;}+ } else if (globMatches(pattern, principalArn)) {+ return true;+ } else if (roleArn != null && globMatches(pattern, roleArn)) {+ return true;}}return false;diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/RequestPrincipal.java b/src/main/java/io/github/hectorvent/floci/services/iam/RequestPrincipal.javanew file mode 100644index 0000000000..2206362f8c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iam/RequestPrincipal.java@@ -0,0 +1,40 @@+package io.github.hectorvent.floci.services.iam;++/**+ * Who a request comes from, as a resource policy's {@code Principal} element sees it. Each kind is+ * matched only by the principal types that can name it (IAM User Guide, "AWS JSON policy elements:+ * Principal"): an IAM identity by {@code AWS}, a service by {@code Service}, and anyone by+ * {@code "*"}.+ *+ * @param type the kind of caller+ * @param arn an IAM caller's own ARN: the user's, or a role session's assumed-role+ * session ARN; null for the other kinds+ * @param roleArn for a role session, the ARN of the role that was assumed, path included,+ * which a {@code Principal} naming the role identifies; null otherwise+ * @param servicePrincipal a service caller's principal name, such as {@code sns.amazonaws.com};+ * null for the other kinds+ */+public record RequestPrincipal(Type type, String arn, String roleArn, String servicePrincipal) {++ public enum Type { IAM, SERVICE, ANONYMOUS }++ /** An IAM user, account root or federated user, or a role session without its role's ARN. */+ public static RequestPrincipal iam(String arn) {+ return new RequestPrincipal(Type.IAM, arn, null, null);+ }++ /** A role session, matched by its session ARN and by the ARN of the role that was assumed. */+ public static RequestPrincipal roleSession(String sessionArn, String roleArn) {+ return new RequestPrincipal(Type.IAM, sessionArn, roleArn, null);+ }++ /** An AWS service acting on its own behalf, such as SNS delivering to a queue. */+ public static RequestPrincipal service(String servicePrincipal) {+ return new RequestPrincipal(Type.SERVICE, null, null, servicePrincipal);+ }++ /** A caller with no credentials. */+ public static RequestPrincipal anonymous() {+ return new RequestPrincipal(Type.ANONYMOUS, null, null, null);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.javaindex d783d21578..ce7eec8acb 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccounimport io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.iam.IamService.CallerArns;+import io.github.hectorvent.floci.services.iam.RequestPrincipal;import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;import io.github.hectorvent.floci.services.iam.ScpProvider;@@ -44,6 +45,7 @@ import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.ArgumentMatchers.isNull;+import static org.mockito.Mockito.atLeastOnce;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.mock;@@ -99,7 +101,7 @@ class IamEnforcementFilterTest {when(arnBuilder.build(any(), any(), any(), any())).thenReturn("*");// Default: scopes are already canonical. Alias handling is asserted explicitly below.when(catalog.canonicalCredentialScope(anyString())).thenAnswer(inv -> inv.getArgument(0));- when(evaluator.evaluateResourcePolicy(any(), any(), any(), any(), any()))+ when(evaluator.evaluateResourcePolicyFor(any(), any(), any(), any(), any())).thenReturn(ResourcePolicyDecision.NEUTRAL);}@@ -1295,6 +1297,32 @@ class IamEnforcementFilterTest {verify(arnBuilder).buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account));}+ @Test+ void aRoleSessionReachesResourcePoliciesAsItsRoleWithItsPath() {+ // The session ARN names the role without its path; a Principal naming the role is matched+ // against the role's own ARN, which the caller lookup returns alongside it.+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);+ String account = "111122223333";+ String akid = "ASIASESSIONEXAMPLE";+ String auth = "AWS4-HMAC-SHA256 Credential=" + akid+ + "/20260629/us-east-1/s3/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("s3", containerRequest)).thenReturn("s3:GetObject");+ when(iamService.resolveCallerContext(akid)).thenReturn(CallerContext.of(List.of()));+ String sessionArn = "arn:aws:sts::" + account + ":assumed-role/App/s";+ String roleArn = "arn:aws:iam::" + account + ":role/team/App";+ when(iamService.resolveCallerArns(akid)).thenReturn(Optional.of(new CallerArns(sessionArn, roleArn)));++ newFilter().filter(containerRequest);++ verify(evaluator, atLeastOnce()).evaluateResourcePolicyFor(+ any(), eq(RequestPrincipal.roleSession(sessionArn, roleArn)), any(), any(), any());+ }+// --- Presigned URL query-string credential (#3195): a presigned PUT/GET carries its// SigV4 credential in X-Amz-Credential, never in the Authorization header, so the filter// must fall back to the query parameter instead of bypassing IAM evaluation entirely.@@ -1530,7 +1558,7 @@ class IamEnforcementFilterTest {conditions, "arn:aws:s3:::partner-bucket", "us-east-1", "222233334444", "111111111111");assertEquals(List.of("111111111111"), expected.get("aws:ResourceAccount"));- when(evaluator.evaluateResourcePolicy(any(), any(), anyString(), anyString(), any()))+ when(evaluator.evaluateResourcePolicyFor(any(), any(), anyString(), anyString(), any())).thenReturn(ResourcePolicyDecision.NEUTRAL);when(evaluator.evaluateResolvedResourcePolicy(any(),diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.javaindex 52d1ba87c8..47907af369 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java@@ -660,10 +660,13 @@ class IamPolicyEvaluatorTest {// Service principal and array of principalsString servicePolicy = """{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"s3:*","Resource":"*"}]}""";- assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(- List.of(servicePolicy), "lambda.amazonaws.com", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicyFor(List.of(servicePolicy),+ RequestPrincipal.service("lambda.amazonaws.com"), "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicyFor(List.of(servicePolicy),+ RequestPrincipal.service("ec2.amazonaws.com"), "s3:GetObject", "arn:aws:s3:::b/k", null));+ // An IAM caller is never a service, whatever its name says.assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(- List.of(servicePolicy), "ec2.amazonaws.com", "s3:GetObject", "arn:aws:s3:::b/k", null));+ List.of(servicePolicy), "lambda.amazonaws.com", "s3:GetObject", "arn:aws:s3:::b/k", null));String arrayPolicy = """{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["arn:aws:iam::123456789012:user/alice","arn:aws:iam::123456789012:user/bob"]},"Action":"s3:*","Resource":"*"}]}""";@@ -675,6 +678,75 @@ class IamPolicyEvaluatorTest {List.of(arrayPolicy), "arn:aws:iam::123456789012:user/charlie", "s3:GetObject", "arn:aws:s3:::b/k", null));}+ @Test+ void eachPrincipalTypeMatchesOnlyTheCallersItCanName() {+ RequestPrincipal alice = RequestPrincipal.iam("arn:aws:iam::123456789012:user/alice");+ RequestPrincipal sns = RequestPrincipal.service("sns.amazonaws.com");+ // {"Service": "*"} is not a form AWS accepts: it matches no one, an IAM caller least of all.+ String serviceWildcard = resourcePolicy("Allow", "\"Principal\":{\"Service\":\"*\"}");+ assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(serviceWildcard, alice));+ assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(serviceWildcard, sns));+ // Federated and CanonicalUser name callers of their own kinds, never an IAM identity.+ assertEquals(ResourcePolicyDecision.NEUTRAL,+ resourceDecision(resourcePolicy("Allow", "\"Principal\":{\"Federated\":\"*\"}"), alice));+ assertEquals(ResourcePolicyDecision.NEUTRAL,+ resourceDecision(resourcePolicy("Allow", "\"Principal\":{\"CanonicalUser\":\"*\"}"), alice));+ // {"AWS": "*"} covers services too: an FIS Deny pausing DynamoDB replication names the+ // replication service that way. Any other AWS entry names IAM identities only.+ assertEquals(ResourcePolicyDecision.EXPLICIT_DENY,+ resourceDecision(resourcePolicy("Deny", "\"Principal\":{\"AWS\":\"*\"}"), sns));+ assertEquals(ResourcePolicyDecision.NEUTRAL,+ resourceDecision(resourcePolicy("Allow", "\"Principal\":{\"AWS\":\"123456789012\"}"), sns));+ // A Service entry names one service, exactly.+ String snsOnly = resourcePolicy("Allow", "\"Principal\":{\"Service\":\"sns.amazonaws.com\"}");+ assertEquals(ResourcePolicyDecision.ALLOW, resourceDecision(snsOnly, sns));+ assertEquals(ResourcePolicyDecision.NEUTRAL,+ resourceDecision(snsOnly, RequestPrincipal.service("sqs.amazonaws.com")));+ assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(snsOnly, alice));+ // NotPrincipal is typed the same way.+ String allButSns = resourcePolicy("Deny", "\"NotPrincipal\":{\"Service\":\"sns.amazonaws.com\"}");+ assertEquals(ResourcePolicyDecision.EXPLICIT_DENY, resourceDecision(allButSns, alice));+ assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(allButSns, sns));+ }++ @Test+ void aRoleSessionMatchesItsRoleByTheRolesOwnArn() {+ // The session ARN names the role without its path; the role's own ARN keeps it.+ RequestPrincipal session = RequestPrincipal.roleSession(+ "arn:aws:sts::111111111111:assumed-role/App/s", "arn:aws:iam::111111111111:role/team/App");+ assertEquals(ResourcePolicyDecision.ALLOW, resourceDecision(resourcePolicy("Allow",+ "\"Principal\":{\"AWS\":\"arn:aws:iam::111111111111:role/team/App\"}"), session));+ assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(resourcePolicy("Allow",+ "\"Principal\":{\"AWS\":\"arn:aws:iam::111111111111:role/App\"}"), session));+ assertEquals(ResourcePolicyDecision.ALLOW, resourceDecision(resourcePolicy("Allow",+ "\"Principal\":{\"AWS\":\"arn:aws:sts::111111111111:assumed-role/App/s\"}"), session));+ }++ @Test+ void aServicePrincipalIsDecidedByTheResourcePolicyAlone() {+ String sns = "sns.amazonaws.com";+ String allowSns = resourcePolicy("Allow", "\"Principal\":{\"Service\":\"sns.amazonaws.com\"}");+ // No identity policy, boundary or SCP stands behind a service: silence denies.+ assertEquals(Decision.DENY, evaluator.evaluateServicePrincipal(null, sns, "sqs:SendMessage", "*", null));+ assertEquals(Decision.DENY, evaluator.evaluateServicePrincipal(+ List.of(resourcePolicy("Allow", "\"Principal\":{\"AWS\":\"123456789012\"}")),+ sns, "sqs:SendMessage", "*", null));+ assertEquals(Decision.ALLOW, evaluator.evaluateServicePrincipal(+ List.of(allowSns), sns, "sqs:SendMessage", "*", null));+ assertEquals(Decision.DENY, evaluator.evaluateServicePrincipal(+ List.of(allowSns, resourcePolicy("Deny", "\"Principal\":{\"AWS\":\"*\"}")),+ sns, "sqs:SendMessage", "*", null));+ }++ private static String resourcePolicy(String effect, String principal) {+ return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"" + effect + "\"," + principal+ + ",\"Action\":\"*\",\"Resource\":\"*\"}]}";+ }++ private ResourcePolicyDecision resourceDecision(String policy, RequestPrincipal principal) {+ return evaluator.evaluateResourcePolicyFor(List.of(policy), principal, "sqs:SendMessage", "*", null);+ }+@Testvoid evaluatesResourcePolicyDenyAndNotPrincipal() {// NotPrincipal inversion: anyone NOT alice is denieddiff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourcePolicyPrincipalTypeEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourcePolicyPrincipalTypeEnforcementIntegrationTest.javanew file mode 100644index 0000000000..8fbde35bfb--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourcePolicyPrincipalTypeEnforcementIntegrationTest.java@@ -0,0 +1,78 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.testing.S3IamEnforcementProfile;+import io.github.hectorvent.floci.testutil.S3RequestSigner;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.TestProfile;+import io.restassured.response.ExtractableResponse;+import io.restassured.response.Response;+import org.junit.jupiter.api.Test;++import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;++/**+ * With IAM enforcement on, a bucket policy's {@code Principal} grants a cross-account caller only+ * through a principal type that names it (IAM User Guide, "AWS JSON policy elements: Principal").+ */+@QuarkusTest+@TestProfile(S3IamEnforcementProfile.class)+class ResourcePolicyPrincipalTypeEnforcementIntegrationTest {++ private static final String CALLER_ACCOUNT = "222222222222";+ private static final S3RequestSigner OWNER = S3RequestSigner.signedAs("test", "test");++ @Test+ void aServiceWildcardGrantsNoIamCaller() {+ // {"Service": "*"} is not a form AWS accepts. It used to be compared with the caller's IAM ARN+ // by glob, so a bucket policy written that way let every IAM caller in from any account.+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String bucket = "principal-type-" + suffix;+ given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);+ given().filter(OWNER).contentType("text/plain").body("payload")+ .when().put("/" + bucket + "/object.txt").then().statusCode(200);+ S3RequestSigner caller = crossAccountReader("reader-" + suffix);++ putBucketPolicy(bucket, """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"*"},+ "Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]}""".formatted(bucket));+ given().filter(caller).when().get("/" + bucket + "/object.txt")+ .then().statusCode(403).body(containsString("<Code>AccessDenied</Code>"));++ // The same caller is let in once the policy names its account.+ putBucketPolicy(bucket, """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"%s"},+ "Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]}""".formatted(CALLER_ACCOUNT, bucket));+ given().filter(caller).when().get("/" + bucket + "/object.txt")+ .then().statusCode(200).body(equalTo("payload"));+ }++ /** An IAM user in another account, allowed s3:GetObject on anything by its own policy. */+ private static S3RequestSigner crossAccountReader(String user) {+ given().formParam("Action", "CreateUser").formParam("UserName", user)+ .header("Authorization", auth(CALLER_ACCOUNT, "iam")).when().post("/").then().statusCode(200);+ given().formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "read")+ .formParam("PolicyDocument", """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""")+ .header("Authorization", auth(CALLER_ACCOUNT, "iam")).when().post("/").then().statusCode(200);+ ExtractableResponse<Response> key = given().formParam("Action", "CreateAccessKey").formParam("UserName", user)+ .header("Authorization", auth(CALLER_ACCOUNT, "iam")).when().post("/")+ .then().statusCode(200).extract();+ return S3RequestSigner.signedAs(+ key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"),+ key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey"));+ }++ private static void putBucketPolicy(String bucket, String policy) {+ given().filter(OWNER).contentType("application/json").body(policy)+ .when().put("/" + bucket + "?policy").then().statusCode(200);+ }++ private static String auth(String accessKeyId, String service) {+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261001/us-east-1/" + service+ + "/aws4_request, SignedHeaders=host, Signature=abc";+ }+}