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.

Fix dispatch-time policy revocation

rcourtmanc74c88fb867f
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 36e0ec05d1..6b8190cb56 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -3978,6 +3978,18 @@
"-count=1"
]
},
+ {
+ "id": "ra35-dispatch-time-policy-revocation",
+ "run": [
+ "go",
+ "test",
+ "./internal/actionlifecycle",
+ "./internal/api",
+ "-run",
+ "TestExecuteUnderPolicyBarrierRevocationsMemoryStore|TestExecuteUnderPolicyBarrierRevocationsSQLite|TestPolicyAdmissionCommitsApprovalAndExecutingAtomicallyMemoryStore|TestPolicyAdmissionCommitsApprovalAndExecutingAtomicallySQLite|TestHumanApprovalSurvivesAutomaticPolicyRevocationMemoryStore|TestHumanApprovalSurvivesAutomaticPolicyRevocationSQLite|TestEmergencyStopBlocksHumanAndPolicyAdmissionMemoryStore|TestEmergencyStopBlocksHumanAndPolicyAdmissionSQLite|TestLegacyPolicyApprovalWithoutLeaseFailsClosedAfterRestart|TestQueuedPolicyActionRevalidatesAfterSQLiteRestart|TestPatrolActionBrokerDispatchTimePolicyRevocation",
+ "-count=1"
+ ]
+ },
{
"id": "ra35-typed-host-storage-cleanup-vertical",
"run": [
@@ -4029,6 +4041,16 @@
}
],
"evidence": [
+ {
+ "repo": "pulse",
+ "path": "internal/actionlifecycle/service.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/actionlifecycle/service_test.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/agentcapabilities/schema.go",
@@ -4109,6 +4131,11 @@
"path": "internal/api/patrol_action_broker.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/api/patrol_action_broker_test.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/hostagent/package_updates.go",
@@ -4119,6 +4146,16 @@
"path": "internal/hostagent/storage_cleanup.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/actions.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/unifiedresources/store.go",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "pkg/aicontracts/action_broker.go",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index b63353a75b..f2400005a0 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -100,6 +100,16 @@ that binary, not separate customer-facing agent products.
## Shared Boundaries
+Automatic Patrol action admission wired through `internal/api/` is API/action-
+lifecycle authority, not agent enrollment or command authority. Agent command
+transport may run only after the lifecycle-owned policy lease has been
+revalidated and the policy approval plus `executing` transition have committed
+atomically; a policy-approved intermediate state is never reusable by an agent.
+Human approvals remain separate lifecycle evidence and are not invalidated by
+later automatic-policy revocation. Emergency stop blocks admission before
+`executing`; cancellation after that boundary is best effort and is not
+rollback proof.
+
Assistant transport scopes do not grant agent command authority. `ai:chat`
and `relay:mobile:access` remain conversation/read/session scopes; an
interactive infrastructure invocation must carry server-bound `ai:execute`
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 678096d015..219d1c976d 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -4624,6 +4624,14 @@ capability eligibility, persisted per-resource allowlist/window, remediation
lock, and the canonical lifecycle. Enterprise receives the resulting pending
or terminal disposition, including honest verification status, but never an
authorization primitive. `OrchestratorDeps.ActionBroker` carries the seam and is
+Policy-authorized submission enters `actionlifecycle.ExecuteUnderPolicy`; the
+broker may evaluate eligibility to decide whether to attempt automatic
+admission, but it cannot persist approval or call an executor itself. The
+lifecycle re-evaluates the full policy under the shared admission coordinator
+and atomically persists the typed authorization lease, policy approval, and
+executing transition. Revocation before that transition produces zero dispatch
+and no policy approval. Human approvals remain semantically separate.
+`OrchestratorDeps.ActionBroker` carries the seam and is
now REQUIRED: the enterprise factory disables the orchestrator when it is
absent rather than falling back. The command-execution side doors are
gone. `OrchestratorChatService` exposes only investigation-specific
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index e047e23255..82f095bed6 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1860,11 +1860,19 @@ a new API state machine, queue contract, or verification-accounting field.
optional recurring window, `NeverAutoRemediate`, and the tenant's effective
Patrol mode all allow it. Assisted mode admits only `low_risk`; unlocked full
mode may also admit `elevated`; monitor, approval, dry-run-only, MFA, missing,
- and unknown policy fail closed to the pending disposition. Core re-reads the
- policy immediately before execution and records the decision as actor
- `pulse_patrol_policy` with approval method `policy`; the canonical lifecycle
- still owns locks, drift validation, execution, verification, publication,
- and replay safety. Proposals
+ and unknown policy fail closed. Automatic admission is lifecycle-owned:
+ `ExecuteUnderPolicy` re-reads the complete tenant, capability, resource,
+ window, unlock, license, and emergency-stop posture under the shared policy
+ admission coordinator, binds it to a typed versioned lease, then persists
+ the `pulse_patrol_policy` / `policy` approval and `executing` transition in
+ one store CAS transaction. No reusable policy-approved state exists.
+ Missing, malformed, stale, unreadable, or revoked policy records a stable
+ refused-before-dispatch failure with no executor call. Human approval stays
+ a distinct path: automatic-mode, allowlist, and recurring-window changes do
+ not revoke a human decision, while plan drift, `NeverAutoRemediate`, and the
+ action emergency stop remain universal. The executing transition is the
+ admission linearization point; a later emergency stop is best-effort
+ cancellation and never claims rollback. Proposals
that populate a capability parameter declared `IsSensitive` are refused
with `ErrSensitiveParamsRequireOperator` before any audit persistence,
so secret material never enters model output, investigation stores, or
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 2084a816f4..bda15692b4 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -18,6 +18,12 @@
Own measurable performance budgets, query-plan guarantees, and hot-path
regression protection.
+Dispatch-time Patrol authorization uses one bounded policy snapshot and one
+storage CAS on the execution hot path. Policy writers serialize against that
+admission coordinator; the broker must not add policy-history scans, resource
+registry walks after admission, or network probes before the executor. Failed
+admission records a stable refusal without invoking executor or network code.
+
## Canonical Files
1. `pkg/metrics/store.go`
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 537b88e65f..0a633e7774 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -344,6 +344,14 @@ the `white_label` branding entitlement.
action lifecycle, but it exposes only typed-proposal capture and gives the
orchestrator no autonomy control, command execution, or command-shaped
approval path.
+ Automatic action authority is a versioned, one-use admission lease rather
+ than a reusable approval. Tenant mode/license/unlock, capability safety and
+ approval floor, resource allowlist/window/Never state, plan hashes, and the
+ action emergency stop are revalidated under one admission coordinator and
+ committed with `executing`. Missing or unreadable policy denies dispatch.
+ Human approval remains separate, but `NeverAutoRemediate`, plan drift, and
+ emergency stop are universal. Emergency stop after `executing` is only
+ best-effort cancellation and must never be described as rollback.
The typed host-update executor wired here is likewise not generic command
authority. It may dispatch only the closed `install_os_updates` operation,
bound to the server-observed package inventory fingerprint and canonical
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index e3d2a8d3ff..55c5ea811d 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -56,6 +56,15 @@ state.
## Shared Boundaries
+The Patrol action broker and shared policy-writer wiring under `internal/api/`
+remain API/action-lifecycle authority even when the target is storage-related.
+Automatic admission requires a fresh, resource-bound policy lease and an
+atomic approval-plus-`executing` transition; missing, unreadable, malformed,
+or revoked policy fails closed before any backup, restore, SMART, or other
+storage executor/network call. Human approval remains distinct evidence.
+Emergency stop after `executing` is best-effort cancellation, never recovery
+or rollback proof.
+
Assistant access to recovery points and storage evidence is read-side context.
`ai:chat`, relay-mobile chat, and the `read_only` control level cannot project
or execute storage/infrastructure mutation, finding lifecycle changes, or
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 435a57470c..e424986dc4 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1480,6 +1480,16 @@ names, and lower-cases the criticality value before persistence. The
`ClearResourceOperatorState`; both the SQLite (table
`resource_operator_state` keyed on `canonical_id`) and Memory stores
implement the same upsert + idempotent-clear contract. The same
+store also owns `RecordActionPolicyExecutionStart`, the automatic-admission
+CAS that moves a planned or pending action directly to `executing` while
+persisting the server-owned policy approval and typed
+`ActionPolicyAuthorizationLease` in the same transaction. Memory and SQLite
+implement identical semantics. The lease binds org/action/resource/capability,
+plan and capability-policy hashes, safety and approval floors, tenant
+mode/license/unlock version, resource allowlist/window/Never version, expiry,
+and digest. A policy approval without that lease is historical-only and cannot
+admit a nonterminal action after restart.
+The same
store powers the agent-consumable bundled context endpoint at
`/api/agent/resource-context/{id}` (handler in
`internal/api/agent_resource_context.go`) — that endpoint reads
diff --git a/internal/actionlifecycle/service.go b/internal/actionlifecycle/service.go
index 1793131512..d2805e36db 100644
--- a/internal/actionlifecycle/service.go
+++ b/internal/actionlifecycle/service.go
@@ -13,6 +13,7 @@ import (
"errors"
"fmt"
"strings"
+ "sync"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/actionplanner"
@@ -39,6 +40,7 @@ type Store interface {
GetActionAudit(actionID string) (unified.ActionAuditRecord, bool, error)
RecordActionDecision(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) error
RecordActionExecutionStart(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) error
+ RecordActionPolicyExecutionStart(record unified.ActionAuditRecord, approvalEvent, executionEvent unified.ActionLifecycleEvent) error
RecordActionExecutionResult(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) error
RecordActionExecutionRefusal(record unified.ActionAuditRecord, event unified.ActionLifecycleEvent) error
RecordActionLifecycleEvent(event unified.ActionLifecycleEvent) error
@@ -50,9 +52,10 @@ type Store interface {
// dependencies are resolved per call so late-bound wiring (executors and
// publishers set after construction) stays current.
type Service struct {
- Registry func(orgID string) (*unified.ResourceRegistry, error)
- Store func(orgID string) (Store, error)
- Executor Executor
+ Registry func(orgID string) (*unified.ResourceRegistry, error)
+ Store func(orgID string) (Store, error)
+ Executor Executor
+ EmergencyStop func(orgID string) (bool, error)
// OnActionCompleted receives every terminal (completed/failed) audit
// record, including refused-before-dispatch failures, so SSE bridges
// and reconcilers observe the full lifecycle regardless of transport.
@@ -68,6 +71,32 @@ type Service struct {
// records additionally flow through OnActionCompleted after this hook.
OnActionTransition func(orgID string, record unified.ActionAuditRecord)
Now func() time.Time
+ PolicyAdmission *PolicyAdmissionCoordinator
+}
+
+type PolicyAdmissionCoordinator struct{ mu sync.RWMutex }
+
+func (s *Service) admissionCoordinator() *PolicyAdmissionCoordinator {
+ if s.PolicyAdmission == nil {
+ s.PolicyAdmission = &PolicyAdmissionCoordinator{}
+ }
+ return s.PolicyAdmission
+}
+
+// PolicyAuthorizer resolves complete, current automatic authority while the
+// lifecycle holds the admission read lock.
+type PolicyAuthorizer func(ctx context.Context, record unified.ActionAuditRecord, now time.Time) (unified.ActionPolicyAuthorizationLease, string, error)
+
+// WithPolicyMutation serializes a policy write against automatic admission.
+// Writers must persist their change before returning.
+func (s *Service) WithPolicyMutation(write func() error) error {
+ if s == nil || write == nil {
+ return errors.New("policy mutation unavailable")
+ }
+ coordinator := s.admissionCoordinator()
+ coordinator.mu.Lock()
+ defer coordinator.mu.Unlock()
+ return write()
}
// PlanOptions carries broker-owned planning metadata that must never be
@@ -458,6 +487,18 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID, actor, reason st
}
now := s.now()
+ if stopped, stopErr := s.emergencyStopped(orgID); stopErr != nil || stopped {
+ if stopErr != nil {
+ return unified.ActionAuditRecord{}, &PolicyCheckError{Err: stopErr}
+ }
+ failed, persistErr := RecordRefusedExecution(store, record, actor, now, unified.ErrActionEmergencyStop)
+ if persistErr != nil {
+ return unified.ActionAuditRecord{}, &PersistError{Op: "emergency-stop refusal", Err: persistErr}
+ }
+ s.publishTransition(orgID, failed)
+ s.publishCompleted(failed)
+ return failed, unified.ErrActionEmergencyStop
+ }
if err := unified.ValidateActionExecutionStart(record, now); err != nil {
if unified.IsPermanentActionExecutionRefusal(err) {
failed, persistErr := RecordRefusedExecution(store, record, actor, now, err)
@@ -532,6 +573,134 @@ func (s *Service) Execute(ctx context.Context, orgID, actionID, actor, reason st
return completed, nil
}
+// ExecuteUnderPolicy is the only automatic dispatch boundary. It revalidates
+// the complete policy under the admission lock and commits policy approval and
+// executing atomically before the executor can be called.
+func (s *Service) ExecuteUnderPolicy(ctx context.Context, orgID, actionID, actor string, authorize PolicyAuthorizer) (unified.ActionAuditRecord, error) {
+ coordinator := s.admissionCoordinator()
+ coordinator.mu.RLock()
+ started, store, admitted, admissionErr := s.beginPolicyExecution(ctx, orgID, actionID, actor, authorize)
+ coordinator.mu.RUnlock()
+ if !admitted {
+ return started, admissionErr
+ }
+ // The executing transition is the authorization linearization point.
+ // Later emergency-stop changes may request best-effort cancellation but
+ // cannot claim that an external mutation was rolled back.
+ result, execErr := s.Executor.ExecuteAction(ctx, started)
+ if execErr != nil {
+ result = &unified.ExecutionResult{Success: false, ErrorMessage: execErr.Error()}
+ }
+ completed, doneEvent, err := unified.CompleteActionExecution(started, result, actor, s.now())
+ if err != nil {
+ return unified.ActionAuditRecord{}, err
+ }
+ if err := store.RecordActionExecutionResult(completed, doneEvent); err != nil {
+ return unified.ActionAuditRecord{}, &PersistError{Op: "action execution result", Err: err}
+ }
+ s.publishTransition(orgID, completed)
+ s.publishCompleted(completed)
+ return completed, nil
+}
+
+func (s *Service) beginPolicyExecution(ctx context.Context, orgID, actionID, actor string, authorize PolicyAuthorizer) (unified.ActionAuditRecord, Store, bool, error) {
+ actionID = strings.TrimSpace(actionID)
+ store, err := s.store(orgID)
+ if err != nil {
+ return unified.ActionAuditRecord{}, nil, false, err
+ }
+ record, found, err := store.GetActionAudit(actionID)
+ if err != nil {
+ return unified.ActionAuditRecord{}, store, false, &QueryError{Op: "action audit", Err: err}
+ }
+ if !found {
+ return unified.ActionAuditRecord{}, store, false, &ActionNotFoundError{ActionID: actionID}
+ }
+ if record.State == unified.ActionStateExecuting || record.State == unified.ActionStateCompleted || record.State == unified.ActionStateFailed {
+ return record, store, false, nil
+ }
+ now := s.now()
+ if record.State == unified.ActionStateApproved {
+ for _, approval := range record.Approvals {
+ if approval.Method == unified.MethodPolicy && approval.PolicyLease == nil {
+ failed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, unified.ErrActionPolicyAuthorizationInvalid)
+ return failed, store, false, refuseErr
+ }
+ }
+ }
+ if stopped, stopErr := s.emergencyStopped(orgID); stopErr != nil || stopped {
+ reason := error(unified.ErrActionEmergencyStop)
+ if stopErr != nil {
+ reason = fmt.Errorf("%w: %v", unified.ErrActionPolicyAuthorizationInvalid, stopErr)
+ }
+ failed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, reason)
+ return failed, store, false, refuseErr
+ }
+ if s.Executor == nil {
+ return unified.ActionAuditRecord{}, store, false, ErrExecutorUnavailable
+ }
+ if err := s.ValidatePlanFresh(orgID, record); err != nil {
+ failed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, fmt.Errorf("%w: %v", unified.ErrActionPlanDrift, err))
+ return failed, store, false, refuseErr
+ }
+ if err := validateExecutionPolicy(store, record); err != nil {
+ if !unified.IsPermanentActionExecutionRefusal(err) {
+ err = fmt.Errorf("%w: %v", unified.ErrActionPolicyAuthorizationInvalid, err)
+ }
+ failed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, err)
+ return failed, store, false, refuseErr
+ }
+ if authorize == nil {
+ failed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, unified.ErrActionPolicyAuthorizationInvalid)
+ return failed, store, false, refuseErr
+ }
+ lease, reason, err := authorize(ctx, record, now)
+ if err != nil {
+ if !errors.Is(err, unified.ErrActionPolicyAuthorizationExpired) && !errors.Is(err, unified.ErrActionPolicyAuthorizationRevoked) {
+ err = fmt.Errorf("%w: %v", unified.ErrActionPolicyAuthorizationInvalid, err)
+ }
+ failed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, err)
+ return failed, store, false, refuseErr
+ }
+ if strings.TrimSpace(lease.OrgID) != strings.TrimSpace(orgID) || lease.ApprovalPolicy != record.Plan.ApprovalPolicy || lease.AutoAuthorization == unified.AutoAuthorizeNever || lease.ApprovalPolicy == unified.ApprovalDryRun || lease.ApprovalPolicy == unified.ApprovalMultiFactor {
+ failed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, unified.ErrActionPolicyAuthorizationInvalid)
+ return failed, store, false, refuseErr
+ }
+ started, approvedEvent, startEvent, err := unified.BeginPolicyActionExecution(record, unified.ActionApprovalRecord{Actor: actor, Reason: reason}, lease, now)
+ if err != nil {
+ failed, refuseErr := s.refusePolicyAdmission(store, orgID, record, actor, now, err)
+ return failed, store, false, refuseErr
+ }
+ if err := store.RecordActionPolicyExecutionStart(started, approvedEvent, startEvent); err != nil {
+ if errors.Is(err, unified.ErrActionAlreadyExecuting) || errors.Is(err, unified.ErrActionExecutionFinal) {
+ current, ok, queryErr := store.GetActionAudit(actionID)
+ if queryErr == nil && ok {
+ return current, store, false, nil
+ }
+ }
+ return unified.ActionAuditRecord{}, store, false, &PersistError{Op: "policy action execution start", Err: err}
+ }
+ s.publishTransition(orgID, started)
+ return started, store, true, nil
+}
+
+func (s *Service) emergencyStopped(orgID string) (bool, error) {
+ if s == nil || s.EmergencyStop == nil {
+ return false, nil
+ }
+ return s.EmergencyStop(orgID)
+}
+
+func (s *Service) refusePolicyAdmission(store Store, orgID string, record unified.ActionAuditRecord, actor string, now time.Time, reason error) (unified.ActionAuditRecord, error) {
+ failed, persistErr := RecordRefusedExecution(store, record, actor, now, reason)
+ if persistErr != nil {
+ return unified.ActionAuditRecord{}, &PersistError{Op: "policy admission refusal", Err: persistErr}
+ }
+ s.publishTransition(orgID, failed)
+ s.publishCompleted(failed)
+ return failed, reason
+}
+
// ValidatePlanFresh replans the persisted request against the live
// resource contract and refuses execution when the action identity, plan
// hash, resource version, or capability policy no longer match. Execute
diff --git a/internal/actionlifecycle/service_test.go b/internal/actionlifecycle/service_test.go
index d77f3e8da5..13b0a80014 100644
--- a/internal/actionlifecycle/service_test.go
+++ b/internal/actionlifecycle/service_test.go
@@ -253,6 +253,309 @@ func TestExecuteAfterSQLiteRestartDoesNotReadmitExecutingAction(t *testing.T) {
}
}
+func policyTestLease(record unified.ActionAuditRecord, now time.Time) unified.ActionPolicyAuthorizationLease {
+ lease := unified.ActionPolicyAuthorizationLease{
+ Version: 1, OrgID: "default", ActionID: record.ID, ResourceID: record.Request.ResourceID,
+ CapabilityName: record.Request.CapabilityName, PlanHash: record.Plan.PlanHash,
+ CapabilityPolicyVersion: record.Plan.PolicyVersion, AutoAuthorization: unified.AutoAuthorizeLowRisk,
+ ApprovalPolicy: record.Plan.ApprovalPolicy, TenantPolicyVersion: "tenant:v1",
+ EffectiveAutonomyLevel: "assisted", LicenseAllowsAutoFix: true,
+ ResourcePolicyVersion: "resource:v1", CapabilityNames: []string{"restart"},
+ IssuedAt: now, ExpiresAt: now.Add(time.Minute),
+ }
+ lease.Digest = unified.ActionPolicyAuthorizationDigest(lease)
+ return lease
+}
+
+func runPolicyAdmissionCommitsAtomically(t *testing.T, store unified.ResourceStore) {
+ now := time.Now().UTC()
+ executor := &stubExecutor{result: &unified.ExecutionResult{Success: true}}
+ service := serviceForStore(t, store, testResource(now, unified.ApprovalAdmin), executor)
+ service.Now = func() time.Time { return now }
+ plan, err := service.Plan(context.Background(), "default", restartRequest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ completed, err := service.ExecuteUnderPolicy(context.Background(), "default", plan.ActionID, "pulse_patrol_policy", func(_ context.Context, record unified.ActionAuditRecord, at time.Time) (unified.ActionPolicyAuthorizationLease, string, error) {
+ return policyTestLease(record, at), "bounded policy", nil
+ })
+ if err != nil || completed.State != unified.ActionStateCompleted || executor.calls != 1 {
+ t.Fatalf("completed=%#v err=%v calls=%d", completed, err, executor.calls)
+ }
+ if len(completed.Approvals) != 1 || completed.Approvals[0].Method != unified.MethodPolicy || completed.Approvals[0].PolicyLease == nil {
+ t.Fatalf("approvals=%#v", completed.Approvals)
+ }
+ events, err := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ seenApproved, seenExecuting := false, false
+ for _, event := range events {
+ seenApproved = seenApproved || event.State == unified.ActionStateApproved
+ seenExecuting = seenExecuting || event.State == unified.ActionStateExecuting
+ }
+ if !seenApproved || !seenExecuting {
+ t.Fatalf("events=%#v", events)
+ }
+}
+
+func TestPolicyAdmissionCommitsApprovalAndExecutingAtomicallyMemoryStore(t *testing.T) {
+ runPolicyAdmissionCommitsAtomically(t, unified.NewMemoryStore())
+}
+func TestPolicyAdmissionCommitsApprovalAndExecutingAtomicallySQLite(t *testing.T) {
+ store, err := unified.NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+ runPolicyAdmissionCommitsAtomically(t, store)
+}
+
+func runPolicyBarrierRevocations(t *testing.T, storeFactory func(t *testing.T) unified.ResourceStore) {
+ cases := []struct {
+ name string
+ mutate func(*unified.ActionPolicyAuthorizationLease) error
+ }{
+ {"policy_row_deleted", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationInvalid
+ }},
+ {"policy_disabled", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"capability_removed_from_allowlist", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"recurring_window_closed", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"mode_downgraded_to_approval", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"mode_downgraded_to_monitor", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"full_mode_unlock_removed", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"license_removes_effective_mode", func(lease *unified.ActionPolicyAuthorizationLease) error {
+ lease.LicenseAllowsAutoFix = false
+ lease.Digest = unified.ActionPolicyAuthorizationDigest(*lease)
+ return nil
+ }},
+ {"capability_removed", func(*unified.ActionPolicyAuthorizationLease) error { return unified.ErrActionPlanDrift }},
+ {"safety_class_changed_to_never", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"approval_floor_changed_to_dry_run", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"approval_floor_changed_to_mfa", func(*unified.ActionPolicyAuthorizationLease) error {
+ return unified.ErrActionPolicyAuthorizationRevoked
+ }},
+ {"never_auto_remediate_enabled", func(*unified.ActionPolicyAuthorizationLease) error { return unified.ErrResourceRemediationLocked }},
+ {"emergency_stop_enabled", func(lease *unified.ActionPolicyAuthorizationLease) error {
+ lease.EmergencyStop = true
+ lease.Digest = unified.ActionPolicyAuthorizationDigest(*lease)
+ return nil
+ }},
+ {"policy_store_unreadable", func(*unified.ActionPolicyAuthorizationLease) error { return errors.New("policy store unavailable") }},
+ {"lease_wrong_org", func(lease *unified.ActionPolicyAuthorizationLease) error {
+ lease.OrgID = "other"
+ lease.Digest = unified.ActionPolicyAuthorizationDigest(*lease)
+ return nil
+ }},
+ {"lease_expired", func(lease *unified.ActionPolicyAuthorizationLease) error {
+ lease.ExpiresAt = lease.IssuedAt
+ lease.Digest = unified.ActionPolicyAuthorizationDigest(*lease)
+ return nil
+ }},
+ {"lease_digest_tampered", func(lease *unified.ActionPolicyAuthorizationLease) error {
+ lease.Digest = "sha256:tampered"
+ return nil
+ }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ store := storeFactory(t)
+ now := time.Now().UTC()
+ executor := &stubExecutor{result: &unified.ExecutionResult{Success: true}}
+ service := serviceForStore(t, store, testResource(now, unified.ApprovalAdmin), executor)
+ service.Now = func() time.Time { return now }
+ plan, err := service.Plan(context.Background(), "default", restartRequest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ failed, err := service.ExecuteUnderPolicy(context.Background(), "default", plan.ActionID, "pulse_patrol_policy", func(_ context.Context, record unified.ActionAuditRecord, at time.Time) (unified.ActionPolicyAuthorizationLease, string, error) {
+ lease := policyTestLease(record, at)
+ if mutationErr := tc.mutate(&lease); mutationErr != nil {
+ return unified.ActionPolicyAuthorizationLease{}, "", mutationErr
+ }
+ return lease, "policy", nil
+ })
+ if err == nil || failed.State != unified.ActionStateFailed || executor.calls != 0 {
+ t.Fatalf("failed=%#v err=%v calls=%d", failed, err, executor.calls)
+ }
+ if len(failed.Approvals) != 0 {
+ t.Fatalf("policy approval persisted: %#v", failed.Approvals)
+ }
+ events, _ := store.GetActionLifecycleEvents(plan.ActionID, time.Time{}, 20)
+ for _, event := range events {
+ if event.State == unified.ActionStateExecuting {
+ t.Fatalf("executing event persisted: %#v", events)
+ }
+ }
+ })
+ }
+}
+
+func TestExecuteUnderPolicyBarrierRevocationsMemoryStore(t *testing.T) {
+ runPolicyBarrierRevocations(t, func(*testing.T) unified.ResourceStore { return unified.NewMemoryStore() })
+}
+func TestExecuteUnderPolicyBarrierRevocationsSQLite(t *testing.T) {
+ runPolicyBarrierRevocations(t, func(t *testing.T) unified.ResourceStore {
+ store, err := unified.NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+ return store
+ })
+}
+
+func runHumanApprovalSurvivesPolicyRevocation(t *testing.T, store unified.ResourceStore) {
+ now := time.Now().UTC()
+ executor := &stubExecutor{result: &unified.ExecutionResult{Success: true}}
+ service := serviceForStore(t, store, testResource(now, unified.ApprovalAdmin), executor)
+ plan, err := service.Plan(context.Background(), "default", restartRequest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = service.Decide(context.Background(), "default", plan.ActionID, unified.ActionApprovalRecord{Actor: "operator", Method: unified.MethodAPI, Outcome: unified.OutcomeApproved}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = service.Execute(context.Background(), "default", plan.ActionID, "operator", ""); err != nil || executor.calls != 1 {
+ t.Fatalf("err=%v calls=%d", err, executor.calls)
+ }
+}
+func TestHumanApprovalSurvivesAutomaticPolicyRevocationMemoryStore(t *testing.T) {
+ runHumanApprovalSurvivesPolicyRevocation(t, unified.NewMemoryStore())
+}
+func TestHumanApprovalSurvivesAutomaticPolicyRevocationSQLite(t *testing.T) {
+ store, err := unified.NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+ runHumanApprovalSurvivesPolicyRevocation(t, store)
+}
+
+func runEmergencyStopBlocksHumanAndPolicy(t *testing.T, store unified.ResourceStore) {
+ now := time.Now().UTC()
+ executor := &stubExecutor{result: &unified.ExecutionResult{Success: true}}
+ service := serviceForStore(t, store, testResource(now, unified.ApprovalAdmin), executor)
+ service.EmergencyStop = func(string) (bool, error) { return true, nil }
+ human := restartRequest()
+ human.RequestID = "human-stop"
+ plan, err := service.Plan(context.Background(), "default", human)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = service.Decide(context.Background(), "default", plan.ActionID, unified.ActionApprovalRecord{Actor: "operator", Method: unified.MethodAPI, Outcome: unified.OutcomeApproved}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = service.Execute(context.Background(), "default", plan.ActionID, "operator", ""); !errors.Is(err, unified.ErrActionEmergencyStop) {
+ t.Fatalf("human error=%v", err)
+ }
+ policy := restartRequest()
+ policy.RequestID = "policy-stop"
+ policyPlan, err := service.Plan(context.Background(), "default", policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = service.ExecuteUnderPolicy(context.Background(), "default", policyPlan.ActionID, "pulse_patrol_policy", func(_ context.Context, record unified.ActionAuditRecord, at time.Time) (unified.ActionPolicyAuthorizationLease, string, error) {
+ return policyTestLease(record, at), "policy", nil
+ }); !errors.Is(err, unified.ErrActionEmergencyStop) {
+ t.Fatalf("policy error=%v", err)
+ }
+ if executor.calls != 0 {
+ t.Fatalf("executor calls=%d", executor.calls)
+ }
+}
+func TestEmergencyStopBlocksHumanAndPolicyAdmissionMemoryStore(t *testing.T) {
+ runEmergencyStopBlocksHumanAndPolicy(t, unified.NewMemoryStore())
+}
+func TestEmergencyStopBlocksHumanAndPolicyAdmissionSQLite(t *testing.T) {
+ store, err := unified.NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+ runEmergencyStopBlocksHumanAndPolicy(t, store)
+}
+
+func TestLegacyPolicyApprovalWithoutLeaseFailsClosedAfterRestart(t *testing.T) {
+ dir := t.TempDir()
+ first, err := unified.NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ service := serviceForStore(t, first, testResource(now, unified.ApprovalAdmin), &stubExecutor{})
+ plan, err := service.Plan(context.Background(), "default", restartRequest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = service.Decide(context.Background(), "default", plan.ActionID, unified.ActionApprovalRecord{Actor: "pulse_patrol_policy", Method: unified.MethodPolicy, Outcome: unified.OutcomeApproved}); err != nil {
+ t.Fatal(err)
+ }
+ if err = first.Close(); err != nil {
+ t.Fatal(err)
+ }
+ second, err := unified.NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer second.Close()
+ executor := &stubExecutor{result: &unified.ExecutionResult{Success: true}}
+ service = serviceForStore(t, second, testResource(now, unified.ApprovalAdmin), executor)
+ failed, err := service.ExecuteUnderPolicy(context.Background(), "default", plan.ActionID, "pulse_patrol_policy", func(_ context.Context, record unified.ActionAuditRecord, at time.Time) (unified.ActionPolicyAuthorizationLease, string, error) {
+ return policyTestLease(record, at), "policy", nil
+ })
+ if !errors.Is(err, unified.ErrActionPolicyAuthorizationInvalid) || failed.State != unified.ActionStateFailed || executor.calls != 0 {
+ t.Fatalf("failed=%#v err=%v calls=%d", failed, err, executor.calls)
+ }
+}
+
+func TestQueuedPolicyActionRevalidatesAfterSQLiteRestart(t *testing.T) {
+ dir := t.TempDir()
+ first, err := unified.NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ service := serviceForStore(t, first, testResource(now, unified.ApprovalAdmin), &stubExecutor{})
+ plan, err := service.Plan(context.Background(), "default", restartRequest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = first.Close(); err != nil {
+ t.Fatal(err)
+ }
+ second, err := unified.NewSQLiteResourceStore(dir, "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer second.Close()
+ executor := &stubExecutor{result: &unified.ExecutionResult{Success: true}}
+ service = serviceForStore(t, second, testResource(now, unified.ApprovalAdmin), executor)
+ failed, err := service.ExecuteUnderPolicy(context.Background(), "default", plan.ActionID, "pulse_patrol_policy", func(context.Context, unified.ActionAuditRecord, time.Time) (unified.ActionPolicyAuthorizationLease, string, error) {
+ return unified.ActionPolicyAuthorizationLease{}, "", unified.ErrActionPolicyAuthorizationRevoked
+ })
+ if !errors.Is(err, unified.ErrActionPolicyAuthorizationRevoked) || failed.State != unified.ActionStateFailed || executor.calls != 0 {
+ t.Fatalf("failed=%#v err=%v calls=%d", failed, err, executor.calls)
+ }
+}
+
type stubExecutor struct {
result *unified.ExecutionResult
err error
diff --git a/internal/api/actions.go b/internal/api/actions.go
index dc35b051e8..8286482511 100644
--- a/internal/api/actions.go
+++ b/internal/api/actions.go
@@ -69,6 +69,8 @@ func (h *ResourceHandlers) ActionLifecycle() *actionlifecycle.Service {
Executor: h.actionExecutor,
OnActionCompleted: h.actionCompleted,
OnActionTransition: h.actionTransition,
+ PolicyAdmission: h.policyAdmission,
+ EmergencyStop: h.actionEmergencyStop,
}
}
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index ffdadabe02..163ba87c4c 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -65,6 +65,7 @@ type AISettingsHandler struct {
resourceStoreProvider func(orgID string) (unifiedresources.ResourceStore, error)
actionBrokerFactory func(orgID string) aicontracts.OrchestratorActionBroker
proposalCatalogFactory func(orgID string) tools.ProposalCatalog
+ policyMutation func(func() error) error
metadataProvider ai.MetadataProvider
patrolThresholdProvider ai.ThresholdProvider
metricsHistoryProvider ai.MetricsHistoryProvider
@@ -135,6 +136,12 @@ func (h *AISettingsHandler) SetResourceStoreProvider(provider func(orgID string)
h.resourceStoreProvider = provider
}
+func (h *AISettingsHandler) SetPolicyMutationCoordinator(coordinator func(func() error) error) {
+ h.stateMu.Lock()
+ defer h.stateMu.Unlock()
+ h.policyMutation = coordinator
+}
+
// SetActionBrokerFactory installs the per-org typed action proposal broker
// used by the investigation orchestrator. Core-owned: it binds the tenant
// and the fixed Patrol actor, so enterprise code can only propose typed
@@ -7654,17 +7661,28 @@ func (h *AISettingsHandler) HandleUpdatePatrolAutonomyMonitorOnly(w http.Respons
// monitor-only save.
effectiveUnlocked := false
- cfg.PatrolAutonomyLevel = config.PatrolAutonomyMonitor
- cfg.PatrolFullModeUnlocked = effectiveUnlocked
- cfg.PatrolInvestigationBudget = req.InvestigationBudget
- cfg.PatrolInvestigationTimeoutSec = req.InvestigationTimeoutSec
-
persistence := h.getPersistence(r.Context())
if persistence == nil {
writeErrorResponse(w, http.StatusServiceUnavailable, "not_configured", "Pulse Patrol not configured", nil)
return
}
- if err := persistence.SaveAIConfig(*cfg); err != nil {
+ write := func() error {
+ cfg.PatrolAutonomyLevel = config.PatrolAutonomyMonitor
+ cfg.PatrolFullModeUnlocked = effectiveUnlocked
+ cfg.PatrolInvestigationBudget = req.InvestigationBudget
+ cfg.PatrolInvestigationTimeoutSec = req.InvestigationTimeoutSec
+ return persistence.SaveAIConfig(*cfg)
+ }
+ h.stateMu.RLock()
+ coordinator := h.policyMutation
+ h.stateMu.RUnlock()
+ var saveErr error
+ if coordinator != nil {
+ saveErr = coordinator(write)
+ } else {
+ saveErr = write()
+ }
+ if saveErr != nil {
writeErrorResponse(w, http.StatusInternalServerError, "save_failed", "Failed to save Pulse Patrol autonomy settings", nil)
return
}
diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.go
index afaaf012fe..7e3a524098 100644
--- a/internal/api/ai_handlers_test.go
+++ b/internal/api/ai_handlers_test.go
@@ -199,6 +199,11 @@ func TestAISettingsHandler_PatrolAutonomyMonitorOnlyAllowsMonitor(t *testing.T)
cfg := &config.Config{DataPath: tmp}
persistence := config.NewConfigPersistence(tmp)
handler := newTestAISettingsHandler(cfg, persistence, nil)
+ policyMutationCalls := 0
+ handler.SetPolicyMutationCoordinator(func(write func() error) error {
+ policyMutationCalls++
+ return write()
+ })
body := `{"autonomy_level":"monitor","full_mode_unlocked":true,"investigation_budget":2,"investigation_timeout_sec":30}`
req := newLoopbackRequest(http.MethodPut, "/api/ai/patrol/autonomy", strings.NewReader(body))
@@ -223,6 +228,7 @@ func TestAISettingsHandler_PatrolAutonomyMonitorOnlyAllowsMonitor(t *testing.T)
require.False(t, saved.PatrolFullModeUnlocked)
require.Equal(t, 5, saved.PatrolInvestigationBudget)
require.Equal(t, 60, saved.PatrolInvestigationTimeoutSec)
+ require.Equal(t, 1, policyMutationCalls)
premiumBody := `{"autonomy_level":"approval","investigation_budget":10,"investigation_timeout_sec":120}`
premiumReq := newLoopbackRequest(http.MethodPut, "/api/ai/patrol/autonomy", strings.NewReader(premiumBody))
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 05632f1fc9..bda9b093c8 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -20637,9 +20637,10 @@ func TestContract_PatrolActionBrokerKeepsPolicyExecutionCoreOwned(t *testing.T)
}
for _, required := range []string{
"autoAuthorizationDecision",
+ "policyAuthorizationLease",
"AutoAuthorizeLowRisk",
"AllowsAutoRemediationAt",
- "MethodPolicy",
+ "ExecuteUnderPolicy",
"pulse_patrol_policy",
} {
if !strings.Contains(src, required) {
diff --git a/internal/api/patrol_action_broker.go b/internal/api/patrol_action_broker.go
index 19c6111865..38b1aa63f9 100644
--- a/internal/api/patrol_action_broker.go
+++ b/internal/api/patrol_action_broker.go
@@ -2,6 +2,8 @@ package api
import (
"context"
+ "crypto/sha256"
+ "encoding/json"
"fmt"
"strings"
"time"
@@ -26,6 +28,8 @@ const patrolActionPolicyActor = "pulse_patrol_policy"
type PatrolActionPolicySnapshot struct {
EffectiveAutonomyLevel string
FullModeUnlocked bool
+ EmergencyStop bool
+ PolicyVersion string
}
type PatrolActionPolicyProvider func(ctx context.Context, orgID string) (PatrolActionPolicySnapshot, error)
@@ -155,27 +159,10 @@ func (b *patrolActionBroker) Submit(ctx context.Context, proposal aicontracts.Ac
return dispositionFromRecord(record), nil
}
- if allowed, reason, policyErr := b.autoAuthorizationDecision(ctx, proposal); policyErr == nil && allowed {
- // Re-evaluate immediately before the decision+dispatch sequence so a
- // resource lock, scope removal, or tenant-mode downgrade cannot leave
- // behind a reusable policy approval. A failed recheck leaves the plan in
- // its ordinary pending/planned state.
- stillAllowed, _, policyErr := b.autoAuthorizationDecision(ctx, proposal)
- if policyErr != nil || !stillAllowed {
- return dispositionFromRecord(record), nil
- }
- if record.State == unified.ActionStatePending {
- record, err = b.lifecycle().Decide(ctx, b.orgID, plan.ActionID, unified.ActionApprovalRecord{
- Actor: patrolActionPolicyActor,
- Method: unified.MethodPolicy,
- Outcome: unified.OutcomeApproved,
- Reason: reason,
- })
- if err != nil {
- return aicontracts.ActionDisposition{}, err
- }
- }
- record, err = b.lifecycle().Execute(ctx, b.orgID, plan.ActionID, patrolActionPolicyActor, reason)
+ if allowed, _, policyErr := b.autoAuthorizationDecision(ctx, proposal); policyErr == nil && allowed {
+ record, err = b.lifecycle().ExecuteUnderPolicy(ctx, b.orgID, plan.ActionID, patrolActionPolicyActor, func(ctx context.Context, current unified.ActionAuditRecord, now time.Time) (unified.ActionPolicyAuthorizationLease, string, error) {
+ return b.policyAuthorizationLease(ctx, proposal, current, now)
+ })
if err != nil {
if record.State == unified.ActionStateFailed {
return dispositionFromRecord(record), nil
@@ -187,6 +174,71 @@ func (b *patrolActionBroker) Submit(ctx context.Context, proposal aicontracts.Ac
return dispositionFromRecord(record), nil
}
+func (b *patrolActionBroker) policyAuthorizationLease(ctx context.Context, proposal aicontracts.ActionProposal, record unified.ActionAuditRecord, now time.Time) (unified.ActionPolicyAuthorizationLease, string, error) {
+ allowed, reason, err := b.autoAuthorizationDecisionAt(ctx, proposal, now)
+ if err != nil {
+ return unified.ActionPolicyAuthorizationLease{}, "", err
+ }
+ if !allowed {
+ return unified.ActionPolicyAuthorizationLease{}, "", unified.ErrActionPolicyAuthorizationRevoked
+ }
+ snapshot, err := b.policy(ctx, b.orgID)
+ if err != nil {
+ return unified.ActionPolicyAuthorizationLease{}, "", err
+ }
+ capabilities, err := b.lifecycle().Capabilities(ctx, b.orgID, proposal.ResourceID)
+ if err != nil {
+ return unified.ActionPolicyAuthorizationLease{}, "", err
+ }
+ var capability unified.ResourceCapability
+ foundCapability := false
+ for _, candidate := range capabilities {
+ if strings.TrimSpace(candidate.Name) == proposal.CapabilityName {
+ capability = candidate
+ foundCapability = true
+ break
+ }
+ }
+ if !foundCapability {
+ return unified.ActionPolicyAuthorizationLease{}, "", unified.ErrActionPolicyAuthorizationRevoked
+ }
+ state, found, err := b.lifecycle().ResourceOperatorState(b.orgID, proposal.ResourceID)
+ if err != nil || !found {
+ if err != nil {
+ return unified.ActionPolicyAuthorizationLease{}, "", err
+ }
+ return unified.ActionPolicyAuthorizationLease{}, "", unified.ErrActionPolicyAuthorizationInvalid
+ }
+ tenantVersion := strings.TrimSpace(snapshot.PolicyVersion)
+ if tenantVersion == "" {
+ tenantVersion = policySnapshotVersion(snapshot)
+ }
+ resourcePayload, _ := json.Marshal(unified.NormalizeResourceOperatorState(state))
+ resourceSum := sha256.Sum256(resourcePayload)
+ expiresAt := record.Plan.ExpiresAt
+ if expiresAt.IsZero() || expiresAt.After(now.Add(time.Minute)) {
+ expiresAt = now.Add(time.Minute)
+ }
+ lease := unified.ActionPolicyAuthorizationLease{
+ Version: 1, OrgID: b.orgID, ActionID: record.ID, ResourceID: proposal.ResourceID, CapabilityName: proposal.CapabilityName,
+ PlanHash: record.Plan.PlanHash, CapabilityPolicyVersion: record.Plan.PolicyVersion,
+ AutoAuthorization: unified.NormalizeActionAutoAuthorizationClass(capability.AutoAuthorization), ApprovalPolicy: capability.MinimumApprovalLevel,
+ TenantPolicyVersion: tenantVersion, EffectiveAutonomyLevel: strings.TrimSpace(snapshot.EffectiveAutonomyLevel), LicenseAllowsAutoFix: true,
+ FullModeUnlocked: snapshot.FullModeUnlocked, EmergencyStop: snapshot.EmergencyStop,
+ ResourcePolicyVersion: fmt.Sprintf("resource-policy:sha256:%x", resourceSum[:12]), CapabilityNames: append([]string(nil), state.AutoRemediationPolicy.CapabilityNames...),
+ Window: state.AutoRemediationPolicy.Window, NeverAutoRemediate: state.NeverAutoRemediate, IssuedAt: now.UTC(), ExpiresAt: expiresAt.UTC(),
+ }
+ lease.Digest = unified.ActionPolicyAuthorizationDigest(lease)
+ return lease, reason, nil
+}
+
+func policySnapshotVersion(snapshot PatrolActionPolicySnapshot) string {
+ snapshot.PolicyVersion = ""
+ payload, _ := json.Marshal(snapshot)
+ sum := sha256.Sum256(payload)
+ return fmt.Sprintf("tenant-policy:sha256:%x", sum[:12])
+}
+
func dispositionFromRecord(record unified.ActionAuditRecord) aicontracts.ActionDisposition {
return aicontracts.ActionDisposition{
ActionID: record.ID,
@@ -197,6 +249,10 @@ func dispositionFromRecord(record unified.ActionAuditRecord) aicontracts.ActionD
}
func (b *patrolActionBroker) autoAuthorizationDecision(ctx context.Context, proposal aicontracts.ActionProposal) (bool, string, error) {
+ return b.autoAuthorizationDecisionAt(ctx, proposal, b.currentTime())
+}
+
+func (b *patrolActionBroker) autoAuthorizationDecisionAt(ctx context.Context, proposal aicontracts.ActionProposal, now time.Time) (bool, string, error) {
if b.policy == nil {
return false, "", nil
}
@@ -204,6 +260,9 @@ func (b *patrolActionBroker) autoAuthorizationDecision(ctx context.Context, prop
if err != nil {
return false, "", err
}
+ if snapshot.EmergencyStop {
+ return false, "", nil
+ }
capabilities, err := b.lifecycle().Capabilities(ctx, b.orgID, proposal.ResourceID)
if err != nil {
return false, "", err
@@ -238,7 +297,7 @@ func (b *patrolActionBroker) autoAuthorizationDecision(ctx context.Context, prop
if err != nil {
return false, "", err
}
- if !found || !state.AllowsAutoRemediationAt(proposal.CapabilityName, b.currentTime()) {
+ if !found || !state.AllowsAutoRemediationAt(proposal.CapabilityName, now) {
return false, "", nil
}
return true, fmt.Sprintf("Patrol %s policy authorized %s capability %s for resource %s", snapshot.EffectiveAutonomyLevel, class, proposal.CapabilityName, proposal.ResourceID), nil
diff --git a/internal/api/patrol_action_broker_test.go b/internal/api/patrol_action_broker_test.go
index 26fd4b8c8b..2426cea9d5 100644
--- a/internal/api/patrol_action_broker_test.go
+++ b/internal/api/patrol_action_broker_test.go
@@ -6,6 +6,7 @@ import (
"errors"
"net/http"
"net/http/httptest"
+ "strings"
"sync/atomic"
"testing"
"time"
@@ -430,7 +431,7 @@ func TestPatrolActionBrokerAutonomyModeIsAnUpperBound(t *testing.T) {
}
}
-func TestPatrolActionBrokerRevokedPolicyCannotLeaveReusableApproval(t *testing.T) {
+func TestPatrolActionBrokerDispatchTimePolicyRevocation(t *testing.T) {
h, executor := newPatrolBrokerTestHandlers(t, unified.ApprovalAdmin)
store, err := h.getStore("default")
if err != nil {
@@ -459,14 +460,14 @@ func TestPatrolActionBrokerRevokedPolicyCannotLeaveReusableApproval(t *testing.T
if err != nil {
t.Fatalf("Submit: %v", err)
}
- if disposition.State != string(unified.ActionStatePending) || executor.calls != 0 {
+ if disposition.State != string(unified.ActionStateFailed) || executor.calls != 0 {
t.Fatalf("revoked disposition=%#v calls=%d", disposition, executor.calls)
}
record, found, err := store.GetActionAudit(disposition.ActionID)
if err != nil || !found {
t.Fatalf("GetActionAudit: found=%v err=%v", found, err)
}
- if len(record.Approvals) != 0 || record.Result != nil {
+ if len(record.Approvals) != 0 || record.Result == nil || !strings.HasPrefix(record.Result.ErrorMessage, "policy_authorization_revoked:") {
t.Fatalf("revoked policy left reusable authority: approvals=%#v result=%#v", record.Approvals, record.Result)
}
}
diff --git a/internal/api/resources.go b/internal/api/resources.go
index 2981175614..96f4fdf36a 100644
--- a/internal/api/resources.go
+++ b/internal/api/resources.go
@@ -12,6 +12,7 @@ import (
"sync"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"
@@ -34,6 +35,8 @@ type ResourceHandlers struct {
actionExecutor ActionExecutor
actionCompleted func(unified.ActionAuditRecord)
actionTransition func(orgID string, record unified.ActionAuditRecord)
+ policyAdmission *actionlifecycle.PolicyAdmissionCoordinator
+ actionEmergencyStop func(orgID string) (bool, error)
discoveryReadiness ResourceDiscoveryReadinessProvider
}
@@ -85,6 +88,7 @@ func NewResourceHandlers(cfg *config.Config) *ResourceHandlers {
stores: make(map[string]unified.ResourceStore),
registryCache: make(map[string]registryCacheEntry),
supplementalRecords: make(map[unified.DataSource]SupplementalRecordsProvider),
+ policyAdmission: &actionlifecycle.PolicyAdmissionCoordinator{},
}
}
@@ -103,6 +107,10 @@ func (h *ResourceHandlers) SetActionExecutor(executor ActionExecutor) {
h.actionExecutor = executor
}
+func (h *ResourceHandlers) SetActionEmergencyStopChecker(checker func(orgID string) (bool, error)) {
+ h.actionEmergencyStop = checker
+}
+
// SetActionCompletedPublisher configures the terminal action notification hook
// used by the agent SSE bridge. It is intentionally outside the execution
// driver so refused-before-dispatch failures and future executor
diff --git a/internal/api/resources_operator_state.go b/internal/api/resources_operator_state.go
index 67439e794a..1072ce8a62 100644
--- a/internal/api/resources_operator_state.go
+++ b/internal/api/resources_operator_state.go
@@ -116,7 +116,12 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
SetAt: time.Now().UTC(),
SetBy: getUserID(r),
}
- persisted, err := unified.SetResourceOperatorStateWithMaintenanceLifecycle(store, state)
+ var persisted unified.ResourceOperatorState
+ err := h.ActionLifecycle().WithPolicyMutation(func() error {
+ var writeErr error
+ persisted, writeErr = unified.SetResourceOperatorStateWithMaintenanceLifecycle(store, state)
+ return writeErr
+ })
if err != nil {
if errors.Is(err, unified.ErrResourceOperatorStateInvalid) {
writeJSONError(w, http.StatusBadRequest, agentcapabilities.AgentErrCodeOperatorStateInvalid, err.Error())
@@ -130,7 +135,9 @@ func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r
case http.MethodDelete:
observedAt := time.Now().UTC()
actor := getUserID(r)
- if err := unified.ClearResourceOperatorStateWithMaintenanceLifecycle(store, resourceID, observedAt, actor); err != nil {
+ if err := h.ActionLifecycle().WithPolicyMutation(func() error {
+ return unified.ClearResourceOperatorStateWithMaintenanceLifecycle(store, resourceID, observedAt, actor)
+ }); err != nil {
http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
return
}
diff --git a/internal/api/router.go b/internal/api/router.go
index ddea2f0320..6b235c2f3c 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -660,7 +660,16 @@ func (r *Router) setupRoutes() {
// AI settings endpoints
r.aiSettingsHandler = NewAISettingsHandler(r.multiTenant, r.mtMonitor, r.agentExecServer)
if r.resourceHandlers != nil {
+ r.resourceHandlers.SetActionEmergencyStopChecker(func(orgID string) (bool, error) {
+ orgCtx := context.WithValue(context.Background(), OrgIDContextKey, approval.NormalizeOrgID(orgID))
+ svc := r.aiSettingsHandler.GetAIService(orgCtx)
+ if svc == nil || svc.GetConfig() == nil {
+ return true, nil
+ }
+ return svc.GetConfig().PatrolActionEmergencyStop, nil
+ })
r.aiSettingsHandler.SetResourceStoreProvider(r.resourceHandlers.getStore)
+ r.aiSettingsHandler.SetPolicyMutationCoordinator(r.resourceHandlers.ActionLifecycle().WithPolicyMutation)
r.resourceHandlers.SetActionTransitionPublisher(r.aiSettingsHandler.ReconcilePatrolActionTransition)
resourceHandlers := r.resourceHandlers
r.aiSettingsHandler.SetActionBrokerFactory(func(orgID string) aicontracts.OrchestratorActionBroker {
@@ -677,6 +686,7 @@ func (r *Router) setupRoutes() {
return PatrolActionPolicySnapshot{
EffectiveAutonomyLevel: svc.GetEffectivePatrolAutonomyLevel(),
FullModeUnlocked: cfg.PatrolFullModeUnlocked,
+ EmergencyStop: cfg.PatrolActionEmergencyStop,
}, nil
})
})
diff --git a/internal/api/router_routes_ai_relay.go b/internal/api/router_routes_ai_relay.go
index 2371a1cc6f..7685a637f7 100644
--- a/internal/api/router_routes_ai_relay.go
+++ b/internal/api/router_routes_ai_relay.go
@@ -352,7 +352,7 @@ func newAIAutoFixHandlerDeps(r *Router) extensions.AIAutoFixHandlerDeps {
if svc == nil {
return nil
}
- return &patrolConfigUpdateAdapter{handler: h, ctx: req.Context()}
+ return &patrolConfigUpdateAdapter{handler: h, ctx: req.Context(), resources: r.resourceHandlers}
},
GetRemediationEngine: func(orgID string) aicontracts.RemediationEngine {
return h.GetRemediationEngineForOrg(orgID)
@@ -865,8 +865,9 @@ func (p *patrolConfigAdapter) IsValidPatrolAutonomyLevel(level string) bool {
// patrolConfigUpdateAdapter implements aicontracts.PatrolConfigUpdater.
type patrolConfigUpdateAdapter struct {
- handler *AISettingsHandler
- ctx context.Context
+ handler *AISettingsHandler
+ ctx context.Context
+ resources *ResourceHandlers
}
var _ aicontracts.PatrolConfigUpdater = (*patrolConfigUpdateAdapter)(nil)
@@ -880,11 +881,17 @@ func (u *patrolConfigUpdateAdapter) SaveAutonomySettings(ctx context.Context, le
if cfg == nil {
return fmt.Errorf("AI config not available")
}
- cfg.PatrolFullModeUnlocked = unlocked
- cfg.PatrolAutonomyLevel = level
- cfg.PatrolInvestigationBudget = budget
- cfg.PatrolInvestigationTimeoutSec = timeoutSec
- return u.handler.getPersistence(ctx).SaveAIConfig(*cfg)
+ write := func() error {
+ cfg.PatrolFullModeUnlocked = unlocked
+ cfg.PatrolAutonomyLevel = level
+ cfg.PatrolInvestigationBudget = budget
+ cfg.PatrolInvestigationTimeoutSec = timeoutSec
+ return u.handler.getPersistence(ctx).SaveAIConfig(*cfg)
+ }
+ if u.resources != nil {
+ return u.resources.ActionLifecycle().WithPolicyMutation(write)
+ }
+ return write()
}
func (u *patrolConfigUpdateAdapter) ReloadConfig(ctx context.Context) error {
diff --git a/internal/config/ai.go b/internal/config/ai.go
index 64c6729fcf..b35bf75238 100644
--- a/internal/config/ai.go
+++ b/internal/config/ai.go
@@ -106,6 +106,7 @@ type AIConfig struct {
// Patrol Autonomy settings - controls automatic investigation and remediation of findings
PatrolAutonomyLevel string `json:"patrol_autonomy_level,omitempty"` // "monitor", "approval", "assisted", "full"
PatrolFullModeUnlocked bool `json:"patrol_full_mode_unlocked"` // User has acknowledged Full mode risks (required to use "full")
+ PatrolActionEmergencyStop bool `json:"patrol_action_emergency_stop"` // Blocks new human and policy action admission; does not imply rollback
PatrolInvestigationBudget int `json:"patrol_investigation_budget,omitempty"` // Max turns per investigation (default: 15)
PatrolInvestigationTimeoutSec int `json:"patrol_investigation_timeout_sec,omitempty"` // Max seconds per investigation (default: 300)
diff --git a/internal/config/ai_config_test.go b/internal/config/ai_config_test.go
index dd4028ccd7..507a25357e 100644
--- a/internal/config/ai_config_test.go
+++ b/internal/config/ai_config_test.go
@@ -68,6 +68,25 @@ func TestAIConfigControlLevelsUseSharedAgentCapabilityVocabulary(t *testing.T) {
}
}
+func TestAIConfigPatrolActionEmergencyStopPersistsExplicitly(t *testing.T) {
+ cfg := NewDefaultAIConfig()
+ if cfg.PatrolActionEmergencyStop {
+ t.Fatal("emergency stop must default to false")
+ }
+ cfg.PatrolActionEmergencyStop = true
+ payload, err := json.Marshal(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var decoded AIConfig
+ if err := json.Unmarshal(payload, &decoded); err != nil {
+ t.Fatal(err)
+ }
+ if !decoded.PatrolActionEmergencyStop {
+ t.Fatal("emergency stop was not preserved")
+ }
+}
+
func TestAIConfig_IsConfigured(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/unifiedresources/actions.go b/internal/unifiedresources/actions.go
index d31385f9b8..f6942e8ee3 100644
--- a/internal/unifiedresources/actions.go
+++ b/internal/unifiedresources/actions.go
@@ -2,6 +2,7 @@ package unifiedresources
import (
"bytes"
+ "crypto/sha256"
"encoding/json"
"errors"
"fmt"
@@ -57,6 +58,67 @@ type ActionApprovalRecord struct {
Timestamp time.Time `json:"timestamp"` // When the decision was made
Outcome ApprovalOutcome `json:"outcome"` // "approved" or "rejected"
Reason string `json:"reason,omitempty"`
+ // PolicyLease is present only for a server-owned policy authorization.
+ // Human decisions never carry this field. Policy approval and execution
+ // admission are persisted atomically, so the lease cannot become reusable.
+ PolicyLease *ActionPolicyAuthorizationLease `json:"policyLease,omitempty"`
+}
+
+// ActionPolicyAuthorizationLease binds automatic authorization to every
+// policy input that was current at the executing transition.
+type ActionPolicyAuthorizationLease struct {
+ Version int `json:"version"`
+ OrgID string `json:"orgId"`
+ ActionID string `json:"actionId"`
+ ResourceID string `json:"resourceId"`
+ CapabilityName string `json:"capabilityName"`
+ PlanHash string `json:"planHash"`
+ CapabilityPolicyVersion string `json:"capabilityPolicyVersion"`
+ AutoAuthorization ActionAutoAuthorizationClass `json:"autoAuthorization"`
+ ApprovalPolicy ActionApprovalLevel `json:"approvalPolicy"`
+ TenantPolicyVersion string `json:"tenantPolicyVersion"`
+ EffectiveAutonomyLevel string `json:"effectiveAutonomyLevel"`
+ LicenseAllowsAutoFix bool `json:"licenseAllowsAutoFix"`
+ FullModeUnlocked bool `json:"fullModeUnlocked"`
+ EmergencyStop bool `json:"emergencyStop"`
+ ResourcePolicyVersion string `json:"resourcePolicyVersion"`
+ CapabilityNames []string `json:"capabilityNames"`
+ Window *AutoRemediationWindow `json:"window,omitempty"`
+ NeverAutoRemediate bool `json:"neverAutoRemediate"`
+ IssuedAt time.Time `json:"issuedAt"`
+ ExpiresAt time.Time `json:"expiresAt"`
+ Digest string `json:"digest"`
+}
+
+// ActionPolicyAuthorizationDigest returns the canonical SHA-256 binding for
+// a lease. Digest itself is excluded from the encoded payload.
+func ActionPolicyAuthorizationDigest(lease ActionPolicyAuthorizationLease) string {
+ lease.Digest = ""
+ payload, _ := json.Marshal(lease)
+ sum := sha256.Sum256(payload)
+ return fmt.Sprintf("sha256:%x", sum[:])
+}
+
+// ValidateActionPolicyAuthorizationLease fails closed on incomplete,
+// malformed, expired, or tampered automatic authority.
+func ValidateActionPolicyAuthorizationLease(lease ActionPolicyAuthorizationLease, record ActionAuditRecord, now time.Time) error {
+ if lease.Version != 1 || strings.TrimSpace(lease.OrgID) == "" ||
+ lease.ActionID != record.ID || lease.ResourceID != CanonicalResourceID(record.Request.ResourceID) ||
+ lease.CapabilityName != strings.TrimSpace(record.Request.CapabilityName) ||
+ lease.PlanHash != record.Plan.PlanHash || lease.CapabilityPolicyVersion != record.Plan.PolicyVersion ||
+ strings.TrimSpace(lease.TenantPolicyVersion) == "" || strings.TrimSpace(lease.ResourcePolicyVersion) == "" {
+ return ErrActionPolicyAuthorizationInvalid
+ }
+ if lease.EmergencyStop || lease.NeverAutoRemediate || !lease.LicenseAllowsAutoFix {
+ return ErrActionPolicyAuthorizationRevoked
+ }
+ if lease.IssuedAt.IsZero() || lease.ExpiresAt.IsZero() || !now.Before(lease.ExpiresAt) {
+ return ErrActionPolicyAuthorizationExpired
+ }
+ if lease.Digest == "" || lease.Digest != ActionPolicyAuthorizationDigest(lease) {
+ return ErrActionPolicyAuthorizationInvalid
+ }
+ return nil
}
// ActionPreflight is the deterministic pre-execution readout shown before an
@@ -315,18 +377,56 @@ var (
// 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")
- ErrActionExecutionRefusal = errors.New("action execution refusal is not a permanent terminal refusal")
- ErrInvalidApprovalOutcome = errors.New("invalid approval outcome")
- ErrActionAuditAlreadyExists = errors.New("action audit already exists")
- ErrActionIdentityConflict = errors.New("action audit identity conflicts with the persisted record")
+ 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")
+ ErrActionExecutionRefusal = errors.New("action execution refusal is not a permanent terminal refusal")
+ ErrInvalidApprovalOutcome = errors.New("invalid approval outcome")
+ ErrActionAuditAlreadyExists = errors.New("action audit already exists")
+ ErrActionIdentityConflict = errors.New("action audit identity conflicts with the persisted record")
+ ErrActionPolicyAuthorizationInvalid = errors.New("policy_authorization_invalid")
+ ErrActionPolicyAuthorizationExpired = errors.New("policy_authorization_expired")
+ ErrActionPolicyAuthorizationRevoked = errors.New("policy_authorization_revoked")
+ ErrActionEmergencyStop = errors.New("action_emergency_stop")
)
+// BeginPolicyActionExecution atomically composes the policy approval and
+// executing record. Stores persist both lifecycle events in one CAS write.
+func BeginPolicyActionExecution(record ActionAuditRecord, approval ActionApprovalRecord, lease ActionPolicyAuthorizationLease, now time.Time) (ActionAuditRecord, ActionLifecycleEvent, ActionLifecycleEvent, error) {
+ if now.IsZero() {
+ now = time.Now().UTC()
+ } else {
+ now = now.UTC()
+ }
+ if record.State != ActionStatePending && record.State != ActionStatePlanned {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ActionLifecycleEvent{}, ErrActionNotApproved
+ }
+ if err := ValidateActionExecutionStart(record, now); err != nil && !errors.Is(err, ErrActionNotApproved) {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ActionLifecycleEvent{}, err
+ }
+ if err := ValidateActionPolicyAuthorizationLease(lease, record, now); err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ActionLifecycleEvent{}, err
+ }
+ approval.Actor = strings.TrimSpace(approval.Actor)
+ approval.Method = MethodPolicy
+ approval.Outcome = OutcomeApproved
+ approval.Timestamp = now
+ approval.PolicyLease = &lease
+ record.Approvals = append(record.Approvals, approval)
+ record.State = ActionStateExecuting
+ record.UpdatedAt = now
+ normalized, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return ActionAuditRecord{}, ActionLifecycleEvent{}, ActionLifecycleEvent{}, err
+ }
+ approvedEvent := ActionLifecycleEvent{ActionID: record.ID, Timestamp: now, State: ActionStateApproved, Actor: approval.Actor, Message: "Action authorized by current Patrol policy."}
+ startedEvent := ActionLifecycleEvent{ActionID: record.ID, Timestamp: now, State: ActionStateExecuting, Actor: approval.Actor, Message: "Policy-authorized action execution started."}
+ return normalized, approvedEvent, startedEvent, nil
+}
+
// ActionAuditIdentityMatches reports whether a replay addresses the same
// immutable governed action. Lifecycle state, timestamps, approvals, results,
// and verification are deliberately excluded because the persisted record is
@@ -559,6 +659,14 @@ func permanentActionExecutionRefusalMessage(reason error) (string, bool) {
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
+ case errors.Is(reason, ErrActionPolicyAuthorizationExpired):
+ return "policy_authorization_expired: automatic authority expired before dispatch", true
+ case errors.Is(reason, ErrActionPolicyAuthorizationInvalid):
+ return "policy_authorization_invalid: automatic authority is missing, unreadable, or malformed", true
+ case errors.Is(reason, ErrActionPolicyAuthorizationRevoked):
+ return "policy_authorization_revoked: automatic authority changed before dispatch", true
+ case errors.Is(reason, ErrActionEmergencyStop):
+ return "action_emergency_stop: action dispatch is stopped by the operator", true
default:
return "", false
}
@@ -611,6 +719,17 @@ func NormalizeActionAuditRecord(record ActionAuditRecord) (ActionAuditRecord, er
record.Plan.Preflight = &preflight
}
record.Approvals = append([]ActionApprovalRecord(nil), record.Approvals...)
+ for i := range record.Approvals {
+ if record.Approvals[i].PolicyLease != nil {
+ lease := *record.Approvals[i].PolicyLease
+ lease.CapabilityNames = append([]string(nil), lease.CapabilityNames...)
+ if lease.Window != nil {
+ window := *lease.Window
+ lease.Window = &window
+ }
+ record.Approvals[i].PolicyLease = &lease
+ }
+ }
record.ID = strings.TrimSpace(record.ID)
record.Plan.ActionID = strings.TrimSpace(record.Plan.ActionID)
if record.ID == "" {
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 031223eabd..27fd5294f1 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -611,7 +611,9 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
// 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(",
+ "ErrResourceRemediationLocked",
+ "type ActionPolicyAuthorizationLease struct",
+ "func BeginPolicyActionExecution(",
// ActionVerificationResult is the canonical post-execution
// read-after-write outcome carrier. The broker writes it onto
// ExecutionResult.Verification; pinning the type here keeps the
@@ -622,8 +624,10 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
},
filepath.Join(".", "store.go"): {
"RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error",
+ "RecordActionPolicyExecutionStart(record ActionAuditRecord, approvalEvent, executionEvent ActionLifecycleEvent) error",
"RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error",
"func (s *SQLiteResourceStore) RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error",
+ "func (s *SQLiteResourceStore) RecordActionPolicyExecutionStart(record ActionAuditRecord, approvalEvent, executionEvent 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
@@ -661,6 +665,7 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
"type AvailabilityChecker interface",
"CheckActionAvailable(ctx context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness",
"func (s *Service) ValidatePlanFresh(orgID string, record unified.ActionAuditRecord) error",
+ "func (s *Service) ExecuteUnderPolicy(",
"func RecordRefusedExecution(store Store, record unified.ActionAuditRecord",
"func (s *Service) publishCompleted(record unified.ActionAuditRecord)",
// The persisted-state transition hook is org-scoped so
@@ -691,6 +696,7 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
"func (h *ResourceHandlers) SetActionExecutor(executor ActionExecutor)",
"func (h *ResourceHandlers) SetActionCompletedPublisher(",
"func (h *ResourceHandlers) SetActionTransitionPublisher(",
+ "policyAdmission *actionlifecycle.PolicyAdmissionCoordinator",
"func (h *ResourceHandlers) applyActionAvailability(ctx context.Context, resources []unified.Resource)",
"resources[i].ActionReadiness = readinesses",
},
@@ -701,6 +707,7 @@ func TestActionExecutionContractStaysAPIOwned(t *testing.T) {
},
filepath.Join("..", "api", "router.go"): {
"r.resourceHandlers.SetActionCompletedPublisher(r.agentEventBroadcaster.PublishActionCompletedRecord)",
+ "SetActionEmergencyStopChecker",
},
filepath.Join("..", "api", "router_routes_monitoring.go"): {
`"POST /api/actions/{id}/execute"`,
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index 38bcdf7649..e3e5d232f3 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -47,6 +47,7 @@ type ResourceStore interface {
GetActionAudits(canonicalID string, since time.Time, limit int) ([]ActionAuditRecord, error)
RecordActionDecision(record ActionAuditRecord, event ActionLifecycleEvent) error
RecordActionExecutionStart(record ActionAuditRecord, event ActionLifecycleEvent) error
+ RecordActionPolicyExecutionStart(record ActionAuditRecord, approvalEvent, executionEvent ActionLifecycleEvent) error
RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error
RecordActionExecutionRefusal(record ActionAuditRecord, event ActionLifecycleEvent) error
RecordActionLifecycleEvent(event ActionLifecycleEvent) error
@@ -2214,6 +2215,68 @@ func (s *SQLiteResourceStore) RecordActionExecutionStart(record ActionAuditRecor
return s.recordActionTransition(normalizedRecord, normalizedEvent, expected, ErrActionNotApproved)
}
+// RecordActionPolicyExecutionStart is the single automatic-admission CAS. It
+// persists the server-owned policy approval and executing transition together,
+// so no reusable approved policy state can escape the transaction.
+func (s *SQLiteResourceStore) RecordActionPolicyExecutionStart(record ActionAuditRecord, approvalEvent, executionEvent ActionLifecycleEvent) error {
+ record, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return err
+ }
+ approvalEvent, err = NormalizeActionLifecycleEvent(approvalEvent)
+ if err != nil {
+ return err
+ }
+ executionEvent, err = NormalizeActionLifecycleEvent(executionEvent)
+ if err != nil {
+ return err
+ }
+ if record.State != ActionStateExecuting || approvalEvent.State != ActionStateApproved || executionEvent.State != ActionStateExecuting || approvalEvent.ActionID != record.ID || executionEvent.ActionID != record.ID {
+ return errors.New("policy admission must persist matching approved and executing events")
+ }
+ if len(record.Approvals) == 0 || record.Approvals[len(record.Approvals)-1].Method != MethodPolicy || record.Approvals[len(record.Approvals)-1].PolicyLease == nil {
+ return ErrActionPolicyAuthorizationInvalid
+ }
+ record = RedactAuditRecord(record)
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ tx, err := s.db.Begin()
+ if err != nil {
+ return fmt.Errorf("begin policy admission transaction: %w", err)
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback()
+ }
+ }()
+ updated, err := updateActionAuditSQL(tx, record, ActionStatePlanned, ActionStatePending)
+ if err != nil {
+ return err
+ }
+ if !updated {
+ current, found, queryErr := getActionAuditFrom(tx, record.ID)
+ if queryErr != nil {
+ return queryErr
+ }
+ if !found {
+ return fmt.Errorf("action audit %q not found", record.ID)
+ }
+ return actionTransitionConflict(current, record, ErrActionNotApproved)
+ }
+ if err := recordActionLifecycleEventSQL(tx, approvalEvent); err != nil {
+ return err
+ }
+ if err := recordActionLifecycleEventSQL(tx, executionEvent); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return fmt.Errorf("commit policy admission transaction: %w", err)
+ }
+ committed = true
+ return nil
+}
+
func (s *SQLiteResourceStore) RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error {
normalizedRecord, err := NormalizeActionAuditRecord(record)
if err != nil {
@@ -3253,6 +3316,46 @@ func (m *MemoryStore) RecordActionExecutionStart(record ActionAuditRecord, event
return nil
}
+func (m *MemoryStore) RecordActionPolicyExecutionStart(record ActionAuditRecord, approvalEvent, executionEvent ActionLifecycleEvent) error {
+ record, err := NormalizeActionAuditRecord(record)
+ if err != nil {
+ return err
+ }
+ approvalEvent, err = NormalizeActionLifecycleEvent(approvalEvent)
+ if err != nil {
+ return err
+ }
+ executionEvent, err = NormalizeActionLifecycleEvent(executionEvent)
+ if err != nil {
+ return err
+ }
+ if record.State != ActionStateExecuting || approvalEvent.State != ActionStateApproved || executionEvent.State != ActionStateExecuting || approvalEvent.ActionID != record.ID || executionEvent.ActionID != record.ID {
+ return errors.New("policy admission must persist matching approved and executing events")
+ }
+ if len(record.Approvals) == 0 || record.Approvals[len(record.Approvals)-1].Method != MethodPolicy || record.Approvals[len(record.Approvals)-1].PolicyLease == nil {
+ return ErrActionPolicyAuthorizationInvalid
+ }
+ record = RedactAuditRecord(record)
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for i := range m.actionAudits {
+ if m.actionAudits[i].ID != record.ID {
+ continue
+ }
+ current := m.actionAudits[i]
+ if !ActionAuditIdentityMatches(current, record) {
+ return ErrActionIdentityConflict
+ }
+ if current.State != ActionStatePlanned && current.State != ActionStatePending {
+ return actionTransitionConflict(current, record, ErrActionNotApproved)
+ }
+ m.actionAudits[i] = record
+ m.actionLifecycleEvents = append(m.actionLifecycleEvents, approvalEvent, executionEvent)
+ return nil
+ }
+ return fmt.Errorf("action audit %q not found", record.ID)
+}
+
func (m *MemoryStore) RecordActionExecutionResult(record ActionAuditRecord, event ActionLifecycleEvent) error {
normalizedRecord, err := NormalizeActionAuditRecord(record)
if err != nil {
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index 9d208c158c..671430733d 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -94,6 +94,29 @@ func TestMemoryStoreActionTransitionsAreMonotonic(t *testing.T) {
}
}
+func TestMemoryStorePolicyExecutionStartRequiresAuthorizationLease(t *testing.T) {
+ store := NewMemoryStore()
+ record := atomicLifecycleTestRecord("act_memory_policy_lease", ActionStatePlanned)
+ record.Plan.RequiresApproval = false
+ if _, _, err := store.CreateActionAudit(record, atomicLifecycleInitialEvents(record)); err != nil {
+ t.Fatal(err)
+ }
+ record.State = ActionStateExecuting
+ record.Approvals = []ActionApprovalRecord{{Actor: "pulse_patrol_policy", Method: MethodPolicy, Outcome: OutcomeApproved}}
+ approval := ActionLifecycleEvent{ActionID: record.ID, Timestamp: record.CreatedAt.Add(time.Minute), State: ActionStateApproved, Actor: "pulse_patrol_policy", Message: "Policy authorization approved action."}
+ executing := ActionLifecycleEvent{ActionID: record.ID, Timestamp: record.CreatedAt.Add(time.Minute), State: ActionStateExecuting, Actor: "pulse_patrol_policy", Message: "Action execution started."}
+ if err := store.RecordActionPolicyExecutionStart(record, approval, executing); !errors.Is(err, ErrActionPolicyAuthorizationInvalid) {
+ t.Fatalf("error = %v, want ErrActionPolicyAuthorizationInvalid", err)
+ }
+ current, found, err := store.GetActionAudit(record.ID)
+ if err != nil || !found {
+ t.Fatalf("GetActionAudit found=%v err=%v", found, err)
+ }
+ if current.State != ActionStatePlanned || len(current.Approvals) != 0 {
+ t.Fatalf("failed admission mutated audit: state=%q approvals=%d", current.State, len(current.Approvals))
+ }
+}
+
func TestMemoryStoreConcurrentExecutionStartHasOneCASWinner(t *testing.T) {
store := NewMemoryStore()
record := atomicLifecycleTestRecord("act_memory_execute", ActionStatePlanned)