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

@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScali
import 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.SsmCfnPro
import 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;
@@ -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;
}
}
@@ -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));
}
}
@@ -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());
}
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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"));
}
}
@@ -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();
}
}