feat(sns): support FilterPolicyScope=MessageBody (#863)

Parse the message body as JSON and evaluate the subscription filter
policy against the parsed tree, with nested-key descent and type-aware
rule matching (string/number/boolean/null values, array-value OR,
exists/prefix/anything-but/numeric). Previously the scope was accepted
but filtering was skipped, so all messages were delivered. Bodies that
are not valid JSON fail closed.

The body is parsed lazily once per publish, only when at least one
subscription uses MessageBody scope, to avoid O(N-subscriptions) parses.
The MessageAttributes scope evaluator is untouched.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-05-16 19:21:37 -05:00
1 parent 43ba8a73b0
commit 9a10f81fb7
3 files changed
+464 -9

No files matched your search

@@ -314,12 +314,18 @@ public class SnsService {
}
String messageId = UUID.randomUUID().toString();
JsonNode parsedBody = null;
boolean bodyParseAttempted = false;
for (Subscription sub : subscriptionsByTopic(effectiveArn, region)) {
if ("true".equals(sub.getAttributes().get("PendingConfirmation"))) {
LOG.debugv("Skipping delivery to pending subscription {0}", sub.getSubscriptionArn());
continue;
}
if (!matchesFilterPolicy(sub, messageAttributes)) {
if (!bodyParseAttempted && isMessageBodyScope(sub)) {
parsedBody = tryParseBody(message);
bodyParseAttempted = true;
}
if (!matchesFilterPolicy(sub, parsedBody, messageAttributes)) {
continue;
}
deliverMessage(sub, message, subject, messageAttributes, messageId, effectiveArn, messageGroupId, dedupId);
@@ -408,9 +414,15 @@ public class SnsService {
String messageId = UUID.randomUUID().toString();
@SuppressWarnings("unchecked")
Map<String, MessageAttributeValue> attrs = (Map<String, MessageAttributeValue>) entry.get("MessageAttributes");
JsonNode parsedBody = null;
boolean bodyParseAttempted = false;
for (Subscription sub : subscriptionsByTopic(topicArn, region)) {
if ("true".equals(sub.getAttributes().get("PendingConfirmation"))) continue;
if (!matchesFilterPolicy(sub, attrs)) continue;
if (!bodyParseAttempted && isMessageBodyScope(sub)) {
parsedBody = tryParseBody(message);
bodyParseAttempted = true;
}
if (!matchesFilterPolicy(sub, parsedBody, attrs)) continue;
deliverMessage(sub, message, subject, attrs, messageId, topicArn, messageGroupId, messageDeduplicationId);
}
LOG.debugv("Batch published message {0} (id={1}) to {2}", messageId, id, topicArn);
@@ -450,28 +462,69 @@ public class SnsService {
* Returns {@code true} if no filter policy is set.
* Returns {@code false} for malformed filter policies (fail closed).
* <p>
* Only {@code FilterPolicyScope=MessageAttributes} is supported. When scope is
* {@code MessageBody}, filtering is skipped and the message is delivered (to avoid
* incorrectly dropping messages for an unsupported scope).
* {@code FilterPolicyScope=MessageAttributes} (default) evaluates the policy against
* the message attribute map. {@code FilterPolicyScope=MessageBody} parses the message
* body as JSON and evaluates the policy against the parsed tree (with nested-key
* descent and type-aware matching). A body that is not valid JSON fails closed.
* <p>
* All keys in the policy must match (AND logic). Within each key's rule array,
* any matching element is sufficient (OR logic).
*/
private boolean matchesFilterPolicy(Subscription sub, Map<String, MessageAttributeValue> messageAttributes) {
private static boolean isMessageBodyScope(Subscription sub) {
return "MessageBody".equals(
sub.getAttributes().getOrDefault("FilterPolicyScope", "MessageAttributes"));
}
/**
* Per AWS SNS docs, {@code exists:true} requires the key to have a non-null and
* non-empty value. Empty strings, empty arrays, and empty objects do not count as
* "exists". Numbers and booleans are always considered non-empty.
*/
private static boolean isNonEmptyValue(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) {
return false;
}
if (node.isTextual()) {
return !node.asText().isEmpty();
}
if (node.isContainerNode()) {
return !node.isEmpty();
}
return true;
}
private JsonNode tryParseBody(String message) {
if (message == null || message.isEmpty()) {
return null;
}
try {
return objectMapper.readTree(message);
} catch (Exception e) {
return null;
}
}
boolean matchesFilterPolicy(Subscription sub, JsonNode parsedBody,
Map<String, MessageAttributeValue> messageAttributes) {
String filterPolicyJson = sub.getAttributes().get("FilterPolicy");
if (filterPolicyJson == null || filterPolicyJson.isBlank()) {
return true;
}
String scope = sub.getAttributes().getOrDefault("FilterPolicyScope", "MessageAttributes");
if ("MessageBody".equals(scope)) {
return true;
}
try {
JsonNode filterPolicy = objectMapper.readTree(filterPolicyJson);
if (!filterPolicy.isObject()) {
LOG.warnv("Invalid FilterPolicy (not a JSON object) for {0}", sub.getSubscriptionArn());
return false;
}
if ("MessageBody".equals(scope)) {
if (parsedBody == null) {
LOG.debugv("FilterPolicyScope=MessageBody but body is not valid JSON for {0}; not delivering",
sub.getSubscriptionArn());
return false;
}
return matchesBodyPolicy(filterPolicy, parsedBody);
}
Map<String, MessageAttributeValue> attrs = messageAttributes != null ? messageAttributes : Map.of();
var fields = filterPolicy.fields();
while (fields.hasNext()) {
@@ -491,6 +544,137 @@ public class SnsService {
}
}
/**
* Evaluates a filter policy object against a parsed JSON body. Each policy key must
* match (AND); a key's value is either a rule array (terminal) or an object (nested
* descent into the body at the same key).
*/
private boolean matchesBodyPolicy(JsonNode policy, JsonNode body) {
if (!policy.isObject()) {
return false;
}
var fields = policy.fields();
while (fields.hasNext()) {
var entry = fields.next();
String key = entry.getKey();
JsonNode ruleOrNested = entry.getValue();
JsonNode bodyValue = (body != null && body.isObject()) ? body.get(key) : null;
if (ruleOrNested.isArray()) {
if (!matchesBodyRules(bodyValue, ruleOrNested)) {
return false;
}
} else if (ruleOrNested.isObject()) {
if (!matchesBodyPolicy(ruleOrNested, bodyValue)) {
return false;
}
} else {
return false;
}
}
return true;
}
/**
* Evaluates a rule array against a body value. When the body value is itself an array,
* the rules are applied to each element (OR over elements), with {@code exists:true}
* additionally matching the array as a whole.
*/
private boolean matchesBodyRules(JsonNode actual, JsonNode rules) {
if (!rules.isArray()) {
return false;
}
if (actual != null && actual.isArray()) {
boolean nonEmpty = !actual.isEmpty();
for (JsonNode rule : rules) {
if (rule.isObject() && rule.has("exists")) {
if (rule.get("exists").asBoolean() == nonEmpty) {
return true;
}
} else {
for (JsonNode element : actual) {
if (matchesSingleBodyRule(element, rule)) {
return true;
}
}
}
}
return false;
}
for (JsonNode rule : rules) {
if (matchesSingleBodyRule(actual, rule)) {
return true;
}
}
return false;
}
private boolean matchesSingleBodyRule(JsonNode actual, JsonNode rule) {
if (rule.isTextual()) {
return actual != null && actual.isTextual() && rule.asText().equals(actual.asText());
}
if (rule.isNumber()) {
if (actual == null || !actual.isNumber()) {
return false;
}
try {
return new BigDecimal(actual.asText()).compareTo(rule.decimalValue()) == 0;
} catch (NumberFormatException e) {
return false;
}
}
if (rule.isBoolean()) {
return actual != null && actual.isBoolean() && rule.booleanValue() == actual.booleanValue();
}
if (rule.isNull()) {
return actual != null && actual.isNull();
}
if (rule.isObject()) {
return matchesObjectRuleForNode(rule, actual);
}
return false;
}
private boolean matchesObjectRuleForNode(JsonNode rule, JsonNode actual) {
if (rule.has("exists")) {
return rule.get("exists").asBoolean() == isNonEmptyValue(actual);
}
boolean present = actual != null && !actual.isMissingNode() && !actual.isNull();
String stringValue = present && actual.isTextual() ? actual.asText() : null;
if (rule.has("prefix")) {
return stringValue != null && stringValue.startsWith(rule.get("prefix").asText());
}
if (rule.has("anything-but")) {
return matchesAnythingButForNode(rule.get("anything-but"), actual, stringValue, present);
}
if (rule.has("numeric") && present && actual.isNumber()) {
return evaluateNumericCondition(actual.decimalValue(), rule.get("numeric"));
}
return false;
}
private boolean matchesAnythingButForNode(JsonNode anythingBut, JsonNode actual,
String stringValue, boolean present) {
if (!present) {
return false;
}
if (anythingBut.isArray()) {
for (JsonNode v : anythingBut) {
if (v.isTextual() && stringValue != null && v.asText().equals(stringValue)) {
return false;
}
if (v.isNumber() && actual.isNumber()
&& actual.decimalValue().compareTo(v.decimalValue()) == 0) {
return false;
}
}
return true;
}
if (anythingBut.isTextual()) {
return stringValue == null || !stringValue.equals(anythingBut.asText());
}
return false;
}
/**
* Checks if an attribute value matches a single filter policy rule set.
* Rules must be a JSON array where ANY element matching means the rule passes (OR logic).