diff --git a/src/main/java/io/github/hectorvent/floci/core/common/XmlParser.java b/src/main/java/io/github/hectorvent/floci/core/common/XmlParser.java index 4ef4dd1a31..5ed1fa2881 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/XmlParser.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/XmlParser.java @@ -34,6 +34,41 @@ public final class XmlParser { private XmlParser() {} + /** + * Reads the text content of the current element if it is a leaf (contains only text). + * If the element contains nested child elements, the entire subtree is skipped + * and {@code null} is returned. + * + *

After this method returns, the reader is positioned on the END_ELEMENT + * of the element that was open when the method was called. + */ + private static String readLeafText(XMLStreamReader r) throws XMLStreamException { + StringBuilder sb = new StringBuilder(); + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) { + sb.append(r.getText()); + } else if (event == XMLStreamConstants.START_ELEMENT) { + // Not a leaf — skip the child subtree, then continue + // consuming until we reach our own END_ELEMENT. + // depth starts at 2: 1 for ourselves (the element readLeafText + // was called for) + 1 for the child START we just saw. + int depth = 2; + while (r.hasNext()) { + int e = r.next(); + if (e == XMLStreamConstants.START_ELEMENT) depth++; + else if (e == XMLStreamConstants.END_ELEMENT) { + if (--depth == 0) break; + } + } + return null; + } else if (event == XMLStreamConstants.END_ELEMENT) { + break; + } + } + return sb.toString(); + } + /** * Extracts the text content of every element whose local name matches {@code elementName}. * @@ -153,8 +188,10 @@ public final class XmlParser { current = new LinkedHashMap<>(); depth = 1; } else if (current != null && depth == 1) { - String text = r.getElementText(); - current.computeIfAbsent(local, k -> new ArrayList<>()).add(text); + String text = readLeafText(r); + if (text != null) { + current.computeIfAbsent(local, k -> new ArrayList<>()).add(text); + } } else if (current != null) { depth++; } @@ -201,8 +238,10 @@ public final class XmlParser { current = new LinkedHashMap<>(); depth = 1; } else if (current != null && depth == 1) { - String text = r.getElementText(); - current.put(local, text); + String text = readLeafText(r); + if (text != null) { + current.put(local, text); + } } else if (current != null) { depth++; } @@ -220,4 +259,60 @@ public final class XmlParser { } catch (XMLStreamException ignored) {} return result; } + + /** + * Extracts key/value pairs from a repeating {@code pairElement} nested at any depth + * inside each {@code parentElement} group, returning one map per group. + * + *

The outer list is index-aligned with the result of + * {@link #extractGroupsMulti(String, String)} for the same {@code parentElement}. + * + *

Example — extracts S3 notification filter rules: + *

{@code
+     * List> filters = XmlParser.extractPairsPerGroup(
+     *         body, "QueueConfiguration", "FilterRule", "Name", "Value");
+     * // filters.get(0) → {prefix=images/, suffix=.jpg}
+     * }
+ */ + public static List> extractPairsPerGroup( + String xml, String parentElement, + String pairElement, String keyElement, String valueElement) { + List> result = new ArrayList<>(); + if (xml == null || xml.isEmpty()) { + return result; + } + try { + XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml)); + Map current = null; + boolean inPair = false; + String pendingKey = null; + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + String local = r.getLocalName(); + if (parentElement.equals(local)) { + current = new LinkedHashMap<>(); + } else if (current != null && pairElement.equals(local)) { + inPair = true; + pendingKey = null; + } else if (inPair && keyElement.equals(local)) { + pendingKey = r.getElementText(); + } else if (inPair && valueElement.equals(local) && pendingKey != null) { + current.put(pendingKey, r.getElementText()); + pendingKey = null; + } + } else if (event == XMLStreamConstants.END_ELEMENT) { + String local = r.getLocalName(); + if (parentElement.equals(local) && current != null) { + result.add(current); + current = null; + } else if (pairElement.equals(local)) { + inPair = false; + } + } + } + r.close(); + } catch (XMLStreamException ignored) {} + return result; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index 2a7aa9d61a..6ac38f740c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.s3.model.Bucket; import io.github.hectorvent.floci.services.s3.model.GetObjectAttributesParts; import io.github.hectorvent.floci.services.s3.model.GetObjectAttributesResult; import io.github.hectorvent.floci.services.s3.model.MultipartUpload; +import io.github.hectorvent.floci.services.s3.model.FilterRule; import io.github.hectorvent.floci.services.s3.model.NotificationConfiguration; import io.github.hectorvent.floci.services.s3.model.ObjectAttributeName; import io.github.hectorvent.floci.services.s3.model.QueueNotification; @@ -30,6 +31,7 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; +import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; @@ -848,6 +850,7 @@ public class S3Controller { for (String event : qn.events()) { xml.elem("Event", event); } + appendFilterRules(xml, qn.filterRules()); xml.end("QueueConfiguration"); } for (TopicNotification tn : config.getTopicConfigurations()) { @@ -857,6 +860,7 @@ public class S3Controller { for (String event : tn.events()) { xml.elem("Event", event); } + appendFilterRules(xml, tn.filterRules()); xml.end("TopicConfiguration"); } xml.end("NotificationConfiguration"); @@ -871,24 +875,13 @@ public class S3Controller { String xml = new String(body, StandardCharsets.UTF_8); NotificationConfiguration config = new NotificationConfiguration(); - var queueConfigs = XmlParser.extractGroupsMulti(xml, "QueueConfiguration"); - for (var group : queueConfigs) { - String id = group.getOrDefault("Id", List.of("")).get(0); - List queueArns = group.get("Queue"); - List events = group.get("Event"); - if (queueArns != null && !queueArns.isEmpty() && events != null && !events.isEmpty()) { - config.getQueueConfigurations().add(new QueueNotification(id, queueArns.get(0), events)); - } + for (var parsed : parseNotificationGroups(xml, "QueueConfiguration", "Queue")) { + config.getQueueConfigurations().add( + new QueueNotification(parsed.id, parsed.arn, parsed.events, parsed.filterRules)); } - - var topicConfigs = XmlParser.extractGroupsMulti(xml, "TopicConfiguration"); - for (var group : topicConfigs) { - String id = group.getOrDefault("Id", List.of("")).get(0); - List topicArns = group.get("Topic"); - List events = group.get("Event"); - if (topicArns != null && !topicArns.isEmpty() && events != null && !events.isEmpty()) { - config.getTopicConfigurations().add(new TopicNotification(id, topicArns.get(0), events)); - } + for (var parsed : parseNotificationGroups(xml, "TopicConfiguration", "Topic")) { + config.getTopicConfigurations().add( + new TopicNotification(parsed.id, parsed.arn, parsed.events, parsed.filterRules)); } s3Service.putBucketNotificationConfiguration(bucket, config); @@ -898,6 +891,44 @@ public class S3Controller { } } + private record ParsedNotificationGroup(String id, String arn, List events, + List filterRules) {} + + private static List parseNotificationGroups( + String xml, String groupElement, String arnElement) { + var groups = XmlParser.extractGroupsMulti(xml, groupElement); + var filters = XmlParser.extractPairsPerGroup(xml, groupElement, + "FilterRule", "Name", "Value"); + List result = new ArrayList<>(); + for (int i = 0; i < groups.size(); i++) { + var group = groups.get(i); + String id = group.getOrDefault("Id", List.of("")).getFirst(); + List arns = group.get(arnElement); + List events = group.get("Event"); + if (arns != null && !arns.isEmpty() && events != null && !events.isEmpty()) { + List rules = i < filters.size() + ? filters.get(i).entrySet().stream() + .map(e -> new FilterRule(e.getKey(), e.getValue())) + .toList() + : List.of(); + result.add(new ParsedNotificationGroup(id, arns.getFirst(), events, rules)); + } + } + return result; + } + + private static void appendFilterRules(XmlBuilder xml, List rules) { + if (rules == null || rules.isEmpty()) return; + xml.start("Filter").start("S3Key"); + for (FilterRule rule : rules) { + xml.start("FilterRule") + .elem("Name", rule.name()) + .elem("Value", rule.value()) + .end("FilterRule"); + } + xml.end("S3Key").end("Filter"); + } + /** * Strips the {@code aws-chunked} token from a {@code Content-Encoding} value before persisting it. * {@code aws-chunked} is a transfer-protocol marker used by AWS SDK v2 streaming uploads and is not diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index 65f7349d66..dd47e55d03 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -1143,7 +1143,7 @@ public class S3Service { String eventJson = buildS3EventJson(bucketName, key, eventName, obj, region, bucket.isVersioningEnabled()); for (QueueNotification qn : config.getQueueConfigurations()) { - if (qn.events().stream().anyMatch(p -> matchesEvent(p, eventName))) { + if (qn.events().stream().anyMatch(p -> matchesEvent(p, eventName)) && qn.matchesKey(key)) { try { sqsService.sendMessage(sqsUrlFromArn(qn.queueArn()), eventJson, 0); LOG.debugv("Fired S3 event {0} to SQS {1}", eventName, qn.queueArn()); @@ -1154,7 +1154,7 @@ public class S3Service { } for (TopicNotification tn : config.getTopicConfigurations()) { - if (tn.events().stream().anyMatch(p -> matchesEvent(p, eventName))) { + if (tn.events().stream().anyMatch(p -> matchesEvent(p, eventName)) && tn.matchesKey(key)) { try { snsService.publish(tn.topicArn(), null, eventJson, "Amazon S3 Notification", region); LOG.debugv("Fired S3 event {0} to SNS {1}", eventName, tn.topicArn()); diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/FilterRule.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/FilterRule.java new file mode 100644 index 0000000000..49387e632d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/FilterRule.java @@ -0,0 +1,22 @@ +package io.github.hectorvent.floci.services.s3.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A single S3 notification filter rule (prefix or suffix match on the object key). + * + * @param name "prefix" or "suffix" + * @param value the value to match against + */ +@RegisterForReflection +public record FilterRule(String name, String value) { + + public boolean matches(String key) { + if (key == null || name == null || value == null) return false; + return switch (name.toLowerCase()) { + case "prefix" -> key.startsWith(value); + case "suffix" -> key.endsWith(value); + default -> false; + }; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/QueueNotification.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/QueueNotification.java index 1442e113ae..c8b0bf02f4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/QueueNotification.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/QueueNotification.java @@ -5,4 +5,13 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.List; @RegisterForReflection -public record QueueNotification(String id, String queueArn, List events) {} +public record QueueNotification(String id, String queueArn, List events, List filterRules) { + + public QueueNotification(String id, String queueArn, List events) { + this(id, queueArn, events, List.of()); + } + + public boolean matchesKey(String key) { + return filterRules == null || filterRules.isEmpty() || filterRules.stream().allMatch(r -> r.matches(key)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/TopicNotification.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/TopicNotification.java index 6994da551d..328b2f29e1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/TopicNotification.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/TopicNotification.java @@ -5,4 +5,13 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.List; @RegisterForReflection -public record TopicNotification(String id, String topicArn, List events) {} +public record TopicNotification(String id, String topicArn, List events, List filterRules) { + + public TopicNotification(String id, String topicArn, List events) { + this(id, topicArn, events, List.of()); + } + + public boolean matchesKey(String key) { + return filterRules == null || filterRules.isEmpty() || filterRules.stream().allMatch(r -> r.matches(key)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/XmlParserTest.java b/src/test/java/io/github/hectorvent/floci/core/common/XmlParserTest.java new file mode 100644 index 0000000000..bbf0c74b33 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/XmlParserTest.java @@ -0,0 +1,216 @@ +package io.github.hectorvent.floci.core.common; + +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class XmlParserTest { + + // --- extractGroupsMulti: nested element resilience --- + + @Test + void extractGroupsMultiSkipsNestedElementsAndParsesLeaves() { + String xml = """ + + + g1 + arn:example + event:one + + value + + + + """; + + List>> groups = XmlParser.extractGroupsMulti(xml, "Group"); + + assertEquals(1, groups.size()); + assertEquals(List.of("g1"), groups.get(0).get("Id")); + assertEquals(List.of("arn:example"), groups.get(0).get("Arn")); + assertEquals(List.of("event:one"), groups.get(0).get("Event")); + assertNull(groups.get(0).get("Nested")); + } + + @Test + void extractGroupsMultiNestedElementBeforeLeaves() { + String xml = """ + + + x + after-nested + + + """; + + List>> groups = XmlParser.extractGroupsMulti(xml, "Group"); + + assertEquals(1, groups.size()); + assertEquals(List.of("after-nested"), groups.get(0).get("Name")); + } + + @Test + void extractGroupsMultiMultipleGroupsWithAndWithoutNested() { + String xml = """ + + + a + + + b + skip + + + """; + + List>> groups = XmlParser.extractGroupsMulti(xml, "Group"); + + assertEquals(2, groups.size()); + assertEquals(List.of("a"), groups.get(0).get("Key")); + assertEquals(List.of("b"), groups.get(1).get("Key")); + } + + // --- extractGroups: same resilience for single-value variant --- + + @Test + void extractGroupsSkipsNestedElements() { + String xml = """ + + + test + skip + kept + + + """; + + List> groups = XmlParser.extractGroups(xml, "Group"); + + assertEquals(1, groups.size()); + assertEquals("test", groups.get(0).get("Name")); + assertEquals("kept", groups.get(0).get("Value")); + assertNull(groups.get(0).get("Nested")); + } + + // --- extractPairsPerGroup --- + + @Test + void extractPairsPerGroupBasic() { + String xml = """ + + + text + + + color + red + + + + + """; + + List> pairs = + XmlParser.extractPairsPerGroup(xml, "Group", "Pair", "Key", "Val"); + + assertEquals(1, pairs.size()); + assertEquals("red", pairs.get(0).get("color")); + } + + @Test + void extractPairsPerGroupMultiplePairsPerGroup() { + String xml = """ + + + + prefiximages/ + suffix.jpg + + + + """; + + List> pairs = + XmlParser.extractPairsPerGroup(xml, "Group", "Rule", "Name", "Value"); + + assertEquals(1, pairs.size()); + assertEquals("images/", pairs.get(0).get("prefix")); + assertEquals(".jpg", pairs.get(0).get("suffix")); + } + + @Test + void extractPairsPerGroupMultipleGroups() { + String xml = """ + + + envprod + + + teaminfra + costshared + + + """; + + List> pairs = + XmlParser.extractPairsPerGroup(xml, "Group", "Tag", "Key", "Val"); + + assertEquals(2, pairs.size()); + assertEquals(Map.of("env", "prod"), pairs.get(0)); + assertEquals(Map.of("team", "infra", "cost", "shared"), pairs.get(1)); + } + + @Test + void extractPairsPerGroupEmptyWhenNoPairsFound() { + String xml = """ + + + no-pairs-here + + + """; + + List> pairs = + XmlParser.extractPairsPerGroup(xml, "Group", "Pair", "Key", "Value"); + + assertEquals(1, pairs.size()); + assertTrue(pairs.get(0).isEmpty()); + } + + @Test + void extractPairsPerGroupNullAndEmptyXml() { + assertTrue(XmlParser.extractPairsPerGroup(null, "G", "P", "K", "V").isEmpty()); + assertTrue(XmlParser.extractPairsPerGroup("", "G", "P", "K", "V").isEmpty()); + } + + @Test + void extractPairsPerGroupIndexAlignedWithExtractGroupsMulti() { + String xml = """ + + + arn:q1 + s3:ObjectCreated:* + + + arn:q2 + s3:ObjectRemoved:* + + prefixlogs/ + + + + """; + + var groups = XmlParser.extractGroupsMulti(xml, "QueueConfiguration"); + var filters = XmlParser.extractPairsPerGroup(xml, "QueueConfiguration", + "FilterRule", "Name", "Value"); + + assertEquals(2, groups.size()); + assertEquals(2, filters.size()); + assertTrue(filters.get(0).isEmpty()); + assertEquals("logs/", filters.get(1).get("prefix")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java index fa6f97708f..1c822f09c3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java @@ -873,4 +873,112 @@ class S3IntegrationTest { given().delete("/encoding-test-bucket/composite-encoded.txt"); given().delete("/encoding-test-bucket"); } + + // --- S3 Notification Configuration with Filter --- + + @Test + @Order(90) + void createNotificationBucket() { + given() + .when() + .put("/notif-test-bucket") + .then() + .statusCode(200); + } + + @Test + @Order(91) + void putNotificationConfigWithFilterIsNotDropped() { + String xml = """ + + + my-notif + arn:aws:sqs:us-east-1:000000000000:test-queue + s3:ObjectCreated:* + + + + prefix + incoming/ + + + + + + """; + + given() + .contentType("application/xml") + .queryParam("notification", "") + .body(xml) + .when() + .put("/notif-test-bucket") + .then() + .statusCode(200); + + given() + .queryParam("notification", "") + .when() + .get("/notif-test-bucket") + .then() + .statusCode(200) + .body(containsString("QueueConfiguration")) + .body(containsString("arn:aws:sqs:us-east-1:000000000000:test-queue")) + .body(containsString("s3:ObjectCreated:*")) + // Verify filter rules are preserved in round-trip + .body(containsString("Filter")) + .body(containsString("FilterRule")) + .body(containsString("prefix")) + .body(containsString("incoming/")); + } + + @Test + @Order(92) + void putNotificationConfigWithFilterBeforeQueueIsNotDropped() { + // Filter appears BEFORE Queue — ensures element order doesn't matter + String xml = """ + + + filter-first + + + + suffix + .csv + + + + arn:aws:sqs:us-east-1:000000000000:csv-queue + s3:ObjectCreated:Put + + + """; + + given() + .contentType("application/xml") + .queryParam("notification", "") + .body(xml) + .when() + .put("/notif-test-bucket") + .then() + .statusCode(200); + + given() + .queryParam("notification", "") + .when() + .get("/notif-test-bucket") + .then() + .statusCode(200) + .body(containsString("QueueConfiguration")) + .body(containsString("arn:aws:sqs:us-east-1:000000000000:csv-queue")) + .body(containsString("s3:ObjectCreated:Put")) + .body(containsString("suffix")) + .body(containsString(".csv")); + } + + @Test + @Order(93) + void cleanupNotificationBucket() { + given().delete("/notif-test-bucket"); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3NotificationModelTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3NotificationModelTest.java new file mode 100644 index 0000000000..1c3f0ed961 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3NotificationModelTest.java @@ -0,0 +1,70 @@ +package io.github.hectorvent.floci.services.s3; + +import io.github.hectorvent.floci.services.s3.model.FilterRule; +import io.github.hectorvent.floci.services.s3.model.QueueNotification; +import io.github.hectorvent.floci.services.s3.model.TopicNotification; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class S3NotificationModelTest { + + // --- matchesKey --- + + @Test + void matchesKeyWithNullFilterRulesFromJacksonDeserialization() { + var qn = new QueueNotification("id", "arn:aws:sqs:us-east-1:000000000000:q", + List.of("s3:ObjectCreated:*"), null); + assertTrue(qn.matchesKey("anything")); + + var tn = new TopicNotification("id", "arn:aws:sns:us-east-1:000000000000:t", + List.of("s3:ObjectCreated:*"), null); + assertTrue(tn.matchesKey("anything")); + } + + @Test + void matchesKeyWithEmptyFilterRulesMatchesAll() { + var qn = new QueueNotification("id", "arn", List.of("s3:ObjectCreated:*")); + assertTrue(qn.matchesKey("anything")); + } + + @Test + void matchesKeyEnforcesAllRules() { + var qn = new QueueNotification("id", "arn", List.of("s3:ObjectCreated:*"), + List.of(new FilterRule("prefix", "images/"), new FilterRule("suffix", ".jpg"))); + assertTrue(qn.matchesKey("images/photo.jpg")); + assertFalse(qn.matchesKey("images/photo.png")); + assertFalse(qn.matchesKey("docs/photo.jpg")); + } + + // --- FilterRule.matches --- + + @Test + void filterRulePrefixMatch() { + FilterRule rule = new FilterRule("prefix", "images/"); + assertTrue(rule.matches("images/photo.jpg")); + assertFalse(rule.matches("docs/file.txt")); + assertFalse(rule.matches(null)); + } + + @Test + void filterRuleSuffixMatch() { + FilterRule rule = new FilterRule("suffix", ".jpg"); + assertTrue(rule.matches("images/photo.jpg")); + assertFalse(rule.matches("images/photo.png")); + } + + @Test + void filterRuleUnknownNameDoesNotMatch() { + FilterRule rule = new FilterRule("extension", ".jpg"); + assertFalse(rule.matches("photo.jpg")); + } + + @Test + void filterRuleNameIsCaseInsensitive() { + assertTrue(new FilterRule("Prefix", "images/").matches("images/photo.jpg")); + assertTrue(new FilterRule("SUFFIX", ".jpg").matches("photo.jpg")); + } +}