fix(iam): evaluate policies against real request resources and conditions (#3765)

* fix(iam): evaluate real request resources and S3 sub-resource actions

* fix(iam): add global context to managed policy evaluation
This commit is contained in:
Chris Jovanovski authored and GitHub committed 2026-09-17 22:42:06 -04:00
1 parent 1d009b9614
commit 33a95e92f2
9 files changed
+555 -174

No files matched your search

@@ -81,6 +81,41 @@ public class IamConditionContextResolver {
};
}
public static Map<String, List<String>> withGlobalContext(Map<String, List<String>> serviceContext,
String resourceArn, String region,
String accountId, String resourceOwnerAccountId) {
Map<String, List<String>> conditions = serviceContext == null
? new LinkedHashMap<>()
: new LinkedHashMap<>(serviceContext);
// aws:ResourceAccount is the account that OWNS the resource, which is not always the
// caller's. Some ARNs carry it; S3 bucket and object ARNs deliberately do not, and there
// the owner has to come from service state. When neither source knows it, the key is left
// out rather than guessed: an absent key fails a Condition that tests it, whereas a wrong
// one would silently authorize cross-account access the policy meant to refuse.
String resourceAccount = accountFromArn(resourceArn);
if (resourceAccount == null || resourceAccount.isBlank()) {
resourceAccount = resourceOwnerAccountId;
}
putIfPresent(conditions, "aws:ResourceAccount", resourceAccount);
putIfPresent(conditions, "aws:PrincipalAccount", accountId);
putIfPresent(conditions, "aws:RequestedRegion", region);
return conditions.isEmpty() ? null : conditions;
}
private static String accountFromArn(String arn) {
if (arn == null || !arn.startsWith("arn:")) {
return null;
}
String[] segments = arn.split(":", 6);
return segments.length > 4 ? segments[4] : null;
}
private static void putIfPresent(Map<String, List<String>> conditions, String key, String value) {
if (value != null && !value.isBlank()) {
conditions.put(key, List.of(value));
}
}
// ── S3 ──────────────────────────────────────────────────────────────────────
private Map<String, List<String>> s3ConditionContext(String action, ContainerRequestContext ctx) {
@@ -251,10 +251,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
: ResourceAccountRelationship.CROSS_ACCOUNT;
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, targetContext);
effectiveResourcePolicies, caller.principalArn(), action, resource, effectiveContext);
Decision decision = evaluator.evaluateResolvedResourcePolicy(
caller, resourcePolicyDecision, accountRelationship, action, resource, targetContext);
caller, resourcePolicyDecision, accountRelationship, action, resource, effectiveContext);
if (decision != Decision.DENY) {
continue;
}
@@ -1,11 +1,5 @@
package io.github.hectorvent.floci.services.iam;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Pattern;
@@ -13,7 +7,7 @@ import org.jboss.logging.Logger;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
/**
* Maps (credentialScope, httpMethod, requestPath) → IAM action string.
@@ -158,71 +152,104 @@ public class IamActionRegistry {
return null;
}
// Subresources S3Controller dispatches ahead of accelerate in its PUT and GET
// chains (acl and tagging are resolved above). When one rides along, that
// operation is what executes, so the accelerate mapping must not claim the
// request. Mirrors the controller's dispatch order — extend together.
private static final List<String> PUT_SUBRESOURCES_BEFORE_ACCELERATE = List.of(
"notification", "versioning", "object-lock", "website", "logging", "policy",
"cors", "lifecycle", "encryption", "publicAccessBlock", "ownershipControls",
"requestPayment");
private static final List<String> GET_SUBRESOURCES_BEFORE_ACCELERATE = List.of(
"uploads", "notification", "versioning", "versions", "location", "object-lock",
"website", "logging", "policy", "cors", "lifecycle", "encryption",
"publicAccessBlock", "ownershipControls", "requestPayment");
// S3Controller's DELETE chain dispatches these ahead of replication (tagging is
// resolved above). Accelerate is NOT here: on DELETE it is dispatched after
// replication. Mirrors the controller's dispatch order — extend together.
private static final List<String> DELETE_SUBRESOURCES_BEFORE_REPLICATION = List.of(
"website", "policy", "cors", "lifecycle", "encryption",
"publicAccessBlock", "ownershipControls");
/** One bucket sub-resource operation: the query parameter that selects it, and the IAM action. */
private record SubResourceAction(String queryParameter, String action) {}
private static SubResourceAction sub(String queryParameter, String action) {
return new SubResourceAction(queryParameter, action);
}
private static final List<SubResourceAction> GET_BUCKET_SUBRESOURCES = List.of(
sub("uploads", "s3:ListBucketMultipartUploads"),
sub("notification", "s3:GetBucketNotification"),
sub("versioning", "s3:GetBucketVersioning"),
sub("versions", "s3:ListBucketVersions"),
sub("location", "s3:GetBucketLocation"),
sub("tagging", "s3:GetBucketTagging"),
sub("object-lock", "s3:GetBucketObjectLockConfiguration"),
sub("website", "s3:GetBucketWebsite"),
sub("logging", "s3:GetBucketLogging"),
sub("policy", "s3:GetBucketPolicy"),
sub("cors", "s3:GetBucketCORS"),
sub("lifecycle", "s3:GetLifecycleConfiguration"),
sub("acl", "s3:GetBucketAcl"),
sub("encryption", "s3:GetEncryptionConfiguration"),
sub("publicAccessBlock", "s3:GetBucketPublicAccessBlock"),
sub("ownershipControls", "s3:GetBucketOwnershipControls"),
sub("requestPayment", "s3:GetBucketRequestPayment"),
sub("accelerate", "s3:GetAccelerateConfiguration"),
sub("replication", "s3:GetReplicationConfiguration"),
sub("metrics", "s3:GetMetricsConfiguration"));
private static final List<SubResourceAction> PUT_BUCKET_SUBRESOURCES = List.of(
sub("notification", "s3:PutBucketNotification"),
sub("versioning", "s3:PutBucketVersioning"),
sub("tagging", "s3:PutBucketTagging"),
sub("object-lock", "s3:PutBucketObjectLockConfiguration"),
sub("website", "s3:PutBucketWebsite"),
sub("logging", "s3:PutBucketLogging"),
sub("policy", "s3:PutBucketPolicy"),
sub("cors", "s3:PutBucketCORS"),
sub("lifecycle", "s3:PutLifecycleConfiguration"),
sub("acl", "s3:PutBucketAcl"),
sub("encryption", "s3:PutEncryptionConfiguration"),
sub("publicAccessBlock", "s3:PutBucketPublicAccessBlock"),
sub("ownershipControls", "s3:PutBucketOwnershipControls"),
sub("requestPayment", "s3:PutBucketRequestPayment"),
sub("accelerate", "s3:PutAccelerateConfiguration"),
sub("replication", "s3:PutReplicationConfiguration"),
sub("metrics", "s3:PutMetricsConfiguration"));
// AWS gives only DeleteBucketPolicy and DeleteBucketWebsite their own action; removing any other
// sub-resource is authorised by the same Put* action that sets it. ?accelerate is absent because
// S3Controller rejects DELETE on it with 405, so no mapping should claim the request.
private static final List<SubResourceAction> DELETE_BUCKET_SUBRESOURCES = List.of(
sub("tagging", "s3:DeleteBucketTagging"),
sub("website", "s3:DeleteBucketWebsite"),
sub("policy", "s3:DeleteBucketPolicy"),
sub("cors", "s3:PutBucketCORS"),
sub("lifecycle", "s3:PutLifecycleConfiguration"),
sub("encryption", "s3:PutEncryptionConfiguration"),
sub("publicAccessBlock", "s3:PutBucketPublicAccessBlock"),
sub("ownershipControls", "s3:PutBucketOwnershipControls"),
sub("replication", "s3:PutReplicationConfiguration"),
sub("metrics", "s3:PutMetricsConfiguration"));
/**
* Resolves S3 sub-resource ops (ACL, tagging, retention, etc.) that
* cannot be distinguished from the parent op by HTTP method + path alone.
* Returns null when no sub-resource is present so the caller falls back
* to the standard rule table.
*/
private static String resolveS3SubResourceAction(String method, ContainerRequestContext ctx) {
var params = ctx.getUriInfo().getQueryParameters();
boolean acl = params.containsKey("acl");
boolean tagging = params.containsKey("tagging");
boolean accelerate = params.containsKey("accelerate");
boolean replication = params.containsKey("replication");
if (!acl && !tagging && !accelerate && !replication) {
return null;
}
// /{bucket}?acl → bucket-level; /{bucket}/{key}?acl → object-level
MultivaluedMap<String, String> params = ctx.getUriInfo().getQueryParameters();
// /{bucket}?acl -> bucket-level; /{bucket}/{key}?acl -> object-level.
// A trailing slash is a valid key character, so /bucket/folder/?acl is an object request -
// we cannot use endsWith("/") to infer bucket-level.
String path = ctx.getUriInfo().getPath();
// Strip leading slash, then check whether there is a key segment after the bucket.
// A trailing slash is a valid key character, so /bucket/folder/?acl is an object
// request — we cannot use endsWith("/") to infer bucket-level.
String stripped = path.startsWith("/") ? path.substring(1) : path;
int firstSlash = stripped.indexOf('/');
boolean isBucketLevel = firstSlash < 0 || firstSlash == stripped.length() - 1;
if (acl) {
if (isBucketLevel) {
return switch (method) {
case "GET" -> "s3:GetBucketAcl";
case "PUT" -> "s3:PutBucketAcl";
default -> null;
};
if (!isBucketLevel) {
return objectSubResourceAction(method, params);
}
List<SubResourceAction> chain = switch (method) {
case "GET" -> GET_BUCKET_SUBRESOURCES;
case "PUT" -> PUT_BUCKET_SUBRESOURCES;
case "DELETE" -> DELETE_BUCKET_SUBRESOURCES;
default -> List.of();
};
for (SubResourceAction entry : chain) {
if (params.containsKey(entry.queryParameter())) {
return entry.action();
}
}
return null;
}
private static String objectSubResourceAction(String method, MultivaluedMap<String, String> params) {
if (params.containsKey("acl")) {
return switch (method) {
case "GET" -> "s3:GetObjectAcl";
case "PUT" -> "s3:PutObjectAcl";
default -> null;
};
}
if (tagging) {
if (isBucketLevel) {
return switch (method) {
case "GET" -> "s3:GetBucketTagging";
case "PUT" -> "s3:PutBucketTagging";
case "DELETE" -> "s3:DeleteBucketTagging";
default -> null;
};
}
if (params.containsKey("tagging")) {
return switch (method) {
case "GET" -> "s3:GetObjectTagging";
case "PUT" -> "s3:PutObjectTagging";
@@ -230,51 +257,7 @@ public class IamActionRegistry {
default -> null;
};
}
// Accelerate and replication are bucket-only subresources; on an object path
// both are inert — the object routes ignore them — so only a bucket-level
// request maps here; everything else falls through to the standard rule table.
if (!isBucketLevel) {
return null;
}
// S3Controller's PUT and GET chains dispatch accelerate ahead of replication,
// so accelerate resolves when both ride along. Its DELETE chain routes
// replication and never routes accelerate to an operation, so on DELETE
// replication resolves even when accelerate is also present.
if (accelerate && !(replication && "DELETE".equals(method))) {
List<String> dispatchedFirst = "PUT".equals(method)
? PUT_SUBRESOURCES_BEFORE_ACCELERATE
: GET_SUBRESOURCES_BEFORE_ACCELERATE;
for (String subresource : dispatchedFirst) {
if (params.containsKey(subresource)) {
return null;
}
}
return switch (method) {
case "GET" -> "s3:GetAccelerateConfiguration";
case "PUT" -> "s3:PutAccelerateConfiguration";
// AWS defines no DELETE for the subresource.
default -> null;
};
}
// Replication. On PUT and GET this is only reached without ?accelerate, so the
// accelerate before-lists cover everything dispatched ahead of replication too.
List<String> dispatchedFirst = switch (method) {
case "PUT" -> PUT_SUBRESOURCES_BEFORE_ACCELERATE;
case "GET" -> GET_SUBRESOURCES_BEFORE_ACCELERATE;
default -> DELETE_SUBRESOURCES_BEFORE_REPLICATION;
};
for (String subresource : dispatchedFirst) {
if (params.containsKey(subresource)) {
return null;
}
}
return switch (method) {
case "GET" -> "s3:GetReplicationConfiguration";
case "PUT" -> "s3:PutReplicationConfiguration";
// AWS authorizes DeleteBucketReplication with the put action.
case "DELETE" -> "s3:PutReplicationConfiguration";
default -> null;
};
return null;
}
/**
@@ -285,49 +268,9 @@ public class IamActionRegistry {
* request is not form-encoded or the body has no {@code Action} field.
*/
private static String readFormAction(ContainerRequestContext ctx) {
MediaType mt = ctx.getMediaType();
if (mt == null
|| !"application".equalsIgnoreCase(mt.getType())
|| !"x-www-form-urlencoded".equalsIgnoreCase(mt.getSubtype())) {
return null;
}
InputStream in = ctx.getEntityStream();
if (in == null) {
return null;
}
byte[] body;
try {
body = in.readAllBytes();
} catch (IOException e) {
LOG.debugv(e, "Failed to buffer form body for IAM action resolution");
return null;
}
ctx.setEntityStream(new ByteArrayInputStream(body));
if (body.length == 0) {
return null;
}
Charset charset = resolveCharset(mt);
String form = new String(body, charset);
for (String pair : form.split("&")) {
int eq = pair.indexOf('=');
String key = eq < 0 ? pair : pair.substring(0, eq);
if (!"Action".equals(URLDecoder.decode(key, charset))) {
continue;
}
return eq < 0 ? "" : URLDecoder.decode(pair.substring(eq + 1), charset);
}
return null;
}
private static Charset resolveCharset(MediaType mt) {
String name = mt.getParameters().get("charset");
if (name == null || name.isBlank()) {
return StandardCharsets.UTF_8;
}
try {
return Charset.forName(name);
} catch (RuntimeException e) {
return StandardCharsets.UTF_8;
}
// Delegates to RequestBodyReader so this and ResourceArnBuilder's per-service resource
// lookups share one buffered copy of the body per request instead of each independently
// reading (and needing to reset) the live entity stream.
return RequestBodyReader.formField(ctx, "Action");
}
}
@@ -0,0 +1,101 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MediaType;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
final class RequestBodyReader {
private static final Logger LOG = Logger.getLogger(RequestBodyReader.class);
private static final String BUFFERED_BODY_PROPERTY =
"io.github.hectorvent.floci.services.iam.RequestBodyReader.bufferedBody";
private RequestBodyReader() {
}
static byte[] buffer(ContainerRequestContext ctx) {
Object cached = ctx.getProperty(BUFFERED_BODY_PROPERTY);
if (cached instanceof byte[] bytes) {
return bytes;
}
InputStream in = ctx.getEntityStream();
byte[] body;
if (in == null) {
body = new byte[0];
} else {
try {
body = in.readAllBytes();
} catch (IOException e) {
LOG.debugv(e, "Failed to buffer request body for IAM enforcement");
body = new byte[0];
}
}
ctx.setEntityStream(new ByteArrayInputStream(body));
ctx.setProperty(BUFFERED_BODY_PROPERTY, body);
return body;
}
static String formField(ContainerRequestContext ctx, String key) {
MediaType mt = ctx.getMediaType();
if (mt == null
|| !"application".equalsIgnoreCase(mt.getType())
|| !"x-www-form-urlencoded".equalsIgnoreCase(mt.getSubtype())) {
return null;
}
byte[] body = buffer(ctx);
if (body.length == 0) {
return null;
}
Charset charset = resolveCharset(mt);
String form = new String(body, charset);
for (String pair : form.split("&")) {
int eq = pair.indexOf('=');
String pairKey = eq < 0 ? pair : pair.substring(0, eq);
if (!key.equals(URLDecoder.decode(pairKey, charset))) {
continue;
}
return eq < 0 ? "" : URLDecoder.decode(pair.substring(eq + 1), charset);
}
return null;
}
static String jsonField(ContainerRequestContext ctx, ObjectMapper objectMapper, String key) {
MediaType mt = ctx.getMediaType();
if (mt == null || !"application".equalsIgnoreCase(mt.getType())
|| mt.getSubtype() == null || !mt.getSubtype().startsWith("x-amz-json")) {
return null;
}
byte[] body = buffer(ctx);
if (body.length == 0) {
return null;
}
try {
JsonNode value = objectMapper.readTree(body).path(key);
return value.isTextual() ? value.asText() : null;
} catch (IOException e) {
LOG.debugv(e, "Failed to parse JSON request body for IAM enforcement");
return null;
}
}
private static Charset resolveCharset(MediaType mt) {
String name = mt.getParameters().get("charset");
if (name == null || name.isBlank()) {
return StandardCharsets.UTF_8;
}
try {
return Charset.forName(name);
} catch (RuntimeException e) {
return StandardCharsets.UTF_8;
}
}
}