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
Keep instance administration away from organization owners
rcourtmandc2057a08c9a
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex f0fbfeb726..9bb70513fb 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -5033,16 +5033,23 @@ auto-register mutation boundary.`TestActionRoutesRequireExplicitSSOAdminOnSSOOnlyInstance`.Org-bound settings are the one place an org-scoped session is not- withheld. `ensureAdminSession` admits the configured administrator or a- manager (owner or admin) of the request's organization inside an- org-scoped request, and that rule is `sessionUserHasSettingsAdminPrivileges`- for both the route gate and the snapshot. The snapshot records it as- `sessionManagesOrg`, never as `sessionIsAdmin`, and it widens only- `infrastructureRead`, `availabilityRead` and `reportingRead`, whose routes- pass `ensureAdminSession` and whose handlers read that organization's own- config and monitor state; `reportingRead` still requires the authorizer's- `read` on `nodes`. Every other capability, `detailLevel` and `authUsername`- stay instance administration. Before this, a provider opening a client+ withheld. `ensureAdminSession`, the session check behind `RequireAdmin` and+ the settings scope helpers, admits only instance administrators (the+ configured administrator or an instance RBAC admin grant) whatever+ organization the request names. Routes whose handlers act only on the+ request organization's own config and monitor state opt into+ `RequireOrgAdmin` / `ensureOrgAdminSession` / `ensureOrgSettingsWriteScope`,+ which also admit a manager (owner or admin) of that organization through+ `sessionUserHasSettingsAdminPrivileges`: agents, nodes, connections,+ availability, TrueNAS and VMware, agent profiles, install commands, deploy+ status, configuration transfer and the org-bound relay mobile token. The+ default is instance administration, so a route that does not opt in fails+ closed. The snapshot records the org rule as `sessionManagesOrg`, never as+ `sessionIsAdmin`, and it widens only `infrastructureRead` and+ `availabilityRead`. Reporting stays instance administration because report+ generation reads the instance's default metrics store. Every other+ capability, `detailLevel` and `authUsername` stay instance administration.+ `internal/api/org_admin_session_authority_test.go` holds the session matrix. Before this, a provider opening a clientworkspace from the Pulse Account portal arrived as the org owner with everycapability `false`, so Settings hid the Infrastructure and Reporting pagesthat the routes would have served and the handoff to@@ -11653,8 +11660,9 @@ routes on mount:and `/api/logs/download`;- `pulseIntelligenceRead` combines the handler's settings-admin/scope checkwith `RequirePermission(read, settings)` from `/api/settings/ai`;-- `reportingRead` combines `ensureAdminSession`, `settings:read`, and- `RequirePermission(read, nodes)` from `/api/admin/reports/catalog`.+- `reportingRead` combines `ensureAdminSession` (instance administrators+ only), `settings:read`, and `RequirePermission(read, nodes)` from+ `/api/admin/reports/catalog`.Those last two must not collapse to `canReadSettings`: a custom authorizer candeny the route even when the caller has the settings scope. Reporting'sdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 453af34825..7875bfec40 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -3244,6 +3244,12 @@ withheld from every org-scoped session, so an org manager is not offeredinstance recovery or configuration transfer. See the api-contracts contract,rule 35.+Superseded in part: `reportingRead` is no longer granted to org managers.+Report generation reads the instance's default metrics store, so reporting+routes stay instance administration until reporting is scoped to the+organization's own metrics. Org managers keep `infrastructureRead` and+`availabilityRead`.+### TLS verification preference survives node re-registrationA PVE or PBS node whose operator disabled certificate verification keeps thatdiff --git a/internal/api/auth.go b/internal/api/auth.goindex 3868c31d8e..1522b3db97 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -1045,10 +1045,24 @@ func RequireAuth(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc}}-// RequireAdmin middleware checks for authentication and admin privileges.-// Proxy-auth users must have the configured admin role. Session/OIDC users-// must match the configured admin identity.+// RequireAdmin middleware checks for authentication and instance admin+// privileges. Proxy-auth users must have the configured admin role. Session and+// OIDC users must be instance administrators (ensureAdminSession); an+// organization's owner or admin is refused.func RequireAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc {+ return requireAdminSession(cfg, ensureAdminSession, handler)+}++// RequireOrgAdmin is RequireAdmin for routes whose handlers act only on the+// request organization's own config and monitor state. Session users who can+// manage that organization are admitted as well (ensureOrgAdminSession). Use it+// only after checking that the handler cannot reach instance-wide state or+// another organization's data.+func RequireOrgAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc {+ return requireAdminSession(cfg, ensureOrgAdminSession, handler)+}++func requireAdminSession(cfg *config.Config, sessionCheck func(*config.Config, http.ResponseWriter, *http.Request) bool, handler http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {// Dev mode bypass for admin endpoints (disabled by default)if adminBypassAppliesToRequest(r) {@@ -1092,8 +1106,8 @@ func RequireAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc}}- // Enforce configured admin identity for session-based auth.- if !ensureAdminSession(cfg, w, r) {+ // Enforce the route's admin identity rule for session-based auth.+ if !sessionCheck(cfg, w, r) {return}diff --git a/internal/api/config_transfer_authorization.go b/internal/api/config_transfer_authorization.goindex c2d17d38ad..de6b295f76 100644--- a/internal/api/config_transfer_authorization.go+++ b/internal/api/config_transfer_authorization.go@@ -112,7 +112,7 @@ func (r *Router) authorizeConfigTransfer(w http.ResponseWriter, req *http.RequesvalidSession = requestMatchesRecoverySession(req, session)}if validSession {- if !ensureAdminSession(r.config, w, req) {+ if !ensureOrgAdminSession(r.config, w, req) {return false}return truediff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 42555cab0c..df121982a5 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -349,7 +349,7 @@ func TestContract_ConfigTransferRoutesUseCanonicalPreHandlerAuthorization(t *tes"isDirectLoopbackRequest(req)","op == configTransferExport","getAPITokenRecordFromRequest(req)",- "ensureAdminSession(r.config, w, req)",+ "ensureOrgAdminSession(r.config, w, req)","config.ScopeSettingsRead","config.ScopeSettingsWrite",} {@@ -26478,12 +26478,12 @@ func orgScopedSessionRequest(t *testing.T, user string, org *models.Organization}// A provider opening a client workspace lands in that client's organization as-// its owner. ensureAdminSession has always let an org manager through the-// org-bound settings routes, but the security status snapshot reported every-// settings capability as false for any org-scoped session, so the settings-// navigation hid Infrastructure and Reporting and the owner had no way to-// connect a single system. Those org-bound capabilities must follow the route-// rule, while instance administration stays closed to org-scoped sessions.+// its owner. ensureOrgAdminSession lets an org manager through the org-bound+// settings routes, but the security status snapshot reported every settings+// capability as false for any org-scoped session, so the settings navigation+// hid Infrastructure and the owner had no way to connect a single system.+// Those org-bound capabilities must follow the route rule, while instance+// administration, reporting included, stays closed to org-scoped sessions.func TestSecurityStatusOrgBoundSettingsFollowOrgManagementRule(t *testing.T) {prev := authpkg.GetAuthorizer()authpkg.SetAuthorizer(&authpkg.DefaultAuthorizer{})@@ -26514,8 +26514,8 @@ func TestSecurityStatusOrgBoundSettingsFollowOrgManagementRule(t *testing.T) {{name: "outsider", user: "u_outsider", manager: false},} {t.Run(tc.name, func(t *testing.T) {- if got := ensureAdminSession(router.config, httptest.NewRecorder(), orgScopedSessionRequest(t, tc.user, org)); got != tc.manager {- t.Fatalf("precondition: ensureAdminSession = %v, want %v", got, tc.manager)+ if got := ensureOrgAdminSession(router.config, httptest.NewRecorder(), orgScopedSessionRequest(t, tc.user, org)); got != tc.manager {+ t.Fatalf("precondition: ensureOrgAdminSession = %v, want %v", got, tc.manager)}caps := router.securityStatusSettingsCapabilitiesFromSnapshot(@@ -26524,7 +26524,6 @@ func TestSecurityStatusOrgBoundSettingsFollowOrgManagementRule(t *testing.T) {orgBound := map[string]bool{"infrastructureRead": caps.InfrastructureRead,"availabilityRead": caps.AvailabilityRead,- "reportingRead": caps.ReportingRead,}for name, got := range orgBound {if got != tc.manager {@@ -26533,6 +26532,7 @@ func TestSecurityStatusOrgBoundSettingsFollowOrgManagementRule(t *testing.T) {}instanceWide := map[string]bool{+ "reportingRead": caps.ReportingRead,"systemSettingsRead": caps.SystemSettingsRead,"diagnosticsRead": caps.DiagnosticsRead,"systemLogsRead": caps.SystemLogsRead,@@ -26556,7 +26556,7 @@ func TestSecurityStatusOrgBoundSettingsFollowOrgManagementRule(t *testing.T) {// With a real RBAC authorizer, reporting also needs read:nodes. An org owner// the authorizer refuses must not be offered the reporting surface, because-// RequirePermission refuses the route before ensureAdminSession runs.+// RequirePermission refuses the route before any session check runs.func TestSecurityStatusOrgBoundReportingRespectsAuthorizer(t *testing.T) {cfg := platformAdminConfig(t, "admin")router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")@@ -26570,7 +26570,7 @@ func TestSecurityStatusOrgBoundReportingRespectsAuthorizer(t *testing.T) {t.Fatal("reportingRead advertised although the authorizer refuses read:nodes")}if !caps.InfrastructureRead {- t.Fatal("infrastructureRead must still follow ensureAdminSession for the org owner")+ t.Fatal("infrastructureRead must still follow ensureOrgAdminSession for the org owner")}}diff --git a/internal/api/org_admin_session_authority_test.go b/internal/api/org_admin_session_authority_test.gonew file mode 100644index 0000000000..980bf28352--- /dev/null+++ b/internal/api/org_admin_session_authority_test.go@@ -0,0 +1,145 @@+package api++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "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"+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"+)++// ensureAdminSession guards instance-wide state: credentials, API tokens, SSO,+// system settings, updates and the rest of instance administration. An+// organization's owner or admin manages that organization, not the instance,+// so only routes that opt in with ensureOrgAdminSession / RequireOrgAdmin admit+// them. Before this split every admin route admitted an org manager who named+// their organization in the request, which let them rotate the instance+// administrator's API token and receive its secret.++const (+ orgAuthorityAdmin = "instance-admin"+ orgAuthorityOwner = "tenant-owner"+ orgAuthorityAdmin2 = "tenant-admin"+ orgAuthorityMember = "tenant-member"+ orgAuthorityRBAC = "sso:oidc:corp:rbac-admin"+)++func orgAuthorityConfig(t *testing.T) *config.Config {+ t.Helper()+ InitSessionStore(t.TempDir())+ manager := installTestRBACManager(t)+ if err := manager.UpdateUserRoles(orgAuthorityRBAC, []string{internalauth.RoleAdmin}); err != nil {+ t.Fatalf("assign admin role: %v", err)+ }+ return &config.Config{AuthUser: orgAuthorityAdmin}+}++func orgAuthorityRequest(t *testing.T, method, target, username, orgID string) *http.Request {+ t.Helper()+ token := generateSessionToken()+ GetSessionStore().CreateSession(token, time.Hour, "agent", "127.0.0.1", username)+ req := newLoopbackRequest(method, target, nil)+ req.AddCookie(&http.Cookie{Name: "pulse_session", Value: token})+ if orgID != "" {+ org := &models.Organization{+ ID: orgID,+ DisplayName: orgID,+ OwnerUserID: orgAuthorityOwner,+ Members: []models.OrganizationMember{+ {UserID: orgAuthorityAdmin2, Role: models.OrgRoleAdmin},+ {UserID: orgAuthorityMember, Role: models.OrgRoleViewer},+ },+ }+ req = req.WithContext(context.WithValue(req.Context(), apicontext.OrgContextKey, org))+ }+ return req+}++type orgAuthorityCase struct {+ name string+ user string+ org string+ instance bool // admitted by ensureAdminSession / RequireAdmin+ orgBound bool // admitted by ensureOrgAdminSession / RequireOrgAdmin+}++var orgAuthorityCases = []orgAuthorityCase{+ {"configured admin, instance context", orgAuthorityAdmin, "", true, true},+ {"RBAC admin, instance context", orgAuthorityRBAC, "", true, true},+ {"configured admin inside a tenant org", orgAuthorityAdmin, "org-a", true, true},+ {"RBAC admin inside a tenant org", orgAuthorityRBAC, "org-a", true, true},+ {"org owner inside their org", orgAuthorityOwner, "org-a", false, true},+ {"org admin inside their org", orgAuthorityAdmin2, "org-a", false, true},+ {"org member inside their org", orgAuthorityMember, "org-a", false, false},+ {"org owner without an org", orgAuthorityOwner, "", false, false},+ {"unknown user without an org", "mallory", "", false, false},+}++func TestAdminSessionChecksSplitInstanceAndOrgAuthority(t *testing.T) {+ cfg := orgAuthorityConfig(t)+ for _, tc := range orgAuthorityCases {+ t.Run(tc.name, func(t *testing.T) {+ rec := httptest.NewRecorder()+ if got := ensureAdminSession(cfg, rec, orgAuthorityRequest(t, http.MethodGet, "/api/x", tc.user, tc.org)); got != tc.instance {+ t.Fatalf("ensureAdminSession = %v, want %v", got, tc.instance)+ }+ if !tc.instance && rec.Code != http.StatusForbidden {+ t.Fatalf("refused instance check answered %d, want 403", rec.Code)+ }+ rec = httptest.NewRecorder()+ if got := ensureOrgAdminSession(cfg, rec, orgAuthorityRequest(t, http.MethodGet, "/api/x", tc.user, tc.org)); got != tc.orgBound {+ t.Fatalf("ensureOrgAdminSession = %v, want %v", got, tc.orgBound)+ }+ })+ }+}++func TestRequireAdminAndRequireOrgAdminFollowTheSessionSplit(t *testing.T) {+ cfg := orgAuthorityConfig(t)+ reached := func(wrap func(*config.Config, http.HandlerFunc) http.HandlerFunc, req *http.Request) (bool, int) {+ hit := false+ rec := httptest.NewRecorder()+ wrap(cfg, func(w http.ResponseWriter, r *http.Request) { hit = true })(rec, req)+ return hit, rec.Code+ }+ for _, tc := range orgAuthorityCases {+ t.Run(tc.name, func(t *testing.T) {+ if hit, code := reached(RequireAdmin, orgAuthorityRequest(t, http.MethodGet, "/api/x", tc.user, tc.org)); hit != tc.instance {+ t.Fatalf("RequireAdmin reached handler = %v (status %d), want %v", hit, code, tc.instance)+ }+ if hit, code := reached(RequireOrgAdmin, orgAuthorityRequest(t, http.MethodGet, "/api/x", tc.user, tc.org)); hit != tc.orgBound {+ t.Fatalf("RequireOrgAdmin reached handler = %v (status %d), want %v", hit, code, tc.orgBound)+ }+ })+ }+}++// Token management, SSO, system settings and the other instance surfaces+// reach their handlers through the settings scope helpers. An org owner's+// session must not pass them, whatever organization it names.+func TestSettingsScopeRefusesOrgOwnerSession(t *testing.T) {+ cfg := orgAuthorityConfig(t)+ for _, check := range []struct {+ name string+ fn func(*config.Config, http.ResponseWriter, *http.Request) bool+ }{+ {"settings read", ensureSettingsReadScope},+ {"settings write", ensureSettingsWriteScope},+ } {+ t.Run(check.name, func(t *testing.T) {+ rec := httptest.NewRecorder()+ req := orgAuthorityRequest(t, http.MethodPost, "/api/security/tokens/some-id/rotate", orgAuthorityOwner, "org-a")+ if check.fn(cfg, rec, req) {+ t.Fatal("an org owner's session passed the instance settings scope check")+ }+ if rec.Code != http.StatusForbidden {+ t.Fatalf("status = %d, want 403", rec.Code)+ }+ })+ }+}diff --git a/internal/api/platform_connection_shared.go b/internal/api/platform_connection_shared.goindex 0caeb3c3ad..bf94d38fae 100644--- a/internal/api/platform_connection_shared.go+++ b/internal/api/platform_connection_shared.go@@ -103,7 +103,8 @@ type platformConnectionItemHandlers struct {// platformConnectionItemRoute builds the shared mux handler for platform// connection item routes: POST .../test, POST .../preview, DELETE, PUT — all-// admin + settings:write gated. handlers is resolved per request so late+// org admin + settings:write gated; the handlers act on the request+// organization's own connections. handlers is resolved per request so late// handler wiring and nil-service checks keep working.func (r *Router) platformConnectionItemRoute(unavailableCode, unavailableMsg string, handlers func() *platformConnectionItemHandlers) http.HandlerFunc {return func(w http.ResponseWriter, req *http.Request) {@@ -114,13 +115,13 @@ func (r *Router) platformConnectionItemRoute(unavailableCode, unavailableMsg str}if req.Method == http.MethodPost && strings.HasSuffix(strings.Trim(req.URL.Path, "/"), "/test") {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, h.test))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, h.test))(w, req)} else if req.Method == http.MethodPost && strings.HasSuffix(strings.Trim(req.URL.Path, "/"), "/preview") {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, h.preview))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, h.preview))(w, req)} else if req.Method == http.MethodDelete {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, h.delete))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, h.delete))(w, req)} else if req.Method == http.MethodPut {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, h.update))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, h.update))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}diff --git a/internal/api/router_routes_auth_security.go b/internal/api/router_routes_auth_security.goindex fa2842a5a0..181a4c22c7 100644--- a/internal/api/router_routes_auth_security.go+++ b/internal/api/router_routes_auth_security.go@@ -247,7 +247,9 @@ func (r *Router) registerAuthSecurityInstallRoutes() {}))r.mux.HandleFunc("/api/security/tokens/relay-mobile", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceUsers, func(w http.ResponseWriter, req *http.Request) {- if !ensureSettingsWriteScope(r.config, w, req) {+ // The token minted here is bound to the request organization and carries+ // only the relay mobile scope, so an org manager may issue it.+ if !ensureOrgSettingsWriteScope(r.config, w, req) {return}if req.Method != http.MethodPost {diff --git a/internal/api/router_routes_registration.go b/internal/api/router_routes_registration.goindex e4e8d296ca..b6916c7064 100644--- a/internal/api/router_routes_registration.go+++ b/internal/api/router_routes_registration.go@@ -64,14 +64,14 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {// Uninstall is a collector's self-removal by token. Anything that is not a// token takes the administrative removal path inside the handler, so it must// be an administrator, as for the unlink and delete routes below.- r.mux.HandleFunc("/api/agents/agent/uninstall", RequireAdmin(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleUninstall)))- r.mux.HandleFunc("/api/agents/host/uninstall", wrapLegacyHostAlias("/api/agents/host/uninstall", RequireAdmin(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleUninstall))))+ r.mux.HandleFunc("/api/agents/agent/uninstall", RequireOrgAdmin(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleUninstall)))+ r.mux.HandleFunc("/api/agents/host/uninstall", wrapLegacyHostAlias("/api/agents/host/uninstall", RequireOrgAdmin(r.config, RequireScope(config.ScopeAgentReport, r.unifiedAgentHandlers.HandleUninstall))))// SECURITY: Use settings:write (not just host_manage) to prevent compromised host tokens from manipulating other hosts- r.mux.HandleFunc("/api/agents/agent/unlink", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleUnlink)))- r.mux.HandleFunc("/api/agents/host/unlink", wrapLegacyHostAlias("/api/agents/host/unlink", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleUnlink))))- r.mux.HandleFunc("/api/agents/agent/link", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleLink)))- r.mux.HandleFunc("/api/agents/host/link", wrapLegacyHostAlias("/api/agents/host/link", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleLink))))- r.mux.HandleFunc("/api/agents/diagnostics", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.handleAgentFleetDiagnostics)))+ r.mux.HandleFunc("/api/agents/agent/unlink", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleUnlink)))+ r.mux.HandleFunc("/api/agents/host/unlink", wrapLegacyHostAlias("/api/agents/host/unlink", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleUnlink))))+ r.mux.HandleFunc("/api/agents/agent/link", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleLink)))+ r.mux.HandleFunc("/api/agents/host/link", wrapLegacyHostAlias("/api/agents/host/link", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.unifiedAgentHandlers.HandleLink))))+ r.mux.HandleFunc("/api/agents/diagnostics", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.handleAgentFleetDiagnostics)))// Unified Agent management routes - config endpoint is accessible by agents (GET) and admins (PATCH)unifiedAgentManagementCore := func(w http.ResponseWriter, req *http.Request) {// Route /api/agents/agent/{id}/config to HandleConfig@@ -79,7 +79,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {// GET is for agents to fetch config (agent config scope)// PATCH is for UI to update config (agent_manage scope, admin only)if req.Method == http.MethodPatch {- RequireAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {+ RequireOrgAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {if !ensureScope(w, req, config.ScopeAgentManage) {return}@@ -93,7 +93,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {// Route POST /api/agents/agent/{id}/allow-reenroll to HandleAllowReenrollif strings.HasSuffix(req.URL.Path, "/allow-reenroll") {if req.Method == http.MethodPost {- RequireAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {+ RequireOrgAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {if !ensureScope(w, req, config.ScopeSettingsWrite) {return}@@ -107,7 +107,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {// Route DELETE /api/agents/agent/{id} to HandleDeleteHost// SECURITY: Require settings:write (not just host_manage) to prevent compromised host tokens from deleting other hostsif req.Method == http.MethodDelete {- RequireAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {+ RequireOrgAdmin(r.config, func(w http.ResponseWriter, req *http.Request) {if !ensureScope(w, req, config.ScopeSettingsWrite) {return}@@ -120,11 +120,11 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {r.mux.HandleFunc("/api/agents/agent/", RequireAuth(r.config, unifiedAgentManagementCore))r.mux.HandleFunc("/api/agents/host/", wrapLegacyHostAlias("/api/agents/host/", RequireAuth(r.config, unifiedAgentManagementCore)))r.mux.HandleFunc("/api/agents/docker/commands/", RequireAuth(r.config, RequireScope(config.ScopeDockerReport, r.dockerAgentHandlers.HandleCommandAck)))- r.mux.HandleFunc("/api/agents/docker/runtimes/", RequireAdmin(r.config, RequireScope(config.ScopeDockerManage, r.dockerAgentHandlers.HandleDockerHostActions)))+ r.mux.HandleFunc("/api/agents/docker/runtimes/", RequireOrgAdmin(r.config, RequireScope(config.ScopeDockerManage, r.dockerAgentHandlers.HandleDockerHostActions)))r.mux.HandleFunc("/api/agents/docker/containers/update", RequireAdmin(r.config, RequireScope(config.ScopeDockerManage, r.dockerAgentHandlers.HandleContainerUpdate)))- r.mux.HandleFunc("/api/agents/kubernetes/clusters/", RequireAdmin(r.config, RequireScope(config.ScopeKubernetesManage, r.kubernetesAgentHandlers.HandleClusterActions)))+ r.mux.HandleFunc("/api/agents/kubernetes/clusters/", RequireOrgAdmin(r.config, RequireScope(config.ScopeKubernetesManage, r.kubernetesAgentHandlers.HandleClusterActions)))r.mux.HandleFunc("/api/diagnostics", RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.handleDiagnostics)))- r.mux.HandleFunc("/api/diagnostics/docker/prepare-token", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.handleDiagnosticsDockerPrepareToken)))+ r.mux.HandleFunc("/api/diagnostics/docker/prepare-token", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.handleDiagnosticsDockerPrepareToken)))r.mux.HandleFunc("/api/config", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.handleConfig)))r.mux.HandleFunc("/api/runtime/branding", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.systemSettingsHandler.HandleGetRuntimeBranding)))r.mux.HandleFunc("/api/runtime/display", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.systemSettingsHandler.HandleGetRuntimeDisplay)))@@ -147,12 +147,12 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {r.mux.HandleFunc("/api/config/nodes", func(w http.ResponseWriter, req *http.Request) {switch req.Method {case http.MethodGet:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.withExternalAgentCapabilityActivity(+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.withExternalAgentCapabilityActivity(agentcapabilities.ListNodesCapabilityName,r.configHandlers.HandleGetNodes,)))(w, req)case http.MethodPost:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(agentcapabilities.AddNodeCapabilityName,r.configHandlers.HandleAddNode,)))(w, req)@@ -163,7 +163,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {// Test node configuration endpoint (for new nodes)r.mux.HandleFunc("/api/config/nodes/test-config", func(w http.ResponseWriter, req *http.Request) {if req.Method == http.MethodPost {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(agentcapabilities.TestNodeCredentialsCapabilityName,r.configHandlers.HandleTestNodeConfig,)))(w, req)@@ -175,7 +175,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {// Test connection endpointr.mux.HandleFunc("/api/config/nodes/test-connection", func(w http.ResponseWriter, req *http.Request) {if req.Method == http.MethodPost {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleTestConnection))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleTestConnection))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -183,24 +183,24 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {r.mux.HandleFunc("/api/config/nodes/", func(w http.ResponseWriter, req *http.Request) {switch req.Method {case http.MethodPut:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(agentcapabilities.UpdateNodeCapabilityName,r.configHandlers.HandleUpdateNode,)))(w, req)case http.MethodDelete:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(agentcapabilities.RemoveNodeCapabilityName,r.configHandlers.HandleDeleteNode,)))(w, req)case http.MethodPost:// Handle test endpoint and refresh-cluster endpointif strings.HasSuffix(req.URL.Path, "/test") {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(agentcapabilities.TestNodeConnectionCapabilityName,r.configHandlers.HandleTestNode,)))(w, req)} else if strings.HasSuffix(req.URL.Path, "/refresh-cluster") {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.withExternalAgentCapabilityActivity(agentcapabilities.RefreshNodeClusterMembershipCapabilityName,r.configHandlers.HandleRefreshClusterNodes,)))(w, req)@@ -222,7 +222,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.connectionsHandlers.HandleList))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.connectionsHandlers.HandleList))(w, req)})// Workloads needs source health at the monitoring tier, but the connection// ledger above is intentionally administrative. Authentication and@@ -246,7 +246,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.connectionsHandlers.HandleProbe))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.connectionsHandlers.HandleProbe))(w, req)})// Agentless availability target management@@ -257,9 +257,9 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {}switch req.Method {case http.MethodGet:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.availabilityHandlers.HandleList))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.availabilityHandlers.HandleList))(w, req)case http.MethodPost:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleAdd))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleAdd))(w, req)default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -271,7 +271,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {return}if req.Method == http.MethodPost {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleTestConnection))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleTestConnection))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -283,11 +283,11 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {return}if req.Method == http.MethodPost && strings.HasSuffix(strings.Trim(req.URL.Path, "/"), "/test") {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleTestSavedConnection))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleTestSavedConnection))(w, req)} else if req.Method == http.MethodDelete {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleDelete))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleDelete))(w, req)} else if req.Method == http.MethodPut {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleUpdate))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.availabilityHandlers.HandleUpdate))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -302,9 +302,9 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {switch req.Method {case http.MethodGet:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.trueNASHandlers.HandleList))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.trueNASHandlers.HandleList))(w, req)case http.MethodPost:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandleAdd))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandleAdd))(w, req)default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -317,7 +317,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {}if req.Method == http.MethodPost {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandleTestConnection))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandleTestConnection))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -330,7 +330,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {}if req.Method == http.MethodPost {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandlePreviewConnection))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.trueNASHandlers.HandlePreviewConnection))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -357,9 +357,9 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {switch req.Method {case http.MethodGet:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.vmwareHandlers.HandleList))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.vmwareHandlers.HandleList))(w, req)case http.MethodPost:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandleAdd))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandleAdd))(w, req)default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -372,7 +372,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {}if req.Method == http.MethodPost {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandleTestConnection))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandleTestConnection))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -385,7 +385,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {}if req.Method == http.MethodPost {- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandlePreviewConnection))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.vmwareHandlers.HandlePreviewConnection))(w, req)} else {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}@@ -406,7 +406,7 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {// Config Profile Routes - Protected by Admin Auth, Settings Scope, and Pro License// SECURITY: Require settings:write scope to prevent low-privilege tokens from modifying agent profiles// r.configProfileHandler.ServeHTTP implements http.Handler, so we wrap it- r.mux.Handle("/api/admin/profiles/", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, RequireLicenseFeature(r.licenseHandlers, featureAgentProfilesKey, func(w http.ResponseWriter, req *http.Request) {+ r.mux.Handle("/api/admin/profiles/", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, RequireLicenseFeature(r.licenseHandlers, featureAgentProfilesKey, func(w http.ResponseWriter, req *http.Request) {http.StripPrefix("/api/admin/profiles", r.configProfileHandler).ServeHTTP(w, req)}))))@@ -466,10 +466,10 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {r.mux.HandleFunc("/api/setup-script", r.configHandlers.HandleSetupScript)// Generate setup script URL with temporary token (for authenticated users)- r.mux.HandleFunc("/api/setup-script-url", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleSetupScriptURL)))+ r.mux.HandleFunc("/api/setup-script-url", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleSetupScriptURL)))// Generate agent install command with API token (for authenticated users)- r.mux.HandleFunc("/api/agent-install-command", RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleAgentInstallCommand)))+ r.mux.HandleFunc("/api/agent-install-command", RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.configHandlers.HandleAgentInstallCommand)))// Auto-register route for setup scriptsr.mux.HandleFunc("/api/auto-register", r.configHandlers.HandleAutoRegister)@@ -530,9 +530,9 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {path := req.URL.Pathswitch {case strings.HasSuffix(path, "/events"):- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandlePreflightEvents))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandlePreflightEvents))(w, req)default:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleGetPreflight))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleGetPreflight))(w, req)}})@@ -540,13 +540,13 @@ func (r *Router) registerConfigSystemRoutes(updateHandlers *UpdateHandlers) {path := req.URL.Pathswitch {case strings.HasSuffix(path, "/events"):- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleJobEvents))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleJobEvents))(w, req)case strings.HasSuffix(path, "/cancel"):- RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.deployHandlers.HandleCancelJob))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.deployHandlers.HandleCancelJob))(w, req)case strings.HasSuffix(path, "/retry"):RequireAdmin(r.config, RequireScope(config.ScopeSettingsWrite, r.deployHandlers.HandleRetryJob))(w, req)default:- RequireAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleGetJob))(w, req)+ RequireOrgAdmin(r.config, RequireScope(config.ScopeSettingsRead, r.deployHandlers.HandleGetJob))(w, req)}})}diff --git a/internal/api/security_setup_fix.go b/internal/api/security_setup_fix.goindex 9fd700552a..c6665500b7 100644--- a/internal/api/security_setup_fix.go+++ b/internal/api/security_setup_fix.go@@ -134,53 +134,63 @@ func isRunningAsRoot() bool {return os.Geteuid() == 0}+// ensureAdminSession admits a session only when it belongs to an instance+// administrator: the configured local admin or a user holding an instance RBAC+// admin grant, whichever organization the request names. It is+// the session check behind RequireAdmin and the settings scope helpers, so it+// guards everything that reads or changes instance-wide state: credentials,+// API tokens, SSO, system settings, updates, relay, logs and diagnostics.+//+// Organization owners and admins are not instance administrators. A route+// that serves only the request's own organization opts into their authority+// explicitly with ensureOrgAdminSession or RequireOrgAdmin; the default is+// instance administration, so a route that forgets to choose fails closed.+// Requests without a session cookie are left to the caller's other checks.func ensureAdminSession(cfg *config.Config, w http.ResponseWriter, req *http.Request) bool {- // Session users must match configured admin identity for privileged operations.- if cookie, err := readSessionCookie(req); err == nil && cookie.Value != "" && ValidateSession(cookie.Value) {- sessionUser := strings.TrimSpace(GetSessionUsername(cookie.Value))- if sessionUserHasSettingsAdminPrivileges(cfg, req, sessionUser) {- return true- }-- log.Warn().- Str("path", req.URL.Path).- Str("user", sessionUser).- Msg("Session user missing admin privileges for privileged operation")- http.Error(w, "Admin privileges required", http.StatusForbidden)- return false- }- return true-}--// ensureInstanceAdminSession is ensureAdminSession for routes that replace the-// instance's own credentials: the administrator login and the whole API token-// inventory. Those belong to the instance, not to any organization, so the-// caller must be an instance administrator. The org management rule-// ensureAdminSession applies to org-scoped sessions does not count here: an-// organization owner who names their organization in the request would-// otherwise rotate the instance administrator credentials and take the-// instance over. Requests without a session cookie are left to the caller's-// other checks, as in ensureAdminSession.-func ensureInstanceAdminSession(cfg *config.Config, w http.ResponseWriter, req *http.Request) bool {cookie, err := readSessionCookie(req)if err != nil || cookie.Value == "" || !ValidateSession(cookie.Value) {return true}sessionUser := strings.TrimSpace(GetSessionUsername(cookie.Value))- if !sessionIsOrgScoped(req) && sessionUserCarriesAdminPrivileges(cfg, sessionUser) {+ if sessionUserCarriesAdminPrivileges(cfg, sessionUser) {return true}log.Warn().Str("path", req.URL.Path).Str("user", sessionUser).- Msg("Session without instance administrator privileges attempted to replace instance credentials")- http.Error(w, "Instance administrator privileges required. Organization owners and admins cannot change the instance administrator login or API tokens.", http.StatusForbidden)+ Bool("org_scoped", sessionIsOrgScoped(req)).+ Msg("Session user missing instance admin privileges for privileged operation")+ http.Error(w, "Admin privileges required", http.StatusForbidden)return false}-// sessionUserHasSettingsAdminPrivileges is the session rule ensureAdminSession-// enforces for settings-bound routes: the configured local admin; on an+// ensureOrgAdminSession is the session check for routes whose handlers read and+// change only the request organization's own config and monitor state, such+// as its infrastructure connections, agents and availability targets. It admits+// every instance administrator and, on an org-scoped request, a user who can+// manage that organization, so a provider opening a client workspace as its+// owner can connect the client's systems. Everything else uses+// ensureAdminSession.+func ensureOrgAdminSession(cfg *config.Config, w http.ResponseWriter, req *http.Request) bool {+ if cookie, err := readSessionCookie(req); err == nil && cookie.Value != "" && ValidateSession(cookie.Value) {+ sessionUser := strings.TrimSpace(GetSessionUsername(cookie.Value))+ if sessionUserCarriesAdminPrivileges(cfg, sessionUser) || sessionUserHasSettingsAdminPrivileges(cfg, req, sessionUser) {+ return true+ }++ log.Warn().+ Str("path", req.URL.Path).+ Str("user", sessionUser).+ Msg("Session user missing admin privileges for organization operation")+ http.Error(w, "Admin privileges required", http.StatusForbidden)+ return false+ }+ return true+}++// sessionUserHasSettingsAdminPrivileges is the session rule ensureOrgAdminSession+// enforces for org-bound routes: the configured local admin; on an// org-scoped request, a user who can manage that organization; otherwise an// instance administrator. The security status snapshot publishes settings// capabilities from this same rule, so a surface the UI offers is one its@@ -301,6 +311,20 @@ func ensureSettingsScope(cfg *config.Config, w http.ResponseWriter, req *http.Rereturn true}+// ensureOrgSettingsScope is ensureSettingsScope for routes that act only on+// the request organization's own state: token callers need the scope, and+// session callers pass ensureOrgAdminSession instead of ensureAdminSession.+func ensureOrgSettingsScope(cfg *config.Config, w http.ResponseWriter, req *http.Request, scope string) bool {+ if record := getAPITokenRecordFromRequest(req); record != nil {+ return ensureSettingsScope(cfg, w, req, scope)+ }+ return ensureOrgAdminSession(cfg, w, req)+}++func ensureOrgSettingsWriteScope(cfg *config.Config, w http.ResponseWriter, req *http.Request) bool {+ return ensureOrgSettingsScope(cfg, w, req, config.ScopeSettingsWrite)+}+func ensureSettingsReadScope(cfg *config.Config, w http.ResponseWriter, req *http.Request) bool {return ensureSettingsScope(cfg, w, req, config.ScopeSettingsRead)}@@ -480,9 +504,6 @@ func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {http.Error(w, "Security setup replaces the administrator credentials and every API token, so it needs a full-access token that is not bound to any non-default organization.", http.StatusForbidden)return}- if authConfigured && !recoveryAuthorized && getAPITokenRecordFromRequest(req) == nil && !ensureInstanceAdminSession(r.config, w, req) {- return- }if setupRequest.Force {log.Info().Msg("Quick security setup invoked with force=true - rotating credentials")@@ -783,9 +804,6 @@ func (r *Router) HandleRegenerateAPIToken(w http.ResponseWriter, rq *http.Requeshttp.Error(w, "Regenerating API tokens replaces every token, so it needs a full-access token that is not bound to any non-default organization. Use POST /api/security/tokens/{id}/rotate to replace one token.", http.StatusForbidden)return}- if getAPITokenRecordFromRequest(rq) == nil && !ensureInstanceAdminSession(r.config, w, rq) {- return- }// Apply rate limiting to prevent abuseclientIP := GetClientIP(rq)diff --git a/internal/api/security_setup_fix_test.go b/internal/api/security_setup_fix_test.goindex 071c6d7d14..22214cb2f0 100644--- a/internal/api/security_setup_fix_test.go+++ b/internal/api/security_setup_fix_test.go@@ -653,7 +653,9 @@ func TestEnsureSettingsWriteScopeAllowsConfiguredAdminSession(t *testing.T) {}}-func TestEnsureSettingsWriteScopeAllowsOrgManagerSession(t *testing.T) {+// Settings scope guards instance-wide settings, so an organization's owner is+// refused there; routes that serve only that organization use the org variant.+func TestSettingsWriteScopeSplitsInstanceAndOrgManagerSession(t *testing.T) {cfg := &config.Config{AuthUser: "platform-admin",}@@ -674,10 +676,16 @@ func TestEnsureSettingsWriteScopeAllowsOrgManagerSession(t *testing.T) {}))rr := httptest.NewRecorder()- result := ensureSettingsWriteScope(cfg, rr, req)+ if ensureSettingsWriteScope(cfg, rr, req) {+ t.Fatal("ensureSettingsWriteScope must refuse an org manager who is not an instance admin")+ }+ if rr.Code != http.StatusForbidden {+ t.Fatalf("expected 403 for org manager session on instance settings, got %d", rr.Code)+ }- if !result {- t.Fatal("ensureSettingsWriteScope should allow org manager session users")+ rr = httptest.NewRecorder()+ if !ensureOrgSettingsWriteScope(cfg, rr, req) {+ t.Fatal("ensureOrgSettingsWriteScope should allow org manager session users")}if rr.Code != http.StatusOK {t.Fatalf("expected 200 for org manager session, got %d", rr.Code)diff --git a/internal/api/security_status_capabilities.go b/internal/api/security_status_capabilities.goindex 5152cc71e8..89ffe71040 100644--- a/internal/api/security_status_capabilities.go+++ b/internal/api/security_status_capabilities.go@@ -79,7 +79,7 @@ type securityStatusAuthSnapshot struct {proxyIsAdmin boolsessionIsAdmin bool// sessionManagesOrg is set for an org-scoped session that- // ensureAdminSession admits: an owner or admin of the request's+ // ensureOrgAdminSession admits: an owner or admin of the request's// organization, or the configured admin. It widens only the org-bound// settings surfaces, never sessionIsAdmin, so instance administration and// the privileged status fields stay closed to org-scoped sessions.@@ -285,18 +285,15 @@ func (r *Router) securityStatusSettingsCapabilitiesFromSnapshot(snapshot securitcanReadReporting := canReadSettings &&r.canAccessPermissionSurface(snapshot, internalauth.ActionRead, internalauth.ResourceNodes, config.ScopeSettingsRead)- // Infrastructure, availability, and reporting are org-bound: their routes- // pass ensureAdminSession, which admits an org manager inside their own- // organization, and their handlers read that organization's config and- // monitor state. A provider opening a client workspace lands there as the- // org owner, and without these the settings navigation hides the only- // pages that connect the client's systems and build its reports. Every- // other capability stays instance administration.+ // Infrastructure and availability are org-bound: their routes use+ // RequireOrgAdmin / ensureOrgAdminSession, which admit an org manager+ // inside their own organization, and their handlers read that+ // organization's config and monitor state. A provider opening a client+ // workspace lands there as the org owner, and without these the settings+ // navigation hides the pages that connect the client's systems. Every other+ // capability, reporting included, stays instance administration: report+ // generation still reads metrics from the instance's default store.canReadOrgSettings := canReadSettings || snapshot.sessionManagesOrg- if snapshot.sessionManagesOrg && !canReadReporting {- allowed, err := r.authorizer.Authorize(snapshot.request.Context(), internalauth.ActionRead, internalauth.ResourceNodes)- canReadReporting = err == nil && allowed- }return securityStatusSettingsCapabilities{InfrastructureRead: canReadOrgSettings,