feat(iam): resolve policy variables in Resource patterns and Condition values (#5639)

A ${...} in a Resource pattern or a Condition value was matched as the text it
is written as, so a statement scoped to arn:aws:iam::*:user/${aws:username}
matched no user at all. AWS's own IAMUserChangePassword policy is written that
way and floci vendors it verbatim, so under enforcement it authorized nothing,
and it is not alone: 244 of the 1586 vendored managed policy documents carry a
variable, and of the 1635 occurrences in them 1443 sit in a Condition value
and 192 in a Resource. The Condition share is where the loss bites hardest,
since a variable that cannot resolve quietly drops a Deny that AWS honours.

The keys a variable resolves against arrived with #5568, which put
aws:username, aws:userid and aws:PrincipalType into the request context. This
is the other half of that work: without substitution the keys answer nobody,
and without the keys substitution has nothing to find.

Variables now resolve wherever the evaluator matches a statement, which covers
every document it reads: identity policies, resource policies, session
policies, permissions boundaries, SCPs, and the Condition of a role trust
policy, whose own Version now reaches the condition check. A trust policy is
the narrow case, since sts:AssumeRole is authorized before there is a session
to describe: that context carries aws:PrincipalArn, the account and region
keys, sts:RoleSessionName and sts:ExternalId, so a variable naming
aws:username, aws:userid or aws:PrincipalType finds nothing there, which
iam.md now says.

Two of the rules are easy to miss. Substitution is gated on "Version":
"2012-10-17", because under the older 2008-10-17, which is also the default
when the element is absent, the user guide says variables "are instead treated
as literal strings in the policy"; the version therefore rides on each parsed
statement, since statements from many documents are evaluated as one list. And
a variable with no value is not an empty string: in Resource the pattern "will
not match any resource", in NotResource that same rule excludes nothing, and
in a Condition the positive operators do not match while the inverted ones do,
which is what makes the Deny AWS documents for an unset principal tag fire.

The rest, also from the user guide: a variable resolves only in the resource
portion of an ARN, after the fifth colon; only with the string and ARN
condition operators, never Numeric, Date, Bool, IpAddress or Null; only for a
single-valued key, a multivalued one having no one value to stand in, which a
default does not rescue, since a default answers a key with no value rather
than one with several; and case-insensitively by key name, a name that holds
no space, the guide allowing one inside a quoted default and nowhere else. A
spaced name, an empty ${}, a missing brace and an unquoted default are the
forms the guide's policy checks call errors, and each stays the text it is.
${*}, ${?} and ${$} stand for a literal character, so the glob gained an
escape marker, honoured only on a pattern that came back from substitution and
stripped from whatever arrived in the policy: a document can write the marker
as a JSON escape, and reading it as one would turn a wildcard of the
document's own into a literal character and narrow the statement it sits in. A
resolved value is not escaped, matching AWS, whose policy checks warn that
variables "can be evaluated as effective wildcards".

Verified at this commit: 7442 tests across the 439 IAM, core, enforcement and
resource-policy classes the evaluator is reached from, Checkstyle and
docs-check clean. AWS's own IAMUserChangePassword document is attached to a
user and called on the request path, both of its patterns included, the second
scoping a user under a path. Each rule was probed by reverting it alone, which
is how two weak tests were found: a valueless variable beside a wildcard and
the operator restriction both needed a case whose answer flips. The escape
marker is probed from both sides, by letting the resolver keep one that
arrived in a policy and by honouring markers on every pattern rather than only
a substituted one, and each side fails a different case of the same test.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-14 22:22:06 -05:00
1 parent a55352bf9d
commit 425cd3167d
8 files changed
+1213 -58

No files matched your search

+58
View File
@@ -1270,8 +1270,66 @@ account key carries no identity policies of its own.
- **Action/Resource patterns**: literal matches, wildcards (`*`, `?`), and `NotAction`/`NotResource` blocks.
Action names match without regard to case, resource ARNs match case-sensitively, as on AWS.
- **Conditions**: support for `Condition` blocks with multiple operators.
- **Policy variables**: `${...}` placeholders in a `Resource` pattern or a `Condition` value,
resolved from the request context.
- **Effects**: `Allow` and `Deny`.
#### Policy variables
A `${...}` placeholder in a `Resource` pattern or a `Condition` value is resolved against the
request context before it is matched, so a statement scoped to
`arn:aws:iam::*:user/${aws:username}` grants the caller their own user and nobody else's. That is
how AWS writes its own `IAMUserChangePassword` policy, and 244 of the 1,586
[managed policies](#aws-managed-policies) floci vendors carry at least one variable: of the 1,635
occurrences in them, 1,443 sit in a `Condition` value and 192 in a `Resource`.
Substitution needs `"Version": "2012-10-17"`. Under the older `2008-10-17`, which is also the
default when the element is absent, the user guide says variables "are instead treated as literal
strings in the policy", and floci matches them as written.
The rest of the rules, all from the user guide:
- In a `Resource` or `NotResource` ARN a variable resolves only in the resource portion, the part
after the fifth colon: a variable "can't ... replace parts of the ARN before the fifth colon,
such as the service or the account", and one written there stays literal text and matches
nothing. One vendored managed policy,
`AmazonTimestreamInfluxDBServiceRolePolicy`, writes `arn:*:kms:*:${aws:PrincipalAccount}:key/*`,
in the account field, so that statement grants nothing under enforcement. floci follows the
documented rule rather than the one policy that reads past it.
- In a `Condition` a variable resolves for the string and ARN operators only: `StringEquals`,
`StringNotEquals`, `StringLike`, `StringNotLike`, their `IgnoreCase` forms, and `ArnEquals`,
`ArnLike` and their negated forms. A variable is not supported with `Numeric`, `Date`, `Bool`,
`IpAddress` or `Null`, so there the value is compared as written.
- A variable whose key has no value leaves the whole value effectively null. In `Resource` the
pattern then "will not match any resource", and in `NotResource` that same rule means it
excludes nothing, so the statement covers every resource. In a `Condition`, `StringEquals` and
`StringLike` do not match while the inverted `StringNotEquals` and `StringNotLike` do.
- Key names are case-insensitive and hold no space. The guide allows a space inside a quoted
default and nowhere else, so `${ aws:username }` is not a variable and stays the text it is,
as do the other forms the guide's policy checks call errors: an empty `${}`, a missing closing
brace, and a default without its quotes.
- Only a single-valued key resolves: a multivalued key cannot be used as a variable, having no one
value to stand in, and a default does not rescue it, a default answering a key with no value
rather than one with several.
- `${key, 'default'}` falls back to the quoted default when the key has no value.
- `${*}`, `${?}` and `${$}` stand for a literal `*`, `?` and `$`. The first two are matched as
those characters rather than as wildcards.
- A resolved value is not escaped, so a value carrying a `*` widens the pattern it lands in. That
is AWS's behaviour too: its own policy checks warn that variables "can be evaluated as effective
wildcards".
Variables resolve in every document the evaluator reads: identity policies, resource policies,
session policies, permissions boundaries, SCPs, and the `Condition` of a role trust policy. A
variable can only resolve to a key floci populates, which is the list under
[Condition keys floci populates](#condition-keys-floci-populates).
A role trust policy is the narrower case, because `sts:AssumeRole` is authorized before there is a
session to describe: its context carries `aws:PrincipalArn`, `aws:PrincipalAccount`,
`aws:ResourceAccount`, `aws:RequestedRegion`, `aws:PrincipalIsAWSService`, `sts:RoleSessionName`,
and `sts:ExternalId` when the request passes one. `aws:username`, `aws:userid` and
`aws:PrincipalType` are not among them, so a variable naming one of those resolves to nothing in a
trust policy and the value it sits in matches nothing.
#### Supported Condition Operators:
- `StringEquals`, `StringNotEquals`, `StringEqualsIgnoreCase`, `StringNotEqualsIgnoreCase`
- `StringLike`, `StringNotLike`: case-sensitive glob matching with `*` and `?`.
@@ -21,9 +21,10 @@ import java.util.regex.Pattern;
* <p>Trust policies are principal-centric and carry no {@code Resource} element, so they cannot be
* evaluated by {@link IamPolicyEvaluator} (which is identity/resource oriented). This focused
* evaluator matches each statement's {@code Action} and {@code Principal} against the caller, hands
* its {@code Condition} to {@link IamPolicyEvaluator#conditionMatches} with the request's context,
* and applies AWS precedence: an explicit {@code Deny} wins, otherwise a matching {@code Allow}
* grants.
* its {@code Condition} to {@link IamPolicyEvaluator#conditionMatches} with the request's context
* and the document's own {@code Version}, which is what decides whether a {@code ${...}} in a
* condition value is a policy variable, and applies AWS precedence: an explicit {@code Deny} wins,
* otherwise a matching {@code Allow} grants.
*
* <p>Only AWS principals are modeled (account-root, bare account id, exact principal ARN, and
* {@code "*"}); {@code Service} and {@code Federated} principals never match a SigV4 caller and are
@@ -94,16 +95,18 @@ public class AssumeRolePolicyEvaluator {
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
return TrustDecision.NEUTRAL;
}
JsonNode statements;
JsonNode root;
try {
statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
root = objectMapper.readTree(trustPolicyDocument);
} catch (Exception e) {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return TrustDecision.NEUTRAL;
}
JsonNode statements = root.path("Statement");
if (!isWellFormed(statements)) {
return TrustDecision.NEUTRAL;
}
String version = root.path("Version").asText(null);
Map<String, List<String>> context = new HashMap<>(requestContext);
if (principalArn != null) {
context.put("aws:PrincipalArn", List.of(principalArn));
@@ -111,7 +114,8 @@ public class AssumeRolePolicyEvaluator {
Iterable<JsonNode> statementList = statements.isArray() ? statements : List.of(statements);
TrustDecision decision = TrustDecision.NEUTRAL;
for (JsonNode stmt : statementList) {
TrustDecision match = evaluateStatement(stmt, callerArn, principalArn, callerAccount, context);
TrustDecision match =
evaluateStatement(stmt, callerArn, principalArn, callerAccount, context, version);
if (match == TrustDecision.EXPLICIT_DENY) {
return TrustDecision.EXPLICIT_DENY;
}
@@ -165,16 +169,18 @@ public class AssumeRolePolicyEvaluator {
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
return false;
}
JsonNode statements;
JsonNode root;
try {
statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
root = objectMapper.readTree(trustPolicyDocument);
} catch (Exception e) {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return false;
}
JsonNode statements = root.path("Statement");
if (!isWellFormed(statements)) {
return false;
}
String version = root.path("Version").asText(null);
Map<String, List<String>> context = new HashMap<>();
if (sourceArn != null) {
context.put("aws:SourceArn", List.of(sourceArn));
@@ -185,14 +191,14 @@ public class AssumeRolePolicyEvaluator {
boolean allow = false;
if (statements.isArray()) {
for (JsonNode statement : statements) {
switch (evaluateServiceStatement(statement, servicePrincipal, context)) {
switch (evaluateServiceStatement(statement, servicePrincipal, context, version)) {
case DENY -> { return false; }
case ALLOW -> allow = true;
case NO_MATCH -> { }
}
}
} else if (statements.isObject()) {
return evaluateServiceStatement(statements, servicePrincipal, context) == Match.ALLOW;
return evaluateServiceStatement(statements, servicePrincipal, context, version) == Match.ALLOW;
}
return allow;
}
@@ -244,7 +250,8 @@ public class AssumeRolePolicyEvaluator {
}
private TrustDecision evaluateStatement(JsonNode stmt, String callerArn, String principalArn,
String callerAccount, Map<String, List<String>> context) {
String callerAccount, Map<String, List<String>> context,
String policyVersion) {
if (!actionApplies(stmt)) {
return TrustDecision.NEUTRAL;
}
@@ -252,7 +259,7 @@ public class AssumeRolePolicyEvaluator {
if (principal == PrincipalMatch.NONE) {
return TrustDecision.NEUTRAL;
}
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context)) {
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context, policyVersion)) {
return TrustDecision.NEUTRAL;
}
return switch (effectOf(stmt)) {
@@ -270,11 +277,11 @@ public class AssumeRolePolicyEvaluator {
}
private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal,
Map<String, List<String>> context) {
Map<String, List<String>> context, String policyVersion) {
if (!actionApplies(stmt) || !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
return Match.NO_MATCH;
}
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context)) {
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context, policyVersion)) {
return Match.NO_MATCH;
}
return effectOf(stmt);
@@ -908,8 +908,8 @@ public class IamPolicyEvaluator {
return false;
}
return matchesAction(stmt, action)
&& matchesResource(stmt, resource)
&& matchesConditions(stmt.getConditions(), ctx);
&& matchesResource(stmt, resource, ctx)
&& matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt));
}
private boolean conditionDirectlyMatchesPrincipalArn(Map<String, Map<String, List<String>>> conditions, String principalArn) {
@@ -944,8 +944,8 @@ public class IamPolicyEvaluator {
PrincipalMatch match = principalMatch(stmt, principal);
if (match == PrincipalMatch.NONE
|| !matchesAction(stmt, action)
|| !matchesResource(stmt, resource)
|| !matchesConditions(stmt.getConditions(), ctx)) {
|| !matchesResource(stmt, resource, ctx)
|| !matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt))) {
return PrincipalMatch.NONE;
}
return match;
@@ -1121,8 +1121,13 @@ public class IamPolicyEvaluator {
private boolean matchesStatement(PolicyStatement stmt, String action, String resource,
Map<String, List<String>> ctx) {
return matchesAction(stmt, action)
&& matchesResource(stmt, resource)
&& matchesConditions(stmt.getConditions(), ctx);
&& matchesResource(stmt, resource, ctx)
&& matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt));
}
/** Whether this statement's document declares the version that gives {@code ${...}} meaning. */
private static boolean policyVariables(PolicyStatement stmt) {
return PolicyVariableResolver.enabledFor(stmt.getVersion());
}
/** Action: matches if any Action pattern matches; NotAction: matches if NO pattern matches. */
@@ -1137,12 +1142,37 @@ public class IamPolicyEvaluator {
}
/** Resource: matches if any Resource pattern matches; NotResource: matches if NO pattern matches. */
private boolean matchesResource(PolicyStatement stmt, String resource) {
private boolean matchesResource(PolicyStatement stmt, String resource,
Map<String, List<String>> ctx) {
if (stmt.getResources() != null) {
return matchesAny(stmt.getResources(), resource);
return matchesAnyResource(stmt.getResources(), resource, ctx, policyVariables(stmt));
}
if (stmt.getNotResources() != null) {
return !matchesAny(stmt.getNotResources(), resource);
return !matchesAnyResource(stmt.getNotResources(), resource, ctx, policyVariables(stmt));
}
return false;
}
/**
* Glob over the Resource or NotResource patterns, with each pattern's policy variables
* resolved first. A pattern holding a variable with no value matches nothing, which the user
* guide states for both elements: "the resource that includes a policy variable with no value
* will not match any resource". In NotResource that reads the other way round, since a
* pattern matching no resource excludes none, so the statement covers every resource.
*/
private boolean matchesAnyResource(List<String> patterns, String resource,
Map<String, List<String>> ctx, boolean policyVariables) {
if (!policyVariables) {
return matchesAny(patterns, resource);
}
if (resource == null) {
return false;
}
for (String pattern : patterns) {
String resolved = PolicyVariableResolver.resolveResourcePattern(pattern, ctx).orElse(null);
if (resolved != null && globMatchesHelper(resolved, resource, true)) {
return true;
}
}
return false;
}
@@ -1177,10 +1207,13 @@ public class IamPolicyEvaluator {
* same operator semantics as every other policy this class reads. For policies this class
* does not match statements for itself: trust policies carry no {@code Resource} element, so
* {@link AssumeRolePolicyEvaluator} matches their principal and action and asks here for the
* condition.
* condition. {@code policyVersion} is that document's own {@code Version} element, since a
* {@code ${...}} is only a policy variable under the version that introduced them.
*/
boolean conditionMatches(JsonNode condition, Map<String, List<String>> conditionCtx) {
return matchesConditions(parseConditions(condition), normalizeConditionContext(conditionCtx));
boolean conditionMatches(JsonNode condition, Map<String, List<String>> conditionCtx,
String policyVersion) {
return matchesConditions(parseConditions(condition), normalizeConditionContext(conditionCtx),
PolicyVariableResolver.enabledFor(policyVersion));
}
/**
@@ -1188,12 +1221,12 @@ public class IamPolicyEvaluator {
* Returns true if ALL blocks pass (or there are no conditions).
*/
private boolean matchesConditions(Map<String, Map<String, List<String>>> conditions,
Map<String, List<String>> ctx) {
Map<String, List<String>> ctx, boolean policyVariables) {
if (conditions == null || conditions.isEmpty()) {
return true;
}
for (Map.Entry<String, Map<String, List<String>>> entry : conditions.entrySet()) {
if (!evaluateConditionBlock(entry.getKey(), entry.getValue(), ctx)) {
if (!evaluateConditionBlock(entry.getKey(), entry.getValue(), ctx, policyVariables)) {
return false;
}
}
@@ -1214,6 +1247,15 @@ public class IamPolicyEvaluator {
"DateLessThan", "DateLessThanEquals", "DateGreaterThan", "DateGreaterThanEquals",
"IpAddress", "NotIpAddress");
/**
* The operators a policy variable may be used with: "Conditions support variables when you
* use string operators or ARN operators", and not Numeric, Date, Boolean, Binary, IP Address
* or Null. With one of those, a {@code ${...}} is the text it is written as.
*/
private static final Set<String> VARIABLE_CONDITION_OPERATORS = Set.of(
"StringEquals", "StringNotEquals", "StringEqualsIgnoreCase", "StringNotEqualsIgnoreCase",
"StringLike", "StringNotLike", "ArnEquals", "ArnNotEquals", "ArnLike", "ArnNotLike");
private record ParsedOperator(SetQuantifier quantifier, String baseOp, boolean ifExists) {}
/**
@@ -1259,23 +1301,42 @@ public class IamPolicyEvaluator {
* multi-valued negated condition and the deny-list idiom for keys such as
* {@code dynamodb:Attributes} ({@code ForAllValues:StringNotEquals}).
*/
private boolean matchesCondValues(String baseOp, String ctxValue, List<String> condValues) {
private boolean matchesCondValues(String baseOp, String ctxValue, List<String> condValues,
Map<String, List<String>> ctx, boolean policyVariables) {
if (isNegatedOperator(baseOp)) {
for (String condValue : condValues) {
if (!evaluateSingleCondition(baseOp, ctxValue, condValue)) {
if (!matchesCondValue(baseOp, ctxValue, condValue, ctx, policyVariables)) {
return false;
}
}
return true;
}
for (String condValue : condValues) {
if (evaluateSingleCondition(baseOp, ctxValue, condValue)) {
if (matchesCondValue(baseOp, ctxValue, condValue, ctx, policyVariables)) {
return true;
}
}
return false;
}
/**
* One policy value against one request value, with the policy value's variables resolved
* first. A value holding a variable with nothing to resolve to is effectively null: there is
* "no equal or like value", so a positive operator does not match, while an inverted one does,
* the request value being neither equal to nor like a null.
*/
private boolean matchesCondValue(String baseOp, String ctxValue, String condValue,
Map<String, List<String>> ctx, boolean policyVariables) {
String resolved = condValue;
if (policyVariables) {
resolved = PolicyVariableResolver.resolveValue(condValue, ctx).orElse(null);
if (resolved == null) {
return isNegatedOperator(baseOp);
}
}
return evaluateSingleCondition(baseOp, ctxValue, resolved, policyVariables);
}
private static boolean isNegatedOperator(String baseOp) {
return switch (baseOp) {
case "StringNotEquals", "StringNotEqualsIgnoreCase", "StringNotLike",
@@ -1287,13 +1348,15 @@ public class IamPolicyEvaluator {
private boolean evaluateConditionBlock(String operator,
Map<String, List<String>> keyValueMap,
Map<String, List<String>> ctx) {
Map<String, List<String>> ctx,
boolean policyVariables) {
if (!isSupportedConditionOperator(operator)) {
return false;
}
ParsedOperator parsed = parseOperator(operator);
String baseOp = parsed.baseOp();
boolean ifExists = parsed.ifExists();
boolean substitute = policyVariables && VARIABLE_CONDITION_OPERATORS.contains(baseOp);
for (Map.Entry<String, List<String>> entry : keyValueMap.entrySet()) {
String condKey = entry.getKey().toLowerCase(java.util.Locale.ROOT);
@@ -1341,14 +1404,14 @@ public class IamPolicyEvaluator {
// matches vacuously, which is why real policies pair ForAllValues with a
// Null:{key:"false"} guard.
case FOR_ALL_VALUES -> ctxValues.stream()
.allMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues));
.allMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues, ctx, substitute));
// At least one request value must match. An empty set never matches.
case FOR_ANY_VALUE -> ctxValues.stream()
.anyMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues));
.anyMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues, ctx, substitute));
// A bare operator against a multi-valued key is a policy authoring error in
// AWS; mirror that by comparing only the first value.
case NONE -> !ctxValues.isEmpty()
&& matchesCondValues(baseOp, ctxValues.getFirst(), condValues);
&& matchesCondValues(baseOp, ctxValues.getFirst(), condValues, ctx, substitute);
};
if (!keyMatch) {
return false;
@@ -1358,16 +1421,25 @@ public class IamPolicyEvaluator {
}
private boolean evaluateSingleCondition(String operator, String ctxValue, String condValue) {
/**
* One comparison. {@code escapes} says the policy value came back from substitution, which is
* the only way a {@link PolicyVariableResolver#ESCAPE} marker can be in it: the glob operators
* then read the marker themselves, while the operators comparing whole strings collapse it
* first. Without substitution no marker is honoured, so one written into a document is the
* character it is and cannot narrow the comparison.
*/
private boolean evaluateSingleCondition(String operator, String ctxValue, String condValue,
boolean escapes) {
String plain = escapes ? PolicyVariableResolver.literal(condValue) : condValue;
return switch (operator) {
case "StringEquals" -> ctxValue.equals(condValue);
case "StringNotEquals" -> !ctxValue.equals(condValue);
case "StringEqualsIgnoreCase" -> ctxValue.equalsIgnoreCase(condValue);
case "StringNotEqualsIgnoreCase" -> !ctxValue.equalsIgnoreCase(condValue);
case "StringLike" -> caseSensitiveGlobMatches(condValue, ctxValue);
case "StringNotLike" -> !caseSensitiveGlobMatches(condValue, ctxValue);
case "ArnEquals", "ArnLike" -> matchesArnCondition(condValue, ctxValue);
case "ArnNotEquals", "ArnNotLike"-> !matchesArnCondition(condValue, ctxValue);
case "StringEquals" -> ctxValue.equals(plain);
case "StringNotEquals" -> !ctxValue.equals(plain);
case "StringEqualsIgnoreCase" -> ctxValue.equalsIgnoreCase(plain);
case "StringNotEqualsIgnoreCase" -> !ctxValue.equalsIgnoreCase(plain);
case "StringLike" -> globMatches(condValue, ctxValue, true, escapes);
case "StringNotLike" -> !globMatches(condValue, ctxValue, true, escapes);
case "ArnEquals", "ArnLike" -> matchesArnCondition(condValue, ctxValue, escapes);
case "ArnNotEquals", "ArnNotLike"-> !matchesArnCondition(condValue, ctxValue, escapes);
case "Bool" -> Boolean.parseBoolean(condValue) == Boolean.parseBoolean(ctxValue);
case "NumericEquals" -> compareNumeric(ctxValue, condValue, order -> order == 0);
case "NumericNotEquals" -> compareNumeric(ctxValue, condValue, order -> order != 0);
@@ -1453,17 +1525,35 @@ public class IamPolicyEvaluator {
* Case-insensitive glob matching supporting {@code *} (any sequence) and {@code ?} (any char).
*/
public static boolean globMatches(String pattern, String value) {
if (pattern == null || value == null) {
return false;
}
return globMatchesHelper(pattern.toLowerCase(), value.toLowerCase());
return globMatches(pattern, value, false, false);
}
public static boolean caseSensitiveGlobMatches(String pattern, String value) {
return pattern != null && value != null && globMatchesHelper(pattern, value);
return globMatches(pattern, value, true, false);
}
/**
* One glob, with {@code caseSensitive} choosing how the characters compare and
* {@code escapes} saying whether a {@link PolicyVariableResolver#ESCAPE} marker in the pattern
* protects the character behind it. Only a pattern that came back from substitution carries a
* marker, so every other caller leaves escapes off and a marker written into a policy is just
* a character.
*/
private static boolean globMatches(String pattern, String value, boolean caseSensitive,
boolean escapes) {
if (pattern == null || value == null) {
return false;
}
return caseSensitive
? globMatchesHelper(pattern, value, escapes)
: globMatchesHelper(pattern.toLowerCase(), value.toLowerCase(), escapes);
}
public static boolean matchesArnCondition(String pattern, String value) {
return matchesArnCondition(pattern, value, false);
}
private static boolean matchesArnCondition(String pattern, String value, boolean escapes) {
if (pattern == null || value == null) {
return false;
}
@@ -1474,21 +1564,43 @@ public class IamPolicyEvaluator {
return false;
}
for (int i = 0; i < patternComponents.length; i++) {
if (!caseSensitiveGlobMatches(patternComponents[i], valueComponents[i])) {
if (!globMatches(patternComponents[i], valueComponents[i], true, escapes)) {
return false;
}
}
return true;
}
/**
* Matches {@code pattern} against {@code value}, where {@code *} is any sequence and
* {@code ?} any single character. A character behind {@link PolicyVariableResolver#ESCAPE}
* matches only itself, which is how {@code ${*}} and {@code ${?}} keep standing for an
* asterisk and a question mark once they are substituted.
*/
private static boolean globMatchesHelper(String pattern, String value) {
return globMatchesHelper(pattern, value, false);
}
private static boolean globMatchesHelper(String pattern, String value, boolean escapes) {
int patternIndex = 0;
int valueIndex = 0;
int starIndex = -1;
int starValueIndex = -1;
while (valueIndex < value.length()) {
if (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
if (escapes && patternIndex + 1 < pattern.length()
&& pattern.charAt(patternIndex) == PolicyVariableResolver.ESCAPE) {
if (pattern.charAt(patternIndex + 1) == value.charAt(valueIndex)) {
patternIndex += 2;
valueIndex++;
continue;
}
if (starIndex < 0) {
return false;
}
patternIndex = starIndex + 1;
valueIndex = ++starValueIndex;
} else if (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
starIndex = patternIndex++;
starValueIndex = valueIndex;
} else if (patternIndex < pattern.length()
@@ -1569,18 +1681,19 @@ public class IamPolicyEvaluator {
private List<PolicyStatement> parseStatements(String document) throws Exception {
JsonNode root = objectMapper.readTree(document);
JsonNode stmtNode = root.path("Statement");
String version = root.path("Version").asText(null);
List<PolicyStatement> result = new ArrayList<>();
if (stmtNode.isArray()) {
for (JsonNode s : stmtNode) {
result.add(parseStatement(s));
result.add(parseStatement(s, version));
}
} else if (stmtNode.isObject()) {
result.add(parseStatement(stmtNode));
result.add(parseStatement(stmtNode, version));
}
return result;
}
private PolicyStatement parseStatement(JsonNode stmt) {
private PolicyStatement parseStatement(JsonNode stmt, String version) {
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"));
@@ -1599,7 +1712,8 @@ public class IamPolicyEvaluator {
notActions.isEmpty() ? null : notActions,
resources.isEmpty() ? null : resources,
notResources.isEmpty()? null : notResources,
conditions);
conditions,
version);
}
private Map<String, List<String>> parsePrincipals(JsonNode node) {
@@ -0,0 +1,196 @@
package io.github.hectorvent.floci.services.iam;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Substitutes IAM policy variables, the {@code ${...}} placeholders a policy writes where it
* cannot know a value until the request arrives.
*
* <p>A variable names a condition context key, so {@code ${aws:username}} in a Resource pattern
* resolves to the name of the user making the request. Key names are case-insensitive, matching
* the user guide, and only a single-valued key resolves: the guide says a multivalued key cannot
* be used as a variable, and there is no one value to put in its place.
*
* <p>An empty {@link Optional} means the text held a variable with nothing to resolve to. The
* caller decides what that means, because AWS gives the two elements different answers: a
* Resource pattern "will not match any resource", while a Condition value is effectively null,
* which a positive operator does not match and an inverted one does.
*
* <p>Three variables name a character rather than a key: {@code ${*}}, {@code ${?}} and
* {@code ${$}} stand for a literal asterisk, question mark and dollar sign. The first two have to
* survive glob matching as themselves, so they resolve to the character behind {@link #ESCAPE},
* which {@code IamPolicyEvaluator}'s glob reads as "the next character matches literally".
* Operators that compare whole strings instead of globbing take {@link #literal} first.
*
* <p>A substituted value is not escaped, so a value carrying a {@code *} widens the pattern it
* lands in. That is AWS's own behaviour: its policy checks warn that "policy variables can be
* evaluated as effective wildcards".
*
* <p>Reporting the key names a document references, which is what
* {@code GetContextKeysForCustomPolicy} answers, is a different question and keeps its own pattern
* in {@code IamPolicyEvaluator}: it has to name the key even where the variable around it is
* written in a form that resolves to nothing here, such as a default value missing its quotes.
*/
final class PolicyVariableResolver {
/**
* Marks the character after it as a literal, so a substituted asterisk or question mark is
* not read as a wildcard. Only text this class has substituted carries a marker: it strips
* any that arrived in the policy, and the matcher honours markers only on a pattern that came
* back from substitution. A document can hold one as the JSON escape {@code \u0000}, and left
* to act as a marker it would turn a wildcard of the document's own into a literal character
* and narrow the statement it sits in. AWS refuses such a document outright, its
* {@code policyDocumentType} admitting tab, newline, carriage return and the printable range
* from the space character upward and nothing below it, but that is AWS's pattern to enforce
* and not a property of what reaches this class.
*/
static final char ESCAPE = '\u0000';
/**
* A variable: {@code ${key}}, or {@code ${key, 'default'}} where the default runs to its
* closing quote rather than to the first brace, so one carrying a brace of its own survives.
* The key is one or more characters and holds no whitespace, the guide saying "you cannot
* include a space in the variable name" while "you can include a space when you specify a
* default variable". Anything else written between {@code ${} and {@code }} matches nothing
* here and stays the text it is, which is what an empty {@code ${}}, a spaced name, an
* unquoted default and a missing brace all come to.
*/
private static final Pattern VARIABLE =
Pattern.compile("\\$\\{([^\\s,}]+)(?:,\\s*'([^']*)'\\s*)?}");
/** The policy language version that introduced variables. */
private static final String VARIABLES_VERSION = "2012-10-17";
private static final int ARN_RESOURCE_COLON = 5;
private PolicyVariableResolver() {
}
/**
* Whether a document declaring this {@code Version} has policy variables at all. They arrived
* with 2012-10-17; under the older 2008-10-17, which is also the default when the element is
* absent, the user guide says they "are instead treated as literal strings in the policy".
* The policy-check reference reads "2012-10-17 or later", and equality covers that: the guide
* lists exactly two values IAM supports for the element, and no later one exists to admit.
*/
static boolean enabledFor(String policyVersion) {
return VARIABLES_VERSION.equals(policyVersion);
}
/**
* Substitutes every variable in a Condition value. Empty when one of them has no value, which
* leaves the whole value effectively null rather than partly resolved.
*/
static Optional<String> resolveValue(String text, Map<String, List<String>> context) {
String plain = withoutMarker(text);
if (plain == null || !plain.contains("${")) {
return Optional.ofNullable(plain);
}
Matcher matcher = VARIABLE.matcher(plain);
StringBuilder resolved = new StringBuilder(plain.length());
int copiedTo = 0;
while (matcher.find()) {
String substitution = substitutionFor(matcher.group(1), matcher.group(2), context);
if (substitution == null) {
return Optional.empty();
}
resolved.append(plain, copiedTo, matcher.start()).append(substitution);
copiedTo = matcher.end();
}
resolved.append(plain, copiedTo, plain.length());
return Optional.of(resolved.toString());
}
/**
* Substitutes variables in the resource portion of an ARN pattern, which is what follows the
* fifth colon. The user guide is explicit that a variable cannot replace any part before it,
* such as the service or the account, so anything written there stays the literal text it is
* and matches nothing. A pattern that is not an ARN, {@code *} among them, has no resource
* portion and is returned unchanged.
*/
static Optional<String> resolveResourcePattern(String pattern, Map<String, List<String>> context) {
if (pattern == null) {
return Optional.empty();
}
String plain = withoutMarker(pattern);
int resourceStart = resourcePortionStart(plain);
if (resourceStart < 0) {
return Optional.of(plain);
}
return resolveValue(plain.substring(resourceStart), context)
.map(resource -> plain.substring(0, resourceStart) + resource);
}
/**
* The text with every {@link #ESCAPE} character removed, applied to whatever arrives from a
* policy. One written into a document is not a marker but a forgery of one, and dropping it
* leaves the document's own wildcards to glob as they are written.
*/
private static String withoutMarker(String text) {
return text == null || text.indexOf(ESCAPE) < 0
? text
: text.replace(String.valueOf(ESCAPE), "");
}
/** The text with every {@link #ESCAPE} marker dropped, leaving the character it protected. */
static String literal(String text) {
if (text == null || text.indexOf(ESCAPE) < 0) {
return text;
}
StringBuilder plain = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++) {
char current = text.charAt(i);
if (current != ESCAPE) {
plain.append(current);
} else if (i + 1 < text.length()) {
plain.append(text.charAt(++i));
}
}
return plain.toString();
}
/** The value to put in a variable's place, or null when it has none. */
private static String substitutionFor(String key, String defaultValue,
Map<String, List<String>> context) {
if ("*".equals(key)) {
return ESCAPE + "*";
}
if ("?".equals(key)) {
return ESCAPE + "?";
}
if ("$".equals(key)) {
return "$";
}
List<String> values = context.get(key.toLowerCase(Locale.ROOT));
if (values == null || values.isEmpty()) {
return defaultValue;
}
if (values.size() > 1) {
// "You can't use a multivalued condition key as a variable", and the guide gives a
// default no part in that rule: it stands in for a key with no value, not for one
// holding several. So the variable resolves to nothing and the value it sits in
// matches nothing, rather than quietly widening to the default.
return null;
}
return values.getFirst();
}
/** The index just past the fifth colon, or -1 when the pattern has fewer than five. */
private static int resourcePortionStart(String pattern) {
int colons = 0;
for (int i = 0; i < pattern.length(); i++) {
if (pattern.charAt(i) == ':') {
colons++;
if (colons == ARN_RESOURCE_COLON) {
return i + 1;
}
}
}
return -1;
}
}
@@ -19,6 +19,11 @@ public class PolicyStatement {
private final List<String> notResources;// NotResource patterns; null when resources is set
// Condition: outer key = operator (e.g. "StringEquals"), inner key = context key, value = list of values
private final Map<String, Map<String, List<String>>> conditions;
// The document's Version element, which decides whether this statement's ${...} are policy
// variables or literal text. It belongs to the document rather than the statement, but
// 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;
public PolicyStatement(String effect,
Map<String, List<String>> principals,
@@ -27,7 +32,8 @@ public class PolicyStatement {
List<String> notActions,
List<String> resources,
List<String> notResources,
Map<String, Map<String, List<String>>> conditions) {
Map<String, Map<String, List<String>>> conditions,
String version) {
this.effect = effect;
this.principals = principals;
this.notPrincipals = notPrincipals;
@@ -36,20 +42,22 @@ public class PolicyStatement {
this.resources = resources;
this.notResources = notResources;
this.conditions = conditions;
this.version = version;
}
/** Without a version, {@code ${...}} stays literal text, as it does under 2008-10-17. */
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);
this(effect, null, null, actions, notActions, resources, notResources, conditions, null);
}
/** Convenience constructor for simple allow/deny without conditions or Not* fields. */
public PolicyStatement(String effect, List<String> actions, List<String> resources) {
this(effect, null, null, actions, null, resources, null, null);
this(effect, null, null, actions, null, resources, null, null, null);
}
public String getEffect() { return effect; }
@@ -60,6 +68,7 @@ public class PolicyStatement {
public List<String> getResources() { return resources; }
public List<String> getNotResources() { return notResources; }
public Map<String, Map<String, List<String>>> getConditions() { return conditions; }
public String getVersion() { return version; }
public boolean isDeny() { return "Deny".equalsIgnoreCase(effect); }
public boolean isAllow() { return "Allow".equalsIgnoreCase(effect); }
@@ -390,6 +390,42 @@ class AssumeRolePolicyEvaluatorTest {
"arn:aws:appsync:us-east-1:111111111111:apis/example", "111111111111"));
}
/**
* A trust policy is a resource policy, and those take policy variables too. The caller's own
* account is one of the keys the request carries, so a session name can be held to it.
*/
@Test
void aTrustConditionResolvesAPolicyVariable() {
String doc = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole",
"Condition":{"StringLike":{"sts:RoleSessionName":"${aws:PrincipalAccount}-*"}}}]}
""";
assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
sessionNamed(CALLER_ACCOUNT + "-build")));
assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
sessionNamed("222222222222-build")));
}
/** The same condition under the version that predates variables compares the text itself. */
@Test
void aTrustConditionVariableStaysLiteralWithoutTheVersion() {
String doc = """
{"Statement":[
{"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole",
"Condition":{"StringLike":{"sts:RoleSessionName":"${aws:PrincipalAccount}-*"}}}]}
""";
assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
sessionNamed(CALLER_ACCOUNT + "-build")));
assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
sessionNamed("${aws:PrincipalAccount}-build")));
}
private static Map<String, List<String>> sessionNamed(String sessionName) {
return Map.of("aws:PrincipalAccount", List.of(CALLER_ACCOUNT),
"sts:RoleSessionName", List.of(sessionName));
}
@Test
void aGrantNamingTheCallerIsToldApartFromAGrantToItsAccount() {
assertEquals(TrustDecision.ALLOW, evaluator.decide(trust("{\"AWS\":\"" + CALLER_ARN + "\"}"),
@@ -0,0 +1,236 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
/**
* A policy variable resolved on the real request path, rather than against a context handed
* straight to the evaluator. {@code aws:PrincipalAccount} is one of the keys the enforcement
* filter already builds for every request, and a bucket named after the account that owns it is
* what AWS's own examples scope this way.
*
* <p>Runs in an account of its own: the emulator is shared, and both buckets here are named after
* an account id, which is the whole point of the grant being tested.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class PolicyVariableEnforcementIntegrationTest {
private static final String ACCOUNT_ID = "000000000777";
private static final String OTHER_ACCOUNT_ID = "999988887777";
private static final String PASSWORD = "Sup3r$ecret!";
private static final String NEW_PASSWORD = "An0ther$ecret!";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@TestHTTPResource("/")
URI baseUri;
/** Allows listing the one bucket whose name ends in the caller's own account id. */
private static String allowingOwnAccountBucket(String version, String prefix) {
return """
{"Version":"%s","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::%s-${aws:PrincipalAccount}"}]}"""
.formatted(version, prefix);
}
@Test
void aResourceVariableBindsTheGrantToTheCallersOwnAccount() {
String prefix = "policy-vars-" + suffix();
String own = createBucket(prefix + "-" + ACCOUNT_ID);
String other = createBucket(prefix + "-" + OTHER_ACCOUNT_ID);
String accessKeyId = userWith(allowingOwnAccountBucket("2012-10-17", prefix));
list(accessKeyId, own).statusCode(200);
list(accessKeyId, other).statusCode(403).body(containsString("AccessDenied"));
}
/**
* The same policy under the version that predates variables, where {@code ${aws:...}} is the
* text it is written as and names no bucket at all.
*/
@Test
void theSameGrantUnderTheOlderVersionNamesNoBucket() {
String prefix = "literal-vars-" + suffix();
String own = createBucket(prefix + "-" + ACCOUNT_ID);
String literal = userWith(allowingOwnAccountBucket("2008-10-17", prefix));
list(literal, own).statusCode(403).body(containsString("AccessDenied"));
// The bucket is reachable with the account spelled out, so it is the variable that is
// inert under the older version and not the grant or the bucket.
String spelledOut = userWith("""
{"Version":"2008-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::%s"}]}"""
.formatted(own));
list(spelledOut, own).statusCode(200);
}
/**
* The policy the change exists for: AWS's own {@code IAMUserChangePassword}, attached as the
* managed policy floci vendors rather than retyped, so a drift in what is vendored fails here
* too. It scopes {@code iam:ChangePassword} to {@code arn:aws:iam::*:user/${aws:username}} and
* to {@code arn:aws:iam::*:user/*}{@code /${aws:username}}, the second for a user under a
* path, so both forms are called.
*/
@Test
void theVendoredChangePasswordPolicyBindsToTheCallersOwnUser() {
Caller flat = consoleUser(null);
attachChangePassword(flat.userName());
changePassword(flat.accessKeyId(), PASSWORD, NEW_PASSWORD).statusCode(200);
Caller underAPath = consoleUser("/eng/");
attachChangePassword(underAPath.userName());
changePassword(underAPath.accessKeyId(), PASSWORD, NEW_PASSWORD).statusCode(200);
// Without the policy the same call is refused, so it is the grant that resolves the
// variable and not enforcement letting the operation through.
Caller ungranted = consoleUser(null);
changePassword(ungranted.accessKeyId(), PASSWORD, NEW_PASSWORD)
.statusCode(403).body(containsString("AccessDenied"));
}
/**
* A permissions boundary resolves variables as an identity policy does, which `iam.md` claims
* for every document the evaluator reads. The user may list any bucket; the boundary narrows
* that to the one named after its own account.
*/
@Test
void aPermissionsBoundaryVariableNarrowsTheGrant() {
String prefix = "pv-boundary-" + suffix();
String own = createBucket(prefix + "-" + ACCOUNT_ID);
String other = createBucket(prefix + "-" + OTHER_ACCOUNT_ID);
String userName = "pv-bounded-" + suffix();
String accessKeyId = EnforcementFixtures.createUser(cleanup, port(),
EnforcementFixtures.auth(ACCOUNT_ID, "iam"), userName).accessKeyId();
iam("PutUserPolicy", Map.of("UserName", userName, "PolicyName", "wide", "PolicyDocument", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}]}"""))
.statusCode(200);
String boundaryArn = iam("CreatePolicy", Map.of("PolicyName", "pv-boundary-" + suffix(),
"PolicyDocument", allowingOwnAccountBucket("2012-10-17", prefix)))
.statusCode(200)
.extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
cleanup.register(() -> EnforcementFixtures.removePolicy(port(),
EnforcementFixtures.auth(ACCOUNT_ID, "iam"), boundaryArn));
iam("PutUserPermissionsBoundary",
Map.of("UserName", userName, "PermissionsBoundary", boundaryArn)).statusCode(200);
cleanup.register(() -> iam("DeleteUserPermissionsBoundary",
Map.of("UserName", userName)).statusCode(200));
list(accessKeyId, own).statusCode(200);
list(accessKeyId, other).statusCode(403).body(containsString("AccessDenied"));
}
/** A user name with the access key that signs for it. */
private record Caller(String userName, String accessKeyId) {}
/** An IAM user holding a console password, under {@code path} when one is given. */
private Caller consoleUser(String path) {
String userName = "pv-cp-" + suffix();
String auth = EnforcementFixtures.auth(ACCOUNT_ID, "iam");
cleanup.register(() -> EnforcementFixtures.removeUser(port(), auth, userName));
iam("CreateUser", path == null
? Map.of("UserName", userName)
: Map.of("UserName", userName, "Path", path)).statusCode(200);
iam("CreateLoginProfile", Map.of("UserName", userName, "Password", PASSWORD))
.statusCode(200);
cleanup.register(() -> iam("DeleteLoginProfile", Map.of("UserName", userName))
.statusCode(200));
return new Caller(userName, iam("CreateAccessKey", Map.of("UserName", userName))
.statusCode(200)
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey"
+ ".AccessKeyId"));
}
private void attachChangePassword(String userName) {
iam("AttachUserPolicy", Map.of("UserName", userName,
"PolicyArn", "arn:aws:iam::aws:policy/IAMUserChangePassword")).statusCode(200);
}
private static ValidatableResponse changePassword(String accessKeyId, String oldPassword,
String newPassword) {
return given()
.header("Authorization", EnforcementFixtures.auth(accessKeyId, "iam"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ChangePassword")
.formParam("Version", "2010-05-08")
.formParam("OldPassword", oldPassword)
.formParam("NewPassword", newPassword)
.when()
.post("/")
.then();
}
private String createBucket(String bucket) {
cleanup.register(() -> EnforcementFixtures.removeBucket(port(), s3Auth(ACCOUNT_ID), bucket));
given()
.header("Authorization", s3Auth(ACCOUNT_ID))
.when()
.put("/" + bucket)
.then()
.statusCode(200);
return bucket;
}
/** An IAM user in {@link #ACCOUNT_ID} carrying {@code policy} inline. */
private String userWith(String policy) {
String user = "policy-vars-" + suffix();
String accessKeyId = EnforcementFixtures.createUser(cleanup, port(),
EnforcementFixtures.auth(ACCOUNT_ID, "iam"), user).accessKeyId();
iam("PutUserPolicy", Map.of("UserName", user, "PolicyName", "p", "PolicyDocument", policy))
.statusCode(200);
return accessKeyId;
}
private static ValidatableResponse list(String accessKeyId, String bucket) {
return given()
.header("Authorization", s3Auth(accessKeyId))
.queryParam("list-type", "2")
.when()
.get("/" + bucket)
.then();
}
private static ValidatableResponse iam(String action, Map<String, String> params) {
RequestSpecification spec = given()
.header("Authorization", EnforcementFixtures.auth(ACCOUNT_ID, "iam"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-05-08");
params.forEach(spec::formParam);
return spec.when().post("/").then();
}
private static String s3Auth(String accessKeyId) {
return EnforcementFixtures.auth(accessKeyId, "s3");
}
private int port() {
return baseUri.getPort();
}
private static String suffix() {
return UUID.randomUUID().toString().substring(0, 8);
}
}
@@ -0,0 +1,499 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Policy variables: the {@code ${...}} placeholders a policy writes where it cannot know a value
* until the request arrives. The evaluator resolved none of them before, so a statement scoped to
* {@code user/${aws:username}} matched no user at all, which is how AWS writes its own
* {@code IAMUserChangePassword} policy and how a great many of the managed policies Floci vendors
* scope themselves to the caller's account.
*
* <p>Both directions are checked for every rule, because the half that matters is often the Deny:
* a pattern that matches nothing silently drops a refusal AWS honours.
*/
class PolicyVariableSubstitutionTest {
private static final String OWN_USER = "arn:aws:iam::111122223333:user/Alice";
private static final String OTHER_USER = "arn:aws:iam::111122223333:user/Bob";
private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
private static String allowingUserResource(String version, String resource) {
return """
{"Version":"%s","Statement":[
{"Effect":"Allow","Action":"iam:ChangePassword","Resource":"%s"}]}"""
.formatted(version, resource);
}
@Test
void aResourceVariableResolvesToTheCallersOwnUser() {
String policy = allowingUserResource("2012-10-17", "arn:aws:iam::*:user/${aws:username}");
assertEquals(Decision.ALLOW, decide(policy, OWN_USER, Map.of("aws:username", List.of("Alice"))));
assertEquals(Decision.DENY, decide(policy, OTHER_USER, Map.of("aws:username", List.of("Alice"))));
}
/**
* The version gate, which is easy to miss and changes everything: "If you don't include the
* Version element and set it to an appropriate version date, variables like ${aws:username}
* are treated as literal strings in the policy." 2008-10-17 is the only other version IAM
* accepts, and is the default when the element is absent.
*/
@Test
void aVariableStaysLiteralTextWithoutTheVersionThatIntroducedThem() {
Map<String, List<String>> context = Map.of("aws:username", List.of("Alice"));
String resource = "arn:aws:iam::*:user/${aws:username}";
assertEquals(Decision.DENY, decide(allowingUserResource("2008-10-17", resource), OWN_USER, context));
assertEquals(Decision.DENY, decide("""
{"Statement":[
{"Effect":"Allow","Action":"iam:ChangePassword","Resource":"%s"}]}"""
.formatted(resource), OWN_USER, context));
// The same document with the name spelled out is allowed either way, so it is the
// variable that is inert under the older version and not the statement.
assertEquals(Decision.ALLOW, decide(
allowingUserResource("2008-10-17", OWN_USER), OWN_USER, context));
}
/** A Deny scoped by a variable has to bind, or the policy refuses nothing. */
@Test
void aDenyScopedByAResourceVariableRefusesTheCallersOwnUser() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:*","Resource":"*"},
{"Effect":"Deny","Action":"iam:ChangePassword",
"Resource":"arn:aws:iam::*:user/${aws:username}"}]}""";
Map<String, List<String>> context = Map.of("aws:username", List.of("Alice"));
assertEquals(Decision.DENY, decide(policy, OWN_USER, context));
assertEquals(Decision.ALLOW, decide(policy, OTHER_USER, context));
}
/**
* "If a variable that has no value in the authorization context is used as part of the
* Resource or NotResource element of a policy, the resource that includes a policy variable
* with no value will not match any resource."
*/
@Test
void aResourceVariableWithNoValueMatchesNoResource() {
String policy = allowingUserResource("2012-10-17", "arn:aws:iam::*:user/${aws:username}");
assertEquals(Decision.DENY, decide(policy, OWN_USER, Map.of()));
assertEquals(Decision.DENY, decide(policy, OWN_USER, Map.of("aws:username", List.of())));
}
/**
* The discriminating half of that rule: a variable with no value is not an empty string. Beside
* a wildcard an empty one would collapse the pattern to {@code reports/*} and grant the whole
* prefix, where AWS matches no resource at all.
*/
@Test
void aResourceVariableWithNoValueMatchesNothingEvenBesideAWildcard() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/${aws:PrincipalTag/team}*"}]}""";
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports/blue/q3.csv", Map.of()));
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports/blue/q3.csv",
Map.of("aws:principaltag/team", List.of("blue"))));
}
/**
* The same sentence covers NotResource, where it reads the other way round: the pattern
* excludes no resource, so the statement covers every one of them.
*/
@Test
void aNotResourceVariableWithNoValueExcludesNothing() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"iam:ChangePassword",
"NotResource":"arn:aws:iam::*:user/${aws:username}"}]}""";
assertEquals(Decision.ALLOW, decide(policy, OWN_USER, Map.of()));
// With a value it excludes the one user it names, and nobody else.
assertEquals(Decision.DENY, decide(policy, OWN_USER, Map.of("aws:username", List.of("Alice"))));
assertEquals(Decision.ALLOW, decide(policy, OTHER_USER, Map.of("aws:username", List.of("Alice"))));
}
/** The same, in a NotResource, where an empty value would exclude the whole prefix instead. */
@Test
void aNotResourceVariableWithNoValueExcludesNothingEvenBesideAWildcard() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"NotResource":"arn:aws:s3:::reports/${aws:PrincipalTag/team}*"}]}""";
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports/blue/q3.csv", Map.of()));
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports/blue/q3.csv",
Map.of("aws:principaltag/team", List.of("blue"))));
}
/**
* "You can use a policy variable in the Resource element, but only in the resource portion of
* the ARN. This portion of the ARN appears after the fifth colon." An account written as a
* variable is therefore the literal text, and matches no account.
*/
@Test
void aVariableBeforeTheFifthColonIsNotSubstituted() {
Map<String, List<String>> context = Map.of("aws:principalaccount", List.of("111122223333"),
"aws:username", List.of("Alice"));
assertEquals(Decision.DENY, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::${aws:PrincipalAccount}:user/Alice"), OWN_USER, context));
// The resource portion of the same ARN still resolves, so the pattern is not refused whole.
assertEquals(Decision.ALLOW, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::111122223333:user/${aws:username}"), OWN_USER, context));
}
/** "Key names are case-insensitive", and the request context is keyed in lower case. */
@Test
void variableKeyNamesAreCaseInsensitive() {
assertEquals(Decision.ALLOW, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${AWS:UserName}"), OWN_USER,
Map.of("aws:username", List.of("Alice"))));
}
/** "You can't use a multivalued condition key as a variable": there is no one value to use. */
@Test
void aMultiValuedKeyDoesNotResolve() {
assertEquals(Decision.DENY, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${aws:username}"), OWN_USER,
Map.of("aws:username", List.of("Alice", "Bob"))));
// Nor does a default rescue it: the guide gives a default the key with no value, not the
// one holding several, so the pattern resolves to nothing rather than widening.
assertEquals(Decision.DENY, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${aws:username, 'Alice'}"), OWN_USER,
Map.of("aws:username", List.of("Alice", "Bob"))));
}
/** A tag variable, which is the form AWS's own examples use most. */
@Test
void aPrincipalTagVariableResolvesInBothElements() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/${aws:PrincipalTag/team}/*"}]}""";
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports/yellow/q3.csv",
Map.of("aws:principaltag/team", List.of("yellow"))));
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports/blue/q3.csv",
Map.of("aws:principaltag/team", List.of("yellow"))));
}
/**
* "To add a default value to a variable, surround the default value with single quotes (' '),
* and separate the variable text and the default value with a comma and space (, )."
*/
@Test
void aDefaultValueStandsInWhenTheKeyHasNone() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports-${aws:PrincipalTag/team, 'company-wide'}/*"}]}""";
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports-company-wide/joining.txt",
Map.of()));
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports-company-wide/joining.txt",
Map.of("aws:principaltag/team", List.of("yellow"))));
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports-yellow/q3.csv",
Map.of("aws:principaltag/team", List.of("yellow"))));
}
/**
* A default value runs to its closing quote, so one carrying a brace stays whole. Without the
* quotes the guide requires there is no default to read, and the variable keeps the text it
* is written as.
*/
@Test
void aDefaultValueIsReadToItsClosingQuote() {
String braced = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/${aws:PrincipalTag/team, 'a}b'}"}]}""";
assertEquals(Decision.ALLOW, decideS3(braced, "arn:aws:s3:::reports/a}b", Map.of()));
String unquoted = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/${aws:PrincipalTag/team, fallback}"}]}""";
assertEquals(Decision.DENY, decideS3(unquoted, "arn:aws:s3:::reports/fallback", Map.of()));
assertEquals(Decision.ALLOW, decideS3(unquoted,
"arn:aws:s3:::reports/${aws:PrincipalTag/team, fallback}", Map.of()));
}
/**
* The three predefined variables stand for a character, so they have to survive glob matching
* as themselves: "inserting an * asterisk in the string would be interpreted as a wildcard,
* matching any characters, instead of as a literal *".
*/
@Test
void theSingleCharacterEscapesMatchThemselvesRatherThanWildcards() {
String star = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/${*}"}]}""";
assertEquals(Decision.ALLOW, decideS3(star, "arn:aws:s3:::reports/*", Map.of()));
assertEquals(Decision.DENY, decideS3(star, "arn:aws:s3:::reports/q3.csv", Map.of()));
String question = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/${?}"}]}""";
assertEquals(Decision.ALLOW, decideS3(question, "arn:aws:s3:::reports/?", Map.of()));
assertEquals(Decision.DENY, decideS3(question, "arn:aws:s3:::reports/a", Map.of()));
String dollar = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/${$}cost"}]}""";
assertEquals(Decision.ALLOW, decideS3(dollar, "arn:aws:s3:::reports/$cost", Map.of()));
assertEquals(Decision.DENY, decideS3(dollar, "arn:aws:s3:::reports/cost", Map.of()));
}
/** An escape keeps its literal meaning around the wildcards the pattern really does carry. */
@Test
void anEscapeAndAWildcardCoexistInOnePattern() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/*${*}.csv"}]}""";
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports/draft*.csv", Map.of()));
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports/draft.csv", Map.of()));
}
/** A condition value resolves the same way a Resource pattern does. */
@Test
void aConditionVariableComparesAgainstTheResolvedValue() {
String policy = conditionPolicy("StringEquals", "${aws:PrincipalTag/team}");
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports/q3.csv",
Map.of("aws:principaltag/team", List.of("yellow"),
"s3:existingobjecttag/team", List.of("yellow"))));
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports/q3.csv",
Map.of("aws:principaltag/team", List.of("yellow"),
"s3:existingobjecttag/team", List.of("blue"))));
}
/**
* The asymmetry a null value creates: "Condition operators like StringEquals or StringLike do
* not match, and the policy statement does not take effect. Inverted condition operators like
* StringNotEquals or StringNotLike do match against a null value."
*/
@Test
void aConditionVariableWithNoValueFailsPositiveOperatorsAndPassesInvertedOnes() {
Map<String, List<String>> context = Map.of("s3:existingobjecttag/team", List.of("yellow"));
assertEquals(Decision.DENY, decideS3(conditionPolicy("StringEquals",
"${aws:PrincipalTag/team}"), "arn:aws:s3:::reports/q3.csv", context));
assertEquals(Decision.DENY, decideS3(conditionPolicy("StringLike",
"${aws:PrincipalTag/team}"), "arn:aws:s3:::reports/q3.csv", context));
assertEquals(Decision.ALLOW, decideS3(conditionPolicy("StringNotEquals",
"${aws:PrincipalTag/team}"), "arn:aws:s3:::reports/q3.csv", context));
assertEquals(Decision.ALLOW, decideS3(conditionPolicy("StringNotLike",
"${aws:PrincipalTag/team}"), "arn:aws:s3:::reports/q3.csv", context));
}
/** And in a condition value, where an empty one would leave a bare wildcard to match on. */
@Test
void aConditionVariableWithNoValueIsNotAnEmptyString() {
String policy = conditionPolicy("StringLike", "${aws:PrincipalTag/team}*");
Map<String, List<String>> tagged = Map.of("s3:existingobjecttag/team", List.of("yellow"));
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports/q3.csv", tagged));
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports/q3.csv",
Map.of("s3:existingobjecttag/team", List.of("yellow"),
"aws:principaltag/team", List.of("yell"))));
}
/**
* Which makes the Deny AWS documents for exactly this case fire: access "is explicitly denied
* when aws:principaltag/Team is not set".
*/
@Test
void theDocumentedDenyOnAnUnsetPrincipalTagFires() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"},
{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::reports/*",
"Condition":{"StringNotEquals":
{"s3:ExistingObjectTag/Team":"${aws:PrincipalTag/Team}"}}}]}""";
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports/q3.csv",
Map.of("s3:existingobjecttag/team", List.of("yellow"))));
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports/q3.csv",
Map.of("s3:existingobjecttag/team", List.of("yellow"),
"aws:principaltag/team", List.of("yellow"))));
}
/**
* "You can't use a policy variable with other operators, such as Numeric, Date, Boolean,
* Binary, IP Address, or Null operators", so with one of those the text stays as written and
* matches nothing, rather than resolving behind the policy author's back.
*/
@Test
void anOperatorThatTakesNoVariableComparesTheTextAsWritten() {
// The request time against itself: resolved it would be greater than or equal to itself
// and allow, so a Deny here is the text being compared as written and failing to parse.
assertEquals(Decision.DENY, decideS3(conditionPolicy("DateGreaterThanEquals",
"${aws:CurrentTime}", "aws:CurrentTime"),
"arn:aws:s3:::reports/q3.csv", Map.of("aws:currenttime", List.of("2026-10-13T00:00:00Z"))));
// Null reads its own values before any substitution could reach them, so a variable there
// is neither "true" nor "false" and the key it guards is simply absent.
assertEquals(Decision.DENY, decideS3(conditionPolicy("Null",
"${aws:PrincipalTag/team}", "aws:PrincipalTag/team"),
"arn:aws:s3:::reports/q3.csv", Map.of()));
}
/** An escape in a condition value is compared as the character, not as the marker. */
@Test
void anEscapeInAConditionValueComparesAsTheCharacter() {
assertEquals(Decision.ALLOW, decideS3(conditionPolicy("StringEquals", "${*}"),
"arn:aws:s3:::reports/q3.csv", Map.of("s3:existingobjecttag/team", List.of("*"))));
assertEquals(Decision.DENY, decideS3(conditionPolicy("StringEquals", "${*}"),
"arn:aws:s3:::reports/q3.csv", Map.of("s3:existingobjecttag/team", List.of("yellow"))));
assertEquals(Decision.ALLOW, decideS3(conditionPolicy("StringLike", "${*}"),
"arn:aws:s3:::reports/q3.csv", Map.of("s3:existingobjecttag/team", List.of("*"))));
assertEquals(Decision.DENY, decideS3(conditionPolicy("StringLike", "${*}"),
"arn:aws:s3:::reports/q3.csv", Map.of("s3:existingobjecttag/team", List.of("yellow"))));
}
/** An ARN operator is the other family that takes a variable. */
@Test
void anArnConditionResolvesAVariable() {
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
"Condition":{"ArnEquals":{"aws:SourceArn":"${aws:PrincipalArn}"}}}]}""";
String principal = "arn:aws:iam::111122223333:user/Alice";
assertEquals(Decision.ALLOW, decideS3(policy, "arn:aws:s3:::reports/q3.csv",
Map.of("aws:principalarn", List.of(principal), "aws:sourcearn", List.of(principal))));
assertEquals(Decision.DENY, decideS3(policy, "arn:aws:s3:::reports/q3.csv",
Map.of("aws:principalarn", List.of(principal),
"aws:sourcearn", List.of("arn:aws:iam::111122223333:user/Bob"))));
}
/**
* A name is not a variable once it holds a space. The policy-check reference calls it an
* error, "A space is not supported within the policy variable text", and resolving it anyway
* would grant the caller their own user through text AWS does not read as a variable.
*/
@Test
void aVariableNameHoldingASpaceIsNotAVariable() {
Map<String, List<String>> context = Map.of("aws:username", List.of("Alice"));
assertEquals(Decision.DENY, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${ aws:username }"), OWN_USER, context));
assertEquals(Decision.DENY, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${aws:username }"), OWN_USER, context));
// The space is the only difference, so the same pattern without it still resolves.
assertEquals(Decision.ALLOW, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${aws:username}"), OWN_USER, context));
}
/**
* The three forms the guide's policy checks call errors, each left as the text it is: an empty
* variable, a missing closing brace, and a default without its quotes. A space is allowed
* inside a quoted default, which is the one place the guide permits one.
*/
@Test
void aMalformedVariableStaysTheTextItIs() {
Map<String, List<String>> context = Map.of("aws:username", List.of("Alice"));
assertEquals(Decision.DENY, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${}Alice"), OWN_USER, context));
assertEquals(Decision.DENY, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${aws:username"), OWN_USER, context));
assertEquals(Decision.DENY, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${aws:username, Alice}"), OWN_USER, context));
assertEquals(Decision.ALLOW, decide(allowingUserResource("2012-10-17",
"arn:aws:iam::*:user/${aws:username, 'Alice Smith'}"),
"arn:aws:iam::111122223333:user/Alice Smith", Map.of()));
// Staying text and resolving to nothing both refuse a Resource, so the two are told
// apart on a Condition instead, where a value that stayed text still compares and one
// that resolved to nothing is null: equal fails and not-equal holds.
Map<String, List<String>> tagged = Map.of("s3:existingobjecttag/team", List.of("${}x"));
assertEquals(Decision.ALLOW, decideS3(conditionPolicy("StringEquals", "${}x"),
"arn:aws:s3:::reports/q3.csv", tagged));
assertEquals(Decision.DENY, decideS3(conditionPolicy("StringNotEquals", "${}x"),
"arn:aws:s3:::reports/q3.csv", tagged));
}
/**
* A resolved value is not escaped, so one carrying a wildcard widens the pattern it lands in.
* That is AWS's behaviour, whose policy checks warn that variables "can be evaluated as
* effective wildcards", and it is worth pinning because the widening also reaches a Deny.
*/
@Test
void aResolvedValueCarryingAWildcardWidensThePattern() {
String policy = allowingUserResource("2012-10-17", "arn:aws:iam::*:user/${aws:username}");
Map<String, List<String>> wildcardName = Map.of("aws:username", List.of("*"));
assertEquals(Decision.ALLOW, decide(policy, OWN_USER, wildcardName));
assertEquals(Decision.ALLOW, decide(policy, OTHER_USER, wildcardName));
}
/**
* The escape marker belongs to the matcher, and a document can write one as the JSON escape
* {@code \\u0000}. Honouring it there would turn a wildcard of the document's own into a
* literal character and shrink the statement it sits in, so a marker is dropped on the way in
* and the matcher reads one only on a pattern that came back from substitution.
*/
@Test
void aDocumentCannotForgeTheEscapeMarker() {
String deny = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"},
{"Effect":"Deny","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/\\u0000*"}]}""";
assertEquals(Decision.DENY, decideS3(deny, "arn:aws:s3:::reports/q3.csv", Map.of()));
assertEquals(Decision.DENY, decideS3(conditionPolicy("StringNotLike", "\\u0000*"),
"arn:aws:s3:::reports/q3.csv", Map.of("s3:existingobjecttag/team", List.of("yellow"))));
// And under the version that substitutes nothing, where the marker cannot be the
// matcher's own: it is an ordinary character the value has to carry, so the Deny matches
// no object at all, not even the one named with the asterisk it was shielding. Reading it
// as a marker instead would make this Deny refuse that object.
assertEquals(Decision.ALLOW, decideS3("""
{"Version":"2008-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"},
{"Effect":"Deny","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::reports/\\u0000*"}]}""",
"arn:aws:s3:::reports/*", Map.of()));
}
private static String conditionPolicy(String operator, String value) {
return conditionPolicy(operator, value, "s3:ExistingObjectTag/Team");
}
private static String conditionPolicy(String operator, String value, String conditionKey) {
return """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
"Condition":{"%s":{"%s":"%s"}}}]}"""
.formatted(operator, conditionKey, value);
}
private Decision decide(String policy, String resource, Map<String, List<String>> context) {
return evaluator.simulateCustomPolicy(List.of(policy), "iam:ChangePassword", resource, context);
}
private Decision decideS3(String policy, String resource, Map<String, List<String>> context) {
return evaluator.simulateCustomPolicy(List.of(policy), "s3:GetObject", resource, context);
}
}