Files
archie/modules/audit/audit.go
T

247 lines
6.2 KiB
Go

// Package audit records and exports append-only security and operational audit
// events, backed by PostgreSQL and a structured stdout log stream.
package audit
import (
"bytes"
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"reflect"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"go.opentelemetry.io/otel/trace"
"github.com/samcharles93/archie-core/internal/platform/auditjson"
"github.com/samcharles93/archie-core/modules/audit/internal/store"
)
const (
defaultLimit = 100
maxLimit = 1000
)
// ErrInvalidFilter indicates invalid query or export filter parameters.
var ErrInvalidFilter = errors.New("invalid audit filter")
// Event is a single immutable audit record.
type Event struct {
ID uuid.UUID `json:"id"`
OrgID string `json:"org_id"`
At time.Time `json:"at"`
Category string `json:"category"`
Action string `json:"action"`
ActorID string `json:"actor_id"`
ActorKind string `json:"actor_kind,omitzero"`
ResourceKind string `json:"resource_kind,omitzero"`
ResourceID string `json:"resource_id,omitzero"`
Outcome string `json:"outcome"`
TraceID string `json:"trace_id,omitzero"`
Detail any `json:"detail,omitzero"`
}
// Filter narrows audit event queries.
type Filter struct {
OrgID string
Category string
Action string
Actor string
Since time.Time
Until time.Time
Limit int
Offset int
}
// Validate checks filter bounds and time range ordering.
func (f Filter) Validate() error {
if f.Limit < 1 || f.Limit > maxLimit {
return fmt.Errorf("%w: limit must be between 1 and %d", ErrInvalidFilter, maxLimit)
}
if f.Offset < 0 {
return fmt.Errorf("%w: offset must be non-negative", ErrInvalidFilter)
}
if !f.Since.IsZero() && !f.Until.IsZero() && f.Since.After(f.Until) {
return fmt.Errorf("%w: since must not be after until", ErrInvalidFilter)
}
return nil
}
type auditStore interface {
Insert(ctx context.Context, row store.EventRow) error
List(ctx context.Context, f store.Filter) ([]store.EventRow, error)
}
// Recorder records immutable security and operational audit events.
type Recorder interface {
Record(ctx context.Context, e Event) error
}
// Emit forwards e to r when r is configured, logging any persistence error to
// log without failing the caller's operation.
func Emit(ctx context.Context, r Recorder, log *slog.Logger, e Event) {
if r == nil {
return
}
v := reflect.ValueOf(r)
if v.Kind() == reflect.Pointer && v.IsNil() {
return
}
if m, ok := r.(*Module); ok && m.store == nil {
return
}
if err := r.Record(ctx, e); err != nil && log != nil {
log.WarnContext(ctx, "record audit event", "category", e.Category, "action", e.Action, "error", err)
}
}
// Module records and serves one organisation's append-only audit stream.
type Module struct {
orgID string
store auditStore
log *slog.Logger
}
// NewModule returns the audit module for orgID.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
var st auditStore
if db != nil {
st = store.New(db)
}
return &Module{orgID: orgID, store: st, log: log}
}
// Record redacts e.Detail, persists the event to audit.events, and emits a
// structured JSON log record tagged with "audit", true.
func (m *Module) Record(ctx context.Context, e Event) error {
if m.store == nil {
return errors.New("audit store is not configured")
}
if e.Category == "" || e.Action == "" || e.ActorID == "" || e.Outcome == "" {
return errors.New("audit event requires category, action, actor_id, and outcome")
}
if e.ID == uuid.Nil {
e.ID = uuid.New()
}
if e.OrgID == "" {
e.OrgID = m.orgID
}
if e.At.IsZero() {
e.At = time.Now().UTC()
}
if e.TraceID == "" {
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
e.TraceID = sc.TraceID().String()
}
}
detail := redactDetail(e.Detail)
row := store.EventRow{
ID: e.ID,
OrgID: e.OrgID,
At: e.At.UTC(),
Category: e.Category,
Action: e.Action,
ActorID: e.ActorID,
ActorKind: e.ActorKind,
ResourceKind: e.ResourceKind,
ResourceID: e.ResourceID,
Outcome: e.Outcome,
TraceID: e.TraceID,
Detail: detail,
}
if err := m.store.Insert(ctx, row); err != nil {
return err
}
if m.log != nil {
m.log.InfoContext(ctx, "audit event",
"audit", true,
"audit_id", row.ID.String(),
"org_id", row.OrgID,
"at", row.At.Format(time.RFC3339Nano),
"category", row.Category,
"action", row.Action,
"actor_id", row.ActorID,
"actor_kind", row.ActorKind,
"resource_kind", row.ResourceKind,
"resource_id", row.ResourceID,
"outcome", row.Outcome,
"trace_id", row.TraceID,
"detail", detail,
)
}
return nil
}
// List returns matching audit events ordered newest first.
func (m *Module) List(ctx context.Context, f Filter) ([]Event, error) {
if m.store == nil {
return nil, errors.New("audit store is not configured")
}
if f.OrgID == "" {
f.OrgID = m.orgID
}
if f.Limit == 0 {
f.Limit = defaultLimit
}
if err := f.Validate(); err != nil {
return nil, err
}
rows, err := m.store.List(ctx, store.Filter{
OrgID: f.OrgID,
Category: f.Category,
Action: f.Action,
ActorID: f.Actor,
Since: f.Since,
Until: f.Until,
Limit: f.Limit,
Offset: f.Offset,
})
if err != nil {
return nil, err
}
return eventsFromRows(rows), nil
}
func redactDetail(v any) jsontext.Value {
if v == nil {
return jsontext.Value(`{}`)
}
if raw, ok := v.(jsontext.Value); ok && len(bytes.TrimSpace(raw)) == 0 {
return jsontext.Value(`{}`)
}
payload := auditjson.FromValue(v)
if !payload.Truncated && len(payload.JSON) > 0 {
return payload.JSON
}
raw, err := json.Marshal(payload)
if err != nil {
return jsontext.Value(`{}`)
}
return raw
}
func eventsFromRows(rows []store.EventRow) []Event {
out := make([]Event, 0, len(rows))
for _, r := range rows {
out = append(out, Event{
ID: r.ID,
OrgID: r.OrgID,
At: r.At,
Category: r.Category,
Action: r.Action,
ActorID: r.ActorID,
ActorKind: r.ActorKind,
ResourceKind: r.ResourceKind,
ResourceID: r.ResourceID,
Outcome: r.Outcome,
TraceID: r.TraceID,
Detail: r.Detail,
})
}
return out
}