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
End confidential reads with their admitted browser session
pulse-triage[bot]35780acb0a1d
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex d4289ca7ee..bf577a95d9 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -10808,3 +10808,12 @@ HTTP delivery before any router exists for default and tenant paths, savedpublic URL precedence and deployment lock, and a tenant grant that cannot override installation revocation.`TestNewRejectsUnreadableNotificationPolicyBeforeQueueCreation` covers corruptsettings and invalid CIDRs without creating queue storage.++### Read lifetime after session logout++The existing protected API reads retain actual admitted browser-session+identity and refuse later disclosure after logout, invalidation, expiry or+replacement. Session withdrawal does not cancel independent agents, updates,+deployments, backups or legacy executions, nor prove original recovery.+`TestContractSessionReadLogoutBoundary` covers persisted logout and native+HTTP/WS refusal; the API contract describes the credential and idle boundaries.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 5292d733f4..2cc02cdc3d 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -133,8 +133,9 @@ normally; a legitimate replacement identity may reconnect.The shared validator returns detached authority without changing the originalHTTP 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.+stale or global inventory. Proxy admission, wanted monitoring reads after+execute-scope removal, other subscribers and canonical data are unchanged.+Browser-session withdrawal follows the session read-lifetime contract below.The existing frontend policy-close path returns to sign-in rather than silentlyretrying withdrawn credentials. No route, token grant or event/history sourceis added, and source/browser proof is not installed recovery or publication.@@ -13485,3 +13486,35 @@ synthetic credentials and preserved live data. `log_bundle_test.go` coversvalue grammars, detached projections, log fallbacks, runtime identity and raceownership. Consuming browser evidence exercises the unchanged download controlwith the exact synthetic native ZIP; it is not installed/customer recovery.++### Logged-out sessions cannot retain confidential live reads++Successful route authentication records the exact selected browser session in+server-only request context. The existing protected WebSocket, agent-event,+System Logs, progress and Assistant stream/result boundaries retain that+session's store, creation identity, principal and recovery kind. Each protected+write (and existing idle recheck) refuses a deleted, expired, replaced or+rebound session. Reads never extend session expiry, re-authenticate with a+fallback credential or refresh an identity provider. Recovery reads retain their+original direct-loopback/IP binding. Proxy/basic/development admission and+explicit-token precedence are unchanged; an ambient cookie or response header+cannot establish session authority.++Before a synchronous result commits, session withdrawal returns generic `401`+and withholds handler-specific headers; an admitted stream ends without new+private data or an appended HTTP error. Monitoring WebSocket uses its existing+`1008`/`Monitoring access ended` close, so its current web consumer returns to+sign-in; System Logs observes EOF and a denied reconnect, not live monitoring.+An already-admitted write can be in flight. This does not erase previously+received data, cancel independent jobs/legacy executions, introduce dynamic+role-policy rechecks or qualify installed/identity-provider recovery. Chat+retains its existing request-bound work lifetime.++`session_read_authority_test.go` covers detached identity, secure-cookie choice,+expiry without sliding extension, replacement, recovery/store withdrawal,+credential precedence and idle/result closure. `session_read_logout_test.go`+and the native Assistant/Logs/event cases exercise real persisted logout and+independent sessions. `TestContractSessionReadLogoutBoundary` asserts native+HTTP/WS logout, private-line withholding and fresh denial, optionally exporting+safe wire evidence for the existing browser consumers; the browser-only fixture+is retained evidence, not product source.diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 8c4ee5f6c4..d59e390469 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -9213,3 +9213,12 @@ settings remain live and unchanged. This is not a backup, credential recovery,agent/guest probe or installed recovery. The normal HTTP contract`TestContractSupportBundleCredentialBoundary` and `log_bundle_test.go` cover thesummary, scope denials, state preservation and configured-file/buffer fallbacks.++### Session read withdrawal is not job cancellation++The existing protected API reads retain actual admitted browser-session+identity and refuse later disclosure after logout, invalidation, expiry or+replacement. Session withdrawal does not cancel independent agents, updates,+deployments, backups or legacy executions, nor prove original recovery.+`TestContractSessionReadLogoutBoundary` covers persisted logout and native+HTTP/WS refusal; the API contract describes the credential and idle boundaries.diff --git a/internal/api/agent_events_auth.go b/internal/api/agent_events_auth.goindex 693c19ef97..83166c569a 100644--- a/internal/api/agent_events_auth.go+++ b/internal/api/agent_events_auth.go@@ -12,12 +12,12 @@ func (r *Router) handleAgentEvents(w http.ResponseWriter, req *http.Request) {// agentEventTokenRevalidator keeps a long-lived token stream bound to its// admitted credential and organization, not its connection-time snapshot.-// Session/proxy authentication is unchanged. The callback runs on the stream+// 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 {- return nil+ return sessionReadRevalidator(req)}admittedContext := req.Context()return func() bool {diff --git a/internal/api/auth.go b/internal/api/auth.goindex 904d960641..66e00440e0 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -715,6 +715,11 @@ func snapshotLocalAuthCredentialsLocked(cfg *config.Config) (string, string) {}func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, writeDefaultFailure bool) bool {+ // Only the credential selected by this authentication attempt may own a+ // long-lived read. A later proxy/token/basic admission must not inherit an+ // earlier session marker if middleware checks this request again.+ *r = *r.WithContext(context.WithValue(r.Context(), sessionReadAdmissionKey{}, (*sessionReadAdmission)(nil)))+// Dev mode bypass for all auth (disabled by default)if adminBypassAppliesToRequest(r) {if w != nil {@@ -799,6 +804,7 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, writesession := GetSessionStore().GetSession(cookie.Value)if session != nil && session.RecoveryBypass {if requestMatchesRecoverySession(r, session) && ValidateAndExtendSession(cookie.Value) {+ attachSessionReadAdmission(r, cookie.Value, session)if session.Username != "" {w.Header().Set("X-Authenticated-User", session.Username)}@@ -812,6 +818,7 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, writeStr("session_ip", session.IP).Msg("Rejected recovery session outside direct loopback binding")} else if ValidateAndExtendSession(cookie.Value) {+ attachSessionReadAdmission(r, cookie.Value, session)username := GetSessionUsername(cookie.Value)if session != nil && hasEnabledSSOProvidersForAuth(cfg) {if shouldRefreshOIDCSessionToken(time.Now(), session) {diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 7319730758..17e954a68a 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -29014,3 +29014,9 @@ func TestContract_AssistantStreamDeadlineSurvivesAPIWrappers(t *testing.T) {func TestContract_AssistantJSONWithdrawAfterPersistedTokenDelete(t *testing.T) {assistantJSONWithdrawAfterPersistedTokenDelete(t)}++// Successful persisted logout withdraws already-admitted System Logs and+// monitoring WebSocket readers as well as their fresh reconnects.+func TestContractSessionReadLogoutBoundary(t *testing.T) {+ sessionReadBrowserEvidence(t)+}diff --git a/internal/api/log_handlers.go b/internal/api/log_handlers.goindex 98035f1f04..c2d28a21ed 100644--- a/internal/api/log_handlers.go+++ b/internal/api/log_handlers.go@@ -32,10 +32,11 @@ func NewLogHandlers(cfg *config.Config, persistence *config.ConfigPersistence) *// HandleStreamLogs streams logs using SSE (Server-Sent Events)func (h *LogHandlers) HandleStreamLogs(w http.ResponseWriter, r *http.Request) {revalidate := tokenStreamSnapshotRevalidator(h.config, r, config.ScopeSettingsRead)+ sessionAllowed := sessionReadRevalidator(r)allowed := func() bool {if revalidate == nil {- // Existing browser-session/proxy admission remains with the route.- return true+ // Other credential admission remains with the route.+ return sessionAllowed == nil || sessionAllowed()}current, ok := revalidate()return ok && tokenActsForInstance(current)@@ -71,10 +72,10 @@ func (h *LogHandlers) HandleStreamLogs(w http.ResponseWriter, r *http.Request) {flusher.Flush()notify := r.Context().Done()- // End an idle withdrawn token reader too, without generating log entries,- // writing keepalive frames or changing session/proxy stream behaviour.+ // End an idle withdrawn token/session reader too, without generating log+ // entries or writing keepalive frames.var recheck <-chan time.Time- if revalidate != nil {+ if revalidate != nil || sessionAllowed != nil {ticker := time.NewTicker(15 * time.Second)defer ticker.Stop()recheck = ticker.Cdiff --git a/internal/api/session_read_authority.go b/internal/api/session_read_authority.gonew file mode 100644index 0000000000..233a57b381--- /dev/null+++ b/internal/api/session_read_authority.go@@ -0,0 +1,63 @@+package api++import (+ "context"+ "net/http"+ "time"+)++type sessionReadAdmissionKey struct{}++// sessionReadAdmission records actual successful session authentication, not+// the presence of an ambient cookie or a mutable response header. Other+// credentials retain their existing precedence and cannot fall back to a+// new session after admission. Never log or serialize this private identity.+type sessionReadAdmission struct {+ store *SessionStore+ token string+ createdAt time.Time+ username string+ recovery bool+ valid bool+}++func attachSessionReadAdmission(req *http.Request, token string, session *SessionData) {+ admission := &sessionReadAdmission{store: GetSessionStore(), token: token}+ if session != nil {+ admission.createdAt = session.CreatedAt+ admission.username = session.Username+ admission.recovery = session.RecoveryBypass+ admission.valid = true+ }+ *req = *req.WithContext(context.WithValue(req.Context(), sessionReadAdmissionKey{}, admission))+}++// sessionReadRevalidator retains only the admitted local session's validity,+// principal and instance identity. It does not extend expiry, refresh an IdP,+// rerun authentication, change tenant/admin policy or cancel independent work.+// A nil callback means this request was not authenticated by a session.+func sessionReadRevalidator(req *http.Request) func() bool {+ marker, _ := req.Context().Value(sessionReadAdmissionKey{}).(*sessionReadAdmission)+ if marker == nil {+ return nil+ }+ admitted := *marker+ // A recovery binding is evaluated against the original immutable request,+ // not a request that returning middleware may still be observing.+ original := req.Clone(req.Context())+ return func() bool {+ sessionStoreMu.Lock()+ currentStore := sessionStore+ sessionStoreMu.Unlock()+ if !admitted.valid || currentStore == nil || currentStore != admitted.store {+ return false+ }+ current := currentStore.GetSession(admitted.token)+ if current == nil || !time.Now().Before(current.ExpiresAt) ||+ !current.CreatedAt.Equal(admitted.createdAt) || current.Username != admitted.username ||+ current.RecoveryBypass != admitted.recovery {+ return false+ }+ return !current.RecoveryBypass || requestMatchesRecoverySession(original, current)+ }+}diff --git a/internal/api/session_read_authority_test.go b/internal/api/session_read_authority_test.gonew file mode 100644index 0000000000..2428834507--- /dev/null+++ b/internal/api/session_read_authority_test.go@@ -0,0 +1,250 @@+package api++import (+ "context"+ "crypto/tls"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/logging"+)++func mutateReadSession(raw, change string) {+ store := GetSessionStore()+ if change == "invalidated" {+ store.InvalidateSession(raw)+ return+ }+ if change == "replaced" {+ prior := store.GetSession(raw)+ store.CreateSession(raw, time.Hour, "fixture", "127.0.0.1", prior.Username)+ return+ }+ store.mu.Lock()+ defer store.mu.Unlock()+ session := store.sessions[sessionHash(raw)]+ switch change {+ case "expired":+ session.ExpiresAt = time.Now().Add(-time.Second)+ case "principal":+ session.Username = "other-operator"+ case "recovery":+ session.RecoveryBypass = !session.RecoveryBypass+ case "recovery_binding":+ session.IP = "192.0.2.1"+ }+}++func TestSessionReadSnapshot(t *testing.T) {+ for _, cookieName := range []string{cookieNameSession, cookieNameSessionSecure} {+ for _, change := range []string{"invalidated", "expired", "principal", "replaced", "recovery"} {+ t.Run(cookieName+"/"+change, func(t *testing.T) {+ InitSessionStore(t.TempDir())+ const raw = "synthetic-read-snapshot"+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1/api/state", nil)+ if cookieName == cookieNameSessionSecure {+ req.TLS = &tls.ConnectionState{}+ }+ req.AddCookie(&http.Cookie{Name: cookieName, Value: raw})+ if !CheckAuth(&config.Config{}, httptest.NewRecorder(), req) {+ t.Fatal("session admission failed")+ }+ allowed := sessionReadRevalidator(req)+ before := GetSessionStore().GetSession(raw).ExpiresAt+ if allowed == nil || !allowed() {+ t.Fatal("missing admitted session")+ }+ if !GetSessionStore().GetSession(raw).ExpiresAt.Equal(before) {+ t.Fatal("read extended session expiry")+ }+ // Returning middleware/header changes cannot retarget the reader.+ req.Header.Set("Cookie", cookieName+"=different")+ mutateReadSession(raw, change)+ if allowed() {+ t.Fatal("old read retained changed session authority")+ }+ })+ }+ }+}++func TestSessionReadAdmissionPrecedence(t *testing.T) {+ InitSessionStore(t.TempDir())+ const raw = "synthetic-read-precedence"+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1/api/state", nil)+ req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})+ // An unselected cookie and a mutable response header are not authority.+ if sessionReadRevalidator(req) != nil {+ t.Fatal("ambient cookie became admission")+ }+ writer := httptest.NewRecorder()+ writer.Header().Set("X-Auth-Method", "session")+ if sessionReadRevalidator(req) != nil {+ t.Fatal("response header became admission")+ }+ cfg := newTestConfigWithTokens(t, newTokenRecord(t, logStreamControl, []string{config.ScopeWildcard}, nil))+ if !CheckAuth(cfg, writer, req) || sessionReadRevalidator(req) == nil {+ t.Fatal("actual session missing")+ }+ req.Header.Set("X-API-Token", logStreamControl)+ if !CheckAuth(cfg, writer, req) || sessionReadRevalidator(req) != nil {+ t.Fatal("explicit token inherited session marker")+ }+ req.Header.Del("X-API-Token")+ cfg.ProxyAuthSecret = "synthetic-read-proxy-secret"+ cfg.ProxyAuthUserHeader = "X-Remote-User"+ req.Header.Set("X-Proxy-Secret", cfg.ProxyAuthSecret)+ req.Header.Set("X-Remote-User", "proxy-user")+ if !CheckAuth(cfg, writer, req) || sessionReadRevalidator(req) != nil {+ t.Fatal("proxy admission inherited session marker")+ }+ // Failed auth also clears a previous marker; no fallback is created.+ req.Header.Del("X-Proxy-Secret")+ req.Header.Set("X-API-Token", "invalid")+ if CheckAuth(cfg, writer, req) || sessionReadRevalidator(req) != nil {+ t.Fatal("failed auth retained session marker")+ }+}++func TestSessionReadStoreReplacementAndRecoveryBinding(t *testing.T) {+ for _, change := range []string{"store", "recovery_binding"} {+ t.Run(change, func(t *testing.T) {+ InitSessionStore(t.TempDir())+ const raw = "synthetic-recovery-read"+ GetSessionStore().CreateRecoverySession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1/api/state", nil)+ req.RemoteAddr = "127.0.0.1:1234"+ req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})+ if !CheckAuth(&config.Config{}, httptest.NewRecorder(), req) {+ t.Fatal("recovery admission failed")+ }+ allowed := sessionReadRevalidator(req)+ if allowed == nil || !allowed() {+ t.Fatal("missing recovery admission")+ }+ if change == "store" {+ InitSessionStore(t.TempDir())+ } else {+ mutateReadSession(raw, change)+ }+ if allowed() {+ t.Fatal("recovery retained replaced store/binding")+ }+ })+ }+}++func TestSessionReadLogoutLogsAndEvents(t *testing.T) {+ t.Run("logs", func(t *testing.T) {+ _, cfg, server := newLogStreamRouter(t)+ cfg.AuthUser = "operator"+ const primaryRaw, controlRaw = "synthetic-logout-logs", "synthetic-logout-logs-control"+ for _, raw := range []string{primaryRaw, controlRaw} {+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ t.Cleanup(func() { GetSessionStore().DeleteSession(raw) })+ }+ primary := openLogStream(t, server, primaryRaw, "session")+ control := openLogStream(t, server, controlRaw, "session")+ logoutReadSession(t, server.URL, primaryRaw)+ const marker = "private-log-after-session-logout"+ logging.GetBroadcaster().Write([]byte(marker))+ readLogStreamMarker(t, control, marker)+ wantLogStreamClosed(t, primary, marker)+ })+ t.Run("events", func(t *testing.T) {+ router, _, server := newAgentLifecycleRouter(t, time.Hour)+ const primaryRaw, controlRaw = "synthetic-logout-events", "synthetic-logout-events-control"+ for _, raw := range []string{primaryRaw, controlRaw} {+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ t.Cleanup(func() { GetSessionStore().DeleteSession(raw) })+ }+ primary := openAgentLifecycleStream(t, server, primaryRaw, "session")+ control := openAgentLifecycleStream(t, server, controlRaw, "session")+ logoutReadSession(t, server.URL, primaryRaw)+ router.agentEventBroadcaster.PublishActionCompletedRecord(agentDisclosureRecord(t, false))+ _ = control.next(t)+ primary.wantClosed(t)+ })+}++func TestSessionReadLogoutAssistantStreams(t *testing.T) {+ for _, kind := range []string{"execute", "investigate-alert", "chat"} {+ t.Run(kind, func(t *testing.T) {+ f := newAssistantStreamFixture(t, kind, []string{assistantScope(kind)})+ const primaryRaw, controlRaw = "synthetic-logout-assistant", "synthetic-logout-assistant-control"+ for _, raw := range []string{primaryRaw, controlRaw} {+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser)+ t.Cleanup(func() { GetSessionStore().DeleteSession(raw) })+ }+ primary := f.open(t, "primary", primaryRaw, "session")+ control := f.open(t, "control", controlRaw, "session")+ logoutReadSession(t, f.server.URL, primaryRaw)+ f.primary.unblock()+ f.control.unblock()+ readAssistantResult(t, primary, false)+ readAssistantResult(t, control, true)+ if kind != "chat" && f.primary.cancelled.Load() {+ t.Fatal("logout cancelled independent legacy work")+ }+ })+ }+}++func TestSessionReadIdleExpiry(t *testing.T) {+ InitSessionStore(t.TempDir())+ const raw = "synthetic-idle-session"+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1/api/progress", nil)+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ req = req.WithContext(ctx)+ req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})+ if !CheckAuth(&config.Config{}, httptest.NewRecorder(), req) {+ t.Fatal("session admission failed")+ }+ entered, finished := make(chan struct{}), make(chan struct{})+ handler := retainTokenStreamAuthority(&config.Config{}, config.ScopeMonitoringRead, false, func(w http.ResponseWriter, req *http.Request) {+ w.WriteHeader(http.StatusOK)+ w.(http.Flusher).Flush()+ close(entered)+ <-req.Context().Done()+ _, err := io.WriteString(w, "private-idle-session")+ if err == nil {+ t.Error("withdrawn idle writer accepted output")+ }+ })+ go func() { defer close(finished); handler(httptest.NewRecorder(), req) }()+ <-entered+ mutateReadSession(raw, "expired")+ select {+ case <-finished:+ case <-time.After(18 * time.Second):+ t.Fatal("idle session read exceeded bounded recheck")+ }+}++func TestSessionReadJSONBodylessExpiry(t *testing.T) {+ InitSessionStore(t.TempDir())+ const raw = "synthetic-bodyless-session"+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1/api/result", nil)+ req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})+ if !CheckAuth(&config.Config{}, httptest.NewRecorder(), req) {+ t.Fatal("session admission failed")+ }+ recorder := httptest.NewRecorder()+ retainTokenResponseAuthority(&config.Config{}, config.ScopeAIExecute, true, func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("X-Private", "private-header")+ mutateReadSession(raw, "expired")+ })(recorder, req)+ if recorder.Code != http.StatusUnauthorized || recorder.Header().Get("X-Private") != "" || strings.Contains(recorder.Body.String(), "private") {+ t.Fatalf("bodyless withdrawn result: %d %s", recorder.Code, recorder.Body)+ }+}diff --git a/internal/api/session_read_browser_test.go b/internal/api/session_read_browser_test.gonew file mode 100644index 0000000000..5b2023117b--- /dev/null+++ b/internal/api/session_read_browser_test.go@@ -0,0 +1,92 @@+package api++import (+ "bufio"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "os"+ "testing"+ "time"++ gorillaws "github.com/gorilla/websocket"+ "github.com/rcourtman/pulse-go-rewrite/internal/logging"+ pulsews "github.com/rcourtman/pulse-go-rewrite/internal/websocket"+)++// This real registered HTTP/WS journey is also a safe, optional wire-evidence+// exporter for the existing System Logs and WebSocket browser consumers. The+// UI fixture itself is evidence only, never a repository test or product route.+func sessionReadBrowserEvidence(t *testing.T) {+ t.Helper()+ _, cfg, server, hub := newMonitoringWebSocketRouter(t)+ cfg.AuthUser = "operator"+ const raw = "synthetic-browser-session-read"+ const before = "synthetic permitted line before session logout"+ const forbidden = "synthetic forbidden line after session logout"+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ t.Cleanup(func() { GetSessionStore().DeleteSession(raw) })+ socket := openMonitoringWebSocket(t, server, raw, "session")+ logging.GetBroadcaster().Write([]byte(before))+ req, _ := http.NewRequest(http.MethodGet, server.URL+"/api/logs/stream", nil)+ req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})+ response, err := server.Client().Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer response.Body.Close()+ if response.StatusCode != http.StatusOK {+ t.Fatalf("log admission = %d", response.StatusCode)+ }+ reader := bufio.NewReader(response.Body)+ readLogStreamMarker(t, reader, before)+ logoutReadSession(t, server.URL, raw)+ logging.GetBroadcaster().Write([]byte(forbidden))+ wantLogStreamClosed(t, reader, forbidden)+ hub.BroadcastMessageToTenant("default", pulsews.Message{Type: "notification", Data: forbidden})+ _ = socket.SetReadDeadline(time.Now().Add(5 * time.Second))+ _, body, err := socket.ReadMessage()+ var closed *gorillaws.CloseError+ if !errors.As(err, &closed) || closed.Code != gorillaws.ClosePolicyViolation || closed.Text != "Monitoring access ended" {+ t.Fatalf("session socket disclosed or closed unexpectedly: %s %v", body, err)+ }+ fresh, _ := http.NewRequest(http.MethodGet, server.URL+"/api/logs/stream", nil)+ fresh.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})+ denied, err := server.Client().Do(fresh)+ if err != nil {+ t.Fatal(err)+ }+ defer denied.Body.Close()+ deniedBody, err := io.ReadAll(denied.Body)+ if err != nil || denied.StatusCode != http.StatusUnauthorized {+ t.Fatalf("reconnect = %d %s %v", denied.StatusCode, deniedBody, err)+ }+ securityResponse, err := server.Client().Get(server.URL + "/api/security/status")+ if err != nil {+ t.Fatal(err)+ }+ defer securityResponse.Body.Close()+ var securityStatus map[string]any+ if err := json.NewDecoder(securityResponse.Body).Decode(&securityStatus); err != nil || securityResponse.StatusCode != http.StatusOK || securityStatus["hasAuthentication"] != true {+ t.Fatalf("post-logout security status: %v %v", securityStatus, err)+ }+ evidence := map[string]any{+ "scope": "Synthetic local full-Router HTTP/WebSocket producer and persisted logout, not installed/native-IdP acceptance",+ "logout": map[string]any{"status": http.StatusOK, "persisted_session_absent": true},+ "logs": map[string]any{"admission_status": response.StatusCode, "content_type": response.Header.Get("Content-Type"), "permitted_line": before, "after_logout_eof": true, "forbidden_line": forbidden, "reconnect_status": denied.StatusCode, "reconnect_body": string(deniedBody)},+ "websocket": map[string]any{"close_code": closed.Code, "close_reason": closed.Text},+ }+ if directory := os.Getenv("PULSE_SESSION_READ_EVIDENCE"); directory != "" {+ if err := os.MkdirAll(directory, 0700); err != nil {+ t.Fatal(err)+ }+ data, err := json.MarshalIndent(evidence, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(directory+"/session-read.json", append(data, '\n'), 0600); err != nil {+ t.Fatal(err)+ }+ }+}diff --git a/internal/api/session_read_logout_test.go b/internal/api/session_read_logout_test.gonew file mode 100644index 0000000000..d07de6e323--- /dev/null+++ b/internal/api/session_read_logout_test.go@@ -0,0 +1,85 @@+package api++import (+ "io"+ "net/http"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ pulsews "github.com/rcourtman/pulse-go-rewrite/internal/websocket"+)++// Use the actual CSRF-protected logout and persisted session store, not just+// an in-memory fixture deletion. This must not invalidate another session.+func logoutReadSession(t *testing.T, serverURL, raw string) {+ t.Helper()+ req, err := http.NewRequest(http.MethodPost, serverURL+"/api/logout", nil)+ if err != nil {+ t.Fatal(err)+ }+ req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})+ req.Header.Set("X-CSRF-Token", generateCSRFToken(raw))+ response, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer response.Body.Close()+ body, err := io.ReadAll(response.Body)+ if err != nil || response.StatusCode != http.StatusOK || ValidateSession(raw) {+ t.Fatalf("logout failed: %d %s %v", response.StatusCode, body, err)+ }+ persisted := NewSessionStore(GetSessionStore().dataPath)+ defer persisted.Shutdown()+ if persisted.GetSession(raw) != nil {+ t.Fatal("logout left persisted session authority")+ }+}++func TestSessionReadLogoutWebSocket(t *testing.T) {+ _, _, server, hub := newMonitoringWebSocketRouter(t)+ const primaryRaw, controlRaw = "synthetic-logout-socket", "synthetic-logout-socket-control"+ for _, raw := range []string{primaryRaw, controlRaw} {+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", "operator")+ t.Cleanup(func() { GetSessionStore().DeleteSession(raw) })+ }+ primary := openMonitoringWebSocket(t, server, primaryRaw, "session")+ control := openMonitoringWebSocket(t, server, controlRaw, "session")+ logoutReadSession(t, server.URL, primaryRaw)+ hub.BroadcastMessageToTenant("default", pulsews.Message{Type: "notification", Data: "private-after-logout"})+ if got := nextMonitoringWebSocketFrame(t, control); got.Data != "private-after-logout" {+ t.Fatalf("independent reader: %+v", got)+ }+ wantMonitoringWebSocketClosed(t, primary)+}++func TestSessionReadLogoutJSON(t *testing.T) {+ for _, kind := range []string{"execute", "kubernetes"} {+ t.Run(kind, func(t *testing.T) {+ f := newAssistantJSONFixture(t, kind, []string{config.ScopeAIExecute})+ const primaryRaw, controlRaw = "synthetic-logout-json", "synthetic-logout-json-control"+ for _, raw := range []string{primaryRaw, controlRaw} {+ GetSessionStore().CreateSession(raw, time.Hour, "fixture", "127.0.0.1", f.router.config.AuthUser)+ t.Cleanup(func() { GetSessionStore().DeleteSession(raw) })+ }+ primary := f.begin(t, "primary", primaryRaw, "session")+ control := f.begin(t, "control", controlRaw, "session")+ logoutReadSession(t, f.server.URL, primaryRaw)+ fresh, err := f.server.Client().Do(f.request(t, "primary", primaryRaw, "session"))+ if err != nil {+ t.Fatal(err)+ }+ fresh.Body.Close()+ if fresh.StatusCode != http.StatusUnauthorized || f.primary.calls.Load() != 1 {+ t.Fatalf("fresh logout admission = %d calls=%d", fresh.StatusCode, f.primary.calls.Load())+ }+ f.primary.unblock()+ f.control.unblock()+ readAssistantJSONResult(t, control, true)+ readAssistantJSONResult(t, primary, false)+ if f.primary.cancelled.Load() {+ t.Fatal("result refusal cancelled admitted work")+ }+ })+ }+}diff --git a/internal/api/token_response_authority.go b/internal/api/token_response_authority.goindex 4dac33a43f..b5fb5f753f 100644--- a/internal/api/token_response_authority.go+++ b/internal/api/token_response_authority.go@@ -15,12 +15,16 @@ import (func retainTokenResponseAuthority(cfg *config.Config, scope string, instanceAdmin bool, next http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {revalidate := tokenStreamSnapshotRevalidator(cfg, r, scope)- if revalidate == nil {- // No new authentication policy for session/proxy requests.+ sessionAllowed := sessionReadRevalidator(r)+ if revalidate == nil && sessionAllowed == nil {+ // No new authentication policy for proxy/basic/bypass requests.next(w, r)return}allowed := func() bool {+ if revalidate == nil {+ return sessionAllowed()+ }current, ok := revalidate()return ok && (!instanceAdmin || tokenActsForInstance(current))}diff --git a/internal/api/token_stream_lifetime.go b/internal/api/token_stream_lifetime.goindex 55b1fc4bc4..313f56159c 100644--- a/internal/api/token_stream_lifetime.go+++ b/internal/api/token_stream_lifetime.go@@ -13,7 +13,8 @@ import (// retainTokenStreamAuthority runs AFTER the route's auth/admin/scope gates.// Recheck the admitted credential at the actual writer, not just when an event// is produced: replay and queued broadcasts can otherwise disclose after a-// credential is withdrawn. Session/proxy admission is intentionally unchanged.+// credential is withdrawn. Session withdrawal is checked too; other+// authentication policy stays with the route.func retainTokenStreamAuthority(cfg *config.Config, scope string, instanceAdmin bool, next http.HandlerFunc) http.HandlerFunc {return retainTokenStreamAuthorityForScopes(cfg, []string{scope}, instanceAdmin, next)}@@ -21,11 +22,12 @@ func retainTokenStreamAuthority(cfg *config.Config, scope string, instanceAdminfunc retainTokenStreamAuthorityForScopes(cfg *config.Config, scopes []string, instanceAdmin bool, next http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {revalidate := tokenStreamSnapshotRevalidator(cfg, r, scopes...)+ sessionAllowed := sessionReadRevalidator(r)allowed := func() bool {if revalidate == nil {- // Session/proxy admission stays with the route. They still- // need the same join-before-return protection from async writes.- return true+ // Proxy/basic/bypass admission stays with the route. A+ // session read retains its exact admitted session instance.+ return sessionAllowed == nil || sessionAllowed()}current, ok := revalidate()return ok && (!instanceAdmin || tokenActsForInstance(current))@@ -62,10 +64,10 @@ func retainTokenStreamAuthorityForScopes(cfg *config.Config, scopes []string, in}}}- if revalidate != nil {+ if revalidate != nil || sessionAllowed != nil {go watch()} else {- // No new periodic authentication checks for session/proxy readers.+ // No new periodic authentication checks for other credentials.close(watchDone)}defer func() {diff --git a/internal/api/websocket_auth.go b/internal/api/websocket_auth.goindex ff6be156ea..16fbcd6010 100644--- a/internal/api/websocket_auth.go+++ b/internal/api/websocket_auth.go@@ -11,7 +11,7 @@ func monitoringWebSocketAuthorization(cfg *config.Config, req *http.Request) fun// request copy, not one its returning middleware may still be observing.revalidate := monitoringTokenSnapshotRevalidator(cfg, req.Clone(req.Context()))if revalidate == nil {- return nil+ return sessionReadRevalidator(req)}return func() bool {_, ok := revalidate()