Files
Pulse/internal/api/agent_events_auth.go
rcourtman f37c102535 Limit the default organization in multi-org mode
In self-hosted multi-organization mode the tenant check let every
signed-in session or proxy user into the default organization, so a
user invited only to another organization could read the default
estate by selecting it with the org header or cookie.

The default organization is now open there only to instance
administrators (local admin, an RBAC admin grant evaluated with
inheritance and deny precedence, or a proxy user admitted with the
admin role) and to explicit members recorded in its org.json, loaded
strictly. Having no other membership is never treated as access.
Single-tenant and hosted runtimes keep the open default organization.

One context-aware policy now serves tenant selection, action
authority, the organization handlers and the WebSocket hub, which
also checks the default organization. WebSocket, SSE and agent-event
streams re-check it every 10 seconds, so revoked access ends live
reads. Handlers that re-derive the org from the request now follow
the authorized org.

A request that names no organization lands in the user's first
organization. A refused default selection answers
default_org_access_denied; the browser clears it and retries reads
only. A user with no usable organization sees their pending
invitations instead of a connection failure.

Instance administrators manage default members from Organization
access. Members are viewers, membership is the only entitlement (an
owner field grants nothing), and every save of the default
organization keeps its current members, so a share or invitation
change made from an older snapshot cannot restore a revoked one. The first
start in this mode seeds RBAC-assigned users who belong to no other
organization, and retries rather than completing on unreadable
tenant metadata or RBAC data.

Listing an organization's invitations now returns [] instead of null
when none are pending; the Organization access panel rejected null and
showed "Organization access unavailable" to any org admin without
pending invitations.
2026-11-03 15:57:34 +00:00

95 lines
3.7 KiB
Go

package api
import (
"net/http"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
func (r *Router) handleAgentEvents(w http.ResponseWriter, req *http.Request) {
r.agentEventBroadcaster.handleAgentEvents(w, req, agentEventTokenRevalidator(r.config, req))
}
// agentEventTokenRevalidator keeps a long-lived token stream bound to its
// admitted credential and organization, not its connection-time snapshot.
// Session withdrawal is checked too. The callback runs on the stream
// goroutine; it never writes an HTTP auth error after streaming has begun.
func agentEventTokenRevalidator(cfg *config.Config, req *http.Request) func() bool {
revalidate := monitoringTokenSnapshotRevalidator(cfg, req)
if revalidate == nil {
// A signed-in user's stream also follows the organization access
// policy, so lost membership or default access ends it.
return combineAuthorization(sessionReadRevalidator(req), orgAccessRevalidator(req))
}
admittedContext := req.Context()
return func() bool {
current, ok := revalidate()
if !ok {
return false
}
// Replace over the admitted context, never the previous refresh. Only
// the SSE goroutine owns this request and its disclosure snapshot.
refreshed := req.WithContext(admittedContext)
attachAPITokenRecord(refreshed, current)
*req = *refreshed
return true
}
}
// monitoringTokenSnapshotRevalidator is shared by long-lived monitoring reads.
// It returns detached current authority without mutating the admitted request;
// WebSocket writes outlive the HTTP handler and must not race its middleware.
// A nil callback preserves existing session/proxy authentication behaviour.
func monitoringTokenSnapshotRevalidator(cfg *config.Config, req *http.Request) func() (*config.APITokenRecord, bool) {
return tokenStreamSnapshotRevalidator(cfg, req, config.ScopeMonitoringRead)
}
// tokenStreamSnapshotRevalidator preserves the stream's admitted credential,
// principal and organization while checking its current operation-specific
// scope. Callers must retain any additional route policy (e.g. instance admin).
func tokenStreamSnapshotRevalidator(cfg *config.Config, req *http.Request, scopes ...string) func() (*config.APITokenRecord, bool) {
admitted := getAPITokenRecordFromRequest(req)
if admitted == nil {
return nil
}
raw, provided := explicitAPITokenFromRequest(req)
orgID := GetOrgID(req.Context())
source, tenantInventory := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
tenantInventory = tenantInventory && source.orgID != "" && source.orgID != "default"
checker := NewAuthorizationChecker(nil)
return func() (*config.APITokenRecord, bool) {
if !provided || raw == "" {
return nil, false
}
config.Mu.RLock()
defer config.Mu.RUnlock()
live := cfg
if tenantInventory {
live = tenantTokenConfigForRequest(req)
if live == nil {
return nil, false
}
}
// Reuse authentication's exclusive metadata ownership and detached
// snapshot. A tenant stream must not fall back to another inventory
// when its current owner disappears or revokes the credential.
current, ok := validateAPITokenLocked(live, raw)
if !ok || (tenantInventory && tenantTokenConfigForRequest(req) != live) {
return nil, false
}
// Keep the route's existing scope alternatives (notably mobile chat)
// rather than requiring a new grant or pinning one interchangeable scope.
hasScope := false
for _, scope := range scopes {
hasScope = hasScope || current.HasScope(scope)
}
if current.ID != admitted.ID || apiTokenAuthenticatedUser(current) != apiTokenAuthenticatedUser(admitted) ||
!hasScope || !checker.CheckAccess(current, "", orgID).Allowed {
return nil, false
}
return current, true
}
}