audit

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: AGPL-3.0 Imports: 14 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 is the append-only audit log of spec section 12.4.

Two properties are structural here rather than conventional.

  1. **A row is never updated and never deleted.** The persistence interface this package writes through offers exactly one method, `AppendAudit`. There is no Update and no Delete to call, so no migration and no handler can rewrite history by accident; a reviewer checks the interface rather than every caller.

  2. **Redaction happens on the way in, not by remembering to.** Every payload passes through the redactor of redact.go before it is marshalled. A caller cannot opt out, and a payload carrying message text, a token, a Google cookie, an enrollment code, an authorization code, a Google account address or attachment bytes is refused rather than stored (section 12.2).

Index

Constants

This section is empty.

Variables

View Source
var ErrNoSource = errors.New("audit: source is required and is never the empty string (spec 12.3)")

ErrNoSource is the refusal for an event with an empty client source.

View Source
var GoogleCookieNames = []string{
	"SID", "HSID", "OSID", "SSID", "APISID", "SAPISID", "__Secure-1PSIDTS",
}

GoogleCookieNames are the seven Google account cookies of section 3.2. They are exported so that a log scanner and a test can enumerate the same list this redactor refuses.

Functions

This section is empty.

Types

type AccountRule

type AccountRule int

AccountRule says whether a kind must, must not, or may carry an account_id.

const (
	// AccountRequired is an account-shaped kind. Section 12.4: every audit
	// row carries account_id where the event belongs to an account, which is
	// how "what happened to this account" stays answerable after the account
	// is removed (section 4.7). The writer refuses one of these without an
	// account.
	AccountRequired AccountRule = iota
	// AccountForbidden is a server-wide kind: OAuth, settings, backup. The
	// column is NULL, and the writer refuses an account_id on one.
	AccountForbidden
	// AccountOptional is the one shape that is genuinely both.
	AccountOptional
)

func Rule

func Rule(k Kind) (AccountRule, bool)

Rule reports the account rule for a kind.

type Appender

type Appender interface {
	AppendAudit(ctx context.Context, row Row) error
}

Appender is the persistence this package writes through, and the whole interface it has.

It offers no Update and no Delete, and that is the point rather than an omission: section 12.4 says an audit row is never rewritten, by a migration or by anything else. A rule stated in prose is checked by reading every caller; a rule stated as a missing method is checked by reading one interface. The store implements this against `audit_events`.

type Event

type Event struct {
	// Kind must be one of the declared kinds.
	Kind Kind
	// AccountID is the acct_ ID, empty for a server-wide event. Section
	// 12.4: every row carries it where the event belongs to an account, so
	// "what happened to this account" stays answerable after the account is
	// removed.
	AccountID string
	// AuthorizationID is the authorization the call was made under, if any.
	AuthorizationID string
	// TargetType and TargetID name what the event was about.
	TargetType string
	TargetID   string
	// Result is ok, refused or failed.
	Result Result
	// Source is the resolved client source of section 12.3, computed
	// elsewhere and never empty: it is the field every per-source limit and
	// every "who did this" question is answered from.
	Source string
	// Payload carries IDs, counts, codes and outcomes. It is redacted on the
	// way in, and a payload carrying anything from section 12.2's list is
	// refused.
	Payload map[string]any
}

Event is what a caller hands the writer.

type FieldsAppender

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

FieldsAppender adapts this package's Event API to the `(kind, fields)` shape `internal/accounts` and `internal/authz` append through.

Those two packages deliberately do not import this one: they declare a one-method Auditor interface so they can be reasoned about, and tested, without the audit store. Something has to join the two, and until this existed nothing did -- `serve` built its supervisor with a nil Auditor, so **`account.paired`, `account.resumed`, `account.signed_out` and `account.state_changed` were written by every test that injected a recorder and by no running server**. A Slice 3 review found the shipped binary's `audit_events` had no `account.*` kind in it at all.

The adapter is thin on purpose. It does two things the Event API needs and the field map does not carry:

  • it lifts `account_id` out of the payload into the column, because section 12.4's "every audit row carries account_id" is a column and not a JSON key, and `--account-id` filters on the column;
  • it supplies the client source, which the supervisor does not know: a pairing is driven by a REST call but completed on a background goroutine minutes later, so the source recorded is the server's own.

Everything else -- the declared-kind check, the account rule, redaction -- is the Writer's, which is the point of routing through it rather than writing rows directly.

func NewFieldsAppender

func NewFieldsAppender(w *Writer, source string) *FieldsAppender

NewFieldsAppender builds an appender over a writer. `source` is the client source recorded on every row it writes; it is never empty, because the Writer refuses a row without one (section 12.3).

func (*FieldsAppender) Append

func (a *FieldsAppender) Append(ctx context.Context, kind string, fields map[string]any) error

Append writes one row. A nil appender, or one over a nil writer, does nothing and reports no error: that is the same "simply does not audit" contract the supervisor's nil Auditor has.

type Kind

type Kind string

Kind is an audit event kind. They are constants so that a typo is a compile error rather than a row nobody will ever find with `--kind`.

const (
	KindAccountPaired       Kind = "account.paired"
	KindAccountResumed      Kind = "account.resumed"
	KindAccountSignedOut    Kind = "account.signed_out"
	KindAccountRemoved      Kind = "account.removed"
	KindAccountLabelChanged Kind = "account.label_changed"
	KindAccountPairFailed   Kind = "account.pair_failed"
	KindAccountStateChanged Kind = "account.state_changed"
)

Account lifecycle and pairing (section 12.4).

const (
	KindAuthAdminSessionMinted    Kind = "auth.admin_session_minted"
	KindAuthAdminSessionNarrowed  Kind = "auth.admin_session_narrowed"
	KindAuthAdminSessionRefreshed Kind = "auth.admin_session_refreshed"
	KindAuthAdminSecretFailed     Kind = "auth.admin_secret_failed"
	KindAuthRefreshTokenReused    Kind = "auth.refresh_token_reused"
)

Admin authentication (section 12.4). None of these ever carries the presented secret; `auth.admin_secret_failed` carries the source and the resulting cooldown state and nothing else.

const (
	KindOperationSend           Kind = "operation.send"
	KindOperationSendMedia      Kind = "operation.send_media"
	KindOperationDeleteMessage  Kind = "operation.delete_message"
	KindOperationAddReaction    Kind = "operation.add_reaction"
	KindOperationRemoveReaction Kind = "operation.remove_reaction"
	KindOperationMarkRead       Kind = "operation.mark_read"
	KindOperationArchive        Kind = "operation.archive"
	KindOperationUnarchive      Kind = "operation.unarchive"
	KindOperationDeleteConv     Kind = "operation.delete_conversation"
	KindOperationStartConv      Kind = "operation.start_conversation"
	KindOperationTyping         Kind = "operation.typing"
	KindOperationCrashRecovered Kind = "operation.crash_recovered"
)

Write operations and their outcomes (section 12.4: "every write operation and its outcome"). The outcome is the Event's Result — ok, refused or failed — so one kind per operation covers both halves, and a listing filtered by `kind_prefix=operation.` returns the whole write history of an account.

const (
	KindSettingsChanged     Kind = "settings.changed"
	KindAdminBackup         Kind = "admin.backup"
	KindAdminBackupPruned   Kind = "admin.backup_pruned"
	KindSecurityUnsafeTrace Kind = "security.unsafe_trace_enabled"
)

Settings, backup and the one unsafe switch.

const (
	KindEnrollmentCreated  Kind = "enrollment.created"
	KindEnrollmentConsumed Kind = "enrollment.consumed"
	KindEnrollmentExpired  Kind = "enrollment.expired"
	KindEnrollmentRevoked  Kind = "enrollment.revoked"

	KindAuthorizationCreated  Kind = "authorization.created"
	KindAuthorizationApproved Kind = "authorization.approved"
	KindAuthorizationDenied   Kind = "authorization.denied"
	KindAuthorizationExpired  Kind = "authorization.expired"
	KindAuthorizationRevoked  Kind = "authorization.revoked"

	KindClientRevoked Kind = "client.revoked"
)

Enrollment, authorization and clients (section 12.4; Slice 3 writes these).

const (
	KindMessageStatusOutOfOrder Kind = "message.status_out_of_order"
)

Ingestion.

func Kinds

func Kinds() []Kind

Kinds returns every declared kind.

type MemoryAppender

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

MemoryAppender is an in-memory Appender for tests. Like the real one it can only append.

func NewMemoryAppender

func NewMemoryAppender() *MemoryAppender

NewMemoryAppender builds an empty in-memory appender.

func (*MemoryAppender) AppendAudit

func (a *MemoryAppender) AppendAudit(_ context.Context, row Row) error

func (*MemoryAppender) Rows

func (a *MemoryAppender) Rows() []Row

Rows returns a copy of everything appended so far.

type RedactionError

type RedactionError struct {
	// Class is the forbidden class, e.g. "message text" or "google cookie".
	Class string
	// Path is the JSON path within the payload, e.g. "attempt.access_token".
	Path string
}

RedactionError is a payload refused on the way in. It names the class of secret and the path it was found at, and it never names the value: an error string that quotes the token it is refusing to store has stored the token in a log instead.

func (*RedactionError) Error

func (e *RedactionError) Error() string

type Redactor

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

Redactor scrubs and refuses payloads. Use NewRedactor; the zero value is not usable.

func NewRedactor

func NewRedactor() *Redactor

NewRedactor returns a redactor using this process's salt.

func (*Redactor) Payload

func (r *Redactor) Payload(p map[string]any) (map[string]any, error)

Payload redacts one payload, returning the value that will be marshalled into `payload_json`.

It is applied by the Writer to every event. There is no path that stores a payload without it, which is the difference between redaction as a property and redaction as a rule callers are asked to remember.

func (*Redactor) PhoneRef

func (r *Redactor) PhoneRef(number string) map[string]any

PhoneRef is what an audit payload carries in place of a phone number: a stable salted hash so two rows about the same number can be correlated, and the last four digits so an owner can recognise it (section 12.2).

type Result

type Result string

Result is the outcome column of section 4.2's audit_events.

const (
	ResultOK      Result = "ok"
	ResultRefused Result = "refused"
	ResultFailed  Result = "failed"
)

type Row

type Row struct {
	ID              string
	Kind            string
	AccountID       *string
	AuthorizationID *string
	TargetType      *string
	TargetID        *string
	Result          string
	Source          string
	PayloadJSON     string
	CreatedAtMs     int64
}

Row is one row of section 4.2's `audit_events`, already redacted and ready to insert. The nullable columns are pointers so that "no account" is NULL and not the empty string: `WHERE account_id = ”` finding rows would be a quiet lie about which events belong to an account.

type Writer

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

Writer appends audit rows. It exposes exactly one method, Append: there is no update and no delete on the type, and none on the interface underneath it.

func NewWriter

func NewWriter(a Appender, c clock.Clock) *Writer

NewWriter builds a writer over an appender and a clock.

func (*Writer) Append

func (w *Writer) Append(ctx context.Context, e Event) error

Append validates, redacts and stores one event.

It refuses, and stores nothing, when:

  • the kind is not declared (a typo must not become an unfindable row);
  • an account-shaped kind carries no account_id, or a server-wide kind carries one;
  • the source is empty;
  • the result is not ok, refused or failed;
  • the payload carries anything from section 12.2's list.

Jump to

Keyboard shortcuts

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