Documentation
¶
Overview ¶
Package cloudtraildelivery implements bounded, metadata-only ingestion of AWS CloudTrail records delivered through two channels that the existing internal/runtime/cloudtrail LookupEvents engine does not cover:
- S3 trail delivery. CloudTrail trails write gzip-compressed JSON log files to a configured S3 bucket. This ingester lists object keys newer than the operator-supplied checkpoint, downloads each log file, parses the `Records[]` array, dedupes by EventId, and hands the resulting metadata-only events to the cloudtrail engine's NormalizeEvent for translation into the shared runtime contract.
- EventBridge delivery. CloudTrail can deliver every event in near-real-time to EventBridge; the standard fan-out is to put events on an SQS queue. This ingester pulls a bounded batch of messages, parses the EventBridge envelope, and normalizes the CloudTrail `detail` payload. Messages whose events are successfully ingested are deleted from the queue so they are not re-delivered; messages that fail normalization are left in the queue and surface as partial-failure diagnostics so the consumer's redrive policy can apply.
Both ingesters share the same IngestRequest/IngestResult shape and produce slices of cloudtrail.NormalizedEvent so the API layer can fold the delivery channels into the same AWSRuntimeEventResult envelope that the LookupEvents path uses. Cross-channel dedupe by EventId is the API layer's responsibility (a single CloudTrail event can arrive via LookupEvents AND S3 AND EventBridge in the same run).
Safety boundaries are inherited from the cloudtrail engine: the ingesters never read, log, or persist request parameters, response elements, secret values, decrypted plaintext, object bodies, or any customer payload from a CloudTrail record. Only the metadata allow-list defined by cloudtrail.NormalizeEvent crosses the boundary. Bounded budgets (MaxFiles, MaxEvents, MaxMessages, file- size limit) cap one ingestion run so a misbehaving trail or queue cannot exhaust the worker.
Index ¶
- Constants
- type CloudTrailLogFile
- type CloudTrailRecord
- type CloudTrailRsrc
- type DeleteMessageBatchEntry
- type DeleteMessageBatchFailure
- type DeleteMessageBatchInput
- type DeleteMessageBatchOutput
- type DeliverySource
- type EventBridgeIngester
- type GetObjectInput
- type GetObjectOutput
- type IngestRequest
- type IngestResult
- type ListObjectsV2Input
- type ListObjectsV2Output
- type ReceiveMessageInput
- type ReceiveMessageOutput
- type S3API
- type S3Client
- type S3Ingester
- type S3Object
- type SDKS3API
- type SDKSQSAPI
- type SQSAPI
- type SQSClient
- type SQSMessage
Constants ¶
const ( DefaultMaxFiles = 50 DefaultMaxEvents = 1000 DefaultMaxMessages = 100 DefaultMaxFileBytes = int64(32 << 20) // 32 MiB per gzip log file DefaultLookbackWindow = 30 * time.Minute DefaultMaxThrottleRetries = 4 DefaultThrottleBackoff = 200 * time.Millisecond DefaultSQSVisibilityBuffer = 30 * time.Second )
Bounded budget defaults. Operators can override per-run; the defaults are sized so one tick of a 5-minute worker comfortably stays inside the budget on a steady-state trail.
const CollectorName = "aws_cloudtrail_delivery"
CollectorName tags every diagnostic emitted by the delivery ingesters so downstream callers can scope diagnostics by source.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CloudTrailLogFile ¶
type CloudTrailLogFile struct {
Records []CloudTrailRecord `json:"Records"`
}
CloudTrailLogFile is the JSON envelope CloudTrail writes to S3 and publishes through EventBridge. The S3 file is `{ "Records": [...] }` containing N events; an EventBridge SQS message contains one envelope whose `detail` is a single CloudTrail record (S3 and EventBridge serialize the same record shape, only the envelope differs).
type CloudTrailRecord ¶
type CloudTrailRecord struct {
EventVersion string `json:"eventVersion,omitempty"`
EventID string `json:"eventID,omitempty"`
EventName string `json:"eventName,omitempty"`
EventSource string `json:"eventSource,omitempty"`
EventTime string `json:"eventTime,omitempty"`
AWSRegion string `json:"awsRegion,omitempty"`
RecipientAccount string `json:"recipientAccountId,omitempty"`
ReadOnly any `json:"readOnly,omitempty"`
UserIdentity map[string]any `json:"userIdentity,omitempty"`
Resources []CloudTrailRsrc `json:"resources,omitempty"`
SourceIPAddress string `json:"sourceIPAddress,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
AdditionalRaw map[string]any `json:"-"`
}
CloudTrailRecord is the metadata-only projection of one CloudTrail record. Field names mirror the documented CloudTrail event JSON. Critically, `requestParameters` and `responseElements` are NOT represented here — the ingesters never decode them, and the engine re-uses cloudtrail.NormalizeEvent's allow-listed extraction over the raw envelope string for any fields it needs from `userIdentity` / `sessionContext`.
type CloudTrailRsrc ¶
type CloudTrailRsrc struct {
ResourceType string `json:"type,omitempty"`
ResourceName string `json:"ARN,omitempty"`
AccountID string `json:"accountId,omitempty"`
}
CloudTrailRsrc mirrors the per-record resource subobject.
type DeleteMessageBatchEntry ¶
DeleteMessageBatchEntry pairs a message id with its receipt handle.
type DeleteMessageBatchFailure ¶
DeleteMessageBatchFailure carries the SQS error code per failed entry so the ingester can attach a per-message diagnostic.
type DeleteMessageBatchInput ¶
type DeleteMessageBatchInput struct {
QueueURL string
Entries []DeleteMessageBatchEntry
}
DeleteMessageBatchInput requests deletion of one or more processed messages.
type DeleteMessageBatchOutput ¶
type DeleteMessageBatchOutput struct {
Successful []string
Failed []DeleteMessageBatchFailure
}
DeleteMessageBatchOutput surfaces the partial-failure structure SQS uses (some deletes can succeed while others fail in one request).
type DeliverySource ¶
type DeliverySource string
DeliverySource identifies which CloudTrail delivery channel produced a record. The API layer uses this both for source-scoped filtering and so operators can attribute a record to its origin in the response.
const ( // DeliverySourceS3 indicates the record was extracted from a // CloudTrail trail's S3 log object. DeliverySourceS3 DeliverySource = "s3" // DeliverySourceEventBridge indicates the record was consumed from // an EventBridge target (typically SQS). DeliverySourceEventBridge DeliverySource = "eventbridge" )
type EventBridgeIngester ¶
type EventBridgeIngester struct {
API SQSAPI
QueueURL string
Now func() time.Time
Sleep func(time.Duration)
}
EventBridgeIngester drives one bounded EventBridge ingestion run by consuming the SQS queue an EventBridge rule targets.
func NewEventBridgeIngester ¶
func NewEventBridgeIngester(api SQSAPI, queueURL string) *EventBridgeIngester
NewEventBridgeIngester returns an EventBridgeIngester with sensible defaults for the Now and Sleep hooks.
func (*EventBridgeIngester) Ingest ¶
func (i *EventBridgeIngester) Ingest(ctx context.Context, request IngestRequest) (IngestResult, error)
Ingest runs one bounded EventBridge ingestion pass.
type GetObjectInput ¶
GetObjectInput is the S3 GetObject request shape.
type GetObjectOutput ¶
type GetObjectOutput struct {
Body io.ReadCloser
ContentLength int64
}
GetObjectOutput is the trimmed S3 response shape. The Body field is the caller's responsibility to close.
type IngestRequest ¶
type IngestRequest struct {
AccountID string
Region string
// Checkpoint is the per-channel resume marker. For S3 it is the
// last completely processed S3 object key, passed to ListObjectsV2
// as StartAfter on the next run. For EventBridge/SQS it is unused
// — the queue itself is the checkpoint, and the ingester deletes
// successfully-processed messages so they are not re-delivered.
Checkpoint string
// LookbackWindow caps how far back the S3 ingester scans for new
// trail files when no Checkpoint is supplied. Defaults to
// DefaultLookbackWindow.
LookbackWindow time.Duration
// MaxFiles caps the number of S3 log objects one S3 ingestion
// run downloads. Defaults to DefaultMaxFiles.
MaxFiles int
// MaxMessages caps the number of SQS messages one EventBridge
// ingestion run consumes. Defaults to DefaultMaxMessages.
MaxMessages int
// MaxEvents caps the total normalized events one ingestion run
// emits across all files / messages. Defaults to
// DefaultMaxEvents.
MaxEvents int
// MaxFileBytes caps each S3 log object's decompressed size.
// Defaults to DefaultMaxFileBytes.
MaxFileBytes int64
// MaxThrottleRetries caps per-request retries when the
// underlying SDK returns a throttling error. Defaults to
// DefaultMaxThrottleRetries.
MaxThrottleRetries int
// ThrottleBackoff is the base linear backoff between retries.
ThrottleBackoff time.Duration
// AppliedFilters are API-side post-ingestion runtime filters. Delivery
// ingesters use these to avoid consuming evidence that the caller did
// not request. Keys are the same filter tokens used in the API layer,
// e.g. event_type, identity, resource.
AppliedFilters map[string]string
}
IngestRequest configures one bounded ingestion run for either delivery channel.
type IngestResult ¶
type IngestResult struct {
Source DeliverySource
Events []cloudtrail.NormalizedEvent
Diagnostics []cloudtrail.Diagnostic
CoverageGaps []cloudtrail.CoverageGap
Status string
FailureReasons []string
RemediationHints []string
// Checkpoint is the new resume marker the caller should persist
// for the next run. For S3 this is the last completely processed
// object key; for EventBridge the field is empty because the queue
// is the implicit checkpoint.
Checkpoint string
// FilesProcessed (S3) and MessagesProcessed (EventBridge) let the
// API layer attach observability metadata to the response.
FilesProcessed int
MessagesProcessed int
EventsConsidered int
// HistoryTruncated is true when the run stopped at the bounded
// budget with more files / messages still available.
HistoryTruncated bool
}
IngestResult is the bounded outcome of one ingestion run.
type ListObjectsV2Input ¶
type ListObjectsV2Input struct {
Bucket string
Prefix string
ContinuationToken string
MaxKeys int32
// StartAfter scopes the listing to keys strictly greater than the
// supplied key. CloudTrail object keys embed an ISO-8601 timestamp,
// so passing the last processed key gives the next run an
// efficient resume marker without re-listing the entire window.
StartAfter string
}
ListObjectsV2Input is the S3 ListObjectsV2 request, expressed independently of the SDK so the ingester layer never imports the SDK types directly.
type ListObjectsV2Output ¶
ListObjectsV2Output is the trimmed S3 response shape.
type ReceiveMessageInput ¶
type ReceiveMessageInput struct {
QueueURL string
MaxNumberOfMessages int32
WaitTimeSeconds int32
VisibilityTimeout int32
}
ReceiveMessageInput mirrors the SDK input.
type ReceiveMessageOutput ¶
type ReceiveMessageOutput struct {
Messages []SQSMessage
}
ReceiveMessageOutput holds the messages pulled from the queue.
type S3API ¶
type S3API interface {
ListObjectsV2(ctx context.Context, input ListObjectsV2Input) (ListObjectsV2Output, error)
GetObject(ctx context.Context, input GetObjectInput) (GetObjectOutput, error)
}
S3API is the narrow seam every S3 backend implements. The SDK adapter wraps s3.Client; tests use a fake to exercise the ingester deterministically without network access.
type S3Client ¶
type S3Client interface {
ListObjectsV2(ctx context.Context, params *s3.ListObjectsV2Input, optFns ...func(*s3.Options)) (*s3.ListObjectsV2Output, error)
GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)
}
S3Client is the minimal seam from the AWS SDK S3 client this package depends on. Defining it here lets the adapter swap in a fake for SDK-layer tests without taking a hard dep on the SDK.
type S3Ingester ¶
type S3Ingester struct {
API S3API
// Bucket and Prefix locate the CloudTrail trail's S3 destination.
// CloudTrail keys look like
// AWSLogs/<account>/CloudTrail/<region>/YYYY/MM/DD/<account>_CloudTrail_<region>_<timestamp>_<uuid>.json.gz
// so a prefix scoped to one account+region greatly reduces the
// number of objects listed per run.
Bucket string
Prefix string
Now func() time.Time
Sleep func(time.Duration)
}
S3Ingester drives one bounded CloudTrail S3 ingestion run.
func NewS3Ingester ¶
func NewS3Ingester(api S3API, bucket, prefix string) *S3Ingester
NewS3Ingester returns an S3Ingester with sensible defaults for the Now and Sleep hooks.
func (*S3Ingester) Ingest ¶
func (i *S3Ingester) Ingest(ctx context.Context, request IngestRequest) (IngestResult, error)
Ingest runs one bounded S3 ingestion pass. Documented failure modes (permission denied, throttling exhaustion, partial-file failures, empty window) are surfaced through IngestResult.Status and Diagnostics rather than the error return so the API layer can serve a stable 200 response. A returned error means a programmer bug or context cancellation.
type SDKS3API ¶
type SDKS3API struct {
// contains filtered or unexported fields
}
SDKS3API implements S3API against the AWS SDK. Only the read-side operations are exposed; PutObject, DeleteObject, and any mutating API are deliberately absent so the adapter cannot accidentally invoke a write.
func NewSDKS3APIFromClient ¶
NewSDKS3APIFromClient wraps a pre-built S3 client.
func (*SDKS3API) GetObject ¶
func (a *SDKS3API) GetObject(ctx context.Context, input GetObjectInput) (GetObjectOutput, error)
GetObject maps the engine input onto the SDK shape. The caller owns closing the response body.
func (*SDKS3API) ListObjectsV2 ¶
func (a *SDKS3API) ListObjectsV2(ctx context.Context, input ListObjectsV2Input) (ListObjectsV2Output, error)
ListObjectsV2 maps the engine input onto the SDK shape and trims the response down to the metadata the ingester actually uses.
type SDKSQSAPI ¶
type SDKSQSAPI struct {
// contains filtered or unexported fields
}
SDKSQSAPI implements SQSAPI against the AWS SDK. Only the read-and-acknowledge operations are exposed; SendMessage, PurgeQueue, and any mutating producer API are deliberately absent so the adapter cannot accidentally produce or destroy queue content.
func NewSDKSQSAPIFromClient ¶
NewSDKSQSAPIFromClient wraps a pre-built SQS client.
func (*SDKSQSAPI) DeleteMessageBatch ¶
func (a *SDKSQSAPI) DeleteMessageBatch(ctx context.Context, input DeleteMessageBatchInput) (DeleteMessageBatchOutput, error)
DeleteMessageBatch acks one or more successfully-processed messages.
func (*SDKSQSAPI) ReceiveMessage ¶
func (a *SDKSQSAPI) ReceiveMessage(ctx context.Context, input ReceiveMessageInput) (ReceiveMessageOutput, error)
ReceiveMessage maps the engine input onto the SDK shape and trims the response down to the metadata the ingester actually uses.
type SQSAPI ¶
type SQSAPI interface {
ReceiveMessage(ctx context.Context, input ReceiveMessageInput) (ReceiveMessageOutput, error)
DeleteMessageBatch(ctx context.Context, input DeleteMessageBatchInput) (DeleteMessageBatchOutput, error)
}
SQSAPI is the narrow seam for the EventBridge → SQS delivery channel. EventBridge fans CloudTrail events out to subscribers; the most common fan-out target in production is an SQS queue, and the ingester pulls a bounded batch of messages, normalizes the CloudTrail `detail` payload, and deletes successfully-ingested messages so they are not re-delivered. Messages whose normalization fails are left in the queue so the queue's redrive policy applies.
type SQSClient ¶
type SQSClient interface {
ReceiveMessage(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error)
DeleteMessageBatch(ctx context.Context, params *sqs.DeleteMessageBatchInput, optFns ...func(*sqs.Options)) (*sqs.DeleteMessageBatchOutput, error)
}
SQSClient is the minimal seam from the AWS SDK SQS client.
type SQSMessage ¶
SQSMessage is the trimmed SDK message shape.