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.

Revalidate API-token authority on agent event streams

pulse-triage[bot]3f2bca2aa2c7
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8ed9f46697..7d17e5d95a 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -15,6 +15,23 @@
## Purpose
+### Agent event subscriptions follow their current token inventory
+
+Before streaming each frame, API-token subscribers revalidate against the
+inventory that admitted them. Metadata normalization and last-use updates reuse
+authentication's exclusive lock and detached snapshot. Tenant streams resolve
+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.
+
+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
+revocation, idle expiry, scope reduction and independent unaffected subscribers.
+No enrolment, runtime action, token scope, recovery operation or event type is
+added. Session/proxy authentication retains its existing lifecycle.
+
+
### Public-URL token checks share authentication ownership
The pre-route public-URL authority check uses the existing locked token
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 2228db1611..626a22f4e8 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -21,6 +21,25 @@
## Purpose
+### Agent event streams retain live API-token authority
+
+The registered agent SSE route revalidates its admitted token before the
+connected frame, each visible product frame and each 15-second idle heartbeat.
+Revocation, expiry, loss of monitoring-read scope, changed identity/principal or
+loss of the selected organization closes the stream and releases its subscription.
+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.
+
+`TestAgentEventTokenLifecycleDeleteThroughHTTP` in the route inventory executes
+the actual persisted DELETE and rejects both continued delivery and reconnect.
+`TestAgentEventTokenLifecycleRefreshesDisclosure` in the contract suite checks
+live command-scope withdrawal, independent subscriber detail and unchanged
+canonical evidence. The normal lifecycle suite covers both token headers,
+idle expiry/revocation, tenant replacement and the shared real MCP consumer.
+Sessions/proxy authentication and existing event payload shapes stay unchanged.
+
+
### Public-URL token checks share authentication ownership
The pre-route public-URL authority check uses the existing locked token
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index faaacb3afe..f416d51034 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -18,6 +18,24 @@
## Purpose
+### Token withdrawal applies to existing agent streams
+
+A successful stream connection does not retain permanent API-token authority.
+The registered SSE handler refreshes a detached, live token snapshot before
+admitting each visible frame or idle heartbeat. Current expiry, runtime-role,
+monitoring-read, organization and admitted identity/principal checks apply.
+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 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
+adds no new event/error payload; it cannot retract a frame admitted before a
+concurrent withdrawal. This changes neither token grants nor administrator or
+private-authorizer recovery, and source proof is not installed recovery.
+
+
### Public-URL token checks share authentication ownership
The pre-route public-URL authority check uses the existing locked token
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index cb8b744043..0ccfa988e8 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -21,6 +21,21 @@
## Purpose
+### Long-lived agent reads preserve current token boundaries
+
+Agent event subscriptions revalidate API-token authority before admitting
+product frames and idle heartbeats. Withdrawing command scope changes the
+read projection, never canonical action/evidence or recovery data. Revocation,
+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.
+
+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.
+Previously stopped recovery work remains stopped; source proof is not recovery.
+
+
### Backup views share bounded owned-focus restoration
Coverage posture sorting and By date regrouping use the same existing backups
diff --git a/internal/api/agent_events.go b/internal/api/agent_events.go
index 9fe52d249a..82b166c7fb 100644
--- a/internal/api/agent_events.go
+++ b/internal/api/agent_events.go
@@ -256,20 +256,33 @@ func (b *AgentEventBroadcaster) SubscriberCount() int {
// HandleAgentEvents serves `GET /api/agent/events` — the SSE stream
// agents subscribe to for real-time notifications. The connection
-// stays open until the client disconnects or the request context
-// cancels. Heartbeats fire every 15s so an agent holding an idle
-// connection can confirm the stream is alive.
+// stays open until the client disconnects, the request context
+// cancels, or the authenticated route withdraws access. Heartbeats fire every
+// 15s so an agent holding an idle connection can confirm the stream is alive.
//
// SSE chosen over WebSocket because it's simpler (one-way, no
// frame-handling), works through every HTTP proxy without
// special-casing, and matches the existing deploy_handlers pattern.
// Agents that need bidirectional comms can call the REST endpoints
// in the capabilities manifest in parallel.
+// The router uses handleAgentEvents with live token revalidation; this raw
+// broadcaster handler does not own authentication.
func (b *AgentEventBroadcaster) HandleAgentEvents(w http.ResponseWriter, r *http.Request) {
+ b.handleAgentEvents(w, r, nil)
+}
+
+// handleAgentEvents checks the route's live token authority before admitting
+// each frame. A closed stream carries no new event kind or error payload: a
+// reconnect must pass the normal authentication and scope checks again.
+func (b *AgentEventBroadcaster) handleAgentEvents(w http.ResponseWriter, r *http.Request, revalidate func() bool) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
+ if revalidate != nil && !revalidate() {
+ http.Error(w, "Authentication required", http.StatusUnauthorized)
+ return
+ }
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming not supported", http.StatusInternalServerError)
@@ -311,9 +324,15 @@ func (b *AgentEventBroadcaster) HandleAgentEvents(w http.ResponseWriter, r *http
if !event.visibleToOrg(orgID) {
continue
}
+ if revalidate != nil && !revalidate() {
+ return
+ }
writeAgentSSEEvent(w, redactAgentEventCommandsForRequest(event, r))
flusher.Flush()
case <-heartbeat.C:
+ if revalidate != nil && !revalidate() {
+ return
+ }
writeAgentSSEEvent(w, b.stampEvent(AgentEvent{Kind: AgentEventHeartbeat}))
flusher.Flush()
}
diff --git a/internal/api/agent_events_auth.go b/internal/api/agent_events_auth.go
new file mode 100644
index 0000000000..7e3b77a3dd
--- /dev/null
+++ b/internal/api/agent_events_auth.go
@@ -0,0 +1,58 @@
+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/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 {
+ 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() bool {
+ if !provided || raw == "" {
+ return false
+ }
+ config.Mu.RLock()
+ defer config.Mu.RUnlock()
+
+ live := cfg
+ if tenantInventory {
+ live = tenantTokenConfigForRequest(req)
+ if live == nil {
+ return 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 false
+ }
+ if current.ID != admitted.ID || apiTokenAuthenticatedUser(current) != apiTokenAuthenticatedUser(admitted) ||
+ !current.HasScope(config.ScopeMonitoringRead) || !checker.CheckAccess(current, "", orgID).Allowed {
+ return false
+ }
+ // In particular, withdrawing ai:execute must redact the very next
+ // action/approval frame, even though monitoring:read still permits it.
+ attachAPITokenRecord(req, current)
+ return true
+ }
+}
diff --git a/internal/api/agent_events_auth_test.go b/internal/api/agent_events_auth_test.go
new file mode 100644
index 0000000000..849c2b33c0
--- /dev/null
+++ b/internal/api/agent_events_auth_test.go
@@ -0,0 +1,315 @@
+package api
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
+)
+
+const agentEventLifecycleToken = "synthetic-event-lifecycle-token.12345678"
+const agentEventControlToken = "synthetic-event-control-token.12345678"
+
+type agentLifecycleStream struct {
+ reader *bufio.Reader
+}
+
+func openAgentLifecycleStream(t *testing.T, server *httptest.Server, raw, transport string) *agentLifecycleStream {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ t.Cleanup(cancel)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/agent/events", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if transport == "session" {
+ req.AddCookie(&http.Cookie{Name: cookieNameSession, Value: raw})
+ } else if transport == "bearer" {
+ req.Header.Set("Authorization", "Bearer "+raw)
+ } else {
+ req.Header.Set("X-API-Token", raw)
+ }
+ resp, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { resp.Body.Close() })
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ t.Fatalf("stream admission = %d: %s", resp.StatusCode, body)
+ }
+ stream := &agentLifecycleStream{reader: bufio.NewReader(resp.Body)}
+ if first := stream.next(t); first.Kind != AgentEventStreamConnected {
+ t.Fatalf("first frame = %q, want connected", first.Kind)
+ }
+ return stream
+}
+
+func (s *agentLifecycleStream) read() (AgentEvent, error) {
+ for {
+ line, err := s.reader.ReadString('\n')
+ if err != nil {
+ return AgentEvent{}, err
+ }
+ if strings.HasPrefix(line, "data: ") {
+ var event AgentEvent
+ err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &event)
+ return event, err
+ }
+ }
+}
+
+func (s *agentLifecycleStream) next(t *testing.T) AgentEvent {
+ t.Helper()
+ for {
+ event, err := s.read()
+ if err != nil {
+ t.Fatalf("read stream frame: %v", err)
+ }
+ if event.Kind != AgentEventHeartbeat {
+ return event
+ }
+ }
+}
+
+func (s *agentLifecycleStream) wantClosed(t *testing.T) {
+ t.Helper()
+ for {
+ event, err := s.read()
+ if errors.Is(err, io.EOF) {
+ return
+ }
+ if err != nil {
+ t.Fatalf("stream did not close cleanly after authority withdrawal: %v", err)
+ }
+ // A heartbeat admitted before the fixture mutation may already be in
+ // flight. It must not hide a product frame or substitute for EOF.
+ if event.Kind != AgentEventHeartbeat {
+ t.Fatalf("withdrawn credential still received %q", event.Kind)
+ }
+ }
+}
+
+func newAgentLifecycleRouter(t *testing.T, heartbeat time.Duration) (*Router, *config.Config, *httptest.Server) {
+ t.Helper()
+ primary := newTokenRecord(t, agentEventLifecycleToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil)
+ control := newTokenRecord(t, agentEventControlToken, []string{config.ScopeWildcard}, nil)
+ cfg := newTestConfigWithTokens(t, primary, control)
+ router := NewRouter(cfg, nil, nil, nil, nil, "test")
+ cleanupTestRouter(t, router)
+ router.agentEventBroadcaster.heartbeatInterval = heartbeat
+ server := httptest.NewServer(router.Handler())
+ t.Cleanup(server.Close)
+ return router, cfg, server
+}
+
+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"} {
+ t.Run(transport+"/"+change, func(t *testing.T) {
+ router, cfg, server := newAgentLifecycleRouter(t, time.Hour)
+ primary := openAgentLifecycleStream(t, server, agentEventLifecycleToken, transport)
+ control := openAgentLifecycleStream(t, server, agentEventControlToken, transport)
+ config.Mu.Lock()
+ switch change {
+ case "revoked":
+ cfg.RemoveAPIToken(cfg.APITokens[0].ID)
+ case "expired":
+ past := time.Now().UTC().Add(-time.Second)
+ cfg.APITokens[0].ExpiresAt = &past
+ case "read_scope_removed":
+ cfg.APITokens[0].Scopes = []string{config.ScopeSettingsRead}
+ case "org_rebound":
+ cfg.APITokens[0].OrgID = "another-org"
+ case "identity_replaced":
+ cfg.APITokens[0].ID = "replacement-identity"
+ case "principal_replaced":
+ cfg.APITokens[0].Metadata = map[string]string{apiTokenMetadataOwnerUserID: "replacement-owner"}
+ case "invalid_role":
+ cfg.APITokens[0].Metadata = map[string]string{internalauth.RuntimeRoleMetadataKey: internalauth.RuntimeRoleActionRunner}
+ }
+ config.Mu.Unlock()
+
+ router.agentEventBroadcaster.PublishActionCompletedRecord(agentDisclosureRecord(t, false))
+ primary.wantClosed(t)
+ event := control.next(t)
+ if event.Kind != AgentEventActionCompleted {
+ t.Fatalf("independent subscriber lost action: %q", event.Kind)
+ }
+ body, _ := json.Marshal(event)
+ assertAgentDisclosureWire(t, body, false)
+ if router.agentEventBroadcaster.SubscriberCount() != 1 {
+ t.Fatal("withdrawn stream did not release its subscription")
+ }
+ })
+ }
+ }
+}
+
+func TestAgentEventTokenLifecycleClosesIdleStream(t *testing.T) {
+ for _, change := range []string{"revoke", "natural_expiry"} {
+ t.Run(change, func(t *testing.T) {
+ _, cfg, server := newAgentLifecycleRouter(t, 10*time.Millisecond)
+ primary := openAgentLifecycleStream(t, server, agentEventLifecycleToken, "header")
+ config.Mu.Lock()
+ if change == "revoke" {
+ cfg.RemoveAPIToken(cfg.APITokens[0].ID)
+ } else {
+ expires := time.Now().UTC().Add(30 * time.Millisecond)
+ cfg.APITokens[0].ExpiresAt = &expires
+ }
+ config.Mu.Unlock()
+ primary.wantClosed(t)
+ })
+ }
+}
+
+func TestAgentEventTokenLifecycleResolvesLiveTenantInventory(t *testing.T) {
+ const orgID = "tenant-a"
+ for _, change := range []string{"replaced", "removed", "same_credential_in_new_owner", "changes_during_validation", "no_global_fallback"} {
+ t.Run(change, func(t *testing.T) {
+ record := newTokenRecord(t, agentEventLifecycleToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil)
+ record.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
+ }
+ old := makeManager(&config.Config{APITokens: []config.APITokenRecord{record}})
+ nextCfg := &config.Config{}
+ if change == "same_credential_in_new_owner" {
+ nextCfg.APITokens = []config.APITokenRecord{record.Clone()}
+ nextCfg.APITokens[0].Scopes = []string{config.ScopeMonitoringRead}
+ }
+ next := makeManager(nextCfg)
+ req := httptest.NewRequest(http.MethodGet, "/api/agent/events", nil)
+ req.Header.Set("X-Pulse-Org-ID", orgID)
+ req.Header.Set("X-API-Token", agentEventLifecycleToken)
+ req = extractAndStoreAuthContext(base, old, req)
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, orgID))
+ source := req.Context().Value(tenantTokenSourceContextKey).(tenantTokenSource)
+ currentManager := old
+ resolutions := 0
+ source.resolveManager = func() *monitoring.MultiTenantMonitor {
+ resolutions++
+ if change == "changes_during_validation" && resolutions%2 == 0 {
+ return next
+ }
+ return currentManager
+ }
+ req = req.WithContext(context.WithValue(req.Context(), tenantTokenSourceContextKey, source))
+ validate := agentEventTokenRevalidator(base, req)
+ if change != "changes_during_validation" && !validate() {
+ t.Fatal("initial tenant credential rejected")
+ }
+ currentManager = next
+ if change == "removed" {
+ currentManager = nil
+ }
+ if change == "changes_during_validation" {
+ currentManager = old
+ }
+ if change == "no_global_fallback" {
+ base.APITokens = []config.APITokenRecord{record.Clone()}
+ }
+ want := change == "same_credential_in_new_owner"
+ if got := validate(); got != want {
+ t.Fatalf("live tenant validation = %v, want %v", got, want)
+ }
+ if want && requestCanReadAgentCommandPayloads(req) {
+ t.Fatal("live owner scope removal left stale command disclosure")
+ }
+ })
+ }
+}
+
+func TestAgentEventTokenLifecyclePreservesSessionDisclosure(t *testing.T) {
+ router, _, server := newAgentLifecycleRouter(t, time.Hour)
+ const session = "synthetic-event-browser-session"
+ GetSessionStore().CreateSession(session, time.Hour, "fixture", "127.0.0.1", "operator")
+ t.Cleanup(func() { GetSessionStore().DeleteSession(session) })
+ stream := openAgentLifecycleStream(t, server, session, "session")
+ router.agentEventBroadcaster.PublishActionCompletedRecord(agentDisclosureRecord(t, false))
+ body, _ := json.Marshal(stream.next(t))
+ assertAgentDisclosureWire(t, body, false)
+}
+
+type agentLifecycleMCPClient struct {
+ client *http.Client
+ ready chan struct{}
+}
+
+func (c agentLifecycleMCPClient) Do(req *http.Request) (*http.Response, error) {
+ resp, err := c.client.Do(req)
+ close(c.ready)
+ return resp, err
+}
+
+// Use the same SSE-to-MCP consumer the shipped pulse-mcp adapter calls, but
+// against the real registered API route, not a fixture-only SSE producer.
+func TestAgentEventTokenLifecycleMCPConsumer(t *testing.T) {
+ router, cfg, server := newAgentLifecycleRouter(t, time.Hour)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ ready := make(chan struct{})
+ notifications := make(chan agentcapabilities.JSONRPCRequest, 4)
+ done := make(chan error, 1)
+ go func() {
+ done <- agentcapabilities.StreamMCPEventNotifications(ctx, agentLifecycleMCPClient{server.Client(), ready}, server.URL, agentcapabilities.AgentEventsPath, agentEventLifecycleToken, func(n agentcapabilities.JSONRPCRequest) error {
+ notifications <- n
+ return nil
+ })
+ }()
+ select {
+ case <-ready:
+ case <-ctx.Done():
+ t.Fatal("MCP stream never connected")
+ }
+ router.agentEventBroadcaster.PublishFindingCreated(AgentEventFindingCreatedPayload{FindingID: "before-revocation"})
+ select {
+ case n := <-notifications:
+ if n.Method != "notifications/finding.created" || !strings.Contains(string(n.Params), "before-revocation") {
+ t.Fatalf("valid MCP notification changed: %+v", n)
+ }
+ case <-ctx.Done():
+ t.Fatal("valid MCP notification never arrived")
+ }
+ config.Mu.Lock()
+ cfg.RemoveAPIToken(cfg.APITokens[0].ID)
+ config.Mu.Unlock()
+ router.agentEventBroadcaster.PublishActionCompletedRecord(agentDisclosureRecord(t, false))
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("withdrawn MCP stream did not reach clean EOF: %v", err)
+ }
+ case <-ctx.Done():
+ t.Fatal("withdrawn MCP stream stayed open")
+ }
+ if len(notifications) != 0 {
+ t.Fatal("MCP forwarded an event after revocation")
+ }
+ err := agentcapabilities.StreamMCPEventNotifications(ctx, server.Client(), server.URL, agentcapabilities.AgentEventsPath, agentEventLifecycleToken, nil)
+ if err == nil || !strings.Contains(err.Error(), "status 401") {
+ t.Fatalf("MCP reconnect did not retain revocation: %v", err)
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 7b2654e383..542cdce763 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -28817,3 +28817,34 @@ func TestContract_AgentRecentChangesRunbookProjection(t *testing.T) {
}
assertJSONSnapshot(t, got, `{"commandRedacted":true,"metadata":{"alert_identifier":"alert-1","automatic":false,"outcome":"partial","runbook_id":"rb-1"},"reason":"Runbook executed (partial)"}`)
}
+
+func TestAgentEventTokenLifecycleRefreshesDisclosure(t *testing.T) {
+ router, cfg, server := newAgentLifecycleRouter(t, time.Hour)
+ primary := openAgentLifecycleStream(t, server, agentEventLifecycleToken, "bearer")
+ control := openAgentLifecycleStream(t, server, agentEventControlToken, "header")
+ record := agentDisclosureRecord(t, false)
+ before, _ := json.Marshal(record)
+ router.agentEventBroadcaster.PublishActionCompletedRecord(record)
+ for _, stream := range []*agentLifecycleStream{primary, control} {
+ body, _ := json.Marshal(stream.next(t))
+ assertAgentDisclosureWire(t, body, false)
+ }
+
+ config.Mu.Lock()
+ cfg.APITokens[0].Scopes = []string{config.ScopeMonitoringRead}
+ config.Mu.Unlock()
+ router.agentEventBroadcaster.PublishApprovalPending(AgentEventApprovalPendingPayload{ApprovalID: "after-downgrade", Command: agentPrivateDetail})
+ router.agentEventBroadcaster.PublishActionCompletedRecord(record)
+ for i, stream := range []*agentLifecycleStream{primary, control} {
+ approval, _ := json.Marshal(stream.next(t))
+ if strings.Contains(string(approval), agentPrivateDetail) != (i == 1) {
+ t.Fatalf("approval did not use current disclosure authority: %s", approval)
+ }
+ action, _ := json.Marshal(stream.next(t))
+ assertAgentDisclosureWire(t, action, i == 0)
+ }
+ after, _ := json.Marshal(record)
+ if !reflect.DeepEqual(before, after) {
+ t.Fatal("refresh/redaction changed the published canonical record")
+ }
+}
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index 95c646de40..5e76d5736f 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -6,6 +6,7 @@ import (
"go/ast"
"go/parser"
"go/token"
+ "io"
"net"
"net/http"
"net/http/httptest"
@@ -909,3 +910,37 @@ func TestRegisteredTestNotificationAdmitsRequestOrganizationManagers(t *testing.
}
}
}
+
+func TestAgentEventTokenLifecycleDeleteThroughHTTP(t *testing.T) {
+ router, cfg, server := newAgentLifecycleRouter(t, time.Hour)
+ primary := openAgentLifecycleStream(t, server, agentEventLifecycleToken, "header")
+ id := cfg.APITokens[0].ID
+ req, _ := http.NewRequest(http.MethodDelete, server.URL+"/api/security/tokens/"+id, nil)
+ req.Header.Set("X-API-Token", agentEventControlToken)
+ 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("real token deletion = %d: %s", resp.StatusCode, body)
+ }
+ persisted, err := router.persistence.LoadAPITokens()
+ if err != nil || len(persisted) != 1 || persisted[0].ID == id {
+ t.Fatalf("revocation was not persisted: %v, %d tokens", err, len(persisted))
+ }
+ router.agentEventBroadcaster.PublishFindingCreated(AgentEventFindingCreatedPayload{FindingID: "after-durable-revoke"})
+ primary.wantClosed(t)
+
+ req, _ = http.NewRequest(http.MethodGet, server.URL+"/api/agent/events", nil)
+ req.Header.Set("X-API-Token", agentEventLifecycleToken)
+ resp, err = server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusUnauthorized {
+ t.Fatalf("revoked reconnect = %d, want 401", resp.StatusCode)
+ }
+}
diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.go
index 6af10d6fb7..41586de126 100644
--- a/internal/api/router_routes_monitoring.go
+++ b/internal/api/router_routes_monitoring.go
@@ -160,7 +160,7 @@ func (r *Router) registerMonitoringResourceRoutes(
if r.agentEventBroadcaster != nil {
r.mux.HandleFunc("/api/agent/events", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.withExternalAgentCapabilityActivity(
agentcapabilities.EventSubscriptionCapabilityName,
- r.agentEventBroadcaster.HandleAgentEvents,
+ r.handleAgentEvents,
))))
}
r.mux.HandleFunc("POST /api/actions/plan", RequireAuth(r.config, RequireAnyScope([]string{config.ScopeActionsPlan, config.ScopeAIExecute}, requireActionCapability(r.config, r.authorizer, auth.ActionPlan, r.withExternalAgentCapabilityActivity(