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.

Add /api/resources/{id}/operator-state GET / PUT / DELETE handlers

rcourtman46646b4293e0
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index e4b212528c..a96162f0cb 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -917,6 +917,20 @@ profile and assignment columns, but embedded table framing must route through
## Current State
+The `/api/resources/{id}/operator-state` GET / PUT / DELETE handlers in
+`internal/api/resources_operator_state.go` are the canonical operator
+surface for setting per-resource intent (intentionally offline, never
+auto-remediate, maintenance window, criticality hint). The route lives
+on the same monitoring router (`router_routes_monitoring.go`) as the
+rest of `/api/resources/{id}/...`; method-keyed scope dispatch means GET
+runs under `monitoring:read` while PUT and DELETE require
+`monitoring:write` because they modulate Patrol's behavior on findings
+against the resource. The agent runtime must surface the same
+operator-set state across restarts — persistence is in the
+`resource_operator_state` SQLite table managed by the unified-resources
+store from slice 29 — so a maintenance window or never-auto-remediate
+flag set before a process restart is honored after the agent reloads.
+
Patrol-finding to unified-finding mirroring in `internal/api/router.go`
also keeps the will_fix_later wake-up deadline (`Finding.RemindAt`)
intact across restarts. Both the live wire-up callback and the
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index d74a9d70bf..77069b6c9a 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1343,6 +1343,27 @@ the canonical monitored-system blocked payload.
## Current State
+`/api/resources/{id}/operator-state` is the canonical surface for
+operator-set per-resource intent (intentionally offline, never
+auto-remediate, maintenance window, criticality hint). GET requires
+`monitoring:read` and returns `404` with `{ "error":
+"operator_state_not_set" }` when no entry exists; PUT and DELETE
+require `monitoring:write` because they modulate Patrol's behavior on
+findings against the resource. PUT replaces the entire record (no
+per-field merge); the `canonicalId` taken from the URL path
+authoritatively wins over any value in the request body so a request
+addressed at `/vm:101` cannot retarget the write at a different
+resource through body manipulation. Server populates `setAt` and
+`setBy` from the request time and authenticated identity, ignoring any
+client values to keep the audit attribution honest. Validation
+violations surface as `400` with `{ "error":
+"operator_state_invalid", "message": "..." }` so the frontend can
+branch on the stable error code rather than string-matching the
+message. DELETE is idempotent (`204` whether or not an entry was
+present). The handler dispatches off `r.Method` rather than mounting
+three sibling routes so the URL surface stays a single resource path
+matching the rest of `/api/resources/{id}/...`.
+
Deploy-job monitored-system volume denials are retired. API routes may still
accept historical payloads that mention old license-slot terminology for
migration or diagnostics, but runtime deploy responses must not emit
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index ebd5eb8006..a7e9c32b17 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -947,6 +947,17 @@ bypass the API fail-closed execution gate.
## Current State
+The `resource_operator_state` SQLite table introduced by the
+unified-resources store keeps operator-set per-resource intent
+(intentionally offline, never auto-remediate, maintenance window,
+criticality) durably alongside the rest of the unified-resource
+durable state. The `/api/resources/{id}/operator-state` API surface in
+`internal/api/resources_operator_state.go` reads and writes that table
+through the canonical store, so storage / recovery flows that rehydrate
+the unified-resources store also rehydrate operator-set state — a
+maintenance window persists across restarts the same way action audits
+and resource overrides do.
+
The patrol findings-recovery sync in `internal/api/router.go` also keeps
the will_fix_later wake-up deadline alongside the rest of the finding's
durable state when re-hydrating findings from disk into the unified
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index c339b09ce2..79efaf9039 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -578,10 +578,15 @@ and lower-cases the criticality value before persistence. The
`GetResourceOperatorState`, `SetResourceOperatorState`, and
`ClearResourceOperatorState`; both the SQLite (table
`resource_operator_state` keyed on `canonical_id`) and Memory stores
-implement the same upsert + idempotent-clear contract. This slice is
-the foundational shape only — the API surface (GET/PUT/DELETE) and the
-finding-suppression / action-broker integrations land in subsequent
-slices that consume this contract.
+implement the same upsert + idempotent-clear contract. The
+`/api/resources/{id}/operator-state` API surface (GET / PUT / DELETE)
+in `internal/api/resources_operator_state.go` is the operator-facing
+consumer of this contract; the URL canonical_id always wins over the
+body, server-side `setAt` / `setBy` populate from request time and
+authenticated identity, and validation rejections surface a stable
+`operator_state_invalid` error code. Finding-suppression and
+action-broker integrations land in subsequent slices that consume the
+same `ResourceOperatorState` shape.
`actions.go` now owns the canonical action preflight and audit-normalization
contract. Action plans must carry dry-run availability, safety checks, and
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index f32956e36e..d43e310e86 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -13232,3 +13232,38 @@ func assertJSONSnapshot(t *testing.T, got []byte, want string) {
t.Fatalf("json snapshot mismatch\nwant: %s\ngot: %s", wantCompact.String(), gotCompact.String())
}
}
+
+// TestContract_ResourceOperatorStateUrlCanonicalIDWinsOverBody pins the
+// security-relevant decision that the URL path's canonical_id always
+// wins over any body-supplied value on PUT
+// /api/resources/{id}/operator-state. Without this rule a request
+// authorized to write at /vm:101 could retarget the write at /vm:102
+// through body manipulation, defeating per-resource scoping.
+func TestContract_ResourceOperatorStateUrlCanonicalIDWinsOverBody(t *testing.T) {
+ cfg := &config.Config{DataPath: t.TempDir()}
+ h := NewResourceHandlers(cfg)
+
+ body := []byte(`{"canonicalId":"vm:999","intentionallyOffline":true}`)
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPut, "/api/resources/vm:101/operator-state", bytes.NewReader(body))
+ h.HandleResourceOperatorState(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200; got %d body=%s", rec.Code, rec.Body.String())
+ }
+ var persisted resourceOperatorStateAPI
+ if err := json.Unmarshal(rec.Body.Bytes(), &persisted); err != nil {
+ t.Fatalf("response not JSON: %v", err)
+ }
+ if persisted.CanonicalID != "vm:101" {
+ t.Errorf("URL canonical_id must override body; got %q (security regression)", persisted.CanonicalID)
+ }
+ // And the resource named in the body must NOT have a state row,
+ // confirming the write didn't bleed across resource scope.
+ rec2 := httptest.NewRecorder()
+ req2 := httptest.NewRequest(http.MethodGet, "/api/resources/vm:999/operator-state", nil)
+ h.HandleResourceOperatorState(rec2, req2)
+ if rec2.Code != http.StatusNotFound {
+ t.Errorf("body-supplied canonical_id must not have been persisted; GET vm:999 returned %d", rec2.Code)
+ }
+}
diff --git a/internal/api/resources_operator_state.go b/internal/api/resources_operator_state.go
new file mode 100644
index 0000000000..7e5e743ca3
--- /dev/null
+++ b/internal/api/resources_operator_state.go
@@ -0,0 +1,156 @@
+package api
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// resourceOperatorStateAPI is the wire shape for the operator-state API
+// surface. It mirrors `unified.ResourceOperatorState` but with explicit
+// JSON field names and string criticality so the contract is explicit at
+// the API boundary regardless of internal type renames. The API layer
+// adapts to and from `unified.ResourceOperatorState` so the storage
+// type's evolution stays decoupled from the wire format.
+type resourceOperatorStateAPI struct {
+ CanonicalID string `json:"canonicalId"`
+ IntentionallyOffline bool `json:"intentionallyOffline"`
+ NeverAutoRemediate bool `json:"neverAutoRemediate"`
+ MaintenanceStartAt *time.Time `json:"maintenanceStartAt,omitempty"`
+ MaintenanceEndAt *time.Time `json:"maintenanceEndAt,omitempty"`
+ MaintenanceReason string `json:"maintenanceReason,omitempty"`
+ Criticality string `json:"criticality,omitempty"`
+ Note string `json:"note,omitempty"`
+ SetAt time.Time `json:"setAt"`
+ SetBy string `json:"setBy,omitempty"`
+}
+
+func toResourceOperatorStateAPI(state unified.ResourceOperatorState) resourceOperatorStateAPI {
+ return resourceOperatorStateAPI{
+ CanonicalID: state.CanonicalID,
+ IntentionallyOffline: state.IntentionallyOffline,
+ NeverAutoRemediate: state.NeverAutoRemediate,
+ MaintenanceStartAt: state.MaintenanceStartAt,
+ MaintenanceEndAt: state.MaintenanceEndAt,
+ MaintenanceReason: state.MaintenanceReason,
+ Criticality: string(state.Criticality),
+ Note: state.Note,
+ SetAt: state.SetAt,
+ SetBy: state.SetBy,
+ }
+}
+
+// HandleResourceOperatorState dispatches GET / PUT / DELETE on
+// /api/resources/{id}/operator-state. Method-keyed scope enforcement is
+// done by the route registration; this handler only re-checks the method
+// and routes to the underlying store calls.
+//
+// Wire-format contract:
+// - GET returns 404 with a stable JSON error body when no entry exists,
+// and 200 with the persisted state otherwise. Operators who have not
+// set any state see 404, distinct from a "default state was explicitly
+// written" 200 with all zero fields.
+// - PUT replaces the entire record (no per-field merge). The request
+// body is the full state shape; the canonical_id is taken from the
+// URL path and overrides any value in the body. SetAt / SetBy are
+// populated by the server from the authenticated identity and
+// request time, ignoring any client-supplied values to keep the
+// audit attribution honest.
+// - DELETE clears the entry, idempotent. Returns 204 whether or not
+// an entry was present.
+func (h *ResourceHandlers) HandleResourceOperatorState(w http.ResponseWriter, r *http.Request) {
+ resourceID := extractOperatorStateResourceID(r.URL.Path)
+ if resourceID == "" {
+ http.Error(w, "Resource ID required", http.StatusBadRequest)
+ return
+ }
+
+ orgID := GetOrgID(r.Context())
+ store, err := h.getStore(orgID)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+
+ switch r.Method {
+ case http.MethodGet:
+ state, found, err := store.GetResourceOperatorState(resourceID)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+ if !found {
+ writeJSONError(w, http.StatusNotFound, "operator_state_not_set",
+ "No operator-set state recorded for this resource.")
+ return
+ }
+ writeJSON(w, http.StatusOK, toResourceOperatorStateAPI(state))
+
+ case http.MethodPut:
+ var payload resourceOperatorStateAPI
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ http.Error(w, "Invalid JSON", http.StatusBadRequest)
+ return
+ }
+ // canonical_id from URL wins over body to prevent scope confusion
+ // (operator wrote vm:101 in the URL but vm:102 in the body).
+ state := unified.ResourceOperatorState{
+ CanonicalID: resourceID,
+ IntentionallyOffline: payload.IntentionallyOffline,
+ NeverAutoRemediate: payload.NeverAutoRemediate,
+ MaintenanceStartAt: payload.MaintenanceStartAt,
+ MaintenanceEndAt: payload.MaintenanceEndAt,
+ MaintenanceReason: payload.MaintenanceReason,
+ Criticality: unified.ResourceCriticality(payload.Criticality),
+ Note: payload.Note,
+ // Server-populated attribution: ignore any client values so
+ // the audit trail can't be spoofed.
+ SetAt: time.Now().UTC(),
+ SetBy: getUserID(r),
+ }
+ if err := store.SetResourceOperatorState(state); err != nil {
+ if errors.Is(err, unified.ErrResourceOperatorStateInvalid) {
+ writeJSONError(w, http.StatusBadRequest, "operator_state_invalid", err.Error())
+ return
+ }
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+ // Read-after-write: return the persisted state so the caller can
+ // see exactly what the server stored, including the
+ // server-populated attribution fields.
+ persisted, _, err := store.GetResourceOperatorState(resourceID)
+ if err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+ writeJSON(w, http.StatusOK, toResourceOperatorStateAPI(persisted))
+
+ case http.MethodDelete:
+ if err := store.ClearResourceOperatorState(resourceID); err != nil {
+ http.Error(w, sanitizeErrorForClient(err, "Internal server error"), http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+
+ default:
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ }
+}
+
+// extractOperatorStateResourceID pulls the canonical resource ID out of a
+// `/api/resources/<id>/operator-state` URL path. Tolerates a trailing
+// slash on the URL (defense-in-depth — Go 1.22 ServeMux normally rejects
+// it on pattern-match, but proxies might rewrite the path) and returns
+// "" if the ID resolves to empty after canonical normalization.
+func extractOperatorStateResourceID(path string) string {
+ trimmed := strings.TrimPrefix(path, "/api/resources/")
+ trimmed = strings.TrimSuffix(trimmed, "/")
+ trimmed = strings.TrimSuffix(trimmed, "/operator-state")
+ trimmed = strings.TrimSuffix(trimmed, "/")
+ return unified.CanonicalResourceID(trimmed)
+}
diff --git a/internal/api/resources_operator_state_test.go b/internal/api/resources_operator_state_test.go
new file mode 100644
index 0000000000..d6ff613517
--- /dev/null
+++ b/internal/api/resources_operator_state_test.go
@@ -0,0 +1,219 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// newOperatorStateHandlers spins up a ResourceHandlers wired against a
+// per-test temp data dir so the SQLite store is ephemeral, mirroring the
+// existing resources_test.go fixtures.
+func newOperatorStateHandlers(t *testing.T) *ResourceHandlers {
+ t.Helper()
+ cfg := &config.Config{DataPath: t.TempDir()}
+ return NewResourceHandlers(cfg)
+}
+
+func TestHandleResourceOperatorState_GetReturns404WhenUnset(t *testing.T) {
+ h := newOperatorStateHandlers(t)
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/resources/vm:101/operator-state", nil)
+
+ h.HandleResourceOperatorState(rec, req)
+
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 on unset state; got %d body=%s", rec.Code, rec.Body.String())
+ }
+ var body map[string]string
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("body must be JSON; got %q", rec.Body.String())
+ }
+ // The handler must surface a stable error code so the frontend can
+ // branch on it without string-matching the human message.
+ if body["error"] != "operator_state_not_set" {
+ t.Errorf("expected error=operator_state_not_set; got %v", body)
+ }
+}
+
+func TestHandleResourceOperatorState_PutPersistsAndGetReturns200(t *testing.T) {
+ h := newOperatorStateHandlers(t)
+
+ start := time.Date(2026, 5, 9, 12, 0, 0, 0, time.UTC)
+ end := time.Date(2026, 5, 9, 14, 0, 0, 0, time.UTC)
+ payload := map[string]any{
+ // canonical_id in body is intentionally a different value to
+ // confirm the URL path wins over body. Anything in the body must
+ // not be able to retarget the write at a different resource.
+ "canonicalId": "vm:999",
+ "intentionallyOffline": true,
+ "neverAutoRemediate": true,
+ "maintenanceStartAt": start.Format(time.RFC3339),
+ "maintenanceEndAt": end.Format(time.RFC3339),
+ "maintenanceReason": "Q3 storage upgrade",
+ "criticality": "high",
+ "note": "do not auto-fix",
+ }
+ body, _ := json.Marshal(payload)
+
+ putRec := httptest.NewRecorder()
+ putReq := httptest.NewRequest(http.MethodPut, "/api/resources/vm:101/operator-state", bytes.NewReader(body))
+ h.HandleResourceOperatorState(putRec, putReq)
+
+ if putRec.Code != http.StatusOK {
+ t.Fatalf("expected 200 on PUT; got %d body=%s", putRec.Code, putRec.Body.String())
+ }
+ var persisted resourceOperatorStateAPI
+ if err := json.Unmarshal(putRec.Body.Bytes(), &persisted); err != nil {
+ t.Fatalf("PUT response must be parseable as resourceOperatorStateAPI; got %q", putRec.Body.String())
+ }
+ // URL canonical_id wins over body — even though body said vm:999.
+ if persisted.CanonicalID != "vm:101" {
+ t.Errorf("URL canonical_id must override body; got %q", persisted.CanonicalID)
+ }
+ if !persisted.IntentionallyOffline || !persisted.NeverAutoRemediate {
+ t.Errorf("boolean flags must round-trip on PUT response: %+v", persisted)
+ }
+ if persisted.Criticality != "high" {
+ t.Errorf("criticality must round-trip; got %q", persisted.Criticality)
+ }
+ // Server-populated attribution: SetAt is populated even when the
+ // body omits it. Ignoring client-supplied values keeps the audit
+ // trail honest.
+ if persisted.SetAt.IsZero() {
+ t.Error("server must populate SetAt; got zero")
+ }
+
+ // Read-back via GET.
+ getRec := httptest.NewRecorder()
+ getReq := httptest.NewRequest(http.MethodGet, "/api/resources/vm:101/operator-state", nil)
+ h.HandleResourceOperatorState(getRec, getReq)
+ if getRec.Code != http.StatusOK {
+ t.Fatalf("expected 200 on GET after PUT; got %d body=%s", getRec.Code, getRec.Body.String())
+ }
+ var got resourceOperatorStateAPI
+ if err := json.Unmarshal(getRec.Body.Bytes(), &got); err != nil {
+ t.Fatalf("GET response must be parseable; got %q", getRec.Body.String())
+ }
+ if got.MaintenanceReason != "Q3 storage upgrade" {
+ t.Errorf("maintenance reason must round-trip via GET; got %q", got.MaintenanceReason)
+ }
+ if got.MaintenanceStartAt == nil || !got.MaintenanceStartAt.Equal(start) {
+ t.Errorf("maintenance start must round-trip; got %v", got.MaintenanceStartAt)
+ }
+}
+
+func TestHandleResourceOperatorState_PutRejectsInvalidWith400(t *testing.T) {
+ h := newOperatorStateHandlers(t)
+
+ // Unknown criticality value — must be rejected with 400 +
+ // operator_state_invalid code, NOT silently coerced or persisted.
+ body, _ := json.Marshal(map[string]any{
+ "criticality": "very-high",
+ })
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPut, "/api/resources/vm:101/operator-state", bytes.NewReader(body))
+ h.HandleResourceOperatorState(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 on invalid state; got %d body=%s", rec.Code, rec.Body.String())
+ }
+ var errBody map[string]string
+ if err := json.Unmarshal(rec.Body.Bytes(), &errBody); err != nil {
+ t.Fatalf("body must be JSON error; got %q", rec.Body.String())
+ }
+ if errBody["error"] != "operator_state_invalid" {
+ t.Errorf("expected error=operator_state_invalid; got %v", errBody)
+ }
+
+ // And the rejection must not have persisted: GET still returns 404.
+ getRec := httptest.NewRecorder()
+ getReq := httptest.NewRequest(http.MethodGet, "/api/resources/vm:101/operator-state", nil)
+ h.HandleResourceOperatorState(getRec, getReq)
+ if getRec.Code != http.StatusNotFound {
+ t.Errorf("rejected PUT must not persist; GET should still 404; got %d", getRec.Code)
+ }
+}
+
+func TestHandleResourceOperatorState_DeleteIsIdempotent(t *testing.T) {
+ h := newOperatorStateHandlers(t)
+
+ // DELETE on a fresh store with no entry: 204 (idempotent).
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodDelete, "/api/resources/vm:101/operator-state", nil)
+ h.HandleResourceOperatorState(rec, req)
+ if rec.Code != http.StatusNoContent {
+ t.Fatalf("expected 204 on idempotent DELETE; got %d body=%s", rec.Code, rec.Body.String())
+ }
+
+ // Set, then DELETE, then GET should 404.
+ setRec := httptest.NewRecorder()
+ setReq := httptest.NewRequest(http.MethodPut, "/api/resources/vm:101/operator-state",
+ bytes.NewReader([]byte(`{"intentionallyOffline":true}`)))
+ h.HandleResourceOperatorState(setRec, setReq)
+ if setRec.Code != http.StatusOK {
+ t.Fatalf("setup PUT failed: %d %s", setRec.Code, setRec.Body.String())
+ }
+
+ delRec := httptest.NewRecorder()
+ delReq := httptest.NewRequest(http.MethodDelete, "/api/resources/vm:101/operator-state", nil)
+ h.HandleResourceOperatorState(delRec, delReq)
+ if delRec.Code != http.StatusNoContent {
+ t.Fatalf("expected 204 on DELETE after PUT; got %d", delRec.Code)
+ }
+
+ getRec := httptest.NewRecorder()
+ getReq := httptest.NewRequest(http.MethodGet, "/api/resources/vm:101/operator-state", nil)
+ h.HandleResourceOperatorState(getRec, getReq)
+ if getRec.Code != http.StatusNotFound {
+ t.Errorf("expected 404 after DELETE; got %d", getRec.Code)
+ }
+}
+
+func TestHandleResourceOperatorState_RejectsEmptyResourceID(t *testing.T) {
+ h := newOperatorStateHandlers(t)
+ rec := httptest.NewRecorder()
+ // Path with no resource ID between /resources/ and /operator-state.
+ req := httptest.NewRequest(http.MethodGet, "/api/resources//operator-state", nil)
+ h.HandleResourceOperatorState(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 on empty resource id; got %d", rec.Code)
+ }
+}
+
+func TestHandleResourceOperatorState_RejectsUnsupportedMethod(t *testing.T) {
+ h := newOperatorStateHandlers(t)
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/resources/vm:101/operator-state", nil)
+ h.HandleResourceOperatorState(rec, req)
+
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Fatalf("expected 405 on POST; got %d", rec.Code)
+ }
+}
+
+func TestExtractOperatorStateResourceID(t *testing.T) {
+ cases := []struct {
+ name string
+ path string
+ want string
+ }{
+ {"canonical resource id", "/api/resources/vm:101/operator-state", "vm:101"},
+ {"trailing slash before suffix", "/api/resources/vm:101/operator-state/", "vm:101"},
+ {"empty id", "/api/resources//operator-state", ""},
+ {"colon-bearing id", "/api/resources/instance:node:200/operator-state", "instance:node:200"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := extractOperatorStateResourceID(tc.path); got != tc.want {
+ t.Errorf("extractOperatorStateResourceID(%q) = %q, want %q", tc.path, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index c46ee09963..049de9934e 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -409,6 +409,7 @@ var allRouteAllowlist = []string{
"/api/resources/",
"/api/resources/{id}/facets",
"/api/resources/{id}/timeline",
+ "/api/resources/{id}/operator-state",
"POST /api/actions/plan",
"POST /api/actions/{id}/decision",
"POST /api/actions/{id}/execute",
diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.go
index e5364ea025..b40bb80b99 100644
--- a/internal/api/router_routes_monitoring.go
+++ b/internal/api/router_routes_monitoring.go
@@ -36,6 +36,27 @@ func (r *Router) registerMonitoringResourceRoutes(
r.mux.HandleFunc("/api/resources/k8s/namespaces", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.resourceHandlers.HandleK8sNamespaces)))
r.mux.HandleFunc("/api/resources/{id}/facets", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.resourceHandlers.HandleGetResourceFacets)))
r.mux.HandleFunc("/api/resources/{id}/timeline", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.resourceHandlers.HandleGetResourceTimeline)))
+ // Per-resource operator-set state. GET is read; PUT/DELETE are
+ // governance-shaping writes (suppress findings, refuse remediation,
+ // schedule maintenance) so they require the write scope. Method-keyed
+ // scope wrap mirrors the guests-metadata and docker-metadata pattern
+ // elsewhere in this file.
+ r.mux.HandleFunc("/api/resources/{id}/operator-state", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
+ switch req.Method {
+ case http.MethodGet:
+ if !ensureScope(w, req, config.ScopeMonitoringRead) {
+ return
+ }
+ case http.MethodPut, http.MethodDelete:
+ if !ensureScope(w, req, config.ScopeMonitoringWrite) {
+ return
+ }
+ default:
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ r.resourceHandlers.HandleResourceOperatorState(w, req)
+ }))
r.mux.HandleFunc("/api/resources/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.resourceHandlers.HandleResourceRoutes)))
r.mux.HandleFunc("POST /api/actions/plan", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandlePlanAction)))
r.mux.HandleFunc("POST /api/actions/{id}/decision", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.resourceHandlers.HandleDecideAction)))