audit

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MPL-2.0 Imports: 27 Imported by: 2 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.

README

Audit Module

This optional Module has its own Go-module version in the existing repository. Version() and Descriptor.Version report the actual packaged Audit dependency; Core has a separate identity. Consumption owns compatible dependency selection and the transition from monolithic releases. The legacy ModuleVersion constant is retained only as a deprecated unpublished source-line label, not component/update/recovery identity; achrix.audit.append, achrix.audit.query and achrix.audit.export use ABI 1 and require Core authorization ABI 2. Release-specific history belongs to the lifecycle guide.

Products explicitly install audit.Migrate(ctx, dsn) with a deadline before startup, then compose audit.NewPostgres(dsn, audit.Config{Now: clock}, logger) and construct audit.NewService(app, module). Runtime startup verifies the exact immutable migration ledger and enabled mutation guards; it does not migrate. This baseline uses the supported PostgreSQL profile with UTF-8, transactional DDL, native transactions and advisory locks, without extensions. Installation and runtime DSN sources, database roles and secrets remain product-owned.

The current ledger has immutable 001_audit.sql and additive 002_attribution.sql. Explicit migration accepts only an exact, nonempty ordered prefix for an existing schema: it verifies the installed columns and mutation guards while holding the same transactional advisory lock, applies missing migrations and their checksum rows, verifies the current result, and commits. A fresh installation applies both. Empty, noncontiguous, changed or future ledgers fail closed; an upgrade does not repair damaged history or disabled guards. Startup requires the complete current ledger. Version 2 adds nullable provenance columns without updating any historical record. DDL and its ledger entry share one native transaction, so a rejected DDL/ledger operation leaves the previous version intact. A lost commit acknowledgement still requires checking the installed ledger before deciding the next action.

Quiesce coupled accountable writes and use the product's supported backup/recovery procedure before changing a retained deployment. Old binaries that require exactly the v1 ledger reject v2; reverting source does not downgrade the schema. Deploy compatible Audit/Identity dependencies together. Capability ABI versions and existing Service signatures remain unchanged; the durable schema and optional Record metadata have advanced. The genuine v1 regression uses the exact historical migration/checksum and retained rows, separately from fresh-current installation and normal consumer restore evidence.

Identity is the real proving domain. Successful account provision, credential replacement, self password change, account status transition and revoke-all are atomic-required: Identity authorizes its domain capability, Audit Prepare authorizes append on the same stable account target, then Identity changes its owned state and calls audit.AppendInTx within that one native PostgreSQL transaction. Audit owns its SQL; Identity never writes Audit tables. Any append error requires rollback of the entire domain transaction. A successful append return is not commit proof. A lost commit acknowledgement is unavailable, not permission to replay a mutation; the domain owns its revision/reconciliation behavior.

Event carries only bounded action, stable target, owning authority capability and the succeeded outcome. Audit derives actor from the authorized principal, generates the opaque record ID and captures the injected UTC time at microsecond precision. Authority metadata describes the domain contract; it grants no permission. The caller must pass opaque actor/target references and domain classification names, never credentials, password hashes, session secrets, display text or request bodies. Audit has no arbitrary payload field. Successful ordinary login, session rotation/logout and repetitive denied/invalid attempts remain outside the retained dataset; operational diagnostics own those concerns.

Trusted request attribution

WithAttribution(ctx, actor, Attribution) is an optional trusted composition API, not a remote input or authorization mechanism. An authenticated entry point supplies ClientID, optional ConnectionID, Channel, RequestID and Operation from its verified request context. The existing Record.Actor remains the subject. Do not populate these fields from unverified identity headers, tool arguments, request bodies, access tokens or session credentials. URI-like non-secret client identifiers are permitted; they are never fetched.

Client and connection identifiers are bounded to 256 UTF-8 bytes without control characters. ClientID is required; absent ConnectionID stays empty. RequestID follows the existing 1–128-character opaque reference rule. Operation and Channel contain ASCII letters, digits, periods, underscores or hyphens, bounded to 96 and 32 characters respectively. A present attribution must include every required field. Product verifiers map external subjects to Audit's existing valid internal actor reference; the helper does not silently normalize, hash or truncate identities.

The helper copies the value into private context state bound to its actor and retains the parent's cancellation/deadline. Prepare rejects an actor mismatch and snapshots that value with its already authorized event. AppendInTx inserts the prepared provenance in the same native transaction as the owning domain change; a later context cannot replace it. No attribution field changes authorization, and the original context/deadline and single-use restrictions still apply.

Record.Attribution is *Attribution. Nil means no provenance was retained, including historical records and existing direct callers. Migration never guesses a client, channel, request or operation for those records. The database accepts either a complete valid tuple (with an optional connection) or complete absence, and the existing UPDATE/DELETE/TRUNCATE guards protect the added columns too. The provenance is trusted product attribution, not cryptographic attestation or an independent assertion that a provider/client is trustworthy.

Prepared is opaque, single-use and bound to its originating live context/deadline and Module. A fresh context cannot revive a canceled preparation. AppendInTx tracks and cancels its owned SQL during Module stop while the caller retains transaction/commit ownership. The consumer must drain its transaction work before Audit stops; Identity declares that dependency. CheckDatabase compares normalized connection credentials, database, runtime/TLS/protocol and fallback settings without exposing them, rejecting ambiguous driver callback settings conservatively. Remote primary and every fallback require certificate-verified TLS with hostname verification. Unix/loopback plaintext is the local development profile, not a remote deployment support claim. Driver environment/service/password/certificate resolution remains trusted product configuration, not public request input.

Query and export have separate target-specific permissions and limits of 1–100 records per call. Cursors use an internal sequence and are bound to the target; every page reauthorizes. Each page reads committed visible records. Pages are not one consistent snapshot across requests, and concurrent insert transactions can become visible out of sequence. For a complete consistent export/recovery operation, quiesce accountable domain writes or use the product's supported database snapshot/backup profile. The baseline retains all records and provides no deletion, mutation or invented retention/legal policy. Corrections/redaction need a separately accepted domain/product requirement.

The optional remote package binds Query and Export to explicit bounded HTTP pages and typed MCP tools using the same Service. It supplies no append, mutation, unbounded export or target/account listing. The package shares Audit's module version; its optional Bridge/SDK module-graph requirements do not make a direct Audit import compile or run those presentation packages. Core and Audit domain source do not import Bridge.

The owned schema rejects record UPDATE, DELETE and TRUNCATE with database triggers and constrains identifiers/metadata. This is append-oriented application integrity, not cryptographic tamper evidence: privileged database operators can change/drop the guards or schema. Startup and explicit installation checks verify guard presence; readiness only pings the database; they are not continuous privileged-tampering detection. Restore must preserve the entire owned audit schema, records, sequence, immutable migration ledger and trigger functions, together with the coupled Identity/account state. Source rollback does not reverse retained state. Whole-product/off-host/RPO/RTO support remains downstream of the real product recovery work.

Config.MaxConns bounds the instance pool (zero defaults to four; explicit minimum one). Config.MaxOperations bounds active owned leases (zero defaults to 16; explicit minimum two), with fail-fast admission and no lease queue. Standalone Append holds its transaction lease plus the nested AppendInTx lease; the minimum supports an isolated append, without promising fairness for concurrent nested work. AppendInTx may use a caller-owned connection, so lease and connection budgets differ. Public calls require deadlines. Pool minima remain zero, with one minute idle/health period, one hour lifetime without jitter and one second connect/ping limits. Typed pool/admission settings are not database identity and do not change CheckDatabase or explicit Migrate profiles. Operations owns aggregate budgets and native demand-based behavior. Operational failures preserve safe public identities and produce phase-aware diagnostics under the contract below. Repeated denied/invalid/capacity traffic creates neither Audit records nor provider-error logs.

ACHRIX_AUDIT_TEST_DSN must identify the separate task-owned validation database with the achrix_audit_ name prefix; tests preflight that guard before explicitly resetting only its Audit schema. Identity tests use a different database and install both owned schemas to prove the real same-transaction consumer. The shared validation script additionally owns normal pinned consumption and retained-dataset restore proof.

Actionable errors and protected diagnostics

*InputError identifies a malformed actor, target, action, authority, outcome, limit or cursor without echoing caller values; errors.Is(err, ErrInput) remains supported. A cursor does not prove permission. Exact target authorization, immutable records and the atomic append contract remain unchanged.

Config.Diagnostic optionally receives (ctx, operation, phase, originalCause) synchronously before ordinary-log suppression. Keep the same trusted request/operation context. This is a protected product-owned boundary: raw provider errors may contain secrets/data, so apply provider-aware targeted redaction before restricted storage/export, keep diagnostics outside public serving, bound retention/volume and return promptly. Do not pass raw causes to an ordinary logger. Normal slog records retain safe source-owned explanations, typed cause, validated SQLSTATE/network reason, phase and relevant outcome. Local process/file diagnosis requires no collector. Operations owns the common handling policy.

MigrateWithDiagnostics(ctx, dsn, logger, diagnostic) adds that boundary to explicit installation. Existing Migrate(ctx, dsn) delegates using the default logger. Startup and migration identify environment, ledger cardinality/version/checksum, runtime columns, missing/disabled mutation guards, lock, DDL, ledger write, commit and cleanup failures. Diagnose and fix the named precondition; do not rewrite immutable migration history. Useful technical facts are retained while arbitrary SQL/driver messages remain protected.

A live-caller dependency timeout/cancellation is operationally diagnosed; a normal caller-aborted read is distinct. Transaction diagnostics distinguish pre-begin not_executed, not_committed, uncertain commit unknown, and acknowledged committed. A SQLSTATE indicating statement/transaction resolution uncertainty is not rollback proof. AppendInTx owns the original append cause; the committing domain may add its distinct transaction outcome. Cleanup failure never overwrites the primary result; harmless pgx.ErrTxClosed is ignored. None of these categories grants blanket retry permission.

The ordinary one-second diagnostic window retains 56 distinct ordinary signatures and reserves eight for unknown mutation outcomes. Its private bounded fingerprint retains no raw cause text and explicitly marks truncated fingerprints with original length in safe metadata. One timer emits repeated counts and overflow even when traffic stops, and shutdown flushes pending summaries. diagnostic_summary=true records use no individual request context; counts are aggregate evidence, not attribution to a single caller. The protected callback still sees every operational cause and owns its own repetition/storage policy. Product handlers preserve these final summaries. This is bounded troubleshooting evidence, separate from durable Audit and from abuse controls.

Documentation

Overview

SPDX-License-Identifier: MPL-2.0

SPDX-License-Identifier: MPL-2.0 Package audit owns retained accountability records. Domains choose accountable actions; operational logs and repeated public denials are not Audit events.

SPDX-License-Identifier: MPL-2.0

SPDX-License-Identifier: MPL-2.0

SPDX-License-Identifier: MPL-2.0

Index

Constants

View Source
const (
	Append = "achrix.audit.append"
	Query  = "achrix.audit.query"
	Export = "achrix.audit.export"
)
View Source
const ModuleVersion = "0.2.0-development"

ModuleVersion is the unpublished source-line label, not the packaged build version. Deprecated: use Module.Descriptor().Version for component/update/recovery identity.

Variables

View Source
var (
	ErrConfiguration = errors.New("invalid audit configuration")
	ErrInput         = errors.New("invalid audit input")
	ErrUnavailable   = errors.New("audit unavailable")
	ErrConflict      = errors.New("audit preparation already consumed")
	ErrLimited       = errors.New("audit capacity exceeded")
)

Functions

func AppendInTx

func AppendInTx(parent context.Context, tx pgx.Tx, prepared Prepared) error

AppendInTx owns Audit SQL while the caller owns the native PostgreSQL transaction and commit. The domain must roll back if this call fails. A successful return alone does not prove either write has committed.

func Migrate

func Migrate(ctx context.Context, dsn string) error

Migrate explicitly installs or advances an exact immutable ledger prefix under one transactional advisory lock. Startup never changes schema. Source rollback does not downgrade retained records or the migration ledger. Existing callers use the default logger. Products needing protected original causes should call MigrateWithDiagnostics with their configured sink.

func MigrateWithDiagnostics added in v0.2.0

func MigrateWithDiagnostics(ctx context.Context, dsn string, logger *slog.Logger, diagnostic func(context.Context, string, string, error)) error

MigrateWithDiagnostics adds product-owned diagnostics without changing the public error chain or immutable migration. The hook receives original causes; it must apply provider-aware redaction before protected retention/export.

func Version

func Version() string

Version identifies this Module's actual packaged source dependency. Local and replacement builds report explicit development categories.

func WithAttribution added in v0.3.0

func WithAttribution(ctx context.Context, actor achrix.Principal, value Attribution) (context.Context, error)

WithAttribution validates and copies verifier-bound attribution for one actor. Trusted entry-point composition supplies this value after authentication; it must never be decoded from public operation arguments or identity headers. It grants no access and preserves the original cancellation/deadline. Prepare checks the actor binding and captures its own immutable value snapshot. Existing direct calls need not attach attribution; absence stays explicit.

Types

type Attribution added in v0.3.0

type Attribution struct {
	ClientID     string
	ConnectionID string
	Channel      string
	RequestID    string
	Operation    string
}

Attribution is trusted product-bound request provenance, not authorization. Actor remains Record.Actor. Client and connection IDs are non-secret opaque identifiers, never access tokens, credentials, headers or arbitrary payloads. A missing connection ID is permitted; every other field is required.

type Config

type Config struct {
	// Diagnostic receives the original cause only at this component's protected
	// owner boundary. The product must redact provider secrets before retention
	// or export, keep access restricted, and return promptly. It must not log
	// the raw error to ordinary output. The original request context is retained.
	// It sees every operational cause before ordinary-log suppression; the
	// product owns its diagnostic sink's volume policy.
	Diagnostic func(context.Context, string, string, error)
	// MaxConns bounds this instance's pool. Zero uses four; negatives are invalid.
	MaxConns int32
	// MaxOperations bounds active owned leases, including nested AppendInTx work.
	// Zero uses 16; explicit values must be at least two.
	MaxOperations int
	Now           func() time.Time
}

Config.Now is a trusted, concurrent-safe product time source. Records store UTC microsecond instants; it conveys no trusted timestamp or clock attestation.

type Event

type Event struct{ Action, Target, Authority, Outcome string }

Event deliberately has no caller-selected actor, time, ID or arbitrary payload. Authority identifies the owning domain capability, not an authorization grant.

type InputError added in v0.2.0

type InputError struct{ Field, Reason string }

InputError identifies a malformed field without echoing caller values.

func (*InputError) Error added in v0.2.0

func (e *InputError) Error() string

func (*InputError) Unwrap added in v0.2.0

func (e *InputError) Unwrap() error

type Module

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

Module owns only Audit storage, pool, admission and lifecycle. Identity's declared dependency orders its shutdown drain before this Module is stopped.

func NewPostgres

func NewPostgres(dsn string, config Config, logger *slog.Logger) (*Module, error)

func (*Module) Descriptor

func (m *Module) Descriptor() achrix.Descriptor

func (*Module) FailureCount

func (m *Module) FailureCount() uint64

FailureCount counts bounded operational failures, not durable accountability.

func (*Module) Ready

func (m *Module) Ready(parent context.Context) error

func (*Module) Start

func (m *Module) Start(ctx context.Context) error

func (*Module) Stop

func (m *Module) Stop(ctx context.Context) error

type Page

type Page struct {
	Records    []Record
	NextCursor string
}

type Prepared

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

Prepared is opaque, single-use and bound to the original live operation and Audit Module. It cannot extend a deadline or be retained as an access grant.

type Record

type Record struct {
	ID         string
	Actor      achrix.Principal
	Action     string
	Target     string
	Authority  string
	Outcome    string
	OccurredAt time.Time
	// Nil means no request provenance was retained; historical/direct records
	// must not acquire a guessed channel, client or request identity.
	Attribution *Attribution
}

type Service

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

func NewService

func NewService(app *achrix.Application, module *Module) (*Service, error)

func (*Service) Append

func (s *Service) Append(parent context.Context, actor achrix.Principal, event Event) (Record, error)

Append commits an authorized standalone record. Atomic domain actions instead use Prepare/AppendInTx within their owning transaction.

func (*Service) CheckDatabase

func (s *Service) CheckDatabase(dsn string) error

CheckDatabase prevents a same-transaction consumer from silently composing different database profiles. Equivalent parsed connection settings match; passwords, TLS trust and fallback settings are compared without being exposed.

func (*Service) Export

func (s *Service) Export(ctx context.Context, actor achrix.Principal, target, cursor string, limit int) (Page, error)

func (*Service) Prepare

func (s *Service) Prepare(ctx context.Context, actor achrix.Principal, event Event) (Prepared, error)

func (*Service) Query

func (s *Service) Query(ctx context.Context, actor achrix.Principal, target, cursor string, limit int) (Page, error)

Query and Export require separate permissions on the exact target. Each is a bounded page of committed visible records, not a snapshot across requests.

Directories

Path Synopsis
SPDX-License-Identifier: MPL-2.0
SPDX-License-Identifier: MPL-2.0

Jump to

Keyboard shortcuts

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