Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Canonicalize pre-upgrade action audit rows at store open
rcourtman208c77d93249
diff --git a/internal/unifiedresources/legacy_expiry_repro_test.go b/internal/unifiedresources/legacy_expiry_repro_test.gonew file mode 100644index 0000000000..2394c78824--- /dev/null+++ b/internal/unifiedresources/legacy_expiry_repro_test.go@@ -0,0 +1,86 @@+package unifiedresources++import (+ "testing"+ "time"+)++// Reproduces the v6.0.5 -> v6.1 upgrade shape: a chat-approval audit row+// whose JSON was written by v6.0.5 (no policyDecision, no approvalRequirement,+// no origin) and left in pending_approval. Lifecycle transitions CAS on the+// stored JSON bytes, so without open-time canonicalization the expiry sweep+// matches zero rows and the record is stranded in the open Actions inbox.+func TestExpireActionAuditsClearsLegacyPendingApproval(t *testing.T) {+ dir := t.TempDir()+ store, err := NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }++ plannedAt := time.Now().UTC().Add(-4 * 24 * time.Hour)+ expiresAt := plannedAt.Add(5 * time.Minute)+ requestJSON := `{+ "requestId": "req-legacy-1",+ "resourceId": "pve02:204",+ "capabilityName": "pulse.control",+ "params": {"command": "start", "targetType": "vm", "targetId": "204", "approvalId": "req-legacy-1", "requestedBy": "assistant:pulse"},+ "reason": "start guest XVM-WIN11-DEV",+ "requestedBy": "assistant:pulse"+ }`+ planJSON := `{+ "actionId": "legacy-approval-1",+ "requestId": "req-legacy-1",+ "allowed": true,+ "requiresApproval": true,+ "approvalPolicy": "admin",+ "rollbackAvailable": true,+ "message": "start guest XVM-WIN11-DEV",+ "plannedAt": "` + plannedAt.Format(time.RFC3339Nano) + `",+ "expiresAt": "` + expiresAt.Format(time.RFC3339Nano) + `",+ "resourceVersion": "",+ "policyVersion": "",+ "planHash": "sha256:legacyhash",+ "preflight": {+ "target": "vm pve02:204",+ "currentState": "Resolved approval target: vm / pve02 / pve02:204.",+ "intendedChange": "start guest XVM-WIN11-DEV",+ "dryRunAvailable": false,+ "generatedAt": "` + plannedAt.Format(time.RFC3339Nano) + `"+ }+ }`+ if _, err := store.db.Exec(+ `INSERT INTO action_audits (id, action_id, canonical_id, request_id, created_at, updated_at, state, decision_revision, request_json, plan_json, approvals_json, result_json, verification_outcome_json, origin_json)+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL, NULL, '', NULL)`,+ "legacy-approval-1", "legacy-approval-1", "pve02:204", "req-legacy-1",+ plannedAt, plannedAt, string(ActionStatePending), requestJSON, planJSON,+ ); err != nil {+ t.Fatalf("insert legacy row: %v", err)+ }+ if err := store.Close(); err != nil {+ t.Fatalf("close store: %v", err)+ }++ // Reopen: the upgrade path. Open-time canonicalization must rewrite the+ // legacy JSON so lifecycle CAS transitions can find the row again.+ store, err = NewSQLiteResourceStore(dir, "default")+ if err != nil {+ t.Fatal(err)+ }+ defer store.Close()++ expired, err := store.ExpireActionAudits(time.Now().UTC(), 500)+ if err != nil {+ t.Fatalf("sweep: %v", err)+ }+ if len(expired) != 1 {+ t.Fatalf("expected legacy pending approval to expire, got %d expired", len(expired))+ }++ current, found, err := store.GetActionAudit("legacy-approval-1")+ if err != nil || !found {+ t.Fatalf("get after sweep: found=%v err=%v", found, err)+ }+ if current.State != ActionStateExpired {+ t.Fatalf("state after sweep = %q, want %q", current.State, ActionStateExpired)+ }+}diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.goindex 4130e12e11..f1d14e4cfb 100644--- a/internal/unifiedresources/store.go+++ b/internal/unifiedresources/store.go@@ -594,6 +594,9 @@ func (s *SQLiteResourceStore) initSchema() error {if err := s.migrateActionAuditRedaction(); err != nil {return err}+ if err := s.migrateActionAuditCanonicalization(); err != nil {+ return err+ }return nil}@@ -744,6 +747,100 @@ func (s *SQLiteResourceStore) migrateActionLifecycleEventsSchema() error {return nil}+// migrateActionAuditCanonicalization rewrites non-terminal action audit rows+// whose persisted JSON predates the current schema shape. Lifecycle+// transitions guard against concurrent writers by comparing the stored+// request/plan/origin JSON byte-for-byte (updateActionAuditSQL); rows written+// by an older release re-marshal differently after read-time normalization,+// so every transition on them — including the expiry sweep — matches zero+// rows and is treated as already-final, stranding the row in the open inbox.+// Rewriting the stored bytes to the current canonical form once at open+// restores the compare-and-swap for pre-upgrade rows.+func (s *SQLiteResourceStore) migrateActionAuditCanonicalization() error {+ rows, err := s.db.Query(`+ SELECT id, request_json, plan_json, COALESCE(origin_json, '')+ FROM action_audits+ WHERE state IN (?, ?, ?, ?)+ `, ActionStatePlanned, ActionStatePending, ActionStateApproved, ActionStateExecuting)+ if err != nil {+ return fmt.Errorf("query action audit canonicalization rows: %w", err)+ }+ type storedRow struct {+ id string+ requestJSON string+ planJSON string+ originJSON string+ }+ var stored []storedRow+ for rows.Next() {+ var row storedRow+ if err := rows.Scan(&row.id, &row.requestJSON, &row.planJSON, &row.originJSON); err != nil {+ rows.Close()+ return fmt.Errorf("scan action audit canonicalization row: %w", err)+ }+ stored = append(stored, row)+ }+ if err := rows.Close(); err != nil {+ return fmt.Errorf("close action audit canonicalization rows: %w", err)+ }+ type canonicalUpdate struct {+ id string+ args []any+ }+ var updates []canonicalUpdate+ for _, row := range stored {+ record, found, err := getActionAuditFrom(s.db, row.id)+ if err != nil || !found {+ if err != nil {+ return fmt.Errorf("read action audit for canonicalization %q: %w", row.id, err)+ }+ continue+ }+ if _, strictErr := NormalizeActionAuditRecord(record); strictErr != nil {+ // The row cannot be expressed in the current shape even with+ // read-time backfills; leave it as stored rather than guessing.+ log.Printf("[WARN] unified_resources: action audit %q cannot be canonicalized and will not transition: %v", row.id, strictErr)+ continue+ }+ args, argsErr := actionAuditSQLArgs(record)+ if argsErr != nil {+ return fmt.Errorf("marshal action audit for canonicalization %q: %w", row.id, argsErr)+ }+ if row.requestJSON == args[8] && row.planJSON == args[9] && row.originJSON == firstNonNilString(args[13]) {+ continue+ }+ updates = append(updates, canonicalUpdate{id: row.id, args: args})+ }+ if len(updates) == 0 {+ return nil+ }+ tx, err := s.db.Begin()+ if err != nil {+ return fmt.Errorf("begin action audit canonicalization: %w", err)+ }+ committed := false+ defer func() {+ if !committed {+ _ = tx.Rollback()+ }+ }()+ for _, update := range updates {+ if _, err := tx.Exec(`+ UPDATE action_audits+ SET request_json = ?, plan_json = ?, approvals_json = ?, result_json = ?, verification_outcome_json = ?, origin_json = ?+ WHERE id = ?+ `, update.args[8], update.args[9], update.args[10], update.args[11], update.args[12], update.args[13], update.id); err != nil {+ return fmt.Errorf("canonicalize action audit %q: %w", update.id, err)+ }+ }+ if err := tx.Commit(); err != nil {+ return fmt.Errorf("commit action audit canonicalization: %w", err)+ }+ committed = true+ log.Printf("[INFO] unified_resources: canonicalized %d pre-upgrade action audit row(s)", len(updates))+ return nil+}+func (s *SQLiteResourceStore) migrateActionAuditRedaction() error {rows, err := s.db.Query(`SELECT id, result_json