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.

Harden action start refusal audit

rcourtmanfbbf1daf4c22
diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.go
index d4ccdceabe..3f9ed55441 100644
--- a/internal/ai/tools/action_audit.go
+++ b/internal/ai/tools/action_audit.go
@@ -360,8 +360,12 @@ func (e *PulseToolExecutor) recordActionExecutionStart(record unifiedresources.A
}
if planFromApproval {
var err error
+ approvalRecord := record
record, err = e.ensureApprovalDecisionBeforeExecution(record, approvalID, actor, now)
if err != nil {
+ if unifiedresources.IsPermanentActionExecutionRefusal(err) {
+ return e.recordActionExecutionRefusal(actionExecutionRefusalRecord(record, approvalRecord), err, actor, now)
+ }
return record, err
}
} else if e != nil && e.actionAuditStore != nil {
@@ -397,6 +401,9 @@ func (e *PulseToolExecutor) recordActionExecutionStart(record unifiedresources.A
Str("action_id", record.ID).
Str("state", string(record.State)).
Msg("failed to normalize action execution start")
+ if unifiedresources.IsPermanentActionExecutionRefusal(err) {
+ return e.recordActionExecutionRefusal(record, err, actor, now)
+ }
return record, err
}
if strings.TrimSpace(message) != "" {
@@ -416,6 +423,45 @@ func (e *PulseToolExecutor) recordActionExecutionStart(record unifiedresources.A
return started, nil
}
+func (e *PulseToolExecutor) recordActionExecutionRefusal(record unifiedresources.ActionAuditRecord, reason error, actor string, now time.Time) (unifiedresources.ActionAuditRecord, error) {
+ failed, event, err := unifiedresources.RefuseActionExecution(record, reason, actor, now)
+ if err != nil {
+ return record, err
+ }
+ if e == nil || e.actionAuditStore == nil {
+ e.publishActionCompleted(failed)
+ return failed, reason
+ }
+ if err := e.actionAuditStore.RecordActionAudit(failed); err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", failed.ID).
+ Str("state", string(failed.State)).
+ Msg("failed to persist action execution refusal")
+ return record, err
+ }
+ if err := e.actionAuditStore.RecordActionLifecycleEvent(event); err != nil {
+ log.Warn().
+ Err(err).
+ Str("action_id", failed.ID).
+ Str("state", string(failed.State)).
+ Msg("failed to persist action execution refusal lifecycle event")
+ return record, err
+ }
+ e.publishActionCompleted(failed)
+ return failed, reason
+}
+
+func actionExecutionRefusalRecord(record, fallback unifiedresources.ActionAuditRecord) unifiedresources.ActionAuditRecord {
+ if len(record.Approvals) == 0 && len(fallback.Approvals) > 0 {
+ record.Approvals = append([]unifiedresources.ActionApprovalRecord(nil), fallback.Approvals...)
+ }
+ if record.Request.Params == nil && len(fallback.Request.Params) > 0 {
+ record.Request.Params = cloneActionParams(fallback.Request.Params)
+ }
+ return record
+}
+
func (e *PulseToolExecutor) ensureApprovalDecisionBeforeExecution(record unifiedresources.ActionAuditRecord, approvalID, actor string, now time.Time) (unifiedresources.ActionAuditRecord, error) {
if e == nil || e.actionAuditStore == nil {
return record, nil
diff --git a/internal/ai/tools/action_audit_execution_test.go b/internal/ai/tools/action_audit_execution_test.go
index de1fd41b46..3174ac1fe6 100644
--- a/internal/ai/tools/action_audit_execution_test.go
+++ b/internal/ai/tools/action_audit_execution_test.go
@@ -961,6 +961,182 @@ func TestExecuteCommandWithDeniedApprovalDoesNotDispatch(t *testing.T) {
}
}
+func TestExecuteCommandWithAuditRefusesApprovedDryRunOnlyAndExpiredPlans(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ suffix string
+ configure func(*approval.ApprovalRequest)
+ wantErr error
+ wantPrefix string
+ }{
+ {
+ name: "dry run only",
+ suffix: "dryrun",
+ configure: func(req *approval.ApprovalRequest) {
+ req.Plan.ApprovalPolicy = unifiedresources.ApprovalDryRun
+ },
+ wantErr: unifiedresources.ErrActionDryRunOnly,
+ wantPrefix: "action_dry_run_only:",
+ },
+ {
+ name: "expired",
+ suffix: "expired",
+ configure: func(req *approval.ApprovalRequest) {
+ req.Plan.ExpiresAt = time.Now().UTC().Add(-time.Minute)
+ },
+ wantErr: unifiedresources.ErrActionPlanExpired,
+ wantPrefix: "action_plan_expired:",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ actionStore := unifiedresources.NewMemoryStore()
+ 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()
+ actionID := "act-" + tc.suffix + "-command"
+ approvalID := "approval-" + tc.suffix + "-command"
+ targetID := "agent-" + tc.suffix
+ command := "systemctl restart workload"
+ reason := "restart workload service"
+ approvedHash := approvalPlanHash(
+ actionID,
+ approvalID,
+ "pulse_control",
+ targetID,
+ command,
+ "agent",
+ targetID,
+ reason,
+ )
+ plan := unifiedresources.ActionPlan{
+ ActionID: actionID,
+ RequestID: approvalID,
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unifiedresources.ApprovalAdmin,
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: approvedHash,
+ }
+ req := &approval.ApprovalRequest{
+ ID: approvalID,
+ Command: command,
+ TargetType: "agent",
+ TargetID: targetID,
+ TargetName: targetID,
+ Context: reason,
+ Plan: &plan,
+ }
+ if err := approvalStore.CreateApproval(req); err != nil {
+ t.Fatalf("CreateApproval: %v", err)
+ }
+ approved, err := approvalStore.Approve(approvalID, "[email protected]")
+ if err != nil {
+ t.Fatalf("Approve: %v", err)
+ }
+ tc.configure(approved)
+
+ agentServer := &mockAgentServer{}
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ AgentServer: agentServer,
+ ActionAuditStore: actionStore,
+ })
+ executor.recordPendingApprovalAction(approved)
+
+ completed := make(chan unifiedresources.ActionAuditRecord, 1)
+ executor.SetOnActionCompleted(func(record unifiedresources.ActionAuditRecord) {
+ completed <- record
+ })
+
+ result, err := executor.executeCommandWithAudit(
+ context.Background(),
+ "pulse_control",
+ targetID,
+ approvalID,
+ true,
+ targetID,
+ agentexec.ExecuteCommandPayload{
+ Command: command,
+ TargetType: "agent",
+ TargetID: targetID,
+ },
+ "pulse_control",
+ reason,
+ )
+ if !errors.Is(err, tc.wantErr) {
+ t.Fatalf("executeCommandWithAudit error = %v, want %v", err, tc.wantErr)
+ }
+ if result != nil {
+ t.Fatalf("expected nil command result on refusal, got %#v", result)
+ }
+ agentServer.AssertNotCalled(t, "ExecuteCommand", mock.Anything, mock.Anything, mock.Anything)
+
+ audit, ok, err := actionStore.GetActionAudit(actionID)
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok {
+ t.Fatalf("expected refused action audit %q", actionID)
+ }
+ if audit.State != unifiedresources.ActionStateFailed {
+ t.Fatalf("audit state = %q, want %q", audit.State, unifiedresources.ActionStateFailed)
+ }
+ if audit.Result == nil || audit.Result.Success {
+ t.Fatalf("expected Result.Success=false, got %#v", audit.Result)
+ }
+ if !strings.HasPrefix(audit.Result.ErrorMessage, tc.wantPrefix) {
+ t.Fatalf("ErrorMessage = %q, want prefix %q", audit.Result.ErrorMessage, tc.wantPrefix)
+ }
+ if len(audit.Approvals) != 1 || audit.Approvals[0].Outcome != unifiedresources.OutcomeApproved {
+ t.Fatalf("expected approved audit record to be preserved, got %#v", audit.Approvals)
+ }
+
+ events, err := actionStore.GetActionLifecycleEvents(actionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ seenFailed := false
+ for _, event := range events {
+ if event.State == unifiedresources.ActionStateExecuting || event.State == unifiedresources.ActionStateCompleted {
+ t.Fatalf("refusal must not create dispatch lifecycle event: %#v", event)
+ }
+ if event.State == unifiedresources.ActionStateFailed {
+ seenFailed = true
+ if !strings.HasPrefix(event.Message, tc.wantPrefix) {
+ t.Fatalf("failed lifecycle message = %q, want prefix %q", event.Message, tc.wantPrefix)
+ }
+ }
+ }
+ if !seenFailed {
+ t.Fatalf("missing failed refusal lifecycle event in %#v", events)
+ }
+
+ select {
+ case received := <-completed:
+ if received.State != unifiedresources.ActionStateFailed {
+ t.Fatalf("callback state = %q, want %q", received.State, unifiedresources.ActionStateFailed)
+ }
+ if received.Result == nil || !strings.HasPrefix(received.Result.ErrorMessage, tc.wantPrefix) {
+ t.Fatalf("callback result = %#v, want prefix %q", received.Result, tc.wantPrefix)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("terminal refusal callback did not fire within 2s")
+ }
+ })
+ }
+}
+
// TestExecuteCommandWithAuditRefusesWhenResourceIsRemediationLocked covers
// the operator-set NeverAutoRemediate safety. When the operator has flagged
// the target resource as never-auto-remediate (via the