mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(sns): enforce FilterPolicy on message delivery (#53)
FilterPolicy subscription attribute was accepted and stored but never evaluated during publish. Messages were delivered to all confirmed subscriptions regardless of filter rules. Now evaluates filter policies supporting exact string matching, numeric comparisons, prefix matching, exists operator, and anything-but operator per SNS specification. Fixes #49
This commit is contained in:
1 parent
ccd630c3bf
commit
2f875d4169
2 files changed
+384
-1
No files matched your search
@@ -12,12 +12,14 @@ import io.github.hectorvent.floci.services.sns.model.Subscription;
|
||||
import io.github.hectorvent.floci.services.sns.model.Topic;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -291,6 +293,9 @@ public class SnsService {
|
||||
LOG.debugv("Skipping delivery to pending subscription {0}", sub.getSubscriptionArn());
|
||||
continue;
|
||||
}
|
||||
if (!matchesFilterPolicy(sub, messageAttributes)) {
|
||||
continue;
|
||||
}
|
||||
deliverMessage(sub, message, subject, messageAttributes, messageId, effectiveArn, messageGroupId);
|
||||
}
|
||||
LOG.infov("Published message {0} to topic {1}", messageId, effectiveArn);
|
||||
@@ -359,6 +364,7 @@ public class SnsService {
|
||||
Map<String, String> attrs = (Map<String, String>) entry.get("MessageAttributes");
|
||||
for (Subscription sub : subscriptionsByTopic(topicArn, region)) {
|
||||
if ("true".equals(sub.getAttributes().get("PendingConfirmation"))) continue;
|
||||
if (!matchesFilterPolicy(sub, attrs)) continue;
|
||||
deliverMessage(sub, message, subject, attrs, messageId, topicArn, messageGroupId);
|
||||
}
|
||||
LOG.debugv("Batch published message {0} (id={1}) to {2}", messageId, id, topicArn);
|
||||
@@ -393,6 +399,140 @@ public class SnsService {
|
||||
return new java.util.LinkedHashMap<>(topic.getTags());
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates whether a message satisfies the subscription's filter policy.
|
||||
* 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).
|
||||
* <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, String> 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;
|
||||
}
|
||||
Map<String, String> attrs = messageAttributes != null ? messageAttributes : Map.of();
|
||||
var fields = filterPolicy.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
String key = entry.getKey();
|
||||
JsonNode rules = entry.getValue();
|
||||
String actualValue = attrs.get(key);
|
||||
if (!matchesAttributeRules(actualValue, rules)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse filter policy for {0}: {1}", sub.getSubscriptionArn(), e.getMessage());
|
||||
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).
|
||||
* Non-array rules are treated as non-matching.
|
||||
*/
|
||||
private boolean matchesAttributeRules(String actualValue, JsonNode rules) {
|
||||
if (!rules.isArray()) {
|
||||
return false;
|
||||
}
|
||||
for (JsonNode rule : rules) {
|
||||
if (rule.isTextual() && rule.asText().equals(actualValue)) {
|
||||
return true;
|
||||
}
|
||||
if (rule.isNumber() && actualValue != null) {
|
||||
try {
|
||||
if (new BigDecimal(actualValue).compareTo(rule.decimalValue()) == 0) {
|
||||
return true;
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
if (rule.isObject() && matchesObjectRule(rule, actualValue)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates a single object-type filter rule (exists, prefix, anything-but, numeric)
|
||||
* against the actual attribute value.
|
||||
*/
|
||||
private boolean matchesObjectRule(JsonNode rule, String actualValue) {
|
||||
if (rule.has("exists")) {
|
||||
boolean shouldExist = rule.get("exists").asBoolean();
|
||||
return shouldExist ? actualValue != null : actualValue == null;
|
||||
}
|
||||
if (rule.has("prefix") && actualValue != null) {
|
||||
return actualValue.startsWith(rule.get("prefix").asText());
|
||||
}
|
||||
if (rule.has("anything-but") && actualValue != null) {
|
||||
return !containsValue(rule.get("anything-but"), actualValue);
|
||||
}
|
||||
if (rule.has("numeric") && actualValue != null) {
|
||||
try {
|
||||
return evaluateNumericCondition(new BigDecimal(actualValue), rule.get("numeric"));
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean containsValue(JsonNode node, String value) {
|
||||
if (node.isArray()) {
|
||||
for (JsonNode element : node) {
|
||||
if (element.asText().equals(value)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
LOG.warnv("FilterPolicy 'anything-but' expected an array but got a scalar; treating as single-value list");
|
||||
return node.asText().equals(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates a numeric condition array against a value.
|
||||
* The conditions array contains alternating operator-target pairs (e.g. [">=", 100, "<", 200]).
|
||||
* All pairs must match for the condition to pass (AND logic).
|
||||
*/
|
||||
private boolean evaluateNumericCondition(BigDecimal value, JsonNode conditions) {
|
||||
if (!conditions.isArray() || conditions.size() % 2 != 0) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < conditions.size(); i += 2) {
|
||||
String op = conditions.get(i).asText();
|
||||
BigDecimal target = conditions.get(i + 1).decimalValue();
|
||||
int cmp = value.compareTo(target);
|
||||
boolean matches = switch (op) {
|
||||
case "=" -> cmp == 0;
|
||||
case ">" -> cmp > 0;
|
||||
case ">=" -> cmp >= 0;
|
||||
case "<" -> cmp < 0;
|
||||
case "<=" -> cmp <= 0;
|
||||
default -> false;
|
||||
};
|
||||
if (!matches) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isDuplicate(String topicArn, String deduplicationId) {
|
||||
String cacheKey = topicArn + ":" + deduplicationId;
|
||||
Instant now = Instant.now();
|
||||
|
||||
Reference in new issue
Block a user