Files
floci/docs/services/cloudtrail.md
T
Sam Fakhreddine fd3c4d9ab6 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.
2026-09-08 19:38:13 -05:00

98 lines
3.4 KiB
Markdown

# CloudTrail
**Protocol:** JSON 1.1 (`X-Amz-Target: com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.*`)
**Endpoint:** `POST http://localhost:4566/`
Floci emulates a CloudTrail trail's full life cycle and emits S3 data
events to the trail's destination bucket as gzipped JSON log files at the
AWS-shaped key path:
```
${prefix}AWSLogs/${accountId}/CloudTrail/${region}/yyyy/MM/dd/${accountId}_CloudTrail_${region}_${YYYYMMDDTHHMMZ}_${rand12}.json.gz
```
## Supported Actions
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `CreateTrail` | Creates a trail, optionally tagged via `TagsList`, and returns its ARN |
| `DescribeTrails` | Returns the settings for one or more trails |
| `DeleteTrail` | Deletes a trail |
| `UpdateTrail` | Updates the settings of an existing trail |
| `PutEventSelectors` | Configures the event selectors for a trail |
| `GetEventSelectors` | - |
| `StartLogging` | Starts logging for a trail |
| `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 |
<!-- floci:actions:end -->
Selector matching honors `ReadWriteType` (`All`, `ReadOnly`, `WriteOnly`)
and `AWS::S3::Object` data resource ARNs in any of these forms:
- `arn:aws:s3:::` — every bucket
- `arn:aws:s3:::bucket/` — every key in the bucket
- `arn:aws:s3:::bucket/prefix` — keys with the given prefix
- `arn:aws:s3:::bucket/prefix/key` — exact key match
## S3 Hook Coverage
Floci emits a CloudTrail data event whenever any of these S3 ops runs
against a bucket matched by an active trail's selectors:
- `PutObject`, `GetObject`, `HeadObject`, `DeleteObject`, `ListObjects`,
`GetObjectAcl`
Both success and `AwsException` paths emit; the latter populates
`errorCode` / `errorMessage` (`NoSuchKey`, `NoSuchBucketPolicy`, etc.).
If `floci.iam.enforcement-enabled` is set, IAM-deny responses also emit
records with `errorCode: "AccessDenied"` for the same op set.
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_CLOUDTRAIL_ENABLED` | `true` | Enable or disable the service |
| `FLOCI_SERVICES_CLOUDTRAIL_FLUSH_INTERVAL_SECONDS` | `60` | How often the writer flushes buffered records into the destination bucket. Real CloudTrail delivers with ~5 minute latency; the local default is shorter for fast feedback loops. |
## Example
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test
aws s3 mb s3://my-source
aws s3 mb s3://my-trail-logs
aws cloudtrail create-trail \
--name my-trail \
--s3-bucket-name my-trail-logs
aws cloudtrail put-event-selectors \
--trail-name my-trail \
--event-selectors '[{
"ReadWriteType": "All",
"IncludeManagementEvents": false,
"DataResources": [{
"Type": "AWS::S3::Object",
"Values": ["arn:aws:s3:::my-source/"]
}]
}]'
aws cloudtrail start-logging --name my-trail
# Drive some traffic
echo hello | aws s3 cp - s3://my-source/greeting.txt
aws s3 cp s3://my-source/greeting.txt -
# After ~60s, log files appear
aws s3 ls s3://my-trail-logs/AWSLogs/ --recursive
```