audit

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: GPL-3.0 Imports: 23 Imported by: 0 modules, 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 persists sessions and tool calls in a local SQLite database.

Writes are asynchronous and best effort by design: a slow or broken audit store must never delay or fail a tool call. Records that cannot be queued are counted and logged, never retried in the request path.

Index

Constants

View Source
const Placeholder = "[REDACTED]"

Placeholder replaces anything a redaction pattern matched.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned when a session or call id does not resolve.

Functions

func Canonical

func Canonical(raw []byte) []byte

Canonical re-encodes a JSON document with object keys sorted and no insignificant whitespace, so that two structurally equal documents always produce the same bytes and therefore the same hash.

func Hash

func Hash(raw []byte) string

Hash returns the sha256 of the canonical form of raw, hex encoded. An empty document hashes to the empty string so that "no result" is distinguishable from "a result that happened to be empty".

func NewID

func NewID() string

NewID returns a lexicographically sortable ULID, used for session and call identifiers. Sorting by id therefore sorts by time.

func TokensEst

func TokensEst(parts ...[]byte) int

TokensEst is the rough token count agentgate reports for budgets and the UI: characters divided by four, the usual back-of-the-envelope for English text and JSON.

func Truncate

func Truncate(raw []byte, max int) ([]byte, bool)

Truncate caps a document at max bytes. It reports whether it had to cut, and keeps the output valid JSON by wrapping the cut text in an object rather than slicing the document in half.

Types

type Call

type Call struct {
	ID         string          `json:"id"`
	SessionID  string          `json:"session_id"`
	TS         time.Time       `json:"ts"`
	Upstream   string          `json:"upstream"`
	Tool       string          `json:"tool"`
	Args       json.RawMessage `json:"args,omitempty"`
	ArgsHash   string          `json:"args_hash,omitempty"`
	Decision   policy.Action   `json:"decision"`
	RuleID     string          `json:"rule_id,omitempty"`
	Reason     string          `json:"reason,omitempty"`
	Result     json.RawMessage `json:"result,omitempty"`
	ResultHash string          `json:"result_hash,omitempty"`
	IsError    bool            `json:"is_error"`
	DurationMS int64           `json:"duration_ms"`
	TokensEst  int             `json:"tokens_est"`
	// ResultTruncated reports that the stored result was capped at the
	// configured size.
	ResultTruncated bool `json:"result_truncated,omitempty"`
	// Error carries a transport level failure (a timeout, a dead upstream).
	Error string `json:"error,omitempty"`
	// Shadow reports that the decision was recorded but not applied: the
	// policy was in shadow mode and the call was forwarded anyway.
	Shadow bool `json:"shadow,omitempty"`
}

Call is one tools/call request and its outcome.

func (*Call) Blocked

func (c *Call) Blocked() bool

Blocked reports whether the call was actually stopped: a deny that was applied, as opposed to one that shadow mode only wrote down.

type CallFilter

type CallFilter struct {
	SessionID string
	// Decision keeps only calls with this decision. Empty means all.
	Decision policy.Action
	// Tool keeps only calls whose tool name contains this substring.
	Tool string
	// AfterID keeps only calls whose id sorts after this one. Ids are ULIDs,
	// so this is "everything newer than the last thing I saw" — what tail uses.
	AfterID string
	// Since keeps only calls made at or after this time.
	Since time.Time
	// RuleID keeps only calls decided by this rule id.
	RuleID string
	Limit  int
}

CallFilter narrows a call listing.

type Options

type Options struct {
	// Path is the database file. The parent directory is created if missing.
	Path string
	// Redactor is applied to arguments and results before they are stored.
	Redactor *Redactor
	// MaxResultBytes caps a stored result. Zero means unlimited.
	MaxResultBytes int
	// Retention deletes sessions older than this on Open. Zero keeps forever.
	Retention time.Duration
	Logger    *slog.Logger
	// ReadOnly opens an existing database without running migrations or the
	// retention job; used by the CLI's reporting commands.
	ReadOnly bool
}

Options configure a Store.

type Redactor

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

Redactor applies the configured patterns to a JSON document before it is written to the audit store.

Patterns are applied in two places, which is what makes a single pattern like

(?i)(api[_-]?key|secret|token|password)\s*[:=]\s*\S+

do the obvious thing in both of these documents:

{"api_key": "sk-live-1234"}          -> {"api_key": "[REDACTED]"}
{"command": "curl -H token=abc123"}  -> {"command": "curl -H [REDACTED]"}

For the first, the pattern is tested against a synthetic "key: value" probe for every object member; a hit replaces the whole value. For the second, the pattern is applied to the string itself and only the match is replaced. Object keys are never rewritten, so the result stays readable and stays valid JSON — which a plain regex over the serialized document could not promise.

func NewRedactor

func NewRedactor(patterns []*regexp.Regexp) *Redactor

NewRedactor returns a Redactor for the given patterns. A Redactor with no patterns passes documents through unchanged.

func (*Redactor) Enabled

func (r *Redactor) Enabled() bool

Enabled reports whether any pattern is configured.

func (*Redactor) Redact

func (r *Redactor) Redact(raw []byte) []byte

Redact rewrites a JSON document. Input that does not parse as JSON is treated as plain text and still redacted.

func (*Redactor) RedactString

func (r *Redactor) RedactString(s string) string

RedactString applies the patterns to a plain string, replacing each match.

type RuleStat

type RuleStat struct {
	RuleID   string        `json:"rule_id"`
	Decision policy.Action `json:"decision"`
	Calls    int           `json:"calls"`
}

RuleStat counts how often a rule decided something.

type Session

type Session struct {
	ID                  string     `json:"id"`
	StartedAt           time.Time  `json:"started_at"`
	EndedAt             *time.Time `json:"ended_at,omitempty"`
	HostName            string     `json:"host_name,omitempty"`
	HostVersion         string     `json:"host_version,omitempty"`
	DownstreamTransport string     `json:"downstream_transport,omitempty"`

	// Calls and Denied are filled in by the listing queries, not stored.
	Calls  int `json:"calls"`
	Denied int `json:"denied"`
}

Session is one downstream connection.

func (*Session) Duration

func (s *Session) Duration() time.Duration

Duration reports how long the session lasted, or how long it has been running.

type SessionFilter

type SessionFilter struct {
	// Since keeps sessions started at or after this time. Zero means all.
	Since time.Time
	// Limit caps the number of rows. Zero means 200.
	Limit int
}

SessionFilter narrows a session listing.

type Stats

type Stats struct {
	Sessions  int `json:"sessions"`
	Calls     int `json:"calls"`
	Denied    int `json:"denied"`
	Shadowed  int `json:"shadowed"`
	Honeypots int `json:"honeypots"`
	Errors    int `json:"errors"`
	Tokens    int `json:"tokens_est"`
}

Stats is the headline the web UI shows above the session list.

type Store

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

Store is the audit database.

func Open

func Open(ctx context.Context, opts Options) (*Store, error)

Open opens (and if needed creates and migrates) the audit database.

func (*Store) Close

func (s *Store) Close(ctx context.Context) error

Close flushes pending writes and closes the database. It waits at most until ctx is done for the queue to drain.

func (*Store) Dropped

func (s *Store) Dropped() int64

Dropped reports how many records were dropped because the queue was full.

func (*Store) EndSession

func (s *Store) EndSession(id string, at time.Time)

EndSession stamps a session as finished. Best effort, like every other write on the hot path.

func (*Store) GetCall

func (s *Store) GetCall(ctx context.Context, id string) (*Call, error)

GetCall looks up a single call by id.

func (*Store) GetSession

func (s *Store) GetSession(ctx context.Context, id string) (*Session, error)

GetSession resolves a session by full id or by unique prefix, which is what makes "agentgate show 01JD" work from a terminal.

func (*Store) ListCalls

func (s *Store) ListCalls(ctx context.Context, f CallFilter) ([]*Call, error)

ListCalls returns the calls of a session in the order they were made.

func (*Store) ListSessions

func (s *Store) ListSessions(ctx context.Context, f SessionFilter) ([]*Session, error)

ListSessions returns sessions newest first, with call and denial counts.

func (*Store) Prune

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

Prune deletes every session that started before cutoff, and its calls.

func (*Store) RecordCall

func (s *Store) RecordCall(c *Call)

RecordCall queues a call for storage. Arguments and results are redacted and hashed on the caller's goroutine so that the record is a snapshot, then the insert happens in the background.

func (*Store) RuleStats

func (s *Store) RuleStats(ctx context.Context, since time.Time, sessionID string) ([]*RuleStat, error)

RuleStats lists the rules that fired since a time, most active first.

func (*Store) SchemaVersion

func (s *Store) SchemaVersion(ctx context.Context) (string, error)

SchemaVersion returns the newest migration applied to the database.

func (*Store) StartSession

func (s *Store) StartSession(ctx context.Context, sess *Session) error

StartSession records the beginning of a downstream connection. It is synchronous: everything else in the session references this row, so it has to exist before the first call is written.

func (*Store) Stats

func (s *Store) Stats(ctx context.Context, since time.Time) (*Stats, error)

Stats aggregates the database, or the part of it since a time.

func (*Store) ToolStats

func (s *Store) ToolStats(ctx context.Context, since time.Time, sessionID string) ([]*ToolStat, error)

ToolStats breaks the calls since a time down by tool, busiest first.

type ToolStat

type ToolStat struct {
	Tool      string    `json:"tool"`
	Upstream  string    `json:"upstream"`
	Calls     int       `json:"calls"`
	Allowed   int       `json:"allowed"`
	Denied    int       `json:"denied"`
	Asked     int       `json:"asked"`
	Errors    int       `json:"errors"`
	AvgMS     float64   `json:"avg_ms"`
	Tokens    int       `json:"tokens_est"`
	LastRule  string    `json:"last_rule,omitempty"`
	FirstSeen time.Time `json:"first_seen"`
	LastSeen  time.Time `json:"last_seen"`
}

ToolStat is one row of the per-tool breakdown.

Jump to

Keyboard shortcuts

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