mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(s3): evaluate bucket policies for authenticated callers (#3632)
This commit is contained in:
1 parent
631d98be64
commit
3c23784ca7
13 files changed
+1417
-88
No files matched your search
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccoun
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.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;
|
||||
|
||||
@Inject
|
||||
public 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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 set
|
||||
private final List<String> actions; // IAM action patterns; null when notActions is set
|
||||
private final List<String> notActions; // NotAction patterns; null when actions is set
|
||||
private 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; }
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@Inject
|
||||
public 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));
|
||||
|
||||
Reference in new issue
Block a user