Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Bound live-token stream refresh context ancestry

pulse-triage[bot]7c71db1fd5f1
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 7d17e5d95a..15a3b6420d 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -24,6 +24,13 @@ the current cached owner both before and after validation, never start a cold
runtime or fall back to a global duplicate after revocation/replacement.
Idle heartbeats also check authority; withdrawal releases the subscription.
+Each refreshed disclosure snapshot replaces a single context layer above the
+admitted request context, not above the previous refresh. Retained ancestry and
+token snapshots stay bounded per connection; cancellation, deadline, principal,
+organization and other admitted values remain intact. The ordinary
+`TestAgentEventTokenRefreshKeepsBoundedContext` streams repeated approval/action
+frames with changing scopes and proves bounded ancestry and cancellation cleanup.
+
The normal lifecycle tests cover removed/replaced owners, scope changes in a
replacement owner, an owner changing across validation and refusal of global
fallback. Real registered-route HTTP and shared MCP tests cover durable
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 626a22f4e8..8b15aa1044 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -31,6 +31,13 @@ No error body is appended to SSE and no event kind, route or grant is added;
reconnects use normal HTTP authentication/scope enforcement. Frames already
admitted before a concurrent withdrawal may still be in flight.
+Refreshing disclosure replaces one context layer rooted at the original admitted
+request; it does not accumulate earlier token snapshots or context ancestors.
+`TestAgentEventTokenRefreshKeepsBoundedContext` checks repeated actual SSE frames,
+live approval/action redaction, preserved context values/deadline and cancellation
+unsubscription for both token headers. Wire payloads and last-use updates are
+unchanged by this bounded-state correction.
+
`TestAgentEventTokenLifecycleDeleteThroughHTTP` in the route inventory executes
the actual persisted DELETE and rejects both continued delivery and reconnect.
`TestAgentEventTokenLifecycleRefreshesDisclosure` in the contract suite checks
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index f416d51034..0a94eaf582 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -28,6 +28,13 @@ Withdrawing only `ai:execute` keeps the permitted monitoring stream but redacts
the next approval/action payload using its current scopes. Canonical evidence
and other subscribers are not rewritten. Session/proxy behaviour is unchanged.
+The current disclosure snapshot is replaced over the original admitted context,
+never chained onto prior refreshes. This bounds per-stream retained snapshots
+without caching authority or losing original cancellation, deadline or identity
+context. `TestAgentEventTokenRefreshKeepsBoundedContext` checks repeated real
+approval/action frames with scope withdrawal/restoration and cancellation cleanup;
+the unchanged lifecycle suite retains current tenant-owner and revocation checks.
+
The normal `agent_events_auth_test.go`, route-inventory persisted-delete test
and contract disclosure test cover invalidation, independent subscribers and
the shared SSE-to-MCP consumer through real authenticated HTTP. Connection close
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 0ccfa988e8..b89bb53bba 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -30,6 +30,12 @@ expiry, invalid identity/principal/role or loss of organization/read authority
closes the stream without executing anything. Tenant-owner replacement cannot
retain a stale inventory or borrow a global duplicate credential.
+Disclosure refreshes replace a bounded context layer above the admitted request,
+not a growing chain of retained token snapshots. The normal repeated-frame
+`TestAgentEventTokenRefreshKeepsBoundedContext` verifies live redaction, unchanged
+canonical evidence and original cancellation cleanup; this is not a recovery or
+filesystem operation.
+
Normal lifecycle, real registered-route persisted deletion, contract disclosure
and shared MCP-consumer tests cover the boundary and unchanged canonical record.
No history source, retention, backup, thaw or filesystem operation is added.
diff --git a/internal/api/agent_events_auth.go b/internal/api/agent_events_auth.go
index 7e3b77a3dd..7bbc800eb6 100644
--- a/internal/api/agent_events_auth.go
+++ b/internal/api/agent_events_auth.go
@@ -24,6 +24,7 @@ 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 {
if !provided || raw == "" {
@@ -52,7 +53,12 @@ func agentEventTokenRevalidator(cfg *config.Config, req *http.Request) func() bo
}
// In particular, withdrawing ai:execute must redact the very next
// action/approval frame, even though monitoring:read still permits it.
- attachAPITokenRecord(req, current)
+ // 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
}
}
diff --git a/internal/api/agent_events_auth_test.go b/internal/api/agent_events_auth_test.go
index 849c2b33c0..9e3fd409c9 100644
--- a/internal/api/agent_events_auth_test.go
+++ b/internal/api/agent_events_auth_test.go
@@ -2,12 +2,14 @@ package api
import (
"bufio"
+ "bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
+ "reflect"
"strings"
"testing"
"time"
@@ -114,6 +116,137 @@ func newAgentLifecycleRouter(t *testing.T, heartbeat time.Duration) (*Router, *c
return router, cfg, server
}
+type agentEventRefreshWriter struct {
+ *httptest.ResponseRecorder
+ afterFlush func()
+}
+
+func (w *agentEventRefreshWriter) Flush() {
+ w.ResponseRecorder.Flush()
+ w.afterFlush()
+}
+
+// Exercise the actual stream's refresh/redaction loop, without timing or heap
+// thresholds. Each flush schedules exactly one next frame on the same goroutine;
+// the last cancels the original context. Inspect only the exported parent field
+// of WithValue's context to prove it cannot retain earlier refresh snapshots.
+func TestAgentEventTokenRefreshKeepsBoundedContext(t *testing.T) {
+ for _, transport := range []string{"header", "bearer"} {
+ t.Run(transport, func(t *testing.T) {
+ const orgID = "refresh-tenant"
+ token := newTokenRecord(t, agentEventLifecycleToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil)
+ token.OrgID = orgID
+ cfg := newTestConfigWithTokens(t, token)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ type requestMarker struct{}
+ ctx = context.WithValue(ctx, requestMarker{}, "admitted-value")
+ ctx = context.WithValue(ctx, OrgIDContextKey, orgID)
+ ctx = internalauth.WithUser(ctx, apiTokenAuthenticatedUser(&token))
+ req := httptest.NewRequest(http.MethodGet, "/api/agent/events", nil).WithContext(ctx)
+ if transport == "bearer" {
+ req.Header.Set("Authorization", "Bearer "+agentEventLifecycleToken)
+ } else {
+ req.Header.Set("X-API-Token", agentEventLifecycleToken)
+ }
+ attachAPITokenRecord(req, &token)
+ admittedContext := req.Context()
+ admittedToken := internalauth.GetAPIToken(admittedContext)
+ deadline, _ := admittedContext.Deadline()
+ broadcaster := NewAgentEventBroadcaster()
+ broadcaster.heartbeatInterval = time.Hour
+ router := &Router{config: cfg, agentEventBroadcaster: broadcaster}
+ record := agentDisclosureRecord(t, false)
+ before, err := json.Marshal(record)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const productFrames = 512
+ flushed := 0
+ restricted := false
+ writer := &agentEventRefreshWriter{ResponseRecorder: httptest.NewRecorder()}
+ writer.afterFlush = func() {
+ // WithValue must be one fresh layer over the original context,
+ // never over the layer created by the previous frame/heartbeat.
+ parent := reflect.ValueOf(req.Context()).Elem().FieldByName("Context")
+ if !parent.IsValid() || !parent.CanInterface() || parent.Interface() != admittedContext {
+ t.Fatalf("refresh %d retained a previous token context instead of the admitted context", flushed+1)
+ }
+ if req.Context().Done() != admittedContext.Done() || req.Context().Value(requestMarker{}) != "admitted-value" ||
+ GetOrgID(req.Context()) != orgID || internalauth.GetUser(req.Context()) != apiTokenAuthenticatedUser(&token) {
+ t.Fatal("refresh lost admitted cancellation, request value, organization or principal")
+ }
+ if got, ok := req.Context().Deadline(); !ok || !got.Equal(deadline) {
+ t.Fatal("refresh changed the admitted deadline")
+ }
+ snapshot := getAPITokenRecordFromRequest(req)
+ if snapshot == nil || snapshot.ID != token.ID || snapshot.HasScope(config.ScopeAIExecute) == restricted {
+ t.Fatal("refresh lost admitted identity or current disclosure scopes")
+ }
+ stream := &agentLifecycleStream{reader: bufio.NewReader(strings.NewReader(writer.Body.String()))}
+ event, err := stream.read()
+ if err != nil {
+ t.Fatal(err)
+ }
+ writer.Body.Reset()
+ if flushed == 0 {
+ if event.Kind != AgentEventStreamConnected {
+ t.Fatalf("first frame = %q, want connected", event.Kind)
+ }
+ } else if flushed%2 == 1 {
+ if event.Kind != AgentEventApprovalPending {
+ t.Fatalf("frame = %q, want approval", event.Kind)
+ }
+ var approval AgentEventApprovalPendingPayload
+ body, _ := json.Marshal(event.Payload)
+ if err := json.Unmarshal(body, &approval); err != nil {
+ t.Fatal(err)
+ }
+ if approval.CommandRedacted != restricted || (approval.Command == "") != restricted {
+ t.Fatal("approval did not use current disclosure scopes")
+ }
+ } else {
+ if event.Kind != AgentEventActionCompleted {
+ t.Fatalf("frame = %q, want action", event.Kind)
+ }
+ body, _ := json.Marshal(event)
+ assertAgentDisclosureWire(t, body, restricted)
+ }
+ if flushed == productFrames {
+ cancel()
+ return
+ }
+ // Change scopes before the next pair of approval/action frames.
+ restricted = (flushed/2)%2 == 1
+ config.Mu.Lock()
+ cfg.APITokens[0].Scopes = []string{config.ScopeMonitoringRead}
+ if !restricted {
+ cfg.APITokens[0].Scopes = append(cfg.APITokens[0].Scopes, config.ScopeAIExecute)
+ }
+ config.Mu.Unlock()
+ if flushed%2 == 0 {
+ broadcaster.PublishApprovalPending(AgentEventApprovalPendingPayload{ApprovalID: "refresh-approval", Command: agentPrivateDetail})
+ } else {
+ broadcaster.PublishActionCompletedRecord(record)
+ }
+ flushed++
+ }
+ router.handleAgentEvents(writer, req)
+ if flushed != productFrames || broadcaster.SubscriberCount() != 0 || req.Context().Err() != context.Canceled {
+ t.Fatalf("stream did not finish all frames and unsubscribe on original cancellation: frames=%d subscribers=%d err=%v", flushed, broadcaster.SubscriberCount(), req.Context().Err())
+ }
+ if !admittedToken.HasScope(config.ScopeAIExecute) {
+ t.Fatal("live refresh mutated the admitted token snapshot")
+ }
+ after, _ := json.Marshal(record)
+ if !bytes.Equal(before, after) {
+ t.Fatal("live redaction changed canonical evidence")
+ }
+ t.Logf("%d product frames: bounded context parent, live approval/action redaction and original cancellation verified", flushed)
+ })
+ }
+}
+
func TestAgentEventTokenLifecycleRejectsWithdrawnAuthority(t *testing.T) {
for _, transport := range []string{"header", "bearer"} {
for _, change := range []string{"revoked", "expired", "read_scope_removed", "org_rebound", "identity_replaced", "principal_replaced", "invalid_role"} {