Light, fluffy, and always free - The AWS Local Emulator alternative
feat(s3): evaluate bucket policies for authenticated callers (#3632)
Simone Primarosa3c23784ca7a6
diff --git a/docs/services/iam.md b/docs/services/iam.mdindex 89341bb1a0..7a2665bf28 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -336,6 +336,15 @@ Policy evaluation follows the standard AWS precedence:5. If a permission boundary is present, it must also explicitly allow the request6. No matching effective allow → implicit deny (HTTP 403)+### Resource-based policies++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.+- 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).+### Service control policies (SCPs)When the caller's account belongs to an [Organizations](organizations.md) organization,diff --git a/docs/services/s3.md b/docs/services/s3.mdindex 8f37de3055..13a012bfa0 100644--- a/docs/services/s3.md+++ b/docs/services/s3.md@@ -201,6 +201,55 @@ CDK asset bucket) is created in one account and read from another.**Why the flag exists, and what it trades away.** Floci partitions every resource by the caller's account, which is the right model for services whose names are account-scoped in AWS. S3 bucket names are not: they are unique across all accounts, a bucket lives in exactly one owning account, and whether another account may touch it is decided by policy rather than by the name being unreachable. A hard per-account partition therefore lets two accounts hold different buckets under one name — a state AWS cannot reach — and makes a legitimate cross-account call fail with `NoSuchBucket` instead of being authorized or denied on its merits. With the flag on, a caller that names another account's bucket resolves it and only IAM and bucket-policy evaluation stand between the caller and the object: AWS-faithful, but stricter than the implicit isolation Floci gives you elsewhere — **provided both `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` (identity-policy checks, applied before the request reaches S3) and `FLOCI_SERVICES_S3_ENFORCE_AUTH` (the S3-specific flag that gates bucket-policy evaluation itself, in `S3Service.authorizeS3Read`/`authorizeS3Write`) are also `true`**. Both default to `false`, and bucket-policy evaluation in particular is a no-op while `FLOCI_SERVICES_S3_ENFORCE_AUTH` is off — regardless of the IAM flag — so in the default configuration enabling the global namespace does not trade per-account isolation for a policy-gated boundary — it removes the only isolation Floci gives S3 for that bucket and replaces it with nothing. Mutations are written back to the bucket's owning account rather than forked into the caller's, and `ListBuckets`/`ListObjects` stay owner-scoped, so the flag never reassigns ownership or leaks a bucket inventory. It is off by default — turn it on when emulating a multi-account estate whose real behaviour depends on the global namespace, and leave it off when the per-account partition is the isolation you are relying on. Account-scoped S3 state, notably the account-level Block Public Access configuration, is never widened by this flag. Note also that retrofitting a global namespace onto state that was previously partitioned per account means that if two accounts already hold a bucket under the same name — a state real AWS can't reach, but Floci's prior per-account isolation could — resolution picks whichever account's copy the backend happens to iterate to first; this is unlikely to be reachable on a fresh LZA-driven account structure, but is worth knowing if you enable the flag on an estate with pre-existing same-name buckets.+## Bucket Policy Enforcement++Floci evaluates S3 bucket policies for authenticated (signed) requests when policy enforcement is enabled. Two flags control this evaluation:++- `FLOCI_SERVICES_S3_ENFORCE_AUTH`: gates bucket policy authorization directly within `S3Service` for bucket read, object write, and bucket write operations.+- `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED`: activates the global IAM request filter to evaluate identity-based policies and resource policies before requests reach the service layer.++Both flags default to `false` for backward compatibility.++### Evaluated Policies and Operations++When `FLOCI_SERVICES_S3_ENFORCE_AUTH` or `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` is active:+- The bucket's attached policy document (configured via `PutBucketPolicy`) is retrieved.+- The caller's authenticated principal ARN is resolved from the signing credentials (for example, `arn:aws:iam::<account>:user/<name>`, `arn:aws:iam::<account>:role/<name>`, or `arn:aws:iam::<account>:root`).+- Policy statements are evaluated for the requested S3 action (e.g. `s3:GetObject`, `s3:PutObject`, `s3:PutBucketPolicy`) and resource ARN (`arn:aws:s3:::bucket` or `arn:aws:s3:::bucket/key`).++### Supported Principal Types++Bucket policy statements can specify principals using `Principal` or `NotPrincipal` with scalar strings or arrays:++- **Wildcard:** `"*"` or `{"AWS": "*"}` matches any caller.+- **IAM User:** `{"AWS": "arn:aws:iam::<account>:user/<name>"}`.+- **IAM Role:** `{"AWS": "arn:aws:iam::<account>:role/<name>"}` (assumed-role sessions also match the underlying role ARN).+- **AWS Account:** `{"AWS": "<12-digit-account-id>"}` or `{"AWS": "arn:aws:iam::<account>:root"}` matches any principal belonging to the specified account.+- **Service Principal:** `{"Service": "<service>.amazonaws.com"}`.+- **NotPrincipal:** Inverts matching so the statement applies to any principal not matching the specified patterns.++### Evaluation Rules++1. An explicit **Deny** always wins and rejects the request.+2. An explicit **Allow** grants access.+3. For bucket owners (principals within the account that owns the bucket), the default decision is **Allow** unless explicitly denied.+4. For non-owner principals, an explicit **Allow** in the bucket policy is required; neutral evaluation results in **Deny**.+5. Unsigned (anonymous) requests and ACL-based public access fall back to standard S3 ACL and anonymous authorization paths.+6. Unknown access key IDs return HTTP 403 with `InvalidAccessKeyId`.++### Wire Response Shape++When a request is denied by bucket policy enforcement, Floci returns HTTP 403 with an S3 XML error body including the `<Resource>` element:++```xml+<Error>+ <Code>AccessDenied</Code>+ <Message>Access Denied</Message>+ <Resource>/my-bucket/my-key</Resource>+ <RequestId>...</RequestId>+</Error>+```+## Account-Level Block Public AccessThe s3control `PutPublicAccessBlock`, `GetPublicAccessBlock` and `DeletePublicAccessBlock` operations are keyed by the `x-amz-account-id` header, stored per account, and persisted like the rest of S3's state so a restart does not silently drop the control. As in AWS, the header must name the caller's own account; a mismatch returns `AccessDenied` (403). Floci keeps one deliberate exception: the configured default (management) account may act on any account, because Floci's launched Lambdas run on placeholder credentials that resolve to the management account instead of assuming a role in the target account — which is how LZA's `Custom::PutPublicAccessBlock` resource reaches this API.@@ -219,6 +268,8 @@ These AWS S3 features have no handler in Floci. Calls will return an error (typi| `FLOCI_SERVICES_S3_ENABLED` | `true` | Enable or disable the service || `FLOCI_SERVICES_S3_DEFAULT_PRESIGN_EXPIRY_SECONDS` | `3600` | Default pre-signed URL expiry (1 hour) || `FLOCI_AUTH_PRESIGN_SECRET` | `local-emulator-secret` | Secret used to sign pre-signed URLs |+| `FLOCI_SERVICES_S3_ENFORCE_AUTH` | `false` | Enable bucket policy evaluation for authenticated callers |+| `FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE` | `false` | Enable cross-account bucket and object resolution |## Examplesdiff --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 4a53ebb59b..29a418dcba 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@@ -9,6 +9,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.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 io.quarkus.vertx.http.runtime.CurrentVertxRequest;@@ -45,8 +46,7 @@ import java.util.regex.Pattern;* </ul>** <p>Evaluates the caller's identity policies, optional session policy, and optional- * permissions boundary. Resource-based policies (S3 bucket policy, Lambda resource- * policy, etc.) are not yet supplied to the primary request-filter path.+ * permissions boundary, as well as applicable resource policies via {@link ResourcePolicyProvider}.** <p>Reads the signing credential from either the {@code Authorization} header or, for a* presigned URL, the {@code X-Amz-Credential} query parameter - both request shapes get the@@ -84,6 +84,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {private final ResolvedServiceCatalog catalog;private final Instance<ScpProvider> scpProvider;private final SessionAccountLookup sessionAccountLookup;+ private final Instance<ResourcePolicyProvider> resourcePolicyProviders;@Injectpublic IamEnforcementFilter(EmulatorConfig config,@@ -98,7 +99,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {CurrentVertxRequest currentVertxRequest,ResolvedServiceCatalog catalog,Instance<ScpProvider> scpProvider,- SessionAccountLookup sessionAccountLookup) {+ SessionAccountLookup sessionAccountLookup,+ Instance<ResourcePolicyProvider> resourcePolicyProviders) {this.config = config;this.accountResolver = accountResolver;this.iamService = iamService;@@ -112,6 +114,26 @@ public class IamEnforcementFilter implements ContainerRequestFilter {this.catalog = catalog;this.scpProvider = scpProvider;this.sessionAccountLookup = sessionAccountLookup;+ this.resourcePolicyProviders = resourcePolicyProviders;+ }++ /** Package-private constructor for callers predating resourcePolicyProviders. */+ IamEnforcementFilter(EmulatorConfig config,+ AccountResolver accountResolver,+ IamService iamService,+ IamPolicyEvaluator evaluator,+ IamActionRegistry actionRegistry,+ ResourceArnBuilder arnBuilder,+ RequestContext requestContext,+ IamConditionContextResolver conditionContextResolver,+ CloudTrailService cloudTrailService,+ CurrentVertxRequest currentVertxRequest,+ ResolvedServiceCatalog catalog,+ Instance<ScpProvider> scpProvider,+ SessionAccountLookup sessionAccountLookup) {+ this(config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,+ requestContext, conditionContextResolver, cloudTrailService, currentVertxRequest,+ catalog, scpProvider, sessionAccountLookup, null);}@Override@@ -202,6 +224,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {? Optional.of("arn:aws:iam::" + accountId + ":root"): iamService.resolveCallerArn(akid);if (principalArn.isPresent()) {+ caller = caller.withPrincipalArn(principalArn.get());conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));}@@ -214,8 +237,24 @@ public class IamEnforcementFilter implements ContainerRequestFilter {}for (String resource : resources) {+ List<ResourcePolicyProvider.ResourcePolicy> resourcePolicies = resolveResourcePolicies(credentialScope, resource);+ String resourceOwnerAccountId = resourcePolicies.isEmpty() ? null : resourcePolicies.getFirst().ownerAccountId();+ List<String> policyDocs = resourcePolicies.stream()+ .map(ResourcePolicyProvider.ResourcePolicy::policyDocument)+ .filter(doc -> doc != null && !doc.isBlank())+ .toList();+ List<String> effectiveResourcePolicies = policyDocs.isEmpty() ? null : policyDocs;++ ResourceAccountRelationship accountRelationship = resourceOwnerAccountId == null+ || accountId.equals(resourceOwnerAccountId)+ ? ResourceAccountRelationship.SAME_ACCOUNT+ : ResourceAccountRelationship.CROSS_ACCOUNT;+for (Map<String, List<String>> targetContext : targetContexts) {- Decision decision = evaluator.evaluate(caller, null, action, resource, targetContext);+ ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicy(+ effectiveResourcePolicies, caller.principalArn(), action, resource, targetContext);+ Decision decision = evaluator.evaluateResolvedResourcePolicy(+ caller, resourcePolicyDecision, accountRelationship, action, resource, targetContext);if (decision != Decision.DENY) {continue;}@@ -225,7 +264,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {+ " on resource: \"" + resource + "\""+ " because no identity-based policy allows the " + action + " action";emitS3DenialIfApplicable(akid, action, resource, ctx, region, denyMessage);- ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType()));+ ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType(), resource));return;}}@@ -321,6 +360,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {? Optional.of("arn:aws:iam::" + accountId + ":root"): iamService.resolveCallerArn(akid);if (principalArn.isPresent()) {+ caller = caller.withPrincipalArn(principalArn.get());conditionContext = new HashMap<>();conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));}@@ -497,11 +537,30 @@ public class IamEnforcementFilter implements ContainerRequestFilter {* <li>everything else (JSON 1.x, REST-JSON) → keep the historical JSON shape</li>* </ul>*/+ private List<ResourcePolicyProvider.ResourcePolicy> resolveResourcePolicies(String credentialScope, String resourceArn) {+ if (resourcePolicyProviders == null || resourcePolicyProviders.isUnsatisfied()) {+ return List.of();+ }+ List<ResourcePolicyProvider.ResourcePolicy> policies = new ArrayList<>();+ for (ResourcePolicyProvider provider : resourcePolicyProviders) {+ List<ResourcePolicyProvider.ResourcePolicy> providerPolicies = provider.getResourcePolicies(credentialScope, resourceArn);+ if (providerPolicies != null && !providerPolicies.isEmpty()) {+ policies.addAll(providerPolicies);+ }+ }+ return policies;+ }+// Package-private for unit testing.static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType) {+ return accessDeniedResponse(action, credentialScope, requestMediaType, null);+ }++ static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType, String resourceArn) {String message = "User is not authorized to perform: " + action;if ("s3".equals(credentialScope)) {- return s3XmlAccessDenied(message);+ String resourcePath = formatS3ResourcePath(resourceArn);+ return s3XmlAccessDenied(message, resourcePath);}if (isFormEncoded(requestMediaType)) {return queryXmlAccessDenied(message);@@ -509,6 +568,17 @@ public class IamEnforcementFilter implements ContainerRequestFilter {return jsonAccessDenied(message);}+ private static String formatS3ResourcePath(String resourceArn) {+ if (resourceArn == null || !resourceArn.startsWith("arn:aws:s3:::")) {+ return null;+ }+ String tail = resourceArn.substring("arn:aws:s3:::".length());+ if (tail.isEmpty() || "*".equals(tail)) {+ return null;+ }+ return "/" + tail;+ }+private static boolean isFormEncoded(MediaType mt) {return mt != null&& "application".equalsIgnoreCase(mt.getType())@@ -530,15 +600,21 @@ public class IamEnforcementFilter implements ContainerRequestFilter {}private static Response s3XmlAccessDenied(String message) {- String xml = new XmlBuilder()+ return s3XmlAccessDenied(message, null);+ }++ private static Response s3XmlAccessDenied(String message, String resourcePath) {+ XmlBuilder xml = new XmlBuilder().raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").start("Error").elem("Code", "AccessDenied")- .elem("Message", message)- .elem("RequestId", UUID.randomUUID().toString())- .end("Error")- .build();- return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml).build();+ .elem("Message", message);+ if (resourcePath != null && !resourcePath.isBlank()) {+ xml.elem("Resource", resourcePath);+ }+ xml.elem("RequestId", UUID.randomUUID().toString())+ .end("Error");+ return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml.build()).build();}private static Response jsonAccessDenied(String message) {diff --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 5e9310e445..fc8cf1fb9d 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@@ -90,7 +90,7 @@ public class IamPolicyEvaluator {* @param resourcePolicies resource-based policy documents (Phase 2); may be null or empty* @param action IAM action, e.g. "s3:GetObject"* @param resource resource ARN, e.g. "arn:aws:s3:::my-bucket/key"- * @param conditionCtx condition context key → values; may be null or empty+ * @param conditionCtx condition context key -> values; may be null or empty* @return {@link Decision#ALLOW} or {@link Decision#DENY}*/public Decision evaluate(CallerContext caller,@@ -98,22 +98,11 @@ public class IamPolicyEvaluator {String action,String resource,Map<String, List<String>> conditionCtx) {- Map<String, List<String>> ctx = normalizeConditionContext(conditionCtx);- String loweredAction = lowercase(action);-- List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());- List<PolicyStatement> resourceStmts = resourcePolicies == null ? List.of() : parseAll(resourcePolicies);- List<PolicyStatement> sessionStmts = caller.sessionPolicyDocument() == null- ? null : parseAll(List.of(caller.sessionPolicyDocument()));- List<PolicyStatement> boundaryStmts = caller.boundaryPolicyDocument() == null- ? null : parseAll(List.of(caller.boundaryPolicyDocument()));-- boolean resourceExplicitDeny = anyExplicitDeny(resourceStmts, loweredAction, resource, ctx);- boolean resourceAllow = anyExplicitAllow(resourceStmts, loweredAction, resource, ctx);- return evaluateParsed(- caller, identityStmts, sessionStmts, boundaryStmts,- resourceExplicitDeny, resourceAllow, false,- ResourceAccountRelationship.SAME_ACCOUNT, loweredAction, resource, ctx);+ String principalArn = caller != null ? caller.principalArn() : null;+ ResourcePolicyDecision resourceDecision = evaluateResourcePolicy(+ resourcePolicies, principalArn, action, resource, conditionCtx);+ return evaluateResolvedResourcePolicy(+ caller, resourceDecision, ResourceAccountRelationship.SAME_ACCOUNT, action, resource, conditionCtx);}/**@@ -167,6 +156,40 @@ public class IamPolicyEvaluator {lowercase(action), resource, ctx);}+ /**+ * Evaluates a resource-based policy standalone for a given caller principal, action,+ * and resource.+ */+ public ResourcePolicyDecision evaluateResourcePolicy(+ List<String> resourcePolicies,+ String principalArn,+ 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)) {+ return ResourcePolicyDecision.EXPLICIT_DENY;+ }+ if (anyResourceDirectIamUserAllow(stmts, principalArn, loweredAction, resource, ctx)) {+ return ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER;+ }+ if (anyResourceExplicitAllow(stmts, principalArn, loweredAction, resource, ctx)) {+ return ResourcePolicyDecision.ALLOW;+ }+ return ResourcePolicyDecision.NEUTRAL;+ }+private Decision evaluateParsed(CallerContext caller,List<PolicyStatement> identityStmts,@@ -352,6 +375,200 @@ public class IamPolicyEvaluator {return false;}+ private boolean anyResourceExplicitDeny(List<PolicyStatement> stmts, String principalArn,+ String action, String resource, Map<String, List<String>> ctx) {+ for (PolicyStatement stmt : stmts) {+ if (stmt.isDeny() && matchesResourceStatement(stmt, principalArn, action, resource, ctx)) {+ return true;+ }+ }+ return false;+ }++ private boolean anyResourceExplicitAllow(List<PolicyStatement> stmts, String principalArn,+ String action, String resource, Map<String, List<String>> ctx) {+ for (PolicyStatement stmt : stmts) {+ if (stmt.isAllow() && matchesResourceStatement(stmt, principalArn, action, resource, ctx)) {+ return true;+ }+ }+ return false;+ }++ private boolean anyResourceDirectIamUserAllow(List<PolicyStatement> stmts, String principalArn,+ String action, String resource, Map<String, List<String>> ctx) {+ for (PolicyStatement stmt : stmts) {+ if (stmt.isAllow() && matchesDirectIamUserStatement(stmt, principalArn, action, resource, ctx)) {+ return true;+ }+ }+ return false;+ }++ private boolean matchesDirectIamUserStatement(PolicyStatement stmt, String principalArn,+ String action, String resource, Map<String, List<String>> ctx) {+ if (principalArn == null || !principalArn.contains(":user/")) {+ return false;+ }+ if (stmt.getPrincipals() == null) {+ return false;+ }+ boolean directMatch = false;+ for (Map.Entry<String, List<String>> entry : stmt.getPrincipals().entrySet()) {+ String type = entry.getKey();+ List<String> patterns = entry.getValue();+ if (patterns == null || patterns.isEmpty()) {+ continue;+ }+ if ("AWS".equalsIgnoreCase(type) || "*".equals(type)) {+ for (String pattern : patterns) {+ if (pattern.equals(principalArn)) {+ directMatch = true;+ break;+ }+ if ("*".equals(pattern) && conditionDirectlyMatchesPrincipalArn(stmt.getConditions(), principalArn)) {+ directMatch = true;+ break;+ }+ }+ }+ if (directMatch) {+ break;+ }+ }+ if (!directMatch) {+ return false;+ }+ return matchesAction(stmt, action)+ && matchesResource(stmt, resource)+ && matchesConditions(stmt.getConditions(), ctx);+ }++ private boolean conditionDirectlyMatchesPrincipalArn(Map<String, Map<String, List<String>>> conditions, String principalArn) {+ if (conditions == null || conditions.isEmpty()) {+ return false;+ }+ for (Map.Entry<String, Map<String, List<String>>> opEntry : conditions.entrySet()) {+ String op = opEntry.getKey();+ if ("StringEquals".equalsIgnoreCase(op) || "ArnEquals".equalsIgnoreCase(op)) {+ Map<String, List<String>> fieldMap = opEntry.getValue();+ if (fieldMap != null) {+ for (Map.Entry<String, List<String>> field : fieldMap.entrySet()) {+ if ("aws:PrincipalArn".equalsIgnoreCase(field.getKey())) {+ List<String> values = field.getValue();+ if (values != null && values.contains(principalArn)) {+ return true;+ }+ }+ }+ }+ }+ }+ return false;+ }++ private boolean matchesResourceStatement(PolicyStatement stmt, String principalArn,+ 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)) {+ return false;+ }+ return matchesAction(stmt, action)+ && matchesResource(stmt, resource)+ && matchesConditions(stmt.getConditions(), ctx);+ }++ private boolean matchesPrincipal(PolicyStatement stmt, String principalArn) {+ if (stmt.getPrincipals() != null) {+ return matchesAnyPrincipal(stmt.getPrincipals(), principalArn);+ }+ if (stmt.getNotPrincipals() != null) {+ return !matchesAnyPrincipal(stmt.getNotPrincipals(), principalArn);+ }+ return false;+ }++ private boolean matchesAnyPrincipal(Map<String, List<String>> principals, String principalArn) {+ for (Map.Entry<String, List<String>> entry : principals.entrySet()) {+ String type = entry.getKey();+ List<String> patterns = entry.getValue();+ if (patterns == null || patterns.isEmpty()) {+ continue;+ }+ if ("*".equals(type)) {+ for (String pattern : patterns) {+ if ("*".equals(pattern)) {+ return true;+ }+ if (principalArn != null && globMatches(pattern, principalArn)) {+ return true;+ }+ }+ } else if ("AWS".equalsIgnoreCase(type)) {+ if (principalArn == null) {+ continue;+ }+ 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 (pattern.matches("arn:aws:iam::\\d{12}:root")) {+ String patternAcct = pattern.substring(13, 25);+ if (patternAcct.equals(accountId)) {+ 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 static String extractAccountId(String arn) {+ if (arn == null || !arn.startsWith("arn:aws:")) {+ return null;+ }+ String[] parts = arn.split(":");+ if (parts.length > 4 && parts[4].matches("\\d{12}")) {+ return parts[4];+ }+ return null;+ }++ private static String extractRoleArnFromAssumedRole(String arn) {+ if (arn == null || !arn.startsWith("arn:aws:sts:")) {+ return null;+ }+ String[] parts = arn.split(":");+ if (parts.length >= 6 && parts[5].startsWith("assumed-role/")) {+ String accountId = parts[4];+ String sessionPath = parts[5].substring("assumed-role/".length());+ int nextSlash = sessionPath.indexOf('/');+ String roleName = nextSlash > 0 ? sessionPath.substring(0, nextSlash) : sessionPath;+ return "arn:aws:iam::" + accountId + ":role/" + roleName;+ }+ return null;+ }+private boolean matchesStatement(PolicyStatement stmt, String action, String resource,Map<String, List<String>> ctx) {return matchesAction(stmt, action)@@ -741,6 +958,8 @@ public class IamPolicyEvaluator {private PolicyStatement parseStatement(JsonNode stmt) {String effect = stmt.path("Effect").asText("Allow");+ Map<String, List<String>> principals = parsePrincipals(stmt.get("Principal"));+ Map<String, List<String>> notPrincipals = parsePrincipals(stmt.get("NotPrincipal"));// Action names are case-insensitive on AWS, so they are lowercased once here instead of// on every request. Resource ARNs are case-sensitive on AWS and are kept as written.List<String> actions = lowercaseAll(nodeToList(stmt.get("Action")));@@ -750,6 +969,8 @@ public class IamPolicyEvaluator {Map<String, Map<String, List<String>>> conditions = parseConditions(stmt.get("Condition"));return new PolicyStatement(effect,+ principals,+ notPrincipals,actions.isEmpty() ? null : actions,notActions.isEmpty() ? null : notActions,resources.isEmpty() ? null : resources,@@ -757,6 +978,31 @@ public class IamPolicyEvaluator {conditions);}+ private Map<String, List<String>> parsePrincipals(JsonNode node) {+ if (node == null || node.isNull() || node.isMissingNode()) {+ return null;+ }+ Map<String, List<String>> result = new LinkedHashMap<>();+ if (node.isTextual()) {+ result.put("*", List.of(node.asText()));+ return result;+ }+ if (node.isArray()) {+ result.put("*", nodeToList(node));+ return result;+ }+ if (node.isObject()) {+ node.fields().forEachRemaining(entry -> {+ List<String> values = nodeToList(entry.getValue());+ if (!values.isEmpty()) {+ result.put(entry.getKey(), values);+ }+ });+ return result.isEmpty() ? null : result;+ }+ return null;+ }+private Map<String, Map<String, List<String>>> parseConditions(JsonNode condNode) {if (condNode == null || condNode.isNull() || !condNode.isObject()) {return null;diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProvider.javanew file mode 100644index 0000000000..b84403aa72--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProvider.java@@ -0,0 +1,25 @@+package io.github.hectorvent.floci.services.iam;++import java.util.List;++/**+ * Supplies the resource-based policy documents that apply to a given (credentialScope, resourceArn).+ *+ * <p>Implemented by services that support resource-based policies (such as S3 for bucket policies);+ * consumed lazily by {@code IamEnforcementFilter} via {@code Instance<ResourcePolicyProvider>}+ * so IAM never depends on resource-owning services directly.</p>+ */+public interface ResourcePolicyProvider {++ record ResourcePolicy(String policyDocument, String ownerAccountId) {}++ /**+ * Returns the resource-based policies that apply to the specified resource,+ * or an empty list if none apply.+ *+ * @param credentialScope the signing credential scope, e.g. "s3"+ * @param resourceArn the target resource ARN, e.g. "arn:aws:s3:::my-bucket/key"+ * @return policy documents and owning account applying to the resource, or an empty list+ */+ List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn);+}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.javaindex 6a518a6ee6..8896e8ca5c 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java@@ -7,35 +7,48 @@ import java.util.List;** <p>Carries all inputs required for the complete AWS policy evaluation algorithm:* <ul>- * <li>{@code identityPolicies} — inline + attached policies of the user, role, and groups</li>- * <li>{@code sessionPolicyDocument} — optional inline session policy from AssumeRole (Phase 3)</li>- * <li>{@code boundaryPolicyDocument} — optional permissions boundary document (Phase 3)</li>- * <li>{@code scpLevels} — optional effective service control policies for the caller's+ * <li>{@code identityPolicies}: inline + attached policies of the user, role, and groups</li>+ * <li>{@code sessionPolicyDocument}: optional inline session policy from AssumeRole (Phase 3)</li>+ * <li>{@code boundaryPolicyDocument}: optional permissions boundary document (Phase 3)</li>+ * <li>{@code scpLevels}: optional effective service control policies for the caller's* account, one list of policy documents per organization level (root, each OU on the* path, account). An action must be allowed at every level and denied at none.* {@code null} when SCPs don't apply (no organization, management account, or SCP* enforcement disabled).</li>+ * <li>{@code principalArn}: optional caller principal ARN used for resource policy evaluation.</li>* </ul>*/public record CallerContext(List<String> identityPolicies,String sessionPolicyDocument,String boundaryPolicyDocument,- List<List<String>> scpLevels+ List<List<String>> scpLevels,+ String principalArn) {+ /** Source-compatible constructor for callers predating principalArn support. */+ public CallerContext(List<String> identityPolicies, String sessionPolicyDocument,+ String boundaryPolicyDocument, List<List<String>> scpLevels) {+ this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, null);+ }+/** Source-compatible constructor for callers predating SCP support. */public CallerContext(List<String> identityPolicies, String sessionPolicyDocument,String boundaryPolicyDocument) {- this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, null);+ this(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, null, null);}/** Convenience factory: no session policy, no boundary, no SCPs. */public static CallerContext of(List<String> identityPolicies) {- return new CallerContext(identityPolicies, null, null, null);+ return new CallerContext(identityPolicies, null, null, null, null);}/** Copy of this context with the effective SCP levels attached. */public CallerContext withScpLevels(List<List<String>> levels) {- return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, levels);+ return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, levels, principalArn);+ }++ /** Copy of this context with the caller principal ARN attached. */+ public CallerContext withPrincipalArn(String principalArn) {+ return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyStatement.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyStatement.javaindex cc3040ab1f..6a34851251 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyStatement.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/PolicyStatement.java@@ -11,6 +11,8 @@ import java.util.Map;public class PolicyStatement {private final String effect; // "Allow" or "Deny"+ private final Map<String, List<String>> principals; // Principal patterns by type; null when not set+ private final Map<String, List<String>> notPrincipals; // NotPrincipal patterns by type; null when not setprivate final List<String> actions; // IAM action patterns; null when notActions is setprivate final List<String> notActions; // NotAction patterns; null when actions is setprivate final List<String> resources; // resource ARN patterns; null when notResources is set@@ -19,12 +21,16 @@ public class PolicyStatement {private final Map<String, Map<String, List<String>>> conditions;public PolicyStatement(String effect,+ Map<String, List<String>> principals,+ Map<String, List<String>> notPrincipals,List<String> actions,List<String> notActions,List<String> resources,List<String> notResources,Map<String, Map<String, List<String>>> conditions) {this.effect = effect;+ this.principals = principals;+ this.notPrincipals = notPrincipals;this.actions = actions;this.notActions = notActions;this.resources = resources;@@ -32,12 +38,23 @@ public class PolicyStatement {this.conditions = conditions;}+ public PolicyStatement(String effect,+ List<String> actions,+ List<String> notActions,+ List<String> resources,+ List<String> notResources,+ Map<String, Map<String, List<String>>> conditions) {+ this(effect, null, null, actions, notActions, resources, notResources, conditions);+ }+/** Convenience constructor for simple allow/deny without conditions or Not* fields. */public PolicyStatement(String effect, List<String> actions, List<String> resources) {- this(effect, actions, null, resources, null, null);+ this(effect, null, null, actions, null, resources, null, null);}public String getEffect() { return effect; }+ public Map<String, List<String>> getPrincipals() { return principals; }+ public Map<String, List<String>> getNotPrincipals() { return notPrincipals; }public List<String> getActions() { return actions; }public List<String> getNotActions() { return notActions; }public List<String> getResources() { return resources; }diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.javaindex cba7bddcdd..c78819dd0c 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java@@ -3099,6 +3099,10 @@ public class S3Controller {// S3 InvalidArgument responses carry ArgumentName and ArgumentValue so the SDK can// surface which input was rejected. They travel through AwsException.extendedData.if (e.getExtendedData() != null) {+ Object resource = e.getExtendedData().get("Resource");+ if (resource != null) {+ xmlBuilder.elem("Resource", resource.toString());+ }Object argumentName = e.getExtendedData().get("ArgumentName");Object argumentValue = e.getExtendedData().get("ArgumentValue");if (argumentName != null) {diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProvider.javanew file mode 100644index 0000000000..49bae1ce3b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3ResourcePolicyProvider.java@@ -0,0 +1,45 @@+package io.github.hectorvent.floci.services.s3;++import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.List;+import java.util.Optional;++/**+ * Supplies S3 bucket policies to the IAM policy evaluation pipeline.+ */+@ApplicationScoped+public class S3ResourcePolicyProvider implements ResourcePolicyProvider {++ private final S3Service s3Service;++ @Inject+ public S3ResourcePolicyProvider(S3Service s3Service) {+ this.s3Service = s3Service;+ }++ @Override+ public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {+ if (!"s3".equalsIgnoreCase(credentialScope) || resourceArn == null) {+ return List.of();+ }+ String bucketName = extractBucketName(resourceArn);+ if (bucketName == null || bucketName.isEmpty() || "*".equals(bucketName)) {+ return List.of();+ }+ Optional<S3Service.BucketPolicyInfo> policyInfo = s3Service.findBucketPolicyInfo(bucketName);+ return policyInfo.map(info -> List.of(new ResourcePolicy(info.policy(), info.ownerAccountId())))+ .orElseGet(List::of);+ }++ private static String extractBucketName(String resourceArn) {+ if (!resourceArn.startsWith("arn:aws:s3:::")) {+ return null;+ }+ String tail = resourceArn.substring("arn:aws:s3:::".length());+ int slash = tail.indexOf('/');+ return slash < 0 ? tail : tail.substring(0, slash);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.javaindex 7a1585250b..e3bc6e2d25 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.Resettable;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;+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.lambda.LambdaService;@@ -141,6 +142,7 @@ public class S3Service implements Resettable, ResourceProvider {private final boolean enforceAuth;private final IamService iamService;private final boolean globalBucketNamespace;+ private final IamPolicyEvaluator policyEvaluator;@Injectpublic S3Service(StorageFactory storageFactory, EmulatorConfig config,@@ -186,6 +188,15 @@ public class S3Service implements Resettable, ResourceProvider {null, "http://localhost:4566", new ObjectMapper(), false, null, false);}+ S3Service(StorageBackend<String, Bucket> bucketStore,+ StorageBackend<String, S3Object> objectStore,+ Path dataRoot, boolean inMemory,+ boolean enforceAuth, IamService iamService) {+ this(bucketStore, objectStore, defaultAnnotationStore(), defaultAccountPublicAccessBlockStore(),+ dataRoot, inMemory, null, null, null, null, null, null, null,+ null, "http://localhost:4566", new ObjectMapper(), enforceAuth, iamService, false);+ }+/** Package-private constructor for testing account-level Block Public Access persistence. */S3Service(StorageBackend<String, Bucket> bucketStore,StorageBackend<String, S3Object> objectStore,@@ -266,6 +277,7 @@ public class S3Service implements Resettable, ResourceProvider {this.enforceAuth = enforceAuth;this.iamService = iamService;this.globalBucketNamespace = globalBucketNamespace;+ this.policyEvaluator = new IamPolicyEvaluator(objectMapper);if (!inMemory) {try {Files.createDirectories(dataRoot);@@ -817,29 +829,31 @@ public class S3Service implements Resettable, ResourceProvider {? authorization: RequestAuthorization.unsigned();if (requestAuthorization.signed()) {+ String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName);+ authorizeSignedBucketPolicy(bucketName, null, action, bucketArn, requestAuthorization);return;}- Bucket bucket = bucketStore.get(bucketName)+ Bucket bucket = resolveBucket(bucketName).orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));// AWS lets only an identity in the bucket owner's account manage the bucket policy; the// policy itself can never grant PutBucketPolicy or DeleteBucketPolicy to an anonymous caller.if (isBucketPolicyAction(action)) {- throw new AwsException("AccessDenied", "Access Denied", 403);+ throw accessDeniedException(bucketName, null);}String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName);S3PublicAccessEvaluator.PublicAccessDecision policyDecision =S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, bucketArn);if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {- throw new AwsException("AccessDenied", "Access Denied", 403);+ throw accessDeniedException(bucketName, null);}if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {return;}- throw new AwsException("AccessDenied", "Access Denied", 403);+ throw accessDeniedException(bucketName, null);}void authorizeObjectRead(String bucketName, String key, String versionId, String action, RequestAuthorization authorization) {@@ -866,17 +880,19 @@ public class S3Service implements Resettable, ResourceProvider {? authorization: RequestAuthorization.unsigned();if (requestAuthorization.signed()) {+ String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key);+ authorizeSignedBucketPolicy(bucketName, key, action, objectArn, requestAuthorization);return;}- Bucket bucket = bucketStore.get(bucketName)+ Bucket bucket = resolveBucket(bucketName).orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key);S3PublicAccessEvaluator.PublicAccessDecision policyDecision =S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, objectArn);if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {- throw new AwsException("AccessDenied", "Access Denied", 403);+ throw accessDeniedException(bucketName, key);}if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {return;@@ -886,7 +902,7 @@ public class S3Service implements Resettable, ResourceProvider {return;}- throw new AwsException("AccessDenied", "Access Denied", 403);+ throw accessDeniedException(bucketName, key);}/**@@ -927,22 +943,17 @@ public class S3Service implements Resettable, ResourceProvider {: RequestAuthorization.unsigned();if (requestAuthorization.signed()) {- if (!isKnownAccessKey(requestAuthorization)) {- throw new AwsException("InvalidAccessKeyId",- "The AWS Access Key Id you provided does not exist in our records.", 403);- }- authorizeSignedPrincipalPolicyDeny(- bucketName, action, resourceArn, requestAuthorization);+ authorizeSignedBucketPolicy(bucketName, key, action, resourceArn, requestAuthorization);return;}- Bucket bucket = bucketStore.get(bucketName)+ Bucket bucket = resolveBucket(bucketName).orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));S3PublicAccessEvaluator.PublicAccessDecision policyDecision =S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, resourceArn);if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {- throw new AwsException("AccessDenied", "Access Denied", 403);+ throw accessDeniedException(bucketName, key);}if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {return;@@ -954,19 +965,99 @@ public class S3Service implements Resettable, ResourceProvider {return;}- throw new AwsException("AccessDenied", "Access Denied", 403);+ throw accessDeniedException(bucketName, key);}- private void authorizeSignedPrincipalPolicyDeny(+ private void authorizeSignedBucketPolicy(String bucketName,+ String key,String action,String resourceArn,RequestAuthorization authorization) {- if (signedPrincipalResourcePolicyDecision(- bucketName, action, resourceArn, authorization)- .decision() == ResourcePolicyDecision.EXPLICIT_DENY) {- throw new AwsException("AccessDenied", "Access Denied", 403);+ if (!isKnownAccessKey(authorization)) {+ throw new AwsException("InvalidAccessKeyId",+ "The AWS Access Key Id you provided does not exist in our records.", 403);+ }++ AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucketEntry = resolveBucketEntry(bucketName)+ .orElseThrow(() -> new AwsException(+ "NoSuchBucket", "The specified bucket does not exist.", 404));+ Bucket bucket = ownedBucketEntry.value();+ String bucketOwner = ownedBucketEntry.account();++ String principalArn = resolvePrincipalArn(authorization.accessKeyId()).orElse(null);+ boolean sameAccountAsOwner = isSameAccountAsBucketOwner(authorization.accessKeyId(), principalArn, bucketOwner);++ if (isBucketPolicyAction(action) && !sameAccountAsOwner) {+ throw accessDeniedException(bucketName, key);+ }++ String policy = bucket.getPolicy();+ if (policy == null || policy.isBlank()) {+ if (sameAccountAsOwner) {+ return;+ }+ throw accessDeniedException(bucketName, key);+ }++ Map<String, List<String>> conditionCtx = principalArn != null+ ? Map.of("aws:PrincipalArn", List.of(principalArn))+ : Map.of();++ ResourcePolicyDecision decision = policyEvaluator.evaluateResourcePolicy(+ List.of(policy),+ principalArn,+ action,+ resourceArn,+ conditionCtx);++ if (decision == ResourcePolicyDecision.EXPLICIT_DENY) {+ throw accessDeniedException(bucketName, key);+ }+ if (decision == ResourcePolicyDecision.ALLOW || decision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER) {+ return;+ }+ if (sameAccountAsOwner) {+ return;+ }+ throw accessDeniedException(bucketName, key);+ }++ private Optional<String> resolvePrincipalArn(String accessKeyId) {+ if (accessKeyId == null || accessKeyId.isBlank()) {+ return Optional.empty();+ }+ if (iamService != null) {+ Optional<String> callerArn = iamService.resolveCallerArn(accessKeyId);+ if (callerArn.isPresent()) {+ return callerArn;+ }+ }+ String account = accessKeyId.matches("\\d{12}") ? accessKeyId : ownerId();+ return Optional.of("arn:aws:iam::" + account + ":root");+ }++ 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()))+ || (accessKeyId != null && accessKeyId.equals(owner))+ || (principalArn != null && owner.equals(extractAccountId(principalArn)));+ }++ private static String extractAccountId(String arn) {+ if (arn == null || !arn.startsWith("arn:aws:")) {+ return null;+ }+ String[] parts = arn.split(":");+ if (parts.length > 4 && parts[4].matches("\\d{12}")) {+ return parts[4];}+ return null;+ }++ private static AwsException accessDeniedException(String bucketName, String key) {+ String resourcePath = key != null ? "/" + bucketName + "/" + key : "/" + bucketName;+ return new AwsException("AccessDenied", "Access Denied", 403, Map.of("Resource", resourcePath));}SignedPrincipalResourcePolicyEvaluation signedPrincipalResourcePolicyDecision(@@ -979,7 +1070,7 @@ public class S3Service implements Resettable, ResourceProvider {return new SignedPrincipalResourcePolicyEvaluation(ResourcePolicyDecision.NEUTRAL, null);}- Optional<String> principalArn = iamService.resolveCallerArn(authorization.accessKeyId());+ Optional<String> principalArn = resolvePrincipalArn(authorization.accessKeyId());if (principalArn.isEmpty()) {return new SignedPrincipalResourcePolicyEvaluation(ResourcePolicyDecision.NEUTRAL, null);}@@ -3281,6 +3372,19 @@ public class S3Service implements Resettable, ResourceProvider {// ──────────────────────────── Policy, CORS, Lifecycle, ACL ────────────────────────────+ public record BucketPolicyInfo(String policy, String ownerAccountId) {}++ public Optional<BucketPolicyInfo> findBucketPolicyInfo(String bucketName) {+ return resolveBucketEntry(bucketName)+ .map(entry -> new BucketPolicyInfo(entry.value().getPolicy(), entry.account()));+ }++ public Optional<String> findBucketPolicy(String bucketName) {+ return findBucketPolicyInfo(bucketName)+ .map(BucketPolicyInfo::policy)+ .filter(policy -> policy != null && !policy.isBlank());+ }+public String getBucketPolicy(String bucketName) {Bucket bucket = resolveBucket(bucketName).orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));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 49de303cf4..1718564a1d 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@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.services.iam.IamActionRegistry;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;@@ -81,6 +83,8 @@ 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()))+ .thenReturn(ResourcePolicyDecision.NEUTRAL);}private IamEnforcementFilter newFilter() {@@ -117,9 +121,10 @@ class IamEnforcementFilterTest {]}""")));when(arnBuilder.buildResources("lambda", containerRequest, "us-east-1", "222233334444")).thenReturn(List.of("arn:aws:lambda:us-east-1:222233334444:function:fn"));- when(evaluator.evaluate(+ when(evaluator.evaluateResolvedResourcePolicy(any(),- isNull(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),eq("lambda:InvokeFunction"),eq("arn:aws:lambda:us-east-1:222233334444:function:fn"),isNull()))@@ -154,9 +159,10 @@ class IamEnforcementFilterTest {]}""")));when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000")).thenReturn(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable"));- when(evaluator.evaluate(+ when(evaluator.evaluateResolvedResourcePolicy(any(),- isNull(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),eq("dynamodb:GetItem"),eq("arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable"),isNull()))@@ -191,9 +197,21 @@ class IamEnforcementFilterTest {"arn:aws:dynamodb:us-east-1:000000000000:table/TableA","arn:aws:dynamodb:us-east-1:000000000000:table/TableB"));- when(evaluator.evaluate(any(), isNull(), eq("dynamodb:BatchGetItem"), eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"), isNull()))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("dynamodb:BatchGetItem"),+ eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),+ isNull())).thenReturn(IamPolicyEvaluator.Decision.ALLOW);- when(evaluator.evaluate(any(), isNull(), eq("dynamodb:BatchGetItem"), eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"), isNull()))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("dynamodb:BatchGetItem"),+ eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),+ isNull())).thenReturn(IamPolicyEvaluator.Decision.ALLOW);when(conditionContextResolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest)).thenReturn(null);@@ -201,8 +219,20 @@ class IamEnforcementFilterTest {IamEnforcementFilter filter = newFilter();filter.filter(containerRequest);- verify(evaluator).evaluate(any(), isNull(), eq("dynamodb:BatchGetItem"), eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"), isNull());- verify(evaluator).evaluate(any(), isNull(), eq("dynamodb:BatchGetItem"), eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"), isNull());+ verify(evaluator).evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("dynamodb:BatchGetItem"),+ eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),+ isNull());+ 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());verify(containerRequest, never()).abortWith(any());}@@ -225,9 +255,21 @@ class IamEnforcementFilterTest {"arn:aws:dynamodb:us-east-1:000000000000:table/TableA","arn:aws:dynamodb:us-east-1:000000000000:table/TableB"));- when(evaluator.evaluate(any(), isNull(), eq("dynamodb:BatchGetItem"), eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"), isNull()))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("dynamodb:BatchGetItem"),+ eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"),+ isNull())).thenReturn(IamPolicyEvaluator.Decision.ALLOW);- when(evaluator.evaluate(any(), isNull(), eq("dynamodb:BatchGetItem"), eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"), isNull()))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("dynamodb:BatchGetItem"),+ eq("arn:aws:dynamodb:us-east-1:000000000000:table/TableB"),+ isNull())).thenReturn(IamPolicyEvaluator.Decision.DENY);when(conditionContextResolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest)).thenReturn(null);@@ -253,7 +295,7 @@ class IamEnforcementFilterTest {filter.filter(containerRequest);verify(iamService, never()).resolveCallerContext(any());- verify(evaluator, never()).evaluate(any(), any(), any(), any(), any());+ verify(evaluator, never()).evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any());verify(containerRequest, never()).abortWith(any());}@@ -278,12 +320,24 @@ class IamEnforcementFilterTest {]}""")));when(conditionContextResolver.resolve("ec2", "ec2:TerminateInstances", containerRequest)).thenReturn(conditions);- when(evaluator.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(conditions)))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("ec2:TerminateInstances"),+ eq("*"),+ eq(conditions))).thenReturn(IamPolicyEvaluator.Decision.DENY);newFilter().filter(containerRequest);- verify(evaluator).evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(conditions));+ verify(evaluator).evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("ec2:TerminateInstances"),+ eq("*"),+ eq(conditions));verify(containerRequest).abortWith(any(Response.class));}@@ -293,14 +347,32 @@ class IamEnforcementFilterTest {Map<String, List<String>> first = Map.of("aws:ResourceTag/Team", List.of("payments"));Map<String, List<String>> second = Map.of("aws:ResourceTag/Team", List.of("engineering"));stubTaggedTerminate(containerRequest, first, List.of(second));- when(evaluator.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(first)))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("ec2:TerminateInstances"),+ eq("*"),+ eq(first))).thenReturn(IamPolicyEvaluator.Decision.ALLOW);- when(evaluator.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(second)))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("ec2:TerminateInstances"),+ eq("*"),+ eq(second))).thenReturn(IamPolicyEvaluator.Decision.DENY);newFilter().filter(containerRequest);- verify(evaluator).evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), eq(second));+ verify(evaluator).evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("ec2:TerminateInstances"),+ eq("*"),+ eq(second));verify(containerRequest).abortWith(any(Response.class));}@@ -310,13 +382,25 @@ class IamEnforcementFilterTest {Map<String, List<String>> first = Map.of("aws:ResourceTag/Team", List.of("payments"));Map<String, List<String>> second = Map.of("aws:ResourceTag/Team", List.of("payments"));stubTaggedTerminate(containerRequest, first, List.of(second));- when(evaluator.evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), any()))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("ec2:TerminateInstances"),+ eq("*"),+ any())).thenReturn(IamPolicyEvaluator.Decision.ALLOW);newFilter().filter(containerRequest);verify(evaluator, org.mockito.Mockito.times(2))- .evaluate(any(), isNull(), eq("ec2:TerminateInstances"), eq("*"), any());+ .evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("ec2:TerminateInstances"),+ eq("*"),+ any());verify(containerRequest, never()).abortWith(any());}@@ -364,15 +448,26 @@ class IamEnforcementFilterTest {.thenReturn(List.of("arn:aws:s3:::bucket"));when(conditionContextResolver.resolve("s3", "s3:ListBucket", containerRequest)).thenReturn(conditions);- when(evaluator.evaluate(any(), isNull(), eq("s3:ListBucket"), eq("arn:aws:s3:::bucket"), eq(conditions)))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("s3:ListBucket"),+ eq("arn:aws:s3:::bucket"),+ eq(conditions))).thenReturn(IamPolicyEvaluator.Decision.ALLOW);IamEnforcementFilter filter = newFilter();filter.filter(containerRequest);- verify(evaluator).evaluate(any(), isNull(), eq("s3:ListBucket"),- eq("arn:aws:s3:::bucket"), eq(conditions));+ verify(evaluator).evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("s3:ListBucket"),+ eq("arn:aws:s3:::bucket"),+ eq(conditions));}@Test@@ -398,7 +493,7 @@ class IamEnforcementFilterTest {]}""")));when(arnBuilder.buildResources(eq("s3"), eq(containerRequest), anyString(), anyString())).thenReturn(List.of("arn:aws:s3:::bucket/key"));- when(evaluator.evaluate(any(), any(), any(), any(), any()))+ when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any())).thenReturn(IamPolicyEvaluator.Decision.DENY);newFilter().filter(containerRequest);@@ -735,8 +830,13 @@ class IamEnforcementFilterTest {.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest)).thenReturn(null);- when(evaluator.evaluate(any(), isNull(), eq("s3:PutObject"),- eq("arn:aws:s3:::some-bucket/test.txt"), any()))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("s3:PutObject"),+ eq("arn:aws:s3:::some-bucket/test.txt"),+ any())).thenReturn(IamPolicyEvaluator.Decision.DENY);newFilter().filter(containerRequest);@@ -765,15 +865,25 @@ class IamEnforcementFilterTest {.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest)).thenReturn(null);- when(evaluator.evaluate(any(), isNull(), eq("s3:PutObject"),- eq("arn:aws:s3:::some-bucket/test.txt"), any()))+ when(evaluator.evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("s3:PutObject"),+ eq("arn:aws:s3:::some-bucket/test.txt"),+ any())).thenReturn(IamPolicyEvaluator.Decision.ALLOW);newFilter().filter(containerRequest);verify(containerRequest, never()).abortWith(any());- verify(evaluator).evaluate(any(), isNull(), eq("s3:PutObject"),- eq("arn:aws:s3:::some-bucket/test.txt"), any());+ verify(evaluator).evaluateResolvedResourcePolicy(+ any(),+ eq(ResourcePolicyDecision.NEUTRAL),+ eq(ResourceAccountRelationship.SAME_ACCOUNT),+ eq("s3:PutObject"),+ eq("arn:aws:s3:::some-bucket/test.txt"),+ any());}@Testdiff --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 a6072e42ff..e7d720b55c 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@@ -512,4 +512,213 @@ class IamPolicyEvaluatorTest {return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"S" + sid + "\",\"Effect\":\"Allow\","+ "\"Action\":\"s3:*\",\"Resource\":\"*\"}]}";}++ @Test+ void evaluatesResourcePolicyPrincipalTypes() {+ // Wildcard '*'+ String wildcard = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:*","Resource":"*"}]}""";+ assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(+ List.of(wildcard), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(+ List.of(wildcard), null, "s3:GetObject", "arn:aws:s3:::b/k", null));++ // AWS wildcard '{"AWS":"*"}'+ String awsWildcard = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"s3:*","Resource":"*"}]}""";+ assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(+ List.of(awsWildcard), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(awsWildcard), null, "s3:GetObject", "arn:aws:s3:::b/k", null));++ // Specific IAM user ARN+ String userPolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:user/alice"},"Action":"s3:*","Resource":"*"}]}""";+ assertEquals(ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, evaluator.evaluateResourcePolicy(+ List.of(userPolicy), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(userPolicy), "arn:aws:iam::123456789012:user/bob", "s3:GetObject", "arn:aws:s3:::b/k", null));++ // IAM role matches assumed-role ARN+ String rolePolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:role/r"},"Action":"s3:*","Resource":"*"}]}""";+ assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(+ List.of(rolePolicy), "arn:aws:sts::123456789012:assumed-role/r/sess", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(rolePolicy), "arn:aws:sts::123456789012:assumed-role/other/sess", "s3:GetObject", "arn:aws:s3:::b/k", null));++ // 12-digit account ID and root ARN match account principals+ String acctPolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"123456789012"},"Action":"s3:*","Resource":"*"}]}""";+ String rootPolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:root"},"Action":"s3:*","Resource":"*"}]}""";+ for (String p : List.of(acctPolicy, rootPolicy)) {+ assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(+ List.of(p), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(p), "arn:aws:iam::999999999999:user/bob", "s3:GetObject", "arn:aws:s3:::b/k", null));+ }++ // 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.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(servicePolicy), "ec2.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":"*"}]}""";+ assertEquals(ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, evaluator.evaluateResourcePolicy(+ List.of(arrayPolicy), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, evaluator.evaluateResourcePolicy(+ List.of(arrayPolicy), "arn:aws:iam::123456789012:user/bob", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(arrayPolicy), "arn:aws:iam::123456789012:user/charlie", "s3:GetObject", "arn:aws:s3:::b/k", null));+ }++ @Test+ void evaluatesResourcePolicyDenyAndNotPrincipal() {+ // NotPrincipal inversion: anyone NOT alice is denied+ String notPrincipal = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Deny","NotPrincipal":{"AWS":"arn:aws:iam::123456789012:user/alice"},"Action":"s3:*","Resource":"*"}]}""";+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(notPrincipal), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.EXPLICIT_DENY, evaluator.evaluateResourcePolicy(+ List.of(notPrincipal), "arn:aws:iam::123456789012:user/bob", "s3:GetObject", "arn:aws:s3:::b/k", null));++ // Explicit Deny overrides Allow+ String denyWins = """+ {"Version":"2012-10-17","Statement":[+ {"Effect":"Allow","Principal":"*","Action":"s3:*","Resource":"*"},+ {"Effect":"Deny","Principal":{"AWS":"arn:aws:iam::123456789012:user/alice"},"Action":"s3:*","Resource":"*"}+ ]}""";+ assertEquals(ResourcePolicyDecision.EXPLICIT_DENY, evaluator.evaluateResourcePolicy(+ List.of(denyWins), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));+ assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(+ List.of(denyWins), "arn:aws:iam::123456789012:user/bob", "s3:GetObject", "arn:aws:s3:::b/k", null));++ // Resource policy statement without Principal matches nothing+ String noPrincipal = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:*","Resource":"*"}]}""";+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(noPrincipal), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));+ }++ @Test+ void evaluatesResourcePolicyConditionsAndIdentityParity() {+ String condPolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:*","Resource":"*",+ "Condition":{"StringEquals":{"aws:SecureTransport":"true"}}}]}""";+ assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(+ List.of(condPolicy), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k",+ Map.of("aws:SecureTransport", List.of("true"))));+ assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(+ List.of(condPolicy), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k",+ Map.of("aws:SecureTransport", List.of("false"))));++ // Identity-based policy without Principal matches regardless of caller principal+ String identityPolicy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:*","Resource":"*"}]}""";+ CallerContext caller = CallerContext.of(List.of(identityPolicy))+ .withPrincipalArn("arn:aws:iam::123456789012:user/alice");+ assertEquals(Decision.ALLOW, evaluator.evaluate(+ caller, null, "s3:GetObject", "arn:aws:s3:::b/k", null));+ }++ @Test+ void crossAccountEvaluationRequiresBothIdentityAndResourcePolicies() {+ String bucketPolicy = """+ {"Version":"2012-10-17","Statement":[{+ "Effect":"Allow",+ "Principal":{"AWS":"arn:aws:iam::111111111111:user/alice"},+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::account-b-bucket/*"+ }]}""";++ // 1. Cross-account caller without identity permission is denied despite bucket policy allow+ CallerContext callerWithoutIdentity = CallerContext.of(List.of())+ .withPrincipalArn("arn:aws:iam::111111111111:user/alice");+ ResourcePolicyDecision resourceDecision = evaluator.evaluateResourcePolicy(+ List.of(bucketPolicy), "arn:aws:iam::111111111111:user/alice", "s3:GetObject", "arn:aws:s3:::account-b-bucket/file.txt", null);+ assertEquals(ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, resourceDecision);+ assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(+ callerWithoutIdentity,+ resourceDecision,+ ResourceAccountRelationship.CROSS_ACCOUNT,+ "s3:GetObject",+ "arn:aws:s3:::account-b-bucket/file.txt",+ null));++ // 2. Cross-account caller with matching identity permission is allowed+ String identityPolicy = """+ {"Version":"2012-10-17","Statement":[{+ "Effect":"Allow",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::account-b-bucket/*"+ }]}""";+ CallerContext callerWithIdentity = CallerContext.of(List.of(identityPolicy))+ .withPrincipalArn("arn:aws:iam::111111111111:user/alice");+ assertEquals(Decision.ALLOW, evaluator.evaluateResolvedResourcePolicy(+ callerWithIdentity,+ resourceDecision,+ ResourceAccountRelationship.CROSS_ACCOUNT,+ "s3:GetObject",+ "arn:aws:s3:::account-b-bucket/file.txt",+ null));+ }++ @Test+ void sameAccountDirectUserBypassesBoundaryWhileAccountGrantDoesNot() {+ String boundaryOmittingS3 = """+ {"Version":"2012-10-17","Statement":[{+ "Effect":"Allow",+ "Action":"dynamodb:*",+ "Resource":"*"+ }]}""";+ CallerContext caller = new CallerContext(+ List.of(),+ null,+ boundaryOmittingS3,+ null,+ "arn:aws:iam::111111111111:user/alice");++ // Direct user ARN in bucket policy bypasses boundary implicit deny+ String directUserPolicy = """+ {"Version":"2012-10-17","Statement":[{+ "Effect":"Allow",+ "Principal":{"AWS":"arn:aws:iam::111111111111:user/alice"},+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::bucket/*"+ }]}""";+ ResourcePolicyDecision directDecision = evaluator.evaluateResourcePolicy(+ List.of(directUserPolicy), "arn:aws:iam::111111111111:user/alice", "s3:GetObject", "arn:aws:s3:::bucket/k", null);+ assertEquals(ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, directDecision);+ assertEquals(Decision.ALLOW, evaluator.evaluateResolvedResourcePolicy(+ caller,+ directDecision,+ ResourceAccountRelationship.SAME_ACCOUNT,+ "s3:GetObject",+ "arn:aws:s3:::bucket/k",+ null));++ // Account delegation or root grant in bucket policy does not bypass boundary implicit deny+ String accountGrantPolicy = """+ {"Version":"2012-10-17","Statement":[{+ "Effect":"Allow",+ "Principal":{"AWS":"arn:aws:iam::111111111111:root"},+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::bucket/*"+ }]}""";+ ResourcePolicyDecision accountDecision = evaluator.evaluateResourcePolicy(+ List.of(accountGrantPolicy), "arn:aws:iam::111111111111:user/alice", "s3:GetObject", "arn:aws:s3:::bucket/k", null);+ assertEquals(ResourcePolicyDecision.ALLOW, accountDecision);+ assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(+ caller,+ accountDecision,+ ResourceAccountRelationship.SAME_ACCOUNT,+ "s3:GetObject",+ "arn:aws:s3:::bucket/k",+ null));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.javanew file mode 100644index 0000000000..519203ed2c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java@@ -0,0 +1,420 @@+package io.github.hectorvent.floci.services.s3;++import io.github.hectorvent.floci.testutil.S3RequestSigner;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+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.Map;+import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertNotNull;++@QuarkusTest+@TestProfile(S3BucketPolicyEnforcementIntegrationTest.EnforcementProfile.class)+class S3BucketPolicyEnforcementIntegrationTest {++ private static final String REGION = "us-east-1";+ private static final String ACCOUNT_A = "111122223333";+ private static final String ACCOUNT_B = "222233334444";+ private static final S3RequestSigner ROOT_SIGNER = S3RequestSigner.signedAs("test", "test");++ record Credentials(String accessKeyId, String secretAccessKey, String userArn) {+ S3RequestSigner signer() {+ return S3RequestSigner.signedAs(accessKeyId, secretAccessKey);+ }+ }++ public static final class EnforcementProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.services.s3.enforce-auth", "true",+ "floci.services.iam.enforcement-enabled", "true",+ "floci.services.s3.global-bucket-namespace", "true"+ );+ }+ }++ private static String auth(String accessKeyId, String service) {+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260629/" + REGION + "/" + service+ + "/aws4_request, SignedHeaders=host, Signature=abc";+ }++ private static Credentials createUser(String userName, String accountId) {+ given()+ .formParam("Action", "CreateUser")+ .formParam("UserName", userName)+ .header("Authorization", auth(accountId, "iam"))+ .when()+ .post("/")+ .then()+ .statusCode(200);++ ExtractableResponse<Response> response = given()+ .formParam("Action", "CreateAccessKey")+ .formParam("UserName", userName)+ .header("Authorization", auth(accountId, "iam"))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract();++ String accessKeyId = response.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");+ String secretAccessKey = response.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey");+ String userArn = "arn:aws:iam::" + accountId + ":user/" + userName;+ return new Credentials(accessKeyId, secretAccessKey, userArn);+ }++ private static Credentials createUserWithCredentials(String userName) {+ return createUser(userName, "000000000000");+ }++ private static Credentials createAccountAdmin(String userName, String accountId) {+ Credentials credentials = createUser(userName, accountId);+ putUserPolicy(userName, "S3Admin", """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": "s3:*",+ "Resource": "*"+ }+ ]+ }""", accountId);+ return credentials;+ }++ private static void putUserPolicy(String userName, String policyName, String policyDocument, String accountId) {+ given()+ .formParam("Action", "PutUserPolicy")+ .formParam("UserName", userName)+ .formParam("PolicyName", policyName)+ .formParam("PolicyDocument", policyDocument)+ .header("Authorization", auth(accountId, "iam"))+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private static String createPolicy(String policyName, String policyDocument, String accountId) {+ ExtractableResponse<Response> response = given()+ .formParam("Action", "CreatePolicy")+ .formParam("PolicyName", policyName)+ .formParam("PolicyDocument", policyDocument)+ .header("Authorization", auth(accountId, "iam"))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract();+ return response.path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");+ }++ private static void putUserPermissionsBoundary(String userName, String boundaryArn, String accountId) {+ given()+ .formParam("Action", "PutUserPermissionsBoundary")+ .formParam("UserName", userName)+ .formParam("PermissionsBoundary", boundaryArn)+ .header("Authorization", auth(accountId, "iam"))+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private static void createBucket(String bucketName) {+ createBucketAs(bucketName, ROOT_SIGNER);+ }++ private static void createBucketAs(String bucketName, S3RequestSigner signer) {+ given()+ .filter(signer)+ .when()+ .put("/" + bucketName)+ .then()+ .statusCode(200);+ }++ private static void putObject(String bucketName, String key, String content) {+ putObjectAs(bucketName, key, content, ROOT_SIGNER);+ }++ private static void putObjectAs(String bucketName, String key, String content, S3RequestSigner signer) {+ given()+ .filter(signer)+ .contentType("text/plain")+ .body(content)+ .when()+ .put("/" + bucketName + "/" + key)+ .then()+ .statusCode(200);+ }++ private static void putBucketPolicy(String bucketName, String policyDocument) {+ putBucketPolicyAs(bucketName, policyDocument, ROOT_SIGNER);+ }++ private static void putBucketPolicyAs(String bucketName, String policyDocument, S3RequestSigner signer) {+ given()+ .filter(signer)+ .contentType("application/json")+ .body(policyDocument)+ .when()+ .put("/" + bucketName + "?policy")+ .then()+ .statusCode(200);+ }++ @Test+ void enforcesBucketPolicyForSignedCallers() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String bucket = "bp-enforce-" + suffix;+ String key = "secret.txt";+ String content = "classified data";++ createBucket(bucket);+ putObject(bucket, key, content);++ Credentials alice = createUserWithCredentials("alice-" + suffix);+ Credentials bob = createUserWithCredentials("bob-" + suffix);+ Credentials charlie = createUserWithCredentials("charlie-" + suffix);++ // Policy allows Alice on object, Bob on bucket, explicitly denies Charlie on object+ String policy = """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {"AWS": "%s"},+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::%s/*"+ },+ {+ "Effect": "Allow",+ "Principal": {"AWS": "%s"},+ "Action": "s3:ListBucket",+ "Resource": "arn:aws:s3:::%s"+ },+ {+ "Effect": "Deny",+ "Principal": {"AWS": "%s"},+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::%s/*"+ }+ ]+ }""".formatted(alice.userArn(), bucket, bob.userArn(), bucket, charlie.userArn(), bucket);+ putBucketPolicy(bucket, policy);++ // 1. Matching caller gets 200+ given()+ .filter(S3RequestSigner.signedAs(alice.accessKeyId(), alice.secretAccessKey()))+ .when()+ .get("/" + bucket + "/" + key)+ .then()+ .statusCode(200)+ .body(equalTo(content));++ // 2. Mismatched caller gets wire-correct 403 XML body with Resource element+ given()+ .filter(S3RequestSigner.signedAs(bob.accessKeyId(), bob.secretAccessKey()))+ .when()+ .get("/" + bucket + "/" + key)+ .then()+ .statusCode(403)+ .body(containsString("<Code>AccessDenied</Code>"))+ .body(containsString("<Resource>/" + bucket + "/" + key + "</Resource>"))+ .body(containsString("<RequestId>"));++ // 3. Explicit deny wins+ given()+ .filter(S3RequestSigner.signedAs(charlie.accessKeyId(), charlie.secretAccessKey()))+ .when()+ .get("/" + bucket + "/" + key)+ .then()+ .statusCode(403)+ .body(containsString("<Code>AccessDenied</Code>"))+ .body(containsString("<Resource>/" + bucket + "/" + key + "</Resource>"));++ // 4. Bucket-level action authorization and resource formatting+ given()+ .filter(S3RequestSigner.signedAs(bob.accessKeyId(), bob.secretAccessKey()))+ .when()+ .get("/" + bucket)+ .then()+ .statusCode(200);++ given()+ .filter(S3RequestSigner.signedAs(alice.accessKeyId(), alice.secretAccessKey()))+ .when()+ .get("/" + bucket)+ .then()+ .statusCode(403)+ .body(containsString("<Code>AccessDenied</Code>"))+ .body(containsString("<Resource>/" + bucket + "</Resource>"));+ }++ @Test+ void crossAccountPrimaryRequestRequiresBothIdentityAndBucketPolicyAllows() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String bucket = "cross-bucket-" + suffix;+ String key = "cross-test.txt";+ String content = "cross-account data";++ Credentials accountAAdmin = createAccountAdmin("admin-a-" + suffix, ACCOUNT_A);+ createBucketAs(bucket, accountAAdmin.signer());+ putObjectAs(bucket, key, content, accountAAdmin.signer());++ Credentials userB = createUser("user-b-" + suffix, ACCOUNT_B);++ // Account A bucket policy allows User B to GetObject+ String bucketPolicy = """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {"AWS": "%s"},+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::%s/*"+ }+ ]+ }""".formatted(userB.userArn(), bucket);+ putBucketPolicyAs(bucket, bucketPolicy, accountAAdmin.signer());++ // 1. User B has bucket policy allow but NO identity policy allow -> 403 AccessDenied with Resource+ given()+ .filter(userB.signer())+ .when()+ .get("/" + bucket + "/" + key)+ .then()+ .statusCode(403)+ .body(containsString("<Code>AccessDenied</Code>"))+ .body(containsString("<Resource>/" + bucket + "/" + key + "</Resource>"));++ // 2. Grant identity policy to User B -> now both allow -> 200 OK+ putUserPolicy(+ "user-b-" + suffix,+ "ReadCrossBucket",+ """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::%s/*"+ }+ ]+ }""".formatted(bucket),+ ACCOUNT_B);++ given()+ .filter(userB.signer())+ .when()+ .get("/" + bucket + "/" + key)+ .then()+ .statusCode(200)+ .body(equalTo(content));+ }++ @Test+ void sameAccountDirectUserBypassesBoundaryOnPrimaryRequest() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String bucket = "boundary-bucket-" + suffix;+ String key = "data.txt";+ String content = "boundary bypass data";++ createBucket(bucket);+ putObject(bucket, key, content);++ // Create boundary policy that only allows dynamodb:* (blocks s3:GetObject)+ String boundaryPolicy = """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": "dynamodb:*",+ "Resource": "*"+ }+ ]+ }""";+ String boundaryArn = createPolicy("boundary-" + suffix, boundaryPolicy, "000000000000");++ String userName = "alice-bnd-" + suffix;+ Credentials alice = createUserWithCredentials(userName);+ putUserPermissionsBoundary(userName, boundaryArn, "000000000000");++ // Identity policy allows s3:GetObject (would be blocked by boundary alone)+ putUserPolicy(userName, "S3Read", """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::%s/*"+ }+ ]+ }""".formatted(bucket), "000000000000");++ // 1. Bucket policy grants to account root: boundary is NOT bypassed -> 403+ String accountGrantPolicy = """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {"AWS": "arn:aws:iam::000000000000:root"},+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::%s/*"+ }+ ]+ }""".formatted(bucket);+ putBucketPolicy(bucket, accountGrantPolicy);++ given()+ .filter(alice.signer())+ .when()+ .get("/" + bucket + "/" + key)+ .then()+ .statusCode(403)+ .body(containsString("<Code>AccessDenied</Code>"))+ .body(containsString("<Resource>/" + bucket + "/" + key + "</Resource>"));++ // 2. Bucket policy directly names Alice's user ARN: boundary IS bypassed -> 200+ String directUserPolicy = """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {"AWS": "%s"},+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::%s/*"+ }+ ]+ }""".formatted(alice.userArn(), bucket);+ putBucketPolicy(bucket, directUserPolicy);++ given()+ .filter(alice.signer())+ .when()+ .get("/" + bucket + "/" + key)+ .then()+ .statusCode(200)+ .body(equalTo(content));+ }+}+