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.

Surface typed helper degradation in Agent Doctor

rcourtmand19398d82a43
diff --git a/cmd/pulse-agent-helper/main_test.go b/cmd/pulse-agent-helper/main_test.go
index a0d4d3d72d..b31a5b00fe 100644
--- a/cmd/pulse-agent-helper/main_test.go
+++ b/cmd/pulse-agent-helper/main_test.go
@@ -17,6 +17,8 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/agenthelper"
+ "github.com/rcourtman/pulse-go-rewrite/internal/hostagent"
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
)
type committerValidationProvider struct {
@@ -274,13 +276,59 @@ func TestFixedPrivilegedEndpointsAreNotCallerConfigurable(t *testing.T) {
}
}
-func TestLocalProxmoxProviderAlwaysReturnsValidJSON(t *testing.T) {
- result, err := (localProxmoxProvider{}).LXCFilesystems(t.Context())
- if err != nil {
- t.Fatalf("LXCFilesystems: %v", err)
- }
- if !json.Valid(result) {
- t.Fatalf("invalid provider JSON: %q", result)
+func TestLocalProxmoxProviderDistinguishesApplicabilityAndCompleteness(t *testing.T) {
+ tests := []struct {
+ name string
+ collection hostagent.ProxmoxLXCFilesystemCollectionResult
+ wantJSON string
+ wantError bool
+ }{
+ {
+ name: "not applicable",
+ wantJSON: `{"inventory":null}`,
+ },
+ {
+ name: "healthy inventory",
+ collection: hostagent.ProxmoxLXCFilesystemCollectionResult{
+ Applicable: true,
+ Inventory: &agentshost.ProxmoxLXCInventory{},
+ },
+ wantJSON: `{"inventory":{"containers":null,"collectedAt":"0001-01-01T00:00:00Z"}}`,
+ },
+ {
+ name: "partial inventory fails closed",
+ collection: hostagent.ProxmoxLXCFilesystemCollectionResult{
+ Applicable: true,
+ Inventory: &agentshost.ProxmoxLXCInventory{},
+ Degraded: true,
+ FailedContainers: 1,
+ },
+ wantError: true,
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ provider := localProxmoxProvider{collect: func(context.Context) hostagent.ProxmoxLXCFilesystemCollectionResult {
+ return test.collection
+ }}
+ result, err := provider.LXCFilesystems(t.Context())
+ if test.wantError {
+ var providerErr *agenthelper.ProviderError
+ if !errors.As(err, &providerErr) || providerErr.Code != agenthelper.ErrorProviderUnavailable {
+ t.Fatalf("provider error = %v", err)
+ }
+ if result != nil {
+ t.Fatalf("degraded provider result = %q, want nil", result)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("LXCFilesystems: %v", err)
+ }
+ if !json.Valid(result) || string(result) != test.wantJSON {
+ t.Fatalf("provider JSON = %q, want %q", result, test.wantJSON)
+ }
+ })
}
}
diff --git a/cmd/pulse-agent-helper/providers.go b/cmd/pulse-agent-helper/providers.go
index 347d4ef675..66a7a772c6 100644
--- a/cmd/pulse-agent-helper/providers.go
+++ b/cmd/pulse-agent-helper/providers.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agenthelper"
"github.com/rcourtman/pulse-go-rewrite/internal/hostagent"
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
)
@@ -32,13 +33,26 @@ func (localSMARTProvider) Snapshot(ctx context.Context) (json.RawMessage, error)
// localProxmoxProvider runs the existing bounded node-local inventory as one
// typed operation. The collector cannot select a VMID, filesystem path,
// command, or pct argument across the helper boundary.
-type localProxmoxProvider struct{}
+type localProxmoxProvider struct {
+ collect func(context.Context) hostagent.ProxmoxLXCFilesystemCollectionResult
+}
-func (localProxmoxProvider) LXCFilesystems(ctx context.Context) (json.RawMessage, error) {
- inventory := hostagent.CollectProxmoxLXCFilesystemsLocal(ctx)
+func (p localProxmoxProvider) LXCFilesystems(ctx context.Context) (json.RawMessage, error) {
+ collect := p.collect
+ if collect == nil {
+ collect = hostagent.CollectProxmoxLXCFilesystemsLocalResult
+ }
+ collection := collect(ctx)
+ if collection.Degraded {
+ return nil, &agenthelper.ProviderError{
+ Code: agenthelper.ErrorProviderUnavailable,
+ Message: "Proxmox LXC filesystem inventory is incomplete",
+ Retryable: true,
+ }
+ }
result, err := json.Marshal(struct {
Inventory *agentshost.ProxmoxLXCInventory `json:"inventory"`
- }{Inventory: inventory})
+ }{Inventory: collection.Inventory})
if err != nil {
return nil, fmt.Errorf("encode Proxmox LXC filesystem inventory: %w", err)
}
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 07fd520bf1..9de33fe09b 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -77,6 +77,21 @@ listening or active systemd socket alone is not helper health. Once the helper
boundary is selected, SMART and Proxmox LXC filesystem collection fail closed
to an omitted/degraded snapshot when the helper fails; the collector must not
silently retry the privileged read locally.
+The collector reports that runtime truth as the shared
+`typed-privilege-helper` module. SMART and Proxmox operation failures remain
+independently active until that exact operation succeeds again, so one healthy
+helper call cannot hide another degraded capability. The module carries only a
+stable classified current error and returns to `running` after complete
+recovery; raw helper messages, payloads, credentials, and caller-selected paths
+never enter the status or persisted report.
+An absent Proxmox inventory is a failure only when Proxmox mode is configured
+or the unprivileged collector can discover the local `pct` binary. Ordinary
+Linux hosts without that provider remain healthy rather than reporting a
+permanent helper warning.
+The Proxmox provider also distinguishes complete collection from a partial
+result internally. If listing or any running-container filesystem query fails,
+protocol v1 returns a stable typed provider failure and omits the affected
+snapshot instead of serializing partial inventory as healthy.
Helper-backed collector updates are a durable pending transaction rather than
a successful binary swap. The helper records activation intent before the
@@ -6996,6 +7011,11 @@ It must not use `PrivateDevices=true`, because SMART collection requires access
to host block devices. Helper absence, incompatibility, or an unavailable
operation degrades only the affected telemetry and must never reactivate a sudo
wrapper, Docker-group membership, ambient capability, or root collector.
+The collector projects post-start operation failure through the canonical
+`typed-privilege-helper` module status. Agent Doctor maps that module to the
+stable `agent_privilege_helper_degraded` reason and explains that affected
+telemetry was omitted without widening collector privilege. The status is an
+observability result only; it never authorizes a fallback or helper repair.
The rate-limited public `/download/pulse-agent-helper?arch=linux-*` endpoint is
the only server delivery path: it rejects non-Linux targets, serves the exact
separate helper artifact with checksum plus detached signatures, and requires a
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 75e818feb8..5d041777c5 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -6893,6 +6893,16 @@ identity plus bounded platform, network, profile, updater, module, reason, and
repair-handoff evidence. Raw machine identity is represented only by a
one-way fingerprint; unbounded or secret-shaped updater/module errors are
redacted before serialization; malformed interface addresses are omitted.
+The shared `typed-privilege-helper` host-telemetry module may derive the
+additive stable reason `agent_privilege_helper_degraded`. Its message states
+that affected privileged telemetry was omitted without widening collector
+privilege, and its evidence uses the same bounded module-error redaction as
+every other diagnostic module. It is an observability reason only: no repair
+action, execution grant, or fallback authority is implied.
+The collector-originated helper module carries only stable classified error
+text. Raw helper messages, bearer-shaped values, request identifiers, and local
+paths are excluded before the host report can enter connection state; Doctor
+redaction remains defense in depth rather than the first secrecy boundary.
Older consumers may ignore the additive fields, while the Agent Doctor client
must tolerate absent optional fields and preserve `/api/connections` fallback
rows. Repair objects describe whether an existing local handoff is supported
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 0d286701bd..a45aa7ed64 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -61,6 +61,21 @@ when the canonical agent ID matches an admitted `action-runner` session with
the closed `typed_actions.v1` capability. Credential presence, expiry,
connection, version, and protocol facts remain distinct, and none may be
inferred from collector health or helper configuration.
+Configured helper posture and current SMART/Proxmox helper operation health
+are also distinct. Monitoring preserves the collector-authored
+`typed-privilege-helper` module status and derives the stable warning
+`agent_privilege_helper_degraded` when it is not running. The reason states
+that affected privileged telemetry was omitted without local privilege
+widening, while its error evidence passes through the existing bounded
+diagnostic redaction. A later success clears only the matching operation on the
+collector; monitoring must not infer recovery from an unrelated healthy helper
+operation.
+The collector emits no Proxmox degradation for an absent inventory on an
+ordinary Linux host unless Proxmox mode or local `pct` discovery establishes
+that the operation applies.
+If any running-container filesystem query fails, the helper returns a stable
+typed operation failure and the collector omits that Proxmox snapshot; partial
+inventory must not be reported as a healthy collection.
Monitor construction also applies the persisted alert schedule's normalized
initial-delivery target to the tenant notification manager. This is runtime
wiring only: monitoring does not choose destinations or own notification
@@ -3054,6 +3069,12 @@ avoids a duplicated distro allowlist, so long-tail distributions such as
Mageia receive the same Linux repair handoff as Ubuntu or Debian. Unknown
updater states remain explicit warnings, and unverified FreeBSD/pfSense
installer state still fails closed for upgrade-command support.
+The `typed-privilege-helper` module is the explicit fail-closed specialization
+of that generic module derivation: a non-running state emits
+`agent_privilege_helper_degraded` and explains the omitted privileged
+telemetry. Ordinary operation degradation remains a warning; a future terminal
+`failed` state may retain critical severity under the same reason code. Neither
+form creates a remote repair action or broadens collector authority.
Credential truth is derived from the current server token inventory, not the
last successful heartbeat alone. A live host whose reported `TokenID` no
longer resolves emits `agent_credential_missing`; a resolved but expired record
diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
index 9c28703766..8c8a38bc3e 100644
--- a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts
@@ -165,6 +165,53 @@ describe('Agent Doctor model', () => {
expect(report).toContain('Privilege least privilege (pulse-agent) · SMART helper active');
});
+ it('surfaces fail-closed typed-helper degradation in the target and copied report', () => {
+ const connection = connectionFixture({ agentUpdateAvailable: false });
+ const [target] = collectInfrastructureAgentDoctorTargets({
+ rows: [rowFixture(connection)],
+ connections: [connection],
+ diagnostics: [
+ diagnosticFixture({
+ status: 'warning',
+ agentModules: [
+ {
+ name: 'typed-privilege-helper',
+ enabled: true,
+ state: 'degraded',
+ lastError: 'smart.snapshot: helper unavailable',
+ },
+ ],
+ reasons: [
+ {
+ code: 'agent_privilege_helper_degraded',
+ severity: 'warning',
+ message:
+ 'The typed privilege helper is degraded; affected privileged telemetry was omitted without widening collector privilege.',
+ evidence: [
+ 'Module: typed-privilege-helper',
+ 'Module state: degraded',
+ 'Last error: smart.snapshot: helper unavailable',
+ ],
+ },
+ ],
+ repairActions: [],
+ }),
+ ],
+ diagnosticsAvailable: true,
+ targetVersion: '6.2.0',
+ });
+
+ expect(target).toMatchObject({
+ source: 'diagnostics',
+ status: 'warning',
+ reasons: [expect.objectContaining({ code: 'agent_privilege_helper_degraded' })],
+ });
+ expect(target.evidence).toContain('Module state: degraded');
+ expect(formatInfrastructureAgentDoctorReport([target])).toContain(
+ 'affected privileged telemetry was omitted without widening collector privilege',
+ );
+ });
+
it('shows local command authority separately from credential execution authority', () => {
const connection = connectionFixture();
const [target] = collectInfrastructureAgentDoctorTargets({
diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.go
index df98fe49a0..8c7bd5a613 100644
--- a/internal/hostagent/agent.go
+++ b/internal/hostagent/agent.go
@@ -192,6 +192,7 @@ type Agent struct {
commandAuthorityWarningSeen bool
collector SystemCollector
privilegedTelemetry PrivilegedTelemetry
+ privilegeHelperHealth *privilegeHelperStatus
newCommandClient func(Config, string, string, string, string) *CommandClient
runCommandClient func(*CommandClient, context.Context) error
packageUpdates *packageUpdateManager
@@ -423,6 +424,10 @@ func New(cfg Config) (*Agent, error) {
packageUpdates, storageCleanup = configurePackageManagers(platform, packageUpdates, storageCleanup)
cfg.packageUpdates = packageUpdates
cfg.storageCleanup = storageCleanup
+ var privilegeHelperHealth *privilegeHelperStatus
+ if cfg.PrivilegedTelemetry != nil {
+ privilegeHelperHealth = newPrivilegeHelperStatus()
+ }
agent := &Agent{
cfg: cfg,
@@ -449,6 +454,7 @@ func New(cfg Config) (*Agent, error) {
observerReporters: observerReporters,
collector: collector,
privilegedTelemetry: cfg.PrivilegedTelemetry,
+ privilegeHelperHealth: privilegeHelperHealth,
newCommandClient: newCommandClientFn,
runCommandClient: runCommandClientFn,
commandAuthorityProfile: commandAuthorityProfile,
@@ -728,6 +734,9 @@ func (a *Agent) currentModuleStatus() []agentshost.ModuleStatus {
if a.cfg.ModuleStatus != nil {
statuses = append(statuses, a.cfg.ModuleStatus()...)
}
+ if a.privilegeHelperHealth != nil {
+ statuses = append(statuses, a.privilegeHelperHealth.moduleStatus())
+ }
// The probe module is owned by the host agent rather than the runtime
// supervisor, so it reports itself and only while it has work assigned.
if status, ok := a.availability.moduleStatus(); ok {
@@ -2222,6 +2231,7 @@ func (a *Agent) collectSMARTData(ctx context.Context, diskExclude []string, unra
var err error
if a.privilegedTelemetry != nil {
smartData, err = a.privilegedTelemetry.SMARTSnapshot(ctx)
+ a.recordPrivilegeHelperOperation(privilegeHelperOperationSMART, err)
if err == nil && len(diskExclude) > 0 {
filtered := smartData[:0]
for _, disk := range smartData {
diff --git a/internal/hostagent/privilege_helper_client.go b/internal/hostagent/privilege_helper_client.go
index 6fd5e1d689..803d35f9c4 100644
--- a/internal/hostagent/privilege_helper_client.go
+++ b/internal/hostagent/privilege_helper_client.go
@@ -12,6 +12,8 @@ import (
const privilegeHelperOperationDeadline = 30 * time.Second
+var errPrivilegeHelperProxmoxInventoryUnavailable = errors.New("helper returned no Proxmox LXC filesystem inventory")
+
// PrivilegedTelemetry is the collector-side view of the no-network helper.
// It intentionally exposes complete typed snapshots rather than commands,
// executable paths, VMIDs, device paths, or caller-selected arguments.
@@ -101,7 +103,7 @@ func (c *privilegeHelperTelemetry) ProxmoxLXCFilesystems(ctx context.Context) (*
return nil, err
}
if response.Inventory == nil {
- return nil, errors.New("helper returned no Proxmox LXC filesystem inventory")
+ return nil, errPrivilegeHelperProxmoxInventoryUnavailable
}
return response.Inventory, nil
}
@@ -115,9 +117,28 @@ func (a *Agent) collectProxmoxLXCFilesystemsForReport(ctx context.Context) *agen
return a.collectProxmoxLXCFilesystems(ctx)
}
inventory, err := a.privilegedTelemetry.ProxmoxLXCFilesystems(ctx)
+ if errors.Is(err, errPrivilegeHelperProxmoxInventoryUnavailable) && !a.expectsProxmoxLXCFilesystems() {
+ a.recordPrivilegeHelperOperation(privilegeHelperOperationProxmoxFilesystems, nil)
+ return nil
+ }
+ a.recordPrivilegeHelperOperation(privilegeHelperOperationProxmoxFilesystems, err)
if err != nil {
a.logger.Debug().Err(err).Msg("Typed helper could not collect Proxmox LXC filesystems")
return nil
}
return inventory
}
+
+func (a *Agent) expectsProxmoxLXCFilesystems() bool {
+ if a == nil {
+ return false
+ }
+ if a.cfg.EnableProxmox {
+ return true
+ }
+ if a.collector == nil || a.collector.GOOS() != "linux" {
+ return false
+ }
+ _, err := resolvePctPath(a.collector.LookPath)
+ return err == nil
+}
diff --git a/internal/hostagent/privilege_helper_client_test.go b/internal/hostagent/privilege_helper_client_test.go
index 81eb80ad73..5557a6e8de 100644
--- a/internal/hostagent/privilege_helper_client_test.go
+++ b/internal/hostagent/privilege_helper_client_test.go
@@ -9,6 +9,8 @@ import (
"net"
"os/exec"
"path/filepath"
+ "strings"
+ "sync"
"testing"
"time"
@@ -171,12 +173,12 @@ func TestCollectSMARTDataDoesNotWidenPrivilegeAfterHelperFailure(t *testing.T) {
return []DiskSMART{{Device: "/dev/fallback"}}, nil
},
}
+ helper := &fakePrivilegedTelemetry{smartErr: errors.New("helper unavailable")}
agent := &Agent{
- collector: collector,
- privilegedTelemetry: &fakePrivilegedTelemetry{
- smartErr: errors.New("helper unavailable"),
- },
- logger: zerolog.Nop(),
+ collector: collector,
+ privilegedTelemetry: helper,
+ privilegeHelperHealth: newPrivilegeHelperStatus(),
+ logger: zerolog.Nop(),
}
if got := agent.collectSMARTData(context.Background(), nil, nil); got != nil {
@@ -185,6 +187,19 @@ func TestCollectSMARTDataDoesNotWidenPrivilegeAfterHelperFailure(t *testing.T) {
if localCalls != 0 {
t.Fatalf("local SMART fallback calls = %d, want 0", localCalls)
}
+ status := requirePrivilegeHelperModuleStatus(t, agent.currentModuleStatus())
+ if status.State != "degraded" || !strings.Contains(status.LastError, privilegeHelperOperationSMART) {
+ t.Fatalf("helper status after SMART failure = %+v", status)
+ }
+
+ helper.smartErr = nil
+ if got := agent.collectSMARTData(context.Background(), nil, nil); got != nil {
+ t.Fatalf("empty SMART recovery result = %+v, want nil", got)
+ }
+ status = requirePrivilegeHelperModuleStatus(t, agent.currentModuleStatus())
+ if status.State != "running" || status.LastError != "" {
+ t.Fatalf("helper status after SMART recovery = %+v", status)
+ }
}
func TestCollectProxmoxLXCFilesystemsDoesNotWidenPrivilegeAfterHelperFailure(t *testing.T) {
@@ -198,9 +213,11 @@ func TestCollectProxmoxLXCFilesystemsDoesNotWidenPrivilegeAfterHelperFailure(t *
}
helper := &fakePrivilegedTelemetry{proxmoxErr: errors.New("helper unavailable")}
agent := &Agent{
- collector: collector,
- privilegedTelemetry: helper,
- logger: zerolog.Nop(),
+ cfg: Config{EnableProxmox: true},
+ collector: collector,
+ privilegedTelemetry: helper,
+ privilegeHelperHealth: newPrivilegeHelperStatus(),
+ logger: zerolog.Nop(),
}
if got := agent.collectProxmoxLXCFilesystemsForReport(context.Background()); got != nil {
@@ -212,4 +229,158 @@ func TestCollectProxmoxLXCFilesystemsDoesNotWidenPrivilegeAfterHelperFailure(t *
if localCalls != 0 {
t.Fatalf("local Proxmox fallback calls = %d, want 0", localCalls)
}
+ status := requirePrivilegeHelperModuleStatus(t, agent.currentModuleStatus())
+ if status.State != "degraded" || !strings.Contains(status.LastError, privilegeHelperOperationProxmoxFilesystems) {
+ t.Fatalf("helper status after Proxmox failure = %+v", status)
+ }
+}
+
+func TestCollectProxmoxLXCFilesystemsDoesNotDegradeNonProxmoxHost(t *testing.T) {
+ lookups := 0
+ collector := &mockCollector{
+ goos: "linux",
+ lookPathFn: func(string) (string, error) {
+ lookups++
+ return "", exec.ErrNotFound
+ },
+ }
+ helper := &fakePrivilegedTelemetry{proxmoxErr: errPrivilegeHelperProxmoxInventoryUnavailable}
+ agent := &Agent{
+ collector: collector,
+ privilegedTelemetry: helper,
+ privilegeHelperHealth: newPrivilegeHelperStatus(),
+ logger: zerolog.Nop(),
+ }
+
+ if got := agent.collectProxmoxLXCFilesystemsForReport(context.Background()); got != nil {
+ t.Fatalf("non-Proxmox inventory = %+v, want nil", got)
+ }
+ if helper.proxmoxCalls != 1 || lookups != 1 {
+ t.Fatalf("helper calls = %d lookups = %d, want 1 each", helper.proxmoxCalls, lookups)
+ }
+ status := requirePrivilegeHelperModuleStatus(t, agent.currentModuleStatus())
+ if status.State != "running" || status.LastError != "" {
+ t.Fatalf("non-Proxmox helper status = %+v", status)
+ }
+}
+
+func TestCollectProxmoxLXCFilesystemsDegradesWhenConfiguredProviderReturnsNoInventory(t *testing.T) {
+ agent := &Agent{
+ cfg: Config{EnableProxmox: true},
+ collector: &mockCollector{goos: "linux"},
+ privilegedTelemetry: &fakePrivilegedTelemetry{proxmoxErr: errPrivilegeHelperProxmoxInventoryUnavailable},
+ privilegeHelperHealth: newPrivilegeHelperStatus(),
+ logger: zerolog.Nop(),
+ }
+
+ if got := agent.collectProxmoxLXCFilesystemsForReport(context.Background()); got != nil {
+ t.Fatalf("configured Proxmox inventory = %+v, want nil", got)
+ }
+ status := requirePrivilegeHelperModuleStatus(t, agent.currentModuleStatus())
+ if status.State != "degraded" || !strings.Contains(status.LastError, "no Proxmox LXC filesystem inventory") {
+ t.Fatalf("configured Proxmox helper status = %+v", status)
+ }
+}
+
+func TestPrivilegeHelperStatusTracksIndependentOperationsAndRecovery(t *testing.T) {
+ status := newPrivilegeHelperStatus()
+ fixed := time.Date(2026, 8, 31, 11, 30, 0, 0, time.UTC)
+ status.now = func() time.Time { return fixed }
+
+ status.record(privilegeHelperOperationProxmoxFilesystems, errors.New("inventory unavailable"))
+ status.record(privilegeHelperOperationSMART, errors.New("smart unavailable"))
+ module := status.moduleStatus()
+ if module.Name != agentshost.ModuleNameTypedPrivilegeHelper || module.State != "degraded" || !module.Enabled {
+ t.Fatalf("degraded helper module = %+v", module)
+ }
+ if !strings.Contains(module.LastError, "proxmox.lxc_filesystems: helper operation failed") ||
+ !strings.Contains(module.LastError, "smart.snapshot: helper operation failed") {
+ t.Fatalf("aggregated helper failure = %q", module.LastError)
+ }
+ if module.UpdatedAt != fixed {
+ t.Fatalf("updatedAt = %v, want %v", module.UpdatedAt, fixed)
+ }
+
+ status.record(privilegeHelperOperationSMART, nil)
+ module = status.moduleStatus()
+ if module.State != "degraded" || strings.Contains(module.LastError, privilegeHelperOperationSMART) ||
+ !strings.Contains(module.LastError, privilegeHelperOperationProxmoxFilesystems) {
+ t.Fatalf("partial helper recovery = %+v", module)
+ }
+
+ status.record(privilegeHelperOperationProxmoxFilesystems, nil)
+ module = status.moduleStatus()
+ if module.State != "running" || module.LastError != "" {
+ t.Fatalf("complete helper recovery = %+v", module)
+ }
+}
+
+func TestPrivilegeHelperStatusNeverPersistsRawErrorDetails(t *testing.T) {
+ status := newPrivilegeHelperStatus()
+ status.record(
+ privilegeHelperOperationSMART,
+ errors.New("request failed token=must-not-leak path=/private/helper.sock"),
+ )
+ status.record(privilegeHelperOperationProxmoxFilesystems, &agenthelper.RemoteError{
+ Code: agenthelper.ErrorProviderUnavailable,
+ Message: "provider failed bearer=remote-secret path=/root/private",
+ RequestID: "secret-request-id",
+ })
+
+ module := status.moduleStatus()
+ if module.State != "degraded" || !strings.Contains(module.LastError, "helper operation failed") {
+ t.Fatalf("classified helper status = %+v", module)
+ }
+ serialized, err := json.Marshal(module)
+ if err != nil {
+ t.Fatalf("marshal module status: %v", err)
+ }
+ for _, secret := range []string{
+ "must-not-leak",
+ "/private/helper.sock",
+ "token=",
+ "remote-secret",
+ "/root/private",
+ "secret-request-id",
+ } {
+ if strings.Contains(string(serialized), secret) {
+ t.Fatalf("raw helper error detail %q reached serialized report state: %s", secret, serialized)
+ }
+ }
+}
+
+func TestPrivilegeHelperStatusConcurrentRecordAndSnapshot(t *testing.T) {
+ status := newPrivilegeHelperStatus()
+ var group sync.WaitGroup
+ for i := 0; i < 32; i++ {
+ group.Add(2)
+ go func(iteration int) {
+ defer group.Done()
+ if iteration%2 == 0 {
+ status.record(privilegeHelperOperationSMART, errors.New("temporary failure"))
+ return
+ }
+ status.record(privilegeHelperOperationSMART, nil)
+ }(i)
+ go func() {
+ defer group.Done()
+ _ = status.moduleStatus()
+ }()
+ }
+ group.Wait()
+ module := status.moduleStatus()
+ if module.State != "running" && module.State != "degraded" {
+ t.Fatalf("concurrent helper state = %+v", module)
+ }
+}
+
+func requirePrivilegeHelperModuleStatus(t *testing.T, statuses []agentshost.ModuleStatus) agentshost.ModuleStatus {
+ t.Helper()
+ for _, status := range statuses {
+ if status.Name == agentshost.ModuleNameTypedPrivilegeHelper {
+ return status
+ }
+ }
+ t.Fatalf("typed privilege helper module missing from %+v", statuses)
+ return agentshost.ModuleStatus{}
}
diff --git a/internal/hostagent/privilege_helper_status.go b/internal/hostagent/privilege_helper_status.go
new file mode 100644
index 0000000000..7f31ac64c0
--- /dev/null
+++ b/internal/hostagent/privilege_helper_status.go
@@ -0,0 +1,125 @@
+package hostagent
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agenthelper"
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
+)
+
+type privilegeHelperStatus struct {
+ mu sync.RWMutex
+ failures map[string]string
+ updatedAt time.Time
+ now func() time.Time
+}
+
+func newPrivilegeHelperStatus() *privilegeHelperStatus {
+ status := &privilegeHelperStatus{
+ failures: make(map[string]string),
+ now: func() time.Time { return time.Now().UTC() },
+ }
+ status.updatedAt = status.now()
+ return status
+}
+
+func (s *privilegeHelperStatus) record(operation string, err error) {
+ if s == nil {
+ return
+ }
+ operation = strings.TrimSpace(operation)
+ if operation == "" {
+ return
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if err == nil {
+ delete(s.failures, operation)
+ } else {
+ s.failures[operation] = classifiedPrivilegeHelperStatusError(err)
+ }
+ s.updatedAt = s.now().UTC()
+}
+
+func (s *privilegeHelperStatus) moduleStatus() agentshost.ModuleStatus {
+ if s == nil {
+ return agentshost.ModuleStatus{}
+ }
+
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ status := agentshost.ModuleStatus{
+ Name: agentshost.ModuleNameTypedPrivilegeHelper,
+ Enabled: true,
+ State: "running",
+ UpdatedAt: s.updatedAt,
+ }
+ if len(s.failures) == 0 {
+ return status
+ }
+
+ operations := make([]string, 0, len(s.failures))
+ for operation := range s.failures {
+ operations = append(operations, operation)
+ }
+ sort.Strings(operations)
+ failures := make([]string, 0, len(operations))
+ for _, operation := range operations {
+ failures = append(failures, fmt.Sprintf("%s: %s", operation, s.failures[operation]))
+ }
+ status.State = "degraded"
+ status.LastError = strings.Join(failures, "; ")
+ return status
+}
+
+func classifiedPrivilegeHelperStatusError(err error) string {
+ if err == nil {
+ return ""
+ }
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
+ return "helper operation deadline exceeded"
+ }
+ if errors.Is(err, errPrivilegeHelperProxmoxInventoryUnavailable) {
+ return "helper returned no Proxmox LXC filesystem inventory"
+ }
+ var remote *agenthelper.RemoteError
+ if errors.As(err, &remote) {
+ switch remote.Code {
+ case agenthelper.ErrorProviderUnavailable:
+ return "helper provider unavailable"
+ case agenthelper.ErrorDeadlineExceeded:
+ return "helper operation deadline exceeded"
+ case agenthelper.ErrorArtifactInvalid:
+ return "helper rejected an invalid artifact"
+ case agenthelper.ErrorStateConflict:
+ return "helper operation state conflict"
+ default:
+ return "helper operation failed"
+ }
+ }
+ var networkError net.Error
+ if errors.As(err, &networkError) {
+ return "helper transport unavailable"
+ }
+ return "helper operation failed"
+}
+
+func (a *Agent) recordPrivilegeHelperOperation(operation string, err error) {
+ if a == nil || a.privilegeHelperHealth == nil {
+ return
+ }
+ a.privilegeHelperHealth.record(operation, err)
+}
+
+const (
+ privilegeHelperOperationSMART = agenthelper.OperationSMARTSnapshot
+ privilegeHelperOperationProxmoxFilesystems = agenthelper.OperationProxmoxLXCFilesystems
+)
diff --git a/internal/hostagent/proxmox_lxc_filesystems.go b/internal/hostagent/proxmox_lxc_filesystems.go
index f04f867141..a1e3eaa112 100644
--- a/internal/hostagent/proxmox_lxc_filesystems.go
+++ b/internal/hostagent/proxmox_lxc_filesystems.go
@@ -56,6 +56,18 @@ type proxmoxLXCRunningContainer struct {
Name string
}
+// ProxmoxLXCFilesystemCollectionResult describes applicability separately from
+// collection health without changing the helper protocol-v1 response shape.
+// A degraded result may retain a partial inventory for local diagnostics, but
+// the privileged helper fails the typed operation so the collector cannot
+// mistake a partial snapshot for a complete one.
+type ProxmoxLXCFilesystemCollectionResult struct {
+ Applicable bool
+ Inventory *agentshost.ProxmoxLXCInventory
+ Degraded bool
+ FailedContainers int
+}
+
// hostFilesystemUsage carries statfs-derived usage for one path plus the
// st_dev identity needed to tell a real mount from its parent filesystem.
type hostFilesystemUsage struct {
@@ -82,12 +94,19 @@ type proxmoxLXCConfigMount struct {
// the root-only typed helper, whose caller cannot supply VMIDs, paths, command
// names, or arguments.
func CollectProxmoxLXCFilesystemsLocal(ctx context.Context) *agentshost.ProxmoxLXCInventory {
+ return CollectProxmoxLXCFilesystemsLocalResult(ctx).Inventory
+}
+
+// CollectProxmoxLXCFilesystemsLocalResult exposes applicability and completeness
+// to the fixed local helper provider. It never accepts caller-selected VMIDs,
+// paths, executables, or command arguments.
+func CollectProxmoxLXCFilesystemsLocalResult(ctx context.Context) ProxmoxLXCFilesystemCollectionResult {
logger := zerolog.Nop()
agent := &Agent{
collector: NewDefaultCollector(),
logger: logger,
}
- return agent.collectProxmoxLXCFilesystems(ctx)
+ return agent.collectProxmoxLXCFilesystemsResult(ctx)
}
// collectProxmoxLXCFilesystems auto-detects the local Proxmox Container
@@ -104,16 +123,24 @@ func CollectProxmoxLXCFilesystemsLocal(ctx context.Context) *agentshost.ProxmoxL
// container gets its own deadline so one slow guest cannot consume the whole
// collection window.
func (a *Agent) collectProxmoxLXCFilesystems(ctx context.Context) *agentshost.ProxmoxLXCInventory {
+ return a.collectProxmoxLXCFilesystemsResult(ctx).Inventory
+}
+
+func (a *Agent) collectProxmoxLXCFilesystemsResult(ctx context.Context) ProxmoxLXCFilesystemCollectionResult {
+ result := ProxmoxLXCFilesystemCollectionResult{}
if a.collector.GOOS() != "linux" {
- return nil
+ return result
}
pctPath, err := resolvePctPath(a.collector.LookPath)
if err != nil {
if !errors.Is(err, exec.ErrNotFound) && !os.IsNotExist(err) {
a.logger.Debug().Err(err).Msg("Failed to locate pct for Proxmox LXC filesystems")
+ result.Applicable = true
+ result.Degraded = true
}
- return nil
+ return result
}
+ result.Applicable = true
listCtx, cancelList := context.WithTimeout(ctx, proxmoxLXCQueryTimeout)
listOutput, err := collectCommandOutputLimited(
@@ -126,12 +153,14 @@ func (a *Agent) collectProxmoxLXCFilesystems(ctx context.Context) *agentshost.Pr
cancelList()
if err != nil {
a.logger.Debug().Err(err).Msg("Failed to list local Proxmox LXC containers")
- return nil
+ result.Degraded = true
+ return result
}
containers, err := parseProxmoxLXCRunningContainers(listOutput)
if err != nil {
a.logger.Debug().Err(err).Msg("Failed to parse local Proxmox LXC container list")
- return nil
+ result.Degraded = true
+ return result
}
prober, _ := a.collector.(filesystemUsageProber)
@@ -145,36 +174,37 @@ func (a *Agent) collectProxmoxLXCFilesystems(ctx context.Context) *agentshost.Pr
collectionCtx, cancelCollection := context.WithTimeout(ctx, proxmoxLXCCollectionTimeout)
defer cancelCollection()
- inventory := &agentshost.ProxmoxLXCInventory{
+ result.Inventory = &agentshost.ProxmoxLXCInventory{
Containers: []agentshost.ProxmoxLXCContainer{},
CollectedAt: a.collector.Now().UTC(),
}
- skipped := 0
for _, container := range containers {
if collectionCtx.Err() != nil {
- skipped++
+ result.FailedContainers++
continue
}
containerCtx, cancelContainer := context.WithTimeout(collectionCtx, proxmoxLXCContainerQueryTimeout)
- disks := a.collectProxmoxLXCContainerDisks(containerCtx, prober, lxcInfoPath, pctPath, container.VMID)
+ disks, collectionErr := a.collectProxmoxLXCContainerDisks(containerCtx, prober, lxcInfoPath, pctPath, container.VMID)
cancelContainer()
- if len(disks) == 0 {
+ if collectionErr != nil {
+ result.FailedContainers++
continue
}
- inventory.Containers = append(inventory.Containers, agentshost.ProxmoxLXCContainer{
+ result.Inventory.Containers = append(result.Inventory.Containers, agentshost.ProxmoxLXCContainer{
VMID: container.VMID,
Name: container.Name,
Disks: disks,
})
}
- if skipped > 0 {
+ if result.FailedContainers > 0 {
+ result.Degraded = true
a.logger.Warn().
- Int("collected", len(inventory.Containers)).
- Int("skipped", skipped).
- Msg("Proxmox LXC filesystem collection budget exhausted before all running containers were queried")
+ Int("collected", len(result.Inventory.Containers)).
+ Int("failed", result.FailedContainers).
+ Msg("Proxmox LXC filesystem collection omitted one or more running containers")
}
- return inventory
+ return result
}
func (a *Agent) collectProxmoxLXCContainerDisks(
@@ -183,11 +213,11 @@ func (a *Agent) collectProxmoxLXCContainerDisks(
lxcInfoPath string,
pctPath string,
vmid int,
-) []agentshost.Disk {
+) ([]agentshost.Disk, error) {
if prober != nil && lxcInfoPath != "" {
disks, fastErr := a.collectProxmoxLXCContainerDisksFast(ctx, prober, lxcInfoPath, vmid)
if fastErr == nil {
- return disks
+ return disks, nil
}
a.logger.Debug().
Err(fastErr).
@@ -208,7 +238,7 @@ func (a *Agent) collectProxmoxLXCContainerDisks(
Err(outputErr).
Int("vmid", vmid).
Msg("Failed to collect Proxmox LXC filesystem usage")
- return nil
+ return nil, errors.New("pct df collection failed")
}
disks, parseErr := parseProxmoxLXCDF(output)
if parseErr != nil || len(disks) == 0 {
@@ -216,9 +246,9 @@ func (a *Agent) collectProxmoxLXCContainerDisks(
Err(parseErr).
Int("vmid", vmid).
Msg("Failed to parse Proxmox LXC filesystem usage")
- return nil
+ return nil, errors.New("pct df result contained no usable filesystems")
}
- return disks
+ return disks, nil
}
// collectProxmoxLXCContainerDisksFast reads the container's config-declared
@@ -270,12 +300,18 @@ func (a *Agent) collectProxmoxLXCContainerDisksFast(
}
target := path.Join(procRoot, mount.Path)
usage, usageErr := prober.FilesystemUsage(target)
- if usageErr != nil || usage.TotalBytes <= 0 {
- continue
+ if usageErr != nil {
+ return nil, fmt.Errorf("probe %s filesystem usage: %w", mount.Key, usageErr)
+ }
+ if usage.TotalBytes <= 0 {
+ return nil, fmt.Errorf("probe %s filesystem usage: invalid total bytes", mount.Key)
}
if mount.Path != "/" {
parent, parentErr := prober.FilesystemUsage(path.Dir(target))
- if parentErr != nil || parent.Device == usage.Device {
+ if parentErr != nil {
+ return nil, fmt.Errorf("probe %s parent filesystem usage: %w", mount.Key, parentErr)
+ }
+ if parent.Device == usage.Device {
continue
}
}
diff --git a/internal/hostagent/proxmox_lxc_filesystems_test.go b/internal/hostagent/proxmox_lxc_filesystems_test.go
index 2f4e4d61ae..706ea29df2 100644
--- a/internal/hostagent/proxmox_lxc_filesystems_test.go
+++ b/internal/hostagent/proxmox_lxc_filesystems_test.go
@@ -66,10 +66,14 @@ mp0 tank:subvol-100-disk-0 1.0T 512.0G 512.0G 50.0 /srv/data
}
agent := &Agent{logger: zerolog.Nop(), collector: collector}
- got := agent.collectProxmoxLXCFilesystems(context.Background())
+ result := agent.collectProxmoxLXCFilesystemsResult(context.Background())
+ got := result.Inventory
if got == nil || !got.CollectedAt.Equal(now) {
t.Fatalf("inventory = %+v", got)
}
+ if !result.Applicable || !result.Degraded || result.FailedContainers != 1 {
+ t.Fatalf("collection result = %+v, want applicable partial failure", result)
+ }
if len(commands) != 3 {
t.Fatalf("commands = %v, want list plus two running df queries", commands)
}
@@ -96,6 +100,34 @@ mp0 tank:subvol-100-disk-0 1.0T 512.0G 512.0G 50.0 /srv/data
}
}
+func TestCollectProxmoxLXCFilesystemsReportsTotalContainerFailure(t *testing.T) {
+ const pctPath = "/usr/sbin/pct"
+ listOutput := "VMID Status Lock Name\n100 running - web\n102 running - database\n"
+ collector := &mockCollector{
+ goos: "linux",
+ lookPathFn: func(file string) (string, error) {
+ if file == "pct" {
+ return pctPath, nil
+ }
+ return "", os.ErrNotExist
+ },
+ commandCombinedOutputLimitedFn: func(_ context.Context, _ int, _ string, args ...string) (string, error) {
+ if strings.Join(args, " ") == "list" {
+ return listOutput, nil
+ }
+ return "", errors.New("pct df unavailable")
+ },
+ }
+
+ result := (&Agent{logger: zerolog.Nop(), collector: collector}).collectProxmoxLXCFilesystemsResult(t.Context())
+ if !result.Applicable || !result.Degraded || result.FailedContainers != 2 {
+ t.Fatalf("collection result = %+v, want two failed containers", result)
+ }
+ if result.Inventory == nil || len(result.Inventory.Containers) != 0 {
+ t.Fatalf("partial inventory = %+v, want empty retained inventory", result.Inventory)
+ }
+}
+
// Regression for the #1477 follow-up: pct df costs over a second per guest,
// so serial pct df inside one shared budget starved every container after the
// first handful. With a resolvable init PID the collector must answer from
@@ -278,6 +310,83 @@ rootfs local-lvm:vm-102-disk-0 8.0G 2.0G 6.0G 25.0 /
}
}
+func TestCollectProxmoxLXCFilesystemsFallsBackAfterPartialStatfsFailure(t *testing.T) {
+ const pctPath = "/usr/sbin/pct"
+ const lxcInfoPath = "/usr/bin/lxc-info"
+ const listOutput = "VMID Status Lock Name\n100 running - web\n"
+ const dfOutput = `MP Volume Size Used Avail Use% Path
+rootfs local-lvm:vm-100-disk-0 8.0G 2.0G 6.0G 25.0 /
+mp0 tank:subvol-100-disk-0 1.0T 512.0G 512.0G 50.0 /srv/data
+`
+
+ for _, test := range []struct {
+ name string
+ fallbackError error
+ wantDegraded bool
+ wantContainerLen int
+ }{
+ {name: "complete fallback recovers", wantContainerLen: 1},
+ {name: "failed fallback degrades container", fallbackError: errors.New("pct df unavailable"), wantDegraded: true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ dfCalls := 0
+ collector := &mockCollector{
+ goos: "linux",
+ lookPathFn: func(file string) (string, error) {
+ switch file {
+ case "pct":
+ return pctPath, nil
+ case "lxc-info":
+ return lxcInfoPath, nil
+ default:
+ return "", os.ErrNotExist
+ }
+ },
+ readFileFn: func(string) ([]byte, error) {
+ return []byte("rootfs: local-lvm:vm-100-disk-0,size=8G\nmp0: tank:subvol-100-disk-0,mp=/srv/data,size=1T\n"), nil
+ },
+ filesystemUsageFn: func(target string) (hostFilesystemUsage, error) {
+ switch target {
+ case "/proc/4242/root":
+ return hostFilesystemUsage{TotalBytes: 8 << 30, UsedBytes: 2 << 30, AvailBytes: 6 << 30, Device: 11}, nil
+ case "/proc/4242/root/srv/data":
+ return hostFilesystemUsage{}, errors.New("statfs access failed")
+ default:
+ t.Fatalf("unexpected statfs path %q", target)
+ return hostFilesystemUsage{}, nil
+ }
+ },
+ commandCombinedOutputLimitedFn: func(_ context.Context, _ int, name string, args ...string) (string, error) {
+ joined := strings.Join(args, " ")
+ switch {
+ case name == pctPath && joined == "list":
+ return listOutput, nil
+ case name == lxcInfoPath && joined == "-n 100 -p":
+ return "PID: 4242\n", nil
+ case name == pctPath && joined == "df 100":
+ dfCalls++
+ return dfOutput, test.fallbackError
+ default:
+ t.Fatalf("unexpected command: %s %v", name, args)
+ return "", nil
+ }
+ },
+ }
+
+ result := (&Agent{logger: zerolog.Nop(), collector: collector}).collectProxmoxLXCFilesystemsResult(t.Context())
+ if dfCalls != 1 {
+ t.Fatalf("pct df calls = %d, want 1 after partial statfs failure", dfCalls)
+ }
+ if result.Degraded != test.wantDegraded || result.Inventory == nil || len(result.Inventory.Containers) != test.wantContainerLen {
+ t.Fatalf("collection result = %+v", result)
+ }
+ if test.wantDegraded && result.FailedContainers != 1 {
+ t.Fatalf("failed containers = %d, want 1", result.FailedContainers)
+ }
+ })
+ }
+}
+
func TestParseProxmoxLXCConfigMountsStopsAtSectionsAndValidates(t *testing.T) {
mounts := parseProxmoxLXCConfigMounts(`# comment
arch: amd64
diff --git a/internal/monitoring/agent_fleet_doctor.go b/internal/monitoring/agent_fleet_doctor.go
index 3b5a308870..1655647d54 100644
--- a/internal/monitoring/agent_fleet_doctor.go
+++ b/internal/monitoring/agent_fleet_doctor.go
@@ -17,6 +17,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/platformsupport"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/internal/updates"
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/rs/zerolog/log"
)
@@ -29,20 +30,21 @@ const (
AgentFleetStatusCritical = "critical"
AgentFleetStatusRemoved = "removed"
- AgentFleetReasonUpdateDisabled = "agent_update_disabled"
- AgentFleetReasonUpdateFailed = "agent_update_failed"
- AgentFleetReasonUpdateStateUnknown = "agent_update_state_unknown"
- AgentFleetReasonUpdatePlatformUnknown = "agent_update_platform_unknown"
- AgentFleetReasonUpdateStateUnverified = "agent_update_installer_state_unverified"
- AgentFleetReasonModuleFailed = "agent_module_failed"
- AgentFleetReasonModuleDegraded = "agent_module_degraded"
- AgentFleetReasonCredentialMissing = "agent_credential_missing"
- AgentFleetReasonCredentialExpired = "agent_credential_expired"
- AgentFleetReasonCredentialUnlisted = "agent_credential_registry_stale"
- AgentFleetReasonExecScopeMissing = "agent_exec_scope_missing"
- AgentFleetReasonExecScopeExcess = "agent_exec_scope_excess"
- AgentFleetReasonCredentialScopeExcess = "agent_credential_scope_excess"
- AgentFleetReasonDuplicateInstallation = "duplicate_host_agent_installation"
+ AgentFleetReasonUpdateDisabled = "agent_update_disabled"
+ AgentFleetReasonUpdateFailed = "agent_update_failed"
+ AgentFleetReasonUpdateStateUnknown = "agent_update_state_unknown"
+ AgentFleetReasonUpdatePlatformUnknown = "agent_update_platform_unknown"
+ AgentFleetReasonUpdateStateUnverified = "agent_update_installer_state_unverified"
+ AgentFleetReasonModuleFailed = "agent_module_failed"
+ AgentFleetReasonModuleDegraded = "agent_module_degraded"
+ AgentFleetReasonPrivilegeHelperDegraded = "agent_privilege_helper_degraded"
+ AgentFleetReasonCredentialMissing = "agent_credential_missing"
+ AgentFleetReasonCredentialExpired = "agent_credential_expired"
+ AgentFleetReasonCredentialUnlisted = "agent_credential_registry_stale"
+ AgentFleetReasonExecScopeMissing = "agent_exec_scope_missing"
+ AgentFleetReasonExecScopeExcess = "agent_exec_scope_excess"
+ AgentFleetReasonCredentialScopeExcess = "agent_credential_scope_excess"
+ AgentFleetReasonDuplicateInstallation = "duplicate_host_agent_installation"
AgentFleetActionAllowReenroll = "allow_reenroll"
AgentFleetActionCopyUpgradeCommand = "copy_upgrade_command"
@@ -884,17 +886,26 @@ func diagnoseAgentModules(subject agentFleetSubject) []AgentFleetDiagnosticReaso
if !module.Enabled {
continue
}
+ name := strings.TrimSpace(module.Name)
state := strings.ToLower(strings.TrimSpace(module.State))
if state == "running" {
continue
}
severity := AgentFleetStatusWarning
code := AgentFleetReasonModuleDegraded
- message := fmt.Sprintf("Enabled agent module %q is not running.", strings.TrimSpace(module.Name))
+ message := fmt.Sprintf("Enabled agent module %q is not running.", name)
+ if name == agentshost.ModuleNameTypedPrivilegeHelper {
+ code = AgentFleetReasonPrivilegeHelperDegraded
+ message = "The typed privilege helper is degraded; affected privileged telemetry was omitted without widening collector privilege."
+ }
if state == "error" || state == "failed" {
severity = AgentFleetStatusCritical
code = AgentFleetReasonModuleFailed
- message = fmt.Sprintf("Enabled agent module %q failed.", strings.TrimSpace(module.Name))
+ message = fmt.Sprintf("Enabled agent module %q failed.", name)
+ if name == agentshost.ModuleNameTypedPrivilegeHelper {
+ code = AgentFleetReasonPrivilegeHelperDegraded
+ message = "The typed privilege helper failed; privileged telemetry is unavailable without widening collector privilege."
+ }
}
reasons = append(reasons, AgentFleetDiagnosticReason{
Code: code,
diff --git a/internal/monitoring/agent_fleet_doctor_test.go b/internal/monitoring/agent_fleet_doctor_test.go
index 45573c88bc..9fd69e6cc0 100644
--- a/internal/monitoring/agent_fleet_doctor_test.go
+++ b/internal/monitoring/agent_fleet_doctor_test.go
@@ -9,6 +9,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/platformsupport"
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
@@ -453,6 +454,59 @@ func TestAgentFleetDiagnosticsSurfacesReportedUpdateModuleAndIdentityEvidence(t
}
}
+func TestAgentFleetDiagnosticsSurfacesTypedPrivilegeHelperDegradation(t *testing.T) {
+ now := time.Date(2026, 8, 31, 11, 30, 0, 0, time.UTC)
+ monitor := newAgentFleetDoctorTestMonitor(t)
+ monitor.state.UpsertHost(models.Host{
+ ID: "agent-safe-profile",
+ Hostname: "pve-safe",
+ DisplayName: "PVE Safe",
+ Platform: "linux",
+ Status: "online",
+ LastSeen: now.Add(-30 * time.Second),
+ IntervalSeconds: 30,
+ AgentVersion: "6.4.2",
+ AgentModules: []models.AgentModuleStatus{{
+ Name: agentshost.ModuleNameTypedPrivilegeHelper,
+ Enabled: true,
+ State: "degraded",
+ LastError: "smart.snapshot: helper unavailable token=must-not-leak",
+ UpdatedAt: now.Add(-time.Minute),
+ }},
+ })
+
+ diagnostics := monitor.GetAgentFleetDiagnosticsForTarget("6.4.2", "6.4.2", now)
+ agent := requireAgentDiagnostic(t, diagnostics, "agent-agent-safe-profile")
+ requireReasonCode(t, agent, AgentFleetReasonPrivilegeHelperDegraded)
+ if agent.Status != AgentFleetStatusWarning {
+ t.Fatalf("status = %q, want warning", agent.Status)
+ }
+ if len(agent.AgentModules) != 1 || agent.AgentModules[0].Name != agentshost.ModuleNameTypedPrivilegeHelper {
+ t.Fatalf("helper module evidence = %+v", agent.AgentModules)
+ }
+ if strings.Contains(agent.AgentModules[0].LastError, "must-not-leak") {
+ t.Fatalf("helper module error was not redacted: %q", agent.AgentModules[0].LastError)
+ }
+ found := false
+ for _, reason := range agent.Reasons {
+ if reason.Code != AgentFleetReasonPrivilegeHelperDegraded {
+ continue
+ }
+ found = true
+ if !strings.Contains(reason.Message, "omitted without widening collector privilege") {
+ t.Fatalf("helper degradation message = %q", reason.Message)
+ }
+ for _, evidence := range reason.Evidence {
+ if strings.Contains(evidence, "must-not-leak") {
+ t.Fatalf("helper reason evidence was not redacted: %#v", reason.Evidence)
+ }
+ }
+ }
+ if !found {
+ t.Fatalf("helper degradation reason missing from %+v", agent.Reasons)
+ }
+}
+
// A least-privilege install is an intentional hardening profile: the doctor
// must surface the reported privilege descriptively and must not degrade the
// agent's health status on that evidence alone.
diff --git a/pkg/agents/host/report.go b/pkg/agents/host/report.go
index 570fe198b0..ae34b0aea4 100644
--- a/pkg/agents/host/report.go
+++ b/pkg/agents/host/report.go
@@ -199,9 +199,13 @@ type PrivilegeStatus struct {
PctHelper bool `json:"pctHelper,omitempty"`
}
+// ModuleNameTypedPrivilegeHelper is the stable report identity for the local
+// no-network helper's aggregate host-telemetry operation health.
+const ModuleNameTypedPrivilegeHelper = "typed-privilege-helper"
+
// ModuleStatus describes whether an enabled Unified Agent module initialized
-// and is actively running. Errors are deliberately limited to the latest
-// operator-facing initialization failure.
+// and is actively running. Errors are deliberately bounded to the current
+// operator-facing initialization or operation failure.
type ModuleStatus struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
diff --git a/pkg/agents/host/report_test.go b/pkg/agents/host/report_test.go
index d15644571a..df78fa523b 100644
--- a/pkg/agents/host/report_test.go
+++ b/pkg/agents/host/report_test.go
@@ -94,6 +94,38 @@ func TestReport_JSONMarshal(t *testing.T) {
}
}
+func TestTypedPrivilegeHelperModuleStatusRoundTrip(t *testing.T) {
+ updatedAt := time.Date(2026, 8, 31, 12, 0, 0, 0, time.UTC)
+ report := Report{
+ Agent: AgentInfo{
+ Modules: []ModuleStatus{{
+ Name: ModuleNameTypedPrivilegeHelper,
+ Enabled: true,
+ State: "degraded",
+ LastError: "proxmox.lxc_filesystems: helper provider unavailable",
+ UpdatedAt: updatedAt,
+ }},
+ },
+ }
+
+ encoded, err := json.Marshal(report)
+ if err != nil {
+ t.Fatalf("marshal report: %v", err)
+ }
+ var decoded Report
+ if err := json.Unmarshal(encoded, &decoded); err != nil {
+ t.Fatalf("unmarshal report: %v", err)
+ }
+ if len(decoded.Agent.Modules) != 1 {
+ t.Fatalf("modules = %+v", decoded.Agent.Modules)
+ }
+ module := decoded.Agent.Modules[0]
+ if module.Name != ModuleNameTypedPrivilegeHelper || !module.Enabled || module.State != "degraded" ||
+ module.LastError != "proxmox.lxc_filesystems: helper provider unavailable" || !module.UpdatedAt.Equal(updatedAt) {
+ t.Fatalf("typed helper module status = %+v", module)
+ }
+}
+
func TestCustomSensorMetricJSONRoundTrip(t *testing.T) {
value := 7200.0
eventAt := time.Date(2026, 7, 30, 18, 0, 0, 0, time.UTC)