Documentation
¶
Overview ¶
Package audit provides audit event structures and utilities for the ToolHive ecosystem, ensuring NIST SP 800-53 compliance.
The core type is AuditEvent, which captures the minimal information needed to audit an event in a uniform, serializable format. Use NewAuditEvent to create events with a generated audit ID and UTC timestamp, or NewAuditEventWithID when the caller provides the ID.
Event Structure ¶
Each audit event records:
- Type: a short identifier for what happened (e.g. "mcp_tool_call")
- Source: where the request originated (network address, local process)
- Outcome: success, failure, error, or denied
- Subjects: identity of who triggered the event
- Component: which system component logged the event
- Target: optional target of the operation
- Data: optional extra payload for forensic analysis
Fluent Setters ¶
Events built with NewAuditEvent support fluent setters for optional fields. A component that audits its own actions should use the EventBuilder instead (see Event Builder below), which takes the actor from the context and enforces the rules that follow.
event := audit.NewAuditEvent(
"mcp_tool_call",
audit.EventSource{Type: audit.SourceTypeNetwork, Value: "10.0.0.1"},
audit.OutcomeSuccess,
map[string]string{"user": "alice"},
"my-service",
).WithTarget(map[string]string{
"type": "tool",
"name": "calculator",
})
Delegation Chains ¶
When an actor acted on behalf of another actor (RFC 8693 `act` claim), attach a DelegationChain to the event via AuditEvent.WithDelegationChain, or, with the EventBuilder, via the WithDelegation event option. The chain is additive to the flat AuditEvent.Subjects map; Subjects remains the backward-compatible identity map and is not modified by setting a chain.
Parse raw `act` claims with ParseDelegationChain, which applies a defensive depth cap (DefaultMaxDelegationDepth, overridable via maxDepth) to bound the size of the retained chain and of the emitted record — not parsing work, since the caller has already decoded the claim — and reports explicit truncation (Truncated/Omitted are never silently omitted). Per-hop identity is the issuer (iss) and subject (sub) pair only: (iss, sub) is the only stable, unique actor identifier (OpenID Connect Core §5.7), and RFC 8693 §6 calls for data minimization. Any extra claims present on a hop are retained in memory for inspection via DelegatedActor.Extra but are never serialized or logged, to avoid leaking Personally Identifiable Information.
The chain is ordered outermost-first: Chain[0] is the current actor and the last entry is the least recent (earliest) actor. The delegating end user is not part of the chain — it is the token's top-level sub, recorded in Subjects. Only the top-level event claims and Chain[0] should drive access-control decisions; prior hops are informational only (RFC 8693 §4.1) and exist for audit.
An event the EventBuilder split into continuations, as the Size Limit section describes, may carry only part of the chain. Each such event that carries hops also carries metadata.extra.hop_offset, the index of its first hop in the full chain, and only the event with offset 0 has the current actor as chain[0]. A rule keyed on chain[0] should check the offset.
Parsing never fails: an audit record must be producible for exactly the tokens that violate expectations, since a malformed delegation assertion from a signature-validated token is itself security-relevant (it indicates an issuer bug or tampering), and dropping the record would let malformed input suppress audit (CWE-223, CWE-778). Non-conformant input is recorded on the chain via Malformed and a low-cardinality MalformedReason, with all hops that parsed successfully preserved. Strict rejection of malformed `act` claims belongs on the token-issuance path, not in the audit sink; consumers that alert can key on the malformed field.
Logging ¶
Use AuditEvent.LogTo to emit the event to a log/slog.Logger at a specified level. This produces structured JSON output suitable for audit log collection.
Audit Handler Middleware ¶
A service that already has one operator logger does not need a second logger for audit events. HandlerMiddleware wraps the service's log/slog.Handler so that LevelAudit records go to a dedicated audit writer, while every other record goes to the wrapped handler unchanged. Register it with logging.WithHandlerMiddleware when building the logger, as the last middleware:
logger := logging.New(
logging.WithLevel(slog.LevelWarn),
logging.WithHandlerMiddleware(traceContextMiddleware),
logging.WithHandlerMiddleware(audit.HandlerMiddleware(
audit.WithEnabled(cfg.AuditEnabled),
audit.WithMeterProvider(meterProvider),
)), // must be last
)
event := audit.NewAuditEvent("widgets.widget.update", source,
audit.OutcomeSuccess, subjects, "example-service")
event.LogTo(ctx, logger, audit.LevelAudit)
The middleware behaves as follows, and each rule has a reason:
- Audit records are written to os.Stdout by default (override with WithWriter); operator records keep their own output, normally stderr. Keeping audit events on their own stream lets a log collector ship them without parsing operator output.
- Each audit record is one JSON line, whatever format the operator logger uses. The level is rendered as "AUDIT" rather than slog's "INFO+2", and every line carries logger=audit, so a collector selects audit events from every service with a single rule. Only the middleware stamps logger=audit; lines written through NewAuditLogger do not carry it.
- Audit records ignore the operator log level. A service running at warn or error still writes its audit events.
- WithEnabled is the only gate. When it is false, Enabled reports LevelAudit as disabled, so slog neither constructs nor dispatches the record, and any audit record that reaches the handler is dropped.
- Attributes and groups added with log/slog.Logger.With and log/slog.Logger.WithGroup apply to operator records only. An audit line contains only the fields of its event, plus time, level, msg and logger=audit, all at the top level, so request-scoped logger context cannot leak into or reshape the audit record.
- The middleware must be registered last, making it the outermost handler. It handles audit records itself and never passes them to the handler it wraps, so no middleware registered before it can see, change or drop an audit record. A middleware registered after it would see audit records, and the library cannot prevent that.
- The write is synchronous, and each record is written with one Write call under a lock shared by every handler built from one HandlerMiddleware result, so concurrent records never interleave. Applying two separate HandlerMiddleware results to one writer gives two locks; build the middleware once per writer. A failed or short write never returns an error to the caller and is never logged, so a broken audit stream neither fails the action being audited nor floods the operator output. Instead each failed record increments the WriteFailuresMetricName counter (no attributes) on the meter provider set with WithMeterProvider, or the global provider by default. After a short write, the next record starts on a new line so it still parses.
Actor From Context ¶
Call sites do not pass the actor. The authentication middleware that verifies a caller stores one Actor in the request context with ContextWithActor, and the EventBuilder writes every actor key of the event's subjects from it. This removes the class of defect where a call site forgets the actor or names it differently, and gives one place to change how actors are identified. A record built away from the request that caused it, such as from stored session state, passes its actor with WithActor instead.
Each principal kind has its own constructor, and each writes a fixed set of subjects keys, plus any optional field set with an ActorOption:
- NewUserActor: principal_kind, user_id, issuer. The user id is the stable id the issuer assigns, never a mutable attribute such as an email, so the trail survives a rename.
- NewServiceAccountActor: principal_kind, user_id.
- NewSCIMIssuerActor: principal_kind, user_id and issuer (both the issuer id), token_fingerprint. The fingerprint is keyed, because a static token can be weak and an unkeyed hash kept for years can be guessed offline.
- NewSystemActor: principal_kind, user_id (the fixed name of the runnable). Only work that no caller started, such as a boot-time job, builds one.
- NewAnonymousActor: principal_kind and never user_id. Only an authentication refusal builds one, so its outcome is denied, or error when the service failed before it could verify the caller.
A SubjectEnricher, set with WithSubjectEnricher, adds component keys to the subjects. It can never set an actor key: any it returns is dropped, so an enricher cannot give an anonymous event a user id. Its keys are bounded as Size Limit describes.
The component generates a request id when a request arrives and stores it with ContextWithRequestID; the builder copies it to metadata.extra.request_id, which joins the event to the access logs. It never reuses an id the client sent, because a client can choose it. A component may also record the id a client sent, such as an X-Request-ID header, in its source extra keys; that value is the client's claim, and a reader must not treat it as the same as metadata.extra.request_id even when the key names match.
Event Builder ¶
EventBuilder.NewEvent takes the context, the type, the Target, the outcome and optional inputs, and returns the events to log:
builder := audit.NewEventBuilder("example-service",
audit.WithBuilderMeterProvider(meterProvider))
// In the authentication middleware:
ctx = audit.ContextWithActor(ctx, audit.NewUserActor(userID, issuer))
ctx = audit.ContextWithRequestID(ctx, requestID)
// At the call site:
events, err := builder.NewEvent(ctx, "widgets.widget.update",
audit.Target{Type: "widget", ID: widget.ID, Name: widget.Name},
audit.OutcomeSuccess,
audit.WithChanges(
audit.FieldChange("color", "blue", "red"),
audit.SecretFieldChange("api_key"),
audit.MembersChange("owners", added, removed),
),
)
if err != nil {
return err // a defect in the call site; see below
}
audit.LogEvents(ctx, logger, events)
Every event it builds has metadata.extra.schema_version equal to SchemaVersion, a new audit id and a UTC loggedAt. A component that re-sends a record, or that builds an event before or after the moment it records, sets the first event's audit id with WithAuditID and the time with WithOccurredAt. The default source is SourceTypeLocal with the host name, which in a Kubernetes pod is the pod name; override it with WithSourceName or, per event, WithSource.
NewEvent refuses to build an event, returns an error and no event, and increments the EventErrorsMetricName counter with a "reason" attribute, when:
- the context has no actor, or a non-anonymous actor with no user id (ErrNoActor, reason no_actor). Every audited request needs a known actor;
- the outcome is not success, failure, error or denied, nor one the builder declared with WithExtraOutcomes (ErrInvalidOutcome, reason invalid_outcome). The set is closed so a SIEM rule can enumerate it. Prefer an existing outcome with a reason where one fits: a write that found no row is a failure with reason "not_found", and a call that returned an error result inside a successful response is a failure with a reason naming it. Declare an extra outcome, such as "unknown" for a call whose result never came back, only when no existing one is true;
- the reason set with WithReason is not a lower snake case token of at most 64 bytes (ErrInvalidReason, reason invalid_reason). A reason is a bounded token such as "not_found", never free text, an error message or a value the caller controls;
- an anonymous actor has an outcome other than denied or error (ErrAnonymousInvalidOutcome, reason anonymous_invalid_outcome);
- the event was built with WithoutSplit and does not fit in one line (ErrTooLarge, reason too_large).
Component keys passed with WithExtra go to metadata.extra, bounded as Size Limit describes. A key the builder writes itself, such as "reason" or "request_id", is dropped, so a component cannot forge one.
WithDelegation attaches the actor's delegation chain (see Delegation Chains). Its hops are a list, split across continuation events like the change list when they do not fit.
Change Detail ¶
WithChanges records what a write changed in metadata.extra.changes. FieldChange records a field's value before and after the write, so the trail shows every value a field has held. MembersChange records the ids of the members added and removed. SecretFieldChange records a secret-bearing field by name only: it has no slot for a value, so a call site cannot put a secret in the trail by mistake. WithCause links an event to the event that caused it, such as the deletion that cascaded to it.
Size Limit ¶
Container runtimes split a stdout line longer than 16 KiB into partial records, and a collector that does not join them breaks the event. The builder therefore keeps each line, measured with the audit handler middleware's own renderer and newline included, within MaxLineBytes. It packs to 16,000 bytes, which leaves headroom for the record time.
- Each actor string, enricher value and component string value is cut so that its JSON encoding takes at most MaxActorStringBytes, because actor strings come from token claims with no length limit. The target id, the source type and value, each source extra string, each change field name and each delegation hop's issuer and subject are capped the same way, and so is each target extra value set in Target.Extra. A composite value, such as a map, is never cut, since a cut encoding is no longer the value: it is kept whole if it fits its source's budget, and dropped otherwise.
- Each of the four sources of extra keys (the subject enricher, the target extra, the source extra and the component keys passed with WithExtra) keeps at most 16 keys, in sorted key order. A key longer than 64 bytes is dropped, and so is each key past the source's byte budget, counted over its encoded keys and values: 2 KiB for the enricher and the component keys, 512 bytes for the target extra and the source extra. These inputs at their caps still leave room for list entries.
- The change list, the member ids and the delegation chain are split, never cut, so an auditor can still find when a given member was added. When they do not fit, the first event is followed by continuation events. Each has its own audit id, sets metadata.extra.cause to the first event's audit id, and repeats the type, outcome, reason, request id, actor and the target's type and id. Every event of the set carries metadata.extra.part and metadata.extra.parts, and each list entry appears in exactly one of them. Each event of the set that carries delegation hops also carries metadata.extra.hop_offset, the index of its first hop in the full chain, so only the event with offset 0 has the current actor as chain[0]. The first event keeps the caller's cause, the component keys, the payload and the target name.
- Any other overflow is cut, in order: the payload set with WithPayload, which becomes a JSON string of its leading bytes; then the target name; then each change value or member id whose encoding is over 4 KiB, cut to 4 KiB, when its entry does not fit in an event on its own. If the entry still does not fit in a continuation, as when both values of a change are long and every source is at its cap, its values over 2 KiB are cut to 2 KiB, then those over 1 KiB to 1 KiB, and so on down to 256 bytes. An entry that fits only in a continuation moves there whole. Sizes are measured in encoded bytes, so characters JSON escapes count in full.
- The builder never cuts the audit id, the time, the type, the outcome, the reason, the request id, the actor (beyond its cap), the cause, the component or the target type. These are set by the component, not the caller, and normally take a few hundred bytes. If the fields every event repeats leave no room for a list entry, which takes an oversized value among these, the builder returns a single event, best effort, rather than one oversized event per list entry. That event keeps every entry, with each value over 4 KiB still cut, and cuts nothing that would not help.
Log every event of a set, in order; LogEvents does. The audit handler middleware writes each event as its own line, so a failed write loses that event only: the WriteFailuresMetricName counter records it, and a reader sees the set is incomplete because fewer events share the first event's audit id (as their own or as their cause) than metadata.extra.parts says. A component whose delivery must never leave part of a record builds it with WithoutSplit, which returns one event or refuses with ErrTooLarge.
Each value cut by these rules is listed in metadata.extra.truncated with its field name, original length and the SHA-256 digest of the full value. A digest lets an auditor match a value they already hold; it does not recover the value. Each key dropped for its length, its count, its source's budget or a value that cannot be encoded is listed with its field name and the length of its value, and no digest: the value appears nowhere else in the trail, and an unsalted digest of a short value, such as a token, can be reversed by guessing. At most 4 dropped keys of one source are listed individually; one summary record, whose field is the source, counts the rest and digests their sorted names. Two kinds of key are dropped without a record, because they are expected rather than lost: an empty key, and a key the source may not set, such as an actor key an enricher returns or a metadata.extra key the builder writes.
Refusal Limiter ¶
A refusal event records an action that the component refused before it ran, such as a request that failed an authorization check. Any caller can cause one, including an unauthenticated one, so refusal events must not let a caller flood the audit trail. A RefusalLimiter bounds them the same way in every component, and a counter still counts every refusal.
Only the call site knows that the action did not run, so the call site marks a refusal by building it with EventBuilder.NewRefusal. The limiter never infers a refusal from the outcome: a call that ran and failed is recorded every time. A refusal's outcome is always denied, and it is always one event. Its source is always the builder's local source, because a refusal never records a client network address: behind a proxy every connection has the proxy's address, so the address would not tell callers apart. The request id joins the event to the access logs, which hold the real address.
Build one limiter per process, write every event through it and close it on shutdown. There is no package-level instance:
limiter := audit.NewRefusalLimiter(logger, "example-service",
audit.WithRefusalMeterProvider(meterProvider))
defer limiter.Close()
// At a call site that refuses an action:
events, err := builder.NewRefusal(ctx, "widgets.widget.delete",
audit.Target{Type: "widget", ID: widget.ID},
audit.WithReason("forbidden"))
if err != nil {
return err
}
limiter.LogEvents(ctx, events)
Pass the limiter the same component name as the EventBuilder, and, with WithRefusalSourceName, the same source name as the builder's WithSourceName. Both source names default to the host name. The limiter writes its summaries with them. EventBuilder.NewRefusal returns the errors NewEvent returns other than the outcome errors. Because a refusal is never split, one whose fields do not fit in one line returns ErrTooLarge, and no event is built for it.
The package-level LogEvents applies no limit and counts nothing, so a refusal or an anonymous event written with it is not bounded.
RefusalLimiter.LogEvents writes an event built with EventBuilder.NewEvent straight through, every time, unless its actor is anonymous. It bounds the rest as follows, and each rule has a reason:
- An authenticated refusal is keyed by its actor's principal kind, issuer and user id, its type, its reason, and its target's type and id. The actor and target parts are SHA-256 digests of the full values, so two long target ids that the builder cuts to the same value are still two keys. The target's name and extra are not part of the key. The first refusal for a key is written and opens a window of RefusalWindow, one minute. The key's other refusals in the window are not written. When the window closes, a summary is written if any were suppressed: it has the type, outcome, actor, target and reason of the first refusal, and metadata.extra.suppressed holds the number of refusals it stands for. A summary is built from the stored key, not from a request, so it has no request id. An authenticated actor has no other cap: it is accountable, so every target it was refused on appears in the trail.
- Every event with an anonymous actor shares one budget of AnonymousRefusalBudget lines, 100, per window, whether it is a refusal (denied) or a failure before the caller could be verified (error). The window opens at the first anonymous event. The first 99 lines are written, and one slot is kept for the overflow summary, which is written at the window's close if any event was suppressed. Its type is RefusalOverflowEventType, its actor is anonymous with no issuer, its outcome is denied, metadata.extra.suppressed holds the total and metadata.extra.suppressed_by_type the count per event type, which sum to the total. Past 32 event types, the rest are counted under "other", so the summary stays one bounded line. An event split across continuation events takes one line of the budget per event, and is written whole or not at all. Anonymous refusals have no per-key window, so each written event keeps its own issuer and token fingerprint, and a replayed token is not hidden behind an earlier refusal at the same issuer. Once the budget is spent, though, every later anonymous event in the window is only counted in the overflow summary, with no issuer, fingerprint or request id, so a burst can hide what follows it until the window closes.
- The limiter holds a window for at most MaxRefusalKeys, 10,000, authenticated keys at once. A refusal for a new key past that bound is written with no window and no stored state. This bounds memory and hides nothing, but while the limiter holds 10,000 keys, refusals for other keys are written every time: a caller that fills the table with distinct targets is not limited further. Such a caller is authenticated, so every line names it. A window's state is freed when it closes.
- A goroutine writes each summary when its window closes, even when no later refusal arrives. RefusalLimiter.Close writes the summary of every open window, then stops it. After Close, a refusal is not written. Summaries pending when a process exits without Close are lost; the counter is the record of the refusals they stood for.
- Each limited event that reaches the limiter with a source other than SourceTypeLocal, such as an anonymous event built with NewEvent and WithSource, is written with the limiter's local source instead. The limiter writes a copy; the caller's event keeps its source.
- Each refusal given to the limiter, written or not, increments the RefusalsMetricName counter with the attributes "type", the event type, and "recorded", true when the limiter passed its events to the logger. The handler's enable gate or a failed write can still drop an event counted as recorded; the WriteFailuresMetricName counter counts the failed writes. It counts refusals, not lines: an anonymous event built with NewEvent and split across continuation events is one refusal, passed on or suppressed whole, so the recorded total equals the refusal lines passed on, summaries aside, only when no such set is passed on. Every refusal built with NewRefusal is one line. Summaries are not counted. The reason is not an attribute, since its values are not a closed set.
The limits apply per limiter, so each replica of a component bounds its own refusals; there is no limit shared across replicas.
Conformance Helper ¶
The audittest subpackage checks a component's audit output against these rules. Each component runs it in its unit tests against every event type it declares; see that package for the checks.
Well-Known Constants ¶
The package defines well-known constants for event types, outcomes, source types, target types, and map keys used in Subjects, Target, Source.Extra, and Metadata.Extra fields. Using these constants ensures consistency across the ToolHive ecosystem.
Stability ¶
This package is Alpha stability. The API may change without notice. See the toolhive-core README for stability level definitions.
Package audit provides MCP-specific audit event types and constants.
Index ¶
- Constants
- Variables
- func ContextWithActor(ctx context.Context, actor Actor) context.Context
- func ContextWithRequestID(ctx context.Context, requestID string) context.Context
- func HandlerMiddleware(opts ...MiddlewareOption) func(slog.Handler) slog.Handler
- func IsValidOutcome(outcome string) bool
- func IsValidReason(reason string) bool
- func LogEvents(ctx context.Context, logger *slog.Logger, events []*AuditEvent)
- func NewAuditLogger(w io.Writer) *slog.Logger
- func RequestIDFromContext(ctx context.Context) (string, bool)
- type Actor
- func ActorFromContext(ctx context.Context) (Actor, bool)
- func NewAnonymousActor(opts ...ActorOption) Actor
- func NewSCIMIssuerActor(issuerID, tokenFingerprint string, opts ...ActorOption) Actor
- func NewServiceAccountActor(id string, opts ...ActorOption) Actor
- func NewSystemActor(runnable string, opts ...ActorOption) Actor
- func NewUserActor(userID, issuer string, opts ...ActorOption) Actor
- type ActorOption
- type AuditEvent
- func (e *AuditEvent) LogTo(ctx context.Context, logger *slog.Logger, level slog.Level)
- func (e *AuditEvent) WithData(data *json.RawMessage) *AuditEvent
- func (e *AuditEvent) WithDataFromString(data string) *AuditEvent
- func (e *AuditEvent) WithDelegationChain(chain *DelegationChain) *AuditEvent
- func (e *AuditEvent) WithTarget(target map[string]string) *AuditEvent
- type BuilderOption
- type Change
- type DelegatedActor
- type DelegationChain
- type EventBuilder
- type EventMetadata
- type EventOption
- func WithActor(actor Actor) EventOption
- func WithAuditID(auditID string) EventOption
- func WithCause(auditID string) EventOption
- func WithChanges(changes ...Change) EventOption
- func WithDelegation(chain *DelegationChain) EventOption
- func WithExtra(extra map[string]any) EventOption
- func WithOccurredAt(t time.Time) EventOption
- func WithPayload(payload json.RawMessage) EventOption
- func WithReason(reason string) EventOption
- func WithSource(source EventSource) EventOption
- func WithoutSplit() EventOption
- type EventSource
- type MalformedReason
- type MiddlewareOption
- type PrincipalKind
- type RefusalLimiter
- type RefusalLimiterOption
- type SubjectEnricher
- type Target
Constants ¶
const ( // SubjectKeyPrincipalKind is the key for the actor's [PrincipalKind]. SubjectKeyPrincipalKind = "principal_kind" // SubjectKeyIssuer is the key for the verified token issuer, or the SCIM // issuer id. SubjectKeyIssuer = "issuer" // SubjectKeyClientID is the key for the OAuth client the token was issued to. SubjectKeyClientID = "client_id" // SubjectKeyTokenFingerprint is the key for a keyed fingerprint of a static // bearer token. Never the token itself. SubjectKeyTokenFingerprint = "token_fingerprint" )
Subject keys that, with SubjectKeyUser, SubjectKeyUserID, SubjectKeyClientName and SubjectKeyClientVersion, make up the actor in an event's subjects. The event builder writes them only from the Actor; a SubjectEnricher can never set them.
const ( // MetadataExtraKeySchemaVersion holds [SchemaVersion]. MetadataExtraKeySchemaVersion = "schema_version" // MetadataExtraKeyReason holds the bounded reason token set with [WithReason]. MetadataExtraKeyReason = "reason" // MetadataExtraKeyRequestID holds the request id from [ContextWithRequestID]. MetadataExtraKeyRequestID = "request_id" // MetadataExtraKeyCause holds the audit id of the event that caused this // one: the caller's [WithCause] on a first event, or the first event's // audit id on a continuation event. MetadataExtraKeyCause = "cause" // MetadataExtraKeyChanges holds the [Change] list set with [WithChanges]. // Read it from the event's JSON form; a [Change] has no accessors. MetadataExtraKeyChanges = "changes" // MetadataExtraKeyTruncated lists each value the builder cut or dropped, // with its field name and original length, and, for a cut value, the // SHA-256 digest of the full value. The value is of an unexported type; // read it from the event's JSON form, where each record is an object with // the keys field and length, and, when set, sha256, dropped and count. MetadataExtraKeyTruncated = "truncated" // MetadataExtraKeyPart is the 1-based position of an event among the // events one [EventBuilder.NewEvent] call returned, when it returned more // than one. MetadataExtraKeyPart = "part" // MetadataExtraKeyParts is the number of events one // [EventBuilder.NewEvent] call returned, when it returned more than one. MetadataExtraKeyParts = "parts" // MetadataExtraKeyHopOffset is the index, in the caller's delegation // chain, of the first hop an event carries, on each event that carries // hops when a call returned more than one event. A continuation's chain // starts part way along the caller's chain, so its chain[0] is the // current actor only when this is 0. MetadataExtraKeyHopOffset = "hop_offset" // MetadataExtraKeySuppressed holds the number of refusals a refusal // summary event stands for. The builder never sets it; it is reserved so // a component key cannot claim it. MetadataExtraKeySuppressed = "suppressed" // MetadataExtraKeySuppressedByType holds, on an anonymous refusal // overflow summary, the number of suppressed refusals per event type. // The builder never sets it; it is reserved so a component key cannot // claim it. MetadataExtraKeySuppressedByType = "suppressed_by_type" )
Keys the EventBuilder writes to metadata.extra. A component key passed with WithExtra that uses one of these names is dropped.
const ( // MaxLineBytes is the largest audit line, trailing newline included, that // the [EventBuilder] aims to produce; a line of exactly this size is // within the limit. Container runtimes split longer stdout lines into // partial records, which breaks the event for a collector that does not // join them again. The builder splits and cuts events to stay within it, // except for one best-effort event when fields it never cuts are too // large; see the package doc's Size Limit section. MaxLineBytes = 16384 // MaxActorStringBytes caps the JSON encoding of each actor string, each // subject enricher value, each component metadata.extra string, the // target id, each target extra value, the source type and value, each // source extra string, each change field name and each delegation hop's // issuer and subject. Actor strings come from token claims with no length // limit. MaxActorStringBytes = 256 // MaxReasonBytes caps the reason token. MaxReasonBytes = 64 )
const ( // OutcomeSuccess indicates the event was successful OutcomeSuccess = "success" // OutcomeFailure indicates the event failed OutcomeFailure = "failure" // OutcomeError indicates the event resulted in an error OutcomeError = "error" // OutcomeDenied indicates the event was denied (e.g., by authorization) OutcomeDenied = "denied" )
Common event outcomes
const ( // SourceTypeNetwork indicates the event came from a network request SourceTypeNetwork = "network" // SourceTypeLocal indicates the event came from a local source SourceTypeLocal = "local" )
Common source types
const ( // EventTypeMCPInitialize represents an MCP initialization event EventTypeMCPInitialize = "mcp_initialize" // EventTypeSSEConnection represents an SSE connection event EventTypeSSEConnection = "sse_connection" // EventTypeMCPToolCall represents an MCP tool call event EventTypeMCPToolCall = "mcp_tool_call" // EventTypeMCPToolsList represents an MCP tools list event EventTypeMCPToolsList = "mcp_tools_list" // EventTypeMCPResourceRead represents an MCP resource read event EventTypeMCPResourceRead = "mcp_resource_read" // EventTypeMCPResourcesList represents an MCP resources list event EventTypeMCPResourcesList = "mcp_resources_list" // EventTypeMCPPromptGet represents an MCP prompt get event EventTypeMCPPromptGet = "mcp_prompt_get" // EventTypeMCPPromptsList represents an MCP prompts list event EventTypeMCPPromptsList = "mcp_prompts_list" // EventTypeMCPNotification represents an MCP notification event EventTypeMCPNotification = "mcp_notification" // EventTypeMCPPing represents an MCP ping event EventTypeMCPPing = "mcp_ping" // EventTypeMCPLogging represents an MCP logging event EventTypeMCPLogging = "mcp_logging" // EventTypeMCPCompletion represents an MCP completion event EventTypeMCPCompletion = "mcp_completion" // EventTypeMCPRootsListChanged represents an MCP roots list changed notification EventTypeMCPRootsListChanged = "mcp_roots_list_changed" // Workflow-specific event types for vMCP composite workflow execution // EventTypeWorkflowStarted represents workflow execution start EventTypeWorkflowStarted = "vmcp_workflow_started" // EventTypeWorkflowCompleted represents successful workflow completion EventTypeWorkflowCompleted = "vmcp_workflow_completed" // EventTypeWorkflowFailed represents workflow failure EventTypeWorkflowFailed = "vmcp_workflow_failed" // EventTypeWorkflowTimedOut represents workflow timeout EventTypeWorkflowTimedOut = "vmcp_workflow_timed_out" // EventTypeWorkflowStepStarted represents workflow step execution start EventTypeWorkflowStepStarted = "vmcp_workflow_step_started" // EventTypeWorkflowStepCompleted represents successful step completion EventTypeWorkflowStepCompleted = "vmcp_workflow_step_completed" // EventTypeWorkflowStepFailed represents step failure EventTypeWorkflowStepFailed = "vmcp_workflow_step_failed" // EventTypeWorkflowStepSkipped represents conditional step skip EventTypeWorkflowStepSkipped = "vmcp_workflow_step_skipped" // Fallback event types for unrecognized or generic requests // EventTypeMCPRequest represents a generic MCP request when specific type cannot be determined EventTypeMCPRequest = "mcp_request" // EventTypeHTTPRequest represents a generic HTTP request (non-MCP) EventTypeHTTPRequest = "http_request" )
MCP-specific event types based on the Model Context Protocol specification
const ( // TargetTypeTool represents a tool target TargetTypeTool = "tool" // TargetTypeResource represents a resource target TargetTypeResource = "resource" // TargetTypePrompt represents a prompt target TargetTypePrompt = "prompt" // TargetTypeServer represents a server target TargetTypeServer = "server" // TargetTypeWorkflow represents a workflow target TargetTypeWorkflow = "workflow" // TargetTypeWorkflowStep represents a workflow step target TargetTypeWorkflowStep = "workflow_step" )
MCP target types for audit events
const ( // TargetKeyType is the key for the target type in the target map TargetKeyType = "type" // TargetKeyName is the key for the target name in the target map TargetKeyName = "name" // TargetKeyURI is the key for the target URI in the target map TargetKeyURI = "uri" // TargetKeyMethod is the key for the MCP method in the target map TargetKeyMethod = "method" // TargetKeyEndpoint is the key for the endpoint in the target map TargetKeyEndpoint = "endpoint" // TargetKeyWorkflowID is the key for the unique workflow execution ID TargetKeyWorkflowID = "workflow_id" // TargetKeyWorkflowName is the key for the workflow definition name TargetKeyWorkflowName = "workflow_name" // TargetKeyStepID is the key for the step identifier TargetKeyStepID = "step_id" // TargetKeyStepType is the key for the step type (tool, elicitation) TargetKeyStepType = "step_type" // TargetKeyToolName is the key for the tool being called (for tool steps) TargetKeyToolName = "tool_name" )
MCP-specific target field keys
const ( // SubjectKeyUser is the key for the user in the subjects map SubjectKeyUser = "user" // SubjectKeyUserID is the key for the user ID in the subjects map SubjectKeyUserID = "user_id" // SubjectKeyClientName is the key for the client name in the subjects map SubjectKeyClientName = "client_name" // SubjectKeyClientVersion is the key for the client version in the subjects map SubjectKeyClientVersion = "client_version" )
MCP-specific subject field keys
const ( // SourceExtraKeyUserAgent is the key for the user agent in the source extra map SourceExtraKeyUserAgent = "user_agent" // SourceExtraKeyRequestID is the key for the request ID in the source extra map SourceExtraKeyRequestID = "request_id" // SourceExtraKeySessionID is the key for the session ID in the source extra map SourceExtraKeySessionID = "session_id" )
MCP-specific source field keys for EventSource.Extra
const ( // MetadataExtraKeyMCPVersion is the key for the MCP version in the metadata extra map MetadataExtraKeyMCPVersion = "mcp_version" // MetadataExtraKeyTransport is the key for the transport type in the metadata extra map MetadataExtraKeyTransport = "transport" // MetadataExtraKeyDuration is the key for the request duration in the metadata extra map MetadataExtraKeyDuration = "duration_ms" // MetadataExtraKeyResponseSize is the key for the response size in the metadata extra map MetadataExtraKeyResponseSize = "response_size_bytes" // MetadataExtraKeyRetryCount is the key for the number of retries performed MetadataExtraKeyRetryCount = "retry_count" // MetadataExtraKeyStepCount is the key for the total number of steps in a workflow MetadataExtraKeyStepCount = "step_count" // MetadataExtraKeyTimeout is the key for the workflow timeout in milliseconds MetadataExtraKeyTimeout = "timeout_ms" )
MCP-specific metadata field keys for EventMetadata.Extra
const ( // RefusalWindow is the length of each refusal window. A window starts at // the first refusal it covers. RefusalWindow = time.Minute // AnonymousRefusalBudget is the number of lines a [RefusalLimiter] // writes per [RefusalWindow] for anonymous events, the overflow summary // included: at most AnonymousRefusalBudget-1 events, then the summary. AnonymousRefusalBudget = 100 // MaxRefusalKeys is the number of authenticated refusal keys a // [RefusalLimiter] holds a window for at once. A refusal for a new key // past it is written with no window, so while the limiter holds this many // keys, refusals for other keys are not limited. MaxRefusalKeys = 10000 // RefusalOverflowEventType is the type of the summary a // [RefusalLimiter] writes for the anonymous events past its budget. RefusalOverflowEventType = "audit.anonymous_refusal.overflow" // RefusalsMetricName is the name of the counter a [RefusalLimiter] // increments once for each refusal it is given, written or not. Its // attributes are "type", the event type, and "recorded", true when the // limiter passed the refusal's events to its logger. The handler's enable // gate or a failed write can still drop an event counted as recorded. A refusal is one call to // [RefusalLimiter.LogEvents]: an anonymous event built with // [EventBuilder.NewEvent] and split across continuation events is one // refusal written as several events. Summaries are not counted. RefusalsMetricName = "stacklok.audit.refusals" )
The bounds a RefusalLimiter applies. They are fixed, so every component bounds refusal events the same way.
const ( // ComponentToolHive is the component name for ToolHive API audit events. // Note that events directed for an MCP server will have the name of the // MCP server as the component instead. ComponentToolHive = "toolhive-api" )
Component name for ToolHive
const DefaultMaxDelegationDepth = 16
DefaultMaxDelegationDepth is the default cap on how many delegation hops ParseDelegationChain retains. It is a parse ceiling, not a minting cap: RFC 8693 sets no limit on chain length, so this bounds the size of the retained chain and of the emitted audit record on attacker-influenceable input. It does not bound parsing work — the caller has already decoded the claim. Callers should pass their own minting-side cap as maxDepth when they have one; the default is intentionally larger than any known consumer's minting cap, so that for consumers passing their (smaller) mint cap, Truncated=true is a genuine signal that a token came from outside their own issuance path.
const EventErrorsMetricName = "stacklok.audit.event.errors"
EventErrorsMetricName is the name of the counter EventBuilder.NewEvent increments each time it refuses to build an event. Its one attribute, "reason", is one of no_actor, invalid_outcome, invalid_reason, anonymous_invalid_outcome and too_large. Every increment but too_large is a defect in the calling code; too_large counts events built with WithoutSplit that did not fit in one line.
const LevelAudit = slog.Level(2)
LevelAudit is a custom slog level for audit events, sitting between slog.LevelInfo (0) and slog.LevelWarn (4). Logging audit events at this dedicated level lets log infrastructure filter them independently from regular application logs. Pass it as the level argument to AuditEvent.LogTo and as the Level in a handler's slog.HandlerOptions so all ToolHive components share one definition rather than hardcoding the numeric value.
const SchemaVersion = 1
SchemaVersion is the value of metadata.extra.schema_version on every event the EventBuilder builds. It increases only on a breaking change to the keys the builder writes.
const TargetKeyID = "id"
TargetKeyID is the key for the target's stable id in the target map.
const ( // WriteFailuresMetricName is the name of the counter [HandlerMiddleware] // increments once for each audit record whose write to the audit writer // failed or was short. It has no attributes. Alert on it to detect lost // audit records. WriteFailuresMetricName = "stacklok.audit.write.failures" )
Variables ¶
var ( // ErrNoActor means the context carries no valid [Actor]. Every audited // request must have one; set it with [ContextWithActor]. ErrNoActor = errors.New("audit: no actor in context") // ErrInvalidOutcome means the outcome is not one of [OutcomeSuccess], // [OutcomeFailure], [OutcomeError] and [OutcomeDenied], nor one the // builder declared with [WithExtraOutcomes]. ErrInvalidOutcome = errors.New("audit: outcome is not success, failure, error, denied or a declared extra outcome") // ErrInvalidReason means the reason is not a lower snake case token of at // most [MaxReasonBytes] bytes. ErrInvalidReason = errors.New("audit: reason is not a bounded lower snake case token") // ErrAnonymousInvalidOutcome means an anonymous actor was given an // outcome other than [OutcomeDenied] or [OutcomeError]. ErrAnonymousInvalidOutcome = errors.New("audit: anonymous actor outcome must be denied or error") // ErrTooLarge means an event built with [WithoutSplit] does not fit in // one line of [MaxLineBytes], even with the cuts the builder makes. ErrTooLarge = errors.New("audit: event does not fit in one line and splitting is off") )
Errors returned by EventBuilder.NewEvent. Each is also counted on the EventErrorsMetricName counter.
Functions ¶
func ContextWithActor ¶ added in v0.0.64
ContextWithActor returns a copy of ctx that carries actor. The authentication middleware calls it once it has verified the caller, and a runnable calls it with a NewSystemActor before it writes.
func ContextWithRequestID ¶ added in v0.0.64
ContextWithRequestID returns a copy of ctx that carries the request id. The component generates the id when the request arrives; it must never reuse an id the client sent, because a client can choose it. The EventBuilder copies it to metadata.extra.request_id.
func HandlerMiddleware ¶ added in v0.0.63
func HandlerMiddleware(opts ...MiddlewareOption) func(slog.Handler) slog.Handler
HandlerMiddleware returns a log/slog.Handler wrapper that routes LevelAudit records to a dedicated audit writer as JSON, and passes every other record to the wrapped handler unchanged. It is designed for logging.WithHandlerMiddleware and must be registered last, so that it is the outermost handler and no other middleware sees audit records.
For audit records the returned handler:
- reports Enabled according to the gate alone, regardless of the wrapped handler's level;
- writes one JSON line per record to the audit writer, with the level rendered as "AUDIT" and the attribute logger=audit;
- never calls the wrapped handler, so attributes and groups added with log/slog.Logger.With or log/slog.Logger.WithGroup do not appear;
- never returns a write error to the caller. Each failed or short write increments the WriteFailuresMetricName counter and is otherwise silent.
The returned function may be applied to several handlers. They all share one audit sink, so their records are serialized on the audit writer and counted on one counter.
func IsValidOutcome ¶ added in v0.0.64
IsValidOutcome reports whether outcome is in the closed outcome set. An EventBuilder also accepts the outcomes declared with WithExtraOutcomes.
func IsValidReason ¶ added in v0.0.64
IsValidReason reports whether reason is a lower snake case token of at most MaxReasonBytes bytes, such as "not_found".
func LogEvents ¶ added in v0.0.64
func LogEvents(ctx context.Context, logger *slog.Logger, events []*AuditEvent)
LogEvents logs every event, in order, at LevelAudit: the events one EventBuilder.NewEvent call returned. Logging only the first would lose the continuation events of a split set. It applies no limit: write events built with EventBuilder.NewRefusal, and events whose actor may be anonymous, with RefusalLimiter.LogEvents instead.
func NewAuditLogger ¶ added in v0.0.37
NewAuditLogger creates a new structured audit logger that writes to the specified writer. A nil writer defaults to os.Stdout.
The logger emits JSON at LevelAudit with the level rendered as the string "AUDIT" for compatibility with log aggregation systems (Loki, Elasticsearch, etc.) that expect standard level names — without the rewrite, audit events would appear as "INFO+2" and break level-based filtering.
func RequestIDFromContext ¶ added in v0.0.64
RequestIDFromContext returns the request id stored by ContextWithRequestID. It reports false when there is none or it is empty.
Types ¶
type Actor ¶ added in v0.0.64
type Actor struct {
// contains filtered or unexported fields
}
Actor is the verified caller of an audited action. The authentication middleware that verifies a caller stores one Actor in the request context with ContextWithActor, and the EventBuilder writes every actor key of the event's subjects from it, so call sites never pass the actor.
Build an Actor with the constructor for its principal kind. The zero Actor is not valid and is treated as no actor.
func ActorFromContext ¶ added in v0.0.64
ActorFromContext returns the actor stored by ContextWithActor. It reports false when ctx carries no actor, or carries one that is not valid (the zero Actor, or a non-anonymous actor with no user id).
func NewAnonymousActor ¶ added in v0.0.64
func NewAnonymousActor(opts ...ActorOption) Actor
NewAnonymousActor returns the actor for an authentication refusal, where no caller was verified. It has no user id, and an event built for it must have the outcome OutcomeDenied or, when the service failed before it could verify the caller, OutcomeError. Only an authentication refusal path should build one. The options may still record what the caller presented, such as the issuer or a token fingerprint.
func NewSCIMIssuerActor ¶ added in v0.0.64
func NewSCIMIssuerActor(issuerID, tokenFingerprint string, opts ...ActorOption) Actor
NewSCIMIssuerActor returns a SCIM provisioning client. The issuer id is both its user id and its issuer. tokenFingerprint is a keyed fingerprint of the bearer token it presented; see WithActorTokenFingerprint. Both win over a WithActorIssuer or WithActorTokenFingerprint option, so the issuer always equals the user id.
func NewServiceAccountActor ¶ added in v0.0.64
func NewServiceAccountActor(id string, opts ...ActorOption) Actor
NewServiceAccountActor returns a non-human actor identified by its stable id.
func NewSystemActor ¶ added in v0.0.64
func NewSystemActor(runnable string, opts ...ActorOption) Actor
NewSystemActor returns the actor for work that no caller started, such as a boot-time job. runnable is the fixed name of that work, for example "jobs.cleanup". Only such work should build a system actor, never a request handler.
func NewUserActor ¶ added in v0.0.64
func NewUserActor(userID, issuer string, opts ...ActorOption) Actor
NewUserActor returns a human actor. userID is the stable principal id the issuer assigns to the person, not a mutable attribute such as an email, so the audit trail still answers "what did this person do" after a rename. issuer wins over a WithActorIssuer option.
func (Actor) Kind ¶ added in v0.0.64
func (a Actor) Kind() PrincipalKind
Kind returns the actor's principal kind, or "" for the zero Actor.
type ActorOption ¶ added in v0.0.64
type ActorOption func(*Actor)
ActorOption sets an optional field of an Actor. Every ActorOption is named WithActor..., which sets them apart from the builder's and the handler middleware's options.
func WithActorClientID ¶ added in v0.0.64
func WithActorClientID(clientID string) ActorOption
WithActorClientID sets the OAuth client the caller's token was issued to.
func WithActorClientInfo ¶ added in v0.0.64
func WithActorClientInfo(name, version string) ActorOption
WithActorClientInfo sets the name and version of the client software the caller used, such as an MCP client.
func WithActorDisplayName ¶ added in v0.0.64
func WithActorDisplayName(name string) ActorOption
WithActorDisplayName sets a display name for the actor. It is informational and must never be used to match an actor; use the user id for that.
func WithActorIssuer ¶ added in v0.0.64
func WithActorIssuer(issuer string) ActorOption
WithActorIssuer sets the verified token issuer. The user and SCIM issuer constructors already set it.
func WithActorTokenFingerprint ¶ added in v0.0.64
func WithActorTokenFingerprint(fingerprint string) ActorOption
WithActorTokenFingerprint sets a keyed fingerprint (for example HMAC-SHA-256 under a key the service holds) of the static bearer token the caller presented. Pass a fingerprint, never the token: an unkeyed hash of a weak token can be reversed offline by anyone who can read the audit trail.
type AuditEvent ¶
type AuditEvent struct {
Metadata EventMetadata `json:"metadata"`
// Type: Defines the type of event that occurred
// This is a small identifier to quickly determine what happened.
// e.g. UserLogin, UserLogout, UserCreate, UserDelete, etc.
Type string `json:"type"`
// LoggedAt: determines when the event occurred.
// Note that this should have sufficient information to authoritatively
// determine the exact time the event was logged at. The output must be in
// Coordinated Universal Time (UTC) format, a modern continuation of
// Greenwich Mean Time (GMT), or local time with an offset from UTC to satisfy
// NIST SP 800-53 requirement AU-8.
LoggedAt time.Time `json:"loggedAt"`
// Source: determines the source of the event.
// Normally, using the IP address of the client, or pod name is sufficient.
// One must be careful of the data that's added here as we don't want to
// leak Personally Identifiable Information.
Source EventSource `json:"source"`
// Outcome: determines whether the event was successful or not, e.g. successful login
// It may also determine if the event was approved or denied.
Outcome string `json:"outcome"`
// Subject: is the identity of the subject of the event.
// e.g. who triggered the event? Additional information
// may be added, such as group membership and/or role
Subjects map[string]string `json:"subjects"`
// Component: allows to determine in which component the event occurred
// (Answering the "Where" question of section c in the NIST SP 800-53
// Revision 5.1 Control AU-3).
Component string `json:"component"`
// Target: Defines where the target of the operation. e.g. the path of
// the REST resource
// (Answering the "Where" question of section c in the NIST SP 800-53
// Revision 5.1 Control AU-3 as well as indicating an entity
// associated for section f).
Target map[string]string `json:"target,omitempty"`
// Data: enhances the audit event with extra information that may be
// useful for forensic analysis.
Data *json.RawMessage `json:"data,omitempty"`
// DelegationChain holds the RFC 8693 `act` delegation chain when the event's
// actor acted on behalf of a prior actor. Additive to Subjects; Subjects
// remains the flat backward-compatible identity map. Omitted when zero
// (no hops, no truncation, no malformation).
DelegationChain *DelegationChain `json:"delegation,omitempty"`
// contains filtered or unexported fields
}
AuditEvent represents an audit event. It provides the minimal information needed to audit an event, as well as a uniform format to persist the events in audit logs.
It is highly recommended to use the NewAuditEvent function to create audit events and set the required fields.
func NewAuditEvent ¶
func NewAuditEvent( eventType string, source EventSource, outcome string, subjects map[string]string, component string, ) *AuditEvent
NewAuditEvent returns a new AuditEvent with an appropriately set AuditID and logging time.
func NewAuditEventWithID ¶
func NewAuditEventWithID( auditID string, eventType string, source EventSource, outcome string, subjects map[string]string, component string, ) *AuditEvent
NewAuditEventWithID returns a new AuditEvent with the passed AuditID.
func (*AuditEvent) LogTo ¶
LogTo logs the audit event to the provided slog.Logger using the custom audit level.
func (*AuditEvent) WithData ¶
func (e *AuditEvent) WithData(data *json.RawMessage) *AuditEvent
WithData sets the data of the event.
func (*AuditEvent) WithDataFromString ¶
func (e *AuditEvent) WithDataFromString(data string) *AuditEvent
WithDataFromString sets the data of the event from a string. Note that validating that this is properly JSON-formatted is the responsibility of the caller.
func (*AuditEvent) WithDelegationChain ¶ added in v0.0.35
func (e *AuditEvent) WithDelegationChain(chain *DelegationChain) *AuditEvent
WithDelegationChain sets the RFC 8693 delegation chain for the event's actor. The chain is attached as-is; parsing raw `act` claims is the caller's responsibility (see ParseDelegationChain). Passing a nil or zero chain (no hops, no truncation, no malformation — see DelegationChain.IsZero) clears any previously set chain. A hopless but malformed chain is kept: "the caller asserted delegation we could not read" is audit-relevant and distinct from "no delegation". Subjects is not modified.
func (*AuditEvent) WithTarget ¶
func (e *AuditEvent) WithTarget(target map[string]string) *AuditEvent
WithTarget sets the target of the event.
type BuilderOption ¶ added in v0.0.64
type BuilderOption func(*builderConfig)
BuilderOption configures NewEventBuilder.
func WithBuilderMeterProvider ¶ added in v0.0.64
func WithBuilderMeterProvider(mp metric.MeterProvider) BuilderOption
WithBuilderMeterProvider sets the meter provider used for the EventErrorsMetricName counter. The default is the global provider returned by otel.GetMeterProvider. A nil provider keeps the default.
func WithExtraOutcomes ¶ added in v0.0.64
func WithExtraOutcomes(outcomes ...string) BuilderOption
WithExtraOutcomes declares outcomes the builder accepts beyond success, failure, error and denied, such as "unknown" for a call whose result never came back. Prefer an existing outcome with a WithReason token where one fits, since every reader of the trail must learn each extra outcome. Each must be a lower snake case token of at most MaxReasonBytes bytes: NewEventBuilder panics on any other value, such as "Unknown", since it is a programming error that would otherwise surface only later, as ErrInvalidOutcome from NewEvent. An anonymous actor's outcome is still denied or error. Declare the same outcomes to the audittest checker.
func WithSourceName ¶ added in v0.0.64
func WithSourceName(name string) BuilderOption
WithSourceName sets the value of the default event source, whose type is SourceTypeLocal. The default is the host name, which in a Kubernetes pod is the pod name.
func WithSubjectEnricher ¶ added in v0.0.64
func WithSubjectEnricher(enricher SubjectEnricher) BuilderOption
WithSubjectEnricher sets a SubjectEnricher that adds component keys to every event's subjects.
type Change ¶ added in v0.0.64
type Change struct {
// contains filtered or unexported fields
}
Change records one field that a write changed. The EventBuilder writes the changes passed with WithChanges to metadata.extra.changes.
Build a Change with FieldChange, SecretFieldChange or MembersChange. A secret field has no slot for a value, so a call site cannot record a secret value by mistake. A Change has no accessors; a test inspects it by decoding the logged line and reading metadata.extra.changes, for example with encoding/json.
func FieldChange ¶ added in v0.0.64
FieldChange records a field whose value went from before to after. Both values are written, so the trail shows each value a field has held.
func MembersChange ¶ added in v0.0.64
MembersChange records a membership change: the ids of the members added to and removed from field. The slices are copied.
func SecretFieldChange ¶ added in v0.0.64
SecretFieldChange records that a secret-bearing field changed, by name only. It takes no value, so neither the old nor the new secret can reach the audit trail.
func (Change) GoString ¶ added in v0.0.64
GoString renders the change like String, so the %#v verb, which does not use String, does not print a field value either.
func (Change) MarshalJSON ¶ added in v0.0.64
MarshalJSON encodes a value change as {"field","before","after"}, a secret change as {"field","secret":true}, and a membership change as {"field","added","removed"}.
type DelegatedActor ¶ added in v0.0.35
type DelegatedActor struct {
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
// contains filtered or unexported fields
}
DelegatedActor represents a single hop in an RFC 8693 delegation chain.
Per-hop identity is the issuer (iss) and subject (sub) pair only: per OpenID Connect Core §5.7 the (iss, sub) combination is the only stable, unique actor identifier, and RFC 8693 §6 calls for data minimization. Any other claims present on a hop are retained in the in-memory-only extra map (never serialized or logged) to avoid leaking Personally Identifiable Information.
func (DelegatedActor) Extra ¶ added in v0.0.35
func (a DelegatedActor) Extra() map[string]any
Extra returns a shallow copy of the hop's extra (non-standard) claims. Mutating the returned map (adding, deleting, or replacing top-level keys) does not affect the hop's internal state. However, mutating a nested map or slice value may share underlying data with the hop's copy. It returns nil when the hop has no extra claims.
The extra claims are deliberately excluded from JSON and slog output as a PII guard, and may contain sensitive or internal claims (session identifiers, emails, roles). Callers MUST NOT serialize or log the returned map; doing so reintroduces the leak this design prevents.
func (DelegatedActor) String ¶ added in v0.0.35
func (a DelegatedActor) String() string
String implements fmt.Stringer so that fmt-based rendering of a hop — or of any struct containing hops, such as a dereferenced DelegationChain — cannot reach the unexported extra claims through %v/%+v. fmt does not consult log/slog.LogValuer, so the PII guard needs this second, fmt-side door closed as well.
type DelegationChain ¶ added in v0.0.35
type DelegationChain struct {
Chain []DelegatedActor `json:"chain"`
Truncated bool `json:"truncated"`
Omitted int `json:"omitted"`
Malformed bool `json:"malformed"`
MalformedReason MalformedReason `json:"malformedReason,omitempty"`
}
DelegationChain holds a flattened, ordered RFC 8693 delegation chain.
The chain is ordered OUTERMOST-FIRST: Chain[0] is the current actor — the party that presented the token — and the last entry is the least recent (original) actor. The party on whose behalf they acted is NOT part of the chain: per RFC 8693 it is the token's top-level sub, carried by the event's own Subjects map; the chain never repeats it. Per RFC 8693 §4.1, only the top-level event claims and Chain[0] may drive access-control decisions; prior hops are informational only and exist for audit.
Ordering rationale — do not assume, and do not "fix": current-actor-first matches the read order of RFC 8693's nested act structure, and it keeps Chain[0] STABLE UNDER TRUNCATION — truncation drops inner (early) hops, so the one hop that may inform decisions is always at index 0, complete chain or not. Beware that append-style flat formats elsewhere (Envoy XFCC, GCP delegates[]) run the OPPOSITE direction (original-first); consumers correlating across systems must map explicitly rather than by position intuition.
Truncated, Omitted, and Malformed intentionally have no omitempty tag: an incomplete or non-conformant chain is never silently indistinguishable from a complete, well-formed one. When Truncated is true, Omitted reports how many inner hops were dropped to satisfy the maxDepth cap; the outermost hops are always preserved (the current actor is never dropped). When Malformed is true, MalformedReason carries the first conformance violation encountered, and Chain holds the hops that parsed successfully before it.
func ParseDelegationChain ¶ added in v0.0.35
func ParseDelegationChain(raw any, maxDepth int) *DelegationChain
ParseDelegationChain parses a raw RFC 8693 `act` claim into a flattened, outermost-first DelegationChain.
The input is expected to be the decoded JSON value of the `act` claim (i.e. a map[string]any, or any named map type with string keys such as jwt.MapClaims). The parser walks nested `act` claims iteratively, bounded by maxDepth, so pathologically deep input cannot cause a stack overflow.
ParseDelegationChain never fails: it is an audit-side parser, and an audit record must be producible for exactly the tokens that violate expectations (an unreadable delegation assertion is forensically distinct from "no delegation"). Non-conformant input is recorded on the returned chain via Malformed/MalformedReason rather than dropped or returned as an error. Enforcement belongs on the issuance path, not here.
Parsing semantics:
- maxDepth <= 0 uses DefaultMaxDelegationDepth.
- A nil input yields a zero chain (no hops, not malformed): a JSON null or absent act claim asserts no delegation.
- A non-object input (string, number, bool, array) yields no hops and Malformed=true with MalformedReasonActNotObject.
- A map with no iss/sub/act yields one hop with empty Subject/Issuer (sub is conventional, not RFC-mandatory; parsing is tolerant).
- A string sub sets that hop's Subject; a string iss sets Issuer. A non-string sub or iss leaves the field empty, flags the chain malformed, and retains the raw value in the hop's in-memory extra claims — the record shows that an identifier was present but unusable.
- A nested `act` map is recursed: the outer map is Chain[0], its act is Chain[1], and so on. The result is naturally outermost-first.
- A nested `act` that is present but not a map (JSON null excepted, which ends the chain) keeps the hops parsed so far and flags the chain malformed with MalformedReasonNestedActNotObject.
- When the depth equals maxDepth exactly, the full chain is returned with Truncated=false and Omitted=0.
- When the depth exceeds maxDepth, the OUTERMOST maxDepth hops are kept (the current actor is preserved), Truncated=true, and Omitted counts the dropped inner hops. A malformed node past the cap flags Malformed but is not counted as an omitted hop.
- Unknown extra keys on a hop are stored in that hop's in-memory-only extra map (see DelegatedActor.Extra) and are never serialized.
func (*DelegationChain) IsZero ¶ added in v0.0.35
func (c *DelegationChain) IsZero() bool
IsZero reports whether the chain carries no information at all: no hops, no truncation, and no malformation. A zero chain is omitted from JSON and log output; a non-zero chain — including a hopless but malformed one — is always recorded.
func (*DelegationChain) LogValue ¶ added in v0.0.35
func (c *DelegationChain) LogValue() slog.Value
LogValue implements log/slog.LogValuer so that every handler — not just JSONHandler, which happens to skip unexported fields via encoding/json — sees only the promoted iss/sub of each hop. Handing the struct to a handler directly would let a text or other fmt-based handler render the unexported extra claims via %+v, defeating the PII guard. The emitted shape mirrors the struct's JSON tags (including omitempty on iss/sub and malformedReason) so slog and JSON output stay structurally identical.
type EventBuilder ¶ added in v0.0.64
type EventBuilder struct {
// contains filtered or unexported fields
}
EventBuilder builds audit events that carry the actor from the request context and keep each line within MaxLineBytes, save for one best-effort event when fields the builder never cuts are too large (see EventBuilder.NewEvent). Create one per component with NewEventBuilder; it is safe for concurrent use.
func NewEventBuilder ¶ added in v0.0.64
func NewEventBuilder(component string, opts ...BuilderOption) *EventBuilder
NewEventBuilder returns an EventBuilder for component, the name of the emitting service, such as "example-service". It panics when an option is given an invalid value, as WithExtraOutcomes describes.
func (*EventBuilder) NewEvent ¶ added in v0.0.64
func (b *EventBuilder) NewEvent( ctx context.Context, eventType string, target Target, outcome string, opts ...EventOption, ) ([]*AuditEvent, error)
NewEvent builds the audit event for an action, with the actor taken from ctx or set with WithActor. It returns one event, or, when the event's lists do not fit in one line of MaxLineBytes, the first event followed by continuation events. Log every returned event, in order, with LogEvents, or with RefusalLimiter.LogEvents when the actor may be anonymous: an anonymous event is bounded only when written through the limiter.
When the fields every event repeats, which the builder never cuts (such as the type or the request id), leave no room for a list entry in a continuation, NewEvent returns a single best-effort event with every entry. That event can exceed MaxLineBytes; the package doc's Size Limit section describes the case.
It returns an error and no event, and increments the EventErrorsMetricName counter, when there is no valid actor (ErrNoActor), the outcome is neither in the closed set nor declared with WithExtraOutcomes (ErrInvalidOutcome), the reason is not a bounded token (ErrInvalidReason), an anonymous actor has an outcome other than denied or error (ErrAnonymousInvalidOutcome), or an event built with WithoutSplit does not fit in one line (ErrTooLarge).
func (*EventBuilder) NewRefusal ¶ added in v0.0.64
func (b *EventBuilder) NewRefusal( ctx context.Context, eventType string, target Target, opts ...EventOption, ) ([]*AuditEvent, error)
NewRefusal builds the audit event for an action the component refused before it ran, such as a request that failed an authorization check, and marks it as a refusal so a RefusalLimiter bounds it. Write the events it returns with RefusalLimiter.LogEvents. Only the call site knows that the action did not run, so a limiter never infers a refusal from the outcome: an event built with EventBuilder.NewEvent is never limited, unless its actor is anonymous.
A refusal's outcome is always OutcomeDenied. Set the reason with WithReason: the limiter keys an authenticated refusal by its actor's principal kind, issuer and id, its type, its reason, and its target's type and id. The target's name and extra are not part of the key, so put anything that tells two targets apart in the type or the id. A refusal is always one event, as if built with WithoutSplit, so it can be counted as one line. Its source is always the builder's local source and a WithSource option is ignored, because a refusal never records a client network address: any caller can cause one, and behind a proxy the address would not tell callers apart.
It returns the errors EventBuilder.NewEvent returns, other than ErrInvalidOutcome and ErrAnonymousInvalidOutcome.
type EventMetadata ¶
type EventMetadata struct {
// AuditID: is a unique identifier for the audit event.
AuditID string `json:"auditId"`
// Extra allows for including additional information about the event
// that aids in tracking, parsing or auditing
Extra map[string]any `json:"extra,omitempty"`
}
EventMetadata contains metadata about the audit event.
type EventOption ¶ added in v0.0.64
type EventOption func(*eventInput)
EventOption sets an optional input of EventBuilder.NewEvent.
func WithActor ¶ added in v0.0.64
func WithActor(actor Actor) EventOption
WithActor sets the event's actor, in place of the one in the context. Use it for a record built away from the request that caused it, such as from stored session state, where the verified actor is at hand but the request's context is not. The same rules apply: an actor that is not valid is refused with ErrNoActor.
func WithAuditID ¶ added in v0.0.64
func WithAuditID(auditID string) EventOption
WithAuditID sets the first event's audit id, in place of a new one, for a component that re-sends a record or that another record points at, and so needs the id to be stable. Continuation events still get new ids and point at it. An empty id is ignored. The builder never cuts the id, so it should be a bounded identifier such as a UUID.
func WithCause ¶ added in v0.0.64
func WithCause(auditID string) EventOption
WithCause sets metadata.extra.cause to the audit id of the event that caused this one, such as the deletion that cascaded to this resource.
func WithChanges ¶ added in v0.0.64
func WithChanges(changes ...Change) EventOption
WithChanges records the fields the action changed, in metadata.extra.changes. Repeated calls append.
func WithDelegation ¶ added in v0.0.64
func WithDelegation(chain *DelegationChain) EventOption
WithDelegation attaches the actor's RFC 8693 delegation chain. A chain too long for one event is split across continuation events.
func WithExtra ¶ added in v0.0.64
func WithExtra(extra map[string]any) EventOption
WithExtra adds component keys to metadata.extra, bounded in number, key length and total size as the package doc's Size Limit section describes. A key the builder writes itself, such as "reason" or "request_id", is dropped. Repeated calls merge.
func WithOccurredAt ¶ added in v0.0.64
func WithOccurredAt(t time.Time) EventOption
WithOccurredAt sets the event's loggedAt, in place of the time NewEvent is called, for an event built before or after the moment it records, such as one built before a transaction commits. The time is written in UTC. A zero time is ignored.
func WithPayload ¶ added in v0.0.64
func WithPayload(payload json.RawMessage) EventOption
WithPayload attaches a captured request or response payload as the event's data. Record a payload only when the operator has turned payload capture on. The builder copies it, and keeps a payload that is not valid JSON, such as a form-encoded body, as a JSON string. It is the first value cut when an event is too large, and is then replaced by a JSON string holding its leading bytes.
func WithReason ¶ added in v0.0.64
func WithReason(reason string) EventOption
WithReason sets metadata.extra.reason, a bounded lower snake case token that details the outcome, such as "conflict" or "not_found". It is never free text, an error message, or a value the caller controls.
func WithSource ¶ added in v0.0.64
func WithSource(source EventSource) EventOption
WithSource overrides the default source, which is SourceTypeLocal with the builder's source name. A component that records a client network address should use the connection's remote address only, never a forwarding header a client can set. EventBuilder.NewRefusal ignores it; a refusal's source is always the builder's local source.
func WithoutSplit ¶ added in v0.0.64
func WithoutSplit() EventOption
WithoutSplit makes NewEvent return exactly one event, or refuse with ErrTooLarge when the event does not fit in one line of MaxLineBytes even after the cuts the package doc's Size Limit section describes. Use it where one record must be one event, joined by one audit id.
type EventSource ¶
type EventSource struct {
// Type indicates the source type. e.g. Network, File, local, etc.
// The intent is to determine where a request came from.
Type string `json:"type"`
// Value aims to indicate the source of the event. e.g. IP address,
// hostname, etc.
Value string `json:"value"`
// Extra allows for including additional information about the event
// source that aids in tracking, parsing or auditing
Extra map[string]any `json:"extra,omitempty"`
}
EventSource represents the source of an audit event.
type MalformedReason ¶ added in v0.0.35
type MalformedReason string
MalformedReason is a low-cardinality label describing the first RFC 8693 conformance violation encountered while parsing an `act` claim. It is deliberately an enum rather than free text so that it is safe to use as a metric or alerting dimension.
const ( // MalformedReasonActNotObject: the top-level act claim value was not a // JSON object (e.g. a string, number, bool, or array). MalformedReasonActNotObject MalformedReason = "act_not_object" // MalformedReasonNestedActNotObject: a nested act member inside a // delegation hop was not a JSON object. MalformedReasonNestedActNotObject MalformedReason = "nested_act_not_object" // MalformedReasonIssNotString: a hop carried an iss claim that was not a // JSON string. The raw value is retained in that hop's in-memory extra // claims under "iss". MalformedReasonIssNotString MalformedReason = "iss_not_string" // MalformedReasonSubNotString: a hop carried a sub claim that was not a // JSON string. The raw value is retained in that hop's in-memory extra // claims under "sub". MalformedReasonSubNotString MalformedReason = "sub_not_string" )
Malformed reasons reported by ParseDelegationChain. The first violation encountered wins; subsequent violations do not overwrite it.
type MiddlewareOption ¶ added in v0.0.63
type MiddlewareOption func(*middlewareConfig)
MiddlewareOption configures HandlerMiddleware.
func WithEnabled ¶ added in v0.0.63
func WithEnabled(enabled bool) MiddlewareOption
WithEnabled sets the audit gate. When false, LevelAudit records are dropped and the handler reports them as disabled, so slog neither constructs nor dispatches the record. The default is true.
func WithMeterProvider ¶ added in v0.0.63
func WithMeterProvider(mp metric.MeterProvider) MiddlewareOption
WithMeterProvider sets the meter provider used for the WriteFailuresMetricName counter. The default is the global provider returned by otel.GetMeterProvider. A nil provider keeps the default.
func WithWriter ¶ added in v0.0.63
func WithWriter(w io.Writer) MiddlewareOption
WithWriter sets where audit lines are written. The default is os.Stdout. A nil writer keeps the default.
type PrincipalKind ¶ added in v0.0.64
type PrincipalKind string
PrincipalKind classifies the actor of an audit event. It is written to the event's subjects under SubjectKeyPrincipalKind.
const ( // PrincipalKindUser is a human caller authenticated by a token issuer. PrincipalKindUser PrincipalKind = "user" // PrincipalKindServiceAccount is a non-human caller with its own identity. PrincipalKindServiceAccount PrincipalKind = "service_account" // PrincipalKindSCIMIssuer is a SCIM provisioning client authenticated by a // static bearer token. PrincipalKindSCIMIssuer PrincipalKind = "scim_issuer" // PrincipalKindSystem is work that no caller started, such as a // boot-time job. Its user id is the fixed name of the runnable. PrincipalKindSystem PrincipalKind = "system" // PrincipalKindAnonymous marks an authentication refusal: there is no // verified caller, so the event has no user id. PrincipalKindAnonymous PrincipalKind = "anonymous" )
The principal kinds. Each has its own Actor constructor.
type RefusalLimiter ¶ added in v0.0.64
type RefusalLimiter struct {
// contains filtered or unexported fields
}
RefusalLimiter writes audit events to a logger and bounds the refusal events among them, so that callers, including unauthenticated ones, cannot flood the audit trail. Build one per process with NewRefusalLimiter, write every event built with EventBuilder.NewRefusal through it, and RefusalLimiter.Close it on shutdown. It is safe for concurrent use. The package doc's Refusal Limiter section describes its bounds.
func NewRefusalLimiter ¶ added in v0.0.64
func NewRefusalLimiter(logger *slog.Logger, component string, opts ...RefusalLimiterOption) *RefusalLimiter
NewRefusalLimiter returns a RefusalLimiter that writes to logger at LevelAudit. component names the emitting service on the summaries it writes; pass the same name as to NewEventBuilder. The limiter starts a goroutine that writes each summary when its window closes; stop it with RefusalLimiter.Close.
func (*RefusalLimiter) Close ¶ added in v0.0.64
func (l *RefusalLimiter) Close() error
Close writes the summary of every open window, then stops the limiter's goroutine. A refusal given to the limiter after Close is not written and is counted with recorded=false. Close always returns nil, and calling it again does nothing. A LogEvents call that was admitted before Close may still be writing its events when Close returns.
func (*RefusalLimiter) LogEvents ¶ added in v0.0.64
func (l *RefusalLimiter) LogEvents(ctx context.Context, events []*AuditEvent)
LogEvents writes events, the events one EventBuilder.NewEvent or EventBuilder.NewRefusal call returned, at LevelAudit, unless the limiter suppresses them.
Events built with NewEvent whose actor is not anonymous are written every time, whatever their outcome, unchanged. Every other set is a refusal: it is counted on the RefusalsMetricName counter and written only within the limiter's bounds. A refusal event whose source is not SourceTypeLocal is written with the limiter's local source instead; the caller's events are not modified. After RefusalLimiter.Close, no refusal is written.
The limiter decides under its lock and writes after releasing it, so a slow logger does not hold up refusals the limiter suppresses.
type RefusalLimiterOption ¶ added in v0.0.64
type RefusalLimiterOption func(*refusalLimiterConfig)
RefusalLimiterOption configures NewRefusalLimiter.
func WithRefusalMeterProvider ¶ added in v0.0.64
func WithRefusalMeterProvider(mp metric.MeterProvider) RefusalLimiterOption
WithRefusalMeterProvider sets the meter provider used for the RefusalsMetricName counter. The default is the global provider returned by otel.GetMeterProvider. A nil provider keeps the default.
func WithRefusalSourceName ¶ added in v0.0.64
func WithRefusalSourceName(name string) RefusalLimiterOption
WithRefusalSourceName sets the value of the source, of type SourceTypeLocal, on the summaries the limiter writes and on any refusal it is given with a source of another type. The default is the host name, which in a Kubernetes pod is the pod name. Pass the same name as to the EventBuilder's WithSourceName.
type SubjectEnricher ¶ added in v0.0.64
SubjectEnricher returns extra subjects keys for an event, derived from the request context. It can never set or override an actor key: any key it returns that the builder writes from the Actor is dropped, whether or not the actor sets it.
type Target ¶ added in v0.0.64
type Target struct {
// Type is the kind of resource, such as "widget".
Type string
// ID is the resource's stable id. An id longer than
// [MaxActorStringBytes] is cut and recorded in metadata.extra.truncated.
ID string
// Name is the resource's name, when it has one. It is omitted when empty.
Name string
// Extra holds further keys that identify the target, such as the
// endpoint and method of an API call. They are written to the target map
// beside type, id and name, which they cannot replace, and are bounded
// as the package doc's Size Limit section describes.
Extra map[string]string
}
Target names the resource an event acted on.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package audittest checks a component's audit output against the rules the audit package's event builder and audit handler middleware enforce.
|
Package audittest checks a component's audit output against the rules the audit package's event builder and audit handler middleware enforce. |