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(api): validate hosted diagnostics URL before token mint

rcourtman9c23e10858f4
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index d74e9190f1..baa22f2555 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -5865,13 +5865,19 @@ URL validator. An invalid authoritative value, an auto-detected `PublicURL`,
or missing configuration fails closed without consulting direct or forwarded
request authority. Config-owned PVE/PBS install commands and setup-script
bootstrap artifacts resolve that target before creating an API or setup token,
-and password-driven PBS setup resolves it before contacting PBS to derive or
-create the managed token label. `TestContract_HostedInstallerOriginsFailClosedAtRouter`
+the diagnostics Docker/Podman migration route resolves it before creating or
+persisting its lifecycle token, and password-driven PBS setup resolves it
+before contacting PBS to derive or create the managed token label.
+`TestContract_HostedInstallerOriginsFailClosedAtRouter`
exercises those registered routes for PVE and PBS with hostile direct Host,
untrusted and trusted forwarded headers, missing/invalid configuration,
configured URL success, rendered setup-script delivery, and zero token/state
-mutation on failure. The self-hosted precedence and validated live-origin
-fallback remain covered by
+mutation on failure. The diagnostics-specific
+`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`
+adds missing, auto-detected-only, invalid, invalid-high-precedence,
+`PublicURL`, and `AgentConnectURL` router proof with exact in-memory and
+persisted token-state checks. The self-hosted precedence and validated
+live-origin fallback remain covered by that diagnostics proof and
`TestContract_RequestOriginCannotRetargetTokenBearingCommands`.
### Runtime branding stays outside agent lifecycle authority
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 2f1beb26b1..dd5b646077 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -8942,18 +8942,24 @@ propagated into `ConfigHandlers` and passed to that same resolver for every
config-owned caller. Hosted resolution accepts only a canonically validated
authoritative `AgentConnectURL` or explicit, non-auto-detected `PublicURL`; an
invalid higher-precedence value fails closed instead of falling through to a
-different URL or to request headers. `/api/agent-install-command` and
-`/api/setup-script-url` must complete this resolution before minting their API
-or setup token, and PBS password-based add-node handling must complete it
+different URL or to request headers. `/api/agent-install-command`,
+`/api/setup-script-url`, and `/api/diagnostics/docker/prepare-token` must
+complete this resolution before minting their API, setup, or container-runtime
+migration token, and PBS password-based add-node handling must complete it
before deriving its managed token label or contacting PBS. A 503 from this
-boundary therefore leaves the API-token store, setup-token map, PBS remote,
-and configured PBS instances unchanged. The router-level
+boundary therefore leaves the in-memory and persisted API-token stores,
+setup-token map, PBS remote, and configured PBS instances unchanged. The
+router-level
`TestContract_HostedInstallerOriginsFailClosedAtRouter` proves missing,
auto-detected, invalid, direct-Host-spoofed, trusted-forwarded, untrusted-
forwarded, configured `PublicURL`, and configured `AgentConnectURL` cases for
both PVE/PBS commands and setup-script artifacts, including fetching the
-rendered script. Self-hosted live-origin precedence stays on the existing
-adversarial contract proof.
+rendered script. The adjacent
+`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`
+applies the same adversarial matrix to the registered diagnostics migration
+route, proves zero in-memory and persisted token mutation on every hosted
+failure, and preserves both configured-URL precedence and the self-hosted
+request-origin fallback.
### Runtime branding is a narrow presentation contract
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 30bc8b7e6f..f52df152b7 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -5245,12 +5245,16 @@ proves the label and helper text remain readable without horizontal overflow.
For hosted runtimes this is also a fail-closed artifact contract: the backend
accepts only a canonically valid authoritative agent-connect URL or explicit
Public URL and does not substitute auto-detection, direct Host, or forwarded
-headers. Existing setup/install error presentation must therefore retain the
-backend failure and offer configuration recovery rather than synthesizing a
-copyable command or download from local form state. No frontend runtime file
-changes in this slice; the registered-route proof is
-`TestContract_HostedInstallerOriginsFailClosedAtRouter`, while the existing
-settings architecture proof continues to own the Public URL guidance.
+headers. The same backend rule applies to the diagnostics Docker/Podman
+migration artifact before its token exists. Existing setup/install and
+diagnostics error presentation must therefore retain the backend failure and
+offer configuration recovery rather than synthesizing a copyable command or
+download from local form state. No frontend runtime file changes in this
+slice; registered-route proof lives in
+`TestContract_HostedInstallerOriginsFailClosedAtRouter` and
+`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`,
+while the existing settings architecture proof continues to own the Public
+URL guidance.
`frontend-modern/src/utils/discoveryPresentation.ts` now owns the
customer-facing discovery-section framing copy, scan-scope labels, subnet
guidance, command-execution settings targets, API Access handoff labels, and
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 6154f371c6..bfed968c4c 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2250,10 +2250,14 @@ Hosted config-owned callers add one constant-size configured-URL validation
before any token mutation. Missing, auto-detected, or invalid hosted
configuration exits before API-token persistence, setup-token insertion, PBS
network I/O, or instance persistence; successful PVE/PBS command and
-setup-artifact generation performs no additional scan or fan-out. Router-level
-proof lives in `TestContract_HostedInstallerOriginsFailClosedAtRouter`, and the
-self-hosted request-origin matrix remains in
-`TestContract_RequestOriginCannotRetargetTokenBearingCommands`.
+setup-artifact generation performs no additional scan or fan-out. The
+diagnostics Docker/Podman migration route performs the same O(1) resolution
+before token generation and adds no persistence read on its hosted failure
+path. Router-level proof lives in
+`TestContract_HostedInstallerOriginsFailClosedAtRouter` and
+`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`,
+while the self-hosted request-origin matrix remains in those diagnostics cases
+and `TestContract_RequestOriginCannotRetargetTokenBearingCommands`.
### Runtime branding remains a bounded bootstrap read
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 31e5cf158f..9a4deb0242 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1863,13 +1863,17 @@ not only inside the router-owned resolver. `Router.hostedMode` is immutable
input to `ConfigHandlers`; hosted config-owned consumers validate the selected
`AgentConnectURL` or explicit `PublicURL` through the canonical Pulse URL
validator and never accept an auto-detected URL, direct Host, or forwarded
-origin as a substitute. PVE/PBS API-token issuance, setup-token issuance, and
-password-driven PBS token-label creation all occur only after that resolution
-succeeds. `TestContract_HostedInstallerOriginsFailClosedAtRouter` proves that
-missing or invalid hosted configuration returns 503 without an API-token
-record, setup-token record, PBS request, or PBS instance mutation, while a
-valid configured URL remains authoritative under hostile direct, trusted-
-forwarded, and untrusted-forwarded request evidence. The same test follows the
+origin as a substitute. PVE/PBS API-token issuance, setup-token issuance,
+diagnostics container-runtime migration-token issuance, and password-driven
+PBS token-label creation all occur only after that resolution succeeds.
+`TestContract_HostedInstallerOriginsFailClosedAtRouter` proves the config-owned
+install/setup boundary, while
+`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`
+proves that missing, auto-detected-only, invalid, or invalid-higher-precedence
+hosted configuration returns 503 from the registered diagnostics route without
+changing the in-memory or persisted API-token store. Both proofs keep valid
+configured URLs authoritative under hostile direct, trusted-forwarded, and
+untrusted-forwarded request evidence; the install/setup proof also follows the
returned setup artifact through the public script route so the rendered
token-bearing shell body remains bound to the configured origin.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 66047a6d7b..ed0c185a60 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -4957,7 +4957,13 @@ cannot leave a remote PBS token or a partially configured PBS instance. This
changes no backup, restore, datastore, protection, or recovery authority.
`TestContract_HostedInstallerOriginsFailClosedAtRouter` proves the no-state
failure cases and follows successful PVE/PBS artifacts through rendered script
-delivery under hostile direct and forwarded request evidence.
+delivery under hostile direct and forwarded request evidence. The shared
+diagnostics migration route now also resolves that target before its durable
+API-token mutation; its 503 path leaves both in-memory and persisted token
+state unchanged and creates no recovery state. The router-level
+`TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation`
+proves that boundary for missing, auto-detected-only, invalid, precedence, and
+configured success cases without widening storage or recovery authority.
The shared `frontend-modern/src/App.tsx` shell boundary this subsystem consumes
gained one authority gate on its global banner block. The banners rendered
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index b4b9d54916..0f0fe49b1d 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -22921,6 +22921,254 @@ func TestContract_RequestOriginCannotRetargetTokenBearingCommands(t *testing.T)
})
}
+func TestContract_HostedDiagnosticsDockerPrepareTokenValidatesOriginBeforeMutation(t *testing.T) {
+ const existingToken = "hosted-diagnostics-existing.12345678"
+
+ type originHeaders struct {
+ host string
+ remoteAddr string
+ trustedProxyCIDR string
+ forwardedHost string
+ forwardedProto string
+ }
+
+ newRouter := func(t *testing.T, hosted bool, publicURL string, autoDetected bool, agentConnectURL string, headers originHeaders) (*Router, *config.Config, *config.ConfigPersistence, []config.APITokenRecord, string) {
+ t.Helper()
+ if hosted {
+ t.Setenv("PULSE_HOSTED_MODE", "true")
+ } else {
+ t.Setenv("PULSE_HOSTED_MODE", "false")
+ }
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", headers.trustedProxyCIDR)
+ resetTrustedProxyCIDRsForTests()
+
+ existingRecord := newTokenRecord(t, existingToken, []string{config.ScopeSettingsRead}, nil)
+ cfg := newTestConfigWithTokens(t, existingRecord)
+ cfg.AuthUser = "admin"
+ cfg.AuthPass = "configured-password-hash"
+ cfg.FrontendPort = 7655
+ cfg.PublicURL = publicURL
+ cfg.PublicURLAutoDetected = autoDetected
+ cfg.AgentConnectURL = agentConnectURL
+ persistence := config.NewConfigPersistence(cfg.DataPath)
+ if err := persistence.SaveAPITokens(cfg.APITokens); err != nil {
+ t.Fatalf("persist baseline API tokens: %v", err)
+ }
+ baseline, err := persistence.LoadAPITokens()
+ if err != nil {
+ t.Fatalf("load baseline API tokens: %v", err)
+ }
+
+ monitor, state, _ := newTestMonitor(t)
+ state.DockerHosts = []models.DockerHost{{ID: "host-1", DisplayName: "Docker Host"}}
+ router := NewRouter(cfg, monitor, nil, nil, nil, "1.0.0")
+ t.Cleanup(router.shutdownBackgroundWorkers)
+ sessionToken := generateSessionToken()
+ GetSessionStore().CreateSession(sessionToken, time.Hour, "test-browser", "127.0.0.1", "admin")
+ if router.hostedMode != hosted {
+ t.Fatalf("Router hosted mode = %t, want %t", router.hostedMode, hosted)
+ }
+ return router, cfg, persistence, baseline, sessionToken
+ }
+
+ doRequest := func(t *testing.T, router *Router, sessionToken string, headers originHeaders) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/api/diagnostics/docker/prepare-token", strings.NewReader(`{"agentId":"host-1"}`))
+ req.Host = headers.host
+ req.RemoteAddr = headers.remoteAddr
+ if headers.forwardedHost != "" {
+ req.Header.Set("X-Forwarded-Host", headers.forwardedHost)
+ }
+ if headers.forwardedProto != "" {
+ req.Header.Set("X-Forwarded-Proto", headers.forwardedProto)
+ }
+ req.AddCookie(&http.Cookie{Name: sessionCookieName(isConnectionSecure(req)), Value: sessionToken})
+ req.Header.Set("X-CSRF-Token", generateCSRFToken(sessionToken))
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ return rec
+ }
+
+ assertTokenRecordsEqual := func(t *testing.T, label string, got []config.APITokenRecord, want []config.APITokenRecord) {
+ t.Helper()
+ gotJSON, err := json.Marshal(got)
+ if err != nil {
+ t.Fatalf("marshal %s API tokens: %v", label, err)
+ }
+ wantJSON, err := json.Marshal(want)
+ if err != nil {
+ t.Fatalf("marshal baseline API tokens: %v", err)
+ }
+ if string(gotJSON) != string(wantJSON) {
+ t.Fatalf("%s API tokens mutated: got %s, want %s", label, gotJSON, wantJSON)
+ }
+ }
+
+ assertPersistedUnchanged := func(t *testing.T, persistence *config.ConfigPersistence, baseline []config.APITokenRecord) {
+ t.Helper()
+ persisted, err := persistence.LoadAPITokens()
+ if err != nil {
+ t.Fatalf("load persisted API tokens: %v", err)
+ }
+ assertTokenRecordsEqual(t, "persisted", persisted, baseline)
+ }
+
+ failureCases := []struct {
+ name string
+ publicURL string
+ autoDetected bool
+ agentConnectURL string
+ headers originHeaders
+ }{
+ {
+ name: "missing configuration ignores hostile direct Host and untrusted forwarding",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "auto-detected URL is not hosted authority",
+ publicURL: "https://auto-detected.example",
+ autoDetected: true,
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ },
+ },
+ {
+ name: "invalid PublicURL ignores trusted forwarding",
+ publicURL: "https://[email protected]",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "192.0.2.44:41000",
+ trustedProxyCIDR: "192.0.2.0/24",
+ forwardedHost: "trusted-forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "invalid higher-precedence AgentConnectURL does not fall through",
+ publicURL: "https://configured.example",
+ agentConnectURL: "https://agents.example/path?retarget=attacker",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ }
+
+ for _, tc := range failureCases {
+ t.Run(tc.name, func(t *testing.T) {
+ router, cfg, persistence, baseline, sessionToken := newRouter(t, true, tc.publicURL, tc.autoDetected, tc.agentConnectURL, tc.headers)
+ rec := doRequest(t, router, sessionToken, tc.headers)
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ }
+ assertTokenRecordsEqual(t, "in-memory", cfg.APITokens, baseline)
+ if strings.Contains(rec.Body.String(), "attacker") {
+ t.Fatalf("failure response retained attacker-controlled origin: %q", rec.Body.String())
+ }
+ assertPersistedUnchanged(t, persistence, baseline)
+ })
+ }
+
+ successCases := []struct {
+ name string
+ publicURL string
+ agentConnectURL string
+ wantBaseURL string
+ headers originHeaders
+ }{
+ {
+ name: "configured PublicURL defeats hostile direct Host and untrusted forwarding",
+ publicURL: "https://configured.example/base/",
+ wantBaseURL: "https://configured.example/base",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "http",
+ },
+ },
+ {
+ name: "configured AgentConnectURL outranks PublicURL and trusted forwarding",
+ publicURL: "https://configured.example",
+ agentConnectURL: "https://agents.configured.example/",
+ wantBaseURL: "https://agents.configured.example",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "192.0.2.44:41000",
+ trustedProxyCIDR: "192.0.2.0/24",
+ forwardedHost: "trusted-forwarded-attacker.example",
+ forwardedProto: "http",
+ },
+ },
+ }
+
+ for _, tc := range successCases {
+ t.Run(tc.name, func(t *testing.T) {
+ router, cfg, persistence, baseline, sessionToken := newRouter(t, true, tc.publicURL, false, tc.agentConnectURL, tc.headers)
+ rec := doRequest(t, router, sessionToken, tc.headers)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ var response map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if response["pulseURL"] != tc.wantBaseURL {
+ t.Fatalf("pulseURL = %q, want %q", response["pulseURL"], tc.wantBaseURL)
+ }
+ command, _ := response["installCommand"].(string)
+ if !strings.Contains(command, tc.wantBaseURL+"/install.sh") || strings.Contains(command, "attacker") {
+ t.Fatalf("install command was not bound to configured URL %q: %q", tc.wantBaseURL, command)
+ }
+ if len(cfg.APITokens) != len(baseline)+1 {
+ t.Fatalf("in-memory API token count = %d, want %d", len(cfg.APITokens), len(baseline)+1)
+ }
+ persisted, err := persistence.LoadAPITokens()
+ if err != nil {
+ t.Fatalf("load persisted API tokens: %v", err)
+ }
+ if len(persisted) != len(baseline)+1 {
+ t.Fatalf("persisted API token count = %d, want %d", len(persisted), len(baseline)+1)
+ }
+ })
+ }
+
+ t.Run("self-hosted request-origin fallback remains available", func(t *testing.T) {
+ headers := originHeaders{host: "pulse.lan:7655", remoteAddr: "198.51.100.20:41000"}
+ router, cfg, persistence, baseline, sessionToken := newRouter(t, false, "", false, "", headers)
+ rec := doRequest(t, router, sessionToken, headers)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ var response map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if response["pulseURL"] != "http://pulse.lan:7655" {
+ t.Fatalf("pulseURL = %q, want self-hosted request origin", response["pulseURL"])
+ }
+ if len(cfg.APITokens) != len(baseline)+1 {
+ t.Fatalf("in-memory API token count = %d, want %d", len(cfg.APITokens), len(baseline)+1)
+ }
+ persisted, err := persistence.LoadAPITokens()
+ if err != nil {
+ t.Fatalf("load persisted API tokens: %v", err)
+ }
+ if len(persisted) != len(baseline)+1 {
+ t.Fatalf("persisted API token count = %d, want %d", len(persisted), len(baseline)+1)
+ }
+ })
+}
+
func TestContract_HostedInstallerOriginsFailClosedAtRouter(t *testing.T) {
const adminToken = "hosted-installer-admin.12345678"
diff --git a/internal/api/router.go b/internal/api/router.go
index 186c52d3e5..3d730c0c0f 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -10886,6 +10886,15 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req
enableHost = *payload.EnableHost
}
+ // Resolve the credential target before minting or persisting the token.
+ // Hosted mode deliberately has no request-origin or localhost fallback, so
+ // an absent or invalid authoritative URL must leave token state untouched.
+ baseURL := normalizeAgentInstallBaseURL(r.resolvePublicURL(req))
+ if r.hostedMode && baseURL == "" {
+ writeConfigAgentInstallBaseURLUnavailable(w)
+ return
+ }
+
rawToken, err := auth.GenerateAPIToken()
if err != nil {
log.Error().Err(err).Msg("Failed to generate container runtime migration token")
@@ -10944,7 +10953,6 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req
}
config.Mu.Unlock()
- baseURL := normalizeAgentInstallBaseURL(r.resolvePublicURL(req))
installCommand := buildContainerRuntimeAgentInstallCommand(baseURL, rawToken, enableHost)
systemdSnippet := fmt.Sprintf("[Service]\nType=simple\nEnvironment=\"PULSE_URL=%s\"\nEnvironment=\"PULSE_TOKEN=%s\"\nExecStart=/usr/local/bin/pulse-agent --url %s --token %s --enable-docker %s --interval 30s\nRestart=always\nRestartSec=5s\nUser=root", baseURL, rawToken, baseURL, rawToken, containerRuntimeAgentHostFlag(enableHost))