Commit Graph
10 Commits
Author SHA1 Message Date
jwoa95 57c4a20dde feat(secretsmanager): publish secret write events through CloudTrail (#6623) 2026-10-30 07:27:51 -04:00
Allen Sanborn 5ad2f64840 fix(cloudtrail): keep a trail's KMS key and CloudWatch Logs delivery (#6989) 2026-10-30 06:54:42 -04:00
Priamo Germosen 37717537a4 fix(iam): record a denied browser PostObject in CloudTrail (#6030)
Under IAM enforcement a denied S3 request is recorded in CloudTrail as
the operation that was refused, but a browser POST upload left no
record. Its credential is only in the form fields, so S3Controller
authorizes it through IamEnforcementFilter.authorizeAdditionalResource,
which threw AccessDenied without going through the denial emitter.

The POST path now calls a new authorizePostObject, which checks
s3:PutObject as before and, when IAM refuses it, records the denial as
PostObject before refusing. AWS's S3 developer guide lists PostObject
among the object-level API actions logged as CloudTrail events; the
current user guide's data events table no longer names it. The
emitter's recording half is split out so both paths share it, and a
record it cannot write is logged as a warning.

The denial is recorded in the Region the form's credential names, as a
presigned URL's is in the one its query credential names, so a trail
that logs only that Region gets it.
2026-10-19 21:32:47 -05:00
Priamo Germosen 401f5ce2d7 fix(iam): name a denied S3 POST in CloudTrail (#5942)
Under IAM enforcement a denied S3 request is recorded in CloudTrail as
the operation that was refused, but a denied POST on an object was not
recorded at all. CreateMultipartUpload and CompleteMultipartUpload are
both checked as s3:PutObject and SelectObjectContent as s3:GetObject,
so the action alone could not say which operation ran, and
RestoreObject had no name.

A denied POST is now named from the sub-resource that chose its action:
?uploads is CreateMultipartUpload, an uploadId CompleteMultipartUpload,
?restore RestoreObject and ?select SelectObjectContent, with ?uploads
ahead of an uploadId as S3Controller runs them. The S3 user guide lists
all four among the object data events CloudTrail logs. A POST naming
none of them still gets no name rather than a wrong one.

SelectObjectContent and GetObjectAttributes were missing from the
read-only events, so a trail logging only reads dropped their denials
and other trails recorded them as writes. CloudTrail counts an event
that changes no resource as read-only, and neither one changes the
object.
2026-10-18 20:43:25 -05:00
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
Matheus André 991470e7c4 fix(cloudtrail): implement CreateTrail with tagging support and add integration tests (#3206)
Signed-off-by: Matheus André <matheusandr2@gmail.com>
2026-09-07 21:46:14 -04:00
Priamo Germosen 671628b525 feat(cloudtrail): implement AddTags, RemoveTags and ListTags (#2934)
* feat(cloudtrail): implement AddTags, RemoveTags and ListTags

CloudTrailJsonHandler dispatched none of the three tag actions, so any
trail lookup went through the unsupported-action path — including the
Terraform AWS provider's transparent-tagging ListTags call on every read
of aws_cloudtrail, which broke refresh/plan/destroy for any state
containing a trail regardless of whether it was tagged.

Tags are tracked per-trail in CloudTrailEntry (not the wire-serialized
Trail record, which AWS never includes tags on) and are resolved by ARN
only, matching AWS's actual request shape for these three actions. An
ARN that isn't a well-formed CloudTrail trail ARN raises
CloudTrailARNInvalidException; a well-formed ARN with no matching trail
raises ResourceNotFoundException, so a stale Terraform state entry
surfaces as a real error instead of an empty tag list.

Fixes floci-io/floci#2297

* fix(cloudtrail): omit Value from ListTags response for valueless tags

AddTags only requires Key, so a tag can legitimately have no Value.
listTags() was serializing that as an explicit "Value":null, but AWS
omits absent optionals from the response entirely.
2026-09-02 17:29:03 -05:00
Guilherme Lima 024d74e5c4 feat(cloudtrail): in-process CloudTrail with S3 data event emission (#1460)
* feat(cloudtrail): in-process CloudTrail with S3 data event emission

New service supporting CreateTrail / DescribeTrails / DeleteTrail /
UpdateTrail / PutEventSelectors / GetEventSelectors / StartLogging /
StopLogging / GetTrailStatus.

S3 ops (PutObject / GetObject / HeadObject / DeleteObject / ListObjects
/ GetObjectAcl) emit CloudTrail data events through a per-trail buffer.
The CloudTrailLogWriter scheduler flushes pending records as gzipped
JSON envelopes into the destination bucket at AWS-shaped key paths
(AWSLogs/<account>/CloudTrail/<region>/yyyy/MM/dd/<file>.json.gz) on
a configurable cadence (default 60s).

IAM-enforcement denials emit matching AccessDenied records by hooking
IamEnforcementFilter. IamActionRegistry now distinguishes
s3:GetObjectAcl / PutObjectAcl / {Get|Put|Delete}ObjectTagging from
their base ops via ?acl / ?tagging query parameters so the right
event names land in the trail.

Seeded AWSCloudTrail_FullAccess / _ReadOnlyAccess managed policies.

* fix(cloudtrail): return LatestDeliveryTime in GetTrailStatus after StartLogging

The sdk-test-java compatibility test asserts latestDeliveryTime() is
non-null immediately after startLogging. Seed it with the startLoggingTime
so the field is always present once logging has been started.

* fix(cloudtrail): emit SnsTopicARN alongside SnsTopicName in CreateTrail/UpdateTrail responses

Accept both SnsTopicARN and SnsTopicName on input (SnsTopicARN takes
precedence). Emit both fields on output so clients reading the current
field name (SnsTopicARN) get a non-null value.

* fix(cloudtrail): wildcard S3 ARN matching, trail name validation, LookupEvents

- matchesS3DataResourceArn: handle bare "arn:aws:s3", "arn:aws:s3:::*", and
  "arn:aws:s3:::*/*" wildcard forms so trails configured via the AWS Console
  "capture everything" selector actually record events (previously fell through
  silently). Unit tests added to CloudTrailSelectorMatchingTest.

- createTrail: enforce AWS trail name rules (3–128 chars, start/end with letter
  or digit, only letters/numbers/./_/-). Integration tests in new
  CloudTrailNameValidationTest.

- CloudTrailJsonHandler: add LookupEvents stub returning an empty Events array,
  matching upstream's addition in #1603.

* fix(cloudtrail): log empty catches, key selectors/logging by trail home region

- CloudTrailLogWriter.stop(): log at WARN instead of silently swallowing the
  final-flush exception (AGENTS.md: never leave a catch block empty).

- CloudTrailService.putEventSelectors / getEventSelectors / startLogging /
  stopLogging / getTrailStatus: use trail.homeRegion() as the storage key
  instead of the request region. Previously a cross-region call (e.g. accessing
  a trail by ARN from a different-region endpoint) stored selectors and logging
  state in the wrong region's map, so trailsMatching() found an empty selector
  list and logging never fired.

- S3Controller.emitCloudTrailEvent / IamEnforcementFilter.emitS3DenialIfApplicable:
  replace empty inner catch blocks with LOG.tracev() so unexpected failures
  during request-context extraction surface at trace level.

* fix(iam): distinguish bucket-level vs object-level ?acl / ?tagging IAM actions

resolveS3SubResourceAction was always mapping ?acl and ?tagging to object-level
actions (s3:PutObjectAcl, s3:GetObjectAcl, etc.) regardless of path depth.
A PUT /{bucket}?acl request requires s3:PutBucketAcl, not s3:PutObjectAcl —
callers with the correct bucket-level permission were incorrectly denied.

Fix: inspect the URL path after stripping the leading slash. When there is no
slash (or the path ends with one), the target is a bucket; otherwise it is an
object. Applies to all six variants: GetBucketAcl, PutBucketAcl,
GetBucketTagging, PutBucketTagging, DeleteBucketTagging (and their object
counterparts).

* fix(cloudtrail): re-queue records on flush failure instead of dropping them

drainPendingRecords atomically dequeues all records before the S3 write.
If serializeAndGzip or s3Service.putObject threw, those records were gone —
permanently lost before the re-throw reached flushAll.

Fix: wrap the serialize+write block in a try-catch that calls requeueRecords
before rethrowing. Records are added back to the tail of the queue and will be
retried on the next flush cycle. The new CloudTrailService.requeueRecords helper
also makes the re-queue path unit-testable independently of flushTrail.

* fix(s3): emit GetObjectAcl error record under correct event name

getObjectAcl was called inside the outer GET-object try block. On any
AwsException (NoSuchKey, AccessDenied, etc.) the catch at the bottom fired
and emitted a GetObject error record. CloudTrail consumers auditing ACL
errors would see the wrong event name.

Wrap the acl branch in its own try-catch that emits GetObjectAcl on both
success and failure paths, mirroring the pattern used by the other hooked ops.

* ci: retrigger

* fix(test): pass CloudTrailService and CurrentVertxRequest to IamEnforcementFilter constructor

* fix(cloudtrail): persist trail state via StorageFactory instead of volatile in-memory maps

* fix(cloudtrail): address review feedback on region, name lookup, and ACL detection

- S3Controller: use request region (from credential scope) instead of
  getDefaultRegion() for CloudTrail event emission, matching the IAM
  denial hook behaviour so allowed and denied calls land in the same trail.

- CloudTrailService.findTrail: name lookup now uses regionKey(region, name)
  directly; ARNs still do a cross-region scan. Prevents two same-name
  single-region trails from resolving ambiguously by map iteration order.

- TrailKey: add eventRegion field so multi-region trail events are written
  to the correct S3 delivery path (CloudTrail/<eventRegion>/) rather than
  always the trail home region. drainPendingRecords/requeueRecords now take
  a TrailKey to carry all three dimensions.

- IamActionRegistry: fix isBucketLevel — trailing slash is a valid S3 key
  character, so /bucket/folder/?acl is an object ACL request. Replaced the
  endsWith("/") check with an index-based test. Add IamActionRegistryTest
  cases for the folder/ regression.

* docs(cloudtrail): sync action table order with make docs-sync
2026-07-21 12:10:19 -04:00
TiM 7d70f64162 feat(docs): generate Supported Actions tables from handler source (#1641)
* feat(docs): generate Supported Actions tables from handler source

The "Supported Actions" tables in docs/services/*.md were hand-maintained and
drifted from the handlers. For example secrets-manager.md omitted RestoreSecret,
which SecretsManagerJsonHandler dispatches, and acm.md listed RenewCertificate,
which is not implemented anywhere in src/.

Derive the action list from handler source so it cannot drift, while keeping the
hand-written Description column:

- tools/docs/regen_action_docs.py extracts actions from `case "X" ->` switch arms
  (including multi-label arms) and JAX-RS REST controllers, and rewrites only the
  rows between the <!-- floci:actions --> markers. Descriptions are preserved by
  action name; new actions get a "-" placeholder. PascalCase-only matching avoids
  picking up SCREAMING_CASE labels from non-action switches.
- tools/docs/services.yaml registers 18 single-table switch services and lists the
  remaining switch handlers under deferred_handlers, so the new-service sentinel
  fires only on a genuinely unregistered handler.
- make docs-sync / docs-check / docs-test, plus a Python-only CI workflow that
  gates on handler, doc, and tooling changes.
- Migrate 18 service docs into marker blocks, reconciling real drift (adds
  RestoreSecret, ImportCertificate, and others; drops the unimplemented
  RenewCertificate).

Revives the parser and CI gate from #738 by @ericbsantana and completes the
description-preservation its spec described. REST-mode, mixed-mode, multi-table,
non-tabular, S3, and ecr docs are deferred and tracked in deferred_handlers.

* docs: drop standalone design spec from action-docs tooling

Remove ideas/auto-generated-action-tables.spec.md and the four references
to it (CONTRIBUTING.md, Makefile, regen_action_docs.py docstring,
services.yaml). It was a planning artifact; the operational docs live in
CONTRIBUTING.md and the tooling is self-documenting. The #738 / @ericbsantana
credit is preserved in the PR description.

* chore: address review on action-docs tooling

- pin actions/checkout to v7.0.0 in docs-actions workflow to match the
  repo-wide bump (#1690), so dependabot does not immediately flag the new file
- document in the generator docstring that a switch case label counts as
  supported purely by existing, so a per-action UnsupportedOperation stub
  would be a false positive (handlers here reject from the default arm)

* docs: regenerate action tables against current handler source

Resync the generated Supported Actions tables to handler source after
rebasing onto the latest main:

- cloudformation: add DescribeStackInstance and DescribeStackSetOperation
  now emitted by the handler, and keep the implemented StackSet descriptions
- cloudtrail: add LookupEvents
- firehose: add UpdateDestination
- step-functions: add PublishStateMachineVersion, ListStateMachineVersions,
  DeleteStateMachineVersion
- register the cloudcontrol handler in deferred_handlers so the strict
  unregistered-handler gate passes (no standalone action table yet)

* fix(docs): prevent action-table generator from silently dropping actions

Address the latest review pass on the action-docs tooling:

- switch extraction now captures case arms whose labels wrap across lines
  (valid Java 14+ syntax). The capture group excludes only `{ } ;` boundaries,
  so it spans newlines between labels but stops at the arm's `->`. A wrapped
  arm was previously missed, and docs-check would stay green because the doc
  and the generated output agreed on the omission, defeating the whole
  drift-prevention guarantee.
- REST extraction skips Javadoc / inline comments between a verb annotation
  and the method signature; such a line otherwise reset the lookahead and
  dropped the action.
- parse_marker_block raises a descriptive error when a marker is not on its
  own line, instead of a bare "substring not found".
- doc, source, and registry reads/writes are pinned to UTF-8 so generation is
  locale-independent (the docs contain non-ASCII text).
- the docs-actions push trigger watches Makefile and the workflow file,
  matching its pull_request trigger.

Adds regression tests for the multi-line arm and comment-skip paths (20 total).
2026-07-06 21:02:04 -05:00
Hector Ventura 717769857b docs: correct service count to 58 and add EMR, WAF v2, CloudTrail pages (#1398)
Reconcile inconsistent service counts (55/54/41) to 58 distinct services across the README, docs index, services overview, and the LocalStack migration guide. Add the missing per-service pages and Service Matrix rows for EMR, WAF v2, and CloudTrail, and wire them into the mkdocs nav and README service tables.
2026-06-16 18:57:37 -05:00