audit

package
v0.72.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package audit builds and writes the Spec 107 audit trail: one JSON line per pre-dispatch authorization decision (authz), one per completed tool dispatch (tool_call), and one per terminal login/logout attempt (auth_event). See specs/107-server-edition-sso-hardening/contracts/ audit-line.schema.json for the binding wire schema and audit-line-events.md for the event vocabulary.

This package has no dependency on internal/server or internal/serveredition (dependency direction: audit is a leaf consumed by both, never the other way around) and depends only on internal/security (StripInternalArgs) plus the standard library and gopkg.in/natefinch/lumberjack.v2 (already a module dependency via internal/logs).

Index

Constants

This section is empty.

Variables

View Source
var ErrSanitisationFailed = errors.New("audit: sanitisation failed")

ErrSanitisationFailed is the sentinel a dispatch path wraps when the sanitisation step itself fails (as opposed to a post-dispatch output sanitisation BLOCK, which is a tool_call outcome:blocked and never reaches ErrorClassOf).

Functions

func CanonicalizeArgs

func CanonicalizeArgs(args map[string]interface{}) ([]byte, error)

CanonicalizeArgs strips `_auth_*` keys (FR-015) and serialises the rest per RFC 8785: keys sorted by UTF-16 code unit, arrays in input order, ES6 number formatting, minimal string escaping, no insignificant whitespace.

func HashArgs

func HashArgs(args map[string]interface{}) (hash string, argsBytes int, err error)

HashArgs returns the lowercase-hex SHA-256 of CanonicalizeArgs(args) and its byte length (schema `args_sha256` / `args_bytes`).

func SanitizeLine

func SanitizeLine(raw []byte) ([]byte, bool)

SanitizeLine is the defence-in-depth whole-line pass applied before a sink write: it must be the identity on well-formed builder output (every caller/operator-controlled field was already masked per field) and only fires on a builder bug. Returns the (possibly masked) line and whether any pattern hit.

Types

type Attempt

type Attempt struct {
	RequestID          string
	TransportRequestID string
	ParentID           string
	SessionID          string
	WorkSessionID      string
	Server             string // canonical server name (Spec 105 FR-009)
	Tool               string // raw upstream tool name
	Operation          string // read|write|destructive|unknown
	Surface            string // call_tool_read|call_tool_write|call_tool_destructive|direct|code_execution|rest
	Source             string // mcp|api|internal — from the mount point
	Origin             string // local|socket|remote(reserved)
	ClientName         string
	ClientVersion      string
	ClientIP           string
	Profile            string
	ProfilePin         string
	ArgsSHA256         string // RFC 8785 canonical hash over StripInternalArgs(args), pre-masking
	ArgsBytes          int
	StartedAt          time.Time
}

Attempt is the immutable per-dispatch-attempt record installed in the request context before the first authorization gate runs (data-model.md §5). It never holds arguments, responses, error text or `_auth_*` values: there is no field through which they could arrive, which is the structural half of FR-015's "never raw args/response/error" invariant.

type AuthEventInput

type AuthEventInput struct {
	Ts        time.Time
	RequestID string
	Origin    string
	Source    string
	Surface   string // login|logout
	Reason    string
	Caller    Caller
	ClientIP  string
	Flags     []string
}

AuthEventInput builds one `auth_event` line: one per terminal login attempt the proxy observes, one per logout.

type AuthzInput

type AuthzInput struct {
	Ts        time.Time
	Attempt   Attempt
	Caller    Caller
	Decision  string // allow|deny
	Reason    string // "none" iff allow; else a pre-dispatch gate reason
	Disclosed *bool  // required iff Decision == deny
}

AuthzInput builds one `authz` line: exactly one per pre-dispatch decision.

type Caller

type Caller struct {
	Kind        string // api_key|socket|stdio|anonymous|agent_token|session_user|session_admin|internal
	UserID      string
	UserEmail   string
	EmailHash   string // auth_event only, verified email, no user record yet
	Role        string // admin|user
	Provider    string // google|github|microsoft|oidc
	TokenName   string
	TokenPrefix string
	ProfilePin  string
}

Caller is the audit line's `caller` object: the identity derived from auth.AuthContext plus the credential kind (contracts/audit-line-events.md "caller.kind derivation"). Fields not applicable to a given kind must be left zero — the per-kind rules are enforced by the line builders, and the schema's identity `allOf` blocks are the binding source of truth.

type Client

type Client struct {
	Name    string
	Version string
	IP      string
}

Client is the audit line's optional `client` object: caller-asserted identification, always untrusted.

type ErrorClass

type ErrorClass string

ErrorClass is one member of the schema's `error_class` enum.

const (
	ErrorClassUpstreamError       ErrorClass = "upstream_error"
	ErrorClassUpstreamTimeout     ErrorClass = "upstream_timeout"
	ErrorClassUpstreamUnavailable ErrorClass = "upstream_unavailable"
	ErrorClassValidation          ErrorClass = "validation"
	ErrorClassSanitisation        ErrorClass = "sanitisation"
	ErrorClassInternal            ErrorClass = "internal"
	ErrorClassCancelled           ErrorClass = "cancelled"
)

func ErrorClassOf

func ErrorClassOf(err error) ErrorClass

ErrorClassOf classifies err. Wrapped chains are unwrapped with errors.Is / errors.As; anything unrecognised (including nil) is `internal`.

type Line

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

Line is a single, already-validated audit line.

func NewAuthEvent

func NewAuthEvent(in AuthEventInput) (Line, error)

NewAuthEvent builds and structurally validates an `auth_event` line.

func NewAuthz

func NewAuthz(in AuthzInput) (Line, error)

NewAuthz builds and structurally validates an `authz` line.

func NewToolCall

func NewToolCall(in ToolCallInput) (Line, error)

NewToolCall builds and structurally validates a `tool_call` line.

func (Line) JSON

func (l Line) JSON() ([]byte, error)

JSON serialises the line. encoding/json sorts map[string]interface{} keys, so repeated calls on the same Line are byte-stable.

type Option

type Option func(*sinkOptions)

Option configures a Sink at construction.

func WithClock

func WithClock(now func() time.Time) Option

WithClock overrides the clock used for the write-failure log rate limit (tests only; production sinks use time.Now).

func WithFailureLogger

func WithFailureLogger(fn func(err error)) Option

WithFailureLogger installs a callback invoked at most once per minute when a write fails, receiving the most recent error.

type Sink

type Sink interface {
	Write(line []byte) error
	WriteFailures() uint64
	SanitizerHits() uint64
	Close() error
}

Sink is the audit line writer: mutex-guarded and synchronous (the caller blocks until the line is on disk/stdout), with an always-on write-failure counter (mirrored to metrics, surfaced by doctor — wiring is T109, not this package) and an always-on defence-in-depth sanitizer-hit counter (contracts/audit-line-events.md "Redaction (FR-015)": Write runs every line through SanitizeLine before it reaches the underlying writer, and a hit — which can only happen on a builder bug, since every well-formed constructor output is untouched by the pass — is counted here).

func NewFileSink

func NewFileSink(path string, maxSizeMB, maxBackups, maxAgeDays int, compress bool, opts ...Option) (Sink, error)

NewFileSink opens (creating if absent) an append-only rotating file at path. It probes writability at construction time — lumberjack itself opens lazily, so a naive wrapper would only fail on the first Write — and returns a non-nil error (never a partially-usable Sink) when the path cannot be opened for append.

func NewStdoutSink

func NewStdoutSink(w io.Writer, opts ...Option) Sink

NewStdoutSink writes raw JSON lines straight to w (one call per line, no zap core, no ANSI, no encoder prefix) — the stdio-transport rule of FR-014: stdout must stay pure JSON-RPC on that transport, so this sink is never installed there.

type ToolCallInput

type ToolCallInput struct {
	Ts            time.Time
	Attempt       Attempt
	Caller        Caller
	Outcome       string // success|error|blocked|rejected
	Reason        string // required iff blocked/rejected; forbidden otherwise
	ErrorClass    string // required iff error; forbidden otherwise
	DurationMs    int
	RequestBytes  *int
	ResponseBytes *int
}

ToolCallInput builds one `tool_call` line: exactly one per `authz allow`, written at completion.

Jump to

Keyboard shortcuts

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