audit

package
v0.7.13-dev.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package audit provides the append-only audit log: a code-registered action catalog (so docs and events cannot drift) and a writer that lands every event in the partitioned audit_events table.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Register

func Register(a Action) bool

Register adds an action to the catalog at start-up: an extension's own actions (pkg/extension.RegisterAuditAction). It reports false, and adds nothing, when the action is already in the catalog — an extension can never take over a core action.

func Registered

func Registered(a Action) bool

Registered reports whether a is in the catalog. The writer refuses unregistered actions so ad-hoc strings can't leak into the log.

Types

type Action

type Action string

Action identifies an auditable action. Every mutating API call, auth event, and state-machine transition writes exactly one.

const (
	// Auth & account. Nothing writes user.register, user.login_failed or
	// user.totp_enabled (the server keeps no credentials of its own); they
	// are catalogued because audit rows may carry them and the log is
	// queried by action.
	ActionUserRegister      Action = "user.register"
	ActionUserLogin         Action = "user.login"
	ActionUserLoginFailed   Action = "user.login_failed"
	ActionUserLogout        Action = "user.logout"
	ActionUserEmailVerified Action = "user.email_verified"
	ActionUserUpdate        Action = "user.update"
	ActionUserTOTPEnabled   Action = "user.totp_enabled"
	// Trusted devices: a browser remembered after it answered the second
	// factor, and the removal of one. A second credential class gets its own
	// audit trail, because "signed in" and "signed in without being asked for
	// the second factor" are different facts and an investigator needs to
	// tell them apart. The sign-in row itself carries the skip in its detail.
	ActionTrustedDeviceAdd    Action = "user.trusted_device_add"
	ActionTrustedDeviceRevoke Action = "user.trusted_device_revoke"
	// ActionTrustedDeviceUse is the directory path's skip: the
	// directory asked whether a browser was remembered and was told yes, so
	// its code page was not shown. The native path records its skip on the
	// user.login row instead; the directory's sign-in reaches the registry
	// only afterwards, as a callback that no longer knows.
	ActionTrustedDeviceUse Action = "user.trusted_device_use"
	ActionPATCreate        Action = "pat.create"
	ActionPATRevoke        Action = "pat.revoke"
	// SSH keys for the git transport.
	ActionSSHKeyAdd          Action = "ssh_key.add"
	ActionSSHKeyRemove       Action = "ssh_key.remove"
	ActionUserDirectoryErase Action = "user.directory_erase"
	// ActionUserStaffSync records a platform_staff change: the staff
	// organization's rule, with the reason it ran.
	ActionUserStaffSync Action = "user.staff_sync"
	ActionUserDelete    Action = "user.delete"
	// ActionUserDataClear records a user clearing their credentials,
	// installs and settings while keeping the account.
	ActionUserDataClear Action = "user.data_clear"
	// Platform staff acting on a person's account: suspending it (every
	// credential revoked), reinstating it, and signing it out everywhere.
	// Each row names the staff member as the actor and carries the reason.
	ActionUserSuspend   Action = "user.suspend"
	ActionUserReinstate Action = "user.reinstate"
	ActionUserSignOut   Action = "user.sign_out_everywhere"
	// ActionUserActivationResend is platform staff sending an unactivated
	// account a new activation link.
	ActionUserActivationResend Action = "user.activation_resend"

	// Orgs & teams.
	ActionOrgCreate       Action = "org.create"
	ActionOrgUpdate       Action = "org.update"
	ActionOrgMemberSet    Action = "org.member_set"
	ActionOrgMemberRemove Action = "org.member_remove"
	// Invitations and approvals: the only doors into an
	// organization, each audited where it is decided.
	ActionOrgInviteCreate  Action = "org.invite_create"
	ActionOrgInviteRevoke  Action = "org.invite_revoke"
	ActionOrgInviteAccept  Action = "org.invite_accept"
	ActionOrgMemberDecline Action = "org.member_decline"
	// The logo set or removed; the detail carries the object
	// key served, never the bytes.
	ActionOrgLogoSet     Action = "org.logo_set"
	ActionOrgLogoRemoved Action = "org.logo_removed"
	// An organization's shared knowledge: a pack created or
	// deleted by an admin, marked exportable or not (detail: exportable),
	// and exported unencrypted (by an admin, or a member of a pack marked
	// exportable). The detail names the pack, never a byte of it.
	ActionOrgKnowledgeCreate Action = "org.knowledge_create"
	ActionOrgKnowledgeUpdate Action = "org.knowledge_update"
	ActionOrgKnowledgeDelete Action = "org.knowledge_delete"
	ActionOrgKnowledgeExport Action = "org.knowledge_export"
	// An administrator shipped one of the organization's packs with a
	// release of an agent in the organization's namespace. The detail
	// names the pack, the agent, the version and the submitter.
	ActionOrgKnowledgeShip Action = "org.knowledge_ship"
	// An organization's house report designs: a design created, replaced
	// (its document or one of its images) or deleted by an admin. The
	// detail names the design, never a byte of it.
	ActionOrgReportDesignCreate Action = "org.report_design_create"
	ActionOrgReportDesignUpdate Action = "org.report_design_update"
	ActionOrgReportDesignDelete Action = "org.report_design_delete"
	// The fold-in: an existing account at the organization's
	// domain became a pending member, at its sign-in or by the sweep.
	ActionOrgMemberPending Action = "org.member_pending"
	// The organization's lifecycle and its domain: a
	// decommission decided, the erasure that ends its hold, platform
	// staff's suspension and reinstatement, and a person's request to
	// join the organization at their email domain.
	ActionOrgDecommission  Action = "org.decommission"
	ActionOrgErase         Action = "org.erase"
	ActionOrgSuspend       Action = "org.suspend"
	ActionOrgReinstate     Action = "org.reinstate"
	ActionOrgAccessRequest Action = "org.access_request"
	ActionTeamCreate       Action = "team.create"
	ActionTeamDelete       Action = "team.delete"
	ActionTeamMemberAdd    Action = "team.member_add"
	ActionTeamMemberRemove Action = "team.member_remove"

	// Agents & repos.
	ActionAgentCreate      Action = "agent.create"
	ActionAgentUpdate      Action = "agent.update"
	ActionAgentGrantSet    Action = "agent.grant_set"
	ActionAgentGrantRemove Action = "agent.grant_remove"
	ActionRepoPush         Action = "repo.push"

	// Versions & publication.
	ActionVersionSubmit     Action = "version.submit"
	ActionVersionTransition Action = "version.transition"
	ActionVersionYank       Action = "version.yank"
	ActionVersionWithdraw   Action = "version.withdraw"

	// Security pipeline.
	ActionReviewDecision  Action = "review.decision"
	ActionFindingVerdict  Action = "finding.verdict"
	ActionPolicyUpdate    Action = "policy.update"
	ActionAgentQuarantine Action = "agent.quarantine"
	ActionAgentBlock      Action = "agent.block"
	ActionAgentReinstate  Action = "agent.reinstate"
	ActionAdvisoryPublish Action = "advisory.publish"
	// ActionAgentDependencyAlert records the daily MCP sweep opening a
	// dependency alert on a published version.
	ActionAgentDependencyAlert Action = "agent.dependency_alert"
	ActionRulesetRelease       Action = "ruleset.release"
	ActionAbuseReport          Action = "abuse.report"
	ActionAbuseTriage          Action = "abuse.triage"

	// Enterprise: SSO, provisioning, webhooks, domain verification, audit
	// export. sso.connection_*, scim.token_* and scim.group_sync name rows
	// this server does not write; they stay in the vocabulary so older rows
	// stay readable.
	ActionSSOConnectionSet    Action = "sso.connection_set"
	ActionSSOConnectionDelete Action = "sso.connection_delete"
	ActionSSOLogin            Action = "sso.login"
	ActionSCIMTokenCreate     Action = "scim.token_create"
	ActionSCIMTokenRevoke     Action = "scim.token_revoke"
	ActionSCIMUserProvision   Action = "scim.user_provision"
	ActionSCIMUserDeactivate  Action = "scim.user_deactivate"
	ActionSCIMGroupSync       Action = "scim.group_sync"
	ActionWebhookCreate       Action = "webhook.create"
	ActionWebhookUpdate       Action = "webhook.update"
	ActionWebhookDelete       Action = "webhook.delete"
	ActionDomainClaim         Action = "domain.claim"
	ActionDomainVerified      Action = "domain.verified"
	ActionAuditExport         Action = "audit.export"

	// Stars, agent lifecycle, and platform operations.
	ActionAgentStar   Action = "agent.star"
	ActionAgentUnstar Action = "agent.unstar"
	// An account install and its removal: the caller's own record,
	// beside the star.
	ActionAgentInstall   Action = "agent.install"
	ActionAgentUninstall Action = "agent.uninstall"
	ActionAgentDelete    Action = "agent.delete"
	// Retire and Restore of a publisher's own agent.
	ActionAgentRetire  Action = "agent.retire"
	ActionAgentRestore Action = "agent.restore"
	// A fork recorded in its own namespace.
	ActionAgentFork         Action = "agent.fork"
	ActionAgentTransfer     Action = "agent.transfer"
	ActionWebhookPing       Action = "webhook.ping"
	ActionAuditPlatformRead Action = "audit.platform_read"
	ActionAuditPrune        Action = "audit.prune"
	ActionSocialLogin       Action = "user.social_login"
)

The v1 action catalog. Append-only: never rename or reuse an id.

type ActorKind

type ActorKind string

ActorKind mirrors audit_events.actor_kind.

const (
	ActorUser   ActorKind = "user"
	ActorPAT    ActorKind = "pat"
	ActorSCIM   ActorKind = "scim"
	ActorSystem ActorKind = "system"
)

Actor kinds.

type Event

type Event struct {
	Actor      uuid.UUID // zero for system events
	ActorKind  ActorKind
	OrgID      uuid.UUID // zero when not org-scoped
	Action     Action
	TargetKind string
	TargetID   uuid.UUID
	IP         netip.Addr
	UserAgent  string
	Detail     map[string]any
}

Event is one audit record. OrgID/Target are optional; Detail must not contain secrets or tokens (reviewers grep for violations).

type FileStream

type FileStream struct {
	// OnDrop, when set, is called for every record dropped on a full buffer
	// (the metrics layer counts it as a fail-open event).
	OnDrop func()
	// contains filtered or unexported fields
}

FileStream appends NDJSON to one file per UTC day in a directory.

func NewFileStream

func NewFileStream(dir string, flush time.Duration, log *slog.Logger) (*FileStream, error)

NewFileStream opens (creating as needed) the archive directory and starts the background flusher.

func (*FileStream) Append

func (fs *FileStream) Append(rec Record)

Append implements Stream.

func (*FileStream) Close

func (fs *FileStream) Close() error

Close implements Stream.

func (*FileStream) Flush

func (fs *FileStream) Flush(context.Context) error

Flush implements Stream.

type LogStream

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

LogStream mirrors every record as one line on the server's logger — `event=audit.<action>` with the record's fields — so an audit event is searchable wherever the server's lines are shipped (docs/logging.md). It is a mirror: the row in audit_events remains the record, and the file archive keeps its own shape. The write is synchronous — one line on stderr, microseconds — so there is no buffer and therefore no drop path of its own; what happens to the line after that is the log shipping's business, which is best-effort by design.

func NewLogStream

func NewLogStream(log *slog.Logger) LogStream

NewLogStream builds the mirror on log (nil means the default logger).

func (LogStream) Append

func (ls LogStream) Append(rec Record)

Append implements Stream.

func (LogStream) Close

func (LogStream) Close() error

Close implements Stream.

func (LogStream) Flush

func (LogStream) Flush(context.Context) error

Flush implements Stream: every line is written as it is appended.

type NopStream

type NopStream struct{}

NopStream discards records (archiving disabled).

func (NopStream) Append

func (NopStream) Append(Record)

Append implements Stream.

func (NopStream) Close

func (NopStream) Close() error

Close implements Stream.

func (NopStream) Flush

func (NopStream) Flush(context.Context) error

Flush implements Stream.

type Record

type Record struct {
	ID         uuid.UUID       `json:"id"`
	OccurredAt time.Time       `json:"occurredAt"`
	ActorID    *uuid.UUID      `json:"actorId,omitempty"`
	ActorKind  string          `json:"actorKind"`
	OrgID      *uuid.UUID      `json:"orgId,omitempty"`
	Action     string          `json:"action"`
	TargetKind string          `json:"targetKind,omitempty"`
	TargetID   *uuid.UUID      `json:"targetId,omitempty"`
	Detail     json.RawMessage `json:"detail,omitempty"`
	IP         string          `json:"-"`
	UserAgent  string          `json:"-"`
	RequestID  string          `json:"-"`
}

Record is one NDJSON line. Field names match the API's AuditEvent shape so the archive and the API describe events identically. The three fields the API does not carry — the caller's address and agent, and the request the event happened in — are on the row and reach the `log` sink; the file archive keeps the API's shape.

type Stream

type Stream interface {
	// Append queues one record. It never blocks and never returns an error:
	// callers are on the request path.
	Append(rec Record)
	// Flush writes everything queued so far.
	Flush(ctx context.Context) error
	// Close flushes and releases the sink.
	Close() error
}

Stream is the NDJSON archive sink.

func NewS3Stream

func NewS3Stream(bucket string, _ time.Duration, _ *slog.Logger) (Stream, error)

NewS3Stream is the hosted-deployment sink (a delivery stream). Not built here: the deployment that needs it is the same one that provisions the delivery stream, and a half-written client that silently drops records would be worse than an explicit refusal at startup.

func NewStream

func NewStream(kind, dir, s3Bucket string, flush time.Duration, log *slog.Logger) Stream

NewStream builds the configured sink. An unconfigured or unsupported kind yields a no-op sink and a log line — a self-host operator who has not set up archival still gets a working registry.

type Writer

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

Writer persists events. It is safe for concurrent use. The query handle is passed per call so events join the caller's transaction: an audited mutation and its audit row commit or roll back together.

func NewWriter

func NewWriter(log *slog.Logger) *Writer

NewWriter builds a Writer. Archiving is off until SetStream is called.

func (*Writer) SetStream

func (w *Writer) SetStream(s Stream)

SetStream attaches the NDJSON archive sink. Called once at startup.

func (*Writer) Stream

func (w *Writer) Stream() Stream

Stream returns the attached archive sink (tests, shutdown flush).

func (*Writer) Write

func (w *Writer) Write(ctx context.Context, q *storegen.Queries, e Event) error

Write records the event via q (pass the transaction-bound queries when the mutation runs in a tx). Failures are returned AND logged: callers in request paths must fail the mutation if the audit write fails (append-only log is a trust property, not telemetry).

Jump to

Keyboard shortcuts

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