fix(iam): resolve DynamoDB table ARN from request body for IAM enforcement (#2928)

* fix(iam): resolve DynamoDB table ARN from request body for IAM enforcement (#2925)

* fix(iam): evaluate multi-table DynamoDB batch and transact requests per table

* fix(iam): support table ARN resolution for DynamoDB PartiQL statements

* fix(iam): handle quoted PartiQL table names with special characters

* fix(iam): use DynamoDbPartiQLParser to extract table from PartiQL statements
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-02 18:06:55 -04:00
1 parent cf628ba2b9
commit 3db883d003
6 files changed
+761 -41

No files matched your search

@@ -169,7 +169,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
caller = caller.withScpLevels(scpLevels);
}
String resource = arnBuilder.build(credentialScope, ctx, region, accountId);
List<String> resources = arnBuilder.buildResources(credentialScope, ctx, region, accountId);
Map<String, String> conditionContext = conditionContextResolver.resolve(credentialScope, action, ctx);
@@ -187,15 +187,18 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
conditionContext.put("aws:PrincipalArn", principalArn.get());
}
Decision decision = evaluator.evaluate(caller, null, action, resource, conditionContext);
if (decision == Decision.DENY) {
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
String denyMessage = "User: arn:aws:iam::" + accountId
+ ":user/" + akid + " is not authorized to perform: " + action
+ " on resource: \"" + resource + "\""
+ " because no identity-based policy allows the " + action + " action";
emitS3DenialIfApplicable(akid, action, resource, ctx, region, denyMessage);
ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType()));
for (String resource : resources) {
Decision decision = evaluator.evaluate(caller, null, action, resource, conditionContext);
if (decision == Decision.DENY) {
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
String denyMessage = "User: arn:aws:iam::" + accountId
+ ":user/" + akid + " is not authorized to perform: " + action
+ " on resource: \"" + resource + "\""
+ " because no identity-based policy allows the " + action + " action";
emitS3DenialIfApplicable(akid, action, resource, ctx, region, denyMessage);
ctx.abortWith(accessDeniedResponse(action, credentialScope, ctx.getMediaType()));
return;
}
}
}
@@ -5,7 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import java.util.*;
class DynamoDbPartiQLParser {
public class DynamoDbPartiQLParser {
enum TType {
SELECT, FROM, WHERE, INSERT, INTO, VALUE,
@@ -20,13 +20,44 @@ class DynamoDbPartiQLParser {
// --- AST node types ---
sealed interface Stmt permits Stmt.Select, Stmt.Insert, Stmt.Update, Stmt.Delete {
public sealed interface Stmt permits Stmt.Select, Stmt.Insert, Stmt.Update, Stmt.Delete {
String table();
record Select(String table, List<String> columns, List<Cond> where) implements Stmt {}
record Insert(String table, Map<String, PVal> item) implements Stmt {}
record Update(String table, List<Assign> sets, List<String> removes, List<Cond> where) implements Stmt {}
record Delete(String table, List<Cond> where) implements Stmt {}
}
/**
* Extracts the target table name from a PartiQL statement using the parser tokenizer,
* ensuring quoted attribute names containing SQL keywords are not mistakenly treated as table names.
*/
public static String extractTable(String statement) {
if (statement == null || statement.isBlank()) {
return null;
}
try {
return parse(statement, List.of()).table();
} catch (Exception e) {
try {
List<Token> tokens = tokenize(statement.trim());
for (int i = 0; i < tokens.size(); i++) {
Token t = tokens.get(i);
if (t.type() == TType.FROM || t.type() == TType.INTO || t.type() == TType.UPDATE) {
if (i + 1 < tokens.size()) {
Token next = tokens.get(i + 1);
if (next.type() == TType.IDENT || next.type() == TType.STRING) {
return next.value();
}
}
}
}
} catch (Exception ignored) {
}
return null;
}
}
sealed interface PVal permits PVal.Str, PVal.Num, PVal.Bool, PVal.Null {
record Str(String v) implements PVal {}
record Num(String v) implements PVal {}
@@ -1,9 +1,20 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Constructs the target resource ARN for a request so the policy evaluator
* can match it against Resource patterns in policy documents.
@@ -14,20 +25,40 @@ import jakarta.ws.rs.container.ContainerRequestContext;
@ApplicationScoped
public class ResourceArnBuilder {
private final ObjectMapper objectMapper;
@Inject
public ResourceArnBuilder(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public ResourceArnBuilder() {
this(new ObjectMapper());
}
public String build(String credentialScope, ContainerRequestContext ctx,
String region, String accountId) {
List<String> list = buildResources(credentialScope, ctx, region, accountId);
return list.isEmpty() ? "*" : list.getFirst();
}
public List<String> buildResources(String credentialScope, ContainerRequestContext ctx,
String region, String accountId) {
if (credentialScope == null) {
return List.of("*");
}
String path = ctx.getUriInfo().getPath();
return switch (credentialScope) {
case "s3" -> buildS3Arn(path);
case "lambda" -> buildLambdaArn(path, region, accountId);
case "sqs" -> buildSqsArn(ctx, region, accountId);
case "sns" -> buildSnsArn(ctx, region, accountId);
case "dynamodb" -> buildDynamoDbArn(ctx, region, accountId);
case "kinesis" -> buildKinesisArn(ctx, region, accountId);
case "secretsmanager" -> buildSecretsManagerArn(ctx, region, accountId);
case "ssm" -> buildSsmArn(ctx, region, accountId);
case "kms" -> buildKmsArn(path, region, accountId);
default -> "*";
case "s3" -> List.of(buildS3Arn(path));
case "lambda" -> List.of(buildLambdaArn(path, region, accountId));
case "sqs" -> List.of(buildSqsArn(ctx, region, accountId));
case "sns" -> List.of(buildSnsArn(ctx, region, accountId));
case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId);
case "kinesis" -> List.of(buildKinesisArn(ctx, region, accountId));
case "secretsmanager" -> List.of(buildSecretsManagerArn(ctx, region, accountId));
case "ssm" -> List.of(buildSsmArn(ctx, region, accountId));
case "kms" -> List.of(buildKmsArn(path, region, accountId));
default -> List.of("*");
};
}
@@ -63,7 +94,20 @@ public class ResourceArnBuilder {
// Try form param for Query-protocol
queueUrl = firstFormParam(ctx, "QueueUrl");
}
if (queueUrl != null) {
if (queueUrl == null) {
JsonNode json = readJsonBody(ctx);
if (json != null && json.isObject()) {
if (json.hasNonNull("QueueUrl")) {
queueUrl = json.get("QueueUrl").asText().trim();
} else if (json.hasNonNull("QueueName")) {
String queueName = json.get("QueueName").asText().trim();
if (!queueName.isEmpty()) {
return AwsArnUtils.Arn.of("sqs", region, accountId, queueName).toString();
}
}
}
}
if (queueUrl != null && !queueUrl.isEmpty()) {
String queueName = queueUrl.substring(queueUrl.lastIndexOf('/') + 1);
return AwsArnUtils.Arn.of("sqs", region, accountId, queueName).toString();
}
@@ -73,27 +117,207 @@ public class ResourceArnBuilder {
// ── SNS ─────────────────────────────────────────────────────────────────────
private String buildSnsArn(ContainerRequestContext ctx, String region, String accountId) {
String topicArn = firstFormParam(ctx, "TopicArn");
return topicArn != null ? topicArn : AwsArnUtils.Arn.of("sns", region, accountId, "*").toString();
if (topicArn == null) {
JsonNode json = readJsonBody(ctx);
if (json != null && json.isObject() && json.hasNonNull("TopicArn")) {
topicArn = json.get("TopicArn").asText().trim();
}
}
return (topicArn != null && !topicArn.isEmpty())
? topicArn
: AwsArnUtils.Arn.of("sns", region, accountId, "*").toString();
}
// ── DynamoDB ─────────────────────────────────────────────────────────────────
private String buildDynamoDbArn(ContainerRequestContext ctx, String region, String accountId) {
// TableName comes in the JSON body; use wildcard since we don't parse the body here
return AwsArnUtils.Arn.of("dynamodb", region, accountId, "table/*").toString();
List<String> arns = buildDynamoDbArns(ctx, region, accountId);
return arns.isEmpty() ? "*" : arns.getFirst();
}
private List<String> buildDynamoDbArns(ContainerRequestContext ctx, String region, String accountId) {
JsonNode json = readJsonBody(ctx);
if (json != null && json.isObject()) {
if (json.hasNonNull("TableName")) {
String tableName = json.get("TableName").asText().trim();
if (!tableName.isEmpty()) {
return List.of(toDynamoDbTableArn(tableName, region, accountId));
}
}
if (json.hasNonNull("ResourceArn")) {
String resourceArn = json.get("ResourceArn").asText().trim();
if (!resourceArn.isEmpty()) {
return List.of(resourceArn);
}
}
if (json.hasNonNull("TableArn")) {
String tableArn = json.get("TableArn").asText().trim();
if (!tableArn.isEmpty()) {
return List.of(tableArn);
}
}
if (json.hasNonNull("StreamArn")) {
String streamArn = json.get("StreamArn").asText().trim();
if (!streamArn.isEmpty()) {
return List.of(streamArn);
}
}
if (json.hasNonNull("ExportArn")) {
String exportArn = json.get("ExportArn").asText().trim();
if (!exportArn.isEmpty()) {
return List.of(exportArn);
}
}
if (json.hasNonNull("RequestItems") && json.get("RequestItems").isObject()) {
Set<String> arns = new LinkedHashSet<>();
var fieldNames = json.get("RequestItems").fieldNames();
while (fieldNames.hasNext()) {
String table = fieldNames.next().trim();
if (!table.isEmpty()) {
arns.add(toDynamoDbTableArn(table, region, accountId));
}
}
if (!arns.isEmpty()) {
return new ArrayList<>(arns);
}
}
if (json.hasNonNull("TransactItems") && json.get("TransactItems").isArray()) {
Set<String> arns = new LinkedHashSet<>();
JsonNode items = json.get("TransactItems");
for (JsonNode item : items) {
String t = null;
if (item.hasNonNull("Put") && item.get("Put").hasNonNull("TableName")) {
t = item.get("Put").get("TableName").asText();
} else if (item.hasNonNull("Delete") && item.get("Delete").hasNonNull("TableName")) {
t = item.get("Delete").get("TableName").asText();
} else if (item.hasNonNull("Update") && item.get("Update").hasNonNull("TableName")) {
t = item.get("Update").get("TableName").asText();
} else if (item.hasNonNull("ConditionCheck") && item.get("ConditionCheck").hasNonNull("TableName")) {
t = item.get("ConditionCheck").get("TableName").asText();
} else if (item.hasNonNull("Get") && item.get("Get").hasNonNull("TableName")) {
t = item.get("Get").get("TableName").asText();
}
if (t != null) {
t = t.trim();
if (!t.isEmpty()) {
arns.add(toDynamoDbTableArn(t, region, accountId));
}
}
}
if (!arns.isEmpty()) {
return new ArrayList<>(arns);
}
}
if (json.hasNonNull("Statement")) {
String stmt = json.get("Statement").asText().trim();
String table = extractDynamoDbTableFromPartiQL(stmt);
if (table != null && !table.isEmpty()) {
return List.of(toDynamoDbTableArn(table, region, accountId));
}
}
if (json.hasNonNull("Statements") && json.get("Statements").isArray()) {
Set<String> arns = new LinkedHashSet<>();
for (JsonNode s : json.get("Statements")) {
if (s.hasNonNull("Statement")) {
String table = extractDynamoDbTableFromPartiQL(s.get("Statement").asText());
if (table != null && !table.isEmpty()) {
arns.add(toDynamoDbTableArn(table, region, accountId));
}
}
}
if (!arns.isEmpty()) {
return new ArrayList<>(arns);
}
}
if (json.hasNonNull("TransactStatements") && json.get("TransactStatements").isArray()) {
Set<String> arns = new LinkedHashSet<>();
for (JsonNode s : json.get("TransactStatements")) {
if (s.hasNonNull("Statement")) {
String table = extractDynamoDbTableFromPartiQL(s.get("Statement").asText());
if (table != null && !table.isEmpty()) {
arns.add(toDynamoDbTableArn(table, region, accountId));
}
}
}
if (!arns.isEmpty()) {
return new ArrayList<>(arns);
}
}
}
return List.of("*");
}
private static String extractDynamoDbTableFromPartiQL(String statement) {
return io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser.extractTable(statement);
}
private String toDynamoDbTableArn(String tableName, String region, String accountId) {
if (tableName.startsWith("arn:aws:dynamodb:")) {
return tableName;
}
return AwsArnUtils.Arn.of("dynamodb", region, accountId, "table/" + tableName).toString();
}
// ── Kinesis ──────────────────────────────────────────────────────────────────
private String buildKinesisArn(ContainerRequestContext ctx, String region, String accountId) {
JsonNode json = readJsonBody(ctx);
if (json != null && json.isObject()) {
if (json.hasNonNull("StreamARN")) {
String streamArn = json.get("StreamARN").asText().trim();
if (!streamArn.isEmpty()) {
return streamArn;
}
}
if (json.hasNonNull("StreamName")) {
String streamName = json.get("StreamName").asText().trim();
if (!streamName.isEmpty()) {
if (streamName.startsWith("arn:aws:kinesis:")) {
return streamName;
}
return AwsArnUtils.Arn.of("kinesis", region, accountId, "stream/" + streamName).toString();
}
}
if (json.hasNonNull("ResourceARN")) {
String resourceArn = json.get("ResourceARN").asText().trim();
if (!resourceArn.isEmpty()) {
return resourceArn;
}
}
}
return AwsArnUtils.Arn.of("kinesis", region, accountId, "stream/*").toString();
}
// ── Secrets Manager ──────────────────────────────────────────────────────────
private String buildSecretsManagerArn(ContainerRequestContext ctx, String region, String accountId) {
JsonNode json = readJsonBody(ctx);
if (json != null && json.isObject()) {
if (json.hasNonNull("SecretId")) {
String secretId = json.get("SecretId").asText().trim();
if (!secretId.isEmpty()) {
if (secretId.startsWith("arn:aws:secretsmanager:")) {
return secretId;
}
return AwsArnUtils.Arn.of("secretsmanager", region, accountId, "secret:" + secretId).toString();
}
}
}
return AwsArnUtils.Arn.of("secretsmanager", region, accountId, "secret:*").toString();
}
// ── SSM ──────────────────────────────────────────────────────────────────────
private String buildSsmArn(ContainerRequestContext ctx, String region, String accountId) {
JsonNode json = readJsonBody(ctx);
if (json != null && json.isObject()) {
if (json.hasNonNull("Name")) {
String name = json.get("Name").asText().trim();
if (!name.isEmpty()) {
if (name.startsWith("arn:aws:ssm:")) {
return name;
}
String paramResource = name.startsWith("/") ? "parameter" + name : "parameter/" + name;
return AwsArnUtils.Arn.of("ssm", region, accountId, paramResource).toString();
}
}
}
return AwsArnUtils.Arn.of("ssm", region, accountId, "parameter/*").toString();
}
@@ -106,6 +330,35 @@ public class ResourceArnBuilder {
// ── Helpers ──────────────────────────────────────────────────────────────────
private JsonNode readJsonBody(ContainerRequestContext ctx) {
Object cached = ctx.getProperty("floci.bufferedJsonBody");
if (cached instanceof JsonNode node) {
return node;
}
InputStream in = ctx.getEntityStream();
if (in == null) {
return null;
}
byte[] body;
try {
body = in.readAllBytes();
} catch (IOException e) {
ctx.setEntityStream(new ByteArrayInputStream(new byte[0]));
return null;
}
ctx.setEntityStream(new ByteArrayInputStream(body));
if (body.length == 0) {
return null;
}
try {
JsonNode node = objectMapper.readTree(body);
ctx.setProperty("floci.bufferedJsonBody", node);
return node;
} catch (Exception e) {
return null;
}
}
private String extractSegmentAfter(String path, String segment) {
String marker = "/" + segment + "/";
int idx = path.indexOf(marker);