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 safe rootless runtime recovery

rcourtman2aece859a537
diff --git a/docs/AGENT_SECURITY.md b/docs/AGENT_SECURITY.md
index a0e2fd2fb7..feb0772031 100644
--- a/docs/AGENT_SECURITY.md
+++ b/docs/AGENT_SECURITY.md
@@ -257,7 +257,7 @@ or generic command path.
| Linux SMART telemetry | `smart.snapshot` through the no-network helper; no caller-selected device or arguments | Implemented, unqualified on representative physical disks. Helper failure omits/degrades SMART only; the collector does not retry as root | Does not yet justify SMART parity or a default change | `agent-lifecycle`: record live SATA, SAS/controller, USB bridge, and NVMe evidence, including standby, permission failure, timeout, and partial-data cases |
| Proxmox node-local LXC filesystem telemetry | `proxmox.lxc_filesystems` through the no-network helper using fixed bounded `pct` operations | Implemented, unqualified on a representative PVE node. Helper failure omits/degrades this snapshot only | Does not yet justify Proxmox host-agent parity or a default change | `agent-lifecycle`: record live running/stopped LXC, mount, timeout, output-bound, and helper-loss behavior on supported PVE versions |
| Rootful Docker or Podman inventory | No direct collector access to a root-equivalent daemon socket | Implemented as a typed-helper summary-only fallback. Migration preserves container ID/name/image/state/status/creation inventory and marks the report `typed-helper-summary`; stats, secondary inventories, update checks, and actions remain unavailable | Unit and installer regressions cover the boundary, but no representative live Docker/Podman qualification exists. Full rootful parity remains an explicit default blocker; the legacy/root profile is not safe-profile evidence | `agent-lifecycle`: record fresh install, migration, restart, helper loss/recovery, bounds, and summary parity on representative rootful Docker and Podman; decide explicitly whether reduced telemetry is sufficient |
-| Collector-owned rootless Docker or Podman | Direct access only to one usable runtime socket owned by the `pulse-agent` UID | Implemented, unqualified live. Ambiguous, root-owned, unreadable, unwritable, or unavailable sockets disable container monitoring | Does not yet justify container-runtime parity or a default change | `deployment-installability`: record fresh install, migration, restart, socket-loss, ambiguity, and telemetry parity on both rootless Docker and rootless Podman |
+| Collector-owned rootless Docker or Podman | Direct access only to one usable runtime socket owned by the `pulse-agent` UID whose daemon also attests rootless mode | Implemented, unqualified live. Discovery is deferred until the collector account exists and accepts exactly one readable/writable, non-symlink socket owned by that UID across Docker and Podman. Cross-user, root-owned, remote, unreadable, non-rootless-daemon, or ambiguous endpoints are rejected. An installer-owned exact pin survives daemon loss and update; the running collector can move between direct rootless monitoring and rootful typed-helper summary without regaining action authority | Does not yet justify container-runtime parity or a default change | `deployment-installability`: record fresh install, migration, restart, socket-loss, ambiguity, helper/direct recovery, and telemetry parity on both rootless Docker and rootless Podman |
| Separate runner package update and package-cache cleanup | Root-owned `pulse-agent-runner`, host-bound action credential, typed request, postcondition, and durable receipt | The schema-v6 committed-main systemd receipt records a real verified apt-cache mutation, stale-fingerprint refusal, replay, nonce-bound readiness, effective-unit override rejection, exact credential rotation, bodyless self-revocation, and collector/helper continuity. A separate production Router regression exercises HTTPS issuance, WSS admission, encrypted token persistence, failed-rotation rollback, exact socket invalidation, two server restarts, old-secret rejection, and durable self-revoke | Qualified for the exercised systemd fixture paths and focused production Router lifecycle. Focused installer tests also cover atomic pending cancellation and fail-closed credential retention. The evidence does not cover every runner operation, representative providers, or an exact release candidate | `agent-lifecycle` and `api-contracts`: reproduce the combined systemd and production Router path from trusted RC artifacts with representative package-update success/failure/cancellation evidence |
| Separate runner Proxmox guest and container lifecycle/update actions | Root-owned runner with closed typed protocols; never the monitoring collector | Implemented, unqualified on representative PVE and container-runtime targets | No live-provider action-parity claim and no default change | `agent-lifecycle`: record target-bound success, stale-state refusal, cancellation, reconnect/replay, and independent postconditions on disposable real targets |
| Appliance, non-systemd, Windows, and macOS host-agent profiles | Platform API where sufficient; otherwise an explicitly named legacy/full-trust profile | **Unavailable for safe-profile apply.** The installer fails closed instead of silently installing a root-equivalent profile | Excluded from the Linux safe-profile claim | `deployment-installability`: land a platform-specific service, filesystem, update, helper, migration, rollback, and live-proof contract before marking that platform supported |
diff --git a/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md b/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md
index bb3eec5191..959681429b 100644
--- a/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md
+++ b/docs/release-control/v6/internal/AGENT_PRIVILEGE_BOUNDARY_PLAN.md
@@ -251,6 +251,24 @@ proofs are recorded, the safe profile remains opt-in and provider degradation
remains an explicit residual rather than evidence that the candidate lane is
complete.
+Rootless runtime admission is now exact by construction. The installer defers
+safe-profile discovery until the dedicated `pulse-agent` account exists,
+requires the socket owner and read/write subject to match that UID, and treats
+simultaneously usable Docker and Podman sockets as an ambiguity rather than
+silently choosing one. The collector independently rebuilds the same one-live-
+endpoint set before every initial connection or reconnect and never probes a
+candidate whose endpoint fails the rootless-path, ownership, or ambiguity
+checks. It accepts the resulting connection only when daemon metadata also
+attests rootless mode. An exact pin recovered
+from the root-owned service unit survives an update while the socket is absent,
+and the running collector can transition between direct rootless monitoring
+and typed-helper summary fallback without restarting or enabling collector
+actions. Legacy Docker report-response commands, registry update scans, and
+orphan-backup cleanup are disabled statically whenever the helper-backed safe
+profile is configured. This is implementation proof only; the live fresh-install, restart,
+ambiguity, loss, bidirectional recovery, and telemetry-parity matrix remains
+the qualification residual.
+
## Target Architecture
### 1. API-Only Monitoring
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 469fbb7981..5de71de12e 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -78,6 +78,21 @@ boundary is selected, SMART, Proxmox LXC filesystem, and rootful Docker/Podman
container inventory collection fail closed to an omitted/degraded snapshot
when the helper fails; the collector must not silently retry the privileged
read locally or adopt a rootful container-runtime socket.
+Direct rootless runtime admission is a separate exact path. Installer
+discovery runs only after the dedicated collector UID exists, accepts one
+readable/writable socket owned by that UID across Docker and Podman, and treats
+multiple usable sockets as ambiguous. The collector independently reconstructs
+that single live endpoint before its first daemon API request and on reconnect;
+rootful-path, remote, cross-user, missing, and ambiguous endpoints are rejected
+without a daemon request. The selected endpoint's daemon must then attest rootless mode through its
+information response. Exact same-UID environment pins recovered from an
+installer-owned service unit may resolve automatic Docker/Podman ambiguity and
+survive socket downtime; conflicting pins fail closed. The collector retries
+direct admission while using helper summary inventory and falls back to a
+complete helper snapshot after repeated direct-runtime loss, without exposing
+container actions in either safe-profile mode. Static profile gates also reject
+legacy Docker report-response update commands and suppress registry scans and
+orphan-backup cleanup in the collector.
The collector reports that runtime truth as the shared
`typed-privilege-helper` module. SMART, Proxmox, and `container.inventory`
operation failures remain independently active until that exact operation
@@ -3115,7 +3130,7 @@ file path. `TestLoadConfig`, `TestCustomSensorKindsAndHTTPFreshness`, and
`TestCustomSensorMetricJSONRoundTrip` pin CLI plumbing, runtime semantics, and
the additive report wire shape.
-### Rootful Docker outranks rootless socket discovery and runtime labels are truthful
+### Legacy rootful precedence and safe rootless admission are explicit
Installer container-runtime discovery
(`discover_rootless_container_runtime` in `scripts/install.sh`) consults a
@@ -3130,6 +3145,20 @@ socket (socket-activated for root's login session on Debian/OMV) outranked a
healthy rootful Docker and pinned the agent to a socket that vanished with the
session.
+That precedence applies to the legacy/root service only. A typed-helper safe
+profile cannot use the rootful socket directly, so it defers rootless discovery
+until `pulse-agent` has been provisioned, scans Docker and Podman as one
+candidate set, and persists an endpoint only when exactly one socket is owned
+and readable/writable by that collector UID. A socket owned by root or another
+login user is ignored; two usable sockets are an explicit ambiguity. The agent
+repeats the same exact-one admission on startup and reconnect, including the
+standard `/run/user/<uid>/docker.sock` and
+`/run/user/<uid>/podman/podman.sock` paths, before any daemon information probe.
+The information response must independently attest rootless mode; an owned
+socket path proxying a rootful daemon is closed and rejected. A root-owned unit
+that is not group/world-writable can preserve its exact standard-path pin
+through an update even while the socket is offline.
+
On the agent side (`internal/dockeragent/agent.go`), the podman runtime
preference is an ordering hint, not an identity override: `detectRuntime` no
longer short-circuits to podman on preference alone, so a podman-preferred
@@ -7028,8 +7057,14 @@ collector uses this operation only as a summary-only reporting fallback when
direct runtime admission fails; it does not expose update or lifecycle methods,
and reports preserve that reduction as `collectionMode: typed-helper-summary`.
Under the helper profile, direct runtime candidates are admitted by endpoint
-type, collector UID ownership, and rootless runtime path before the first daemon
-API request; rejected candidates are closed without probing daemon information.
+type, collector UID ownership, rootless runtime path, and an exact-one live
+candidate rule before the first daemon API request. Rejected rootful, remote,
+cross-user, missing, conflicting-pin, and ambiguous Docker/Podman candidates
+are never probed. A candidate that passes the filesystem boundary must also
+attest rootless daemon mode. The same admission is rebuilt during daemon
+reconnect; the collector can promote from helper summary to direct rootless
+monitoring or fall back after repeated direct loss, and the safe collector never
+exports container action authority in either mode.
The `agent_update.activate.v1` and `agent_update.rollback.v1` families accept only
fixed-root, regular, owned, digest-bound update artifacts and produce durable
activation identity around an atomic swap. Their collector staging,
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 9562b36a4c..e9e0c9e236 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -238,6 +238,21 @@ socket, the typed helper supplies summary-only container inventory and the
report carries `collectionMode: typed-helper-summary`. Stats, secondary
inventory, update checks, and actions remain unavailable; the safe profile
never restores Docker by adding the collector to a root-equivalent group.
+Safe-profile rootless discovery is deferred until `pulse-agent` exists and
+selects across Docker and Podman as one set. Exactly one live socket must be
+owned and readable/writable by the collector UID before its URI and runtime
+directory enter the service environment. Root-owned, cross-user, unreadable,
+remote, and simultaneously usable Docker/Podman endpoints fail closed; the
+agent repeats this exact-one admission before the first API probe and on every
+reconnect, then requires daemon metadata to attest rootless mode. An exact pin
+is recovered only from the root-owned collector service unit when it is not
+group/world-writable, so
+updates preserve the choice while the socket is offline. The running collector
+can move between direct rootless monitoring and typed-helper summary fallback
+without a restart or collector action authority. Legacy Docker report-response
+commands and autonomous cleanup/update work remain disabled in the safe
+collector even while direct rootless monitoring is active. Legacy/root discovery retains
+its separate rootful-Docker-first behavior for compatibility.
Release builds and archives carry both helper and runner binaries for the five
Linux targets (`amd64`, `arm64`, `armv7`, `armv6`, and `386`) with checksum,
@@ -2016,8 +2031,8 @@ execution, and continues to reject the moving `main` archive. Future release
guidance may advance the pin only after the new exact-version provider asset
and sidecars pass the same publication barrier.
-The shell installer's container-runtime discovery prefers a working rootful
-Docker daemon over any rootless socket (#1647).
+The shell installer's legacy/root container-runtime discovery prefers a working
+rootful Docker daemon over any rootless socket (#1647).
`discover_rootless_container_runtime` in `scripts/install.sh` first calls
`system_docker_runtime_is_active` — a `docker info` check with
`DOCKER_HOST`/`CONTAINER_HOST` stripped, falling back to probing
@@ -2030,6 +2045,18 @@ the agent service environment. This applies to auto-detection and explicit
API socket can no longer capture the agent unit on hosts whose real runtime is
rootful Docker.
+The typed-helper safe profile deliberately does not reuse that broad
+`/run/user/*` selection. It waits until the dedicated collector account has
+been provisioned, filters sockets by exact UID ownership and collector
+read/write access, combines Docker and Podman candidates into one ambiguity
+set, and writes service environment pins only for one exact match. The runtime
+independently enforces one live collector-owned Unix endpoint before probing
+daemon metadata, requires the selected daemon to attest rootless mode, and
+repeats the check when recovering a lost socket. An exact standard-path pin
+from a root-owned existing service unit survives update-time socket downtime;
+the live process can recover direct monitoring from helper summary mode and can
+fall back to a complete helper summary after repeated direct loss.
+
Stable and stable-dry-run callers now select SignPath as the canonical Windows
Authenticode backend. The reusable builder fails fast on missing configuration,
submits the GitHub-hosted unsigned artifact through the pinned official action,
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 2dded56cea..954138f84d 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -76,6 +76,14 @@ infer recovery from the Docker module merely remaining connected. A Docker-only
collector's explicit incomplete status report updates liveness and helper
health while retaining its last complete inventory, including across the
degraded interval; only a complete report may replace that inventory.
+When the safe collector uses direct rootless Docker or Podman monitoring, every
+collection revalidates the exact socket path, ownership, mode, and fresh daemon
+rootless attestation immediately after `Info` and before any other daemon API.
+A boundary change or permission revocation is runtime unavailability: no
+post-`Info` inventory call is allowed, reconnect must repeat full admission,
+and repeated failure may recover only through a complete typed-helper summary.
+The safe collector cannot execute report-response update commands or autonomous
+cleanup/update work in either direct or helper monitoring mode.
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.
diff --git a/frontend-modern/public/docs/AGENT_SECURITY.md b/frontend-modern/public/docs/AGENT_SECURITY.md
index a0e2fd2fb7..feb0772031 100644
--- a/frontend-modern/public/docs/AGENT_SECURITY.md
+++ b/frontend-modern/public/docs/AGENT_SECURITY.md
@@ -257,7 +257,7 @@ or generic command path.
| Linux SMART telemetry | `smart.snapshot` through the no-network helper; no caller-selected device or arguments | Implemented, unqualified on representative physical disks. Helper failure omits/degrades SMART only; the collector does not retry as root | Does not yet justify SMART parity or a default change | `agent-lifecycle`: record live SATA, SAS/controller, USB bridge, and NVMe evidence, including standby, permission failure, timeout, and partial-data cases |
| Proxmox node-local LXC filesystem telemetry | `proxmox.lxc_filesystems` through the no-network helper using fixed bounded `pct` operations | Implemented, unqualified on a representative PVE node. Helper failure omits/degrades this snapshot only | Does not yet justify Proxmox host-agent parity or a default change | `agent-lifecycle`: record live running/stopped LXC, mount, timeout, output-bound, and helper-loss behavior on supported PVE versions |
| Rootful Docker or Podman inventory | No direct collector access to a root-equivalent daemon socket | Implemented as a typed-helper summary-only fallback. Migration preserves container ID/name/image/state/status/creation inventory and marks the report `typed-helper-summary`; stats, secondary inventories, update checks, and actions remain unavailable | Unit and installer regressions cover the boundary, but no representative live Docker/Podman qualification exists. Full rootful parity remains an explicit default blocker; the legacy/root profile is not safe-profile evidence | `agent-lifecycle`: record fresh install, migration, restart, helper loss/recovery, bounds, and summary parity on representative rootful Docker and Podman; decide explicitly whether reduced telemetry is sufficient |
-| Collector-owned rootless Docker or Podman | Direct access only to one usable runtime socket owned by the `pulse-agent` UID | Implemented, unqualified live. Ambiguous, root-owned, unreadable, unwritable, or unavailable sockets disable container monitoring | Does not yet justify container-runtime parity or a default change | `deployment-installability`: record fresh install, migration, restart, socket-loss, ambiguity, and telemetry parity on both rootless Docker and rootless Podman |
+| Collector-owned rootless Docker or Podman | Direct access only to one usable runtime socket owned by the `pulse-agent` UID whose daemon also attests rootless mode | Implemented, unqualified live. Discovery is deferred until the collector account exists and accepts exactly one readable/writable, non-symlink socket owned by that UID across Docker and Podman. Cross-user, root-owned, remote, unreadable, non-rootless-daemon, or ambiguous endpoints are rejected. An installer-owned exact pin survives daemon loss and update; the running collector can move between direct rootless monitoring and rootful typed-helper summary without regaining action authority | Does not yet justify container-runtime parity or a default change | `deployment-installability`: record fresh install, migration, restart, socket-loss, ambiguity, helper/direct recovery, and telemetry parity on both rootless Docker and rootless Podman |
| Separate runner package update and package-cache cleanup | Root-owned `pulse-agent-runner`, host-bound action credential, typed request, postcondition, and durable receipt | The schema-v6 committed-main systemd receipt records a real verified apt-cache mutation, stale-fingerprint refusal, replay, nonce-bound readiness, effective-unit override rejection, exact credential rotation, bodyless self-revocation, and collector/helper continuity. A separate production Router regression exercises HTTPS issuance, WSS admission, encrypted token persistence, failed-rotation rollback, exact socket invalidation, two server restarts, old-secret rejection, and durable self-revoke | Qualified for the exercised systemd fixture paths and focused production Router lifecycle. Focused installer tests also cover atomic pending cancellation and fail-closed credential retention. The evidence does not cover every runner operation, representative providers, or an exact release candidate | `agent-lifecycle` and `api-contracts`: reproduce the combined systemd and production Router path from trusted RC artifacts with representative package-update success/failure/cancellation evidence |
| Separate runner Proxmox guest and container lifecycle/update actions | Root-owned runner with closed typed protocols; never the monitoring collector | Implemented, unqualified on representative PVE and container-runtime targets | No live-provider action-parity claim and no default change | `agent-lifecycle`: record target-bound success, stale-state refusal, cancellation, reconnect/replay, and independent postconditions on disposable real targets |
| Appliance, non-systemd, Windows, and macOS host-agent profiles | Platform API where sufficient; otherwise an explicitly named legacy/full-trust profile | **Unavailable for safe-profile apply.** The installer fails closed instead of silently installing a root-equivalent profile | Excluded from the Linux safe-profile claim | `deployment-installability`: land a platform-specific service, filesystem, update, helper, migration, rollback, and live-proof contract before marking that platform supported |
diff --git a/internal/dockeragent/agent.go b/internal/dockeragent/agent.go
index 547d9a4dc5..a7adf99b15 100644
--- a/internal/dockeragent/agent.go
+++ b/internal/dockeragent/agent.go
@@ -133,6 +133,9 @@ type Agent struct {
cfg Config
docker dockerClient
helperInventory ContainerInventory
+ directDisableChecks bool
+ directServices bool
+ directTasks bool
daemonHost string
daemonID string // Cached at init; Podman can return unstable IDs across calls
runtime RuntimeKind
@@ -293,6 +296,10 @@ func New(cfg Config) (*Agent, error) {
return nil, fmt.Errorf("dockeragent.New: normalize runtime: %w", err)
}
+ directDisableChecks := cfg.DisableUpdateChecks
+ directServices := cfg.IncludeServices
+ directTasks := cfg.IncludeTasks
+
connect := connectRuntimeFn
if cfg.HelperInventory != nil {
// The helper profile must reject rootful, remote, and otherwise
@@ -300,13 +307,15 @@ func New(cfg Config) (*Agent, error) {
connect = connectCollectorRuntimeFn
}
runtimeDockerClient, info, runtimeKind, connectErr := connect(runtimePref, logger)
- if connectErr == nil && cfg.HelperInventory != nil && !collectorOwnsRootlessEndpoint(runtimeDockerClient.DaemonHost()) {
- endpoint := runtimeDockerClient.DaemonHost()
- closeErr := runtimeDockerClient.Close()
- runtimeDockerClient = nil
- connectErr = fmt.Errorf("direct runtime endpoint %q is not a collector-owned rootless Unix socket", endpoint)
- if closeErr != nil {
- connectErr = errors.Join(connectErr, fmt.Errorf("close rejected direct runtime client: %w", closeErr))
+ if connectErr == nil && cfg.HelperInventory != nil {
+ validationErr := validateCollectorDirectRuntime(runtimeDockerClient, info)
+ if validationErr != nil {
+ closeErr := runtimeDockerClient.Close()
+ runtimeDockerClient = nil
+ connectErr = validationErr
+ if closeErr != nil {
+ connectErr = errors.Join(connectErr, fmt.Errorf("close rejected direct runtime client: %w", closeErr))
+ }
}
}
if connectErr == nil && cfg.HelperInventory != nil && cfg.HelperOperationStatus != nil {
@@ -453,29 +462,32 @@ func New(cfg Config) (*Agent, error) {
helperInventory = cfg.HelperInventory
}
agent := &Agent{
- cfg: cfg,
- docker: runtimeClient,
- helperInventory: helperInventory,
- daemonHost: daemonHost,
- daemonID: info.ID, // Cache at init for stable agent ID
- runtime: runtimeKind,
- runtimePref: runtimePref,
- runtimeVer: info.ServerVersion,
- agentVersion: agentVersion,
- reportStreamID: reportStreamID,
- supportsSwarm: runtimeKind == RuntimeDocker,
- httpClients: httpClients,
- trustedHTTPClients: trustedHTTPClients,
- logger: *logger,
- machineID: machineID,
- hostName: hostName,
- targets: cfg.Targets,
- allowedStates: make(map[string]struct{}, len(stateFilters)),
- stateFilters: stateFilters,
- prevContainerCPU: make(map[string]cpuSample),
- reportBuffer: primaryBuffer,
- reportBuffers: reportBuffers,
- registryChecker: newRegistryCheckerWithConfig(*logger, !cfg.DisableUpdateChecks),
+ cfg: cfg,
+ docker: runtimeClient,
+ helperInventory: helperInventory,
+ directDisableChecks: directDisableChecks,
+ directServices: directServices,
+ directTasks: directTasks,
+ daemonHost: daemonHost,
+ daemonID: info.ID, // Cache at init for stable agent ID
+ runtime: runtimeKind,
+ runtimePref: runtimePref,
+ runtimeVer: info.ServerVersion,
+ agentVersion: agentVersion,
+ reportStreamID: reportStreamID,
+ supportsSwarm: runtimeKind == RuntimeDocker,
+ httpClients: httpClients,
+ trustedHTTPClients: trustedHTTPClients,
+ logger: *logger,
+ machineID: machineID,
+ hostName: hostName,
+ targets: cfg.Targets,
+ allowedStates: make(map[string]struct{}, len(stateFilters)),
+ stateFilters: stateFilters,
+ prevContainerCPU: make(map[string]cpuSample),
+ reportBuffer: primaryBuffer,
+ reportBuffers: reportBuffers,
+ registryChecker: newRegistryCheckerWithConfig(*logger, !cfg.DisableUpdateChecks),
}
agent.registryChecker.credentials = registryCredentialSourceForConfig(cfg, *logger)
@@ -660,17 +672,52 @@ func connectRuntime(preference RuntimeKind, logger *zerolog.Logger) (dockerClien
}
func connectCollectorOwnedRootlessRuntime(preference RuntimeKind, logger *zerolog.Logger) (dockerClient, systemtypes.Info, RuntimeKind, error) {
- return connectRuntimeWithProbe(preference, logger, func(opts []client.Opt) (dockerClient, systemtypes.Info, error) {
- return tryRuntimeCandidateWithEndpointAdmission(opts, collectorOwnsRootlessEndpoint)
+ candidates, err := collectorRootlessRuntimeCandidates(preference)
+ if err != nil {
+ return nil, systemtypes.Info{}, RuntimeAuto, err
+ }
+ return connectRuntimeCandidatesWithProbe(preference, candidates, logger, func(opts []client.Opt) (dockerClient, systemtypes.Info, error) {
+ cli, info, probeErr := tryRuntimeCandidateWithEndpointAdmission(opts, collectorOwnsRootlessEndpoint)
+ if probeErr != nil {
+ return nil, systemtypes.Info{}, probeErr
+ }
+ if !runtimeInfoIsRootless(info) {
+ endpoint := cli.DaemonHost()
+ closeErr := cli.Close()
+ probeErr = fmt.Errorf("runtime endpoint %q is owned by the collector but the daemon did not attest rootless mode", endpoint)
+ if closeErr != nil {
+ probeErr = errors.Join(probeErr, fmt.Errorf("close non-rootless runtime client: %w", closeErr))
+ }
+ return nil, systemtypes.Info{}, probeErr
+ }
+ return cli, info, nil
})
}
+func runtimeInfoIsRootless(info systemtypes.Info) bool {
+ for _, option := range info.SecurityOptions {
+ normalized := strings.ToLower(strings.TrimSpace(option))
+ if normalized == "rootless" || normalized == "name=rootless" || strings.HasPrefix(normalized, "name=rootless,") {
+ return true
+ }
+ }
+ return false
+}
+
func connectRuntimeWithProbe(
preference RuntimeKind,
logger *zerolog.Logger,
probe func([]client.Opt) (dockerClient, systemtypes.Info, error),
) (dockerClient, systemtypes.Info, RuntimeKind, error) {
- candidates := buildRuntimeCandidatesFn(preference)
+ return connectRuntimeCandidatesWithProbe(preference, buildRuntimeCandidatesFn(preference), logger, probe)
+}
+
+func connectRuntimeCandidatesWithProbe(
+ preference RuntimeKind,
+ candidates []runtimeCandidate,
+ logger *zerolog.Logger,
+ probe func([]client.Opt) (dockerClient, systemtypes.Info, error),
+) (dockerClient, systemtypes.Info, RuntimeKind, error) {
var attempts []string
for _, candidate := range candidates {
@@ -924,10 +971,6 @@ func (a *Agent) Run(ctx context.Context) error {
ticker := newTickerFn(interval)
defer ticker.Stop()
- if a.helperInventory != nil {
- return a.runHelperInventoryLoop(ctx, ticker)
- }
-
const (
updateInterval = 24 * time.Hour
startupJitterWindow = 2 * time.Minute
@@ -942,8 +985,9 @@ func (a *Agent) Run(ctx context.Context) error {
cleanupTicker := newTickerFn(15 * time.Minute)
defer cleanupTicker.Stop()
- // Perform cleanup of orphaned backup containers on startup
- go a.cleanupOrphanedBackups(ctx)
+ // Perform cleanup only while a directly admitted runtime is active. The
+ // typed helper exposes summary inventory and never grants lifecycle access.
+ a.scheduleDirectCleanup()
if err := a.collectOnce(ctx); err != nil {
if errors.Is(err, ErrStopRequested) {
@@ -975,33 +1019,14 @@ func (a *Agent) Run(ctx context.Context) error {
Msg("Failed to send docker report")
}
case <-updateTimer.C:
- go a.checkForUpdates(ctx)
+ a.scheduleDirectUpdateCheck()
nextDelay := updateInterval + randomDurationFn(recurringJitterWindow)
if nextDelay <= 0 {
nextDelay = updateInterval
}
updateTimer.Reset(nextDelay)
case <-cleanupTicker.C:
- go a.cleanupOrphanedBackups(ctx)
- }
- }
-}
-
-func (a *Agent) runHelperInventoryLoop(ctx context.Context, ticker *time.Ticker) error {
- collect := func(phase string) {
- if err := a.collectOnce(ctx); err != nil && !errors.Is(err, context.Canceled) {
- a.logger.Error().Err(err).Str("phase", phase).
- Str("collection_mode", agentsdocker.CollectionModeTypedHelperSummary).
- Msg("Failed to send typed helper container summary")
- }
- }
- collect("startup")
- for {
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-ticker.C:
- collect("periodic")
+ a.scheduleDirectCleanup()
}
}
}
@@ -1071,6 +1096,10 @@ func (a *Agent) collectOnceWithReport(ctx context.Context) (agentsdocker.Report,
a.collectMu.Lock()
defer a.collectMu.Unlock()
+ if a.helperInventory != nil {
+ a.maybePromoteCollectorRootlessRuntime()
+ }
+
var report agentsdocker.Report
var err error
if a.helperInventory != nil {
@@ -1078,8 +1107,12 @@ func (a *Agent) collectOnceWithReport(ctx context.Context) (agentsdocker.Report,
} else {
report, err = a.buildReport(ctx)
}
- if err != nil && a.helperInventory == nil && a.maybeReconnectRuntime(err) {
- report, err = a.buildReport(ctx)
+ if err != nil && a.helperInventory == nil {
+ if a.maybeReconnectRuntime(err) {
+ report, err = a.buildReport(ctx)
+ } else if a.runtimeGoneStreak >= runtimeReconnectFailureThreshold && a.maybeFallbackToHelperInventory(ctx) {
+ report, err = a.buildHelperInventoryReport(ctx)
+ }
}
if err != nil {
buildErr := fmt.Errorf("build docker report: %w", err)
@@ -1103,11 +1136,46 @@ func (a *Agent) collectOnceWithReport(ctx context.Context) (agentsdocker.Report,
return report, nil
}
-// ContainerActionsAvailable reports whether this module owns a direct runtime
-// client. Summary-only helper inventory never grants lifecycle or update
-// authority to the collector.
+// ContainerActionsAvailable reports whether this is a legacy direct-runtime
+// module. A collector configured with the typed helper is a monitoring-only
+// component even while it uses an admitted rootless socket directly; mutation
+// authority remains isolated in the separate action runner.
func (a *Agent) ContainerActionsAvailable() bool {
- return a != nil && a.helperInventory == nil && a.docker != nil
+ if a == nil {
+ return false
+ }
+ a.collectMu.Lock()
+ defer a.collectMu.Unlock()
+ return a.cfg.HelperInventory == nil && a.docker != nil
+}
+
+// scheduleDirectCleanup reserves the background slot while holding collectMu,
+// so a helper fallback cannot close the direct client between the mode check
+// and task admission.
+func (a *Agent) scheduleDirectCleanup() {
+ a.collectMu.Lock()
+ defer a.collectMu.Unlock()
+ if a.cfg.HelperInventory != nil || a.helperInventory != nil || a.docker == nil || !a.tryStartCleanupTask() {
+ return
+ }
+ a.runAsync(func(ctx context.Context) {
+ defer a.finishCleanupTask()
+ a.cleanupOrphanedBackupsTask(ctx)
+ })
+}
+
+// scheduleDirectUpdateCheck applies the same admission ordering to self-update
+// work, which can otherwise overlap a direct-to-helper mode transition.
+func (a *Agent) scheduleDirectUpdateCheck() {
+ a.collectMu.Lock()
+ defer a.collectMu.Unlock()
+ if a.cfg.HelperInventory != nil || a.helperInventory != nil || a.docker == nil || !a.tryStartUpdateCheck() {
+ return
+ }
+ a.runAsync(func(ctx context.Context) {
+ defer a.finishUpdateCheck()
+ a.checkForUpdatesTask(ctx)
+ })
}
func (a *Agent) flushBuffer(ctx context.Context) {
@@ -1375,7 +1443,16 @@ func (a *Agent) sendReportToTarget(ctx context.Context, target TargetConfig, pay
}
func (a *Agent) handleCommand(ctx context.Context, target TargetConfig, command agentsdocker.Command) error {
- switch strings.ToLower(command.Type) {
+ commandType := strings.ToLower(command.Type)
+ if a.cfg.HelperInventory != nil {
+ switch commandType {
+ case agentsdocker.CommandTypeUpdateContainer, agentsdocker.CommandTypeUpdateAll, agentsdocker.CommandTypeCheckUpdates:
+ a.rejectMonitoringOnlyCommand(ctx, target, command)
+ return nil
+ }
+ }
+
+ switch commandType {
case agentsdocker.CommandTypeStop:
return a.handleStopCommand(ctx, target, command)
case agentsdocker.CommandTypeUpdateContainer:
@@ -1394,6 +1471,29 @@ func (a *Agent) handleCommand(ctx context.Context, target TargetConfig, command
}
}
+func (a *Agent) rejectMonitoringOnlyCommand(ctx context.Context, target TargetConfig, command agentsdocker.Command) {
+ a.logger.Warn().
+ Str("target", target.URL).
+ Str("command", command.Type).
+ Str("commandID", command.ID).
+ Msg("Rejected Docker control command in monitoring-only collector profile")
+ if strings.TrimSpace(command.ID) == "" {
+ return
+ }
+ if err := a.sendCommandAck(
+ ctx,
+ target,
+ command.ID,
+ agentsdocker.CommandStatusFailed,
+ "Monitoring-only collector profile does not execute container control commands",
+ ); err != nil {
+ a.logger.Warn().Err(err).
+ Str("target", target.URL).
+ Str("commandID", command.ID).
+ Msg("Failed to acknowledge rejected Docker control command")
+ }
+}
+
func (a *Agent) handleCheckUpdatesCommand(ctx context.Context, target TargetConfig, command agentsdocker.Command) error {
command.ID = strings.TrimSpace(command.ID)
if command.ID == "" {
diff --git a/internal/dockeragent/agent_http_test.go b/internal/dockeragent/agent_http_test.go
index c16984ebc2..1577fa5561 100644
--- a/internal/dockeragent/agent_http_test.go
+++ b/internal/dockeragent/agent_http_test.go
@@ -630,6 +630,52 @@ func TestHandleCommand(t *testing.T) {
})
}
+func TestMonitoringOnlyCollectorRejectsForgedReportCommand(t *testing.T) {
+ var ack agentsdocker.CommandAck
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/report") {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"commands":[{"id":"forged-update","type":"update_container","payload":{"containerId":"container-1"}}]}`))
+ return
+ }
+ if strings.HasSuffix(r.URL.Path, "/commands/forged-update/ack") {
+ if err := json.NewDecoder(r.Body).Decode(&ack); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ defer server.Close()
+
+ mutations := 0
+ helper := &helperInventoryStub{}
+ agent := &Agent{
+ cfg: Config{HelperInventory: helper},
+ hostID: "safe-host",
+ docker: &fakeDockerClient{
+ containerInspectFn: func(context.Context, string) (containertypes.InspectResponse, error) {
+ mutations++
+ return containertypes.InspectResponse{}, errors.New("must not execute")
+ },
+ },
+ httpClients: map[bool]*http.Client{false: server.Client()},
+ logger: zerolog.Nop(),
+ }
+ target := TargetConfig{Name: "primary", URL: server.URL, Token: "token", Authoritative: true}
+ if err := agent.sendReportToTarget(context.Background(), target, []byte("ignored"), 0); err != nil {
+ t.Fatalf("safe report response: %v", err)
+ }
+ if mutations != 0 {
+ t.Fatalf("forged report command reached direct runtime %d times", mutations)
+ }
+ if ack.Status != agentsdocker.CommandStatusFailed || !strings.Contains(ack.Message, "Monitoring-only collector") {
+ t.Fatalf("rejected command acknowledgement = %+v", ack)
+ }
+}
+
func TestHandleStopCommand(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("systemd stop-command behavior is not available on Windows")
diff --git a/internal/dockeragent/agent_internal_test.go b/internal/dockeragent/agent_internal_test.go
index acac00c6a3..67759f54af 100644
--- a/internal/dockeragent/agent_internal_test.go
+++ b/internal/dockeragent/agent_internal_test.go
@@ -14,6 +14,7 @@ import (
"reflect"
"strings"
"sync"
+ "syscall"
"testing"
"time"
@@ -1794,3 +1795,17 @@ func TestRegistryCredentialSourceForConfig(t *testing.T) {
t.Fatalf("expected nil credential source when disabled, got %T", disabled)
}
}
+
+func TestCollectorRuntimeBoundaryLossIsDaemonUnavailable(t *testing.T) {
+ for _, err := range []error{
+ errCollectorRuntimeBoundaryChanged,
+ fmt.Errorf("cycle validation: %w", errCollectorRuntimeBoundaryChanged),
+ syscall.EACCES,
+ syscall.EPERM,
+ errors.New("dial unix /run/user/991/docker.sock: permission denied"),
+ } {
+ if !isDockerDaemonUnavailable(err) {
+ t.Fatalf("collector boundary loss %q was not classified unavailable", err)
+ }
+ }
+}
diff --git a/internal/dockeragent/cleanup.go b/internal/dockeragent/cleanup.go
index 4769823d22..584be2a1a2 100644
--- a/internal/dockeragent/cleanup.go
+++ b/internal/dockeragent/cleanup.go
@@ -11,12 +11,19 @@ import (
// cleanupOrphanedBackups searches for and removes any Pulse backup containers
// (created during updates) that are older than 15 minutes.
func (a *Agent) cleanupOrphanedBackups(ctx context.Context) {
+ if a.cfg.HelperInventory != nil {
+ a.logger.Debug().Msg("Skipping orphaned backup cleanup in monitoring-only collector profile")
+ return
+ }
if !a.tryStartCleanupTask() {
a.logger.Debug().Msg("Skipping orphaned backup cleanup - previous cleanup still running")
return
}
defer a.finishCleanupTask()
+ a.cleanupOrphanedBackupsTask(ctx)
+}
+func (a *Agent) cleanupOrphanedBackupsTask(ctx context.Context) {
a.logger.Debug().Msg("Checking for orphaned backup containers")
// List all containers (including stopped ones)
diff --git a/internal/dockeragent/collect.go b/internal/dockeragent/collect.go
index a4d7c758c8..ac8b3582cd 100644
--- a/internal/dockeragent/collect.go
+++ b/internal/dockeragent/collect.go
@@ -42,6 +42,11 @@ func (a *Agent) buildReport(ctx context.Context) (agentsdocker.Report, error) {
if err != nil {
return agentsdocker.Report{}, fmt.Errorf("failed to query docker info: %w", annotateDockerConnectionError(err))
}
+ if a.cfg.HelperInventory != nil {
+ if err := validateCollectorDirectRuntime(a.docker, info); err != nil {
+ return agentsdocker.Report{}, fmt.Errorf("%w: %v", errCollectorRuntimeBoundaryChanged, err)
+ }
+ }
a.runtimeVer = info.ServerVersion
if a.daemonHost == "" {
diff --git a/internal/dockeragent/hardening.go b/internal/dockeragent/hardening.go
index cd76b6a6ac..22db170ee2 100644
--- a/internal/dockeragent/hardening.go
+++ b/internal/dockeragent/hardening.go
@@ -51,6 +51,8 @@ const (
dockerRetryBaseDelay = 200 * time.Millisecond
)
+var errCollectorRuntimeBoundaryChanged = errors.New("collector rootless runtime boundary changed")
+
// startCollectCycleWatchdog arms an independent timer that fires only if a
// collection cycle is still running after budget. The cycle context deadline
// should abort the cycle well before then, so the watchdog firing means
@@ -215,8 +217,13 @@ func isDockerDaemonUnavailable(err error) bool {
if err == nil {
return false
}
+ if errors.Is(err, errCollectorRuntimeBoundaryChanged) {
+ return true
+ }
for _, unavailableErrno := range []error{
+ syscall.EACCES,
+ syscall.EPERM,
syscall.ECONNREFUSED,
syscall.ECONNRESET,
syscall.EPIPE,
@@ -235,6 +242,8 @@ func isDockerDaemonUnavailable(err error) bool {
for _, marker := range []string{
"cannot connect to the docker daemon",
"is the docker daemon running",
+ "permission denied",
+ "operation not permitted",
"connection refused",
"connection reset by peer",
"broken pipe",
diff --git a/internal/dockeragent/helper_inventory_test.go b/internal/dockeragent/helper_inventory_test.go
index 573c11c594..f93d4fcf49 100644
--- a/internal/dockeragent/helper_inventory_test.go
+++ b/internal/dockeragent/helper_inventory_test.go
@@ -305,6 +305,89 @@ func TestHelperInventoryStatusTracksFailureAndCompleteRecovery(t *testing.T) {
}
}
+func TestDirectRootlessLossFallsBackToCompleteHelperInventory(t *testing.T) {
+ originalMetrics := hostmetricsCollectWithDiskFilters
+ t.Cleanup(func() { hostmetricsCollectWithDiskFilters = originalMetrics })
+ hostmetricsCollectWithDiskFilters = func(context.Context, []string, []string) (hostmetrics.Snapshot, error) {
+ return hostmetrics.Snapshot{}, nil
+ }
+
+ closed := false
+ helper := &helperInventoryStub{result: agenthelper.ContainerInventoryResult{
+ Runtimes: []agenthelper.ContainerRuntimeSnapshot{{
+ Runtime: "docker", Available: true,
+ Containers: []agenthelper.ContainerSummary{{ID: "container-1", Names: []string{"app"}, State: "running"}},
+ }},
+ }}
+ agent := &Agent{
+ cfg: Config{
+ HelperInventory: helper, IncludeServices: true, IncludeTasks: true,
+ },
+ docker: newSwappableDockerClient(&fakeDockerClient{closeFn: func() error { closed = true; return nil }}),
+ runtime: RuntimeDocker,
+ runtimePref: RuntimeDocker,
+ runtimeGoneStreak: runtimeReconnectFailureThreshold,
+ registryChecker: newRegistryCheckerWithConfig(zerolog.Nop(), true),
+ allowedStates: map[string]struct{}{"running": {}},
+ logger: zerolog.Nop(),
+ }
+
+ if !agent.maybeFallbackToHelperInventory(context.Background()) {
+ t.Fatal("complete helper inventory did not become the recovery source")
+ }
+ if !closed || agent.docker != nil || agent.helperInventory != helper {
+ t.Fatalf("fallback state = closed:%t docker:%T helper:%T", closed, agent.docker, agent.helperInventory)
+ }
+ if agent.cfg.IncludeServices || agent.cfg.IncludeTasks || !agent.cfg.DisableUpdateChecks || agent.registryChecker.Enabled() {
+ t.Fatalf("helper fallback retained direct-only configuration: %+v", agent.cfg)
+ }
+ report, err := agent.buildHelperInventoryReport(context.Background())
+ if err != nil {
+ t.Fatalf("build recovered helper report: %v", err)
+ }
+ if report.InventoryComplete == nil || !*report.InventoryComplete || report.Host.CollectionMode != agentsdocker.CollectionModeTypedHelperSummary || len(report.Containers) != 1 {
+ t.Fatalf("recovered helper report = %+v", report)
+ }
+}
+
+func TestDirectRootlessLossDefersHelperFallbackWhileBackgroundTaskRuns(t *testing.T) {
+ helper := &helperInventoryStub{result: agenthelper.ContainerInventoryResult{
+ Runtimes: []agenthelper.ContainerRuntimeSnapshot{{Runtime: "docker", Available: true}},
+ }}
+ agent := &Agent{
+ cfg: Config{HelperInventory: helper},
+ docker: &fakeDockerClient{},
+ runtimeGoneStreak: runtimeReconnectFailureThreshold,
+ cleanupTaskRunning: true,
+ logger: zerolog.Nop(),
+ }
+ if agent.maybeFallbackToHelperInventory(context.Background()) {
+ t.Fatal("helper fallback raced an active direct-runtime cleanup")
+ }
+ if helper.calls != 0 || agent.helperInventory != nil || agent.docker == nil {
+ t.Fatalf("busy fallback mutated state: calls=%d helper=%T docker=%T", helper.calls, agent.helperInventory, agent.docker)
+ }
+}
+
+func TestMonitoringOnlyCollectorNeverSchedulesLegacyMutationTasks(t *testing.T) {
+ helper := &helperInventoryStub{}
+ agent := &Agent{
+ cfg: Config{HelperInventory: helper},
+ docker: &fakeDockerClient{},
+ logger: zerolog.Nop(),
+ }
+ agent.scheduleDirectCleanup()
+ agent.scheduleDirectUpdateCheck()
+ if agent.cleanupTaskRunning || agent.updateCheckRunning {
+ t.Fatalf("monitoring-only collector scheduled legacy tasks: cleanup=%t update=%t", agent.cleanupTaskRunning, agent.updateCheckRunning)
+ }
+ agent.cleanupOrphanedBackups(context.Background())
+ agent.checkForUpdates(context.Background())
+ if agent.cleanupTaskRunning || agent.updateCheckRunning {
+ t.Fatalf("direct legacy task entrypoints bypassed profile gate: cleanup=%t update=%t", agent.cleanupTaskRunning, agent.updateCheckRunning)
+ }
+}
+
func TestBuildHelperInventoryReportIsExplicitlySummaryOnly(t *testing.T) {
originalMetrics := hostmetricsCollectWithDiskFilters
t.Cleanup(func() { hostmetricsCollectWithDiskFilters = originalMetrics })
diff --git a/internal/dockeragent/rootless_endpoint_linux.go b/internal/dockeragent/rootless_endpoint_linux.go
index 97938e8abc..fe74ed9030 100644
--- a/internal/dockeragent/rootless_endpoint_linux.go
+++ b/internal/dockeragent/rootless_endpoint_linux.go
@@ -3,6 +3,8 @@
package dockeragent
import (
+ "errors"
+ "fmt"
"os"
"path/filepath"
"strconv"
@@ -26,13 +28,119 @@ func collectorOwnsRootlessEndpoint(endpoint string) bool {
}
uid := effectiveUID()
root := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(uid))
- if path != root && !strings.HasPrefix(path, root+string(filepath.Separator)) {
+ dockerPath := filepath.Join(root, "docker.sock")
+ podmanPath := filepath.Join(root, "podman", "podman.sock")
+ if path != dockerPath && path != podmanPath {
return false
}
info, err := os.Lstat(path)
if err != nil || info.Mode()&os.ModeSocket == 0 || info.Mode()&os.ModeSymlink != 0 {
return false
}
+ if info.Mode().Perm()&0o600 != 0o600 {
+ return false
+ }
stat, ok := info.Sys().(*syscall.Stat_t)
return ok && stat.Uid == uint32(uid)
}
+
+// collectorRootlessRuntimeCandidates returns one exact, live runtime endpoint
+// owned by the collector. A typed-helper collector must never probe a rootful,
+// remote, cross-user, or ambiguous daemon endpoint. Explicit environment pins
+// resolve automatic discovery, but conflicting live pins still fail closed.
+func collectorRootlessRuntimeCandidates(preference RuntimeKind) ([]runtimeCandidate, error) {
+ uidRoot := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(effectiveUID()))
+ dockerURI := "unix://" + filepath.Join(uidRoot, "docker.sock")
+ podmanURI := "unix://" + filepath.Join(uidRoot, "podman", "podman.sock")
+ configured := make([]runtimeCandidate, 0, 3)
+ addConfigured := func(label, value, expected string) error {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return nil
+ }
+ if value != expected {
+ return fmt.Errorf("%s must pin the exact collector-owned endpoint %q", label, expected)
+ }
+ configured = append(configured, runtimeCandidate{host: value, label: label})
+ return nil
+ }
+
+ var configErr error
+ switch preference {
+ case RuntimeDocker:
+ configErr = addConfigured("DOCKER_HOST", os.Getenv("DOCKER_HOST"), dockerURI)
+ case RuntimePodman:
+ configErr = errors.Join(
+ addConfigured("PODMAN_HOST", os.Getenv("PODMAN_HOST"), podmanURI),
+ addConfigured("CONTAINER_HOST", os.Getenv("CONTAINER_HOST"), podmanURI),
+ )
+ default:
+ configErr = errors.Join(
+ addConfigured("DOCKER_HOST", os.Getenv("DOCKER_HOST"), dockerURI),
+ addConfigured("PODMAN_HOST", os.Getenv("PODMAN_HOST"), podmanURI),
+ addConfigured("CONTAINER_HOST", os.Getenv("CONTAINER_HOST"), podmanURI),
+ )
+ }
+ if configErr != nil {
+ return nil, configErr
+ }
+
+ candidates := configured
+ if len(candidates) == 0 {
+ switch preference {
+ case RuntimeDocker:
+ candidates = append(candidates, runtimeCandidate{
+ host: "unix://" + filepath.Join(uidRoot, "docker.sock"),
+ label: "collector rootless docker socket",
+ })
+ case RuntimePodman:
+ candidates = append(candidates, runtimeCandidate{
+ host: "unix://" + filepath.Join(uidRoot, "podman", "podman.sock"),
+ label: "collector rootless podman socket",
+ })
+ default:
+ candidates = append(candidates,
+ runtimeCandidate{
+ host: "unix://" + filepath.Join(uidRoot, "docker.sock"),
+ label: "collector rootless docker socket",
+ },
+ runtimeCandidate{
+ host: "unix://" + filepath.Join(uidRoot, "podman", "podman.sock"),
+ label: "collector rootless podman socket",
+ },
+ )
+ }
+ }
+ configuredEndpoints := make(map[string]struct{}, len(configured))
+ for _, candidate := range configured {
+ configuredEndpoints[candidate.host] = struct{}{}
+ }
+ if len(configuredEndpoints) > 1 {
+ return nil, fmt.Errorf("conflicting collector rootless runtime pins are configured")
+ }
+
+ live := make([]runtimeCandidate, 0, len(candidates))
+ seen := make(map[string]struct{}, len(candidates))
+ for _, candidate := range candidates {
+ if _, exists := seen[candidate.host]; exists {
+ continue
+ }
+ seen[candidate.host] = struct{}{}
+ if collectorOwnsRootlessEndpoint(candidate.host) {
+ live = append(live, candidate)
+ }
+ }
+
+ switch len(live) {
+ case 0:
+ return nil, fmt.Errorf("no live collector-owned rootless %s endpoint is available", preference)
+ case 1:
+ return live, nil
+ default:
+ endpoints := make([]string, 0, len(live))
+ for _, candidate := range live {
+ endpoints = append(endpoints, candidate.host)
+ }
+ return nil, fmt.Errorf("ambiguous collector-owned rootless runtime endpoints: %s", strings.Join(endpoints, ", "))
+ }
+}
diff --git a/internal/dockeragent/rootless_endpoint_linux_test.go b/internal/dockeragent/rootless_endpoint_linux_test.go
index 4f8b408c61..0142afd54c 100644
--- a/internal/dockeragent/rootless_endpoint_linux_test.go
+++ b/internal/dockeragent/rootless_endpoint_linux_test.go
@@ -3,11 +3,22 @@
package dockeragent
import (
+ "context"
+ "errors"
"net"
"os"
"path/filepath"
"strconv"
+ "strings"
"testing"
+
+ containertypes "github.com/moby/moby/api/types/container"
+ systemtypes "github.com/moby/moby/api/types/system"
+ "github.com/moby/moby/client"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agenthelper"
+ "github.com/rcourtman/pulse-go-rewrite/internal/hostmetrics"
+ agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
+ "github.com/rs/zerolog"
)
func TestCollectorOwnsRootlessEndpointRequiresOwnedRuntimeSocket(t *testing.T) {
@@ -49,3 +60,454 @@ func TestCollectorOwnsRootlessEndpointRequiresOwnedRuntimeSocket(t *testing.T) {
t.Fatal("symlinked runtime endpoint was accepted")
}
}
+
+func TestCollectorRootlessRuntimeCandidatesRequireOneExactOwnedSocket(t *testing.T) {
+ originalRoot := rootlessRuntimeRoot
+ originalUID := effectiveUID
+ t.Cleanup(func() {
+ rootlessRuntimeRoot = originalRoot
+ effectiveUID = originalUID
+ })
+ t.Setenv("DOCKER_HOST", "")
+ t.Setenv("CONTAINER_HOST", "")
+ t.Setenv("PODMAN_HOST", "")
+
+ rootlessRuntimeRoot = t.TempDir()
+ effectiveUID = os.Geteuid
+ runtimeDir := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(os.Geteuid()))
+ if err := os.MkdirAll(filepath.Join(runtimeDir, "podman"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+
+ dockerPath := filepath.Join(runtimeDir, "docker.sock")
+ dockerListener, err := net.Listen("unix", dockerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer dockerListener.Close()
+
+ candidates, err := collectorRootlessRuntimeCandidates(RuntimeAuto)
+ if err != nil {
+ t.Fatalf("single Docker candidate: %v", err)
+ }
+ if len(candidates) != 1 || candidates[0].host != "unix://"+dockerPath {
+ t.Fatalf("Docker candidates = %+v", candidates)
+ }
+
+ podmanPath := filepath.Join(runtimeDir, "podman", "podman.sock")
+ podmanListener, err := net.Listen("unix", podmanPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer podmanListener.Close()
+
+ if _, err := collectorRootlessRuntimeCandidates(RuntimeAuto); err == nil || !strings.Contains(err.Error(), "ambiguous") {
+ t.Fatalf("auto discovery with Docker and Podman = %v, want ambiguity", err)
+ }
+
+ candidates, err = collectorRootlessRuntimeCandidates(RuntimeDocker)
+ if err != nil {
+ t.Fatalf("explicit Docker preference: %v", err)
+ }
+ if len(candidates) != 1 || candidates[0].host != "unix://"+dockerPath {
+ t.Fatalf("Docker preference candidates = %+v", candidates)
+ }
+
+ t.Setenv("DOCKER_HOST", "unix://"+dockerPath)
+ candidates, err = collectorRootlessRuntimeCandidates(RuntimeAuto)
+ if err != nil {
+ t.Fatalf("explicit endpoint pin: %v", err)
+ }
+ if len(candidates) != 1 || candidates[0].label != "DOCKER_HOST" {
+ t.Fatalf("explicit candidates = %+v", candidates)
+ }
+}
+
+func TestCollectorRootlessRuntimeCandidatesRejectCrossUserAndConflictingPins(t *testing.T) {
+ originalRoot := rootlessRuntimeRoot
+ originalUID := effectiveUID
+ t.Cleanup(func() {
+ rootlessRuntimeRoot = originalRoot
+ effectiveUID = originalUID
+ })
+
+ rootlessRuntimeRoot = t.TempDir()
+ effectiveUID = os.Geteuid
+ runtimeDir := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(os.Geteuid()))
+ if err := os.MkdirAll(filepath.Join(runtimeDir, "podman"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+
+ dockerPath := filepath.Join(runtimeDir, "docker.sock")
+ dockerListener, err := net.Listen("unix", dockerPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer dockerListener.Close()
+ podmanPath := filepath.Join(runtimeDir, "podman", "podman.sock")
+ podmanListener, err := net.Listen("unix", podmanPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer podmanListener.Close()
+
+ t.Setenv("DOCKER_HOST", "unix://"+dockerPath)
+ t.Setenv("PODMAN_HOST", "unix://"+podmanPath)
+ t.Setenv("CONTAINER_HOST", "")
+ if _, err := collectorRootlessRuntimeCandidates(RuntimeAuto); err == nil || !strings.Contains(err.Error(), "conflicting") {
+ t.Fatalf("conflicting live pins = %v, want conflict rejection", err)
+ }
+
+ t.Setenv("DOCKER_HOST", "unix://"+filepath.Join(runtimeDir, "custom.sock"))
+ t.Setenv("PODMAN_HOST", "")
+ if _, err := collectorRootlessRuntimeCandidates(RuntimeAuto); err == nil || !strings.Contains(err.Error(), "exact collector-owned endpoint") {
+ t.Fatalf("custom same-UID pin = %v, want exact-path rejection", err)
+ }
+
+ t.Setenv("DOCKER_HOST", "")
+ t.Setenv("PODMAN_HOST", "")
+ effectiveUID = func() int { return os.Geteuid() + 1 }
+ if _, err := collectorRootlessRuntimeCandidates(RuntimeAuto); err == nil || !strings.Contains(err.Error(), "no live collector-owned") {
+ t.Fatalf("cross-user sockets = %v, want fail-closed rejection", err)
+ }
+}
+
+func TestCollectorRootlessRuntimeAmbiguityIsRejectedBeforeDaemonProbe(t *testing.T) {
+ originalRoot := rootlessRuntimeRoot
+ originalUID := effectiveUID
+ originalNewClient := newDockerClientFn
+ t.Cleanup(func() {
+ rootlessRuntimeRoot = originalRoot
+ effectiveUID = originalUID
+ newDockerClientFn = originalNewClient
+ })
+ t.Setenv("DOCKER_HOST", "")
+ t.Setenv("CONTAINER_HOST", "")
+ t.Setenv("PODMAN_HOST", "")
+
+ rootlessRuntimeRoot = t.TempDir()
+ effectiveUID = os.Geteuid
+ runtimeDir := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(os.Geteuid()))
+ if err := os.MkdirAll(filepath.Join(runtimeDir, "podman"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+
+ listeners := make([]net.Listener, 0, 2)
+ for _, path := range []string{
+ filepath.Join(runtimeDir, "docker.sock"),
+ filepath.Join(runtimeDir, "podman", "podman.sock"),
+ } {
+ listener, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ listeners = append(listeners, listener)
+ }
+ defer func() {
+ for _, listener := range listeners {
+ _ = listener.Close()
+ }
+ }()
+
+ probes := 0
+ newDockerClientFn = func(...client.Opt) (dockerClient, error) {
+ probes++
+ return nil, nil
+ }
+ if _, _, _, err := connectCollectorOwnedRootlessRuntime(RuntimeAuto, nil); err == nil || !strings.Contains(err.Error(), "ambiguous") {
+ t.Fatalf("ambiguous connection = %v", err)
+ }
+ if probes != 0 {
+ t.Fatalf("ambiguous endpoints reached daemon client construction %d times", probes)
+ }
+}
+
+func TestCollectorRootlessRuntimeRejectsSymlinkAndUnreadableSocket(t *testing.T) {
+ originalRoot := rootlessRuntimeRoot
+ originalUID := effectiveUID
+ t.Cleanup(func() {
+ rootlessRuntimeRoot = originalRoot
+ effectiveUID = originalUID
+ })
+ t.Setenv("DOCKER_HOST", "")
+ t.Setenv("CONTAINER_HOST", "")
+ t.Setenv("PODMAN_HOST", "")
+
+ rootlessRuntimeRoot = t.TempDir()
+ effectiveUID = os.Geteuid
+ runtimeDir := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(os.Geteuid()))
+ if err := os.MkdirAll(runtimeDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ realPath := filepath.Join(runtimeDir, "real.sock")
+ listener, err := net.Listen("unix", realPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+ standardPath := filepath.Join(runtimeDir, "docker.sock")
+ if err := os.Symlink(realPath, standardPath); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := collectorRootlessRuntimeCandidates(RuntimeAuto); err == nil {
+ t.Fatal("symlinked rootless runtime endpoint was accepted")
+ }
+ if err := os.Remove(standardPath); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(realPath, standardPath); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(standardPath, 0); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := collectorRootlessRuntimeCandidates(RuntimeAuto); err == nil {
+ t.Fatal("collector-unreadable rootless runtime endpoint was accepted")
+ }
+}
+
+func TestCollectorRootlessRuntimeRejectsOwnedSocketBackedByRootfulDaemon(t *testing.T) {
+ originalRoot := rootlessRuntimeRoot
+ originalUID := effectiveUID
+ originalNewClient := newDockerClientFn
+ t.Cleanup(func() {
+ rootlessRuntimeRoot = originalRoot
+ effectiveUID = originalUID
+ newDockerClientFn = originalNewClient
+ })
+ t.Setenv("DOCKER_HOST", "")
+ t.Setenv("CONTAINER_HOST", "")
+ t.Setenv("PODMAN_HOST", "")
+
+ rootlessRuntimeRoot = t.TempDir()
+ effectiveUID = os.Geteuid
+ runtimeDir := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(os.Geteuid()))
+ if err := os.MkdirAll(runtimeDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ socketPath := filepath.Join(runtimeDir, "docker.sock")
+ listener, err := net.Listen("unix", socketPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+
+ closed := false
+ newDockerClientFn = func(...client.Opt) (dockerClient, error) {
+ return &fakeDockerClient{
+ daemonHost: "unix://" + socketPath,
+ infoFunc: func(context.Context) (systemtypes.Info, error) {
+ return systemtypes.Info{SecurityOptions: []string{"name=seccomp,profile=default"}}, nil
+ },
+ closeFn: func() error { closed = true; return nil },
+ }, nil
+ }
+ if _, _, _, err := connectCollectorOwnedRootlessRuntime(RuntimeDocker, nil); err == nil || !strings.Contains(err.Error(), "did not attest rootless mode") {
+ t.Fatalf("owned-path rootful daemon = %v", err)
+ }
+ if !closed {
+ t.Fatal("owned-path rootful daemon client was not closed")
+ }
+
+ newDockerClientFn = func(...client.Opt) (dockerClient, error) {
+ return &fakeDockerClient{
+ daemonHost: "unix://" + socketPath,
+ infoFunc: func(context.Context) (systemtypes.Info, error) {
+ return systemtypes.Info{SecurityOptions: []string{"name=rootless", "name=seccomp,profile=default"}}, nil
+ },
+ }, nil
+ }
+ cli, _, runtimeKind, err := connectCollectorOwnedRootlessRuntime(RuntimeDocker, nil)
+ if err != nil {
+ t.Fatalf("rootless daemon: %v", err)
+ }
+ if cli == nil || runtimeKind != RuntimeDocker {
+ t.Fatalf("rootless daemon connection = cli:%T runtime:%s", cli, runtimeKind)
+ }
+}
+
+func TestTypedHelperInventoryPromotesToAttestedRootlessRuntime(t *testing.T) {
+ originalRoot := rootlessRuntimeRoot
+ originalUID := effectiveUID
+ originalConnect := connectCollectorRuntimeFn
+ t.Cleanup(func() {
+ rootlessRuntimeRoot = originalRoot
+ effectiveUID = originalUID
+ connectCollectorRuntimeFn = originalConnect
+ })
+
+ rootlessRuntimeRoot = t.TempDir()
+ effectiveUID = os.Geteuid
+ runtimeDir := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(os.Geteuid()))
+ if err := os.MkdirAll(runtimeDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ socketPath := filepath.Join(runtimeDir, "docker.sock")
+ listener, err := net.Listen("unix", socketPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+
+ rootlessClient := &fakeDockerClient{daemonHost: "unix://" + socketPath}
+ connectCollectorRuntimeFn = func(RuntimeKind, *zerolog.Logger) (dockerClient, systemtypes.Info, RuntimeKind, error) {
+ return rootlessClient, systemtypes.Info{
+ ID: "rootless-daemon", ServerVersion: "28.0.0", SecurityOptions: []string{"name=rootless"},
+ }, RuntimeDocker, nil
+ }
+ helper := &helperInventoryStub{}
+ agent := &Agent{
+ cfg: Config{
+ HelperInventory: helper, DisableUpdateChecks: true,
+ },
+ helperInventory: helper,
+ directDisableChecks: false,
+ directServices: true,
+ directTasks: true,
+ runtimePref: RuntimeAuto,
+ runtime: RuntimeDocker,
+ registryChecker: newRegistryCheckerWithConfig(zerolog.Nop(), false),
+ logger: zerolog.Nop(),
+ }
+
+ if !agent.maybePromoteCollectorRootlessRuntime() {
+ t.Fatal("attested rootless runtime was not promoted")
+ }
+ if agent.helperInventory != nil || agent.docker == nil || agent.daemonID != "rootless-daemon" {
+ t.Fatalf("promoted state = helper:%T docker:%T daemon:%q", agent.helperInventory, agent.docker, agent.daemonID)
+ }
+ if agent.cfg.DisableUpdateChecks || !agent.cfg.IncludeServices || !agent.cfg.IncludeTasks || !agent.registryChecker.Enabled() {
+ t.Fatalf("direct configuration was not restored: %+v", agent.cfg)
+ }
+ if agent.ContainerActionsAvailable() {
+ t.Fatal("safe collector promotion exposed container action authority")
+ }
+}
+
+func TestTypedHelperInventoryTransitionsThroughRootlessPodman(t *testing.T) {
+ originalRoot := rootlessRuntimeRoot
+ originalUID := effectiveUID
+ originalConnect := connectCollectorRuntimeFn
+ t.Cleanup(func() {
+ rootlessRuntimeRoot = originalRoot
+ effectiveUID = originalUID
+ connectCollectorRuntimeFn = originalConnect
+ })
+
+ rootlessRuntimeRoot = t.TempDir()
+ effectiveUID = os.Geteuid
+ runtimeDir := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(os.Geteuid()), "podman")
+ if err := os.MkdirAll(runtimeDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ socketPath := filepath.Join(runtimeDir, "podman.sock")
+ listener, err := net.Listen("unix", socketPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+
+ connectCollectorRuntimeFn = func(RuntimeKind, *zerolog.Logger) (dockerClient, systemtypes.Info, RuntimeKind, error) {
+ return &fakeDockerClient{daemonHost: "unix://" + socketPath}, systemtypes.Info{
+ ID: "rootless-podman", ServerVersion: "5.5.0 podman", SecurityOptions: []string{"name=rootless"},
+ }, RuntimePodman, nil
+ }
+ helper := &helperInventoryStub{result: agenthelper.ContainerInventoryResult{
+ Runtimes: []agenthelper.ContainerRuntimeSnapshot{{Runtime: "podman", Available: true}},
+ }}
+ agent := &Agent{
+ cfg: Config{HelperInventory: helper, DisableUpdateChecks: true},
+ helperInventory: helper,
+ directDisableChecks: false,
+ directServices: true,
+ directTasks: true,
+ runtimePref: RuntimePodman,
+ runtime: RuntimePodman,
+ registryChecker: newRegistryCheckerWithConfig(zerolog.Nop(), false),
+ logger: zerolog.Nop(),
+ }
+ if !agent.maybePromoteCollectorRootlessRuntime() {
+ t.Fatal("attested rootless Podman runtime was not promoted")
+ }
+ if agent.runtime != RuntimePodman || agent.cfg.IncludeServices || agent.cfg.IncludeTasks || agent.helperInventory != nil {
+ t.Fatalf("promoted Podman state = runtime:%s services:%t tasks:%t helper:%T", agent.runtime, agent.cfg.IncludeServices, agent.cfg.IncludeTasks, agent.helperInventory)
+ }
+ agent.runtimeGoneStreak = runtimeReconnectFailureThreshold
+ if !agent.maybeFallbackToHelperInventory(context.Background()) {
+ t.Fatal("rootless Podman loss did not fall back to typed helper summary")
+ }
+ if agent.helperInventory != helper || agent.docker != nil || agent.runtime != RuntimePodman {
+ t.Fatalf("Podman fallback state = helper:%T docker:%T runtime:%s", agent.helperInventory, agent.docker, agent.runtime)
+ }
+}
+
+func TestCycleBoundaryChangeStopsDirectCallsAndFallsBackToHelper(t *testing.T) {
+ originalRoot := rootlessRuntimeRoot
+ originalUID := effectiveUID
+ originalConnect := connectCollectorRuntimeFn
+ originalMetrics := hostmetricsCollectWithDiskFilters
+ t.Cleanup(func() {
+ rootlessRuntimeRoot = originalRoot
+ effectiveUID = originalUID
+ connectCollectorRuntimeFn = originalConnect
+ hostmetricsCollectWithDiskFilters = originalMetrics
+ })
+
+ rootlessRuntimeRoot = t.TempDir()
+ effectiveUID = os.Geteuid
+ runtimeDir := filepath.Join(rootlessRuntimeRoot, strconv.Itoa(os.Geteuid()))
+ if err := os.MkdirAll(runtimeDir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ socketPath := filepath.Join(runtimeDir, "docker.sock")
+ listener, err := net.Listen("unix", socketPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+
+ postInfoCalls := 0
+ direct := &fakeDockerClient{
+ daemonHost: "unix://" + socketPath,
+ infoFunc: func(context.Context) (systemtypes.Info, error) {
+ return systemtypes.Info{SecurityOptions: []string{"name=seccomp,profile=default"}}, nil
+ },
+ containerListFunc: func(context.Context, dockerContainerListOptions) ([]containertypes.Summary, error) {
+ postInfoCalls++
+ return nil, nil
+ },
+ }
+ connectCollectorRuntimeFn = func(RuntimeKind, *zerolog.Logger) (dockerClient, systemtypes.Info, RuntimeKind, error) {
+ return nil, systemtypes.Info{}, RuntimeAuto, errors.New("replacement failed rootless admission")
+ }
+ hostmetricsCollectWithDiskFilters = func(context.Context, []string, []string) (hostmetrics.Snapshot, error) {
+ return hostmetrics.Snapshot{}, nil
+ }
+ helper := &helperInventoryStub{result: agenthelper.ContainerInventoryResult{
+ Runtimes: []agenthelper.ContainerRuntimeSnapshot{{Runtime: "docker", Available: true}},
+ }}
+ agent := &Agent{
+ cfg: Config{HelperInventory: helper, IncludeContainers: true},
+ docker: newSwappableDockerClient(direct),
+ directServices: true,
+ directTasks: true,
+ runtime: RuntimeDocker,
+ runtimePref: RuntimeDocker,
+ runtimeGoneStreak: runtimeReconnectFailureThreshold - 1,
+ registryChecker: newRegistryCheckerWithConfig(zerolog.Nop(), false),
+ allowedStates: map[string]struct{}{},
+ logger: zerolog.Nop(),
+ reportStreamID: "boundary-change",
+ }
+
+ report, err := agent.collectOnceWithReport(context.Background())
+ if err != nil {
+ t.Fatalf("boundary fallback collection: %v", err)
+ }
+ if postInfoCalls != 0 {
+ t.Fatalf("changed runtime boundary received %d post-Info daemon calls", postInfoCalls)
+ }
+ if agent.helperInventory != helper || agent.docker != nil || report.Host.CollectionMode != agentsdocker.CollectionModeTypedHelperSummary {
+ t.Fatalf("boundary fallback state = helper:%T docker:%T mode:%q", agent.helperInventory, agent.docker, report.Host.CollectionMode)
+ }
+}
diff --git a/internal/dockeragent/rootless_endpoint_other.go b/internal/dockeragent/rootless_endpoint_other.go
index 837e5be618..ca49d3886e 100644
--- a/internal/dockeragent/rootless_endpoint_other.go
+++ b/internal/dockeragent/rootless_endpoint_other.go
@@ -2,4 +2,10 @@
package dockeragent
+import "errors"
+
func collectorOwnsRootlessEndpoint(string) bool { return false }
+
+func collectorRootlessRuntimeCandidates(RuntimeKind) ([]runtimeCandidate, error) {
+ return nil, errors.New("collector-owned rootless container runtimes are supported only on Linux")
+}
diff --git a/internal/dockeragent/runtime_reconnect.go b/internal/dockeragent/runtime_reconnect.go
index eb5d330454..2cc2345cd3 100644
--- a/internal/dockeragent/runtime_reconnect.go
+++ b/internal/dockeragent/runtime_reconnect.go
@@ -2,6 +2,7 @@ package dockeragent
import (
"context"
+ "fmt"
"io"
"sync"
@@ -22,6 +23,19 @@ import (
// ends) and without a reconnect the agent errors forever until restarted.
const runtimeReconnectFailureThreshold = 3
+func validateCollectorDirectRuntime(cli dockerClient, info systemtypes.Info) error {
+ if cli == nil {
+ return fmt.Errorf("collector direct runtime client is nil")
+ }
+ if !collectorOwnsRootlessEndpoint(cli.DaemonHost()) {
+ return fmt.Errorf("direct runtime endpoint %q is not a collector-owned rootless Unix socket", cli.DaemonHost())
+ }
+ if !runtimeInfoIsRootless(info) {
+ return fmt.Errorf("direct runtime endpoint %q did not attest rootless mode", cli.DaemonHost())
+ }
+ return nil
+}
+
// swappableDockerClient lets the agent replace its runtime connection while
// concurrent goroutines (orphan cleanup, container update commands) keep using
// the same dockerClient handle. Only the inner pointer swaps, under the lock.
@@ -174,15 +188,17 @@ func (a *Agent) maybeReconnectRuntime(err error) bool {
Msg("Container runtime endpoint unavailable; reconnect attempt failed")
return false
}
- if a.cfg.HelperInventory != nil && !collectorOwnsRootlessEndpoint(cli.DaemonHost()) {
- endpoint := cli.DaemonHost()
- if closeErr := cli.Close(); closeErr != nil {
- a.logger.Debug().Err(closeErr).Msg("Failed to close rejected runtime reconnect client")
+ if a.cfg.HelperInventory != nil {
+ validationErr := validateCollectorDirectRuntime(cli, info)
+ if validationErr != nil {
+ if closeErr := cli.Close(); closeErr != nil {
+ a.logger.Debug().Err(closeErr).Msg("Failed to close rejected runtime reconnect client")
+ }
+ a.logger.Warn().
+ Err(validationErr).
+ Msg("Rejected runtime reconnect outside the collector-owned rootless boundary")
+ return false
}
- a.logger.Warn().
- Str("daemon_host", endpoint).
- Msg("Rejected runtime reconnect outside the collector-owned rootless boundary")
- return false
}
previous := a.adoptRuntimeConnection(cli, info, runtimeKind)
@@ -199,6 +215,101 @@ func (a *Agent) maybeReconnectRuntime(err error) bool {
return true
}
+// maybePromoteCollectorRootlessRuntime is called under collectMu while the
+// agent is using helper summary inventory. Each collection re-evaluates the
+// exact collector-owned endpoint set, so a rootless daemon that appears later
+// can recover full direct monitoring without a process restart.
+func (a *Agent) maybePromoteCollectorRootlessRuntime() bool {
+ if a == nil || a.helperInventory == nil || a.cfg.HelperInventory == nil {
+ return false
+ }
+
+ cli, info, runtimeKind, err := connectCollectorRuntimeFn(a.runtimePref, &a.logger)
+ if err != nil {
+ return false
+ }
+ if err := validateCollectorDirectRuntime(cli, info); err != nil {
+ if closeErr := cli.Close(); closeErr != nil {
+ a.logger.Debug().Err(closeErr).Msg("Failed to close rejected promoted runtime client")
+ }
+ a.logger.Warn().Err(err).Msg("Rejected promoted runtime outside the collector-owned rootless boundary")
+ return false
+ }
+
+ a.cfg.DisableUpdateChecks = a.directDisableChecks
+ a.cfg.IncludeServices = a.directServices
+ a.cfg.IncludeTasks = a.directTasks
+ previous := a.adoptRuntimeConnection(cli, info, runtimeKind)
+ a.helperInventory = nil
+ if a.registryChecker != nil {
+ a.registryChecker.SetEnabled(!a.cfg.DisableUpdateChecks)
+ }
+ if a.cfg.HelperOperationStatus != nil {
+ a.cfg.HelperOperationStatus.Record("container.inventory", nil)
+ }
+ if previous != nil {
+ if closeErr := previous.Close(); closeErr != nil {
+ a.logger.Debug().Err(closeErr).Msg("Failed to close stale runtime client after helper recovery")
+ }
+ }
+ a.runtimeGoneStreak = 0
+ a.logger.Info().
+ Str("runtime", string(runtimeKind)).
+ Str("daemon_host", cli.DaemonHost()).
+ Msg("Recovered direct collector-owned rootless runtime monitoring")
+ return true
+}
+
+// maybeFallbackToHelperInventory is called under collectMu after direct
+// runtime reconnect has reached its failure threshold. It changes mode only
+// after a complete helper snapshot is available and no direct-runtime
+// background operation remains active.
+func (a *Agent) maybeFallbackToHelperInventory(ctx context.Context) bool {
+ if a == nil || a.helperInventory != nil || a.cfg.HelperInventory == nil || !a.backgroundTasksIdle() {
+ return false
+ }
+
+ probeCtx, cancel := context.WithTimeout(ctx, helperInventoryOperationDeadline)
+ result, err := a.cfg.HelperInventory.Inventory(probeCtx)
+ cancel()
+ if err == nil {
+ _, err = selectHelperRuntime(result, a.runtimePref)
+ }
+ if err != nil {
+ a.recordHelperInventoryStatus(err)
+ a.logger.Warn().Err(err).Msg("Typed helper inventory unavailable during rootless runtime recovery")
+ return false
+ }
+
+ if a.docker != nil {
+ if closeErr := a.docker.Close(); closeErr != nil {
+ a.logger.Debug().Err(closeErr).Msg("Failed to close unavailable direct runtime client")
+ }
+ }
+ a.docker = nil
+ a.helperInventory = a.cfg.HelperInventory
+ a.daemonHost = ""
+ a.daemonID = ""
+ a.cfg.DisableUpdateChecks = true
+ a.cfg.IncludeServices = false
+ a.cfg.IncludeTasks = false
+ if a.registryChecker != nil {
+ a.registryChecker.SetEnabled(false)
+ }
+ a.clearDockerCollectionCaches()
+ a.recordHelperInventoryStatus(nil)
+ a.logger.Info().
+ Str("collection_mode", "typed-helper-summary").
+ Msg("Fell back to typed helper inventory after rootless runtime loss")
+ return true
+}
+
+func (a *Agent) backgroundTasksIdle() bool {
+ a.backgroundMu.Lock()
+ defer a.backgroundMu.Unlock()
+ return !a.updateCheckRunning && !a.cleanupTaskRunning
+}
+
// adoptRuntimeConnection swaps in a freshly discovered runtime connection and
// refreshes the runtime identity fields. Called under collectMu; returns the
// replaced client so the caller can close it.
@@ -208,10 +319,13 @@ func (a *Agent) adoptRuntimeConnection(cli dockerClient, info systemtypes.Info,
previous = sw.swap(cli)
} else {
previous = a.docker
- a.docker = cli
+ a.docker = newSwappableDockerClient(cli)
}
a.daemonHost = cli.DaemonHost()
+ if info.ID != "" {
+ a.daemonID = info.ID
+ }
a.runtimeVer = info.ServerVersion
if runtimeKind != a.runtime {
a.logger.Info().
diff --git a/internal/dockeragent/self_update.go b/internal/dockeragent/self_update.go
index d93eb5e767..c1f4ede380 100644
--- a/internal/dockeragent/self_update.go
+++ b/internal/dockeragent/self_update.go
@@ -81,12 +81,19 @@ func (a *Agent) selfTestToken(target TargetConfig) string {
// checkForUpdates checks if a newer version is available and performs self-update if needed
func (a *Agent) checkForUpdates(ctx context.Context) {
+ if a.cfg.HelperInventory != nil {
+ a.logger.Debug().Msg("Skipping Docker module self-update in monitoring-only collector profile")
+ return
+ }
if !a.tryStartUpdateCheck() {
a.logger.Debug().Msg("Skipping update check - previous check still running")
return
}
defer a.finishUpdateCheck()
+ a.checkForUpdatesTask(ctx)
+}
+func (a *Agent) checkForUpdatesTask(ctx context.Context) {
// Skip updates if disabled via config
if a.cfg.DisableAutoUpdate {
a.logger.Info().Msg("Skipping update check - auto-update disabled")
diff --git a/scripts/install.sh b/scripts/install.sh
index b7e5fd24d7..995bbea862 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -142,6 +142,7 @@ ROOTLESS_RUNTIME_KIND=""
ROOTLESS_RUNTIME_SOCKET_PATH=""
ROOTLESS_RUNTIME_SOCKET_URI=""
ROOTLESS_RUNTIME_XDG_DIR=""
+SAFE_PROFILE_DOCKER_DETECTION_DEFERRED="false"
# Least-privilege profile: run the service as a dedicated system user instead
# of root, with optional exact-command sudo helpers for the two collectors
@@ -3239,7 +3240,7 @@ discover_single_socket_match() {
local candidate=""
for candidate in $pattern; do
- [[ -S "$candidate" ]] || continue
+ [[ -S "$candidate" && ! -L "$candidate" ]] || continue
matches+=("$candidate")
done
@@ -3335,6 +3336,7 @@ discover_rootless_container_runtime() {
safe_profile_selected_rootless_runtime_usable() {
local collector_uid=""
local socket_uid=""
+ local socket_mode=""
[[ -n "$ROOTLESS_RUNTIME_KIND" && -S "$ROOTLESS_RUNTIME_SOCKET_PATH" ]] || return 1
collector_uid=$(id -u "$LEAST_PRIVILEGE_USER" 2>/dev/null || true)
socket_uid=$(stat -c '%u' "$ROOTLESS_RUNTIME_SOCKET_PATH" 2>/dev/null || true)
@@ -3344,6 +3346,187 @@ safe_profile_selected_rootless_runtime_usable() {
runuser -u "$LEAST_PRIVILEGE_USER" -- test -w "$ROOTLESS_RUNTIME_SOCKET_PATH" || return 1
}
+discover_safe_profile_rootless_container_runtime() {
+ local rootless_root="${PULSE_ROOTLESS_RUNTIME_ROOT:-/run/user}"
+ local collector_uid=""
+ local socket_uid=""
+ local candidate=""
+ local matches=()
+
+ ROOTLESS_RUNTIME_KIND=""
+ ROOTLESS_RUNTIME_SOCKET_PATH=""
+ ROOTLESS_RUNTIME_SOCKET_URI=""
+ ROOTLESS_RUNTIME_XDG_DIR=""
+
+ [[ "$(uname -s)" == "Linux" ]] || return 1
+ collector_uid=$(id -u "$LEAST_PRIVILEGE_USER" 2>/dev/null || true)
+ [[ -n "$collector_uid" ]] || return 1
+ command -v runuser >/dev/null 2>&1 || return 1
+
+ for candidate in "${rootless_root}/${collector_uid}/docker.sock"; do
+ [[ -S "$candidate" && ! -L "$candidate" ]] || continue
+ socket_uid=$(stat -c '%u' "$candidate" 2>/dev/null || true)
+ [[ "$socket_uid" == "$collector_uid" ]] || continue
+ socket_mode=$(stat -c '%a' "$candidate" 2>/dev/null || true)
+ [[ "$socket_mode" =~ ^[0-7]+$ ]] || continue
+ (( (8#$socket_mode & 0600) == 0600 )) || continue
+ runuser -u "$LEAST_PRIVILEGE_USER" -- test -r "$candidate" || continue
+ runuser -u "$LEAST_PRIVILEGE_USER" -- test -w "$candidate" || continue
+ matches+=("docker|${candidate}")
+ done
+ for candidate in "${rootless_root}/${collector_uid}/podman/podman.sock"; do
+ [[ -S "$candidate" && ! -L "$candidate" ]] || continue
+ socket_uid=$(stat -c '%u' "$candidate" 2>/dev/null || true)
+ [[ "$socket_uid" == "$collector_uid" ]] || continue
+ socket_mode=$(stat -c '%a' "$candidate" 2>/dev/null || true)
+ [[ "$socket_mode" =~ ^[0-7]+$ ]] || continue
+ (( (8#$socket_mode & 0600) == 0600 )) || continue
+ runuser -u "$LEAST_PRIVILEGE_USER" -- test -r "$candidate" || continue
+ runuser -u "$LEAST_PRIVILEGE_USER" -- test -w "$candidate" || continue
+ matches+=("podman|${candidate}")
+ done
+
+ if [[ "${#matches[@]}" -gt 1 ]]; then
+ log_warn "Multiple collector-owned rootless container-runtime sockets are usable; stop one runtime or preserve one existing installer-owned service pin before retrying."
+ return 1
+ fi
+ [[ "${#matches[@]}" -eq 1 ]] || return 1
+
+ ROOTLESS_RUNTIME_KIND="${matches[0]%%|*}"
+ ROOTLESS_RUNTIME_SOCKET_PATH="${matches[0]#*|}"
+ ROOTLESS_RUNTIME_SOCKET_URI="unix://${ROOTLESS_RUNTIME_SOCKET_PATH}"
+ if [[ "$ROOTLESS_RUNTIME_KIND" == "docker" ]]; then
+ ROOTLESS_RUNTIME_XDG_DIR="$(dirname "$ROOTLESS_RUNTIME_SOCKET_PATH")"
+ else
+ ROOTLESS_RUNTIME_XDG_DIR="${ROOTLESS_RUNTIME_SOCKET_PATH%/podman/podman.sock}"
+ fi
+ return 0
+}
+
+safe_profile_fixed_container_runtime_socket_present() {
+ local candidate=""
+ for candidate in \
+ "${PULSE_SYSTEM_DOCKER_SOCKET:-/var/run/docker.sock}" \
+ /run/podman/podman.sock \
+ /var/run/podman/podman.sock; do
+ [[ -S "$candidate" && ! -L "$candidate" ]] && return 0
+ done
+ return 1
+}
+
+recover_safe_profile_rootless_runtime_pin() {
+ local unit_path="${PULSE_AGENT_SYSTEMD_UNIT_PATH:-/etc/systemd/system/${AGENT_NAME}.service}"
+ local unit_uid=""
+ local unit_mode=""
+ local collector_uid=""
+ local docker_uri=""
+ local podman_uri=""
+ local container_uri=""
+ local selected_uri=""
+ local expected_path=""
+
+ [[ -f "$unit_path" && ! -L "$unit_path" ]] || return 1
+ unit_uid=$(stat -c '%u' "$unit_path" 2>/dev/null || true)
+ unit_mode=$(stat -c '%a' "$unit_path" 2>/dev/null || true)
+ [[ "$unit_uid" == "0" && "$unit_mode" =~ ^[0-7]+$ ]] || return 1
+ (( (8#$unit_mode & 0022) == 0 )) || return 1
+ grep -q "^User=${LEAST_PRIVILEGE_USER}$" "$unit_path" || return 1
+
+ collector_uid=$(id -u "$LEAST_PRIVILEGE_USER" 2>/dev/null || true)
+ [[ -n "$collector_uid" ]] || return 1
+ docker_uri=$(sed -n 's/^Environment="DOCKER_HOST=\(unix:\/\/[^"[:space:]]*\)"$/\1/p' "$unit_path" | sort -u)
+ podman_uri=$(sed -n 's/^Environment="PODMAN_HOST=\(unix:\/\/[^"[:space:]]*\)"$/\1/p' "$unit_path" | sort -u)
+ container_uri=$(sed -n 's/^Environment="CONTAINER_HOST=\(unix:\/\/[^"[:space:]]*\)"$/\1/p' "$unit_path" | sort -u)
+
+ [[ "$docker_uri" != *$'\n'* && "$podman_uri" != *$'\n'* && "$container_uri" != *$'\n'* ]] || return 1
+ if [[ -n "$podman_uri" && -n "$container_uri" && "$podman_uri" != "$container_uri" ]]; then
+ return 1
+ fi
+ [[ -z "$docker_uri" || ( -z "$podman_uri" && -z "$container_uri" ) ]] || return 1
+
+ if [[ -n "$docker_uri" ]]; then
+ ROOTLESS_RUNTIME_KIND="docker"
+ selected_uri="$docker_uri"
+ expected_path="${PULSE_ROOTLESS_RUNTIME_ROOT:-/run/user}/${collector_uid}/docker.sock"
+ else
+ selected_uri="${podman_uri:-$container_uri}"
+ [[ -n "$selected_uri" ]] || return 1
+ ROOTLESS_RUNTIME_KIND="podman"
+ expected_path="${PULSE_ROOTLESS_RUNTIME_ROOT:-/run/user}/${collector_uid}/podman/podman.sock"
+ fi
+
+ ROOTLESS_RUNTIME_SOCKET_PATH="${selected_uri#unix://}"
+ [[ "$ROOTLESS_RUNTIME_SOCKET_PATH" == "$expected_path" ]] || return 1
+ ROOTLESS_RUNTIME_SOCKET_URI="$selected_uri"
+ if [[ "$ROOTLESS_RUNTIME_KIND" == "docker" ]]; then
+ ROOTLESS_RUNTIME_XDG_DIR="$(dirname "$ROOTLESS_RUNTIME_SOCKET_PATH")"
+ else
+ ROOTLESS_RUNTIME_XDG_DIR="${ROOTLESS_RUNTIME_SOCKET_PATH%/podman/podman.sock}"
+ fi
+ return 0
+}
+
+resolve_safe_profile_container_runtime() {
+ local rootless_selected="false"
+
+ if recover_safe_profile_rootless_runtime_pin; then
+ rootless_selected="true"
+ log_info "Preserving the existing collector-owned rootless ${ROOTLESS_RUNTIME_KIND} runtime pin."
+ elif discover_safe_profile_rootless_container_runtime; then
+ rootless_selected="true"
+ fi
+
+ if [[ "$SAFE_PROFILE_DOCKER_DETECTION_DEFERRED" == "true" ]]; then
+ if [[ "$rootless_selected" == "true" ]] || safe_profile_fixed_container_runtime_socket_present; then
+ ENABLE_DOCKER="true"
+ log_info "Container runtime detected without probing a privileged daemon - enabling container monitoring"
+ else
+ ENABLE_DOCKER="false"
+ fi
+ fi
+
+ if [[ "$ENABLE_DOCKER" == "true" && "$rootless_selected" == "true" ]]; then
+ configure_discovered_rootless_runtime_environment
+ fi
+ safe_profile_apply_docker_degradation
+}
+
+resolve_initial_container_monitoring_detection() {
+ [[ "$DOCKER_EXPLICIT" != "true" ]] || return 0
+ if [[ "$LEAST_PRIVILEGE" == "true" && "$PRIVILEGED_HELPER_ENABLED" == "true" ]]; then
+ SAFE_PROFILE_DOCKER_DETECTION_DEFERRED="true"
+ log_info "Safe-profile container detection deferred until the collector account exists; no daemon endpoint is probed as root."
+ elif detect_docker; then
+ log_info "Docker/Podman detected - enabling container monitoring"
+ log_info " (use --disable-docker to skip)"
+ ENABLE_DOCKER="true"
+ else
+ ENABLE_DOCKER="false"
+ fi
+}
+
+configure_discovered_rootless_runtime_environment() {
+ if [[ "$ROOTLESS_RUNTIME_KIND" == "docker" ]]; then
+ if ! service_env_has_key "DOCKER_HOST"; then
+ append_service_env "DOCKER_HOST" "$ROOTLESS_RUNTIME_SOCKET_URI"
+ if ! service_env_has_key "XDG_RUNTIME_DIR"; then
+ append_service_env "XDG_RUNTIME_DIR" "$ROOTLESS_RUNTIME_XDG_DIR"
+ fi
+ log_info "Using rootless Docker socket for agent service: ${ROOTLESS_RUNTIME_SOCKET_PATH}"
+ fi
+ elif [[ "$ROOTLESS_RUNTIME_KIND" == "podman" ]]; then
+ if ! service_env_has_key "CONTAINER_HOST" && ! service_env_has_key "PODMAN_HOST"; then
+ append_service_env "PULSE_DOCKER_RUNTIME" "podman"
+ append_service_env "CONTAINER_HOST" "$ROOTLESS_RUNTIME_SOCKET_URI"
+ append_service_env "PODMAN_HOST" "$ROOTLESS_RUNTIME_SOCKET_URI"
+ if ! service_env_has_key "XDG_RUNTIME_DIR"; then
+ append_service_env "XDG_RUNTIME_DIR" "$ROOTLESS_RUNTIME_XDG_DIR"
+ fi
+ log_info "Using rootless Podman socket for agent service: ${ROOTLESS_RUNTIME_SOCKET_PATH}"
+ fi
+ fi
+}
+
safe_profile_apply_docker_degradation() {
[[ "$SAFE_PROFILE_ACTION" == "apply" && "$ENABLE_DOCKER" == "true" ]] || return 0
if safe_profile_selected_rootless_runtime_usable; then
@@ -4889,15 +5072,7 @@ fi
# Only auto-detect if flags weren't explicitly set
log_info "Detecting available platforms..."
-if [[ "$DOCKER_EXPLICIT" != "true" ]]; then
- if detect_docker; then
- log_info "Docker/Podman detected - enabling container monitoring"
- log_info " (use --disable-docker to skip)"
- ENABLE_DOCKER="true"
- else
- ENABLE_DOCKER="false"
- fi
-fi
+resolve_initial_container_monitoring_detection
if [[ "$KUBERNETES_EXPLICIT" != "true" ]]; then
if detect_kubernetes; then
@@ -4941,32 +5116,18 @@ else
log_info " Command execution is off; enable only when Patrol actions or Proxmox LXC Docker inventory are needed."
fi
-# discover_rootless_container_runtime returns non-zero when a rootful Docker
-# daemon is live, so an explicit --enable-docker with working system Docker
-# never gets the rootless podman socket pinned into the service environment.
-if [[ "$ENABLE_DOCKER" == "true" ]] && discover_rootless_container_runtime; then
- if [[ "$ROOTLESS_RUNTIME_KIND" == "docker" ]]; then
- if ! service_env_has_key "DOCKER_HOST"; then
- append_service_env "DOCKER_HOST" "$ROOTLESS_RUNTIME_SOCKET_URI"
- if ! service_env_has_key "XDG_RUNTIME_DIR"; then
- append_service_env "XDG_RUNTIME_DIR" "$ROOTLESS_RUNTIME_XDG_DIR"
- fi
- log_info "Using rootless Docker socket for agent service: ${ROOTLESS_RUNTIME_SOCKET_PATH}"
- fi
- elif [[ "$ROOTLESS_RUNTIME_KIND" == "podman" ]]; then
- if ! service_env_has_key "CONTAINER_HOST" && ! service_env_has_key "PODMAN_HOST"; then
- append_service_env "PULSE_DOCKER_RUNTIME" "podman"
- append_service_env "CONTAINER_HOST" "$ROOTLESS_RUNTIME_SOCKET_URI"
- append_service_env "PODMAN_HOST" "$ROOTLESS_RUNTIME_SOCKET_URI"
- if ! service_env_has_key "XDG_RUNTIME_DIR"; then
- append_service_env "XDG_RUNTIME_DIR" "$ROOTLESS_RUNTIME_XDG_DIR"
- fi
- log_info "Using rootless Podman socket for agent service: ${ROOTLESS_RUNTIME_SOCKET_PATH}"
- fi
- fi
+# Legacy/root installs retain the system-Docker-first behavior from issue
+# #1647. Typed-helper collectors defer discovery until the dedicated collector
+# account exists, then accept exactly one socket owned and usable by that UID.
+if [[ "$ENABLE_DOCKER" == "true" &&
+ ! ( "$LEAST_PRIVILEGE" == "true" && "$PRIVILEGED_HELPER_ENABLED" == "true" ) ]] &&
+ discover_rootless_container_runtime; then
+ configure_discovered_rootless_runtime_environment
fi
-safe_profile_apply_docker_degradation
+if [[ "$LEAST_PRIVILEGE" != "true" || "$PRIVILEGED_HELPER_ENABLED" != "true" ]]; then
+ safe_profile_apply_docker_degradation
+fi
finalize_plist_env_block
@@ -6596,6 +6757,7 @@ if command -v systemctl >/dev/null 2>&1; then
SERVICE_USER="$LEAST_PRIVILEGE_USER"
provision_least_privilege_user
if [[ "$PRIVILEGED_HELPER_ENABLED" == "true" ]]; then
+ resolve_safe_profile_container_runtime
protect_typed_profile_credentials
provision_typed_privileged_helper
if [[ "$SAFE_PROFILE_ACTION" == "apply" ]]; then
diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.go
index 73c61d8ffe..6daac6cff4 100644
--- a/scripts/installtests/install_sh_test.go
+++ b/scripts/installtests/install_sh_test.go
@@ -2207,6 +2207,11 @@ func TestInstallSHPersistsRootlessContainerRuntimeServiceEnvironment(t *testing.
`ROOTLESS_RUNTIME_SOCKET_URI=""`,
`system_docker_runtime_is_active() {`,
`discover_rootless_container_runtime() {`,
+ `discover_safe_profile_rootless_container_runtime() {`,
+ `recover_safe_profile_rootless_runtime_pin() {`,
+ `resolve_initial_container_monitoring_detection() {`,
+ `resolve_safe_profile_container_runtime() {`,
+ `configure_discovered_rootless_runtime_environment() {`,
// Issue #1647: a live rootful Docker must win before any rootless
// socket discovery pins podman variables into the service environment.
`if system_docker_runtime_is_active; then`,
@@ -2217,6 +2222,9 @@ func TestInstallSHPersistsRootlessContainerRuntimeServiceEnvironment(t *testing.
`append_service_env "CONTAINER_HOST" "$ROOTLESS_RUNTIME_SOCKET_URI"`,
`append_service_env "PODMAN_HOST" "$ROOTLESS_RUNTIME_SOCKET_URI"`,
`append_service_env "XDG_RUNTIME_DIR" "$ROOTLESS_RUNTIME_XDG_DIR"`,
+ `Multiple collector-owned rootless container-runtime sockets are usable`,
+ `provision_least_privilege_user`,
+ `discover_safe_profile_rootless_container_runtime`,
`env_line="$SYSTEMD_ENV_LINES"`,
`local service_env_lines="$SHELL_EXPORT_LINES"`,
`</array>${PLIST_ENV_BLOCK}`,
@@ -2230,6 +2238,249 @@ func TestInstallSHPersistsRootlessContainerRuntimeServiceEnvironment(t *testing.
}
}
+func TestInstallSHSafeProfileRootlessDiscoveryIsCollectorOwnedAndUnambiguous(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("/tmp", "pulse-safe-rootless-*")
+ if err != nil {
+ t.Fatalf("mktemp dir: %v", err)
+ }
+ defer os.RemoveAll(tmpDir)
+
+ dockerDir := filepath.Join(tmpDir, "run", "user", "991")
+ podmanDir := filepath.Join(tmpDir, "run", "user", "991", "podman")
+ if err := os.MkdirAll(dockerDir, 0o755); err != nil {
+ t.Fatalf("mkdir Docker runtime dir: %v", err)
+ }
+ if err := os.MkdirAll(podmanDir, 0o755); err != nil {
+ t.Fatalf("mkdir Podman runtime dir: %v", err)
+ }
+ dockerPath := filepath.Join(dockerDir, "docker.sock")
+ dockerListener, err := net.Listen("unix", dockerPath)
+ if err != nil {
+ t.Fatalf("listen Docker socket: %v", err)
+ }
+ defer dockerListener.Close()
+ podmanPath := filepath.Join(podmanDir, "podman.sock")
+ podmanListener, err := net.Listen("unix", podmanPath)
+ if err != nil {
+ t.Fatalf("listen Podman socket: %v", err)
+ }
+ defer podmanListener.Close()
+
+ common := `
+ set -euo pipefail
+ LEAST_PRIVILEGE_USER=pulse-agent
+ PULSE_ROOTLESS_RUNTIME_ROOT="` + filepath.Join(tmpDir, "run", "user") + `"
+ log_warn() { :; }
+ uname() { echo Linux; }
+ id() { [[ "$1" == "-u" && "$2" == "pulse-agent" ]] && echo 991; }
+ runuser() { return 0; }
+` + extractInstallShellFunction(t, "discover_safe_profile_rootless_container_runtime") + `
+`
+
+ oneOwned := common + `
+ stat() {
+ [[ "$2" == "%a" ]] && { echo 600; return; }
+ case "$3" in
+ "` + dockerPath + `") echo 991 ;;
+ "` + podmanPath + `") echo 1000 ;;
+ *) return 1 ;;
+ esac
+ }
+ discover_safe_profile_rootless_container_runtime
+ [[ "$ROOTLESS_RUNTIME_KIND" == docker ]]
+ [[ "$ROOTLESS_RUNTIME_SOCKET_PATH" == "` + dockerPath + `" ]]
+ `
+ if out, err := exec.Command("bash", "-c", oneOwned).CombinedOutput(); err != nil {
+ t.Fatalf("single collector-owned socket: %v\n%s", err, out)
+ }
+
+ ambiguous := common + `
+ stat() { [[ "$2" == "%a" ]] && echo 600 || echo 991; }
+ if discover_safe_profile_rootless_container_runtime; then
+ echo "ambiguous sockets were accepted" >&2
+ exit 1
+ fi
+ [[ -z "$ROOTLESS_RUNTIME_SOCKET_PATH" ]]
+ `
+ if out, err := exec.Command("bash", "-c", ambiguous).CombinedOutput(); err != nil {
+ t.Fatalf("ambiguous collector-owned sockets: %v\n%s", err, out)
+ }
+
+ crossUser := common + `
+ stat() { echo 1000; }
+ if discover_safe_profile_rootless_container_runtime; then
+ echo "cross-user sockets were accepted" >&2
+ exit 1
+ fi
+ `
+ if out, err := exec.Command("bash", "-c", crossUser).CombinedOutput(); err != nil {
+ t.Fatalf("cross-user sockets: %v\n%s", err, out)
+ }
+
+ unreadable := common + `
+ stat() {
+ [[ "$2" == "%a" ]] && { echo 600; return; }
+ case "$3" in
+ "` + dockerPath + `") echo 991 ;;
+ *) echo 1000 ;;
+ esac
+ }
+ runuser() { return 1; }
+ if discover_safe_profile_rootless_container_runtime; then
+ echo "collector-unreadable socket was accepted" >&2
+ exit 1
+ fi
+ `
+ if out, err := exec.Command("bash", "-c", unreadable).CombinedOutput(); err != nil {
+ t.Fatalf("collector-unreadable socket: %v\n%s", err, out)
+ }
+}
+
+func TestInstallSHSafeProfileRejectsSymlinkedRootlessSocket(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("/tmp", "psr-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(tmpDir)
+ runtimeRoot := filepath.Join(tmpDir, "run", "user")
+ runtimeDir := filepath.Join(runtimeRoot, "991")
+ if err := os.MkdirAll(runtimeDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ realPath := filepath.Join(runtimeDir, "real.sock")
+ listener, err := net.Listen("unix", realPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+ if err := os.Symlink(realPath, filepath.Join(runtimeDir, "docker.sock")); err != nil {
+ t.Fatal(err)
+ }
+
+ script := `
+ set -euo pipefail
+ LEAST_PRIVILEGE_USER=pulse-agent
+ PULSE_ROOTLESS_RUNTIME_ROOT="` + runtimeRoot + `"
+ log_warn() { :; }
+ uname() { echo Linux; }
+ id() { [[ "$1" == -u && "$2" == pulse-agent ]] && echo 991; }
+ stat() { echo 991; }
+ runuser() { return 0; }
+` + extractInstallShellFunction(t, "discover_safe_profile_rootless_container_runtime") + `
+ if discover_safe_profile_rootless_container_runtime; then
+ echo "symlinked runtime socket was accepted" >&2
+ exit 1
+ fi
+ `
+ if out, err := exec.Command("bash", "-c", script).CombinedOutput(); err != nil {
+ t.Fatalf("symlinked safe rootless socket: %v\n%s", err, out)
+ }
+}
+
+func TestInstallSHSafeProfileDefersDetectionWithoutDaemonProbe(t *testing.T) {
+ script := `
+ set -euo pipefail
+ DOCKER_EXPLICIT=false
+ LEAST_PRIVILEGE=true
+ PRIVILEGED_HELPER_ENABLED=true
+ SAFE_PROFILE_DOCKER_DETECTION_DEFERRED=false
+ ENABLE_DOCKER=true
+ probe_log="${TMPDIR}/probe-log"
+ log_info() { :; }
+ detect_docker() { echo daemon-probe >> "$probe_log"; return 0; }
+` + extractInstallShellFunction(t, "resolve_initial_container_monitoring_detection") + `
+ resolve_initial_container_monitoring_detection
+ [[ "$SAFE_PROFILE_DOCKER_DETECTION_DEFERRED" == true ]]
+ [[ ! -e "$probe_log" ]]
+ `
+ cmd := exec.Command("bash", "-c", script)
+ cmd.Env = append(os.Environ(), "TMPDIR="+t.TempDir())
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("deferred safe detection: %v\n%s", err, out)
+ }
+}
+
+func TestInstallSHSafeProfileResolvesRuntimeOnlyAfterCollectorProvisioning(t *testing.T) {
+ script := `
+ set -euo pipefail
+ SAFE_PROFILE_DOCKER_DETECTION_DEFERRED=true
+ ENABLE_DOCKER=false
+ configured=false
+ log_info() { :; }
+ recover_safe_profile_rootless_runtime_pin() { return 1; }
+ discover_safe_profile_rootless_container_runtime() {
+ ROOTLESS_RUNTIME_KIND=docker
+ ROOTLESS_RUNTIME_SOCKET_PATH=/run/user/991/docker.sock
+ ROOTLESS_RUNTIME_SOCKET_URI=unix:///run/user/991/docker.sock
+ ROOTLESS_RUNTIME_XDG_DIR=/run/user/991
+ return 0
+ }
+ safe_profile_fixed_container_runtime_socket_present() { echo unexpected-fixed-probe >&2; return 1; }
+ configure_discovered_rootless_runtime_environment() { configured=true; }
+ safe_profile_apply_docker_degradation() { :; }
+` + extractInstallShellFunction(t, "resolve_safe_profile_container_runtime") + `
+ resolve_safe_profile_container_runtime
+ [[ "$ENABLE_DOCKER" == true && "$configured" == true ]]
+ `
+ if out, err := exec.Command("bash", "-c", script).CombinedOutput(); err != nil {
+ t.Fatalf("post-provision safe runtime resolution: %v\n%s", err, out)
+ }
+}
+
+func TestInstallSHRecoversExactRootlessPinWhileSocketIsOffline(t *testing.T) {
+ tmpDir := t.TempDir()
+ unitPath := filepath.Join(tmpDir, "pulse-agent.service")
+ rootlessRoot := filepath.Join(tmpDir, "run", "user")
+ expectedPath := filepath.Join(rootlessRoot, "991", "docker.sock")
+ unit := "[Service]\nUser=pulse-agent\nEnvironment=\"DOCKER_HOST=unix://" + expectedPath + "\"\n"
+ if err := os.WriteFile(unitPath, []byte(unit), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ script := `
+ set -euo pipefail
+ AGENT_NAME=pulse-agent
+ LEAST_PRIVILEGE_USER=pulse-agent
+ PULSE_AGENT_SYSTEMD_UNIT_PATH="` + unitPath + `"
+ PULSE_ROOTLESS_RUNTIME_ROOT="` + rootlessRoot + `"
+ ROOTLESS_RUNTIME_KIND=""
+ ROOTLESS_RUNTIME_SOCKET_PATH=""
+ ROOTLESS_RUNTIME_SOCKET_URI=""
+ ROOTLESS_RUNTIME_XDG_DIR=""
+ id() { [[ "$1" == -u && "$2" == pulse-agent ]] && echo 991; }
+ stat() {
+ case "$2" in
+ %u) echo 0 ;;
+ %a) echo 644 ;;
+ *) return 1 ;;
+ esac
+ }
+` + extractInstallShellFunction(t, "recover_safe_profile_rootless_runtime_pin") + `
+ if [[ "${EXPECT_REJECT:-false}" == true ]]; then
+ if recover_safe_profile_rootless_runtime_pin; then exit 9; fi
+ exit 0
+ fi
+ recover_safe_profile_rootless_runtime_pin
+ [[ "$ROOTLESS_RUNTIME_KIND" == docker ]]
+ [[ "$ROOTLESS_RUNTIME_SOCKET_PATH" == "` + expectedPath + `" ]]
+ [[ "$ROOTLESS_RUNTIME_SOCKET_URI" == "unix://` + expectedPath + `" ]]
+ [[ ! -e "$ROOTLESS_RUNTIME_SOCKET_PATH" ]]
+ `
+ if out, err := exec.Command("bash", "-c", script).CombinedOutput(); err != nil {
+ t.Fatalf("recover offline rootless pin: %v\n%s", err, out)
+ }
+
+ conflicting := strings.Replace(unit, "\n", "\nEnvironment=\"PODMAN_HOST=unix://"+filepath.Join(rootlessRoot, "991", "podman", "podman.sock")+"\"\n", 1)
+ if err := os.WriteFile(unitPath, []byte(conflicting), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command("bash", "-c", script)
+ cmd.Env = append(os.Environ(), "EXPECT_REJECT=true")
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("conflicting recovered pin was not rejected: %v\n%s", err, out)
+ }
+}
+
func TestInstallSHServiceEnvAccumulatorRendersRootlessSocketVariables(t *testing.T) {
script := `
APPLIED_SERVICE_ENV_KEYS="|"