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 CatalogEntry
- type ChainProblem
- type Link
- type Options
- type Redactor
- type RuleStat
- type Session
- type SessionFilter
- type Stats
- type Store
- func (s *Store) Catalog(ctx context.Context, hash string) (json.RawMessage, error)
- 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) Head(ctx context.Context) (Link, error)
- func (s *Store) LatestCatalog(ctx context.Context) (json.RawMessage, 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) PrunedAt(ctx context.Context) (time.Time, bool, error)
- func (s *Store) RecordCall(c *Call)
- func (s *Store) RuleStats(ctx context.Context, since time.Time, sessionID string) ([]*RuleStat, error)
- func (s *Store) SaveCatalog(raw []byte) string
- 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)
- func (s *Store) Verify(ctx context.Context, expect *Link) (*VerifyReport, error)
- type ToolStat
- type VerifyReport
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"`
// Labels are the labels the session earned with this call.
Labels []string `json:"labels,omitempty"`
// CatalogHash names the tool catalog in force when the call was made.
CatalogHash string `json:"catalog_hash,omitempty"`
// Seq, PrevHash and RowHash are the call's link in the hash chain. They
// are assigned when the row is written; Seq is zero for rows written
// before the chain existed.
Seq int64 `json:"seq,omitempty"`
PrevHash string `json:"prev_hash,omitempty"`
RowHash string `json:"row_hash,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
// SeqAfter keeps only calls recorded after this link of the hash chain,
// in the order they were recorded. It is what a live view follows: a
// slow call that started early is still picked up when it finishes.
SeqAfter *int64
// Newest returns the most recent calls first.
Newest bool
Limit int
}
CallFilter narrows a call listing.
type CatalogEntry ¶ added in v0.4.0
type CatalogEntry struct {
Upstream string `json:"upstream"`
Exposed string `json:"exposed"`
Tool json.RawMessage `json:"tool"`
}
CatalogEntry is one tool of a catalog snapshot: the definition exactly as the upstream server sent it, and the name agentgate exposed it under.
type ChainProblem ¶ added in v0.4.0
type ChainProblem struct {
Seq int64 `json:"seq"`
CallID string `json:"call_id,omitempty"`
What string `json:"what"`
}
ChainProblem is one place where the chain does not hold.
type Link ¶ added in v0.4.0
Link identifies one position in the chain.
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"`
// CatalogHash names the tool catalog the session started with; see
// Store.Catalog.
CatalogHash string `json:"catalog_hash,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"`
// Canaries counts calls stopped for carrying a canary out.
Canaries int `json:"canaries"`
// Quarantined counts calls to tools held back by pinning.
Quarantined int `json:"quarantined"`
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) LatestCatalog ¶ added in v0.4.0
LatestCatalog returns the tool catalog recorded most recently, which is the best offline answer to "what tools do the servers offer".
func (*Store) ListSessions ¶
ListSessions returns sessions newest first, with call and denial counts.
func (*Store) Prune ¶
Prune applies the retention period: it deletes the calls made before cutoff and then every session that started before cutoff and has no calls left. It returns the number of sessions deleted.
Calls leave the hash chain from the front only. A call that is still within the retention period keeps every later link, even one that is older, and the last deleted link becomes the chain's anchor so that what remains still verifies.
func (*Store) PrunedAt ¶ added in v0.4.0
PrunedAt reports when retention last cut the chain, if it has.
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) SaveCatalog ¶ added in v0.4.0
SaveCatalog stores a tool catalog under its hash, once, and returns the hash. It is asynchronous and best effort like every other write; the hash is computed up front so the caller can reference the catalog at once.
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.
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.
type VerifyReport ¶ added in v0.4.0
type VerifyReport struct {
// Checked is the number of chained calls verified.
Checked int64 `json:"checked"`
// Legacy counts calls written before the chain existed. They cannot be
// verified and are not part of it.
Legacy int64 `json:"legacy"`
// Anchor is where retention cut the chain, if it has.
Anchor *Link `json:"anchor,omitempty"`
// Head is the newest link.
Head Link `json:"head"`
// Problems lists every break found. Empty means the chain holds.
Problems []ChainProblem `json:"problems,omitempty"`
// AnchorChecked reports that an anchor given to Verify was found intact.
AnchorChecked bool `json:"anchor_checked,omitempty"`
}
VerifyReport is the outcome of walking the chain.
func (*VerifyReport) OK ¶ added in v0.4.0
func (r *VerifyReport) OK() bool
OK reports whether the chain verified.