Files
archie/modules/audit/internal/store/store.go
T

96 lines
2.6 KiB
Go

// Package store holds the SQL persistence for append-only audit events.
package store
import (
"context"
"encoding/json/jsontext"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// EventRow is one row in audit.events.
type EventRow struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
At time.Time `db:"at"`
Category string `db:"category"`
Action string `db:"action"`
ActorID string `db:"actor_id"`
ActorKind string `db:"actor_kind"`
ResourceKind string `db:"resource_kind"`
ResourceID string `db:"resource_id"`
Outcome string `db:"outcome"`
TraceID string `db:"trace_id"`
Detail jsontext.Value `db:"detail"`
}
// Filter narrows List queries on audit.events.
type Filter struct {
OrgID string
Category string
Action string
ActorID string
Since time.Time
Until time.Time
Limit int
Offset int
}
// Store persists and queries audit.events.
type Store struct {
db *sqlx.DB
}
// New returns a Store backed by db.
func New(db *sqlx.DB) *Store {
return &Store{db: db}
}
// Insert appends row to audit.events.
func (s *Store) Insert(ctx context.Context, row EventRow) error {
if _, err := s.db.ExecContext(ctx, `
INSERT INTO audit.events (
id, org_id, at, category, action, actor_id, actor_kind,
resource_kind, resource_id, outcome, trace_id, detail
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
row.ID, row.OrgID, row.At, row.Category, row.Action, row.ActorID,
row.ActorKind, row.ResourceKind, row.ResourceID, row.Outcome, row.TraceID, row.Detail,
); err != nil {
return fmt.Errorf("insert audit event: %w", err)
}
return nil
}
// List returns events matching f ordered newest first.
func (s *Store) List(ctx context.Context, f Filter) ([]EventRow, error) {
var out []EventRow
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, at, category, action, actor_id, actor_kind,
resource_kind, resource_id, outcome, trace_id, detail
FROM audit.events
WHERE org_id = $1
AND ($2 = '' OR category = $2)
AND ($3 = '' OR action = $3)
AND ($4 = '' OR actor_id = $4)
AND ($5::timestamptz IS NULL OR at >= $5)
AND ($6::timestamptz IS NULL OR at < $6)
ORDER BY at DESC, id DESC
LIMIT $7 OFFSET $8`,
f.OrgID, f.Category, f.Action, f.ActorID,
nullTime(f.Since), nullTime(f.Until), f.Limit, f.Offset,
); err != nil {
return nil, fmt.Errorf("list audit events: %w", err)
}
return out, nil
}
func nullTime(t time.Time) *time.Time {
if t.IsZero() {
return nil
}
return &t
}