fix(s3): match a bucket policy's Principal the way IAM does in S3's own checks (#4961)

Follow-up from the reviews of #4838 and #4839.

S3 checks a bucket policy itself in two places, and neither matched its
Principal the way the IAM evaluator does since #4839:

- The signed-request check (s3.enforce-auth) passed the caller to the IAM
  evaluator as a bare ARN, so a role session was matched through a role ARN
  rebuilt from the session ARN, which drops the role's path. A bucket policy
  naming role/team/App never reached that role's sessions.
- The CopyObject/UploadPartCopy source check used S3's own matcher, which
  compared each AWS entry with the caller's ARN as a string. A grant to the
  caller's account, by id or root ARN, or to its role, never matched, so a
  cross-account caller allowed to read an object could not copy it.

Both now pass the typed caller to the IAM evaluator, a role session with the
ARN of the role it assumed, through a RequestPrincipal.caller factory the
enforcement filter now uses too. The copy check's own matcher is gone: its
direct-grant rules (an exact user ARN, or "*" with aws:PrincipalArn pinned to
it) are the IAM evaluator's, and the unit tests that pinned them there move to
IamPolicyEvaluatorTest. S3PublicAccessEvaluator keeps its principal matching
for CloudFront's origin access identity check.

A CanonicalUser entry matched nothing since #4839, and docs/services/iam.md
described that as AWS behaviour. The IAM User Guide ("AWS account principals")
lets an S3 bucket policy name an account by its canonical user ID, which the
S3 User Guide describes as an obfuscated form of the account ID. It now
matches the IAM identities of that account, as an account principal does.
Floci's canonical ID for an account is its account id, the owner ID its S3 ACL
responses report.

Integration tests (IAM and S3 enforcement, real SigV4) read and copy across
accounts under bucket policies naming the caller's account, a role under a
path, and the account's canonical ID; each fails on main. docs/services/iam.md
and docs/services/s3.md describe the matching.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-02 17:17:27 -05:00
1 parent 8581497b0a
commit b679fe2312
10 files changed
+200 -279

No files matched your search

@@ -413,7 +413,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
targetContexts.add(targetContext);
}
RequestPrincipal principal = requestPrincipal(callerArns.orElse(null));
RequestPrincipal principal = RequestPrincipal.caller(callerArns.orElse(null));
if (abortIfDenied(ctx, caller, principal, action, credentialScope, resources, targetContexts,
region, accountId, akid)) {
return;
@@ -512,20 +512,6 @@ 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();
@@ -779,7 +765,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (effectiveDecision == null) {
effectiveDecision = evaluator.evaluateResourcePolicyFor(
policyDocs.isEmpty() ? null : policyDocs,
requestPrincipal(callerArns.orElse(null)), action, resource, effectiveContext);
RequestPrincipal.caller(callerArns.orElse(null)), action, resource, effectiveContext);
}
ResourceAccountRelationship accountRelationship = effectiveOwnerAccountId == null
@@ -733,8 +733,11 @@ public class IamPolicyEvaluator {
* 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.
* and matches nothing. {@code CanonicalUser}, which S3 bucket policies accept, names an account
* by its S3 canonical user ID, and matches the IAM identities of that account as an account
* principal does; Floci's canonical ID for an account is the account id, as its S3 ACLs report
* it. {@code Federated} 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()) {
@@ -770,6 +773,13 @@ public class IamPolicyEvaluator {
}
}
}
} else if ("CanonicalUser".equalsIgnoreCase(type)) {
if (principal.type() == RequestPrincipal.Type.IAM && principal.arn() != null) {
String accountId = extractAccountId(principal.arn());
if (accountId != null && patterns.contains(accountId)) {
return true;
}
}
}
}
return false;
@@ -28,6 +28,21 @@ public record RequestPrincipal(Type type, String arn, String roleArn, String ser
return new RequestPrincipal(Type.IAM, sessionArn, roleArn, null);
}
/**
* The caller an access key resolved to: a role session when its caller ARN and principal ARN
* differ, otherwise the IAM identity itself, and anonymous when nothing was resolved. A role
* session carries the ARN of the role it assumed, path included, because the session ARN alone
* names the role without its path.
*/
public static RequestPrincipal caller(IamService.CallerArns callerArns) {
if (callerArns == null) {
return anonymous();
}
return callerArns.callerArn().equals(callerArns.principalArn())
? iam(callerArns.callerArn())
: roleSession(callerArns.callerArn(), callerArns.principalArn());
}
/** 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);
@@ -49,12 +49,6 @@ final class S3PublicAccessEvaluator {
NEUTRAL
}
record PrincipalPolicyEvaluation(
PublicAccessDecision decision,
boolean directPrincipalAllow
) {
}
private S3PublicAccessEvaluator() {
}
@@ -101,25 +95,12 @@ final class S3PublicAccessEvaluator {
String action,
String resourceArn,
Map<String, String> context) {
return principalPolicyEvaluation(
objectMapper, policy, principalType, principalValue, action, resourceArn, context).decision();
}
static PrincipalPolicyEvaluation principalPolicyEvaluation(
ObjectMapper objectMapper,
String policy,
String principalType,
String principalValue,
String action,
String resourceArn,
Map<String, String> context) {
if (policy == null || policy.isBlank()) {
return new PrincipalPolicyEvaluation(PublicAccessDecision.NEUTRAL, false);
return PublicAccessDecision.NEUTRAL;
}
try {
JsonNode statements = objectMapper.readTree(policy).path("Statement");
boolean allowed = false;
boolean directPrincipalAllow = false;
Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
for (JsonNode statement : iterable) {
String effect = statement.path("Effect").asText("");
@@ -135,18 +116,14 @@ final class S3PublicAccessEvaluator {
continue;
}
if ("Deny".equalsIgnoreCase(effect)) {
return new PrincipalPolicyEvaluation(PublicAccessDecision.DENY, false);
return PublicAccessDecision.DENY;
}
allowed = true;
directPrincipalAllow |= principalDirectlyMatches(
statement, principalType, principalValue);
}
PublicAccessDecision decision = allowed
? PublicAccessDecision.ALLOW : PublicAccessDecision.NEUTRAL;
return new PrincipalPolicyEvaluation(decision, directPrincipalAllow);
return allowed ? PublicAccessDecision.ALLOW : PublicAccessDecision.NEUTRAL;
} catch (JsonProcessingException e) {
LOG.debugv("Failed to evaluate S3 bucket policy for principal access: {0}", e.getMessage());
return new PrincipalPolicyEvaluation(PublicAccessDecision.NEUTRAL, false);
return PublicAccessDecision.NEUTRAL;
}
}
@@ -350,83 +327,6 @@ final class S3PublicAccessEvaluator {
return false;
}
private static boolean principalDirectlyMatches(
JsonNode statement, String principalType, String principalValue) {
if (!statement.hasNonNull("Principal")) {
return false;
}
JsonNode principal = statement.path("Principal");
return principalNodeDirectlyMatches(principal, principalType, principalValue)
|| ("AWS".equalsIgnoreCase(principalType)
&& hasPublicPrincipal(principal)
&& conditionDirectlyMatchesPrincipalArn(
statement.path("Condition"), principalValue));
}
private static boolean conditionDirectlyMatchesPrincipalArn(
JsonNode conditions, String principalValue) {
if (conditions == null || !conditions.isObject()) {
return false;
}
Iterator<Map.Entry<String, JsonNode>> operators = conditions.fields();
while (operators.hasNext()) {
Map.Entry<String, JsonNode> operator = operators.next();
if (!("StringEquals".equalsIgnoreCase(operator.getKey())
|| "ArnEquals".equalsIgnoreCase(operator.getKey()))
|| !operator.getValue().isObject()) {
continue;
}
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> entry = entries.next();
if ("aws:PrincipalArn".equalsIgnoreCase(entry.getKey())
&& conditionValueMatches(entry.getValue(), principalValue, false)) {
return true;
}
}
}
return false;
}
private static boolean principalNodeDirectlyMatches(
JsonNode principal, String principalType, String principalValue) {
if (principal == null || principal.isMissingNode() || principal.isNull()) {
return false;
}
if (principal.isTextual() || principal.isArray()) {
return principalValueDirectlyMatches(principal, principalValue);
}
if (!principal.isObject()) {
return false;
}
Iterator<Map.Entry<String, JsonNode>> fields = principal.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
if (field.getKey().equalsIgnoreCase(principalType)
&& principalValueDirectlyMatches(field.getValue(), principalValue)) {
return true;
}
}
return false;
}
private static boolean principalValueDirectlyMatches(JsonNode candidate, String principalValue) {
if (candidate == null || candidate.isNull()) {
return false;
}
if (candidate.isTextual()) {
return candidate.asText().equals(principalValue);
}
if (candidate.isArray()) {
for (JsonNode item : candidate) {
if (principalValueDirectlyMatches(item, principalValue)) {
return true;
}
}
}
return false;
}
private static boolean principalNodeMatches(
JsonNode principal, String principalType, String principalValue) {
if (principal == null || principal.isMissingNode() || principal.isNull()) {
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
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.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
@@ -1093,17 +1094,12 @@ public class S3Service implements Resettable, ResourceProvider {
throw accessDeniedException(bucketName, key);
}
Map<String, List<String>> conditionCtx = caller != null
? Map.of("aws:PrincipalArn", List.of(caller.principalArn()),
"aws:PrincipalIsAWSService", List.of("false"))
: Map.of("aws:PrincipalIsAWSService", List.of("false"));
ResourcePolicyDecision decision = policyEvaluator.evaluateResourcePolicy(
ResourcePolicyDecision decision = policyEvaluator.evaluateResourcePolicyFor(
List.of(policy),
principalArn,
RequestPrincipal.caller(caller),
action,
resourceArn,
conditionCtx);
bucketPolicyContext(caller));
if (decision == ResourcePolicyDecision.EXPLICIT_DENY) {
throw accessDeniedException(bucketName, key);
@@ -1138,6 +1134,17 @@ public class S3Service implements Resettable, ResourceProvider {
return Optional.of(new CallerArns(rootArn, rootArn));
}
/**
* The request context a bucket policy is evaluated with here: the caller is an IAM principal,
* never a service, and for a role session {@code aws:PrincipalArn} is the role's ARN.
*/
private static Map<String, List<String>> bucketPolicyContext(CallerArns caller) {
return caller != null
? Map.of("aws:PrincipalArn", List.of(caller.principalArn()),
"aws:PrincipalIsAWSService", List.of("false"))
: Map.of("aws:PrincipalIsAWSService", List.of("false"));
}
private boolean isSameAccountAsBucketOwner(String accessKeyId, String principalArn, String bucketOwnerAccount) {
String owner = bucketOwnerAccount != null ? bucketOwnerAccount : ownerId();
return (LEGACY_ACCESS_KEY_ID.equals(accessKeyId) && owner.equals(ownerId()))
@@ -1176,23 +1183,15 @@ public class S3Service implements Resettable, ResourceProvider {
AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
.orElseThrow(() -> new AwsException(
"NoSuchBucket", "The specified bucket does not exist.", 404));
S3PublicAccessEvaluator.PrincipalPolicyEvaluation policyEvaluation =
S3PublicAccessEvaluator.principalPolicyEvaluation(
objectMapper,
ownedBucket.value().getPolicy(),
"AWS",
caller.get().callerArn(),
String policy = ownedBucket.value().getPolicy();
ResourcePolicyDecision decision = policy == null || policy.isBlank()
? ResourcePolicyDecision.NEUTRAL
: policyEvaluator.evaluateResourcePolicyFor(
List.of(policy),
RequestPrincipal.caller(caller.get()),
action,
resourceArn,
Map.of("aws:PrincipalArn", caller.get().principalArn(),
"aws:PrincipalIsAWSService", "false"));
ResourcePolicyDecision decision = switch (policyEvaluation.decision()) {
case ALLOW -> policyEvaluation.directPrincipalAllow() && caller.get().callerArn().contains(":user/")
? ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER
: ResourcePolicyDecision.ALLOW;
case DENY -> ResourcePolicyDecision.EXPLICIT_DENY;
case NEUTRAL -> ResourcePolicyDecision.NEUTRAL;
};
bucketPolicyContext(caller.get()));
return new SignedPrincipalResourcePolicyEvaluation(decision, ownedBucket.account());
}