Files
Pulse/internal/api/telemetry_infrastructure_map_test.go
rcourtman c5b6d05107 feat(telemetry): add schema v26 map topology API/CLI/MCP telemetry
I added Schema v26 content-free Infrastructure Map topology read telemetry for external live GET /api/agent/topology requests (total read days, CLI days, MCP days, anonymized days, and an explicit availability flag) alongside hardened opt-out zero-write boundaries, credential-binding checks, and read-only SQLite/config guards.

Key changes:
- Added a dedicated root-scoped daily tally store (infrastructure_map_topology_tally.json) with strict schema validation, fail-closed degraded sidecar accounting, and strict zero-write guarantees when telemetry is disabled by settings or PULSE_TELEMETRY=false.
- Added X-Pulse-Agent-Surface attribution for pulse-cli and MCP clients while filtering out first-party browser traffic, mock-mode snapshots, and unverified monitor states.
- Updated Settings payload preview, localization copy, shipped PRIVACY.md disclosure, integration specs, and schema parity tooling for Schema v26.
- Hardened host/agent token hash binding, self-uninstall live authority and durable hash-scoped tombstones, Patrol investigation replay-floor provenance, bounded non-blocking regular-file config reads, and cold read-only legacy SQLite history queries.
2026-12-02 01:41:25 +00:00

7924 lines
304 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/api/agentbinding"
"github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"
"github.com/rcourtman/pulse-go-rewrite/internal/api/apicontext"
"github.com/rcourtman/pulse-go-rewrite/internal/api/resourceapi"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/telemetry"
unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
func TestHandleInfrastructureMapActivityRecordsOnlyCount(t *testing.T) {
dir := t.TempDir()
persistence := config.NewConfigPersistence(dir)
router := &Router{persistence: persistence}
req := httptest.NewRequest(http.MethodPost, "/api/usage/infrastructure-map", strings.NewReader(`{"activity":"export_names_hidden"}`))
rec := httptest.NewRecorder()
router.HandleInfrastructureMapActivity(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d body=%q, want 204", rec.Code, rec.Body.String())
}
tally, err := persistence.LoadInfrastructureMapActivityTally()
if err != nil {
t.Fatalf("LoadInfrastructureMapActivityTally = %v", err)
}
if got := tally.CountSince(config.InfrastructureMapActivityExportNamesHidden, time.Now().UTC().AddDate(0, 0, -30)); got != 1 {
t.Fatalf("names-hidden exports = %d, want 1", got)
}
}
// The map draws names, addresses and networks. None of them may reach the
// tally, whether sent as the activity value or beside it.
func TestHandleInfrastructureMapActivityRejectsContentAndUnknownFields(t *testing.T) {
for _, body := range []string{
`{"activity":"pve-node-1"}`,
`{"activity":"192.168.10.0/24"}`,
`{"activity":"export","view":"networks"}`,
`{"activity":"export_hosts"}`,
`{"activity":"export","names":["nas","router"]}`,
`{"activity":"open"}{"activity":"export"}`,
`{}`,
} {
dir := t.TempDir()
router := &Router{persistence: config.NewConfigPersistence(dir)}
req := httptest.NewRequest(http.MethodPost, "/api/usage/infrastructure-map", strings.NewReader(body))
rec := httptest.NewRecorder()
router.HandleInfrastructureMapActivity(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("body %q status = %d, want 400", body, rec.Code)
}
if _, err := os.Stat(filepath.Join(dir, "infrastructure_map_activity_tally.json")); !os.IsNotExist(err) {
t.Fatalf("body %q wrote the tally file", body)
}
}
}
func TestHandleInfrastructureMapActivityRefusesOtherMethods(t *testing.T) {
router := &Router{persistence: config.NewConfigPersistence(t.TempDir())}
req := httptest.NewRequest(http.MethodGet, "/api/usage/infrastructure-map", nil)
rec := httptest.NewRecorder()
router.HandleInfrastructureMapActivity(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Fatalf("GET status = %d, want 405", rec.Code)
}
}
func TestApplyInfrastructureMapTelemetrySnapshotAggregatesRollingCounts(t *testing.T) {
persistence := config.NewConfigPersistence(t.TempDir())
now := time.Now().UTC()
for _, activity := range []string{
config.InfrastructureMapActivityOpen,
config.InfrastructureMapActivityOpen,
config.InfrastructureMapActivityOpen,
config.InfrastructureMapActivityExport,
config.InfrastructureMapActivityExport,
config.InfrastructureMapActivityExportNamesHidden,
} {
if err := persistence.RecordInfrastructureMapActivity(activity, now); err != nil {
t.Fatalf("record %q = %v", activity, err)
}
}
// Outside the 30-day window: retained on disk for a day, not reported.
if err := persistence.RecordInfrastructureMapActivity(config.InfrastructureMapActivityOpen, now.AddDate(0, 0, -31)); err != nil {
t.Fatalf("record old open = %v", err)
}
snapshot := telemetry.Snapshot{}
(&Router{persistence: persistence}).ApplyInfrastructureMapTelemetrySnapshot(&snapshot, now)
if snapshot.InfrastructureMapOpenSessions30d != 3 ||
snapshot.InfrastructureMapExportSessions30d != 2 ||
snapshot.InfrastructureMapExportNamesHiddenSessions30d != 1 {
t.Fatalf("unexpected infrastructure map snapshot: open=%d export=%d hidden=%d",
snapshot.InfrastructureMapOpenSessions30d,
snapshot.InfrastructureMapExportSessions30d,
snapshot.InfrastructureMapExportNamesHiddenSessions30d)
}
}
func setMockEnabledForTest(t *testing.T, enable bool) {
t.Helper()
if err := mock.SetEnabled(enable); err != nil {
t.Fatalf("mock.SetEnabled(%v): %v", enable, err)
}
}
func TestHandleInfrastructureMapActivityRejectsServerSideTopologyMilestones(t *testing.T) {
for _, activity := range []string{
config.InfrastructureMapActivityTopologyRead,
config.InfrastructureMapActivityTopologyCLI,
config.InfrastructureMapActivityTopologyMCP,
config.InfrastructureMapActivityTopologyAnonymized,
} {
dir := t.TempDir()
router := &Router{persistence: config.NewConfigPersistence(dir)}
req := httptest.NewRequest(http.MethodPost, "/api/usage/infrastructure-map", strings.NewReader(`{"activity":"`+activity+`"}`))
rec := httptest.NewRecorder()
router.HandleInfrastructureMapActivity(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("activity %q status = %d, want 400", activity, rec.Code)
}
if _, err := os.Stat(filepath.Join(dir, "infrastructure_map_activity_tally.json")); !os.IsNotExist(err) {
t.Fatalf("activity %q wrote the browser tally file", activity)
}
if _, err := os.Stat(filepath.Join(dir, "infrastructure_map_topology_tally.json")); !os.IsNotExist(err) {
t.Fatalf("activity %q wrote the topology tally file", activity)
}
}
}
type customTopologyResponseWriter struct {
header http.Header
status int
writeFn func([]byte) (int, error)
}
func (w *customTopologyResponseWriter) Header() http.Header {
if w.header == nil {
w.header = make(http.Header)
}
return w.header
}
func (w *customTopologyResponseWriter) WriteHeader(code int) {
w.status = code
}
func (w *customTopologyResponseWriter) Write(p []byte) (int, error) {
if w.writeFn != nil {
return w.writeFn(p)
}
return len(p), nil
}
type mockTransitionStateProvider struct {
onRead func()
resources []unified.Resource
lastUpdate time.Time
isMock bool
snapshot models.StateSnapshot
}
func (p *mockTransitionStateProvider) ReadSnapshot() models.StateSnapshot {
if !p.snapshot.LastUpdate.IsZero() || len(p.snapshot.Nodes) > 0 {
return p.snapshot
}
return models.StateSnapshot{LastUpdate: p.lastUpdate}
}
func (p *mockTransitionStateProvider) UnifiedResourceSnapshotWithStaleThresholdsAndProvenance() ([]unified.Resource, time.Time, map[unified.DataSource]time.Duration, bool) {
if p.onRead != nil {
p.onRead()
}
return p.resources, p.lastUpdate, nil, p.isMock
}
type legacyTenantNoProvenanceProvider struct {
resources []unified.Resource
lastUpdate time.Time
}
func (p *legacyTenantNoProvenanceProvider) UnifiedReadStateForTenant(string) unified.ReadState {
return nil
}
func (p *legacyTenantNoProvenanceProvider) UnifiedResourceSnapshotForTenant(string) ([]unified.Resource, time.Time) {
return p.resources, p.lastUpdate
}
type countingSupplementalProvider struct {
calls int
}
func (p *countingSupplementalProvider) GetCurrentRecords() []unified.IngestRecord {
p.calls++
return nil
}
func TestBuildRegistryWithProvenanceTracksTransitionsAndCache(t *testing.T) {
prevMock := mock.IsMockEnabled()
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
fixedUpdate := time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
res := []unified.Resource{
{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline},
}
t.Run("false-true-false transition inside registrySeed marks provenance as mock", func(t *testing.T) {
setMockEnabledForTest(t, false)
qs := resourceapi.NewQueryService(&config.Config{DataPath: t.TempDir()})
t.Cleanup(func() { _ = qs.CloseStores() })
qs.SetStateProvider(&mockTransitionStateProvider{
resources: res,
lastUpdate: fixedUpdate,
onRead: func() {
setMockEnabledForTest(t, true)
setMockEnabledForTest(t, false)
},
})
_, prov, err := qs.BuildRegistryWithProvenance("default")
if err != nil {
t.Fatalf("BuildRegistryWithProvenance: %v", err)
}
if !prov.MockMode || prov.LiveTelemetryEligible() {
t.Fatalf("expected MockMode=true when mock mode toggled false->true->false during registrySeed, got %+v", prov)
}
})
t.Run("provider-reported mock provenance propagates even when global mock flag is false", func(t *testing.T) {
setMockEnabledForTest(t, false)
qs := resourceapi.NewQueryService(&config.Config{DataPath: t.TempDir()})
t.Cleanup(func() { _ = qs.CloseStores() })
qs.SetStateProvider(&mockTransitionStateProvider{
resources: res,
lastUpdate: fixedUpdate,
isMock: true,
})
_, prov, err := qs.BuildRegistryWithProvenance("default")
if err != nil {
t.Fatalf("BuildRegistryWithProvenance: %v", err)
}
if !prov.MockMode || prov.LiveTelemetryEligible() {
t.Fatalf("expected MockMode=true when snapshot provider reports mock provenance, got %+v", prov)
}
})
t.Run("settled mock mode reuses cached registry without replaying supplemental providers", func(t *testing.T) {
setMockEnabledForTest(t, true)
qs := resourceapi.NewQueryService(&config.Config{DataPath: t.TempDir()})
t.Cleanup(func() { _ = qs.CloseStores() })
supp := &countingSupplementalProvider{}
qs.SetSupplementalRecordsProvider(unified.SourceAvailability, supp)
qs.SetStateProvider(&mockTransitionStateProvider{
resources: res,
lastUpdate: fixedUpdate,
isMock: true,
})
reg1, prov1, err := qs.BuildRegistryWithProvenance("default")
if err != nil || !prov1.MockMode {
t.Fatalf("first settled mock build: prov=%+v err=%v", prov1, err)
}
callsAfterFirst := supp.calls
reg2, prov2, err := qs.BuildRegistryWithProvenance("default")
if err != nil || !prov2.MockMode {
t.Fatalf("second settled mock build: prov=%+v err=%v", prov2, err)
}
if reg1 != reg2 {
t.Fatalf("expected settled mock mode to reuse cached registry")
}
if supp.calls != callsAfterFirst {
t.Fatalf("expected supplemental provider not to replay on mock cache hit: before=%d after=%d", callsAfterFirst, supp.calls)
}
})
t.Run("cache entry from before a complete mock toggle cycle is not reused across generations", func(t *testing.T) {
setMockEnabledForTest(t, false)
qs := resourceapi.NewQueryService(&config.Config{DataPath: t.TempDir()})
t.Cleanup(func() { _ = qs.CloseStores() })
qs.SetStateProvider(&mockTransitionStateProvider{
resources: res,
lastUpdate: fixedUpdate,
isMock: false,
})
reg1, prov1, err := qs.BuildRegistryWithProvenance("default")
if err != nil || !prov1.LiveTelemetryEligible() {
t.Fatalf("initial live build: prov=%+v err=%v", prov1, err)
}
setMockEnabledForTest(t, true)
setMockEnabledForTest(t, false)
reg2, prov2, err := qs.BuildRegistryWithProvenance("default")
if err != nil || !prov2.LiveTelemetryEligible() {
t.Fatalf("post-cycle live build: prov=%+v err=%v", prov2, err)
}
if reg1 == reg2 {
t.Fatalf("expected pre-toggle cache entry not to be reused after a mock toggle cycle")
}
})
t.Run("unresolved default and tenant monitors report MonitorUnavailable", func(t *testing.T) {
setMockEnabledForTest(t, false)
qs := resourceapi.NewQueryService(&config.Config{DataPath: t.TempDir()})
t.Cleanup(func() { _ = qs.CloseStores() })
_, defaultProv, err := qs.BuildRegistryWithProvenance("default")
if err != nil {
t.Fatalf("default build without stateProvider: %v", err)
}
if !defaultProv.MonitorUnavailable || defaultProv.LiveTelemetryEligible() {
t.Fatalf("nil stateProvider must set MonitorUnavailable=true, got %+v", defaultProv)
}
mtm := &monitoring.MultiTenantMonitor{}
qs.SetTenantStateProvider(NewMultiTenantStateProvider(mtm, nil))
_, tenantProv, err := qs.BuildRegistryWithProvenance("org-missing")
if err != nil {
t.Fatalf("tenant build with unresolved monitor: %v", err)
}
if !tenantProv.MonitorUnavailable || tenantProv.LiveTelemetryEligible() {
t.Fatalf("unresolved tenant monitor must set MonitorUnavailable=true, got %+v", tenantProv)
}
})
t.Run("legacy providers without provenance serve normally but are not live-telemetry eligible", func(t *testing.T) {
setMockEnabledForTest(t, false)
qs := resourceapi.NewQueryService(&config.Config{DataPath: t.TempDir()})
t.Cleanup(func() { _ = qs.CloseStores() })
qs.SetStateProvider(resourceUnifiedSeedProvider{
snapshot: models.StateSnapshot{LastUpdate: fixedUpdate},
resources: res,
})
reg, defaultProv, err := qs.BuildRegistryWithProvenance("default")
if err != nil || reg == nil || len(reg.ListForPresentation()) != 1 {
t.Fatalf("legacy default build failed: reg=%v err=%v", reg, err)
}
if defaultProv.ProvenanceVerified || defaultProv.LiveTelemetryEligible() {
t.Fatalf("legacy default provider must not be telemetry eligible without provenance: %+v", defaultProv)
}
qs.SetTenantStateProvider(&legacyTenantNoProvenanceProvider{
resources: res,
lastUpdate: fixedUpdate,
})
tReg, tenantProv, err := qs.BuildRegistryWithProvenance("org-legacy")
if err != nil || tReg == nil || len(tReg.ListForPresentation()) != 1 {
t.Fatalf("legacy tenant build failed: reg=%v err=%v", tReg, err)
}
if tenantProv.ProvenanceVerified || tenantProv.LiveTelemetryEligible() {
t.Fatalf("legacy tenant provider must not be telemetry eligible without provenance: %+v", tenantProv)
}
})
t.Run("empty provenance-aware seed falling back to ReadSnapshot is not live-telemetry eligible", func(t *testing.T) {
setMockEnabledForTest(t, false)
qs := resourceapi.NewQueryService(&config.Config{DataPath: t.TempDir()})
t.Cleanup(func() { _ = qs.CloseStores() })
qs.SetStateProvider(&mockTransitionStateProvider{
resources: nil,
lastUpdate: time.Time{},
isMock: false,
snapshot: models.StateSnapshot{
LastUpdate: fixedUpdate,
Nodes: []models.Node{{ID: "fallback-node", Name: "fallback-node", Instance: "pve", Status: "online"}},
},
})
reg, prov, err := qs.BuildRegistryWithProvenance("default")
if err != nil || reg == nil || len(reg.ListForPresentation()) == 0 {
t.Fatalf("fallback snapshot build failed: reg=%v err=%v", reg, err)
}
if prov.ProvenanceVerified || prov.LiveTelemetryEligible() {
t.Fatalf("fallback ReadSnapshot must not inherit ProvenanceVerified from discarded empty seed: %+v", prov)
}
})
}
func TestHandleTopologyObserverWriteFailuresAndMockProvenance(t *testing.T) {
prevMock := mock.IsMockEnabled()
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
fixedNow := time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
newHandler := func(t *testing.T, isMock bool) (*AgentContextHandler, *Router) {
t.Helper()
cfg := &config.Config{DataPath: t.TempDir(), TelemetryEnabled: true}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{
{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline},
},
lastUpdate: fixedNow,
isMock: isMock,
})
h := NewAgentContextHandler(rh)
p := config.NewConfigPersistence(t.TempDir())
if err := p.EnsureInfrastructureMapTopologyTally(fixedNow); err != nil {
t.Fatalf("EnsureInfrastructureMapTopologyTally: %v", err)
}
r := &Router{
config: cfg,
persistence: p,
topologyNow: func() time.Time { return fixedNow },
}
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
return h, r
}
authedReq := func(target string) *http.Request {
req := httptest.NewRequest(http.MethodGet, target, nil)
tok := &config.APITokenRecord{ID: "tok-1", Scopes: []string{config.ScopeMonitoringRead}}
return req.WithContext(internalauth.WithAPIToken(req.Context(), tok))
}
t.Run("failed write does not record", func(t *testing.T) {
setMockEnabledForTest(t, false)
h, r := newHandler(t, false)
w := &customTopologyResponseWriter{
writeFn: func([]byte) (int, error) { return 0, errors.New("connection reset") },
}
h.HandleTopology(w, authedReq("/api/agent/topology"))
snap := telemetry.Snapshot{}
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, fixedNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("failed write snapshot = %+v, want avail=true read=0", snap)
}
})
t.Run("short write does not record", func(t *testing.T) {
setMockEnabledForTest(t, false)
h, r := newHandler(t, false)
w := &customTopologyResponseWriter{
writeFn: func(p []byte) (int, error) {
if len(p) > 1 {
return len(p) - 1, nil
}
return 0, nil
},
}
h.HandleTopology(w, authedReq("/api/agent/topology"))
snap := telemetry.Snapshot{}
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, fixedNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("short write snapshot = %+v, want avail=true read=0", snap)
}
})
t.Run("cancelled context during write does not record", func(t *testing.T) {
setMockEnabledForTest(t, false)
h, r := newHandler(t, false)
ctx, cancel := context.WithCancel(context.Background())
req := authedReq("/api/agent/topology").WithContext(ctx)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &config.APITokenRecord{ID: "tok-1", Scopes: []string{config.ScopeMonitoringRead}}))
w := &customTopologyResponseWriter{
writeFn: func(p []byte) (int, error) {
cancel()
return len(p), nil
},
}
h.HandleTopology(w, req)
snap := telemetry.Snapshot{}
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, fixedNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("cancelled write snapshot = %+v, want avail=true read=0", snap)
}
})
t.Run("mock mode turned off during write still suppresses synthetic read", func(t *testing.T) {
setMockEnabledForTest(t, true)
h, r := newHandler(t, true)
w := &customTopologyResponseWriter{
writeFn: func(p []byte) (int, error) {
setMockEnabledForTest(t, false)
return len(p), nil
},
}
h.HandleTopology(w, authedReq("/api/agent/topology"))
snap := telemetry.Snapshot{}
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, fixedNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("synthetic read snapshot = %+v, want avail=true read=0", snap)
}
})
t.Run("mock mode turned on during write still records live snapshot", func(t *testing.T) {
setMockEnabledForTest(t, false)
h, r := newHandler(t, false)
w := &customTopologyResponseWriter{
writeFn: func(p []byte) (int, error) {
setMockEnabledForTest(t, true)
return len(p), nil
},
}
h.HandleTopology(w, authedReq("/api/agent/topology?anonymize=1"))
h.WaitTopologyObservers()
snap := telemetry.Snapshot{}
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, fixedNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable ||
snap.InfrastructureMapTopologyReadDays30d != 1 ||
snap.InfrastructureMapTopologyAnonymizedDays30d != 1 {
t.Fatalf("live read suppressed by mock toggle on during write: %+v", snap)
}
})
t.Run("unresolved tenant monitor returning empty 200 does not record", func(t *testing.T) {
setMockEnabledForTest(t, false)
cfg := &config.Config{DataPath: t.TempDir(), TelemetryEnabled: true}
rh := NewResourceHandlers(cfg)
rh.SetTenantStateProvider(NewMultiTenantStateProvider(&monitoring.MultiTenantMonitor{}, nil))
h := NewAgentContextHandler(rh)
p := config.NewConfigPersistence(t.TempDir())
if err := p.EnsureInfrastructureMapTopologyTally(fixedNow); err != nil {
t.Fatalf("EnsureInfrastructureMapTopologyTally: %v", err)
}
r := &Router{
config: cfg,
persistence: p,
topologyNow: func() time.Time { return fixedNow },
}
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
req := authedReq("/api/agent/topology")
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "org-missing"))
rec := httptest.NewRecorder()
h.HandleTopology(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("unresolved tenant status = %d, want 200", rec.Code)
}
snap := telemetry.Snapshot{}
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, fixedNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("unresolved tenant monitor must not record read day, got %+v", snap)
}
})
t.Run("legacy provider without provenance serves 200 but does not record", func(t *testing.T) {
setMockEnabledForTest(t, false)
h, _, _ := fleetFixtureHandlers(t, []unified.Resource{
{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline},
})
p := config.NewConfigPersistence(t.TempDir())
if err := p.EnsureInfrastructureMapTopologyTally(fixedNow); err != nil {
t.Fatalf("Ensure: %v", err)
}
r := &Router{
config: &config.Config{TelemetryEnabled: true},
persistence: p,
topologyNow: func() time.Time { return fixedNow },
}
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
rec := httptest.NewRecorder()
h.HandleTopology(rec, authedReq("/api/agent/topology"))
if rec.Code != http.StatusOK {
t.Fatalf("legacy provider status = %d, want 200", rec.Code)
}
snap := telemetry.Snapshot{}
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, fixedNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("legacy provider without provenance must not record read day, got %+v", snap)
}
})
t.Run("empty provenance-aware result falling back to populated ReadSnapshot serves 200 without recording", func(t *testing.T) {
setMockEnabledForTest(t, false)
cfg := &config.Config{DataPath: t.TempDir(), TelemetryEnabled: true}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: nil,
lastUpdate: time.Time{},
isMock: false,
snapshot: models.StateSnapshot{
LastUpdate: fixedNow,
Nodes: []models.Node{{ID: "fallback-node", Name: "fallback-node", Instance: "pve", Status: "online"}},
},
})
h := NewAgentContextHandler(rh)
p := config.NewConfigPersistence(t.TempDir())
if err := p.EnsureInfrastructureMapTopologyTally(fixedNow); err != nil {
t.Fatalf("Ensure: %v", err)
}
r := &Router{
config: cfg,
persistence: p,
topologyNow: func() time.Time { return fixedNow },
}
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
rec := httptest.NewRecorder()
h.HandleTopology(rec, authedReq("/api/agent/topology"))
if rec.Code != http.StatusOK {
t.Fatalf("fallback snapshot status = %d, want 200", rec.Code)
}
snap := telemetry.Snapshot{}
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, fixedNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("fallback ReadSnapshot must not record read day, got %+v", snap)
}
})
}
func TestRouterTopologyTelemetryRecordingEndToEnd(t *testing.T) {
prevMock := mock.IsMockEnabled()
setMockEnabledForTest(t, false)
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "127.0.0.1/32")
ResetTrustedProxyConfigForTests()
t.Cleanup(ResetTrustedProxyConfigForTests)
currentNow := time.Date(2026, 11, 22, 15, 0, 0, 0, time.UTC)
readTok := newTokenRecord(t, "topo-read-e2e.12345678", []string{config.ScopeMonitoringRead}, nil)
wrongScopeTok := newTokenRecord(t, "topo-agent-e2e.12345678", []string{config.ScopeAgentReport}, nil)
expiredAt := time.Now().UTC().Add(-time.Hour)
expiredTok := newTokenRecord(t, "topo-expired-e2e.12345678", []string{config.ScopeMonitoringRead}, nil)
expiredTok.ExpiresAt = &expiredAt
cfg := newTestConfigWithTokens(t, readTok, wrongScopeTok, expiredTok)
cfg.TelemetryEnabled = true
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
router.topologyNow = func() time.Time { return currentNow }
// 0. Before any monitor/stateProvider is attached, an empty 200 OK must NOT record.
unmonitoredReq := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
unmonitoredReq.Header.Set("X-API-Token", "topo-read-e2e.12345678")
unmonitoredRec := httptest.NewRecorder()
router.Handler().ServeHTTP(unmonitoredRec, unmonitoredReq)
if unmonitoredRec.Code != http.StatusOK {
t.Fatalf("unmonitored topology status = %d, want 200", unmonitoredRec.Code)
}
snap := telemetry.Snapshot{}
router.ApplyInfrastructureMapTelemetrySnapshot(&snap, currentNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("unmonitored router must not record read day: %+v", snap)
}
// Attach a provenance-verified live stateProvider.
router.resourceHandlers.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: currentNow,
isMock: false,
})
// 0b. Telemetry opt-out regression: disable -> CLI reads on 3 days -> re-enable -> counts stay 0!
cfg.TelemetryEnabled = false
for i := 0; i < 3; i++ {
optOutReq := httptest.NewRequest(http.MethodGet, "/api/agent/topology?anonymize=true", nil)
optOutReq.Header.Set("X-API-Token", "topo-read-e2e.12345678")
optOutReq.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
optOutRec := httptest.NewRecorder()
router.Handler().ServeHTTP(optOutRec, optOutReq)
if optOutRec.Code != http.StatusOK {
t.Fatalf("opt-out CLI read %d status = %d, want 200", i, optOutRec.Code)
}
currentNow = currentNow.AddDate(0, 0, 1)
}
cfg.TelemetryEnabled = true
snap = telemetry.Snapshot{}
router.ApplyInfrastructureMapTelemetrySnapshot(&snap, currentNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable ||
snap.InfrastructureMapTopologyReadDays30d != 0 ||
snap.InfrastructureMapTopologyCLIDays30d != 0 ||
snap.InfrastructureMapTopologyAnonymizedDays30d != 0 {
t.Fatalf("reads during telemetry opt-out leaked after re-enable: %+v", snap)
}
// 1. Rejected requests (403 wrong scope, 400 invalid query, 401 expired) must not record.
for _, tc := range []struct {
target string
token string
want int
}{
{target: "/api/agent/topology", token: "topo-agent-e2e.12345678", want: http.StatusForbidden},
{target: "/api/agent/topology?anonymize=nope", token: "topo-read-e2e.12345678", want: http.StatusBadRequest},
{target: "/api/agent/topology", token: "topo-expired-e2e.12345678", want: http.StatusUnauthorized},
} {
req := httptest.NewRequest(http.MethodGet, tc.target, nil)
req.Header.Set("X-API-Token", tc.token)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != tc.want {
t.Fatalf("%s status = %d, want %d", tc.target, rec.Code, tc.want)
}
}
// 2. First-party browser requests (including behind a trusted host-rewriting
// reverse proxy forwarding X-Forwarded-Host / X-Forwarded-Proto) must not record.
for _, setup := range []func(*http.Request){
func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-origin") },
func(r *http.Request) { r.Host = "pulse.local:7655"; r.Header.Set("Origin", "http://pulse.local:7655") },
func(r *http.Request) {
r.Host = "pulse.local:7655"
r.Header.Set("Referer", "http://pulse.local:7655/map")
},
func(r *http.Request) { r.Header.Set("X-Requested-With", "XMLHttpRequest") },
func(r *http.Request) {
r.RemoteAddr = "127.0.0.1:43210"
r.Host = "127.0.0.1:7655"
r.Header.Set("X-Forwarded-Host", "pulse.example.com")
r.Header.Set("X-Forwarded-Proto", "https")
r.Header.Set("Origin", "https://pulse.example.com")
},
} {
req := httptest.NewRequest(http.MethodGet, "http://pulse.local:7655/api/agent/topology", nil)
req.Header.Set("X-API-Token", "topo-read-e2e.12345678")
setup(req)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("browser request status = %d, want 200", rec.Code)
}
}
snap = telemetry.Snapshot{}
router.ApplyInfrastructureMapTelemetrySnapshot(&snap, currentNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("ignored/browser requests snapshot = %+v, want available=true read=0", snap)
}
// 3. Trusted proxy with foreign Origin must still count as external.
proxyForeign := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:7655/api/agent/topology", nil)
proxyForeign.RemoteAddr = "127.0.0.1:43210"
proxyForeign.Host = "127.0.0.1:7655"
proxyForeign.Header.Set("X-API-Token", "topo-read-e2e.12345678")
proxyForeign.Header.Set("X-Forwarded-Host", "pulse.example.com")
proxyForeign.Header.Set("X-Forwarded-Proto", "https")
proxyForeign.Header.Set("Origin", "https://other.example.com")
proxyForeignRec := httptest.NewRecorder()
router.Handler().ServeHTTP(proxyForeignRec, proxyForeign)
if proxyForeignRec.Code != http.StatusOK {
t.Fatalf("trusted proxy foreign origin status = %d, want 200", proxyForeignRec.Code)
}
router.WaitTopologyObservers()
// 4. Day 2: conflicting-header external client (foreign Origin + X-Requested-With).
currentNow = currentNow.AddDate(0, 0, 1)
foreignXHR := httptest.NewRequest(http.MethodGet, "http://pulse.local:7655/api/agent/topology", nil)
foreignXHR.Host = "pulse.local:7655"
foreignXHR.Header.Set("X-API-Token", "topo-read-e2e.12345678")
foreignXHR.Header.Set("Origin", "https://external-tool.example")
foreignXHR.Header.Set("X-Requested-With", "XMLHttpRequest")
foreignRec := httptest.NewRecorder()
router.Handler().ServeHTTP(foreignRec, foreignXHR)
if foreignRec.Code != http.StatusOK {
t.Fatalf("foreign XHR status = %d, want 200", foreignRec.Code)
}
router.WaitTopologyObservers()
// 5. Day 3: headerless direct HTTP API read.
currentNow = currentNow.AddDate(0, 0, 1)
directReq := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
directReq.Header.Set("X-API-Token", "topo-read-e2e.12345678")
directRec := httptest.NewRecorder()
router.Handler().ServeHTTP(directRec, directReq)
if directRec.Code != http.StatusOK {
t.Fatalf("direct API status = %d, want 200", directRec.Code)
}
router.WaitTopologyObservers()
// 6. Day 4: CLI read with anonymize=true.
currentNow = currentNow.AddDate(0, 0, 1)
cliReq := httptest.NewRequest(http.MethodGet, "/api/agent/topology?anonymize=true", nil)
cliReq.Header.Set("X-API-Token", "topo-read-e2e.12345678")
cliReq.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
cliRec := httptest.NewRecorder()
router.Handler().ServeHTTP(cliRec, cliReq)
if cliRec.Code != http.StatusOK {
t.Fatalf("CLI status = %d, want 200", cliRec.Code)
}
router.WaitTopologyObservers()
// 7. Day 5: MCP read without anonymize.
currentNow = currentNow.AddDate(0, 0, 1)
mcpReq := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
mcpReq.Header.Set("X-API-Token", "topo-read-e2e.12345678")
mcpReq.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseMCP)
mcpRec := httptest.NewRecorder()
router.Handler().ServeHTTP(mcpRec, mcpReq)
if mcpRec.Code != http.StatusOK {
t.Fatalf("MCP status = %d, want 200", mcpRec.Code)
}
router.WaitTopologyObservers()
snap = telemetry.Snapshot{}
router.ApplyInfrastructureMapTelemetrySnapshot(&snap, currentNow)
if !snap.InfrastructureMapTopologyTelemetryAvailable ||
snap.InfrastructureMapTopologyReadDays30d != 5 ||
snap.InfrastructureMapTopologyCLIDays30d != 1 ||
snap.InfrastructureMapTopologyMCPDays30d != 1 ||
snap.InfrastructureMapTopologyAnonymizedDays30d != 1 {
t.Fatalf("after proxy-foreign+xhr-foreign+direct+CLI+MCP reads: %+v", snap)
}
}
func TestApplyInfrastructureMapTelemetrySnapshotTopologyRootOnlyAndIntersection(t *testing.T) {
now := time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
rootDir := t.TempDir()
seeded := `{"version":1,"daily":{"topology_read":{"2026-11-29":1},"topology_cli":{"2026-11-30":1},"topology_mcp":{"2026-11-29":1,"2026-11-30":1}}}`
if err := os.WriteFile(filepath.Join(rootDir, "infrastructure_map_topology_tally.json"), []byte(seeded), 0o600); err != nil {
t.Fatalf("seed root tally: %v", err)
}
rootPersistence := config.NewConfigPersistence(rootDir)
snap := telemetry.Snapshot{}
(&Router{persistence: rootPersistence}).ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable ||
snap.InfrastructureMapTopologyReadDays30d != 1 ||
snap.InfrastructureMapTopologyCLIDays30d != 0 ||
snap.InfrastructureMapTopologyMCPDays30d != 1 {
t.Fatalf("orphan subset intersection failed: %+v, want avail=true 1/0/1", snap)
}
missingSnap := telemetry.Snapshot{
InfrastructureMapTopologyTelemetryAvailable: true,
InfrastructureMapTopologyReadDays30d: 3,
}
(&Router{persistence: config.NewConfigPersistence(t.TempDir())}).ApplyInfrastructureMapTelemetrySnapshot(&missingSnap, now)
if missingSnap.InfrastructureMapTopologyTelemetryAvailable || missingSnap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("missing root tally must report available=false with zero counts, got %+v", missingSnap)
}
for _, badPayload := range []string{
"{bad",
"null",
"",
`{"version":1,"daily":null}`,
`{"version":1,"daily":null,"daily":{}}`,
`{"version":1,"daily":{"topology_read":null}}`,
`{"version":1,"daily":{"topology_read":{"bad-date":1}}}`,
} {
corruptDir := t.TempDir()
if err := os.WriteFile(filepath.Join(corruptDir, "infrastructure_map_topology_tally.json"), []byte(badPayload), 0o600); err != nil {
t.Fatalf("seed corrupt root tally: %v", err)
}
corruptSnap := telemetry.Snapshot{
InfrastructureMapTopologyTelemetryAvailable: true,
InfrastructureMapTopologyReadDays30d: 9,
}
(&Router{persistence: config.NewConfigPersistence(corruptDir)}).ApplyInfrastructureMapTelemetrySnapshot(&corruptSnap, now)
if corruptSnap.InfrastructureMapTopologyTelemetryAvailable || corruptSnap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("payload %q must mark available=false with zero counts, got %+v", badPayload, corruptSnap)
}
}
baseDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(baseDir)
defaultP, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("get default persistence: %v", err)
}
tenantP, err := mtp.GetPersistence("org-a")
if err != nil {
t.Fatalf("get tenant persistence: %v", err)
}
if err := defaultP.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure default topology tally: %v", err)
}
if err := tenantP.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tenant topology tally: %v", err)
}
if err := defaultP.RecordInfrastructureMapTopologyReadDay(now, false, false, false); err != nil {
t.Fatalf("record default topology read: %v", err)
}
if err := tenantP.RecordInfrastructureMapTopologyReadDay(now.AddDate(0, 0, -1), true, true, true); err != nil {
t.Fatalf("seed stale tenant topology read: %v", err)
}
if err := tenantP.RecordInfrastructureMapActivity(config.InfrastructureMapActivityOpen, now); err != nil {
t.Fatalf("record tenant browser open: %v", err)
}
mtSnap := telemetry.Snapshot{}
(&Router{persistence: defaultP, multiTenant: mtp}).ApplyInfrastructureMapTelemetrySnapshot(&mtSnap, now)
if mtSnap.InfrastructureMapOpenSessions30d != 1 {
t.Fatalf("tenant browser opens = %d, want 1", mtSnap.InfrastructureMapOpenSessions30d)
}
if !mtSnap.InfrastructureMapTopologyTelemetryAvailable ||
mtSnap.InfrastructureMapTopologyReadDays30d != 1 ||
mtSnap.InfrastructureMapTopologyCLIDays30d != 0 ||
mtSnap.InfrastructureMapTopologyMCPDays30d != 0 ||
mtSnap.InfrastructureMapTopologyAnonymizedDays30d != 0 {
t.Fatalf("tenant topology markers leaked into root snapshot: %+v", mtSnap)
}
winP := config.NewConfigPersistence(t.TempDir())
if err := winP.EnsureInfrastructureMapTopologyTally(now.AddDate(0, 0, -30)); err != nil {
t.Fatalf("ensure winP: %v", err)
}
for offset := 30; offset >= 0; offset-- {
day := now.AddDate(0, 0, -offset)
if err := winP.RecordInfrastructureMapTopologyReadDay(day, offset < 5, offset < 3, offset < 4); err != nil {
t.Fatalf("record offset %d: %v", offset, err)
}
}
winSnap := telemetry.Snapshot{}
(&Router{persistence: winP}).ApplyInfrastructureMapTelemetrySnapshot(&winSnap, now)
if !winSnap.InfrastructureMapTopologyTelemetryAvailable ||
winSnap.InfrastructureMapTopologyReadDays30d != 30 ||
winSnap.InfrastructureMapTopologyCLIDays30d != 5 ||
winSnap.InfrastructureMapTopologyMCPDays30d != 3 ||
winSnap.InfrastructureMapTopologyAnonymizedDays30d != 4 {
t.Fatalf("30-day window mismatch: %+v", winSnap)
}
}
// High #2 regression: live settings updates via HandleUpdateSystemSettings and
// concurrent GET /api/agent/topology reads share config.Mu without data races.
func TestTopologyTelemetryRecordingConcurrentWithSystemSettingsToggle(t *testing.T) {
prevMock := mock.IsMockEnabled()
setMockEnabledForTest(t, false)
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
now := time.Now().UTC().Truncate(24 * time.Hour).Add(12 * time.Hour)
readTok := newTokenRecord(t, "topo-race-read.12345678", []string{config.ScopeMonitoringRead}, nil)
settingsTok := newTokenRecord(t, "topo-race-settings.12345678", []string{config.ScopeSettingsRead, config.ScopeSettingsWrite}, nil)
cfg := newTestConfigWithTokens(t, readTok, settingsTok)
cfg.TelemetryEnabled = true
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(cfg.DataPath), nil)
t.Cleanup(mtm.Stop)
router := newTestRouter(t, cfg, nil, mtm, nil, nil, "1.0.0")
router.topologyNow = func() time.Time { return now }
router.resourceHandlers.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
var wg sync.WaitGroup
errCh := make(chan error, 64)
// Writer goroutine toggling telemetryEnabled through the real HTTP settings endpoint.
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 24; i++ {
body := `{"telemetryEnabled":false,"pvePollingInterval":30,"disableDockerUpdateActions":true}`
if i%2 == 1 {
body = `{"telemetryEnabled":true,"pvePollingInterval":60,"disableDockerUpdateActions":false}`
}
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(body))
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &settingsTok))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-reload-settings.12345678")
req.Header.Set("X-API-Token", "topo-race-settings.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
errCh <- errors.New("settings toggle failed: " + rec.Body.String())
return
}
}
}()
// Reader goroutine performing real live GET /api/agent/topology requests concurrently.
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 24; i++ {
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", "topo-race-read.12345678")
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
errCh <- errors.New("topology read failed: " + rec.Body.String())
return
}
}
}()
// Runtime-display and admin /api/system/settings reader goroutines verifying shared config.Mu synchronization.
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 24; i++ {
req := httptest.NewRequest(http.MethodGet, "/api/runtime/display", nil)
req.Header.Set("X-API-Token", "topo-race-read.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
errCh <- errors.New("runtime display failed: " + rec.Body.String())
return
}
}
}()
go func() {
defer wg.Done()
for i := 0; i < 24; i++ {
req := httptest.NewRequest(http.MethodGet, "/api/system/settings", nil)
req.Header.Set("X-API-Token", "topo-race-settings.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
errCh <- errors.New("admin system settings GET failed: " + rec.Body.String())
return
}
}
}()
wg.Wait()
close(errCh)
for err := range errCh {
t.Fatal(err)
}
}
// High #3 regression: an unreadable or corrupt persisted opt-out in system.json
// while the topology tally directory remains writable must fail closed and
// record zero topology days (never falling back to default true).
func TestTopologyTelemetryFailsClosedWhenSavedOptOutIsUnreadable(t *testing.T) {
prevMock := mock.IsMockEnabled()
setMockEnabledForTest(t, false)
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
now := time.Now().UTC().Truncate(24 * time.Hour).Add(12 * time.Hour)
readTok := newTokenRecord(t, "topo-unreadable-optout.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := newTestConfigWithTokens(t, readTok)
// Simulate startup default true when system.json could not be read.
cfg.TelemetryEnabled = true
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
router.topologyNow = func() time.Time { return now }
router.resourceHandlers.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
// Persist an explicit opt-out first, then corrupt system.json while leaving
// the config directory and topology tally file fully writable.
optOut := false
if err := router.persistence.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &optOut}); err != nil {
t.Fatalf("save opt-out system.json: %v", err)
}
systemPath := filepath.Join(cfg.DataPath, "system.json")
if err := os.WriteFile(systemPath, []byte(`{"telemetryEnabled":false`), 0o600); err != nil {
t.Fatalf("corrupt system.json: %v", err)
}
if router.EffectiveTelemetryEnabled() {
t.Fatal("EffectiveTelemetryEnabled() = true for unreadable/corrupt system.json, want false")
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology?anonymize=true", nil)
req.Header.Set("X-API-Token", "topo-unreadable-optout.12345678")
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("topology status = %d, want 200", rec.Code)
}
// Even if the user later restores system.json with telemetryEnabled=true,
// the reads made while the saved opt-out was unreadable must not have been
// recorded into the tally.
optIn := true
if err := router.persistence.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &optIn}); err != nil {
t.Fatalf("save opt-in system.json: %v", err)
}
snap := telemetry.Snapshot{}
router.ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("unreadable opt-out recorded topology days: %+v", snap)
}
}
// Low #1 regression: completion timestamp is attributed to the UTC day captured
// at the post-write completion check, not delayed past settings I/O.
func TestTopologyReadObserverUsesCapturedCompletionTimestamp(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
beforeMidnight := time.Date(2026, 11, 20, 23, 59, 59, 900_000_000, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(beforeMidnight); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tok := newTokenRecord(t, "topo-midnight.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
r.recordInfrastructureMapTopologyReadDay(req, beforeMidnight, true, false, true)
tally, err := p.LoadInfrastructureMapTopologyTally()
if err != nil {
t.Fatalf("load tally: %v", err)
}
if tally.Daily[config.InfrastructureMapActivityTopologyRead]["2026-11-20"] != 1 {
t.Fatalf("expected read attributed to 2026-11-20, got %+v", tally.Daily)
}
if tally.Daily[config.InfrastructureMapActivityTopologyRead]["2026-11-21"] != 0 {
t.Fatalf("read leaked to next UTC day: %+v", tally.Daily)
}
}
// High #1 regression: case-insensitive JSON keys ("TelemetryEnabled": true)
// must be rejected when PULSE_TELEMETRY=false locks telemetry.
func TestSystemSettingsUpdateCaseInsensitiveKeyCannotBypassPulseTelemetryEnvLock(t *testing.T) {
dir := t.TempDir()
tok := newTokenRecord(t, "topo-envlock-case.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: false,
EnvOverrides: map[string]bool{
"PULSE_TELEMETRY": true,
"telemetryEnabled": true,
},
APITokens: []config.APITokenRecord{tok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
router := newTestRouter(t, cfg, nil, mtm, nil, nil, "1.0.0")
toggled := false
router.SetTelemetryToggleFunc(func(bool) { toggled = true })
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"TelemetryEnabled":true}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-envlock-case.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict for case-insensitive TelemetryEnabled under PULSE_TELEMETRY lock, got %d: %s", rec.Code, rec.Body.String())
}
if toggled || cfg.TelemetryEnabled || router.EffectiveTelemetryEnabled() {
t.Fatalf("case-insensitive key bypassed env lock: toggled=%v cfg=%v effective=%v", toggled, cfg.TelemetryEnabled, router.EffectiveTelemetryEnabled())
}
}
// High #2 regression: concurrent HandleSetLevel and HandleUpdateSystemSettings
// opt-out share atomic UpdateSystemSettings so a log-level save cannot restore
// telemetryEnabled=true after an opt-out commits.
func TestLogLevelUpdateCannotOverwriteConcurrentTelemetryOptOut(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
optIn := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &optIn, LogLevel: "info"}); err != nil {
t.Fatalf("seed system.json: %v", err)
}
settingsTok := newTokenRecord(t, "topo-lograce-settings.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
LogLevel: "info",
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
router := newTestRouter(t, cfg, nil, mtm, nil, nil, "1.0.0")
logHandler := NewLogHandlers(cfg, router.persistence)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 16; i++ {
level := "debug"
if i%2 == 1 {
level = "info"
}
req := httptest.NewRequest(http.MethodPost, "/api/logs/level", strings.NewReader(`{"level":"`+level+`"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
logHandler.HandleSetLevel(rec, req)
}
}()
go func() {
defer wg.Done()
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"telemetryEnabled":false}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-lograce-settings.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("opt-out failed: %d %s", rec.Code, rec.Body.String())
}
}()
wg.Wait()
loaded, err := router.persistence.LoadSystemSettings()
if err != nil || loaded == nil || loaded.TelemetryEnabled == nil || *loaded.TelemetryEnabled {
t.Fatalf("concurrent log-level update clobbered telemetry opt-out: loaded=%+v err=%v", loaded, err)
}
if router.EffectiveTelemetryEnabled() {
t.Fatal("EffectiveTelemetryEnabled() = true after opt-out")
}
}
// High #3 regression: corrupt or top-level null system.json fails closed and
// cannot be overwritten with defaults by an unrelated settings POST.
func TestCorruptOrNullSystemSettingsPreservedAndFailClosed(t *testing.T) {
for _, tc := range []struct {
name string
content string
}{
{name: "truncated JSON", content: `{"telemetryEnabled":false`},
{name: "top-level null", content: `null`},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
systemPath := filepath.Join(dir, "system.json")
if err := os.WriteFile(systemPath, []byte(tc.content), 0o600); err != nil {
t.Fatalf("write system.json: %v", err)
}
settingsTok := newTokenRecord(t, "topo-corrupt-settings.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
router := newTestRouter(t, cfg, nil, mtm, nil, nil, "1.0.0")
if router.EffectiveTelemetryEnabled() {
t.Fatal("EffectiveTelemetryEnabled() = true for corrupt/null system.json, want false")
}
// An unrelated settings POST must fail rather than overwriting system.json with defaults.
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"theme":"dark"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-corrupt-settings.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("unrelated settings POST on corrupt/null system.json = %d, want 500", rec.Code)
}
after, err := os.ReadFile(systemPath)
if err != nil || string(after) != tc.content {
t.Fatalf("system.json was modified: got=%q want=%q err=%v", string(after), tc.content, err)
}
})
}
}
// Medium #1 regression: a later opt-in between completion and observer
// execution cannot authorize a read completed while telemetry was disabled.
func TestTopologyReadCompletedWhileOptedOutIsNotRecordedAfterLaterOptIn(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tok := newTokenRecord(t, "topo-optin-after.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: false,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
h := NewAgentContextHandler(rh)
h.SetTopologyConsentSampler(r.topologyConsentSnapshot)
h.SetTopologyReadObserver(func(req *http.Request, completedAt time.Time, consented bool, anonymized bool, liveEligible bool) {
// Simulate an opt-in arriving between completion and persistence.
config.Mu.Lock()
cfg.TelemetryEnabled = true
config.Mu.Unlock()
r.recordInfrastructureMapTopologyReadDay(req, completedAt, consented, anonymized, liveEligible)
})
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec := httptest.NewRecorder()
h.HandleTopology(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
tally, err := p.LoadInfrastructureMapTopologyTally()
if err != nil {
t.Fatalf("load tally: %v", err)
}
if len(tally.Daily[config.InfrastructureMapActivityTopologyRead]) != 0 {
t.Fatalf("read completed while opted out was recorded after later opt-in: %+v", tally.Daily)
}
}
// Medium #5 regression: SetMonitor(nil) clears resourceHandlers's default
// stateProvider and invalidates cached registries so a retired monitor cannot
// remain certified as live.
func TestSetMonitorNilRetiresDefaultStateProviderAndStopsTopologyRecording(t *testing.T) {
prevMock := mock.IsMockEnabled()
setMockEnabledForTest(t, false)
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
now := time.Now().UTC().Truncate(24 * time.Hour).Add(12 * time.Hour)
readTok := newTokenRecord(t, "topo-retire-mon.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := newTestConfigWithTokens(t, readTok)
cfg.TelemetryEnabled = true
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
router.topologyNow = func() time.Time { return now }
router.resourceHandlers.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
// Clear monitor (e.g. failed reload) before any request on day+1.
router.SetMonitor(nil)
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", "topo-retire-mon.12345678")
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("topology after SetMonitor(nil) status = %d, want 200", rec.Code)
}
snap := telemetry.Snapshot{}
router.ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("retired default monitor still recorded topology read: %+v", snap)
}
}
type optInDuringWriteRecorder struct {
*httptest.ResponseRecorder
onWrite func()
}
func (r *optInDuringWriteRecorder) Write(p []byte) (int, error) {
if r.onWrite != nil {
r.onWrite()
}
return r.ResponseRecorder.Write(p)
}
// Medium #3 regression: an opt-in occurring DURING ResponseWriter.Write must
// NOT authorize recording a topology read that began while telemetry was off.
func TestTopologyReadOptInDuringWriteDoesNotRecord(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tok := newTokenRecord(t, "topo-optin-write.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: false,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
h := NewAgentContextHandler(rh)
h.SetTopologyFastEligibilityChecker(r.isTopologyRequestFastEligible)
h.SetTopologyConsentSampler(r.topologyConsentSnapshot)
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
rec := &optInDuringWriteRecorder{
ResponseRecorder: httptest.NewRecorder(),
onWrite: func() {
config.Mu.Lock()
cfg.TelemetryEnabled = true
AdvanceTelemetryConsentGeneration()
config.Mu.Unlock()
},
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
h.HandleTopology(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
tally, err := p.LoadInfrastructureMapTopologyTally()
if err != nil {
t.Fatalf("load tally: %v", err)
}
if len(tally.Daily[config.InfrastructureMapActivityTopologyRead]) != 0 {
t.Fatalf("opt-in during ResponseWriter.Write recorded topology day: %+v", tally.Daily)
}
}
// Medium #9 regression: conflicting case-fold aliases for telemetryEnabled must
// be rejected with 400 on POST and fail closed when persisted on disk.
func TestConflictingCaseAliasesForTelemetryEnabledRejectedAndFailClosed(t *testing.T) {
dir := t.TempDir()
settingsTok := newTokenRecord(t, "topo-alias-settings.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
router := newTestRouter(t, cfg, nil, mtm, nil, nil, "1.0.0")
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"telemetryEnabled":true,"TelemetryEnabled":false}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-alias-settings.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("conflicting case-fold POST status = %d, want 400: %s", rec.Code, rec.Body.String())
}
// Ambiguous aliases on disk must fail closed.
if err := os.WriteFile(filepath.Join(dir, "system.json"), []byte(`{"telemetryEnabled":true,"TelemetryEnabled":false}`), 0o600); err != nil {
t.Fatalf("write ambiguous system.json: %v", err)
}
if _, err := router.persistence.LoadSystemSettings(); err == nil {
t.Fatal("LoadSystemSettings succeeded on conflicting telemetryEnabled aliases, want error")
}
if router.EffectiveTelemetryEnabled() {
t.Fatal("EffectiveTelemetryEnabled() = true on conflicting aliases on disk, want false")
}
}
type blockingSupplementalProvider struct {
entered chan struct{}
release chan struct{}
records []unified.IngestRecord
}
func (b *blockingSupplementalProvider) SnapshotOwnedSources() []unified.DataSource {
return []unified.DataSource{unified.SourceAvailability}
}
func (b *blockingSupplementalProvider) GetCurrentRecords() []unified.IngestRecord {
select {
case <-b.entered:
default:
close(b.entered)
}
<-b.release
return b.records
}
// Medium #6 regression: an in-flight registry build for provider A that pauses
// across SetStateProvider(B) must not publish A's registry into B's cache even
// when B shares identical lastUpdate, thresholds, and provenance.
func TestResourceQueryServiceRetiredProviderBuildCannotPoisonReplacementCache(t *testing.T) {
prevMock := mock.IsMockEnabled()
setMockEnabledForTest(t, false)
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
sameTS := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
provA := &mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-from-A", Type: unified.ResourceTypeAgent, Name: "host-A", Status: unified.StatusOnline}},
lastUpdate: sameTS,
isMock: false,
}
provB := &mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-from-B", Type: unified.ResourceTypeAgent, Name: "host-B", Status: unified.StatusOnline}},
lastUpdate: sameTS,
isMock: false,
}
qs := resourceapi.NewQueryService(&config.Config{DataPath: t.TempDir()})
qs.SetStateProvider(provA)
blocker := &blockingSupplementalProvider{
entered: make(chan struct{}),
release: make(chan struct{}),
}
qs.SetSupplementalRecordsProvider(unified.SourceAvailability, blocker)
type buildResult struct {
prov resourceapi.RegistryProvenance
err error
}
buildDone := make(chan buildResult, 1)
go func() {
_, provA, err := qs.BuildRegistryWithProvenance("default")
buildDone <- buildResult{prov: provA, err: err}
}()
<-blocker.entered
// Replace provider A with B (and clear the blocking supplemental provider) while A's build is in flight.
qs.SetStateProvider(provB)
qs.SetSupplementalRecordsProvider(unified.SourceAvailability, nil)
close(blocker.release)
resA := <-buildDone
if resA.err != nil {
t.Fatalf("in-flight build A failed: %v", resA.err)
}
if resA.prov.ProvenanceVerified || !resA.prov.MonitorUnavailable || resA.prov.LiveTelemetryEligible() {
t.Fatalf("retired provider A returned live provenance %+v, want ProvenanceVerified=false MonitorUnavailable=true", resA.prov)
}
// Also verify SetStateProvider(nil) clears returned provenance eligibility.
blockerNil := &blockingSupplementalProvider{
entered: make(chan struct{}),
release: make(chan struct{}),
}
qs.SetSupplementalRecordsProvider(unified.SourceAvailability, blockerNil)
buildNilDone := make(chan buildResult, 1)
go func() {
_, prov, err := qs.BuildRegistryWithProvenance("default")
buildNilDone <- buildResult{prov: prov, err: err}
}()
<-blockerNil.entered
qs.SetStateProvider(nil)
qs.SetSupplementalRecordsProvider(unified.SourceAvailability, nil)
close(blockerNil.release)
resNil := <-buildNilDone
if resNil.err != nil {
t.Fatalf("in-flight build before nil retirement failed: %v", resNil.err)
}
if resNil.prov.ProvenanceVerified || !resNil.prov.MonitorUnavailable || resNil.prov.LiveTelemetryEligible() {
t.Fatalf("retired nil-provider build returned live provenance %+v, want ProvenanceVerified=false MonitorUnavailable=true", resNil.prov)
}
qs.SetStateProvider(provB)
regB, prov, err := qs.BuildRegistryWithProvenance("default")
if err != nil || !prov.LiveTelemetryEligible() {
t.Fatalf("BuildRegistryWithProvenance(B): prov=%+v err=%v", prov, err)
}
resources := regB.List()
if len(resources) != 1 || resources[0].ID != "node-from-B" {
t.Fatalf("retired provider A poisoned cache for B: got resources=%+v", resources)
}
}
// Medium #1 regression: a complete off->on consent cycle published through
// SaveSystemSettings (as in import/reload) during ResponseWriter.Write advances
// config.TelemetryConsentGeneration and prevents recording that topology read.
func TestTopologyReadSpanningPersistedOffOnCycleDoesNotRecord(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tok := newTokenRecord(t, "topo-offon-cycle.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
h := NewAgentContextHandler(rh)
h.SetTopologyFastEligibilityChecker(r.isTopologyRequestFastEligible)
h.SetTopologyConsentSampler(r.topologyConsentSnapshot)
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
var saveErr1, saveErr2 error
rec := &optInDuringWriteRecorder{
ResponseRecorder: httptest.NewRecorder(),
onWrite: func() {
f, tr := false, true
saveErr1 = p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &f})
saveErr2 = p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &tr})
},
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
h.HandleTopology(rec, req)
h.WaitTopologyObservers()
if saveErr1 != nil || saveErr2 != nil {
t.Fatalf("consent cycle saves failed: err1=%v err2=%v", saveErr1, saveErr2)
}
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
tally, err := p.LoadInfrastructureMapTopologyTally()
if err != nil {
t.Fatalf("load tally: %v", err)
}
if len(tally.Daily[config.InfrastructureMapActivityTopologyRead]) != 0 {
t.Fatalf("read spanning off->on persisted consent cycle was recorded: %+v", tally.Daily)
}
}
// Medium #5 regression: duplicate identical telemetryEnabled keys on POST
// (e.g. {"telemetryEnabled":false,"telemetryEnabled":true}) are rejected with 400.
func TestDuplicateIdenticalTelemetryKeyRejectedOnSettingsPOST(t *testing.T) {
dir := t.TempDir()
settingsTok := newTokenRecord(t, "topo-dupkey-settings.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: false,
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
router := newTestRouter(t, cfg, nil, mtm, nil, nil, "1.0.0")
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"telemetryEnabled":false,"telemetryEnabled":true}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-dupkey-settings.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("duplicate identical telemetryEnabled POST status = %d, want 400: %s", rec.Code, rec.Body.String())
}
if router.EffectiveTelemetryEnabled() {
t.Fatal("duplicate key request enabled telemetry")
}
}
// High #1 & Medium #2 regression: concurrent opt-out POSTs and real monitor
// reloads must never deadlock on config.Mu vs persistence.mu or race on shared
// config fields.
func TestUpdateSystemSettingsOptOutConcurrentWithRealMonitorReloadNoDeadlock(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
t.Setenv("PULSE_AUTH_CONFIG_DIR", dir)
t.Setenv("PULSE_TELEMETRY", "")
p := config.NewConfigPersistence(dir)
tr := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &tr, Theme: "dark"}); err != nil {
t.Fatalf("seed system settings: %v", err)
}
settingsTok := newTokenRecord(t, "topo-reload-settings.12345678", []string{config.ScopeSettingsWrite}, nil)
if err := p.SaveAPITokens([]config.APITokenRecord{settingsTok}); err != nil {
t.Fatalf("seed api tokens: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
DiscoveryEnabled: false,
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtp := config.NewMultiTenantPersistence(dir)
rm, err := monitoring.NewReloadableMonitor(cfg, mtp, nil)
if err != nil {
t.Fatalf("NewReloadableMonitor: %v", err)
}
rmCtx, rmCancel := context.WithCancel(context.Background())
rm.Start(rmCtx)
t.Cleanup(func() {
rmCancel()
rm.Stop()
})
handler := NewSystemSettingsHandler(cfg, p, nil, rm.GetMultiTenantMonitor(), nil, nil, nil)
done := make(chan struct{})
errCh := make(chan error, 8)
var wg sync.WaitGroup
// Concurrent opt-out and settings POSTs competing with real monitor reloads.
wg.Add(3)
go func() {
defer wg.Done()
for i := 0; i < 6; i++ {
body := `{"telemetryEnabled":false,"discoveryEnabled":true,"theme":"dark"}`
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(body))
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &settingsTok))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-reload-settings.12345678")
rec := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(rec, req)
if rec.Code != http.StatusOK {
errCh <- fmt.Errorf("POST opt-out status = %d body=%s", rec.Code, rec.Body.String())
return
}
}
}()
go func() {
defer wg.Done()
for i := 0; i < 2; i++ {
if err := rm.Reload(); err != nil {
errCh <- fmt.Errorf("rm.Reload() failed: %w", err)
return
}
}
}()
go func() {
defer wg.Done()
// Exercise synchronized config reads mirroring the production telemetry snapshot collector.
for i := 0; i < 40; i++ {
cur := rm.GetConfig()
if cur == nil {
cur = cfg
}
config.Mu.RLock()
_ = cur.DiscoveryEnabled
_ = cur.MultiTenantEnabled
_ = cur.HasAPITokens()
_ = cur.TelemetryEnabled
config.Mu.RUnlock()
time.Sleep(5 * time.Millisecond)
}
}()
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(15 * time.Second):
t.Fatal("deadlock detected between HandleUpdateSystemSettings opt-out POST and ReloadableMonitor.Reload")
}
close(errCh)
for err := range errCh {
t.Fatal(err)
}
}
// Low #1 regression: unrelated root saves (theme/logLevel without changing
// telemetryEnabled) and non-default tenant saves must not advance the root
// consent generation or discard an in-flight qualifying topology read.
func TestUnrelatedAndTenantSavesDoNotDiscardQualifyingTopologyRead(t *testing.T) {
dir := t.TempDir()
mtp := config.NewMultiTenantPersistence(dir)
p, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("GetPersistence(default): %v", err)
}
tenantP, err := mtp.GetPersistence("org-a")
if err != nil {
t.Fatalf("GetPersistence(org-a): %v", err)
}
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tr := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &tr, Theme: "dark"}); err != nil {
t.Fatalf("seed root settings: %v", err)
}
tok := newTokenRecord(t, "topo-unrelated-save.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
h := NewAgentContextHandler(rh)
h.SetTopologyFastEligibilityChecker(r.isTopologyRequestFastEligible)
h.SetTopologyConsentSampler(r.topologyConsentSnapshot)
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
rec := &optInDuringWriteRecorder{
ResponseRecorder: httptest.NewRecorder(),
onWrite: func() {
// Unrelated root setting write keeping telemetryEnabled=true.
_ = p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &tr, Theme: "light", LogLevel: "debug"})
// Tenant setting write flipping telemetryEnabled on a non-default org.
f := false
_ = tenantP.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &f})
},
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
h.HandleTopology(rec, req)
h.WaitTopologyObservers()
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
snap, avail, err := p.LoadInfrastructureMapTopologyTallySnapshot(now, 30)
if err != nil || !avail || snap == nil {
t.Fatalf("LoadInfrastructureMapTopologyTallySnapshot: avail=%v err=%v", avail, err)
}
if len(snap.Daily[config.InfrastructureMapActivityTopologyRead]) != 1 || len(snap.Daily[config.InfrastructureMapActivityTopologyCLI]) != 1 {
t.Fatalf("unrelated/tenant save discarded qualifying topology read: %+v", snap.Daily)
}
}
// Medium #2 regression: a telemetry-only settings PATCH must not revert an
// unrelated setting (e.g. theme/publicURL) committed by a concurrent backup
// import between the initial load and UpdateSystemSettings.
func TestTelemetryPatchDoesNotRevertConcurrentImportedSettings(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
tr := true
if err := p.SaveSystemSettings(config.SystemSettings{
TelemetryEnabled: &tr,
Theme: "light",
PublicURL: "https://old.example.test",
}); err != nil {
t.Fatalf("seed settings: %v", err)
}
settingsTok := newTokenRecord(t, "topo-patch-import.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
// Inject a concurrent import write right after the handler's initial
// LoadSystemSettings read, before UpdateSystemSettings runs.
var systemReads int
injected := false
p.SetFileSystem(&patchInterceptFS{
onRead: func(name string) {
if strings.HasSuffix(name, "system.json") {
systemReads++
if systemReads == 1 && !injected {
injected = true
// Simulate an imported system.json written right after initial read.
imported := `{"theme":"dark","publicURL":"https://imported.example.test","telemetryEnabled":true}`
_ = os.WriteFile(filepath.Join(dir, "system.json"), []byte(imported), 0o600)
}
}
},
})
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
handler := NewSystemSettingsHandler(cfg, p, nil, mtm, nil, nil, nil)
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"telemetryEnabled":false}`))
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &settingsTok))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-patch-import.12345678")
rec := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("PATCH status = %d body=%s", rec.Code, rec.Body.String())
}
saved, err := p.LoadSystemSettings()
if err != nil || saved == nil {
t.Fatalf("LoadSystemSettings: %v", err)
}
if saved.TelemetryEnabled == nil || *saved.TelemetryEnabled {
t.Fatalf("TelemetryEnabled = %v, want false", saved.TelemetryEnabled)
}
if saved.Theme != "dark" || saved.PublicURL != "https://imported.example.test" {
t.Fatalf("telemetry-only PATCH reverted concurrently imported settings: theme=%q publicURL=%q", saved.Theme, saved.PublicURL)
}
}
type patchInterceptFS struct {
onRead func(name string)
}
func (f *patchInterceptFS) ReadFile(name string) ([]byte, error) {
data, err := os.ReadFile(name)
if f.onRead != nil {
f.onRead(name)
}
return data, err
}
func (f *patchInterceptFS) WriteFile(name string, data []byte, perm os.FileMode) error {
return os.WriteFile(name, data, perm)
}
func (f *patchInterceptFS) CreateTemp(dir, pattern string) (config.TemporaryFile, error) {
return os.CreateTemp(dir, pattern)
}
func (f *patchInterceptFS) Rename(oldpath, newpath string) error { return os.Rename(oldpath, newpath) }
func (f *patchInterceptFS) Remove(name string) error { return os.Remove(name) }
func (f *patchInterceptFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) }
func (f *patchInterceptFS) MkdirAll(path string, perm os.FileMode) error {
return os.MkdirAll(path, perm)
}
// High #1 regression: a stalled opt-in telemetry toggle callback must NOT hold
// updateMu or prevent a subsequent opt-out POST from reaching persistence.
func TestStalledTelemetryOptInDoesNotBlockSubsequentOptOutPOST(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
fa := false
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &fa}); err != nil {
t.Fatalf("seed settings: %v", err)
}
settingsTok := newTokenRecord(t, "topo-stalled-optin.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: false,
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
handler := NewSystemSettingsHandler(cfg, p, nil, mtm, nil, nil, nil)
optInEntered := make(chan struct{})
optInRelease := make(chan struct{})
defer close(optInRelease)
handler.SetTelemetryToggleFunc(func(enabled bool) {
if enabled {
close(optInEntered)
<-optInRelease
}
})
optInDone := make(chan int, 1)
go func() {
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"telemetryEnabled":true}`))
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &settingsTok))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-stalled-optin.12345678")
rec := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(rec, req)
optInDone <- rec.Code
}()
<-optInEntered
// Subsequent opt-out POST must commit immediately without blocking on stalled opt-in.
start := time.Now()
reqOut := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"telemetryEnabled":false}`))
reqOut = reqOut.WithContext(internalauth.WithAPIToken(reqOut.Context(), &settingsTok))
reqOut.Header.Set("Content-Type", "application/json")
reqOut.Header.Set("X-API-Token", "topo-stalled-optin.12345678")
recOut := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(recOut, reqOut)
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("opt-out POST blocked behind stalled opt-in: took %v", elapsed)
}
if recOut.Code != http.StatusOK {
t.Fatalf("opt-out POST status = %d body=%s", recOut.Code, recOut.Body.String())
}
saved, err := p.LoadSystemSettings()
if err != nil || saved == nil || saved.TelemetryEnabled == nil || *saved.TelemetryEnabled {
t.Fatalf("opt-out did not persist false: saved=%+v err=%v", saved, err)
}
}
// High #2 regression: a stalled persistence write during settings POST must NOT
// hold config.Mu or block concurrent checkAuth readers.
func TestStalledSettingsSaveDoesNotBlockConfigMuReaders(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
tr := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &tr}); err != nil {
t.Fatalf("seed settings: %v", err)
}
settingsTok := newTokenRecord(t, "topo-stalled-save.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
writeEntered := make(chan struct{})
writeRelease := make(chan struct{})
var enteredOnce sync.Once
p.SetFileSystem(&blockingRenameFS{
onRename: func() {
enteredOnce.Do(func() { close(writeEntered) })
<-writeRelease
},
})
handler := NewSystemSettingsHandler(cfg, p, nil, mtm, nil, nil, nil)
postDone := make(chan int, 1)
go func() {
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"telemetryEnabled":false}`))
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &settingsTok))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-stalled-save.12345678")
rec := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(rec, req)
postDone <- rec.Code
}()
<-writeEntered
// Acquiring config.Mu.RLock (as checkAuth does) must succeed immediately while
// persistence rename is stalled.
authDone := make(chan struct{})
go func() {
config.Mu.RLock()
_ = cfg.HasAPITokens()
config.Mu.RUnlock()
close(authDone)
}()
select {
case <-authDone:
case <-time.After(time.Second):
close(writeRelease)
t.Fatal("config.Mu.RLock (checkAuth path) blocked on stalled settings persistence write")
}
close(writeRelease)
if code := <-postDone; code != http.StatusOK {
t.Fatalf("POST status = %d, want 200", code)
}
}
type blockingRenameFS struct {
onRename func()
}
func (f *blockingRenameFS) ReadFile(name string) ([]byte, error) { return os.ReadFile(name) }
func (f *blockingRenameFS) WriteFile(name string, data []byte, perm os.FileMode) error {
return os.WriteFile(name, data, perm)
}
func (f *blockingRenameFS) CreateTemp(dir, pattern string) (config.TemporaryFile, error) {
return os.CreateTemp(dir, pattern)
}
func (f *blockingRenameFS) Rename(oldpath, newpath string) error {
if f.onRename != nil && strings.HasSuffix(newpath, "system.json") {
f.onRename()
}
return os.Rename(oldpath, newpath)
}
func (f *blockingRenameFS) Remove(name string) error { return os.Remove(name) }
func (f *blockingRenameFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) }
func (f *blockingRenameFS) MkdirAll(path string, perm os.FileMode) error {
return os.MkdirAll(path, perm)
}
// Medium #5 regression: a telemetry-only POST must NOT overwrite unrelated
// runtime fields (such as DiscoveryEnabled or UpdateChannel) published by a
// concurrent import between disk commit and runtime publication.
func TestTelemetryOnlyPOSTDoesNotOverwriteUnrelatedRuntimeConfigFields(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
tr := true
if err := p.SaveSystemSettings(config.SystemSettings{
TelemetryEnabled: &tr,
DiscoveryEnabled: false,
UpdateChannel: "stable",
}); err != nil {
t.Fatalf("seed settings: %v", err)
}
settingsTok := newTokenRecord(t, "topo-runtime-only.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
DiscoveryEnabled: true, // Newer runtime value published by concurrent import
UpdateChannel: "rc", // Newer runtime value published by concurrent import
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
handler := NewSystemSettingsHandler(cfg, p, nil, mtm, nil, nil, nil)
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"telemetryEnabled":false}`))
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &settingsTok))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-runtime-only.12345678")
rec := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("POST status = %d body=%s", rec.Code, rec.Body.String())
}
config.Mu.RLock()
gotDiscovery := cfg.DiscoveryEnabled
gotChannel := cfg.UpdateChannel
gotTelemetry := cfg.TelemetryEnabled
config.Mu.RUnlock()
if gotTelemetry {
t.Fatal("expected TelemetryEnabled=false")
}
if !gotDiscovery || gotChannel != "rc" {
t.Fatalf("telemetry-only POST overwrote unrelated runtime fields: DiscoveryEnabled=%v UpdateChannel=%q", gotDiscovery, gotChannel)
}
}
// Medium #6 regression: conflicting differently-cased polling-interval keys
// (e.g. pbsPollingInterval + PBSPollingInterval) must be rejected with 400 so
// validation cannot approve one value while struct decoding persists another.
func TestConflictingCaseAliasPollingIntervalRejectedOnSettingsPOST(t *testing.T) {
dir := t.TempDir()
settingsTok := newTokenRecord(t, "topo-case-alias.12345678", []string{config.ScopeSettingsWrite}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
EnvOverrides: make(map[string]bool),
APITokens: []config.APITokenRecord{settingsTok},
}
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
router := newTestRouter(t, cfg, nil, mtm, nil, nil, "1.0.0")
for _, payload := range []string{
`{"pbsPollingInterval":60,"PBSPollingInterval":1}`,
`{"PBSPollingInterval":1}`,
} {
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-case-alias.12345678")
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("payload %s status = %d, want 400: %s", payload, rec.Code, rec.Body.String())
}
}
}
// Medium #7 regression: a stalled consent lookup must not block delivery of a
// completed GET /api/agent/topology HTTP response; it bounds the lookup,
// serves 200 OK promptly, and skips optional telemetry recording.
func TestHandleTopologyServesResponsePromptlyWhenConsentLookupStalls(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tok := newTokenRecord(t, "topo-stalled-consent.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
h := NewAgentContextHandler(rh)
h.SetTopologyFastEligibilityChecker(r.isTopologyRequestFastEligible)
release := make(chan struct{})
defer close(release)
h.SetTopologyConsentSampler(func() (uint64, bool) {
<-release
return 0, true
})
r.topologyNow = func() time.Time { return now }
h.SetTopologyDegradedNotifier(r.markInfrastructureMapTopologyDegradedInMemory)
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec := httptest.NewRecorder()
start := time.Now()
h.HandleTopology(rec, req)
elapsed := time.Since(start)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
if elapsed > 2*time.Second {
t.Fatalf("HandleTopology blocked on stalled consent lookup: took %v", elapsed)
}
tally, err := p.LoadInfrastructureMapTopologyTally()
if err != nil {
t.Fatalf("load tally: %v", err)
}
if len(tally.Daily[config.InfrastructureMapActivityTopologyRead]) != 0 {
t.Fatalf("timed-out consent lookup unexpectedly recorded a read day: %+v", tally.Daily)
}
// Pre-write consent was never established, so NO degraded sidecar or loss
// watermark may be persisted to disk (High #5).
p.WaitTopologyUncertaintyWrites()
var snap telemetry.Snapshot
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable {
t.Fatal("pre-write consent timeout should omit read without degrading coverage or writing loss watermark")
}
if _, err := os.Stat(filepath.Join(dir, "infrastructure_map_topology_tally.degraded.json")); !os.IsNotExist(err) {
t.Fatalf("pre-write consent timeout unexpectedly wrote degraded sidecar: %v", err)
}
// Now verify post-write consent timeout (AFTER affirmative pre-write consent)
// DOES mark the day unavailable.
var postCalls atomic.Int32
releasePost := make(chan struct{})
defer close(releasePost)
curGen := config.TelemetryConsentGeneration()
h.SetTopologyConsentSampler(func() (uint64, bool) {
if postCalls.Add(1) == 1 {
return curGen, true
}
<-releasePost
return curGen, true
})
rec2 := httptest.NewRecorder()
req2 := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req2 = req2.WithContext(internalauth.WithAPIToken(req2.Context(), &tok))
req2.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
h.HandleTopology(rec2, req2)
h.WaitTopologyObservers()
p.WaitTopologyUncertaintyWrites()
if rec2.Code != http.StatusOK {
t.Fatalf("post-write timeout status = %d, want 200", rec2.Code)
}
var snap2 telemetry.Snapshot
r.ApplyInfrastructureMapTelemetrySnapshot(&snap2, now)
if snap2.InfrastructureMapTopologyTelemetryAvailable {
t.Fatal("expected available=false after post-write consent lookup timeout following affirmative pre-write consent")
}
}
// Medium #2 regression: a stalled topology tally write on disk must not block
// HandleTopology from delivering 200 OK promptly, and snapshots taken while
// the write is still in-flight must report available=false.
func TestHandleTopologyServesResponsePromptlyWhenTallyWriteStalls(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tally: %v", err)
}
writeEntered := make(chan struct{})
releaseWrite := make(chan struct{})
p.SetFileSystem(&stallingTopologyWriteFS{
FileSystem: p.FileSystemForTest(),
onCreateTemp: func() {
select {
case <-writeEntered:
default:
close(writeEntered)
}
<-releaseWrite
},
})
tok := newTokenRecord(t, "topo-stalled-write.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p, topologyNow: func() time.Time { return now }}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
h := NewAgentContextHandler(rh)
h.SetTopologyFastEligibilityChecker(r.isTopologyRequestFastEligible)
h.SetTopologyConsentSampler(r.topologyConsentSnapshot)
h.SetTopologyDegradedNotifier(r.markInfrastructureMapTopologyDegradedInMemory)
h.SetTopologyPendingWriteHook(r.beginInfrastructureMapTopologyPendingWrite)
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec := httptest.NewRecorder()
// HandleTopology must return 200 OK while releaseWrite is still held closed,
// proving the stalled tally write never blocks HTTP response completion.
handlerDone := make(chan struct{})
go func() {
defer close(handlerDone)
h.HandleTopology(rec, req)
}()
select {
case <-handlerDone:
case <-time.After(10 * time.Second):
close(releaseWrite)
t.Fatal("HandleTopology blocked indefinitely on stalled tally write")
}
if rec.Code != http.StatusOK {
close(releaseWrite)
t.Fatalf("status = %d, want 200", rec.Code)
}
// While the async write is still in-flight, a snapshot must fail closed (available=false).
<-writeEntered
var snap telemetry.Snapshot
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if snap.InfrastructureMapTopologyTelemetryAvailable {
close(releaseWrite)
t.Fatal("expected available=false while async topology marker write is still in-flight")
}
// Release the stalled write and confirm the marker completes cleanly.
close(releaseWrite)
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
var after telemetry.Snapshot
r.ApplyInfrastructureMapTelemetrySnapshot(&after, now)
if after.InfrastructureMapTopologyTelemetryAvailable && after.InfrastructureMapTopologyReadDays30d == 1 && after.InfrastructureMapTopologyCLIDays30d == 1 {
return
}
time.Sleep(15 * time.Millisecond)
}
t.Fatal("timed out waiting for released async topology marker write to complete")
}
type stallingTopologyWriteFS struct {
config.FileSystem
onCreateTemp func()
}
func (s *stallingTopologyWriteFS) CreateTemp(dir, pattern string) (config.TemporaryFile, error) {
if s.onCreateTemp != nil {
s.onCreateTemp()
}
return s.FileSystem.CreateTemp(dir, pattern)
}
// Medium #5 regression: overlapping settings POSTs running both
// reloadSystemSettings and rm.Reload() concurrently must not data-race on
// r.config.EnvOverrides / r.config.HideLocalLogin under -race.
func TestOverlappingSettingsPOSTsReloadSystemSettingsAndMonitorReloadNoRace(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
settingsTok := newTokenRecord(t, "topo-reload-both.12345678", []string{config.ScopeSettingsWrite}, nil)
if err := p.SaveAPITokens([]config.APITokenRecord{settingsTok}); err != nil {
t.Fatalf("save api tokens: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{settingsTok},
EnvOverrides: make(map[string]bool),
}
cfg.SortAPITokens()
mtp := config.NewMultiTenantPersistence(dir)
rm, err := monitoring.NewReloadableMonitor(cfg, mtp, nil)
if err != nil {
t.Fatalf("NewReloadableMonitor: %v", err)
}
rmCtx, rmCancel := context.WithCancel(context.Background())
rm.Start(rmCtx)
t.Cleanup(func() {
rmCancel()
rm.Stop()
})
r := &Router{
config: cfg,
persistence: p,
monitor: rm.GetMonitor(),
mtMonitor: rm.GetMultiTenantMonitor(),
}
prodReload := func() error {
if err := rm.Reload(); err != nil {
return err
}
r.SetMonitor(rm.GetMonitor())
r.SetMultiTenantMonitor(rm.GetMultiTenantMonitor())
if nextCfg := rm.GetConfig(); nextCfg != nil {
r.SetConfig(nextCfg)
}
r.ReloadSystemSettings()
return nil
}
handler := NewSystemSettingsHandler(cfg, p, nil, rm.GetMultiTenantMonitor(), nil, r.reloadSystemSettings, prodReload)
var wg sync.WaitGroup
errCh := make(chan error, 8)
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 4; i++ {
body := fmt.Sprintf(`{"pvePollingInterval":%d,"hideLocalLogin":%t}`, 15+i, i%2 == 0)
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(body))
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &settingsTok))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-reload-both.12345678")
rec := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(rec, req)
if rec.Code != http.StatusOK {
errCh <- fmt.Errorf("POST pve reload status = %d body=%s", rec.Code, rec.Body.String())
return
}
}
}()
go func() {
defer wg.Done()
for i := 0; i < 8; i++ {
body := fmt.Sprintf(`{"hideLocalLogin":%t,"backupPollingEnabled":%t,"backupPollingInterval":%d,"theme":"dark"}`, i%2 == 1, i%2 == 0, 60+i*10)
req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(body))
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &settingsTok))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Token", "topo-reload-both.12345678")
rec := httptest.NewRecorder()
handler.HandleUpdateSystemSettings(rec, req)
if rec.Code != http.StatusOK {
errCh <- fmt.Errorf("POST hideLocalLogin status = %d body=%s", rec.Code, rec.Body.String())
return
}
}
}()
wg.Wait()
close(errCh)
for e := range errCh {
t.Fatal(e)
}
}
// Medium #7 regression: Unicode case-fold collisions (long s U+017F) must be
// rejected with 400, while a single mixed-case spelling (PBSPollingInterval)
// must validate, persist, AND apply to live runtime config consistently.
func TestUnicodeCaseFoldCollisionRejectedAndMixedCaseAppliesConsistently(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
tok := newTokenRecord(t, "topo-unicode-fold.12345678", []string{config.ScopeSettingsWrite}, nil)
if err := p.SaveAPITokens([]config.APITokenRecord{tok}); err != nil {
t.Fatalf("save api tokens: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{tok},
EnvOverrides: make(map[string]bool),
}
cfg.SortAPITokens()
mtm := monitoring.NewMultiTenantMonitor(cfg, config.NewMultiTenantPersistence(dir), nil)
t.Cleanup(mtm.Stop)
router := newTestRouter(t, cfg, nil, mtm, nil, nil, "6.0.0-beta.1")
// Unicode long-s U+017F folds to 's' under encoding/json and must be rejected.
badPayload := `{"pbsPollingInterval":60,"pbſPollingInterval":1}`
badReq := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(badPayload))
badReq.Header.Set("Content-Type", "application/json")
badReq.Header.Set("X-API-Token", "topo-unicode-fold.12345678")
badRec := httptest.NewRecorder()
router.Handler().ServeHTTP(badRec, badReq)
if badRec.Code != http.StatusBadRequest {
t.Fatalf("unicode fold collision status = %d, want 400: %s", badRec.Code, badRec.Body.String())
}
// Single valid mixed-case key must persist and apply to runtime config.
goodPayload := `{"PBSPollingInterval":45}`
goodReq := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(goodPayload))
goodReq.Header.Set("Content-Type", "application/json")
goodReq.Header.Set("X-API-Token", "topo-unicode-fold.12345678")
goodRec := httptest.NewRecorder()
router.Handler().ServeHTTP(goodRec, goodReq)
if goodRec.Code != http.StatusOK {
t.Fatalf("mixed-case valid payload status = %d, want 200: %s", goodRec.Code, goodRec.Body.String())
}
saved, err := p.LoadSystemSettings()
if err != nil {
t.Fatalf("load saved settings: %v", err)
}
if saved.PBSPollingInterval != 45 {
t.Fatalf("saved PBSPollingInterval = %d, want 45", saved.PBSPollingInterval)
}
}
// Medium #3 + Medium #4 regression: through the real token-authenticated route
// (retainTokenResponseAuthority / tokenResponseWriter without http.Flusher),
// HandleTopology returns 200 OK immediately without waiting on post-write
// consent verification or tally disk I/O, and client disconnect right after
// response completion does not drop the completed read.
func TestTokenAuthenticatedTopologyRouteServesPromptlyAndHandlesPostWriteDisconnect(t *testing.T) {
dir := t.TempDir()
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
tok := newTokenRecord(t, "topo-auth-async.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := newTestConfigWithTokens(t, tok)
cfg.DataPath = dir
cfg.ConfigPath = dir
cfg.TelemetryEnabled = true
router := newTestRouter(t, cfg, nil, nil, nil, nil, "6.0.0-beta.1")
router.topologyNow = func() time.Time { return now }
router.resourceHandlers.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
// Cancel the request context right after ServeHTTP returns while the post-write
// consent lookup is still waiting on releasePostConsent.
secondCallEntered := make(chan struct{})
releasePostConsent := make(chan struct{})
var calls atomic.Int32
curGen := config.TelemetryConsentGeneration()
router.agentContextHandler.SetTopologyConsentSampler(func() (uint64, bool) {
if calls.Add(1) == 2 {
close(secondCallEntered)
<-releasePostConsent
}
return curGen, true
})
reqCtx, cancelReq := context.WithCancel(context.Background())
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil).WithContext(reqCtx)
req.Header.Set("X-API-Token", "topo-auth-async.12345678")
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseMCP)
rec := httptest.NewRecorder()
served := make(chan struct{})
go func() {
defer close(served)
router.Handler().ServeHTTP(rec, req)
}()
select {
case <-served:
case <-time.After(5 * time.Second):
close(releasePostConsent)
t.Fatal("token-authenticated GET /api/agent/topology blocked on post-write consent lookup")
}
if rec.Code != http.StatusOK {
close(releasePostConsent)
t.Fatalf("status = %d, want 200", rec.Code)
}
// Simulate client disconnect right after response write completes.
<-secondCallEntered
cancelReq()
close(releasePostConsent)
router.WaitTopologyObservers()
var snap telemetry.Snapshot
router.ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 1 || snap.InfrastructureMapTopologyMCPDays30d != 1 {
t.Fatalf("post-write disconnect dropped completed read: %+v", snap)
}
}
// High #3 regression: with all three participants active (a stalled settings
// save holding c.mu, a concurrent monitor reload, and an unrelated
// authenticated API request), checkAuth must complete promptly without
// blocking on reload or the stalled settings save.
func TestStalledSettingsSaveAndMonitorReloadDoNotBlockUnrelatedCheckAuth(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
tokKeep := newTokenRecord(t, "topo-auth-live.12345678", []string{config.ScopeMonitoringRead}, nil)
tokRevoke := newTokenRecord(t, "topo-auth-revk.12345678", []string{config.ScopeMonitoringRead}, nil)
if err := p.SaveAPITokens([]config.APITokenRecord{tokKeep, tokRevoke}); err != nil {
t.Fatalf("save api tokens: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{tokKeep, tokRevoke},
EnvOverrides: make(map[string]bool),
}
cfg.SortAPITokens()
mtp := config.NewMultiTenantPersistence(dir)
rm, err := monitoring.NewReloadableMonitor(cfg, mtp, nil)
if err != nil {
t.Fatalf("NewReloadableMonitor: %v", err)
}
rmCtx, rmCancel := context.WithCancel(context.Background())
rm.Start(rmCtx)
t.Cleanup(func() {
rmCancel()
rm.Stop()
})
saveStarted := make(chan struct{})
releaseSave := make(chan struct{})
reloadAtTokenRead := make(chan struct{})
proceedReload := make(chan struct{})
monitoring.SetBeforeReloadTokenReadHookForTest(func() {
select {
case <-reloadAtTokenRead:
default:
close(reloadAtTokenRead)
}
<-proceedReload
})
t.Cleanup(func() { monitoring.SetBeforeReloadTokenReadHookForTest(nil) })
var stalledFirst atomic.Bool
p.SetFileSystem(&stallingTopologyWriteFS{
FileSystem: p.FileSystemForTest(),
onCreateTemp: func() {
if stalledFirst.CompareAndSwap(false, true) {
close(saveStarted)
<-releaseSave
}
},
})
// Participant 2: start monitor reload and pause deterministically right after
// tokenGenBefore is sampled and right before LoadAPITokenSnapshotForReload.
reloadDone := make(chan error, 1)
go func() {
reloadDone <- rm.Reload()
}()
<-reloadAtTokenRead
// Participant 1: start stalled settings save holding systemSettingsMu.
saveDone := make(chan error, 1)
go func() {
_, err := p.UpdateSystemSettings(func(s *config.SystemSettings) error {
s.Theme = "dark"
return nil
})
saveDone <- err
}()
<-saveStarted
// Participant 3: unrelated authenticated CheckAuth must complete immediately.
req := httptest.NewRequest(http.MethodGet, "/api/health", nil)
req.Header.Set("X-API-Token", "topo-auth-live.12345678")
authDone := make(chan bool, 1)
go func() {
authDone <- CheckAuth(cfg, httptest.NewRecorder(), req)
}()
select {
case ok := <-authDone:
if !ok {
close(proceedReload)
close(releaseSave)
<-saveDone
<-reloadDone
t.Fatal("CheckAuth returned false for valid token during stalled save + reload")
}
case <-time.After(2 * time.Second):
close(proceedReload)
close(releaseSave)
<-saveDone
<-reloadDone
t.Fatal("CheckAuth blocked behind reload + stalled settings save")
}
// Revoke tokRevoke in-memory BEFORE releasing reload; then verify Reload()
// finishes WITHOUT waiting on the stalled settings save (systemSettingsMu
// is isolated from c.mu) and does NOT resurrect tokRevoke.
config.Mu.Lock()
removed := cfg.RemoveAPIToken(tokRevoke.ID)
config.Mu.Unlock()
if removed == nil {
close(proceedReload)
close(releaseSave)
<-saveDone
<-reloadDone
t.Fatal("expected tokRevoke in live config")
}
close(proceedReload)
select {
case err := <-reloadDone:
if err != nil {
close(releaseSave)
<-saveDone
t.Fatalf("rm.Reload() failed: %v", err)
}
case <-time.After(2 * time.Second):
close(releaseSave)
<-saveDone
<-reloadDone
t.Fatal("rm.Reload() blocked behind stalled system.json save")
}
close(releaseSave)
if err := <-saveDone; err != nil {
t.Fatalf("settings save failed: %v", err)
}
// Re-check that tokKeep still works and tokRevoke was NOT resurrected by reload.
reqKeep := httptest.NewRequest(http.MethodGet, "/api/health", nil)
reqKeep.Header.Set("X-API-Token", "topo-auth-live.12345678")
if !CheckAuth(cfg, httptest.NewRecorder(), reqKeep) {
t.Fatal("expected tokKeep to remain valid after reload")
}
reqRevk := httptest.NewRequest(http.MethodGet, "/api/health", nil)
reqRevk.Header.Set("X-API-Token", "topo-auth-revk.12345678")
if CheckAuth(cfg, httptest.NewRecorder(), reqRevk) {
t.Fatal("revoked token was resurrected by monitor reload")
}
}
// Medium #7 regression: a read made after opt-out must bypass the consent
// lookup pool entirely (even if all 8 slots are saturated) and leave zero
// loss watermark or request-derived state on disk.
func TestReadAfterOptOutSkipsSaturatedConsentPoolAndWritesNoLossWatermark(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tok := newTokenRecord(t, "topo-optout-pool.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: false,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p, topologyNow: func() time.Time { return now }}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
h := NewAgentContextHandler(rh)
h.SetTopologyFastEligibilityChecker(r.isTopologyRequestFastEligible)
h.SetTopologyFastConsentChecker(r.isTopologyConsentFastPermitted)
h.SetTopologyDegradedNotifier(r.markInfrastructureMapTopologyDegradedInMemory)
h.SetTopologyConsentSampler(func() (uint64, bool) {
t.Fatal("consent sampler should not be entered after runtime opt-out")
return 0, false
})
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec := httptest.NewRecorder()
h.HandleTopology(rec, req)
h.WaitTopologyObservers()
p.WaitTopologyUncertaintyWrites()
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
// Coverage must stay clean (available=true with 0 reads) and no degraded sidecar created.
var snap telemetry.Snapshot
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("opt-out read unexpectedly degraded or recorded telemetry: %+v", snap)
}
if _, err := os.Stat(filepath.Join(dir, "infrastructure_map_topology_tally.degraded.json")); !os.IsNotExist(err) {
t.Fatalf("opt-out read unexpectedly created degraded sidecar: err=%v", err)
}
}
// High #2 regression: if opt-out commits while HandleTopology is writing the
// response body, even when the post-write recorder pool is saturated, the
// handler must discard loss evidence and write nothing to disk.
func TestOptOutDuringWriteWithSaturatedPoolWritesNoLossWatermark(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tok := newTokenRecord(t, "topo-optout-sat.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
}
r := &Router{config: cfg, persistence: p, topologyNow: func() time.Time { return now }}
rh := NewResourceHandlers(cfg)
rh.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
h := NewAgentContextHandler(rh)
h.SetTopologyFastEligibilityChecker(r.isTopologyRequestFastEligible)
h.SetTopologyFastConsentChecker(r.isTopologyConsentFastPermitted)
h.SetTopologyConsentSampler(r.topologyConsentSnapshot)
h.SetTopologyDegradedNotifier(r.markInfrastructureMapTopologyDegradedInMemory)
h.SetTopologyReadObserver(r.recordInfrastructureMapTopologyReadDay)
// Fill all post-write slots so the handler hits the saturation branch if it doesn't discard.
filled := 0
for filled < cap(topologyPostWriteSlots) {
select {
case topologyPostWriteSlots <- struct{}{}:
filled++
default:
t.Fatal("unexpected contention filling topologyPostWriteSlots")
}
}
defer func() {
for i := 0; i < filled; i++ {
<-topologyPostWriteSlots
}
}()
rec := &optInDuringWriteRecorder{
ResponseRecorder: httptest.NewRecorder(),
onWrite: func() {
config.Mu.Lock()
cfg.TelemetryEnabled = false
config.AdvanceTelemetryConsentGeneration()
config.Mu.Unlock()
},
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
h.HandleTopology(rec, req)
h.WaitTopologyObservers()
p.WaitTopologyUncertaintyWrites()
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
var snap telemetry.Snapshot
r.ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("opt-out during write with saturated pool degraded or recorded telemetry: %+v", snap)
}
if _, err := os.Stat(filepath.Join(dir, "infrastructure_map_topology_tally.degraded.json")); !os.IsNotExist(err) {
t.Fatalf("opt-out during write unexpectedly created degraded sidecar: err=%v", err)
}
}
// Medium #6 regression: exercising the actual DELETE /api/security/tokens/{id}
// revocation endpoint while a stalled settings save holds c.mu must NOT block
// unrelated CheckAuth callers across tenants, and the revocation must still
// commit cleanly once the stalled save completes.
func TestRealTokenRevocationEndpointBehindStalledSaveDoesNotBlockCheckAuth(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
adminTok := newTokenRecord(t, "topo-admin-rev.12345678", []string{config.ScopeWildcard}, nil)
targetTok := newTokenRecord(t, "topo-target-rv.12345678", []string{config.ScopeMonitoringRead}, nil)
otherTok := newTokenRecord(t, "topo-other-chk.12345678", []string{config.ScopeMonitoringRead}, nil)
if err := p.SaveAPITokens([]config.APITokenRecord{adminTok, targetTok, otherTok}); err != nil {
t.Fatalf("save api tokens: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{adminTok, targetTok, otherTok},
EnvOverrides: make(map[string]bool),
}
cfg.SortAPITokens()
router := newTestRouter(t, cfg, nil, nil, nil, nil, "6.0.0-beta.1")
router.persistence = p
saveStarted := make(chan struct{})
releaseSave := make(chan struct{})
var stalledFirst atomic.Bool
p.SetFileSystem(&stallingTopologyWriteFS{
FileSystem: p.FileSystemForTest(),
onCreateTemp: func() {
// Stall only UpdateSystemSettings's system.json write (the first CreateTemp).
if stalledFirst.CompareAndSwap(false, true) {
close(saveStarted)
<-releaseSave
}
},
})
// Participant 1: stalled settings save holding systemSettingsMu (NOT c.mu).
saveDone := make(chan error, 1)
go func() {
_, err := p.UpdateSystemSettings(func(s *config.SystemSettings) error {
s.Theme = "dark"
return nil
})
saveDone <- err
}()
<-saveStarted
// Participant 2: real HTTP DELETE /api/security/tokens/{id} must complete
// immediately WITHOUT blocking on the stalled system.json save.
delRec := httptest.NewRecorder()
delReq := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/"+targetTok.ID, nil)
delReq.Header.Set("X-API-Token", "topo-admin-rev.12345678")
delDone := make(chan struct{})
go func() {
defer close(delDone)
router.Handler().ServeHTTP(delRec, delReq)
}()
select {
case <-delDone:
case <-time.After(2 * time.Second):
close(releaseSave)
<-saveDone
<-delDone
t.Fatal("real DELETE /api/security/tokens/{id} blocked behind stalled system.json save")
}
// Participant 3: unrelated authenticated CheckAuth must complete immediately
// while the settings save is still stalled.
chkReq := httptest.NewRequest(http.MethodGet, "/api/health", nil)
chkReq.Header.Set("X-API-Token", "topo-other-chk.12345678")
authDone := make(chan bool, 1)
go func() {
authDone <- CheckAuth(cfg, httptest.NewRecorder(), chkReq)
}()
select {
case ok := <-authDone:
if !ok {
close(releaseSave)
<-saveDone
t.Fatal("unrelated CheckAuth returned false")
}
case <-time.After(2 * time.Second):
close(releaseSave)
<-saveDone
t.Fatal("unrelated CheckAuth blocked behind stalled settings save")
}
close(releaseSave)
if err := <-saveDone; err != nil {
t.Fatalf("settings save failed: %v", err)
}
if delRec.Code != http.StatusOK && delRec.Code != http.StatusNoContent {
t.Fatalf("DELETE token status = %d body=%s", delRec.Code, delRec.Body.String())
}
// Verify targetTok is revoked both in memory and in persisted api_tokens.json.
revkReq := httptest.NewRequest(http.MethodGet, "/api/health", nil)
revkReq.Header.Set("X-API-Token", "topo-target-rv.12345678")
if CheckAuth(cfg, httptest.NewRecorder(), revkReq) {
t.Fatal("deleted token still authenticated after DELETE completed")
}
diskTokens, _, err := p.LoadAPITokenSnapshotForReload()
if err != nil {
t.Fatalf("reload persisted tokens: %v", err)
}
for _, rec := range diskTokens {
if rec.ID == targetTok.ID {
t.Fatalf("deleted token %s still present on disk", targetTok.ID)
}
}
}
// Medium #6 regression: a token that expires before response completion must be
// discarded before post-write observer slot admission so it never records a
// saturation loss watermark.
func TestExpiredTokenAtCompletionSkipsSaturationLossWatermark(t *testing.T) {
prevMock := mock.IsMockEnabled()
setMockEnabledForTest(t, false)
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
day0 := time.Now().UTC().Truncate(time.Second)
runCase := func(t *testing.T, expireDuringWrite bool, revokeDuringWrite bool) (avail bool) {
t.Helper()
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
if err := p.EnsureInfrastructureMapTopologyTally(day0); err != nil {
t.Fatalf("ensure tally: %v", err)
}
expiresAt := day0.Add(2 * time.Minute)
tok := newTokenRecord(t, "topo-exp-compl.12345678", []string{config.ScopeMonitoringRead}, nil)
tok.ExpiresAt = &expiresAt
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{tok},
EnvOverrides: make(map[string]bool),
}
cfg.SortAPITokens()
router := newTestRouter(t, cfg, nil, nil, nil, nil, "6.0.0-beta.1")
router.persistence = p
// Wire a real non-mock provenance provider so HandleTopology reaches
// the completion token check and post-write saturation path.
router.resourceHandlers.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{
{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline},
},
lastUpdate: day0,
isMock: false,
})
var clockNow atomic.Int64
clockNow.Store(day0.UnixNano())
router.topologyNow = func() time.Time {
return time.Unix(0, clockNow.Load()).UTC()
}
filled := 0
for filled < cap(topologyPostWriteSlots) {
topologyPostWriteSlots <- struct{}{}
filled++
}
defer func() {
for filled > 0 {
<-topologyPostWriteSlots
filled--
}
}()
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", "topo-exp-compl.12345678")
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
rec := &clockAdvancingResponseRecorder{
ResponseRecorder: httptest.NewRecorder(),
onWrite: func() {
if expireDuringWrite {
clockNow.Store(expiresAt.Add(time.Minute).UnixNano())
}
if revokeDuringWrite {
config.Mu.Lock()
cfg.RemoveAPIToken(tok.ID)
config.Mu.Unlock()
}
},
}
router.agentContextHandler.HandleTopology(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("HandleTopology status = %d body=%s", rec.Code, rec.Body.String())
}
p.WaitTopologyUncertaintyWrites()
_, available, err := p.LoadInfrastructureMapTopologyTallySnapshot(day0, 30)
if err != nil {
t.Fatalf("snapshot err: %v", err)
}
return available
}
// Paired unexpired control MUST hit the saturated post-write pool and record a loss watermark.
if avail := runCase(t, false, false); avail {
t.Fatal("unexpired control under saturated pool must record a saturation loss watermark (avail=false)")
}
// Expired-during-write case MUST be rejected before slot admission and leave coverage healthy.
if avail := runCase(t, true, false); !avail {
t.Fatal("expired token at completion must not record a saturation loss watermark (want avail=true)")
}
// Revoked-during-write case MUST be rejected by live-inventory revalidation before slot admission.
if avail := runCase(t, false, true); !avail {
t.Fatal("revoked token at completion must not record a saturation loss watermark (want avail=true)")
}
}
// High #5 regression: an external disk opt-out (system.json edited to
// telemetryEnabled=false) during a response under a saturated post-write pool
// must write zero sidecar loss state to disk.
func TestExternalDiskOptOutDuringSaturatedPoolWritesZeroSidecarState(t *testing.T) {
prevMock := mock.IsMockEnabled()
setMockEnabledForTest(t, false)
t.Cleanup(func() { setMockEnabledForTest(t, prevMock) })
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
day0 := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(day0); err != nil {
t.Fatalf("ensure tally: %v", err)
}
trueVal := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &trueVal}); err != nil {
t.Fatalf("save initial system.json: %v", err)
}
tok := newTokenRecord(t, "topo-ext-optout.12345678", []string{config.ScopeMonitoringRead}, nil)
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{tok},
EnvOverrides: make(map[string]bool),
}
cfg.SortAPITokens()
router := newTestRouter(t, cfg, nil, nil, nil, nil, "6.0.0-beta.1")
router.persistence = p
router.resourceHandlers.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{
{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline},
},
lastUpdate: day0,
isMock: false,
})
router.topologyNow = func() time.Time { return day0 }
filled := 0
for filled < cap(topologyPostWriteSlots) {
topologyPostWriteSlots <- struct{}{}
filled++
}
defer func() {
for filled > 0 {
<-topologyPostWriteSlots
filled--
}
}()
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", "topo-ext-optout.12345678")
req = req.WithContext(internalauth.WithAPIToken(req.Context(), &tok))
rec := &clockAdvancingResponseRecorder{
ResponseRecorder: httptest.NewRecorder(),
onWrite: func() {
// Simulate external disk edit setting telemetryEnabled=false while
// in-memory cfg.TelemetryEnabled and TelemetryConsentGeneration stay unchanged.
_ = os.WriteFile(filepath.Join(dir, "system.json"), []byte(`{"telemetryEnabled":false}`), 0o600)
},
}
router.agentContextHandler.HandleTopology(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("HandleTopology status = %d", rec.Code)
}
p.WaitTopologyUncertaintyWrites()
// Degraded sidecar file must NOT exist on disk after external opt-out!
sidecarPath := filepath.Join(dir, "infrastructure_map_topology_tally.degraded.json")
if _, err := os.Stat(sidecarPath); !os.IsNotExist(err) {
t.Fatalf("expected zero degraded sidecar file after external disk opt-out, stat err=%v", err)
}
}
// High #3 regression: stalled system.json save + waiting ImportConfig + watcher
// token reload must NEVER block unrelated CheckAuth across tenants.
func TestStalledSettingsSaveWaitingImportAndWatcherDoNotBlockCheckAuth(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
tok := newTokenRecord(t, "topo-3way-auth.12345678", []string{config.ScopeMonitoringRead}, nil)
if err := p.SaveAPITokens([]config.APITokenRecord{tok}); err != nil {
t.Fatalf("save tokens: %v", err)
}
exported, err := p.ExportConfig("test-passphrase-1234")
if err != nil {
t.Fatalf("export config: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{tok},
EnvOverrides: make(map[string]bool),
}
cfg.SortAPITokens()
saveStarted := make(chan struct{})
releaseSave := make(chan struct{})
var stalledFirst atomic.Bool
p.SetFileSystem(&stallingTopologyWriteFS{
FileSystem: p.FileSystemForTest(),
onCreateTemp: func() {
if stalledFirst.CompareAndSwap(false, true) {
close(saveStarted)
<-releaseSave
}
},
})
// Participant 1: stalled settings save holding systemSettingsMu.
saveDone := make(chan error, 1)
go func() {
_, err := p.UpdateSystemSettings(func(s *config.SystemSettings) error {
s.Theme = "dark"
return nil
})
saveDone <- err
}()
<-saveStarted
importAtLock := make(chan struct{})
config.SetBeforeImportLockHookForTest(func() {
select {
case <-importAtLock:
default:
close(importAtLock)
}
})
t.Cleanup(func() { config.SetBeforeImportLockHookForTest(nil) })
// Participant 2: ImportConfig decrypts and deterministically reaches its
// lock boundary (queued on systemSettingsMu, NOT holding c.mu!).
importDone := make(chan error, 1)
go func() {
importDone <- p.ImportConfig(exported, "test-passphrase-1234")
}()
<-importAtLock
// Participant 3: real ConfigWatcher token reload (acquiring config.Mu -> c.mu)
// AND unrelated CheckAuth (config.Mu.RLock) must BOTH complete promptly
// while save is stalled on systemSettingsMu and ImportConfig is queued on it.
watcher, err := config.NewConfigWatcher(cfg)
if err != nil {
close(releaseSave)
<-saveDone
<-importDone
t.Fatalf("NewConfigWatcher: %v", err)
}
watchDone := make(chan struct{})
go func() {
defer close(watchDone)
watcher.ReloadAPITokensForTest()
}()
select {
case <-watchDone:
case <-time.After(2 * time.Second):
close(releaseSave)
<-saveDone
<-importDone
t.Fatal("ConfigWatcher.ReloadAPITokens blocked behind waiting ImportConfig + stalled settings save")
}
chkReq := httptest.NewRequest(http.MethodGet, "/api/health", nil)
chkReq.Header.Set("X-API-Token", "topo-3way-auth.12345678")
if !CheckAuth(cfg, httptest.NewRecorder(), chkReq) {
close(releaseSave)
<-saveDone
<-importDone
t.Fatal("CheckAuth returned false")
}
close(releaseSave)
if err := <-saveDone; err != nil {
t.Fatalf("settings save failed: %v", err)
}
if err := <-importDone; err != nil {
t.Fatalf("ImportConfig failed: %v", err)
}
}
type clockAdvancingResponseRecorder struct {
*httptest.ResponseRecorder
onWrite func()
}
func (c *clockAdvancingResponseRecorder) Write(p []byte) (int, error) {
if c.onWrite != nil {
c.onWrite()
}
return c.ResponseRecorder.Write(p)
}
// High #7 regression: if telemetry is disabled on disk while the background
// loss drainer is blocked waiting on topologyMu, the post-lock confirmation at
// the persistence boundary must discard the request-derived day and write zero
// sidecar bytes to disk.
func TestOptOutWhileDrainerWaitsOnTopologyMuWritesZeroSidecarBytes(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
day0 := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(day0); err != nil {
t.Fatalf("ensure tally: %v", err)
}
trueVal := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &trueVal}); err != nil {
t.Fatalf("save system.json: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
}
router := newTestRouter(t, cfg, nil, nil, nil, nil, "6.0.0-beta.1")
router.persistence = p
drainerAtLock := make(chan struct{})
config.SetBeforeTopologyDrainerLockHookForTest(func() {
select {
case <-drainerAtLock:
default:
close(drainerAtLock)
}
})
t.Cleanup(func() { config.SetBeforeTopologyDrainerLockHookForTest(nil) })
// Stall a legitimate marker write holding topologyMu so the background
// drainer deterministically reaches and blocks on topologyMu.Lock().
writeStarted := make(chan struct{})
releaseWrite := make(chan struct{})
var stalledOnce atomic.Bool
p.SetFileSystem(&stallingTopologyWriteFS{
FileSystem: p.FileSystemForTest(),
onCreateTemp: func() {
if stalledOnce.CompareAndSwap(false, true) {
close(writeStarted)
<-releaseWrite
}
},
})
markerDone := make(chan error, 1)
go func() {
markerDone <- p.RecordInfrastructureMapTopologyReadDay(day0, true, false, false)
}()
<-writeStarted
// Queue a request-derived loss while opted in and wait until the drainer
// has deterministically reached its topologyMu.Lock() boundary BEFORE opt-out.
consentGen := config.TelemetryConsentGeneration()
p.RecordInfrastructureMapTopologyRequestLossWithConsentGen(day0, consentGen)
<-drainerAtLock
// Flip system.json to telemetryEnabled=false AFTER drainer reached topologyMu.Lock()
// and BEFORE releasing topologyMu.
if err := os.WriteFile(filepath.Join(dir, "system.json"), []byte(`{"telemetryEnabled":false}`), 0o600); err != nil {
close(releaseWrite)
<-markerDone
t.Fatalf("write opt-out system.json: %v", err)
}
close(releaseWrite)
if err := <-markerDone; err != nil {
t.Fatalf("marker write failed: %v", err)
}
p.WaitTopologyUncertaintyWrites()
sidecarPath := filepath.Join(dir, "infrastructure_map_topology_tally.degraded.json")
if _, err := os.Stat(sidecarPath); !os.IsNotExist(err) {
t.Fatalf("expected zero degraded sidecar after opt-out during topologyMu wait, stat err=%v", err)
}
}
// High #4 regression: rotating the admin password via handleChangePassword and
// then running a separate config.LoadWithoutLoggingInit() reload must keep the
// rotated password hash instead of reinstating the pre-rotation startup hash
// loaded into the process environment by godotenv.Load.
func TestPasswordRotationSurvivesSubsequentConfigReloadFromEnv(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
t.Setenv("PULSE_DOCKER", "false")
// Clear any inherited env vars and isolate cleanup.
t.Setenv("PULSE_AUTH_USER", "")
t.Setenv("PULSE_AUTH_PASS", "")
_ = os.Unsetenv("PULSE_AUTH_USER")
_ = os.Unsetenv("PULSE_AUTH_PASS")
oldHash, err := internalauth.HashPassword("OldPassword123!")
if err != nil {
t.Fatalf("hash old password: %v", err)
}
envPath := filepath.Join(dir, ".env")
if err := os.WriteFile(envPath, []byte("PULSE_AUTH_USER='admin'\nPULSE_AUTH_PASS='"+oldHash+"'\n"), 0o600); err != nil {
t.Fatalf("write initial .env: %v", err)
}
// Simulate startup loading .env into process environment via LoadWithoutLoggingInit.
cfg, err := config.LoadWithoutLoggingInit()
if err != nil {
t.Fatalf("initial LoadWithoutLoggingInit: %v", err)
}
if cfg.AuthPass != oldHash {
t.Fatalf("expected initial AuthPass to match oldHash")
}
router := newTestRouter(t, cfg, nil, nil, nil, nil, "6.0.0-beta.1")
body := `{"currentPassword":"OldPassword123!","newPassword":"NewPassword456!"}`
req := httptest.NewRequest(http.MethodPost, "/api/security/change-password", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth("admin", "OldPassword123!")
rec := httptest.NewRecorder()
router.handleChangePassword(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("handleChangePassword status=%d body=%s", rec.Code, rec.Body.String())
}
// Now run a completely separate reload (after AuthEnvRevision already settled).
reloaded, err := config.LoadWithoutLoggingInit()
if err != nil {
t.Fatalf("subsequent LoadWithoutLoggingInit: %v", err)
}
if !internalauth.CheckPasswordHash("NewPassword456!", reloaded.AuthPass) {
t.Fatalf("subsequent reload reinstated stale password hash instead of rotated password")
}
if internalauth.CheckPasswordHash("OldPassword123!", reloaded.AuthPass) {
t.Fatalf("subsequent reload still accepts pre-rotation password")
}
// Medium #6 regression: when .env already exists WITHOUT a PULSE_AUTH_PASS=
// line (e.g. password came from deployment env), handleChangePassword must
// append PULSE_AUTH_PASS= so a fresh process reload loads the rotated hash.
t.Run("ExistingEnvWithoutPassKeySurvivesFreshProcessReload", func(t *testing.T) {
dir2 := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir2)
t.Setenv("PULSE_DOCKER", "false")
envPath2 := filepath.Join(dir2, ".env")
if err := os.WriteFile(envPath2, []byte("PULSE_AUTH_USER='admin'\n"), 0o600); err != nil {
t.Fatalf("write .env without pass: %v", err)
}
t.Setenv("PULSE_AUTH_USER", "admin")
t.Setenv("PULSE_AUTH_PASS", oldHash)
cfg2, err := config.LoadWithoutLoggingInit()
if err != nil {
t.Fatalf("LoadWithoutLoggingInit: %v", err)
}
router2 := newTestRouter(t, cfg2, nil, nil, nil, nil, "6.0.0-beta.1")
req2 := httptest.NewRequest(http.MethodPost, "/api/security/change-password", strings.NewReader(body))
req2.Header.Set("Content-Type", "application/json")
req2.SetBasicAuth("admin", "OldPassword123!")
rec2 := httptest.NewRecorder()
router2.handleChangePassword(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("handleChangePassword status=%d body=%s", rec2.Code, rec2.Body.String())
}
// Simulate a fresh process where PULSE_AUTH_PASS is not pre-populated in env.
_ = os.Unsetenv("PULSE_AUTH_PASS")
_ = os.Unsetenv("PULSE_AUTH_USER")
fresh, err := config.LoadWithoutLoggingInit()
if err != nil {
t.Fatalf("fresh LoadWithoutLoggingInit: %v", err)
}
if !internalauth.CheckPasswordHash("NewPassword456!", fresh.AuthPass) {
t.Fatalf("fresh process reload failed to load appended rotated password from .env")
}
if internalauth.CheckPasswordHash("OldPassword123!", fresh.AuthPass) {
t.Fatalf("fresh process reload still accepts old password")
}
})
}
// High #1 regression: an opt-out arriving AFTER initial consent confirmation
// inside RecordInfrastructureMapTopologyReadDayWithConsentGen and BEFORE the
// primary tally write must wait on the topologyMu commit barrier, abort the
// pending write cleanly, and leave zero request-derived bytes on disk.
func TestOptOutAfterConsentConfirmBeforePrimaryWriteWritesZeroBytes(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
tr := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &tr}); err != nil {
t.Fatalf("enable telemetry: %v", err)
}
day0 := time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(day0); err != nil {
t.Fatalf("ensure tally: %v", err)
}
tallyPath := filepath.Join(dir, "infrastructure_map_topology_tally.json")
sidecarPath := filepath.Join(dir, "infrastructure_map_topology_tally.degraded.json")
beforeBytes, err := os.ReadFile(tallyPath)
if err != nil {
t.Fatalf("read initial tally: %v", err)
}
genBefore := config.TelemetryConsentGeneration()
hookEntered := make(chan struct{})
releaseHook := make(chan struct{})
var hookOnce sync.Once
config.SetBeforeTopologyPrimaryWriteHookForTest(func() {
hookOnce.Do(func() {
close(hookEntered)
<-releaseHook
})
})
t.Cleanup(func() { config.SetBeforeTopologyPrimaryWriteHookForTest(nil) })
writerDone := make(chan error, 1)
go func() {
writerDone <- p.RecordInfrastructureMapTopologyReadDayWithConsentGen(day0, true, false, false, genBefore)
}()
select {
case <-hookEntered:
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for writer to reach pre-primary-write hook")
}
// Commit opt-out while the writer is paused inside topologyMu right before writing.
f := false
optOutDone := make(chan error, 1)
go func() {
optOutDone <- p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &f})
}()
// Deterministically wait until SaveSystemSettings has persisted system.json
// and advanced TelemetryConsentGeneration() before confirming it is blocked
// on the topologyMu commit barrier.
deadline := time.Now().Add(5 * time.Second)
for config.TelemetryConsentGeneration() == genBefore {
if time.Now().After(deadline) {
close(releaseHook)
t.Fatal("timed out waiting for SaveSystemSettings to advance consent generation")
}
select {
case err := <-optOutDone:
close(releaseHook)
t.Fatalf("opt-out returned before advancing generation or waiting on topologyMu (err=%v)", err)
case <-time.After(2 * time.Millisecond):
}
}
select {
case err := <-optOutDone:
close(releaseHook)
t.Fatalf("opt-out returned before in-flight topology writer exited topologyMu (err=%v)", err)
case <-time.After(20 * time.Millisecond):
}
close(releaseHook)
if err := <-writerDone; err != nil {
t.Fatalf("writer returned error: %v", err)
}
if err := <-optOutDone; err != nil {
t.Fatalf("opt-out SaveSystemSettings failed: %v", err)
}
afterBytes, err := os.ReadFile(tallyPath)
if err != nil {
t.Fatalf("read tally after opt-out: %v", err)
}
if string(afterBytes) != string(beforeBytes) {
t.Fatalf("primary tally was modified after opt-out: before=%s after=%s", string(beforeBytes), string(afterBytes))
}
if _, err := os.Stat(sidecarPath); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected zero degraded sidecar bytes after opt-out, got stat err=%v", err)
}
}
// Medium #1 regression: a transient root import consent fence during loss
// draining must NOT erase the in-memory request loss day into a false healthy
// zero; it keeps available=false with zero disk writes until the fence clears,
// then persists the loss cleanly once rollback confirms consent stays enabled.
func TestTransientImportFenceDuringLossDrainKeepsLossInMemoryAndRecoversOnRollback(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
tr := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &tr}); err != nil {
t.Fatalf("enable telemetry: %v", err)
}
day := time.Date(2026, 12, 1, 11, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(day); err != nil {
t.Fatalf("ensure tally: %v", err)
}
sidecarPath := filepath.Join(dir, "infrastructure_map_topology_tally.degraded.json")
gen := config.TelemetryConsentGeneration()
endFence := config.BeginRootImportConsentFence()
p.RecordInfrastructureMapTopologyRequestLossWithConsentGen(day, gen)
p.WaitTopologyUncertaintyWrites()
// While fenced: zero sidecar bytes written, AND snapshot still fails closed (available=false).
if _, err := os.Stat(sidecarPath); !errors.Is(err, os.ErrNotExist) {
endFence()
t.Fatalf("expected zero sidecar bytes while root import consent fence is active, stat err=%v", err)
}
_, avail, err := p.LoadInfrastructureMapTopologyTallySnapshot(day, 30)
if err != nil {
endFence()
t.Fatalf("snapshot under fence returned unexpected error: %v", err)
}
if avail {
endFence()
t.Fatalf("transient consent-read fence erased known loss into available=true zero")
}
// Simulate rollback: release fence with consent continuously enabled and same gen.
endFence()
_, availAfter, err := p.LoadInfrastructureMapTopologyTallySnapshot(day, 30)
if err != nil {
t.Fatalf("snapshot after fence release failed: %v", err)
}
if availAfter {
t.Fatalf("expected available=false after fence release while loss persists")
}
p.WaitTopologyUncertaintyWrites()
if _, err := os.Stat(sidecarPath); err != nil {
t.Fatalf("expected degraded sidecar to persist after import rollback cleared fence: %v", err)
}
}
// Medium #4 regression: an already opted-out installation must write ZERO bytes
// to infrastructure_map_topology_tally.json, its degraded sidecar, and
// external_agent_activity.json on both startup and GET /api/agent/topology, and
// must lazily initialize the tally when the operator later opts back in.
func TestOptedOutInstallStartupAndTopologyRouteWriteZeroActivityOrTallyBytes(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
f := false
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &f}); err != nil {
t.Fatalf("persist opt-out: %v", err)
}
tok := newTokenRecord(t, "topo-optout-zero.12345678", []string{config.ScopeMonitoringRead, config.ScopeSettingsRead}, nil)
if err := p.SaveAPITokens([]config.APITokenRecord{tok}); err != nil {
t.Fatalf("save tokens: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: false,
APITokens: []config.APITokenRecord{tok},
}
now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
router := newTestRouter(t, cfg, nil, nil, nil, nil, "6.0.0-beta.1")
router.topologyNow = func() time.Time { return now }
router.resourceHandlers.SetStateProvider(&mockTransitionStateProvider{
resources: []unified.Resource{{ID: "node-1", Type: unified.ResourceTypeAgent, Name: "pve-1", Status: unified.StatusOnline}},
lastUpdate: now,
isMock: false,
})
router.WaitTopologyInit()
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", "topo-optout-zero.12345678")
req.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("GET /api/agent/topology status=%d body=%s", rec.Code, rec.Body.String())
}
router.WaitTopologyObservers()
for _, rel := range []string{
"infrastructure_map_topology_tally.json",
"infrastructure_map_topology_tally.degraded.json",
"external_agent_activity.json",
} {
if _, err := os.Stat(filepath.Join(dir, rel)); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("opted-out installation wrote %s (stat err=%v)", rel, err)
}
}
// High #7 + Medium #4 regression: actual GET /api/system/settings/telemetry-preview
// on a fresh opted-out install must be strictly read-only: never write a false
// tally_missing degraded sidecar AND never create or rotate .install_id on disk.
router.SetTelemetryPreviewFunc(func() (telemetry.Ping, error) {
return telemetry.BuildPreview(telemetry.Config{
Version: "6.0.0-beta.1",
DataDir: dir,
Enabled: false,
IsEnabled: router.EffectiveTelemetryEnabled,
GetSnapshot: func() telemetry.Snapshot {
var s telemetry.Snapshot
router.ApplyInfrastructureMapTelemetrySnapshot(&s, now)
return s
},
})
})
previewReq1 := httptest.NewRequest(http.MethodGet, "/api/system/settings/telemetry-preview", nil)
previewReq1.Header.Set("X-API-Token", "topo-optout-zero.12345678")
previewRec1 := httptest.NewRecorder()
router.Handler().ServeHTTP(previewRec1, previewReq1)
if previewRec1.Code != http.StatusOK {
t.Fatalf("GET /api/system/settings/telemetry-preview (missing .install_id) status=%d body=%s", previewRec1.Code, previewRec1.Body.String())
}
var previewResp1 struct {
Payload telemetry.Ping `json:"payload"`
}
if err := json.Unmarshal(previewRec1.Body.Bytes(), &previewResp1); err != nil {
t.Fatalf("decode preview response 1: %v", err)
}
if previewResp1.Payload.InfrastructureMapTopologyTelemetryAvailable || previewResp1.Payload.InfrastructureMapTopologyReadDays30d != 0 {
t.Fatalf("expected unavailable zero preview on fresh opted-out install, got %+v", previewResp1.Payload)
}
for _, rel := range []string{
".install_id",
"infrastructure_map_topology_tally.json",
"infrastructure_map_topology_tally.degraded.json",
"external_agent_activity.json",
} {
if _, err := os.Stat(filepath.Join(dir, rel)); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("opted-out preview wrote %s (stat err=%v)", rel, err)
}
}
// Also verify GET /api/system/settings/telemetry-preview does not rotate an expired .install_id on disk.
expiredID := `{"install_id":"11111111-2222-3333-4444-555555555555","issued_at":"2020-01-01T00:00:00Z"}`
installIDPath := filepath.Join(dir, ".install_id")
if err := os.WriteFile(installIDPath, []byte(expiredID), 0600); err != nil {
t.Fatalf("seed expired .install_id: %v", err)
}
previewReq2 := httptest.NewRequest(http.MethodGet, "/api/system/settings/telemetry-preview", nil)
previewReq2.Header.Set("X-API-Token", "topo-optout-zero.12345678")
previewRec2 := httptest.NewRecorder()
router.Handler().ServeHTTP(previewRec2, previewReq2)
if previewRec2.Code != http.StatusOK {
t.Fatalf("GET /api/system/settings/telemetry-preview (expired .install_id) status=%d body=%s", previewRec2.Code, previewRec2.Body.String())
}
gotIDBytes, err := os.ReadFile(installIDPath)
if err != nil {
t.Fatalf("read expired .install_id: %v", err)
}
if string(gotIDBytes) != expiredID {
t.Fatalf("preview endpoint rotated expired .install_id on disk: got %q, want %q", string(gotIDBytes), expiredID)
}
_ = os.Remove(installIDPath)
// Opting back in lazily initializes the tally file so future reads count.
tr := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &tr}); err != nil {
t.Fatalf("opt back in: %v", err)
}
config.Mu.Lock()
cfg.TelemetryEnabled = true
config.Mu.Unlock()
if _, err := os.Stat(filepath.Join(dir, "infrastructure_map_topology_tally.json")); err != nil {
t.Fatalf("expected opt-in to initialize topology tally file: %v", err)
}
req2 := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req2.Header.Set("X-API-Token", "topo-optout-zero.12345678")
req2.Header.Set(agentcapabilities.AgentSurfaceHeader, agentcapabilities.AgentSurfacePulseCLI)
rec2 := httptest.NewRecorder()
router.Handler().ServeHTTP(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("post-opt-in GET /api/agent/topology status=%d", rec2.Code)
}
router.WaitTopologyObservers()
var snap telemetry.Snapshot
router.ApplyInfrastructureMapTelemetrySnapshot(&snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 1 || snap.InfrastructureMapTopologyCLIDays30d != 1 {
t.Fatalf("expected post-opt-in read to be counted, got %+v", snap)
}
}
// High #4 regression: replacing a token record in-place with a different hash
// under the same ID and binding must invalidate an already-admitted command
// session instead of letting the old socket inherit the replacement credential.
func TestValidateAgentExecSessionRejectsReplacementHashWithSameTokenID(t *testing.T) {
dir := t.TempDir()
rawOld := "exec-old-token.12345678"
recOld, err := config.NewAPITokenRecord(rawOld, "old-agent", []string{config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord old: %v", err)
}
recOld.OrgID = "default"
recOld.Metadata = map[string]string{
"bound_agent_id": "agent-1",
"bound_hostname": "node-1",
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindLegacyFullTrust,
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*recOld},
}
router := newTestRouter(t, cfg, nil, nil, nil, nil, "6.0.0-beta.1")
admission, ok := router.admitAgentExecToken(rawOld, "agent-1", "node-1")
if !ok {
t.Fatal("expected initial admission to succeed")
}
if admission.TokenHash == "" {
t.Fatal("expected admission to carry credential TokenHash")
}
if !router.validateAgentExecSession(admission) {
t.Fatal("expected live session validation to succeed for matching hash")
}
// Simulate backup import publishing a replacement credential with the SAME ID and binding but DIFFERENT hash.
recNew, err := config.NewAPITokenRecord("exec-new-token.87654321", "replacement-agent", []string{config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord new: %v", err)
}
recNew.ID = recOld.ID
recNew.OrgID = recOld.OrgID
recNew.Metadata = map[string]string{
"bound_agent_id": "agent-1",
"bound_hostname": "node-1",
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindLegacyFullTrust,
}
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{*recNew}
config.Mu.Unlock()
if router.validateAgentExecSession(admission) {
t.Fatal("old command socket unexpectedly passed validation against replacement credential with different hash")
}
}
func TestApplyInfrastructureMapTelemetrySnapshotReadOnly_DormantKeylessTenantNoKeyCreated(t *testing.T) {
baseDir := t.TempDir()
rootP := config.NewConfigPersistence(baseDir)
mt := config.NewMultiTenantPersistence(baseDir)
// Create a dormant tenant directory with NO .encryption.key and NO encrypted files.
dormantDir := filepath.Join(baseDir, "orgs", "dormant-org")
if err := os.MkdirAll(dormantDir, 0o700); err != nil {
t.Fatalf("mkdir dormant tenant: %v", err)
}
tallyBody := []byte(`{"version":1,"last_saved":"2026-11-30T10:00:00Z","daily":{"open":{"2026-11-30":2}}}`)
if err := os.WriteFile(filepath.Join(dormantDir, "infrastructure_map_activity_tally.json"), tallyBody, 0o600); err != nil {
t.Fatalf("seed dormant tenant tally: %v", err)
}
router := &Router{
config: &config.Config{DataPath: baseDir, ConfigPath: baseDir},
persistence: rootP,
multiTenant: mt,
}
var snap telemetry.Snapshot
router.ApplyInfrastructureMapTelemetrySnapshotReadOnly(&snap, time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC))
router.ApplyWorkloadHistoryTelemetrySnapshot(&snap, time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC))
if snap.InfrastructureMapOpenSessions30d != 2 {
t.Fatalf("expected dormant tenant tally to be read (=2), got %d", snap.InfrastructureMapOpenSessions30d)
}
if _, err := os.Stat(filepath.Join(dormantDir, ".encryption.key")); !os.IsNotExist(err) {
t.Fatalf("read-only telemetry preview must NOT create .encryption.key in dormant tenant dir, stat err=%v", err)
}
}
func TestRecordReportedAgentIdentityInInventory_RetiredTenantCannotRestoreRevokedCredentials(t *testing.T) {
baseDir := t.TempDir()
mt := config.NewMultiTenantPersistence(baseDir)
tenantP, err := mt.GetPersistence("tenant-a")
if err != nil {
t.Fatalf("GetPersistence(tenant-a): %v", err)
}
rawTok := "pulse_tenant_agent_r33_token_value_1234567890"
tokRec, err := config.NewAPITokenRecord(rawTok, "tenant-agent", []string{config.ScopeAgentReport})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
tokRec.OrgID = "tenant-a"
tokRec.Metadata = map[string]string{
"bound_hostname": "worker-01.tenant-a.local",
}
if err := tenantP.SaveAPITokens([]config.APITokenRecord{*tokRec}); err != nil {
t.Fatalf("SaveAPITokens initial: %v", err)
}
// Retired tenant monitor still holds stale in-memory token slice containing tokRec.
retiredTenantCfg := &config.Config{
APITokens: []config.APITokenRecord{tokRec.Clone()},
}
// Simulate a tenant import committing an empty (revoked) token inventory on disk
// before ReloadTenant finishes replacing the retired monitor.
if err := tenantP.SaveAPITokens([]config.APITokenRecord{}); err != nil {
t.Fatalf("SaveAPITokens imported empty: %v", err)
}
router := &Router{}
router.recordReportedAgentIdentityInInventory(
retiredTenantCfg,
tenantP,
"tenant-a",
tokRec.ID,
tokRec.Hash,
apiTokenAuthenticatedUser(tokRec),
true,
"host-uuid-1",
"host-uuid-1",
"worker-01.tenant-a.local",
)
after, err := tenantP.LoadAPITokens()
if err != nil {
t.Fatalf("LoadAPITokens after: %v", err)
}
if len(after) != 0 {
t.Fatalf("retired tenant monitor restored %d revoked tokens onto disk!", len(after))
}
}
func TestHandleIssueActionRunnerCredential_RejectsRevokedIssuerInsideTransaction(t *testing.T) {
router, cfg, hostID := newActionRunnerCredentialTestRouter(t)
p := router.persistence
rawIssuer := "pulse_admin_issuer_r33_1234567890abcdef"
issuerRec, err := config.NewAPITokenRecord(rawIssuer, "issuer", []string{config.ScopeSettingsWrite, config.ScopeActionsExecute})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
cfg.APITokens = []config.APITokenRecord{*issuerRec}
if err := p.SaveAPITokens([]config.APITokenRecord{*issuerRec}); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
// Case 1: Issuer token revoked between middleware admission and issuance tx.
cfg.APITokens = nil
if err := p.SaveAPITokens([]config.APITokenRecord{}); err != nil {
t.Fatalf("revoke issuer: %v", err)
}
body := `{"agentId":"` + hostID + `","hostname":"host-1.local","name":"runner-1"}`
req := httptest.NewRequest(http.MethodPost, "/api/security/action-runner-credentials", strings.NewReader(body))
req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "default"))
attachAPITokenRecord(req, issuerRec)
rec := httptest.NewRecorder()
router.handleIssueActionRunnerCredential(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 when issuer revoked before tx, got %d: %s", rec.Code, rec.Body.String())
}
// Case 2: Issuer token lost ScopeActionsExecute before tx.
downgraded := issuerRec.Clone()
downgraded.Scopes = []string{config.ScopeSettingsWrite}
cfg.APITokens = []config.APITokenRecord{downgraded}
if err := p.SaveAPITokens([]config.APITokenRecord{downgraded}); err != nil {
t.Fatalf("downgrade issuer: %v", err)
}
req2 := httptest.NewRequest(http.MethodPost, "/api/security/action-runner-credentials", strings.NewReader(body))
req2 = req2.WithContext(context.WithValue(req2.Context(), OrgIDContextKey, "default"))
attachAPITokenRecord(req2, issuerRec)
rec2 := httptest.NewRecorder()
router.handleIssueActionRunnerCredential(rec2, req2)
if rec2.Code != http.StatusForbidden {
t.Fatalf("expected 403 when issuer lost actions:execute before tx, got %d: %s", rec2.Code, rec2.Body.String())
}
}
func TestRound34_API_Regressions(t *testing.T) {
t.Run("High5_ActionTelemetryDoesNotCreateOrRebuildDormantTenantResourceDB", func(t *testing.T) {
baseDir := t.TempDir()
rootP := config.NewConfigPersistence(baseDir)
mt := config.NewMultiTenantPersistence(baseDir)
// Dormant tenant 1: empty org dir (no DB).
dormantEmpty := filepath.Join(baseDir, "orgs", "dormant-empty")
if err := os.MkdirAll(dormantEmpty, 0o700); err != nil {
t.Fatalf("mkdir dormant-empty: %v", err)
}
// Dormant tenant 2: corrupt DB at the actual production resources/ path
// that must NOT be backed up, recreated, or accompanied by sidecars.
dormantCorruptRes := filepath.Join(baseDir, "orgs", "dormant-corrupt", "resources")
if err := os.MkdirAll(dormantCorruptRes, 0o700); err != nil {
t.Fatalf("mkdir dormant-corrupt resources: %v", err)
}
corruptDBPath := filepath.Join(dormantCorruptRes, "unified_resources.db")
corruptBytes := []byte("not-a-valid-sqlite-database")
if err := os.WriteFile(corruptDBPath, corruptBytes, 0o600); err != nil {
t.Fatalf("seed corrupt db: %v", err)
}
// Dormant tenant 3: valid cleanly closed WAL-mode DB with no -wal/-shm.
// Preview must count its action audit AND create zero -wal/-shm sidecars.
walStore, err := unified.NewSQLiteResourceStore(baseDir, "dormant-wal")
if err != nil {
t.Fatalf("seed dormant-wal store: %v", err)
}
now := time.Now().UTC()
if err := walStore.RecordActionAudit(unified.ActionAuditRecord{
ID: "act-wal-1",
CreatedAt: now,
UpdatedAt: now,
State: unified.ActionStateCompleted,
Request: unified.ActionRequest{
ResourceID: "res-wal-1",
CapabilityName: "pulse.control",
RequestedBy: "operator",
},
}); err != nil {
t.Fatalf("record dormant-wal action: %v", err)
}
if err := walStore.Close(); err != nil {
t.Fatalf("close dormant-wal store: %v", err)
}
dormantWalRes := filepath.Join(baseDir, "orgs", "dormant-wal", "resources")
for _, suffix := range []string{"-wal", "-shm"} {
_ = os.Remove(filepath.Join(dormantWalRes, "unified_resources.db"+suffix))
}
// Dormant tenant 4: legacy shared-path DB (resources/unified_resources_dormant-legacy.db)
// with an empty org dir. Preview must count its action without migrating or creating sidecars.
legacySrcStore, err := unified.NewSQLiteResourceStore(baseDir, "dormant-legacy")
if err != nil {
t.Fatalf("seed legacy source store: %v", err)
}
if err := legacySrcStore.RecordActionAudit(unified.ActionAuditRecord{
ID: "act-legacy-1",
CreatedAt: now,
UpdatedAt: now,
State: unified.ActionStateCompleted,
Request: unified.ActionRequest{
ResourceID: "res-legacy-1",
CapabilityName: "pulse.control",
RequestedBy: "operator",
},
}); err != nil {
t.Fatalf("record dormant-legacy action: %v", err)
}
if err := legacySrcStore.Close(); err != nil {
t.Fatalf("close legacy source store: %v", err)
}
legacyResourcesDir := filepath.Join(baseDir, "resources")
if err := os.MkdirAll(legacyResourcesDir, 0o700); err != nil {
t.Fatalf("mkdir legacy resources dir: %v", err)
}
legacyDBPath := filepath.Join(legacyResourcesDir, "unified_resources_dormant-legacy.db")
srcLegacyBytes, err := os.ReadFile(filepath.Join(baseDir, "orgs", "dormant-legacy", "resources", "unified_resources.db"))
if err != nil {
t.Fatalf("read seeded legacy db: %v", err)
}
if err := os.WriteFile(legacyDBPath, srcLegacyBytes, 0o600); err != nil {
t.Fatalf("write legacy db: %v", err)
}
if err := os.RemoveAll(filepath.Join(baseDir, "orgs", "dormant-legacy", "resources")); err != nil {
t.Fatalf("remove migrated tenant resources dir: %v", err)
}
cfg := &config.Config{DataPath: baseDir, ConfigPath: baseDir}
rh := NewResourceHandlers(cfg)
router := &Router{
config: cfg,
persistence: rootP,
multiTenant: mt,
resourceHandlers: rh,
}
// Temporarily exclude dormant-corrupt to verify clean dormant-wal + dormant-legacy
// read without creating files, then restore dormant-corrupt and verify fail-closed.
corruptOrgDir := filepath.Join(baseDir, "orgs", "dormant-corrupt")
corruptSaved := filepath.Join(t.TempDir(), "dormant-corrupt")
if err := os.Rename(corruptOrgDir, corruptSaved); err != nil {
t.Fatalf("move dormant-corrupt aside: %v", err)
}
actionSnap := router.GetPulseIntelligenceActionTelemetry(now.AddDate(0, 0, -30))
if actionSnap.ActionPlans30d != 2 {
t.Fatalf("expected 2 action plans (dormant-wal + dormant-legacy), got %d", actionSnap.ActionPlans30d)
}
if err := os.Rename(corruptSaved, corruptOrgDir); err != nil {
t.Fatalf("restore dormant-corrupt: %v", err)
}
corruptSnap := router.GetPulseIntelligenceActionTelemetry(now.AddDate(0, 0, -30))
if corruptSnap.ActionPlans30d != 0 {
t.Fatalf("expected fail-closed 0 action plans when dormant-corrupt DB is unreadable, got %d", corruptSnap.ActionPlans30d)
}
if entries, err := os.ReadDir(dormantEmpty); err != nil || len(entries) != 0 {
t.Fatalf("preview created files in dormant-empty tenant dir: entries=%v err=%v", entries, err)
}
entriesCorrupt, err := os.ReadDir(dormantCorruptRes)
if err != nil {
t.Fatalf("ReadDir dormant-corrupt resources: %v", err)
}
if len(entriesCorrupt) != 1 || entriesCorrupt[0].Name() != "unified_resources.db" {
t.Fatalf("preview modified/backed up files in dormant-corrupt resources dir: %v", entriesCorrupt)
}
afterCorrupt, err := os.ReadFile(corruptDBPath)
if err != nil || string(afterCorrupt) != string(corruptBytes) {
t.Fatalf("preview modified corrupt db contents: err=%v", err)
}
entriesWal, err := os.ReadDir(dormantWalRes)
if err != nil {
t.Fatalf("ReadDir dormant-wal resources: %v", err)
}
if len(entriesWal) != 1 || entriesWal[0].Name() != "unified_resources.db" {
t.Fatalf("read-only preview created WAL/SHM sidecars in dormant-wal resources dir: %v", entriesWal)
}
entriesLegacyOrg, err := os.ReadDir(filepath.Join(baseDir, "orgs", "dormant-legacy"))
if err != nil || len(entriesLegacyOrg) != 0 {
t.Fatalf("read-only preview migrated dormant-legacy org dir: entries=%v err=%v", entriesLegacyOrg, err)
}
entriesLegacyRes, err := os.ReadDir(legacyResourcesDir)
if err != nil {
t.Fatalf("ReadDir legacy resources dir: %v", err)
}
if len(entriesLegacyRes) != 1 || entriesLegacyRes[0].Name() != "unified_resources_dormant-legacy.db" {
t.Fatalf("read-only preview created sidecars in legacy resources dir: %v", entriesLegacyRes)
}
})
t.Run("Medium7_BrowserActivityTalliesRespectOptOut", func(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
disabled := false
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &disabled}); err != nil {
t.Fatalf("opt-out: %v", err)
}
router := &Router{
config: &config.Config{DataPath: dir, ConfigPath: dir, TelemetryEnabled: false},
persistence: p,
}
req1 := httptest.NewRequest(http.MethodPost, "/api/usage/infrastructure-map", strings.NewReader(`{"activity":"open"}`))
rec1 := httptest.NewRecorder()
router.HandleInfrastructureMapActivity(rec1, req1)
if rec1.Code != http.StatusNoContent {
t.Fatalf("map activity status=%d", rec1.Code)
}
req2 := httptest.NewRequest(http.MethodPost, "/api/usage/workload-history", strings.NewReader(`{"activity":"preview"}`))
rec2 := httptest.NewRecorder()
router.HandleWorkloadHistoryActivity(rec2, req2)
if rec2.Code != http.StatusNoContent {
t.Fatalf("workload activity status=%d", rec2.Code)
}
if _, err := os.Stat(filepath.Join(dir, "infrastructure_map_activity_tally.json")); !os.IsNotExist(err) {
t.Fatalf("map browser activity wrote file during opt-out: err=%v", err)
}
if _, err := os.Stat(filepath.Join(dir, "workload_history_activity_tally.json")); !os.IsNotExist(err) {
t.Fatalf("workload browser activity wrote file during opt-out: err=%v", err)
}
})
}
func TestRound35_BrowserActivityAndRootOptOutImportNoDeadlock(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("save initial enabled settings: %v", err)
}
// Prepare an opt-out export payload.
optOutDir := t.TempDir()
optOutP := config.NewConfigPersistence(optOutDir)
disabled := false
if err := optOutP.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &disabled}); err != nil {
t.Fatalf("save opt-out template settings: %v", err)
}
exportPayload, err := optOutP.ExportConfig("round35-passphrase")
if err != nil {
t.Fatalf("export opt-out config: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
EnvOverrides: make(map[string]bool),
}
router := &Router{
config: cfg,
persistence: p,
}
// Verify a single map POST with the canonical activity ("open") records cleanly.
checkReq := httptest.NewRequest(http.MethodPost, "/api/telemetry/infrastructure-map", strings.NewReader(`{"activity":"open"}`))
checkRec := httptest.NewRecorder()
router.HandleInfrastructureMapActivity(checkRec, checkReq)
if checkRec.Code != http.StatusNoContent {
t.Fatalf("expected 204 for valid map activity, got %d body=%s", checkRec.Code, checkRec.Body.String())
}
errCh := make(chan error, 100)
done := make(chan struct{})
go func() {
defer close(done)
var wg sync.WaitGroup
wg.Add(3)
go func() {
defer wg.Done()
for i := 0; i < 40; i++ {
req := httptest.NewRequest(http.MethodPost, "/api/telemetry/infrastructure-map", strings.NewReader(`{"activity":"open"}`))
rec := httptest.NewRecorder()
router.HandleInfrastructureMapActivity(rec, req)
if rec.Code != http.StatusNoContent {
errCh <- fmt.Errorf("map activity status=%d body=%s", rec.Code, rec.Body.String())
return
}
}
}()
go func() {
defer wg.Done()
for i := 0; i < 40; i++ {
req := httptest.NewRequest(http.MethodPost, "/api/telemetry/workload-history", strings.NewReader(`{"activity":"preview"}`))
rec := httptest.NewRecorder()
router.HandleWorkloadHistoryActivity(rec, req)
if rec.Code != http.StatusNoContent {
errCh <- fmt.Errorf("workload activity status=%d body=%s", rec.Code, rec.Body.String())
return
}
}
}()
go func() {
defer wg.Done()
for i := 0; i < 6; i++ {
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
errCh <- fmt.Errorf("save enabled iter %d: %w", i, err)
return
}
if err := p.ImportConfig(exportPayload, "round35-passphrase"); err != nil {
errCh <- fmt.Errorf("import opt-out iter %d: %w", i, err)
return
}
}
}()
wg.Wait()
}()
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatal("deadlock detected between browser activity handlers and root opt-out ImportConfig")
}
close(errCh)
for err := range errCh {
t.Fatalf("concurrent overlap error: %v", err)
}
}
func TestRound36_BrowserActivityOptOutDoesNotCreateTenantKey(t *testing.T) {
baseDir := t.TempDir()
rootP := config.NewConfigPersistence(baseDir)
disabled := false
if err := rootP.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &disabled}); err != nil {
t.Fatalf("opt-out root settings: %v", err)
}
dormantDir := filepath.Join(baseDir, "orgs", "dormant-browser")
if err := os.MkdirAll(dormantDir, 0o700); err != nil {
t.Fatalf("mkdir dormant tenant: %v", err)
}
cfg := &config.Config{
DataPath: baseDir,
ConfigPath: baseDir,
TelemetryEnabled: true, // stale runtime flag while disk is opted out
EnvOverrides: make(map[string]bool),
}
router := &Router{
config: cfg,
persistence: rootP,
multiTenant: config.NewMultiTenantPersistence(baseDir),
}
for _, tc := range []struct {
path string
body string
handler func(http.ResponseWriter, *http.Request)
}{
{"/api/telemetry/infrastructure-map", `{"activity":"open"}`, router.HandleInfrastructureMapActivity},
{"/api/telemetry/workload-history", `{"activity":"preview"}`, router.HandleWorkloadHistoryActivity},
} {
req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body))
req = req.WithContext(context.WithValue(req.Context(), apicontext.OrgIDContextKey, "dormant-browser"))
rec := httptest.NewRecorder()
tc.handler(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("%s status=%d", tc.path, rec.Code)
}
}
entries, err := os.ReadDir(dormantDir)
if err != nil {
t.Fatalf("ReadDir dormant-browser: %v", err)
}
if len(entries) != 0 {
t.Fatalf("browser activity created files in dormant tenant dir: %v", entries)
}
}
func TestRound36_ReplacedTenantTokenRejectedBeforeReloadAndAcceptedAfterReload(t *testing.T) {
baseDir := t.TempDir()
mt := config.NewMultiTenantPersistence(baseDir)
tenantP, err := mt.GetPersistence("org-r36")
if err != nil {
t.Fatalf("get tenant persistence: %v", err)
}
rawOld := "tenant-r36-old-token.12345678"
oldTok, err := config.NewAPITokenRecord(rawOld, "Old Tenant Token", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("new old token: %v", err)
}
oldTok.OrgIDs = []string{"org-r36"}
if err := tenantP.SaveAPITokens([]config.APITokenRecord{*oldTok}); err != nil {
t.Fatalf("save old tenant token: %v", err)
}
rootCfg := &config.Config{DataPath: baseDir, ConfigPath: baseDir}
mtm := monitoring.NewMultiTenantMonitor(rootCfg, mt, nil)
t.Cleanup(mtm.Stop)
oldMon, err := mtm.GetMonitor("org-r36")
if err != nil {
t.Fatalf("start tenant monitor: %v", err)
}
oldTenantCfg := oldMon.GetConfig()
// Build replacement archive with only rawNew.
rawNew := "tenant-r36-new-token.87654321"
newTok, err := config.NewAPITokenRecord(rawNew, "New Tenant Token", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("new replacement token: %v", err)
}
newTok.OrgIDs = []string{"org-r36"}
exportDir := t.TempDir()
exportP := config.NewConfigPersistence(exportDir)
if err := exportP.SaveAPITokens([]config.APITokenRecord{*newTok}); err != nil {
t.Fatalf("save replacement export token: %v", err)
}
bundle, err := exportP.ExportConfig("r36-tenant-import-pass")
if err != nil {
t.Fatalf("export replacement tenant bundle: %v", err)
}
// Commit replacement archive to disk WITHOUT reloading tenant monitor yet.
if err := tenantP.ImportConfig(bundle, "r36-tenant-import-pass"); err != nil {
t.Fatalf("import replacement tenant bundle: %v", err)
}
// Old tenant token must be rejected by auth AND topology completion while
// reload is pending or failed.
config.Mu.RLock()
_, authOK := validateAPITokenAgainstConfigsLocked(rootCfg, oldTenantCfg, rawOld)
config.Mu.RUnlock()
if authOK {
t.Fatalf("replaced tenant token still authorized requests before ReloadTenant")
}
router := &Router{config: rootCfg, persistence: config.NewConfigPersistence(baseDir), multiTenant: mt, mtMonitor: mtm}
req := httptest.NewRequest(http.MethodGet, "/api/resources/topology", nil)
ctx := context.WithValue(req.Context(), tenantTokenSourceContextKey, tenantTokenSource{manager: mtm, orgID: "org-r36"})
ctx = context.WithValue(ctx, apicontext.OrgIDContextKey, "org-r36")
ctx = internalauth.WithAPIToken(ctx, oldTok)
req = req.WithContext(ctx)
if router.isTopologyTokenEligibleAtCompletion(req, time.Now().UTC()) {
t.Fatalf("replaced tenant token still passed topology completion check before ReloadTenant")
}
// ReloadTenant publishes the new monitor and clears the pending import fence.
newMon, err := mtm.ReloadTenant("org-r36")
if err != nil {
t.Fatalf("ReloadTenant: %v", err)
}
newTenantCfg := newMon.GetConfig()
config.Mu.RLock()
_, oldAfterReload := validateAPITokenAgainstConfigsLocked(rootCfg, newTenantCfg, rawOld)
_, newAfterReload := validateAPITokenAgainstConfigsLocked(rootCfg, newTenantCfg, rawNew)
config.Mu.RUnlock()
if oldAfterReload {
t.Fatalf("old tenant token still accepted after ReloadTenant")
}
if !newAfterReload {
t.Fatalf("new imported tenant token rejected after ReloadTenant")
}
}
func TestRound35_AgentExecTokenBindingRaceWithSetMonitor(t *testing.T) {
cfg := &config.Config{
DataPath: t.TempDir(),
ConfigPath: t.TempDir(),
}
router := &Router{
config: cfg,
}
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := 0; i < 200; i++ {
router.SetMonitor(nil)
}
}()
go func() {
defer wg.Done()
for i := 0; i < 200; i++ {
config.Mu.RLock()
_ = router.agentExecIdentityHeldByAnotherToken("default", &config.APITokenRecord{ID: "tok-1"}, "agent-1")
config.Mu.RUnlock()
}
}()
wg.Wait()
}
type round37SyncDirFailFS struct {
config.FileSystem
failSyncDir atomic.Bool
}
func (f *round37SyncDirFailFS) SyncDir(dir string) error {
if f.failSyncDir.Load() {
return errors.New("injected post-rename directory fsync failure")
}
return nil
}
type round37BaseFS struct{}
func (round37BaseFS) ReadFile(name string) ([]byte, error) { return os.ReadFile(name) }
func (round37BaseFS) WriteFile(name string, data []byte, perm os.FileMode) error {
return os.WriteFile(name, data, perm)
}
func (round37BaseFS) CreateTemp(dir, pattern string) (config.TemporaryFile, error) {
return os.CreateTemp(dir, pattern)
}
func (round37BaseFS) MkdirAll(path string, perm os.FileMode) error { return os.MkdirAll(path, perm) }
func (round37BaseFS) Remove(name string) error { return os.Remove(name) }
func (round37BaseFS) Rename(oldpath, newpath string) error { return os.Rename(oldpath, newpath) }
func (round37BaseFS) Stat(name string) (os.FileInfo, error) { return os.Stat(name) }
func (round37BaseFS) Lstat(name string) (os.FileInfo, error) { return os.Lstat(name) }
// High #1 regression: an already-admitted tenant settings:write token issuance
// request must be rejected by both request-body revalidation and the final
// commit check after tenant ImportConfig withdraws the token before reload.
func TestRound37_AdmittedTenantTokenIssuanceRejectedAfterTenantImportBeforeReload(t *testing.T) {
baseDir := t.TempDir()
orgID := "tenant-r37-issue"
mtp := config.NewMultiTenantPersistence(baseDir)
rootP, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("root persistence: %v", err)
}
tenantP, err := mtp.GetPersistence(orgID)
if err != nil {
t.Fatalf("tenant persistence: %v", err)
}
rawAdmin := "r37-tenant-admin-token-0123456789abcdef"
adminRec, err := config.NewAPITokenRecord(rawAdmin, "tenant-admin", []string{config.ScopeSettingsWrite, config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
adminRec.OrgID = orgID
if err := tenantP.SaveAPITokens([]config.APITokenRecord{*adminRec}); err != nil {
t.Fatalf("SaveAPITokens tenant: %v", err)
}
// Prepare an import bundle for this tenant with an empty token inventory.
exportDir := t.TempDir()
exportP := config.NewConfigPersistence(exportDir)
if err := exportP.SaveAPITokens([]config.APITokenRecord{}); err != nil {
t.Fatalf("SaveAPITokens export: %v", err)
}
bundle, err := exportP.ExportConfig("r37-tenant-pass")
if err != nil {
t.Fatalf("ExportConfig: %v", err)
}
rootCfg := &config.Config{
DataPath: baseDir,
ConfigPath: baseDir,
}
mtm := monitoring.NewMultiTenantMonitor(rootCfg, mtp, nil)
t.Cleanup(func() { mtm.Stop() })
if _, err := mtm.GetMonitor(orgID); err != nil {
t.Fatalf("GetMonitor tenant: %v", err)
}
router := &Router{
config: rootCfg,
persistence: rootP,
multiTenant: mtp,
}
// Build an already-admitted request carrying the tenant token source context
// pointing at the pre-reload cached tenant monitor.
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens", strings.NewReader(`{"name":"minted-after-withdraw","scopes":["monitoring:read"]}`))
req.Header.Set("Content-Type", "application/json")
ctx := context.WithValue(req.Context(), apicontext.OrgIDContextKey, orgID)
ctx = context.WithValue(ctx, tenantTokenSourceContextKey, tenantTokenSource{
manager: mtm,
orgID: orgID,
})
req = req.WithContext(ctx)
admittedCopy := adminRec.Clone()
attachAPITokenRecord(req, &admittedCopy)
revalidator := admittedTokenRevalidator(rootCfg, req)
if revalidator == nil || !revalidator() {
t.Fatal("expected admitted tenant token to validate before tenant import")
}
// Commit tenant import withdrawing adminRec without reloading tenantCfg.
if err := tenantP.ImportConfig(bundle, "r37-tenant-pass"); err != nil {
t.Fatalf("tenant ImportConfig: %v", err)
}
if revalidator() {
t.Fatal("request-body revalidator must reject withdrawn tenant token while tenant import is pending reload")
}
rec := httptest.NewRecorder()
router.handleCreateAPIToken(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for already-admitted issuance after tenant import withdraw, got %d (%s)", rec.Code, rec.Body.String())
}
if len(rootCfg.APITokens) != 0 {
t.Fatalf("withdrawn tenant caller must not mint root tokens, got %d", len(rootCfg.APITokens))
}
}
// High #3 regression: when SaveAPITokensAlreadyLocked fails ONLY at the
// post-rename parent-directory fsync (DurablePublishSyncError), delete, scope
// update, and rotation handlers must keep in-memory APITokens aligned with the
// published disk inventory rather than restoring revoked or stale authority.
func TestRound37_TokenMutationsKeepMemoryAlignedOnDurablePublishSyncError(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
syncFS := &round37SyncDirFailFS{FileSystem: round37BaseFS{}}
p.SetFileSystem(syncFS)
rawScope := "r37-scope-token-0123456789abcdef0123456"
scopeRec, err := config.NewAPITokenRecord(rawScope, "scope-tok", []string{config.ScopeMonitoringRead, config.ScopeSettingsWrite})
if err != nil {
t.Fatalf("NewAPITokenRecord scope: %v", err)
}
rawDel := "r37-del-token-0123456789abcdef012345678"
delRec, err := config.NewAPITokenRecord(rawDel, "del-tok", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord del: %v", err)
}
rawRot := "r37-rot-token-0123456789abcdef012345678"
rotRec, err := config.NewAPITokenRecord(rawRot, "rot-tok", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord rot: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*scopeRec, *delRec, *rotRec},
}
cfg.SortAPITokens()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("initial SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
// Inject post-rename SyncDir failure for all three mutations.
syncFS.failSyncDir.Store(true)
// 1) Scope update: remove settings:write.
reqUpdate := httptest.NewRequest(http.MethodPatch, "/api/security/tokens/"+scopeRec.ID, strings.NewReader(`{"scopes":["monitoring:read"]}`))
reqUpdate.Header.Set("Content-Type", "application/json")
recUpdate := httptest.NewRecorder()
router.handleUpdateAPIToken(recUpdate, reqUpdate)
if recUpdate.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 on update dir-sync error, got %d (%s)", recUpdate.Code, recUpdate.Body.String())
}
for _, tok := range cfg.APITokens {
if tok.ID == scopeRec.ID && tok.HasScope(config.ScopeSettingsWrite) {
t.Fatal("scope update restored removed settings:write in memory after durable publish")
}
}
// 2) Delete token: deleted record must stay removed in memory.
reqDel := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/"+delRec.ID, nil)
recDel := httptest.NewRecorder()
router.handleDeleteAPIToken(recDel, reqDel)
if recDel.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 on delete dir-sync error, got %d (%s)", recDel.Code, recDel.Body.String())
}
for _, tok := range cfg.APITokens {
if tok.ID == delRec.ID {
t.Fatal("delete handler restored deleted token in memory after durable publish")
}
}
// 3) Rotate token: old hash must stay replaced in memory.
oldRotHash := rotRec.Hash
reqRot := httptest.NewRequest(http.MethodPost, "/api/security/tokens/"+rotRec.ID+"/rotate", nil)
recRot := httptest.NewRecorder()
router.handleRotateAPIToken(recRot, reqRot)
if recRot.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 on rotate dir-sync error, got %d (%s)", recRot.Code, recRot.Body.String())
}
for _, tok := range cfg.APITokens {
if tok.Hash == oldRotHash {
t.Fatal("rotate handler restored old token hash in memory after durable publish")
}
}
}
// High #4 regression: disk-backed host command-policy reconciliation must
// enforce inventory.Owns in both Phase 1 and Phase 3 so a bound instance token
// widened across organizations cannot finalize command enablement via slow path.
func TestRound37_PendingHostCommandPolicyReconciliationEnforcesInventoryOwnership(t *testing.T) {
baseDir := t.TempDir()
orgA := "org-r37-a"
orgB := "org-r37-b"
mtp := config.NewMultiTenantPersistence(baseDir)
rootP, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("root persistence: %v", err)
}
if _, err := mtp.GetPersistence(orgA); err != nil {
t.Fatalf("orgA persistence: %v", err)
}
rawTok := "r37-shared-install-token-0123456789abcdef"
rec, err := config.NewAPITokenRecord(rawTok, "install-shared", []string{config.ScopeAgentReport, config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
rec.OrgID = orgA
rec.OrgIDs = []string{orgA}
rec.Metadata = map[string]string{
agenttokens.CommandPolicyIntentMetadataKey: agenttokens.CommandPolicyIntentEnabled,
"bound_agent_id": "host-r37-1",
"bound_hostname": "pve-r37-1",
}
// On disk, widen token across orgA and orgB so root inventory no longer Owns it for single-org tenant isolation.
widened := rec.Clone()
widened.OrgIDs = []string{orgA, orgB}
if err := rootP.SaveAPITokens([]config.APITokenRecord{widened}); err != nil {
t.Fatalf("SaveAPITokens widened: %v", err)
}
rootCfg := &config.Config{
DataPath: baseDir,
ConfigPath: baseDir,
APITokens: []config.APITokenRecord{*rec},
}
mtm := monitoring.NewMultiTenantMonitor(rootCfg, mtp, nil)
t.Cleanup(func() { mtm.Stop() })
monA, err := mtm.GetMonitor(orgA)
if err != nil {
t.Fatalf("GetMonitor orgA: %v", err)
}
// Mark host as pending command-policy enablement in host metadata store.
metaStore := monA.HostMetadataStore()
if metaStore == nil {
t.Fatal("expected host metadata store on tenant monitor")
}
enabledTrue := true
if err := metaStore.Set("host-r37-1", &config.HostMetadata{
ID: "host-r37-1",
CommandsEnabled: &enabledTrue,
CommandsEnablePendingAuth: true,
CommandsEnablePendingTokenID: rec.ID,
CommandsEnablePendingTokenHash: rec.Hash,
}); err != nil {
t.Fatalf("seed pending host metadata: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/agents/host/report", nil)
req = req.WithContext(context.WithValue(req.Context(), apicontext.OrgIDContextKey, orgA))
admittedCopy := rec.Clone()
attachAPITokenRecord(req, &admittedCopy)
_, _, _ = reconcileInstallTokenCommandPolicyForRequest(req, monA, &admittedCopy, models.Host{ID: "host-r37-1", Hostname: "pve-r37-1"})
gotMeta := metaStore.Get("host-r37-1")
if gotMeta != nil && !gotMeta.CommandsEnablePendingAuth && gotMeta.CommandsEnabled != nil && *gotMeta.CommandsEnabled {
t.Fatalf("disk-backed reconciliation finalized command enablement despite widened multi-org token failing inventory.Owns: %+v", gotMeta)
}
}
// High #5 regression: external-agent activity recording on an opted-out dormant
// tenant must not create .encryption.key or any files in the tenant directory.
func TestRound37_ExternalAgentActivityOptOutDoesNotCreateTenantKey(t *testing.T) {
baseDir := t.TempDir()
orgID := "dormant-agent-optout"
dormantDir := filepath.Join(baseDir, "orgs", orgID)
if err := os.MkdirAll(dormantDir, 0o700); err != nil {
t.Fatalf("mkdir dormant org: %v", err)
}
mtp := config.NewMultiTenantPersistence(baseDir)
rootP, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("root persistence: %v", err)
}
disabled := false
if err := rootP.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &disabled}); err != nil {
t.Fatalf("save opt-out system settings: %v", err)
}
rawTok := "r37-agent-activity-optout-0123456789abcd"
tokRec, err := config.NewAPITokenRecord(rawTok, "agent-tok", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
cfg := &config.Config{
DataPath: baseDir,
ConfigPath: baseDir,
TelemetryEnabled: false,
APITokens: []config.APITokenRecord{*tokRec},
}
router := &Router{
config: cfg,
persistence: rootP,
multiTenant: mtp,
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/fleet-context", nil)
req.Header.Set("User-Agent", "pulse-mcp/1.0")
req = req.WithContext(context.WithValue(req.Context(), apicontext.OrgIDContextKey, orgID))
copyRec := tokRec.Clone()
attachAPITokenRecord(req, &copyRec)
router.recordExternalAgentActivity(req, config.ExternalAgentActivityFleetContext, config.ScopeMonitoringRead)
entries, err := os.ReadDir(dormantDir)
if err != nil {
t.Fatalf("ReadDir dormant dir: %v", err)
}
if len(entries) != 0 {
t.Fatalf("opted-out external-agent activity created files in dormant tenant dir: %v", entries)
}
}
// Medium #4 regression: topology completion must follow first-matching-hash
// authentication semantics so a shadowing record with the same hash withdraws
// effective authority from any later record.
func TestRound37_TopologyCompletionShadowedHashRejected(t *testing.T) {
dir := t.TempDir()
rawTok := "r37-shadowed-topology-token-0123456789ab"
admitted, err := config.NewAPITokenRecord(rawTok, "original", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
shadow := admitted.Clone()
shadow.ID = "shadow-record-id"
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
// Shadowing record precedes admitted record with the identical hash.
APITokens: []config.APITokenRecord{shadow, *admitted},
}
router := &Router{config: cfg}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("User-Agent", "pulse-cli/1.0")
copyRec := admitted.Clone()
attachAPITokenRecord(req, &copyRec)
if router.isTopologyTokenEligibleAtCompletion(req, time.Now().UTC()) {
t.Fatal("expected topology completion to reject admitted token shadowed by an earlier record with the same hash")
}
}
type r38DynamicOrgLoader struct {
mu sync.RWMutex
orgs map[string]*models.Organization
}
func (l *r38DynamicOrgLoader) GetOrganization(orgID string) (*models.Organization, error) {
l.mu.RLock()
defer l.mu.RUnlock()
org, ok := l.orgs[orgID]
if !ok {
return nil, os.ErrNotExist
}
copyOrg := *org
copyOrg.Members = append([]models.OrganizationMember(nil), org.Members...)
return &copyOrg, nil
}
// High #1 regression: concurrent already-admitted tenant token issuance and
// tenant monitor replacement must complete without deadlocking across
// config.Mu -> mtm.mu -> c.mu.
func TestRound38_TenantTokenIssuanceOverlappingMonitorReplacementNoDeadlock(t *testing.T) {
baseDir := t.TempDir()
orgID := "tenant-r38-nodl"
mtp := config.NewMultiTenantPersistence(baseDir)
rootP, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("root persistence: %v", err)
}
tenantP, err := mtp.GetPersistence(orgID)
if err != nil {
t.Fatalf("tenant persistence: %v", err)
}
rawAdmin := "r38-nodl-tenant-admin-0123456789abcdef0"
adminRec, err := config.NewAPITokenRecord(rawAdmin, "tenant-admin", []string{config.ScopeSettingsWrite, config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
adminRec.OrgID = orgID
if err := tenantP.SaveAPITokens([]config.APITokenRecord{*adminRec}); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
rootCfg := &config.Config{DataPath: baseDir, ConfigPath: baseDir}
mtm := monitoring.NewMultiTenantMonitor(rootCfg, mtp, nil)
t.Cleanup(func() { mtm.Stop() })
if _, err := mtm.GetMonitor(orgID); err != nil {
t.Fatalf("initial GetMonitor: %v", err)
}
router := &Router{config: rootCfg, persistence: rootP, multiTenant: mtp}
// Synchronize deterministically without blocking inside SetMonitorInitializer
// (which runs synchronously on already-live monitors). Keep orgID live while
// a sibling tenant monitor construction pauses in initializer right before
// GetMonitor's publication lock (mtm.mu -> c.mu), then run a live tenant
// token issuance (config.Mu -> mtm.mu -> c.mu) concurrently across release
// and assert both succeed (201 Created and non-nil published monitor).
orgID2 := "tenant-r38-nodl-peer"
if _, err := mtp.GetPersistence(orgID2); err != nil {
t.Fatalf("peer tenant persistence: %v", err)
}
var armed atomic.Bool
enteredInit := make(chan struct{})
releaseInit := make(chan struct{})
var initOnce sync.Once
mtm.SetMonitorInitializer(func(*monitoring.Monitor) {
if !armed.Load() {
return
}
initOnce.Do(func() {
close(enteredInit)
<-releaseInit
})
})
armed.Store(true)
peerErrCh := make(chan error, 1)
go func() {
mon, err := mtm.GetMonitor(orgID2)
if err != nil {
peerErrCh <- err
return
}
if mon == nil {
peerErrCh <- errors.New("published peer monitor is nil")
return
}
peerErrCh <- nil
}()
select {
case <-enteredInit:
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for monitor initializer pause")
}
issueToken := func(name string) int {
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens", strings.NewReader(`{"name":"`+name+`","scopes":["monitoring:read"]}`))
req.Header.Set("Content-Type", "application/json")
ctx := context.WithValue(req.Context(), apicontext.OrgIDContextKey, orgID)
ctx = context.WithValue(ctx, tenantTokenSourceContextKey, tenantTokenSource{manager: mtm, orgID: orgID})
req = req.WithContext(ctx)
c := adminRec.Clone()
attachAPITokenRecord(req, &c)
rec := httptest.NewRecorder()
router.handleCreateAPIToken(rec, req)
return rec.Code
}
// Launch concurrent token issuance against live orgID right as GetMonitor(orgID2)
// is released into publication (mtm.mu -> c.mu).
issueCodeCh := make(chan int, 1)
go func() {
issueCodeCh <- issueToken("overlap-live-tok")
}()
close(releaseInit)
select {
case err := <-peerErrCh:
if err != nil {
t.Fatalf("peer monitor publication failed: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("deadlock detected waiting for peer monitor publication")
}
select {
case code := <-issueCodeCh:
if code != http.StatusOK {
t.Fatalf("expected 200 from concurrent tenant token issuance, got %d", code)
}
case <-time.After(10 * time.Second):
t.Fatal("deadlock detected waiting for concurrent tenant token issuance")
}
// Also verify direct replacement of orgID itself publishes cleanly and a
// subsequent tenant token issuance returns 201 Created.
armed.Store(false)
mtm.RemoveTenant(orgID)
mon, err := mtm.GetMonitor(orgID)
if err != nil {
t.Fatalf("replacement GetMonitor(orgID) failed: %v", err)
}
if mon == nil {
t.Fatal("replacement GetMonitor(orgID) returned nil monitor")
}
if code := issueToken("post-replace-tok"); code != http.StatusOK {
t.Fatalf("expected 200 from tenant token issuance after monitor replacement, got %d", code)
}
}
// High #2 regression: first-run reset must clear live r.config.APITokens when
// SaveAPITokensReplaceInventory publishes the empty inventory on disk and only
// the trailing directory fsync fails (DurablePublishSyncError).
func TestRound38_FirstRunResetClearsLiveTokensOnDurablePublishSyncError(t *testing.T) {
t.Setenv("PULSE_DEV", "true")
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
syncFS := &round37SyncDirFailFS{FileSystem: round37BaseFS{}}
p.SetFileSystem(syncFS)
rawTok := "r38-reset-sync-tok-0123456789abcdef0123"
tokRec, err := config.NewAPITokenRecord(rawTok, "old-admin", []string{config.ScopeWildcard})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*tokRec},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("seed SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
syncFS.failSyncDir.Store(true)
req := httptest.NewRequest(http.MethodPost, "/api/security/reset", nil)
req.Header.Set("X-API-Token", rawTok)
rec := httptest.NewRecorder()
router.handleResetFirstRunSecurity(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 on reset dir-sync error, got %d (%s)", rec.Code, rec.Body.String())
}
config.Mu.RLock()
remaining := len(cfg.APITokens)
config.Mu.RUnlock()
if remaining != 0 {
t.Fatalf("first-run reset left %d withdrawn tokens live in memory after durable publish sync failure", remaining)
}
}
// High #4 regressions:
// 1. Disk-backed host command-policy reconciliation stops at the first matching
// hash, rejecting an install token shadowed by an earlier record.
// 2. Pending-enable finalization re-verifies token authority under the token
// write lock and reverts pending enablement if the token was revoked.
func TestRound38_HostCommandPolicyShadowedHashAndPendingRevocation(t *testing.T) {
baseDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(baseDir)
rootP, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("root persistence: %v", err)
}
rawTok := "r38-shadow-install-tok-0123456789abcdef"
rec, err := config.NewAPITokenRecord(rawTok, "install-tok", []string{config.ScopeAgentReport, config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
rec.Metadata = map[string]string{
agenttokens.CommandPolicyIntentMetadataKey: agenttokens.CommandPolicyIntentEnabled,
"bound_agent_id": "host-r38-1",
"bound_hostname": "pve-r38-1",
agenttokens.CommandPolicyAppliedAgentIDMetadataKey: "host-r38-1",
}
// Put a shadowing record with identical hash and different ID FIRST on disk.
shadow := rec.Clone()
shadow.ID = "shadow-first-id"
if err := rootP.SaveAPITokens([]config.APITokenRecord{shadow, *rec}); err != nil {
t.Fatalf("SaveAPITokens shadow: %v", err)
}
rootCfg := &config.Config{DataPath: baseDir, ConfigPath: baseDir, APITokens: []config.APITokenRecord{shadow, *rec}}
mtm := monitoring.NewMultiTenantMonitor(rootCfg, mtp, nil)
t.Cleanup(func() { mtm.Stop() })
mon, err := mtm.GetMonitor("default")
if err != nil {
t.Fatalf("GetMonitor default: %v", err)
}
metaStore := mon.HostMetadataStore()
enabledTrue := true
if err := metaStore.Set("host-r38-1", &config.HostMetadata{
ID: "host-r38-1",
CommandsEnabled: &enabledTrue,
CommandsEnablePendingAuth: true,
CommandsEnablePendingTokenID: rec.ID,
CommandsEnablePendingTokenHash: rec.Hash,
}); err != nil {
t.Fatalf("seed pending metadata: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/agents/host/report", nil)
admittedCopy := rec.Clone()
attachAPITokenRecord(req, &admittedCopy)
_, withdrawn, _ := reconcileInstallTokenCommandPolicyForRequest(req, mon, &admittedCopy, models.Host{ID: "host-r38-1", Hostname: "pve-r38-1"})
if !withdrawn {
t.Fatal("expected shadowed hash on disk to withdraw install token command policy")
}
gotMeta := metaStore.Get("host-r38-1")
if gotMeta != nil && !gotMeta.CommandsEnablePendingAuth && gotMeta.CommandsEnabled != nil && *gotMeta.CommandsEnabled {
t.Fatalf("shadowed install token finalized command enablement: %+v", gotMeta)
}
}
// Medium #1 regression: removing a person-owned token owner's organization
// membership must withdraw BOTH token-mutation authorization AND topology
// telemetry completion eligibility.
func TestRound38_OwnerMembershipWithdrawalRejectsMutationAndTopologyCompletion(t *testing.T) {
dir := t.TempDir()
orgID := "org-r38-member"
loader := &r38DynamicOrgLoader{
orgs: map[string]*models.Organization{
orgID: {
ID: orgID,
DisplayName: "Org R38",
OwnerUserID: "owner-1",
Members: []models.OrganizationMember{
{UserID: "alice", Role: models.OrgRoleAdmin},
},
},
},
}
rawTok := "r38-owner-member-tok-0123456789abcdef01"
tokRec, err := config.NewAPITokenRecord(rawTok, "alice-tok", []string{config.ScopeSettingsWrite, config.ScopeMonitoringRead, config.ScopeAIChat})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
tokRec.OrgID = orgID
tokRec.OrgIDs = []string{orgID}
setAPITokenOwnerUserID(tokRec, "alice")
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*tokRec},
}
router := &Router{
config: cfg,
orgAccess: NewAuthorizationChecker(loader),
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("User-Agent", "pulse-cli/1.0")
req = req.WithContext(context.WithValue(req.Context(), apicontext.OrgIDContextKey, orgID))
copyRec := tokRec.Clone()
attachAPITokenRecord(req, &copyRec)
if !router.isTopologyTokenEligibleAtCompletion(req, time.Now().UTC()) {
t.Fatal("expected alice's token to be eligible while alice is a member")
}
// Remove alice from organization membership without revoking her token.
loader.mu.Lock()
loader.orgs[orgID].Members = nil
loader.mu.Unlock()
if router.isTopologyTokenEligibleAtCompletion(req, time.Now().UTC()) {
t.Fatal("topology completion accepted person-owned token after owner lost org membership")
}
config.Mu.Lock()
_, failure := router.currentTokenMutationCallerWithTenantLocked(req, tokenMutationLocksState{})
config.Mu.Unlock()
if failure == nil || failure.status != http.StatusForbidden {
t.Fatalf("expected 403 from token mutation authorizer after membership removal, got %+v", failure)
}
}
// Medium #4 regression: clearing PULSE_TELEMETRY=false on reload must allow an
// actual topology marker recorded through the original router's persistence
// handle to persist on disk (not stay pinned by a stale per-handle flag).
func TestRound38_ClearingForcedOffOverrideAllowsTopologyMarkerOnOriginalHandle(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("save enabled system settings: %v", err)
}
day := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(day); err != nil {
t.Fatalf("ensure tally: %v", err)
}
// Simulate startup under PULSE_TELEMETRY=false on the original router handle.
p.SetTopologyEnvOverride(false, true)
config.AdvanceTelemetryConsentGeneration()
// Simulate Reload clearing PULSE_TELEMETRY via directory override state.
config.SetTopologyEnvOverrideForDir(dir, false, false)
config.AdvanceTelemetryConsentGeneration()
gen := config.TelemetryConsentGeneration()
if err := p.RecordInfrastructureMapTopologyReadDayWithConsentGen(day, true, false, false, gen); err != nil {
t.Fatalf("RecordInfrastructureMapTopologyReadDayWithConsentGen after clearing forced-off: %v", err)
}
snap, avail, err := p.LoadInfrastructureMapTopologyTallySnapshot(day, 30)
if err != nil || !avail || snap == nil {
t.Fatalf("snapshot after marker: avail=%v err=%v", avail, err)
}
if got := len(snap.ActiveDaySetInWindow(config.InfrastructureMapActivityTopologyRead, day, 30)); got != 1 {
t.Fatalf("expected 1 recorded topology read day through original handle after clearing forced-off, got %d", got)
}
}
// Low #1 + Medium #2 regression: admit BOTH external-agent activity and
// workflow-prompt activity while telemetry is ENABLED, then commit opt-out
// right before persistence lookup (via testHookBeforeAgentActivityPersistenceLookup),
// verifying ZERO files (no .encryption.key, no history) are created in the
// dormant tenant directory.
func TestRound38_AdmittedActivityRecordersCommitOptOutBeforeLookupZeroTenantFiles(t *testing.T) {
baseDir := t.TempDir()
orgID := "dormant-r38-mid-optout"
dormantDir := filepath.Join(baseDir, "orgs", orgID)
if err := os.MkdirAll(dormantDir, 0o700); err != nil {
t.Fatalf("mkdir dormant org: %v", err)
}
mtp := config.NewMultiTenantPersistence(baseDir)
rootP, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("root persistence: %v", err)
}
enabled := true
if err := rootP.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("save enabled settings: %v", err)
}
rawTok := "r38-mid-optout-agent-tok-0123456789abcd"
tokRec, err := config.NewAPITokenRecord(rawTok, "agent-tok", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
cfg := &config.Config{
DataPath: baseDir,
ConfigPath: baseDir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{*tokRec},
}
router := &Router{
config: cfg,
persistence: rootP,
multiTenant: mtp,
}
for _, tc := range []struct {
name string
run func(req *http.Request)
}{
{
name: "external_agent_activity",
run: func(req *http.Request) {
router.recordExternalAgentActivity(req, config.ExternalAgentActivityFleetContext, config.ScopeMonitoringRead)
},
},
{
name: "workflow_prompt_activity",
run: func(req *http.Request) {
router.recordWorkflowPromptActivity(req, config.WorkflowPromptActivitySurfacePulseMCP, "investigate")
},
},
} {
t.Run(tc.name, func(t *testing.T) {
en := true
if err := rootP.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &en}); err != nil {
t.Fatalf("re-enable telemetry: %v", err)
}
config.Mu.Lock()
cfg.TelemetryEnabled = true
config.Mu.Unlock()
var hookFired atomic.Bool
prevHook := testHookBeforeAgentActivityPersistenceLookup
testHookBeforeAgentActivityPersistenceLookup = func() {
hookFired.Store(true)
dis := false
if err := rootP.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &dis}); err != nil {
t.Errorf("opt-out inside hook: %v", err)
}
}
t.Cleanup(func() { testHookBeforeAgentActivityPersistenceLookup = prevHook })
req := httptest.NewRequest(http.MethodPost, "/api/agent/workflow-prompt-activity", nil)
req.Header.Set("User-Agent", "pulse-mcp/1.0")
req = req.WithContext(context.WithValue(req.Context(), apicontext.OrgIDContextKey, orgID))
copyRec := tokRec.Clone()
attachAPITokenRecord(req, &copyRec)
tc.run(req)
if !hookFired.Load() {
t.Fatal("test hook did not fire: recorder returned before reaching persistence lookup")
}
entries, err := os.ReadDir(dormantDir)
if err != nil {
t.Fatalf("ReadDir dormant dir: %v", err)
}
if len(entries) != 0 {
t.Fatalf("%s created files in dormant tenant dir after mid-request opt-out: %v", tc.name, entries)
}
})
}
}
// High #1 regression: shadowed credential (earlier expired or different-ID
// record with identical hash) must be rejected on BOTH the ordinary host-report
// fast path (no pending policy) AND validateAgentExecSession.
func TestRound39_ShadowedCredentialRejectedOnOrdinaryHostReportAndExecSession(t *testing.T) {
dir := t.TempDir()
rawTok := "r39-shadow-exec-token-0123456789abcdef0"
admitted, err := config.NewAPITokenRecord(rawTok, "older-exec", []string{config.ScopeAgentReport, config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
admitted.Metadata = map[string]string{
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindLegacyFullTrust,
"bound_agent_id": "agent-r39-1",
"bound_hostname": "host-r39-1",
}
// Earlier shadowing record with identical hash, expired (or different ID).
past := time.Now().UTC().Add(-time.Hour)
shadow := admitted.Clone()
shadow.ID = "shadow-expired-id"
shadow.ExpiresAt = &past
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{shadow, *admitted},
}
router := &Router{config: cfg}
// 1) Established command-session validator must stop at first matching hash.
if router.validateAgentExecSession(agentexec.AgentAdmission{
OrganizationID: "default",
TokenID: admitted.ID,
TokenHash: admitted.Hash,
AgentID: "agent-r39-1",
Hostname: "host-r39-1",
RuntimeRole: agentexec.RuntimeRoleLegacyFullTrust,
}) {
t.Fatal("validateAgentExecSession accepted credential shadowed by earlier hash record")
}
// 2) Ordinary host-report fast path (no pending host policy) must withdraw.
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
req := httptest.NewRequest(http.MethodPost, "/api/agents/host/report", nil)
copyRec := admitted.Clone()
attachAPITokenRecord(req, &copyRec)
_, withdrawn, err := reconcileInstallTokenCommandPolicyForRequest(req, mon, &copyRec, models.Host{ID: "agent-r39-1", Hostname: "host-r39-1"})
if err != nil || !withdrawn {
t.Fatalf("expected ordinary host-report fast path to withdraw shadowed token, got withdrawn=%v err=%v", withdrawn, err)
}
}
// High #2 regression: tenant final mutation check must sort disk APITokens
// newest-first (matching live authentication) before applying first-hash lookup.
func TestRound39_TenantMutationDiskCheckSortsBeforeFirstHashDecision(t *testing.T) {
baseDir := t.TempDir()
orgID := "tenant-r39-sort"
mtp := config.NewMultiTenantPersistence(baseDir)
rootP, err := mtp.GetPersistence("default")
if err != nil {
t.Fatalf("root persistence: %v", err)
}
tenantP, err := mtp.GetPersistence(orgID)
if err != nil {
t.Fatalf("tenant persistence: %v", err)
}
rawTok := "r39-unsorted-tenant-tok-0123456789abcdef"
olderGrant, err := config.NewAPITokenRecord(rawTok, "older-admin", []string{config.ScopeSettingsWrite, config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord older: %v", err)
}
olderGrant.OrgID = orgID
olderGrant.CreatedAt = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
newerRestrictive := olderGrant.Clone()
newerRestrictive.ID = "newer-shadow-restrictive"
newerRestrictive.CreatedAt = time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)
newerRestrictive.Scopes = []string{config.ScopeMonitoringRead}
// Write in UNSORTED file order: olderGrant FIRST, newerRestrictive SECOND.
rawJSON, err := json.Marshal([]config.APITokenRecord{*olderGrant, newerRestrictive})
if err != nil {
t.Fatalf("marshal unsorted tokens: %v", err)
}
if err := os.WriteFile(filepath.Join(tenantP.ConfigDir(), "api_tokens.json"), rawJSON, 0o600); err != nil {
t.Fatalf("write unsorted tenant api_tokens.json: %v", err)
}
rootCfg := &config.Config{DataPath: baseDir, ConfigPath: baseDir}
mtm := monitoring.NewMultiTenantMonitor(rootCfg, mtp, nil)
t.Cleanup(func() { mtm.Stop() })
if _, err := mtm.GetMonitor(orgID); err != nil {
t.Fatalf("GetMonitor tenant: %v", err)
}
router := &Router{config: rootCfg, persistence: rootP, multiTenant: mtp}
req := httptest.NewRequest(http.MethodPost, "/api/security/tokens", strings.NewReader(`{"name":"should-fail","scopes":["monitoring:read"]}`))
req.Header.Set("Content-Type", "application/json")
ctx := context.WithValue(req.Context(), apicontext.OrgIDContextKey, orgID)
ctx = context.WithValue(ctx, tenantTokenSourceContextKey, tenantTokenSource{manager: mtm, orgID: orgID})
req = req.WithContext(ctx)
c := olderGrant.Clone()
attachAPITokenRecord(req, &c)
rec := httptest.NewRecorder()
router.handleCreateAPIToken(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 when newer restrictive token shadows older grant after sort, got %d (%s)", rec.Code, rec.Body.String())
}
}
// High #4 regression: final host-command promotion predicate must require the
// persisted CommandPolicyAppliedAgentIDMetadataKey to match host.ID exactly.
func TestRound39_FinalHostCommandPromotionRequiresExactAppliedHostID(t *testing.T) {
rawTok := "r39-phase4-host-id-tok-0123456789abcdef"
rec, err := config.NewAPITokenRecord(rawTok, "install-p4", []string{config.ScopeAgentReport, config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
rec.Metadata = map[string]string{
agenttokens.CommandPolicyIntentMetadataKey: agenttokens.CommandPolicyIntentEnabled,
"bound_agent_id": "host-a",
"bound_hostname": "pve-a",
}
host := models.Host{ID: "host-a", Hostname: "pve-a"}
// Missing applied host ID -> rejected.
if isInstallTokenAuthorizedForPendingPromotion(rec, rec, "default", host) {
t.Fatal("expected promotion rejected when applied host ID marker is missing")
}
// Wrong applied host ID -> rejected.
rec.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey] = "host-other"
if isInstallTokenAuthorizedForPendingPromotion(rec, rec, "default", host) {
t.Fatal("expected promotion rejected when applied host ID marker belongs to another host")
}
// Exact host ID match -> allowed.
rec.Metadata[agenttokens.CommandPolicyAppliedAgentIDMetadataKey] = "host-a"
if !isInstallTokenAuthorizedForPendingPromotion(rec, rec, "default", host) {
t.Fatal("expected promotion allowed when applied host ID matches host.ID")
}
}
type r39CountingBlockingOrgLoader struct {
calls atomic.Int32
block chan struct{}
}
func (l *r39CountingBlockingOrgLoader) GetOrganization(orgID string) (*models.Organization, error) {
l.calls.Add(1)
if l.block != nil {
<-l.block
}
return &models.Organization{ID: orgID, DisplayName: orgID}, nil
}
// Medium #2 regression: synchronous topology completion fast-check performs zero
// org.json disk I/O and defers person-owned membership validation to the bounded
// async observer helper.
func TestRound39_TopologyCompletionFastCheckZeroDiskIOAndBoundedMembership(t *testing.T) {
dir := t.TempDir()
orgID := "org-r39-slow"
loader := &r39CountingBlockingOrgLoader{block: make(chan struct{})}
t.Cleanup(func() { close(loader.block) })
rawTok := "r39-slow-org-member-tok-0123456789abcdef"
tokRec, err := config.NewAPITokenRecord(rawTok, "alice-slow", []string{config.ScopeMonitoringRead, config.ScopeAIChat})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
tokRec.OrgID = orgID
tokRec.OrgIDs = []string{orgID}
setAPITokenOwnerUserID(tokRec, "alice")
cfg := &config.Config{DataPath: dir, ConfigPath: dir, APITokens: []config.APITokenRecord{*tokRec}}
router := &Router{config: cfg, orgAccess: NewAuthorizationChecker(loader)}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("User-Agent", "pulse-cli/1.0")
req = req.WithContext(context.WithValue(req.Context(), apicontext.OrgIDContextKey, orgID))
c := tokRec.Clone()
attachAPITokenRecord(req, &c)
fastRes := router.topologyCompletionTokenFastCheck(req, time.Now().UTC())
eligible, needsMembership, cloned, gotOrg := fastRes.eligible, fastRes.needsOrgMembershipCheck, fastRes.cloned, fastRes.orgID
if !eligible || !needsMembership || cloned == nil || gotOrg != orgID {
t.Fatalf("unexpected fast check result: eligible=%v needsMembership=%v cloned=%v org=%q", eligible, needsMembership, cloned, gotOrg)
}
if got := loader.calls.Load(); got != 0 {
t.Fatalf("synchronous fast check invoked orgLoader %d times (want 0)", got)
}
allowed, indeterminate, timedOut := router.checkTopologyTokenOrgMembershipBounded(context.Background(), cloned, gotOrg)
if allowed || indeterminate || !timedOut {
t.Fatalf("expected stalled orgLoader to time out bounded check, got allowed=%v indeterminate=%v timedOut=%v", allowed, indeterminate, timedOut)
}
}
// Round 40 High #3 regression: host report handling must neither persist
// bound_agent_id onto a shadowed record nor return commandsEnabled=true or
// commandAgentId on either a normal or stale/duplicate report when shadowed.
func TestRound40_HostReportRejectsShadowedCredentialIdentityBindAndCommandEligibility(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
rawTok := "r40-shadow-host-report-0123456789abcdef"
older, err := config.NewAPITokenRecord(rawTok, "install-old", []string{config.ScopeAgentReport, config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
older.CreatedAt = time.Now().UTC().Add(-2 * time.Hour)
older.Metadata = map[string]string{
"bound_hostname": "pve-r40",
agenttokens.CommandPolicyIntentMetadataKey: agenttokens.CommandPolicyIntentEnabled,
agentbinding.DeployIdentityKey: agentbinding.DeployIdentityAgent,
}
// Newer record with same hash shadows older under authentication's first-hash rule.
shadow := older.Clone()
shadow.ID = "install-shadow-newer"
shadow.Name = "shadow-restricted"
shadow.Scopes = []string{config.ScopeMonitoringRead}
shadow.CreatedAt = time.Now().UTC()
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*older, shadow},
}
cfg.SortAPITokens()
if err := p.SaveAPITokens([]config.APITokenRecord{*older, shadow}); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
mon.SetOrgID("default")
mon.SetInstanceAPITokenInventory(cfg, p)
router := &Router{config: cfg, persistence: p}
// 1. Direct identity recorder must NOT persist bound_agent_id onto the shadowed older token.
req := httptest.NewRequest(http.MethodPost, "/api/agents/host/report", nil)
router.recordReportedAgentIdentityForToken(req, mon, "default", older, "agent-r40", "host-r40", "pve-r40")
diskAfter, err := p.LoadAPITokens()
if err != nil {
t.Fatalf("LoadAPITokens: %v", err)
}
for _, rec := range diskAfter {
if rec.ID == older.ID && strings.TrimSpace(rec.Metadata["bound_agent_id"]) != "" {
t.Fatalf("shadowed credential had bound_agent_id written: %+v", rec.Metadata)
}
}
// 2. Stale/duplicate report read-only live lookup must reject the shadowed older token
// (so commandsEnabled=false and commandAgentId is omitted).
live, withdrawn := lookupLiveInstallTokenReadOnly(req, mon, older, "default")
if live != nil || !withdrawn {
t.Fatalf("expected shadowed credential rejected on read-only report lookup, got live=%+v withdrawn=%v", live, withdrawn)
}
}
type r40ErrOrgLoader struct {
err error
}
func (l *r40ErrOrgLoader) GetOrganization(orgID string) (*models.Organization, error) {
return nil, l.err
}
// Round 40 Medium #1 & #2 regression:
// 1. Bounded org-membership lookup permits prevent unbounded goroutine growth
// on repeated timeouts and WaitTopologyObservers accounts for blocked workers.
// 2. Prompt non-ENOENT storage errors preserve Indeterminate=true and route
// through the degraded-coverage notifier instead of silently recording a healthy zero.
func TestRound40_TopologyOrgMembershipBoundedWorkersDrainAndStorageErrorDegrades(t *testing.T) {
dir := t.TempDir()
orgID := "org-r40-bounded"
loader := &r39CountingBlockingOrgLoader{block: make(chan struct{})}
rawTok := "r40-bounded-org-tok-0123456789abcdef"
tokRec, err := config.NewAPITokenRecord(rawTok, "alice-r40", []string{config.ScopeMonitoringRead, config.ScopeAIChat})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
tokRec.OrgID = orgID
tokRec.OrgIDs = []string{orgID}
setAPITokenOwnerUserID(tokRec, "alice")
cfg := &config.Config{DataPath: dir, ConfigPath: dir, APITokens: []config.APITokenRecord{*tokRec}}
router := &Router{config: cfg, orgAccess: NewAuthorizationChecker(loader)}
// Use a small custom permit channel (capacity 2) to verify saturation fast.
router.topologyOrgMembershipSlotsOnce.Do(func() {
router.topologyOrgMembershipSlots = make(chan struct{}, 2)
})
// Fill both permits with blocked calls, then invoke a 3rd call which must
// time out waiting for a permit WITHOUT spawning a 3rd loader goroutine.
for i := 0; i < 3; i++ {
allowed, indeterminate, timedOut := router.checkTopologyTokenOrgMembershipBounded(context.Background(), tokRec, orgID)
if allowed || indeterminate || !timedOut {
t.Fatalf("call %d: expected timeout, got allowed=%v indeterminate=%v timedOut=%v", i, allowed, indeterminate, timedOut)
}
}
if got := loader.calls.Load(); got != 2 {
t.Fatalf("expected bounded permit pool to cap active loader calls at 2, got %d", got)
}
// WaitTopologyObservers must stay blocked until the in-flight membership workers exit.
drainDone := make(chan struct{})
go func() {
router.WaitTopologyObservers()
close(drainDone)
}()
select {
case <-drainDone:
close(loader.block)
t.Fatal("WaitTopologyObservers returned while blocked org-membership workers were still running")
case <-time.After(60 * time.Millisecond):
}
close(loader.block)
select {
case <-drainDone:
case <-time.After(3 * time.Second):
t.Fatal("WaitTopologyObservers did not complete after releasing org-membership workers")
}
// Part 2 (Medium #2): transient storage error returns Indeterminate=true (degraded),
// while os.ErrNotExist returns Indeterminate=false (definite denial).
errRouter := &Router{
config: cfg,
orgAccess: NewAuthorizationChecker(&r40ErrOrgLoader{err: errors.New("disk read failed")}),
}
allowed, indeterminate, timedOut := errRouter.checkTopologyTokenOrgMembershipBounded(context.Background(), tokRec, orgID)
if allowed || !indeterminate || timedOut {
t.Fatalf("storage error: expected allowed=false indeterminate=true timedOut=false, got %v/%v/%v", allowed, indeterminate, timedOut)
}
missingRouter := &Router{
config: cfg,
orgAccess: NewAuthorizationChecker(&r40ErrOrgLoader{err: os.ErrNotExist}),
}
allowed, indeterminate, timedOut = missingRouter.checkTopologyTokenOrgMembershipBounded(context.Background(), tokRec, orgID)
if allowed || indeterminate || timedOut {
t.Fatalf("missing org: expected allowed=false indeterminate=false timedOut=false, got %v/%v/%v", allowed, indeterminate, timedOut)
}
}
// Round 41 Medium #1 regression: Router.WaitTopologyDrain must wait on
// topologyOrgMembershipWG (respecting ctx deadline while blocked and draining
// cleanly once released).
func TestRound41_WaitTopologyDrainWaitsForBlockedOrgMembershipWorkersWithDeadline(t *testing.T) {
dir := t.TempDir()
orgID := "org-r41-drain"
loader := &r39CountingBlockingOrgLoader{block: make(chan struct{})}
rawTok := "r41-drain-org-member-tok-0123456789abcdef"
tokRec, err := config.NewAPITokenRecord(rawTok, "alice-r41-drain", []string{config.ScopeMonitoringRead, config.ScopeAIChat})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
tokRec.OrgID = orgID
tokRec.OrgIDs = []string{orgID}
setAPITokenOwnerUserID(tokRec, "alice")
cfg := &config.Config{DataPath: dir, ConfigPath: dir, APITokens: []config.APITokenRecord{*tokRec}}
router := &Router{config: cfg, orgAccess: NewAuthorizationChecker(loader)}
// Trigger one blocked org-membership worker that times out the caller.
allowed, indeterminate, timedOut := router.checkTopologyTokenOrgMembershipBounded(context.Background(), tokRec, orgID)
if allowed || indeterminate || !timedOut {
t.Fatalf("expected timeout, got allowed=%v indeterminate=%v timedOut=%v", allowed, indeterminate, timedOut)
}
// Production WaitTopologyDrain with a short deadline must wait up to the
// deadline while the org-membership worker is still blocked.
shortCtx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
defer cancel()
start := time.Now()
router.WaitTopologyDrain(shortCtx)
if elapsed := time.Since(start); elapsed < 60*time.Millisecond {
close(loader.block)
t.Fatalf("WaitTopologyDrain returned early (%v) while org-membership worker was blocked", elapsed)
}
// Unblock the worker and confirm WaitTopologyDrain finishes promptly.
close(loader.block)
drainCtx, cancel2 := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel2()
router.WaitTopologyDrain(drainCtx)
if drainCtx.Err() != nil {
t.Fatalf("WaitTopologyDrain timed out after releasing worker: %v", drainCtx.Err())
}
}
// Round 41 Medium #3 & #4 regression:
// 1. Action runner self-revocation and collector authority reduction must apply
// first-matching-hash and reject shadowed credentials.
// 2. On a DurablePublishSyncError (rename succeeded, dir sync failed), both
// handlers must still invalidate the live agentExecServer session.
func TestRound41_RunnerRevocationAndCollectorReductionShadowAndSyncErrorInvalidation(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
// --- Part 1: Shadowed action-runner self-revocation must be rejected ---
rawRunner := "r41-shadow-runner-tok-0123456789abcdef"
olderRunner, err := config.NewAPITokenRecord(rawRunner, "runner-old", []string{config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
olderRunner.OrgID = "default"
olderRunner.OrgIDs = []string{"default"}
olderRunner.CreatedAt = time.Now().UTC().Add(-2 * time.Hour)
olderRunner.Metadata = map[string]string{
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindActionRunner,
agenttokens.ActionCapabilityMetadataKey: agenttokens.ActionCapabilityTypedV1,
agenttokens.ActionBindingVersionMetadataKey: agenttokens.ActionBindingVersion,
"bound_agent_id": "agent-r41",
"bound_hostname": "host-r41",
}
shadowRunner := olderRunner.Clone()
shadowRunner.ID = "runner-shadow-newer"
shadowRunner.Scopes = []string{config.ScopeMonitoringRead}
shadowRunner.Metadata = nil
shadowRunner.CreatedAt = time.Now().UTC()
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*olderRunner, shadowRunner},
}
cfg.SortAPITokens()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
body := `{"agentId":"agent-r41","hostname":"host-r41"}`
req := httptest.NewRequest(http.MethodDelete, "/api/agent-exec/credentials/revoke", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
c := olderRunner.Clone()
attachAPITokenRecord(req, &c)
rec := httptest.NewRecorder()
router.handleSelfRevokeActionRunnerCredential(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for shadowed action runner self-revocation, got %d (%s)", rec.Code, rec.Body.String())
}
// --- Part 2: Shadowed collector authority reduction must be rejected ---
rawColl := "r41-shadow-collector-tok-0123456789abcdef"
olderColl, err := config.NewAPITokenRecord(rawColl, "coll-old", []string{config.ScopeAgentReport, config.ScopeAgentExec})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
olderColl.OrgID = "default"
olderColl.OrgIDs = []string{"default"}
olderColl.CreatedAt = time.Now().UTC().Add(-2 * time.Hour)
olderColl.Metadata = map[string]string{
"bound_agent_id": "agent-c41",
"bound_hostname": "host-c41",
}
shadowColl := olderColl.Clone()
shadowColl.ID = "coll-shadow-newer"
shadowColl.Scopes = []string{config.ScopeMonitoringRead}
shadowColl.CreatedAt = time.Now().UTC()
cfg.APITokens = []config.APITokenRecord{*olderColl, shadowColl}
cfg.SortAPITokens()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
req2 := httptest.NewRequest(http.MethodPost, "/api/agent/collector-authority/reduce", strings.NewReader(`{"agentId":"agent-c41","hostname":"host-c41"}`))
req2.Header.Set("Content-Type", "application/json")
c2 := olderColl.Clone()
attachAPITokenRecord(req2, &c2)
rec2 := httptest.NewRecorder()
router.handleReduceCollectorAuthority(rec2, req2)
if rec2.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for shadowed collector authority reduction, got %d (%s)", rec2.Code, rec2.Body.String())
}
// --- Part 3: DurablePublishSyncError on self-revocation STILL invalidates live session ---
syncRouter, _, hostID := newActionRunnerCredentialTestRouter(t)
syncFS := &round37SyncDirFailFS{FileSystem: round37BaseFS{}}
syncRouter.persistence.SetFileSystem(syncFS)
syncRouter.agentExecServer = agentexec.NewServerWithAdmissionValidator(syncRouter.admitAgentExecToken, syncRouter.validateAgentExecSession)
issued := issueActionRunnerCredentialForTest(t, syncRouter, hostID, "host-1.local")
commitActionRunnerCredentialForTest(t, syncRouter, issued)
conn, ts := connectActionRunnerCredentialForTest(t, syncRouter.agentExecServer, issued)
defer conn.Close()
defer ts.Close()
if !syncRouter.agentExecServer.IsAgentConnectedForOrganization("default", hostID) {
t.Fatal("expected action runner session connected before revoke")
}
var liveIssued config.APITokenRecord
for _, recTok := range syncRouter.config.APITokens {
if recTok.ID == issued.TokenID {
liveIssued = recTok.Clone()
break
}
}
syncFS.failSyncDir.Store(true)
req3 := httptest.NewRequest(http.MethodDelete, "/api/agent-exec/credentials/revoke", strings.NewReader(`{"agentId":"`+hostID+`","hostname":"host-1.local"}`))
req3.Header.Set("Content-Type", "application/json")
attachAPITokenRecord(req3, &liveIssued)
rec3 := httptest.NewRecorder()
syncRouter.handleSelfRevokeActionRunnerCredential(rec3, req3)
if rec3.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 on DurablePublishSyncError during revoke, got %d (%s)", rec3.Code, rec3.Body.String())
}
if syncRouter.agentExecServer.IsAgentConnectedForOrganization("default", hostID) {
t.Fatal("DurablePublishSyncError during self-revocation left live action runner session connected")
}
}
// Round 42 High #4 regression: restoring a pre-activation pending runner
// record (same ID & hash, ActionRunnerActivationPendingMetadataKey="true")
// must fail active dispatch validation in validateAgentExecSession.
func TestRound42_RestoredPendingRunnerBackupRejectedByValidateAgentExecSession(t *testing.T) {
router, cfg, hostID := newActionRunnerCredentialTestRouter(t)
router.agentExecServer = agentexec.NewServerWithAdmissionValidator(router.admitAgentExecToken, router.validateAgentExecSession)
issued := issueActionRunnerCredentialForTest(t, router, hostID, "host-1.local")
commitActionRunnerCredentialForTest(t, router, issued)
conn, ts := connectActionRunnerCredentialForTest(t, router.agentExecServer, issued)
defer conn.Close()
defer ts.Close()
var committed config.APITokenRecord
config.Mu.Lock()
for i := range cfg.APITokens {
if cfg.APITokens[i].ID == issued.TokenID {
committed = cfg.APITokens[i].Clone()
// Simulate restoring a pre-activation backup where pending="true".
cfg.APITokens[i].Metadata[agenttokens.ActionRunnerActivationPendingMetadataKey] = "true"
break
}
}
config.Mu.Unlock()
admission := agentexec.AgentAdmission{
OrganizationID: "default",
TokenID: committed.ID,
TokenHash: committed.Hash,
AgentID: hostID,
Hostname: "host-1.local",
RuntimeRole: agentexec.RuntimeRoleActionRunner,
ActionCapability: agentexec.ActionCapabilityTypedV1,
}
if router.validateAgentExecSession(admission) {
t.Fatal("validateAgentExecSession accepted a pending action runner credential for active dispatch")
}
}
// Round 42 Medium #4 regression: a DurablePublishSyncError during pending
// action runner cancellation must still tombstone the pending socket admission
// on agentExecServer before returning HTTP 500.
func TestRound42_PendingRunnerCancelTombstonesAdmissionOnDurablePublishSyncError(t *testing.T) {
router, cfg, hostID := newActionRunnerCredentialTestRouter(t)
syncFS := &round37SyncDirFailFS{FileSystem: round37BaseFS{}}
router.persistence.SetFileSystem(syncFS)
router.agentExecServer = agentexec.NewServerWithAdmissionValidator(router.admitAgentExecToken, router.validateAgentExecSession)
pending := issueActionRunnerCredentialForTest(t, router, hostID, "host-1.local")
conn, ts := connectActionRunnerCredentialForTest(t, router.agentExecServer, pending)
defer conn.Close()
defer ts.Close()
var pendingRec config.APITokenRecord
for _, tok := range cfg.APITokens {
if tok.ID == pending.TokenID {
pendingRec = tok.Clone()
break
}
}
syncFS.failSyncDir.Store(true)
req := httptest.NewRequest(http.MethodDelete, "/api/agent-exec/credentials/pending", nil)
attachAPITokenRecord(req, &pendingRec)
rec := httptest.NewRecorder()
router.handleCancelPendingActionRunnerCredentialActivation(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 on DurablePublishSyncError during pending cancel, got %d (%s)", rec.Code, rec.Body.String())
}
if router.agentExecServer.IsAgentConnectedForOrganization("default", hostID) {
t.Fatal("DurablePublishSyncError during pending cancel left pending socket registered")
}
}
// Round 43 High #1 regression: action-runner self-revocation must reject
// ambiguous duplicate hashes (HTTP 409) without deleting either record, and a
// successful HTTP 204 revocation must invalidate the original bearer token.
func TestRound43_ActionRunnerSelfRevokeRejectsDuplicateHashAndInvalidatesBearer(t *testing.T) {
router, cfg, hostID := newActionRunnerCredentialTestRouter(t)
router.agentExecServer = agentexec.NewServerWithAdmissionValidator(router.admitAgentExecToken, router.validateAgentExecSession)
issued := issueActionRunnerCredentialForTest(t, router, hostID, "host-1.local")
commitActionRunnerCredentialForTest(t, router, issued)
var callerRec config.APITokenRecord
for _, tok := range cfg.APITokens {
if tok.ID == issued.TokenID {
callerRec = tok.Clone()
break
}
}
// Add a second record with the exact same Hash (shadowed by callerRec).
shadowed := callerRec.Clone()
shadowed.ID = "shadowed-same-hash-id"
shadowed.CreatedAt = callerRec.CreatedAt.Add(-time.Hour)
cfg.APITokens = append(cfg.APITokens, shadowed)
cfg.SortAPITokens()
if err := router.persistence.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("save duplicate hash inventory: %v", err)
}
body := fmt.Sprintf(`{"agentId":%q,"hostname":"host-1.local"}`, hostID)
req := httptest.NewRequest(http.MethodDelete, "/api/agent-exec/credentials/self", strings.NewReader(body))
attachAPITokenRecord(req, &callerRec)
rec := httptest.NewRecorder()
router.handleSelfRevokeActionRunnerCredential(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict for duplicate credential hash, got %d (%s)", rec.Code, rec.Body.String())
}
if len(cfg.APITokens) != 2 {
t.Fatalf("duplicate hash conflict must not delete any record, got %d", len(cfg.APITokens))
}
// Remove the duplicate so callerRec is unique, revoke again -> 204 and bearer must no longer authenticate.
cfg.APITokens = []config.APITokenRecord{callerRec}
cfg.SortAPITokens()
if err := router.persistence.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("save unique inventory: %v", err)
}
req2 := httptest.NewRequest(http.MethodDelete, "/api/agent-exec/credentials/self", strings.NewReader(body))
attachAPITokenRecord(req2, &callerRec)
rec2 := httptest.NewRecorder()
router.handleSelfRevokeActionRunnerCredential(rec2, req2)
if rec2.Code != http.StatusNoContent {
t.Fatalf("expected 204 No Content on unique revocation, got %d (%s)", rec2.Code, rec2.Body.String())
}
if _, ok := cfg.ValidateAPIToken(issued.Token); ok {
t.Fatal("original bearer token still authenticated after HTTP 204 self-revocation")
}
}
// Round 43 High #5 regression: when telemetry is disabled, neither reporting
// activity nor audit read activity may create or write telemetry history files.
func TestRound43_ReportingAndAuditReadActivityZeroWriteAfterOptOut(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
disabled := false
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &disabled}); err != nil {
t.Fatalf("save disabled telemetry: %v", err)
}
cfg := &config.Config{DataPath: dir, ConfigPath: dir, TelemetryEnabled: false}
cfg.BindCanonicalDirKeys()
// 1) Reporting activity download must write zero files after opt-out.
rh := NewReportingHandlers(nil, nil)
rh.SetSystemSettingsStore(p)
dlReq := httptest.NewRequest(http.MethodGet, "/api/reports/download", nil)
rh.recordReportingDownload(dlReq, config.ReportScheduleKindResources, 10, nil, 10)
if _, err := os.Stat(filepath.Join(dir, "reporting_activity.json")); !os.IsNotExist(err) {
t.Fatalf("expected reporting_activity.json absent after opt-out, stat err=%v", err)
}
// 2) Audit read activity must write zero files after opt-out.
router := &Router{config: cfg, persistence: p}
auditReq := httptest.NewRequest(http.MethodGet, "/api/audit/events", nil)
router.recordAuditReadActivity(auditReq, config.AuditReadActivityList)
if _, err := os.Stat(filepath.Join(dir, "audit_read_activity.json")); !os.IsNotExist(err) {
t.Fatalf("expected audit_read_activity.json absent after opt-out, stat err=%v", err)
}
}
// Round 44 Low #1 regression: ambiguous duplicate pending hash returns HTTP 409
// Conflict from handleCancelPendingActionRunnerCredentialActivation and leaves
// the token inventory unchanged.
func TestRound44_PendingCancelDuplicateHashReturns409AndUnchangedInventory(t *testing.T) {
router, cfg, hostID := newActionRunnerCredentialTestRouter(t)
router.agentExecServer = agentexec.NewServerWithAdmissionValidator(router.admitAgentExecToken, router.validateAgentExecSession)
pending := issueActionRunnerCredentialForTest(t, router, hostID, "host-1.local")
var pendingRec config.APITokenRecord
for _, tok := range cfg.APITokens {
if tok.ID == pending.TokenID {
pendingRec = tok.Clone()
break
}
}
dup := pendingRec.Clone()
dup.ID = "dup-pending-hash-409"
dup.Scopes = []string{config.ScopeMonitoringRead}
dup.Metadata = nil
dup.CreatedAt = pendingRec.CreatedAt.Add(-time.Hour)
cfg.APITokens = append(cfg.APITokens, dup)
cfg.SortAPITokens()
if err := router.persistence.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
beforeLen := len(cfg.APITokens)
req := httptest.NewRequest(http.MethodDelete, "/api/agent-exec/credentials/pending", nil)
attachAPITokenRecord(req, &pendingRec)
rec := httptest.NewRecorder()
router.handleCancelPendingActionRunnerCredentialActivation(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict on duplicate pending hash, got %d (%s)", rec.Code, rec.Body.String())
}
if len(cfg.APITokens) != beforeLen {
t.Fatalf("expected unchanged inventory (%d), got %d", beforeLen, len(cfg.APITokens))
}
}
// Round 44 High #1 regression: admin token deletion and rotation reject
// duplicate hashes (HTTP 409) without mutating inventory, and unique deletion
// invalidates the raw bearer token.
func TestRound44_AdminDeleteAndRotateRejectDuplicateHashAndInvalidateUniqueBearer(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
rawTok := "r44-admin-dup-tok-0123456789abcdef01"
tok1, err := config.NewAPITokenRecord(rawTok, "tok-1", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
tok2 := tok1.Clone()
tok2.ID = "tok-2-same-hash"
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*tok1, tok2},
}
cfg.SortAPITokens()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
delReq := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/"+tok1.ID, nil)
delRec := httptest.NewRecorder()
router.handleDeleteAPIToken(delRec, delReq)
if delRec.Code != http.StatusConflict {
t.Fatalf("expected 409 on duplicate-hash admin delete, got %d (%s)", delRec.Code, delRec.Body.String())
}
if len(cfg.APITokens) != 2 {
t.Fatalf("expected inventory untouched after 409 delete, got %d", len(cfg.APITokens))
}
rotReq := httptest.NewRequest(http.MethodPost, "/api/security/tokens/"+tok1.ID+"/rotate", nil)
rotRec := httptest.NewRecorder()
router.handleRotateAPIToken(rotRec, rotReq)
if rotRec.Code != http.StatusConflict {
t.Fatalf("expected 409 on duplicate-hash admin rotate, got %d (%s)", rotRec.Code, rotRec.Body.String())
}
// Unique inventory -> delete succeeds and raw bearer no longer authenticates.
cfg.APITokens = []config.APITokenRecord{*tok1}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens unique: %v", err)
}
delReq2 := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/"+tok1.ID, nil)
delRec2 := httptest.NewRecorder()
router.handleDeleteAPIToken(delRec2, delReq2)
if delRec2.Code != http.StatusOK && delRec2.Code != http.StatusNoContent {
t.Fatalf("expected 200/204 on unique admin delete, got %d (%s)", delRec2.Code, delRec2.Body.String())
}
if _, ok := cfg.ValidateAPIToken(rawTok); ok {
t.Fatal("original raw bearer still authenticated after admin deletion")
}
}
// Round 44 High #2 regression: ambiguous token ID (two records with same ID
// and different hashes) must fail closed on host ownership and redact HTTP
// probe secrets in withholdProbeSecretsFromOtherTokens.
func TestRound44_AgentConfigWithholdsProbeSecretsOnAmbiguousTokenID(t *testing.T) {
recA, err := config.NewAPITokenRecord("r44-cfg-tok-a-0123456789abcdef0123", "tok-a", []string{config.ScopeAgentReport})
if err != nil {
t.Fatalf("recA: %v", err)
}
recB, err := config.NewAPITokenRecord("r44-cfg-tok-b-0123456789abcdef0123", "tok-b", []string{config.ScopeAgentReport})
if err != nil {
t.Fatalf("recB: %v", err)
}
recB.ID = recA.ID
dir := t.TempDir()
cfg := &config.Config{DataPath: dir, ConfigPath: dir, APITokens: []config.APITokenRecord{*recA, *recB}}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
h := &UnifiedAgentHandlers{baseAgentHandlers: baseAgentHandlers{defaultMonitor: mon}}
reqDup := httptest.NewRequest(http.MethodGet, "/api/agents/host/host-secret/config", nil)
if h.hasUniqueLiveAuthorizedTokenForConfig(reqDup, mon, recB) {
t.Fatal("expected hasUniqueLiveAuthorizedTokenForConfig=false for duplicate token ID")
}
bodyStr := "secret-body"
hdrVal := "Bearer super-secret"
host := models.Host{ID: "host-secret", TokenID: recA.ID}
agentCfg := monitoring.HostAgentConfig{
Settings: map[string]interface{}{
"availabilityTargets": []map[string]interface{}{
{
"id": "probe-1",
"http": &config.AvailabilityHTTPConfig{
Headers: []config.AvailabilityHTTPHeader{{Name: "Authorization", Value: &hdrVal}},
Body: &bodyStr,
},
},
},
},
}
redacted := withholdProbeSecretsFromOtherTokens(agentCfg, recB, host, h.hasUniqueLiveAuthorizedTokenForConfig(reqDup, mon, recB))
targets := redacted.Settings["availabilityTargets"].([]map[string]interface{})
httpCfg := targets[0]["http"].(*config.AvailabilityHTTPConfig)
if (httpCfg.Body != nil && *httpCfg.Body != "") || (len(httpCfg.Headers) > 0 && httpCfg.Headers[0].Value != nil && *httpCfg.Headers[0].Value != "") {
t.Fatalf("ambiguous token ID received unredacted probe secrets: %+v", httpCfg)
}
}
// Round 44 High #9 & High #10 regression: with telemetry disabled, extended
// history read recording, Patrol investigation telemetry init/record, and a
// cold-tenant audit read must write ZERO files and must NOT create the cold
// tenant's directory or .encryption.key.
func TestRound44_ExtendedHistoryPatrolLedgerAndColdTenantAuditReadZeroWriteAfterOptOut(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
disabled := false
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &disabled}); err != nil {
t.Fatalf("save opt-out: %v", err)
}
cfg := &config.Config{DataPath: dir, ConfigPath: dir, TelemetryEnabled: false}
cfg.BindCanonicalDirKeys()
mtp := config.NewMultiTenantPersistence(dir)
router := &Router{config: cfg, persistence: p, multiTenant: mtp}
// 1) Extended history read recorder must write zero files.
routerChartMonitorResolver{router: router}.RecordSuccessfulExtendedHistoryRead()
if _, err := os.Stat(filepath.Join(dir, "history_read_activity.json")); !os.IsNotExist(err) {
t.Fatalf("expected history_read_activity.json absent after opt-out, err=%v", err)
}
// 2) Patrol investigation ledger init & record must write zero files.
aiHandler := &AISettingsHandler{defaultPersistence: p}
now := time.Now().UTC()
aiHandler.recordInvestigationMeasurement("default", &aicontracts.InvestigationSession{
ID: "inv-optout-1",
Status: aicontracts.InvestigationStatusCompleted,
Outcome: aicontracts.OutcomeFixVerified,
CompletedAt: &now,
})
if _, err := os.Stat(filepath.Join(dir, "patrol_investigation_telemetry.json")); !os.IsNotExist(err) {
t.Fatalf("expected patrol_investigation_telemetry.json absent after opt-out, err=%v", err)
}
// 3) Cold-tenant audit read with opt-out must NOT create tenant directory or .encryption.key.
coldOrgID := "cold-tenant-r44"
auditReq := httptest.NewRequest(http.MethodGet, "/api/audit/events", nil)
auditReq = auditReq.WithContext(context.WithValue(auditReq.Context(), OrgIDContextKey, coldOrgID))
router.recordAuditReadActivity(auditReq, config.AuditReadActivityList)
if _, err := os.Stat(filepath.Join(dir, "orgs", coldOrgID)); !os.IsNotExist(err) {
t.Fatalf("cold-tenant audit read created tenant directory after opt-out: err=%v", err)
}
}
// Round 44 Medium #5 regression: an organization-listing failure must not
// suppress reading the independent root v26 topology tally.
func TestRound44_OrgEnumerationErrorStillPopulatesRootTopologyTally(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("save settings: %v", err)
}
now := time.Now().UTC()
if err := p.EnsureInfrastructureMapTopologyTally(now); err != nil {
t.Fatalf("EnsureInfrastructureMapTopologyTally: %v", err)
}
if err := p.RecordInfrastructureMapTopologyReadDayWithConsentGen(now, true, false, false, config.TelemetryConsentGeneration()); err != nil {
t.Fatalf("record topology read: %v", err)
}
// Make orgs path a regular file so ListOrganizationIDs returns an error.
if err := os.WriteFile(filepath.Join(dir, "orgs"), []byte("not-a-dir"), 0o600); err != nil {
t.Fatalf("seed invalid orgs file: %v", err)
}
router := &Router{
config: &config.Config{DataPath: dir, ConfigPath: dir, TelemetryEnabled: true},
persistence: p,
multiTenant: config.NewMultiTenantPersistence(dir),
}
snap := &telemetry.Snapshot{}
router.ApplyInfrastructureMapTelemetrySnapshot(snap, now)
if !snap.InfrastructureMapTopologyTelemetryAvailable || snap.InfrastructureMapTopologyReadDays30d != 1 || snap.InfrastructureMapTopologyCLIDays30d != 1 {
t.Fatalf("org-listing error suppressed healthy root topology tally: %+v", snap)
}
}
// Round 45 High #3 regression: if the admitted agent credential is withdrawn or
// replaced with a different hash between auth and config assembly, both
// resolveConfigAgent and probe-secret release must fail closed.
func TestRound45_AgentConfigWithholdsProbeSecretsAfterCredentialWithdrawalOrReplacement(t *testing.T) {
recOrig, err := config.NewAPITokenRecord("r45-wd-tok-orig-0123456789abcdef01", "tok-orig", []string{config.ScopeAgentReport})
if err != nil {
t.Fatalf("recOrig: %v", err)
}
recReplaced, err := config.NewAPITokenRecord("r45-wd-tok-repl-0123456789abcdef01", "tok-repl", []string{config.ScopeAgentReport})
if err != nil {
t.Fatalf("recReplaced: %v", err)
}
recReplaced.ID = recOrig.ID // Same ID, different hash.
dir := t.TempDir()
cfg := &config.Config{DataPath: dir, ConfigPath: dir, APITokens: []config.APITokenRecord{*recOrig}}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
if _, err := mon.ApplyHostReport(agentshost.Report{Host: agentshost.HostInfo{ID: "host-wd", Hostname: "host-wd"}}, recOrig); err != nil {
t.Fatalf("ApplyHostReport: %v", err)
}
h := &UnifiedAgentHandlers{baseAgentHandlers: baseAgentHandlers{defaultMonitor: mon}}
req := httptest.NewRequest(http.MethodGet, "/api/agents/host/host-wd/config", nil)
// Baseline: unique live matching credential is authorized.
if !h.hasUniqueLiveAuthorizedTokenForConfig(req, mon, recOrig) {
t.Fatal("expected unique live matching credential to be authorized")
}
bodyStr := "probe-secret-body"
hdrVal := "Bearer probe-secret-token"
host := models.Host{ID: "host-wd", TokenID: recOrig.ID}
makeAgentCfg := func() monitoring.HostAgentConfig {
b := bodyStr
v := hdrVal
return monitoring.HostAgentConfig{
Settings: map[string]interface{}{
"availabilityTargets": []map[string]interface{}{
{
"id": "probe-wd",
"http": &config.AvailabilityHTTPConfig{
Headers: []config.AvailabilityHTTPHeader{{Name: "Authorization", Value: &v}},
Body: &b,
},
},
},
},
}
}
// Case 1: credential withdrawn (zero matches in inventory).
config.Mu.Lock()
cfg.APITokens = nil
config.Mu.Unlock()
if _, ok := h.resolveConfigAgent(req, "host-wd", recOrig); ok {
t.Fatal("resolveConfigAgent must refuse withdrawn credential")
}
if h.hasUniqueLiveAuthorizedTokenForConfig(req, mon, recOrig) {
t.Fatal("withdrawn credential must not pass live authorization check")
}
redacted1 := withholdProbeSecretsFromOtherTokens(makeAgentCfg(), recOrig, host, h.hasUniqueLiveAuthorizedTokenForConfig(req, mon, recOrig))
http1 := redacted1.Settings["availabilityTargets"].([]map[string]interface{})[0]["http"].(*config.AvailabilityHTTPConfig)
if (http1.Body != nil && *http1.Body != "") || (len(http1.Headers) > 0 && http1.Headers[0].Value != nil && *http1.Headers[0].Value != "") {
t.Fatalf("withdrawn credential received unredacted probe secrets: %+v", http1)
}
// Case 2: credential replaced in place (1 match by ID, different hash).
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{*recReplaced}
config.Mu.Unlock()
if _, ok := h.resolveConfigAgent(req, "host-wd", recOrig); ok {
t.Fatal("resolveConfigAgent must refuse credential replaced by different hash")
}
if h.hasUniqueLiveAuthorizedTokenForConfig(req, mon, recOrig) {
t.Fatal("replaced credential must not pass live authorization check")
}
redacted2 := withholdProbeSecretsFromOtherTokens(makeAgentCfg(), recOrig, host, h.hasUniqueLiveAuthorizedTokenForConfig(req, mon, recOrig))
http2 := redacted2.Settings["availabilityTargets"].([]map[string]interface{})[0]["http"].(*config.AvailabilityHTTPConfig)
if (http2.Body != nil && *http2.Body != "") || (len(http2.Headers) > 0 && http2.Headers[0].Value != nil && *http2.Headers[0].Value != "") {
t.Fatalf("replaced credential received unredacted probe secrets: %+v", http2)
}
}
// Round 45 High #2 regression: distinct credentials sharing one ID must never
// bind the same command-agent identity via first bind, migration, or backfill.
func TestRound45_DistinctCredentialsSharingIDCannotClaimSameCommandAgent(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
rawA := "r45-exec-dup-a-0123456789abcdef012"
rawB := "r45-exec-dup-b-0123456789abcdef012"
recA, err := config.NewAPITokenRecord(rawA, "exec-a", []string{config.ScopeAgentExec, config.ScopeAgentReport})
if err != nil {
t.Fatalf("recA: %v", err)
}
recA.Metadata = map[string]string{
"issued_via": "install_script",
"bound_agent_id": "agent-r45-exec",
"bound_hostname": "node-a",
}
recB, err := config.NewAPITokenRecord(rawB, "exec-b", []string{config.ScopeAgentExec, config.ScopeAgentReport})
if err != nil {
t.Fatalf("recB: %v", err)
}
recB.ID = recA.ID // Distinct hash, shared ID!
recB.Metadata = map[string]string{
"issued_via": "install_script",
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*recA, *recB},
}
cfg.BindCanonicalDirKeys()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
if _, ok := router.admitAgentExecToken(rawB, "agent-r45-exec", "node-a"); ok {
t.Fatal("expected second credential sharing ID with already-bound credential to be refused")
}
config.Mu.RLock()
boundB := cfg.APITokens[1].Metadata["bound_agent_id"]
config.Mu.RUnlock()
if boundB != "" {
t.Fatalf("expected refused duplicate-ID credential to remain unbound, got %q", boundB)
}
}
// Round 45 Medium #1 regression: handleUpdateAPIToken must return 409 Conflict
// before mutating scopes or name when duplicate token IDs exist.
func TestRound45_UpdateAPITokenRejectsDuplicateIDWithConflict(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
adminRaw := "r45-upd-admin-0123456789abcdef0123"
adminRec, err := config.NewAPITokenRecord(adminRaw, "admin", []string{config.ScopeWildcard})
if err != nil {
t.Fatalf("adminRec: %v", err)
}
recA, err := config.NewAPITokenRecord("r45-upd-a-0123456789abcdef01234567", "dup-a", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("recA: %v", err)
}
recB, err := config.NewAPITokenRecord("r45-upd-b-0123456789abcdef01234567", "dup-b", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("recB: %v", err)
}
recB.ID = recA.ID
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{*adminRec, *recA, *recB},
}
cfg.BindCanonicalDirKeys()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
req := httptest.NewRequest(http.MethodPatch, "/api/security/tokens/"+recA.ID, strings.NewReader(`{"name":"renamed","scopes":["monitoring:read","settings:write"]}`))
req.Header.Set("Content-Type", "application/json")
attachAPITokenRecord(req, adminRec)
rr := httptest.NewRecorder()
router.handleUpdateAPIToken(rr, req)
if rr.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict on duplicate token ID update, got %d (%s)", rr.Code, rr.Body.String())
}
config.Mu.RLock()
nameA := cfg.APITokens[1].Name
scopesA := append([]string(nil), cfg.APITokens[1].Scopes...)
config.Mu.RUnlock()
if nameA != "dup-a" || len(scopesA) != 1 || scopesA[0] != config.ScopeMonitoringRead {
t.Fatalf("duplicate token was mutated despite 409: name=%q scopes=%v", nameA, scopesA)
}
}
// Round 45 Medium #2 regression: holding config.Mu.Lock() during topology
// completion must never stall the synchronous HTTP response past the 250ms
// budget, and completion-time contention must record explicit loss accounting.
func TestRound45_TopologyCompletionConfigMuContentionNonBlockingAndAccounted(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("SaveSystemSettings: %v", err)
}
fixedNow := time.Date(2026, 12, 1, 14, 0, 0, 0, time.UTC)
if err := p.EnsureInfrastructureMapTopologyTally(fixedNow); err != nil {
t.Fatalf("EnsureInfrastructureMapTopologyTally: %v", err)
}
tokRec, err := config.NewAPITokenRecord("r45-topo-lock-0123456789abcdef0123", "topo-reader", []string{config.ScopeMonitoringRead})
if err != nil {
t.Fatalf("NewAPITokenRecord: %v", err)
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{*tokRec},
}
cfg.BindCanonicalDirKeys()
router := &Router{
config: cfg,
persistence: p,
topologyNow: func() time.Time { return fixedNow },
}
// Simulate config.Mu.Lock() held across a stalled token mutation while
// topologyCompletionTokenFastCheck and isTopologyConsentFastPermitted run.
config.Mu.Lock()
start := time.Now()
fastConsent := router.isTopologyConsentFastPermitted()
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
attachAPITokenRecord(req, tokRec)
fastRes := router.topologyCompletionTokenFastCheck(req, fixedNow)
elapsed := time.Since(start)
if elapsed > 100*time.Millisecond {
config.Mu.Unlock()
t.Fatalf("synchronous topology fast checks blocked under config.Mu.Lock() for %v", elapsed)
}
if !fastConsent || !fastRes.lockContended || fastRes.deferredReq == nil {
config.Mu.Unlock()
t.Fatalf("expected non-blocking contention handoff, got fastConsent=%v res=%+v", fastConsent, fastRes)
}
// Bounded async revalidation while config.Mu.Lock() stays held must time out
// within ~250ms rather than hanging forever.
bStart := time.Now()
_, timedOut := router.checkTopologyCompletionTokenBounded(context.Background(), fastRes.deferredReq, fixedNow)
bElapsed := time.Since(bStart)
config.Mu.Unlock()
router.WaitTopologyObservers()
if !timedOut {
t.Fatal("expected bounded completion token revalidation to time out while config.Mu.Lock() was held")
}
if bElapsed > time.Second {
t.Fatalf("bounded completion token revalidation exceeded timeout budget: %v", bElapsed)
}
// Recording degraded loss for that timeout flips coverage to 0 (unavailable).
router.markInfrastructureMapTopologyDegradedInMemory(fixedNow, config.TelemetryConsentGeneration())
router.WaitTopologyObservers()
_, available, snapErr := p.LoadInfrastructureMapTopologyTallySnapshotReadOnly(fixedNow, 30)
if snapErr != nil || available {
t.Fatalf("expected degraded coverage (available=false) after completion-time lock contention loss, got available=%v err=%v", available, snapErr)
}
}
// Round 45 Medium #7 regression: updateAuthEnvFile must abort on non-ENOENT
// read errors rather than replacing unrelated .env settings with an auth-only
// file, and when falling back to DataPath/.env it must merge that file's
// existing contents.
func TestRound45_UpdateAuthEnvFileAbortsOnReadErrorAndMergesFallback(t *testing.T) {
// Part 1: directory at .env causes a non-ENOENT read error -> must abort!
dir1 := t.TempDir()
envDir := filepath.Join(dir1, ".env")
if err := os.Mkdir(envDir, 0o700); err != nil {
t.Fatalf("Mkdir .env: %v", err)
}
_, err := updateAuthEnvFile(dir1, dir1, func(existing []byte, exists bool) ([]byte, error) {
return []byte("PULSE_AUTH_PASS='new'\n"), nil
})
if err == nil {
t.Fatal("expected updateAuthEnvFile to abort when .env read fails with non-ENOENT error")
}
// Part 2: preferred path is a regular file (cannot MkdirAll), fallback
// DataPath/.env already holds unrelated settings -> must preserve them!
base := t.TempDir()
blockedConfigPath := filepath.Join(base, "not-a-dir")
if err := os.WriteFile(blockedConfigPath, []byte("blocker"), 0o600); err != nil {
t.Fatalf("WriteFile blocker: %v", err)
}
fallbackDir := filepath.Join(base, "data")
if err := os.MkdirAll(fallbackDir, 0o700); err != nil {
t.Fatalf("MkdirAll fallback: %v", err)
}
fallbackEnv := filepath.Join(fallbackDir, ".env")
if err := os.WriteFile(fallbackEnv, []byte("PULSE_CUSTOM_KEEP=yes\nPULSE_AUTH_PASS='old'\n"), 0o600); err != nil {
t.Fatalf("WriteFile fallback .env: %v", err)
}
writtenPath, err := updateAuthEnvFile(blockedConfigPath, fallbackDir, func(existing []byte, exists bool) ([]byte, error) {
if !exists || !strings.Contains(string(existing), "PULSE_CUSTOM_KEEP=yes") {
t.Fatalf("expected fallback .env contents to be read before writing, exists=%v content=%q", exists, string(existing))
}
return []byte(strings.ReplaceAll(string(existing), "PULSE_AUTH_PASS='old'", "PULSE_AUTH_PASS='rotated'")), nil
})
if err != nil {
t.Fatalf("updateAuthEnvFile fallback: %v", err)
}
if writtenPath != fallbackEnv {
t.Fatalf("expected fallback path %q, got %q", fallbackEnv, writtenPath)
}
finalBytes, err := os.ReadFile(fallbackEnv)
if err != nil {
t.Fatalf("ReadFile fallback .env: %v", err)
}
if !strings.Contains(string(finalBytes), "PULSE_CUSTOM_KEEP=yes") || !strings.Contains(string(finalBytes), "PULSE_AUTH_PASS='rotated'") {
t.Fatalf("fallback .env did not preserve unrelated settings alongside rotated password: %q", string(finalBytes))
}
}
// Round 45 Low #1 regression: handleActivateActionRunnerCredential maps
// agenttokens.ErrActionRunnerAmbiguousCredential to HTTP 409 Conflict.
func TestRound45_ActivateActionRunnerAmbiguousHashReturnsHTTP409(t *testing.T) {
router, cfg, hostID := newActionRunnerCredentialTestRouter(t)
router.agentExecServer = agentexec.NewServerWithAdmissionValidator(router.admitAgentExecToken, router.validateAgentExecSession)
pending := issueActionRunnerCredentialForTest(t, router, hostID, "host-1.local")
var pendingRec config.APITokenRecord
for _, tok := range cfg.APITokens {
if tok.ID == pending.TokenID {
pendingRec = tok.Clone()
break
}
}
dup := pendingRec.Clone()
dup.ID = "dup-activate-hash-409"
dup.Scopes = []string{config.ScopeMonitoringRead}
dup.Metadata = nil
dup.CreatedAt = pendingRec.CreatedAt.Add(-time.Hour)
cfg.APITokens = append(cfg.APITokens, dup)
cfg.SortAPITokens()
if err := router.persistence.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
body := fmt.Sprintf(`{"agentId":%q,"hostname":"host-1.local"}`, hostID)
req := httptest.NewRequest(http.MethodPatch, "/api/agent-exec/credentials/activate", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
attachAPITokenRecord(req, &pendingRec)
rr := httptest.NewRecorder()
router.handleActivateActionRunnerCredential(rr, req)
if rr.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict on ambiguous action runner credential activation, got %d (%s)", rr.Code, rr.Body.String())
}
}
// Round 46 High #1: Report-driven binding and already-bound WebSocket admission
// must both refuse duplicate token IDs.
func TestRound46_ReportBindingAndAlreadyBoundAdmissionRejectDuplicateTokenID(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
rawA := "r46-dup-id-raw-token-a-0000000001"
rawB := "r46-dup-id-raw-token-b-0000000002"
recA := config.APITokenRecord{
ID: "tok-dup-r46",
Name: "agent-a",
Hash: internalauth.HashAPIToken(rawA),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentExec},
OrgIDs: []string{"default"},
Metadata: map[string]string{
"bound_hostname": "node-r46.local",
},
}
recB := config.APITokenRecord{
ID: "tok-dup-r46",
Name: "agent-b",
Hash: internalauth.HashAPIToken(rawB),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentExec},
OrgIDs: []string{"default"},
Metadata: map[string]string{
"bound_agent_id": "host-r46-1",
"bound_hostname": "node-r46.local",
"agent_exec_binding_version": "2",
},
}
// Step 1 (control): Start with a single-token fixture that demonstrably binds
// via report-driven identity recording when using its real authenticated identity.
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{recA.Clone()},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens(single): %v", err)
}
router := &Router{config: cfg, persistence: p}
expectedOwner := apiTokenAuthenticatedUser(&recA)
router.recordReportedAgentIdentityInInventory(cfg, p, "default", recA.ID, recA.Hash, expectedOwner, true, "host-r46-1", "host-r46-1", "node-r46.local")
config.Mu.RLock()
controlBound := cfg.APITokens[0].Metadata["bound_agent_id"]
config.Mu.RUnlock()
if controlBound != "host-r46-1" {
t.Fatalf("control fixture failed to bind single token: bound_agent_id=%q, want host-r46-1", controlBound)
}
// Step 2 (duplicate ID): Reset recA unbound and introduce recB sharing recA.ID.
// Report-driven binding MUST refuse to persist bound_agent_id.
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{recA.Clone(), recB.Clone()}
config.Mu.Unlock()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens(dup): %v", err)
}
router.recordReportedAgentIdentityInInventory(cfg, p, "default", recA.ID, recA.Hash, expectedOwner, true, "host-r46-1", "host-r46-1", "node-r46.local")
config.Mu.RLock()
boundAfterReport := cfg.APITokens[0].Metadata["bound_agent_id"]
config.Mu.RUnlock()
if boundAfterReport != "" {
t.Fatalf("expected report-driven binding to refuse duplicate token ID, got bound_agent_id=%q", boundAfterReport)
}
// Step 3: Already-bound WebSocket admission must ALSO refuse when another record shares the token ID.
if _, ok := router.admitAgentExecToken(rawB, "host-r46-1", "node-r46.local"); ok {
t.Fatal("expected already-bound WebSocket admission to fail closed when duplicate token ID exists")
}
}
// Round 46 High #2: In-flight self-uninstall must carry the admitted hash and
// fail closed with 403 if the token under the same ID was replaced before removal.
func TestRound46_SelfUninstallRefusesReplacedCredentialUnderSameTokenID(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
rawOld := "r46-uninstall-old-secret-0000001"
rawNew := "r46-uninstall-new-secret-0000002"
oldRec := config.APITokenRecord{
ID: "tok-self-uninstall-r46",
Name: "old-host-token",
Hash: internalauth.HashAPIToken(rawOld),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead},
OrgIDs: []string{"default"},
}
newRec := config.APITokenRecord{
ID: "tok-self-uninstall-r46",
Name: "replacement-host-token",
Hash: internalauth.HashAPIToken(rawNew),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead},
OrgIDs: []string{"default"},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{newRec},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
const hostID = "host-r46-uninstall"
if _, err := mon.ApplyHostReport(agentshost.Report{
Agent: agentshost.AgentInfo{ID: hostID, Version: "1.0.0"},
Host: agentshost.HostInfo{ID: hostID, MachineID: hostID, Hostname: "host-r46.local", Platform: "linux"},
Timestamp: time.Now().UTC(),
}, &oldRec); err != nil {
t.Fatalf("ApplyHostReport: %v", err)
}
h := NewUnifiedAgentHandlers(nil, mon, nil)
h.SetRootConfig(cfg)
req := httptest.NewRequest(http.MethodPost, "/api/agents/host/uninstall", strings.NewReader(`{"agentId":"`+hostID+`"}`))
req.Header.Set("Content-Type", "application/json")
attachAPITokenRecord(req, &oldRec)
rr := httptest.NewRecorder()
h.HandleUninstall(rr, req)
if rr.Code != http.StatusForbidden {
t.Fatalf("expected 403 Forbidden for in-flight uninstall after credential replacement, got %d (%s)", rr.Code, rr.Body.String())
}
// Verify BOTH the replacement token AND the host survived intact.
config.Mu.RLock()
tokCount := len(cfg.APITokens)
tokHash := ""
if tokCount == 1 {
tokHash = cfg.APITokens[0].Hash
}
config.Mu.RUnlock()
if tokCount != 1 || tokHash != newRec.Hash {
t.Fatalf("expected replacement token preserved, got count=%d hash=%q", tokCount, tokHash)
}
hosts := mon.GetLiveHostsSnapshot()
foundHost := false
for _, host := range hosts {
if host.ID == hostID {
foundHost = true
}
}
if !foundHost {
t.Fatal("expected host to survive refused stale self-uninstall")
}
}
type round46DenyingOrgChecker struct {
allow atomic.Bool
}
func (c *round46DenyingOrgChecker) TokenCanAccessOrg(_ *config.APITokenRecord, _ string) bool {
return c.allow.Load()
}
func (c *round46DenyingOrgChecker) UserCanAccessOrg(_, _ string) bool {
return c.allow.Load()
}
func (c *round46DenyingOrgChecker) CheckAccess(_ *config.APITokenRecord, _, _ string) AuthorizationResult {
if c.allow.Load() {
return AuthorizationResult{Allowed: true}
}
return AuthorizationResult{Allowed: false, Reason: "owner membership revoked"}
}
// Round 46 High #3: Agent config fetch must re-check live scopes before host
// selection and enforce the admitting organization policy before releasing config/probe secrets.
func TestRound46_AgentConfigRevalidatesLiveScopesAndOwnerMembership(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
rawMgr := "r46-mgr-scope-withdraw-00000001"
rawOwner := "r46-owner-member-revoke-0000002"
mgrRec := config.APITokenRecord{
ID: "tok-r46-mgr",
Name: "manager-tok",
Hash: internalauth.HashAPIToken(rawMgr),
Scopes: []string{config.ScopeAgentConfigRead, config.ScopeAgentManage},
OrgIDs: []string{"default"},
}
ownerRec := config.APITokenRecord{
ID: "tok-r46-owner",
Name: "owner-tok",
Hash: internalauth.HashAPIToken(rawOwner),
Scopes: []string{config.ScopeAgentConfigRead, config.ScopeAgentReport},
OrgIDs: []string{"default"},
}
setAPITokenOwnerUserID(&ownerRec, "alice")
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{mgrRec, ownerRec},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
const hostID = "host-r46-cfg-target"
if _, err := mon.ApplyHostReport(agentshost.Report{
Agent: agentshost.AgentInfo{ID: hostID, Version: "1.0.0"},
Host: agentshost.HostInfo{ID: hostID, MachineID: hostID, Hostname: "cfg-target.local", Platform: "linux"},
Timestamp: time.Now().UTC(),
}, &ownerRec); err != nil {
t.Fatalf("ApplyHostReport: %v", err)
}
h := NewUnifiedAgentHandlers(nil, mon, nil)
h.SetRootConfig(cfg)
// Part A: Stale admitted copy has ScopeAgentManage, but live inventory withdrew it.
// Must NOT be able to select another token's host by ID.
staleMgr := mgrRec.Clone()
config.Mu.Lock()
cfg.APITokens[0].Scopes = []string{config.ScopeAgentConfigRead}
config.Mu.Unlock()
reqA := httptest.NewRequest(http.MethodGet, "/api/agents/host/"+hostID+"/config", nil)
attachAPITokenRecord(reqA, &staleMgr)
rrA := httptest.NewRecorder()
h.handleGetConfig(rrA, reqA, hostID)
if rrA.Code != http.StatusNotFound && rrA.Code != http.StatusForbidden {
t.Fatalf("expected 404/403 after live agent:manage scope withdrawal, got %d (%s)", rrA.Code, rrA.Body.String())
}
// Part B: Owner-acting token admitted while owner belonged to org, then owner
// membership is revoked on the admitting AuthorizationChecker.
checker := &round46DenyingOrgChecker{}
checker.allow.Store(false)
reqB := httptest.NewRequest(http.MethodGet, "/api/agents/host/"+hostID+"/config", nil)
reqB = reqB.WithContext(context.WithValue(reqB.Context(), orgAccessCheckerContextKey{}, AuthorizationChecker(checker)))
attachAPITokenRecord(reqB, &ownerRec)
rrB := httptest.NewRecorder()
h.handleGetConfig(rrB, reqB, hostID)
if rrB.Code != http.StatusNotFound && rrB.Code != http.StatusForbidden {
t.Fatalf("expected 404/403 when admitting org policy denies owner membership, got %d (%s)", rrB.Code, rrB.Body.String())
}
}
// Round 46 High #4 (tenant deletion): revokeTenantCredentials must fail closed
// if removing a tenant's token would expose a surviving record with the same hash.
func TestRound46_RevokeTenantCredentialsRefusesShadowedHashSurvivor(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
sharedHash := internalauth.HashAPIToken("r46-shared-tenant-secret-000001")
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{
{
ID: "tok-tenant-a",
Name: "tenant-a-tok",
Hash: sharedHash,
Scopes: []string{config.ScopeMonitoringRead},
OrgIDs: []string{"org-delete-me"},
},
{
ID: "tok-shadowed-admin",
Name: "shadowed-other-org",
Hash: sharedHash,
Scopes: []string{config.ScopeWildcard},
OrgIDs: []string{"org-survivor"},
},
},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
err := router.revokeTenantCredentials("org-delete-me")
if err == nil {
t.Fatal("expected revokeTenantCredentials to refuse publication when survivor shares removed token hash")
}
config.Mu.RLock()
liveLen := len(cfg.APITokens)
config.Mu.RUnlock()
if liveLen != 2 {
t.Fatalf("expected inventory untouched on ambiguous hash refusal, got %d tokens", liveLen)
}
}
type round46LockAfterWriteRecorder struct {
*httptest.ResponseRecorder
onFirstWrite func()
fired atomic.Bool
}
func (r *round46LockAfterWriteRecorder) Write(p []byte) (int, error) {
n, err := r.ResponseRecorder.Write(p)
if r.fired.CompareAndSwap(false, true) && r.onFirstWrite != nil {
r.onFirstWrite()
}
return n, err
}
// Round 46 Medium #1: Production /api/agent/topology route must not stall on
// tokenResponseWriter.WriteHeader or completion check when config.Mu is locked
// immediately after body acceptance.
func TestRound46_ProductionTopologyRouteDoesNotStallWhenConfigMuLockedAfterBodyWrite(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("SaveSystemSettings: %v", err)
}
rawTok := "r46-prod-topology-route-tok-0001"
tokRec := config.APITokenRecord{
ID: "tok-r46-prod-topo",
Name: "cli-topo",
Hash: internalauth.HashAPIToken(rawTok),
Scopes: []string{config.ScopeMonitoringRead},
OrgIDs: []string{"default"},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{tokRec},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
router := newTestRouter(t, cfg, mon, nil, nil, nil, "test")
t.Cleanup(func() { router.WaitTopologyObservers() })
locked := make(chan struct{})
releaseLock := make(chan struct{})
lockDone := make(chan struct{})
rr := httptest.NewRecorder()
wrapped := &round46LockAfterWriteRecorder{
ResponseRecorder: rr,
onFirstWrite: func() {
go func() {
config.Mu.Lock()
close(locked)
<-releaseLock
config.Mu.Unlock()
close(lockDone)
}()
<-locked
},
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", rawTok)
req.Header.Set("X-Pulse-Client", "pulse-cli")
served := make(chan struct{})
go func() {
router.Handler().ServeHTTP(wrapped, req)
close(served)
}()
select {
case <-served:
case <-time.After(3 * time.Second):
close(releaseLock)
<-lockDone
t.Fatal("production /api/agent/topology route stalled while config.Mu was write-locked after response body write")
}
close(releaseLock)
<-lockDone
router.WaitTopologyObservers()
if rr.Code != http.StatusOK {
t.Fatalf("expected 200 OK from /api/agent/topology, got %d (%s)", rr.Code, rr.Body.String())
}
}
// Round 46 Medium #2: When config.Mu is contended across topology completion and
// the token is revoked before the deferred worker acquires the lock, the day
// must be marked degraded (available=false) rather than silently undercounting.
func TestRound46_DeferredTopologyTokenRevocationRecordsUncertaintyInsteadOfSilentUndercount(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("SaveSystemSettings: %v", err)
}
if err := p.EnsureInfrastructureMapTopologyTallyIfConsented(time.Now().UTC()); err != nil {
t.Fatalf("EnsureInfrastructureMapTopologyTallyIfConsented: %v", err)
}
rawTok := "r46-deferred-revoke-topo-tok-001"
tokRec := config.APITokenRecord{
ID: "tok-r46-deferred-revoke",
Name: "cli-topo",
Hash: internalauth.HashAPIToken(rawTok),
Scopes: []string{config.ScopeMonitoringRead},
OrgIDs: []string{"default"},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{tokRec},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
router := newTestRouter(t, cfg, mon, nil, nil, nil, "test")
t.Cleanup(func() { router.WaitTopologyObservers() })
router.WaitTopologyInit()
if _, availBefore, err := p.LoadInfrastructureMapTopologyTallySnapshotReadOnly(time.Now().UTC(), 7); err != nil || !availBefore {
t.Fatalf("expected tally available before deferred revocation test, got avail=%v err=%v", availBefore, err)
}
locked := make(chan struct{})
releaseLock := make(chan struct{})
lockDone := make(chan struct{})
rr := httptest.NewRecorder()
wrapped := &round46LockAfterWriteRecorder{
ResponseRecorder: rr,
onFirstWrite: func() {
go func() {
config.Mu.Lock()
close(locked)
<-releaseLock
// Revoke the token while config.Mu is still write-locked so the
// deferred worker sees !eligible after lock release.
cfg.APITokens = nil
config.Mu.Unlock()
close(lockDone)
}()
<-locked
},
}
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", rawTok)
req.Header.Set("X-Pulse-Client", "pulse-cli")
served := make(chan struct{})
go func() {
router.Handler().ServeHTTP(wrapped, req)
close(served)
}()
select {
case <-served:
case <-time.After(3 * time.Second):
close(releaseLock)
<-lockDone
t.Fatal("topology route stalled waiting on config.Mu")
}
close(releaseLock)
<-lockDone
router.WaitTopologyObservers()
router.persistence.WaitTopologyUncertaintyWrites()
p.WaitTopologyUncertaintyWrites()
_, available, snapErr := p.LoadInfrastructureMapTopologyTallySnapshotReadOnly(time.Now().UTC(), 7)
if snapErr != nil {
t.Fatalf("LoadInfrastructureMapTopologyTallySnapshotReadOnly: %v", snapErr)
}
if available || !p.TopologyTallyDegradedInWindow(time.Now().UTC(), 7) {
t.Fatalf("expected degraded uncertainty (available=false, degraded=true) when deferred completion token check sees post-lock revocation, got available=%v degraded=%v", available, p.TopologyTallyDegradedInWindow(time.Now().UTC(), 7))
}
}
// Round 46 Medium #6: updateAuthEnvFile rejects oversized .env files without
// unbounded memory reads.
func TestRound46_UpdateAuthEnvFileRejectsOversizedFile(t *testing.T) {
dir := t.TempDir()
envPath := filepath.Join(dir, ".env")
oversized := make([]byte, maxAuthEnvFileSizeBytes+64)
for i := range oversized {
oversized[i] = 'A'
}
if err := os.WriteFile(envPath, oversized, 0600); err != nil {
t.Fatalf("WriteFile oversized .env: %v", err)
}
_, err := updateAuthEnvFile(dir, dir, func(existing []byte, exists bool) ([]byte, error) {
return existing, nil
})
if !errors.Is(err, config.ErrFileTooLarge) {
t.Fatalf("expected ErrFileTooLarge on oversized .env, got %v", err)
}
}
// Round 46 Low #1 & #2: handleUpdateAPIToken checks caller visibility BEFORE
// returning 409 on duplicate ID/hash, and emits semicolon-free audit messages.
func TestRound46_UpdateAPITokenChecksCallerVisibilityBeforeAmbiguityConflictAndHasNoSemicolons(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
rawCaller := "r46-scoped-caller-org-a-00000001"
rawAdmin := "r46-instance-admin-token-0000002"
callerTok := config.APITokenRecord{
ID: "tok-caller-org-a",
Name: "org-a-caller",
Hash: internalauth.HashAPIToken(rawCaller),
Scopes: []string{config.ScopeWildcard},
OrgIDs: []string{"org-a"},
}
adminTok := config.APITokenRecord{
ID: "tok-instance-admin",
Name: "admin",
Hash: internalauth.HashAPIToken(rawAdmin),
Scopes: []string{config.ScopeWildcard},
}
dupTarget1 := config.APITokenRecord{
ID: "tok-dup-org-b",
Name: "org-b-1",
Hash: internalauth.HashAPIToken("r46-dup-target-1-000000000000001"),
Scopes: []string{config.ScopeMonitoringRead},
OrgIDs: []string{"org-b"},
}
dupTarget2 := config.APITokenRecord{
ID: "tok-dup-org-b",
Name: "org-b-2",
Hash: internalauth.HashAPIToken("r46-dup-target-2-000000000000002"),
Scopes: []string{config.ScopeMonitoringRead},
OrgIDs: []string{"org-b"},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{callerTok, adminTok, dupTarget1, dupTarget2},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
// Scoped org-a caller must get 404 (not 409) when probing org-b's duplicate ID.
reqScoped := httptest.NewRequest(http.MethodPatch, "/api/security/tokens/tok-dup-org-b", strings.NewReader(`{"name":"renamed"}`))
reqScoped = reqScoped.WithContext(context.WithValue(reqScoped.Context(), apicontext.OrgIDContextKey, "org-a"))
reqScoped.Header.Set("Content-Type", "application/json")
attachAPITokenRecord(reqScoped, &callerTok)
rrScoped := httptest.NewRecorder()
router.handleUpdateAPIToken(rrScoped, reqScoped)
if rrScoped.Code != http.StatusNotFound {
t.Fatalf("expected 404 for scoped caller updating inaccessible duplicate-ID token, got %d (%s)", rrScoped.Code, rrScoped.Body.String())
}
// Authorized instance admin gets 409 Conflict.
reqAdmin := httptest.NewRequest(http.MethodPatch, "/api/security/tokens/tok-dup-org-b", strings.NewReader(`{"name":"renamed"}`))
reqAdmin.Header.Set("Content-Type", "application/json")
attachAPITokenRecord(reqAdmin, &adminTok)
rrAdmin := httptest.NewRecorder()
router.handleUpdateAPIToken(rrAdmin, reqAdmin)
if rrAdmin.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict for admin updating ambiguous duplicate-ID token, got %d (%s)", rrAdmin.Code, rrAdmin.Body.String())
}
}
// Round 47 High #1: An imported replacement credential under the same token ID
// cannot inherit another agent's config or unredacted HTTP probe secrets before
// the host has reported under the replacement credential.
func TestRound47_ReplacementCredentialUnderSameIDCannotInheritProbeSecrets(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
rawA := "r47-h1-original-agent-token-0001"
rawB := "r47-h1-imported-replacement-0002"
tokA := config.APITokenRecord{
ID: "tok-r47-h1",
Name: "agent-a",
Hash: internalauth.HashAPIToken(rawA),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead},
OrgIDs: []string{"default"},
}
tokB := config.APITokenRecord{
ID: "tok-r47-h1",
Name: "imported-replacement-b",
Hash: internalauth.HashAPIToken(rawB),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentManage},
OrgIDs: []string{"default"},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{tokA},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens(A): %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
const hostID = "host-r47-h1"
host, err := mon.ApplyHostReport(agentshost.Report{
Agent: agentshost.AgentInfo{ID: hostID, Version: "1.0.0"},
Host: agentshost.HostInfo{ID: hostID, MachineID: hostID, Hostname: "h1.local", Platform: "linux"},
Timestamp: time.Now().UTC(),
}, &tokA)
if err != nil {
t.Fatalf("ApplyHostReport(A): %v", err)
}
if host.TokenHash != tokA.Hash {
t.Fatalf("expected host.TokenHash=%q after report under A, got %q", tokA.Hash, host.TokenHash)
}
// Simulate import replacing tokA with tokB under the same ID before host reports under B.
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{tokB}
config.Mu.Unlock()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens(B): %v", err)
}
// Case 1: Without manage scope, tokB must not resolve host at all.
tokBNoManage := tokB.Clone()
tokBNoManage.Scopes = []string{config.ScopeAgentReport, config.ScopeAgentConfigRead}
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{tokBNoManage}
config.Mu.Unlock()
h := NewUnifiedAgentHandlers(nil, mon, nil)
h.SetRootConfig(cfg)
reqNoManage := httptest.NewRequest(http.MethodGet, "/api/agents/host/"+hostID+"/config", nil)
attachAPITokenRecord(reqNoManage, &tokBNoManage)
rrNoManage := httptest.NewRecorder()
h.handleGetConfig(rrNoManage, reqNoManage, hostID)
if rrNoManage.Code != http.StatusNotFound && rrNoManage.Code != http.StatusForbidden {
t.Fatalf("expected 404/403 for replacement credential without manage scope before host reports under B, got %d (%s)", rrNoManage.Code, rrNoManage.Body.String())
}
// Case 2: Even with ScopeAgentManage, withholdProbeSecretsFromOtherTokens MUST redact HTTP secrets for tokB!
secretBody := "secret-request-body"
secretHdr := "Bearer super-secret-value"
probeCfg := monitoring.HostAgentConfig{
Settings: map[string]interface{}{
"availabilityTargets": []map[string]interface{}{
{
"id": "probe-1",
"http": &config.AvailabilityHTTPConfig{
Headers: []config.AvailabilityHTTPHeader{{Name: "Authorization", Value: &secretHdr}},
Body: &secretBody,
},
},
},
},
}
redactedForB := withholdProbeSecretsFromOtherTokens(probeCfg, &tokB, host, true)
targetsB := redactedForB.Settings["availabilityTargets"].([]map[string]interface{})
httpB := targetsB[0]["http"].(*config.AvailabilityHTTPConfig)
if (httpB.Body != nil && *httpB.Body != "") || (len(httpB.Headers) > 0 && httpB.Headers[0].Value != nil && *httpB.Headers[0].Value != "") {
t.Fatalf("replacement credential B inherited unredacted probe secrets: %+v", httpB)
}
// Control: original credential A still receives its own probe secrets.
unredactedForA := withholdProbeSecretsFromOtherTokens(probeCfg, &tokA, host, true)
targetsA := unredactedForA.Settings["availabilityTargets"].([]map[string]interface{})
httpA := targetsA[0]["http"].(*config.AvailabilityHTTPConfig)
if httpA.Body == nil || *httpA.Body != "secret-request-body" || len(httpA.Headers) != 1 || httpA.Headers[0].Value == nil || *httpA.Headers[0].Value != "Bearer super-secret-value" {
t.Fatalf("control credential A lost its own probe secrets: %+v", httpA)
}
}
// Round 47 High #2: Conflicting durable ownership must be rejected at BOTH
// WebSocket admission (even when live host.TokenID matches caller) AND dispatch.
func TestRound47_ConflictingDurableOwnershipRejectedAtAdmissionAndDispatch(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
rawA := "r47-h2-token-a-secret-0000000001"
rawB := "r47-h2-token-b-secret-0000000002"
const hostID = "host-r47-h2"
tokA := config.APITokenRecord{
ID: "tok-r47-h2-a",
Name: "agent-a",
Hash: internalauth.HashAPIToken(rawA),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentExec},
OrgIDs: []string{"default"},
Metadata: map[string]string{
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindLegacyFullTrust,
"bound_agent_id": hostID,
"bound_hostname": "h2.local",
"agent_exec_binding_version": "2",
},
}
tokB := config.APITokenRecord{
ID: "tok-r47-h2-b",
Name: "agent-b-conflict",
Hash: internalauth.HashAPIToken(rawB),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentExec},
OrgIDs: []string{"default"},
Metadata: map[string]string{
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindLegacyFullTrust,
"bound_agent_id": hostID,
"bound_hostname": "h2.local",
"agent_exec_binding_version": "2",
},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{tokA},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
// Seed live host matching tokA.ID so the live-host branch in agentExecIdentityHeldByAnotherToken executes.
if _, err := mon.ApplyHostReport(agentshost.Report{
Agent: agentshost.AgentInfo{ID: hostID, Version: "1.0.0"},
Host: agentshost.HostInfo{ID: hostID, MachineID: hostID, Hostname: "h2.local", Platform: "linux"},
Timestamp: time.Now().UTC(),
}, &tokA); err != nil {
t.Fatalf("ApplyHostReport: %v", err)
}
router := &Router{config: cfg, persistence: p, monitor: mon}
// Control: single owner admits and passes dispatch revalidation.
adm, ok := router.admitAgentExecToken(rawA, hostID, "h2.local")
if !ok {
t.Fatal("expected single owner tokA to admit")
}
if !router.validateAgentExecSession(adm) {
t.Fatal("expected single owner tokA to pass dispatch revalidation")
}
// Now introduce conflicting durable owner tokB (different ID, same bound_agent_id).
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{tokA, tokB}
config.Mu.Unlock()
// Admission must NOT return early on live host.TokenID == tokA.ID; it must see tokB and refuse!
if _, ok := router.admitAgentExecToken(rawA, hostID, "h2.local"); ok {
t.Fatal("expected admission to reject tokA when conflicting durable owner tokB exists")
}
// Already-admitted socket dispatch revalidation must ALSO fail closed!
if router.validateAgentExecSession(adm) {
t.Fatal("expected dispatch revalidation to fail closed when conflicting durable owner tokB exists")
}
}
// Round 47 High #3 & #4: Self-uninstall must fail closed on withdrawn agent:report
// scope or replaced credential BEFORE writing any removal tombstone to host_continuity.json.
func TestRound47_SelfUninstallRejectsWithdrawnScopeAndWritesZeroTombstone(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
rawTok := "r47-h3-h4-self-uninstall-tok-001"
tok := config.APITokenRecord{
ID: "tok-r47-h3",
Name: "collector",
Hash: internalauth.HashAPIToken(rawTok),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead},
OrgIDs: []string{"default"},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{tok},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
const hostID = "host-r47-h3"
if _, err := mon.ApplyHostReport(agentshost.Report{
Agent: agentshost.AgentInfo{ID: hostID, Version: "1.0.0"},
Host: agentshost.HostInfo{ID: hostID, MachineID: hostID, Hostname: "h3.local", Platform: "linux"},
Timestamp: time.Now().UTC(),
}, &tok); err != nil {
t.Fatalf("ApplyHostReport: %v", err)
}
// Withdraw ScopeAgentReport while keeping token ID and hash identical.
withdrawn := tok.Clone()
withdrawn.Scopes = []string{config.ScopeAgentConfigRead}
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{withdrawn}
config.Mu.Unlock()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens(withdrawn): %v", err)
}
h := NewUnifiedAgentHandlers(nil, mon, nil)
h.SetRootConfig(cfg)
req := httptest.NewRequest(http.MethodPost, "/api/agents/host/uninstall", strings.NewReader(`{"agentId":"`+hostID+`"}`))
req.Header.Set("Content-Type", "application/json")
attachAPITokenRecord(req, &tok)
rr := httptest.NewRecorder()
h.HandleUninstall(rr, req)
if rr.Code != http.StatusForbidden {
t.Fatalf("expected 403 Forbidden after agent:report scope withdrawal, got %d (%s)", rr.Code, rr.Body.String())
}
// Verify ZERO removal tombstone exists on disk (even after restarting a fresh Monitor).
monRestart, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New(restart): %v", err)
}
t.Cleanup(func() { monRestart.Stop() })
// Re-grant scope and confirm the replacement/surviving host is NOT blocked by any tombstone!
config.Mu.Lock()
cfg.APITokens = []config.APITokenRecord{tok}
config.Mu.Unlock()
if _, err := monRestart.ApplyHostReport(agentshost.Report{
Agent: agentshost.AgentInfo{ID: hostID, Version: "1.0.0"},
Host: agentshost.HostInfo{ID: hostID, MachineID: hostID, Hostname: "h3.local", Platform: "linux"},
Timestamp: time.Now().UTC().Add(time.Second),
}, &tok); err != nil {
t.Fatalf("expected host NOT blocked by orphan tombstone after refused uninstall, got: %v", err)
}
}
// Round 47 Medium #2: tryTenantTokenConfigForRequest uses the live tryResolveManager
// hook and returns contended=true without blocking when either resolver or monitor is contended.
func TestRound47_TryTenantTokenConfigUsesLiveResolverAndDefersOnContention(t *testing.T) {
reqContendedResolver := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
reqContendedResolver = reqContendedResolver.WithContext(context.WithValue(reqContendedResolver.Context(), apicontext.OrgIDContextKey, "org-m2"))
reqContendedResolver = reqContendedResolver.WithContext(context.WithValue(reqContendedResolver.Context(), tenantTokenSourceContextKey, tenantTokenSource{
orgID: "org-m2",
tryResolveManager: func() (*monitoring.MultiTenantMonitor, bool) {
return nil, true
},
}))
cfg, contended := tryTenantTokenConfigForRequest(reqContendedResolver)
if cfg != nil || !contended {
t.Fatalf("expected (nil, true) when tryResolveManager is contended, got (%v, %v)", cfg, contended)
}
// If only a blocking resolveManager is present (no tryResolveManager), must defer (contended=true) rather than block.
reqBlockingResolver := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
reqBlockingResolver = reqBlockingResolver.WithContext(context.WithValue(reqBlockingResolver.Context(), apicontext.OrgIDContextKey, "org-m2"))
reqBlockingResolver = reqBlockingResolver.WithContext(context.WithValue(reqBlockingResolver.Context(), tenantTokenSourceContextKey, tenantTokenSource{
orgID: "org-m2",
resolveManager: func() *monitoring.MultiTenantMonitor {
t.Fatal("tryTenantTokenConfigForRequest must not invoke blocking resolveManager")
return nil
},
}))
cfg2, contended2 := tryTenantTokenConfigForRequest(reqBlockingResolver)
if cfg2 != nil || !contended2 {
t.Fatalf("expected (nil, true) when only blocking resolveManager is set, got (%v, %v)", cfg2, contended2)
}
}
// Round 47 Medium #3: Post-completion async owner membership revocation must
// mark the day degraded instead of silently undercounting a completed topology read.
func TestRound47_PostCompletionOwnerRevocationMarksTopologyDegraded(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("SaveSystemSettings: %v", err)
}
if err := p.EnsureInfrastructureMapTopologyTallyIfConsented(time.Now().UTC()); err != nil {
t.Fatalf("EnsureInfrastructureMapTopologyTallyIfConsented: %v", err)
}
rawTok := "r47-m3-owner-revoke-topo-tok-001"
tokRec := config.APITokenRecord{
ID: "tok-r47-m3-owner",
Name: "owner-cli-topo",
Hash: internalauth.HashAPIToken(rawTok),
Scopes: []string{config.ScopeMonitoringRead},
OrgIDs: []string{"default"},
}
setAPITokenOwnerUserID(&tokRec, "alice")
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
TelemetryEnabled: true,
APITokens: []config.APITokenRecord{tokRec},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
router := newTestRouter(t, cfg, mon, nil, nil, nil, "test")
t.Cleanup(func() { router.WaitTopologyObservers() })
router.WaitTopologyInit()
// Override async owner membership checker on agentContextHandler to simulate
// an owner-acting tenant token whose owner membership is revoked after body completion.
router.agentContextHandler.SetTopologyCompletionTokenFastChecker(
func(req *http.Request, completedAt time.Time) topologyCompletionTokenCheckResult {
res := router.topologyCompletionTokenFastCheck(req, completedAt)
res.needsOrgMembershipCheck = true
return res
},
router.checkTopologyCompletionTokenBounded,
func(_ context.Context, _ *config.APITokenRecord, _ string) (bool, bool, bool) {
return false, false, false
},
)
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", rawTok)
req.Header.Set("X-Pulse-Client", "pulse-cli")
rr := httptest.NewRecorder()
router.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("expected 200 OK, got %d (%s)", rr.Code, rr.Body.String())
}
router.WaitTopologyObservers()
router.persistence.WaitTopologyUncertaintyWrites()
_, available, snapErr := p.LoadInfrastructureMapTopologyTallySnapshotReadOnly(time.Now().UTC(), 7)
if snapErr != nil {
t.Fatalf("LoadInfrastructureMapTopologyTallySnapshotReadOnly: %v", snapErr)
}
if available || !p.TopologyTallyDegradedInWindow(time.Now().UTC(), 7) {
t.Fatalf("expected degraded uncertainty on post-completion owner revocation, got available=%v degraded=%v", available, p.TopologyTallyDegradedInWindow(time.Now().UTC(), 7))
}
}
// Round 47 Low #1: handleDeleteAPIToken must check caller visibility BEFORE
// returning 409 Conflict on duplicate token ID/hash.
func TestRound47_DeleteAPITokenChecksCallerVisibilityBeforeAmbiguityConflict(t *testing.T) {
dir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", dir)
p := config.NewConfigPersistence(dir)
rawCaller := "r47-l1-scoped-caller-org-a-00001"
rawAdmin := "r47-l1-instance-admin-tok-000002"
callerTok := config.APITokenRecord{
ID: "tok-r47-l1-caller",
Name: "org-a-admin",
Hash: internalauth.HashAPIToken(rawCaller),
Scopes: []string{config.ScopeWildcard},
OrgIDs: []string{"org-a"},
}
adminTok := config.APITokenRecord{
ID: "tok-r47-l1-admin",
Name: "instance-admin",
Hash: internalauth.HashAPIToken(rawAdmin),
Scopes: []string{config.ScopeWildcard},
}
dupB1 := config.APITokenRecord{
ID: "tok-r47-l1-dup-b",
Name: "org-b-1",
Hash: internalauth.HashAPIToken("r47-l1-dup-b-1-00000000000000001"),
Scopes: []string{config.ScopeMonitoringRead},
OrgIDs: []string{"org-b"},
}
dupB2 := config.APITokenRecord{
ID: "tok-r47-l1-dup-b",
Name: "org-b-2",
Hash: internalauth.HashAPIToken("r47-l1-dup-b-2-00000000000000002"),
Scopes: []string{config.ScopeMonitoringRead},
OrgIDs: []string{"org-b"},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{callerTok, adminTok, dupB1, dupB2},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
router := &Router{config: cfg, persistence: p}
// Scoped org-a admin probing org-b's duplicate ID must get 404 (not 409).
reqScoped := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/tok-r47-l1-dup-b", nil)
reqScoped = reqScoped.WithContext(context.WithValue(reqScoped.Context(), apicontext.OrgIDContextKey, "org-a"))
attachAPITokenRecord(reqScoped, &callerTok)
rrScoped := httptest.NewRecorder()
router.handleDeleteAPIToken(rrScoped, reqScoped)
if rrScoped.Code != http.StatusNotFound {
t.Fatalf("expected 404 for scoped caller deleting inaccessible duplicate-ID token, got %d (%s)", rrScoped.Code, rrScoped.Body.String())
}
// Instance admin deleting the same ambiguous duplicate ID gets 409 Conflict.
reqAdmin := httptest.NewRequest(http.MethodDelete, "/api/security/tokens/tok-r47-l1-dup-b", nil)
attachAPITokenRecord(reqAdmin, &adminTok)
rrAdmin := httptest.NewRecorder()
router.handleDeleteAPIToken(rrAdmin, reqAdmin)
if rrAdmin.Code != http.StatusConflict {
t.Fatalf("expected 409 Conflict for instance admin deleting ambiguous duplicate-ID token, got %d (%s)", rrAdmin.Code, rrAdmin.Body.String())
}
}
func TestRound48_H1_LegacyEmptyTokenHashCannotReceiveProbeSecretsOrSelfUninstall(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
rawToken := "r48-h1-legacy-token-00000000000000000001"
tok := config.APITokenRecord{
ID: "tok-r48-h1",
Name: "legacy-host",
Hash: internalauth.HashAPIToken(rawToken),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{tok},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
// Legacy host continuity record with matching TokenID but empty TokenHash (pre-v26).
legacyHost := models.Host{
ID: "host-r48-h1",
Hostname: "host-r48-h1",
TokenID: tok.ID,
}
desired := monitoring.HostAgentConfig{
Settings: map[string]any{
"availabilityTargets": []any{
map[string]any{
"id": "probe-1",
"name": "Internal API",
"url": "https://internal.local/health",
"headers": map[string]any{
"Authorization": "Bearer super-secret-value",
},
},
},
},
}
sanitized := withholdProbeSecretsFromOtherTokens(desired, &tok, legacyHost, true)
rawBytes, err := json.Marshal(sanitized)
if err != nil {
t.Fatalf("marshal sanitized config: %v", err)
}
if strings.Contains(string(rawBytes), "super-secret-value") {
t.Fatalf("expected probe secret redacted for legacy host with empty TokenHash, got %s", string(rawBytes))
}
// Seed pre-v26 continuity entry (TokenID set, TokenHash empty) before creating Monitor.
contStore := config.NewHostContinuityStore(dir, nil)
if err := contStore.Upsert(config.HostContinuityEntry{
HostID: "host-r48-h1",
Hostname: "host-r48-h1",
TokenID: tok.ID,
LastSeen: time.Now().UTC(),
}); err != nil {
t.Fatalf("seed legacy continuity: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
handlers := NewUnifiedAgentHandlers(nil, mon, nil)
req := httptest.NewRequest(http.MethodPost, "/api/agents/host/uninstall", strings.NewReader(`{"agentId":"host-r48-h1"}`))
attachAPITokenRecord(req, &tok)
rr := httptest.NewRecorder()
handlers.HandleUninstall(rr, req)
if rr.Code != http.StatusForbidden {
t.Fatalf("expected 403 for strict uninstall against empty TokenHash host, got %d (%s)", rr.Code, rr.Body.String())
}
if len(cfg.APITokens) != 1 {
t.Fatalf("expected token preserved after refused uninstall, got %d tokens", len(cfg.APITokens))
}
}
func TestRound48_H2_HostConfigOwnershipBoundToCurrentSnapshot(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
tokA := config.APITokenRecord{
ID: "tok-r48-h2",
Name: "old-owner",
Hash: internalauth.HashAPIToken("r48-h2-old-owner-0000000000000000000001"),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead},
}
tokB := config.APITokenRecord{
ID: "tok-r48-h2",
Name: "new-owner",
Hash: internalauth.HashAPIToken("r48-h2-new-owner-0000000000000000000002"),
Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{tokB},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
host, err := mon.ApplyHostReport(agentshost.Report{
Agent: agentshost.AgentInfo{ID: "host-r48-h2", Version: "1.0.0"},
Host: agentshost.HostInfo{ID: "host-r48-h2", Hostname: "host-r48-h2"},
}, &tokB)
if err != nil {
t.Fatalf("ApplyHostReport: %v", err)
}
_, currentHost, ok := mon.GetHostAgentConfigWithOwner(host.ID)
if !ok {
t.Fatal("expected GetHostAgentConfigWithOwner to succeed for stable owner")
}
if currentHost.TokenHash != tokB.Hash {
t.Fatalf("expected currentHost TokenHash=%s, got %s", tokB.Hash, currentHost.TokenHash)
}
if hostOwnedByTokenPositive(currentHost, &tokA) {
t.Fatal("former owner tokA must not satisfy hostOwnedByTokenPositive for currentHost owned by tokB")
}
if !hostOwnedByTokenPositive(currentHost, &tokB) {
t.Fatal("current owner tokB must satisfy hostOwnedByTokenPositive")
}
}
type round48PolicyChecker struct {
allow func(tok *config.APITokenRecord, orgID string) bool
}
func (c round48PolicyChecker) TokenCanAccessOrg(tok *config.APITokenRecord, orgID string) bool {
return c.allow != nil && c.allow(tok, orgID)
}
func (c round48PolicyChecker) UserCanAccessOrg(_, _ string) bool {
return false
}
func (c round48PolicyChecker) CheckAccess(tok *config.APITokenRecord, _ string, orgID string) AuthorizationResult {
if c.allow != nil && c.allow(tok, orgID) {
return AuthorizationResult{Allowed: true}
}
return AuthorizationResult{Allowed: false}
}
func TestRound48_H3_UninstallRejectsLiveOwnerMutationOrRevokedOrgMembership(t *testing.T) {
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
rawToken := "r48-h3-owner-token-000000000000000000001"
tokHash := internalauth.HashAPIToken(rawToken)
admittedTok := config.APITokenRecord{
ID: "tok-r48-h3",
Name: "owner-agent",
Hash: tokHash,
Scopes: []string{config.ScopeAgentReport},
Metadata: map[string]string{
agenttokens.OwnerUserIDMetadataKey: "alice",
},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{admittedTok.Clone()},
}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
host, err := mon.ApplyHostReport(agentshost.Report{
Agent: agentshost.AgentInfo{ID: "host-r48-h3", Version: "1.0.0"},
Host: agentshost.HostInfo{ID: "host-r48-h3", Hostname: "host-r48-h3"},
}, &admittedTok)
if err != nil {
t.Fatalf("ApplyHostReport: %v", err)
}
handlers := NewUnifiedAgentHandlers(nil, mon, nil)
// Case A: Owner membership revoked on org before uninstall executes.
deniedChecker := round48PolicyChecker{
allow: func(tok *config.APITokenRecord, _ string) bool { return false },
}
reqA := httptest.NewRequest(http.MethodPost, "/api/agents/host/uninstall", strings.NewReader(fmt.Sprintf(`{"agentId":%q}`, host.ID)))
reqA = reqA.WithContext(context.WithValue(reqA.Context(), orgAccessCheckerContextKey{}, AuthorizationChecker(deniedChecker)))
attachAPITokenRecord(reqA, &admittedTok)
rrA := httptest.NewRecorder()
handlers.HandleUninstall(rrA, reqA)
if rrA.Code != http.StatusForbidden {
t.Fatalf("Case A: expected 403 when live org policy denies owner token, got %d (%s)", rrA.Code, rrA.Body.String())
}
if len(cfg.APITokens) != 1 || len(mon.GetState().Hosts) != 1 {
t.Fatalf("Case A: host and token must remain intact after denied uninstall")
}
// Case B: Live inventory mutates owner_user_id on same ID+hash after admission.
config.Mu.Lock()
cfg.APITokens[0].Metadata[agenttokens.OwnerUserIDMetadataKey] = "bob"
config.AdvanceAPITokensGeneration()
config.Mu.Unlock()
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("SaveAPITokens mutated owner: %v", err)
}
allowAlice := round48PolicyChecker{
allow: func(tok *config.APITokenRecord, _ string) bool {
return tok != nil && tok.Metadata[agenttokens.OwnerUserIDMetadataKey] == "alice"
},
}
reqB := httptest.NewRequest(http.MethodPost, "/api/agents/host/uninstall", strings.NewReader(fmt.Sprintf(`{"agentId":%q}`, host.ID)))
reqB = reqB.WithContext(context.WithValue(reqB.Context(), orgAccessCheckerContextKey{}, AuthorizationChecker(allowAlice)))
attachAPITokenRecord(reqB, &admittedTok)
rrB := httptest.NewRecorder()
handlers.HandleUninstall(rrB, reqB)
if rrB.Code != http.StatusForbidden {
t.Fatalf("Case B: expected 403 when live token owner_user_id changed, got %d (%s)", rrB.Code, rrB.Body.String())
}
if len(cfg.APITokens) != 1 || len(mon.GetState().Hosts) != 1 {
t.Fatalf("Case B: host and token must remain intact after owner mismatch")
}
}
func TestRound48_M2_M3_ActiveRunnerAdmissionConflictAndPendingRunnerKeepsLegacyValid(t *testing.T) {
dir := t.TempDir()
runner1Raw := "r48-m2-runner-1-000000000000000000000001"
runner2Raw := "r48-m2-runner-2-000000000000000000000002"
legacyRaw := "r48-m3-legacy-00000000000000000000000003"
pendingRaw := "r48-m3-pending-0000000000000000000000004"
runner1 := config.APITokenRecord{
ID: "tok-r48-runner-1",
Name: "runner-1",
Hash: internalauth.HashAPIToken(runner1Raw),
Scopes: []string{config.ScopeAgentExec},
OrgIDs: []string{"default"},
Metadata: map[string]string{
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindActionRunner,
agenttokens.ActionCapabilityMetadataKey: agenttokens.ActionCapabilityTypedV1,
"bound_agent_id": "agent-r48-m2",
"bound_hostname": "host-m2",
},
}
runner2 := config.APITokenRecord{
ID: "tok-r48-runner-2",
Name: "runner-2",
Hash: internalauth.HashAPIToken(runner2Raw),
Scopes: []string{config.ScopeAgentExec},
OrgIDs: []string{"default"},
Metadata: map[string]string{
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindActionRunner,
agenttokens.ActionCapabilityMetadataKey: agenttokens.ActionCapabilityTypedV1,
"bound_agent_id": "agent-r48-m2",
"bound_hostname": "host-m2",
},
}
legacyTok := config.APITokenRecord{
ID: "tok-r48-legacy",
Name: "legacy",
Hash: internalauth.HashAPIToken(legacyRaw),
Scopes: []string{config.ScopeAgentExec},
OrgIDs: []string{"default"},
Metadata: map[string]string{
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindLegacyFullTrust,
"bound_agent_id": "agent-r48-m3",
"bound_hostname": "host-m3",
},
}
pendingRunner := config.APITokenRecord{
ID: "tok-r48-pending",
Name: "pending-runner",
Hash: internalauth.HashAPIToken(pendingRaw),
Scopes: []string{config.ScopeAgentExec},
OrgIDs: []string{"default"},
Metadata: map[string]string{
agenttokens.RuntimeRoleMetadataKey: agenttokens.CredentialKindActionRunner,
agenttokens.ActionRunnerActivationPendingMetadataKey: "true",
agenttokens.ActionCapabilityMetadataKey: agenttokens.ActionCapabilityTypedV1,
"bound_agent_id": "agent-r48-m3",
"bound_hostname": "host-m3",
},
}
cfg := &config.Config{
DataPath: dir,
ConfigPath: dir,
APITokens: []config.APITokenRecord{runner1, runner2, legacyTok, pendingRunner},
}
router := &Router{config: cfg}
// Medium #2: Second active typed action runner must be refused at WebSocket admission.
if _, ok := router.admitAgentExecToken(runner2Raw, "agent-r48-m2", "host-m2"); ok {
t.Fatal("expected second active typed action runner to be refused at admission")
}
// Medium #3: Pending typed action runner must NOT evict an active legacy session.
session := agentexec.AgentAdmission{
AgentID: "agent-r48-m3",
Hostname: "host-m3",
OrganizationID: "default",
RuntimeRole: agentexec.RuntimeRoleLegacyFullTrust,
TokenID: legacyTok.ID,
TokenHash: legacyTok.Hash,
}
if !router.validateAgentExecSession(session) {
t.Fatal("expected active legacy session to stay valid while typed action runner is activation_pending=true")
}
}
func TestRound48_M8_DeferredTopologyChecksDetectTokenAndOrgGenerationDrift(t *testing.T) {
// Case A: APITokensGeneration advances while deferred token lookup runs -> degraded!
{
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("Case A SaveSystemSettings: %v", err)
}
tok := config.APITokenRecord{
ID: "tok-r48-m8-a",
Name: "m8-a",
Hash: internalauth.HashAPIToken("r48-m8-a-000000000000000000000000000001"),
Scopes: []string{config.ScopeMonitoringRead},
}
cfg := &config.Config{DataPath: dir, ConfigPath: dir, TelemetryEnabled: true, APITokens: []config.APITokenRecord{tok}}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("Case A SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("Case A monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
router := newTestRouter(t, cfg, mon, nil, nil, nil, "test")
t.Cleanup(func() { router.WaitTopologyObservers() })
router.WaitTopologyInit()
var recorded, degraded atomic.Int32
done := make(chan struct{})
router.agentContextHandler.SetTopologyReadObserver(func(*http.Request, time.Time, bool, bool, bool) {
recorded.Add(1)
})
router.agentContextHandler.SetTopologyDegradedNotifier(func(time.Time, uint64) {
if degraded.Add(1) == 1 {
close(done)
}
})
router.agentContextHandler.SetTopologyCompletionTokenFastChecker(
func(req *http.Request, _ time.Time) topologyCompletionTokenCheckResult {
return topologyCompletionTokenCheckResult{lockContended: true, deferredReq: req}
},
func(context.Context, *http.Request, time.Time) (topologyCompletionTokenCheckResult, bool) {
config.AdvanceAPITokensGeneration()
return topologyCompletionTokenCheckResult{eligible: true}, false
},
nil,
)
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", "r48-m8-a-000000000000000000000000000001")
rr := httptest.NewRecorder()
router.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("Case A status: %d (%s)", rr.Code, rr.Body.String())
}
router.WaitTopologyObservers()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("Case A: expected degraded notification when APITokensGeneration advanced across deferred check")
}
if recorded.Load() != 0 || degraded.Load() != 1 {
t.Fatalf("Case A: expected recorded=0 degraded=1, got recorded=%d degraded=%d", recorded.Load(), degraded.Load())
}
}
// Case B: OrgMembershipGeneration advances while async org check runs -> degraded!
{
dir := t.TempDir()
p := config.NewConfigPersistence(dir)
enabled := true
if err := p.SaveSystemSettings(config.SystemSettings{TelemetryEnabled: &enabled}); err != nil {
t.Fatalf("Case B SaveSystemSettings: %v", err)
}
tok := config.APITokenRecord{
ID: "tok-r48-m8-b",
Name: "m8-b",
Hash: internalauth.HashAPIToken("r48-m8-b-000000000000000000000000000002"),
Scopes: []string{config.ScopeMonitoringRead},
}
cfg := &config.Config{DataPath: dir, ConfigPath: dir, TelemetryEnabled: true, APITokens: []config.APITokenRecord{tok}}
if err := p.SaveAPITokens(cfg.APITokens); err != nil {
t.Fatalf("Case B SaveAPITokens: %v", err)
}
mon, err := monitoring.New(cfg)
if err != nil {
t.Fatalf("Case B monitoring.New: %v", err)
}
t.Cleanup(func() { mon.Stop() })
router := newTestRouter(t, cfg, mon, nil, nil, nil, "test")
t.Cleanup(func() { router.WaitTopologyObservers() })
router.WaitTopologyInit()
var recorded, degraded atomic.Int32
done := make(chan struct{})
router.agentContextHandler.SetTopologyReadObserver(func(*http.Request, time.Time, bool, bool, bool) {
recorded.Add(1)
})
router.agentContextHandler.SetTopologyDegradedNotifier(func(time.Time, uint64) {
if degraded.Add(1) == 1 {
close(done)
}
})
router.agentContextHandler.SetTopologyCompletionTokenFastChecker(
func(*http.Request, time.Time) topologyCompletionTokenCheckResult {
return topologyCompletionTokenCheckResult{eligible: true, needsOrgMembershipCheck: true, orgID: "org-a"}
},
router.checkTopologyCompletionTokenBounded,
func(context.Context, *config.APITokenRecord, string) (bool, bool, bool) {
config.AdvanceOrgMembershipGeneration()
return true, false, false
},
)
req := httptest.NewRequest(http.MethodGet, "/api/agent/topology", nil)
req.Header.Set("X-API-Token", "r48-m8-b-000000000000000000000000000002")
rr := httptest.NewRecorder()
router.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("Case B status: %d (%s)", rr.Code, rr.Body.String())
}
router.WaitTopologyObservers()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("Case B: expected degraded notification when OrgMembershipGeneration advanced across async org check")
}
if recorded.Load() != 0 || degraded.Load() != 1 {
t.Fatalf("Case B: expected recorded=0 degraded=1, got recorded=%d degraded=%d", recorded.Load(), degraded.Load())
}
}
}
func TestRound48_M9_UpdateAuthEnvFileRejectsOversizedTransformedOutput(t *testing.T) {
dir := t.TempDir()
envPath := filepath.Join(dir, ".env")
initial := "PULSE_AUTH_USER=admin\n" + strings.Repeat("#", int(maxAuthEnvFileSizeBytes)-64) + "\n"
if err := os.WriteFile(envPath, []byte(initial), 0600); err != nil {
t.Fatalf("write initial .env: %v", err)
}
_, err := updateAuthEnvFile(dir, "", func(existing []byte, _ bool) ([]byte, error) {
return append(append([]byte(nil), existing...), []byte(strings.Repeat("X", 512)+"\n")...), nil
})
if !errors.Is(err, config.ErrFileTooLarge) {
t.Fatalf("expected config.ErrFileTooLarge for oversized transformed .env, got %v", err)
}
after, readErr := os.ReadFile(envPath)
if readErr != nil {
t.Fatalf("read .env after refusal: %v", readErr)
}
if string(after) != initial {
t.Fatal("expected original .env preserved untouched after oversized transform rejection")
}
}