Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Redact known secret shapes from action audit log persistence

rcourtman643d5f299211
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index b181182c12..4a0624422a 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -492,7 +492,26 @@ AI-only summary payloads, or page-local heuristics.
`frontend-modern/src/features/infrastructure/useInfrastructurePageState.ts`
and the unified-resource selectors it composes. The header must not become
a second state owner, scope banner, or provider-local filter surface.
-20. Keep governed-action drift refusal canonical in
+20. Keep audit-log persistence credential-safe.
+ `internal/unifiedresources/audit_redaction.go` provides
+ `RedactAuditText` and `RedactAuditRecord`, and every
+ `ActionAuditRecord` persistence boundary in
+ `internal/unifiedresources/store.go` (`RecordActionAudit`,
+ `RecordActionExecutionStart`, `RecordActionExecutionResult` for both
+ the SQLite and in-memory store implementations) must call
+ `RedactAuditRecord` before writing. Operators sometimes paste
+ secrets into a natural-language `reason`, and command output
+ sometimes echoes tokens; both must be scrubbed to redaction
+ markers (`[redacted]`, `[redacted-secret]`,
+ `[redacted-credentials]`) before plaintext SQL persistence.
+ `Plan`, `Approvals`, and identity fields are produced by Pulse
+ rather than operators or external command output and must be left
+ untouched by redaction (mutating them would break the
+ `PlanHash`-based drift detection contract). The redactor set is
+ intentionally narrower than the patrol-failure redactor: arbitrary
+ URLs are preserved so operators can reference runbooks, ticket
+ links, and GitHub issues in audit reasons.
+21. Keep governed-action drift refusal canonical in
`internal/unifiedresources/actions.go`. `ErrActionPlanDrift` is the
error any broker must return when the payload presented at execute
time hashes to anything different than the approval-recorded
diff --git a/internal/unifiedresources/audit_redaction.go b/internal/unifiedresources/audit_redaction.go
new file mode 100644
index 0000000000..c437d1d622
--- /dev/null
+++ b/internal/unifiedresources/audit_redaction.go
@@ -0,0 +1,93 @@
+package unifiedresources
+
+import (
+ "regexp"
+)
+
+// auditSecretRedactors scrubs well-known credential shapes from audit-log
+// text fields before persistence. The audit log is plaintext SQL; an
+// operator who pastes a secret into a natural-language `reason` field, or a
+// command output that echoes a token, must not have that secret persisted
+// unredacted.
+//
+// The set is intentionally narrower than the patrol-failure redactor in
+// internal/ai/patrol_runtime_failure.go: this redactor must not strip
+// arbitrary URLs, because operators legitimately reference public URLs
+// (runbooks, ticket links, GitHub issues) in audit reasons. It targets
+// only patterns that are very likely real secrets.
+var auditSecretRedactors = []struct {
+ pattern *regexp.Regexp
+ replacement string
+}{
+ // URL with embedded basic-auth credentials: https://user:pass@host
+ {
+ pattern: regexp.MustCompile(`(?i)(https?://)[^\s/@:]+:[^\s/@]+@`),
+ replacement: `${1}[redacted-credentials]@`,
+ },
+ // Authorization: Bearer <token> headers
+ {
+ pattern: regexp.MustCompile(`(?i)((?:authorization:\s*bearer|x-api-key:)\s+)[^\s,;]+`),
+ replacement: `${1}[redacted]`,
+ },
+ // Query-string secret params: ?key=..., &api_key=..., &access_token=...
+ {
+ pattern: regexp.MustCompile(`(?i)([?&](?:key|api_key|apikey|access_token|token)=)[^\s&"']+`),
+ replacement: `${1}[redacted]`,
+ },
+ // JSON-style secret fields: "api_key": "...", "token": "...", "password": "..."
+ {
+ pattern: regexp.MustCompile(`(?i)("(?:api[_-]?key|apikey|access[_-]?token|token|authorization|x-api-key|password|secret)"\s*:\s*")[^"]+`),
+ replacement: `${1}[redacted]`,
+ },
+ // Unquoted env-style or CLI-style secret assignments: PASSWORD=..., api_key=...
+ {
+ pattern: regexp.MustCompile(`(?i)\b((?:password|passwd|api[_-]?key|apikey|access[_-]?token|token|secret)\s*=\s*)\S+`),
+ replacement: `${1}[redacted]`,
+ },
+ // OpenAI/Anthropic-style API keys
+ {
+ pattern: regexp.MustCompile(`\bsk-[A-Za-z0-9_-]{8,}\b`),
+ replacement: `[redacted-secret]`,
+ },
+}
+
+// RedactAuditText returns the input with well-known credential shapes
+// replaced by [redacted] markers. Safe to call on operator-authored reasons,
+// command strings, and command output before persistence to the audit log.
+// Returns the original string when no redactor matches.
+func RedactAuditText(s string) string {
+ if s == "" {
+ return s
+ }
+ for _, redactor := range auditSecretRedactors {
+ s = redactor.pattern.ReplaceAllString(s, redactor.replacement)
+ }
+ return s
+}
+
+// RedactAuditRecord returns a copy of the input ActionAuditRecord with
+// known secret shapes scrubbed from the operator-authored reason, the
+// params map's string values, and the execution result's output. The
+// canonical Plan, Approvals, and identity fields are left alone — they
+// are produced by Pulse, not by operators or external command output.
+func RedactAuditRecord(record ActionAuditRecord) ActionAuditRecord {
+ record.Request.Reason = RedactAuditText(record.Request.Reason)
+ if len(record.Request.Params) > 0 {
+ redactedParams := make(map[string]any, len(record.Request.Params))
+ for k, v := range record.Request.Params {
+ if str, ok := v.(string); ok {
+ redactedParams[k] = RedactAuditText(str)
+ } else {
+ redactedParams[k] = v
+ }
+ }
+ record.Request.Params = redactedParams
+ }
+ if record.Result != nil {
+ redacted := *record.Result
+ redacted.Output = RedactAuditText(redacted.Output)
+ redacted.ErrorMessage = RedactAuditText(redacted.ErrorMessage)
+ record.Result = &redacted
+ }
+ return record
+}
diff --git a/internal/unifiedresources/audit_redaction_test.go b/internal/unifiedresources/audit_redaction_test.go
new file mode 100644
index 0000000000..64175c00f8
--- /dev/null
+++ b/internal/unifiedresources/audit_redaction_test.go
@@ -0,0 +1,151 @@
+package unifiedresources
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestRedactAuditText_StripsCommonSecretShapes(t *testing.T) {
+ cases := []struct {
+ name string
+ input string
+ mustStrip string
+ mustContain string // a marker the redactor inserts
+ }{
+ {
+ name: "openai-style API key",
+ input: "rotate sk-abc123def456ghi key after leak",
+ mustStrip: "sk-abc123def456ghi",
+ mustContain: "[redacted-secret]",
+ },
+ {
+ name: "Authorization Bearer header",
+ input: "curl -H 'Authorization: Bearer eyJabc.def.ghi' https://api.example.com/v1",
+ mustStrip: "eyJabc.def.ghi",
+ mustContain: "[redacted]",
+ },
+ {
+ name: "x-api-key header",
+ input: "headers: x-api-key: prod-secret-12345 caused 401",
+ mustStrip: "prod-secret-12345",
+ mustContain: "[redacted]",
+ },
+ {
+ name: "URL with embedded credentials",
+ input: "fetched from https://admin:[email protected]/api/snapshot to verify",
+ mustStrip: "hunter2",
+ mustContain: "[redacted-credentials]",
+ },
+ {
+ name: "query string secret param",
+ input: "called https://api.example.com/v1/items?api_key=verysecret&limit=10",
+ mustStrip: "verysecret",
+ mustContain: "[redacted]",
+ },
+ {
+ name: "JSON-style token field",
+ input: `payload {"name":"app","token":"sup3rs3cret","tier":"pro"}`,
+ mustStrip: "sup3rs3cret",
+ mustContain: "[redacted]",
+ },
+ {
+ name: "env-style password assignment",
+ input: "ran: PASSWORD=hunter2 service start",
+ mustStrip: "hunter2",
+ mustContain: "[redacted]",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := RedactAuditText(tc.input)
+ if strings.Contains(got, tc.mustStrip) {
+ t.Fatalf("expected secret %q to be stripped, got: %s", tc.mustStrip, got)
+ }
+ if !strings.Contains(got, tc.mustContain) {
+ t.Fatalf("expected redaction marker %q, got: %s", tc.mustContain, got)
+ }
+ })
+ }
+}
+
+func TestRedactAuditText_LeavesPublicURLsAlone(t *testing.T) {
+ // Operators legitimately reference runbooks, ticket links, and
+ // GitHub issues in audit reasons. The redactor must NOT strip
+ // arbitrary URLs — only URLs with embedded credentials.
+ input := "see https://runbook.example.com/restart-procedure or ticket https://github.com/org/repo/issues/123"
+ got := RedactAuditText(input)
+ if got != input {
+ t.Fatalf("expected public URLs preserved, got: %s", got)
+ }
+}
+
+func TestRedactAuditText_EmptyStringPassesThrough(t *testing.T) {
+ if got := RedactAuditText(""); got != "" {
+ t.Fatalf("expected empty string passthrough, got %q", got)
+ }
+}
+
+func TestRedactAuditRecord_ScrubsRequestAndResultStringFields(t *testing.T) {
+ now := time.Now().UTC()
+ record := ActionAuditRecord{
+ ID: "act-1",
+ CreatedAt: now,
+ UpdatedAt: now,
+ State: ActionStateCompleted,
+ Request: ActionRequest{
+ RequestID: "req-1",
+ ResourceID: "vm-100",
+ CapabilityName: "pulse_control",
+ // Operator-authored reason includes a secret they pasted.
+ Reason: "rotate the key sk-abc123def456 because it leaked into logs",
+ RequestedBy: "[email protected]",
+ Params: map[string]any{
+ "command": "curl -H 'Authorization: Bearer eyJsecret' https://api.example.com",
+ "targetType": "agent",
+ "approvalId": "approval-1",
+ "requestedBy": "pulse_control",
+ "retries": 3, // non-string param value left untouched
+ },
+ },
+ Plan: ActionPlan{
+ ActionID: "act-1",
+ RequestID: "req-1",
+ PlanHash: "deadbeef",
+ },
+ Result: actionResultStub(),
+ }
+ redacted := RedactAuditRecord(record)
+
+ if strings.Contains(redacted.Request.Reason, "sk-abc123def456") {
+ t.Fatalf("Reason still contains secret: %s", redacted.Request.Reason)
+ }
+ if !strings.Contains(redacted.Request.Reason, "[redacted-secret]") {
+ t.Fatalf("Reason missing redaction marker: %s", redacted.Request.Reason)
+ }
+ cmd, _ := redacted.Request.Params["command"].(string)
+ if strings.Contains(cmd, "eyJsecret") {
+ t.Fatalf("Params[command] still contains Bearer token: %s", cmd)
+ }
+ if got := redacted.Request.Params["retries"]; got != 3 {
+ t.Fatalf("non-string Params value mutated: %#v", got)
+ }
+ // Plan must be untouched — it is produced by Pulse, not operators.
+ if redacted.Plan.PlanHash != "deadbeef" {
+ t.Fatalf("Plan hash mutated: %s", redacted.Plan.PlanHash)
+ }
+ // Result.Output redacted
+ if strings.Contains(redacted.Result.Output, "hunter2") {
+ t.Fatalf("Result.Output still contains password: %s", redacted.Result.Output)
+ }
+}
+
+// actionResultStub builds a result fixture with secret-shaped output and
+// error message for the audit-record redaction test.
+func actionResultStub() *ExecutionResult {
+ return &ExecutionResult{
+ Success: false,
+ Output: "ran: PASSWORD=hunter2 service start && exit 1",
+ ErrorMessage: "auth failed: api_key=leakedkey not accepted",
+ }
+}
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index adcd70a774..7dc704a197 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -365,6 +365,17 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
"RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error",
"func (s *SQLiteResourceStore) RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error",
"func (s *SQLiteResourceStore) RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error",
+ // Audit-log secret redaction must run at every persistence
+ // boundary so operator-authored reasons and command output do
+ // not leak credentials into the plaintext SQL audit history.
+ // Pin the call sites in store.go to keep redaction wired even
+ // across future refactors.
+ "record = RedactAuditRecord(normalized)",
+ "normalizedRecord = RedactAuditRecord(normalizedRecord)",
+ },
+ filepath.Join(".", "audit_redaction.go"): {
+ "func RedactAuditText(s string) string",
+ "func RedactAuditRecord(record ActionAuditRecord) ActionAuditRecord",
},
filepath.Join("..", "api", "actions.go"): {
"type ActionExecutor interface",
diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.go
index eb472c1541..6564473cf8 100644
--- a/internal/unifiedresources/registry_test.go
+++ b/internal/unifiedresources/registry_test.go
@@ -10,6 +10,62 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"
)
+// TestMemoryStore_RecordActionAuditAppliesRedaction is an integration check
+// at the registry-store boundary. The MemoryStore is the backing store the
+// registry uses in tests and contract examples, and operator-authored audit
+// fields must be scrubbed of secret shapes uniformly across both SQLite and
+// in-memory persistence so test fixtures cannot accidentally exercise an
+// unredacted path that production never sees.
+func TestMemoryStore_RecordActionAuditAppliesRedaction(t *testing.T) {
+ store := NewMemoryStore()
+ now := time.Now().UTC()
+ record := ActionAuditRecord{
+ ID: "act-redact",
+ CreatedAt: now,
+ UpdatedAt: now,
+ State: ActionStatePlanned,
+ Request: ActionRequest{
+ RequestID: "req-redact",
+ ResourceID: "vm-100",
+ CapabilityName: "pulse_control",
+ Reason: "rotate sk-leakedkey1234567 because it appeared in logs",
+ RequestedBy: "[email protected]",
+ Params: map[string]any{
+ "command": "curl -H 'Authorization: Bearer eyJleak' https://api.example.com",
+ "targetType": "agent",
+ },
+ },
+ Plan: ActionPlan{
+ ActionID: "act-redact",
+ RequestID: "req-redact",
+ Allowed: true,
+ PlanHash: "deadbeef",
+ },
+ }
+ if err := store.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit: %v", err)
+ }
+
+ stored, ok, err := store.GetActionAudit("act-redact")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok {
+ t.Fatalf("expected stored audit, got none")
+ }
+ if strings.Contains(stored.Request.Reason, "sk-leakedkey1234567") {
+ t.Fatalf("Reason still contains secret after persistence: %s", stored.Request.Reason)
+ }
+ if cmd, _ := stored.Request.Params["command"].(string); strings.Contains(cmd, "eyJleak") {
+ t.Fatalf("Params[command] still contains Bearer token: %s", cmd)
+ }
+ // Plan fields must be untouched so PlanHash-based drift detection
+ // continues to work.
+ if stored.Plan.PlanHash != "deadbeef" {
+ t.Fatalf("Plan.PlanHash mutated by redaction: %s", stored.Plan.PlanHash)
+ }
+}
+
func TestResourceRegistry_ListByType(t *testing.T) {
rr := NewRegistry(nil)
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index ea696a4cd1..2d447c63cd 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -951,7 +951,11 @@ func (s *SQLiteResourceStore) RecordActionAudit(record ActionAuditRecord) error
if err != nil {
return err
}
- record = normalized
+ // Redact known secret shapes from operator-authored text and command
+ // output before persisting. The audit log is plaintext SQL; raw
+ // secrets pasted into a reason field or echoed in command output
+ // must not be retained.
+ record = RedactAuditRecord(normalized)
s.mu.Lock()
defer s.mu.Unlock()
@@ -1124,6 +1128,9 @@ func (s *SQLiteResourceStore) RecordActionExecutionStart(record ActionAuditRecor
if normalizedEvent.ActionID != normalizedRecord.ID {
return fmt.Errorf("action execution start event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
}
+ // Redact secret shapes from operator-authored fields and command
+ // output before persisting; see RecordActionAudit for the contract.
+ normalizedRecord = RedactAuditRecord(normalizedRecord)
s.mu.Lock()
defer s.mu.Unlock()
@@ -1180,6 +1187,9 @@ func (s *SQLiteResourceStore) RecordActionExecutionResult(record ActionAuditReco
if normalizedEvent.ActionID != normalizedRecord.ID {
return fmt.Errorf("action execution result event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
}
+ // Redact secret shapes from operator-authored fields and command
+ // output before persisting; see RecordActionAudit for the contract.
+ normalizedRecord = RedactAuditRecord(normalizedRecord)
s.mu.Lock()
defer s.mu.Unlock()
@@ -1630,7 +1640,12 @@ func (m *MemoryStore) RecordActionAudit(record ActionAuditRecord) error {
if err != nil {
return err
}
- record = normalized
+ // Redact secret shapes from operator-authored fields and command
+ // output before persisting in-memory too. The MemoryStore is used in
+ // tests and contract examples; redaction must apply uniformly so test
+ // fixtures cannot accidentally exercise an unredacted persistence
+ // path that production never sees.
+ record = RedactAuditRecord(normalized)
m.mu.Lock()
defer m.mu.Unlock()
@@ -1707,6 +1722,9 @@ func (m *MemoryStore) RecordActionExecutionStart(record ActionAuditRecord, event
if normalizedEvent.ActionID != normalizedRecord.ID {
return fmt.Errorf("action execution start event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
}
+ // Redact secret shapes from operator-authored fields and command
+ // output before persisting; see RecordActionAudit for the contract.
+ normalizedRecord = RedactAuditRecord(normalizedRecord)
m.mu.Lock()
defer m.mu.Unlock()
@@ -1746,6 +1764,9 @@ func (m *MemoryStore) RecordActionExecutionResult(record ActionAuditRecord, even
if normalizedEvent.ActionID != normalizedRecord.ID {
return fmt.Errorf("action execution result event id %q does not match action audit id %q", normalizedEvent.ActionID, normalizedRecord.ID)
}
+ // Redact secret shapes from operator-authored fields and command
+ // output before persisting; see RecordActionAudit for the contract.
+ normalizedRecord = RedactAuditRecord(normalizedRecord)
m.mu.Lock()
defer m.mu.Unlock()