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.

Persist permanent action refusal outcomes

rcourtmaneb78bf9f3716
diff --git a/internal/api/actions.go b/internal/api/actions.go
index 2b759cb164..728bd28947 100644
--- a/internal/api/actions.go
+++ b/internal/api/actions.go
@@ -348,6 +348,14 @@ func (h *ResourceHandlers) HandleExecuteAction(w http.ResponseWriter, r *http.Re
actor := actionDecisionActor(h, r)
now := time.Now().UTC()
if err := unified.ValidateActionExecutionStart(record, now); err != nil {
+ if unified.IsPermanentActionExecutionRefusal(err) {
+ if failed, persistErr := recordRefusedActionExecution(store, record, actor, now, err); persistErr == nil {
+ h.publishActionCompleted(failed)
+ } else {
+ writeJSONError(w, http.StatusInternalServerError, "action_execution_persist_failed", sanitizeErrorForClient(persistErr, "Failed to persist refused action execution"))
+ return
+ }
+ }
writeActionExecutionApplyError(w, err)
return
}
@@ -447,56 +455,20 @@ func (h *ResourceHandlers) validateActionPlanFresh(orgID string, record unified.
}
func recordRefusedActionExecution(store unified.ResourceStore, record unified.ActionAuditRecord, actor string, now time.Time, reason error) (unified.ActionAuditRecord, error) {
- if now.IsZero() {
- now = time.Now().UTC()
- } else {
- now = now.UTC()
- }
- actor = strings.TrimSpace(actor)
- if actor == "" {
- actor = "api:authenticated"
- }
- record.State = unified.ActionStateFailed
- record.UpdatedAt = now
- record.Result = &unified.ExecutionResult{
- Success: false,
- ErrorMessage: refusedActionExecutionMessage(reason),
- }
- normalized, err := unified.NormalizeActionAuditRecord(record)
+ failed, event, err := unified.RefuseActionExecution(record, reason, actor, now)
if err != nil {
return unified.ActionAuditRecord{}, err
}
if store == nil {
return unified.ActionAuditRecord{}, errors.New("action audit store unavailable")
}
- if err := store.RecordActionAudit(normalized); err != nil {
- return unified.ActionAuditRecord{}, err
- }
- event, err := unified.NormalizeActionLifecycleEvent(unified.ActionLifecycleEvent{
- ActionID: normalized.ID,
- Timestamp: now,
- State: unified.ActionStateFailed,
- Actor: actor,
- Message: normalized.Result.ErrorMessage,
- })
- if err != nil {
+ if err := store.RecordActionAudit(failed); err != nil {
return unified.ActionAuditRecord{}, err
}
if err := store.RecordActionLifecycleEvent(event); err != nil {
return unified.ActionAuditRecord{}, err
}
- return normalized, nil
-}
-
-func refusedActionExecutionMessage(reason error) string {
- if errors.Is(reason, unified.ErrActionPlanDrift) {
- return "plan_drift: action plan no longer matches the current resource contract; re-plan before executing"
- }
- message := strings.TrimSpace(fmt.Sprint(reason))
- if message == "" {
- message = "action execution refused before dispatch"
- }
- return message
+ return failed, nil
}
func (h *ResourceHandlers) publishActionCompleted(record unified.ActionAuditRecord) {
diff --git a/internal/api/actions_test.go b/internal/api/actions_test.go
index 7914b7eecc..8777de7291 100644
--- a/internal/api/actions_test.go
+++ b/internal/api/actions_test.go
@@ -675,6 +675,10 @@ func TestHandleExecuteActionRejectsDryRunOnlyPlan(t *testing.T) {
h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "should not run"}}
h.SetActionExecutor(executor)
+ published := make(chan unified.ActionAuditRecord, 1)
+ h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) {
+ published <- record
+ })
store, err := h.getStore("default")
if err != nil {
@@ -727,15 +731,114 @@ func TestHandleExecuteActionRejectsDryRunOnlyPlan(t *testing.T) {
if err != nil {
t.Fatalf("GetActionAudit: %v", err)
}
- if !ok || got.State != unified.ActionStatePlanned || got.Result != nil {
- t.Fatalf("dry-run-only audit changed = %#v, ok=%v", got, ok)
+ if !ok || got.State != unified.ActionStateFailed || got.Result == nil || got.Result.Success || !strings.HasPrefix(got.Result.ErrorMessage, "action_dry_run_only:") {
+ t.Fatalf("dry-run-only audit = %#v, ok=%v", got, ok)
+ }
+ select {
+ case eventRecord := <-published:
+ if eventRecord.ID != "act_dry_run_only" || eventRecord.State != unified.ActionStateFailed {
+ t.Fatalf("published dry-run-only completion = %#v", eventRecord)
+ }
+ default:
+ t.Fatal("expected dry-run-only refusal to publish a terminal action completion event")
}
events, err := store.GetActionLifecycleEvents("act_dry_run_only", time.Time{}, 10)
if err != nil {
t.Fatalf("GetActionLifecycleEvents: %v", err)
}
- if len(events) != 0 {
- t.Fatalf("dry-run-only execution must not append lifecycle events: %#v", events)
+ if len(events) != 1 || events[0].State != unified.ActionStateFailed || !strings.HasPrefix(events[0].Message, "action_dry_run_only:") {
+ t.Fatalf("expected one failed dry-run-only lifecycle event, got %#v", events)
+ }
+}
+
+func TestHandleExecuteActionRejectsExpiredPlanAsFailedAudit(t *testing.T) {
+ now := time.Now().UTC().Truncate(time.Second)
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ executor := &stubActionExecutor{result: &unified.ExecutionResult{Success: true, Output: "should not run"}}
+ h.SetActionExecutor(executor)
+ published := make(chan unified.ActionAuditRecord, 1)
+ h.SetActionCompletedPublisher(func(record unified.ActionAuditRecord) {
+ published <- record
+ })
+
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("get store: %v", err)
+ }
+ record := unified.ActionAuditRecord{
+ ID: "act_expired",
+ CreatedAt: now.Add(-10 * time.Minute),
+ UpdatedAt: now.Add(-6 * time.Minute),
+ State: unified.ActionStateApproved,
+ Request: unified.ActionRequest{
+ RequestID: "req-expired",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "Recover after confirmed outage",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: unified.ActionPlan{
+ ActionID: "act_expired",
+ RequestID: "req-expired",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unified.ApprovalAdmin,
+ PlannedAt: now.Add(-10 * time.Minute),
+ ExpiresAt: now.Add(-5 * time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ Approvals: []unified.ActionApprovalRecord{
+ {
+ Actor: "[email protected]",
+ Method: unified.MethodAPI,
+ Timestamp: now.Add(-6 * time.Minute),
+ Outcome: unified.OutcomeApproved,
+ Reason: "approved before expiry",
+ },
+ },
+ }
+ if err := store.RecordActionAudit(record); err != nil {
+ t.Fatalf("RecordActionAudit: %v", err)
+ }
+
+ executeRec := httptest.NewRecorder()
+ executeReq := httptest.NewRequest(http.MethodPost, "/api/actions/act_expired/execute", bytes.NewBufferString(`{}`))
+ executeReq.SetPathValue("id", "act_expired")
+ executeReq = executeReq.WithContext(auth.WithUser(executeReq.Context(), "[email protected]"))
+ h.HandleExecuteAction(executeRec, executeReq)
+ if executeRec.Code != http.StatusConflict {
+ t.Fatalf("execute status = %d, body=%s", executeRec.Code, executeRec.Body.String())
+ }
+ if !strings.Contains(executeRec.Body.String(), `"error":"action_plan_expired"`) {
+ t.Fatalf("execute body = %s", executeRec.Body.String())
+ }
+ if executor.calls != 0 {
+ t.Fatalf("expired plan should not call executor, calls=%d received=%#v", executor.calls, executor.received)
+ }
+
+ got, ok, err := store.GetActionAudit("act_expired")
+ if err != nil {
+ t.Fatalf("GetActionAudit: %v", err)
+ }
+ if !ok || got.State != unified.ActionStateFailed || got.Result == nil || got.Result.Success || !strings.HasPrefix(got.Result.ErrorMessage, "action_plan_expired:") {
+ t.Fatalf("expired-plan audit = %#v, ok=%v", got, ok)
+ }
+ select {
+ case eventRecord := <-published:
+ if eventRecord.ID != "act_expired" || eventRecord.State != unified.ActionStateFailed {
+ t.Fatalf("published expired-plan completion = %#v", eventRecord)
+ }
+ default:
+ t.Fatal("expected expired-plan refusal to publish a terminal action completion event")
+ }
+ events, err := store.GetActionLifecycleEvents("act_expired", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ if len(events) != 1 || events[0].State != unified.ActionStateFailed || !strings.HasPrefix(events[0].Message, "action_plan_expired:") {
+ t.Fatalf("expected one failed expired-plan lifecycle event, got %#v", events)
}
}
diff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.go
index ea06548592..782b60d80b 100644
--- a/internal/api/agent_capabilities.go
+++ b/internal/api/agent_capabilities.go
@@ -217,14 +217,14 @@ var agentCapabilitiesManifest = AgentCapabilitiesManifest{
},
{
Name: "execute_action",
- Description: "Execute a previously planned and (when required) approved action. Returns the persisted audit record with the execution result attached. Refuses with stable codes when the action is in the wrong lifecycle state (action_not_approved, action_already_executing, action_execution_final, action_dry_run_only), when the approved plan no longer matches the current resource/capability contract (action_plan_drift), or when the API instance has no executor wired (action_executor_unavailable). action.completed SSE events fire on every terminal state so agents watching the stream do not need to poll this endpoint after dispatch.",
+ Description: "Execute a previously planned and (when required) approved action. Returns the persisted audit record with the execution result attached. Refuses with stable codes when the action is in the wrong lifecycle state (action_not_approved, action_already_executing, action_execution_final, action_dry_run_only, action_plan_expired), when the approved plan no longer matches the current resource/capability contract (action_plan_drift), or when the API instance has no executor wired (action_executor_unavailable). action.completed SSE events fire on every terminal state so agents watching the stream do not need to poll this endpoint after dispatch.",
Category: "action",
Method: http.MethodPost,
Path: "/api/actions/{actionId}/execute",
Scope: "ai:execute",
RequestBodyShape: "{ reason?: string }",
ResponseShape: "ActionExecutionResponse",
- ErrorCodes: []string{"missing_id", "invalid_id", "invalid_action_execution", "action_not_found", "action_not_approved", "action_already_executing", "action_execution_final", "action_dry_run_only", "action_plan_drift", "action_executor_unavailable"},
+ ErrorCodes: []string{"missing_id", "invalid_id", "invalid_action_execution", "action_not_found", "action_not_approved", "action_already_executing", "action_execution_final", "action_dry_run_only", "action_plan_expired", "action_plan_drift", "action_executor_unavailable"},
},
},
}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 72f5f837e8..dd897b3415 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -12508,15 +12508,15 @@ func TestContract_ActionDryRunOnlyExecutionErrorJSONSnapshot(t *testing.T) {
if err != nil {
t.Fatalf("GetActionAudit: %v", err)
}
- if !ok || gotAudit.State != unifiedresources.ActionStatePlanned || gotAudit.Result != nil {
+ if !ok || gotAudit.State != unifiedresources.ActionStateFailed || gotAudit.Result == nil || gotAudit.Result.Success || !strings.HasPrefix(gotAudit.Result.ErrorMessage, "action_dry_run_only:") {
t.Fatalf("dry-run audit mutated: ok=%v state=%q result=%#v", ok, gotAudit.State, gotAudit.Result)
}
events, err := store.GetActionLifecycleEvents("act_dry_run_contract", time.Time{}, 10)
if err != nil {
t.Fatalf("GetActionLifecycleEvents: %v", err)
}
- if len(events) != 0 {
- t.Fatalf("dry-run execution should not append lifecycle events, got %d", len(events))
+ if len(events) != 1 || events[0].State != unifiedresources.ActionStateFailed || !strings.HasPrefix(events[0].Message, "action_dry_run_only:") {
+ t.Fatalf("dry-run execution should append one failed lifecycle event, got %#v", events)
}
}
@@ -12527,9 +12527,11 @@ func TestContract_APIActionExecutionRevalidatesPlanFreshness(t *testing.T) {
}
src := string(source)
for _, snippet := range []string{
+ "if unified.IsPermanentActionExecutionRefusal(err)",
"if err := h.validateActionPlanFresh(orgID, record); err != nil",
"errors.Is(err, unified.ErrActionPlanDrift)",
"recordRefusedActionExecution(store, record, actor, now, err)",
+ "unified.RefuseActionExecution(record, reason, actor, now)",
"writeJSONError(w, http.StatusConflict, \"action_plan_drift\"",
} {
if !strings.Contains(src, snippet) {
@@ -12542,6 +12544,25 @@ func TestContract_APIActionExecutionRevalidatesPlanFreshness(t *testing.T) {
}
}
+func TestContract_ExecuteActionCapabilityDeclaresPlanExpired(t *testing.T) {
+ source, err := os.ReadFile("agent_capabilities.go")
+ if err != nil {
+ t.Fatalf("read agent_capabilities.go: %v", err)
+ }
+ src := string(source)
+ start := strings.Index(src, `Name: "execute_action"`)
+ if start < 0 {
+ t.Fatal("agent capabilities manifest must declare execute_action")
+ }
+ block := src[start:]
+ if end := strings.Index(block, "\n\t\t},"); end >= 0 {
+ block = block[:end]
+ }
+ if !strings.Contains(block, `"action_plan_expired"`) {
+ t.Error("execute_action manifest must declare action_plan_expired so agents can branch on permanent expired-plan refusals")
+ }
+}
+
func TestContract_ResourceTimelineEndpointsIncludeRelatedChanges(t *testing.T) {
now := time.Date(2026, 4, 25, 22, 15, 0, 0, time.UTC)
h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index 1e26534f00..9c83f8289b 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -222,6 +222,7 @@ var (
ErrActionExecutionFinal = errors.New("action execution is already final")
ErrActionPlanExpired = errors.New("action plan expired")
ErrActionDryRunOnly = errors.New("action plan is dry-run only")
+ ErrActionExecutionRefusal = errors.New("action execution refusal is not a permanent terminal refusal")
ErrInvalidApprovalOutcome = errors.New("invalid approval outcome")
)
@@ -375,6 +376,69 @@ func CompleteActionExecution(record ActionAuditRecord, result *ExecutionResult,
return normalized, normalizedEvent, nil
}
+// RefuseActionExecution records a permanent pre-dispatch refusal as the same
+// terminal failed audit shape used by runtime execution failures.
+func RefuseActionExecution(record ActionAuditRecord, reason error, actor string, now time.Time) (ActionAuditRecord, ActionLifecycleEvent, error) {
+ if now.IsZero() {
+ now = time.Now().UTC()
+ } else {
+ now = now.UTC()
+ }
+ message, ok := permanentActionExecutionRefusalMessage(reason)
+ if !ok {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, fmt.Errorf("%w: %v", ErrActionExecutionRefusal, reason)
+ }
+ actor = strings.TrimSpace(actor)
+ if actor == "" {
+ actor = "api:authenticated"
+ }
+
+ record.State = ActionStateFailed
+ record.UpdatedAt = now
+ record.Result = &ExecutionResult{
+ Success: false,
+ ErrorMessage: message,
+ }
+ normalized, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ event := ActionLifecycleEvent{
+ ActionID: normalized.ID,
+ Timestamp: now,
+ State: ActionStateFailed,
+ Actor: actor,
+ Message: normalized.Result.ErrorMessage,
+ }
+ normalizedEvent, err := NormalizeActionLifecycleEvent(event)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, err
+ }
+ return normalized, normalizedEvent, nil
+}
+
+// IsPermanentActionExecutionRefusal reports whether err represents a
+// non-dispatchable execution attempt that should terminally fail the audit.
+func IsPermanentActionExecutionRefusal(err error) bool {
+ _, ok := permanentActionExecutionRefusalMessage(err)
+ return ok
+}
+
+func permanentActionExecutionRefusalMessage(reason error) (string, bool) {
+ switch {
+ case errors.Is(reason, ErrActionPlanDrift):
+ return "plan_drift: action plan no longer matches the current resource contract; re-plan before executing", true
+ case errors.Is(reason, ErrActionPlanExpired):
+ return "action_plan_expired: action plan has expired; re-plan before executing", true
+ case errors.Is(reason, ErrActionDryRunOnly):
+ return "action_dry_run_only: action plan is dry-run only and cannot be executed", true
+ case errors.Is(reason, ErrResourceRemediationLocked):
+ return "resource_remediation_locked: resource is operator-locked against automated remediation", true
+ default:
+ return "", false
+ }
+}
+
// ValidateActionExecutionStart checks whether the current persisted state may
// enter execution without mutating the record.
func ValidateActionExecutionStart(record ActionAuditRecord, now time.Time) error {
@@ -383,6 +447,12 @@ func ValidateActionExecutionStart(record ActionAuditRecord, now time.Time) error
} else {
now = now.UTC()
}
+ switch record.State {
+ case ActionStateExecuting:
+ return ErrActionAlreadyExecuting
+ case ActionStateCompleted, ActionStateFailed:
+ return ErrActionExecutionFinal
+ }
if !record.Plan.ExpiresAt.IsZero() && !now.Before(record.Plan.ExpiresAt) {
return ErrActionPlanExpired
}
@@ -399,10 +469,6 @@ func ValidateActionExecutionStart(record ActionAuditRecord, now time.Time) error
return ErrActionNotApproved
case ActionStatePending, ActionStateRejected:
return ErrActionNotApproved
- case ActionStateExecuting:
- return ErrActionAlreadyExecuting
- case ActionStateCompleted, ActionStateFailed:
- return ErrActionExecutionFinal
default:
return fmt.Errorf("unsupported action state %q", record.State)
}
diff --git a/internal/unifiedresources/actions_test.go b/internal/unifiedresources/actions_test.go
index 83168139af..98154807bb 100644
--- a/internal/unifiedresources/actions_test.go
+++ b/internal/unifiedresources/actions_test.go
@@ -257,6 +257,12 @@ func TestBeginActionExecutionRejectsUnsafeStates(t *testing.T) {
if _, _, err := BeginActionExecution(completed, "[email protected]", now); !errors.Is(err, ErrActionExecutionFinal) {
t.Fatalf("completed error = %v, want %v", err, ErrActionExecutionFinal)
}
+ failedExpired := base
+ failedExpired.State = ActionStateFailed
+ failedExpired.Plan.ExpiresAt = now.Add(-time.Second)
+ if _, _, err := BeginActionExecution(failedExpired, "[email protected]", now); !errors.Is(err, ErrActionExecutionFinal) {
+ t.Fatalf("failed expired error = %v, want %v", err, ErrActionExecutionFinal)
+ }
expired := base
expired.State = ActionStateApproved
expired.Plan.ExpiresAt = now.Add(-time.Second)
@@ -272,6 +278,65 @@ func TestBeginActionExecutionRejectsUnsafeStates(t *testing.T) {
}
}
+func TestRefuseActionExecutionRecordsPermanentRefusal(t *testing.T) {
+ now := time.Date(2026, 5, 4, 13, 0, 0, 0, time.UTC)
+ record := ActionAuditRecord{
+ ID: "act_refused",
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-30 * time.Second),
+ State: ActionStateApproved,
+ Request: ActionRequest{
+ RequestID: "req-refused",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Reason: "recover service",
+ RequestedBy: "agent:oncall-helper",
+ },
+ Plan: ActionPlan{
+ ActionID: "act_refused",
+ RequestID: "req-refused",
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: ApprovalAdmin,
+ PlannedAt: now.Add(-time.Minute),
+ ExpiresAt: now.Add(time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ }
+
+ for _, tc := range []struct {
+ name string
+ reason error
+ wantPrefix string
+ }{
+ {name: "plan drift", reason: ErrActionPlanDrift, wantPrefix: "plan_drift:"},
+ {name: "expired", reason: ErrActionPlanExpired, wantPrefix: "action_plan_expired:"},
+ {name: "dry run only", reason: ErrActionDryRunOnly, wantPrefix: "action_dry_run_only:"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ updated, event, err := RefuseActionExecution(record, tc.reason, " [email protected] ", now)
+ if err != nil {
+ t.Fatalf("RefuseActionExecution: %v", err)
+ }
+ if updated.State != ActionStateFailed || updated.Result == nil || updated.Result.Success {
+ t.Fatalf("updated action = %#v, want failed result", updated)
+ }
+ if !strings.HasPrefix(updated.Result.ErrorMessage, tc.wantPrefix) {
+ t.Fatalf("ErrorMessage = %q, want prefix %q", updated.Result.ErrorMessage, tc.wantPrefix)
+ }
+ if event.ActionID != updated.ID || event.State != ActionStateFailed || event.Actor != "[email protected]" || event.Message != updated.Result.ErrorMessage {
+ t.Fatalf("lifecycle event = %#v, updated result = %#v", event, updated.Result)
+ }
+ })
+ }
+
+ if _, _, err := RefuseActionExecution(record, errors.New("transient executor unavailable"), "", now); !errors.Is(err, ErrActionExecutionRefusal) {
+ t.Fatalf("unexpected refusal error = %v, want %v", err, ErrActionExecutionRefusal)
+ }
+}
+
func TestCompleteActionExecutionRecordsResult(t *testing.T) {
now := time.Date(2026, 5, 4, 12, 45, 0, 0, time.UTC)
record := ActionAuditRecord{