auditlog

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: AGPL-3.0 Imports: 34 Imported by: 0

Documentation

Overview

Package auditlog serves the audit log (A5 §3.10, §5.14): filtered event list, event detail with before/after values, streamed CSV/JSON exports, streaming to a webhook and retention. Entries are immutable.

Index

Constants

View Source
const InstanceScope = "instance"

InstanceScope is the workspace filter value for instance-level entries.

Variables

View Source
var Categories = []AuditCategory{
	{Key: "sending", Label: "Sending", Groups: []string{"campaign", "approval", "send", "report", "template", "automation"}},
	{Key: "routing", Label: "Routing & providers", Groups: []string{"routing", "provider", "warmup", "deliverability", "domain", "sender"}},
	{Key: "audience", Label: "Audience & consent", Groups: []string{"contact", "contacts", "subscriber", "subscribers", "list", "segment", "form", "consent", "suppression", "import", "growth"}},
	{Key: "team", Label: "Team & access", Groups: []string{"team", "member", "role", "apikey", "agent", "auth", "invitation", "user", "session", "sso"}},
	{Key: "settings", Label: "Settings", Groups: []string{"workspace", "webhook", "audit", "settings", "mcp", "instance"}},
	{Key: "integrations", Label: "Integrations", Groups: []string{"integration", "wordpress", "hostrepute"}},
	{Key: "transactional", Label: "Transactional", Groups: []string{"transactional", "smtp_relay"}},
	{Key: "scoring", Label: "Scoring", Groups: []string{"scoring"}},

	{Key: "digests", Label: "Digests", Groups: []string{"digest"}},
	{Key: "polls", Label: "Polls & surveys", Groups: []string{"poll", "survey"}},

	{Key: "ai", Label: "AI", Groups: []string{"ai"}},

	{Key: "earn", Label: "Earn", Groups: []string{"payments", "earn", "paid_member", "sponsors"}},
	{Key: "verification", Label: "Verification", Groups: []string{"verification"}},
	{Key: "placement", Label: "Placement tests", Groups: []string{"placement"}},

	{Key: "website", Label: "Website", Groups: []string{"website", "post", "tag", "page"}},

	{Key: "grow", Label: "Grow", Groups: []string{"referral", "recommendation", "partner"}},

	{Key: "products", Label: "Products", Groups: []string{"product", "order"}},

	{Key: "commerce", Label: "Commerce", Groups: []string{"store"}},

	{Key: "sms", Label: "SMS", Groups: []string{"sms_provider", "sms_sender", "sms_registration", "sms_routes", "sms_rules", "sms_short_domain",
		"sms_suppression", "sms_terms", "sms_test_number", "sms"}},

	{Key: "push", Label: "Push", Groups: []string{"push_keys", "push_site", "push_prompt", "push_settings", "push_subscription"}},
	{Key: "whatsapp", Label: "WhatsApp", Groups: []string{"whatsapp", "whatsapp_templates", "whatsapp_rates", "whatsapp_settings"}},

	{Key: "agency", Label: "Agency", Groups: []string{"agency"}},
}

Categories are the action filter's choices, in the order of the board.

Functions

func Client

func Client(ua string) string

Client turns a User-Agent into "Chrome 141 on macOS 26".

func ClientIn

func ClientIn(l i18n.Lang, ua string) string

ClientIn is Client in a language: "Chrome 141 trên macOS 26".

func Describe

func Describe(action, targetType, targetName string) string

Describe writes "Changed the Broadcasts routing rule" style sentences from an action, in English.

func DescribeIn

func DescribeIn(l i18n.Lang, action, targetType, targetName string) string

DescribeIn writes an entry's What line in a language: a whole sentence per action's verb (what.<key>), with what was acted on (type.<type>) and its name. An action whose verb has no sentence reads as its words, in English, as audit action names do.

func Format

func Format(v json.RawMessage) string

Format renders a JSON value on one line with the spacing of the detail panel: { "ses_us_east_1": 95, "postal_mta": 5 }.

func Register

func Register(h huma.API, s *Service)

Register adds the audit log operations.

func RegisterInstance

func RegisterInstance(h huma.API, s *Service)

RegisterInstance adds the instance-level audit operations (instance admins only).

func RegisterInstanceJobs

func RegisterInstanceJobs(reg *jobs.Registry, s *Service, log *slog.Logger)

RegisterInstanceJobs adds the instance stream worker, run every 30 seconds.

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, s *Service, log *slog.Logger)

RegisterJobs adds the stream worker, run every 30 seconds.

func SignInFailed

func SignInFailed(l i18n.Lang, method string, failed int) string

SignInFailed is a sign-in after failed attempts: "Password · 3 failed".

func SignInMethod

func SignInMethod(l i18n.Lang, method, provider string) string

SignInMethod names a sign-in method like the boards: "Password + TOTP", "Google Workspace SSO", "Passkey", in a language.

func SignInRejection

func SignInRejection(l i18n.Lang, code, reason string) string

SignInRejection says in a few words why a sign-in was refused, in a language. A reason ReputeCast doesn't know stays as it was written.

func SignInSummary

func SignInSummary(l i18n.Lang, action, reason string, m SignInMeta) string

SignInSummary is the details line of a sign-in entry, as on the boards: "Password + TOTP · break-glass Owner", "wrong password · attempt 3 of 10", "Google Workspace SSO · email domain not allowed · reference auth_…", in a language. A refusal's own reason, as the identity provider or the policy gave it, stays as it was written unless ReputeCast knows its code.

func TypeLabel

func TypeLabel(t string, capital bool) string

TypeLabel turns a target type into words: "routing_rule" → "routing rule" ("Routing rule" with capital), "api_key" → "API key".

Types

type AuditActor

type AuditActor struct {
	Type        string `json:"type" enum:"user,api_key,mcp_agent,system"`
	ID          string `json:"id,omitempty"`
	Name        string `json:"name"`
	AvatarColor string `json:"avatarColor,omitempty"`
	// Label is "member", "API key", "integration key", "MCP agent" or "automatic".
	Label string `json:"label"`
	// Role is the member's current role in the workspace ("Admin").
	Role string `json:"role,omitempty"`
}

AuditActor is who acted.

type AuditActorRef

type AuditActorRef struct {
	Type string `json:"type"`
	ID   string `json:"id"`
	Name string `json:"name"`
}

AuditActorRef is an actor seen in the log, for the actor filter.

type AuditCategory

type AuditCategory struct {
	Key    string   `json:"key"`
	Label  string   `json:"label"`
	Groups []string `json:"groups"`
}

AuditCategory is one choice of the action filter: the action groups (the part before the dot) it covers.

type AuditDiffLine

type AuditDiffLine struct {
	Kind string `json:"kind" enum:"same,del,add"`
	Text string `json:"text"`
}

AuditDiffLine is one line of the before → after view.

func Diff

func Diff(before, after json.RawMessage) []AuditDiffLine

Diff lists the top-level keys of before and after, one per line, marking changed keys as a removed and an added line.

type AuditEventDetail

type AuditEventDetail struct {
	Event AuditEventItem `json:"event"`
	// What is a sentence: "Changed the Broadcasts routing rule".
	What      string `json:"what"`
	Workspace string `json:"workspace"`
	IP        string `json:"ip,omitempty"`
	UserAgent string `json:"userAgent,omitempty"`
	// Client is the user agent in words: "Chrome 141 on macOS 26".
	Client string `json:"client,omitempty"`
	// Permission is the permission the action needed (providers:manage).
	Permission string          `json:"permission,omitempty"`
	Before     json.RawMessage `json:"before,omitempty"`
	After      json.RawMessage `json:"after,omitempty"`
	Diff       []AuditDiffLine `json:"diff"`
	Related    []string        `json:"related"`
	// Link is the app path of the target, with its label ("Open routing").
	Link      string `json:"link,omitempty"`
	LinkLabel string `json:"linkLabel,omitempty"`
	// Restore undoes the delete the entry records while that is still
	// possible: a deleted list, for 30 days.
	Restore *AuditRestore `json:"restore,omitempty"`
	// JSON is the full entry for "Copy JSON".
	JSON json.RawMessage `json:"json"`
}

AuditEventDetail is the event detail panel.

type AuditEventItem

type AuditEventItem struct {
	ID         string     `json:"id"`
	OccurredAt time.Time  `json:"occurredAt"`
	Actor      AuditActor `json:"actor"`
	Action     string     `json:"action"`
	TargetType string     `json:"targetType"`
	TargetID   string     `json:"targetId"`
	TargetName string     `json:"targetName"`
	// Target is the line under the action ("Routing rule · Broadcasts").
	Target string `json:"target"`
	// Summary is the details line ("SES 95% / Postal 5% → SES 90% / Postal 10%").
	Summary   string      `json:"summary"`
	Source    AuditSource `json:"source"`
	Result    string      `json:"result" enum:"allowed,denied,error"`
	Reason    string      `json:"reason,omitempty"`
	RequestID string      `json:"requestId,omitempty"`
	// Changes tells that the entry changed an existing object: it has both a
	// before and an after to compare.
	Changes bool `json:"changes"`
}

AuditEventItem is one row of the event list.

type AuditEventList

type AuditEventList struct {
	Items      []AuditEventItem `json:"items"`
	NextCursor string           `json:"nextCursor,omitempty"`
	// Total is the number of entries kept for the workspace.
	Total         int64             `json:"total"`
	RetentionDays int32             `json:"retentionDays"`
	Stream        AuditStreamStatus `json:"stream"`
	Actors        []AuditActorRef   `json:"actors"`
	ActionGroups  []string          `json:"actionGroups"`
	// Categories are the choices of the action filter.
	Categories []AuditCategory `json:"categories"`
}

AuditEventList is one page of the log.

type AuditFilterInput

type AuditFilterInput struct {
	api.WorkspaceInput
	Search    string    `query:"q" maxLength:"200" doc:"Target name, target id, request id or actor name"`
	ActorType string    `query:"actorType" enum:"user,api_key,mcp_agent,system"`
	Actor     string    `query:"actor" doc:"Actor id"`
	Action    string    `query:"action" maxLength:"80" doc:"Action group (routing) or action (routing.updated)"`
	Category  string    `` /* 248-byte string literal not displayed */
	Result    string    `query:"result" enum:"allowed,denied,error"`
	Range     string    `query:"range" enum:"24h,7d,30d,90d,all" default:"7d"`
	Since     time.Time `query:"since" doc:"Overrides range"`
	Until     time.Time `query:"until"`
}

AuditFilterInput is a path or query input shared by several operations.

type AuditRestore

type AuditRestore struct {
	Kind  string    `json:"kind" enum:"list"`
	ID    string    `json:"id"`
	Name  string    `json:"name"`
	Until time.Time `json:"until"`
}

AuditRestore is a delete an entry can undo, until when.

type AuditSettings

type AuditSettings struct {
	RetentionDays int32             `json:"retentionDays"`
	Stream        AuditStreamStatus `json:"stream"`
	Total         int64             `json:"total"`
	CanManage     bool              `json:"canManage" doc:"Changing settings needs workspace:manage"`
}

AuditSettings is the retention and stream configuration.

type AuditSettingsInput

type AuditSettingsInput struct {
	RetentionDays *int32            `json:"retentionDays,omitempty" minimum:"30" maximum:"3650"`
	Stream        *AuditStreamInput `json:"stream,omitempty"`
}

AuditSettingsInput changes retention and the stream.

type AuditSettingsResult

type AuditSettingsResult struct {
	Settings AuditSettings `json:"settings"`
	Secret   string        `json:"secret,omitempty" doc:"New signing secret, shown only in this response"`
}

AuditSettingsResult carries a new stream secret, shown once.

type AuditSource

type AuditSource struct {
	Channel string `json:"channel"`
	Detail  string `json:"detail,omitempty"`
}

AuditSource is where the action came from: "web · 203.0.113.9", "mcp · rc_agent_7a…c2", "guard · threshold".

type AuditStreamInput

type AuditStreamInput struct {
	Enabled bool   `json:"enabled"`
	URL     string `json:"url,omitempty" maxLength:"500"`
	// RotateSecret issues a new signing secret (shown once).
	RotateSecret bool `json:"rotateSecret,omitempty"`
}

AuditStreamInput configures streaming the log to a webhook.

type AuditStreamStatus

type AuditStreamStatus struct {
	Enabled bool `json:"enabled"`
	// Host is where entries go ("warehouse.acme.io"); the full URL is in Settings.
	Host         string     `json:"host,omitempty"`
	URL          string     `json:"url,omitempty"`
	HasSecret    bool       `json:"hasSecret"`
	LastOKAt     *time.Time `json:"lastOkAt,omitempty"`
	FailingSince *time.Time `json:"failingSince,omitempty"`
	LastError    string     `json:"lastError,omitempty"`
	Delivered    int64      `json:"delivered"`
}

AuditStreamStatus describes the webhook stream of the log.

type AuditWorkspaceRef

type AuditWorkspaceRef struct {
	Slug string `json:"slug"`
	Name string `json:"name"`
}

AuditWorkspaceRef names a workspace for the workspace filter.

type Filter

type Filter struct {
	Search    string
	ActorType string
	ActorID   string
	Action    string // a group ("routing") or an action ("routing.updated")
	Category  string // one of Categories ("sending"); Action wins when both are set
	Result    string
	Range     string // 24h, 7d, 30d, 90d, all
	Since     *time.Time
	Until     *time.Time
	Cursor    string
	Limit     int
}

Filter narrows the log.

type InstanceAuditDetail

type InstanceAuditDetail struct {
	AuditEventDetail
	WorkspaceSlug string `json:"workspaceSlug,omitempty"`
	// AdminPath is the Instance admin screen of an instance-level target,
	// relative to /w/{workspace}/admin/ ("sso/0190…", "users?q=tom@acme.io").
	AdminPath string `json:"adminPath,omitempty"`
}

InstanceAuditDetail is the detail of an entry in the instance view.

type InstanceAuditFilterInput

type InstanceAuditFilterInput struct {
	Search    string    `query:"q" maxLength:"200" doc:"Account, target, request id or sign-in reference"`
	Workspace string    `query:"workspace" maxLength:"64" doc:"Workspace slug, or instance for instance-level entries only"`
	ActorType string    `query:"actorType" enum:"user,api_key,mcp_agent,system"`
	Result    string    `query:"result" enum:"allowed,denied,error"`
	Range     string    `query:"range" enum:"24h,7d,30d,90d,all" default:"30d"`
	Since     time.Time `query:"since" doc:"Overrides range"`
	Until     time.Time `query:"until"`
	// Category narrows to a group of actions, as in the workspace view
	// (agency: the agency's actions across the instance).
	Category string `` /* 184-byte string literal not displayed */
}

InstanceAuditFilterInput is the query of the instance view and its export.

type InstanceAuditItem

type InstanceAuditItem struct {
	AuditEventItem
	// Workspace is the entry's workspace; empty for instance-level entries.
	Workspace     string `json:"workspace,omitempty"`
	WorkspaceSlug string `json:"workspaceSlug,omitempty"`
}

InstanceAuditItem is one row of the instance view.

type InstanceAuditList

type InstanceAuditList struct {
	Items      []InstanceAuditItem `json:"items"`
	NextCursor string              `json:"nextCursor,omitempty"`
	Workspaces []AuditWorkspaceRef `json:"workspaces"`
	// RetentionDays is the retention of the instance-level entries.
	RetentionDays int32 `json:"retentionDays"`
}

InstanceAuditList is one page of the instance view.

type InstanceAuditSettings

type InstanceAuditSettings struct {
	RetentionDays int32             `json:"retentionDays"`
	Stream        AuditStreamStatus `json:"stream"`
	// Total is the number of instance-level entries kept.
	Total            int64                     `json:"total"`
	WorkspaceStreams []InstanceWorkspaceStream `json:"workspaceStreams"`
}

InstanceAuditSettings is the retention and stream of the instance-level log.

type InstanceAuditSettingsResult

type InstanceAuditSettingsResult struct {
	Settings InstanceAuditSettings `json:"settings"`
	Secret   string                `json:"secret,omitempty" doc:"New signing secret, shown only in this response"`
}

InstanceAuditSettingsResult carries a new stream secret, shown once.

type InstanceFilter

type InstanceFilter struct {
	Filter
	// Workspace is a workspace slug, or InstanceScope for the entries that
	// belong to no workspace.
	Workspace string
}

InstanceFilter narrows the instance view.

type InstanceStreamArgs

type InstanceStreamArgs struct{}

InstanceStreamArgs pushes new instance-level entries to the instance stream.

func (InstanceStreamArgs) InsertOpts

func (InstanceStreamArgs) InsertOpts() river.InsertOpts

InsertOpts keeps one run at a time.

func (InstanceStreamArgs) Kind

func (InstanceStreamArgs) Kind() string

Kind implements river.JobArgs.

type InstanceStreamWorker

type InstanceStreamWorker struct {
	river.WorkerDefaults[InstanceStreamArgs]
	S   *Service
	Log *slog.Logger
}

InstanceStreamWorker delivers instance-level entries in order, 500 per request, signed like outgoing webhooks. The cursor only moves after a 2xx.

func (*InstanceStreamWorker) Work

Work implements river.Worker.

type InstanceWorkspaceStream

type InstanceWorkspaceStream struct {
	Slug    string `json:"slug"`
	Name    string `json:"name"`
	Host    string `json:"host"`
	Failing bool   `json:"failing"`
}

InstanceWorkspaceStream is a workspace that streams its own log.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	// AllowPrivate reports whether endpoints may resolve to private
	// networks (webhooks.allow_private_networks); read at each use.
	AllowPrivate func() bool
	Now          func() time.Time
	// HTTP overrides the stream client (tests).
	HTTP *http.Client
}

func (*Service) Export

func (s *Service) Export(ctx context.Context, ws *store.Workspace, f Filter, format string, w io.Writer) error

Export writes the entries matching the filter as CSV or JSON, page by page, so large logs stream without being held in memory. The export itself is recorded in the log.

func (*Service) Get

Get returns one entry of the workspace log.

func (*Service) InstanceExport

func (s *Service) InstanceExport(ctx context.Context, f InstanceFilter, format string, w io.Writer) error

InstanceExport writes the matching entries as CSV or JSON, page by page.

func (*Service) InstanceGet

func (s *Service) InstanceGet(ctx context.Context, id uuid.UUID) (InstanceAuditDetail, error)

InstanceGet returns any entry on the instance.

func (*Service) InstanceList

func (s *Service) InstanceList(ctx context.Context, f InstanceFilter) (InstanceAuditList, error)

InstanceList returns one page of every entry on the instance.

func (*Service) InstanceSettings

func (s *Service) InstanceSettings(ctx context.Context) (InstanceAuditSettings, error)

InstanceSettings returns the instance-level retention and stream, and which workspaces stream their own log.

func (*Service) List

func (s *Service) List(ctx context.Context, ws *store.Workspace, f Filter) (AuditEventList, error)

List returns one page of the workspace log.

func (*Service) Settings

func (s *Service) Settings(ctx context.Context, ws *store.Workspace, p *authz.Principal) (AuditSettings, error)

Settings returns the audit settings of the workspace.

func (*Service) UpdateInstanceSettings

func (s *Service) UpdateInstanceSettings(ctx context.Context, in AuditSettingsInput) (InstanceAuditSettingsResult, error)

UpdateInstanceSettings changes the instance retention or stream.

func (*Service) UpdateSettings

UpdateSettings changes retention and the stream configuration.

type SignInMeta

type SignInMeta struct {
	Method      string `json:"method"`
	Provider    string `json:"provider"`
	AMR         string `json:"amr"`
	Code        string `json:"code"`
	Reference   string `json:"reference"`
	BreakGlass  bool   `json:"break_glass"`
	Workspace   string `json:"workspace"`
	Failures    int    `json:"failures"`
	MaxAttempts int    `json:"max_attempts"`
	// FailedBefore counts the failed attempts before a successful one.
	FailedBefore int `json:"failed_before"`
}

SignInMeta is what sign-in entries keep in their metadata.

type StreamArgs

type StreamArgs struct{}

StreamArgs is the periodic job that pushes new entries to each workspace's audit stream endpoint.

func (StreamArgs) InsertOpts

func (StreamArgs) InsertOpts() river.InsertOpts

InsertOpts keeps one run at a time.

func (StreamArgs) Kind

func (StreamArgs) Kind() string

Kind implements river.JobArgs.

type StreamWorker

type StreamWorker struct {
	river.WorkerDefaults[StreamArgs]
	S   *Service
	Log *slog.Logger
}

StreamWorker delivers audit entries in order, 500 per request, signed like outgoing webhooks. The cursor only moves after a 2xx.

func (*StreamWorker) Work

func (w *StreamWorker) Work(ctx context.Context, _ *river.Job[StreamArgs]) error

Work implements river.Worker.

Jump to

Keyboard shortcuts

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