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
- Variables
- func Canonical(raw []byte) []byte
- func Hash(raw []byte) string
- func NewID() string
- func TokensEst(parts ...[]byte) int
- func Truncate(raw []byte, max int) ([]byte, bool)
- type Call
- type CallFilter
- type Options
- type Redactor
- type RuleStat
- type Session
- type SessionFilter
- type Stats
- type Store
- func (s *Store) Close(ctx context.Context) error
- func (s *Store) Dropped() int64
- func (s *Store) EndSession(id string, at time.Time)
- func (s *Store) GetCall(ctx context.Context, id string) (*Call, error)
- func (s *Store) GetSession(ctx context.Context, id string) (*Session, error)
- func (s *Store) ListCalls(ctx context.Context, f CallFilter) ([]*Call, error)
- func (s *Store) ListSessions(ctx context.Context, f SessionFilter) ([]*Session, error)
- func (s *Store) Prune(ctx context.Context, cutoff time.Time) (int64, error)
- func (s *Store) RecordCall(c *Call)
- func (s *Store) RuleStats(ctx context.Context, since time.Time, sessionID string) ([]*RuleStat, error)
- func (s *Store) SchemaVersion(ctx context.Context) (string, error)
- func (s *Store) StartSession(ctx context.Context, sess *Session) error
- func (s *Store) Stats(ctx context.Context, since time.Time) (*Stats, error)
- func (s *Store) ToolStats(ctx context.Context, since time.Time, sessionID string) ([]*ToolStat, error)
- type ToolStat
Constants ¶
const Placeholder = "[REDACTED]"
Placeholder replaces anything a redaction pattern matched.
Variables ¶
var ErrNotFound = errors.New("not found")
ErrNotFound is returned when a session or call id does not resolve.
Functions ¶
func Canonical ¶
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 ¶
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.
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.
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 ¶
NewRedactor returns a Redactor for the given patterns. A Redactor with no patterns passes documents through unchanged.
func (*Redactor) Redact ¶
Redact rewrites a JSON document. Input that does not parse as JSON is treated as plain text and still redacted.
func (*Redactor) RedactString ¶
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.
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 (*Store) Close ¶
Close flushes pending writes and closes the database. It waits at most until ctx is done for the queue to drain.
func (*Store) EndSession ¶
EndSession stamps a session as finished. Best effort, like every other write on the hot path.
func (*Store) GetSession ¶
GetSession resolves a session by full id or by unique prefix, which is what makes "agentgate show 01JD" work from a terminal.
func (*Store) ListSessions ¶
ListSessions returns sessions newest first, with call and denial counts.
func (*Store) RecordCall ¶
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 ¶
SchemaVersion returns the newest migration applied to the database.
func (*Store) StartSession ¶
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.
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.