Documentation
¶
Overview ¶
Package audit is chok's compliance-grade audit log component.
Audit log records "who did what to which resource" — distinct from:
- access log (parts/log AccessFiles): HTTP traffic, request-scoped, short retention, ops-facing.
- metrics (parts/metrics): aggregate counters, no per-event detail.
- traces (parts/tracing OpenTelemetry): performance / latency attribution, sampled, not retained for compliance.
Audit is long-retention (≥ months), per-event, and queryable by auditors / admins. Write path is async (buffered channel → batch insert) so business handlers don't pay DB latency on every event; the trade-off (back-pressure vs drop) is configured per deployment via config.AuditOptions.DropOnFull.
This package only defines the data model + Logger contract + context-extraction helpers. The Component plumbing (channel + worker + cron purge + admin HTTP route) lives in parts/audit.
Reference: SPEC parts-audit-claude.md.
Index ¶
- Constants
- type DBLogger
- func (l *DBLogger) Close()
- func (l *DBLogger) LastError() (error, time.Time)
- func (l *DBLogger) Log(ctx context.Context, entry Entry)
- func (l *DBLogger) LogSync(ctx context.Context, entry Entry) error
- func (l *DBLogger) Query(ctx context.Context, q Query) ([]Log, int64, error)
- func (l *DBLogger) Stats() Stats
- type DBLoggerOption
- type Entry
- type Log
- type Logger
- type Query
- type Stats
- type Statser
Constants ¶
const ( ResultSuccess = "success" ResultFailure = "failure" ResultDenied = "denied" )
Result is the canonical outcome enum stored in Log.Result. The values are stable: changing them would break audit history queries and admin UI filters. New outcomes go through SPEC review.
const ( ActorTypeUser = "user" ActorTypeSystem = "system" ActorTypeAPIKey = "api_key" )
Actor type enum. Stored in Log.ActorType. Distinguishes a real user from system-driven actions (cron, replication) and machine-to- machine API key callers (where ActorID is the key ID, not a user).
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type DBLogger ¶
type DBLogger struct {
// contains filtered or unexported fields
}
DBLogger is the async DB-backed Logger used by parts/audit. The Component owns one and exposes it as audit.Logger to callers.
Why not parts/pool: audit is a single-producer-MPSC batched sink — many callers feed one channel, one worker drains, batches by size or interval, commits with one INSERT. Pool's any-func-any-time task model doesn't compose with batch ordering or with a Close that must drain the in-flight batch before db is closed by parts. SPEC §8 was updated (v0.3.5) to drop pool from Dependencies.
Backpressure semantics:
- DropOnFull=true : Log enqueues non-blocking. Channel full ⇒ entry dropped + Stats.Dropped++. Use when audit must never delay business requests.
- DropOnFull=false : Log blocks until channel has space (or ctx cancels). Use when audit is a compliance precondition for the business operation.
LogSync always commits synchronously regardless of DropOnFull, for the rare callsite that needs "audit before action".
func NewDBLogger ¶
func NewDBLogger(parent context.Context, db *gorm.DB, bufferSize int, dropOnFull bool, logger log.Logger, opts ...DBLoggerOption) *DBLogger
NewDBLogger constructs an async DB-backed Logger. The worker goroutine starts immediately under parent (typically context.Background; do NOT pass an Init ctx — it's bounded by startup timeout and would kill the long-running worker).
db must be ready (post-Init); bufferSize > 0; logger may be nil (defaults to log.Empty()).
func (*DBLogger) Close ¶
func (l *DBLogger) Close()
Close stops the worker. Idempotent. Returns when the worker has drained any pending batch and exited. Caller (parts/audit Component.Close) is responsible for waiting before letting the underlying DB go away.
func (*DBLogger) LastError ¶
LastError returns the most recent sink-side DB error and when it happened. Returns (nil, zero-time) when no error has occurred. Useful for the parts/audit Health output.
func (*DBLogger) LogSync ¶
LogSync commits a single Entry synchronously. The pending counter is not touched (sync writes don't go through the buffer).
type DBLoggerOption ¶
type DBLoggerOption func(*DBLogger)
DBLoggerOption tunes test-side knobs (smaller batches, faster flush) without exposing the surface to operators — production callers go through parts/audit which uses the constants.
type Entry ¶
type Entry struct {
// What — required.
Action string
// On what — recommended; some events have no resource binding.
Resource string
ResourceID string
// Outcome. Defaults to ResultSuccess when blank.
Result string
// Optional diffs (operator-supplied any; Logger marshals to JSON).
// Strip large/sensitive fields client-side — the Logger does not
// size-cap.
Before any
After any
// Operator note. Plain text, ≤ 512 chars (truncated by sink if
// longer; depending on dialect VARCHAR(512) may itself reject).
Reason string
// Free-form structured metadata. Marshalled to JSON.
Metadata map[string]any
// Who — typically populated by FromContext. Callers may override
// (e.g. system actions setting ActorType=ActorTypeSystem).
ActorID string
ActorType string
ActorIP string
// Cross-references — populated by FromContext from OTel + ctxval.
TraceID string
RequestID string
// OccurredAt is when the event happened from the caller's
// perspective. Zero ⇒ "now" at sink time. Non-zero overrides
// for events backfilled from external systems.
OccurredAt time.Time
}
Entry is the operator-facing audit input. Callers fill the "what" fields; framework helpers (FromContext) populate "who" and observability cross-references. Entry is the wire shape; Logger implementations are responsible for translating it into Log records (assigning ID, defaulting Result, marshalling Before/After to JSON).
Required fields: Action. Resource is strongly recommended; an empty Resource is allowed for events that aren't bound to a concrete object (e.g. "auth.login" — the actor IS the resource, pointed at via ActorID/ActorType).
Defaulting: Logger implementations apply Result=ResultSuccess when blank, ActorType=ActorTypeUser when ActorID is non-empty and ActorType is blank, and OccurredAt=time.Now() when zero. Operators that need different defaults set the field explicitly.
func FromContext ¶
FromContext returns an Entry pre-populated with framework-derived fields: ActorID/ActorType from auth.Principal, ActorIP from ctxval.ClientIPFrom, TraceID from the active OTel span, RequestID from ctxval.RequestIDFrom. Caller fills the business-side fields (Action, Resource, ResourceID, Before, After, Reason, Metadata) and passes the result to Logger.Log.
Behaviour when a source is missing:
- no auth.Principal in ctx ⇒ ActorID/ActorType blank, the entry is still loggable (the action was anonymous — auditors see that explicitly).
- no OTel span / sampler turned off ⇒ TraceID blank, no error.
- nil ctx ⇒ all fields blank; FromContext does not panic. Real callsites always have a ctx; the nil guard is purely defensive.
FromContext does not set OccurredAt — that's left to the Logger implementation so the timestamp reflects the moment of sink (when the row is in flight to the DB), not the moment the helper was called. Caller code that needs caller-side wallclock sets OccurredAt explicitly.
func MergeContext ¶
MergeContext fills any framework-derived field on entry that the caller left blank. Use when a caller has partially constructed an Entry (e.g. set ActorType=ActorTypeSystem before invocation) but still wants automatic ActorIP / TraceID / RequestID. Fields the caller already populated are preserved verbatim — auditors must trust that an explicit field beats a context-derived one.
type Log ¶
type Log struct {
ID string `gorm:"primaryKey;type:varchar(24)"`
OccurredAt time.Time `gorm:"index;not null"`
// Who — actor identity at the time of the event.
ActorID string `gorm:"type:varchar(64);index:idx_audit_actor_time,priority:1"`
ActorType string `gorm:"type:varchar(16)"` // user | system | api_key
ActorIP string `gorm:"type:varchar(45)"` // IPv4 or IPv6
// What — action name (verb-object form: "task.create",
// "user.role.assign") and outcome enum.
Action string `gorm:"type:varchar(64);index:idx_audit_action_time,priority:1"`
Result string `gorm:"type:varchar(16)"` // success | failure | denied
// On what — resource type + ID + optional before/after diffs.
// Before/After are operator-supplied JSON; callers must strip
// large fields (binary blobs, base64 avatars) themselves —
// the framework does not size-cap, because compliance often
// requires the full payload.
Resource string `gorm:"type:varchar(64);index:idx_audit_resource_time,priority:1"`
ResourceID string `gorm:"type:varchar(64);index:idx_audit_resource_time,priority:2"`
Before datatypes.JSON `gorm:"type:json"`
After datatypes.JSON `gorm:"type:json"`
// Context — links to other observability layers.
TraceID string `gorm:"type:varchar(32);index"`
RequestID string `gorm:"type:varchar(64);index"`
// Metadata is a free-form JSON bag for fields that don't fit
// the typed schema (campaign IDs, feature flag values, etc).
Metadata datatypes.JSON `gorm:"type:json"`
// Reason is an optional operator note explaining the action
// (e.g. cancellation reason, override justification). Plain
// text rather than structured because auditors read it.
Reason string `gorm:"type:varchar(512)"`
}
Log is the persisted audit record. The struct shape is the canonical schema; gorm.AutoMigrate creates the table from these tags. Composite indexes mirror the three documented query patterns (SPEC §3):
- "what did actor X do recently" — (ActorID, OccurredAt DESC)
- "history of resource (type, id)" — (Resource, ResourceID, OccurredAt DESC)
- "all events of action type" — (Action, OccurredAt DESC)
IDs use rid.New("audit"); collisions are not a concern at the expected scale (~1B events ≪ 12-char base62 space).
type Logger ¶
type Logger interface {
// LogSync writes synchronously and returns when the row is
// committed (or fails). Use ONLY when audit success is a
// pre-condition for the business operation (rare — typically
// "compliance refused, abort the action"). For all other
// callsites prefer Log.
LogSync(ctx context.Context, entry Entry) error
// Log enqueues asynchronously. Returns immediately on success
// (entry queued) or when the buffer is full and DropOnFull=true
// (entry counted as dropped). With DropOnFull=false the call
// blocks until the buffer has space — that's the back-pressure
// path for compliance-critical workloads.
Log(ctx context.Context, entry Entry)
// Query reads the persisted records. Returns the page slice and
// the total matching row count for pagination UI. The total is
// computed under the same filter as the page so admin UIs
// don't see drift between page count and total.
Query(ctx context.Context, q Query) ([]Log, int64, error)
}
Logger is the contract every audit sink implements. parts/audit wires *dbLogger (async DB sink) into chok components; tests can inject a *MemoryLogger or similar without changing call sites.
Lifecycle: Logger is bound to a Component (parts/audit). After Component.Close, calls to Log/LogSync return errors / drop on the floor — caller code must not assume the sink remains live past shutdown. Query is read-only against the underlying table; it keeps working as long as DB stays alive.
type Query ¶
type Query struct {
ActorID string
Resource string
ResourceID string
Action string
Result string
From, To time.Time
Page, Size int
}
Query is the parameter shape for Logger.Query — admin UI / CLI pagination + filter. Empty fields mean "any". Time range bounds are inclusive on both ends; zero time on either side disables that bound. Page is 1-indexed; Size <= 0 falls back to a Logger- implementation default (typical 50).
type Stats ¶
type Stats struct {
Pending uint64 // entries in the async buffer right now
Dropped uint64 // lifetime DropOnFull-mode rejections
Written uint64 // lifetime successful inserts (committed rows)
Failed uint64 // lifetime sink failures (DB error etc.)
}
Stats is exposed by Logger implementations that want to surface async-sink health to operators (matching the WatcherStats pattern in authz/casbin). Not all Loggers implement this — the in-memory test logger doesn't; the parts/audit DB-backed Logger does. Callers type-assert on this interface to decide whether to render the panel.