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 request-derived command origins

rcourtman860f639f3b84
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 0a62ea72e6..0385711216 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": "request-origin-security-20260808-lane-l6",
+ "agent_id": "request-origin-security-20260808",
+ "summary": "Contain request-origin spoofing in token-bearing API command generation and repair API/security/lifecycle contracts",
+ "target_id": "v6-product-lane-expansion",
+ "claimed_at": "2026-08-08T08:28:31Z",
+ "heartbeat_at": "2026-08-08T08:28:31Z",
+ "expires_at": "2026-08-08T16:28:31Z",
+ "work_item": {
+ "kind": "lane",
+ "id": "L6"
+ }
+ }
+ ],
"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 98b3856401..56e3cf1e73 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -5824,19 +5824,29 @@ split. `internal/hostagent/proxmox_setup_test.go`,
health, first-install, type/host binding, one-time consumption, rejection,
host-token bootstrap, and concurrent-completion contracts.
-### Shared internal/api request-origin helpers are read-only URL derivation
-
-The shared `internal/api` boundary this subsystem consumes gained
-`requestOriginBaseURL`, `requestForwardedScheme` and `requestForwardedHost` in
-`internal/api/router.go`, factored out of the existing SSO OIDC callback URL
-builder so SSO provider responses can derive endpoint URLs from the inbound
-request instead of guessing `http://localhost:7655`. The helpers only read the
-request; they honor forwarded headers under the same trusted-proxy gate the
-callback builder already applied, and they neither mutate nor persist
-`config.PublicURL`. No agent registration, token issuance, command admission,
-update targeting, or fleet-lifecycle authority is touched, and the
-extension-point expectations on `internal/api/` and `internal/api/router.go`
-are otherwise unchanged.
+### 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
+`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.
+
+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.
+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,
+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.
### 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 d90994a0ff..f9cfb73a7b 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -8887,13 +8887,17 @@ Identity Provider, so a localhost guess was copied straight into an IdP where
it fails with no diagnosable cause; the admin's own request, by contrast,
necessarily arrived over an address that reaches Pulse.
-The request-derived base URL uses the shared
-`requestOriginBaseURL` / `requestForwardedScheme` / `requestForwardedHost`
-helpers in `internal/api/router.go`, which honor `X-Forwarded-Proto`,
-`X-Forwarded-Scheme` and `X-Forwarded-Host` only when the immediate peer is a
-trusted proxy (`PULSE_TRUSTED_PROXY_CIDRS`). `buildSSOOIDCCallbackURL` in
-`internal/api/oidc_handlers.go` now shares those helpers; its output is
-unchanged.
+The request-derived base URL uses the single `resolveRequestOrigin` trust
+boundary behind `requestOriginBaseURL` in `internal/api/router.go`. Direct
+`Host` is accepted only as a strict host authority: userinfo, schemes, paths,
+queries, fragments, whitespace/control characters, malformed labels, invalid
+brackets, and out-of-range ports fail closed. `X-Forwarded-Proto`,
+`X-Forwarded-Scheme`, `X-Forwarded-Host`, and `X-Forwarded-Port` are considered
+only when the immediate peer is a trusted proxy
+(`PULSE_TRUSTED_PROXY_CIDRS`); malformed forwarded fields are ignored and a
+valid direct authority remains the fallback. `buildSSOOIDCCallbackURL` in
+`internal/api/oidc_handlers.go` consumes the same base-URL resolver rather than
+reassembling scheme and host independently.
All five fields are `omitempty` and are now omitted entirely when neither
source resolves a host, rather than carrying a wrong absolute URL. Clients must
@@ -8903,6 +8907,28 @@ in `internal/api/contract_test.go` pins the precedence, the request fallback,
the trusted-proxy gate on forwarded headers, and the empty-rather-than-wrong
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.
+
+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.
+
### Runtime branding is a narrow presentation contract
`GET /api/runtime/branding` is the authenticated `monitoring:read` boundary
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 8ace7a569b..6d27fb3887 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2235,14 +2235,15 @@ remains an O(1) target projection. Cache-prevention headers and the
agent-supplied non-secret cache key add no inventory scan, persistence read,
metrics fan-out, or background work to `GET /api/agent/version`.
-### Request-origin URL helpers on internal/api/router.go stay O(1)
-
-The `requestForwardedScheme`, `requestForwardedHost` and `requestOriginBaseURL`
-helpers added to `internal/api/router.go` perform only header reads and string
-manipulation on the request already in hand. They add no inventory scan,
-persistence read, lock acquisition, metrics fan-out, or background work, and
-their cost is constant per SSO provider entry rendered in the admin settings
-response.
+### 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.
### 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 0c03e488b4..e9d0ebf23e 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1827,20 +1827,30 @@ rejected. The target-version query on `/download/pulse-agent` is cache identity,
not trust evidence: checksum, embedded-key signature, self-test, and atomic
replacement validation remain mandatory and fail closed.
-### Request-derived SSO endpoint URLs keep the trusted-proxy gate
-
-`internal/api/router.go` gained `requestForwardedScheme`,
-`requestForwardedHost` and `requestOriginBaseURL`, extracted verbatim from the
-SSO OIDC callback URL builder so SSO provider responses can derive endpoint
-URLs from the inbound request instead of returning a hardcoded
-`http://localhost:7655`. The trust boundary is unchanged and fail-closed:
-`X-Forwarded-Proto`, `X-Forwarded-Scheme` and `X-Forwarded-Host` are honored
-only when the immediate peer matches `PULSE_TRUSTED_PROXY_CIDRS`, which is
-empty by default, so an untrusted client cannot steer a returned URL to a host
-or scheme of its choosing — it can only reach the same `Host` header handling
-the request already depends on. The derived value is returned in an
-admin-authenticated settings response and is never persisted, never used as a
-redirect target, and never used to make an authorization decision.
+### 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`.
+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
+1-65535. `X-Forwarded-Proto`, `X-Forwarded-Scheme`, `X-Forwarded-Host`, and
+`X-Forwarded-Port` are honored only when the immediate peer matches
+`PULSE_TRUSTED_PROXY_CIDRS`, which is empty by default. Invalid forwarded
+values are ignored independently rather than being copied or allowed to erase
+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
+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
+`TestContract_RequestOriginCannotRetargetTokenBearingCommands` in
+`internal/api/contract_test.go`.
### 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 bd5f5bc9eb..394124805e 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -4930,19 +4930,19 @@ while storage detail drawers and filter controls must route summary series IDs,
source tones, and disk metrics through the shared storage helpers instead of
reconstructing them from local table state.
-### Shared internal/api request-origin helpers persist nothing
-
-The shared `internal/api` boundary this subsystem consumes gained
-`requestOriginBaseURL`, `requestForwardedScheme` and `requestForwardedHost` in
-`internal/api/router.go`, used by `internal/api/identity_sso_handlers.go` to
-derive SSO endpoint URLs from the inbound request when no public URL is
-configured. The derivation is per-response and read-only: nothing is written to
-`system.json`, the SSO config, or any other persisted artifact, and the
-separate `capturePublicURLFromRequest` detection path that does persist a
-detected public URL is unchanged. Tenant workspace preservation, recovery flows
-that copy `system.json` forward, and backup or restore attribution are
-unaffected, and the extension-point expectations on `internal/api/` and
-`internal/api/router.go` are otherwise unchanged.
+### 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.
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 ea9b279170..17154a949b 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -22499,6 +22499,171 @@ func TestContract_SSOProviderResponseBaseURLNeverGuessesLocalhost(t *testing.T)
})
}
+// TestContract_RequestOriginCannotRetargetTokenBearingCommands pins the single
+// request-origin trust boundary used by SSO URLs, agent install commands, and
+// deploy payloads. Direct Host remains useful live-origin evidence only after
+// strict authority validation; forwarded values require an explicitly trusted
+// immediate proxy.
+func TestContract_RequestOriginCannotRetargetTokenBearingCommands(t *testing.T) {
+ const autoDetectedURL = "http://192.168.50.10:7655"
+
+ newRouter := func() *Router {
+ return &Router{config: &config.Config{
+ PublicURL: autoDetectedURL,
+ PublicURLAutoDetected: true,
+ FrontendPort: 7655,
+ }}
+ }
+
+ t.Run("untrusted forwarded origin is ignored", func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")
+ resetTrustedProxyCIDRsForTests()
+
+ req := httptest.NewRequest(http.MethodPost, "http://pulse.lan:7655/api/diagnostics/docker/prepare-token", nil)
+ req.RemoteAddr = "198.51.100.20:43210"
+ req.Header.Set("X-Forwarded-Host", "attacker.example")
+ req.Header.Set("X-Forwarded-Proto", "https")
+ req.Header.Set("X-Forwarded-Port", "443")
+
+ if got, want := newRouter().resolvePublicURL(req), "http://pulse.lan:7655"; got != want {
+ t.Fatalf("untrusted forwarded origin resolved to %q, want %q", got, want)
+ }
+ })
+
+ t.Run("malformed direct hosts fall back without carrying attacker bytes", func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")
+ resetTrustedProxyCIDRsForTests()
+
+ for _, host := range []string{
+ "pulse.example/path",
+ "pulse.example?next=attacker",
+ "pulse.example#fragment",
+ "pulse.example:7655;curl-attacker",
+ "pulse.example\r\nX-Injected: attacker",
+ " pulse.example ",
+ "[2001:db8::1]garbage",
+ "example..com",
+ "example.com:70000",
+ } {
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.Host = host
+ req.RemoteAddr = "198.51.100.20:43210"
+ if got := newRouter().resolvePublicURL(req); got != autoDetectedURL {
+ t.Errorf("Host %q resolved to %q, want safe fallback %q", host, got, autoDetectedURL)
+ }
+ }
+ })
+
+ t.Run("trusted proxy preserves the external host scheme and port", func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "192.0.2.0/24")
+ resetTrustedProxyCIDRsForTests()
+
+ req := httptest.NewRequest(http.MethodGet, "http://backend.internal:7655/", nil)
+ req.RemoteAddr = "192.0.2.44:41000"
+ req.Header.Set("X-Forwarded-Host", "pulse.example.com, backend.internal:7655")
+ req.Header.Set("X-Forwarded-Proto", "https, http")
+ req.Header.Set("X-Forwarded-Port", "8443")
+
+ if got, want := newRouter().resolvePublicURL(req), "https://pulse.example.com:8443"; got != want {
+ t.Fatalf("trusted forwarded origin resolved to %q, want %q", got, want)
+ }
+ })
+
+ t.Run("malformed trusted headers are ignored independently", func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "192.0.2.0/24")
+ resetTrustedProxyCIDRsForTests()
+
+ req := httptest.NewRequest(http.MethodGet, "https://pulse.lan:9443/", nil)
+ req.RemoteAddr = "192.0.2.44:41000"
+ req.Header.Set("X-Forwarded-Host", "https://attacker.example/path")
+ req.Header.Set("X-Forwarded-Proto", "javascript")
+ req.Header.Set("X-Forwarded-Scheme", "also-invalid")
+ req.Header.Set("X-Forwarded-Port", "70000")
+
+ if got, want := newRouter().resolvePublicURL(req), "https://pulse.lan:9443"; got != want {
+ t.Fatalf("malformed forwarded headers resolved to %q, want %q", got, want)
+ }
+ })
+
+ t.Run("IPv4 and IPv6 authorities remain usable", func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "192.0.2.0/24")
+ resetTrustedProxyCIDRsForTests()
+
+ ipv4 := httptest.NewRequest(http.MethodGet, "http://192.0.2.10:7655/", nil)
+ if got, want := newRouter().resolvePublicURL(ipv4), "http://192.0.2.10:7655"; got != want {
+ t.Fatalf("IPv4 origin = %q, want %q", got, want)
+ }
+
+ ipv6 := httptest.NewRequest(http.MethodGet, "http://[2001:db8::10]/", nil)
+ ipv6.RemoteAddr = "192.0.2.44:41000"
+ ipv6.Header.Set("X-Forwarded-Host", "2001:db8::20")
+ ipv6.Header.Set("X-Forwarded-Proto", "https")
+ ipv6.Header.Set("X-Forwarded-Port", "8443")
+ if got, want := newRouter().resolvePublicURL(ipv6), "https://[2001:db8::20]:8443"; got != want {
+ t.Fatalf("IPv6 forwarded origin = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("explicit public URL remains authoritative", func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "192.0.2.0/24")
+ resetTrustedProxyCIDRsForTests()
+
+ router := &Router{config: &config.Config{PublicURL: "https://configured.example/base/"}}
+ req := httptest.NewRequest(http.MethodGet, "http://request.example/", nil)
+ req.RemoteAddr = "192.0.2.44:41000"
+ req.Header.Set("X-Forwarded-Host", "forwarded.example")
+ req.Header.Set("X-Forwarded-Proto", "http")
+
+ if got, want := router.resolvePublicURL(req), "https://configured.example/base"; got != want {
+ t.Fatalf("configured public URL resolved to %q, want %q", got, want)
+ }
+ })
+
+ t.Run("diagnostics and deploy token targets use the sanitized fallback", func(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")
+ resetTrustedProxyCIDRsForTests()
+
+ req := httptest.NewRequest(http.MethodPost, "/api/clusters/lab/agent-deploy/jobs", nil)
+ req.Host = "attacker.example/path;sh"
+ req.RemoteAddr = "198.51.100.20:43210"
+ req.Header.Set("X-Forwarded-Host", "forwarded-attacker.example")
+ req.Header.Set("X-Forwarded-Proto", "https")
+
+ baseURL := newRouter().resolvePublicURL(req)
+ diagnosticsCommand := buildContainerRuntimeAgentInstallCommand(baseURL, "diagnostics-secret", true)
+ if !strings.Contains(diagnosticsCommand, autoDetectedURL) || !strings.Contains(diagnosticsCommand, "diagnostics-secret") {
+ t.Fatalf("diagnostics command did not retain safe target and token: %q", diagnosticsCommand)
+ }
+ if strings.Contains(diagnosticsCommand, "attacker") {
+ t.Fatalf("diagnostics command retained attacker-controlled origin bytes: %q", diagnosticsCommand)
+ }
+
+ deployPayload := agentexec.DeployInstallPayload{
+ RequestID: "request-origin-contract",
+ JobID: "job-request-origin-contract",
+ PulseURL: baseURL,
+ Targets: []agentexec.DeployInstallTarget{{
+ TargetID: "target-1",
+ NodeName: "pve-1",
+ NodeIP: "192.0.2.50",
+ Arch: "amd64",
+ BootstrapToken: "deploy-secret",
+ }},
+ }
+ encoded, err := json.Marshal(deployPayload)
+ if err != nil {
+ t.Fatalf("marshal deploy payload: %v", err)
+ }
+ if !bytes.Contains(encoded, []byte(autoDetectedURL)) || !bytes.Contains(encoded, []byte("deploy-secret")) {
+ t.Fatalf("deploy payload did not retain safe target and token: %s", encoded)
+ }
+ if bytes.Contains(encoded, []byte("attacker")) {
+ t.Fatalf("deploy payload retained attacker-controlled origin bytes: %s", encoded)
+ }
+ })
+}
+
// Issue1649 regression coverage. Docker update (and every other typed) action
// used to sit in "executing" forever whenever the agent could not produce a
// terminal receipt: the agent-side receipt store marks an in-flight receipt
diff --git a/internal/api/oidc_handlers.go b/internal/api/oidc_handlers.go
index f5c4fe89b8..0d8aca67d4 100644
--- a/internal/api/oidc_handlers.go
+++ b/internal/api/oidc_handlers.go
@@ -310,7 +310,11 @@ func buildSSOOIDCCallbackURL(req *http.Request, providerID string, configuredURL
return configured
}
- return fmt.Sprintf("%s://%s/api/oidc/%s/callback", requestForwardedScheme(req), requestForwardedHost(req), providerID)
+ baseURL := requestOriginBaseURL(req)
+ if baseURL == "" {
+ return ""
+ }
+ return fmt.Sprintf("%s/api/oidc/%s/callback", baseURL, providerID)
}
// handleSSOOIDCLogin handles login for a multi-provider SSO OIDC provider.
diff --git a/internal/api/router.go b/internal/api/router.go
index e1e2780f87..f115a8867b 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -4694,61 +4694,15 @@ func (r *Router) capturePublicURLFromRequest(req *http.Request) {
return
}
- peerIP := extractRemoteIP(req.RemoteAddr)
- trustedProxy := isTrustedProxyIP(peerIP)
-
- rawHost := ""
- if trustedProxy {
- rawHost = firstForwardedValue(req.Header.Get("X-Forwarded-Host"))
- }
- if rawHost == "" {
- rawHost = req.Host
- }
- hostWithPort, hostOnly := sanitizeForwardedHost(rawHost)
- if hostWithPort == "" {
+ origin, ok := resolveRequestOrigin(req)
+ if !ok {
return
}
- if isLoopbackHost(hostOnly) {
+ if isLoopbackHost(origin.hostname) {
return
}
- rawProto := ""
- if trustedProxy {
- rawProto = firstForwardedValue(req.Header.Get("X-Forwarded-Proto"))
- if rawProto == "" {
- rawProto = firstForwardedValue(req.Header.Get("X-Forwarded-Scheme"))
- }
- }
- scheme := strings.ToLower(strings.TrimSpace(rawProto))
- switch scheme {
- case "https", "http":
- // supported values
- default:
- if req.TLS != nil {
- scheme = "https"
- } else {
- scheme = "http"
- }
- }
- if scheme == "" {
- scheme = "http"
- }
-
- if _, _, err := net.SplitHostPort(hostWithPort); err != nil {
- if forwardedPort := firstForwardedValue(req.Header.Get("X-Forwarded-Port")); forwardedPort != "" {
- if shouldAppendForwardedPort(forwardedPort, scheme) {
- if strings.Contains(hostWithPort, ":") && !strings.HasPrefix(hostWithPort, "[") {
- hostWithPort = fmt.Sprintf("[%s]", hostWithPort)
- } else if strings.HasPrefix(hostWithPort, "[") && !strings.Contains(hostWithPort, "]") {
- hostWithPort = fmt.Sprintf("[%s]", strings.TrimPrefix(hostWithPort, "["))
- }
- hostWithPort = fmt.Sprintf("%s:%s", hostWithPort, forwardedPort)
- }
- }
- }
-
- candidate := fmt.Sprintf("%s://%s", scheme, hostWithPort)
- normalizedCandidate := strings.TrimRight(strings.TrimSpace(candidate), "/")
+ normalizedCandidate := origin.baseURL()
r.publicURLMu.Lock()
if r.publicURLDetected {
@@ -4791,59 +4745,84 @@ func firstForwardedValue(header string) string {
return strings.TrimSpace(parts[0])
}
-// requestForwardedScheme resolves the scheme the client used to reach Pulse.
-// X-Forwarded-Proto / X-Forwarded-Scheme are only honored when the immediate
-// peer is a trusted proxy, so untrusted clients cannot spoof "https".
-func requestForwardedScheme(req *http.Request) string {
- scheme := "http"
+type resolvedRequestOrigin struct {
+ scheme string
+ authority string
+ hostname string
+}
+
+func (o resolvedRequestOrigin) baseURL() string {
+ if o.scheme == "" || o.authority == "" {
+ return ""
+ }
+ return o.scheme + "://" + o.authority
+}
+
+type validatedRequestHost struct {
+ authority string
+ hostname string
+ hasPort bool
+}
+
+// resolveRequestOrigin is the single trust boundary for request-derived
+// absolute URLs. Direct Host values are always parsed as a strict HTTP
+// authority. Forwarded host, scheme, and port values are considered only when
+// the immediate peer is configured in PULSE_TRUSTED_PROXY_CIDRS; malformed
+// forwarded values are ignored independently and cannot poison the direct
+// request fallback.
+func resolveRequestOrigin(req *http.Request) (resolvedRequestOrigin, bool) {
if req == nil {
- return scheme
+ return resolvedRequestOrigin{}, false
+ }
+
+ trustedProxy := isTrustedProxyIP(extractRemoteIP(req.RemoteAddr))
+ var host validatedRequestHost
+ var ok bool
+ if trustedProxy {
+ host, ok = validateRequestHost(firstForwardedValue(req.Header.Get("X-Forwarded-Host")))
}
+ if !ok {
+ host, ok = validateRequestHost(req.Host)
+ }
+ if !ok {
+ return resolvedRequestOrigin{}, false
+ }
+
+ scheme := "http"
if req.TLS != nil {
scheme = "https"
}
-
- if isTrustedProxyIP(extractRemoteIP(req.RemoteAddr)) {
- if proto := firstForwardedValue(req.Header.Get("X-Forwarded-Proto")); proto != "" {
- scheme = proto
- } else if proto := firstForwardedValue(req.Header.Get("X-Forwarded-Scheme")); proto != "" {
- scheme = proto
+ if trustedProxy {
+ if forwardedScheme, valid := validateForwardedScheme(firstForwardedValue(req.Header.Get("X-Forwarded-Proto"))); valid {
+ scheme = forwardedScheme
+ } else if forwardedScheme, valid := validateForwardedScheme(firstForwardedValue(req.Header.Get("X-Forwarded-Scheme"))); valid {
+ scheme = forwardedScheme
}
}
- scheme = strings.ToLower(strings.TrimSpace(scheme))
- switch scheme {
- case "http", "https":
- return scheme
- default:
- if req.TLS != nil {
- return "https"
+ if trustedProxy && !host.hasPort {
+ if forwardedPort := firstForwardedValue(req.Header.Get("X-Forwarded-Port")); shouldAppendForwardedPort(forwardedPort, scheme) {
+ host.authority = net.JoinHostPort(host.hostname, forwardedPort)
+ host.hasPort = true
}
- return "http"
}
-}
-// requestForwardedHost resolves the host:port the client used to reach Pulse.
-// X-Forwarded-Host is only honored when the immediate peer is a trusted proxy.
-// Returns "" when no host can be resolved.
-func requestForwardedHost(req *http.Request) string {
- if req == nil {
- return ""
- }
-
- rawHost := ""
- if isTrustedProxyIP(extractRemoteIP(req.RemoteAddr)) {
- rawHost = firstForwardedValue(req.Header.Get("X-Forwarded-Host"))
- }
- if rawHost == "" {
- rawHost = req.Host
- }
+ return resolvedRequestOrigin{
+ scheme: scheme,
+ authority: host.authority,
+ hostname: host.hostname,
+ }, true
+}
- host, _ := sanitizeForwardedHost(rawHost)
- if host == "" {
- host = strings.TrimSpace(req.Host)
+func validateForwardedScheme(raw string) (string, bool) {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case "http":
+ return "http", true
+ case "https":
+ return "https", true
+ default:
+ return "", false
}
- return host
}
// requestOriginBaseURL derives the scheme://host base URL the admin's browser
@@ -4852,33 +4831,116 @@ func requestForwardedHost(req *http.Request) string {
// request necessarily arrived over a reachable address, unlike a hardcoded
// localhost guess. Returns "" when the host cannot be resolved.
func requestOriginBaseURL(req *http.Request) string {
- host := requestForwardedHost(req)
- if host == "" {
+ origin, ok := resolveRequestOrigin(req)
+ if !ok {
return ""
}
- return requestForwardedScheme(req) + "://" + host
+ return origin.baseURL()
}
func sanitizeForwardedHost(raw string) (string, string) {
- host := strings.TrimSpace(raw)
- if host == "" {
+ host, ok := validateRequestHost(raw)
+ if !ok {
return "", ""
}
+ return host.authority, host.hostname
+}
- host = strings.TrimPrefix(host, "http://")
- host = strings.TrimPrefix(host, "https://")
- host = strings.TrimSpace(strings.TrimSuffix(host, "/"))
- if host == "" {
- return "", ""
+func validateRequestHost(raw string) (validatedRequestHost, bool) {
+ if raw == "" || strings.TrimSpace(raw) != raw {
+ return validatedRequestHost{}, false
+ }
+ for i := 0; i < len(raw); i++ {
+ if raw[i] <= 0x20 || raw[i] >= 0x7f {
+ return validatedRequestHost{}, false
+ }
+ }
+ if strings.ContainsAny(raw, "/\\?#@%") {
+ return validatedRequestHost{}, false
}
- hostOnly := host
- if h, _, err := net.SplitHostPort(hostOnly); err == nil {
- hostOnly = h
+ authority := raw
+ hostname := raw
+ hasPort := false
+
+ if strings.HasPrefix(raw, "[") {
+ closing := strings.IndexByte(raw, ']')
+ if closing <= 1 {
+ return validatedRequestHost{}, false
+ }
+ hostname = raw[1:closing]
+ if ip := net.ParseIP(hostname); ip == nil || ip.To4() != nil {
+ return validatedRequestHost{}, false
+ }
+ suffix := raw[closing+1:]
+ switch {
+ case suffix == "":
+ authority = "[" + hostname + "]"
+ case strings.HasPrefix(suffix, ":") && validRequestPort(suffix[1:]):
+ hasPort = true
+ authority = net.JoinHostPort(hostname, suffix[1:])
+ default:
+ return validatedRequestHost{}, false
+ }
+ } else if strings.Count(raw, ":") > 1 {
+ if ip := net.ParseIP(raw); ip == nil || ip.To4() != nil {
+ return validatedRequestHost{}, false
+ }
+ hostname = raw
+ authority = "[" + raw + "]"
+ } else if strings.Contains(raw, ":") {
+ hostPart, port, err := net.SplitHostPort(raw)
+ if err != nil || !validRequestPort(port) {
+ return validatedRequestHost{}, false
+ }
+ hostname = hostPart
+ hasPort = true
+ }
+
+ if ip := net.ParseIP(hostname); ip == nil && !validRequestHostname(hostname) {
+ return validatedRequestHost{}, false
}
- hostOnly = strings.Trim(hostOnly, "[]")
- return host, hostOnly
+ return validatedRequestHost{
+ authority: authority,
+ hostname: hostname,
+ hasPort: hasPort,
+ }, true
+}
+
+func validRequestHostname(hostname string) bool {
+ name := strings.TrimSuffix(hostname, ".")
+ if name == "" || len(name) > 253 {
+ return false
+ }
+ if allNumericAndDots := strings.Trim(name, "0123456789.") == ""; allNumericAndDots {
+ return false
+ }
+ for _, label := range strings.Split(name, ".") {
+ if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
+ return false
+ }
+ for i := 0; i < len(label); i++ {
+ c := label[i]
+ if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '-' {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+func validRequestPort(port string) bool {
+ if port == "" {
+ return false
+ }
+ for i := 0; i < len(port); i++ {
+ if port[i] < '0' || port[i] > '9' {
+ return false
+ }
+ }
+ value, err := strconv.Atoi(port)
+ return err == nil && value >= 1 && value <= 65535
}
func isLoopbackHost(host string) bool {
@@ -4898,10 +4960,7 @@ func isLoopbackHost(host string) bool {
}
func shouldAppendForwardedPort(port, scheme string) bool {
- if port == "" {
- return false
- }
- if _, err := strconv.Atoi(port); err != nil {
+ if !validRequestPort(port) {
return false
}
if scheme == "https" && port == "443" {
@@ -10908,6 +10967,10 @@ func (r *Router) handleDiagnosticsDockerPrepareToken(w http.ResponseWriter, req
}
func (r *Router) resolvePublicURL(req *http.Request) string {
+ if r == nil || r.config == 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 {
@@ -10933,21 +10996,8 @@ func (r *Router) resolvePublicURL(req *http.Request) string {
return strings.TrimRight(publicURL, "/")
}
- scheme := "http"
- if req != nil {
- if req.TLS != nil {
- scheme = "https"
- } else if proto := req.Header.Get("X-Forwarded-Proto"); strings.EqualFold(proto, "https") {
- scheme = "https"
- }
- }
-
- host := ""
- if req != nil {
- host = strings.TrimSpace(req.Host)
- }
- if host != "" {
- return fmt.Sprintf("%s://%s", scheme, host)
+ if requestURL := requestOriginBaseURL(req); requestURL != "" {
+ return requestURL
}
if publicURL != "" {
@@ -10955,12 +11005,9 @@ func (r *Router) resolvePublicURL(req *http.Request) string {
}
if r.config.FrontendPort > 0 {
- host = fmt.Sprintf("localhost:%d", r.config.FrontendPort)
- } else {
- host = "localhost:7655"
+ return fmt.Sprintf("http://localhost:%d", r.config.FrontendPort)
}
-
- return fmt.Sprintf("%s://%s", scheme, host)
+ return "http://localhost:7655"
}
func fileExists(path string) bool {
diff --git a/internal/api/router_test.go b/internal/api/router_test.go
index c49970f9fb..68e2560e8e 100644
--- a/internal/api/router_test.go
+++ b/internal/api/router_test.go
@@ -319,10 +319,10 @@ func TestSanitizeForwardedHost(t *testing.T) {
wantHostOnly: "example.com",
},
{
- name: "hostname with whitespace",
+ name: "hostname with whitespace is rejected",
raw: " example.com ",
- wantFull: "example.com",
- wantHostOnly: "example.com",
+ wantFull: "",
+ wantHostOnly: "",
},
{
name: "fqdn",
@@ -351,44 +351,44 @@ func TestSanitizeForwardedHost(t *testing.T) {
wantHostOnly: "example.com",
},
- // With scheme prefixes
+ // Host is an authority, never a URL.
{
- name: "http scheme stripped",
+ name: "http scheme rejected",
raw: "http://example.com",
- wantFull: "example.com",
- wantHostOnly: "example.com",
+ wantFull: "",
+ wantHostOnly: "",
},
{
- name: "https scheme stripped",
+ name: "https scheme rejected",
raw: "https://example.com",
- wantFull: "example.com",
- wantHostOnly: "example.com",
+ wantFull: "",
+ wantHostOnly: "",
},
{
- name: "http scheme with port",
+ name: "http scheme with port rejected",
raw: "http://example.com:8080",
- wantFull: "example.com:8080",
- wantHostOnly: "example.com",
+ wantFull: "",
+ wantHostOnly: "",
},
{
- name: "https scheme with port",
+ name: "https scheme with port rejected",
raw: "https://example.com:9443",
- wantFull: "example.com:9443",
- wantHostOnly: "example.com",
+ wantFull: "",
+ wantHostOnly: "",
},
// Trailing slashes/paths
{
- name: "trailing slash stripped",
+ name: "trailing slash rejected",
raw: "example.com/",
- wantFull: "example.com",
- wantHostOnly: "example.com",
+ wantFull: "",
+ wantHostOnly: "",
},
{
- name: "scheme and trailing slash",
+ name: "scheme and trailing slash rejected",
raw: "https://example.com/",
- wantFull: "example.com",
- wantHostOnly: "example.com",
+ wantFull: "",
+ wantHostOnly: "",
},
// IPv4 addresses
@@ -405,10 +405,10 @@ func TestSanitizeForwardedHost(t *testing.T) {
wantHostOnly: "192.168.1.1",
},
{
- name: "IPv4 with scheme",
+ name: "IPv4 with scheme rejected",
raw: "http://10.0.0.1",
- wantFull: "10.0.0.1",
- wantHostOnly: "10.0.0.1",
+ wantFull: "",
+ wantHostOnly: "",
},
// IPv6 addresses (key edge case - bracket handling)
@@ -437,15 +437,15 @@ func TestSanitizeForwardedHost(t *testing.T) {
wantHostOnly: "2001:db8::1",
},
{
- name: "IPv6 with scheme",
+ name: "IPv6 with scheme rejected",
raw: "https://[::1]:9443",
- wantFull: "[::1]:9443",
- wantHostOnly: "::1",
+ wantFull: "",
+ wantHostOnly: "",
},
{
name: "IPv6 without brackets (raw - no port possible)",
raw: "::1",
- wantFull: "::1",
+ wantFull: "[::1]",
wantHostOnly: "::1",
},
@@ -646,10 +646,22 @@ func TestShouldAppendForwardedPort(t *testing.T) {
want: false,
},
{
- name: "negative port string (Atoi accepts it)",
+ name: "negative port rejected",
port: "-80",
scheme: "http",
- want: true, // strconv.Atoi parses "-80" as -80 (valid int)
+ want: false,
+ },
+ {
+ name: "zero port rejected",
+ port: "0",
+ scheme: "http",
+ want: false,
+ },
+ {
+ name: "out of range port rejected",
+ port: "65536",
+ scheme: "https",
+ want: false,
},
// Default ports that should NOT be appended
@@ -707,12 +719,6 @@ func TestShouldAppendForwardedPort(t *testing.T) {
},
// Edge cases
- {
- name: "port 0",
- port: "0",
- scheme: "http",
- want: true,
- },
{
name: "high port number",
port: "65535",
@@ -854,6 +860,7 @@ func TestResolvePublicURL_AutoDetectedYieldsToRequest(t *testing.T) {
autoDetected bool
reqHost string
forwardProto string
+ trustedProxy bool
want string
}{
{
@@ -862,6 +869,7 @@ func TestResolvePublicURL_AutoDetectedYieldsToRequest(t *testing.T) {
autoDetected: true,
reqHost: "pulse.example.com",
forwardProto: "https",
+ trustedProxy: true,
want: "https://pulse.example.com",
},
{
@@ -889,6 +897,13 @@ func TestResolvePublicURL_AutoDetectedYieldsToRequest(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
+ if tt.trustedProxy {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "192.0.2.1/32")
+ } else {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")
+ }
+ resetTrustedProxyConfig()
+
r := &Router{
config: &config.Config{
PublicURL: tt.publicURL,
@@ -900,6 +915,9 @@ func TestResolvePublicURL_AutoDetectedYieldsToRequest(t *testing.T) {
if tt.reqHost != "" {
req = httptest.NewRequest(http.MethodGet, "/", nil)
req.Host = tt.reqHost
+ if tt.trustedProxy {
+ req.RemoteAddr = "192.0.2.1:12345"
+ }
if tt.forwardProto != "" {
req.Header.Set("X-Forwarded-Proto", tt.forwardProto)
}
@@ -935,18 +953,18 @@ func TestResolvePublicURL_FromRequest(t *testing.T) {
want: "https://pulse.example.com",
},
{
- name: "HTTP request with X-Forwarded-Proto https",
+ name: "untrusted X-Forwarded-Proto https is ignored",
host: "pulse.example.com",
useTLS: false,
xForwardProto: "https",
- want: "https://pulse.example.com",
+ want: "http://pulse.example.com",
},
{
- name: "X-Forwarded-Proto case insensitive",
+ name: "untrusted X-Forwarded-Proto case variant is ignored",
host: "pulse.example.com",
useTLS: false,
xForwardProto: "HTTPS",
- want: "https://pulse.example.com",
+ want: "http://pulse.example.com",
},
{
name: "X-Forwarded-Proto http remains http",
@@ -962,10 +980,10 @@ func TestResolvePublicURL_FromRequest(t *testing.T) {
want: "http://pulse.example.com:8080",
},
{
- name: "Host with whitespace is trimmed",
+ name: "Host with whitespace is rejected",
host: " pulse.example.com ",
useTLS: false,
- want: "http://pulse.example.com",
+ want: "http://localhost:7655",
},
}