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.

Refuse action dispatch when resource is operator-locked against remediation

rcourtmane1103bf119c8
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index c49117986b..aa09f43353 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -596,7 +596,16 @@ new-finding path auto-dismisses with reason `expected_behavior`,
attributes the suppression on the lifecycle timeline
(`operator_state_cause: maintenance_window`, with
`maintenance_end_at` metadata), and persists the finding for audit
-history. The `IntentionallyOffline` branch is the indefinite
+history. The action broker (`executeCommandWithAudit` in
+`internal/ai/tools/action_audit.go`) consults the same
+`resource_operator_state` table on every dispatch and refuses with
+`unifiedresources.ErrResourceRemediationLocked` when the operator
+has set `NeverAutoRemediate=true` on the target resource. Refusal
+persists a Failed audit record whose `ErrorMessage` is prefixed
+`resource_remediation_locked:` so the audit timeline shows every
+refused dispatch, paralleling the `plan_drift:` shape from the drift
+guard. Operator state outranks per-action approval — the broker
+refuses even when the approval ID resolves and the plan hash matches. The `IntentionallyOffline` branch is the indefinite
counterpart — same auto-dismiss but with
`operator_state_cause: intentionally_offline` and no
`maintenance_end_at` field because the suppression has no scheduled
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 79efaf9039..755bb7e888 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -584,9 +584,15 @@ in `internal/api/resources_operator_state.go` is the operator-facing
consumer of this contract; the URL canonical_id always wins over the
body, server-side `setAt` / `setBy` populate from request time and
authenticated identity, and validation rejections surface a stable
-`operator_state_invalid` error code. Finding-suppression and
-action-broker integrations land in subsequent slices that consume the
-same `ResourceOperatorState` shape.
+`operator_state_invalid` error code. The action broker
+(`executeCommandWithAudit`) consults the same store on every dispatch
+and refuses with `ErrResourceRemediationLocked` when the operator has
+set `NeverAutoRemediate=true`; the refusal is persisted as a Failed
+audit record with `resource_remediation_locked:` prefix on the
+`ErrorMessage` so audit-UI filters and alert rules can branch on the
+stable token. Finding-suppression integrations consume the same
+`ResourceOperatorState` shape via the
+`ResourceOperatorStateProvider` interface in `internal/ai`.
`actions.go` now owns the canonical action preflight and audit-normalization
contract. Action plans must carry dry-run availability, safety checks, and
diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.go
index 81bcf72273..58e270bfac 100644
--- a/internal/ai/tools/action_audit.go
+++ b/internal/ai/tools/action_audit.go
@@ -135,6 +135,35 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
}
}
+ // Operator-set NeverAutoRemediate refusal: when the operator has
+ // flagged the target resource as never-auto-remediate, the broker
+ // must refuse the dispatch even with a valid approval and matching
+ // plan hash. The operator's per-resource intent outranks the
+ // per-action approval — this is the safety mechanism for "do not
+ // touch this resource even if you think you should." Persists a
+ // Failed audit record with `resource_remediation_locked:` prefix
+ // so the audit history shows every refused dispatch.
+ if locked, lockErr := e.isResourceRemediationLocked(resourceID); lockErr != nil {
+ log.Warn().Str("action_id", plan.ActionID).Err(lockErr).Msg("Operator-state lookup failed; allowing dispatch (fail-open) but logging")
+ } else if locked {
+ log.Warn().
+ Str("action_id", plan.ActionID).
+ Str("resource_id", resourceID).
+ Str("capability", capabilityName).
+ Msg("Refusing action execution: resource is operator-locked against automated remediation")
+ now := time.Now().UTC()
+ record.State = unifiedresources.ActionStateFailed
+ record.UpdatedAt = now
+ errMessage := fmt.Sprintf("resource_remediation_locked: %s", unifiedresources.ErrResourceRemediationLocked.Error())
+ record.Result = &unifiedresources.ExecutionResult{
+ Success: false,
+ ErrorMessage: errMessage,
+ }
+ e.recordActionAudit(record)
+ e.recordActionLifecycle(record.ID, unifiedresources.ActionStateFailed, requestedBy, "resource remediation lock refused")
+ return nil, unifiedresources.ErrResourceRemediationLocked
+ }
+
record, err := e.recordActionExecutionStart(record, approvalID, requestedBy, fmt.Sprintf("dispatching command to agent %s", agentID), planFromApproval)
if err != nil {
return nil, err
@@ -926,3 +955,29 @@ func approvalTimestamp(req *approval.ApprovalRequest) time.Time {
}
return req.DecidedAt.UTC()
}
+
+// isResourceRemediationLocked returns whether the operator has set
+// NeverAutoRemediate=true on the resource the dispatch targets.
+// Returns (false, nil) when no audit store is wired (degraded mode —
+// the fail-open posture is consistent with the rest of audit-store
+// callers in this file), when the resource has no operator state, or
+// when only IntentionallyOffline (without NeverAutoRemediate) is set.
+// Returns the error from the store on lookup failure so the caller can
+// log it; caller policy is fail-open on lookup error.
+func (e *PulseToolExecutor) isResourceRemediationLocked(resourceID string) (bool, error) {
+ if e == nil || e.actionAuditStore == nil {
+ return false, nil
+ }
+ canonical := strings.TrimSpace(resourceID)
+ if canonical == "" {
+ return false, nil
+ }
+ state, found, err := e.actionAuditStore.GetResourceOperatorState(canonical)
+ if err != nil {
+ return false, err
+ }
+ if !found {
+ return false, nil
+ }
+ return state.NeverAutoRemediate, nil
+}
diff --git a/internal/ai/tools/action_audit_execution_test.go b/internal/ai/tools/action_audit_execution_test.go
index 6bc2b39e3d..0c22a32c57 100644
--- a/internal/ai/tools/action_audit_execution_test.go
+++ b/internal/ai/tools/action_audit_execution_test.go
@@ -960,3 +960,180 @@ func TestExecuteCommandWithDeniedApprovalDoesNotDispatch(t *testing.T) {
}
}
}
+
+// TestExecuteCommandWithAuditRefusesWhenResourceIsRemediationLocked covers
+// the operator-set NeverAutoRemediate safety. When the operator has flagged
+// the target resource as never-auto-remediate (via the
+// /api/resources/{id}/operator-state surface), the broker must refuse the
+// dispatch even with a valid approval and matching plan hash. The
+// per-resource intent outranks the per-action approval — this is the
+// safety mechanism for "do not touch this resource even if you think you
+// should." The refusal must be visible on the audit timeline as a Failed
+// record with a `resource_remediation_locked:` ErrorMessage prefix.
+func TestExecuteCommandWithAuditRefusesWhenResourceIsRemediationLocked(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+
+ // Operator has marked the target resource as never-auto-remediate.
+ if err := actionStore.SetResourceOperatorState(unifiedresources.ResourceOperatorState{
+ CanonicalID: "agent-locked",
+ NeverAutoRemediate: true,
+ Note: "manual-only — Pulse must not touch this host",
+ SetAt: time.Now().UTC(),
+ SetBy: "operator:richard",
+ }); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+
+ approvalStore, err := approval.NewStore(approval.StoreConfig{
+ DataDir: t.TempDir(),
+ DisablePersistence: true,
+ })
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ previousApprovalStore := approval.GetStore()
+ approval.SetStore(approvalStore)
+ t.Cleanup(func() { approval.SetStore(previousApprovalStore) })
+
+ now := time.Now().UTC()
+ approvedHash := approvalPlanHash(
+ "act-locked",
+ "approval-locked",
+ "pulse_control",
+ "agent-locked",
+ "systemctl restart workload",
+ "agent",
+ "agent-locked",
+ "restart workload service",
+ )
+ plan := unifiedresources.ActionPlan{
+ ActionID: "act-locked",
+ RequestID: "approval-locked",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ PlanHash: approvedHash,
+ }
+ req := &approval.ApprovalRequest{
+ ID: "approval-locked",
+ Command: "systemctl restart workload",
+ TargetType: "agent",
+ TargetID: "agent-locked",
+ TargetName: "agent-locked",
+ Context: "restart workload service",
+ Plan: &plan,
+ }
+ if err := approvalStore.CreateApproval(req); err != nil {
+ t.Fatalf("CreateApproval: %v", err)
+ }
+ if _, err := approvalStore.Approve("approval-locked", "[email protected]"); err != nil {
+ t.Fatalf("Approve: %v", err)
+ }
+
+ agentServer := &mockAgentServer{}
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: actionStore,
+ })
+ executor.recordPendingApprovalAction(req)
+
+ // Payload matches the approval (no drift); only the operator-set lock
+ // should refuse this. If the broker dispatches anyway, the operator's
+ // per-resource intent has been overridden by the approval, which is
+ // the failure we're guarding against.
+ result, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "agent-locked",
+ "approval-locked",
+ true,
+ "agent-locked",
+ agentexec.ExecuteCommandPayload{
+ Command: "systemctl restart workload",
+ TargetType: "agent",
+ TargetID: "agent-locked",
+ },
+ "pulse_control",
+ "restart workload service",
+ )
+ if !errors.Is(err, unifiedresources.ErrResourceRemediationLocked) {
+ t.Fatalf("executeCommandWithAudit error = %v, want ErrResourceRemediationLocked", err)
+ }
+ if result != nil {
+ t.Fatalf("expected nil result on remediation-locked refusal, got %#v", result)
+ }
+ agentServer.AssertNotCalled(t, "ExecuteCommand", mock.Anything, mock.Anything, mock.Anything)
+
+ // Refusal must be observable in the audit history with the canonical
+ // `resource_remediation_locked:` ErrorMessage prefix so audit-UI
+ // filters and alert rules can branch on the stable token.
+ audits, err := actionStore.GetActionAudits("agent-locked", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits: %v", err)
+ }
+ if len(audits) != 1 {
+ t.Fatalf("expected 1 refused audit record, got %d", len(audits))
+ }
+ refused := audits[0]
+ if refused.State != unifiedresources.ActionStateFailed {
+ t.Fatalf("audit state = %q, want %q", refused.State, unifiedresources.ActionStateFailed)
+ }
+ if refused.Result == nil || refused.Result.Success {
+ t.Fatalf("expected Result.Success=false, got %#v", refused.Result)
+ }
+ if !strings.HasPrefix(refused.Result.ErrorMessage, "resource_remediation_locked:") {
+ t.Fatalf("expected ErrorMessage to start with resource_remediation_locked:, got %q", refused.Result.ErrorMessage)
+ }
+}
+
+// TestExecuteCommandWithAuditAllowsDispatchWhenResourceUnlocked covers
+// the negative case: a resource that has operator state recorded but
+// without NeverAutoRemediate set must NOT block the dispatch. Pin this
+// so the refusal branch can't drift into "always refuse when state
+// exists".
+func TestExecuteCommandWithAuditAllowsDispatchWhenResourceUnlocked(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+ // State recorded but with NeverAutoRemediate=false — should not refuse.
+ if err := actionStore.SetResourceOperatorState(unifiedresources.ResourceOperatorState{
+ CanonicalID: "agent-allowed",
+ IntentionallyOffline: true,
+ NeverAutoRemediate: false,
+ SetAt: time.Now().UTC(),
+ }); err != nil {
+ t.Fatalf("SetResourceOperatorState: %v", err)
+ }
+
+ agentServer := &mockAgentServer{}
+ agentServer.On("ExecuteCommand", mock.Anything, "agent-allowed", mock.Anything).
+ Return(&agentexec.CommandResultPayload{Stdout: "OK", ExitCode: 0}, nil)
+
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: actionStore,
+ })
+
+ result, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ "agent-allowed",
+ "", // no approval (not testing approval flow here)
+ false, // requiresApproval=false
+ "agent-allowed",
+ agentexec.ExecuteCommandPayload{
+ Command: "systemctl status workload",
+ TargetType: "agent",
+ TargetID: "agent-allowed",
+ },
+ "pulse_control",
+ "check status",
+ )
+ if err != nil {
+ t.Fatalf("executeCommandWithAudit unexpected error: %v", err)
+ }
+ if result == nil {
+ t.Fatal("expected dispatch to proceed; got nil result")
+ }
+ agentServer.AssertCalled(t, "ExecuteCommand", mock.Anything, "agent-allowed", mock.Anything)
+}
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index d56ae9acb7..82b1b02a70 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -153,13 +153,21 @@ var (
// is the contract for "the operator approved exactly this action"; if
// it does not match, the broker must refuse execution rather than run a
// drifted plan under a stale approval.
- ErrActionPlanDrift = errors.New("approved plan hash does not match execution payload; refusing to run drifted plan")
- ErrActionNotExecuting = errors.New("action is not executing")
- ErrActionAlreadyExecuting = errors.New("action is already executing")
- ErrActionExecutionFinal = errors.New("action execution is already final")
- ErrActionPlanExpired = errors.New("action plan expired")
- ErrActionDryRunOnly = errors.New("action plan is dry-run only")
- ErrInvalidApprovalOutcome = errors.New("invalid approval outcome")
+ ErrActionPlanDrift = errors.New("approved plan hash does not match execution payload; refusing to run drifted plan")
+ // ErrResourceRemediationLocked is returned when the operator has set
+ // NeverAutoRemediate=true on the target resource. The action broker
+ // must refuse the dispatch even when the approval ID resolves and
+ // the plan hash matches; the operator's per-resource intent
+ // outranks the per-action approval. Persists a Failed audit
+ // record with `resource_remediation_locked:` prefix on the
+ // ErrorMessage so the audit timeline shows every refused dispatch.
+ ErrResourceRemediationLocked = errors.New("resource is operator-locked against automated remediation")
+ ErrActionNotExecuting = errors.New("action is not executing")
+ ErrActionAlreadyExecuting = errors.New("action is already executing")
+ ErrActionExecutionFinal = errors.New("action execution is already final")
+ ErrActionPlanExpired = errors.New("action plan expired")
+ ErrActionDryRunOnly = errors.New("action plan is dry-run only")
+ ErrInvalidApprovalOutcome = errors.New("invalid approval outcome")
)
// ApplyActionDecision records an explicit approval or rejection against a
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index ff2378a705..f997fd58a4 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -359,6 +359,12 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
// honest: drift refusal cannot silently turn into another error
// kind that callers fail to detect.
"ErrActionPlanDrift = errors.New(",
+ // ErrResourceRemediationLocked is the canonical error returned
+ // when the operator has set NeverAutoRemediate=true on the
+ // target resource. Pin it here so the broker contract stays
+ // honest: per-resource lock refusal cannot silently turn into
+ // another error kind that callers fail to detect.
+ "ErrResourceRemediationLocked = errors.New(",
},
filepath.Join(".", "store.go"): {
"RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error",