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): harden PVE and PBS installer origins

rcourtman9ac11eeb548b
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 0a62ea72e6..91f9e714e1 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -9177,7 +9177,21 @@
],
"coverage_gaps": [],
"candidate_lanes": [],
- "work_claims": [],
+ "work_claims": [
+ {
+ "id": "installer-origin-019fde93-lane-l16",
+ "agent_id": "installer-origin-019fde93",
+ "summary": "Harden PVE/PBS token-bearing install commands through the canonical trust-aware request-origin resolver and add endpoint-specific adversarial proof.",
+ "target_id": "v6-product-lane-expansion",
+ "claimed_at": "2026-08-08T09:11:11Z",
+ "heartbeat_at": "2026-08-08T09:11:11Z",
+ "expires_at": "2026-08-08T17:11:11Z",
+ "work_item": {
+ "kind": "lane",
+ "id": "L16"
+ }
+ }
+ ],
"open_decisions": [
{
"id": "self-hosted-commercial-surfaces-owner-approval",
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 56e3cf1e73..7cd4986168 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -5827,18 +5827,24 @@ host-token bootstrap, and concurrent-completion contracts.
### Shared internal/api request-origin resolution is lifecycle credential targeting
The shared `internal/api` boundary this subsystem consumes now routes
-`requestOriginBaseURL`, in-memory public-URL capture, and
-`Router.resolvePublicURL` through one `resolveRequestOrigin` trust boundary in
+`requestOriginBaseURL`, in-memory public-URL capture,
+`Router.resolvePublicURL`, config-owned PVE/PBS install commands, and
+setup-script artifacts through one `resolveRequestOrigin` trust boundary and
+one `resolveConfiguredPublicBaseURL` precedence function in
`internal/api/router.go`. Forwarded host, scheme, and port are admitted only
from an immediate peer in `PULSE_TRUSTED_PROXY_CIDRS`; direct and forwarded
hosts must pass strict authority validation, including bounded ports and valid
-IPv4/IPv6 forms, before they can become an absolute URL.
+IPv4/IPv6 forms, before they can become an absolute URL. The prior
+`resolveLoopbackAwarePublicBaseURL` implementation is retired so lifecycle
+code cannot drift back to raw request authority or untrusted forwarded scheme
+handling.
The earlier governance claim that this derivation touched no token issuance,
update targeting, or fleet lifecycle was false once live request origin began
outranking an auto-detected public URL. The resolved value targets
-token-bearing diagnostics install commands and cluster deployment payloads,
-and it also feeds hosted install, onboarding, and agent URL projections.
+token-bearing config PVE/PBS install commands, setup-script artifacts,
+diagnostics install commands, and cluster deployment payloads, and it also
+feeds hosted install, onboarding, and agent URL projections.
Therefore lifecycle consumers must treat it as an API/security credential-
target boundary: explicit `AgentConnectURL` or operator `PublicURL` remains
authoritative, only validated live origin may replace an auto-detected guess,
@@ -5846,7 +5852,9 @@ invalid request evidence falls back safely, and hosted mode never guesses.
It does not itself grant registration or command authority, but raw Host or
forwarded headers must never bypass it before credentials are placed into an
install or deploy transport. `TestContract_RequestOriginCannotRetargetTokenBearingCommands`
-is the routed lifecycle/API proof.
+is the routed lifecycle/API proof and invokes the actual
+`POST /api/agent-install-command` PVE/PBS handler so every asserted target is
+paired with the fresh token returned by that endpoint.
### 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 f9cfb73a7b..5bedfb54df 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -8909,25 +8909,33 @@ behavior.
### Request-origin fallback cannot retarget credential-bearing commands
-`Router.resolvePublicURL` preserves the live-origin behavior required when an
-auto-detected LAN address is only a stale guess, but request-derived evidence
-now comes exclusively from `resolveRequestOrigin`. `AgentConnectURL` remains
-authoritative, an explicitly configured `PublicURL` remains authoritative, a
-validated live request origin may outrank only an auto-detected `PublicURL`,
-and invalid or absent request evidence falls back to that auto-detected value
-before the local frontend default. Hosted mode still never uses request origin
-or localhost.
+`resolveConfiguredPublicBaseURL` is the single precedence function behind
+`Router.resolvePublicURL`, config-owned PVE/PBS install commands, setup-script
+artifacts, and request-derived PBS token labels. Request evidence inside that
+function comes exclusively from `resolveRequestOrigin`. `AgentConnectURL`
+remains authoritative, an explicitly configured `PublicURL` remains
+authoritative, a validated live request origin may outrank only an
+auto-detected `PublicURL`, and invalid or absent request evidence falls back to
+that auto-detected value before the local frontend default. Hosted mode still
+never uses request origin or localhost. The superseded
+`resolveLoopbackAwarePublicBaseURL` path is retired rather than retained as a
+second raw-header implementation.
This resolver is a credential-target boundary, not presentation-only URL
-formatting. The diagnostics Docker/Podman migration response embeds a freshly
-minted token in its install command and service snippet, while cluster deploy
-install payloads pair `pulse_url` with per-target bootstrap tokens. Those
-consumers, hosted agent-install generation, onboarding, privileged security
-status, and magic-link URL generation must not read raw `Host` or forwarded
-headers around the resolver. `TestContract_RequestOriginCannotRetargetTokenBearingCommands`
-pins untrusted and malformed header rejection, trusted-proxy preserved-host
-behavior, IPv4/IPv6 and port handling, explicit configuration precedence, and
-the exact diagnostics/deploy target paired with token-bearing transport.
+formatting. `POST /api/agent-install-command` embeds a freshly minted PVE/PBS
+API token in its returned installer command, setup-script artifacts carry a
+short-lived setup token, the diagnostics Docker/Podman migration response
+embeds a fresh token in its install command and service snippet, and cluster
+deploy install payloads pair `pulse_url` with per-target bootstrap tokens.
+Those consumers, hosted agent-install generation, onboarding, privileged
+security status, and magic-link URL generation must not read raw `Host` or
+forwarded headers around the resolver.
+`TestContract_RequestOriginCannotRetargetTokenBearingCommands` now exercises
+the real PVE/PBS endpoint and pins Host-spoof containment, untrusted and trusted
+forwarded-header behavior, malformed authority rejection, IPv4/IPv6 and port
+handling, `AgentConnectURL` and explicit `PublicURL` precedence, auto-detected
+and local fallback, and the exact sanitized target paired with each fresh
+token-bearing command.
### 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 e723455f20..5d557ab6df 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -5236,6 +5236,12 @@ workspace instead of the System/Network route. Shared prop contracts for the
network-boundary surface must extend
`frontend-modern/src/components/Settings/networkSettingsModel.ts` instead of
re-expanding the shell or reintroducing page-local section types.
+The Public URL control must describe both customer alert links and copied
+agent install/update command targets, recommend the externally reachable HTTPS
+domain used through a reverse proxy, and present request auto-detection as a
+fallback rather than implying the field affects notifications alone. The
+settings architecture proof pins that copy, and the responsive browser receipt
+proves the label and helper text remain readable without horizontal overflow.
`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 6d27fb3887..60d14c028a 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2237,13 +2237,15 @@ metrics fan-out, or background work to `GET /api/agent/version`.
### Canonical request-origin resolution on internal/api/router.go stays O(1)
-`resolveRequestOrigin` and `requestOriginBaseURL` in `internal/api/router.go`
-perform bounded trusted-peer lookup, header selection, and strict authority
-parsing on the request already in hand. Reuse by public-URL capture, SSO
-responses, install-command targeting, deployment payloads, onboarding, and
-security status adds no inventory scan, persistence read, metrics fan-out, or
-background work. The trusted-proxy CIDR cache remains process-local, and the
-resolver's request cost is bounded by the small authority/header inputs.
+`resolveRequestOrigin`, `requestOriginBaseURL`, and
+`resolveConfiguredPublicBaseURL` in `internal/api/router.go` perform bounded
+trusted-peer lookup, header selection, strict authority parsing, and constant-
+size configuration precedence on the request already in hand. Reuse by
+public-URL capture, SSO responses, config-owned PVE/PBS install commands,
+setup-script artifacts, deployment payloads, onboarding, and security status
+adds no inventory scan, persistence read, metrics fan-out, or background work.
+The trusted-proxy CIDR cache remains process-local, and the resolver's request
+cost is bounded by the small authority/header inputs.
### 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 e9d0ebf23e..2b0c7c7ac5 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1830,7 +1830,9 @@ replacement validation remain mandatory and fail closed.
### Request-derived absolute URLs share one trusted command-target boundary
`internal/api/router.go` owns one `resolveRequestOrigin` boundary behind
-`requestOriginBaseURL`, public-URL capture, and `Router.resolvePublicURL`.
+`requestOriginBaseURL`, public-URL capture, and the shared
+`resolveConfiguredPublicBaseURL` precedence function consumed by
+`Router.resolvePublicURL` and config-owned installer paths.
Direct `Host` values must parse as strict HTTP authorities and reject
userinfo, schemes, path/query/fragment bytes, whitespace and controls,
malformed DNS labels, invalid IPv4/IPv6 bracket forms, and ports outside
@@ -1843,14 +1845,18 @@ a valid direct fallback.
This derivation is not authorization evidence, but it is security-sensitive
credential targeting. A validated live origin may outrank only an
auto-detected `PublicURL`; `AgentConnectURL` and explicit `PublicURL` remain
-authoritative. Diagnostics install commands, cluster deploy payloads, hosted
+authoritative. Config-owned PVE/PBS install commands and setup-script
+artifacts, diagnostics install commands, cluster deploy payloads, hosted
install commands, onboarding payloads, security status, SSO endpoint
responses, and magic links must consume the canonical resolver instead of raw
request headers because several of those payloads pair the resulting URL with
-fresh API or bootstrap tokens. Hosted mode remains fail-closed without a
-configured external URL. The adversarial contract proof is
+fresh API or bootstrap tokens. The legacy loopback-aware helper that copied
+raw `Host` and untrusted forwarded scheme values is retired. Hosted mode
+remains fail-closed without a configured external URL. The adversarial
+contract proof is
`TestContract_RequestOriginCannotRetargetTokenBearingCommands` in
-`internal/api/contract_test.go`.
+`internal/api/contract_test.go`, including direct execution of the PVE/PBS
+`POST /api/agent-install-command` handler with a newly minted token.
### The global security banner no longer scores a truncated status payload
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 394124805e..a4c3363324 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -4933,16 +4933,19 @@ reconstructing them from local table state.
### Shared internal/api request-origin resolution creates no recovery state
The shared `internal/api` boundary this subsystem consumes routes
-`requestOriginBaseURL`, `capturePublicURLFromRequest`, and
-`Router.resolvePublicURL` through one strict `resolveRequestOrigin` trust
-boundary in `internal/api/router.go`. The resolver itself performs no
-persistence. Capture may update the running config's auto-detected public URL
-for notification and SAML consumers, while command-target resolution may use
-the validated live origin ahead of that auto-detected guess; neither behavior
-creates a recovery point, backup artifact, restore authority, or protection
-freshness fact. No request-derived origin is written to storage/recovery
-records, and tenant workspace preservation or recovery flows that copy
-`system.json` remain outside this URL trust boundary.
+`requestOriginBaseURL`, `capturePublicURLFromRequest`,
+`Router.resolvePublicURL`, config-owned install commands, setup-script
+artifacts, and PBS token labels through one strict `resolveRequestOrigin`
+trust boundary and one `resolveConfiguredPublicBaseURL` precedence function in
+`internal/api/router.go`. The resolver itself performs no persistence. Capture
+may update the running config's auto-detected public URL for notification and
+SAML consumers, while command-target resolution may use the validated live
+origin ahead of that auto-detected guess; neither behavior creates a recovery
+point, backup artifact, restore authority, or protection freshness fact. The
+retired loopback-aware helper no longer provides a second request-header path.
+No request-derived origin is written to storage/recovery records, and tenant
+workspace preservation or recovery flows that copy `system.json` remain
+outside this URL trust boundary.
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/agent_install_command_shared.go b/internal/api/agent_install_command_shared.go
index 436fda94eb..527c87f3ee 100644
--- a/internal/api/agent_install_command_shared.go
+++ b/internal/api/agent_install_command_shared.go
@@ -3,10 +3,8 @@ package api
import (
"errors"
"fmt"
- "net"
"net/http"
"net/url"
- "strconv"
"strings"
"time"
@@ -186,53 +184,6 @@ func withPrivilegeEscalation(command string) string {
`; else echo "Root privileges required. Run as root (su -) and retry." >&2; exit 1; fi; }`
}
-func requestTargetsLocalFrontend(host string, frontendPort int) bool {
- if frontendPort <= 0 {
- return false
- }
-
- parsedHost, parsedPort, err := net.SplitHostPort(strings.TrimSpace(host))
- if err != nil || parsedPort != strconv.Itoa(frontendPort) {
- return false
- }
-
- switch strings.Trim(parsedHost, "[]") {
- case "127.0.0.1", "localhost", "::1":
- return true
- default:
- return false
- }
-}
-
-func resolveLoopbackAwarePublicBaseURL(req *http.Request, cfg *config.Config) string {
- if req != nil && cfg != nil && requestTargetsLocalFrontend(req.Host, cfg.FrontendPort) {
- if publicURL := strings.TrimSpace(cfg.PublicURL); publicURL != "" {
- if parsedURL, err := url.Parse(publicURL); err == nil && parsedURL.Scheme != "" && parsedURL.Host != "" {
- return strings.TrimRight(parsedURL.String(), "/")
- }
- }
- }
-
- host := ""
- if req != nil {
- host = strings.TrimSpace(req.Host)
- }
- if host == "" {
- if cfg != nil && cfg.FrontendPort > 0 {
- host = fmt.Sprintf("localhost:%d", cfg.FrontendPort)
- } else {
- host = "localhost:7655"
- }
- }
-
- scheme := "http"
- if req != nil && (req.TLS != nil || strings.EqualFold(req.Header.Get("X-Forwarded-Proto"), "https")) {
- scheme = "https"
- }
-
- return fmt.Sprintf("%s://%s", scheme, host)
-}
-
func buildProxmoxAgentInstallCommand(opts agentInstallCommandOptions) string {
baseURL := normalizeAgentInstallBaseURL(opts.BaseURL)
installScriptURL := baseURL + "/install.sh"
@@ -397,11 +348,5 @@ func buildSetupScriptInstallArtifact(baseURL string, installType string, host st
}
func resolveConfigAgentInstallBaseURL(req *http.Request, cfg *config.Config) string {
- if cfg != nil {
- if agentConnectURL := strings.TrimSpace(cfg.AgentConnectURL); agentConnectURL != "" {
- return normalizeAgentInstallBaseURL(agentConnectURL)
- }
- }
-
- return resolveLoopbackAwarePublicBaseURL(req, cfg)
+ return resolveConfiguredPublicBaseURL(req, cfg, false)
}
diff --git a/internal/api/config_node_handlers.go b/internal/api/config_node_handlers.go
index dbb75dab60..2df769b7ad 100644
--- a/internal/api/config_node_handlers.go
+++ b/internal/api/config_node_handlers.go
@@ -581,7 +581,7 @@ func (h *ConfigHandlers) handleAddNode(w http.ResponseWriter, r *http.Request) {
// Fallback to password auth
pbsPassword = req.Password
} else {
- pulseURL := resolveLoopbackAwarePublicBaseURL(r, h.getConfig(r.Context()))
+ pulseURL := resolveConfiguredPublicBaseURL(r, h.getConfig(r.Context()), false)
tokenName := buildPulseMonitorTokenName(pulseURL)
tokenID, tokenSecret, err := pbsClient.SetupMonitoringAccess(context.Background(), tokenName)
diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.go
index be711f31b4..88543bf02f 100644
--- a/internal/api/config_setup_handlers.go
+++ b/internal/api/config_setup_handlers.go
@@ -729,7 +729,7 @@ func (h *ConfigHandlers) handleSetupScriptURL(w http.ResponseWriter, r *http.Req
Msg("Generated temporary setup token")
// Build the canonical bootstrap artifact for setup-script transport.
- pulseURL := resolveLoopbackAwarePublicBaseURL(r, h.getConfig(r.Context()))
+ pulseURL := resolveConfiguredPublicBaseURL(r, h.getConfig(r.Context()), false)
artifact := buildSetupScriptInstallArtifact(
pulseURL,
req.Type,
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 17154a949b..b3ad3ada22 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -7217,7 +7217,7 @@ func TestContract_AssignProfileRejectsMissingProfile(t *testing.T) {
}
}
-func TestContract_ResolveLoopbackAwarePublicBaseURLPreservesConfiguredHTTPS(t *testing.T) {
+func TestContract_ResolveConfiguredPublicBaseURLPreservesConfiguredHTTPS(t *testing.T) {
cfg := &config.Config{
PublicURL: "https://public.example.com/base/",
FrontendPort: 7655,
@@ -7225,7 +7225,7 @@ func TestContract_ResolveLoopbackAwarePublicBaseURLPreservesConfiguredHTTPS(t *t
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Host = "127.0.0.1:7655"
- if got := resolveLoopbackAwarePublicBaseURL(req, cfg); got != "https://public.example.com/base" {
+ if got := resolveConfiguredPublicBaseURL(req, cfg, false); got != "https://public.example.com/base" {
t.Fatalf("baseURL = %q, want %q", got, "https://public.example.com/base")
}
}
@@ -22662,6 +22662,262 @@ func TestContract_RequestOriginCannotRetargetTokenBearingCommands(t *testing.T)
t.Fatalf("deploy payload retained attacker-controlled origin bytes: %s", encoded)
}
})
+
+ t.Run("PVE and PBS install endpoint uses only the canonical resolved origin", func(t *testing.T) {
+ type installOriginCase struct {
+ name string
+ installType string
+ trustedProxyCIDR string
+ publicURL string
+ publicAuto bool
+ agentConnectURL string
+ host string
+ remoteAddr string
+ tls bool
+ headers map[string]string
+ wantBaseURL string
+ forbidden []string
+ }
+
+ cases := []installOriginCase{
+ {
+ name: "PVE ignores untrusted forwarded host proto and port",
+ installType: "pve",
+ publicURL: autoDetectedURL,
+ publicAuto: true,
+ host: "pulse.lan:7655",
+ remoteAddr: "198.51.100.20:43210",
+ headers: map[string]string{
+ "X-Forwarded-Host": "forwarded-attacker.example",
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-Port": "443",
+ },
+ wantBaseURL: "http://pulse.lan:7655",
+ forbidden: []string{"forwarded-attacker.example"},
+ },
+ {
+ name: "PBS accepts external IPv6 origin from a trusted proxy",
+ installType: "pbs",
+ trustedProxyCIDR: "192.0.2.0/24",
+ publicURL: autoDetectedURL,
+ publicAuto: true,
+ host: "backend.internal:7655",
+ remoteAddr: "192.0.2.44:41000",
+ headers: map[string]string{
+ "X-Forwarded-Host": "2001:db8::20",
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-Port": "8443",
+ },
+ wantBaseURL: "https://[2001:db8::20]:8443",
+ forbidden: []string{"backend.internal"},
+ },
+ {
+ name: "PVE preserves direct IPv4 authority and port",
+ installType: "pve",
+ publicURL: autoDetectedURL,
+ publicAuto: true,
+ host: "192.0.2.10:8765",
+ remoteAddr: "198.51.100.20:43210",
+ wantBaseURL: "http://192.0.2.10:8765",
+ },
+ {
+ name: "PBS rejects direct userinfo to auto-detected fallback",
+ installType: "pbs",
+ publicURL: autoDetectedURL,
+ publicAuto: true,
+ remoteAddr: "198.51.100.20:43210",
+ wantBaseURL: autoDetectedURL,
+ forbidden: []string{"attacker.example"},
+ },
+ {
+ name: "PVE rejects direct path bytes to auto-detected fallback",
+ installType: "pve",
+ publicURL: autoDetectedURL,
+ publicAuto: true,
+ host: "attacker.example/path",
+ remoteAddr: "198.51.100.20:43210",
+ wantBaseURL: autoDetectedURL,
+ forbidden: []string{"attacker.example"},
+ },
+ {
+ name: "PBS rejects direct control bytes to auto-detected fallback",
+ installType: "pbs",
+ publicURL: autoDetectedURL,
+ publicAuto: true,
+ host: "attacker.example\r\nX-Injected: yes",
+ remoteAddr: "198.51.100.20:43210",
+ wantBaseURL: autoDetectedURL,
+ forbidden: []string{"attacker.example", "X-Injected"},
+ },
+ {
+ name: "PVE rejects out-of-range direct port to auto-detected fallback",
+ installType: "pve",
+ publicURL: autoDetectedURL,
+ publicAuto: true,
+ host: "attacker.example:70000",
+ remoteAddr: "198.51.100.20:43210",
+ wantBaseURL: autoDetectedURL,
+ forbidden: []string{"attacker.example"},
+ },
+ {
+ name: "PVE ignores malformed trusted forwarded fields independently",
+ installType: "pve",
+ trustedProxyCIDR: "192.0.2.0/24",
+ publicURL: autoDetectedURL,
+ publicAuto: true,
+ host: "pulse.lan:9443",
+ remoteAddr: "192.0.2.44:41000",
+ tls: true,
+ headers: map[string]string{
+ "X-Forwarded-Host": "https://attacker.example/path",
+ "X-Forwarded-Proto": "javascript",
+ "X-Forwarded-Scheme": "also-invalid",
+ "X-Forwarded-Port": "70000",
+ },
+ wantBaseURL: "https://pulse.lan:9443",
+ forbidden: []string{"attacker.example", "javascript"},
+ },
+ {
+ name: "PBS explicit PublicURL defeats valid Host spoofing",
+ installType: "pbs",
+ publicURL: "https://configured.example/base/",
+ host: "host-spoof.attacker.example:9443",
+ remoteAddr: "198.51.100.20:43210",
+ wantBaseURL: "https://configured.example/base",
+ forbidden: []string{"host-spoof.attacker.example"},
+ },
+ {
+ name: "PVE AgentConnectURL outranks configured and forwarded origins",
+ installType: "pve",
+ trustedProxyCIDR: "192.0.2.0/24",
+ publicURL: "https://configured.example/base",
+ agentConnectURL: "https://agents.example:9443/",
+ host: "host-spoof.attacker.example",
+ remoteAddr: "192.0.2.44:41000",
+ headers: map[string]string{
+ "X-Forwarded-Host": "forwarded-attacker.example",
+ "X-Forwarded-Proto": "http",
+ },
+ wantBaseURL: "https://agents.example:9443",
+ forbidden: []string{"host-spoof.attacker.example", "forwarded-attacker.example", "configured.example"},
+ },
+ {
+ name: "PBS malformed request uses safe local fallback without configured URL",
+ installType: "pbs",
+ host: "pulse.example:7655;curl-attacker",
+ remoteAddr: "198.51.100.20:43210",
+ wantBaseURL: "http://localhost:7655",
+ forbidden: []string{"curl-attacker"},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", tc.trustedProxyCIDR)
+ resetTrustedProxyCIDRsForTests()
+
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ AuthUser: "admin",
+ AuthPass: "hashed-password",
+ FrontendPort: 7655,
+ PublicURL: tc.publicURL,
+ PublicURLAutoDetected: tc.publicAuto,
+ AgentConnectURL: tc.agentConnectURL,
+ }
+ handler := &ConfigHandlers{
+ defaultConfig: cfg,
+ defaultPersistence: config.NewConfigPersistence(cfg.DataPath),
+ }
+
+ req := httptest.NewRequest(
+ http.MethodPost,
+ "/api/agent-install-command",
+ strings.NewReader(fmt.Sprintf(`{"type":%q}`, tc.installType)),
+ )
+ req.Host = tc.host
+ req.RemoteAddr = tc.remoteAddr
+ if tc.tls {
+ req.TLS = &tls.ConnectionState{}
+ }
+ for name, value := range tc.headers {
+ req.Header.Set(name, value)
+ }
+
+ rec := httptest.NewRecorder()
+ handler.HandleAgentInstallCommand(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+
+ var response AgentInstallCommandResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if response.Token == "" || !strings.Contains(response.Command, response.Token) {
+ t.Fatalf("fresh token was not carried by install command: %#v", response)
+ }
+ if !strings.Contains(response.Command, tc.wantBaseURL+"/install.sh") ||
+ !strings.Contains(response.Command, "--url "+posixShellQuote(tc.wantBaseURL)) {
+ t.Fatalf("install command did not use resolved base URL %q: %q", tc.wantBaseURL, response.Command)
+ }
+ for _, forbidden := range tc.forbidden {
+ if strings.Contains(response.Command, forbidden) {
+ t.Fatalf("install command retained forbidden origin bytes %q: %q", forbidden, response.Command)
+ }
+ }
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("minted token record count = %d, want 1", len(cfg.APITokens))
+ }
+ })
+ }
+ })
+
+ t.Run("setup-script artifact cannot retarget its setup token", func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")
+ resetTrustedProxyCIDRsForTests()
+
+ cfg := &config.Config{
+ DataPath: t.TempDir(),
+ FrontendPort: 7655,
+ PublicURL: autoDetectedURL,
+ PublicURLAutoDetected: true,
+ }
+ handler := newTestConfigHandlers(t, cfg)
+ req := httptest.NewRequest(
+ http.MethodPost,
+ "/api/setup-script-url",
+ strings.NewReader(`{"type":"pve","host":"pve1.local"}`),
+ )
+ req.Host = "[email protected]/path:70000"
+ req.RemoteAddr = "198.51.100.20:43210"
+ req.Header.Set("X-Forwarded-Host", "forwarded-attacker.example")
+ req.Header.Set("X-Forwarded-Proto", "https")
+
+ rec := httptest.NewRecorder()
+ handler.HandleSetupScriptURL(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+
+ var artifact setupScriptInstallArtifact
+ if err := json.Unmarshal(rec.Body.Bytes(), &artifact); err != nil {
+ t.Fatalf("decode setup artifact: %v", err)
+ }
+ if artifact.SetupToken == "" ||
+ !strings.Contains(artifact.DownloadURL, artifact.SetupToken) ||
+ !strings.Contains(artifact.Command, artifact.SetupToken) {
+ t.Fatalf("setup token was not carried by canonical artifact: %#v", artifact)
+ }
+ if !strings.HasPrefix(artifact.URL, autoDetectedURL+"/api/setup-script?") ||
+ !strings.HasPrefix(artifact.DownloadURL, autoDetectedURL+"/api/setup-script?") {
+ t.Fatalf("setup artifact did not use sanitized fallback %q: %#v", autoDetectedURL, artifact)
+ }
+ if strings.Contains(artifact.Command, "attacker") || strings.Contains(artifact.DownloadURL, "attacker") {
+ t.Fatalf("setup artifact retained attacker-controlled origin bytes: %#v", artifact)
+ }
+ })
}
// Issue1649 regression coverage. Docker update (and every other typed) action
diff --git a/internal/api/router.go b/internal/api/router.go
index f115a8867b..bbc443f27f 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -10966,24 +10966,24 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req
}
}
-func (r *Router) resolvePublicURL(req *http.Request) string {
- if r == nil || r.config == nil {
+func resolveConfiguredPublicBaseURL(req *http.Request, cfg *config.Config, hostedMode bool) string {
+ if cfg == nil {
return ""
}
// Hosted mode must never fall back to request host or localhost.
// A canonical externally-reachable URL must be configured via PublicURL / AgentConnectURL.
- if r != nil && r.hostedMode {
- if agentConnectURL := strings.TrimSpace(r.config.AgentConnectURL); agentConnectURL != "" {
+ if hostedMode {
+ if agentConnectURL := strings.TrimSpace(cfg.AgentConnectURL); agentConnectURL != "" {
return strings.TrimRight(agentConnectURL, "/")
}
- if publicURL := strings.TrimSpace(r.config.PublicURL); publicURL != "" {
+ if publicURL := strings.TrimSpace(cfg.PublicURL); publicURL != "" {
return strings.TrimRight(publicURL, "/")
}
return ""
}
- if agentConnectURL := strings.TrimSpace(r.config.AgentConnectURL); agentConnectURL != "" {
+ if agentConnectURL := strings.TrimSpace(cfg.AgentConnectURL); agentConnectURL != "" {
return strings.TrimRight(agentConnectURL, "/")
}
@@ -10991,8 +10991,8 @@ func (r *Router) resolvePublicURL(req *http.Request) string {
// is only a guess (boot-time LAN IP probe or first-request capture), so the
// live request's own origin outranks it: the URL the admin is browsing
// right now is fresher evidence of how this instance is reached (#1692).
- publicURL := strings.TrimSpace(r.config.PublicURL)
- if publicURL != "" && !r.config.PublicURLAutoDetected {
+ publicURL := strings.TrimSpace(cfg.PublicURL)
+ if publicURL != "" && !cfg.PublicURLAutoDetected {
return strings.TrimRight(publicURL, "/")
}
@@ -11004,12 +11004,19 @@ func (r *Router) resolvePublicURL(req *http.Request) string {
return strings.TrimRight(publicURL, "/")
}
- if r.config.FrontendPort > 0 {
- return fmt.Sprintf("http://localhost:%d", r.config.FrontendPort)
+ if cfg.FrontendPort > 0 {
+ return fmt.Sprintf("http://localhost:%d", cfg.FrontendPort)
}
return "http://localhost:7655"
}
+func (r *Router) resolvePublicURL(req *http.Request) string {
+ if r == nil {
+ return ""
+ }
+ return resolveConfiguredPublicBaseURL(req, r.config, r.hostedMode)
+}
+
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil