auditlog

package
v0.47.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: 45 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 auditlog records who did what — tool executions, human approvals, policy decisions, data and configuration changes — as structured audit events shipped over OTLP logs, so the collector infrastructure already running for traces and metrics carries the audit trail too.

Three layers:

  • Events (event.go): a small, versioned schema. Every event embeds Common (tenant, actor, session, source IPs, time) and is validated before it leaves the process, so a malformed record fails at your boundary rather than disappearing at the collector.
  • Client (client.go, otlp.go): encodes events as OTLP LogRecords and exports them over gRPC or HTTP/protobuf, with TLS/mTLS. Send is synchronous and returns the export error — including a collector's partial rejection — because an audit record the caller believes was written but was not is the failure mode audit exists to prevent.
  • Agent integration (agent.go): a tool middleware, a ConfirmFunc wrapper, a PermissionChecker decorator, and an EventHandler that audit an agent's actions without per-tool code. WithFailClosed makes the tool middleware refuse to execute when its audit record cannot be written.

Service identity (name, namespace, instance) rides the OTLP Resource; the tenant the data belongs to rides every event. When the caller's ctx carries a span, the record carries its trace and span IDs, linking the audit trail to the trace of the run that produced it.

Experimental: the API may change in a minor release until an adopter's production use settles it.

Minimal use:

c, err := auditlog.New(ctx, auditlog.Config{Endpoint: "collector:4317", ServiceName: "billing-agent"})
if err != nil { ... }
defer c.Close(ctx)

ctx = auditlog.WithActor(ctx, auditlog.Actor{TenantID: "acme", UserID: "u-42"})
reg.Register(tools.Chain(refundTool, auditlog.ToolMiddleware(c)))

Index

Constants

View Source
const (
	ProtocolGRPC = "grpc"
	ProtocolHTTP = "http/protobuf"
)

OTLP transport protocols.

View Source
const (
	EnvEndpoint    = "GOPHERAGENT_AUDIT_ENDPOINT"     // host:port — set it to turn auditing on
	EnvRequired    = "GOPHERAGENT_AUDIT_REQUIRED"     // true: a missing endpoint is an error, not "off"
	EnvProtocol    = "GOPHERAGENT_AUDIT_PROTOCOL"     // grpc (default) | http/protobuf
	EnvInsecure    = "GOPHERAGENT_AUDIT_INSECURE"     // true: plaintext, local collectors only
	EnvServiceName = "GOPHERAGENT_AUDIT_SERVICE_NAME" // default: OTEL_SERVICE_NAME, then "gopheragent"
	EnvTenantID    = "GOPHERAGENT_AUDIT_TENANT_ID"    // default tenant when ctx has no Actor; default "default"
	EnvHMACKey     = "GOPHERAGENT_AUDIT_HMAC_KEY"     // ≥16 bytes: keyed fingerprints + signed records
	EnvHeaders     = "GOPHERAGENT_AUDIT_HEADERS"      // k=v,k2=v2 — e.g. authorization=Bearer%20token
	EnvMode        = "GOPHERAGENT_AUDIT_MODE"         // blocking (default) | batch
	EnvCAFile      = "GOPHERAGENT_AUDIT_CA_FILE"
	EnvCertFile    = "GOPHERAGENT_AUDIT_CERT_FILE"
	EnvKeyFile     = "GOPHERAGENT_AUDIT_KEY_FILE"
)

Environment variables read by FromEnv. Only the endpoint is required; with it unset, auditing is off.

View Source
const SchemaVersion = "v1"

SchemaVersion is the version suffix of every event name. It changes only on a breaking change to an event's fields.

Variables

View Source
var (
	// ErrRejected wraps a collector's refusal of one or more records.
	ErrRejected = errors.New("auditlog: records rejected")
	// ErrClosed is returned by Send after Close.
	ErrClosed = errors.New("auditlog: client closed")
	// ErrBufferFull is returned by Send in ModeBatch when the buffer has no
	// room: those events were dropped and counted.
	ErrBufferFull = errors.New("auditlog: batch buffer full")
)
View Source
var ErrInvalidEvent = errors.New("auditlog: invalid event")

ErrInvalidEvent is wrapped by every validation failure.

Functions

func AuditConfirm

func AuditConfirm(inner agent.ConfirmFunc, e Emitter, opts ...Option) agent.ConfirmFunc

AuditConfirm wraps a HITL ConfirmFunc so every human verdict — approved, denied, timed out, or cancelled — is recorded as an ApprovalDecision.

func AuditPermissions

func AuditPermissions(inner agent.PermissionChecker, e Emitter, opts ...Option) agent.PermissionChecker

AuditPermissions decorates a PermissionChecker so deny and confirm verdicts (and allow, with WithAllowDecisions) are recorded as PolicyDecisions. The verdict itself is never changed.

func EventHandler

func EventHandler(e Emitter, opts ...Option) agent.EventHandler

EventHandler records security-relevant loop events: a request rejected by a policy hook becomes a SecurityViolation. Register it with loop.OnEvent(auditlog.EventHandler(client)).

func EventName

func EventName(e Event) string

EventName is the OTLP event name for e: "gopheragent.audit.<Kind>.v1".

func Hash

func Hash(key []byte, value string) string

Hash returns the keyed fingerprint of value — what ToolInvocation.ArgsHMAC holds. An auditor with the key computes Hash(key, knownArgs) to find the records of a known request; without the key the fingerprint reveals nothing, even for low-entropy values a plain hash would leak.

func ToolMiddleware

func ToolMiddleware(e Emitter, opts ...Option) tools.Middleware

ToolMiddleware audits every execution of the wrapped tool as a ToolInvocation at the tool's Level (see WithPolicy; default LevelMetadata). The argument fingerprint is keyed: it is recorded only when e holds an HMAC key (Config.HMACKey). A failed outcome write goes to the error handler; with WithFailClosed, a failed pre-execution write stops the tool from running.

func WithActor

func WithActor(ctx context.Context, a Actor) context.Context

WithActor returns a ctx carrying a for the audit integrations.

Types

type Actor

type Actor struct {
	TenantID       string
	UserID         string
	ImpersonatorID string
	AppID          string
	SourceIPs      []string
}

Actor identifies who is acting, carried on ctx from the request boundary so every audit record of the turn is attributed without threading arguments.

func ActorFromContext

func ActorFromContext(ctx context.Context) (Actor, bool)

ActorFromContext returns the Actor set by WithActor.

type ApprovalDecision

type ApprovalDecision struct {
	Common
	Tool     string   `json:"tool"`
	CallID   string   `json:"call_id,omitempty"`
	Decision Decision `json:"decision"` // approved | denied | timed_out | cancelled
}

ApprovalDecision records a human-in-the-loop verdict on a tool call.

func (ApprovalDecision) Kind

func (ApprovalDecision) Kind() string

func (ApprovalDecision) Validate

func (e ApprovalDecision) Validate() error

type BatchConfig

type BatchConfig struct {
	// BufferSize is the queue capacity; beyond it Send drops and returns
	// ErrBufferFull. Default 10000.
	BufferSize int
	// MaxBatch is the most records per export request. Default 400.
	MaxBatch int
	// MaxWait is how long a partial batch waits before export. Default 1s.
	MaxWait time.Duration
}

BatchConfig tunes ModeBatch.

type Change

type Change struct {
	Name     string `json:"name"`
	OldValue string `json:"old_value,omitempty"`
	NewValue string `json:"new_value,omitempty"`
}

Change is one attribute's before/after value.

type Client

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

Client ships audit events to an OTLP collector. It is safe for concurrent use. A nil *Client is a valid, disabled client: every method is a no-op, so code can audit unconditionally and leave enabling it to configuration (see FromEnv).

func FromEnv

func FromEnv(ctx context.Context) (*Client, error)

FromEnv builds a Client from GOPHERAGENT_AUDIT_* environment variables. With GOPHERAGENT_AUDIT_ENDPOINT unset it returns a nil *Client and no error — a disabled client whose methods do nothing — so the same code runs with auditing on or off. Where auditing is mandatory, set GOPHERAGENT_AUDIT_REQUIRED=true so a missing or misspelled endpoint fails startup instead of silently disabling the trail.

The client's self-health metrics go to the global OTel MeterProvider, so with telemetry enabled (otelsetup.Setup, before or after) failed and dropped records are visible without extra wiring:

audit, err := auditlog.FromEnv(ctx)
if err != nil { ... }          // set but invalid configuration
defer audit.Close(ctx)
audit.Instrument(loop)

func New

func New(ctx context.Context, cfg Config) (*Client, error)

New validates cfg and connects. The gRPC connection is lazy: a collector that is down surfaces on the first Send, not here.

func (*Client) Close

func (c *Client) Close(ctx context.Context) error

Close drains the batch buffer (ModeBatch) and releases the connection. Send fails with ErrClosed afterwards.

func (*Client) Fingerprint

func (c *Client) Fingerprint(value string) string

Fingerprint returns Hash(HMACKey, value), or "" without a key.

func (*Client) Flush

func (c *Client) Flush(ctx context.Context) error

Flush blocks until every event queued before the call is exported (or its failure reported to OnError). A no-op in ModeBlocking.

func (*Client) Instrument

func (c *Client) Instrument(loop *agent.AgentLoop, opts ...Option) *agent.AgentLoop

Instrument audits an already-built loop in one call: every tool in loop.Tools (ToolMiddleware), the HITL callback (AuditConfirm), the permission policy (AuditPermissions), and hook rejections (EventHandler). opts are passed to each, e.g. WithFailClosed or WithPolicy. Records fall back to Config.DefaultTenantID when the ctx carries no Actor.

Call it last — after ConfirmHITL, Permissions, and the tools are set; ones set afterwards are not audited (a warning names them on the loop's first event). Tools are never double-wrapped, but the callback, policy, and event handler are, so call it once per loop. A nil client changes nothing. Returns loop for chaining.

func (*Client) Send

func (c *Client) Send(ctx context.Context, events ...Event) error

Send validates every event and delivers them per the client's Mode. If any event is invalid, none is sent.

func (*Client) SendSync

func (c *Client) SendSync(ctx context.Context, events ...Event) error

SendSync delivers synchronously regardless of Mode, like ModeBlocking.

type Common

type Common struct {
	// Time of the action; zero means "now" at send time. Encoded once, as the
	// envelope's "time" field.
	Time time.Time `json:"-"`
	// TenantID owns the data the action touched. Required.
	TenantID string `json:"tenant_id"`
	// ActorID is the user (or service principal) that initiated the action.
	ActorID string `json:"actor_id,omitempty"`
	// ImpersonatorID is set when ActorID acted on behalf of someone else.
	ImpersonatorID string `json:"impersonator_id,omitempty"`
	// SourceIPs are the client addresses the request came from.
	SourceIPs []string `json:"source_ips,omitempty"`
	// AppID identifies the calling application.
	AppID string `json:"app_id,omitempty"`
	// SessionID is the agent session (conversation) the action belongs to.
	SessionID string `json:"session_id,omitempty"`
	// Context is free-form, bounded key/value metadata.
	Context map[string]string `json:"context,omitempty"`
}

Common is embedded in every event: who acted, for which tenant, and when.

type Config

type Config struct {
	// Endpoint is the collector address as host:port. Required.
	Endpoint string
	// Protocol is ProtocolGRPC (default) or ProtocolHTTP. HTTP posts to
	// /v1/logs on Endpoint.
	Protocol string

	// Insecure sends in plaintext. Local collectors only.
	Insecure bool
	// TLS is a complete TLS configuration. Mutually exclusive with the
	// file fields below. Nil (and no files) means system roots.
	TLS *tls.Config
	// CAFile verifies the collector; CertFile + KeyFile present a client
	// certificate (mTLS). PEM files.
	CAFile, CertFile, KeyFile string
	// Headers are sent with every export (gRPC metadata or HTTP headers),
	// e.g. an authorization token.
	Headers map[string]string
	// Gzip compresses export payloads.
	Gzip bool
	// Timeout bounds one export attempt; default 10s.
	Timeout time.Duration
	// MaxAttempts bounds retries of a transient export failure; default 3.
	MaxAttempts int

	// DefaultTenantID attributes records made by Instrument when the ctx
	// carries no Actor tenant — what a single-tenant app sets instead of
	// calling WithActor per request.
	DefaultTenantID string

	// HMACKey (at least 16 bytes) enables keyed argument fingerprints
	// (ToolInvocation.ArgsHMAC) and a signature on every record, which Verify
	// checks. Keep it out of the audit store: whoever holds it can forge
	// records. Nil: no fingerprints, records numbered but unsigned.
	HMACKey []byte

	// Mode is ModeBlocking (default) or ModeBatch. See Mode.
	Mode Mode
	// Batch tunes ModeBatch; ignored otherwise.
	Batch BatchConfig
	// OnError receives export failures in ModeBatch, where no caller is
	// waiting for them. Default: log.
	OnError func(ctx context.Context, err error)

	// Meter, when set, records the client's own health:
	// gopheragent.audit.records{kind, result=sent|failed|invalid|dropped} and
	// gopheragent.audit.export.duration. Alert on failed and dropped — a
	// broken audit pipeline is otherwise silent.
	Meter metric.Meter

	// ServiceName (required), ServiceNamespace, ServiceInstanceID, and
	// Environment identify the sender on the OTLP Resource. Restricted to
	// [A-Za-z0-9._/~-] — identifiers, not free text.
	ServiceName       string
	ServiceNamespace  string
	ServiceInstanceID string
	Environment       string
}

Config holds the connection and identity settings for a Client.

type ConfigurationChange

type ConfigurationChange struct {
	Common
	ObjectType string   `json:"object_type"`
	ObjectID   string   `json:"object_id"`
	Changes    []Change `json:"changes"`
	Outcome    Outcome  `json:"outcome"`
}

ConfigurationChange records a change to system or tenant configuration.

func (ConfigurationChange) Kind

func (ConfigurationChange) Kind() string

func (ConfigurationChange) Validate

func (e ConfigurationChange) Validate() error

type Custom

type Custom struct {
	Common
	Name    string         `json:"name"`
	Payload map[string]any `json:"payload,omitempty"`
}

Custom carries an application-specific audit event. Name becomes part of the event identity; Payload must be JSON-serializable.

func (Custom) Kind

func (Custom) Kind() string

func (Custom) Validate

func (e Custom) Validate() error

type DataAccess

type DataAccess struct {
	Common
	ObjectType string   `json:"object_type"`
	ObjectID   string   `json:"object_id"`
	Fields     []string `json:"fields,omitempty"`
	Channel    string   `json:"channel,omitempty"` // e.g. "tool:sql_agent", "api"
}

DataAccess records a read of tenant data.

func (DataAccess) Kind

func (DataAccess) Kind() string

func (DataAccess) Validate

func (e DataAccess) Validate() error

type DataModification

type DataModification struct {
	Common
	ObjectType string   `json:"object_type"`
	ObjectID   string   `json:"object_id"`
	Operation  string   `json:"operation"` // create | update | delete
	Changes    []Change `json:"changes,omitempty"`
	Outcome    Outcome  `json:"outcome"`
}

DataModification records a create, update, or delete of tenant data.

func (DataModification) Kind

func (DataModification) Kind() string

func (DataModification) Validate

func (e DataModification) Validate() error

type Decision

type Decision string

Decision is a human or policy verdict.

const (
	DecisionApproved Decision = "approved"
	DecisionDenied   Decision = "denied"
	DecisionTimedOut Decision = "timed_out"
	DecisionCanceled Decision = "cancelled"
	DecisionAllow    Decision = "allow"
	DecisionDeny     Decision = "deny"
	DecisionConfirm  Decision = "confirm"
)

type Emitter

type Emitter interface {
	Send(ctx context.Context, events ...Event) error
}

Emitter is the narrow interface the agent integrations depend on, so tests and adopters can substitute their own sink.

func Multi

func Multi(emitters ...Emitter) Emitter

Multi fans events out to several emitters in parallel and succeeds when at least one of them does — keep two independent destinations (say the collector and a local JSONLWriter) so one outage doesn't lose the trail. It fails only when every emitter fails.

func MultiAll

func MultiAll(emitters ...Emitter) Emitter

MultiAll is Multi that requires every emitter to succeed.

type Event

type Event interface {
	// Kind is the event's type name, e.g. "ToolInvocation".
	Kind() string
	// Validate reports every constraint violation, joined; each wraps
	// ErrInvalidEvent.
	Validate() error
	// contains filtered or unexported methods
}

Event is implemented by the event types in this package only.

type Fingerprinter

type Fingerprinter interface {
	Fingerprint(value string) string
}

Fingerprinter is implemented by emitters configured with an HMAC key.

type Gap

type Gap struct {
	Stream        string
	After, Before uint64
}

Gap is a run of missing sequence numbers in a stream: After and Before are the records on either side.

type JSONLWriter

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

JSONLWriter writes each event as one JSON line to w — a local audit device for development or as Multi's second destination. Writes are serialized; rotation and fsync policy belong to w.

func NewJSONLWriter

func NewJSONLWriter(w io.Writer) *JSONLWriter

NewJSONLWriter returns a JSONLWriter on w.

func (*JSONLWriter) Send

func (j *JSONLWriter) Send(_ context.Context, events ...Event) error

Send validates every event, then writes one line per event: the same body the OTLP client sends, wrapped with its event name.

type Level

type Level int

Level is how much of a tool call ToolMiddleware records.

const (
	// LevelNone: don't audit the tool (it is left unwrapped).
	LevelNone Level = iota
	// LevelMetadata (default): outcome, duration, error, keyed args fingerprint.
	LevelMetadata
	// LevelRequest: Metadata plus the raw arguments.
	LevelRequest
	// LevelRequestResponse: Request plus the tool's model-facing result text.
	LevelRequestResponse
)

type Mode

type Mode int

Mode selects when Send returns.

const (
	// ModeBlocking (default): Send returns after the collector acknowledged
	// the records. Nothing is buffered; a nil return means written.
	ModeBlocking Mode = iota
	// ModeBatch: Send validates synchronously, then queues; a background
	// worker exports in batches. Higher throughput and no per-event network
	// latency, but a crash loses queued records and a full buffer drops
	// (ErrBufferFull). Call Flush or Close to drain.
	ModeBatch
)

type Option

type Option func(*options)

Option configures the agent integrations.

func WithAllowDecisions

func WithAllowDecisions() Option

WithAllowDecisions makes AuditPermissions record allow verdicts too, not only deny and confirm.

func WithDefaultTenant

func WithDefaultTenant(tenant string) Option

WithDefaultTenant attributes records to tenant when ctx carries no Actor tenant — for single-tenant deployments.

func WithErrorHandler

func WithErrorHandler(fn func(ctx context.Context, err error)) Option

WithErrorHandler receives audit write failures the integration cannot return to a caller. The default logs them.

func WithFailClosed

func WithFailClosed() Option

WithFailClosed makes ToolMiddleware write a "started" record before the tool runs and refuse to run it if that write fails: no audit record, no action. The outcome record follows execution as usual.

func WithLevel

func WithLevel(l Level) Option

WithLevel applies one Level to every tool.

func WithPolicy

func WithPolicy(level func(tools.ToolDescriptor) Level) Option

WithPolicy picks each tool's audit Level once, when the tool is wrapped — the first matching rule of a policy, evaluated at registration, not per call. Arguments and results often hold PII, so raise the level only where the record needs them:

auditlog.WithPolicy(func(d tools.ToolDescriptor) auditlog.Level {
    if d.RequiresConfirmation { return auditlog.LevelRequest }
    return auditlog.LevelMetadata
})

type Outcome

type Outcome string

Outcome is the result of an audited action.

const (
	OutcomeStarted Outcome = "started" // fail-closed pre-execution record
	OutcomeSuccess Outcome = "success"
	OutcomeFailure Outcome = "failure"
)

type PolicyDecision

type PolicyDecision struct {
	Common
	Tool     string   `json:"tool"`
	Decision Decision `json:"decision"` // allow | deny | confirm
	Policy   string   `json:"policy,omitempty"`
}

PolicyDecision records an automated permission-policy verdict.

func (PolicyDecision) Kind

func (PolicyDecision) Kind() string

func (PolicyDecision) Validate

func (e PolicyDecision) Validate() error

type Record

type Record struct {
	Stream    string
	Sequence  uint64
	EventID   string
	EventName string
	Body      string
	Signature string
}

Record is the integrity-relevant view of one stored audit record.

func RecordFromOTLP

func RecordFromOTLP(lr *logspb.LogRecord) Record

RecordFromOTLP extracts a Record from an exported OTLP log record, for verification tooling reading from the audit store.

type SecurityViolation

type SecurityViolation struct {
	Common
	Category string `json:"category"` // e.g. "hook_rejected", "unauthorized"
	Detail   string `json:"detail,omitempty"`
}

SecurityViolation records a blocked request: a rejected prompt, a malicious or unauthorized request.

func (SecurityViolation) Kind

func (SecurityViolation) Kind() string

func (SecurityViolation) Validate

func (e SecurityViolation) Validate() error

type SyncEmitter

type SyncEmitter interface {
	SendSync(ctx context.Context, events ...Event) error
}

SyncEmitter is implemented by emitters that can bypass their buffering. WithFailClosed uses it: a "started" record must be written, not queued, before the tool may run.

type ToolInvocation

type ToolInvocation struct {
	Common
	Tool     string        `json:"tool"`
	CallID   string        `json:"call_id,omitempty"`
	Outcome  Outcome       `json:"outcome"`
	Error    string        `json:"error,omitempty"`
	Duration time.Duration `json:"duration_ns,omitempty"`
	// ArgsHMAC is a keyed fingerprint of the arguments ("hmac-sha256:<hex>",
	// see Hash): it matches a record to a known request without storing the
	// arguments, and without the key it can't be brute-forced back to them.
	// Empty when the client has no HMACKey.
	ArgsHMAC string `json:"args_hmac,omitempty"`
	// Args is the raw argument JSON (LevelRequest and above).
	Args string `json:"args,omitempty"`
	// Result is the tool's model-facing text (LevelRequestResponse).
	Result string `json:"result,omitempty"`
}

ToolInvocation records one tool execution by an agent.

func (ToolInvocation) Kind

func (ToolInvocation) Kind() string

func (ToolInvocation) Validate

func (e ToolInvocation) Validate() error

type VerifyReport

type VerifyReport struct {
	Checked      int
	BadSignature []Record // modified, forged, or signed with another key
	Gaps         []Gap    // deleted records — or a Send that returned an error
	Conflicts    []Record // a sequence number reused by a different event
}

VerifyReport is the result of Verify. OK reports a clean trail.

func Verify

func Verify(key []byte, records []Record) VerifyReport

Verify checks a set of records from the audit store: every signature, and per stream, that sequence numbers are contiguous. Duplicate deliveries of the same event (a retried export) are benign and skipped. Detects modified, forged, and deleted records; cannot detect records removed from the end of a stream, so verify against the latest sequence your monitoring has seen. A gap also appears where Send returned an error — the caller saw that failure, so correlate gaps with export-error metrics.

func (VerifyReport) OK

func (r VerifyReport) OK() bool

OK reports whether no tampering was detected.

Jump to

Keyboard shortcuts

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