mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): match absent context keys with ForAllValues (#5482)
* fix(iam): match absent context keys with ForAllValues * fix(iam): preserve condition guards for missing keys * fix(iam): reject unsupported condition shortcuts * docs(iam): clarify supported IfExists conditions * fix(iam): enforce requested keys in set conditions * docs(iam): clarify unresolved attribute conditions * fix(iam): enforce requested S3 object tag keys * fix(iam): scope object tag keys to the authorized action
This commit is contained in:
1 parent
6e38c080fb
commit
ea8da22226
12 files changed
+655
-69
No files matched your search
+26
-17
@@ -1199,11 +1199,13 @@ account key carries no identity policies of its own.
|
||||
- `NumericEquals`, `NumericNotEquals`, `NumericLessThan`, `NumericGreaterThan` (and Equals variants)
|
||||
- `DateEquals`, `DateNotEquals`, `DateLessThan`, `DateGreaterThan` (and Equals variants)
|
||||
- `Bool`, `IpAddress`, `NotIpAddress`, `Null`
|
||||
- Supports `...IfExists` variants for all operators.
|
||||
- Supports `...IfExists` variants for all operators except `Null`.
|
||||
- Set operators `ForAllValues:` and `ForAnyValue:` over multi-valued condition keys, in AWS's
|
||||
own spelling (the prefix match is case-sensitive). They compose with `IfExists`
|
||||
(`ForAnyValue:StringEqualsIfExists`). `ForAllValues:` over an empty set matches vacuously
|
||||
and `ForAnyValue:` over an empty set does not match, so pair `ForAllValues:` with
|
||||
(`ForAnyValue:StringEqualsIfExists`). `ForAllValues:` matches when the context key is absent
|
||||
or its value set is empty; `ForAnyValue:` does not match either case. This follows the
|
||||
[AWS set-operator rules](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-single-vs-multi-valued-context-keys.html).
|
||||
Pair `ForAllValues:` with
|
||||
`"Null":{"<key>":"false"}` as you would on AWS: `Null` treats a present-but-empty set as
|
||||
absent, so the guard fires either way.
|
||||
- When a condition lists several values, a positive operator matches if the request value
|
||||
@@ -1232,11 +1234,17 @@ floci populates:
|
||||
An allow conditioned on it denies the delete of a correctly tagged object, and a create cannot
|
||||
be gated on tags an object does not have yet.
|
||||
- `s3:RequestObjectTag/<key>`: a tag the request asks to attach. `s3:PutObject` reads these
|
||||
from the `x-amz-tagging` header and `s3:PutObjectTagging` from the `<Tagging>` body. Any pair
|
||||
from the `x-amz-tagging` header, or its query parameter when the header is absent,
|
||||
and `s3:PutObjectTagging` from the `<Tagging>` body. Any pair
|
||||
that does not decode is dropped, so a policy conditioned on the key denies such a request. Where
|
||||
enforcement lets it through, the handler still answers a malformed header with
|
||||
`400 InvalidTag`. `s3:RequestObjectTagKeys` is **not** populated, so a condition on it never
|
||||
matches.
|
||||
`400 InvalidTag`.
|
||||
- `s3:RequestObjectTagKeys`: the case-sensitive requested object tag keys from the same
|
||||
`PutObject` header/query source or `PutObjectTagging` body. Header and query tag keys
|
||||
are URL-decoded before matching; a present header takes precedence over the query.
|
||||
`ForAllValues:StringEquals` can limit all requested keys without a `Null` guard; an
|
||||
omitted or empty tag set still follows the absent-key rules above. Existing object tags
|
||||
do not contribute to this requested set. See the [AWS object-tag policy guidance](https://docs.aws.amazon.com/AmazonS3/latest/userguide/tagging-and-policies.html).
|
||||
- A `PutObject` carrying `If-Match` is authorized as `s3:GetObject` as well, and that second
|
||||
check is made without the object's tags in the context, as measured on AWS. `If-None-Match`
|
||||
needs no such permission.
|
||||
@@ -1247,6 +1255,9 @@ floci populates:
|
||||
`assumed-role` session ARN, as AWS reports it ("For IAM roles, the request context returns the
|
||||
ARN of the role"); a condition naming the session ARN does not match. It is **absent** only for
|
||||
unknown keys, where nothing about the caller can be resolved.
|
||||
- `aws:TagKeys`: the case-sensitive requested tag keys for EC2 `RunInstances` and
|
||||
`CreateTags`, and S3 `PutBucketTagging`. `ForAllValues:StringEquals` can restrict the
|
||||
complete requested set without a `Null` guard; no tags still means absent context.
|
||||
- `dynamodb:LeadingKeys`, `dynamodb:Attributes`, `dynamodb:Select`: from the DynamoDB request
|
||||
body, for `GetItem`, `PutItem`, `UpdateItem`, `DeleteItem`, `Query`, `BatchGetItem` and
|
||||
`BatchWriteItem` (`dynamodb:Select` for `Query` and `Scan`). `LeadingKeys` holds the
|
||||
@@ -1256,18 +1267,16 @@ floci populates:
|
||||
projection / update / filter / condition / key-condition expressions, and
|
||||
`ExpressionAttributeNames`); a request with no projection returns every attribute while
|
||||
reporting only the names it mentions, exactly as on AWS, which is why AWS pairs `Attributes`
|
||||
with `dynamodb:Select`. Each key is **omitted** when it cannot be determined (unknown table,
|
||||
a `Key` that omits the partition attribute, an unparseable `KeyConditionExpression`, a
|
||||
multi-table batch), so a policy scoping access through it denies the request rather than
|
||||
allowing an unproven one.
|
||||
with `dynamodb:Select`. Query equality supports the attribute on either side, including aliases.
|
||||
Each batch entry uses its own table schema; authorization evaluates each table's requested
|
||||
keys separately, combining name and ARN entries for the same table. Each key is **omitted**
|
||||
when it cannot be determined, such as an unknown table, a missing partition attribute, or
|
||||
an unparseable expression. A `ForAllValues` condition matches absent context; add
|
||||
`Null:false` when the policy must require a resolved key. Malformed requests that pass
|
||||
authorization are still checked by the DynamoDB handler.
|
||||
|
||||
**Consequence:** with enforcement on and access scoped purely through `dynamodb:LeadingKeys`,
|
||||
a malformed request (such as a `GetItem` whose `Key` omits the partition attribute) is answered with
|
||||
`AccessDeniedException` instead of the `ValidationException` DynamoDB would return. Failing
|
||||
closed is the correct direction for a security boundary.
|
||||
|
||||
**Any other condition key is absent from the request context.** A plain (non-`IfExists`)
|
||||
operator on an absent key makes the whole statement *not apply*: it neither matches nor
|
||||
**Any other condition key is absent from the request context.** A positive scalar operator
|
||||
without `IfExists` on an absent key makes the whole statement *not apply*: it neither matches nor
|
||||
blocks. A `DenyRootUser`-style guardrail keyed on `aws:PrincipalArn` therefore fires against
|
||||
the account root the same way it does on real AWS, consistent with the account root already
|
||||
being bounded by SCPs (below): both forms of root enforcement now agree. A negated operator
|
||||
|
||||
+81
-18
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbConditionKeys;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
|
||||
@@ -24,8 +25,10 @@ import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Builds the IAM request context: the condition keys a policy's Condition block can match,
|
||||
@@ -53,6 +56,7 @@ public class IamConditionContextResolver {
|
||||
private static final String RESOURCE_TAG_PREFIX = "aws:ResourceTag/";
|
||||
public static final String EXISTING_OBJECT_TAG_PREFIX = "s3:ExistingObjectTag/";
|
||||
public static final String REQUEST_OBJECT_TAG_PREFIX = "s3:RequestObjectTag/";
|
||||
public static final String REQUEST_OBJECT_TAG_KEYS = "s3:RequestObjectTagKeys";
|
||||
|
||||
private final Instance<DynamoDbFacade> dynamoDbFacade;
|
||||
private final Instance<Ec2Service> ec2Service;
|
||||
@@ -183,15 +187,20 @@ public class IamConditionContextResolver {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code s3:RequestObjectTag/<key>} from a PutObject's {@code x-amz-tagging} header, which the
|
||||
* S3 model documents as a URL query parameter encoding of the tag-set.
|
||||
* {@code s3:RequestObjectTag/<key>} from a PutObject's {@code x-amz-tagging} header, or the
|
||||
* query parameter where a presigner may place it. The header takes precedence, including
|
||||
* an empty header, matching the source the S3 controller applies to the object.
|
||||
*/
|
||||
private Map<String, List<String>> s3RequestObjectTagConditionContext(ContainerRequestContext ctx) {
|
||||
String header = ctx.getHeaderString("x-amz-tagging");
|
||||
if (header == null && ctx.getUriInfo() != null) {
|
||||
header = ctx.getUriInfo().getQueryParameters().getFirst("x-amz-tagging");
|
||||
}
|
||||
if (header == null || header.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
Set<String> requestedKeys = new LinkedHashSet<>();
|
||||
for (String pair : header.split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
if (eq <= 0) {
|
||||
@@ -203,6 +212,10 @@ public class IamConditionContextResolver {
|
||||
continue;
|
||||
}
|
||||
conditions.put(REQUEST_OBJECT_TAG_PREFIX + name, List.of(value));
|
||||
requestedKeys.add(name);
|
||||
}
|
||||
if (!requestedKeys.isEmpty()) {
|
||||
conditions.put(REQUEST_OBJECT_TAG_KEYS, new ArrayList<>(requestedKeys));
|
||||
}
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
@@ -220,6 +233,7 @@ public class IamConditionContextResolver {
|
||||
}
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
tags.forEach((k, v) -> conditions.put(REQUEST_OBJECT_TAG_PREFIX + k, List.of(v)));
|
||||
conditions.put(REQUEST_OBJECT_TAG_KEYS, new ArrayList<>(tags.keySet()));
|
||||
return conditions;
|
||||
}
|
||||
|
||||
@@ -286,6 +300,9 @@ public class IamConditionContextResolver {
|
||||
new String(body, StandardCharsets.UTF_8), "Tag", "Key", "Value");
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
requested.forEach((key, value) -> conditions.put(REQUEST_TAG_PREFIX + key, List.of(value)));
|
||||
if (!requested.isEmpty()) {
|
||||
conditions.put("aws:TagKeys", List.copyOf(requested.keySet()));
|
||||
}
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
@@ -408,7 +425,12 @@ public class IamConditionContextResolver {
|
||||
String prefix) {
|
||||
for (int i = 1; form.containsKey(prefix + i + ".Key"); i++) {
|
||||
String value = form.get(prefix + i + ".Value");
|
||||
conditions.put(REQUEST_TAG_PREFIX + form.get(prefix + i + ".Key"),
|
||||
String key = form.get(prefix + i + ".Key");
|
||||
List<String> keys = conditions.computeIfAbsent("aws:TagKeys", ignored -> new ArrayList<>());
|
||||
if (!keys.contains(key)) {
|
||||
keys.add(key);
|
||||
}
|
||||
conditions.put(REQUEST_TAG_PREFIX + key,
|
||||
List.of(value == null ? "" : value));
|
||||
}
|
||||
}
|
||||
@@ -499,16 +521,19 @@ public class IamConditionContextResolver {
|
||||
* {@code dynamodb:Select} from the buffered request body.
|
||||
*
|
||||
* <p>A key that cannot be resolved (unknown table, a Key that omits the partition
|
||||
* attribute, an unparseable KeyConditionExpression) is omitted rather than guessed. A
|
||||
* policy scoping access through the missing key then does not match, so the request is
|
||||
* denied: a request that cannot be proven in scope is treated as out of scope.
|
||||
* attribute, an unparseable KeyConditionExpression) is omitted rather than guessed.
|
||||
* A {@code ForAllValues} condition matches an absent key; policies must pair it with
|
||||
* {@code Null:false} to require a resolved key.
|
||||
*/
|
||||
Map<String, List<String>> dynamoDbConditionContext(String action, ContainerRequestContext ctx) {
|
||||
JsonNode body = bufferedJsonBody(ctx);
|
||||
if (body == null || !body.isObject()) {
|
||||
return null;
|
||||
}
|
||||
TableDefinition table = describeTargetTable(body);
|
||||
if (isDynamoDbBatch(action)) {
|
||||
return dynamoDbBatchConditionContext(action, ctx, null);
|
||||
}
|
||||
TableDefinition table = describeTargetTable(targetTableName(body));
|
||||
DynamoDbConditionKeys.Result keys = DynamoDbConditionKeys.extract(action, body, table);
|
||||
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
@@ -524,6 +549,53 @@ public class IamConditionContextResolver {
|
||||
return conditions.isEmpty() ? null : conditions;
|
||||
}
|
||||
|
||||
/** Resolves each batch entry with its own schema, optionally restricted to one resource. */
|
||||
Map<String, List<String>> dynamoDbBatchConditionContext(String action, ContainerRequestContext ctx,
|
||||
String resourceArn) {
|
||||
if (!isDynamoDbBatch(action)) {
|
||||
return null;
|
||||
}
|
||||
Map<String, List<String>> conditions = new LinkedHashMap<>();
|
||||
JsonNode body = bufferedJsonBody(ctx);
|
||||
JsonNode items = body == null ? null : body.get("RequestItems");
|
||||
if (items == null || !items.isObject()) {
|
||||
return conditions;
|
||||
}
|
||||
List<String> leadingKeys = new ArrayList<>();
|
||||
Set<String> attributes = new LinkedHashSet<>();
|
||||
items.properties().forEach(entry -> {
|
||||
String reference = entry.getKey().trim();
|
||||
if (resourceArn != null && !matchesTableResource(reference, resourceArn)) {
|
||||
return;
|
||||
}
|
||||
ObjectNode single = ((ObjectNode) body).objectNode();
|
||||
single.setAll((ObjectNode) body);
|
||||
single.putObject("RequestItems").set(entry.getKey(), entry.getValue());
|
||||
DynamoDbConditionKeys.Result keys = DynamoDbConditionKeys.extract(
|
||||
action, single, describeTargetTable(reference));
|
||||
leadingKeys.addAll(keys.leadingKeys());
|
||||
attributes.addAll(keys.attributes());
|
||||
});
|
||||
if (!leadingKeys.isEmpty()) {
|
||||
conditions.put("dynamodb:LeadingKeys", List.copyOf(leadingKeys));
|
||||
}
|
||||
if (!attributes.isEmpty()) {
|
||||
conditions.put("dynamodb:Attributes", List.copyOf(attributes));
|
||||
}
|
||||
return conditions;
|
||||
}
|
||||
|
||||
private static boolean isDynamoDbBatch(String action) {
|
||||
return "dynamodb:BatchGetItem".equals(action) || "dynamodb:BatchWriteItem".equals(action);
|
||||
}
|
||||
|
||||
private static boolean matchesTableResource(String reference, String resourceArn) {
|
||||
if (AwsArnUtils.isArn(reference)) {
|
||||
return reference.equals(resourceArn);
|
||||
}
|
||||
return AwsArnUtils.parse(resourceArn).resource().equals("table/" + reference);
|
||||
}
|
||||
|
||||
private JsonNode bufferedJsonBody(ContainerRequestContext ctx) {
|
||||
Object cached = ctx.getProperty(BUFFERED_JSON_BODY);
|
||||
return cached instanceof JsonNode node ? node : null;
|
||||
@@ -535,8 +607,7 @@ public class IamConditionContextResolver {
|
||||
* {@code findTable} rather than {@code describeTable} so the O(items) item-count refresh
|
||||
* never runs on the enforcement hot path.
|
||||
*/
|
||||
private TableDefinition describeTargetTable(JsonNode body) {
|
||||
String tableName = targetTableName(body);
|
||||
private TableDefinition describeTargetTable(String tableName) {
|
||||
if (tableName == null || !dynamoDbFacade.isResolvable()) {
|
||||
return null;
|
||||
}
|
||||
@@ -546,11 +617,7 @@ public class IamConditionContextResolver {
|
||||
return dynamoDb.tables().findTable(dynamoDb.scope(region), tableName).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The single table this request targets: the TableName field, or the sole RequestItems
|
||||
* entry for the batch operations. A multi-table batch has no single key schema, so it
|
||||
* gets no leading keys and fails closed.
|
||||
*/
|
||||
/** The table targeted by a non-batch request. */
|
||||
private String targetTableName(JsonNode body) {
|
||||
if (body.hasNonNull("TableName")) {
|
||||
String tableName = body.get("TableName").asText().trim();
|
||||
@@ -558,10 +625,6 @@ public class IamConditionContextResolver {
|
||||
return tableName;
|
||||
}
|
||||
}
|
||||
JsonNode requestItems = body.get("RequestItems");
|
||||
if (requestItems != null && requestItems.isObject() && requestItems.size() == 1) {
|
||||
return requestItems.fieldNames().next();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -684,6 +684,16 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
for (Map<String, List<String>> targetContext : targetContexts) {
|
||||
Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(
|
||||
targetContext, resource, region, accountId, resourceOwnerAccountId);
|
||||
if ("dynamodb".equals(credentialScope)) {
|
||||
Map<String, List<String>> batchContext =
|
||||
conditionContextResolver.dynamoDbBatchConditionContext(action, ctx, resource);
|
||||
if (batchContext != null) {
|
||||
effectiveContext.remove("dynamodb:LeadingKeys");
|
||||
effectiveContext.remove("dynamodb:Attributes");
|
||||
effectiveContext.remove("dynamodb:Select");
|
||||
effectiveContext.putAll(batchContext);
|
||||
}
|
||||
}
|
||||
ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicyFor(
|
||||
effectiveResourcePolicies, principal, action, resource, effectiveContext);
|
||||
Decision decision = evaluator.evaluateResolvedResourcePolicy(
|
||||
@@ -759,7 +769,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
Map<String, List<String>> copy = new HashMap<>(targetContext);
|
||||
copy.keySet().removeIf(key ->
|
||||
key.startsWith(IamConditionContextResolver.EXISTING_OBJECT_TAG_PREFIX)
|
||||
|| key.startsWith(IamConditionContextResolver.REQUEST_OBJECT_TAG_PREFIX));
|
||||
|| key.startsWith(IamConditionContextResolver.REQUEST_OBJECT_TAG_PREFIX)
|
||||
|| key.equals(IamConditionContextResolver.REQUEST_OBJECT_TAG_KEYS));
|
||||
stripped.add(copy.isEmpty() ? null : copy);
|
||||
}
|
||||
return stripped;
|
||||
|
||||
+4
-4
@@ -24,9 +24,9 @@ import java.util.regex.Pattern;
|
||||
*
|
||||
* <p>Everything is best effort. Whatever cannot be determined is simply absent from the
|
||||
* result: an unresolvable leading key produces an empty list, the condition key is then
|
||||
* omitted from the request context, and a policy that scopes access through it fails closed.
|
||||
* Note that this "fail closed" behavior applies to {@code dynamodb:LeadingKeys}; for
|
||||
* {@code dynamodb:Attributes} evaluated under {@code ForAllValues}, under-reporting is the
|
||||
* omitted from the request context. A {@code ForAllValues} policy must include a
|
||||
* {@code Null:false} guard to require a resolved leading key.
|
||||
* For {@code dynamodb:Attributes} evaluated under {@code ForAllValues}, under-reporting is the
|
||||
* unsafe direction because omitting a referenced attribute could allow an unauthorized
|
||||
* operation to pass.
|
||||
*/
|
||||
@@ -307,7 +307,7 @@ public final class DynamoDbConditionKeys {
|
||||
* Top-level attribute names a DynamoDB expression references: a FilterExpression,
|
||||
* ConditionExpression or KeyConditionExpression. Walks the parsed tree so a literal name
|
||||
* such as {@code ssn} in {@code "ssn = :x"} is captured, not only {@code #alias}es.
|
||||
* A malformed expression yields nothing, which only ever denies.
|
||||
* A malformed expression yields no attribute names; normal absent-key condition rules apply.
|
||||
*/
|
||||
private static void addExpressionAttributes(Set<String> attributes, String expression,
|
||||
JsonNode exprAttrNames) {
|
||||
|
||||
+11
-8
@@ -17,7 +17,8 @@ import java.util.List;
|
||||
* <p>Exists so IAM condition-key extraction can reuse the expression parser without making
|
||||
* the whole {@link DynamoDbAccessPathValidator} public. Everything here is best effort: a
|
||||
* malformed or unsupported expression yields {@code null}, and the caller treats that as
|
||||
* "the leading key could not be determined", which fails closed at the policy layer.
|
||||
* "the leading key could not be determined". A {@code ForAllValues} policy needs a
|
||||
* {@code Null:false} guard to require that key.
|
||||
*/
|
||||
final class DynamoDbKeyConditionParser {
|
||||
|
||||
@@ -43,22 +44,24 @@ final class DynamoDbKeyConditionParser {
|
||||
try {
|
||||
root = ExpressionEvaluator.parse(keyConditionExpression);
|
||||
} catch (RuntimeException e) {
|
||||
return null; // unparseable expression → leading key unknown → fail closed upstream
|
||||
return null; // Unparseable expression: omit the unknown leading key from the context.
|
||||
}
|
||||
if (root == null) {
|
||||
return null;
|
||||
}
|
||||
List<Expr> conditions = root instanceof AndExpr and ? and.operands() : List.of(root);
|
||||
for (Expr condition : conditions) {
|
||||
if (!(condition instanceof CompareExpr compare)
|
||||
|| compare.op() != TokenType.EQ
|
||||
|| !(compare.right() instanceof PlaceholderOperand placeholder)) {
|
||||
if (!(condition instanceof CompareExpr compare) || compare.op() != TokenType.EQ) {
|
||||
continue;
|
||||
}
|
||||
if (!pkName.equals(topLevelAttribute(compare.left(), exprAttrNames))) {
|
||||
continue;
|
||||
if (compare.right() instanceof PlaceholderOperand placeholder
|
||||
&& pkName.equals(topLevelAttribute(compare.left(), exprAttrNames))) {
|
||||
return scalarValue(exprAttrValues.get(placeholder.name()));
|
||||
}
|
||||
if (compare.left() instanceof PlaceholderOperand placeholder
|
||||
&& pkName.equals(topLevelAttribute(compare.right(), exprAttrNames))) {
|
||||
return scalarValue(exprAttrValues.get(placeholder.name()));
|
||||
}
|
||||
return scalarValue(exprAttrValues.get(placeholder.name()));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1218,6 +1218,9 @@ public class IamPolicyEvaluator {
|
||||
private boolean evaluateConditionBlock(String operator,
|
||||
Map<String, List<String>> keyValueMap,
|
||||
Map<String, List<String>> ctx) {
|
||||
if (!isSupportedConditionOperator(operator)) {
|
||||
return false;
|
||||
}
|
||||
ParsedOperator parsed = parseOperator(operator);
|
||||
String baseOp = parsed.baseOp();
|
||||
boolean ifExists = parsed.ifExists();
|
||||
@@ -1239,6 +1242,9 @@ public class IamPolicyEvaluator {
|
||||
if (ifExists) {
|
||||
continue; // key missing + IfExists → pass this key
|
||||
}
|
||||
if (parsed.quantifier() == SetQuantifier.FOR_ALL_VALUES) {
|
||||
continue;
|
||||
}
|
||||
// A negated operator asks for the key not to match, and an absent key matches
|
||||
// nothing, so the condition holds (IAM User Guide, condition operators). The set
|
||||
// operators keep their own rule for an absent key.
|
||||
|
||||
+65
-5
@@ -26,9 +26,11 @@ import org.mockito.ArgumentCaptor;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -92,6 +94,7 @@ class IamConditionContextResolverTest {
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn(path);
|
||||
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(containerRequest.getEntityStream())
|
||||
.thenReturn(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
|
||||
return containerRequest;
|
||||
@@ -149,6 +152,55 @@ class IamConditionContextResolverTest {
|
||||
assertNull(resolver.resolve("s3", "s3:GetObject", containerRequest));
|
||||
}
|
||||
|
||||
@Test
|
||||
void objectTagKeysDecodeHeadersAndRetainCaseWithoutDuplicates() {
|
||||
ContainerRequestContext request = s3Request("/bucket/object", "");
|
||||
when(request.getHeaderString("x-amz-tagging"))
|
||||
.thenReturn("%54eam=one&Team=two&team=three&Cost%20Center=four&bad=%zz");
|
||||
Map<String, List<String>> conditions = resolver.resolve("s3", "s3:PutObject", request);
|
||||
assertEquals(List.of("Team", "team", "Cost Center"), conditions.get("s3:RequestObjectTagKeys"));
|
||||
assertEquals(List.of("two"), conditions.get("s3:RequestObjectTag/Team"));
|
||||
assertFalse(conditions.containsKey("s3:RequestObjectTag/bad"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryObjectTagKeysUseHeaderPrecedenceIncludingAnEmptyHeader() {
|
||||
ContainerRequestContext request = s3Request("/bucket/object", "");
|
||||
request.getUriInfo().getQueryParameters().putSingle("x-amz-tagging", "%54eam=payments");
|
||||
Map<String, List<String>> query = resolver.resolve("s3", "s3:PutObject", request);
|
||||
assertEquals(List.of("Team"), query.get("s3:RequestObjectTagKeys"));
|
||||
assertEquals(List.of("payments"), query.get("s3:RequestObjectTag/Team"));
|
||||
when(request.getHeaderString("x-amz-tagging")).thenReturn("Other=value");
|
||||
assertEquals(List.of("Other"), resolver.resolve("s3", "s3:PutObject", request)
|
||||
.get("s3:RequestObjectTagKeys"));
|
||||
when(request.getHeaderString("x-amz-tagging")).thenReturn("");
|
||||
assertNull(resolver.resolve("s3", "s3:PutObject", request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void objectTagKeysComeOnlyFromTheRequestedXmlTags() {
|
||||
ContainerRequestContext request = s3Request("/bucket/object",
|
||||
"<Tagging><TagSet><Tag><Key>Team</Key><Value>payments</Value></Tag>"
|
||||
+ "<Tag><Key>Cost&Center</Key><Value>42</Value></Tag></TagSet></Tagging>");
|
||||
when(request.getUriInfo().getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(s3Service.getObjectTagging("bucket", "object", null)).thenReturn(Map.of("Previous", "old"));
|
||||
Map<String, List<String>> conditions = resolver.resolve("s3", "s3:PutObjectTagging", request);
|
||||
assertEquals(Set.of("Team", "Cost&Center"), new HashSet<>(conditions.get("s3:RequestObjectTagKeys")));
|
||||
assertEquals(List.of("old"), conditions.get("s3:ExistingObjectTag/Previous"));
|
||||
assertEquals(List.of("42"), conditions.get("s3:RequestObjectTag/Cost&Center"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyObjectTagRequestsDoNotExposeRequestedKeys() {
|
||||
assertNull(resolver.resolve("s3", "s3:PutObject", s3Request("/bucket/object", "")));
|
||||
ContainerRequestContext empty = s3Request("/bucket/object", "<Tagging><TagSet/></Tagging>");
|
||||
when(empty.getUriInfo().getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(s3Service.getObjectTagging("bucket", "object", null)).thenReturn(Map.of("Previous", "old"));
|
||||
Map<String, List<String>> conditions = resolver.resolve("s3", "s3:PutObjectTagging", empty);
|
||||
assertEquals(List.of("old"), conditions.get("s3:ExistingObjectTag/Previous"));
|
||||
assertFalse(conditions.containsKey("s3:RequestObjectTagKeys"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesDynamoDbLeadingKeysForGetItem() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
@@ -220,19 +272,25 @@ class IamConditionContextResolverTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void omitsLeadingKeysForAMultiTableBatch() {
|
||||
// A batch spanning two tables has no single key schema: applying table A's partition
|
||||
// key name to table B's items would be wrong, so no leading keys are produced.
|
||||
void resolvesEachBatchTableWithItsOwnSchema() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
when(containerRequest.getProperty("floci.bufferedJsonBody")).thenReturn(json("""
|
||||
{"RequestItems":{
|
||||
"FgacTable":{"Keys":[{"PK":{"S":"USER_alice"}}]},
|
||||
"OtherTable":{"Keys":[{"PK":{"S":"USER_bob"}}]}}}"""));
|
||||
"OtherTable":{"Keys":[{"Tenant":{"S":"USER_bob"}}]}}}"""));
|
||||
|
||||
TableDefinition other = new TableDefinition();
|
||||
other.setTableName("OtherTable");
|
||||
other.setKeySchema(List.of(new KeySchemaElement("Tenant", "HASH")));
|
||||
when(dynamoDbService.findTable("FgacTable", "us-east-1")).thenReturn(Optional.of(fgacTable()));
|
||||
when(dynamoDbService.findTable("OtherTable", "us-east-1")).thenReturn(Optional.of(other));
|
||||
Map<String, List<String>> conditions =
|
||||
resolver.resolve("dynamodb", "dynamodb:BatchGetItem", containerRequest);
|
||||
|
||||
assertFalse(conditions.containsKey("dynamodb:LeadingKeys"));
|
||||
assertEquals(List.of("USER_alice", "USER_bob"), conditions.get("dynamodb:LeadingKeys"));
|
||||
assertEquals(List.of("USER_bob"), resolver.dynamoDbBatchConditionContext(
|
||||
"dynamodb:BatchGetItem", containerRequest,
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/OtherTable").get("dynamodb:LeadingKeys"));
|
||||
}
|
||||
|
||||
// ── aws:RequestTag and aws:ResourceTag ─────────────────────────────────────
|
||||
@@ -249,6 +307,7 @@ class IamConditionContextResolverTest {
|
||||
|
||||
assertEquals(List.of("payments"), conditions.get("aws:RequestTag/Team"));
|
||||
assertEquals(List.of("prod"), conditions.get("aws:RequestTag/Env"));
|
||||
assertEquals(Set.of("Team", "Env"), new HashSet<>(conditions.get("aws:TagKeys")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -295,6 +354,7 @@ class IamConditionContextResolverTest {
|
||||
|
||||
assertEquals(List.of("payments"), conditions.get("aws:RequestTag/Team"));
|
||||
assertEquals(List.of("prod"), conditions.get("aws:RequestTag/Env"));
|
||||
assertEquals(List.of("Team", "Env"), conditions.get("aws:TagKeys"));
|
||||
assertFalse(conditions.containsKey("aws:ResourceTag/Team"));
|
||||
}
|
||||
|
||||
|
||||
+125
-9
@@ -6,6 +6,9 @@ import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -88,9 +91,8 @@ class DynamoDbFgacEnforcementIntegrationTest {
|
||||
|
||||
String accessKeyId = assumeRoleWithLeadingKeysSessionPolicy(roleName);
|
||||
|
||||
// The Key omits the partition attribute, so the leading key cannot be resolved. With
|
||||
// access scoped purely through dynamodb:LeadingKeys this is denied rather than passed
|
||||
// to DynamoDB, which is the correct direction for a security boundary.
|
||||
// The Key omits the partition attribute, so the leading key cannot be resolved.
|
||||
// The session policy's Null:false guard denies it before DynamoDB handles the request.
|
||||
given()
|
||||
.header("Authorization", auth(accessKeyId, "dynamodb"))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
|
||||
@@ -155,6 +157,115 @@ class DynamoDbFgacEnforcementIntegrationTest {
|
||||
.body(containsString("AccessDeniedException"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {":uid = PK", ":uid = #pk"})
|
||||
void reversedQueryRequiresTheRequestedPartitionWithoutNullGuard(String expression) {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String table = "fgac-reversed-" + suffix;
|
||||
String role = "FgacReversed" + suffix;
|
||||
createTable(table);
|
||||
putItem(table, "USER_alice");
|
||||
putItem(table, "USER_bob");
|
||||
createRole(role);
|
||||
putBroadDynamoDbRolePolicy(role);
|
||||
String accessKey = assumeRoleWithLeadingKeysSessionPolicy(role, false);
|
||||
for (String user : new String[]{"USER_alice", "USER_bob"}) {
|
||||
given().header("Authorization", auth(accessKey, "dynamodb"))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.Query")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"TableName":"%s","KeyConditionExpression":"%s",%s
|
||||
"ExpressionAttributeValues":{":uid":{"S":"%s"}}}
|
||||
""".formatted(table, expression, expression.contains("#")
|
||||
? "\"ExpressionAttributeNames\":{\"#pk\":\"PK\"}," : "", user))
|
||||
.post("/").then().statusCode(user.equals("USER_alice") ? 200 : 400)
|
||||
.body(containsString(user.equals("USER_alice") ? "USER_alice" : "AccessDeniedException"));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"BatchGetItem,false", "BatchGetItem,true", "BatchWriteItem,false", "BatchWriteItem,true"})
|
||||
void everyBatchEntryContributesLeadingKeysWithoutNullGuard(String action, boolean alias) {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String table = "fgac-batch-" + suffix;
|
||||
String other = alias ? "arn:aws:dynamodb:" + REGION + ":" + ROLE_ACCOUNT_ID + ":table/" + table
|
||||
: "fgac-other-" + suffix;
|
||||
String role = "FgacBatch" + suffix;
|
||||
createTable(table);
|
||||
if (!alias) {
|
||||
createTable(other);
|
||||
}
|
||||
putItem(table, "USER_alice");
|
||||
putItem(other, "USER_bob");
|
||||
createRole(role);
|
||||
putBroadDynamoDbRolePolicy(role);
|
||||
String accessKey = assumeRoleWithLeadingKeysSessionPolicy(role, false);
|
||||
for (String user : new String[]{"USER_alice_2", "USER_bob"}) {
|
||||
String first = batchEntry(action, "USER_alice");
|
||||
String second = batchEntry(action, user);
|
||||
given().header("Authorization", auth(accessKey, "dynamodb"))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810." + action)
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("{\"RequestItems\":{\"" + table + "\":" + first + ",\"" + other + "\":" + second + "}}")
|
||||
.post("/").then().statusCode(user.equals("USER_bob") ? 400 : 200)
|
||||
.body(containsString(user.equals("USER_bob") ? "AccessDeniedException"
|
||||
: action.equals("BatchGetItem") ? "Responses" : "UnprocessedItems"));
|
||||
}
|
||||
given().header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("{\"TableName\":\"" + other + "\",\"Key\":{\"PK\":{\"S\":\"USER_bob\"}}}")
|
||||
.post("/").then().statusCode(200).body("Item.PK.S", equalTo("USER_bob"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchPoliciesEvaluateEachTableWithOnlyItsOwnKeys() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String first = "fgac-first-" + suffix;
|
||||
String second = "fgac-second-" + suffix;
|
||||
String role = "FgacSeparate" + suffix;
|
||||
createTable(first);
|
||||
createTable(second);
|
||||
putItem(first, "USER_alice");
|
||||
putItem(second, "USER_bob");
|
||||
createRole(role);
|
||||
String statements = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:BatchGetItem","Resource":"%s",
|
||||
"Condition":{"ForAllValues:StringEquals":{"dynamodb:LeadingKeys":["USER_alice"]}}},
|
||||
{"Effect":"Allow","Action":"dynamodb:BatchGetItem","Resource":"%s",
|
||||
"Condition":{"ForAllValues:StringEquals":{"dynamodb:LeadingKeys":["USER_bob"]}}}]}
|
||||
""".formatted("arn:aws:dynamodb:" + REGION + ":" + ROLE_ACCOUNT_ID + ":table/" + first,
|
||||
"arn:aws:dynamodb:" + REGION + ":" + ROLE_ACCOUNT_ID + ":table/" + second);
|
||||
given().header("Authorization", auth(ROLE_ACCOUNT_ID, "iam"))
|
||||
.formParam("Action", "PutRolePolicy").formParam("RoleName", role)
|
||||
.formParam("PolicyName", "Tables").formParam("PolicyDocument", statements)
|
||||
.post("/").then().statusCode(200);
|
||||
String accessKey = given().header("Authorization", auth(CALLER_ACCOUNT_ID, "sts"))
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT_ID + ":role/" + role)
|
||||
.formParam("RoleSessionName", "separate-tables")
|
||||
.post("/").then().statusCode(200).extract()
|
||||
.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
|
||||
for (boolean swapped : new boolean[]{false, true}) {
|
||||
given().header("Authorization", auth(accessKey, "dynamodb"))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.BatchGetItem")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
.body("{\"RequestItems\":{\"" + first + "\":"
|
||||
+ batchEntry("BatchGetItem", swapped ? "USER_bob" : "USER_alice")
|
||||
+ ",\"" + second + "\":"
|
||||
+ batchEntry("BatchGetItem", swapped ? "USER_alice" : "USER_bob") + "}}")
|
||||
.post("/").then().statusCode(swapped ? 400 : 200)
|
||||
.body(containsString(swapped ? "AccessDeniedException" : "USER_bob"));
|
||||
}
|
||||
}
|
||||
|
||||
private static String batchEntry(String action, String user) {
|
||||
String key = "{\"PK\":{\"S\":\"" + user + "\"}}";
|
||||
return action.equals("BatchGetItem") ? "{\"Keys\":[" + key + "]}"
|
||||
: "[{\"DeleteRequest\":{\"Key\":" + key + "}}]";
|
||||
}
|
||||
|
||||
private static void createTable(String tableName) {
|
||||
given()
|
||||
.header("Authorization", auth(ROLE_ACCOUNT_ID, "dynamodb"))
|
||||
@@ -272,16 +383,21 @@ class DynamoDbFgacEnforcementIntegrationTest {
|
||||
* allow or a deny can only come from the LeadingKeys condition.
|
||||
*/
|
||||
private static String assumeRoleWithLeadingKeysSessionPolicy(String roleName) {
|
||||
return assumeRoleWithLeadingKeysSessionPolicy(roleName, true);
|
||||
}
|
||||
|
||||
private static String assumeRoleWithLeadingKeysSessionPolicy(String roleName, boolean nullGuard) {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:*","Resource":"*",
|
||||
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}%s}}
|
||||
]}
|
||||
""".formatted(nullGuard ? ",\"Null\":{\"dynamodb:LeadingKeys\":\"false\"}" : "");
|
||||
return given()
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT_ID + ":role/" + roleName)
|
||||
.formParam("RoleSessionName", "fgac-leading-keys-test")
|
||||
.formParam("Policy", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:*","Resource":"*",
|
||||
"Condition":{"ForAllValues:StringLike":
|
||||
{"dynamodb:LeadingKeys":["USER_alice*"]}}}
|
||||
]}""")
|
||||
.formParam("Policy", policy)
|
||||
.header("Authorization", auth(CALLER_ACCOUNT_ID, "sts"))
|
||||
.when()
|
||||
.post("/")
|
||||
|
||||
+3
-2
@@ -219,7 +219,8 @@ class IamEnforcementIntegrationTest {
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":["dynamodb:GetItem","dynamodb:Query"],
|
||||
"Resource":"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
|
||||
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
|
||||
"Condition":{"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]},
|
||||
"Null":{"dynamodb:LeadingKeys":"false"}}}
|
||||
]}""";
|
||||
|
||||
@Test
|
||||
@@ -234,7 +235,7 @@ class IamEnforcementIntegrationTest {
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
|
||||
Map.of("dynamodb:LeadingKeys", List.of("USER_bob"))));
|
||||
|
||||
// The leading key could not be resolved from the request: fail closed.
|
||||
// Null:false requires a leading key even though ForAllValues alone would match.
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
|
||||
List.of(LEADING_KEYS_SCOPED_POLICY), "dynamodb:GetItem",
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable",
|
||||
|
||||
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -421,6 +422,51 @@ class IamIntegrationTest {
|
||||
equalTo("implicitDeny"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"ForAllValues:StringLike, allowed",
|
||||
"ForAllValues:StringNotLike, allowed",
|
||||
"ForAnyValue:StringLike, implicitDeny",
|
||||
"ForAnyValue:StringNotLike, implicitDeny"
|
||||
})
|
||||
void simulateCustomPolicyUsesSetOperatorSemanticsForMissingKeys(String operator, String decision) {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
|
||||
"Condition":{"%s":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
|
||||
]}""".formatted(operator);
|
||||
given()
|
||||
.formParam("Action", "SimulateCustomPolicy")
|
||||
.formParam("PolicyInputList.member.1", policy)
|
||||
.formParam("ActionNames.member.1", "dynamodb:GetItem")
|
||||
.formParam("ResourceArns.member.1", "*")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults.member.EvalDecision",
|
||||
equalTo(decision));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ForAllValues:StringTypoIfExists", "ForAnyValue:StringTypoIfExists",
|
||||
"StringTypoIfExists", "ForAllValues:Null", "ForAnyValue:Null", "NullIfExists",
|
||||
"ForAllValues:NullIfExists", "ForAnyValue:NullIfExists"})
|
||||
void simulateCustomPolicyRejectsUnsupportedMissingKeyShortcuts(String operator) {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
|
||||
"Condition":{"%s":{"dynamodb:LeadingKeys":["true"]}}}
|
||||
]}""".formatted(operator);
|
||||
given()
|
||||
.formParam("Action", "SimulateCustomPolicy")
|
||||
.formParam("PolicyInputList.member.1", policy)
|
||||
.formParam("ActionNames.member.1", "dynamodb:GetItem")
|
||||
.formParam("ResourceArns.member.1", "*")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("SimulateCustomPolicyResponse.SimulateCustomPolicyResult.EvaluationResults.member.EvalDecision",
|
||||
equalTo("implicitDeny"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(37)
|
||||
void simulateCustomPolicyAppliesPermissionsBoundary() {
|
||||
|
||||
@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccoun
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
@@ -396,11 +398,81 @@ class IamPolicyEvaluatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void setOperatorWithoutIfExistsFailsClosedWhenTheKeyIsAbsent() {
|
||||
// The key is absent from the context entirely — not an empty set. A request that
|
||||
// cannot be proven in scope is treated as out of scope.
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
|
||||
void forAllValuesMatchesWhenTheKeyIsAbsent() {
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
|
||||
List.of(LEADING_KEYS_FOR_ALL), "dynamodb:GetItem", "*", Map.of()));
|
||||
assertEquals(Decision.ALLOW, evaluator.evaluate(CallerContext.of(List.of(LEADING_KEYS_FOR_ALL)),
|
||||
List.of(), "dynamodb:GetItem", "*", Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void forAllValuesExplicitDenyMatchesWhenTheKeyIsAbsent() {
|
||||
String deny = LEADING_KEYS_FOR_ALL.replace("\"Effect\":\"Allow\"", "\"Effect\":\"Deny\"");
|
||||
assertEquals(Decision.DENY, evaluator.evaluate(CallerContext.of(List.of(ALLOW_ALL, deny)),
|
||||
List.of(), "dynamodb:GetItem", "*", Map.of()));
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.EXPLICIT_DENY, evaluator.simulatePrincipalPolicy(
|
||||
CallerContext.of(List.of(ALLOW_ALL, deny)), "dynamodb:GetItem", "*", Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void forAllValuesMissingKeyStillRequiresOtherConditionKeysToMatch() {
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
|
||||
"Condition":{"ForAllValues:StringLike":{
|
||||
"dynamodb:LeadingKeys":["USER_alice*"],"aws:TagKeys":["environment"]}}}
|
||||
]}""";
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "dynamodb:GetItem", "*",
|
||||
Map.of("aws:TagKeys", List.of("unapproved"))));
|
||||
assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), "dynamodb:GetItem", "*",
|
||||
Map.of("aws:TagKeys", List.of("environment"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownForAllValuesOperatorsDoNotMatchMissingKeys() {
|
||||
for (String operator : List.of("ForAllValues:StringTypo", "ForAllValues:ForAnyValue:StringLike")) {
|
||||
String allow = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
|
||||
"Condition":{"%s":{"dynamodb:LeadingKeys":["USER_alice*"]}}}
|
||||
]}""".formatted(operator);
|
||||
String deny = allow.replace("\"Effect\":\"Allow\"", "\"Effect\":\"Deny\"");
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
|
||||
List.of(allow), "dynamodb:GetItem", "*", Map.of()));
|
||||
assertEquals(Decision.DENY, evaluator.evaluate(CallerContext.of(List.of(allow)),
|
||||
List.of(), "dynamodb:GetItem", "*", Map.of()));
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.ALLOWED, evaluator.simulatePrincipalPolicy(
|
||||
CallerContext.of(List.of(ALLOW_ALL, deny)), "dynamodb:GetItem", "*", Map.of()));
|
||||
assertEquals(Decision.ALLOW, evaluator.evaluate(CallerContext.of(List.of(ALLOW_ALL, deny)),
|
||||
List.of(), "dynamodb:GetItem", "*", Map.of()));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ForAllValues:StringTypoIfExists", "ForAnyValue:StringTypoIfExists",
|
||||
"StringTypoIfExists", "ForAllValues:Null", "ForAnyValue:Null", "NullIfExists",
|
||||
"ForAllValues:NullIfExists", "ForAnyValue:NullIfExists"})
|
||||
void unsupportedOperatorsCannotBypassConditionChecks(String operator) {
|
||||
String allow = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
|
||||
"Condition":{"%s":{"dynamodb:LeadingKeys":["true"]}}}
|
||||
]}""".formatted(operator);
|
||||
String deny = allow.replace("\"Effect\":\"Allow\"", "\"Effect\":\"Deny\"");
|
||||
List<Map<String, List<String>>> contexts = List.of(Map.of(),
|
||||
Map.of("dynamodb:LeadingKeys", List.of()),
|
||||
Map.of("dynamodb:LeadingKeys", List.of("USER_alice")));
|
||||
for (Map<String, List<String>> context : contexts) {
|
||||
assertFalse(IamPolicyEvaluator.isSupportedConditionOperator(operator));
|
||||
assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
|
||||
List.of(allow), "dynamodb:GetItem", "*", context));
|
||||
assertEquals(Decision.DENY, evaluator.evaluate(CallerContext.of(List.of(allow)),
|
||||
List.of(), "dynamodb:GetItem", "*", context));
|
||||
assertEquals(IamPolicyEvaluator.SimulationDecision.ALLOWED, evaluator.simulatePrincipalPolicy(
|
||||
CallerContext.of(List.of(ALLOW_ALL, deny)), "dynamodb:GetItem", "*", context));
|
||||
assertEquals(Decision.ALLOW, evaluator.evaluate(CallerContext.of(List.of(ALLOW_ALL, deny)),
|
||||
List.of(), "dynamodb:GetItem", "*", context));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -426,7 +498,7 @@ class IamPolicyEvaluatorTest {
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*",
|
||||
"Condition":{
|
||||
"ForAllValues:StringLikeIfExists":{"dynamodb:LeadingKeys":["USER_alice*"]},
|
||||
"ForAllValues:StringLike":{"dynamodb:LeadingKeys":["USER_alice*"]},
|
||||
"Null":{"dynamodb:LeadingKeys":"false"}}}
|
||||
]}""";
|
||||
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
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 org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.createUser;
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.removeBucket;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class IamTagKeysEnforcementIntegrationTest {
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@Test
|
||||
void ec2CreateTagsRejectsAnUnlistedKeyWithoutNullGuard() {
|
||||
String id = given().header("Authorization", auth("test", "ec2"))
|
||||
.formParam("Action", "CreateVpc").formParam("CidrBlock", "10.89.0.0/16")
|
||||
.post("/").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
|
||||
int port = endpoint.getPort();
|
||||
cleanup.register(() -> given().port(port).header("Authorization", auth("test", "ec2"))
|
||||
.formParam("Action", "DeleteVpc").formParam("VpcId", id).post("/"));
|
||||
String key = scopedUser("ec2:CreateTags", "aws:TagKeys");
|
||||
given().header("Authorization", auth(key, "ec2"))
|
||||
.formParam("Action", "CreateTags").formParam("ResourceId.1", id)
|
||||
.formParam("Tag.1.Key", "Team").formParam("Tag.1.Value", "payments")
|
||||
.post("/").then().statusCode(200);
|
||||
given().header("Authorization", auth(key, "ec2"))
|
||||
.formParam("Action", "CreateTags").formParam("ResourceId.1", id)
|
||||
.formParam("Tag.1.Key", "Team").formParam("Tag.1.Value", "payments")
|
||||
.formParam("Tag.2.Key", "Admin").formParam("Tag.2.Value", "true")
|
||||
.post("/").then().statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3BucketTaggingRejectsAnUnlistedKeyWithoutNullGuard() {
|
||||
String bucket = bucket();
|
||||
String key = scopedUser("s3:PutBucketTagging", "aws:TagKeys");
|
||||
String allowed = "<Tag><Key>Team</Key><Value>payments</Value></Tag>";
|
||||
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
|
||||
.body("<Tagging><TagSet>" + allowed + "</TagSet></Tagging>")
|
||||
.put("/" + bucket).then().statusCode(204);
|
||||
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
|
||||
.body("<Tagging><TagSet>" + allowed
|
||||
+ "<Tag><Key>Admin</Key><Value>true</Value></Tag></TagSet></Tagging>")
|
||||
.put("/" + bucket).then().statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Admin", "team"})
|
||||
void s3ObjectUploadRestrictsAllRequestedKeysWithoutNullGuard(String forbiddenKey) {
|
||||
String bucket = bucket();
|
||||
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
|
||||
String path = "/" + bucket + "/object";
|
||||
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "%54eam=payments")
|
||||
.body("original").put(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(key, "s3"))
|
||||
.header("x-amz-tagging", "Team=payments&" + forbiddenKey + "=true")
|
||||
.body("forbidden replacement").put(path).then().statusCode(403)
|
||||
.body(containsString("AccessDenied"));
|
||||
given().header("Authorization", auth("test", "s3")).get(path)
|
||||
.then().statusCode(200).body(equalTo("original"));
|
||||
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
|
||||
.then().statusCode(200).body(containsString("<Key>Team</Key>"))
|
||||
.body(not(containsString("<Key>" + forbiddenKey + "</Key>")));
|
||||
// No tags retain the vacuous ForAllValues match; there is no Null guard.
|
||||
given().header("Authorization", auth(key, "s3")).body("untagged").put(path)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Admin", "team"})
|
||||
void s3ObjectTaggingRestrictsAllRequestedKeysWithoutNullGuard(String forbiddenKey) {
|
||||
String bucket = bucket();
|
||||
String path = "/" + bucket + "/object";
|
||||
given().header("Authorization", auth("test", "s3")).body("original").put(path)
|
||||
.then().statusCode(200);
|
||||
String key = scopedUser("s3:PutObjectTagging", "s3:RequestObjectTagKeys");
|
||||
String allowed = "<Tag><Key>Team</Key><Value>payments</Value></Tag>";
|
||||
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
|
||||
.body("<Tagging><TagSet>" + allowed + "</TagSet></Tagging>")
|
||||
.put(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
|
||||
.body("<Tagging><TagSet>" + allowed + "<Tag><Key>" + forbiddenKey
|
||||
+ "</Key><Value>true</Value></Tag></TagSet></Tagging>")
|
||||
.put(path).then().statusCode(403).body(containsString("AccessDenied"));
|
||||
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
|
||||
.then().statusCode(200).body(containsString("<Key>Team</Key>"))
|
||||
.body(not(containsString("<Key>" + forbiddenKey + "</Key>")));
|
||||
// An empty tag set removes the tags and still matches ForAllValues.
|
||||
given().header("Authorization", auth(key, "s3")).queryParam("tagging", "")
|
||||
.body("<Tagging><TagSet/></Tagging>").put(path).then().statusCode(200);
|
||||
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
|
||||
.then().statusCode(200).body(not(containsString("<Key>Team</Key>")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Admin", "team"})
|
||||
void s3QueryTagKeysAreCheckedBeforeAnUpload(String forbiddenKey) {
|
||||
String bucket = bucket();
|
||||
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
|
||||
String path = "/" + bucket + "/object";
|
||||
given().header("Authorization", auth(key, "s3")).queryParam("x-amz-tagging", "%54eam=payments")
|
||||
.body("original").put(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(key, "s3"))
|
||||
.queryParam("x-amz-tagging", "Team=payments&" + forbiddenKey + "=true")
|
||||
.body("forbidden").put(path).then().statusCode(403);
|
||||
given().header("Authorization", auth("test", "s3")).get(path)
|
||||
.then().statusCode(200).body(equalTo("original"));
|
||||
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
|
||||
.then().statusCode(200).body(containsString("<Key>Team</Key>"))
|
||||
.body(not(containsString("<Key>" + forbiddenKey + "</Key>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3TagHeaderTakesPrecedenceOverTheQuery() {
|
||||
String bucket = bucket();
|
||||
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
|
||||
String path = "/" + bucket + "/object";
|
||||
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "Team=payments")
|
||||
.queryParam("x-amz-tagging", "Admin=true").body("original").put(path).then().statusCode(200);
|
||||
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "Admin=true")
|
||||
.queryParam("x-amz-tagging", "Team=payments").body("forbidden").put(path).then().statusCode(403);
|
||||
given().header("Authorization", auth("test", "s3")).get(path)
|
||||
.then().statusCode(200).body(equalTo("original"));
|
||||
given().header("Authorization", auth("test", "s3")).queryParam("tagging", "").get(path)
|
||||
.then().statusCode(200).body(containsString("<Key>Team</Key>"))
|
||||
.body(not(containsString("<Key>Admin</Key>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalUploadCannotUseRequestedKeysToGrantReadAccess() {
|
||||
String bucket = bucket();
|
||||
String path = "/" + bucket + "/object";
|
||||
String etag = given().header("Authorization", auth("test", "s3")).body("original")
|
||||
.put(path).then().statusCode(200).extract().header("ETag");
|
||||
String key = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"},
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
|
||||
"Condition":{"ForAnyValue:StringEquals":{"s3:RequestObjectTagKeys":["Team"]}}}]}
|
||||
""");
|
||||
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "Team=payments")
|
||||
.header("If-Match", etag).body("forbidden").put(path).then().statusCode(403);
|
||||
given().header("Authorization", auth("test", "s3")).get(path)
|
||||
.then().statusCode(200).body(equalTo("original"));
|
||||
String allowedKey = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":["s3:PutObject","s3:GetObject"],"Resource":"*"}]}
|
||||
""");
|
||||
given().header("Authorization", auth(allowedKey, "s3")).header("x-amz-tagging", "Team=payments")
|
||||
.header("If-Match", etag).body("allowed").put(path).then().statusCode(200);
|
||||
given().header("Authorization", auth("test", "s3")).get(path)
|
||||
.then().statusCode(200).body(equalTo("allowed"));
|
||||
}
|
||||
|
||||
private String bucket() {
|
||||
String bucket = "tagkeys-" + UUID.randomUUID();
|
||||
int port = endpoint.getPort();
|
||||
cleanup.register(() -> removeBucket(port, auth("test", "s3"), bucket));
|
||||
given().header("Authorization", auth("test", "s3")).put("/" + bucket).then().statusCode(200);
|
||||
return bucket;
|
||||
}
|
||||
|
||||
private String scopedUser(String action, String conditionKey) {
|
||||
return userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"%s",
|
||||
"Resource":"*","Condition":{"ForAllValues:StringEquals":{"%s":["Team"]}}}]}
|
||||
""".formatted(action, conditionKey));
|
||||
}
|
||||
|
||||
private String userWithPolicy(String policy) {
|
||||
String user = "tagkeys-" + UUID.randomUUID();
|
||||
String accessKey = createUser(cleanup, endpoint.getPort(), auth("test", "iam"), user).accessKeyId();
|
||||
given().header("Authorization", auth("test", "iam"))
|
||||
.formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "tags")
|
||||
.formParam("PolicyDocument", policy).post("/").then().statusCode(200);
|
||||
return accessKey;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user