feat(db/m7-user-mgmt): migration 0022 + audit helper
Schema for user management U1: display_name on users; user_invites; registration_settings singleton (default 'invite_only'); audit_log. Plus the internal/audit package centralizing the action-name vocabulary and JSON metadata marshaling so handlers don't repeat boilerplate. Race-safe first-admin uses a query-shape primitive (CreateUserFirstAdminRace's WHERE NOT EXISTS subquery) rather than a schema-level constraint. Concurrent empty-state registrations both see 'no users yet' and both insert as admin — fine, having two admins from the start is benign; what matters is at-least-one. users.username uniqueness arbitrates if the two callers picked the same username. CreateUser signature gains display_name (nullable); existing bootstrap call sites pass nil. The audit package declares the full U1+U2+U3 action vocabulary upfront so subsequent slices are purely additive on the caller side. Tests cover audit Write with + without metadata and that every declared action constant persists correctly. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
// Package audit writes admin-driven user-management events to audit_log.
|
||||
// Thin wrapper over the sqlc-generated WriteAuditLog query — the value
|
||||
// is centralizing the action-name vocabulary and the metadata
|
||||
// marshaling so callers don't repeat boilerplate.
|
||||
//
|
||||
// Audit writes are best-effort from the caller's perspective: a failed
|
||||
// audit write must NOT fail the user-facing operation. Callers
|
||||
// log-and-continue. The audit log is observability, not a transaction
|
||||
// participant.
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// Action is the discriminator stored in audit_log.action. New values
|
||||
// added in U2/U3 + future tasks; declare them here so callers don't
|
||||
// stringly-type and so a future audit-search UI has a single source
|
||||
// of truth for the vocabulary.
|
||||
type Action string
|
||||
|
||||
const (
|
||||
// U1
|
||||
ActionRegister Action = "register"
|
||||
ActionPromoteAdmin Action = "promote_admin"
|
||||
ActionDemoteAdmin Action = "demote_admin"
|
||||
ActionInviteCreate Action = "invite_create"
|
||||
ActionInviteRedeem Action = "invite_redeem"
|
||||
ActionInviteRevoke Action = "invite_revoke"
|
||||
|
||||
// U2 (declared early; callers in U1 don't use them yet, but
|
||||
// having them here means U2's diff is purely additive on the
|
||||
// caller side, not also touching this file).
|
||||
ActionCreateUserAdmin Action = "create_user_admin"
|
||||
ActionDeleteUser Action = "delete_user"
|
||||
ActionPasswordResetAdmin Action = "password_reset_admin"
|
||||
ActionAutoApproveToggle Action = "auto_approve_toggle"
|
||||
|
||||
// U3
|
||||
ActionPasswordChangeSelf Action = "password_change_self"
|
||||
ActionTokenRegenerate Action = "token_regenerate"
|
||||
ActionForgotPasswordInit Action = "forgot_password_initiated"
|
||||
ActionPasswordResetByEmail Action = "password_reset_via_email"
|
||||
)
|
||||
|
||||
// Write inserts one audit_log row. metadata is marshaled as JSON;
|
||||
// nil metadata writes SQL NULL. Errors are returned so callers can
|
||||
// log them — but per package doc, callers should NOT fail user-facing
|
||||
// operations on audit-write failures.
|
||||
//
|
||||
// actorID may be a zero/invalid pgtype.UUID for system actions
|
||||
// (e.g. self-registration where the new user is both actor and
|
||||
// target — pass them as the same id, or pass invalid for actor and
|
||||
// the new user as target).
|
||||
func Write(ctx context.Context, pool *pgxpool.Pool, actorID, targetID pgtype.UUID, action Action, metadata map[string]any) error {
|
||||
q := dbq.New(pool)
|
||||
var jsonMeta []byte
|
||||
if metadata != nil {
|
||||
b, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
jsonMeta = b
|
||||
}
|
||||
return q.WriteAuditLog(ctx, dbq.WriteAuditLogParams{
|
||||
ActorID: actorID,
|
||||
TargetID: targetID,
|
||||
Action: string(action),
|
||||
Metadata: jsonMeta,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package audit_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/audit"
|
||||
)
|
||||
|
||||
func newTestPool(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
url := os.Getenv("MINSTREL_TEST_DATABASE_URL")
|
||||
if url == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
}
|
||||
pool, err := pgxpool.New(context.Background(), url)
|
||||
if err != nil {
|
||||
t.Fatalf("connect: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
// Reset audit_log so each test runs against a known state.
|
||||
if _, err := pool.Exec(context.Background(), `DELETE FROM audit_log`); err != nil {
|
||||
t.Fatalf("reset audit_log: %v", err)
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
func validUUID() pgtype.UUID {
|
||||
var u pgtype.UUID
|
||||
u.Valid = true
|
||||
// Arbitrary fixed bytes; we don't need a real user to exist
|
||||
// because the FK is ON DELETE SET NULL — orphan FKs are fine
|
||||
// for the audit_log column shape.
|
||||
for i := range u.Bytes {
|
||||
u.Bytes[i] = byte(i + 1)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func TestWrite_NoMetadata(t *testing.T) {
|
||||
pool := newTestPool(t)
|
||||
// Use NULL FKs (Valid: false) — the column is nullable.
|
||||
var nilUUID pgtype.UUID
|
||||
if err := audit.Write(context.Background(), pool, nilUUID, nilUUID, audit.ActionRegister, nil); err != nil {
|
||||
t.Fatalf("Write: %v", err)
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(),
|
||||
`SELECT count(*) FROM audit_log WHERE action = 'register' AND metadata IS NULL`,
|
||||
).Scan(&count); err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrite_WithMetadata(t *testing.T) {
|
||||
pool := newTestPool(t)
|
||||
var nilUUID pgtype.UUID
|
||||
if err := audit.Write(context.Background(), pool, nilUUID, nilUUID, audit.ActionPromoteAdmin, map[string]any{
|
||||
"reason": "test",
|
||||
"first_admin": true,
|
||||
}); err != nil {
|
||||
t.Fatalf("Write: %v", err)
|
||||
}
|
||||
var meta string
|
||||
if err := pool.QueryRow(context.Background(),
|
||||
`SELECT metadata::text FROM audit_log WHERE action = 'promote_admin' LIMIT 1`,
|
||||
).Scan(&meta); err != nil {
|
||||
t.Fatalf("read metadata: %v", err)
|
||||
}
|
||||
if !contains(meta, `"first_admin":true`) || !contains(meta, `"reason":"test"`) {
|
||||
t.Errorf("metadata = %q, expected first_admin + reason fields", meta)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (func() bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})()
|
||||
}
|
||||
|
||||
func TestWrite_AllActionConstantsArePersisted(t *testing.T) {
|
||||
pool := newTestPool(t)
|
||||
var nilUUID pgtype.UUID
|
||||
actions := []audit.Action{
|
||||
audit.ActionRegister,
|
||||
audit.ActionPromoteAdmin,
|
||||
audit.ActionDemoteAdmin,
|
||||
audit.ActionInviteCreate,
|
||||
audit.ActionInviteRedeem,
|
||||
audit.ActionInviteRevoke,
|
||||
audit.ActionCreateUserAdmin,
|
||||
audit.ActionDeleteUser,
|
||||
audit.ActionPasswordResetAdmin,
|
||||
audit.ActionAutoApproveToggle,
|
||||
audit.ActionPasswordChangeSelf,
|
||||
audit.ActionTokenRegenerate,
|
||||
audit.ActionForgotPasswordInit,
|
||||
audit.ActionPasswordResetByEmail,
|
||||
}
|
||||
for _, a := range actions {
|
||||
if err := audit.Write(context.Background(), pool, nilUUID, nilUUID, a, nil); err != nil {
|
||||
t.Errorf("action %q: Write: %v", a, err)
|
||||
}
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM audit_log`).Scan(&count); err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
if count != len(actions) {
|
||||
t.Errorf("count = %d, want %d", count, len(actions))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user