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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Extract alert delivery API package
rcourtman58bf77c1aeaa
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 4c2d80f864..c50c153d03 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -3000,7 +3000,7 @@ restriction lists, role mappings, and masked secret-presence markers create noagent install, enrollment, setup-token, command, fleet liveness, or agentprofile semantics.-Alert delivery diagnosis on shared `internal/api/alerts.go` is likewise+Alert delivery diagnosis on shared `internal/api/alerting/alerts.go` is likewiseadjacent only: `/api/alerts/delivery-diagnosis` is alerts/API-contract ownedread-only notification-policy evidence and must not be interpreted as agentenrollment, agent liveness, install progress, setup-token authority, or fleet@@ -4523,18 +4523,18 @@ or recover those tokens through encrypted-at-rest session payloads, and anymissing-crypto or invalid-ciphertext path must drop the refresh token insteadof leaving plaintext-at-rest session state on the lifecycle runtime path.That same shared `internal/api/` dependency also assumes notification test-handlers stay decode-and-delegate only: `internal/api/notifications.go` may+handlers stay decode-and-delegate only: `internal/api/alerting/notifications.go` maysurface adjacent operator test actions, but service-template selection andgeneric webhook-test payload fallback must remain notifications-owned insteadof becoming a second API-layer owner under the shared helper surface.That same shared API boundary also assumes legacy service-specific webhook-aliases are rewritten at ingress only: `internal/api/notifications.go` may+aliases are rewritten at ingress only: `internal/api/alerting/notifications.go` mayaccept compatibility keys like Pushover `app_token` / `user_token`, but itmust return and forward only canonical `token` / `user` fields so agent-adjacent shared `internal/api/` surfaces do not inherit a second live aliascontract.That notification boundary also carries resource-tag routing configuration.-`internal/api/notifications.go` may preserve and normalize `tagFilter` plus+`internal/api/alerting/notifications.go` may preserve and normalize `tagFilter` plus`tagFilterMode` for email and webhook destinations, but those fields remainnotifications/alerts-owned delivery policy. They do not change agentenrollment, command targeting, lifecycle authority, or host identity.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 7dbf1fa69c..36ecde42e2 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -20,6 +20,15 @@## Purpose+The API runtime is decomposed along production domain boundaries so Go can+compile and execute domain qualification packages concurrently. Shared tenant+identity and scope enforcement live in `internal/api/apicontext/` and+`internal/api/apihttp/`; alert lifecycle, notification management, queue/DLQ,+and their monitor adapters live together in `internal/api/alerting/` with their+unit and contract tests. The root `internal/api` package retains router wiring,+cross-domain integration proof, and compatibility aliases for established+extensions; domain behavior must not be copied back into that root facade.+Browser WebSocket shutdown distinguishes ordinary client lifecycle fromtransport failure. Normal closure, navigation/going-away, and abnormal closurecodes used by disconnected clients are informational; policy violations and@@ -126,7 +135,7 @@ continues to mint and quote the enrollment token.1c. `internal/config/persistence_metadata_accessors.go`2. `internal/api/resources.go`3. `internal/api/discovery_handlers.go`-4. `internal/api/alerts.go`+4. `internal/api/alerting/alerts.go`4a. `internal/api/attention_handlers.go`4b. `internal/api/attention_receipts.go`5. `internal/api/activity_audit_handlers.go`@@ -250,7 +259,10 @@ continues to mint and quote the enrollment token.83. `scripts/generate-types.go`83a. `internal/api/agent_fleet_doctor.go`83b. `frontend-modern/src/api/agentDiagnostics.ts`-84. `internal/api/notification_queue.go`+84. `internal/api/alerting/notification_queue.go`+ 84a. `internal/api/alerting/notifications.go`+ 84b. `internal/api/apicontext/`+ 84c. `internal/api/apihttp/`85. `docs/release-control/v6/internal/MOBILE_COMPATIBILITY_MANIFEST.json`86. `docs/release-control/v6/internal/mobile_compatibility_manifest.schema.json`87. `scripts/release_control/generate_mobile_compatibility.py`@@ -355,7 +367,7 @@ the config lock.WebSocket state refreshes triggered by API handlers are invalidation signals,not a parallel API payload contract. `internal/api/agent_handlers_base.go` and-`internal/api/alerts.go` may check subscriber counts, then call+`internal/api/alerting/alerts.go` may check subscriber counts, then call`BroadcastCurrentState` / `BroadcastCurrentStateToTenant`; they must not buildor retain full frontend-state payloads at the handler boundary. The WebSockethub owns tenant-aware state resolution after coalescing, through the same state@@ -1755,7 +1767,9 @@ payload shape change when the portal presents compact client rows.must treat this payload as the canonical provider health contract ratherthan parsing free-form provider error strings.66. `internal/api/ai_intelligence_handlers.go` shared with `ai-runtime`: AI intelligence handlers are both an AI runtime control surface and a canonical API payload contract boundary.-67. `internal/api/config_setup_handlers.go` shared with `agent-lifecycle`: auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.+67. `internal/api/alerting/notification_queue.go` shared with `notifications`: the notification queue and DLQ handler is both a notification delivery consequence surface and a canonical API payload boundary for operational transition links.+68. `internal/api/alerting/notifications.go` shared with `notifications`: notification handlers are both a notification delivery control surface and a canonical API payload contract boundary.+69. `internal/api/config_setup_handlers.go` shared with `agent-lifecycle`: auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.That same shared boundary also owns reachable-host selection truth for canonical Proxmox registration: runtime callers may propose ordered `candidateHosts`, but the API contract must persist and echo the first candidate Pulse can actually reach instead of freezing the caller's rejected first preference into the stored node endpoint.That same canonical payload contract also owns strict-TLS truth for that selected host: `/api/auto-register` may only persist `VerifySSL=true` when Pulse actually captured a certificate fingerprint for the selected candidate, and it must not pretend public-CA verification is safe after every candidate fingerprint probe failed.For PVE cluster sources, that same contract must distinguish primary@@ -1832,9 +1846,9 @@ payload shape change when the portal presents compact client rows.`VM.GuestAgent.FileRead` on PVE 9+ and reserve `VM.Monitor` for the legacyPVE 8 fallback, so API-generated scripts, runtime setup, installer setup,and browser manual guidance stay on one privilege contract.-68. `internal/api/enterprise_extension_rbac_admin.go` shared with `organization-settings`: RBAC admin extension endpoints are both an organization settings control surface and a canonical API payload contract boundary.-69. `internal/api/licensing_bridge.go` shared with `cloud-paid`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.-70. `internal/api/licensing_handlers.go` shared with `cloud-paid`: commercial licensing handlers carry both API payload contract and cloud-paid entitlement boundary ownership.+70. `internal/api/enterprise_extension_rbac_admin.go` shared with `organization-settings`: RBAC admin extension endpoints are both an organization settings control surface and a canonical API payload contract boundary.+71. `internal/api/licensing_bridge.go` shared with `cloud-paid`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.+72. `internal/api/licensing_handlers.go` shared with `cloud-paid`: commercial licensing handlers carry both API payload contract and cloud-paid entitlement boundary ownership.That same shared licensing boundary also owns authenticatedinstall-version and runtime-build attribution: `internal/api/router.go`must hand the canonical process `serverVersion` and normalized runtime@@ -1855,9 +1869,7 @@ payload shape change when the portal presents compact client rows.destination, but the browser/API contract must not reintroducePulse-Pro-as-page-name copy in callback titles, actions, or retryguidance.-71. `internal/api/licensing_legacy_retry.go` shared with `cloud-paid`: the background legacy-exchange retry loop carries both API payload contract and cloud-paid entitlement boundary ownership.-72. `internal/api/notification_queue.go` shared with `notifications`: the notification queue and DLQ handler is both a notification delivery consequence surface and a canonical API payload boundary for operational transition links.-73. `internal/api/notifications.go` shared with `notifications`: notification handlers are both a notification delivery control surface and a canonical API payload contract boundary.+73. `internal/api/licensing_legacy_retry.go` shared with `cloud-paid`: the background legacy-exchange retry loop carries both API payload contract and cloud-paid entitlement boundary ownership.74. `internal/api/org_handlers.go` shared with `organization-settings`: organization management handlers are both an organization settings control surface and a canonical API payload contract boundary.75. `internal/api/org_lifecycle_handlers.go` shared with `organization-settings`: organization lifecycle handlers are both an organization settings control surface and a canonical API payload contract boundary.76. `internal/api/payments_webhook_handlers.go` shared with `cloud-paid`: commercial payment webhook handlers carry both API payload contract and cloud-paid billing boundary ownership.@@ -4079,6 +4091,12 @@ auto-register mutation boundary.## Current State+The first production package boundary is active under+`internal/api/alerting/`, backed by shared tenant-context and scope-enforcement+packages. Alert and notification unit/contract proof executes independently;+the root router package retains cross-domain integration tests and stable+compatibility aliases instead of duplicating domain behavior.+### Host sensor payloads carry typed command and REST custom readingsAgent, host-model, frontend, and unified-resource sensor payloads now include a@@ -6657,7 +6675,7 @@ surfaces consume it: `status_explanation`, `explanation`, andmissing mixed-version fields may be repaired only inside that API client layerrather than in panel-local fallback helpers.That same shared API boundary rule now also applies to notification test-handlers: `internal/api/notifications.go` may decode webhook-test requests and+handlers: `internal/api/alerting/notifications.go` may decode webhook-test requests andreturn the governed response envelope, but notifications-owned service-templateselection, safe header copying, and generic webhook-test payload fallback muststay in `internal/notifications/` rather than becoming a second API-layer ownerdiff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.mdindex cb7a8ddd19..534382a896 100644--- a/docs/release-control/v6/internal/subsystems/notifications.md+++ b/docs/release-control/v6/internal/subsystems/notifications.md@@ -39,24 +39,24 @@ group headings, and HTML-escape every resource, message, and category field.2. `internal/notifications/queue.go`3. `internal/notifications/email_enhanced.go`4. `internal/notifications/webhook_enhanced.go`-5. `internal/api/notifications.go`+5. `internal/api/alerting/notifications.go`6. `frontend-modern/src/api/notifications.ts`7. `internal/operationaltrust/contracts.go`-8. `internal/api/notification_queue.go`+8. `internal/api/alerting/notification_queue.go`9. `internal/notifications/tag_routing.go`10. `internal/notifications/delivery_health.go`## Shared Boundaries1. `frontend-modern/src/api/notifications.ts` shared with `api-contracts`: the notifications frontend client is both a notification delivery control surface and a canonical API payload contract boundary.-2. `internal/api/notification_queue.go` shared with `api-contracts`: the notification queue and DLQ handler is both a notification delivery consequence surface and a canonical API payload boundary for operational transition links.-3. `internal/api/notifications.go` shared with `api-contracts`: notification handlers are both a notification delivery control surface and a canonical API payload contract boundary.+2. `internal/api/alerting/notification_queue.go` shared with `api-contracts`: the notification queue and DLQ handler is both a notification delivery consequence surface and a canonical API payload boundary for operational transition links.+3. `internal/api/alerting/notifications.go` shared with `api-contracts`: notification handlers are both a notification delivery control surface and a canonical API payload contract boundary.4. `internal/operationaltrust/contracts.go` shared with `alerts`: the operational trust contract is jointly consumed by canonical alert lifecycle ownership and notification delivery linkage without making delivery state operational truth.## Extension Points1. Add or change provider delivery, queue processing, or retry behavior through `internal/notifications/`-2. Add or change notification-management request or response handling through `internal/api/notifications.go`+2. Add or change notification-management request or response handling through `internal/api/alerting/notifications.go`3. Add or change notification-management frontend transport through `frontend-modern/src/api/notifications.ts`4. Add or change the delivery-health verdict through`internal/notifications/delivery_health.go`. `ClassifyQueueHealth` is the@@ -65,7 +65,7 @@ group headings, and HTML-escape every resource, message, and category field.carry their own copy. Only terminal failed or dead-letter outcomes count asunhealthy; recoverable retry attempts do not. A queue that cannot be readreports `unavailable` and never `healthy`, because an unreadable queue must- not be mistaken for successful delivery. `internal/api/notifications.go`+ not be mistaken for successful delivery. `internal/api/alerting/notifications.go`delegates to this rule rather than reimplementing it, and `monitoring`consumes it to raise the notification-delivery system alert.@@ -107,6 +107,12 @@ stable opaque routing identities and must not expose credentials.## Current State+Notification-management HTTP production and its unit/contract proof now live+together under `internal/api/alerting/`. Router-level scope and integration+tests remain in `internal/api`, while the compatibility aliases there keep the+existing extension surface stable. This gives notification qualification a+native Go package scheduling boundary without changing routes or payloads.+This subsystem now makes email, webhook, Apprise, queueing, and deliverysafety explicit inside the current architecture lane instead of leaving themimplied by the broader alerts surface. A later lane split can still promote@@ -285,7 +291,7 @@ already-pending alert separately; service templates must be rendered onlyafter the grouped summary contains every alert, so provider-specific payloadscannot silently collapse to the first alert.-`internal/api/notifications.go` and+`internal/api/alerting/notifications.go` and`frontend-modern/src/api/notifications.ts` are shared boundaries with`api-contracts`: they are the product-facing control surface fornotification-management transport, while canonical payload-shape governancediff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex a793c9d3ca..a3621e90cc 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -787,6 +787,22 @@"api-contracts"]},+ {+ "path": "internal/api/alerting/notification_queue.go",+ "rationale": "the notification queue and DLQ handler is both a notification delivery consequence surface and a canonical API payload boundary for operational transition links",+ "subsystems": [+ "api-contracts",+ "notifications"+ ]+ },+ {+ "path": "internal/api/alerting/notifications.go",+ "rationale": "notification handlers are both a notification delivery control surface and a canonical API payload contract boundary",+ "subsystems": [+ "api-contracts",+ "notifications"+ ]+ },{"path": "internal/api/config_setup_handlers.go","rationale": "auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary",@@ -827,22 +843,6 @@"cloud-paid"]},- {- "path": "internal/api/notification_queue.go",- "rationale": "the notification queue and DLQ handler is both a notification delivery consequence surface and a canonical API payload boundary for operational transition links",- "subsystems": [- "api-contracts",- "notifications"- ]- },- {- "path": "internal/api/notifications.go",- "rationale": "notification handlers are both a notification delivery control surface and a canonical API payload contract boundary",- "subsystems": [- "api-contracts",- "notifications"- ]- },{"path": "internal/api/org_handlers.go","rationale": "organization management handlers are both an organization settings control surface and a canonical API payload contract boundary",@@ -2865,7 +2865,7 @@"match_prefixes": [],"match_files": ["frontend-modern/src/api/alertIntentPolicies.ts",- "internal/api/alerts.go"+ "internal/api/alerting/alerts.go"],"allow_same_subsystem_tests": false,"test_prefixes": [],@@ -2909,7 +2909,7 @@"internal/api/availability_handlers_test.go","internal/api/contract_test.go","internal/api/docker_agents_report_size_test.go",- "internal/api/external_probe_notifications_test.go",+ "internal/api/alerting/external_probe_notifications_test.go","internal/api/host_agent_removal_lifecycle_integration_test.go","internal/api/issue1640_readiness_gate_test.go","internal/api/issue1640_readiness_transport_test.go",@@ -5884,8 +5884,8 @@],"owned_files": ["frontend-modern/src/api/notifications.ts",- "internal/api/notification_queue.go",- "internal/api/notifications.go",+ "internal/api/alerting/notification_queue.go",+ "internal/api/alerting/notifications.go","internal/operationaltrust/contracts.go"],"verification": {@@ -5900,17 +5900,19 @@"match_prefixes": [],"match_files": ["frontend-modern/src/api/notifications.ts",- "internal/api/notification_queue.go",- "internal/api/notifications.go"+ "internal/api/alerting/notification_queue.go",+ "internal/api/alerting/notifications.go"],"allow_same_subsystem_tests": false,"test_prefixes": [],"exact_files": ["frontend-modern/src/api/__tests__/notifications.test.ts",- "internal/api/notification_queue_additional_test.go",- "internal/api/notification_queue_error_test.go",- "internal/api/notifications_scope_test.go",- "internal/api/notifications_test.go"+ "internal/api/alerting/notification_queue_additional_test.go",+ "internal/api/alerting/notification_queue_error_test.go",+ "internal/api/alerting/notifications_health_test.go",+ "internal/api/alerting/notifications_test.go",+ "internal/api/alerting/rate_limit_integration_test.go",+ "internal/api/notifications_scope_test.go"]},{diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 7014652406..40850f23cb 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -2459,7 +2459,7 @@ restriction lists, role mappings, and masked secret-presence markers create nostorage health, recovery-point, backup verification, restore authorization, orprovider-coverage semantics.-Alert delivery diagnosis on shared `internal/api/alerts.go` is likewise+Alert delivery diagnosis on shared `internal/api/alerting/alerts.go` is likewiseadjacent only: `/api/alerts/delivery-diagnosis` exposes alerts/API-contractread-only notification-policy evidence and creates no storage health,recovery-point, backup verification, restore authorization, or provider@@ -4320,12 +4320,12 @@ recovery-adjacent routes that rely on shared auth helpers may not reintroduceper-handler `returnTo` concatenation or absolute-target acceptance when theyinherit those browser handoff paths through the common API router surface.That same shared `internal/api/` dependency also assumes notification test-handlers stay decode-and-delegate only: `internal/api/notifications.go` may+handlers stay decode-and-delegate only: `internal/api/alerting/notifications.go` mayshare the API helper boundary with storage-adjacent routes, but service-templateselection and generic webhook-test payload fallback must remainnotifications-owned instead of becoming a second API-layer owner.That same shared API boundary also assumes legacy service-specific webhook-aliases are rewritten at ingress only: `internal/api/notifications.go` may+aliases are rewritten at ingress only: `internal/api/alerting/notifications.go` mayaccept compatibility keys like Pushover `app_token` / `user_token`, but itmust return and forward only canonical `token` / `user` fields so storage-adjacent shared `internal/api/` helpers do not inherit a second live aliasdiff --git a/internal/api/alerts.go b/internal/api/alerting/alerts.gosimilarity index 96%rename from internal/api/alerts.gorename to internal/api/alerting/alerts.goindex 81441e5745..57b6143488 100644--- a/internal/api/alerts.go+++ b/internal/api/alerting/alerts.go@@ -1,4 +1,4 @@-package api+package alertingimport ("context"@@ -14,6 +14,8 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/memory""github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/api/apicontext"+ "github.com/rcourtman/pulse-go-rewrite/internal/api/apihttp""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/mock""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -119,7 +121,7 @@ func (h *AlertHandlers) getMonitor(ctx context.Context) AlertMonitor {defaultMonitor := h.defaultMonitorh.stateMu.RUnlock()- orgID := GetOrgID(ctx)+ orgID := apicontext.OrgID(ctx)if mtMonitor != nil {if m, err := mtMonitor.GetMonitor(orgID); err == nil && m != nil {return NewAlertMonitorWrapper(m)@@ -128,12 +130,19 @@ func (h *AlertHandlers) getMonitor(ctx context.Context) AlertMonitor {return defaultMonitor}+// MonitorForContext resolves the tenant-scoped alert runtime used by handlers.+// It is the supported extension boundary for integrations that need the same+// tenant selection semantics as HTTP alert routes.+func (h *AlertHandlers) MonitorForContext(ctx context.Context) AlertMonitor {+ return h.getMonitor(ctx)+}+func (h *AlertHandlers) broadcastStateForContext(ctx context.Context) {if h.wsHub == nil {return}- orgID := GetOrgID(ctx)+ orgID := apicontext.OrgID(ctx)if orgID != "" {if h.wsHub.GetTenantClientCount(orgID) == 0 {return@@ -1156,88 +1165,88 @@ func (h *AlertHandlers) HandleAlerts(w http.ResponseWriter, r *http.Request) {switch {case path == "config" && r.Method == http.MethodGet:- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}h.GetAlertConfig(w, r)case path == "config" && r.Method == http.MethodPut:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.UpdateAlertConfig(w, r)case path == "intent-policies" && r.Method == http.MethodGet:- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}h.GetAlertIntentPolicies(w, r)case path == "intent-policies" && r.Method == http.MethodPut:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.UpdateAlertIntentPolicies(w, r)case path == "intent-policies/preview" && r.Method == http.MethodPost:- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}h.PreviewAlertIntentPolicy(w, r)case path == "activate" && r.Method == http.MethodPost:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.ActivateAlerts(w, r)case path == "active" && r.Method == http.MethodGet:- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}h.GetActiveAlerts(w, r)case path == "delivery-diagnosis" && r.Method == http.MethodGet:- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}h.GetAlertDeliveryDiagnosis(w, r)case path == "history" && r.Method == http.MethodGet:- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}h.GetAlertHistory(w, r)case path == "incidents" && r.Method == http.MethodGet:- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}h.GetAlertIncidentTimeline(w, r)case path == "incidents/note" && r.Method == http.MethodPost:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.SaveAlertIncidentNote(w, r)case path == "history" && r.Method == http.MethodDelete:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.ClearAlertHistory(w, r)case path == "bulk/acknowledge" && r.Method == http.MethodPost:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.BulkAcknowledgeAlerts(w, r)case path == "bulk/clear" && r.Method == http.MethodPost:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.BulkClearAlerts(w, r)// Body-based endpoints (preferred - avoids URL encoding issues with reverse proxies)case path == "acknowledge" && r.Method == http.MethodPost:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.AcknowledgeAlertByBody(w, r)case path == "unacknowledge" && r.Method == http.MethodPost:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.UnacknowledgeAlertByBody(w, r)case path == "clear" && r.Method == http.MethodPost:- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}h.ClearAlertByBody(w, r)diff --git a/internal/api/alerts_test.go b/internal/api/alerting/alerts_test.gosimilarity index 99%rename from internal/api/alerts_test.gorename to internal/api/alerting/alerts_test.goindex 5c8ea48f22..cf47405e9f 100644--- a/internal/api/alerts_test.go+++ b/internal/api/alerting/alerts_test.go@@ -1,4 +1,4 @@-package api+package alertingimport ("bytes"diff --git a/internal/api/external_probe_notifications.go b/internal/api/alerting/external_probe_notifications.gosimilarity index 95%rename from internal/api/external_probe_notifications.gorename to internal/api/alerting/external_probe_notifications.goindex cbb0e1e6f9..ecf3c1ecbf 100644--- a/internal/api/external_probe_notifications.go+++ b/internal/api/alerting/external_probe_notifications.go@@ -1,4 +1,4 @@-package api+package alertingimport ("strings"@@ -10,7 +10,7 @@ import (// externalProbePushNotification keeps mobile payloads deliberately generic:// alert metadata selects the event, while infrastructure names and addresses// remain inside the self-hosted Pulse instance.-func externalProbePushNotification(+func ExternalProbePushNotification(alert *alerts.Alert,hasProbeAssignments func(string) bool,) (relay.PushNotificationPayload, bool) {diff --git a/internal/api/external_probe_notifications_test.go b/internal/api/alerting/external_probe_notifications_test.gosimilarity index 87%rename from internal/api/external_probe_notifications_test.gorename to internal/api/alerting/external_probe_notifications_test.goindex 3a8fa85f86..8791649386 100644--- a/internal/api/external_probe_notifications_test.go+++ b/internal/api/alerting/external_probe_notifications_test.go@@ -1,4 +1,4 @@-package api+package alertingimport ("testing"@@ -15,7 +15,7 @@ func TestExternalProbePushNotificationSelectsOnlyProbeLoss(t *testing.T) {"incidentSource": alerts.ExternalProbeIncidentSource,},}- notification, ok := externalProbePushNotification(alert, nil)+ notification, ok := ExternalProbePushNotification(alert, nil)if !ok {t.Fatal("external probe loss did not produce a push notification")}@@ -37,7 +37,7 @@ func TestExternalProbePushNotificationSelectsOnlyProbeLoss(t *testing.T) {"incidentSource": alerts.ExternalProbeIncidentSource,}},} {- if got, ok := externalProbePushNotification(other, nil); ok {+ if got, ok := ExternalProbePushNotification(other, nil); ok {t.Fatalf("unrelated alert %#v produced push %#v", other, got)}}@@ -52,7 +52,7 @@ func TestExternalProbePushNotificationSelectsAssignedHostOffline(t *testing.T) {},}ownsAssignments := func(agentID string) bool { return agentID == "agent-1" }- notification, ok := externalProbePushNotification(alert, ownsAssignments)+ notification, ok := ExternalProbePushNotification(alert, ownsAssignments)if !ok {t.Fatal("assigned probe host-offline alert did not produce a push")}@@ -60,7 +60,7 @@ func TestExternalProbePushNotificationSelectsAssignedHostOffline(t *testing.T) {t.Fatalf("notification = %#v, want external probe mobile routing", notification)}- if got, ok := externalProbePushNotification(alert, func(string) bool { return false }); ok {+ if got, ok := ExternalProbePushNotification(alert, func(string) bool { return false }); ok {t.Fatalf("ordinary host-offline alert produced external probe push %#v", got)}}diff --git a/internal/api/monitor_wrappers.go b/internal/api/alerting/monitor_wrappers.gosimilarity index 99%rename from internal/api/monitor_wrappers.gorename to internal/api/alerting/monitor_wrappers.goindex 48d2b8d4fa..9f709035d9 100644--- a/internal/api/monitor_wrappers.go+++ b/internal/api/alerting/monitor_wrappers.go@@ -1,4 +1,4 @@-package api+package alertingimport ("github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"diff --git a/internal/api/monitor_wrappers_test.go b/internal/api/alerting/monitor_wrappers_test.gosimilarity index 99%rename from internal/api/monitor_wrappers_test.gorename to internal/api/alerting/monitor_wrappers_test.goindex 8dd748ebe6..ba850bc19d 100644--- a/internal/api/monitor_wrappers_test.go+++ b/internal/api/alerting/monitor_wrappers_test.go@@ -1,4 +1,4 @@-package api+package alertingimport ("reflect"diff --git a/internal/api/notification_queue.go b/internal/api/alerting/notification_queue.gosimilarity index 94%rename from internal/api/notification_queue.gorename to internal/api/alerting/notification_queue.goindex 2d04ffa99e..c1a7e53b1b 100644--- a/internal/api/notification_queue.go+++ b/internal/api/alerting/notification_queue.go@@ -1,10 +1,11 @@-package api+package alertingimport ("encoding/json""net/http""strconv"+ "github.com/rcourtman/pulse-go-rewrite/internal/api/apihttp""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rcourtman/pulse-go-rewrite/internal/notifications"@@ -26,7 +27,7 @@ func NewNotificationQueueHandlers(monitor *monitoring.Monitor) *NotificationQueu// GetDLQ returns notifications in the dead letter queuefunc (h *NotificationQueueHandlers) GetDLQ(w http.ResponseWriter, r *http.Request) {- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}@@ -57,7 +58,7 @@ func (h *NotificationQueueHandlers) GetDLQ(w http.ResponseWriter, r *http.Reques// GetQueueStats returns statistics about the notification queuefunc (h *NotificationQueueHandlers) GetQueueStats(w http.ResponseWriter, r *http.Request) {- if !ensureScope(w, r, config.ScopeMonitoringRead) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringRead) {return}@@ -81,7 +82,7 @@ func (h *NotificationQueueHandlers) GetQueueStats(w http.ResponseWriter, r *http// RetryDLQItem retries a specific notification from the DLQfunc (h *NotificationQueueHandlers) RetryDLQItem(w http.ResponseWriter, r *http.Request) {- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}@@ -128,7 +129,7 @@ func (h *NotificationQueueHandlers) RetryDLQItem(w http.ResponseWriter, r *http.// DeleteDLQItem removes a notification from the DLQ permanentlyfunc (h *NotificationQueueHandlers) DeleteDLQItem(w http.ResponseWriter, r *http.Request) {- if !ensureScope(w, r, config.ScopeMonitoringWrite) {+ if !apihttp.EnsureScope(w, r, config.ScopeMonitoringWrite) {return}diff --git a/internal/api/notification_queue_additional_test.go b/internal/api/alerting/notification_queue_additional_test.gosimilarity index 99%rename from internal/api/notification_queue_additional_test.gorename to internal/api/alerting/notification_queue_additional_test.goindex fbc14e2828..4d9cbbd026 100644--- a/internal/api/notification_queue_additional_test.go+++ b/internal/api/alerting/notification_queue_additional_test.go@@ -1,4 +1,4 @@-package api+package alertingimport ("bytes"diff --git a/internal/api/notification_queue_error_test.go b/internal/api/alerting/notification_queue_error_test.gosimilarity index 96%rename from internal/api/notification_queue_error_test.gorename to internal/api/alerting/notification_queue_error_test.goindex de32652c94..ef832bd2f2 100644--- a/internal/api/notification_queue_error_test.go+++ b/internal/api/alerting/notification_queue_error_test.go@@ -1,4 +1,4 @@-package api+package alertingimport ("bytes"@@ -10,6 +10,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rcourtman/pulse-go-rewrite/internal/notifications"+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth")func TestNotificationQueueHandlers_GetDLQ_MissingScope(t *testing.T) {@@ -17,7 +18,7 @@ func TestNotificationQueueHandlers_GetDLQ_MissingScope(t *testing.T) {req := httptest.NewRequest(http.MethodGet, "/api/notifications/dlq", nil)record := &config.APITokenRecord{Scopes: []string{config.ScopeMonitoringWrite}}- attachAPITokenRecord(req, record)+ req = req.WithContext(internalauth.WithAPIToken(req.Context(), record))rec := httptest.NewRecorder()handler.GetDLQ(rec, req)diff --git a/internal/api/notifications.go b/internal/api/alerting/notifications.gosimilarity index 98%rename from internal/api/notifications.gorename to internal/api/alerting/notifications.goindex 8053b37fc5..c2b1f2dbd0 100644--- a/internal/api/notifications.go+++ b/internal/api/alerting/notifications.go@@ -1,4 +1,4 @@-package api+package alertingimport ("context"@@ -12,11 +12,14 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/api/apicontext"+ "github.com/rcourtman/pulse-go-rewrite/internal/api/apihttp""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rcourtman/pulse-go-rewrite/internal/notifications""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/internal/utils"+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rs/zerolog/log")@@ -123,7 +126,7 @@ func (h *NotificationHandlers) getMonitor(ctx context.Context) NotificationMonitdefaultMonitor := h.defaultMonitorh.stateMu.RUnlock()- orgID := GetOrgID(ctx)+ orgID := apicontext.OrgID(ctx)if mtMonitor != nil {if m, err := mtMonitor.GetMonitor(orgID); err == nil && m != nil {return NewNotificationMonitorWrapper(m)@@ -132,6 +135,12 @@ func (h *NotificationHandlers) getMonitor(ctx context.Context) NotificationMonitreturn defaultMonitor}+// MonitorForContext resolves the tenant-scoped notification runtime used by+// handlers and extensions.+func (h *NotificationHandlers) MonitorForContext(ctx context.Context) NotificationMonitor {+ return h.getMonitor(ctx)+}+// getReadState returns the tenant-scoped ReadState for the request context.// It resolves the correct monitor for the org and returns its ReadState.// Falls back to the handler-level readState only for default/empty org.@@ -142,7 +151,7 @@ func (h *NotificationHandlers) getReadState(ctx context.Context) unifiedresourcefallback := h.readStateh.stateMu.RUnlock()- orgID := GetOrgID(ctx)+ orgID := apicontext.OrgID(ctx)if mtMonitor != nil {if m, err := mtMonitor.GetMonitor(orgID); err == nil && m != nil {if rs := m.GetUnifiedReadState(); rs != nil {@@ -989,7 +998,7 @@ func (h *NotificationHandlers) HandleNotifications(w http.ResponseWriter, r *httpath := strings.TrimPrefix(r.URL.Path, "/api/notifications")requireAnyScope := func(required string, scopes ...string) bool {- record := getAPITokenRecordFromRequest(r)+ record := internalauth.GetAPIToken(r.Context())if record == nil {return true}@@ -998,7 +1007,7 @@ func (h *NotificationHandlers) HandleNotifications(w http.ResponseWriter, r *httreturn true}}- respondMissingScope(w, required)+ apihttp.RespondMissingScope(w, required)return false}diff --git a/internal/api/alerting/notifications_contract_test.go b/internal/api/alerting/notifications_contract_test.gonew file mode 100644index 0000000000..4f37877f56--- /dev/null+++ b/internal/api/alerting/notifications_contract_test.go@@ -0,0 +1,70 @@+package alerting++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"+ tmock "github.com/stretchr/testify/mock"+)++// TestContract_WebhookSigningSecretMaskedAndPreserved pins the webhook+// management payload contract for delivery signing secrets.+func TestContract_WebhookSigningSecretMaskedAndPreserved(t *testing.T) {+ mockMonitor := new(MockNotificationMonitor)+ mockManager := new(MockNotificationManager)+ mockPersistence := new(MockNotificationConfigPersistence)+ mockMonitor.On("GetNotificationManager").Return(mockManager)+ mockMonitor.On("GetConfigPersistence").Return(mockPersistence)+ h := NewNotificationHandlers(nil, mockMonitor)++ stored := notifications.WebhookConfig{+ ID: "wh-signed",+ Name: "Signed Webhook",+ URL: "https://psa.example.com/inbound/pulse",+ Enabled: true,+ Service: "generic",+ SigningSecret: "stored-secret",+ }++ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{stored}).Once()+ rec := httptest.NewRecorder()+ h.GetWebhooks(rec, httptest.NewRequest(http.MethodGet, "/api/notifications/webhooks", nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("GetWebhooks responded %d", rec.Code)+ }+ var listed []map[string]interface{}+ if err := json.Unmarshal(rec.Body.Bytes(), &listed); err != nil {+ t.Fatalf("decode webhook list: %v", err)+ }+ if len(listed) != 1 {+ t.Fatalf("expected one webhook in list, got %d", len(listed))+ }+ if got := listed[0]["signingSecret"]; got != "***REDACTED***" {+ t.Fatalf("list signingSecret = %v, want masked placeholder", got)+ }++ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{stored}).Once()+ mockManager.On("ValidateWebhookURL", stored.URL).Return(nil).Once()+ mockManager.On("UpdateWebhook", "wh-signed", tmock.MatchedBy(func(w notifications.WebhookConfig) bool {+ return w.SigningSecret == "stored-secret"+ })).Return(nil).Once()+ mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{stored}).Once()+ mockPersistence.On("SaveWebhooks", tmock.Anything).Return(nil).Once()++ update := stored+ update.SigningSecret = "***REDACTED***"+ body, err := json.Marshal(update)+ if err != nil {+ t.Fatalf("marshal update: %v", err)+ }+ rec = httptest.NewRecorder()+ h.UpdateWebhook(rec, httptest.NewRequest(http.MethodPut, "/api/notifications/webhooks/wh-signed", bytes.NewReader(body)))+ if rec.Code != http.StatusOK {+ t.Fatalf("UpdateWebhook responded %d: %s", rec.Code, rec.Body.String())+ }+ mockManager.AssertExpectations(t)+}diff --git a/internal/api/notifications_health_test.go b/internal/api/alerting/notifications_health_test.gosimilarity index 99%rename from internal/api/notifications_health_test.gorename to internal/api/alerting/notifications_health_test.goindex 6dd736445c..b1744003e9 100644--- a/internal/api/notifications_health_test.go+++ b/internal/api/alerting/notifications_health_test.go@@ -1,4 +1,4 @@-package api+package alertingimport ("encoding/json"diff --git a/internal/api/notifications_test.go b/internal/api/alerting/notifications_test.gosimilarity index 99%rename from internal/api/notifications_test.gorename to internal/api/alerting/notifications_test.goindex f097ce4431..a58e93452a 100644--- a/internal/api/notifications_test.go+++ b/internal/api/alerting/notifications_test.go@@ -1,4 +1,4 @@-package api+package alertingimport ("bytes"diff --git a/internal/api/rate_limit_integration_test.go b/internal/api/alerting/rate_limit_integration_test.gosimilarity index 99%rename from internal/api/rate_limit_integration_test.gorename to internal/api/alerting/rate_limit_integration_test.goindex 85830b7449..a60cca786e 100644--- a/internal/api/rate_limit_integration_test.go+++ b/internal/api/alerting/rate_limit_integration_test.go@@ -1,4 +1,4 @@-package api+package alertingimport ("bytes"diff --git a/internal/api/alerting/reflection_test.go b/internal/api/alerting/reflection_test.gonew file mode 100644index 0000000000..9f0e379c5d--- /dev/null+++ b/internal/api/alerting/reflection_test.go@@ -0,0 +1,16 @@+package alerting++import (+ "reflect"+ "testing"+ "unsafe"+)++func setUnexportedField(t *testing.T, target any, fieldName string, value any) {+ t.Helper()+ field := reflect.ValueOf(target).Elem().FieldByName(fieldName)+ if !field.IsValid() {+ t.Fatalf("field %q not found", fieldName)+ }+ reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Set(reflect.ValueOf(value))+}diff --git a/internal/api/alerting_compat.go b/internal/api/alerting_compat.gonew file mode 100644index 0000000000..cfb4533610--- /dev/null+++ b/internal/api/alerting_compat.go@@ -0,0 +1,35 @@+package api++import (+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ alertingapi "github.com/rcourtman/pulse-go-rewrite/internal/api/alerting"+ "github.com/rcourtman/pulse-go-rewrite/internal/relay"+)++// Compatibility aliases keep the established internal/api extension surface+// stable while alert-delivery production code and tests live in their domain+// package and can be scheduled independently by the Go toolchain.+type AlertManager = alertingapi.AlertManager+type ConfigPersistence = alertingapi.ConfigPersistence+type AlertMonitor = alertingapi.AlertMonitor+type AlertHandlers = alertingapi.AlertHandlers+type NotificationManager = alertingapi.NotificationManager+type NotificationConfigPersistence = alertingapi.NotificationConfigPersistence+type NotificationMonitor = alertingapi.NotificationMonitor+type NotificationHandlers = alertingapi.NotificationHandlers+type NotificationQueueHandlers = alertingapi.NotificationQueueHandlers+type AlertMonitorWrapper = alertingapi.AlertMonitorWrapper+type NotificationMonitorWrapper = alertingapi.NotificationMonitorWrapper++var NewAlertHandlers = alertingapi.NewAlertHandlers+var NewNotificationHandlers = alertingapi.NewNotificationHandlers+var NewNotificationQueueHandlers = alertingapi.NewNotificationQueueHandlers+var NewAlertMonitorWrapper = alertingapi.NewAlertMonitorWrapper+var NewNotificationMonitorWrapper = alertingapi.NewNotificationMonitorWrapper++func externalProbePushNotification(+ alert *alerts.Alert,+ hasProbeAssignments func(string) bool,+) (relay.PushNotificationPayload, bool) {+ return alertingapi.ExternalProbePushNotification(alert, hasProbeAssignments)+}diff --git a/internal/api/apicontext/context.go b/internal/api/apicontext/context.gonew file mode 100644index 0000000000..ec7fc9772e--- /dev/null+++ b/internal/api/apicontext/context.go@@ -0,0 +1,31 @@+package apicontext++import (+ "context"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++// OrganizationContextKey is shared by tenant middleware and domain handlers.+type OrganizationContextKey string++const (+ OrgIDContextKey OrganizationContextKey = "org_id"+ OrgContextKey OrganizationContextKey = "org_object"+)++// OrgID returns the selected tenant or the historical default tenant.+func OrgID(ctx context.Context) string {+ if id, ok := ctx.Value(OrgIDContextKey).(string); ok {+ return id+ }+ return "default"+}++// Organization returns the selected organization or the default organization.+func Organization(ctx context.Context) *models.Organization {+ if org, ok := ctx.Value(OrgContextKey).(*models.Organization); ok {+ return org+ }+ return &models.Organization{ID: "default", DisplayName: "Default Organization"}+}diff --git a/internal/api/apihttp/scope.go b/internal/api/apihttp/scope.gonew file mode 100644index 0000000000..8b87903457--- /dev/null+++ b/internal/api/apihttp/scope.go@@ -0,0 +1,66 @@+package apihttp++import (+ "encoding/json"+ "net/http"+ "strings"++ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++// EnsureScope admits sessions and API tokens carrying the required scope.+func EnsureScope(w http.ResponseWriter, r *http.Request, scope string) bool {+ return EnsureAnyScope(w, r, scope)+}++// EnsureAnyScope admits sessions and API tokens carrying any required scope.+func EnsureAnyScope(w http.ResponseWriter, r *http.Request, scopes ...string) bool {+ normalized := make([]string, 0, len(scopes))+ for _, scope := range scopes {+ scope = strings.TrimSpace(scope)+ if scope == "" {+ return true+ }+ normalized = append(normalized, scope)+ }+ if len(normalized) == 0 {+ return true+ }++ record := internalauth.GetAPIToken(r.Context())+ if record == nil {+ return true+ }+ for _, scope := range normalized {+ if record.HasScope(scope) {+ return true+ }+ }++ if len(normalized) == 1 {+ RespondMissingScope(w, normalized[0])+ return false+ }+ if w != nil {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusForbidden)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "error": "missing_scope",+ "requiredScopes": normalized,+ })+ }+ return false+}++// RespondMissingScope writes the canonical single-scope denial envelope.+func RespondMissingScope(w http.ResponseWriter, scope string) {+ if w == nil {+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusForbidden)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "error": "missing_scope",+ "requiredScope": scope,+ })+}diff --git a/internal/api/auth.go b/internal/api/auth.goindex aa7a71e8db..e50b27f442 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -13,6 +13,7 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/api/apihttp""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rcourtman/pulse-go-rewrite/pkg/auth"@@ -1236,62 +1237,19 @@ func RequireAnyScope(scopes []string, handler http.HandlerFunc) http.HandlerFunc}func respondMissingScope(w http.ResponseWriter, scope string) {- if w == nil {- return- }-- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusForbidden)- _ = json.NewEncoder(w).Encode(map[string]any{- "error": "missing_scope",- "requiredScope": scope,- })+ apihttp.RespondMissingScope(w, scope)}// ensureScope enforces that the request either originates from a session or a token// possessing the specified scope. Returns true when access should continue.func ensureScope(w http.ResponseWriter, r *http.Request, scope string) bool {- return ensureAnyScope(w, r, scope)+ return apihttp.EnsureScope(w, r, scope)}// ensureAnyScope enforces that the request either originates from a session or// a token possessing at least one of the specified scopes.func ensureAnyScope(w http.ResponseWriter, r *http.Request, scopes ...string) bool {- normalized := make([]string, 0, len(scopes))- for _, scope := range scopes {- scope = strings.TrimSpace(scope)- if scope == "" {- return true- }- normalized = append(normalized, scope)- }- if len(normalized) == 0 {- return true- }-- record := getAPITokenRecordFromRequest(r)- if record == nil {- return true- }- for _, scope := range normalized {- if record.HasScope(scope) {- return true- }- }-- if len(normalized) == 1 {- respondMissingScope(w, normalized[0])- return false- }- if w != nil {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusForbidden)- _ = json.NewEncoder(w).Encode(map[string]any{- "error": "missing_scope",- "requiredScopes": normalized,- })- }- return false+ return apihttp.EnsureAnyScope(w, r, scopes...)}func attachAPITokenRecord(r *http.Request, record *config.APITokenRecord) {diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 76a1e09992..55d4a601e5 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -42,7 +42,6 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/mock""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/monitoring"- "github.com/rcourtman/pulse-go-rewrite/internal/notifications""github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt""github.com/rcourtman/pulse-go-rewrite/internal/recovery""github.com/rcourtman/pulse-go-rewrite/internal/relay"@@ -545,15 +544,15 @@ func TestContract_PatrolAttentionRoutesAcceptMobileRelayCapability(t *testing.T)}func TestContract_AlertDeliveryDiagnosisRouteIsReadOnlyMonitoringRead(t *testing.T) {- source, err := os.ReadFile("alerts.go")+ source, err := os.ReadFile(filepath.Join("alerting", "alerts.go"))if err != nil {- t.Fatalf("read alerts.go: %v", err)+ t.Fatalf("read alerting/alerts.go: %v", err)}src := string(source)required := []string{`case path == "delivery-diagnosis" && r.Method == http.MethodGet:`,- `ensureScope(w, r, config.ScopeMonitoringRead)`,+ `apihttp.EnsureScope(w, r, config.ScopeMonitoringRead)`,`h.GetAlertDeliveryDiagnosis(w, r)`,`manager.DiagnoseAlertDelivery(alertIdentifier)`,}@@ -21941,69 +21940,6 @@ func TestContract_MetadataGetPayloadsUseZeroRecordsInsteadOf404(t *testing.T) {}}-// TestContract_WebhookSigningSecretMaskedAndPreserved pins the webhook-// management payload contract for delivery signing secrets: the list API must-// mask a configured secret with the shared redaction placeholder, and an-// update that echoes the placeholder must preserve the stored secret instead-// of overwriting it with the literal placeholder string.-func TestContract_WebhookSigningSecretMaskedAndPreserved(t *testing.T) {- mockMonitor := new(MockNotificationMonitor)- mockManager := new(MockNotificationManager)- mockPersistence := new(MockNotificationConfigPersistence)- mockMonitor.On("GetNotificationManager").Return(mockManager)- mockMonitor.On("GetConfigPersistence").Return(mockPersistence)- h := NewNotificationHandlers(nil, mockMonitor)-- stored := notifications.WebhookConfig{- ID: "wh-signed",- Name: "Signed Webhook",- URL: "https://psa.example.com/inbound/pulse",- Enabled: true,- Service: "generic",- SigningSecret: "stored-secret",- }-- // List must mask the configured secret.- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{stored}).Once()- rec := httptest.NewRecorder()- h.GetWebhooks(rec, httptest.NewRequest(http.MethodGet, "/api/notifications/webhooks", nil))- if rec.Code != http.StatusOK {- t.Fatalf("GetWebhooks responded %d", rec.Code)- }- var listed []map[string]interface{}- if err := json.Unmarshal(rec.Body.Bytes(), &listed); err != nil {- t.Fatalf("decode webhook list: %v", err)- }- if len(listed) != 1 {- t.Fatalf("expected one webhook in list, got %d", len(listed))- }- if got := listed[0]["signingSecret"]; got != "***REDACTED***" {- t.Fatalf("list signingSecret = %v, want masked placeholder", got)- }-- // Update echoing the masked placeholder must preserve the stored secret.- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{stored}).Once()- mockManager.On("ValidateWebhookURL", stored.URL).Return(nil).Once()- mockManager.On("UpdateWebhook", "wh-signed", tmock.MatchedBy(func(w notifications.WebhookConfig) bool {- return w.SigningSecret == "stored-secret"- })).Return(nil).Once()- mockManager.On("GetWebhooks").Return([]notifications.WebhookConfig{stored}).Once()- mockPersistence.On("SaveWebhooks", tmock.Anything).Return(nil).Once()-- update := stored- update.SigningSecret = "***REDACTED***"- body, err := json.Marshal(update)- if err != nil {- t.Fatalf("marshal update: %v", err)- }- rec = httptest.NewRecorder()- h.UpdateWebhook(rec, httptest.NewRequest(http.MethodPut, "/api/notifications/webhooks/wh-signed", bytes.NewReader(body)))- if rec.Code != http.StatusOK {- t.Fatalf("UpdateWebhook responded %d: %s", rec.Code, rec.Body.String())- }- mockManager.AssertExpectations(t)-}-// TestContract_OrgBoundTokenIsScopedAwayFromDefaultOrg pins the MSP tenant// isolation boundary: a token explicitly bound to client organizations must// not implicitly reach the default org's data (a leaked client-site token@@ -22120,7 +22056,7 @@ func TestContract_StateBroadcastsUseLazyCurrentStateInvalidation(t *testing.T) {"BroadcastState(state)",},},- "alerts.go": {+ filepath.Join("alerting", "alerts.go"): {required: []string{"h.wsHub.BroadcastCurrentStateToTenant(orgID)","h.wsHub.BroadcastCurrentState()",diff --git a/internal/api/middleware_tenant.go b/internal/api/middleware_tenant.goindex 9486928a36..00712801f9 100644--- a/internal/api/middleware_tenant.go+++ b/internal/api/middleware_tenant.go@@ -8,20 +8,21 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"+ "github.com/rcourtman/pulse-go-rewrite/internal/api/apicontext""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rs/zerolog/log")-type OrganizationContextKey string+type OrganizationContextKey = apicontext.OrganizationContextKeyconst (- OrgIDContextKey OrganizationContextKey = "org_id"- OrgContextKey OrganizationContextKey = "org_object"- subStateActive string = "active"- subStateGrace string = "grace"- subStateTrial string = "trial"+ OrgIDContextKey = apicontext.OrgIDContextKey+ OrgContextKey = apicontext.OrgContextKey+ subStateActive string = "active"+ subStateGrace string = "grace"+ subStateTrial string = "trial")// TenantMiddleware extracts the organization ID from the request and@@ -243,18 +244,12 @@ func writeJSONErrorWithDetails(w http.ResponseWriter, status int, code, message// Helper to get OrgID from contextfunc GetOrgID(ctx context.Context) string {- if id, ok := ctx.Value(OrgIDContextKey).(string); ok {- return id- }- return "default"+ return apicontext.OrgID(ctx)}// Helper to get Organization from contextfunc GetOrganization(ctx context.Context) *models.Organization {- if org, ok := ctx.Value(OrgContextKey).(*models.Organization); ok {- return org- }- return &models.Organization{ID: "default", DisplayName: "Default Organization"}+ return apicontext.Organization(ctx)}// isHostedSubscriptionValid checks whether a hosted Cloud tenant has a valid subscriptiondiff --git a/internal/api/router_helpers_more_test.go b/internal/api/router_helpers_more_test.goindex 0ef9845ecd..f3fe4ef8d7 100644--- a/internal/api/router_helpers_more_test.go+++ b/internal/api/router_helpers_more_test.go@@ -184,11 +184,11 @@ func TestSetMultiTenantMonitor_WiresHandlers(t *testing.T) {if router.monitor != defaultMonitor {t.Fatalf("expected router monitor to be set to default monitor")}- if router.alertHandlers.mtMonitor != mtm {- t.Fatalf("expected alertHandlers mtMonitor to be set")+ if got := router.alertHandlers.MonitorForContext(context.Background()); got == nil || got.GetAlertManager() != defaultMonitor.GetAlertManager() {+ t.Fatalf("expected alertHandlers to resolve the default tenant monitor")}- if router.notificationHandlers.mtMonitor != mtm {- t.Fatalf("expected notificationHandlers mtMonitor to be set")+ if got := router.notificationHandlers.MonitorForContext(context.Background()); got == nil || got.GetNotificationManager() != defaultMonitor.GetNotificationManager() {+ t.Fatalf("expected notificationHandlers to resolve the default tenant monitor")}if router.configHandlers.mtMonitor != mtm {t.Fatalf("expected configHandlers mtMonitor to be set")