audit

package
v0.30.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package audit records who did what on the control plane: every mutating admin action, every denial, and every login/logout, as one row per HTTP request.

Capture happens at three seams rather than per handler, so a new admin endpoint is covered the moment it calls Authorize:

  • Middleware mints an in-flight Event on the request context (actor, request id, method, path, client IP) and emits it after the response with the observed HTTP status.
  • Authorizer wraps the configured authz.Authorizer: each Authorize call contributes an action, a resource (with its scope chain) and an allow/deny status; the marking rule then decides whether the request earns a row.
  • Changed and Record are the two explicit calls: Changed attaches the JSON paths a write touched; Record covers handlers (login, logout) that never call Authorize.

WriteRows is the one path outside an HTTP request: the offline relay secret commands write their rows synchronously under a cli actor.

Values are never recorded — only field paths, and a path naming a secret is dropped outright. Writes go through a bounded, drop-on-full Emitter so no handler ever waits on the audit store. Reading rows back is the control plane's GET /api/audit; retention is the "audit" settings section, applied by the emitter's hourly prune.

Out of scope: data-plane traffic (usage events already record it) and export to an external SIEM.

Index

Constants

View Source
const (
	ActorUser       = "user"
	ActorAdminToken = "admin-token"
	ActorAnonymous  = "anonymous"
	ActorSCIMClient = "scim-client"
	ActorCLI        = "cli"
)

Actor kinds. Anonymous covers unauthenticated callers — notably a failed login, where the attempted username is all that is known. A SCIM client is an identity provider provisioning through /scim/v2, named by its client name. CLI is a relay command run against the database directly, named by the OS user.

View Source
const (
	StatusAllowed = "allowed"
	StatusDenied  = "denied"
	StatusError   = "error"
)

Outcome statuses. Error is an authorizer backend failure, which is not the same as a denial.

View Source
const (
	DefaultLimit = 100
	MaxLimit     = 10000
)

DefaultLimit and MaxLimit bound a list page.

View Source
const AnyField = "*"

AnyField is the field list for a whole-row write (create, delete), where naming individual paths says nothing the action doesn't.

View Source
const (
	// QueueSize is the bounded-channel capacity. Admin traffic is orders of
	// magnitude below the data plane; 4096 absorbs a long PG stall.
	QueueSize = 4096
)

Variables

View Source
var Dropped = prometheus.NewCounter(prometheus.CounterOpts{
	Namespace: metrics.Namespace,
	Subsystem: "audit",
	Name:      "dropped_total",
	Help:      "Audit events dropped because the emitter queue was full.",
})

Dropped counts audit events discarded because the queue was full. A dropped audit row is a hole in the record, so it gets its own counter rather than a label on the shared records_lost_total.

Functions

func Changed

func Changed(ctx context.Context, fields []string)

Changed attaches the JSON paths a write touched to the in-flight event. Secret-bearing paths are dropped here, so no call site has to remember to. No-op outside an audited request.

func DiffFields

func DiffFields(existing, incoming any) []string

DiffFields lists the JSON paths that differ between two entity values, one level under each top-level object ("metadata.displayName", "spec.enabled"). One level is enough to say what an operator edited without reconstructing the value.

func Discard

func Discard(ctx context.Context)

Discard drops the request's row: a dry run changes nothing, and its authorization pass would otherwise read as the writes it only planned.

func EffectiveLimit

func EffectiveLimit(limit int) int

EffectiveLimit clamps a caller-supplied page size.

func Middleware

func Middleware(e *Emitter, trusted []*net.IPNet) func(http.Handler) http.Handler

Middleware mints the in-flight event for every control-plane request and emits it once the response is written. Mount it after the session and admin-token middlewares so the actor is already in context. trusted is the proxy set X-Forwarded-For is honoured behind; nil records the peer.

func Record

func Record(ctx context.Context, action string, res Resource, status string, actorOverride ...Actor)

Record writes an event for a handler that never calls Authorize (login, logout). actorOverride replaces the middleware's actor — a failed login has no session to identify the caller, only the attempted username.

func RecordEach

func RecordEach(ctx context.Context, rows []Row)

RecordEach replaces the request's single row with one per change: a bulk write (apply) makes many changes in one request, and each is its own audited action. No-op outside an audited request.

func RecordExtra added in v0.10.8

func RecordExtra(ctx context.Context, row Row)

RecordExtra adds a row beside the request's own, for a write a handler makes on the way to recording something else: a sign-in that links an account is still recorded as the login. No-op outside an audited request.

func ScopeOf

func ScopeOf(snap *catalog.Snapshot, owner *meta.Owner) []string

ScopeOf renders an owner's scope chain the way Authorize records it, for rows written through RecordEach.

func WriteRows added in v0.11.6

func WriteRows(ctx context.Context, sink Sink, actor Actor, req Request, rows []Row) error

WriteRows writes rows attributed to actor straight to sink, for an action taken outside an HTTP request (an offline relay command). Unlike Emit it waits for the write, so the caller can tell its operator that the record is missing. A row without a Code records 200.

Types

type Actor

type Actor struct {
	Kind      string `` /* 244-byte string literal not displayed */
	ID        string `json:"id,omitempty"        doc:"User id, when a user acted."`
	Name      string `json:"name,omitempty"      doc:"Username, attempted username, SCIM client name or OS user."`
	SessionID string `json:"sessionId,omitempty" doc:"Session the request came on, for a signed-in user."`
	IP        string `json:"ip,omitempty"        doc:"Client address, honouring trusted proxies."`
}

Actor is the caller an event is attributed to.

type Authorizer

type Authorizer struct {
	Inner authz.Authorizer
	// Snap resolves the current catalog snapshot for the owner's scope
	// chain. nil leaves Resource.Scope empty.
	Snap func() *catalog.Snapshot
}

Authorizer wraps the configured authorizer and feeds every decision into the in-flight event. Wrapping is what keeps handlers free of audit calls: the action string and resource a handler already passes to Authorize are exactly what the row needs.

func (Authorizer) Authorize

func (a Authorizer) Authorize(ctx context.Context, action string, res authz.Resource) error

Authorize implements authz.Authorizer, delegating verbatim.

func (Authorizer) Explain added in v0.11.0

func (a Authorizer) Explain(ctx context.Context, who *actor.Actor, action string, res authz.Resource) (rbac.Explanation, error)

Explain implements authz.Explainer by delegation. An explanation acts on nothing, so it adds no decision to the in-flight event; the access review records its own row.

func (Authorizer) Unwrap added in v0.11.0

func (a Authorizer) Unwrap() authz.Authorizer

Unwrap returns the wrapped authorizer, for capability checks such as authz.Explains.

func (Authorizer) Visible

func (a Authorizer) Visible(ctx context.Context, kind, id string, owner meta.Owner) bool

Visible implements authz.Scoper by delegation. An inner authorizer that doesn't scope reads stays unscoped — wrapping must not change what a caller can see.

type Change

type Change struct {
	Fields []string `json:"fields,omitempty" doc:"JSON paths the write changed; values are never recorded."`
}

Change lists the JSON paths a write touched. Values are never carried — the paths plus the row's own history answer "what changed".

type Emitter

type Emitter struct {
	// contains filtered or unexported fields
}

Emitter is the write path: handlers Emit, one goroutine batches into the Sink and enforces retention. Emit never blocks — a full queue drops and counts, which is the same contract the data plane's observers hold.

func NewEmitter

func NewEmitter(sink Sink, log *slog.Logger) *Emitter

NewEmitter starts the drain goroutine. Close it at shutdown.

func (*Emitter) Close

func (e *Emitter) Close()

Close drains what is queued and stops the prune loop. The queue channel is never closed: a concurrent Emit would panic on the send, and an audit trail must not be able to take the process down at shutdown.

func (*Emitter) DroppedCount

func (e *Emitter) DroppedCount() uint64

DroppedCount is the cumulative drop count, for assertions.

func (*Emitter) Emit

func (e *Emitter) Emit(ev Event)

Emit queues ev. Non-blocking: a full queue drops and increments Dropped.

func (*Emitter) Prune

func (e *Emitter) Prune()

Prune enforces the current retention window. Exported so the prune pass is testable without waiting an hour.

func (*Emitter) QueueDepth

func (e *Emitter) QueueDepth() int

QueueDepth is the number of events waiting to be written.

func (*Emitter) SetRetentionDays

func (e *Emitter) SetRetentionDays(days int)

SetRetentionDays updates the live retention window. Wired to the "audit" settings section by the composition root.

type Event

type Event struct {
	ID       string    `json:"id"               doc:"Event id."`
	TS       time.Time `json:"ts"               doc:"When the request was handled."`
	Actor    Actor     `json:"actor"            doc:"Who made the request."`
	Action   string    `json:"action"           doc:"The authorized action, such as policies.update."`
	Resource Resource  `json:"resource"         doc:"What the action targeted."`
	Outcome  Outcome   `json:"outcome"          doc:"The verdict and the status returned."`
	Request  Request   `json:"request"          doc:"The HTTP request."`
	Change   *Change   `json:"change,omitempty" doc:"What a write changed; absent for reads and refusals."`
}

Event is one audited control-plane request.

type Outcome

type Outcome struct {
	Status string `json:"status" enum:"allowed,denied,error" doc:"The authorization verdict; error is an authorizer failure, not a denial."`
	Code   int    `json:"code"   doc:"HTTP status the caller received."`
}

Outcome is the authorization verdict plus the HTTP status the caller saw.

type Query

type Query struct {
	ActorID       string
	ActorName     string
	Actions       []string
	ResourceKinds []string
	ResourceID    string
	Scopes        []string
	Status        string
	From          time.Time
	To            time.Time
	CursorTS      time.Time
	CursorID      string
	Limit         int
}

Query filters a list of audit events. Empty fields don't filter. Cursor* is the keyset position: rows strictly older than (CursorTS, CursorID).

type Reader

type Reader interface {
	Events(ctx context.Context, q Query) ([]Event, error)
}

Reader is the read side of the audit log.

type Request

type Request struct {
	ID     string `json:"id,omitempty"     doc:"Request id."`
	Method string `json:"method,omitempty" doc:"HTTP method."`
	Path   string `json:"path,omitempty"   doc:"Request path."`
}

Request identifies the HTTP request the event came from.

type Resource

type Resource struct {
	Kind  string      `json:"kind"            doc:"Target kind, as an API singular."`
	ID    string      `json:"id,omitempty"    doc:"Target id."`
	Name  string      `json:"name,omitempty"  doc:"Target slug."`
	Owner *meta.Owner `json:"owner,omitempty" doc:"The target's owner."`
	Scope []string    `` /* 134-byte string literal not displayed */
}

Resource is the target of the action, as it was passed to Authorize. Scope is the owner's scope chain rendered as "project:<id>" / "team:<id>", most specific first; the global scope is omitted.

type Row

type Row struct {
	Action   string
	Resource Resource
	Status   string // empty = StatusAllowed
	Fields   []string
	// Code is the HTTP status the row records; 0 takes the request's. A request that failed part-way sets it on the changes that did happen.
	Code int
}

Row is one change a bulk write made.

type Sink

type Sink interface {
	Write(ctx context.Context, events []Event) error
	Prune(ctx context.Context, before time.Time) (int64, error)
}

Sink persists a batch of events.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store reads and writes audit_events. It satisfies both Sink and Reader.

func NewStore

func NewStore(q *gen.Queries) *Store

NewStore constructs a Store from an existing sqlc Queries handle.

func (*Store) Events

func (s *Store) Events(ctx context.Context, q Query) ([]Event, error)

Events returns matching events, newest first.

func (*Store) Prune

func (s *Store) Prune(ctx context.Context, before time.Time) (int64, error)

Prune deletes events older than before, returning the row count.

func (*Store) Write

func (s *Store) Write(ctx context.Context, events []Event) error

Write inserts a batch in one COPY round-trip. All or nothing: a partial audit batch is worse than a logged failure the drop counter already surfaces.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL