feat(cloudtrail): support AdvancedEventSelectors and CloudFormation Trail provisioning (#2720)

* feat(cloudtrail): support AdvancedEventSelectors in PutEventSelectors and S3 capture

Adds AdvancedEventSelector/AdvancedFieldSelector models, JSON wiring
through PutEventSelectors/GetEventSelectors, mutual-exclusivity
enforcement against basic EventSelectors, and field-selector evaluation
(Equals/NotEquals/StartsWith/NotStartsWith/EndsWith/NotEndsWith) in the
S3 data-event capture path. Lets a trail exclude its own log-delivery
bucket via resources.ARN NotStartsWith, avoiding the CloudTrail
circular-logging cost problem. Basic-selector behavior is unchanged.

* feat(cloudtrail): add CloudFormation provisioner for AWS::CloudTrail::Trail

Handles create/update/delete of AWS::CloudTrail::Trail via
CloudTrailService, applies EventSelectors or AdvancedEventSelectors
(mutually exclusive, same JSON shapes as PutEventSelectors), starts
logging when IsLogging is true, and sets the trail ARN as the
resource's physical id and Arn attribute. Delete is idempotent when
the trail is already gone.

* feat(cloudtrail): implement ListTrails and trail tagging

Adds ListTrails (returns Name/TrailARN/HomeRegion for trails visible
in the region, including multi-region trails), plus AddTags/ListTags
backed by per-trail stored state, keyed by trail name or ARN.

* fix(cloudtrail): emit data events for the trail's own log deliveries

CloudTrailLogWriter.flushTrail() wrote delivered log files via a direct
S3Service.putObject() call, bypassing S3Controller.emitCloudTrailEvent()
- the only place that recorded an S3 data event. A trail whose selector
matched its own destination bucket (the exact circular-logging config
from upstream issue #1192 / PR #1194) never saw its own deliveries,
so the emulator could prove the dangerous config was live but not
reproduce the loop it causes.

flushTrail now calls cloudTrailService.emitS3DataEvent() after each
delivery, so internal writes are evaluated against selectors identically
to API-driven ones. Closes issues/0034.

* docs: mark issue 0034 fixed

* fix(cloudtrail): resources.type reflects actual S3 resource, not hardcoded object

Advanced selector matching hardcoded resources.type to AWS::S3::Object for
every event, so an object-scoped AdvancedEventSelectors exclusion (the
real-world fix for the issue 0034 self-delivery loop) still let bucket-level
calls like ListObjects through against the excluded bucket. Now derived per
event from whether an object key is present.

Live-verified on 1160-ct: loop confirmed unbounded and compounding with
external writes, then confirmed stopped by the real AdvancedEventSelectors
remediation, with this gap found and closed in the same pass. Details in
issues/0034 and issues/0035.

* docs(0034): add raw delivery-size timeline from 1160-ct verification

Per-cycle size data showing the burst-compounding and the fix-stop point
concretely, not just summarized.

* fix(cloudtrail): match delete() to current CfnResourceProvisioner signature

Upstream/main dropped the accountId parameter from
CfnResourceProvisioner.delete() since this branch was originally
authored; the provisioner never used accountId in its body, so the
fix is a straight signature match with no behavior change.

* docs(cloudtrail): regen action table and register CFN Trail resource type

New ListTrails/AddTags/ListTags actions and the CloudFormation
AWS::CloudTrail::Trail resource type need doc entries per the repo's
docs-check gate.

* fix(cloudtrail): enforce AddTags 200-tag list limit

Botocore's AddTagsRequest.TagsList models a 200-item max (service-2.json,
cloudtrail 2013-11-01); the handler accepted an unbounded list. RED test
added first (addTagsRejectsMoreThanTwoHundredTags), confirmed failing
(200 instead of 400), then fixed by rejecting oversized lists with
TagsLimitExceededException, matching AWS's modeled error for AddTags.

* fix(cloudformation): close two audit-control gaps in CloudTrailCfnProvisioner

Local code review flagged two HIGH findings in the new CFN provisioner:

- physicalId was only set after selector validation and startLogging
  succeeded, so a create that failed on the mutually-exclusive
  EventSelectors/AdvancedEventSelectors check left a real trail with no
  recorded physical id for the engine to clean up. Now set immediately
  after createTrail returns.
- update only called startLogging when IsLogging was explicitly true,
  never stopLogging when it was explicitly false, so a template setting
  IsLogging: false on a currently-logging trail silently left logging
  enabled.

RED tests confirmed both failures against the pre-fix code, then GREEN
after the fix (6/6 provisioner tests, 51/51 CloudTrail suite).

* docs(issues): ledger deferred CloudTrail local-review findings

MEDIUM/LOW findings from the local code-review pass, plus a few
inherited-not-ours items on code this branch didn't touch, that are
real but out of scope for the CFN provisioner / advanced-selectors PR.

* style(cloudtrail): brace unbraced conditionals in ListTrails and event-matching traversal

Per AGENTS.md style rule (always use braces in conditionals).

* fix(cloudtrail): avoid NPE on List.of(trailName) when TrailName is missing

PutEventSelectors/GetEventSelectors called List.of(trailName) with a
possibly-null trailName before findTrailOrThrow could validate it,
throwing an NPE (500 InternalFailure) instead of the modeled
TrailNotFoundException. Guard the lookup so the null flows through to
the existing validation.

* fix(cloudtrail): do not re-queue records on self-delivery emission failure

flushTrail wrapped the self-delivery emitS3DataEvent call in the same
try/catch as the S3 write. A failure there re-queued records that were
already durably written, causing the next flush to redeliver the same
batch. Split the write and the emission into separate try blocks so
only a write failure triggers requeue.

* docs(cloudformation): register AWS::CloudTrail::Trail in the resource-type inventory

CfnResourceInventoryTest and the docs-sync resource-type table both
derived from supported-resource-types.tsv, which never picked up
CloudTrailCfnProvisioner's registration.

* docs(issues): drop fork-local ledger files from the PR

Per maintainer review, the issues/ ledger entries are fork-local tracking notes and are kept out of the upstream contribution.

* fix(cloudformation): wire CloudTrailCfnProvisioner into CfnProvisionerFixture

CfnProvisionerFixtureTest.everyProvisionerIsReachableThroughThePublicBuilderOrExplicitlyExempt
failed because CloudTrailCfnProvisioner had no field, setter, or
construction arm in the test fixture, so a test naming CloudTrailService
would silently fall through to the stub arm instead of exercising the
real provisioner.

Add cloudTrailService field, cloudTrail(CloudTrailService) setter, and
the discovered.add(new CloudTrailCfnProvisioner(...)) construction arm,
mirroring the existing Route53Service wiring.

* fix(cloudtrail): drop em-dashes from new test comments per AGENTS.md style check

* fix(cloudtrail): reject mixed basic and advanced selectors with InvalidEventSelectorsException

PutEventSelectors does not model InvalidParameterCombinationException; the
error it declares for an invalid selector combination is
InvalidEventSelectorsException (botocore cloudtrail/2013-11-01). Both the
JSON handler and the AWS::CloudTrail::Trail provisioner now throw that
code, and the integration test pins it. Also braces the remaining
one-line conditionals in matchesAdvancedFieldSelector.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-09-08 19:38:13 -05:00
1 parent c1e5cc239f
commit fd3c4d9ab6
20 files changed
+1416 -30

No files matched your search

@@ -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();
}
}
@@ -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 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, advancedSelectors, true, time,
stopLoggingTime, tags);
}
public CloudTrailEntry stopLogging(long time) {
return new CloudTrailEntry(trail, selectors, advancedSelectors, false, startLoggingTime,
time, tags);
}
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());
return new CloudTrailEntry(updatedTrail, updated, logging, startLoggingTime, stopLoggingTime, tags);
}
public CloudTrailEntry startLogging(long time) {
return new CloudTrailEntry(trail, selectors, true, time, stopLoggingTime, tags);
}
public CloudTrailEntry stopLogging(long time) {
return new CloudTrailEntry(trail, selectors, false, startLoggingTime, time, tags);
}
public CloudTrailEntry withTags(Map<String, String> updated) {
return new CloudTrailEntry(trail, selectors, logging, startLoggingTime, stopLoggingTime, updated);
}
/** Returns a mutable copy suitable for merging in new tags. */
@@ -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();
}
@@ -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) {
@@ -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;
}
}
@@ -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;
@@ -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) {
}
@@ -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) {
}