mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
c1e5cc239f
commit
fd3c4d9ab6
20 files changed
+1416
-30
No files matched your search
@@ -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 -->
|
||||
|
||||
|
||||
@@ -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 |
|
||||
|
||||
+122
@@ -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. */
|
||||
|
||||
+37
-7
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
+32
-2
@@ -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) {
|
||||
|
||||
+78
@@ -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;
|
||||
}
|
||||
}
|
||||
+126
-6
@@ -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;
|
||||
|
||||
+16
@@ -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) {
|
||||
}
|
||||
+21
@@ -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) {
|
||||
}
|
||||
+11
@@ -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;
|
||||
|
||||
+170
@@ -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;
|
||||
}
|
||||
}
|
||||
+86
@@ -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));
|
||||
}
|
||||
}
|
||||
+186
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+177
@@ -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);
|
||||
}
|
||||
}
|
||||
+129
@@ -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;
|
||||
}
|
||||
}
|
||||
+24
@@ -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"));
|
||||
}
|
||||
}
|
||||
+162
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ AWS::CDK::Metadata CdkMetadataCfnProvisioner
|
||||
AWS::CertificateManager::Certificate AcmCfnProvisioner
|
||||
AWS::CloudFormation::CustomResource LEGACY_SWITCH
|
||||
AWS::CloudFront::Distribution LEGACY_SWITCH
|
||||
AWS::CloudTrail::Trail CloudTrailCfnProvisioner
|
||||
AWS::CloudWatch::Alarm CloudWatchCfnProvisioner
|
||||
AWS::CodeBuild::Project CodeBuildCfnProvisioner
|
||||
AWS::CodePipeline::CustomActionType CodePipelineCfnProvisioner
|
||||
|
||||
|
@@ -49,6 +49,7 @@ order:
|
||||
- AWS::WAFv2
|
||||
- AWS::Config
|
||||
- AWS::CloudFormation
|
||||
- AWS::CloudTrail
|
||||
- Custom
|
||||
- AWS::CDK
|
||||
|
||||
@@ -105,6 +106,7 @@ service_labels:
|
||||
AWS::CertificateManager: ACM
|
||||
AWS::CloudFormation: CloudFormation
|
||||
AWS::CloudFront: CloudFront
|
||||
AWS::CloudTrail: CloudTrail
|
||||
AWS::CloudWatch: CloudWatch
|
||||
AWS::CodeBuild: CodeBuild
|
||||
AWS::CodePipeline: CodePipeline
|
||||
|
||||
Reference in new issue
Block a user