Files
Pulse/internal/api/resources_compat.go
rcourtman 05ed4334a9 Harden action authority, lifecycle isolation, and agent events
Bound action plan requestId and reason sizes and stream audit canonicalization, bind owning org context in action recovery, Patrol proposals, and Docker observation, derive Basic action credential IDs from username rather than Authorization header hash, tag approval.pending and action.completed events with owning org, recheck live token and session credentials before action decision and execution commits, prevent non-reviewers from replaying stored action records via execute, and withhold action authority from relay mobile tokens minted by non-approvers.

Contract-Neutral: Security fixes closing action authority, multi-tenant event and recovery isolation, replay disclosure, and audit OOM bugs
2026-11-24 14:20:36 +00:00

183 lines
7.0 KiB
Go

package api
import (
"context"
"net/http"
"strings"
"sync/atomic"
"github.com/rcourtman/pulse-go-rewrite/internal/actionlifecycle"
"github.com/rcourtman/pulse-go-rewrite/internal/api/apicontext"
"github.com/rcourtman/pulse-go-rewrite/internal/api/resourceapi"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
// ResourceHandlers preserves the established router and extension surface
// while composing the resource-query service with API-owned action mutations.
// QueryService owns resource registry construction, durable resource storage,
// filtering, projections, and read handlers. The fields below remain here
// because action lifecycle and operator-state mutations are separate domains.
type ResourceHandlers struct {
resourceapi.QueryService
cfg *config.Config
tenantStateProvider TenantStateProvider
actionExecutor ActionExecutor
broadcastAvailability atomic.Pointer[broadcastAvailabilityChecker]
actionCompleted func(orgID string, record unified.ActionAuditRecord)
actionTransition func(orgID string, record unified.ActionAuditRecord)
policyAdmission *actionlifecycle.PolicyAdmissionCoordinator
actionEmergencyStop func(orgID string) (bool, error)
actionDecisionAuthorizer actionlifecycle.DecisionAuthorizer
actionExecutionAuthorizer actionlifecycle.ExecutionAuthorizer
actionLiveCheckAuthorizer actionlifecycle.LiveCheckAuthorizer
actionRefreshPlanner actionlifecycle.RefreshPlanner
operatorStateChanged func(orgID, resourceID string)
operatorStateRemediation func(*http.Request) bool
}
type SupplementalRecordsProvider = resourceapi.SupplementalRecordsProvider
type TenantSupplementalRecordsProvider = resourceapi.TenantSupplementalRecordsProvider
type SupplementalSnapshotSourceOwner = resourceapi.SupplementalSnapshotSourceOwner
type TenantSupplementalSnapshotSourceOwner = resourceapi.TenantSupplementalSnapshotSourceOwner
type ResourcesResponse = resourceapi.ResourcesResponse
type ResourcesMeta = resourceapi.ResourcesMeta
type StorageSummaryResponse = resourceapi.StorageSummaryResponse
type StorageSummaryIncident = resourceapi.StorageSummaryIncident
type StorageIncidentsResponse = resourceapi.StorageIncidentsResponse
type StorageIncidentSection = resourceapi.StorageIncidentSection
func EmptyResourcesResponse() ResourcesResponse { return resourceapi.EmptyResourcesResponse() }
func EmptyStorageSummaryResponse() StorageSummaryResponse {
return resourceapi.EmptyStorageSummaryResponse()
}
func EmptyStorageIncidentsResponse() StorageIncidentsResponse {
return resourceapi.EmptyStorageIncidentsResponse()
}
// NewResourceHandlers builds the compatibility composition used by Router.
func NewResourceHandlers(cfg *config.Config) *ResourceHandlers {
return &ResourceHandlers{
QueryService: *resourceapi.NewQueryService(cfg),
cfg: cfg,
policyAdmission: &actionlifecycle.PolicyAdmissionCoordinator{},
}
}
func (h *ResourceHandlers) ensureQueryService() *resourceapi.QueryService {
return &h.QueryService
}
func (h *ResourceHandlers) SetStateProvider(provider SnapshotProvider) {
h.ensureQueryService().SetStateProvider(provider)
}
func (h *ResourceHandlers) SetTenantStateProvider(provider TenantStateProvider) {
h.tenantStateProvider = provider
h.ensureQueryService().SetTenantStateProvider(provider)
}
func (h *ResourceHandlers) SetActionExecutor(executor ActionExecutor) {
h.actionExecutor = executor
checker, _ := executor.(actionlifecycle.AvailabilityChecker)
h.ensureQueryService().SetActionAvailabilityChecker(checker)
h.broadcastAvailability.Store(&broadcastAvailabilityChecker{checker: checker})
}
// broadcastAvailabilityChecker lets monitor goroutines, which can tick before
// the router finishes wiring its executors, read the checker without a race.
type broadcastAvailabilityChecker struct {
checker actionlifecycle.AvailabilityChecker
}
// AttachBroadcastActionRefusals records the server's action refusals on one
// organization's broadcast rows, so a browser learns of a refusal, or of its
// end, from the next websocket frame and not from its next REST read.
func (h *ResourceHandlers) AttachBroadcastActionRefusals(orgID string, resources []unified.Resource) {
holder := h.broadcastAvailability.Load()
if holder == nil || holder.checker == nil {
return
}
ctx := context.WithValue(context.Background(), apicontext.OrgIDContextKey, orgID)
actionlifecycle.AttachActionRefusals(ctx, holder.checker, resources)
}
func (h *ResourceHandlers) SetActionEmergencyStopChecker(checker func(orgID string) (bool, error)) {
h.actionEmergencyStop = checker
}
func (h *ResourceHandlers) SetActionAuthorizers(decision actionlifecycle.DecisionAuthorizer, execution actionlifecycle.ExecutionAuthorizer, liveCheck actionlifecycle.LiveCheckAuthorizer) {
h.actionDecisionAuthorizer = decision
h.actionExecutionAuthorizer = execution
h.actionLiveCheckAuthorizer = liveCheck
}
func (h *ResourceHandlers) SetActionRefreshPlanner(planner actionlifecycle.RefreshPlanner) {
h.actionRefreshPlanner = planner
}
func (h *ResourceHandlers) SetActionCompletedPublisher(publisher func(orgID string, record unified.ActionAuditRecord)) {
h.actionCompleted = publisher
}
func (h *ResourceHandlers) SetActionTransitionPublisher(publisher func(orgID string, record unified.ActionAuditRecord)) {
h.actionTransition = publisher
}
func (h *ResourceHandlers) SetOperatorStateChanged(callback func(orgID, resourceID string)) {
h.operatorStateChanged = callback
}
// SetOperatorStateRemediationAuthority sets who may change what a resource's
// operator state tells the action lifecycle and Patrol: the Never
// auto-remediate lock, the lifecycle state and the automatic remediation
// policy. Without it nobody may. Everyone the route admits keeps the rest of
// the record (monitoring mode, maintenance windows, criticality, notes).
func (h *ResourceHandlers) SetOperatorStateRemediationAuthority(allowed func(*http.Request) bool) {
h.operatorStateRemediation = allowed
}
func (h *ResourceHandlers) buildRegistry(orgID string) (*unified.ResourceRegistry, error) {
return h.ensureQueryService().BuildRegistry(orgID)
}
func (h *ResourceHandlers) getStore(orgID string) (unified.ResourceStore, error) {
return h.ensureQueryService().Store(orgID)
}
func (h *ResourceHandlers) invalidateCache(orgID string) {
h.ensureQueryService().InvalidateCache(orgID)
}
func (h *ResourceHandlers) CloseTenantStore(orgID string) error {
if h == nil {
return nil
}
return h.QueryService.CloseTenantStore(orgID)
}
func (h *ResourceHandlers) CloseStores() error {
if h == nil {
return nil
}
return h.QueryService.CloseStores()
}
// firstNonEmptyTrimmed is retained for non-resource connection projections.
func firstNonEmptyTrimmed(values ...string) string {
for _, value := range values {
if trimmed := strings.TrimSpace(value); trimmed != "" {
return trimmed
}
}
return ""
}
func getUserID(r *http.Request) string {
return auth.GetUser(r.Context())
}