mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -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
+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.
|
||||
|
||||
Reference in new issue
Block a user