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;
}
}
}
@@ -488,6 +488,51 @@ class IamConditionContextResolverTest {
formRequest("Action=TerminateInstances&InstanceId.1=i-denied&InstanceId.1=i-allowed")));
}
@Test
void globalKeysArePopulatedForEveryServiceAndAction() {
Map<String, List<String>> conditions = IamConditionContextResolver.withGlobalContext(
null, "arn:aws:lambda:eu-west-2:000000000000:function:task", "eu-west-2",
"000000000000", "000000000000");
assertEquals(List.of("000000000000"), conditions.get("aws:ResourceAccount"));
assertEquals(List.of("000000000000"), conditions.get("aws:PrincipalAccount"));
assertEquals(List.of("eu-west-2"), conditions.get("aws:RequestedRegion"));
}
@Test
void resourceAccountComesFromTheResourceArnWhenItCarriesOne() {
Map<String, List<String>> conditions = IamConditionContextResolver.withGlobalContext(
Map.of("service:key", List.of("value")),
"arn:aws:sqs:eu-west-2:111111111111:queue", "eu-west-2", "000000000000", "000000000000");
assertEquals(List.of("111111111111"), conditions.get("aws:ResourceAccount"));
assertEquals(List.of("value"), conditions.get("service:key"));
assertFalse(conditions.containsKey("aws:SecureTransport"));
}
@Test
void resourceAccountIsTheBucketOwnerWhenAnS3ArnCarriesNoAccount() {
// S3 bucket and object ARNs have an empty account segment by design, so the owner has to
// come from service state. Falling back to the caller would make a cross-account bucket
// look like the caller's own.
Map<String, List<String>> conditions = IamConditionContextResolver.withGlobalContext(
null, "arn:aws:s3:::partner-bucket/report.csv", "eu-west-2",
"000000000000", "111111111111");
assertEquals(List.of("111111111111"), conditions.get("aws:ResourceAccount"));
assertEquals(List.of("000000000000"), conditions.get("aws:PrincipalAccount"));
}
@Test
void resourceAccountIsOmittedWhenNeitherTheArnNorServiceStateKnowsTheOwner() {
Map<String, List<String>> conditions = IamConditionContextResolver.withGlobalContext(
null, "arn:aws:s3:::orphan-bucket", "eu-west-2", "000000000000", null);
assertFalse(conditions.containsKey("aws:ResourceAccount"),
"guessing the owner would authorize cross-account access a Condition meant to refuse");
assertEquals(List.of("000000000000"), conditions.get("aws:PrincipalAccount"));
}
private Decision decisionForEveryTarget(String policy, String action, ContainerRequestContext request) {
Decision first = evaluator.simulateCustomPolicy(List.of(policy), action, "*",
resolver.resolve("ec2", action, request));
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicy
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.ResourcePolicyProvider;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.enterprise.inject.Instance;
@@ -203,7 +204,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
isNull()))
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -211,7 +212,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
isNull()))
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(conditionContextResolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest))
.thenReturn(null);
@@ -225,14 +226,14 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
isNull());
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000")));
verify(evaluator).evaluateResolvedResourcePolicy(
any(),
eq(ResourcePolicyDecision.NEUTRAL),
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
isNull());
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000")));
verify(containerRequest, never()).abortWith(any());
}
@@ -261,7 +262,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),
isNull()))
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", "000000000000"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -269,7 +270,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("dynamodb:BatchGetItem"),
eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),
isNull()))
eq(globalContext(null, "arn:aws:dynamodb:us-east-1:000000000000:table/TableB", "000000000000"))))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
when(conditionContextResolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest))
.thenReturn(null);
@@ -326,7 +327,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(conditions)))
eq(globalContext(conditions, "*", "222233334444"))))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
newFilter().filter(containerRequest);
@@ -337,7 +338,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(conditions));
eq(globalContext(conditions, "*", "222233334444")));
verify(containerRequest).abortWith(any(Response.class));
}
@@ -353,7 +354,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(first)))
eq(globalContext(first, "*", "222233334444"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -361,7 +362,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(second)))
eq(globalContext(second, "*", "222233334444"))))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
newFilter().filter(containerRequest);
@@ -372,7 +373,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("ec2:TerminateInstances"),
eq("*"),
eq(second));
eq(globalContext(second, "*", "222233334444")));
verify(containerRequest).abortWith(any(Response.class));
}
@@ -404,6 +405,15 @@ class IamEnforcementFilterTest {
verify(containerRequest, never()).abortWith(any());
}
// These cases stub no resource policy, so the filter resolves no owner and passes null. Where
// the ARN carries an account the key is still populated from it; where it does not, such as an
// S3 bucket ARN or a bare "*", the key is correctly absent rather than defaulted to the caller.
private static Map<String, List<String>> globalContext(Map<String, List<String>> serviceContext,
String resourceArn, String accountId) {
return IamConditionContextResolver.withGlobalContext(
serviceContext, resourceArn, "us-east-1", accountId, null);
}
private void stubTaggedTerminate(ContainerRequestContext containerRequest,
Map<String, List<String>> first,
List<Map<String, List<String>>> remaining) {
@@ -454,7 +464,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("s3:ListBucket"),
eq("arn:aws:s3:::bucket"),
eq(conditions)))
eq(globalContext(conditions, "arn:aws:s3:::bucket", "222233334444"))))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
IamEnforcementFilter filter = newFilter();
@@ -467,7 +477,7 @@ class IamEnforcementFilterTest {
eq(ResourceAccountRelationship.SAME_ACCOUNT),
eq("s3:ListBucket"),
eq("arn:aws:s3:::bucket"),
eq(conditions));
eq(globalContext(conditions, "arn:aws:s3:::bucket", "222233334444")));
}
@Test
@@ -1007,4 +1017,77 @@ class IamEnforcementFilterTest {
}
return entity.toString();
}
@Test
void s3ResourceAccountIsTheBucketOwnerNotTheCallerOnCrossAccountAccess() {
// An S3 bucket ARN carries no account, so aws:ResourceAccount has to come from S3 state.
// The caller is 222233334444 and the bucket belongs to 111111111111; a policy conditioned
// on aws:ResourceAccount must see the owner, not the caller.
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
Map<String, List<String>> conditions = Map.of("s3:prefix", List.of("shared/"));
String auth = "AWS4-HMAC-SHA256 Credential=ASIACROSS/20260706/us-east-1/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc";
requestContext.setAccountId("222233334444");
requestContext.setRegion("us-east-1");
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIACROSS");
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:ListBucket");
when(iamService.resolveCallerContext("ASIACROSS"))
.thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
]}""")));
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
.thenReturn(List.of("arn:aws:s3:::partner-bucket"));
when(conditionContextResolver.resolve("s3", "s3:ListBucket", containerRequest))
.thenReturn(conditions);
Map<String, List<String>> expected = IamConditionContextResolver.withGlobalContext(
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()))
.thenReturn(ResourcePolicyDecision.NEUTRAL);
when(evaluator.evaluateResolvedResourcePolicy(
any(),
eq(ResourcePolicyDecision.NEUTRAL),
eq(ResourceAccountRelationship.CROSS_ACCOUNT),
eq("s3:ListBucket"),
eq("arn:aws:s3:::partner-bucket"),
eq(expected)))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
filterWithBucketOwner("111111111111").filter(containerRequest);
verify(evaluator).evaluateResolvedResourcePolicy(
any(),
eq(ResourcePolicyDecision.NEUTRAL),
eq(ResourceAccountRelationship.CROSS_ACCOUNT),
eq("s3:ListBucket"),
eq("arn:aws:s3:::partner-bucket"),
eq(expected));
}
/** Builds a filter whose only resource-policy provider reports the given bucket owner. */
private IamEnforcementFilter filterWithBucketOwner(String ownerAccountId) {
ResourcePolicyProvider provider = (scope, arn) ->
List.of(new ResourcePolicyProvider.ResourcePolicy(null, ownerAccountId));
@SuppressWarnings("unchecked")
jakarta.enterprise.inject.Instance<ResourcePolicyProvider> providers =
mock(jakarta.enterprise.inject.Instance.class);
when(providers.isUnsatisfied()).thenReturn(false);
when(providers.iterator()).thenReturn(List.of(provider).iterator());
@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, scpProvider, sessionAccountLookup, providers);
}
}
@@ -176,18 +176,15 @@ class IamActionRegistryTest {
@Test
void s3AccelerateYieldsToSubresourcesDispatchedFirst() {
// The controller executes the requestPayment operation for this request, so the
// accelerate mapping must not claim it; resolution falls back to the rule table,
// exactly like a plain ?requestPayment request today.
MultivaluedMap<String, String> withRequestPayment = new MultivaluedHashMap<>();
withRequestPayment.add("requestPayment", "");
withRequestPayment.add("accelerate", "");
assertEquals("s3:CreateBucket",
assertEquals("s3:PutBucketRequestPayment",
registry.resolve("s3", mockCtx("PUT", "/bucket", withRequestPayment, null, "")));
MultivaluedMap<String, String> withLocation = new MultivaluedHashMap<>();
withLocation.add("location", "");
withLocation.add("accelerate", "");
assertEquals("s3:ListBucket",
assertEquals("s3:GetBucketLocation",
registry.resolve("s3", mockCtx("GET", "/bucket", withLocation, null, "")));
// uploads is a GET-only dispatch branch; on PUT it is inert and accelerate executes,
// so the mapping must still claim the request there.
@@ -230,23 +227,22 @@ class IamActionRegistryTest {
@Test
void s3ReplicationYieldsToSubresourcesDispatchedFirst() {
// The controller executes the requestPayment operation for this request, so the
// replication mapping must not claim it; resolution falls back to the rule table.
// The first dispatched subresource determines the required permission.
MultivaluedMap<String, String> withRequestPayment = new MultivaluedHashMap<>();
withRequestPayment.add("requestPayment", "");
withRequestPayment.add("replication", "");
assertEquals("s3:CreateBucket",
assertEquals("s3:PutBucketRequestPayment",
registry.resolve("s3", mockCtx("PUT", "/bucket", withRequestPayment, null, "")));
MultivaluedMap<String, String> withLocation = new MultivaluedHashMap<>();
withLocation.add("location", "");
withLocation.add("replication", "");
assertEquals("s3:ListBucket",
assertEquals("s3:GetBucketLocation",
registry.resolve("s3", mockCtx("GET", "/bucket", withLocation, null, "")));
// The DELETE chain dispatches website ahead of replication.
MultivaluedMap<String, String> withWebsite = new MultivaluedHashMap<>();
withWebsite.add("website", "");
withWebsite.add("replication", "");
assertEquals("s3:DeleteBucket",
assertEquals("s3:DeleteBucketWebsite",
registry.resolve("s3", mockCtx("DELETE", "/bucket", withWebsite, null, "")));
// requestPayment has no DELETE dispatch branch; it is inert there and
// replication executes, so the mapping must still claim the request.
@@ -309,6 +305,67 @@ class IamActionRegistryTest {
registry.resolve("s3", mockCtx("DELETE", "/bucket/key.txt", withTagging, null, "")));
}
@Test
void s3BucketSubResourceWritesResolveToTheirOwnActionNotCreateBucket() {
// The live failure: CDK's BucketNotificationsHandler role grants s3:PutBucketNotification
// on "*", exactly what real AWS requires, and the deploy died on
// "not authorized to perform: s3:CreateBucket" because method + path alone decided.
assertEquals("s3:PutBucketNotification", bucketAction("PUT", "notification"));
assertEquals("s3:GetBucketNotification", bucketAction("GET", "notification"));
assertEquals("s3:PutBucketPolicy", bucketAction("PUT", "policy"));
assertEquals("s3:PutBucketVersioning", bucketAction("PUT", "versioning"));
assertEquals("s3:PutEncryptionConfiguration", bucketAction("PUT", "encryption"));
assertEquals("s3:PutLifecycleConfiguration", bucketAction("PUT", "lifecycle"));
assertEquals("s3:PutBucketCORS", bucketAction("PUT", "cors"));
assertEquals("s3:PutBucketPublicAccessBlock", bucketAction("PUT", "publicAccessBlock"));
}
@Test
void s3BucketSubResourceReadsResolveToTheirOwnActionNotListBucket() {
assertEquals("s3:GetBucketLocation", bucketAction("GET", "location"));
assertEquals("s3:GetBucketVersioning", bucketAction("GET", "versioning"));
assertEquals("s3:ListBucketVersions", bucketAction("GET", "versions"));
assertEquals("s3:ListBucketMultipartUploads", bucketAction("GET", "uploads"));
assertEquals("s3:GetBucketPolicy", bucketAction("GET", "policy"));
assertEquals("s3:GetLifecycleConfiguration", bucketAction("GET", "lifecycle"));
assertEquals("s3:GetEncryptionConfiguration", bucketAction("GET", "encryption"));
}
@Test
void s3BucketSubResourceDeletesDoNotDemandDeleteBucket() {
// Removing a CORS rule asked for permission to delete the whole bucket. AWS authorises
// most sub-resource removals with the same Put* action that sets them; only policy and
// website have their own Delete action.
assertEquals("s3:PutBucketCORS", bucketAction("DELETE", "cors"));
assertEquals("s3:PutLifecycleConfiguration", bucketAction("DELETE", "lifecycle"));
assertEquals("s3:PutEncryptionConfiguration", bucketAction("DELETE", "encryption"));
assertEquals("s3:PutReplicationConfiguration", bucketAction("DELETE", "replication"));
assertEquals("s3:DeleteBucketPolicy", bucketAction("DELETE", "policy"));
assertEquals("s3:DeleteBucketWebsite", bucketAction("DELETE", "website"));
// A plain DELETE with no sub-resource still deletes the bucket.
assertEquals("s3:DeleteBucket",
registry.resolve("s3", mockCtx("DELETE", "/bucket", new MultivaluedHashMap<>(), null, "")));
}
@Test
void s3BucketOnlySubResourcesStayInertOnAnObjectPath() {
// ?notification on an object path is ignored by the object routes, so the request really
// is a GetObject/PutObject and must resolve as one.
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.add("notification", "");
assertEquals("s3:GetObject",
registry.resolve("s3", mockCtx("GET", "/bucket/key.txt", params, null, "")));
assertEquals("s3:PutObject",
registry.resolve("s3", mockCtx("PUT", "/bucket/key.txt", params, null, "")));
}
private String bucketAction(String method, String subResource) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.add(subResource, "");
return registry.resolve("s3", mockCtx(method, "/bucket", params, null, ""));
}
// -------------------------------------------------------------------------
private static ContainerRequestContext mockCtx(String method, String path,
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
@@ -14,6 +15,7 @@ import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -296,7 +298,14 @@ class IamManagedPolicyAccountScopeTest {
assertTrue(caller.identityPolicies().stream()
.anyMatch(document -> document.contains("logs:CreateLogGroup")));
assertTrue(caller.boundaryPolicyDocument().contains("NotAction"));
assertFalse(caller.boundaryPolicyDocument().contains("\"Action\":\"*\""));
assertFalse(caller.boundaryPolicyDocument().contains("\"Action\":\"*\"")); IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
String logArn = "arn:aws:logs:us-east-1:" + REQUEST_ACCT + ":log-group:/aws/lambda/task-role:*";
for (String action : List.of("logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents")) {
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
evaluator.evaluate(caller, List.of(), action, logArn, Map.of()));
}
assertEquals(IamPolicyEvaluator.Decision.DENY,
evaluator.evaluate(caller, List.of(), "s3:GetObject", "arn:aws:s3:::private-bucket/key", Map.of()));
}
/**
* The alias is the only IAM entity keyed by a constant rather than a caller-supplied name, so
@@ -0,0 +1,106 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
import io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@QuarkusTest
@TestProfile(LambdaExecutionRoleIamEnforcementIntegrationTest.IamEnforcementProfile.class)
class LambdaScopedTablePermissionIntegrationTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String REGION = "us-east-1";
@Inject
IamService iamService;
@Inject
LambdaExecutionRoleCredentials executionRoleCredentials;
@Test
void executionRoleCanUseOnlyItsGrantedTableAndRequestBodySurvivesAuthorization() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String tableName = "granted-table-" + suffix;
String roleName = "ScopedTableRole" + suffix;
String tableArn = "arn:aws:dynamodb:" + REGION + ":" + ACCOUNT_ID + ":table/" + tableName;
given().config(io.restassured.RestAssured.config().encoderConfig(
io.restassured.config.EncoderConfig.encoderConfig().encodeContentTypeAs(
"application/x-amz-json-1.0", io.restassured.http.ContentType.TEXT)))
.header("Authorization", auth("test"))
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType("application/x-amz-json-1.0")
.body("""
{"TableName":"%s","KeySchema":[{"AttributeName":"id","KeyType":"HASH"}],
"AttributeDefinitions":[{"AttributeName":"id","AttributeType":"S"}],
"BillingMode":"PAY_PER_REQUEST"}
""".formatted(tableName))
.when().post("/")
.then().statusCode(200);
iamService.createRole(roleName, "/", "{}", null, 3600, null);
iamService.putRolePolicy(roleName, "TableAccess", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["dynamodb:PutItem","dynamodb:GetItem"],"Resource":"%s"}]}
""".formatted(tableArn));
LambdaFunction function = new LambdaFunction();
function.setFunctionName("scoped-table-" + suffix);
function.setAccountId(ACCOUNT_ID);
function.setRole("arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName);
SessionCreds credentials = executionRoleCredentials.forFunction(function).orElseThrow();
try {
given().config(io.restassured.RestAssured.config().encoderConfig(
io.restassured.config.EncoderConfig.encoderConfig().encodeContentTypeAs(
"application/x-amz-json-1.0", io.restassured.http.ContentType.TEXT)))
.header("Authorization", auth(credentials.accessKeyId()))
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType("application/x-amz-json-1.0")
.body("""
{"TableName":"%s","Item":{"id":{"S":"record"},"value":{"S":"persisted"}}}
""".formatted(tableName))
.when().post("/")
.then().statusCode(200);
given().config(io.restassured.RestAssured.config().encoderConfig(
io.restassured.config.EncoderConfig.encoderConfig().encodeContentTypeAs(
"application/x-amz-json-1.0", io.restassured.http.ContentType.TEXT)))
.header("Authorization", auth(credentials.accessKeyId()))
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType("application/x-amz-json-1.0")
.body("""
{"TableName":"%s","Key":{"id":{"S":"record"}}}
""".formatted(tableName))
.when().post("/")
.then().statusCode(200).body(containsString("persisted"));
given().config(io.restassured.RestAssured.config().encoderConfig(
io.restassured.config.EncoderConfig.encoderConfig().encodeContentTypeAs(
"application/x-amz-json-1.0", io.restassured.http.ContentType.TEXT)))
.header("Authorization", auth(credentials.accessKeyId()))
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType("application/x-amz-json-1.0")
.body("""
{"TableName":"not-granted-%s","Key":{"id":{"S":"record"}}}
""".formatted(suffix))
.when().post("/")
.then().statusCode(403).body(containsString("AccessDenied"));
} finally {
executionRoleCredentials.unregister(ACCOUNT_ID, credentials.accessKeyId());
iamService.deleteRolePolicy(roleName, "TableAccess");
iamService.deleteRole(roleName);
}
}
private static String auth(String accessKeyId) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260910/" + REGION
+ "/dynamodb/aws4_request, SignedHeaders=host, Signature=abc";
}
}