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): fail closed for hosted installer origins

rcourtman2030d71fd94f
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 0a62ea72e6..28eb5d68aa 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": "hosted-installer-origin-019fde93-lane-l16",
+ "agent_id": "hosted-installer-origin-019fde93",
+ "summary": "Close the hosted installer-origin gap by propagating runtime hosted mode into canonical PVE/PBS command and setup-artifact resolution before any token mutation, with router-level adversarial proof.",
+ "target_id": "v6-product-lane-expansion",
+ "claimed_at": "2026-08-08T09:43:22Z",
+ "heartbeat_at": "2026-08-08T09:43:22Z",
+ "expires_at": "2026-08-08T17:43:22Z",
+ "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 7cd4986168..d74e9190f1 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -5856,6 +5856,24 @@ 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.
+Hosted lifecycle callers now receive the runtime mode from
+`Router.hostedMode` through `ConfigHandlers`; they no longer call the shared
+resolver with a self-hosted constant. In hosted mode, a non-empty
+`AgentConnectURL` remains authoritative and an explicit `PublicURL` remains
+the fallback, but the selected value must pass the canonical Pulse HTTP base
+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`
+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
+`TestContract_RequestOriginCannotRetargetTokenBearingCommands`.
+
### Runtime branding stays outside agent lifecycle authority
The authenticated `GET /api/runtime/branding` presentation endpoint is an
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5bedfb54df..2f1beb26b1 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -8937,6 +8937,24 @@ handling, `AgentConnectURL` and explicit `PublicURL` precedence, auto-detected
and local fallback, and the exact sanitized target paired with each fresh
token-bearing command.
+The hosted API contract additionally requires `Router.hostedMode` to be
+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
+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
+`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.
+
### 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/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 5d557ab6df..30bc8b7e6f 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -5242,6 +5242,15 @@ 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.
+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.
`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 60d14c028a..6154f371c6 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2246,6 +2246,14 @@ 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.
+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`.
### 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 2b0c7c7ac5..31e5cf158f 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1858,6 +1858,21 @@ contract proof is
`internal/api/contract_test.go`, including direct execution of the PVE/PBS
`POST /api/agent-install-command` handler with a newly minted token.
+Hosted fail-closed behavior is now enforced at the registered config routes,
+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
+returned setup artifact through the public script route so the rendered
+token-bearing shell body remains bound to the configured origin.
+
### The global security banner no longer scores a truncated status payload
`/api/security/status` in `internal/api/router_routes_auth_security.go` returns
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index a4c3363324..66047a6d7b 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -4947,6 +4947,18 @@ 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.
+`Router.hostedMode` now reaches the config-owned setup boundary explicitly.
+Hosted PVE/PBS setup artifacts require a canonically valid authoritative
+`AgentConnectURL` or explicit `PublicURL` before the short-lived setup token is
+created; missing, auto-detected, or invalid configuration leaves the setup-token
+map empty. The adjacent password-driven PBS path resolves the same target
+before deriving its Pulse-managed token label or contacting PBS, so failure
+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.
+
The shared `frontend-modern/src/App.tsx` shell boundary this subsystem consumes
gained one authority gate on its global banner block. The banners rendered
above the authenticated shell (security, demo, commercial migration, update,
diff --git a/internal/api/agent_install_command_shared.go b/internal/api/agent_install_command_shared.go
index 527c87f3ee..8dd7e67ced 100644
--- a/internal/api/agent_install_command_shared.go
+++ b/internal/api/agent_install_command_shared.go
@@ -347,6 +347,10 @@ func buildSetupScriptInstallArtifact(baseURL string, installType string, host st
}
}
-func resolveConfigAgentInstallBaseURL(req *http.Request, cfg *config.Config) string {
- return resolveConfiguredPublicBaseURL(req, cfg, false)
+func resolveConfigAgentInstallBaseURL(req *http.Request, cfg *config.Config, hostedMode bool) string {
+ return resolveConfiguredPublicBaseURL(req, cfg, hostedMode)
+}
+
+func writeConfigAgentInstallBaseURLUnavailable(w http.ResponseWriter) {
+ http.Error(w, "A valid external Pulse URL is required", http.StatusServiceUnavailable)
}
diff --git a/internal/api/agent_install_command_shared_test.go b/internal/api/agent_install_command_shared_test.go
index 248c307828..7d5b9b94fe 100644
--- a/internal/api/agent_install_command_shared_test.go
+++ b/internal/api/agent_install_command_shared_test.go
@@ -277,10 +277,10 @@ func TestResolveConfigAgentInstallBaseURL(t *testing.T) {
req.Host = "127.0.0.1:7655"
req.Header.Set("X-Forwarded-Proto", "https")
- require.Equal(t, "https://agents.example.com", resolveConfigAgentInstallBaseURL(req, cfg))
+ require.Equal(t, "https://agents.example.com", resolveConfigAgentInstallBaseURL(req, cfg, false))
cfg.AgentConnectURL = ""
- require.Equal(t, "https://public.example.com", resolveConfigAgentInstallBaseURL(req, cfg))
+ require.Equal(t, "https://public.example.com", resolveConfigAgentInstallBaseURL(req, cfg, false))
}
func TestResolveConfigAgentInstallBaseURL_PreservesConfiguredPublicSchemeOnLoopback(t *testing.T) {
@@ -291,7 +291,7 @@ func TestResolveConfigAgentInstallBaseURL_PreservesConfiguredPublicSchemeOnLoopb
req := httptest.NewRequest("POST", "/api/agent-install-command", nil)
req.Host = "127.0.0.1:7655"
- require.Equal(t, "https://public.example.com/base", resolveConfigAgentInstallBaseURL(req, cfg))
+ require.Equal(t, "https://public.example.com/base", resolveConfigAgentInstallBaseURL(req, cfg, false))
}
func TestResolveConfigAgentInstallBaseURL_UsesConfiguredPublicURLForIPv6Loopback(t *testing.T) {
@@ -302,7 +302,7 @@ func TestResolveConfigAgentInstallBaseURL_UsesConfiguredPublicURLForIPv6Loopback
req := httptest.NewRequest("POST", "/api/agent-install-command", nil)
req.Host = "[::1]:7655"
- require.Equal(t, "https://public.example.com", resolveConfigAgentInstallBaseURL(req, cfg))
+ require.Equal(t, "https://public.example.com", resolveConfigAgentInstallBaseURL(req, cfg, false))
}
func TestIssueAndPersistAgentInstallToken(t *testing.T) {
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.go
index 6056835938..1fa47f9016 100644
--- a/internal/api/config_handlers.go
+++ b/internal/api/config_handlers.go
@@ -196,6 +196,7 @@ type ConfigHandlers struct {
stateMu sync.RWMutex
mtPersistence *config.MultiTenantPersistence
mtMonitor *monitoring.MultiTenantMonitor
+ hostedMode bool
// Default-org runtime fields used when tenant-specific state is unavailable.
defaultConfig *config.Config
defaultPersistence *config.ConfigPersistence
@@ -217,7 +218,7 @@ type ConfigHandlers struct {
}
// NewConfigHandlers creates a new ConfigHandlers instance
-func NewConfigHandlers(mtp *config.MultiTenantPersistence, mtm *monitoring.MultiTenantMonitor, reloadFunc func() error, wsHub *websocket.Hub, guestMetadataHandler *GuestMetadataHandler, reloadSystemSettingsFunc func()) *ConfigHandlers {
+func NewConfigHandlers(mtp *config.MultiTenantPersistence, mtm *monitoring.MultiTenantMonitor, reloadFunc func() error, wsHub *websocket.Hub, guestMetadataHandler *GuestMetadataHandler, reloadSystemSettingsFunc func(), hostedMode bool) *ConfigHandlers {
// Initialize with default-org values from multi-tenant managers when available.
var defaultConfig *config.Config
var defaultMonitor *monitoring.Monitor
@@ -240,6 +241,7 @@ func NewConfigHandlers(mtp *config.MultiTenantPersistence, mtm *monitoring.Multi
h := &ConfigHandlers{
mtPersistence: mtp,
mtMonitor: mtm,
+ hostedMode: hostedMode,
defaultConfig: defaultConfig,
defaultMonitor: defaultMonitor,
defaultPersistence: defaultPersistence,
diff --git a/internal/api/config_handlers_auto_register_test.go b/internal/api/config_handlers_auto_register_test.go
index 9543d5bedb..df3296f399 100644
--- a/internal/api/config_handlers_auto_register_test.go
+++ b/internal/api/config_handlers_auto_register_test.go
@@ -27,7 +27,7 @@ func newTestConfigHandlers(t *testing.T, cfg *config.Config) *ConfigHandlers {
if cfg.DataPath == "" {
cfg.DataPath = t.TempDir()
}
- h := NewConfigHandlers(nil, nil, func() error { return nil }, nil, nil, func() {})
+ h := NewConfigHandlers(nil, nil, func() error { return nil }, nil, nil, func() {}, false)
h.defaultConfig = cfg
h.defaultPersistence = config.NewConfigPersistence(cfg.DataPath)
monitor, _, _ := newTestMonitor(t)
diff --git a/internal/api/config_node_handlers.go b/internal/api/config_node_handlers.go
index 2df769b7ad..9b33e1526d 100644
--- a/internal/api/config_node_handlers.go
+++ b/internal/api/config_node_handlers.go
@@ -558,6 +558,11 @@ func (h *ConfigHandlers) handleAddNode(w http.ResponseWriter, r *http.Request) {
} else if req.Password != "" {
// Using password authentication - try to create a token via API
// This enables turnkey setup for Docker/containerized PBS
+ pulseURL := resolveConfigAgentInstallBaseURL(r, h.getConfig(r.Context()), h.hostedMode)
+ if pulseURL == "" {
+ writeConfigAgentInstallBaseURLUnavailable(w)
+ return
+ }
pbsUser = req.User
if pbsUser != "" && !strings.Contains(pbsUser, "@") {
pbsUser = pbsUser + "@pbs" // Default to @pbs realm if not specified
@@ -581,7 +586,6 @@ func (h *ConfigHandlers) handleAddNode(w http.ResponseWriter, r *http.Request) {
// Fallback to password auth
pbsPassword = req.Password
} else {
- 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 88543bf02f..6022920c20 100644
--- a/internal/api/config_setup_handlers.go
+++ b/internal/api/config_setup_handlers.go
@@ -705,6 +705,11 @@ func (h *ConfigHandlers) handleSetupScriptURL(w http.ResponseWriter, r *http.Req
return
}
req.Host = normalizedHost
+ pulseURL := resolveConfigAgentInstallBaseURL(r, h.getConfig(r.Context()), h.hostedMode)
+ if pulseURL == "" {
+ writeConfigAgentInstallBaseURLUnavailable(w)
+ return
+ }
// Generate a temporary setup token for setup-script bootstrap transport.
token := h.generateSetupTokenRecord()
@@ -729,7 +734,6 @@ 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 := resolveConfiguredPublicBaseURL(r, h.getConfig(r.Context()), false)
artifact := buildSetupScriptInstallArtifact(
pulseURL,
req.Type,
@@ -2480,6 +2484,11 @@ func (h *ConfigHandlers) handleAgentInstallCommand(w http.ResponseWriter, r *htt
cfg := h.getConfig(r.Context())
persistence := h.getPersistence(r.Context())
+ baseURL := resolveConfigAgentInstallBaseURL(r, cfg, h.hostedMode)
+ if baseURL == "" {
+ writeConfigAgentInstallBaseURLUnavailable(w)
+ return
+ }
rawToken := ""
if authConfiguredForAgentLifecycle(cfg) {
@@ -2511,7 +2520,6 @@ func (h *ConfigHandlers) handleAgentInstallCommand(w http.ResponseWriter, r *htt
}
}
- baseURL := resolveConfigAgentInstallBaseURL(r, cfg)
command := buildProxmoxAgentInstallCommand(agentInstallCommandOptions{
BaseURL: baseURL,
Token: rawToken,
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index b3ad3ada22..b4b9d54916 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -19,6 +19,7 @@ import (
"regexp"
"sort"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -22920,6 +22921,253 @@ func TestContract_RequestOriginCannotRetargetTokenBearingCommands(t *testing.T)
})
}
+func TestContract_HostedInstallerOriginsFailClosedAtRouter(t *testing.T) {
+ const adminToken = "hosted-installer-admin.12345678"
+
+ type originHeaders struct {
+ host string
+ remoteAddr string
+ trustedProxyCIDR string
+ forwardedHost string
+ forwardedProto string
+ }
+
+ newHostedRouter := func(t *testing.T, publicURL string, autoDetected bool, agentConnectURL string, headers originHeaders) (*Router, *config.Config) {
+ t.Helper()
+ t.Setenv("PULSE_HOSTED_MODE", "true")
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", headers.trustedProxyCIDR)
+ resetTrustedProxyCIDRsForTests()
+
+ adminRecord := newTokenRecord(t, adminToken, []string{config.ScopeSettingsWrite}, nil)
+ cfg := newTestConfigWithTokens(t, adminRecord)
+ cfg.FrontendPort = 7655
+ cfg.PublicURL = publicURL
+ cfg.PublicURLAutoDetected = autoDetected
+ cfg.AgentConnectURL = agentConnectURL
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+ if !router.hostedMode || router.configHandlers == nil || !router.configHandlers.hostedMode {
+ t.Fatal("Router hosted mode was not propagated into ConfigHandlers")
+ }
+ return router, cfg
+ }
+
+ doRequest := func(t *testing.T, router *Router, method string, target string, body string, headers originHeaders, authenticated bool) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(method, target, strings.NewReader(body))
+ 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)
+ }
+ if authenticated {
+ req.Header.Set("Authorization", "Bearer "+adminToken)
+ }
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ return rec
+ }
+
+ failureCases := []struct {
+ name string
+ publicURL string
+ publicAuto bool
+ agentConnectURL string
+ headers originHeaders
+ }{
+ {
+ name: "missing URL ignores direct Host and untrusted forwarded headers",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "auto-detected URL is not explicit hosted configuration",
+ publicURL: "https://auto-detected.example",
+ publicAuto: true,
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "https",
+ },
+ },
+ {
+ name: "invalid URL ignores trusted forwarded headers",
+ publicURL: "http://configured.example:7655",
+ 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 AgentConnectURL does not fall through to PublicURL",
+ publicURL: "https://configured.example",
+ agentConnectURL: "https://[email protected]",
+ 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) {
+ for _, installType := range []string{"pve", "pbs"} {
+ t.Run(installType+" install command", func(t *testing.T) {
+ router, cfg := newHostedRouter(t, tc.publicURL, tc.publicAuto, tc.agentConnectURL, tc.headers)
+ rec := doRequest(t, router, http.MethodPost, "/api/agent-install-command", fmt.Sprintf(`{"type":%q}`, installType), tc.headers, true)
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ }
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("API token record count = %d, want original admin record only", len(cfg.APITokens))
+ }
+ if strings.Contains(rec.Body.String(), "attacker") {
+ t.Fatalf("failure response retained attacker origin: %q", rec.Body.String())
+ }
+ })
+ }
+
+ t.Run("setup artifacts", func(t *testing.T) {
+ router, cfg := newHostedRouter(t, tc.publicURL, tc.publicAuto, tc.agentConnectURL, tc.headers)
+ for _, installType := range []string{"pve", "pbs"} {
+ rec := doRequest(t, router, http.MethodPost, "/api/setup-script-url", fmt.Sprintf(`{"type":%q,"host":%q}`, installType, installType+"1.local"), tc.headers, true)
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("%s status = %d, want %d: %s", installType, rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ }
+ router.configHandlers.codeMutex.RLock()
+ setupTokenCount := len(router.configHandlers.setupTokens)
+ router.configHandlers.codeMutex.RUnlock()
+ if setupTokenCount != 0 {
+ t.Fatalf("%s setup token count = %d, want 0", installType, setupTokenCount)
+ }
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("%s API token record count = %d, want original admin record only", installType, len(cfg.APITokens))
+ }
+ }
+ })
+
+ t.Run("PBS token label", func(t *testing.T) {
+ var pbsRequests atomic.Int64
+ pbsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ pbsRequests.Add(1)
+ http.Error(w, "PBS must not be contacted without a safe hosted origin", http.StatusInternalServerError)
+ }))
+ defer pbsServer.Close()
+
+ router, cfg := newHostedRouter(t, tc.publicURL, tc.publicAuto, tc.agentConnectURL, tc.headers)
+ body := fmt.Sprintf(`{"name":"pbs1","type":"pbs","host":%q,"user":"root@pam","password":"secret"}`, pbsServer.URL)
+ rec := doRequest(t, router, http.MethodPost, "/api/config/nodes", body, tc.headers, true)
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusServiceUnavailable, rec.Body.String())
+ }
+ if got := pbsRequests.Load(); got != 0 {
+ t.Fatalf("PBS received %d requests before hosted origin validation, want 0", got)
+ }
+ if len(cfg.PBSInstances) != 0 {
+ t.Fatalf("PBS instance count = %d, want 0", len(cfg.PBSInstances))
+ }
+ })
+ })
+ }
+
+ successCases := []struct {
+ name string
+ agentConnectURL string
+ headers originHeaders
+ }{
+ {
+ name: "configured URL defeats direct Host and untrusted forwarded headers",
+ headers: originHeaders{
+ host: "direct-attacker.example",
+ remoteAddr: "198.51.100.20:41000",
+ forwardedHost: "forwarded-attacker.example",
+ forwardedProto: "http",
+ },
+ },
+ {
+ name: "AgentConnectURL defeats direct Host and trusted forwarded headers",
+ agentConnectURL: "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) {
+ wantBaseURL := "https://configured.example"
+ if tc.agentConnectURL != "" {
+ wantBaseURL = "https://agents.configured.example"
+ }
+
+ for _, installType := range []string{"pve", "pbs"} {
+ t.Run(installType, func(t *testing.T) {
+ router, cfg := newHostedRouter(t, "https://configured.example/", false, tc.agentConnectURL, tc.headers)
+ rec := doRequest(t, router, http.MethodPost, "/api/agent-install-command", fmt.Sprintf(`{"type":%q}`, installType), tc.headers, true)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("install 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 install response: %v", err)
+ }
+ if response.Token == "" || !strings.Contains(response.Command, response.Token) || !strings.Contains(response.Command, wantBaseURL+"/install.sh") {
+ t.Fatalf("install response did not bind fresh token to configured URL %q: %#v", wantBaseURL, response)
+ }
+ if strings.Contains(response.Command, "attacker") || len(cfg.APITokens) != 2 {
+ t.Fatalf("install response or token records drifted: command=%q records=%d", response.Command, len(cfg.APITokens))
+ }
+ })
+ }
+
+ for _, installType := range []string{"pve", "pbs"} {
+ t.Run(installType+" setup artifact", func(t *testing.T) {
+ router, _ := newHostedRouter(t, "https://configured.example/", false, tc.agentConnectURL, tc.headers)
+ rec := doRequest(t, router, http.MethodPost, "/api/setup-script-url", fmt.Sprintf(`{"type":%q,"host":%q}`, installType, installType+"1.local"), tc.headers, true)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("artifact 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.HasPrefix(artifact.DownloadURL, wantBaseURL+"/api/setup-script?") || strings.Contains(artifact.Command, "attacker") {
+ t.Fatalf("setup artifact did not bind fresh token to configured URL %q: %#v", wantBaseURL, artifact)
+ }
+
+ download, err := url.Parse(artifact.DownloadURL)
+ if err != nil {
+ t.Fatalf("parse download URL: %v", err)
+ }
+ downloadRec := doRequest(t, router, http.MethodGet, download.RequestURI(), "", tc.headers, false)
+ if downloadRec.Code != http.StatusOK {
+ t.Fatalf("setup script status = %d, want %d: %s", downloadRec.Code, http.StatusOK, downloadRec.Body.String())
+ }
+ if !strings.Contains(downloadRec.Body.String(), wantBaseURL) || !strings.Contains(downloadRec.Body.String(), artifact.SetupToken) || strings.Contains(downloadRec.Body.String(), "attacker") {
+ t.Fatalf("rendered setup script did not preserve configured token target")
+ }
+ })
+ }
+ })
+ }
+}
+
// 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/router.go b/internal/api/router.go
index bbc443f27f..186c52d3e5 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -64,6 +64,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/pkg/extensions"
metricstore "github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/securityutil"
"github.com/rs/zerolog/log"
"golang.org/x/sync/singleflight"
)
@@ -429,7 +430,7 @@ func (r *Router) setupRoutes() {
guestMetadataHandler := NewGuestMetadataHandler(r.multiTenant)
dockerMetadataHandler := NewDockerMetadataHandler(r.multiTenant)
hostMetadataHandler := NewHostMetadataHandler(r.multiTenant)
- r.configHandlers = NewConfigHandlers(r.multiTenant, r.mtMonitor, r.reloadFunc, r.wsHub, guestMetadataHandler, r.reloadSystemSettings)
+ r.configHandlers = NewConfigHandlers(r.multiTenant, r.mtMonitor, r.reloadFunc, r.wsHub, guestMetadataHandler, r.reloadSystemSettings, r.hostedMode)
if r.monitor != nil {
r.configHandlers.SetMonitor(r.monitor)
r.bindDefaultMetadataStores(r.monitor)
@@ -10975,10 +10976,18 @@ func resolveConfiguredPublicBaseURL(req *http.Request, cfg *config.Config, hoste
// A canonical externally-reachable URL must be configured via PublicURL / AgentConnectURL.
if hostedMode {
if agentConnectURL := strings.TrimSpace(cfg.AgentConnectURL); agentConnectURL != "" {
- return strings.TrimRight(agentConnectURL, "/")
+ normalized, err := securityutil.NormalizePulseHTTPBaseURL(agentConnectURL)
+ if err != nil {
+ return ""
+ }
+ return strings.TrimRight(normalized.String(), "/")
}
- if publicURL := strings.TrimSpace(cfg.PublicURL); publicURL != "" {
- return strings.TrimRight(publicURL, "/")
+ if publicURL := strings.TrimSpace(cfg.PublicURL); publicURL != "" && !cfg.PublicURLAutoDetected {
+ normalized, err := securityutil.NormalizePulseHTTPBaseURL(publicURL)
+ if err != nil {
+ return ""
+ }
+ return strings.TrimRight(normalized.String(), "/")
}
return ""
}
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 00b5bae748..2f35c79bc5 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -4620,7 +4620,7 @@ func TestSSHKeyGenerationBlockedInContainer(t *testing.T) {
homeDir := t.TempDir()
t.Setenv("HOME", homeDir)
- handler := NewConfigHandlers(nil, nil, func() error { return nil }, nil, nil, func() {})
+ handler := NewConfigHandlers(nil, nil, func() error { return nil }, nil, nil, func() {}, false)
keys := handler.getOrGenerateSSHKeys()
if keys.SensorsPublicKey != "" {
t.Fatalf("expected empty key when container SSH generation is blocked")