mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-05 18:12:58 +00:00
End dashboard token streams when their authority is withdrawn (#3652)
**End dashboard token streams when their authority is withdrawn** Revalidate the admitted token before every websocket data frame, queued flush and idle ping. Share the current-tenant snapshot validator without mutating a returned HTTP request. Keep session, origin, licensing and wanted monitoring reads unchanged; exercise real token deletion, client cleanup and independent subscribers. **Preserve the existing unknown-organization reconnect refusal** The first race proof closed every withdrawn socket but the reconnect assertion expected only 401 or 403. Normal middleware first resolves the rebound token's nonexistent organization and returns 400 invalid_org. Assert that exact existing refusal without changing runtime authority, frames or status codes. --- Fleet candidate `20261031T195231Z-core-runtime` from the `core-runtime` lane. Reviewed tip `096f655034b08f2d898c8402853509a7acb1bda9` on `main`. [How Pulse handles triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
@@ -15,6 +15,19 @@
|
||||
|
||||
## Purpose
|
||||
|
||||
### Dashboard token lifetime is not agent-execution authority
|
||||
|
||||
An already-open dashboard `/ws` read loses access when its admitted API token
|
||||
is revoked, expires or loses its identity/principal, organization or monitoring
|
||||
read authority. The shared current-inventory validator supplies detached
|
||||
snapshots; the socket writer checks each data/queued frame and its existing
|
||||
idle ping. Policy close 1008 uses only a fixed reason. Agent command sockets,
|
||||
enrollment, sessions, origin/licensing checks and token grants are unchanged.
|
||||
The ordinary registered-route deletion and writer queue/idle tests establish
|
||||
read withdrawal, not installed agent or original guest recovery. SSE retains
|
||||
its bounded context replacement and fresh disclosure scopes.
|
||||
|
||||
|
||||
### Agent event subscriptions follow their current token inventory
|
||||
|
||||
Before streaming each frame, API-token subscribers revalidate against the
|
||||
|
||||
@@ -21,6 +21,34 @@
|
||||
|
||||
## Purpose
|
||||
|
||||
### Dashboard sockets do not retain withdrawn token authority
|
||||
|
||||
The existing `/ws` route keeps its initial authentication, monitoring-read,
|
||||
organization, origin and licensing gates. For API tokens, its single writer
|
||||
revalidates the admitted identity/principal against the current owning token
|
||||
inventory before every outgoing data frame, including each queued flush, and
|
||||
before the existing 30-second idle ping. Revocation, expiry, read-scope removal,
|
||||
changed identity/principal or lost organization authority ends the connection
|
||||
with code 1008 and fixed reason `Monitoring access ended`; it sends no queued
|
||||
product data or HTTP error after that refusal. An already admitted frame can
|
||||
still be in flight during a concurrent withdrawal. New requests authenticate
|
||||
normally; a legitimate replacement identity may reconnect.
|
||||
|
||||
The shared validator returns detached authority without changing the original
|
||||
HTTP request after its handler returns. Tenant removal cannot fall back to a
|
||||
stale or global inventory. Session/proxy behaviour, wanted monitoring reads
|
||||
after execute-scope removal, other subscribers and canonical data are unchanged.
|
||||
The existing frontend policy-close path returns to sign-in rather than silently
|
||||
retrying withdrawn credentials. No route, token grant or event/history source
|
||||
is added, and source/browser proof is not installed recovery or publication.
|
||||
|
||||
`websocket_auth_test.go` exercises all three existing token transports, current
|
||||
tenant ownership and immutable requests. The contract's real persisted HTTP
|
||||
DELETE ends an already-open registered socket. `hub_test.go` exercises queued
|
||||
flush refusal and the actual idle ping, without a shortened production timer.
|
||||
The agent SSE lifecycle suite retains its bounded disclosure refresh contract.
|
||||
|
||||
|
||||
### Agent event streams retain live API-token authority
|
||||
|
||||
The registered agent SSE route revalidates its admitted token before the
|
||||
|
||||
@@ -18,6 +18,34 @@
|
||||
|
||||
## Purpose
|
||||
|
||||
### Dashboard sockets do not retain withdrawn token authority
|
||||
|
||||
The existing `/ws` route keeps its initial authentication, monitoring-read,
|
||||
organization, origin and licensing gates. For API tokens, its single writer
|
||||
revalidates the admitted identity/principal against the current owning token
|
||||
inventory before every outgoing data frame, including each queued flush, and
|
||||
before the existing 30-second idle ping. Revocation, expiry, read-scope removal,
|
||||
changed identity/principal or lost organization authority ends the connection
|
||||
with code 1008 and fixed reason `Monitoring access ended`; it sends no queued
|
||||
product data or HTTP error after that refusal. An already admitted frame can
|
||||
still be in flight during a concurrent withdrawal. New requests authenticate
|
||||
normally; a legitimate replacement identity may reconnect.
|
||||
|
||||
The shared validator returns detached authority without changing the original
|
||||
HTTP request after its handler returns. Tenant removal cannot fall back to a
|
||||
stale or global inventory. Session/proxy behaviour, wanted monitoring reads
|
||||
after execute-scope removal, other subscribers and canonical data are unchanged.
|
||||
The existing frontend policy-close path returns to sign-in rather than silently
|
||||
retrying withdrawn credentials. No route, token grant or event/history source
|
||||
is added, and source/browser proof is not installed recovery or publication.
|
||||
|
||||
`websocket_auth_test.go` exercises all three existing token transports, current
|
||||
tenant ownership and immutable requests. The contract's real persisted HTTP
|
||||
DELETE ends an already-open registered socket. `hub_test.go` exercises queued
|
||||
flush refusal and the actual idle ping, without a shortened production timer.
|
||||
The agent SSE lifecycle suite retains its bounded disclosure refresh contract.
|
||||
|
||||
|
||||
### Token withdrawal applies to existing agent streams
|
||||
|
||||
A successful stream connection does not retain permanent API-token authority.
|
||||
|
||||
@@ -21,6 +21,18 @@
|
||||
|
||||
## Purpose
|
||||
|
||||
### Revoked monitoring sockets do not preserve recovery access
|
||||
|
||||
Dashboard `/ws` token reads revalidate current authority before data/queued
|
||||
frames and idle pings; refusal closes only that connection, without sending
|
||||
queued state. Current tenant ownership is resolved without stale/global
|
||||
fallback. This neither removes saved inventory, data or credentials nor changes
|
||||
storage/backup operations, authorized sessions or independent administrator
|
||||
access. Real persisted token DELETE and immutable-request/tenant tests cover
|
||||
the boundary. It does not establish original workload thaw, filesystem writes,
|
||||
credential recovery, publication or an installed runtime outcome.
|
||||
|
||||
|
||||
### Long-lived agent reads preserve current token boundaries
|
||||
|
||||
Agent event subscriptions revalidate API-token authority before admitting
|
||||
|
||||
@@ -15,6 +15,30 @@ func (r *Router) handleAgentEvents(w http.ResponseWriter, req *http.Request) {
|
||||
// Session/proxy authentication is unchanged. 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 {
|
||||
return nil
|
||||
}
|
||||
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) {
|
||||
admitted := getAPITokenRecordFromRequest(req)
|
||||
if admitted == nil {
|
||||
return nil
|
||||
@@ -24,11 +48,10 @@ func agentEventTokenRevalidator(cfg *config.Config, req *http.Request) func() bo
|
||||
source, tenantInventory := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
|
||||
tenantInventory = tenantInventory && source.orgID != "" && source.orgID != "default"
|
||||
checker := NewAuthorizationChecker(nil)
|
||||
admittedContext := req.Context()
|
||||
|
||||
return func() bool {
|
||||
return func() (*config.APITokenRecord, bool) {
|
||||
if !provided || raw == "" {
|
||||
return false
|
||||
return nil, false
|
||||
}
|
||||
config.Mu.RLock()
|
||||
defer config.Mu.RUnlock()
|
||||
@@ -37,7 +60,7 @@ func agentEventTokenRevalidator(cfg *config.Config, req *http.Request) func() bo
|
||||
if tenantInventory {
|
||||
live = tenantTokenConfigForRequest(req)
|
||||
if live == nil {
|
||||
return false
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
// Reuse authentication's exclusive metadata ownership and detached
|
||||
@@ -45,20 +68,12 @@ func agentEventTokenRevalidator(cfg *config.Config, req *http.Request) func() bo
|
||||
// when its current owner disappears or revokes the credential.
|
||||
current, ok := validateAPITokenLocked(live, raw)
|
||||
if !ok || (tenantInventory && tenantTokenConfigForRequest(req) != live) {
|
||||
return false
|
||||
return nil, false
|
||||
}
|
||||
if current.ID != admitted.ID || apiTokenAuthenticatedUser(current) != apiTokenAuthenticatedUser(admitted) ||
|
||||
!current.HasScope(config.ScopeMonitoringRead) || !checker.CheckAccess(current, "", orgID).Allowed {
|
||||
return false
|
||||
return nil, false
|
||||
}
|
||||
// In particular, withdrawing ai:execute must redact the very next
|
||||
// action/approval frame, even though monitoring:read still permits it.
|
||||
// Replace from the admitted context, not the previous refresh: wrapping
|
||||
// req.Context() here would retain every earlier token snapshot for the
|
||||
// lifetime of the stream. Keep its cancellation and other values intact.
|
||||
refreshed := req.WithContext(admittedContext)
|
||||
attachAPITokenRecord(refreshed, current)
|
||||
*req = *refreshed
|
||||
return true
|
||||
return current, true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28848,3 +28848,7 @@ func TestAgentEventTokenLifecycleRefreshesDisclosure(t *testing.T) {
|
||||
t.Fatal("refresh/redaction changed the published canonical record")
|
||||
}
|
||||
}
|
||||
|
||||
func TestContract_MonitoringWebSocketTokenDeleteThroughHTTP(t *testing.T) {
|
||||
deleteMonitoringWebSocketTokenThroughHTTP(t)
|
||||
}
|
||||
|
||||
@@ -7556,7 +7556,7 @@ func (r *Router) handleWebSocket(w http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
r.wsHub.HandleWebSocket(w, boundReq)
|
||||
r.wsHub.HandleWebSocketWithAuthorization(w, boundReq, monitoringWebSocketAuthorization(r.config, boundReq))
|
||||
}
|
||||
|
||||
// handleSimpleStats serves a simple stats page
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
)
|
||||
|
||||
func monitoringWebSocketAuthorization(cfg *config.Config, req *http.Request) func() bool {
|
||||
// The socket writer outlives this HTTP request. Give it an immutable
|
||||
// request copy, not one its returning middleware may still be observing.
|
||||
revalidate := monitoringTokenSnapshotRevalidator(cfg, req.Clone(req.Context()))
|
||||
if revalidate == nil {
|
||||
return nil
|
||||
}
|
||||
return func() bool {
|
||||
_, ok := revalidate()
|
||||
return ok
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
gorillaws "github.com/gorilla/websocket"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
|
||||
pulsews "github.com/rcourtman/pulse-go-rewrite/internal/websocket"
|
||||
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
|
||||
)
|
||||
|
||||
const monitoringWebSocketToken = "synthetic-monitoring-websocket-token.12345678"
|
||||
const monitoringWebSocketControl = "synthetic-monitoring-websocket-control.12345678"
|
||||
|
||||
func newMonitoringWebSocketRouter(t *testing.T) (*Router, *config.Config, *httptest.Server, *pulsews.Hub) {
|
||||
t.Helper()
|
||||
cfg := newTestConfigWithTokens(t,
|
||||
newTokenRecord(t, monitoringWebSocketToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil),
|
||||
newTokenRecord(t, monitoringWebSocketControl, []string{config.ScopeWildcard}, nil))
|
||||
hub := pulsews.NewHub(nil)
|
||||
go hub.Run()
|
||||
t.Cleanup(hub.Stop)
|
||||
router := NewRouter(cfg, nil, nil, hub, nil, "test")
|
||||
cleanupTestRouter(t, router)
|
||||
server := httptest.NewServer(router.Handler())
|
||||
t.Cleanup(server.Close)
|
||||
return router, cfg, server, hub
|
||||
}
|
||||
|
||||
func monitoringWebSocketAddress(server *httptest.Server, raw, transport string) (string, http.Header) {
|
||||
address := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws?org_id=default"
|
||||
headers := http.Header{"Origin": []string{server.URL}}
|
||||
switch transport {
|
||||
case "query":
|
||||
address += "&token=" + raw
|
||||
case "bearer":
|
||||
headers.Set("Authorization", "Bearer "+raw)
|
||||
case "session":
|
||||
headers.Set("Cookie", cookieNameSession+"="+raw)
|
||||
default:
|
||||
headers.Set("X-API-Token", raw)
|
||||
}
|
||||
return address, headers
|
||||
}
|
||||
|
||||
func openMonitoringWebSocket(t *testing.T, server *httptest.Server, raw, transport string) *gorillaws.Conn {
|
||||
t.Helper()
|
||||
address, headers := monitoringWebSocketAddress(server, raw, transport)
|
||||
conn, _, err := gorillaws.DefaultDialer.Dial(address, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { conn.Close() })
|
||||
// A real application ping/pong synchronizes writer admission, without
|
||||
// waiting for the unrelated delayed initial-state builder.
|
||||
if err := conn.WriteJSON(pulsews.Message{Type: "ping"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame := nextMonitoringWebSocketFrame(t, conn); frame.Type != "pong" {
|
||||
t.Fatalf("admitted socket = %q, want pong", frame.Type)
|
||||
}
|
||||
return conn
|
||||
}
|
||||
|
||||
func nextMonitoringWebSocketFrame(t *testing.T, conn *gorillaws.Conn) pulsews.Message {
|
||||
t.Helper()
|
||||
if err := conn.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var msg pulsews.Message
|
||||
if err := conn.ReadJSON(&msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func wantMonitoringWebSocketClientCount(t *testing.T, hub *pulsews.Hub, want int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if hub.GetClientCount() == want {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatalf("remaining socket clients = %d, want %d", hub.GetClientCount(), want)
|
||||
}
|
||||
|
||||
func wantMonitoringWebSocketClosed(t *testing.T, conn *gorillaws.Conn) {
|
||||
t.Helper()
|
||||
if err := conn.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, body, err := conn.ReadMessage()
|
||||
var closed *gorillaws.CloseError
|
||||
if !errors.As(err, &closed) || closed.Code != gorillaws.ClosePolicyViolation || closed.Text != "Monitoring access ended" {
|
||||
t.Fatalf("withdrawn socket = %s, %v; want fixed policy close, no product frame", body, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitoringWebSocketRejectsWithdrawnTokenAuthority(t *testing.T) {
|
||||
for _, transport := range []string{"header", "bearer", "query"} {
|
||||
for _, change := range []string{"revoked", "expired", "read_scope_removed", "org_rebound", "identity_replaced", "principal_replaced", "invalid_role"} {
|
||||
t.Run(transport+"/"+change, func(t *testing.T) {
|
||||
_, cfg, server, hub := newMonitoringWebSocketRouter(t)
|
||||
primary := openMonitoringWebSocket(t, server, monitoringWebSocketToken, transport)
|
||||
control := openMonitoringWebSocket(t, server, monitoringWebSocketControl, transport)
|
||||
config.Mu.Lock()
|
||||
switch change {
|
||||
case "revoked":
|
||||
cfg.RemoveAPIToken(cfg.APITokens[0].ID)
|
||||
case "expired":
|
||||
past := time.Now().Add(-time.Second)
|
||||
cfg.APITokens[0].ExpiresAt = &past
|
||||
case "read_scope_removed":
|
||||
cfg.APITokens[0].Scopes = []string{config.ScopeAgentReport}
|
||||
case "org_rebound":
|
||||
cfg.APITokens[0].OrgID = "other-org"
|
||||
case "identity_replaced":
|
||||
cfg.APITokens[0].ID = "other-credential"
|
||||
case "principal_replaced":
|
||||
cfg.APITokens[0].Metadata = map[string]string{apiTokenMetadataOwnerUserID: "other-owner"}
|
||||
case "invalid_role":
|
||||
cfg.APITokens[0].Metadata = map[string]string{internalauth.RuntimeRoleMetadataKey: internalauth.RuntimeRoleActionRunner}
|
||||
}
|
||||
config.Mu.Unlock()
|
||||
hub.BroadcastMessageToTenant("default", pulsews.Message{Type: "notification", Data: "after-withdrawal"})
|
||||
wantMonitoringWebSocketClosed(t, primary)
|
||||
wantMonitoringWebSocketClientCount(t, hub, 1)
|
||||
if frame := nextMonitoringWebSocketFrame(t, control); frame.Type != "notification" || frame.Data != "after-withdrawal" {
|
||||
t.Fatalf("independent credential lost its frame: %+v", frame)
|
||||
}
|
||||
// The normal upgrade path must also reject the withdrawn identity.
|
||||
address, headers := monitoringWebSocketAddress(server, monitoringWebSocketToken, transport)
|
||||
conn, resp, err := gorillaws.DefaultDialer.Dial(address, headers)
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
}
|
||||
if change == "identity_replaced" || change == "principal_replaced" {
|
||||
// A new request may authenticate the new identity. Only the
|
||||
// already-admitted connection is bound to its old principal.
|
||||
if err != nil {
|
||||
t.Fatalf("new valid identity could not reconnect: %v", err)
|
||||
}
|
||||
} else if change == "org_rebound" {
|
||||
// Without an explicit org header/cookie, normal middleware
|
||||
// resolves the token's newly bound (nonexistent) org before
|
||||
// websocket admission. Preserve that exact existing refusal.
|
||||
if err == nil || resp == nil || resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("unknown-org reconnect: %v, %v", resp, err)
|
||||
}
|
||||
var denial map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&denial); err != nil || denial["error"] != "invalid_org" {
|
||||
t.Fatalf("unknown-org reconnect lost its exact refusal: %v, %v", denial, err)
|
||||
}
|
||||
} else if err == nil || resp == nil || (resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden) {
|
||||
t.Fatalf("withdrawn reconnect: %v, %v", resp, err)
|
||||
}
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitoringWebSocketPreservesAllowedTokenAndSession(t *testing.T) {
|
||||
_, cfg, server, hub := newMonitoringWebSocketRouter(t)
|
||||
primary := openMonitoringWebSocket(t, server, monitoringWebSocketToken, "query")
|
||||
const session = "synthetic-monitoring-websocket-session"
|
||||
GetSessionStore().CreateSession(session, time.Hour, "fixture", "127.0.0.1", "operator")
|
||||
t.Cleanup(func() { GetSessionStore().DeleteSession(session) })
|
||||
browser := openMonitoringWebSocket(t, server, session, "session")
|
||||
config.Mu.Lock()
|
||||
// Withdrawing execute alone must not remove wanted monitoring reads.
|
||||
cfg.APITokens[0].Scopes = []string{config.ScopeMonitoringRead}
|
||||
config.Mu.Unlock()
|
||||
hub.BroadcastMessageToTenant("default", pulsews.Message{Type: "notification", Data: "still-readable"})
|
||||
for _, conn := range []*gorillaws.Conn{primary, browser} {
|
||||
if frame := nextMonitoringWebSocketFrame(t, conn); frame.Data != "still-readable" {
|
||||
t.Fatalf("allowed read changed: %+v", frame)
|
||||
}
|
||||
}
|
||||
config.Mu.Lock()
|
||||
cfg.RemoveAPIToken(cfg.APITokens[0].ID)
|
||||
config.Mu.Unlock()
|
||||
hub.BroadcastMessageToTenant("default", pulsews.Message{Type: "notification", Data: "session-still-readable"})
|
||||
wantMonitoringWebSocketClosed(t, primary)
|
||||
if frame := nextMonitoringWebSocketFrame(t, browser); frame.Data != "session-still-readable" {
|
||||
t.Fatalf("token removal changed independent session: %+v", frame)
|
||||
}
|
||||
}
|
||||
|
||||
// The socket uses the same current-owner resolution as normal authentication,
|
||||
// without starting a monitored tenant or opening an appliance/database runtime.
|
||||
func TestMonitoringWebSocketAuthorizationUsesLiveTenantWithoutMutatingRequest(t *testing.T) {
|
||||
const orgID = "socket-tenant"
|
||||
token := newTokenRecord(t, monitoringWebSocketToken, []string{config.ScopeMonitoringRead}, nil)
|
||||
token.OrgID = orgID
|
||||
base := &config.Config{}
|
||||
mtp := config.NewMultiTenantPersistence(t.TempDir())
|
||||
if _, err := mtp.GetPersistence(orgID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
makeManager := func(cfg *config.Config) *monitoring.MultiTenantMonitor {
|
||||
manager := monitoring.NewMultiTenantMonitor(base, mtp, nil)
|
||||
monitor := &monitoring.Monitor{}
|
||||
setUnexportedField(t, monitor, "config", cfg)
|
||||
setUnexportedField(t, manager, "monitors", map[string]*monitoring.Monitor{orgID: monitor})
|
||||
t.Cleanup(manager.Stop)
|
||||
return manager
|
||||
}
|
||||
owner := makeManager(&config.Config{APITokens: []config.APITokenRecord{token}})
|
||||
empty := makeManager(&config.Config{})
|
||||
replacement := makeManager(&config.Config{APITokens: []config.APITokenRecord{token.Clone()}})
|
||||
req := httptest.NewRequest(http.MethodGet, "/ws?token="+monitoringWebSocketToken, nil)
|
||||
req.Header.Set("Upgrade", "websocket")
|
||||
req.Header.Set("Connection", "Upgrade")
|
||||
req.Header.Set("X-Pulse-Org-ID", orgID)
|
||||
req = extractAndStoreAuthContext(base, owner, req)
|
||||
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, orgID))
|
||||
source := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
|
||||
var current atomic.Pointer[monitoring.MultiTenantMonitor]
|
||||
current.Store(owner)
|
||||
source.resolveManager = current.Load
|
||||
req = req.WithContext(context.WithValue(req.Context(), tenantTokenSourceContextKey, source))
|
||||
originalContext := req.Context()
|
||||
originalToken := getAPITokenRecordFromRequest(req).Clone()
|
||||
originalHeader := req.Header.Clone()
|
||||
authorize := monitoringWebSocketAuthorization(base, req)
|
||||
if authorize == nil || !authorize() {
|
||||
t.Fatal("admitted tenant rejected")
|
||||
}
|
||||
// A copied request remains safe after the HTTP handler returns and another
|
||||
// observer reads its original context/headers concurrently with refreshes.
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for range 64 {
|
||||
if !authorize() {
|
||||
t.Error("unchanged tenant authority rejected")
|
||||
}
|
||||
}
|
||||
}()
|
||||
for range 64 {
|
||||
if req.Context() != originalContext || !reflect.DeepEqual(req.Header, originalHeader) || !reflect.DeepEqual(getAPITokenRecordFromRequest(req).Clone(), originalToken) {
|
||||
t.Fatal("socket validation mutated its admitted HTTP request")
|
||||
}
|
||||
}
|
||||
<-done
|
||||
current.Store(replacement)
|
||||
if !authorize() {
|
||||
t.Fatal("same valid credential in current tenant owner was rejected")
|
||||
}
|
||||
config.Mu.Lock()
|
||||
base.APITokens = []config.APITokenRecord{token.Clone()}
|
||||
config.Mu.Unlock()
|
||||
for _, manager := range []*monitoring.MultiTenantMonitor{empty, nil} {
|
||||
current.Store(manager)
|
||||
if authorize() {
|
||||
t.Fatal("removed tenant authority fell back to a stale or global inventory")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func deleteMonitoringWebSocketTokenThroughHTTP(t *testing.T) {
|
||||
t.Helper()
|
||||
router, cfg, server, hub := newMonitoringWebSocketRouter(t)
|
||||
primary := openMonitoringWebSocket(t, server, monitoringWebSocketToken, "query")
|
||||
id := cfg.APITokens[0].ID
|
||||
req, _ := http.NewRequest(http.MethodDelete, server.URL+"/api/security/tokens/"+id, nil)
|
||||
req.Header.Set("X-API-Token", monitoringWebSocketControl)
|
||||
resp, err := server.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("token deletion = %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
persisted, err := router.persistence.LoadAPITokens()
|
||||
if err != nil || len(persisted) != 1 || persisted[0].ID == id {
|
||||
t.Fatalf("token revocation not persisted: %v", err)
|
||||
}
|
||||
hub.BroadcastMessageToTenant("default", pulsews.Message{Type: "notification", Data: "after-persisted-deletion"})
|
||||
wantMonitoringWebSocketClosed(t, primary)
|
||||
wantMonitoringWebSocketClientCount(t, hub, 0)
|
||||
wire, _ := json.Marshal(map[string]any{"code": gorillaws.ClosePolicyViolation, "reason": "Monitoring access ended"})
|
||||
t.Logf("actual registered-route policy close after persisted HTTP deletion: %s", wire)
|
||||
}
|
||||
@@ -296,6 +296,9 @@ type Client struct {
|
||||
// display snapshots and the socket deliberately has no delta baseline.
|
||||
restRecovery bool
|
||||
maxInboundBytes atomic.Int64
|
||||
// authorizeWrite is immutable after admission and called only by writePump.
|
||||
// Authentication remains owned by the API, not this transport package.
|
||||
authorizeWrite func() bool
|
||||
}
|
||||
|
||||
func (c *Client) inboundLimitBytes() int64 {
|
||||
@@ -1032,6 +1035,13 @@ func (h *Hub) tryRegisterClient(client *Client) bool {
|
||||
|
||||
// HandleWebSocket handles WebSocket upgrade requests
|
||||
func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
h.HandleWebSocketWithAuthorization(w, r, nil)
|
||||
}
|
||||
|
||||
// HandleWebSocketWithAuthorization keeps an admitted connection subject to
|
||||
// current authority. The callback runs only on its writer, before every frame
|
||||
// (including queued frames and idle pings). Nil preserves existing callers.
|
||||
func (h *Hub) HandleWebSocketWithAuthorization(w http.ResponseWriter, r *http.Request, authorize func() bool) {
|
||||
log.Info().
|
||||
Str("origin", r.Header.Get("Origin")).
|
||||
Str("host", r.Host).
|
||||
@@ -1150,9 +1160,10 @@ func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
conn: conn,
|
||||
orgID: orgID,
|
||||
// Keep buffer bounded to avoid holding large state snapshots indefinitely if a client stalls.
|
||||
send: make(chan []byte, 128),
|
||||
id: clientID,
|
||||
lastPing: time.Now(),
|
||||
send: make(chan []byte, 128),
|
||||
id: clientID,
|
||||
lastPing: time.Now(),
|
||||
authorizeWrite: authorize,
|
||||
}
|
||||
// This must be captured from the upgrade URL before registration: initial
|
||||
// state construction begins as soon as the hub accepts the client.
|
||||
@@ -1946,7 +1957,20 @@ func (c *Client) readPump() {
|
||||
}
|
||||
}
|
||||
|
||||
// writePump handles outgoing messages to the client
|
||||
// allowWrite checks current authority without disclosing authentication detail.
|
||||
func (c *Client) allowWrite() bool {
|
||||
if c.authorizeWrite == nil || c.authorizeWrite() {
|
||||
return true
|
||||
}
|
||||
// Never send an HTTP error or queued data after authority ends. The fixed
|
||||
// policy close is understood by the existing frontend authentication path.
|
||||
_ = c.conn.WriteControl(websocket.CloseMessage,
|
||||
websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "Monitoring access ended"),
|
||||
time.Now().Add(10*time.Second))
|
||||
return false
|
||||
}
|
||||
|
||||
// writePump handles outgoing messages to the client.
|
||||
func (c *Client) writePump() {
|
||||
// Maximum consecutive write failures before disconnecting.
|
||||
// This provides graceful degradation for slow clients.
|
||||
@@ -1981,6 +2005,9 @@ func (c *Client) writePump() {
|
||||
}
|
||||
return
|
||||
}
|
||||
if !c.allowWrite() {
|
||||
return
|
||||
}
|
||||
|
||||
// Send the primary message
|
||||
if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {
|
||||
@@ -2012,7 +2039,10 @@ func (c *Client) writePump() {
|
||||
flushLoop:
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case msg := <-c.send:
|
||||
case msg, ok := <-c.send:
|
||||
if !ok || !c.allowWrite() {
|
||||
return
|
||||
}
|
||||
if err := c.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
|
||||
log.Warn().Err(err).Str("client", c.id).Int("msgSize", len(msg)).Msg("failed to flush queued message")
|
||||
// Don't disconnect on queued message failure, just break the flush loop
|
||||
@@ -2024,6 +2054,9 @@ func (c *Client) writePump() {
|
||||
}
|
||||
|
||||
case <-ticker.C:
|
||||
if !c.allowWrite() {
|
||||
return
|
||||
}
|
||||
if err := c.conn.SetWriteDeadline(time.Now().Add(pingDeadline)); err != nil {
|
||||
log.Warn().Err(err).Str("client", c.id).Msg("failed to set write deadline for ping")
|
||||
}
|
||||
|
||||
@@ -2,9 +2,12 @@ package websocket
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -1471,3 +1474,85 @@ func TestHubInstanceEventsReachAllTenants(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Queue all frames before starting the real writer. Revalidation only around
|
||||
// the outer select would admit the second/third frame through its flush loop.
|
||||
func TestClientWriterRevalidatesEveryQueuedFrame(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
done := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
defer close(done)
|
||||
conn, err := (&gorillawebsocket.Upgrader{}).Upgrade(w, req, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
client := &Client{conn: conn, send: make(chan []byte, 3), authorizeWrite: func() bool {
|
||||
return calls.Add(1) == 1
|
||||
}}
|
||||
client.send <- []byte("admitted-frame")
|
||||
client.send <- []byte("queued-after-withdrawal-1")
|
||||
client.send <- []byte("queued-after-withdrawal-2")
|
||||
client.writePump()
|
||||
}))
|
||||
defer server.Close()
|
||||
conn, _, err := gorillawebsocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if err := conn.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, first, err := conn.ReadMessage()
|
||||
if err != nil || string(first) != "admitted-frame" {
|
||||
t.Fatalf("first frame = %q, %v", first, err)
|
||||
}
|
||||
_, second, err := conn.ReadMessage()
|
||||
var closed *gorillawebsocket.CloseError
|
||||
if !errors.As(err, &closed) || closed.Code != gorillawebsocket.ClosePolicyViolation || closed.Text != "Monitoring access ended" {
|
||||
t.Fatalf("queued write after withdrawal = %q, %v", second, err)
|
||||
}
|
||||
<-done
|
||||
if calls.Load() != 2 {
|
||||
t.Fatalf("authorization calls = %d, want one for each attempted data frame", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientWriterRevalidatesIdleConnection(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
done := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
defer close(done)
|
||||
conn, err := (&gorillawebsocket.Upgrader{}).Upgrade(w, req, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
client := &Client{conn: conn, send: make(chan []byte), authorizeWrite: func() bool {
|
||||
calls.Add(1)
|
||||
return false
|
||||
}}
|
||||
// No data or inbound request triggers this writer: its actual existing
|
||||
// 30-second ping must revalidate before sending any keepalive.
|
||||
client.writePump()
|
||||
}))
|
||||
defer server.Close()
|
||||
conn, _, err := gorillawebsocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if err := conn.SetReadDeadline(time.Now().Add(45 * time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, body, err := conn.ReadMessage()
|
||||
var closed *gorillawebsocket.CloseError
|
||||
if !errors.As(err, &closed) || closed.Code != gorillawebsocket.ClosePolicyViolation || closed.Text != "Monitoring access ended" {
|
||||
t.Fatalf("idle withdrawal = %q, %v", body, err)
|
||||
}
|
||||
<-done
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("idle authorization calls = %d, want 1", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user