diff --git a/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java
index 78a6f1b1f8..4427cda2ca 100644
--- a/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java
+++ b/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java
@@ -88,6 +88,36 @@ public class IamPolicyEvaluator {
NEUTRAL
}
+ /** What a request came to: allowed, denied by an explicit Deny, or denied for want of an Allow. */
+ public enum Outcome { ALLOW, EXPLICIT_DENY, IMPLICIT_DENY }
+
+ /** The policy family that decided a request. */
+ public enum PolicyLayer { IDENTITY, RESOURCE, SESSION, PERMISSIONS_BOUNDARY, SERVICE_CONTROL }
+
+ /**
+ * The statement that decided a request.
+ *
+ * @param layer the policy family it sits in
+ * @param level the SCP level, or -1 outside {@link PolicyLayer#SERVICE_CONTROL}
+ * @param document its document's index in that layer's list (SCP: within the level; session and
+ * boundary: 0); -1 for {@link PolicyLayer#RESOURCE}, which arrives already decided
+ * @param statement its index in the document's {@code Statement} (0 for a single object); -1 for
+ * {@link PolicyLayer#RESOURCE}
+ * @param sid its {@code Sid}, or null
+ */
+ public record DecidingStatement(PolicyLayer layer, int level, int document, int statement, String sid) {
+ }
+
+ /**
+ * Why a request was decided as it was. {@code statement} is null for an implicit deny, which no
+ * statement caused.
+ */
+ public record DecisionRecord(Outcome outcome, PolicyLayer layer, DecidingStatement statement) {
+ public Decision decision() {
+ return outcome == Outcome.ALLOW ? Decision.ALLOW : Decision.DENY;
+ }
+ }
+
/** How a resource policy statement's principal names a caller: itself, only its account, or not at all. */
private enum PrincipalMatch { NONE, ACCOUNT, CALLER }
@@ -190,25 +220,117 @@ public class IamPolicyEvaluator {
String action,
String resource,
Map> conditionCtx) {
+ return explain(caller, resourcePolicyDecision, accountRelationship, action, resource, conditionCtx)
+ .decision();
+ }
+
+ /**
+ * Evaluates exactly as {@link #evaluateResolvedResourcePolicy} does and names what decided it:
+ * the outcome, the policy family and, for an explicit deny or an identity allow, the statement.
+ * An explicit deny names the first one in the order SCP levels, identity, resource, session,
+ * boundary. An implicit deny names the first layer that stops the request: SCP levels,
+ * identity (or resource), boundary, session.
+ */
+ public DecisionRecord explain(
+ CallerContext caller,
+ ResourcePolicyDecision resourcePolicyDecision,
+ ResourceAccountRelationship accountRelationship,
+ String action,
+ String resource,
+ Map> conditionCtx) {
Map> ctx = normalizeConditionContext(conditionCtx);
- List identityStmts = parseAll(caller.identityPolicies());
- List sessionStmts = caller.sessionPolicyDocument() == null
- ? null : parseAll(List.of(caller.sessionPolicyDocument()));
- List boundaryStmts = caller.boundaryPolicyDocument() == null
- ? null : parseAll(List.of(caller.boundaryPolicyDocument()));
+ String loweredAction = lowercase(action);
+ List identityDocs = parseEach(caller.identityPolicies());
+ List sessionDocs = caller.sessionPolicyDocument() == null
+ ? null : parseEach(List.of(caller.sessionPolicyDocument()));
+ List boundaryDocs = caller.boundaryPolicyDocument() == null
+ ? null : parseEach(List.of(caller.boundaryPolicyDocument()));
ResourcePolicyDecision resolvedDecision = resourcePolicyDecision == null
? ResourcePolicyDecision.NEUTRAL : resourcePolicyDecision;
ResourceAccountRelationship relationship = accountRelationship == null
? ResourceAccountRelationship.CROSS_ACCOUNT : accountRelationship;
- return evaluateParsed(
- caller, identityStmts, sessionStmts, boundaryStmts,
- resolvedDecision == ResourcePolicyDecision.EXPLICIT_DENY,
- resolvedDecision == ResourcePolicyDecision.ALLOW
- || resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER
- || resolvedDecision == ResourcePolicyDecision.ALLOW_ACCOUNT
- && relationship == ResourceAccountRelationship.CROSS_ACCOUNT,
- resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER,
- relationship, lowercase(action), resource, ctx);
+ boolean resourceAllow = resolvedDecision == ResourcePolicyDecision.ALLOW
+ || resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER
+ || resolvedDecision == ResourcePolicyDecision.ALLOW_ACCOUNT
+ && relationship == ResourceAccountRelationship.CROSS_ACCOUNT;
+ boolean directIamUserResourceAllow = resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER;
+
+ // 1. Explicit deny in ANY policy → DENY, whatever else would have been decided.
+ ScpWalk scp = scpWalk(caller.scpLevels(), loweredAction, resource, ctx);
+ DecidingStatement deny = scp.firstDeny();
+ if (deny == null) {
+ deny = firstMatch(PolicyLayer.IDENTITY, -1, identityDocs, true, loweredAction, resource, ctx);
+ }
+ if (deny == null && resolvedDecision == ResourcePolicyDecision.EXPLICIT_DENY) {
+ deny = resourceStatement();
+ }
+ if (deny == null && sessionDocs != null) {
+ deny = firstMatch(PolicyLayer.SESSION, -1, sessionDocs, true, loweredAction, resource, ctx);
+ }
+ if (deny == null && boundaryDocs != null) {
+ deny = firstMatch(PolicyLayer.PERMISSIONS_BOUNDARY, -1, boundaryDocs, true, loweredAction, resource, ctx);
+ }
+ if (deny != null) {
+ return new DecisionRecord(Outcome.EXPLICIT_DENY, deny.layer(), deny);
+ }
+
+ // 2. Service control policies gate everything: the action must be allowed at EVERY
+ // organization level and explicitly denied at none, before identity policies are
+ // even consulted. An empty level means FullAWSAccess semantics and is skipped;
+ // a level holding an unparseable document denies.
+ if (!scp.allows()) {
+ return implicitDeny(PolicyLayer.SERVICE_CONTROL);
+ }
+
+ // 3. Base grant: same-account access needs either policy family; cross-account access
+ // needs both the caller's identity policy and the resource owner's policy.
+ DecidingStatement identityAllow =
+ firstMatch(PolicyLayer.IDENTITY, -1, identityDocs, false, loweredAction, resource, ctx);
+ if (relationship == ResourceAccountRelationship.CROSS_ACCOUNT) {
+ if (identityAllow == null) {
+ return implicitDeny(PolicyLayer.IDENTITY);
+ }
+ if (!resourceAllow) {
+ return implicitDeny(PolicyLayer.RESOURCE);
+ }
+ } else if (identityAllow == null && !resourceAllow) {
+ return implicitDeny(PolicyLayer.IDENTITY);
+ }
+
+ // 4. A same-account resource policy that names an IAM user ARN grants directly to that
+ // user. Its boundary's implicit deny does not cap the grant; explicit denies were
+ // already handled above. Other grants remain limited by the boundary intersection.
+ // AWS checks the boundary ahead of the session policy, so a request both lack is
+ // stopped at the boundary.
+ boolean directSameAccountUserGrant = directIamUserResourceAllow
+ && relationship == ResourceAccountRelationship.SAME_ACCOUNT;
+ boolean boundaryAllows = boundaryDocs == null
+ || firstMatch(PolicyLayer.PERMISSIONS_BOUNDARY, -1, boundaryDocs, false,
+ loweredAction, resource, ctx) != null;
+ if (!directSameAccountUserGrant && !boundaryAllows) {
+ return implicitDeny(PolicyLayer.PERMISSIONS_BOUNDARY);
+ }
+
+ // 5. Session policy (if present) must also allow (intersection)
+ if (sessionDocs != null
+ && firstMatch(PolicyLayer.SESSION, -1, sessionDocs, false, loweredAction, resource, ctx) == null) {
+ return implicitDeny(PolicyLayer.SESSION);
+ }
+
+ // 6. Allowed: the identity statement that granted it, or the resource policy alone. A direct
+ // grant the boundary does not allow is the resource policy's, whatever identity said.
+ DecidingStatement granting = identityAllow != null && !(directSameAccountUserGrant && !boundaryAllows)
+ ? identityAllow : resourceStatement();
+ return new DecisionRecord(Outcome.ALLOW, granting.layer(), granting);
+ }
+
+ private static DecisionRecord implicitDeny(PolicyLayer layer) {
+ return new DecisionRecord(Outcome.IMPLICIT_DENY, layer, null);
+ }
+
+ /** The resource layer arrives already decided, so it has no statement to point at. */
+ private static DecidingStatement resourceStatement() {
+ return new DecidingStatement(PolicyLayer.RESOURCE, -1, -1, -1, null);
}
/**
@@ -283,64 +405,6 @@ public class IamPolicyEvaluator {
return decision == ResourcePolicyDecision.ALLOW ? Decision.ALLOW : Decision.DENY;
}
- private Decision evaluateParsed(
- CallerContext caller,
- List identityStmts,
- List sessionStmts,
- List boundaryStmts,
- boolean resourceExplicitDeny,
- boolean resourceAllow,
- boolean directIamUserResourceAllow,
- ResourceAccountRelationship accountRelationship,
- String action,
- String resource,
- Map> ctx) {
-
- // 0. Service control policies gate everything: the action must be allowed at EVERY
- // organization level and explicitly denied at none, before identity policies are
- // even consulted. An empty level means FullAWSAccess semantics and is skipped;
- // a level holding an unparseable document denies.
- if (!scpAllows(caller.scpLevels(), action, resource, ctx)) {
- return Decision.DENY;
- }
-
- // 1. Explicit deny in ANY policy → DENY immediately
- if (anyExplicitDeny(identityStmts, action, resource, ctx)
- || resourceExplicitDeny
- || (sessionStmts != null && anyExplicitDeny(sessionStmts, action, resource, ctx))
- || (boundaryStmts != null && anyExplicitDeny(boundaryStmts, action, resource, ctx))) {
- return Decision.DENY;
- }
-
- // 2. Base grant: same-account access needs either policy family; cross-account access
- // needs both the caller's identity policy and the resource owner's policy.
- boolean identityAllow = anyExplicitAllow(identityStmts, action, resource, ctx);
- if (accountRelationship == ResourceAccountRelationship.CROSS_ACCOUNT) {
- if (!identityAllow || !resourceAllow) {
- return Decision.DENY;
- }
- } else if (!identityAllow && !resourceAllow) {
- return Decision.DENY;
- }
-
- // 3. Session policy (if present) must also allow (intersection)
- if (sessionStmts != null && !anyExplicitAllow(sessionStmts, action, resource, ctx)) {
- return Decision.DENY;
- }
-
- // 4. A same-account resource policy that names an IAM user ARN grants directly to that
- // user. Its boundary's implicit deny does not cap the grant; explicit denies were
- // already handled above. Other grants remain limited by the boundary intersection.
- boolean directSameAccountUserGrant = directIamUserResourceAllow
- && accountRelationship == ResourceAccountRelationship.SAME_ACCOUNT;
- if (!directSameAccountUserGrant && boundaryStmts != null
- && !anyExplicitAllow(boundaryStmts, action, resource, ctx)) {
- return Decision.DENY;
- }
-
- return Decision.ALLOW;
- }
-
/**
* Convenience overload: identity policies only, no conditions.
* Backward-compatible with Phase 1 callers.
@@ -555,7 +619,7 @@ public class IamPolicyEvaluator {
* The service namespaces an SCP chain leaves reachable, backing the service list in
* {@code GetOrganizationsAccessReport}.
*
- * Level conventions are {@link #scpAllows}'s. A {@code null} chain means SCPs do not apply
+ *
Level conventions are {@link #scpWalk}'s. A {@code null} chain means SCPs do not apply
* and every published namespace is reachable, which is the management account's case. A level
* with no document constrains nothing, since AWS keeps FullAWSAccess attached to every target,
* and a level carrying a document that fails to parse leaves nothing reachable, because the
@@ -569,7 +633,7 @@ public class IamPolicyEvaluator {
* What a namespace-wide reading got right stays right: an SCP denying {@code s3:DeleteBucket}
* alone keeps S3 on the list, because every other S3 action is still reachable.
*
- *
This is not {@link #scpAllows} asked once per namespace. That question needs a concrete
+ *
This is not {@link #scpWalk} asked once per namespace. That question needs a concrete
* action, and a request action of {@code s3:*} would not match a statement naming
* {@code s3:GetObject}, because a pattern globs against a request value and never the other
* way round. The survivors are found by probing instead, with the actions the policies
@@ -756,36 +820,45 @@ public class IamPolicyEvaluator {
}
/**
- * SCP evaluation: at every organization level the action must be explicitly allowed
- * and not explicitly denied. {@code null} levels mean SCPs don't apply; a level with
- * no documents at all (defensive — the last SCP on a target can't be detached) is
- * FullAWSAccess semantics and passes.
+ * SCP evaluation, in one pass over the levels: at every organization level the action must be
+ * explicitly allowed and not explicitly denied. {@code null} levels mean SCPs don't apply; a
+ * level with no documents at all (defensive: the last SCP on a target can't be detached) is
+ * FullAWSAccess semantics and passes. The result carries the first explicit Deny (level,
+ * document, statement order) as well, since an explicit Deny decides ahead of every other
+ * layer.
*
*
A level containing a document that fails to parse denies. The ceiling cannot tell
* what an unreadable guardrail would have said, and every target also carries
* FullAWSAccess, so skipping the bad document would silently leave the level allowing
- * everything the operator meant to forbid.
+ * everything the operator meant to forbid. The Deny lookup alone skips such a document.
*/
- private boolean scpAllows(List> scpLevels, String action, String resource,
- Map> ctx) {
+ private ScpWalk scpWalk(List> scpLevels, String action, String resource,
+ Map> ctx) {
if (scpLevels == null) {
- return true;
+ return new ScpWalk(null, true);
}
- for (List level : scpLevels) {
- ParsedDocuments parsed = parseAllTracked(level);
- if (parsed.anyFailed()) {
- return false;
+ boolean allows = true;
+ for (int level = 0; level < scpLevels.size(); level++) {
+ ParsedDocuments parsed = parseAllTracked(scpLevels.get(level));
+ DecidingStatement deny = firstMatch(PolicyLayer.SERVICE_CONTROL, level, parsed.documents(), true,
+ action, resource, ctx);
+ if (deny != null) {
+ return new ScpWalk(deny, false);
}
- List levelStmts = parsed.statements();
- if (levelStmts.isEmpty()) {
+ if (!allows) {
continue;
}
- if (anyExplicitDeny(levelStmts, action, resource, ctx)
- || !anyExplicitAllow(levelStmts, action, resource, ctx)) {
- return false;
+ List levelStmts = parsed.statements();
+ if (parsed.anyFailed()
+ || (!levelStmts.isEmpty() && !anyExplicitAllow(levelStmts, action, resource, ctx))) {
+ allows = false;
}
}
- return true;
+ return new ScpWalk(null, allows);
+ }
+
+ /** What {@link #scpWalk} found: the first explicit Deny or null, and whether every level passes. */
+ private record ScpWalk(DecidingStatement firstDeny, boolean allows) {
}
// -----------------------------------------------------------------------
@@ -815,24 +888,47 @@ public class IamPolicyEvaluator {
return normalized;
}
- private boolean anyExplicitDeny(List stmts, String action, String resource,
- Map> ctx) {
- for (PolicyStatement stmt : stmts) {
- if (stmt.isDeny() && matchesStatement(stmt, action, resource, ctx)) {
- return true;
+ /**
+ * The first statement, in document then statement order, whose Effect is Deny (or Allow) and
+ * which matches the request, or null. The matching loop is {@link #indexOfMatch}.
+ */
+ private DecidingStatement firstMatch(PolicyLayer layer, int level, List documents,
+ boolean deny, String action, String resource,
+ Map> ctx) {
+ for (int d = 0; d < documents.size(); d++) {
+ List stmts = documents.get(d).statements();
+ int s = indexOfMatch(stmts, deny, action, resource, ctx);
+ if (s >= 0) {
+ return new DecidingStatement(layer, level, d, s, stmts.get(s).getSid());
}
}
- return false;
+ return null;
+ }
+
+ /**
+ * The index of the first statement whose Effect is Deny (or Allow) and which matches the
+ * request, or -1. The one loop behind {@link #firstMatch}, {@link #anyExplicitDeny} and
+ * {@link #anyExplicitAllow}.
+ */
+ private int indexOfMatch(List stmts, boolean deny, String action, String resource,
+ Map> ctx) {
+ for (int i = 0; i < stmts.size(); i++) {
+ PolicyStatement stmt = stmts.get(i);
+ if ((deny ? stmt.isDeny() : stmt.isAllow()) && matchesStatement(stmt, action, resource, ctx)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ private boolean anyExplicitDeny(List stmts, String action, String resource,
+ Map> ctx) {
+ return indexOfMatch(stmts, true, action, resource, ctx) >= 0;
}
private boolean anyExplicitAllow(List stmts, String action, String resource,
Map> ctx) {
- for (PolicyStatement stmt : stmts) {
- if (stmt.isAllow() && matchesStatement(stmt, action, resource, ctx)) {
- return true;
- }
- }
- return false;
+ return indexOfMatch(stmts, false, action, resource, ctx) >= 0;
}
private boolean anyResourceExplicitDeny(List stmts, RequestPrincipal principal,
@@ -1697,30 +1793,40 @@ public class IamPolicyEvaluator {
return IamPolicyDocuments.readsAsPolicyDocument(document);
}
+ /** Each document's parse, in order and position for position, so a statement can be located. */
+ private List parseEach(List documents) {
+ List result = new ArrayList<>();
+ if (documents != null) {
+ for (String doc : documents) {
+ result.add(parseDocument(doc));
+ }
+ }
+ return result;
+ }
+
private List parseAll(List documents) {
return parseAllTracked(documents).statements();
}
/**
- * Parses every document, skipping (and logging) any that fails, and reports whether
- * any did. Callers that can safely ignore a broken document use {@link #parseAll};
- * SCP evaluation reads {@code anyFailed} so the ceiling can fail closed.
+ * Parses every document through {@link #parseEach} and flattens the statements, skipping (and
+ * logging) any that fails, and reports whether any did. Callers that can safely ignore a
+ * broken document use {@link #parseAll}; SCP evaluation reads {@code anyFailed} so the ceiling
+ * can fail closed, and keeps the documents so a statement can be located.
*/
private ParsedDocuments parseAllTracked(List documents) {
- List result = new ArrayList<>();
- if (documents == null) {
- return new ParsedDocuments(result, false);
- }
+ List parsed = parseEach(documents);
+ List statements = new ArrayList<>();
boolean anyFailed = false;
- for (String doc : documents) {
- CachedDocument parsed = parseDocument(doc);
- result.addAll(parsed.statements());
- anyFailed |= parsed.failed();
+ for (CachedDocument document : parsed) {
+ statements.addAll(document.statements());
+ anyFailed |= document.failed();
}
- return new ParsedDocuments(result, anyFailed);
+ return new ParsedDocuments(parsed, statements, anyFailed);
}
- private record ParsedDocuments(List statements, boolean anyFailed) {
+ private record ParsedDocuments(List documents, List statements,
+ boolean anyFailed) {
}
private CachedDocument parseDocument(String document) {
@@ -1786,7 +1892,8 @@ public class IamPolicyEvaluator {
resources.isEmpty() ? null : resources,
notResources.isEmpty()? null : notResources,
conditions,
- version);
+ version,
+ stmt.path("Sid").isTextual() ? stmt.get("Sid").asText() : null);
}
private Map> parsePrincipals(JsonNode node) {
diff --git a/src/main/java/io/floci/aws/services/iam/model/PolicyStatement.java b/src/main/java/io/floci/aws/services/iam/model/PolicyStatement.java
index 99f1c58843..01191c2972 100644
--- a/src/main/java/io/floci/aws/services/iam/model/PolicyStatement.java
+++ b/src/main/java/io/floci/aws/services/iam/model/PolicyStatement.java
@@ -24,6 +24,8 @@ public class PolicyStatement {
// statements from many documents are evaluated as one list, so each carries its own. Null
// when the document has no Version element, which is the 2008-10-17 default.
private final String version;
+ // The statement's Sid, for naming it in a decision record. Never used in matching. Null when absent.
+ private final String sid;
public PolicyStatement(String effect,
Map> principals,
@@ -34,6 +36,20 @@ public class PolicyStatement {
List notResources,
Map>> conditions,
String version) {
+ this(effect, principals, notPrincipals, actions, notActions, resources, notResources, conditions,
+ version, null);
+ }
+
+ public PolicyStatement(String effect,
+ Map> principals,
+ Map> notPrincipals,
+ List actions,
+ List notActions,
+ List resources,
+ List notResources,
+ Map>> conditions,
+ String version,
+ String sid) {
this.effect = effect;
this.principals = principals;
this.notPrincipals = notPrincipals;
@@ -43,6 +59,7 @@ public class PolicyStatement {
this.notResources = notResources;
this.conditions = conditions;
this.version = version;
+ this.sid = sid;
}
/** Without a version, {@code ${...}} stays literal text, as it does under 2008-10-17. */
@@ -69,6 +86,7 @@ public class PolicyStatement {
public List getNotResources() { return notResources; }
public Map>> getConditions() { return conditions; }
public String getVersion() { return version; }
+ public String getSid() { return sid; }
public boolean isDeny() { return "Deny".equalsIgnoreCase(effect); }
public boolean isAllow() { return "Allow".equalsIgnoreCase(effect); }
diff --git a/src/test/java/io/floci/aws/services/iam/IamPolicyEvaluatorDecisionRecordTest.java b/src/test/java/io/floci/aws/services/iam/IamPolicyEvaluatorDecisionRecordTest.java
new file mode 100644
index 0000000000..6e8f0c0649
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/iam/IamPolicyEvaluatorDecisionRecordTest.java
@@ -0,0 +1,289 @@
+package io.floci.aws.services.iam;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.floci.aws.services.iam.IamPolicyEvaluator.DecidingStatement;
+import io.floci.aws.services.iam.IamPolicyEvaluator.Decision;
+import io.floci.aws.services.iam.IamPolicyEvaluator.DecisionRecord;
+import io.floci.aws.services.iam.IamPolicyEvaluator.Outcome;
+import io.floci.aws.services.iam.IamPolicyEvaluator.PolicyLayer;
+import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
+import io.floci.aws.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
+import io.floci.aws.services.iam.model.CallerContext;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * The decision record of the policy evaluator. Expected values follow the AWS IAM policy
+ * evaluation logic (an explicit deny in any applicable policy wins; service control policies,
+ * permissions boundaries and session policies limit; identity or resource policies grant;
+ * otherwise the request is implicitly denied) and are computed by hand, not from the evaluator.
+ */
+class IamPolicyEvaluatorDecisionRecordTest {
+
+ private static final String ACTION = "s3:GetObject";
+ private static final String RESOURCE = "arn:aws:s3:::bucket/key";
+
+ private static final String ALLOW_ALL =
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Action\":\"*\",\"Resource\":\"*\"}]}";
+ private static final String ALLOW_DYNAMODB_ONLY =
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Action\":\"dynamodb:*\",\"Resource\":\"*\"}]}";
+ private static final String ALLOW_ALL_DENY_S3 =
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}";
+ private static final String MALFORMED = "{\"Version\":\"2012-10-17\",\"Statement\":[";
+
+ private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
+
+ private record Row(String name, CallerContext caller, ResourcePolicyDecision resourceDecision,
+ ResourceAccountRelationship relationship, Outcome outcome, PolicyLayer layer) {
+ }
+
+ private static Row row(String name, CallerContext caller, ResourcePolicyDecision resourceDecision,
+ ResourceAccountRelationship relationship, Outcome outcome, PolicyLayer layer) {
+ return new Row(name, caller, resourceDecision, relationship, outcome, layer);
+ }
+
+ private static CallerContext callerWithScps(List identity, List> scpLevels) {
+ return new CallerContext(identity, null, null, scpLevels);
+ }
+
+ private static CallerContext callerWithBoundary(List identity, String boundary) {
+ return new CallerContext(identity, null, boundary);
+ }
+
+ private static CallerContext callerWithSession(List identity, String session) {
+ return new CallerContext(identity, session, null);
+ }
+
+ private static List table() {
+ ResourcePolicyDecision neutral = ResourcePolicyDecision.NEUTRAL;
+ ResourceAccountRelationship same = ResourceAccountRelationship.SAME_ACCOUNT;
+ ResourceAccountRelationship cross = ResourceAccountRelationship.CROSS_ACCOUNT;
+ CallerContext admin = CallerContext.of(List.of(ALLOW_ALL));
+ return List.of(
+ row("scp explicit deny beats identity allow",
+ callerWithScps(List.of(ALLOW_ALL), List.of(List.of(ALLOW_ALL_DENY_S3))),
+ neutral, same, Outcome.EXPLICIT_DENY, PolicyLayer.SERVICE_CONTROL),
+ row("scp level without a matching allow",
+ callerWithScps(List.of(ALLOW_ALL), List.of(List.of(ALLOW_DYNAMODB_ONLY))),
+ neutral, same, Outcome.IMPLICIT_DENY, PolicyLayer.SERVICE_CONTROL),
+ row("scp level holding a malformed document fails closed",
+ callerWithScps(List.of(ALLOW_ALL), List.of(List.of(ALLOW_ALL, MALFORMED))),
+ neutral, same, Outcome.IMPLICIT_DENY, PolicyLayer.SERVICE_CONTROL),
+ row("scp allows at every level",
+ callerWithScps(List.of(ALLOW_ALL), List.of(List.of(ALLOW_ALL), List.of(ALLOW_ALL))),
+ neutral, same, Outcome.ALLOW, PolicyLayer.IDENTITY),
+ row("identity explicit deny beats resource allow",
+ CallerContext.of(List.of(ALLOW_ALL_DENY_S3)),
+ ResourcePolicyDecision.ALLOW, same, Outcome.EXPLICIT_DENY, PolicyLayer.IDENTITY),
+ row("resource explicit deny beats identity allow",
+ admin, ResourcePolicyDecision.EXPLICIT_DENY, same,
+ Outcome.EXPLICIT_DENY, PolicyLayer.RESOURCE),
+ row("session policy explicit deny",
+ callerWithSession(List.of(ALLOW_ALL), ALLOW_ALL_DENY_S3),
+ neutral, same, Outcome.EXPLICIT_DENY, PolicyLayer.SESSION),
+ row("session policy without a matching allow",
+ callerWithSession(List.of(ALLOW_ALL), ALLOW_DYNAMODB_ONLY),
+ neutral, same, Outcome.IMPLICIT_DENY, PolicyLayer.SESSION),
+ row("boundary explicit deny",
+ callerWithBoundary(List.of(ALLOW_ALL), ALLOW_ALL_DENY_S3),
+ neutral, same, Outcome.EXPLICIT_DENY, PolicyLayer.PERMISSIONS_BOUNDARY),
+ row("boundary without a matching allow",
+ callerWithBoundary(List.of(ALLOW_ALL), ALLOW_DYNAMODB_ONLY),
+ neutral, same, Outcome.IMPLICIT_DENY, PolicyLayer.PERMISSIONS_BOUNDARY),
+ row("boundary also caps a resource policy wildcard grant in the same account",
+ callerWithBoundary(List.of(), ALLOW_DYNAMODB_ONLY),
+ ResourcePolicyDecision.ALLOW, same, Outcome.IMPLICIT_DENY, PolicyLayer.PERMISSIONS_BOUNDARY),
+ row("boundary without a matching allow is checked before a session policy that also does not allow",
+ new CallerContext(List.of(ALLOW_ALL), ALLOW_DYNAMODB_ONLY, ALLOW_DYNAMODB_ONLY),
+ neutral, same, Outcome.IMPLICIT_DENY, PolicyLayer.PERMISSIONS_BOUNDARY),
+ row("session policy without a matching allow decides once the boundary allows",
+ new CallerContext(List.of(ALLOW_ALL), ALLOW_DYNAMODB_ONLY, ALLOW_ALL),
+ neutral, same, Outcome.IMPLICIT_DENY, PolicyLayer.SESSION),
+ row("cross-account needs both: identity allow, resource neutral",
+ admin, neutral, cross, Outcome.IMPLICIT_DENY, PolicyLayer.RESOURCE),
+ row("cross-account needs both: resource allow, no identity allow",
+ CallerContext.of(List.of()), ResourcePolicyDecision.ALLOW, cross,
+ Outcome.IMPLICIT_DENY, PolicyLayer.IDENTITY),
+ row("cross-account with both allows",
+ admin, ResourcePolicyDecision.ALLOW, cross, Outcome.ALLOW, PolicyLayer.IDENTITY),
+ row("same account, no identity allow and no resource grant",
+ CallerContext.of(List.of()), neutral, same, Outcome.IMPLICIT_DENY, PolicyLayer.IDENTITY),
+ row("same account, resource policy alone grants",
+ CallerContext.of(List.of()), ResourcePolicyDecision.ALLOW, same,
+ Outcome.ALLOW, PolicyLayer.RESOURCE),
+ row("same account, account-only resource grant without identity allow",
+ CallerContext.of(List.of()), ResourcePolicyDecision.ALLOW_ACCOUNT, same,
+ Outcome.IMPLICIT_DENY, PolicyLayer.IDENTITY),
+ row("direct IAM user resource grant bypasses the boundary's implicit deny",
+ callerWithBoundary(List.of(), ALLOW_DYNAMODB_ONLY),
+ ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, same,
+ Outcome.ALLOW, PolicyLayer.RESOURCE),
+ row("direct IAM user grant stays resource-attributed when a boundary does not allow",
+ callerWithBoundary(List.of(ALLOW_ALL), ALLOW_DYNAMODB_ONLY),
+ ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, same,
+ Outcome.ALLOW, PolicyLayer.RESOURCE),
+ row("direct IAM user grant with a boundary that allows is an identity allow",
+ callerWithBoundary(List.of(ALLOW_ALL), ALLOW_ALL),
+ ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, same,
+ Outcome.ALLOW, PolicyLayer.IDENTITY),
+ row("direct IAM user resource grant does not bypass a boundary explicit deny",
+ callerWithBoundary(List.of(), ALLOW_ALL_DENY_S3),
+ ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, same,
+ Outcome.EXPLICIT_DENY, PolicyLayer.PERMISSIONS_BOUNDARY),
+ row("malformed identity document grants nothing",
+ CallerContext.of(List.of(MALFORMED)), neutral, same,
+ Outcome.IMPLICIT_DENY, PolicyLayer.IDENTITY),
+ row("malformed identity document beside a valid allow is skipped",
+ CallerContext.of(List.of(MALFORMED, ALLOW_ALL)), neutral, same,
+ Outcome.ALLOW, PolicyLayer.IDENTITY),
+ row("plain identity allow",
+ admin, neutral, same, Outcome.ALLOW, PolicyLayer.IDENTITY));
+ }
+
+ @Test
+ void explainDecisionEqualsEvaluateResolvedResourcePolicyForEveryStage() {
+ for (Row r : table()) {
+ DecisionRecord record = evaluator.explain(r.caller(), r.resourceDecision(), r.relationship(),
+ ACTION, RESOURCE, null);
+ Decision expected = r.outcome() == Outcome.ALLOW ? Decision.ALLOW : Decision.DENY;
+
+ assertEquals(expected, evaluator.evaluateResolvedResourcePolicy(r.caller(), r.resourceDecision(),
+ r.relationship(), ACTION, RESOURCE, null), r.name() + ": evaluateResolvedResourcePolicy");
+ assertEquals(expected, record.decision(), r.name() + ": explain().decision()");
+ assertEquals(r.outcome(), record.outcome(), r.name() + ": outcome");
+ assertEquals(r.layer(), record.layer(), r.name() + ": layer");
+ }
+ }
+
+ @Test
+ void identityExplicitDenyNamesLayerDocumentStatementAndSid() {
+ String readOnly = """
+ {"Version":"2012-10-17","Statement":[
+ {"Sid":"Ec2","Effect":"Allow","Action":"ec2:*","Resource":"*"},
+ {"Sid":"DenyRead","Effect":"Deny","Action":"s3:GetObject","Resource":"*"},
+ {"Sid":"DenyAllS3","Effect":"Deny","Action":"s3:*","Resource":"*"}
+ ]}""";
+ // The session policy denies too, but the order is SCP, identity, resource, session, boundary.
+ CallerContext caller = new CallerContext(List.of(ALLOW_ALL, readOnly), ALLOW_ALL_DENY_S3, null);
+
+ DecisionRecord record = evaluator.explain(caller, ResourcePolicyDecision.NEUTRAL,
+ ResourceAccountRelationship.SAME_ACCOUNT, ACTION, RESOURCE, null);
+
+ assertEquals(Outcome.EXPLICIT_DENY, record.outcome());
+ assertEquals(PolicyLayer.IDENTITY, record.layer());
+ assertEquals(new DecidingStatement(PolicyLayer.IDENTITY, -1, 1, 1, "DenyRead"), record.statement());
+ assertEquals(Decision.DENY, record.decision());
+ }
+
+ @Test
+ void scpExplicitDenyWinsOverMissingIdentityAllowAndNamesTheLevel() {
+ String levelOne = """
+ {"Version":"2012-10-17","Statement":[
+ {"Sid":"AllowAll","Effect":"Allow","Action":"*","Resource":"*"},
+ {"Sid":"NoS3","Effect":"Deny","Action":"s3:*","Resource":"*"}
+ ]}""";
+ CallerContext caller = callerWithScps(List.of(), List.of(List.of(ALLOW_ALL), List.of(levelOne)));
+
+ DecisionRecord record = evaluator.explain(caller, ResourcePolicyDecision.NEUTRAL,
+ ResourceAccountRelationship.SAME_ACCOUNT, ACTION, RESOURCE, null);
+
+ assertEquals(Outcome.EXPLICIT_DENY, record.outcome());
+ assertEquals(PolicyLayer.SERVICE_CONTROL, record.layer());
+ assertEquals(new DecidingStatement(PolicyLayer.SERVICE_CONTROL, 1, 0, 1, "NoS3"), record.statement());
+ }
+
+ @Test
+ void scpWithoutAnAllowIsAnImplicitDenyWithNoStatement() {
+ CallerContext caller = callerWithScps(List.of(ALLOW_ALL),
+ List.of(List.of(ALLOW_ALL), List.of(ALLOW_DYNAMODB_ONLY)));
+
+ DecisionRecord record = evaluator.explain(caller, ResourcePolicyDecision.NEUTRAL,
+ ResourceAccountRelationship.SAME_ACCOUNT, ACTION, RESOURCE, null);
+
+ assertEquals(Outcome.IMPLICIT_DENY, record.outcome());
+ assertEquals(PolicyLayer.SERVICE_CONTROL, record.layer());
+ assertNull(record.statement());
+ assertEquals(Decision.DENY, record.decision());
+ }
+
+ @Test
+ void noIdentityAllowInTheSameAccountIsAnImplicitIdentityDeny() {
+ DecisionRecord record = evaluator.explain(CallerContext.of(List.of(ALLOW_DYNAMODB_ONLY)),
+ ResourcePolicyDecision.NEUTRAL, ResourceAccountRelationship.SAME_ACCOUNT,
+ ACTION, RESOURCE, null);
+
+ assertEquals(Outcome.IMPLICIT_DENY, record.outcome());
+ assertEquals(PolicyLayer.IDENTITY, record.layer());
+ assertNull(record.statement());
+ }
+
+ @Test
+ void aBoundaryThatDoesNotAllowIsAnImplicitBoundaryDeny() {
+ CallerContext caller = callerWithBoundary(List.of(ALLOW_ALL), ALLOW_DYNAMODB_ONLY);
+
+ DecisionRecord record = evaluator.explain(caller, ResourcePolicyDecision.NEUTRAL,
+ ResourceAccountRelationship.SAME_ACCOUNT, ACTION, RESOURCE, null);
+
+ assertEquals(Outcome.IMPLICIT_DENY, record.outcome());
+ assertEquals(PolicyLayer.PERMISSIONS_BOUNDARY, record.layer());
+ assertNull(record.statement());
+ }
+
+ @Test
+ void anAllowNamesTheFirstMatchingIdentityAllowStatement() {
+ String firstDocument = """
+ {"Version":"2012-10-17","Statement":[
+ {"Sid":"Ec2","Effect":"Allow","Action":"ec2:*","Resource":"*"}
+ ]}""";
+ String secondDocument = """
+ {"Version":"2012-10-17","Statement":[
+ {"Sid":"Ddb","Effect":"Allow","Action":"dynamodb:*","Resource":"*"},
+ {"Sid":"ReadS3","Effect":"Allow","Action":"s3:GetObject","Resource":"*"},
+ {"Sid":"AllS3","Effect":"Allow","Action":"s3:*","Resource":"*"}
+ ]}""";
+ CallerContext caller = CallerContext.of(List.of(firstDocument, secondDocument));
+
+ DecisionRecord record = evaluator.explain(caller, ResourcePolicyDecision.NEUTRAL,
+ ResourceAccountRelationship.SAME_ACCOUNT, ACTION, RESOURCE, Map.of());
+
+ assertEquals(Outcome.ALLOW, record.outcome());
+ assertEquals(PolicyLayer.IDENTITY, record.layer());
+ assertEquals(new DecidingStatement(PolicyLayer.IDENTITY, -1, 1, 1, "ReadS3"), record.statement());
+ assertEquals(Decision.ALLOW, record.decision());
+ }
+
+ @Test
+ void aDirectIamUserGrantIsAttributedToTheResourceOnlyWhenTheBoundaryDoesNotAllow() {
+ String identity = """
+ {"Version":"2012-10-17","Statement":[
+ {"Sid":"ReadS3","Effect":"Allow","Action":"s3:GetObject","Resource":"*"}
+ ]}""";
+
+ // The boundary does not allow the action: only the resource policy lets the request through.
+ DecisionRecord viaResource = evaluator.explain(callerWithBoundary(List.of(identity), ALLOW_DYNAMODB_ONLY),
+ ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, ResourceAccountRelationship.SAME_ACCOUNT,
+ ACTION, RESOURCE, null);
+
+ assertEquals(Outcome.ALLOW, viaResource.outcome());
+ assertEquals(PolicyLayer.RESOURCE, viaResource.layer());
+ assertEquals(new DecidingStatement(PolicyLayer.RESOURCE, -1, -1, -1, null), viaResource.statement());
+
+ // The boundary allows the action: the identity policy grants it.
+ DecisionRecord viaIdentity = evaluator.explain(callerWithBoundary(List.of(identity), ALLOW_ALL),
+ ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, ResourceAccountRelationship.SAME_ACCOUNT,
+ ACTION, RESOURCE, null);
+
+ assertEquals(Outcome.ALLOW, viaIdentity.outcome());
+ assertEquals(PolicyLayer.IDENTITY, viaIdentity.layer());
+ assertEquals(new DecidingStatement(PolicyLayer.IDENTITY, -1, 0, 0, "ReadS3"), viaIdentity.statement());
+ }
+}