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.

fix(agent): refuse to serve an agent binary older than the server

rcourtman883e95102305
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 4915725589..e8acbe0880 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -100,6 +100,17 @@ looser about location than an install's, but never about the far end of the
name: a backup copy of a wrapper script, or an editor holding one open, is not
a supervisor and must never be a termination target.
+An agent and the wrapper that starts it are one unit, so a server must never
+hand out an agent older than the wrapper template it will be launched by. The
+installer renders that wrapper from the server's current template, and an agent
+predating a flag the template now passes exits on startup and crash-loops under
+its supervisor, which reads as a broken host rather than a version mismatch.
+The download path therefore refuses an agent binary that does not carry the
+server's own agent version, and resolves that expected version from the same
+source the agent build stamps in rather than from a compiled-in build
+placeholder, because development builds carry placeholders no version parser
+accepts and those are precisely the builds whose local artifacts go stale.
+
Mock mode is a clean room on the report-admission boundary. Mock mode already
suspends pull-based PVE/PBS/PMG collection by never building those clients, and
push-based agent reports are held to the same rule: `ApplyHostReport`,
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 19aa5ecee6..0dc8b65465 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -6872,6 +6872,15 @@ download the shared installer into an ephemeral directory, run
`/download/pulse-agent?arch=...` is reachable with checksum metadata, and
pass selected tokens to the installer through an ephemeral `--token-file`
instead of a raw `--token` service argument.
+`/download/pulse-agent` serves only an agent binary carrying this server's own
+agent version. A local artifact that satisfies the report-contract and
+signature checks but predates the running server is refused the same way an
+incompatible one is, because the installer renders its wrapper from the current
+template and an older agent rejects flags that template now passes. Callers
+must treat the resulting 404 as a build or packaging fault to be surfaced, not
+as an absent architecture to be worked around; on published releases the route
+falls through to the release-asset proxy and returns the matching version
+instead.
The loopback-originated install and setup payloads now also preserve the full
configured `PublicURL` when that URL is the canonical external route, instead
of rewriting only the host and inheriting an `http://` request-local scheme
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 8f73451a89..e61aaaa642 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -2795,7 +2795,21 @@ For Unix-family copied host installs, the deployment-owned shell installer must
support preflight before privilege escalation: `--preflight-only` may run
without root, must check both `/api/health` and the exact
`/download/pulse-agent?arch=...` artifact for checksum metadata, and must fail
-before installation if the server cannot provide that binary. Token-bearing
+before installation if the server cannot provide that binary.
+A server may only hand out an agent binary that carries its own agent version.
+Local agent artifacts are build outputs that nothing refreshes on their own, so
+they go stale silently, and staleness is not cosmetic: the installer renders its
+service wrapper from this server's current template, so a binary predating a
+flag that template now passes fails to start and crash-loops under its
+supervisor. The download path therefore refuses a binary that does not carry the
+expected version, alongside the existing report-contract and signature checks.
+The expected version resolves from the same source the agent build stamps in,
+never from a compiled-in placeholder, because development builds carry
+placeholders that no version parser accepts and those are exactly the builds
+whose artifacts go stale. Refusal is loud rather than silent: a development
+server answers 404 naming the stale path and the build command, and a published
+release falls through to the release-asset proxy and fetches the matching
+version. Token-bearing
copy-paste commands must pass credentials through ephemeral `--token-file`
transport and leave the installed service configured with the persistent
runtime token file, never a raw `--token` process argument.
diff --git a/internal/api/unified_agent.go b/internal/api/unified_agent.go
index eb08ad9376..7ac213cf92 100644
--- a/internal/api/unified_agent.go
+++ b/internal/api/unified_agent.go
@@ -199,6 +199,7 @@ func (r *Router) handleDownloadUnifiedAgent(w http.ResponseWriter, req *http.Req
)
}
+ expectedAgentVersion := expectedAgentBinaryVersion(r.resolveAgentBinaryVersionSource())
invalidCandidates := make([]string, 0, len(searchPaths))
for _, candidate := range searchPaths {
@@ -211,7 +212,7 @@ func (r *Router) handleDownloadUnifiedAgent(w http.ResponseWriter, req *http.Req
continue
}
- if err := validateUnifiedAgentBinary(candidate); err != nil {
+ if err := validateUnifiedAgentBinary(candidate, expectedAgentVersion); err != nil {
log.Warn().Err(err).Str("path", candidate).Msg("Skipping incompatible local unified agent binary")
invalidCandidates = append(invalidCandidates, fmt.Sprintf("%s (%v)", candidate, err))
continue
@@ -284,14 +285,25 @@ func (r *Router) handleDownloadUnifiedAgent(w http.ResponseWriter, req *http.Req
http.Error(w, "Agent binary not found. Specify ?arch=linux-amd64 (or your architecture)", http.StatusNotFound)
}
-func validateUnifiedAgentBinary(path string) error {
+// validateUnifiedAgentBinary rejects a local agent binary that this server must
+// not hand out. The endpoint checks catch a binary built against a superseded
+// report contract; the version check catches one that is merely old.
+//
+// Staleness is not cosmetic. The installer generates its wrapper from this
+// server's current template, so a binary predating a flag that template now
+// passes fails to start and crash-loops under the watchdog. `bin/` is a
+// gitignored build output that nothing refreshes on its own, so it goes stale
+// silently. Refusing here turns that into a loud failure at the point of
+// download: a dev server answers 404 with the build command, and a published
+// release falls through to the GitHub proxy and fetches the correct version.
+func validateUnifiedAgentBinary(path string, expectedVersion string) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("open binary: %w", err)
}
defer file.Close()
- hasCanonical, hasLegacy, err := scanUnifiedAgentBinaryContract(file)
+ hasCanonical, hasLegacy, hasVersion, err := scanUnifiedAgentBinaryContract(file, expectedVersion)
if err != nil {
return fmt.Errorf("scan binary contract: %w", err)
}
@@ -301,16 +313,69 @@ func validateUnifiedAgentBinary(path string) error {
if !hasCanonical {
return fmt.Errorf("missing canonical host endpoint %s", canonicalUnifiedAgentReportPath)
}
+ if !hasVersion {
+ return fmt.Errorf("stale build: does not carry this server's agent version %s", expectedVersion)
+ }
return nil
}
-func scanUnifiedAgentBinaryContract(r io.Reader) (hasCanonical bool, hasLegacy bool, err error) {
+// resolveAgentBinaryVersionSource picks the version this server should expect
+// its agent binaries to carry.
+//
+// It deliberately prefers updates.GetCurrentVersion over the compiled-in
+// serverVersion. A development server is exactly where agent binaries go stale,
+// and there the compiled-in value is a placeholder ("dev", "dev-pro") that no
+// version parser accepts, which would silently disable the freshness check on
+// the only builds that need it. GetCurrentVersion resolves the VERSION file,
+// the same source `make build-agents` stamps into the agent, so dev and release
+// builds compare against one identity. IsDevelopment is intentionally not
+// consulted: a dev build still knows which agent it expects.
+func (r *Router) resolveAgentBinaryVersionSource() string {
+ if versionInfo, err := updates.GetCurrentVersion(); err == nil && versionInfo != nil {
+ if resolved := strings.TrimSpace(versionInfo.Version); resolved != "" {
+ return resolved
+ }
+ }
+ return r.serverVersion
+}
+
+// expectedAgentBinaryVersion reduces a server version to the release-identity
+// string that `make build-agents` stamps into the agent through
+// -X main.Version, i.e. "v6.2.0-rc.8" for a server reporting
+// "6.2.0-rc.8+git.44.gdd72bd149.dirty". Build metadata is dropped because it
+// records how the server itself was built and never appears in the agent.
+// Returns "" when the version cannot be parsed, which disables the freshness
+// check rather than rejecting every candidate.
+func expectedAgentBinaryVersion(rawVersion string) string {
+ rawVersion = strings.TrimSpace(rawVersion)
+ if rawVersion == "" || strings.EqualFold(rawVersion, "dev") {
+ return ""
+ }
+ version, err := updates.ParseVersion(rawVersion)
+ if err != nil {
+ return ""
+ }
+ identity := fmt.Sprintf("v%d.%d.%d", version.Major, version.Minor, version.Patch)
+ if prerelease := strings.TrimSpace(version.Prerelease); prerelease != "" {
+ identity += "-" + prerelease
+ }
+ return identity
+}
+
+func scanUnifiedAgentBinaryContract(r io.Reader, versionNeedle string) (hasCanonical bool, hasLegacy bool, hasVersion bool, err error) {
canonicalNeedle := []byte(canonicalUnifiedAgentReportPath)
legacyNeedle := []byte(legacyUnifiedAgentReportPath)
+ versionBytes := []byte(versionNeedle)
+ // An empty needle would match everything, so treat "no expected version"
+ // as "already satisfied" and skip the comparison entirely.
+ hasVersion = len(versionBytes) == 0
maxNeedleLen := len(canonicalNeedle)
if len(legacyNeedle) > maxNeedleLen {
maxNeedleLen = len(legacyNeedle)
}
+ if len(versionBytes) > maxNeedleLen {
+ maxNeedleLen = len(versionBytes)
+ }
overlap := maxNeedleLen - 1
if overlap < 0 {
overlap = 0
@@ -328,8 +393,11 @@ func scanUnifiedAgentBinaryContract(r io.Reader) (hasCanonical bool, hasLegacy b
if bytes.Contains(window, legacyNeedle) {
hasLegacy = true
}
- if hasCanonical && hasLegacy {
- return true, true, nil
+ if !hasVersion && bytes.Contains(window, versionBytes) {
+ hasVersion = true
+ }
+ if hasCanonical && hasLegacy && hasVersion {
+ return true, true, true, nil
}
if len(window) > overlap {
window = append(window[:0], window[len(window)-overlap:]...)
@@ -339,10 +407,10 @@ func scanUnifiedAgentBinaryContract(r io.Reader) (hasCanonical bool, hasLegacy b
break
}
if readErr != nil {
- return false, false, readErr
+ return false, false, false, readErr
}
}
- return hasCanonical, hasLegacy, nil
+ return hasCanonical, hasLegacy, hasVersion, nil
}
// proxyAgentBinaryFromGitHub downloads an agent binary from GitHub releases and serves
diff --git a/internal/api/unified_agent_test.go b/internal/api/unified_agent_test.go
index 81ac70ec61..1036856dd7 100644
--- a/internal/api/unified_agent_test.go
+++ b/internal/api/unified_agent_test.go
@@ -15,6 +15,7 @@ import (
"strings"
"testing"
+ "github.com/rcourtman/pulse-go-rewrite/internal/updates"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -36,8 +37,20 @@ func setupUnifiedAgentRouter(t *testing.T) (*Router, string) {
return router, tempDir
}
+// expectedAgentVersionForTest mirrors what the download handler will look for,
+// so fixtures that stand in for a healthy agent carry the version a real build
+// would. Without it every "valid" fixture reads as a stale build.
+func expectedAgentVersionForTest() string {
+ versionInfo, err := updates.GetCurrentVersion()
+ if err != nil || versionInfo == nil {
+ return ""
+ }
+ return expectedAgentBinaryVersion(versionInfo.Version)
+}
+
func validTestUnifiedAgentBinary(suffix string) []byte {
- return []byte("ELF test binary " + canonicalUnifiedAgentReportPath + " " + suffix)
+ return []byte("ELF test binary " + canonicalUnifiedAgentReportPath + " " +
+ expectedAgentVersionForTest() + " " + suffix)
}
func staleTestUnifiedAgentBinary(suffix string) []byte {
@@ -562,3 +575,74 @@ func buildTestTarGz(t *testing.T, name string, payload []byte) []byte {
require.NoError(t, gzw.Close())
return buf.Bytes()
}
+
+// writeAgentBinaryFixture builds a stand-in for a compiled agent. The real
+// validator is a byte scan, so a file carrying the same needles exercises it
+// faithfully without shipping a multi-megabyte binary into the test tree.
+func writeAgentBinaryFixture(t *testing.T, reportPath string, versionString string) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "pulse-agent")
+ body := "\x7fELF padding " + reportPath + " more padding " + versionString + " trailing\n"
+ if err := os.WriteFile(path, []byte(body), 0o755); err != nil {
+ t.Fatalf("write agent fixture: %v", err)
+ }
+ return path
+}
+
+func TestExpectedAgentBinaryVersionDropsBuildMetadata(t *testing.T) {
+ cases := map[string]string{
+ // A dev server carries git metadata the agent never has.
+ "6.2.0-rc.8+git.44.gdd72bd149.dirty": "v6.2.0-rc.8",
+ "6.2.0-rc.8": "v6.2.0-rc.8",
+ "v6.1.2": "v6.1.2",
+ // Unknown versions disable the check rather than rejecting everything.
+ // "dev-pro" is the enterprise build's compiled-in placeholder: it is
+ // why the caller resolves the version through updates.GetCurrentVersion
+ // instead of the compiled-in serverVersion, because a dev server is
+ // exactly where agent binaries go stale and this value would silently
+ // switch the freshness check off there.
+ "dev": "",
+ "dev-pro": "",
+ "": "",
+ "not-a-version": "",
+ }
+ for input, want := range cases {
+ if got := expectedAgentBinaryVersion(input); got != want {
+ t.Errorf("expectedAgentBinaryVersion(%q) = %q, want %q", input, got, want)
+ }
+ }
+}
+
+func TestValidateUnifiedAgentBinaryRejectsStaleBuild(t *testing.T) {
+ // The shape that broke a live host: a binary on the canonical report
+ // contract, so every existing check passes, but built weeks earlier.
+ stale := writeAgentBinaryFixture(t, canonicalUnifiedAgentReportPath, "v6.0.5-54-gc862fb0ca0")
+
+ if err := validateUnifiedAgentBinary(stale, "v6.2.0-rc.8"); err == nil {
+ t.Fatal("a binary that does not carry this server's agent version must be refused")
+ } else if !strings.Contains(err.Error(), "stale build") {
+ t.Fatalf("error should name staleness, got %v", err)
+ }
+
+ // Premise check: without the version guard this same binary is accepted,
+ // which is exactly how it reached a host in the first place.
+ if err := validateUnifiedAgentBinary(stale, ""); err != nil {
+ t.Fatalf("premise check failed: the stale binary is supposed to pass every other check, got %v", err)
+ }
+}
+
+func TestValidateUnifiedAgentBinaryAcceptsMatchingBuild(t *testing.T) {
+ current := writeAgentBinaryFixture(t, canonicalUnifiedAgentReportPath, "v6.2.0-rc.8")
+ if err := validateUnifiedAgentBinary(current, "v6.2.0-rc.8"); err != nil {
+ t.Fatalf("a binary carrying this server's agent version must be served: %v", err)
+ }
+}
+
+func TestValidateUnifiedAgentBinaryStillRejectsLegacyContract(t *testing.T) {
+ // The version guard must not displace the endpoint guard: a correctly
+ // versioned binary on the deprecated report path is still refused.
+ legacy := writeAgentBinaryFixture(t, legacyUnifiedAgentReportPath, "v6.2.0-rc.8")
+ if err := validateUnifiedAgentBinary(legacy, "v6.2.0-rc.8"); err == nil {
+ t.Fatal("a binary on the deprecated report endpoint must still be refused")
+ }
+}