Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Harden Discovery command-scan gating

rcourtman435cf816fb80
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 45843377c6..9ef5be6e9d 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -752,7 +752,11 @@ profile and assignment columns, but embedded table framing must route through
compact: the persistent page may expose only a concise discovery status
line plus `Run discovery` / `Discovery settings` actions, while new-source
admission stays on the per-platform table actions instead of competing
- with discovery at the top of the page.
+ with discovery at the top of the page. Command-backed discovery sweeps and
+ forced single-resource refreshes remain API/AI-owned admin operations:
+ lifecycle surfaces may expose the controls, but route-level authority must
+ require `settings:write` plus the Discovery enablement gate, not
+ `monitoring:write`, enrollment state, or any fleet lifecycle shortcut.
The editor's probe step calls the aggregator probe endpoint and
dispatches the detected or manually-selected type into a credential
slot; it must not bypass the probe endpoint or fabricate probe
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 9bc584a7e9..a1663696b1 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -1151,6 +1151,15 @@ must honor that `Trusted` flag by bypassing the approval requirement,
while still enforcing `PolicyBlock`. AI tool calls, Patrol fixes, and
Assistant remediation must continue to flow through the governed approval
record path and must never set `Trusted` on their payloads.
+Discovery command-backed scans are additionally gated by the operator's
+Discovery setting, not by the mere presence of a service-discovery store,
+connected agent, or command-capable agent token. `discovery_enabled=false`
+must fail closed for background sweeps, `/api/discovery/run`, forced
+single-resource discovery, and `pulse_discovery` refreshes before any
+`DeepScanner` command dispatch. `discovery_enabled=true` with
+`discovery_interval_hours: 0` is the only manual-command-scan mode: recurring
+scans stay stopped, but explicit admin-triggered refreshes may use the
+hardcoded trusted catalog.
The same action-audit boundary now also requires persisted action records to
carry a normalized plan and preflight: action id, request id, capability,
approval policy, dry-run availability, safety checks, verification steps, and
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index c7da9b6393..a246e20508 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -1403,10 +1403,11 @@ the canonical monitored-system blocked payload.
must send `discovery_enabled` and `discovery_interval_hours` together as
explicit form truth, and the backend must persist a provided
`discovery_interval_hours: 0` as manual-only rather than replacing it with
- the automatic-scan default. Manual discovery can be triggered directly
- through the discovery API for a known resource, through the settings-level
- `/api/discovery/run` sweep for new/changed/stale workload refresh, and
- through the governed `pulse_discovery` tool; the API progress payload must
+ the automatic-scan default. Manual command-backed discovery is available
+ only while `discovery_enabled` is true and must be admin-gated at the
+ backend. When Discovery is disabled, direct known-resource refreshes,
+ `/api/discovery/run`, and governed `pulse_discovery` refreshes must fail
+ closed before any agent command dispatch. The API progress payload must
describe discovery evidence analysis rather than presenting background work
as a visible Pulse Assistant chat session.
25. Keep shared AI runtime reads centralized on that same governed contract:
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 817b431f3f..f5d28dcba9 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -933,9 +933,9 @@ AI runtime.
settings pair so selecting "Every 6 hours" or "Manual only" round-trips
through `/api/settings/ai` without depending on stale read-side diffing.
The same workload-discovery settings section must expose a manual
- "Run discovery now" action wired through `/api/discovery/run` even when
- recurring workload discovery is off, while resource-drawer discovery remains
- the forced single-resource refresh path.
+ "Run discovery now" action wired through `/api/discovery/run` when
+ workload discovery is enabled in manual-only mode, while resource-drawer
+ discovery remains the forced single-resource refresh path.
Assistant-only controls inside the shared shell, such
as execution permissions and session maintenance, must stay explicitly
labeled as Pulse Assistant controls, while Patrol schedule and autonomy
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c50bc3a983..5ebe61f367 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -485,7 +485,10 @@ bypass the API fail-closed execution gate.
to that adjacent discovery/API boundary. Storage and recovery surfaces may
consume refreshed workload discovery records, but they must not reinterpret
the sweep as a recovery scan, protected-system admission, or storage-local
- ownership signal.
+ ownership signal. Because that sweep can dispatch agent-backed discovery
+ commands, adjacent storage/recovery surfaces must also inherit the
+ API/runtime gate: `settings:write` plus enabled Discovery are required
+ before command-backed refresh, and `monitoring:write` remains insufficient.
That same adjacent `internal/api/` boundary also keeps public hosted signup
commercial-only: storage and recovery surfaces must not infer tenant
existence, email issuance, or readiness from `/api/public/signup` response
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 4fc0be8534..7f3176482e 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -561,8 +561,11 @@ func (s *Service) initDiscoveryServiceLocked() {
// Create the discovery service with config-driven settings
discoveryCfg := servicediscovery.DefaultConfig()
+ commandScanningEnabled := false
if s.cfg != nil {
discoveryCfg.Interval = s.cfg.GetDiscoveryInterval()
+ commandScanningEnabled = s.cfg.Enabled && s.cfg.IsDiscoveryEnabled() && s.provider != nil
+ discoveryCfg.CommandScanning = commandScanningEnabled
}
s.discoveryService = servicediscovery.NewService(
@@ -574,13 +577,15 @@ func (s *Service) initDiscoveryServiceLocked() {
s.discoveryService.SetReadState(s.readState)
// Start background discovery if enabled and interval is set
- if s.cfg != nil && s.cfg.IsDiscoveryEnabled() && s.cfg.GetDiscoveryInterval() > 0 {
+ if commandScanningEnabled && s.cfg.GetDiscoveryInterval() > 0 {
s.discoveryService.Start(context.Background())
log.Info().
Dur("interval", s.cfg.GetDiscoveryInterval()).
Msg("AI-powered deep discovery service started with automatic scanning")
+ } else if commandScanningEnabled {
+ log.Info().Msg("AI-powered deep discovery service initialized (manual command scanning mode)")
} else {
- log.Info().Msg("AI-powered deep discovery service initialized (manual mode)")
+ log.Info().Msg("AI-powered deep discovery service initialized with command scanning disabled")
}
}
@@ -870,6 +875,7 @@ func (s *Service) updateDiscoverySettings(cfg *config.AIConfig) {
enabled := s.IsEnabled() && cfg.IsDiscoveryEnabled()
interval := cfg.GetDiscoveryInterval()
+ s.discoveryService.SetCommandScanningEnabled(enabled)
if enabled && interval > 0 {
// Update interval and ensure service is running
diff --git a/internal/ai/service_test.go b/internal/ai/service_test.go
index 64ab0deedf..016c78dfa4 100644
--- a/internal/ai/service_test.go
+++ b/internal/ai/service_test.go
@@ -212,6 +212,24 @@ func TestService_LoadConfig_SyncsInfraDiscoveryLifecycle(t *testing.T) {
if status.Running {
t.Fatalf("expected infra discovery to stay stopped when discovery is disabled")
}
+ if svc.discoveryService == nil {
+ t.Fatalf("expected deep discovery service to be initialized")
+ }
+ if svc.discoveryService.IsCommandScanningEnabled() {
+ t.Fatalf("expected deep discovery command scanning to stay disabled when discovery is disabled")
+ }
+
+ saveConfig(config.AIConfig{
+ Enabled: false,
+ Model: "ollama:llama3.2",
+ OllamaBaseURL: "http://localhost:11434",
+ DiscoveryEnabled: true,
+ DiscoveryIntervalHours: 2,
+ })
+
+ if svc.discoveryService.IsCommandScanningEnabled() {
+ t.Fatalf("expected deep discovery command scanning to stay disabled when AI is disabled")
+ }
saveConfig(config.AIConfig{
Enabled: true,
@@ -228,6 +246,9 @@ func TestService_LoadConfig_SyncsInfraDiscoveryLifecycle(t *testing.T) {
if status.Interval != 2*time.Hour {
t.Fatalf("expected infra discovery interval 2h, got %v", status.Interval)
}
+ if !svc.discoveryService.IsCommandScanningEnabled() {
+ t.Fatalf("expected deep discovery command scanning to enable with AI discovery")
+ }
saveConfig(config.AIConfig{
Enabled: true,
@@ -257,6 +278,9 @@ func TestService_LoadConfig_SyncsInfraDiscoveryLifecycle(t *testing.T) {
if status.Running {
t.Fatalf("expected infra discovery to stop in manual discovery mode")
}
+ if !svc.discoveryService.IsCommandScanningEnabled() {
+ t.Fatalf("expected manual discovery mode to keep command scanning enabled")
+ }
}
func TestService_GetCostSummary_NoStore(t *testing.T) {
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index d8df162ec0..b9e24ca325 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -8597,6 +8597,42 @@ func TestContract_CachedDiscoveryResponseJSONSnapshot(t *testing.T) {
}
}
+func TestContract_DiscoveryCommandScanRoutesRequireSettingsWrite(t *testing.T) {
+ monitoringToken := "discovery-command-monitoring-token-123.12345678"
+ settingsToken := "discovery-command-settings-token-123.12345678"
+ monitoringRecord := newTokenRecord(t, monitoringToken, []string{config.ScopeMonitoringWrite}, nil)
+ settingsRecord := newTokenRecord(t, settingsToken, []string{config.ScopeSettingsWrite}, nil)
+ cfg := newTestConfigWithTokens(t, monitoringRecord, settingsRecord)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ paths := []string{
+ "/api/discovery/run",
+ "/api/discovery/agent/host-1/resource-1",
+ "/api/discovery/vm/host-1/resource-1",
+ }
+
+ for _, path := range paths {
+ req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{}`))
+ req.Header.Set("X-API-Token", monitoringToken)
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("expected monitoring:write token to be forbidden for command-scan route %s, got %d", path, rec.Code)
+ }
+ if !strings.Contains(rec.Body.String(), config.ScopeSettingsWrite) {
+ t.Fatalf("expected command-scan route %s to require %q, got %q", path, config.ScopeSettingsWrite, rec.Body.String())
+ }
+
+ req = httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{}`))
+ req.Header.Set("X-API-Token", settingsToken)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code == http.StatusForbidden && strings.Contains(rec.Body.String(), config.ScopeSettingsWrite) {
+ t.Fatalf("expected settings:write token to pass route scope for command-scan route %s, got %d: %s", path, rec.Code, rec.Body.String())
+ }
+ }
+}
+
func TestContract_AutoRegisterRequestJSONSnapshot(t *testing.T) {
payload := AutoRegisterRequest{
Type: "pve",
diff --git a/internal/api/discovery_handlers.go b/internal/api/discovery_handlers.go
index 5f1ba03231..cc9ec6e2b8 100644
--- a/internal/api/discovery_handlers.go
+++ b/internal/api/discovery_handlers.go
@@ -212,6 +212,18 @@ func (h *DiscoveryHandlers) isAdminRequest(r *http.Request) bool {
return false
}
+func (h *DiscoveryHandlers) requireCommandScanningAccess(w http.ResponseWriter, r *http.Request) bool {
+ if !h.isAdminRequest(r) {
+ writeDiscoveryError(w, http.StatusForbidden, "Admin privileges required")
+ return false
+ }
+ if h.service == nil || !h.service.IsCommandScanningEnabled() {
+ writeDiscoveryError(w, http.StatusForbidden, "Discovery command scanning is disabled")
+ return false
+ }
+ return true
+}
+
// redactSensitiveFields removes sensitive data from a discovery for non-admin users.
// This creates a copy to avoid modifying the original.
func redactSensitiveFields(d *servicediscovery.ResourceDiscovery) *servicediscovery.ResourceDiscovery {
@@ -314,6 +326,9 @@ func (h *DiscoveryHandlers) HandleTriggerDiscovery(w http.ResponseWriter, r *htt
writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")
return
}
+ if !h.requireCommandScanningAccess(w, r) {
+ return
+ }
// Parse path
path := strings.TrimPrefix(r.URL.Path, "/api/discovery/")
@@ -551,6 +566,9 @@ func (h *DiscoveryHandlers) HandleRunDiscovery(w http.ResponseWriter, r *http.Re
writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")
return
}
+ if !h.requireCommandScanningAccess(w, r) {
+ return
+ }
summary, err := h.service.RunManualDiscoveryRefresh(r.Context())
if err != nil {
diff --git a/internal/api/discovery_handlers_test.go b/internal/api/discovery_handlers_test.go
index 7fb73fe34e..f6e142b512 100644
--- a/internal/api/discovery_handlers_test.go
+++ b/internal/api/discovery_handlers_test.go
@@ -49,6 +49,7 @@ func (m *MockCommandExecutor) IsAgentConnected(agentID string) bool {
func setupDiscoveryHandlers(t *testing.T) (*DiscoveryHandlers, *servicediscovery.Service, *servicediscovery.Store) {
// Create temp dir
tmpDir := t.TempDir()
+ InitSessionStore(tmpDir)
// Create real store
store, err := servicediscovery.NewStore(tmpDir)
@@ -60,6 +61,7 @@ func setupDiscoveryHandlers(t *testing.T) (*DiscoveryHandlers, *servicediscovery
// Create service
cfg := servicediscovery.DefaultConfig()
+ cfg.CommandScanning = true
service := servicediscovery.NewService(store, scanner, cfg)
// Create config for handlers (needed for admin check)
@@ -269,6 +271,7 @@ func TestHandleTriggerDiscovery(t *testing.T) {
reqBody := `{"force": true, "hostname": "my-vm"}`
req := httptest.NewRequest("POST", "/api/discovery/vm/node1/100", bytes.NewBufferString(reqBody))
+ req.SetBasicAuth("admin", "admin")
w := httptest.NewRecorder()
// This will fail because MockCommandExecutor returns error for unmocked calls
@@ -290,6 +293,23 @@ func TestHandleTriggerDiscovery(t *testing.T) {
assert.True(t, w.Code == http.StatusInternalServerError || w.Code == http.StatusOK)
}
+func TestHandleTriggerDiscoveryRequiresAdminAndEnabledCommandScanning(t *testing.T) {
+ h, svc, _ := setupDiscoveryHandlers(t)
+
+ req := httptest.NewRequest("POST", "/api/discovery/vm/node1/100", bytes.NewBufferString(`{"force":true}`))
+ w := httptest.NewRecorder()
+ h.HandleTriggerDiscovery(w, req)
+ assert.Equal(t, http.StatusForbidden, w.Code)
+
+ svc.SetCommandScanningEnabled(false)
+ req = httptest.NewRequest("POST", "/api/discovery/vm/node1/100", bytes.NewBufferString(`{"force":true}`))
+ req.SetBasicAuth("admin", "admin")
+ w = httptest.NewRecorder()
+ h.HandleTriggerDiscovery(w, req)
+ assert.Equal(t, http.StatusForbidden, w.Code)
+ assert.Contains(t, w.Body.String(), "Discovery command scanning is disabled")
+}
+
func TestHandleUpdateNotes(t *testing.T) {
h, svc, store := setupDiscoveryHandlers(t)
@@ -361,6 +381,7 @@ func TestHandleRunDiscovery(t *testing.T) {
svc.SetAIAnalyzer(discoveryHandlerTestAnalyzer{})
req := httptest.NewRequest("POST", "/api/discovery/run", nil)
+ req.SetBasicAuth("admin", "admin")
w := httptest.NewRecorder()
h.HandleRunDiscovery(w, req)
@@ -372,6 +393,30 @@ func TestHandleRunDiscovery(t *testing.T) {
assert.Equal(t, 0, summary.CandidateCount)
}
+func TestHandleRunDiscoveryTokenRequiresSettingsWrite(t *testing.T) {
+ h, svc, _ := setupDiscoveryHandlers(t)
+ svc.SetAIAnalyzer(discoveryHandlerTestAnalyzer{})
+
+ monitoringToken, err := config.NewAPITokenRecord("discovery-monitoring-token-123.12345678", "monitoring", []string{config.ScopeMonitoringWrite})
+ require.NoError(t, err)
+ settingsToken, err := config.NewAPITokenRecord("discovery-settings-token-123.12345678", "settings", []string{config.ScopeSettingsWrite})
+ require.NoError(t, err)
+ h.config.APITokens = []config.APITokenRecord{*monitoringToken, *settingsToken}
+ h.config.SortAPITokens()
+
+ req := httptest.NewRequest("POST", "/api/discovery/run", nil)
+ req.Header.Set("X-API-Token", "discovery-monitoring-token-123.12345678")
+ w := httptest.NewRecorder()
+ h.HandleRunDiscovery(w, req)
+ assert.Equal(t, http.StatusForbidden, w.Code)
+
+ req = httptest.NewRequest("POST", "/api/discovery/run", nil)
+ req.Header.Set("X-API-Token", "discovery-settings-token-123.12345678")
+ w = httptest.NewRecorder()
+ h.HandleRunDiscovery(w, req)
+ assert.Equal(t, http.StatusOK, w.Code)
+}
+
func TestHandleUpdateSettings(t *testing.T) {
h, _, _ := setupDiscoveryHandlers(t)
diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.go
index 83f03f3f37..7d55aed396 100644
--- a/internal/api/router_routes_monitoring.go
+++ b/internal/api/router_routes_monitoring.go
@@ -262,7 +262,7 @@ func (r *Router) registerMonitoringResourceRoutes(
// AI-powered infrastructure discovery endpoints
r.mux.HandleFunc("/api/discovery", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleListDiscoveries)))
r.mux.HandleFunc("/api/discovery/status", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleGetStatus)))
- r.mux.HandleFunc("/api/discovery/run", RequireAuth(r.config, RequireScope(config.ScopeMonitoringWrite, func(w http.ResponseWriter, req *http.Request) {
+ r.mux.HandleFunc("/api/discovery/run", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, func(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodPost {
r.discoveryHandlers.HandleRunDiscovery(w, req)
} else {
@@ -303,7 +303,7 @@ func (r *Router) registerMonitoringResourceRoutes(
http.Error(w, "Invalid path", http.StatusBadRequest)
}
case http.MethodPost:
- if !ensureScope(w, req, config.ScopeMonitoringWrite) {
+ if !ensureScope(w, req, config.ScopeSettingsWrite) {
return
}
// POST /api/discovery/agent/{agentId}/{resourceId} → trigger discovery
@@ -341,7 +341,7 @@ func (r *Router) registerMonitoringResourceRoutes(
r.discoveryHandlers.HandleGetDiscovery(w, req)
}
case http.MethodPost:
- if !ensureScope(w, req, config.ScopeMonitoringWrite) {
+ if !ensureScope(w, req, config.ScopeSettingsWrite) {
return
}
r.discoveryHandlers.HandleTriggerDiscovery(w, req)
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index f43ff332ee..71c9717db2 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -2429,27 +2429,28 @@ func TestDiscoveryReadEndpointsRequireMonitoringReadScope(t *testing.T) {
}
}
-func TestDiscoveryMutationEndpointsRequireMonitoringWriteScope(t *testing.T) {
+func TestDiscoveryMutationEndpointsRequireWriteScopes(t *testing.T) {
rawToken := "discovery-write-token-123.12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeMonitoringRead}, nil)
cfg := newTestConfigWithTokens(t, record)
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
paths := []struct {
- method string
- path string
- body string
+ method string
+ path string
+ body string
+ requiredScope string
}{
- {method: http.MethodPost, path: "/api/discovery/run", body: `{}`},
- {method: http.MethodPost, path: "/api/discovery/agent/host-1/resource-1", body: `{}`},
- {method: http.MethodPut, path: "/api/discovery/agent/host-1/resource-1/notes", body: `{}`},
- {method: http.MethodDelete, path: "/api/discovery/agent/host-1/resource-1", body: ""},
- {method: http.MethodPost, path: "/api/discovery/agent/host-1/resource-1", body: `{}`},
- {method: http.MethodPut, path: "/api/discovery/agent/host-1/resource-1/notes", body: `{}`},
- {method: http.MethodDelete, path: "/api/discovery/agent/host-1/resource-1", body: ""},
- {method: http.MethodPost, path: "/api/discovery/resource-1", body: `{}`},
- {method: http.MethodPut, path: "/api/discovery/resource-1/notes", body: `{}`},
- {method: http.MethodDelete, path: "/api/discovery/resource-1", body: ""},
+ {method: http.MethodPost, path: "/api/discovery/run", body: `{}`, requiredScope: config.ScopeSettingsWrite},
+ {method: http.MethodPost, path: "/api/discovery/agent/host-1/resource-1", body: `{}`, requiredScope: config.ScopeSettingsWrite},
+ {method: http.MethodPut, path: "/api/discovery/agent/host-1/resource-1/notes", body: `{}`, requiredScope: config.ScopeMonitoringWrite},
+ {method: http.MethodDelete, path: "/api/discovery/agent/host-1/resource-1", body: "", requiredScope: config.ScopeMonitoringWrite},
+ {method: http.MethodPost, path: "/api/discovery/agent/host-1/resource-1", body: `{}`, requiredScope: config.ScopeSettingsWrite},
+ {method: http.MethodPut, path: "/api/discovery/agent/host-1/resource-1/notes", body: `{}`, requiredScope: config.ScopeMonitoringWrite},
+ {method: http.MethodDelete, path: "/api/discovery/agent/host-1/resource-1", body: "", requiredScope: config.ScopeMonitoringWrite},
+ {method: http.MethodPost, path: "/api/discovery/resource-1", body: `{}`, requiredScope: config.ScopeSettingsWrite},
+ {method: http.MethodPut, path: "/api/discovery/resource-1/notes", body: `{}`, requiredScope: config.ScopeMonitoringWrite},
+ {method: http.MethodDelete, path: "/api/discovery/resource-1", body: "", requiredScope: config.ScopeMonitoringWrite},
}
for _, tc := range paths {
@@ -2458,10 +2459,10 @@ func TestDiscoveryMutationEndpointsRequireMonitoringWriteScope(t *testing.T) {
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
- t.Fatalf("expected 403 for missing monitoring:write scope on %s %s, got %d", tc.method, tc.path, rec.Code)
+ t.Fatalf("expected 403 for missing %s scope on %s %s, got %d", tc.requiredScope, tc.method, tc.path, rec.Code)
}
- if !strings.Contains(rec.Body.String(), config.ScopeMonitoringWrite) {
- t.Fatalf("expected missing scope response to mention %q, got %q", config.ScopeMonitoringWrite, rec.Body.String())
+ if !strings.Contains(rec.Body.String(), tc.requiredScope) {
+ t.Fatalf("expected missing scope response to mention %q, got %q", tc.requiredScope, rec.Body.String())
}
}
}
diff --git a/internal/servicediscovery/service.go b/internal/servicediscovery/service.go
index 0952d2c450..051e1100e5 100644
--- a/internal/servicediscovery/service.go
+++ b/internal/servicediscovery/service.go
@@ -256,6 +256,7 @@ type Service struct {
mu sync.RWMutex
running bool
stopping bool
+ commandScanning bool
stopCh chan struct{}
loopDone chan struct{}
runCancel context.CancelFunc
@@ -302,6 +303,7 @@ type Config struct {
// Fingerprint-based discovery settings
MaxDiscoveryAge time.Duration // Rediscover after this duration (default 30 days)
FingerprintInterval time.Duration // How often to collect fingerprints (default 5 min)
+ CommandScanning bool // Enables agent command-backed deep scans
}
const (
@@ -321,6 +323,7 @@ func DefaultConfig() Config {
DeepScanTimeout: defaultDiscoveryScanTimeout,
MaxDiscoveryAge: defaultDiscoveryMaxAge,
FingerprintInterval: defaultDiscoveryInterval,
+ CommandScanning: false,
}
}
@@ -395,9 +398,31 @@ func NewService(store *Store, scanner *DeepScanner, cfg Config) *Service {
intervalCh: make(chan time.Duration, 1), // Buffered to prevent blocking
analysisCache: make(map[string]*analysisCacheEntry),
inProgress: make(map[string]*discoveryInProgress),
+ commandScanning: cfg.CommandScanning,
}
}
+// SetCommandScanningEnabled controls whether this service may dispatch
+// command-backed deep scans through connected Pulse agents.
+func (s *Service) SetCommandScanningEnabled(enabled bool) {
+ if s == nil {
+ return
+ }
+ s.mu.Lock()
+ s.commandScanning = enabled
+ s.mu.Unlock()
+}
+
+// IsCommandScanningEnabled reports whether command-backed deep scans may run.
+func (s *Service) IsCommandScanningEnabled() bool {
+ if s == nil {
+ return false
+ }
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.commandScanning
+}
+
// SetAIAnalyzer sets the AI analyzer for discovery.
func (s *Service) SetAIAnalyzer(analyzer AIAnalyzer) {
s.mu.Lock()
@@ -420,6 +445,11 @@ func (s *Service) Start(ctx context.Context) {
s.mu.Unlock()
return
}
+ if !s.commandScanning {
+ s.mu.Unlock()
+ log.Info().Msg("Discovery command scanning disabled; background discovery service not started")
+ return
+ }
runCtx, cancel := context.WithCancel(ctx)
s.running = true
stopCh := make(chan struct{})
@@ -635,6 +665,9 @@ func (s *Service) RunManualDiscoveryRefresh(ctx context.Context) (DiscoveryRefre
if ctx == nil || ctx.Err() != nil || s.store == nil {
return DiscoveryRefreshSummary{Mode: "manual"}, fmt.Errorf("discovery service is not ready")
}
+ if !s.IsCommandScanningEnabled() {
+ return DiscoveryRefreshSummary{Mode: "manual"}, fmt.Errorf("discovery command scanning is disabled")
+ }
s.collectFingerprints(ctx)
return s.runDiscoveryRefresh(ctx, "manual")
@@ -645,6 +678,9 @@ func (s *Service) runDiscoveryRefresh(ctx context.Context, mode string) (Discove
if ctx == nil || ctx.Err() != nil || s.store == nil {
return summary, fmt.Errorf("discovery service is not ready")
}
+ if !s.IsCommandScanningEnabled() {
+ return summary, fmt.Errorf("discovery command scanning is disabled")
+ }
s.mu.RLock()
analyzerConfigured := s.aiAnalyzer != nil
@@ -1285,7 +1321,7 @@ func (s *Service) discoverDockerContainers(ctx context.Context, hosts []DockerHo
if discovery != nil {
// Smart auto deep scan: enhance if discovery is incomplete or low-confidence
// Also deep scan if there's no existing discovery (first time)
- if s.scanner != nil && (existing == nil || s.needsDeepScan(discovery)) {
+ if s.scanner != nil && s.IsCommandScanningEnabled() && (existing == nil || s.needsDeepScan(discovery)) {
log.Info().
Str("id", id).
Float64("confidence", discovery.Confidence).
@@ -1314,7 +1350,7 @@ func (s *Service) enhanceWithDeepScan(ctx context.Context, discovery *ResourceDi
s.mu.RUnlock()
timeout = normalizeDeepScanTimeout(timeout)
- if s.scanner == nil || analyzer == nil {
+ if s.scanner == nil || analyzer == nil || !s.IsCommandScanningEnabled() {
return discovery
}
@@ -1645,7 +1681,7 @@ func (s *Service) DiscoverResource(ctx context.Context, req DiscoveryRequest) (*
// Run deep scan if scanner is available
var scanResult *ScanResult
var scanError error
- if s.scanner != nil {
+ if s.scanner != nil && s.IsCommandScanningEnabled() {
scanResult, scanError = s.scanner.Scan(ctx, req)
if scanError != nil {
log.Warn().
@@ -2864,6 +2900,7 @@ func (s *Service) GetStatusSnapshot() ServiceStatus {
AIAnalyzerSet: s.aiAnalyzer != nil,
ScannerSet: s.scanner != nil,
StoreSet: s.store != nil,
+ CommandScanning: s.commandScanning,
DeepScanTimeout: s.deepScanTimeout.String(),
AIAnalysisTimeout: s.aiAnalysisTimeout.String(),
MaxDiscoveryAge: s.maxDiscoveryAge.String(),
diff --git a/internal/servicediscovery/service_test.go b/internal/servicediscovery/service_test.go
index fbd2b6efb5..46749c0187 100644
--- a/internal/servicediscovery/service_test.go
+++ b/internal/servicediscovery/service_test.go
@@ -941,6 +941,7 @@ func TestService_RunManualDiscoveryRefreshDiscoversNewFingerprints(t *testing.T)
response: `{"service_type":"nginx","service_name":"Nginx","service_version":"1.2","category":"web_server","cli_access":"docker exec {container} nginx -v","facts":[],"config_paths":["/etc/nginx"],"data_paths":[],"log_paths":[],"ports":[{"port":80,"protocol":"tcp","process":"nginx","address":"0.0.0.0"}],"confidence":0.9,"reasoning":"image"}`,
}
service := NewService(store, nil, DefaultConfig())
+ service.SetCommandScanningEnabled(true)
service.SetReadState(readStateFromSnapshot(state))
service.SetAIAnalyzer(analyzer)
@@ -1061,6 +1062,7 @@ func TestService_PromptsAndDiscoveryLoop(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
service.initialDelay = time.Millisecond
+ service.SetCommandScanningEnabled(true)
service.Start(ctx)
service.Start(ctx)
service.Stop()
@@ -1097,6 +1099,7 @@ func TestService_FingerprintLoop_StopAndCancel(t *testing.T) {
service := NewService(store, nil, DefaultConfig())
service.SetReadState(readStateFromSnapshot(state))
+ service.SetCommandScanningEnabled(true)
// Analyzer should be called by automatic refresh for changed/new resources.
analyzer := &stubAnalyzer{
response: `{"service_type":"nginx","service_name":"Nginx","service_version":"1.2","category":"web_server","cli_access":"docker exec {container} nginx -v","facts":[],"config_paths":[],"data_paths":[],"ports":[],"confidence":0.9,"reasoning":"image"}`,
@@ -1188,6 +1191,7 @@ func TestService_StartDuringStopDoesNotStartNewLoop(t *testing.T) {
service.SetReadState(readStateFromSnapshot(state))
service.initialDelay = time.Millisecond
service.interval = time.Hour
+ service.SetCommandScanningEnabled(true)
analyzer := &blockingAnalyzer{started: make(chan struct{})}
service.SetAIAnalyzer(analyzer)
@@ -1347,7 +1351,9 @@ func TestService_DiscoverResource_ScanError(t *testing.T) {
store.crypto = nil
scanner := NewDeepScanner(nil)
- service := NewService(store, scanner, DefaultConfig())
+ cfg := DefaultConfig()
+ cfg.CommandScanning = true
+ service := NewService(store, scanner, cfg)
service.SetAIAnalyzer(&stubAnalyzer{
response: `{"service_type":"nginx","service_name":"Nginx","service_version":"1.2","category":"web_server","cli_access":"docker exec {container} nginx -v","facts":[],"config_paths":[],"data_paths":[],"ports":[],"confidence":0.9,"reasoning":"image"}`,
})
@@ -1364,6 +1370,40 @@ func TestService_DiscoverResource_ScanError(t *testing.T) {
}
}
+func TestService_DiscoverResource_CommandScanningDisabledSkipsScanner(t *testing.T) {
+ store, err := NewStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("NewStore error: %v", err)
+ }
+ store.crypto = nil
+
+ exec := &stubExecutor{
+ agents: []ConnectedAgent{{AgentID: "host1", Hostname: "host1"}},
+ }
+ scanner := NewDeepScanner(exec)
+ service := NewService(store, scanner, DefaultConfig())
+ service.SetAIAnalyzer(&stubAnalyzer{
+ response: `{"service_type":"nginx","service_name":"Nginx","service_version":"1.2","category":"web_server","cli_access":"","facts":[],"config_paths":[],"data_paths":[],"ports":[],"confidence":0.9,"reasoning":"metadata"}`,
+ })
+
+ _, err = service.DiscoverResource(context.Background(), DiscoveryRequest{
+ ResourceType: ResourceTypeDocker,
+ ResourceID: "web",
+ TargetID: "host1",
+ Hostname: "host1",
+ Force: true,
+ })
+ if err != nil {
+ t.Fatalf("DiscoverResource error: %v", err)
+ }
+
+ exec.mu.Lock()
+ defer exec.mu.Unlock()
+ if len(exec.commands) != 0 {
+ t.Fatalf("expected command scanning disabled to skip executor, got commands: %v", exec.commands)
+ }
+}
+
func TestService_DiscoveryLoop_ContextDoneAtStart(t *testing.T) {
service := NewService(nil, nil, DefaultConfig())
service.initialDelay = time.Hour
@@ -1400,7 +1440,9 @@ func TestService_DiscoverResource_WithScanResult(t *testing.T) {
},
}
- service := NewService(store, scanner, DefaultConfig())
+ cfg := DefaultConfig()
+ cfg.CommandScanning = true
+ service := NewService(store, scanner, cfg)
service.SetReadState(readStateFromSnapshot(state))
service.SetAIAnalyzer(&stubAnalyzer{
response: `{"service_type":"nginx","service_name":"Nginx","service_version":"1.2","category":"web_server","cli_access":"docker exec {container} nginx -v","facts":[],"config_paths":[],"data_paths":[],"ports":[{"port":80,"protocol":"tcp","process":"nginx","address":"0.0.0.0"}],"confidence":0.9,"reasoning":"image"}`,
diff --git a/internal/servicediscovery/tools_adapter.go b/internal/servicediscovery/tools_adapter.go
index 87d2715787..ea51d8dec4 100644
--- a/internal/servicediscovery/tools_adapter.go
+++ b/internal/servicediscovery/tools_adapter.go
@@ -84,6 +84,20 @@ func (a *ToolsAdapter) FormatForAIContext(sourceData []tools.DiscoverySourceData
// TriggerDiscovery implements tools.DiscoverySource - initiates discovery for a resource
func (a *ToolsAdapter) TriggerDiscovery(ctx context.Context, resourceType, targetID, resourceID string, force bool) (tools.DiscoverySourceData, error) {
+ if !a.service.IsCommandScanningEnabled() {
+ if force {
+ return tools.DiscoverySourceData{}, fmt.Errorf("discovery command scanning is disabled")
+ }
+ discovery, err := a.service.GetDiscoveryByResource(ResourceType(resourceType), targetID, resourceID)
+ if err != nil {
+ return tools.DiscoverySourceData{}, fmt.Errorf("get discovery for %s/%s/%s: %w", resourceType, targetID, resourceID, err)
+ }
+ if discovery == nil {
+ return tools.DiscoverySourceData{}, nil
+ }
+ return a.convertToSourceData(discovery), nil
+ }
+
req := DiscoveryRequest{
ResourceType: ResourceType(resourceType),
TargetID: targetID,
diff --git a/internal/servicediscovery/tools_adapter_test.go b/internal/servicediscovery/tools_adapter_test.go
index 50288f90b1..b8f70baf95 100644
--- a/internal/servicediscovery/tools_adapter_test.go
+++ b/internal/servicediscovery/tools_adapter_test.go
@@ -230,4 +230,16 @@ func TestToolsAdapter_TriggerDiscovery(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, id, result.ID)
})
+
+ t.Run("disabled command scanning rejects forced refresh", func(t *testing.T) {
+ _, err := adapter.TriggerDiscovery(context.Background(), "docker", "h1", "r1", true)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "discovery command scanning is disabled")
+ })
+
+ t.Run("disabled command scanning does not create missing discovery", func(t *testing.T) {
+ result, err := adapter.TriggerDiscovery(context.Background(), "docker", "h1", "missing", false)
+ require.NoError(t, err)
+ assert.Empty(t, result.ID)
+ })
}
diff --git a/internal/servicediscovery/types.go b/internal/servicediscovery/types.go
index ec1fee028e..b0def7d691 100644
--- a/internal/servicediscovery/types.go
+++ b/internal/servicediscovery/types.go
@@ -339,6 +339,7 @@ type ServiceStatus struct {
AIAnalyzerSet bool
ScannerSet bool
StoreSet bool
+ CommandScanning bool
DeepScanTimeout string
AIAnalysisTimeout string
MaxDiscoveryAge string
@@ -368,6 +369,7 @@ func (s ServiceStatus) ToMap() map[string]any {
"ai_analyzer_set": s.AIAnalyzerSet,
"scanner_set": s.ScannerSet,
"store_set": s.StoreSet,
+ "command_scanning": s.CommandScanning,
"deep_scan_timeout": s.DeepScanTimeout,
"ai_analysis_timeout": s.AIAnalysisTimeout,
"max_discovery_age": s.MaxDiscoveryAge,