audit

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0 Imports: 17 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 writes writgate's audit log (docs/SPEC.md section 6): one JSON object per line, each carrying the hash of the line before it.

An allowed call writes two records: an "intent" before the upstream request is sent and an "outcome" after. A refused call writes one "denied" record. An intent with no outcome means writgate stopped between the two, so the call's result is unknown.

Index

Constants

View Source
const (
	TypeIntent    = "intent"
	TypeOutcome   = "outcome"
	TypeDenied    = "denied"
	TypeRecovered = "recovered"
)

Record types.

View Source
const (
	ResultCompleted = "completed" // a response came back
	ResultNotSent   = "not_sent"  // the request never left writgate
	ResultUnknown   = "unknown"   // the request was sent and no response came back
)

Results of an outcome record. Whether the API accepted the call is told by the HTTP status, not by the result.

View Source
const (
	ResultApplied    = "applied"     // the API has the call's result
	ResultNotApplied = "not_applied" // the API has no trace of the call
)

Results of a recovered record, which settles a call whose result was unknown. ResultUnknown is used again when it still can't be settled.

View Source
const Marker = "[redacted]"

Marker replaces a sensitive value.

View Source
const MaxBody = 16 << 10

MaxBody is the most of a response body a record holds.

View Source
const Version = 1

Version is the record format version, written as "v" in every record. Readers must ignore fields they don't know, so adding a field does not change it; renaming one or changing what a value means does.

Variables

This section is empty.

Functions

func NewCallID

func NewCallID() string

NewCallID returns a UUIDv7: unique, and sortable by creation time.

Types

type Checkpoint

type Checkpoint struct {
	V    int    `json:"v"`
	Time string `json:"time"`
	Seq  uint64 `json:"seq"`
	Hash string `json:"hash"` // hashLine of record Seq
}

A Checkpoint says what the log's newest record was at one moment: "record Seq had this hash at this time". Kept somewhere the log's writer can't rewrite, it catches what the chain alone can't: a log rewritten from some point on with every hash recomputed, or cut short.

type FileSink

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

FileSink appends to a file.

func OpenFile

func OpenFile(path string) (*FileSink, error)

OpenFile opens or creates an audit log file and locks it, so two writgate processes can't interleave records in one log. A final line with no newline is a write that was cut off by a crash; it is removed, so the file always ends on a whole record.

func (*FileSink) Close

func (s *FileSink) Close() error

Close flushes the file to disk and closes it.

func (*FileSink) Last

func (s *FileSink) Last() []byte

Last implements Sink.

func (*FileSink) Write

func (s *FileSink) Write(line []byte, durable bool) error

Write implements Sink. The line and its newline go in one write call.

type Log

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

Log appends records to a sink in order, numbering and chaining them. It is safe for concurrent use.

func New

func New(sink Sink, opts Options) (*Log, error)

New returns a Log that continues from the sink's last record, if any.

func (*Log) Append

func (l *Log) Append(r *Record, durable bool) (seq uint64, err error)

Append numbers, timestamps and chains r, and writes it. With durable set it returns only once the record is safely stored.

Any failure is permanent: after a failed write the state of the file is unknown, so the Log refuses every later Append with the same error.

func (*Log) Close

func (l *Log) Close() error

Close writes a final checkpoint, then flushes and closes the sinks.

func (*Log) Err

func (l *Log) Err() error

Err reports the failure that stopped the Log, or nil.

type Options

type Options struct {
	// Checkpoints is where checkpoints are appended. A failed write stops
	// the Log, like a failed record write.
	Checkpoints Sink
	// OnCheckpoint is also given each checkpoint line, e.g. to print it to
	// stderr for a log collector.
	OnCheckpoint func(line []byte)
	// Every writes a checkpoint after this many records. Zero means 100.
	Every int
	// Interval writes a checkpoint this long after a record that hasn't
	// had one yet. Zero means 60 seconds; negative turns the timer off.
	Interval time.Duration
}

Options configures a Log. The zero value writes no checkpoints.

type Problem

type Problem struct {
	From, To uint64 // record numbers, inclusive
	What     string
	// Checkpoint says the problem was found by a checkpoint, not the chain.
	Checkpoint bool
}

Problem is one sign of tampering or damage, and the records it covers.

func (Problem) String

func (p Problem) String() string

type Record

type Record struct {
	V         int             `json:"v"`
	Seq       uint64          `json:"seq"`                  // 1, 2, 3, ... with no gaps
	Time      string          `json:"time"`                 //
	Type      string          `json:"type"`                 //
	CallID    string          `json:"call_id"`              // shared by a call's intent and outcome
	IntentSeq uint64          `json:"intent_seq,omitempty"` // outcome, recovered: the seq of the intent
	Client    string          `json:"client,omitempty"`     // the MCP client, as "name/version"
	Tool      string          `json:"tool"`                 //
	Arguments json.RawMessage `json:"arguments,omitempty"`  // as the agent sent them, redacted
	Rule      string          `json:"rule,omitempty"`       // the policy rule that decided
	Policy    string          `json:"policy,omitempty"`     // digest of the policy in force
	Request   *Request        `json:"request,omitempty"`    // intent: what will be sent; recovered: the lookup
	Result    string          `json:"result,omitempty"`     // outcome, recovered: one of the Result constants
	Error     string          `json:"error,omitempty"`      // why there is no response, or how the result was settled
	Duration  *int64          `json:"duration_ms,omitempty"`
	Response  *Response       `json:"response,omitempty"` // outcome: what came back
	Redacted  []string        `json:"redacted,omitempty"` // paths of the values replaced in this record
	Prev      string          `json:"prev"`               // "sha256:<hex>" of the previous line, "" on the first
}

Record is one line of the log. Fields are written in this order, and a field that doesn't apply to a record's type is left out.

type Redactor

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

A Redactor removes sensitive values from one call's records. It works two ways: a field whose name is marked sensitive has its value replaced wherever that field appears, and every value replaced that way is then also replaced wherever else it turns up, such as in an API's error message that echoes it back.

func NewRedactor

func NewRedactor(fields map[string]bool, secrets ...string) *Redactor

NewRedactor returns a Redactor for a tool's sensitive field names. secrets are extra values to remove on sight, such as the upstream API key.

func (*Redactor) JSON

func (r *Redactor) JSON(path string, raw []byte) (out json.RawMessage, ok bool)

JSON redacts a JSON document. path names it in the "redacted" list, e.g. "arguments". ok is false when raw isn't one JSON value. Numbers are copied digit for digit; object keys come out sorted.

func (*Redactor) Mark

func (r *Redactor) Mark(path string)

Mark adds a path to the "redacted" list, for a value the caller replaced itself.

func (*Redactor) Response

func (r *Redactor) Response(status int, body []byte, cut bool) *Response

Response builds the response part of an outcome record. cut says the body was already cut short when it was read.

func (*Redactor) TakePaths

func (r *Redactor) TakePaths() []string

TakePaths returns the paths redacted since the last call, for one record's "redacted" list.

func (*Redactor) Text

func (r *Redactor) Text(path, s string) string

Text removes known sensitive values from a string.

type Report

type Report struct {
	Records     int
	Checkpoints int
	// Checkpointed is the seq of the newest checkpoint that matches the
	// log. Records after it are protected by the chain only: removing them
	// from the end leaves no trace.
	Checkpointed uint64
	// Problems are the places where the log is not what was written. An
	// empty list means it is intact.
	Problems []Problem
	// Unknown are the calls whose result isn't recorded: an intent with no
	// outcome, or an outcome saying no response came back, that no
	// recovered record has settled since.
	Unknown []Record
	// CutOff says the last line has no newline: a write was interrupted. It
	// is removed the next time writgate opens the log.
	CutOff bool
}

Report is the result of verifying a log.

func Verify

func Verify(log, checkpoints io.Reader) (*Report, error)

Verify reads a log and, when checkpoints is not nil, its checkpoints. It checks that every record is numbered in order and carries the hash of the line before it, that every checkpoint still matches the record it names, and that every outcome answers a real intent.

The error is for input that can't be read; tampering is reported in the Report.

func (*Report) OK

func (rep *Report) OK() bool

OK reports whether the log is intact.

type Request

type Request struct {
	Method         string `json:"method"`
	URL            string `json:"url"`
	IdempotencyKey string `json:"idempotency_key,omitempty"`
}

Request is the upstream request an intent record announces.

type Response

type Response struct {
	Status    int             `json:"status"`
	Bytes     int             `json:"bytes"`     // size of the body as received
	Truncated bool            `json:"truncated"` // the body written here is cut short
	Body      json.RawMessage `json:"body,omitempty"`
	BodyText  string          `json:"body_text,omitempty"`
}

Response is the upstream response an outcome record reports. The body is in Body when it is JSON that fits, and otherwise in BodyText.

type Sink

type Sink interface {
	// Last returns the last line already in the sink, without its newline,
	// or nil when the sink is empty or can't be read back.
	Last() []byte
	// Write appends one line. With durable set it returns only once the
	// line would survive a crash or power loss.
	Write(line []byte, durable bool) error
	Close() error
}

Sink is where audit lines go.

type WriterSink

type WriterSink struct{ W io.Writer }

WriterSink writes lines to a stream such as stdout, for platforms that collect a process's output (e.g. Cloud Logging). It can't read back what it wrote, so each run starts a new chain.

func (WriterSink) Close

func (WriterSink) Close() error

Close implements Sink.

func (WriterSink) Last

func (WriterSink) Last() []byte

Last implements Sink.

func (WriterSink) Write

func (s WriterSink) Write(line []byte, _ bool) error

Write implements Sink.

Jump to

Keyboard shortcuts

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