Documentation
¶
Overview ¶
Package cloudtrail implements bounded, metadata-only ingestion of AWS CloudTrail LookupEvents records into the runtime event contract defined in internal/api. It is deliberately decoupled from the AWS SDK: the public surface depends only on a narrow LookupEventsAPI seam so unit tests can drive every pagination, throttling, permission-denied, and partial-failure branch without network access or AWS credentials.
Coverage scope: CloudTrail's LookupEvents API only indexes management events (and Insights events when explicitly requested). Data events — notably S3 GetObject, Lambda Invoke, Bedrock Agent / AgentCore tool invocations, and DynamoDB item-level reads — are not searchable through LookupEvents and require a separate CloudTrail trail with data-event selectors (or CloudTrail Lake). The normalizer keeps the classification logic for those event types so the same engine can fold a data-events source in once it is wired, but operators must not interpret an empty data-event slice from this ingester as "the activity did not happen". See docs/aws-runtime-events.md for the per-event-type coverage matrix.
Safety boundaries:
- Metadata only. The ingester never reads, logs, or persists userIdentity payloads, arbitrary request parameters, response elements, secret values, decrypted plaintext, object bodies, or any other customer payload from CloudTrailEvent JSON. Only metadata-only fields whose names are listed in payloadAllowedKeys cross the boundary. For STS AssumeRole, session tag values are deliberately dropped and only tag keys cross the boundary. Any failure to extract one of those fields is treated as missing — not as a normalization failure.
- Bounded budgets. MaxPages, MaxEvents, MaxThrottleRetries, and the LookbackWindow are enforced in the ingester loop so a hostile or misbehaving trail cannot exhaust the worker.
Index ¶
- Constants
- func NormalizeEvent(raw Event, accountID string, region string, collectedAt time.Time) ([]NormalizedEvent, *Diagnostic, bool)
- type CloudTrailClient
- type CoverageGap
- type Diagnostic
- type Event
- type EventResource
- type IngestRequest
- type IngestResult
- type Ingester
- type LookupAttribute
- type LookupEventsAPI
- type LookupEventsInput
- type LookupEventsPage
- type NormalizedEvent
- type SDKLookupEventsAPI
Constants ¶
const ( // CollectorName tags every diagnostic emitted by this ingester so // downstream callers can scope diagnostics by collector. CollectorName = "aws_cloudtrail_lookup_events" // DefaultLookbackWindow is the default amount of CloudTrail // history one ingestion run scans. Chosen to match a single // hourly worker tick with enough slack to absorb CloudTrail // delivery delay. DefaultLookbackWindow = 90 * time.Minute // MaxLookbackWindow is the CloudTrail LookupEvents retention // horizon. Requests beyond this are silently clamped. MaxLookbackWindow = 90 * 24 * time.Hour // DefaultMaxPages bounds the number of LookupEvents pages one // ingestion run consumes. CloudTrail page size is 50, so the // default caps a run at 50 * 20 = 1000 events. DefaultMaxPages = 20 // DefaultMaxEvents bounds the total events ingested in one run. DefaultMaxEvents = 1000 // DefaultMaxThrottleRetries bounds per-page throttling retries. DefaultMaxThrottleRetries = 4 // DefaultThrottleBackoff is the base sleep between throttling // retries; each attempt sleeps DefaultThrottleBackoff * (n + 1). DefaultThrottleBackoff = 200 * time.Millisecond // DefaultPageSize is the LookupEvents MaxResults default; // CloudTrail's hard cap is 50. DefaultPageSize = int32(50) // RedactionBoundary is the redaction label every normalized event // carries; it documents that the ingester only crossed the // metadata boundary. RedactionBoundary = "metadata_only_no_payloads_no_secret_values" )
Variables ¶
This section is empty.
Functions ¶
func NormalizeEvent ¶
func NormalizeEvent(raw Event, accountID string, region string, collectedAt time.Time) ([]NormalizedEvent, *Diagnostic, bool)
NormalizeEvent converts one CloudTrail Event into one or more NormalizedEvents. Multi-resource CloudTrail events (e.g. BatchGetSecretValue reading several secrets) fan out to one normalized event per Resources entry — using suffixed EventIDs to keep dedupe deterministic — so the resource-level filter, the graph relationship builder, and the per-resource summary counts all see every secret/key/object the event touched. The collectedAt argument is the wall-clock time of the ingestion run; live records use it instead of `observed_at + 2min` so audit ordering, cache invalidation, and freshness checks see the actual collection time.
Exported so the S3 and EventBridge delivery ingesters in internal/runtime/cloudtraildelivery can reuse the same metadata-only normalization without duplicating the allow-listed payload extraction.
Types ¶
type CloudTrailClient ¶
type CloudTrailClient interface {
LookupEvents(ctx context.Context, params *cloudtrail.LookupEventsInput, optFns ...func(*cloudtrail.Options)) (*cloudtrail.LookupEventsOutput, error)
}
CloudTrailClient is the minimal seam from the AWS SDK CloudTrail client this package depends on. Defining it here lets the adapter be swapped for a fake in tests of the SDK wrapper itself, though the ingester tests already use the higher-level LookupEventsAPI.
type CoverageGap ¶
CoverageGap explains why one collection capability returned no events or partial coverage.
type Diagnostic ¶
type Diagnostic struct {
SourceID string
Code string
Message string
Remediation string
Retryable bool
}
Diagnostic explains a partial failure inside an ingestion run.
type Event ¶
type Event struct {
EventID string
EventName string
EventSource string
EventTime time.Time
ReadOnly string
AccessKeyID string
Username string
Resources []EventResource
// RawEvent is the unparsed CloudTrailEvent JSON string. The
// ingester uses it only to pull a small allow-listed set of
// metadata fields (region, sourceIPAddress, userAgent, recipient
// account, the userIdentity arn/type/principalId/session context, and
// STS session request metadata needed for lineage). It is never logged
// or persisted.
RawEvent string
}
Event is the metadata-only projection of a CloudTrail LookupEvents item we are willing to ingest. The SDK adapter performs the SDK → Event mapping so the ingester sees only payload-safe fields.
type EventResource ¶
EventResource mirrors the CloudTrail Resource subobject.
type IngestRequest ¶
type IngestRequest struct {
AccountID string
Region string
// LookbackWindow is the wall-clock window of CloudTrail history to
// scan. Defaults to DefaultLookbackWindow if zero. CloudTrail
// retains LookupEvents history for 90 days, so anything beyond
// that is silently clamped.
LookbackWindow time.Duration
// EventSourceFilter, when non-empty, scopes ingestion to one
// CloudTrail event source (e.g. "kms.amazonaws.com"). Empty pulls
// every source the trail captures.
EventSourceFilter string
// MutationOnly, when true, requests ReadOnly=false events from
// CloudTrail.
MutationOnly bool
// MaxPages caps the number of paginated LookupEvents calls.
// Defaults to DefaultMaxPages.
MaxPages int
// MaxEvents caps the total number of events ingested across all
// pages. Defaults to DefaultMaxEvents.
MaxEvents int
// MaxThrottleRetries caps retries per page when CloudTrail returns
// a throttling error. Defaults to DefaultMaxThrottleRetries.
MaxThrottleRetries int
// ThrottleBackoff is the base sleep between throttling retries;
// each retry waits ThrottleBackoff * (attempt + 1). Defaults to
// DefaultThrottleBackoff. The ingester sleeps with the supplied
// Sleep hook so tests stay fast.
ThrottleBackoff time.Duration
// PageSize is the LookupEvents MaxResults. Defaults to
// DefaultPageSize; CloudTrail caps at 50.
PageSize int32
}
IngestRequest configures one bounded ingestion run.
type IngestResult ¶
type IngestResult struct {
AccountID string
Region string
Events []NormalizedEvent
Diagnostics []Diagnostic
CoverageGaps []CoverageGap
// Status mirrors the runtime event contract: "ready", "degraded",
// "blocked". "blocked" is reserved for permission-denied results.
Status string
FailureReasons []string
RemediationHints []string
// PagesFetched and EventsConsidered let the API layer attach
// observability metadata to the response.
PagesFetched int
EventsConsidered int
// HistoryTruncated is true when the ingester stopped because it
// hit MaxPages or MaxEvents with more events available.
HistoryTruncated bool
}
IngestResult is the bounded outcome of one ingestion run.
type Ingester ¶
type Ingester struct {
API LookupEventsAPI
Now func() time.Time
Sleep func(d time.Duration)
}
Ingester drives one bounded LookupEvents ingestion run.
func New ¶
func New(api LookupEventsAPI) *Ingester
New returns an Ingester with the supplied LookupEvents seam and sensible defaults for Now and Sleep. Tests inject deterministic versions.
func (*Ingester) Ingest ¶
func (i *Ingester) Ingest(ctx context.Context, request IngestRequest) (IngestResult, error)
Ingest runs one bounded LookupEvents ingestion pass and returns the normalized result. Ingest never returns an error for documented failure modes (permission denied, throttling, partial failure, empty); those are surfaced through IngestResult.Status, Diagnostics, and CoverageGaps so the API layer can return a stable 200 response. A returned error means a programmer bug or a missing seam.
type LookupAttribute ¶
LookupAttribute carries the optional single CloudTrail lookup attribute. Both fields are empty when no attribute is set.
type LookupEventsAPI ¶
type LookupEventsAPI interface {
LookupEvents(ctx context.Context, input LookupEventsInput) (LookupEventsPage, error)
}
LookupEventsAPI is the narrow seam every CloudTrail backend implements. The SDK adapter in sdk_lookup_events.go wraps cloudtrail.Client; tests use a fake to exercise the ingester deterministically.
func NewSDKLookupEventsAPIFromAssumeRole ¶
func NewSDKLookupEventsAPIFromAssumeRole(ctx context.Context, region string, profile string, roleARN string, externalID string, sessionName string) (LookupEventsAPI, error)
NewSDKLookupEventsAPIFromAssumeRole builds the SDK-backed adapter after assuming a connector role with the supplied external ID. This is the production code path: Identrail never embeds long-lived CloudTrail credentials and always reaches CloudTrail through a short-lived assumed role.
func NewSDKLookupEventsAPIWithContext ¶
func NewSDKLookupEventsAPIWithContext(ctx context.Context, region string, profile string) (LookupEventsAPI, error)
NewSDKLookupEventsAPIWithContext builds the SDK-backed adapter using ambient AWS credentials and the supplied region/profile.
type LookupEventsInput ¶
type LookupEventsInput struct {
StartTime time.Time
EndTime time.Time
NextToken string
MaxResults int32
// Attributes is a single attribute key/value pair — CloudTrail
// permits exactly one — used to scope a focused lookup, e.g.
// {Key: "ReadOnly", Value: "false"} for mutation events.
Attributes LookupAttribute
}
LookupEventsInput is a CloudTrail LookupEvents request, expressed independently of the SDK so the ingester layer never imports the SDK types.
type LookupEventsPage ¶
LookupEventsPage is one page of CloudTrail LookupEvents.
type NormalizedEvent ¶
type NormalizedEvent struct {
EventID string
AccountID string
Region string
EventType string
EventSource string
EventName string
Action string
ActorPrincipalARN string
ActorPrincipalType string
SessionID string
AssumedRoleARN string
SessionIssuerARN string
SourceIdentity string
RoleSessionName string
SessionTagKeys []string
TransitiveTagKeys []string
OriginalActorARN string
ChainedFromARN string
LineageStatus string
LineageReason string
SourceIPAddress string
UserAgent string
SessionStartedAt time.Time
SessionExpiresAt time.Time
TargetResourceARN string
TargetResourceType string
TargetResourceName string
// AgentID, AgentType, and AgentRuntimeVersion are derived from
// the target-resource ARN for agent-tool events. The API layer
// composes the canonical AgentNodeID from these via the same
// helper the AI-agent inventory and provider normalizer use, so
// the runtime evidence graph joins back to the agent inventory
// nodes. AgentRuntimeVersion is the third path segment for an
// AgentCore runtime endpoint (the endpoint alias / runtime
// version that the inventory also stamps into the node id); it
// is empty for bedrock-agent ARNs which do not carry one.
AgentID string
AgentType string
AgentRuntimeVersion string
Owner string
EvidenceCategory string
Confidence float64
ObservedAt time.Time
CollectedAt time.Time
Status string
ReadOnly bool
RedactionBoundary string
}
NormalizedEvent is the metadata-only contract emitted by the ingester. The API layer maps these into AWSRuntimeEventRecord. Field names mirror the runtime contract so the mapping in internal/api/aws_runtime_cloudtrail.go is a 1:1 copy.
type SDKLookupEventsAPI ¶
type SDKLookupEventsAPI struct {
// contains filtered or unexported fields
}
SDKLookupEventsAPI implements LookupEventsAPI against the AWS SDK. It only exposes the LookupEvents operation; PutEvents and the CloudTrail Lake read APIs are deliberately absent so the adapter cannot accidentally invoke a mutation.
func NewSDKLookupEventsAPIFromClient ¶
func NewSDKLookupEventsAPIFromClient(client CloudTrailClient) *SDKLookupEventsAPI
NewSDKLookupEventsAPIFromClient wraps a pre-built CloudTrail client. Used both by production wiring and by SDK-layer tests.
func (*SDKLookupEventsAPI) LookupEvents ¶
func (a *SDKLookupEventsAPI) LookupEvents(ctx context.Context, input LookupEventsInput) (LookupEventsPage, error)
LookupEvents calls the SDK and converts the response into the engine-facing LookupEventsPage type. Mapping is one-to-one and never touches request parameters or response elements from the CloudTrailEvent JSON; the engine performs allow-listed extraction after this returns.