audit

package
v2.0.3 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package audit appends governance events as JSONL.

Package audit provides tamper-evident audit persistence, compatible logical queries, authenticated verification, and checkpoint-aware rotation pruning. New records use a fixed v2 envelope; legacy plaintext and base64-age rows remain readable before v2 history. Destructive authorization remains the responsibility of the consumer before it confirms a prune operation.

Index

Constants

View Source
const (
	StatusPending       = "pending"
	StatusDenied        = "denied"
	StatusSuccess       = "success"
	StatusFailed        = "failed"
	StatusPartialFailed = "partial-failed"
)

Event status values written to Event.Status.

View Source
const DefaultMaxSizeBytes int64 = 100 * 1024 * 1024

DefaultMaxSizeBytes is the default active audit log size before rotation.

Variables

This section is empty.

Functions

func APIVersion

func APIVersion() string

APIVersion returns the apiVersion stamp emitted by audit query JSON output.

func Append

func Append(path string, event Event) error

Append appends one JSONL event. The file is owner-only.

func AppendRecord

func AppendRecord(path string, record any, opts Options) error

AppendRecord appends one JSONL record using the record's own JSON shape.

func AppendWithOptions

func AppendWithOptions(path string, event Event, opts Options) error

AppendWithOptions appends one JSONL event and rotates the active log when it exceeds the configured max size.

func Configure

func Configure(next Config)

Configure sets package-level audit defaults for a consumer CLI.

func DefaultPath

func DefaultPath() (string, error)

DefaultPath returns the default audit log path.

func ParseTime

func ParseTime(value string, now time.Time) (time.Time, error)

ParseTime parses a --since/--until value. Accepts either a relative offset (24h / 7d / 30m / 90s / 2w) interpreted as "now minus duration", or an absolute RFC3339 timestamp.

func RotatedFileTimestamp

func RotatedFileTimestamp(activePath, candidate string) (time.Time, bool)

RotatedFileTimestamp returns the timestamp encoded in a rotated audit file.

func RotatedFiles

func RotatedFiles(path string) ([]string, error)

RotatedFiles returns strictly named rotated audit logs sorted by timestamp and numeric collision suffix.

Types

type AppendCommitState

type AppendCommitState string

AppendCommitState reports whether an AppendRecordWithResult call durably committed its record.

const (
	// AppendCommitNotCommitted means the record is absent, including after a
	// successful truncate-and-sync rollback of a failed write.
	AppendCommitNotCommitted AppendCommitState = "not-committed"
	// AppendCommitCommitted means the record reached the platform commit point
	// and all post-commit bookkeeping completed.
	AppendCommitCommitted AppendCommitState = "committed"
	// AppendCommitCommittedPostCommitError means the record reached the
	// platform commit point, but later checkpoint or lock cleanup failed.
	AppendCommitCommittedPostCommitError AppendCommitState = "committed-postcommit-error"
	// AppendCommitIndeterminate means the record may be present because neither
	// commit nor a durable rollback could be established.
	AppendCommitIndeterminate AppendCommitState = "indeterminate"
)

type AppendResult

type AppendResult struct {
	State AppendCommitState
}

AppendResult describes the durable record state returned by AppendRecordWithResult.

func AppendRecordWithResult

func AppendRecordWithResult(path string, record any, opts Options) (AppendResult, error)

AppendRecordWithResult appends one JSONL record and reports its durable commit state. Existing active files commit when the appended bytes are fsynced. Newly created active files additionally pass the platform parent directory sync step: POSIX fsyncs the directory, while Windows treats the synced and closed file as the available platform durability boundary because directory handles do not provide the POSIX fsync contract.

A write or file-sync failure is rolled back with Truncate followed by Sync while the audit lock is still held. A successful rollback is AppendCommitNotCommitted; a failed rollback is AppendCommitIndeterminate.

func (AppendResult) IsCommitted

func (result AppendResult) IsCommitted() bool

IsCommitted reports whether the record is known to have reached its platform commit point, even if a later operation returned an error.

type AuditPruneDetail

type AuditPruneDetail struct {
	DeletedFiles []string `json:"deletedFiles"`
	Count        int      `json:"count"`
}

AuditPruneDetail records audit rotated files pruned by audit prune.

type BackupPruneDetail

type BackupPruneDetail struct {
	DeletedDirs []string `json:"deletedDirs"`
	Count       int      `json:"count"`
}

BackupPruneDetail records backup snapshots pruned after new backups.

type Config

type Config struct {
	APIVersion         string
	ConfigDirName      string
	PrivateKeyEnvVar   string
	TargetTypeJSONName string
	TimestampJSONName  string
	EventTypeJSONName  string
	OperatorJSONName   string
}

Config controls package-level defaults for audit logs.

type Event

type Event struct {
	Timestamp   time.Time             `json:"timestamp"`
	EventType   EventType             `json:"eventType"`
	Operator    string                `json:"operator,omitempty"`
	Context     EventContext          `json:"context"`
	Ticket      string                `json:"ticket,omitempty"`
	Reason      string                `json:"reason,omitempty"`
	Target      EventTarget           `json:"target"`
	Status      string                `json:"status"`
	Diff        string                `json:"diff,omitempty"`
	Error       *EventError           `json:"error,omitempty"`
	RoleChange  *EventRoleChange      `json:"roleChange,omitempty"`
	AuditPrune  *AuditPruneDetail     `json:"auditPrune,omitempty"`
	BackupPrune *BackupPruneDetail    `json:"backupPrune,omitempty"`
	RoleFetch   *EventRoleFetchDetail `json:"roleFetch,omitempty"`
}

Event is one JSONL audit record.

type EventContext

type EventContext struct {
	Name      string `json:"name,omitempty"`
	Env       string `json:"env,omitempty"`
	Protected bool   `json:"protected,omitempty"`
}

EventContext identifies the active context.

type EventError

type EventError struct {
	Code    string `json:"code,omitempty"`
	Message string `json:"message"`
}

EventError records a failed result.

type EventRoleChange

type EventRoleChange struct {
	ChangedOperator string `json:"changedOperator"`
	Role            string `json:"role,omitempty"`
}

EventRoleChange records RBAC role assignments and revocations.

type EventRoleFetchDetail

type EventRoleFetchDetail struct {
	URL        string `json:"url,omitempty"`
	CacheState string `json:"cacheState"`
}

EventRoleFetchDetail records remote RBAC role fetches.

type EventTarget

type EventTarget struct {
	App          string `json:"app,omitempty"`
	ResourceType string `json:"-"`
	Resource     string `json:"resource,omitempty"`
}

EventTarget identifies the changed resource set.

func (EventTarget) MarshalJSON

func (t EventTarget) MarshalJSON() ([]byte, error)

func (*EventTarget) UnmarshalJSON

func (t *EventTarget) UnmarshalJSON(data []byte) error

type EventType

type EventType string

EventType is an audit event category.

const (
	EventContextExport       EventType = "ctx.export"
	EventContextImport       EventType = "ctx.import"
	EventContextTest         EventType = "ctx.test"
	EventBackupPrune         EventType = "backup.prune"
	EventRoleAssign          EventType = "role.assign"
	EventRoleRevoke          EventType = "role.revoke"
	EventRoleFetch           EventType = "role.fetch"
	EventAuditPrune          EventType = "audit.prune"
	EventAuthorizationDenied EventType = "authorization.denied"
)

type Filter

type Filter struct {
	Since            *time.Time
	Until            *time.Time
	EventType        string
	Operator         string
	ContextName      string
	Env              string
	Protected        *bool
	Ticket           string
	App              string
	ResourceType     string
	Resource         string
	Status           string
	Limit            int
	Reverse          bool
	PrivateKey       string
	IntegrityKeyPath string
}

Filter is the set of optional predicates applied to audit log entries. All fields are AND-combined. Empty string fields mean "no filter".

type Options

type Options struct {
	MaxSizeBytes         int64
	EncryptPublicKeyPath string
	IntegrityKeyPath     string
}

Options controls audit append behavior.

type PruneCheckpointState

type PruneCheckpointState string

PruneCheckpointState reports the durable checkpoint state of a prune call.

const (
	// PruneCheckpointUnchanged means the call did not need to, or did not yet,
	// advance the authenticated checkpoint base.
	PruneCheckpointUnchanged PruneCheckpointState = "unchanged"
	// PruneCheckpointAdvanced means this call durably advanced the checkpoint
	// base before deleting authenticated rotations.
	PruneCheckpointAdvanced PruneCheckpointState = "advanced"
	// PruneCheckpointAlreadyAdvanced means the selected files are residue from
	// an earlier partial prune whose checkpoint advance already committed.
	PruneCheckpointAlreadyAdvanced PruneCheckpointState = "already-advanced"
	// PruneCheckpointIndeterminate means a checkpoint write failed after it may
	// have replaced the prior checkpoint. No candidate deletion is attempted.
	PruneCheckpointIndeterminate PruneCheckpointState = "indeterminate"
)

type PruneOptions

type PruneOptions struct {
	Confirm          bool
	IntegrityKeyPath string
	// ExpectedRotatedFiles, when non-nil, must exactly match RotatedFiles
	// while the audit lock is held. Candidates must still be its oldest prefix.
	ExpectedRotatedFiles []string
}

PruneOptions controls rotated audit log pruning. Callers remain responsible for completing their R3 authorization before setting Confirm.

type PruneResult

type PruneResult struct {
	Candidates      []string             `json:"candidates"`
	DeletedFiles    []string             `json:"deletedFiles"`
	Started         bool                 `json:"started"`
	CheckpointState PruneCheckpointState `json:"checkpointState"`
}

PruneResult describes the durable progress of PruneRotatedFiles. DeletedFiles contains only removals followed by the platform parent durability step: directory sync on POSIX, and completed removal on Windows. Started is true once the call may have changed persistent state.

func PruneRotatedFiles

func PruneRotatedFiles(
	path string,
	candidates []string,
	opts PruneOptions,
) (PruneResult, error)

PruneRotatedFiles deletes an explicitly selected, continuous oldest prefix of RotatedFiles. It validates the full history under the append lock. For v2 history it durably advances the authenticated checkpoint base before any deletion, allowing a partial deletion to be retried safely.

type RawRecord

type RawRecord struct {
	Line      string
	Timestamp time.Time
	EventType string
	Operator  string
}

RawRecord is one matched audit row plus the fields parsed for filtering.

type RawResult

type RawResult struct {
	Records          []RawRecord
	MalformedEntries int
}

RawResult aggregates matched raw rows and a count of unparseable lines skipped.

func QueryRaw

func QueryRaw(path string, filter Filter) (RawResult, error)

QueryRaw streams audit logs and returns matching raw JSONL rows.

type Result

type Result struct {
	Events           []Event
	MalformedEntries int
}

Result aggregates matched events and a count of unparseable lines skipped.

func Query

func Query(path string, filter Filter) (Result, error)

Query streams an audit log file, returning entries that satisfy the filter. File-not-exist is not an error: callers get an empty Result. Lines that fail JSON decode are skipped and counted in Result.MalformedEntries.

type VerifyFileResult

type VerifyFileResult struct {
	Path                     string `json:"path"`
	Total                    int    `json:"total"`
	Valid                    int    `json:"valid"`
	Malformed                int    `json:"malformed"`
	Quarantine               string `json:"quarantine,omitempty"`
	Repaired                 bool   `json:"repaired,omitempty"`
	SchemaError              int    `json:"schemaErrors,omitempty"`
	TimestampOrderViolations int    `json:"timestampOrderViolations,omitempty"`
	Authenticated            int    `json:"authenticated,omitempty"`
	LegacyUnauthenticated    int    `json:"legacyUnauthenticated,omitempty"`
	EncryptedOpaque          int    `json:"encryptedOpaque,omitempty"`
	IntegrityErrors          int    `json:"integrityErrors,omitempty"`
	SequenceViolations       int    `json:"sequenceViolations,omitempty"`
}

VerifyFileResult summarizes one active or rotated audit file.

type VerifyLockStatus

type VerifyLockStatus struct {
	Path    string `json:"path,omitempty"`
	Present bool   `json:"present"`
	Content string `json:"content,omitempty"`
}

VerifyLockStatus reports the active audit lock file if present.

type VerifyOptions

type VerifyOptions struct {
	Decrypt          bool
	PrivateKey       string
	Repair           bool
	Confirm          bool
	IntegrityKeyPath string
	// ExpectedRotatedFiles, when non-nil, must exactly match RotatedFiles
	// while the audit lock is held. It binds a preview to repair/verification.
	ExpectedRotatedFiles []string
}

VerifyOptions controls audit log verification.

type VerifyResult

type VerifyResult struct {
	Files                    []VerifyFileResult `json:"files"`
	Total                    int                `json:"total"`
	Valid                    int                `json:"valid"`
	Malformed                int                `json:"malformed"`
	SchemaErrors             int                `json:"schemaErrors"`
	TimestampOrderViolations int                `json:"timestampOrderViolations"`
	Authenticated            int                `json:"authenticated"`
	LegacyUnauthenticated    int                `json:"legacyUnauthenticated"`
	EncryptedOpaque          int                `json:"encryptedOpaque"`
	IntegrityErrors          int                `json:"integrityErrors"`
	SequenceViolations       int                `json:"sequenceViolations"`
	CheckpointViolations     int                `json:"checkpointViolations"`
	TruncationDetected       bool               `json:"truncationDetected"`
	Lock                     VerifyLockStatus   `json:"lock"`
}

VerifyResult summarizes audit log verification.

func Verify

func Verify(path string, opts VerifyOptions) (VerifyResult, error)

Verify scans active and rotated audit files under the same lock used by append, authenticating v2 envelopes before inspecting their payloads.

func (VerifyResult) HasProblems

func (result VerifyResult) HasProblems() bool

HasProblems reports whether verification found malformed, invalid, or discontinuous audit history.

Jump to

Keyboard shortcuts

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