Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudtrail): support AdvancedEventSelectors and CloudFormation Trail provisioning (#2720)
Sam Fakhreddinefd3c4d9ab6b8
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 76f6640d63..f17fc4663f 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -105,6 +105,7 @@ cross-resource references.| WAFv2 | `WebACL` || Config | `ConfigRule` || CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `Stack` (nested stacks), `Custom::*` (Lambda-backed) |+| CloudTrail | `Trail` || CDK | `CDK::Metadata` (accepted; no-op) |<!-- floci:cfn-types:end -->diff --git a/docs/services/cloudtrail.md b/docs/services/cloudtrail.mdindex cef00df0a2..4073d1490e 100644--- a/docs/services/cloudtrail.md+++ b/docs/services/cloudtrail.md@@ -26,6 +26,7 @@ ${prefix}AWSLogs/${accountId}/CloudTrail/${region}/yyyy/MM/dd/${accountId}_Cloud| `StopLogging` | Stops logging for a trail || `GetTrailStatus` | Returns the logging status of a trail || `LookupEvents` | - |+| `ListTrails` | - || `AddTags` | Adds or overwrites tags on a trail, identified by ARN || `RemoveTags` | Removes the given tag keys from a trail, identified by ARN || `ListTags` | Returns the tags for one or more trails, identified by ARN |diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudTrailCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudTrailCfnProvisioner.javanew file mode 100644index 0000000000..1e39a687c8--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudTrailCfnProvisioner.java@@ -0,0 +1,122 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;+import io.github.hectorvent.floci.services.cloudtrail.CloudTrailSelectorJson;+import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedEventSelector;+import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;+import io.github.hectorvent.floci.services.cloudtrail.model.Trail;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.List;+import java.util.Set;++@ApplicationScoped+public class CloudTrailCfnProvisioner implements CfnResourceProvisioner {++ private static final String CLOUDTRAIL_TRAIL = "AWS::CloudTrail::Trail";++ private final CloudTrailService trailService;++ @Inject+ public CloudTrailCfnProvisioner(CloudTrailService trailService) {+ this.trailService = trailService;+ }++ @Override+ public Set<String> resourceTypes() {+ return Set.of(CLOUDTRAIL_TRAIL);+ }++ @Override+ public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {+ JsonNode resolved = ctx.engine().resolveNode(props);+ String previousPhysicalId = resource.getPhysicalId();+ boolean isCreate = previousPhysicalId == null;++ String name = text(resolved, "TrailName");+ if (name == null || name.isBlank()) {+ name = isCreate ? ctx.generatePhysicalName(resource.getLogicalId(), 128, false) : previousPhysicalId;+ }+ String s3BucketName = text(resolved, "S3BucketName");+ String s3KeyPrefix = text(resolved, "S3KeyPrefix");+ String snsTopicName = text(resolved, "SnsTopicName");++ Trail trail;+ if (isCreate) {+ boolean includeGlobalServiceEvents = resolved.path("IncludeGlobalServiceEvents").asBoolean(true);+ boolean isMultiRegionTrail = resolved.path("IsMultiRegionTrail").asBoolean(false);+ boolean enableLogFileValidation = resolved.path("EnableLogFileValidation").asBoolean(false);+ boolean isOrganizationTrail = resolved.path("IsOrganizationTrail").asBoolean(false);+ trail = trailService.createTrail(ctx.region(), name, s3BucketName, s3KeyPrefix, snsTopicName,+ includeGlobalServiceEvents, isMultiRegionTrail, enableLogFileValidation, isOrganizationTrail);+ resource.setPhysicalId(trail.trailArn());+ applySelectors(resolved, ctx.region(), name);+ if (resolved.path("IsLogging").asBoolean(false)) {+ trailService.startLogging(ctx.region(), name);+ }+ } else {+ Boolean includeGlobalServiceEvents = resolved.has("IncludeGlobalServiceEvents")+ ? resolved.path("IncludeGlobalServiceEvents").asBoolean() : null;+ Boolean isMultiRegionTrail = resolved.has("IsMultiRegionTrail")+ ? resolved.path("IsMultiRegionTrail").asBoolean() : null;+ Boolean enableLogFileValidation = resolved.has("EnableLogFileValidation")+ ? resolved.path("EnableLogFileValidation").asBoolean() : null;+ Boolean isOrganizationTrail = resolved.has("IsOrganizationTrail")+ ? resolved.path("IsOrganizationTrail").asBoolean() : null;+ trail = trailService.updateTrail(ctx.region(), previousPhysicalId, s3BucketName, s3KeyPrefix,+ snsTopicName, includeGlobalServiceEvents, isMultiRegionTrail, enableLogFileValidation,+ isOrganizationTrail);+ applySelectors(resolved, ctx.region(), previousPhysicalId);+ if (resolved.has("IsLogging")) {+ if (resolved.path("IsLogging").asBoolean()) {+ trailService.startLogging(ctx.region(), previousPhysicalId);+ } else {+ trailService.stopLogging(ctx.region(), previousPhysicalId);+ }+ }+ }++ resource.setPhysicalId(trail.trailArn());+ resource.getAttributes().put("Arn", trail.trailArn());+ resource.getAttributes().put("SnsTopicArn", trail.snsTopicArn());+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ if (physicalId == null) {+ return;+ }+ boolean exists = !trailService.describeTrails(region, List.of(physicalId)).isEmpty();+ if (exists) {+ trailService.deleteTrail(region, physicalId);+ }+ }++ private void applySelectors(JsonNode resolved, String region, String trailNameOrArn) {+ boolean hasBasic = resolved.has("EventSelectors") && resolved.path("EventSelectors").isArray()+ && !resolved.path("EventSelectors").isEmpty();+ boolean hasAdvanced = resolved.has("AdvancedEventSelectors") && resolved.path("AdvancedEventSelectors").isArray()+ && !resolved.path("AdvancedEventSelectors").isEmpty();+ if (hasBasic && hasAdvanced) {+ throw new AwsException("InvalidEventSelectorsException",+ "EventSelectors and AdvancedEventSelectors are mutually exclusive on a single trail.", 400);+ }+ if (hasAdvanced) {+ List<AdvancedEventSelector> advanced =+ CloudTrailSelectorJson.parseAdvancedEventSelectors(resolved.path("AdvancedEventSelectors"));+ trailService.putAdvancedEventSelectors(region, trailNameOrArn, advanced);+ } else if (hasBasic) {+ List<EventSelector> selectors = CloudTrailSelectorJson.parseEventSelectors(resolved.path("EventSelectors"));+ trailService.putEventSelectors(region, trailNameOrArn, selectors);+ }+ }++ private String text(JsonNode node, String field) {+ JsonNode value = node == null ? null : node.get(field);+ return value == null || value.isNull() ? null : value.asText();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailEntry.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailEntry.javaindex ebd8977e3b..13387abb1d 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailEntry.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailEntry.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudtrail;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import com.fasterxml.jackson.annotation.JsonInclude;+import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedEventSelector;import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;import io.github.hectorvent.floci.services.cloudtrail.model.Trail;import io.quarkus.runtime.annotations.RegisterForReflection;@@ -17,6 +18,7 @@ import java.util.Map;public record CloudTrailEntry(Trail trail,List<EventSelector> selectors,+ List<AdvancedEventSelector> advancedSelectors,boolean logging,Long startLoggingTime,Long stopLoggingTime,@@ -29,28 +31,45 @@ public record CloudTrailEntry(}public CloudTrailEntry withTrail(Trail updated) {- return new CloudTrailEntry(updated, selectors, logging, startLoggingTime, stopLoggingTime, tags);+ return new CloudTrailEntry(updated, selectors, advancedSelectors, logging,+ startLoggingTime, stopLoggingTime, tags);}+ /** Sets basic selectors, clearing any advanced selectors — a trail holds one kind or the other. */public CloudTrailEntry withSelectors(List<EventSelector> updated, boolean hasCustomSelectors) {- Trail updatedTrail = new Trail(- trail.name(), trail.trailArn(), trail.s3BucketName(), trail.s3KeyPrefix(),- trail.snsTopicArn(), trail.includeGlobalServiceEvents(), trail.isMultiRegionTrail(),- trail.homeRegion(), trail.logFileValidationEnabled(), hasCustomSelectors,- trail.hasInsightSelectors(), trail.isOrganizationTrail());- return new CloudTrailEntry(updatedTrail, updated, logging, startLoggingTime, stopLoggingTime, tags);+ Trail updatedTrail = withHasCustomSelectors(hasCustomSelectors);+ return new CloudTrailEntry(updatedTrail, updated, List.of(), logging,+ startLoggingTime, stopLoggingTime, tags);+ }++ /** Sets advanced selectors, clearing any basic selectors — a trail holds one kind or the other. */+ public CloudTrailEntry withAdvancedSelectors(List<AdvancedEventSelector> updated, boolean hasCustomSelectors) {+ Trail updatedTrail = withHasCustomSelectors(hasCustomSelectors);+ return new CloudTrailEntry(updatedTrail, List.of(), updated, logging,+ startLoggingTime, stopLoggingTime, tags);+ }++ public CloudTrailEntry withTags(Map<String, String> updated) {+ return new CloudTrailEntry(trail, selectors, advancedSelectors, logging,+ startLoggingTime, stopLoggingTime, updated);}public CloudTrailEntry startLogging(long time) {- return new CloudTrailEntry(trail, selectors, true, time, stopLoggingTime, tags);+ return new CloudTrailEntry(trail, selectors, advancedSelectors, true, time,+ stopLoggingTime, tags);}public CloudTrailEntry stopLogging(long time) {- return new CloudTrailEntry(trail, selectors, false, startLoggingTime, time, tags);+ return new CloudTrailEntry(trail, selectors, advancedSelectors, false, startLoggingTime,+ time, tags);}- public CloudTrailEntry withTags(Map<String, String> updated) {- return new CloudTrailEntry(trail, selectors, logging, startLoggingTime, stopLoggingTime, updated);+ private Trail withHasCustomSelectors(boolean hasCustomSelectors) {+ return new Trail(+ trail.name(), trail.trailArn(), trail.s3BucketName(), trail.s3KeyPrefix(),+ trail.snsTopicArn(), trail.includeGlobalServiceEvents(), trail.isMultiRegionTrail(),+ trail.homeRegion(), trail.logFileValidationEnabled(), hasCustomSelectors,+ trail.hasInsightSelectors(), trail.isOrganizationTrail());}/** Returns a mutable copy suitable for merging in new tags. */diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.javaindex 49f0592461..74565c315a 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedEventSelector;import io.github.hectorvent.floci.services.cloudtrail.model.DataResource;import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;import io.github.hectorvent.floci.services.cloudtrail.model.Trail;@@ -41,6 +42,7 @@ public class CloudTrailJsonHandler {case "StopLogging" -> stopLogging(request, region);case "GetTrailStatus" -> getTrailStatus(request, region);case "LookupEvents" -> lookupEvents(request, region);+ case "ListTrails" -> listTrails(request, region);case "AddTags" -> addTags(request);case "RemoveTags" -> removeTags(request);case "ListTags" -> listTags(request);@@ -131,28 +133,56 @@ public class CloudTrailJsonHandler {private Response putEventSelectors(JsonNode req, String region) {String trailName = req.path("TrailName").asText(null);- List<EventSelector> selectors = parseEventSelectors(req.path("EventSelectors"));- List<EventSelector> stored = service.putEventSelectors(region, trailName, selectors);+ boolean hasBasic = req.has("EventSelectors") && req.path("EventSelectors").isArray()+ && !req.path("EventSelectors").isEmpty();+ boolean hasAdvanced = req.has("AdvancedEventSelectors") && req.path("AdvancedEventSelectors").isArray()+ && !req.path("AdvancedEventSelectors").isEmpty();+ if (hasBasic && hasAdvanced) {+ throw new AwsException("InvalidEventSelectorsException",+ "EventSelectors and AdvancedEventSelectors are mutually exclusive on a single trail.", 400);+ }ObjectNode resp = mapper.createObjectNode();- Trail trail = firstTrail(service.describeTrails(region, List.of(trailName)));+ Trail trail = trailName != null ? firstTrail(service.describeTrails(region, List.of(trailName))) : null;if (trail != null) {resp.put("TrailARN", trail.trailArn());}- resp.set("EventSelectors", mapper.valueToTree(stored));++ if (hasAdvanced) {+ List<AdvancedEventSelector> advanced =+ CloudTrailSelectorJson.parseAdvancedEventSelectors(req.path("AdvancedEventSelectors"));+ List<AdvancedEventSelector> stored = service.putAdvancedEventSelectors(region, trailName, advanced);+ resp.set("AdvancedEventSelectors", mapper.valueToTree(stored));+ } else {+ List<EventSelector> selectors = parseEventSelectors(req.path("EventSelectors"));+ List<EventSelector> stored = service.putEventSelectors(region, trailName, selectors);+ resp.set("EventSelectors", mapper.valueToTree(stored));+ }return Response.ok(resp).build();}private Response getEventSelectors(JsonNode req, String region) {String trailName = req.path("TrailName").asText(null);- List<EventSelector> selectors = service.getEventSelectors(region, trailName);+ List<AdvancedEventSelector> advancedSelectors = service.getAdvancedEventSelectors(region, trailName);ObjectNode resp = mapper.createObjectNode();- Trail trail = firstTrail(service.describeTrails(region, List.of(trailName)));+ Trail trail = trailName != null ? firstTrail(service.describeTrails(region, List.of(trailName))) : null;if (trail != null) {resp.put("TrailARN", trail.trailArn());}- resp.set("EventSelectors", mapper.valueToTree(selectors));+ if (!advancedSelectors.isEmpty()) {+ resp.set("AdvancedEventSelectors", mapper.valueToTree(advancedSelectors));+ } else {+ List<EventSelector> selectors = service.getEventSelectors(region, trailName);+ resp.set("EventSelectors", mapper.valueToTree(selectors));+ }+ return Response.ok(resp).build();+ }++ private Response listTrails(JsonNode req, String region) {+ List<CloudTrailService.TrailInfo> trails = service.listTrails(region);+ ObjectNode resp = mapper.createObjectNode();+ resp.set("Trails", mapper.valueToTree(trails));return Response.ok(resp).build();}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.javaindex 33a1d06ce7..525dfe8b2f 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriter.java@@ -134,12 +134,14 @@ public class CloudTrailLogWriter {return;}+ byte[] payload;+ String objectKey;try {- byte[] payload = serializeAndGzip(records);+ payload = serializeAndGzip(records);String accountId = regionResolver.getAccountId();// Use the event region for the S3 delivery path so multi-region trail// events from us-west-2 land under CloudTrail/us-west-2, not the trail's home region.- String objectKey = buildObjectKey(trail, accountId, key.eventRegion());+ objectKey = buildObjectKey(trail, accountId, key.eventRegion());s3Service.putObject(trail.s3BucketName(), objectKey, payload,"application/x-gzip", Map.of());LOG.debugv("CloudTrail wrote {0} records to s3://{1}/{2}",@@ -151,6 +153,34 @@ public class CloudTrailLogWriter {key.trailName(), records.size());throw e;}++ // The write above already succeeded and durably delivered the records —+ // from here on, records must never be re-queued. Doing so on a failure+ // in this block would deliver the same batch to S3 again next flush.+ try {+ // This write goes straight to S3Service, bypassing the HTTP-facing+ // S3Controller that normally emits data events for API-driven puts.+ // Any trail whose selector matches its own destination bucket must+ // still see its own deliveries — that's the real circular-logging+ // behavior (issue #1192 / PR #1194) this emulator exists to prove.+ cloudTrailService.emitS3DataEvent(CloudTrailService.S3EventInput.builder()+ .region(key.eventRegion())+ .eventName("PutObject")+ .bucketName(trail.s3BucketName())+ .key(objectKey)+ .accessKeyId(null)+ .sourceIp(null)+ .userAgent("cloudtrail.amazonaws.com")+ .bytesIn(payload.length)+ .bytesOut(0)+ .errorCode(null)+ .errorMessage(null)+ .eventTimeMillis(System.currentTimeMillis())+ .build());+ } catch (RuntimeException e) {+ LOG.warnv(e, "CloudTrail self-delivery event emission failed for trail {0} "+ + "(write already succeeded, records not re-queued)", key.trailName());+ }}private byte[] serializeAndGzip(List<ObjectNode> records) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelectorJson.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelectorJson.javanew file mode 100644index 0000000000..3d1c434c5b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelectorJson.java@@ -0,0 +1,78 @@+package io.github.hectorvent.floci.services.cloudtrail;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedEventSelector;+import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedFieldSelector;+import io.github.hectorvent.floci.services.cloudtrail.model.DataResource;+import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;++import java.util.ArrayList;+import java.util.List;++/**+ * Shared JSON parsing for basic and advanced CloudTrail event selectors. Used by the+ * {@code AWS::CloudTrail::Trail} CFN provisioner so it accepts the same shapes the+ * PutEventSelectors control-plane action does.+ */+public final class CloudTrailSelectorJson {++ private CloudTrailSelectorJson() {+ }++ public static List<EventSelector> parseEventSelectors(JsonNode selectorsNode) {+ List<EventSelector> result = new ArrayList<>();+ if (selectorsNode == null || !selectorsNode.isArray()) {+ return result;+ }+ for (JsonNode sel : selectorsNode) {+ String readWriteType = sel.has("ReadWriteType") ? sel.path("ReadWriteType").asText() : "All";+ Boolean includeManagement = sel.has("IncludeManagementEvents")+ ? sel.path("IncludeManagementEvents").asBoolean() : null;+ List<String> excludeManagement = extractStringList(sel, "ExcludeManagementEventSources");+ List<DataResource> dataResources = new ArrayList<>();+ if (sel.has("DataResources")) {+ for (JsonNode dr : sel.path("DataResources")) {+ String type = dr.path("Type").asText(null);+ List<String> values = extractStringList(dr, "Values");+ dataResources.add(new DataResource(type, values));+ }+ }+ result.add(new EventSelector(readWriteType, includeManagement, dataResources,+ excludeManagement.isEmpty() ? null : excludeManagement));+ }+ return result;+ }++ public static List<AdvancedEventSelector> parseAdvancedEventSelectors(JsonNode selectorsNode) {+ List<AdvancedEventSelector> result = new ArrayList<>();+ if (selectorsNode == null || !selectorsNode.isArray()) {+ return result;+ }+ for (JsonNode sel : selectorsNode) {+ String name = sel.has("Name") ? sel.path("Name").asText(null) : null;+ List<AdvancedFieldSelector> fieldSelectors = new ArrayList<>();+ if (sel.has("FieldSelectors")) {+ for (JsonNode fs : sel.path("FieldSelectors")) {+ fieldSelectors.add(new AdvancedFieldSelector(+ fs.path("Field").asText(null),+ extractStringList(fs, "Equals"),+ extractStringList(fs, "NotEquals"),+ extractStringList(fs, "StartsWith"),+ extractStringList(fs, "NotStartsWith"),+ extractStringList(fs, "EndsWith"),+ extractStringList(fs, "NotEndsWith")));+ }+ }+ result.add(new AdvancedEventSelector(name, fieldSelectors));+ }+ return result;+ }++ private static List<String> extractStringList(JsonNode node, String fieldName) {+ List<String> result = new ArrayList<>();+ if (node != null && node.has(fieldName)) {+ node.path(fieldName).forEach(n -> result.add(n.asText()));+ }+ return result;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.javaindex 4600fb0931..3431875b29 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.cloudtrail;+import com.fasterxml.jackson.annotation.JsonProperty;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;@@ -9,12 +10,15 @@ import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedEventSelector;+import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedFieldSelector;import io.github.hectorvent.floci.services.cloudtrail.model.DataResource;import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;import io.github.hectorvent.floci.services.cloudtrail.model.Trail;import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.iam.model.AccessKey;import io.github.hectorvent.floci.services.iam.model.IamUser;+import io.quarkus.runtime.annotations.RegisterForReflection;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;@@ -107,7 +111,7 @@ public class CloudTrailService {name, arn, s3BucketName, s3KeyPrefix, snsTopicArn,includeGlobalServiceEvents, isMultiRegionTrail, region,enableLogFileValidation, false, false, isOrganizationTrail);- store.put(key, new CloudTrailEntry(trail, List.of(), false, null, null, initialTags));+ store.put(key, new CloudTrailEntry(trail, List.of(), List.of(), false, null, null, initialTags));return trail;}@@ -183,6 +187,44 @@ public class CloudTrailService {.orElse(List.of());}+ public List<AdvancedEventSelector> putAdvancedEventSelectors(+ String region, String trailNameOrArn, List<AdvancedEventSelector> selectors) {+ Trail trail = findTrailOrThrow(region, trailNameOrArn);+ List<AdvancedEventSelector> normalized = selectors == null ? List.of() : List.copyOf(selectors);+ String key = regionKey(trail.homeRegion(), trail.name());+ withTrailLock(key, () -> store.get(key).ifPresent(entry -> store.put(key, entry.withAdvancedSelectors(normalized, true))));+ return normalized;+ }++ public List<AdvancedEventSelector> getAdvancedEventSelectors(String region, String trailNameOrArn) {+ Trail trail = findTrailOrThrow(region, trailNameOrArn);+ return store.get(regionKey(trail.homeRegion(), trail.name()))+ .map(e -> e.advancedSelectors() != null ? e.advancedSelectors() : List.<AdvancedEventSelector>of())+ .orElse(List.of());+ }++ public List<TrailInfo> listTrails(String region) {+ List<TrailInfo> result = new ArrayList<>();+ for (String k : store.keys()) {+ CloudTrailEntry entry = store.get(k).orElse(null);+ if (entry == null) {+ continue;+ }+ Trail t = entry.trail();+ if (regionFromKey(k).equals(region) || t.isMultiRegionTrail()) {+ result.add(new TrailInfo(t.name(), t.trailArn(), t.homeRegion()));+ }+ }+ return result;+ }++ @RegisterForReflection+ public record TrailInfo(+ @JsonProperty("Name") String name,+ @JsonProperty("TrailARN") String trailArn,+ @JsonProperty("HomeRegion") String homeRegion) {+ }+public void startLogging(String region, String trailNameOrArn) {Trail trail = findTrailOrThrow(region, trailNameOrArn);String key = regionKey(trail.homeRegion(), trail.name());@@ -374,12 +416,26 @@ public class CloudTrailService {String trailRegion = regionFromKey(k);boolean sameRegion = trailRegion.equals(region);CloudTrailEntry entry = store.get(k).orElse(null);- if (entry == null) continue;+ if (entry == null) {+ continue;+ }Trail trail = entry.trail();- if (!sameRegion && !trail.isMultiRegionTrail()) continue;- if (!entry.logging()) continue;- List<EventSelector> selectors = entry.selectors() != null ? entry.selectors() : List.of();- if (matchesAnySelector(selectors, in)) {+ if (!sameRegion && !trail.isMultiRegionTrail()) {+ continue;+ }+ if (!entry.logging()) {+ continue;+ }+ List<AdvancedEventSelector> advancedSelectors =+ entry.advancedSelectors() != null ? entry.advancedSelectors() : List.of();+ boolean matched;+ if (!advancedSelectors.isEmpty()) {+ matched = matchesAnyAdvancedSelector(advancedSelectors, in);+ } else {+ List<EventSelector> selectors = entry.selectors() != null ? entry.selectors() : List.of();+ matched = matchesAnySelector(selectors, in);+ }+ if (matched) {result.add(new MatchedTrail(trail, trailRegion));}}@@ -413,6 +469,70 @@ public class CloudTrailService {return false;}+ private boolean matchesAnyAdvancedSelector(List<AdvancedEventSelector> selectors, S3EventInput in) {+ String arn = "arn:aws:s3:::" + in.bucketName() + (in.key() != null ? "/" + in.key() : "");+ // Bucket-level operations (e.g. ListObjects) have no object key and are reported+ // by CloudTrail as AWS::S3::Bucket resources, not AWS::S3::Object — matching real+ // AWS behavior, an AWS::S3::Object DataResource selector must never match them.+ String resourceType = in.key() != null ? "AWS::S3::Object" : "AWS::S3::Bucket";+ for (AdvancedEventSelector sel : selectors) {+ if (matchesAdvancedSelector(sel, arn, resourceType)) {+ return true;+ }+ }+ return false;+ }++ private boolean matchesAdvancedSelector(AdvancedEventSelector selector, String s3ObjectArn, String resourceType) {+ List<AdvancedFieldSelector> fieldSelectors = selector.fieldSelectors();+ if (fieldSelectors == null || fieldSelectors.isEmpty()) {+ return false;+ }+ for (AdvancedFieldSelector fs : fieldSelectors) {+ if (!matchesAdvancedFieldSelector(fs, s3ObjectArn, resourceType)) {+ return false;+ }+ }+ return true;+ }++ // Package-private for unit testing. Only the fields CloudTrail evaluates for S3 data events+ // are supported: eventCategory, resources.type, resources.ARN.+ static boolean matchesAdvancedFieldSelector(AdvancedFieldSelector fs, String s3ObjectArn, String resourceType) {+ String value = switch (fs.field()) {+ case "eventCategory" -> "Data";+ case "resources.type" -> resourceType;+ case "resources.ARN" -> s3ObjectArn;+ default -> null;+ };+ if (value == null) {+ return false;+ }+ if (!isEmpty(fs.equalsValues()) && fs.equalsValues().stream().noneMatch(value::equals)) {+ return false;+ }+ if (!isEmpty(fs.notEquals()) && fs.notEquals().stream().anyMatch(value::equals)) {+ return false;+ }+ if (!isEmpty(fs.startsWith()) && fs.startsWith().stream().noneMatch(value::startsWith)) {+ return false;+ }+ if (!isEmpty(fs.notStartsWith()) && fs.notStartsWith().stream().anyMatch(value::startsWith)) {+ return false;+ }+ if (!isEmpty(fs.endsWith()) && fs.endsWith().stream().noneMatch(value::endsWith)) {+ return false;+ }+ if (!isEmpty(fs.notEndsWith()) && fs.notEndsWith().stream().anyMatch(value::endsWith)) {+ return false;+ }+ return true;+ }++ private static boolean isEmpty(List<String> values) {+ return values == null || values.isEmpty();+ }+// Package-private for unit testing.static boolean matchesS3DataResourceArn(String configured, String bucketName, String key) {if (configured == null) return false;diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/AdvancedEventSelector.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/AdvancedEventSelector.javanew file mode 100644index 0000000000..e083ac29d6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/AdvancedEventSelector.java@@ -0,0 +1,16 @@+package io.github.hectorvent.floci.services.cloudtrail.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.List;++@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+@JsonIgnoreProperties(ignoreUnknown = true)+public record AdvancedEventSelector(+ @JsonProperty("Name") String name,+ @JsonProperty("FieldSelectors") List<AdvancedFieldSelector> fieldSelectors) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/AdvancedFieldSelector.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/AdvancedFieldSelector.javanew file mode 100644index 0000000000..96dec3636b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/model/AdvancedFieldSelector.java@@ -0,0 +1,21 @@+package io.github.hectorvent.floci.services.cloudtrail.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonInclude;+import com.fasterxml.jackson.annotation.JsonProperty;+import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.List;++@RegisterForReflection+@JsonInclude(JsonInclude.Include.NON_NULL)+@JsonIgnoreProperties(ignoreUnknown = true)+public record AdvancedFieldSelector(+ @JsonProperty("Field") String field,+ @JsonProperty("Equals") List<String> equalsValues,+ @JsonProperty("NotEquals") List<String> notEquals,+ @JsonProperty("StartsWith") List<String> startsWith,+ @JsonProperty("NotStartsWith") List<String> notStartsWith,+ @JsonProperty("EndsWith") List<String> endsWith,+ @JsonProperty("NotEndsWith") List<String> notEndsWith) {+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.javaindex 32b70a6932..a8abae3c7e 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScaliimport io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;+import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrailCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2LaunchTemplateCfnProvisioner;@@ -65,6 +66,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.SsmCfnProimport io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;+import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;import io.github.hectorvent.floci.services.cognito.CognitoService;@@ -157,6 +159,7 @@ final class CfnProvisionerFixture {private DocDbService docDbService;private CloudFrontService cloudFrontService;private Route53Service route53Service;+ private CloudTrailService cloudTrailService;private SchedulerService schedulerService;// Services that back a provisioner without being a constructor argument of the// dispatcher. They exist only so inferredProvisioners() can wire their provisioner.@@ -310,6 +313,9 @@ final class CfnProvisionerFixture {if (route53Service != null) {discovered.add(new Route53CfnProvisioner(route53Service));}+ if (cloudTrailService != null) {+ discovered.add(new CloudTrailCfnProvisioner(cloudTrailService));+ }if (schedulerService != null) {discovered.add(new SchedulerScheduleGroupCfnProvisioner(schedulerService));}@@ -441,6 +447,11 @@ final class CfnProvisionerFixture {return this;}+ public Builder cloudTrail(CloudTrailService v) {+ this.cloudTrailService = v;+ return this;+ }+public Builder scheduler(SchedulerService v) {this.schedulerService = v;return this;diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudTrailCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudTrailCfnProvisionerTest.javanew file mode 100644index 0000000000..18dbaf96b0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudTrailCfnProvisionerTest.java@@ -0,0 +1,170 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;+import io.github.hectorvent.floci.services.cloudtrail.model.EventSelector;+import io.github.hectorvent.floci.services.cloudtrail.model.Trail;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.util.HashMap;+import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyBoolean;+import static org.mockito.ArgumentMatchers.anyList;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++class CloudTrailCfnProvisionerTest {++ private final CloudTrailService trailService = mock(CloudTrailService.class);+ private final CloudTrailCfnProvisioner provisioner = new CloudTrailCfnProvisioner(trailService);+ private final ObjectMapper mapper = new ObjectMapper();++ @Test+ void createsTrailAppliesBasicSelectorsAndStartsLoggingWhenRequested() {+ Trail created = trail("audit-trail", "arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail");+ when(trailService.createTrail(eq("us-east-1"), eq("audit-trail"), eq("dest-bucket"),+ eq((String) null), eq((String) null), eq(true), eq(false), eq(false), eq(false)))+ .thenReturn(created);+ when(trailService.putEventSelectors(eq("us-east-1"), eq("audit-trail"), anyList()))+ .thenReturn(List.of());++ ObjectNode props = mapper.createObjectNode()+ .put("TrailName", "audit-trail")+ .put("S3BucketName", "dest-bucket")+ .put("IsLogging", true);+ props.set("EventSelectors", mapper.createArrayNode().add(mapper.createObjectNode()+ .put("ReadWriteType", "All")));+ StackResource resource = resource();++ provisioner.provision(resource, props, context());++ ArgumentCaptor<List<EventSelector>> selectorsCaptor = ArgumentCaptor.forClass(List.class);+ verify(trailService).putEventSelectors(eq("us-east-1"), eq("audit-trail"), selectorsCaptor.capture());+ assertEquals(1, selectorsCaptor.getValue().size());+ assertEquals("All", selectorsCaptor.getValue().get(0).readWriteType());+ verify(trailService).startLogging("us-east-1", "audit-trail");+ assertEquals(created.trailArn(), resource.getPhysicalId());+ assertEquals(created.trailArn(), resource.getAttributes().get("Arn"));+ }++ @Test+ void updateUsesExistingPhysicalIdAndSkipsSelectorsWhenAbsent() {+ Trail updated = trail("audit-trail", "arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail");+ when(trailService.updateTrail(eq("us-east-1"),+ eq("arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail"),+ eq("dest-bucket"), any(), any(), any(), any(), any(), any()))+ .thenReturn(updated);++ ObjectNode props = mapper.createObjectNode()+ .put("TrailName", "audit-trail")+ .put("S3BucketName", "dest-bucket");+ StackResource resource = resource();+ resource.setPhysicalId("arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail");++ provisioner.provision(resource, props, context());++ verify(trailService, never()).putEventSelectors(anyString(), anyString(), anyList());+ verify(trailService, never()).putAdvancedEventSelectors(anyString(), anyString(), anyList());+ verify(trailService, never()).startLogging(anyString(), anyString());+ assertEquals(updated.trailArn(), resource.getPhysicalId());+ }++ @Test+ void bothBasicAndAdvancedSelectorsAreRejected() {+ Trail created = trail("audit-trail", "arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail");+ when(trailService.createTrail(eq("us-east-1"), eq("audit-trail"), eq("dest-bucket"),+ any(), any(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean()))+ .thenReturn(created);++ ObjectNode props = mapper.createObjectNode()+ .put("TrailName", "audit-trail")+ .put("S3BucketName", "dest-bucket");+ props.set("EventSelectors", mapper.createArrayNode().add(mapper.createObjectNode()+ .put("ReadWriteType", "All")));+ props.set("AdvancedEventSelectors", mapper.createArrayNode().add(mapper.createObjectNode()+ .put("Name", "x")+ .set("FieldSelectors", mapper.createArrayNode().add(mapper.createObjectNode()+ .put("Field", "eventCategory")+ .set("Equals", mapper.createArrayNode().add("Data"))))));+ StackResource resource = resource();++ assertThrows(io.github.hectorvent.floci.core.common.AwsException.class,+ () -> provisioner.provision(resource, props, context()));+ assertEquals(created.trailArn(), resource.getPhysicalId(),+ "physicalId must be recorded right after createTrail succeeds, "+ + "before selector validation can fail and leak the created trail");+ }++ @Test+ void updateStopsLoggingWhenIsLoggingExplicitlyFalse() {+ Trail updated = trail("audit-trail", "arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail");+ when(trailService.updateTrail(eq("us-east-1"),+ eq("arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail"),+ eq("dest-bucket"), any(), any(), any(), any(), any(), any()))+ .thenReturn(updated);++ ObjectNode props = mapper.createObjectNode()+ .put("TrailName", "audit-trail")+ .put("S3BucketName", "dest-bucket")+ .put("IsLogging", false);+ StackResource resource = resource();+ resource.setPhysicalId("arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail");++ provisioner.provision(resource, props, context());++ verify(trailService).stopLogging("us-east-1", "arn:aws:cloudtrail:us-east-1:111122223333:trail/audit-trail");+ verify(trailService, never()).startLogging(anyString(), anyString());+ }++ @Test+ void deleteRemovesExistingTrailAndIsIdempotentWhenMissing() {+ when(trailService.describeTrails(eq("us-east-1"), eq(List.of("trail-arn"))))+ .thenReturn(List.of(trail("audit-trail", "trail-arn")));++ provisioner.delete("AWS::CloudTrail::Trail", "trail-arn", "us-east-1");++ verify(trailService).deleteTrail("us-east-1", "trail-arn");+ }++ @Test+ void deleteIsNoOpWhenTrailAlreadyGone() {+ when(trailService.describeTrails(eq("us-east-1"), eq(List.of("missing-arn"))))+ .thenReturn(List.of());++ provisioner.delete("AWS::CloudTrail::Trail", "missing-arn", "us-east-1");++ verify(trailService, never()).deleteTrail(anyString(), anyString());+ }++ private Trail trail(String name, String arn) {+ return new Trail(name, arn, "dest-bucket", null, null, true, false,+ "us-east-1", false, false, false, false);+ }++ private ProvisionContext context() {+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);+ when(engine.resolveNode(any(JsonNode.class))).thenAnswer(inv -> inv.getArgument(0));+ return new ProvisionContext(engine, "us-east-1", "111122223333", "stack");+ }++ private StackResource resource() {+ StackResource resource = new StackResource();+ resource.setLogicalId("AuditTrail");+ resource.setResourceType("AWS::CloudTrail::Trail");+ resource.setAttributes(new HashMap<>());+ return resource;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailAdvancedSelectorMatchingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailAdvancedSelectorMatchingTest.javanew file mode 100644index 0000000000..522ed7075c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailAdvancedSelectorMatchingTest.java@@ -0,0 +1,86 @@+package io.github.hectorvent.floci.services.cloudtrail;++import io.github.hectorvent.floci.services.cloudtrail.model.AdvancedFieldSelector;+import org.junit.jupiter.api.Test;++import java.util.List;++import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Unit tests for {@link CloudTrailService}'s advanced-selector field matcher, the building+ * block for AdvancedEventSelectors evaluation. Full capture/exclusion pipeline coverage lives+ * in {@code CloudTrailAdvancedSelectorsIntegrationTest}.+ */+class CloudTrailAdvancedSelectorMatchingTest {++ private static final String OTHER_BUCKET_ARN = "arn:aws:s3:::other-bucket/key";+ private static final String LOG_BUCKET_ARN = "arn:aws:s3:::log-bucket/some-key";+ private static final String OBJECT_TYPE = "AWS::S3::Object";+ private static final String BUCKET_TYPE = "AWS::S3::Bucket";++ @Test+ void eventCategoryEquals_matchesDataEvents() {+ AdvancedFieldSelector fs = new AdvancedFieldSelector(+ "eventCategory", List.of("Data"), null, null, null, null, null);+ assertTrue(CloudTrailService.matchesAdvancedFieldSelector(fs, OTHER_BUCKET_ARN, OBJECT_TYPE));+ }++ @Test+ void eventCategoryEquals_rejectsNonDataValue() {+ AdvancedFieldSelector fs = new AdvancedFieldSelector(+ "eventCategory", List.of("Management"), null, null, null, null, null);+ assertFalse(CloudTrailService.matchesAdvancedFieldSelector(fs, OTHER_BUCKET_ARN, OBJECT_TYPE));+ }++ @Test+ void resourcesTypeEquals_matchesS3Object() {+ AdvancedFieldSelector fs = new AdvancedFieldSelector(+ "resources.type", List.of("AWS::S3::Object"), null, null, null, null, null);+ assertTrue(CloudTrailService.matchesAdvancedFieldSelector(fs, OTHER_BUCKET_ARN, OBJECT_TYPE));+ }++ @Test+ void resourcesTypeEquals_rejectsBucketLevelOperation() {+ // Bucket-level calls (ListObjects, no object key) are AWS::S3::Bucket resources:+ // an AWS::S3::Object DataResource selector must never match them.+ AdvancedFieldSelector fs = new AdvancedFieldSelector(+ "resources.type", List.of("AWS::S3::Object"), null, null, null, null, null);+ assertFalse(CloudTrailService.matchesAdvancedFieldSelector(fs, "arn:aws:s3:::other-bucket", BUCKET_TYPE));+ }++ @Test+ void resourcesArnNotStartsWith_excludesMatchingPrefix() {+ AdvancedFieldSelector fs = new AdvancedFieldSelector(+ "resources.ARN", null, null, null, List.of("arn:aws:s3:::log-bucket/"), null, null);+ assertFalse(CloudTrailService.matchesAdvancedFieldSelector(fs, LOG_BUCKET_ARN, OBJECT_TYPE));+ assertTrue(CloudTrailService.matchesAdvancedFieldSelector(fs, OTHER_BUCKET_ARN, OBJECT_TYPE));+ }++ @Test+ void resourcesArnStartsWith_onlyMatchesGivenPrefix() {+ AdvancedFieldSelector fs = new AdvancedFieldSelector(+ "resources.ARN", null, null, List.of("arn:aws:s3:::log-bucket/"), null, null, null);+ assertTrue(CloudTrailService.matchesAdvancedFieldSelector(fs, LOG_BUCKET_ARN, OBJECT_TYPE));+ assertFalse(CloudTrailService.matchesAdvancedFieldSelector(fs, OTHER_BUCKET_ARN, OBJECT_TYPE));+ }++ @Test+ void resourcesArnEndsWithAndNotEndsWith() {+ AdvancedFieldSelector endsWith = new AdvancedFieldSelector(+ "resources.ARN", null, null, null, null, List.of("some-key"), null);+ assertTrue(CloudTrailService.matchesAdvancedFieldSelector(endsWith, LOG_BUCKET_ARN, OBJECT_TYPE));++ AdvancedFieldSelector notEndsWith = new AdvancedFieldSelector(+ "resources.ARN", null, null, null, null, null, List.of("some-key"));+ assertFalse(CloudTrailService.matchesAdvancedFieldSelector(notEndsWith, LOG_BUCKET_ARN, OBJECT_TYPE));+ }++ @Test+ void unsupportedField_neverMatches() {+ AdvancedFieldSelector fs = new AdvancedFieldSelector(+ "readOnly", List.of("true"), null, null, null, null, null);+ assertFalse(CloudTrailService.matchesAdvancedFieldSelector(fs, OTHER_BUCKET_ARN, OBJECT_TYPE));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailAdvancedSelectorsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailAdvancedSelectorsIntegrationTest.javanew file mode 100644index 0000000000..6cc9e04bbe--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailAdvancedSelectorsIntegrationTest.java@@ -0,0 +1,186 @@+package io.github.hectorvent.floci.services.cloudtrail;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * End-to-end coverage for AdvancedEventSelectors: the trail's S3 data-event capture decision+ * must be driven by the advanced selector, not the basic one, once advanced selectors are set.+ * This is the reproduction case for the CloudTrail circular-logging cost problem: excluding the+ * trail's own destination bucket via {@code resources.ARN notStartsWith} stops the trail from+ * recording its own delivery writes.+ */+@QuarkusTest+class CloudTrailAdvancedSelectorsIntegrationTest {++ private static final String CT_TARGET = "CloudTrail_20131101.";+ private static final String JSON11 = "application/x-amz-json-1.1";++ @Inject+ CloudTrailLogWriter writer;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void advancedSelectorsExcludeLogBucketButCaptureOthers() throws Exception {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String logBucket = "log-bucket-" + suffix;+ String otherBucket = "other-bucket-" + suffix;+ String destBucket = "audit-dest-" + suffix;+ String trailName = "adv-" + suffix;++ createBucket(logBucket);+ createBucket(otherBucket);+ createBucket(destBucket);++ invokeCloudTrail("CreateTrail", String.format("""+ {"Name":"%s","S3BucketName":"%s"}+ """, trailName, destBucket))+ .then().statusCode(200);++ String putAdvanced = String.format("""+ {"TrailName":"%s","AdvancedEventSelectors":[+ {"Name":"exclude-log-bucket","FieldSelectors":[+ {"Field":"eventCategory","Equals":["Data"]},+ {"Field":"resources.type","Equals":["AWS::S3::Object"]},+ {"Field":"resources.ARN","NotStartsWith":["arn:aws:s3:::%s/"]}+ ]}+ ]}+ """, trailName, logBucket);+ invokeCloudTrail("PutEventSelectors", putAdvanced)+ .then().statusCode(200)+ .body(containsString("AdvancedEventSelectors"));++ invokeCloudTrail("StartLogging", String.format("{\"Name\":\"%s\"}", trailName))+ .then().statusCode(200);++ putObject(logBucket, "some-key", "excluded");+ putObject(otherBucket, "key", "captured");++ writer.flushNow();++ String listingXml = given()+ .when().get("/" + destBucket + "?list-type=2")+ .then().statusCode(200)+ .extract().asString();++ assertTrue(listingXml.contains(".json.gz"),+ "Expected a delivered log file for the captured (other-bucket) event:\n" + listingXml);++ String logKey = extractFirstKey(listingXml);+ byte[] gz = given().when().get("/" + destBucket + "/" + logKey)+ .then().statusCode(200).extract().asByteArray();+ String json = gunzip(gz);++ assertTrue(json.contains(otherBucket), "Expected other-bucket event to be captured:\n" + json);+ assertFalse(json.contains(logBucket), "Expected log-bucket event to be excluded:\n" + json);+ }++ @Test+ void basicSelectorsStillCaptureAllS3DataEvents() throws Exception {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String sourceBucket = "basic-source-" + suffix;+ String destBucket = "basic-dest-" + suffix;+ String trailName = "basic-" + suffix;++ createBucket(sourceBucket);+ createBucket(destBucket);++ invokeCloudTrail("CreateTrail", String.format("""+ {"Name":"%s","S3BucketName":"%s"}+ """, trailName, destBucket))+ .then().statusCode(200);++ String putBasic = String.format("""+ {"TrailName":"%s","EventSelectors":[+ {"ReadWriteType":"All","DataResources":[+ {"Type":"AWS::S3::Object","Values":["arn:aws:s3:::%s/"]}+ ]}+ ]}+ """, trailName, sourceBucket);+ invokeCloudTrail("PutEventSelectors", putBasic)+ .then().statusCode(200)+ .body(containsString("EventSelectors"));++ invokeCloudTrail("StartLogging", String.format("{\"Name\":\"%s\"}", trailName))+ .then().statusCode(200);++ putObject(sourceBucket, "hello.txt", "hello");+ writer.flushNow();++ String listingXml = given()+ .when().get("/" + destBucket + "?list-type=2")+ .then().statusCode(200)+ .extract().asString();+ assertTrue(listingXml.contains(".json.gz"), "Basic selector should still capture events:\n" + listingXml);+ }++ @Test+ void puttingBothBasicAndAdvancedSelectorsErrors() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String destBucket = "both-dest-" + suffix;+ String trailName = "both-" + suffix;++ createBucket(destBucket);+ invokeCloudTrail("CreateTrail", String.format("""+ {"Name":"%s","S3BucketName":"%s"}+ """, trailName, destBucket))+ .then().statusCode(200);++ String putBoth = String.format("""+ {"TrailName":"%s",+ "EventSelectors":[{"ReadWriteType":"All"}],+ "AdvancedEventSelectors":[{"Name":"x","FieldSelectors":[+ {"Field":"eventCategory","Equals":["Data"]}]}]}+ """, trailName);+ invokeCloudTrail("PutEventSelectors", putBoth)+ .then().statusCode(400)+ .body(containsString("InvalidEventSelectorsException"));+ }++ // --- Helpers ---++ private static io.restassured.response.Response invokeCloudTrail(String action, String body) {+ return given()+ .header("X-Amz-Target", CT_TARGET + action)+ .contentType(JSON11)+ .body(body)+ .when().post("/");+ }++ private static void createBucket(String name) {+ given().when().put("/" + name).then().statusCode(200);+ }++ private static void putObject(String bucket, String key, String body) {+ given().body(body)+ .when().put("/" + bucket + "/" + key)+ .then().statusCode(200);+ }++ private static String extractFirstKey(String xml) {+ int open = xml.indexOf("<Key>");+ if (open < 0) return null;+ int close = xml.indexOf("</Key>", open);+ return xml.substring(open + 5, close);+ }++ private static String gunzip(byte[] gz) throws Exception {+ try (var gzin = new java.util.zip.GZIPInputStream(new java.io.ByteArrayInputStream(gz))) {+ return new String(gzin.readAllBytes());+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailListingAndTagsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailListingAndTagsIntegrationTest.javanew file mode 100644index 0000000000..38315821c1--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailListingAndTagsIntegrationTest.java@@ -0,0 +1,177 @@+package io.github.hectorvent.floci.services.cloudtrail;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * End-to-end coverage for ListTrails, AddTags, and ListTags: the trail+ * discovery and tagging control-plane actions.+ */+@QuarkusTest+class CloudTrailListingAndTagsIntegrationTest {++ private static final String CT_TARGET = "CloudTrail_20131101.";+ private static final String JSON11 = "application/x-amz-json-1.1";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void listTrailsIncludesCreatedTrailByNameArnAndHomeRegion() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String trailName = "list-" + suffix;+ String destBucket = "list-logs-" + suffix;++ createBucket(destBucket);+ String createBody = invokeCloudTrail("CreateTrail", String.format("""+ {"Name":"%s","S3BucketName":"%s"}+ """, trailName, destBucket))+ .then().statusCode(200)+ .extract().asString();+ String trailArn = extractField(createBody, "TrailARN");++ String listBody = invokeCloudTrail("ListTrails", "{}")+ .then().statusCode(200)+ .body(containsString(trailName))+ .body(containsString(trailArn))+ .body(containsString("us-east-1"))+ .extract().asString();++ assertTrue(listBody.contains("\"Name\":\"" + trailName + "\""),+ "Expected ListTrails to include trail name:\n" + listBody);+ assertTrue(listBody.contains("\"TrailARN\":\"" + trailArn + "\""),+ "Expected ListTrails to include trail ARN:\n" + listBody);+ assertTrue(listBody.contains("\"HomeRegion\":\"us-east-1\""),+ "Expected ListTrails to include home region:\n" + listBody);+ }++ @Test+ void addTagsThenListTagsRoundTripsByResourceId() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String trailName = "tag-" + suffix;+ String destBucket = "tag-logs-" + suffix;++ createBucket(destBucket);+ String createBody = invokeCloudTrail("CreateTrail", String.format("""+ {"Name":"%s","S3BucketName":"%s"}+ """, trailName, destBucket))+ .then().statusCode(200)+ .extract().asString();+ String trailArn = extractField(createBody, "TrailARN");++ invokeCloudTrail("AddTags", String.format("""+ {"ResourceId":"%s","TagsList":[+ {"Key":"Environment","Value":"prod"},+ {"Key":"Owner","Value":"security-team"}+ ]}+ """, trailArn))+ .then().statusCode(200);++ String listTagsBody = invokeCloudTrail("ListTags", String.format("""+ {"ResourceIdList":["%s"]}+ """, trailArn))+ .then().statusCode(200)+ .body(containsString(trailArn))+ .body(containsString("Environment"))+ .body(containsString("prod"))+ .body(containsString("Owner"))+ .body(containsString("security-team"))+ .extract().asString();++ assertTrue(listTagsBody.contains("\"ResourceId\":\"" + trailArn + "\""),+ "Expected ListTags to key by resource id:\n" + listTagsBody);+ }++ @Test+ void addTagsMergesWithPreviouslyAddedTags() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String trailName = "merge-" + suffix;+ String destBucket = "merge-logs-" + suffix;++ createBucket(destBucket);+ String createBody = invokeCloudTrail("CreateTrail", String.format("""+ {"Name":"%s","S3BucketName":"%s"}+ """, trailName, destBucket))+ .then().statusCode(200)+ .extract().asString();+ String trailArn = extractField(createBody, "TrailARN");++ invokeCloudTrail("AddTags", String.format("""+ {"ResourceId":"%s","TagsList":[{"Key":"Environment","Value":"prod"}]}+ """, trailArn))+ .then().statusCode(200);+ invokeCloudTrail("AddTags", String.format("""+ {"ResourceId":"%s","TagsList":[{"Key":"Owner","Value":"security-team"}]}+ """, trailArn))+ .then().statusCode(200);++ invokeCloudTrail("ListTags", String.format("""+ {"ResourceIdList":["%s"]}+ """, trailArn))+ .then().statusCode(200)+ .body(containsString("Environment"))+ .body(containsString("Owner"));+ }++ @Test+ void addTagsRejectsMoreThanTwoHundredTags() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String trailName = "toomany-" + suffix;+ String destBucket = "toomany-logs-" + suffix;++ createBucket(destBucket);+ String createBody = invokeCloudTrail("CreateTrail", String.format("""+ {"Name":"%s","S3BucketName":"%s"}+ """, trailName, destBucket))+ .then().statusCode(200)+ .extract().asString();+ String trailArn = extractField(createBody, "TrailARN");++ StringBuilder tags = new StringBuilder();+ for (int i = 0; i < 201; i++) {+ if (i > 0) {+ tags.append(",");+ }+ tags.append(String.format("{\"Key\":\"k%d\",\"Value\":\"v%d\"}", i, i));+ }++ invokeCloudTrail("AddTags", String.format("""+ {"ResourceId":"%s","TagsList":[%s]}+ """, trailArn, tags))+ .then().statusCode(400)+ .body(containsString("TagsLimitExceededException"));+ }++ // --- Helpers ---++ private static io.restassured.response.Response invokeCloudTrail(String action, String body) {+ return given()+ .header("X-Amz-Target", CT_TARGET + action)+ .contentType(JSON11)+ .body(body)+ .when().post("/");+ }++ private static void createBucket(String name) {+ given().when().put("/" + name).then().statusCode(200);+ }++ private static String extractField(String json, String field) {+ String marker = "\"" + field + "\":\"";+ int open = json.indexOf(marker);+ if (open < 0) return null;+ int start = open + marker.length();+ int close = json.indexOf('"', start);+ return json.substring(start, close);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterRequeueTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterRequeueTest.javanew file mode 100644index 0000000000..476cd38e1f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailLogWriterRequeueTest.java@@ -0,0 +1,129 @@+package io.github.hectorvent.floci.services.cloudtrail;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.services.cloudtrail.model.Trail;+import io.quarkus.test.junit.QuarkusMock;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;+import java.util.List;+import java.util.UUID;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * Reproduces the review finding on {@link CloudTrailLogWriter#flushTrail}: the+ * self-delivery {@code emitS3DataEvent} call was folded into the same+ * try/catch as the S3 write. If emission fails AFTER the write already+ * succeeded, the catch re-queues records that were already durably delivered,+ * causing the next flush to write a duplicate log file to S3.+ *+ * <p>{@link CloudTrailService} is fully mocked here (rather than spied) to+ * avoid recursing through its Arc client proxy, and to deterministically+ * force the post-write emission failure that is not otherwise reachable+ * through the real implementation (which defensively swallows its own+ * exceptions).+ */+@QuarkusTest+class CloudTrailLogWriterRequeueTest {++ @Inject+ CloudTrailLogWriter writer;++ @Inject+ CloudTrailService realService;++ @AfterEach+ void restoreRealService() {+ QuarkusMock.installMockForType(realService, CloudTrailService.class);+ }++ @Test+ void selfDeliveryEmissionFailureAfterSuccessfulWriteDoesNotDuplicateDelivery() {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String bucket = "requeue-logs-" + suffix;+ String trailName = "requeue-trail-" + suffix;+ String region = "us-east-1";++ createBucket(bucket);++ Trail trail = new Trail(trailName, "arn:aws:cloudtrail:" + region + ":000000000000:trail/" + trailName,+ bucket, null, null, true, false, region, false, false, false, false);+ CloudTrailService.TrailKey key = new CloudTrailService.TrailKey(region, trailName, region);++ ObjectMapper mapper = new ObjectMapper();+ List<ObjectNode> pending = new ArrayList<>(List.of(mapper.createObjectNode().put("eventName", "PutObject")));++ CloudTrailService mockService = mock(CloudTrailService.class);+ when(mockService.trailsWithPendingRecords())+ .thenAnswer(inv -> pending.isEmpty() ? List.of() : List.of(key));+ when(mockService.getTrail(region, trailName)).thenReturn(trail);+ when(mockService.drainPendingRecords(key)).thenAnswer(inv -> {+ List<ObjectNode> drained = new ArrayList<>(pending);+ pending.clear();+ return drained;+ });+ doAnswer(inv -> {+ List<ObjectNode> records = inv.getArgument(1);+ pending.addAll(records);+ return null;+ }).when(mockService).requeueRecords(eq(key), any());+ doThrow(new RuntimeException("boom: self-delivery emission failed"))+ .when(mockService).emitS3DataEvent(any());++ QuarkusMock.installMockForType(mockService, CloudTrailService.class);++ // Delivery attempt #1: the S3 write succeeds, but the self-delivery+ // emission afterward throws. Under the bug, that throw re-queues the+ // already-written records back into `pending`.+ writer.flushNow();++ // Delivery attempt #2: if the records were wrongly re-queued, this+ // flush writes them again, producing a second log file for the same+ // batch.+ writer.flushNow();++ List<String> logFiles = new ArrayList<>();+ for (String k : listKeys(bucket)) {+ if (k.contains("/CloudTrail/") && k.endsWith(".json.gz")) {+ logFiles.add(k);+ }+ }+ assertEquals(1, logFiles.size(),+ "Expected exactly one delivered log file: a self-delivery emission "+ + "failure must not re-queue records that were already durably "+ + "written to S3, but found: " + logFiles);+ }++ // --- Helpers ---++ private static void createBucket(String name) {+ given().when().put("/" + name).then().statusCode(200);+ }++ private static List<String> listKeys(String bucket) {+ String xml = given().when().get("/" + bucket + "?list-type=2")+ .then().statusCode(200).extract().asString();+ List<String> keys = new ArrayList<>();+ int from = 0;+ while (true) {+ int open = xml.indexOf("<Key>", from);+ if (open < 0) break;+ int close = xml.indexOf("</Key>", open);+ keys.add(xml.substring(open + 5, close));+ from = close + 6;+ }+ return keys;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailNameValidationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailNameValidationTest.javaindex 97a5db1092..3e62b7f774 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailNameValidationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailNameValidationTest.java@@ -90,4 +90,28 @@ class CloudTrailNameValidationTest {.then().statusCode(200);}++ @Test+ void putEventSelectors_missingTrailName_rejectsWithTrailNotFoundException() {+ given()+ .header("X-Amz-Target", CT_TARGET + "PutEventSelectors")+ .contentType(JSON11)+ .body("{\"EventSelectors\":[{\"ReadWriteType\":\"All\"}]}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body(containsString("TrailNotFoundException"));+ }++ @Test+ void getEventSelectors_missingTrailName_rejectsWithTrailNotFoundException() {+ given()+ .header("X-Amz-Target", CT_TARGET + "GetEventSelectors")+ .contentType(JSON11)+ .body("{}")+ .when().post("/")+ .then()+ .statusCode(400)+ .body(containsString("TrailNotFoundException"));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelfDeliveryTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelfDeliveryTest.javanew file mode 100644index 0000000000..190ab20bc1--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailSelfDeliveryTest.java@@ -0,0 +1,162 @@+package io.github.hectorvent.floci.services.cloudtrail;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import jakarta.inject.Inject;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.io.ByteArrayInputStream;+import java.util.ArrayList;+import java.util.List;+import java.util.UUID;+import java.util.zip.GZIPInputStream;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Reproduces issue 0034: a trail whose blanket S3 data-event selector matches+ * its own destination bucket must see its own log deliveries as PutObject+ * data events (the circular-logging bug PR #1194 / upstream issue #1192+ * describe). {@link CloudTrailLogWriter} writes deliveries via a direct+ * {@code S3Service} call, which must still be visible to CloudTrail's own+ * data-event capture, not just API-driven writes.+ */+@QuarkusTest+class CloudTrailSelfDeliveryTest {++ private static final String CT_TARGET = "CloudTrail_20131101.";+ private static final String JSON11 = "application/x-amz-json-1.1";++ @Inject+ CloudTrailLogWriter writer;++ @Test+ void trailWithBlanketSelectorCapturesItsOwnLogDeliveryAsDataEvent() throws Exception {+ String suffix = UUID.randomUUID().toString().substring(0, 8);+ String bucket = "loop-logs-" + suffix;+ String trailName = "loop-trail-" + suffix;++ createBucket(bucket);++ invokeCloudTrail("CreateTrail", String.format("""+ {"Name":"%s","S3BucketName":"%s"}+ """, trailName, bucket))+ .then().statusCode(200);++ // Blanket selector: every S3 object in every bucket, including the+ // trail's own delivery bucket. This is the pathological "before"+ // config (uc-build-loop): s3DataEvents true, no exclusions.+ invokeCloudTrail("PutEventSelectors", String.format("""+ {+ "TrailName": "%s",+ "EventSelectors": [+ {+ "ReadWriteType": "All",+ "IncludeManagementEvents": false,+ "DataResources": [+ {"Type": "AWS::S3::Object", "Values": ["arn:aws:s3:::"]}+ ]+ }+ ]+ }+ """, trailName))+ .then().statusCode(200);++ invokeCloudTrail("StartLogging",+ String.format("{\"Name\":\"%s\"}", trailName))+ .then().statusCode(200);++ // Seed one real data event so the first flush has something to+ // deliver.+ putObject(bucket, "seed.txt", "seed");++ // Delivery #1: writes a log file into `bucket`. Under the fix, that+ // write is itself a PutObject matching the blanket selector, so it+ // must be queued for delivery #2.+ writer.flushNow();++ // Delivery #2: should contain a record describing delivery #1's own+ // log-file write, the self-referential loop.+ writer.flushNow();++ List<String> keys = new ArrayList<>();+ for (String key : listKeys(bucket)) {+ if (key.contains("/CloudTrail/") && key.endsWith(".json.gz")) {+ keys.add(key);+ }+ }+ assertTrue(keys.size() >= 2,+ "Expected at least 2 delivered log files (seed delivery + self-referential delivery), got: "+ + keys);++ boolean sawSelfReferentialPut = false;+ ObjectMapper mapper = new ObjectMapper();+ for (String key : keys) {+ byte[] gz = given().when().get("/" + bucket + "/" + key)+ .then().statusCode(200).extract().asByteArray();+ byte[] json;+ try (GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(gz))) {+ json = gzin.readAllBytes();+ }+ JsonNode records = mapper.readTree(json).get("Records");+ for (JsonNode rec : records) {+ String eventName = rec.path("eventName").asText();+ String recBucket = rec.path("requestParameters").path("bucketName").asText(null);+ String recKey = rec.path("requestParameters").path("key").asText("");+ if ("PutObject".equals(eventName) && bucket.equals(recBucket)+ && recKey.contains("/CloudTrail/")) {+ sawSelfReferentialPut = true;+ }+ }+ }++ assertTrue(sawSelfReferentialPut,+ "Expected a PutObject record for the trail's own CloudTrail log delivery "+ + "(self-referential / circular-logging reproduction) but found none in "+ + keys.size() + " delivered files");+ }++ // --- Helpers ---++ private static io.restassured.response.Response invokeCloudTrail(String action, String body) {+ return given()+ .header("X-Amz-Target", CT_TARGET + action)+ .contentType(JSON11)+ .body(body)+ .when().post("/");+ }++ private static void createBucket(String name) {+ given().when().put("/" + name).then().statusCode(200);+ }++ private static void putObject(String bucket, String key, String body) {+ given().body(body)+ .when().put("/" + bucket + "/" + key)+ .then().statusCode(200);+ }++ private static List<String> listKeys(String bucket) {+ String xml = given().when().get("/" + bucket + "?list-type=2")+ .then().statusCode(200).extract().asString();+ List<String> keys = new ArrayList<>();+ int from = 0;+ while (true) {+ int open = xml.indexOf("<Key>", from);+ if (open < 0) break;+ int close = xml.indexOf("</Key>", open);+ keys.add(xml.substring(open + 5, close));+ from = close + 6;+ }+ return keys;+ }++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }+}diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsvindex bc36c487b7..9ef1d3caf2 100644--- a/src/test/resources/cloudformation/supported-resource-types.tsv+++ b/src/test/resources/cloudformation/supported-resource-types.tsv@@ -28,6 +28,7 @@ AWS::CDK::Metadata CdkMetadataCfnProvisionerAWS::CertificateManager::Certificate AcmCfnProvisionerAWS::CloudFormation::CustomResource LEGACY_SWITCHAWS::CloudFront::Distribution LEGACY_SWITCH+AWS::CloudTrail::Trail CloudTrailCfnProvisionerAWS::CloudWatch::Alarm CloudWatchCfnProvisionerAWS::CodeBuild::Project CodeBuildCfnProvisionerAWS::CodePipeline::CustomActionType CodePipelineCfnProvisionerdiff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yamlindex ca4a97c0e6..d095c052ec 100644--- a/tools/docs/cfn_resource_types.yaml+++ b/tools/docs/cfn_resource_types.yaml@@ -49,6 +49,7 @@ order:- AWS::WAFv2- AWS::Config- AWS::CloudFormation+ - AWS::CloudTrail- Custom- AWS::CDK@@ -105,6 +106,7 @@ service_labels:AWS::CertificateManager: ACMAWS::CloudFormation: CloudFormationAWS::CloudFront: CloudFront+ AWS::CloudTrail: CloudTrailAWS::CloudWatch: CloudWatchAWS::CodeBuild: CodeBuildAWS::CodePipeline: CodePipeline