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
fix(relay): introduce dedicated mobile runtime scope
rcourtman8ba8f0b47537
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex c37ea6fefe..f957b3131f 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -123,6 +123,7 @@ management, and fleet control surfaces.6. Add or change profile management, the extracted agent profiles runtime owner, the pure unified-agent inventory/install model, the direct Proxmox workspace shell, route model, reporting summary owner, shared install/inventory/dialog section owners, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners plus their shared model, shared frontend install-command assembly, Proxmox setup/install API transport, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureReportingPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInventorySection.tsx`, `frontend-modern/src/components/Settings/InfrastructureActiveRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureIgnoredRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureStopMonitoringDialog.tsx`, `frontend-modern/src/components/Settings/InfrastructureDirectConnectionsSummaryCard.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/ProxmoxSettingsPanel.tsx`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ProxmoxDirectWorkspace.tsx`, `frontend-modern/src/components/Settings/ProxmoxConfiguredNodesTable.tsx`, `frontend-modern/src/components/Settings/ProxmoxDirectConnectionsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDiscoveryResultsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDeleteNodeDialog.tsx`, `frontend-modern/src/components/Settings/ProxmoxNodeModalStack.tsx`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/useProxmoxDirectWorkspaceState.ts`, `frontend-modern/src/components/Settings/NodeModal.tsx`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, `frontend-modern/src/components/Infrastructure/deploy/ResultsStep.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`.7. Preserve canonical token-lifecycle reads in shared `internal/api/` auth/security helpers so lifecycle-adjacent setup and install flows do not revoke a displayed relay pairing token after `lastUsedAt` proves that an already paired device is actively depending on that credential.8. Preserve backend-owned Pulse Mobile relay runtime credential minting in those same shared `internal/api/` auth/security helpers so lifecycle-adjacent setup and install flows reuse the canonical mobile token route instead of reintroducing wildcard or browser-authored runtime token bundles.+9. Preserve the dedicated backend-owned `relay:mobile:access` capability and its governed backward-compatible route gates in those same shared helpers so lifecycle-adjacent setup and install flows do not widen the mobile device credential back into general AI chat/execute scope ownership.## Forbidden Paths@@ -189,6 +190,12 @@ reintroducing local array or JSON parsing rules.The owned backend API surfaces must preserve the exact-release installerfallback, canonical /api/auto-register behavior, and hosted org install-commandcontracts instead of leaving those guarantees implied by generic API ownership.+Those shared auth/security helpers now also own the dedicated+`relay:mobile:access` capability that backs Pulse Mobile pairing. Lifecycle-+adjacent setup and install flows may depend on that helper layer, but they may+only consume the server-owned minting route and the governed compatibility+gates for the mobile runtime endpoints. They must not recreate broader+AI-scoped mobile credentials or invent route-local scope exceptions.The direct Proxmox fallback workspace now also lives explicitly inside thislifecycle boundary: `InfrastructureWorkspace.tsx`,`infrastructureWorkspaceModel.ts`,diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex f18e0f0066..18900508f9 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -107,6 +107,13 @@ it. `frontend-modern/src/api/ai.ts`,`internal/api/ai_handlers.go`, and`internal/api/ai_intelligence_handlers.go` are runtime control surfaces forthe AI product while also remaining canonical payload contract boundaries.+That same AI transport boundary now also defines the narrow Pulse Mobile+runtime compatibility rule: mobile relay credentials are minted with the+dedicated backend-owned `relay:mobile:access` scope, and only the governed+mobile runtime routes may accept that scope as a compatibility alias alongside+legacy `ai:chat` or `ai:execute` mobile tokens. Broader AI runtime surfaces+must stay on their canonical AI scopes instead of treating the mobile relay+capability as a general-purpose AI permission.The same ownership includes the Pulse query tool schema under`internal/ai/tools/`: topology-query input names must stay canonical insidethe AI runtime itself, so new tool arguments such as `max_proxmox_nodes`diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 61a9274d53..9a39ac6cd8 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -131,7 +131,7 @@ Own canonical runtime payload shapes between backend and frontend.10. Add or change infrastructure operations token generation, lookup, assignment, the pure unified-agent inventory/install model, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners, the shared infrastructure-operations state provider/context shell, and reporting/install presentation through `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, and `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`11. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.12. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.-13. Keep Pulse Mobile relay credential minting on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator, but browser callers must only consume that route and must not define the mobile runtime scope bundle or token-purpose metadata locally.+13. Keep Pulse Mobile relay credential minting and permission ownership on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, `internal/api/auth.go`, `internal/api/router_routes_ai_relay.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator and governed route gates, but browser callers must only consume that route and must not define the mobile runtime scope, compatibility gate list, or token-purpose metadata locally.## Forbidden Paths@@ -1533,6 +1533,8 @@ reads. `internal/api/security_tokens.go`,consume that same contract when deciding whether a displayed QR token can berevoked or must be preserved as an already-used device credential. That samecontract now also owns backend-minted Pulse Mobile relay access tokens: the-server route, not the browser, defines the canonical mobile runtime scope-bundle and token-purpose metadata, and the pairing UI only consumes that-server-owned credential when requesting the onboarding payload.+server route, not the browser, defines the canonical dedicated+`relay:mobile:access` runtime scope, its backward-compatible server-side route+gates alongside legacy `ai:chat` and `ai:execute` mobile tokens, and the+token-purpose metadata. The pairing UI only consumes that server-owned+credential when requesting the onboarding payload.diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 10ac629d28..ec6f5da494 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -500,6 +500,10 @@ settings surface must label those Pulse Mobile relay access credentialsdistinctly from long-lived automation tokens so operators can identify andrevoke stale mobile devices or abandoned pairing attempts without guessingwhich credential was created for mobile runtime access.+That same runtime contract now uses a dedicated backend-owned+`relay:mobile:access` scope, with the server preserving backward-compatible+gates for older mobile tokens that still carry the legacy AI scopes during the+post-RC migration window.Relay pairing refresh behavior is part of that lifecycle contract too: asuccessful QR refresh must revoke the superseded token once the new token-backedpayload is ready only if the superseded token still shows no device use, whilediff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 571239800f..740d682d85 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -150,6 +150,13 @@ That same trust boundary also governs API token scope identity: legacymigration boundaries, where they must be rewritten immediately into canonical`agent:*` scopes. Live token records and runtime scope checks may not keep thelegacy scope names as an active second contract.+That same token-scope boundary now also governs Pulse Mobile relay runtime+credentials: `internal/api/security_tokens.go` must mint only the dedicated+backend-owned `relay:mobile:access` scope for new mobile relay tokens, and the+shared auth/router helpers may expose backward-compatible gates for older+mobile tokens only on the governed mobile runtime routes. Browser callers and+route-local handlers must not recreate wildcard or broad AI-scoped mobile+credentials.That same trust rule also applies to AI-owned persisted state under`internal/config/persistence.go`: findings, usage history, patrol run history,and chat sessions may use plaintext files only as migration input. Once thosediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex f98ca2091d..d40792aa8d 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -72,6 +72,7 @@ querying, and the operator-facing storage health presentation layer.15. Preserve the governed root-or-sudo Unix wrapper in shared backend install-command helpers so storage- and recovery-adjacent transport surfaces do not inherit a stale raw `| bash -s --` install payload shape from the canonical agent-install-command API and hosted Proxmox install responses.16. Preserve optional-auth tokenless behavior in those same shared backend install-command helpers so adjacent transport surfaces do not implicitly persist API tokens and flip auth-configured state when an operator only requested a Proxmox install command on a token-optional Pulse instance.17. Preserve backend-owned Pulse Mobile relay runtime credential minting in those same shared `internal/api/` auth/security helpers so storage- and recovery-adjacent transport surfaces do not inherit browser-authored wildcard token bundles when they depend on the canonical security helper layer.+18. Preserve the dedicated backend-owned `relay:mobile:access` capability and its governed backward-compatible route gates in those same shared helpers so storage- and recovery-adjacent transport surfaces do not treat the mobile relay credential as a general AI scope bundle.## Forbidden Pathsdiff --git a/frontend-modern/src/api/__tests__/security.test.ts b/frontend-modern/src/api/__tests__/security.test.tsindex 4b26509480..7058796e56 100644--- a/frontend-modern/src/api/__tests__/security.test.ts+++ b/frontend-modern/src/api/__tests__/security.test.ts@@ -164,7 +164,7 @@ describe('SecurityAPI', () => {prefix: 'pmp_',suffix: 'bile',createdAt: '',- scopes: ['ai:chat', 'ai:execute'],+ scopes: ['relay:mobile:access'],ownerUserId: '[email protected]',},};diff --git a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsxindex d048ef97f9..b6e979a47e 100644--- a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx@@ -110,7 +110,7 @@ describe('RelaySettingsPanel runtime', () => {prefix: 'pmp_',suffix: '1234',createdAt: '',- scopes: ['ai:chat', 'ai:execute'],+ scopes: ['relay:mobile:access'],},});deleteTokenMock.mockResolvedValue(undefined);@@ -120,7 +120,7 @@ describe('RelaySettingsPanel runtime', () => {prefix: 'pmp_',suffix: '1234',createdAt: '',- scopes: ['ai:chat', 'ai:execute'],+ scopes: ['relay:mobile:access'],});getQRPayloadMock.mockResolvedValue({schema: 'pulse-onboarding/v1',diff --git a/internal/api/ai_findings_endpoint_test.go b/internal/api/ai_findings_endpoint_test.goindex 9c7cf0eb2a..153dc37064 100644--- a/internal/api/ai_findings_endpoint_test.go+++ b/internal/api/ai_findings_endpoint_test.go@@ -422,8 +422,10 @@ func TestFindingsRouterDispatch_UnknownSubpath(t *testing.T) {}}-func TestFindingsRouterDispatch_RequiresAIExecuteScope(t *testing.T) {- // Token with only ai:chat scope — should be denied ai:execute endpoints+func TestFindingsRouterDispatch_RequiresRelayMobileOrAIExecuteScopeForReadEndpoints(t *testing.T) {+ // Token with only ai:chat scope — should be denied investigation reads+ // because they now accept either the dedicated mobile relay capability or+ // the legacy ai:execute scope.rawToken := "ai-findings-scope-test.12345678"record := newTokenRecord(t, rawToken, []string{config.ScopeAIChat}, nil)cfg := newTestConfigWithTokens(t, record)@@ -435,8 +437,6 @@ func TestFindingsRouterDispatch_RequiresAIExecuteScope(t *testing.T) {}{{http.MethodGet, "/api/ai/findings/f-1/investigation"},{http.MethodGet, "/api/ai/findings/f-1/investigation/messages"},- {http.MethodPost, "/api/ai/findings/f-1/reinvestigate"},- {http.MethodPost, "/api/ai/findings/f-1/reapprove"},}for _, tc := range paths {@@ -456,6 +456,37 @@ func TestFindingsRouterDispatch_RequiresAIExecuteScope(t *testing.T) {if rec.Code != http.StatusForbidden {t.Errorf("%s %s: expected 403 for wrong scope, got %d", tc.method, tc.path, rec.Code)}+ if !strings.Contains(rec.Body.String(), config.ScopeRelayMobileAccess) {+ t.Errorf("%s %s: expected missing scope response to mention %q, got %q", tc.method, tc.path, config.ScopeRelayMobileAccess, rec.Body.String())+ }+ if !strings.Contains(rec.Body.String(), config.ScopeAIExecute) {+ t.Errorf("%s %s: expected missing scope response to mention %q, got %q", tc.method, tc.path, config.ScopeAIExecute, rec.Body.String())+ }+ }+}++func TestFindingsRouterDispatch_MutationsStillRequireAIExecuteScope(t *testing.T) {+ rawToken := "ai-findings-mutation-scope-test.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeRelayMobileAccess}, nil)+ cfg := newTestConfigWithTokens(t, record)+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")++ paths := []string{+ "/api/ai/findings/f-1/reinvestigate",+ "/api/ai/findings/f-1/reapprove",+ }++ for _, path := range paths {+ req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{}`))+ req.Header.Set("X-API-Token", rawToken)+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusForbidden {+ t.Errorf("POST %s: expected 403 for missing ai:execute scope, got %d", path, rec.Code)+ }+ if !strings.Contains(rec.Body.String(), config.ScopeAIExecute) {+ t.Errorf("POST %s: expected missing scope response to mention %q, got %q", path, config.ScopeAIExecute, rec.Body.String())+ }}}diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex 3faa5a73f6..ae4036fdb2 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -6304,8 +6304,10 @@ func (h *AISettingsHandler) HandleApproveCommand(w http.ResponseWriter, r *http.return}- // SECURITY: Validating command execution scope- if !ensureScope(w, r, config.ScopeAIExecute) {+ // SECURITY: Approval execution accepts the dedicated mobile relay capability+ // for new pairings while remaining backward-compatible with older mobile+ // tokens that still carry ai:execute.+ if !ensureAnyScope(w, r, relayMobileExecuteCompatibleScopes...) {return}diff --git a/internal/api/auth.go b/internal/api/auth.goindex de7d94eaa1..32c82d8614 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -1017,8 +1017,15 @@ func RequirePermission(cfg *config.Config, authorizer auth.Authorizer, action, r// RequireScope ensures that token-authenticated requests include the specified scope.// Session-based (browser) requests bypass the scope check.func RequireScope(scope string, handler http.HandlerFunc) http.HandlerFunc {+ return RequireAnyScope([]string{scope}, handler)+}++// RequireAnyScope ensures that token-authenticated requests include at least+// one of the specified scopes. Session-based (browser) requests bypass the+// scope check.+func RequireAnyScope(scopes []string, handler http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {- if !ensureScope(w, r, scope) {+ if !ensureAnyScope(w, r, scopes...) {return}handler(w, r)@@ -1041,14 +1048,46 @@ func respondMissingScope(w http.ResponseWriter, scope string) {// 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 {- if scope == "" {+ return ensureAnyScope(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 || record.HasScope(scope) {+ if record == nil {return true}- respondMissingScope(w, scope)+ 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}diff --git a/internal/api/auth_scope_test.go b/internal/api/auth_scope_test.goindex 663cdc0c97..88547ae1f0 100644--- a/internal/api/auth_scope_test.go+++ b/internal/api/auth_scope_test.go@@ -228,3 +228,46 @@ func TestEnsureScope_RejectsWithProperJSONResponse(t *testing.T) {t.Fatalf("expected required scope in body, got: %s", body)}}++func TestRequireAnyScopeAllowsMatchingAlternativeScope(t *testing.T) {+ handler := RequireAnyScope([]string{config.ScopeRelayMobileAccess, config.ScopeAIExecute}, func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusAccepted)+ })++ req := httptest.NewRequest(http.MethodGet, "/", nil)+ record := config.APITokenRecord{ID: "token-mobile", Scopes: []string{config.ScopeRelayMobileAccess}}+ attachAPITokenRecord(req, &record)++ rr := httptest.NewRecorder()+ handler(rr, req)++ if rr.Code != http.StatusAccepted {+ t.Fatalf("expected status 202 when alternative scope present, got %d", rr.Code)+ }+}++func TestEnsureAnyScopeRejectsWithScopeList(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/", nil)+ record := config.APITokenRecord{ID: "token-4", Scopes: []string{config.ScopeMonitoringRead}}+ attachAPITokenRecord(req, &record)+ rr := httptest.NewRecorder()++ result := ensureAnyScope(rr, req, config.ScopeRelayMobileAccess, config.ScopeAIExecute)+ if result {+ t.Fatal("expected ensureAnyScope to return false")+ }+ if rr.Code != http.StatusForbidden {+ t.Fatalf("expected status 403, got %d", rr.Code)+ }++ body := rr.Body.String()+ if !strings.Contains(body, "requiredScopes") {+ t.Fatalf("expected requiredScopes in body, got: %s", body)+ }+ if !strings.Contains(body, config.ScopeRelayMobileAccess) {+ t.Fatalf("expected relay mobile scope in body, got: %s", body)+ }+ if !strings.Contains(body, config.ScopeAIExecute) {+ t.Fatalf("expected ai:execute scope in body, got: %s", body)+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex 4f9525eb2c..344e140d4d 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -657,20 +657,44 @@ func (r *Router) routeAISessions(w http.ResponseWriter, req *http.Request) {if len(parts) > 1 {switch parts[1] {case "messages":+ if !ensureAnyScope(w, req, relayMobileChatCompatibleScopes...) {+ return+ }r.aiHandler.HandleMessages(w, req, sessionID)case "abort":+ if !ensureAnyScope(w, req, relayMobileChatCompatibleScopes...) {+ return+ }r.aiHandler.HandleAbort(w, req, sessionID)case "summarize":+ if !ensureScope(w, req, config.ScopeAIChat) {+ return+ }r.aiHandler.HandleSummarize(w, req, sessionID)case "diff":+ if !ensureScope(w, req, config.ScopeAIChat) {+ return+ }r.aiHandler.HandleDiff(w, req, sessionID)case "fork":+ if !ensureScope(w, req, config.ScopeAIChat) {+ return+ }r.aiHandler.HandleFork(w, req, sessionID)case "revert":+ if !ensureScope(w, req, config.ScopeAIChat) {+ return+ }r.aiHandler.HandleRevert(w, req, sessionID)case "unrevert":+ if !ensureScope(w, req, config.ScopeAIChat) {+ return+ }r.aiHandler.HandleUnrevert(w, req, sessionID)default:+ if !ensureScope(w, req, config.ScopeAIChat) {+ return+ }http.Error(w, "Not found", http.StatusNotFound)}return@@ -679,12 +703,85 @@ func (r *Router) routeAISessions(w http.ResponseWriter, req *http.Request) {// Handle session-level operationsswitch req.Method {case http.MethodDelete:+ if !ensureAnyScope(w, req, relayMobileChatCompatibleScopes...) {+ return+ }r.aiHandler.HandleDeleteSession(w, req, sessionID)+ default:+ if !ensureScope(w, req, config.ScopeAIChat) {+ return+ }+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ }+}++func (r *Router) routeAISessionsCollection(w http.ResponseWriter, req *http.Request) {+ if !ensureAnyScope(w, req, relayMobileChatCompatibleScopes...) {+ return+ }++ switch req.Method {+ case http.MethodGet:+ r.aiHandler.HandleSessions(w, req)+ case http.MethodPost:+ r.aiHandler.HandleCreateSession(w, req)default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}}+func (r *Router) routeAIPatrolFindings(w http.ResponseWriter, req *http.Request) {+ switch req.Method {+ case http.MethodGet:+ if !ensureAnyScope(w, req, relayMobileExecuteCompatibleScopes...) {+ return+ }+ r.aiSettingsHandler.HandleGetPatrolFindings(w, req)+ case http.MethodDelete:+ if !ensureScope(w, req, config.ScopeAIExecute) {+ return+ }+ // Clear all findings - doesn't require Pro license so users can clean up accumulated findings+ r.aiSettingsHandler.HandleClearAllFindings(w, req)+ default:+ if !ensureScope(w, req, config.ScopeAIExecute) {+ return+ }+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ }+}++func (r *Router) routeAIFindings(w http.ResponseWriter, req *http.Request) {+ path := req.URL.Path+ switch {+ case strings.HasSuffix(path, "/investigation/messages"):+ if !ensureAnyScope(w, req, relayMobileExecuteCompatibleScopes...) {+ return+ }+ r.aiSettingsHandler.HandleGetInvestigationMessages(w, req)+ case strings.HasSuffix(path, "/investigation"):+ if !ensureAnyScope(w, req, relayMobileExecuteCompatibleScopes...) {+ return+ }+ r.aiSettingsHandler.HandleGetInvestigation(w, req)+ case strings.HasSuffix(path, "/reinvestigate"):+ if !ensureScope(w, req, config.ScopeAIExecute) {+ return+ }+ r.aiAutoFixEndpoints.HandleReinvestigateFinding(w, req)+ case strings.HasSuffix(path, "/reapprove"):+ if !ensureScope(w, req, config.ScopeAIExecute) {+ return+ }+ r.aiAutoFixEndpoints.HandleReapproveInvestigationFix(w, req)+ default:+ if !ensureScope(w, req, config.ScopeAIExecute) {+ return+ }+ http.Error(w, "Not found", http.StatusNotFound)+ }+}+// routeApprovals routes approval-specific requestsfunc (r *Router) routeApprovals(w http.ResponseWriter, req *http.Request) {// Extract approval ID and action from path: /api/ai/approvals/{id}[/approve|/deny]diff --git a/internal/api/router_routes_ai_relay.go b/internal/api/router_routes_ai_relay.goindex cc93c40afd..c423a953c2 100644--- a/internal/api/router_routes_ai_relay.go+++ b/internal/api/router_routes_ai_relay.go@@ -25,6 +25,11 @@ const (featureAIAutoFixKey = "ai_autofix")+var (+ relayMobileChatCompatibleScopes = []string{config.ScopeRelayMobileAccess, config.ScopeAIChat}+ relayMobileExecuteCompatibleScopes = []string{config.ScopeRelayMobileAccess, config.ScopeAIExecute}+)+func (r *Router) registerAIRelayRoutesGroup() {// Resolve AI extension endpoints. In the open-source build (no enterprise binder),// the free adapters return 402 for all premium operations. Enterprise binders@@ -106,29 +111,19 @@ func (r *Router) registerAIRelayRoutesGroup() {// SECURITY: Patrol status and stream require ai:execute scope to access findingsr.mux.HandleFunc("/api/ai/patrol/status", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleGetPatrolStatus)))r.mux.HandleFunc("/api/ai/patrol/stream", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandlePatrolStream)))- r.mux.HandleFunc("/api/ai/patrol/findings", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, func(w http.ResponseWriter, req *http.Request) {- switch req.Method {- case http.MethodGet:- r.aiSettingsHandler.HandleGetPatrolFindings(w, req)- case http.MethodDelete:- // Clear all findings - doesn't require Pro license so users can clean up accumulated findings- r.aiSettingsHandler.HandleClearAllFindings(w, req)- default:- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- }- })))+ r.mux.HandleFunc("/api/ai/patrol/findings", RequireAuth(r.config, r.routeAIPatrolFindings))// SECURITY: AI Patrol read endpoints - require ai:execute scoper.mux.HandleFunc("/api/ai/patrol/history", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleGetFindingsHistory)))r.mux.HandleFunc("/api/ai/patrol/run", RequireAdmin(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleForcePatrol)))// SECURITY: AI Patrol mutation endpoints - require ai:execute scope to prevent low-privilege tokens from// dismissing, suppressing, or otherwise hiding findings. This prevents attackers from blinding AI Patrol.- r.mux.HandleFunc("/api/ai/patrol/acknowledge", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleAcknowledgeFinding)))+ r.mux.HandleFunc("/api/ai/patrol/acknowledge", RequireAuth(r.config, RequireAnyScope(relayMobileExecuteCompatibleScopes, r.aiSettingsHandler.HandleAcknowledgeFinding)))// Dismiss and resolve don't require Pro license - users should be able to clear findings they can see// This is especially important for users who accumulated findings before fixing the patrol-without-AI bug- r.mux.HandleFunc("/api/ai/patrol/dismiss", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleDismissFinding)))+ r.mux.HandleFunc("/api/ai/patrol/dismiss", RequireAuth(r.config, RequireAnyScope(relayMobileExecuteCompatibleScopes, r.aiSettingsHandler.HandleDismissFinding)))r.mux.HandleFunc("/api/ai/patrol/findings/note", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleSetFindingNote)))r.mux.HandleFunc("/api/ai/patrol/suppress", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleSuppressFinding)))- r.mux.HandleFunc("/api/ai/patrol/snooze", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleSnoozeFinding)))+ r.mux.HandleFunc("/api/ai/patrol/snooze", RequireAuth(r.config, RequireAnyScope(relayMobileExecuteCompatibleScopes, r.aiSettingsHandler.HandleSnoozeFinding)))r.mux.HandleFunc("/api/ai/patrol/resolve", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleResolveFinding)))r.mux.HandleFunc("/api/ai/patrol/runs", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleGetPatrolRunHistory)))r.mux.HandleFunc("/api/ai/patrol/runs/", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleGetPatrolRun)))@@ -160,21 +155,7 @@ func (r *Router) registerAIRelayRoutesGroup() {// Investigation endpoints - viewing is free; reinvestigation and fix execution gated via extension// SECURITY: Require ai:execute scope to prevent low-privilege tokens from reading investigation details- r.mux.HandleFunc("/api/ai/findings/", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, func(w http.ResponseWriter, req *http.Request) {- path := req.URL.Path- switch {- case strings.HasSuffix(path, "/investigation/messages"):- r.aiSettingsHandler.HandleGetInvestigationMessages(w, req)- case strings.HasSuffix(path, "/investigation"):- r.aiSettingsHandler.HandleGetInvestigation(w, req)- case strings.HasSuffix(path, "/reinvestigate"):- r.aiAutoFixEndpoints.HandleReinvestigateFinding(w, req)- case strings.HasSuffix(path, "/reapprove"):- r.aiAutoFixEndpoints.HandleReapproveInvestigationFix(w, req)- default:- http.Error(w, "Not found", http.StatusNotFound)- }- })))+ r.mux.HandleFunc("/api/ai/findings/", RequireAuth(r.config, r.routeAIFindings))// AI Intelligence endpoints - expose learned patterns, correlations, and predictions// SECURITY: Require ai:execute scope to prevent low-privilege tokens from reading sensitive intelligence@@ -221,23 +202,14 @@ func (r *Router) registerAIRelayRoutesGroup() {// AI chat endpoints// SECURITY: Status endpoint is part of chat UX and should require ai:chat scope for token clients.r.mux.HandleFunc("/api/ai/status", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.aiHandler.HandleStatus)))- r.mux.HandleFunc("/api/ai/chat", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.aiHandler.HandleChat)))- r.mux.HandleFunc("/api/ai/sessions", RequireAuth(r.config, RequireScope(config.ScopeAIChat, func(w http.ResponseWriter, req *http.Request) {- switch req.Method {- case http.MethodGet:- r.aiHandler.HandleSessions(w, req)- case http.MethodPost:- r.aiHandler.HandleCreateSession(w, req)- default:- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)- }- })))- r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.routeAISessions)))+ r.mux.HandleFunc("/api/ai/chat", RequireAuth(r.config, RequireAnyScope(relayMobileChatCompatibleScopes, r.aiHandler.HandleChat)))+ r.mux.HandleFunc("/api/ai/sessions", RequireAuth(r.config, r.routeAISessionsCollection))+ r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, r.routeAISessions))// AI approval endpoints - for command approval workflow// Require ai:execute scope to prevent low-privilege tokens from enumerating or denying approvals- r.mux.HandleFunc("/api/ai/approvals", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiAutoFixEndpoints.HandleListApprovals)))- r.mux.HandleFunc("/api/ai/approvals/", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.routeApprovals)))+ r.mux.HandleFunc("/api/ai/approvals", RequireAuth(r.config, RequireAnyScope(relayMobileExecuteCompatibleScopes, r.aiAutoFixEndpoints.HandleListApprovals)))+ r.mux.HandleFunc("/api/ai/approvals/", RequireAuth(r.config, RequireAnyScope(relayMobileExecuteCompatibleScopes, r.routeApprovals)))// AI question endpoints - require ai:chat scope for interactive AI featuresr.mux.HandleFunc("/api/ai/question/", RequireAuth(r.config, RequireScope(config.ScopeAIChat, r.routeQuestions)))@@ -411,6 +383,12 @@ func newAIAutoFixHandlerDeps(r *Router) extensions.AIAutoFixHandlerDeps {return getAuthUsername(h.getConfig(req.Context()), req)},EnsureScope: func(w http.ResponseWriter, req *http.Request, scope string) bool {+ if scope == config.ScopeAIExecute && strings.HasPrefix(req.URL.Path, "/api/ai/approvals/") {+ // Approval execution accepts the dedicated mobile relay capability+ // for new pairings while remaining backward-compatible with legacy+ // ai:execute-scoped mobile tokens.+ return ensureAnyScope(w, req, relayMobileExecuteCompatibleScopes...)+ }return ensureScope(w, req, scope)},AuditLog: LogAuditEvent,diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex 449fd11931..fc3b14cce9 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -1291,6 +1291,81 @@ func TestAIExecuteReadEndpointsRequireAIExecuteScope(t *testing.T) {}}+func TestRelayMobileAccessScopeAllowsGovernedMobileRuntimeEndpoints(t *testing.T) {+ rawToken := "relay-mobile-runtime-token-123.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeRelayMobileAccess}, nil)+ cfg := newTestConfigWithTokens(t, record)+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")++ paths := []struct {+ method string+ path string+ body string+ }{+ {method: http.MethodGet, path: "/api/ai/patrol/findings", body: ""},+ {method: http.MethodGet, path: "/api/ai/findings/finding-1/investigation", body: ""},+ {method: http.MethodGet, path: "/api/ai/findings/finding-1/investigation/messages", body: ""},+ {method: http.MethodPost, path: "/api/ai/patrol/acknowledge", body: `{}`},+ {method: http.MethodPost, path: "/api/ai/patrol/dismiss", body: `{}`},+ {method: http.MethodPost, path: "/api/ai/patrol/snooze", body: `{}`},+ {method: http.MethodGet, path: "/api/ai/approvals", body: ""},+ {method: http.MethodPost, path: "/api/ai/approvals/approval-1/approve", body: `{}`},+ {method: http.MethodPost, path: "/api/ai/approvals/approval-1/deny", body: `{}`},+ {method: http.MethodPost, path: "/api/ai/chat", body: `{}`},+ {method: http.MethodGet, path: "/api/ai/sessions", body: ""},+ {method: http.MethodGet, path: "/api/ai/sessions/session-1/messages", body: ""},+ {method: http.MethodPost, path: "/api/ai/sessions/session-1/abort", body: `{}`},+ {method: http.MethodDelete, path: "/api/ai/sessions/session-1", body: ""},+ }++ for _, tc := range paths {+ req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))+ req.Header.Set("X-API-Token", rawToken)+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code == http.StatusForbidden && strings.Contains(rec.Body.String(), "missing_scope") {+ t.Fatalf("expected relay mobile scope to pass scope gating on %s %s, got %d with body %q", tc.method, tc.path, rec.Code, rec.Body.String())+ }+ }+}++func TestRelayMobileAccessScopeDeniesAdjacentAIRoutes(t *testing.T) {+ rawToken := "relay-mobile-adjacent-token-123.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeRelayMobileAccess}, nil)+ cfg := newTestConfigWithTokens(t, record)+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")++ paths := []struct {+ method string+ path string+ body string+ want string+ }{+ {method: http.MethodGet, path: "/api/ai/models", body: "", want: config.ScopeAIChat},+ {method: http.MethodGet, path: "/api/ai/status", body: "", want: config.ScopeAIChat},+ {method: http.MethodGet, path: "/api/ai/agents", body: "", want: config.ScopeAIExecute},+ {method: http.MethodDelete, path: "/api/ai/patrol/findings", body: "", want: config.ScopeAIExecute},+ {method: http.MethodPost, path: "/api/ai/findings/finding-1/reinvestigate", body: `{}`, want: config.ScopeAIExecute},+ {method: http.MethodPost, path: "/api/ai/findings/finding-1/reapprove", body: `{}`, want: config.ScopeAIExecute},+ {method: http.MethodPost, path: "/api/ai/sessions/session-1/summarize", body: `{}`, want: config.ScopeAIChat},+ {method: http.MethodGet, path: "/api/ai/sessions/session-1/diff", body: "", want: config.ScopeAIChat},+ {method: http.MethodPost, path: "/api/ai/sessions/session-1/fork", body: `{}`, want: config.ScopeAIChat},+ }++ for _, tc := range paths {+ req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))+ req.Header.Set("X-API-Token", rawToken)+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusForbidden {+ t.Fatalf("expected 403 for relay mobile token on %s %s, got %d", tc.method, tc.path, rec.Code)+ }+ if !strings.Contains(rec.Body.String(), tc.want) {+ t.Fatalf("expected missing scope response to mention %q for %s %s, got %q", tc.want, tc.method, tc.path, rec.Body.String())+ }+ }+}+func TestAIExecuteMutationEndpointsRequireAIExecuteScope(t *testing.T) {rawToken := "ai-exec-mutate-token-123.12345678"record := newTokenRecord(t, rawToken, []string{config.ScopeAIChat}, nil)diff --git a/internal/api/security_tokens.go b/internal/api/security_tokens.goindex 77061024ec..2a930e11de 100644--- a/internal/api/security_tokens.go+++ b/internal/api/security_tokens.go@@ -133,8 +133,7 @@ func canonicalizeRequestedScope(scope string) string {func relayMobileAccessTokenScopes() []string {return []string{- config.ScopeAIChat,- config.ScopeAIExecute,+ config.ScopeRelayMobileAccess,}}diff --git a/internal/api/security_tokens_handlers_test.go b/internal/api/security_tokens_handlers_test.goindex c0e07d48b0..58a392404c 100644--- a/internal/api/security_tokens_handlers_test.go+++ b/internal/api/security_tokens_handlers_test.go@@ -269,7 +269,7 @@ func TestSecurityTokens_CreateRelayMobileAccessToken(t *testing.T) {if !strings.HasPrefix(createResp.Record.Name, "Pulse Mobile relay access ") {t.Fatalf("unexpected relay mobile token name %q", createResp.Record.Name)}- wantScopes := []string{config.ScopeAIChat, config.ScopeAIExecute}+ wantScopes := []string{config.ScopeRelayMobileAccess}if len(createResp.Record.Scopes) != len(wantScopes) {t.Fatalf("relay mobile scopes length = %d, want %d", len(createResp.Record.Scopes), len(wantScopes))}diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.goindex 527f045256..d0e6f34194 100644--- a/internal/config/api_tokens.go+++ b/internal/config/api_tokens.go@@ -12,22 +12,23 @@ import (// Canonical API token scope strings.const (- ScopeWildcard = "*"- ScopeMonitoringRead = "monitoring:read"- ScopeMonitoringWrite = "monitoring:write"- ScopeDockerReport = "docker:report"- ScopeDockerManage = "docker:manage"- ScopeKubernetesReport = "kubernetes:report"- ScopeKubernetesManage = "kubernetes:manage"- ScopeAgentReport = "agent:report"- ScopeAgentConfigRead = "agent:config:read"- ScopeAgentManage = "agent:manage"- ScopeSettingsRead = "settings:read"- ScopeSettingsWrite = "settings:write"- ScopeAIExecute = "ai:execute" // Allows executing AI commands and remediation plans- ScopeAIChat = "ai:chat" // Allows AI chat participation- ScopeAgentExec = "agent:exec" // Allows agent execution WebSocket connections- ScopeAgentEnroll = "agent:enroll" // Bootstrap enrollment only+ ScopeWildcard = "*"+ ScopeMonitoringRead = "monitoring:read"+ ScopeMonitoringWrite = "monitoring:write"+ ScopeDockerReport = "docker:report"+ ScopeDockerManage = "docker:manage"+ ScopeKubernetesReport = "kubernetes:report"+ ScopeKubernetesManage = "kubernetes:manage"+ ScopeAgentReport = "agent:report"+ ScopeAgentConfigRead = "agent:config:read"+ ScopeAgentManage = "agent:manage"+ ScopeSettingsRead = "settings:read"+ ScopeSettingsWrite = "settings:write"+ ScopeAIExecute = "ai:execute" // Allows executing AI commands and remediation plans+ ScopeAIChat = "ai:chat" // Allows AI chat participation+ ScopeRelayMobileAccess = "relay:mobile:access" // Allows the governed Pulse Mobile relay runtime surface+ ScopeAgentExec = "agent:exec" // Allows agent execution WebSocket connections+ ScopeAgentEnroll = "agent:enroll" // Bootstrap enrollment only)// AllKnownScopes enumerates scopes recognized by the backend (excluding the wildcard sentinel).@@ -45,6 +46,7 @@ var AllKnownScopes = []string{ScopeSettingsWrite,ScopeAIExecute,ScopeAIChat,+ ScopeRelayMobileAccess,ScopeAgentExec,ScopeAgentEnroll,}diff --git a/internal/config/api_tokens_coverage_test.go b/internal/config/api_tokens_coverage_test.goindex db005144a8..48c11fb829 100644--- a/internal/config/api_tokens_coverage_test.go+++ b/internal/config/api_tokens_coverage_test.go@@ -114,6 +114,9 @@ func TestAPITokenScopesHelpers(t *testing.T) {if !IsKnownScope(ScopeMonitoringWrite) {t.Fatalf("known scope should be recognized")}+ if !IsKnownScope(ScopeRelayMobileAccess) {+ t.Fatalf("relay mobile scope should be recognized")+ }if IsKnownScope("host-agent:config:read") {t.Fatalf("legacy host-agent:config:read alias should not be recognized as a canonical runtime scope")}