fix(iam): match a resource policy's Principal by the kind of caller it names (#4839)

IamPolicyEvaluator matched a resource policy's Principal against one string,
the caller's ARN, and compared every principal type other than AWS and "*"
with it by glob. So {"Service": "*"} and {"Federated": "*"} matched every IAM
caller: under enforcement a bucket policy granting {"Service": "*"}, a form AWS
does not accept at all, let an IAM user from any account read the bucket.
Services could not be passed as a caller at all, so {"AWS": "*"}, which AWS
itself relies on to cover services (an FIS Deny pausing DynamoDB replication
names the replication service that way), could not match one. And a role
session matched a Principal naming its role only through a role ARN rebuilt
from the session ARN, which drops the role's path, so a policy naming
role/team/App never matched that role's sessions.

A new RequestPrincipal carries the kind of caller (IAM, service, anonymous),
and for a role session the ARN of the role it assumed. Each principal type now
matches only the callers it can name (IAM User Guide, "AWS JSON policy
elements: Principal"): "*" anyone; {"AWS": "*"} IAM identities and services;
any other AWS entry IAM identities only, a role session matching through its
role's own ARN; {"Service": "<name>"} that service exactly; {"Service": "*"}
nothing; Federated and CanonicalUser never an IAM caller. NotPrincipal is typed
the same way. The direct-IAM-user branch and the aws:PrincipalArn stand-in for
a missing caller stay IAM-only.

A new evaluateResourcePolicyFor takes a RequestPrincipal; the existing String
evaluateResourcePolicy reads its argument as an IAM caller and delegates to it.
The typed method has its own name rather than being an overload of the same
arity, so a call passing a literal null caller to the String form still
compiles. A new
evaluateServicePrincipal decides a call a service makes on its own behalf from
the resource policy alone, since a service principal has no identity policy,
boundary or session policy and SCPs do not apply to it: Deny denies, Allow
allows, silence denies. Nothing calls it yet; the shared service-call
authorizer will.

The enforcement filter now passes the typed principal, with a role session's
role ARN from IamService.resolveCallerArns, to both resource-policy
evaluations. S3's own bucket-policy checks still go through the String
overload; giving them the role ARN follows the change that splits the two ARNs
there.

docs/services/iam.md describes the matching rules.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-01 21:18:26 -05:00
1 parent b512d273e1
commit 2bdfe45207
7 files changed
+364 -68

No files matched your search

@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccoun
import 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(),
@@ -660,10 +660,13 @@ class IamPolicyEvaluatorTest {
// Service principal and array of principals
String 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);
}
@Test
void evaluatesResourcePolicyDenyAndNotPrincipal() {
// NotPrincipal inversion: anyone NOT alice is denied
@@ -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";
}
}