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(hosted): trust cloud proxy origins for websockets

rcourtman39fb7521780a
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8019c9fe94..55cf1bfcde 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -179,6 +179,11 @@ instead of adopting execution-history persistence as a side effect.
Those unified audit list endpoints also clamp oversized `limit` requests to
the governed maximum, so audit history stays bounded even when callers ask
for arbitrarily large pages.
+That same shared `internal/api/` dependency also now assumes hosted runtime
+websocket upgrades trust the cloud proxy only through explicit tenant
+`PULSE_TRUSTED_PROXY_CIDRS` wiring, so first-session handoff and agent-facing
+live activity surfaces do not degrade into reconnect loops when a hosted
+workspace is opened through the control plane.
The same shared API runtime now also exposes dedicated unified-resource
timeline reads through `internal/api/resources.go` plus the bundled facet
history read used by the drawer, but those query surfaces remain owned by the
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index a626158efb..b8d6b32cd3 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -218,6 +218,12 @@ path, signup path, and stable workspace summary fields such as `created_at`.
That workspace summary contract must expose explicit health semantics: `healthy`
for passing health checks, `checking` only when no completed health check
exists yet, and `unhealthy` for a failed latest health check.
+That same shared `internal/api/` boundary also owns trusted-proxy websocket
+origin continuity for hosted runtimes. When a hosted tenant is opened through
+the cloud proxy, the runtime must derive the effective same-origin
+`https://<tenant-host>` boundary from trusted forwarded host/proto headers
+only after the hosted container contract has injected explicit proxy CIDRs, so
+live updates stay connected without weakening cross-site websocket checks.
`/portal` is now one bootstrap-driven shell for both anonymous and
authenticated users, so new account frontend work must extend that shared
contract rather than inventing a second local payload shape, reviving separate
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 422b24af43..997ecbfc29 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -127,6 +127,11 @@ lease before storage- or recovery-adjacent runtime consumers inspect
assistant availability, so recovery points, restore guidance, and related
operator surfaces do not read a tenant-org AI readiness state that diverges
from the machine-owned hosted entitlement already governing the instance.
+That same shared `internal/api/` dependency also now assumes hosted runtime
+websocket upgrades trust the cloud proxy only through explicit tenant
+`PULSE_TRUSTED_PROXY_CIDRS` wiring, so storage- and recovery-adjacent live
+status surfaces do not fall into reconnect loops after a hosted workspace
+handoff.
The recovery frontend now also separates that ownership more explicitly:
`frontend-modern/src/features/recovery/useRecoverySurfaceState.ts` owns
canonical route parsing, filter/query state, transport hook inputs, and URL
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index a582b12ddd..f7da89bad0 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -16,6 +16,7 @@ import (
"time"
"github.com/golang-jwt/jwt/v5"
+ "github.com/gorilla/websocket"
"github.com/rcourtman/pulse-go-rewrite/internal/ai"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
@@ -35,6 +36,34 @@ import (
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
)
+func TestContract_WebSocketTrustedProxyHostedOrigin(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "127.0.0.1/32")
+ resetTrustedProxyCIDRsForTests()
+
+ rawToken := "contract-ws-origin-forwarded-123.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeMonitoringRead}, nil)
+
+ server, cleanup := newWebSocketRouter(t, []string{}, record)
+ defer cleanup()
+
+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws?org_id=default"
+ headers := http.Header{}
+ headers.Set("X-API-Token", rawToken)
+ headers.Set("Origin", "https://tenant.example.com")
+ headers.Set("X-Forwarded-Proto", "https")
+ headers.Set("X-Forwarded-Host", "tenant.example.com")
+
+ conn, resp, err := websocket.DefaultDialer.Dial(wsURL, headers)
+ if err != nil {
+ t.Fatalf("expected websocket connection behind trusted proxy, got %v", err)
+ }
+ if resp == nil || resp.StatusCode != http.StatusSwitchingProtocols {
+ conn.Close()
+ t.Fatalf("expected 101 switching protocols, got %v", resp)
+ }
+ conn.Close()
+}
+
func TestContract_FindingJSONSnapshot(t *testing.T) {
now := time.Date(2026, 2, 8, 13, 14, 15, 0, time.UTC)
lastSeen := now.Add(5 * time.Minute)
@@ -2484,12 +2513,6 @@ func TestContract_HostedBillingStateFallbackJSONSnapshot(t *testing.T) {
func TestContract_HandoffExchangeJSONSnapshot(t *testing.T) {
key := []byte("test-handoff-key")
configDir := t.TempDir()
- resetSessionStoreForTests()
- t.Cleanup(resetSessionStoreForTests)
- resetCSRFStoreForTests()
- t.Cleanup(resetCSRFStoreForTests)
- InitSessionStore(configDir)
- InitCSRFStore(configDir)
secretsDir := filepath.Join(configDir, "secrets")
if err := os.MkdirAll(secretsDir, 0o755); err != nil {
t.Fatalf("MkdirAll() error = %v", err)
@@ -2500,9 +2523,7 @@ func TestContract_HandoffExchangeJSONSnapshot(t *testing.T) {
handler := HandleHandoffExchange(configDir)
tenantID := "tenant-contract"
- t.Setenv("PULSE_HOSTED_MODE", "true")
t.Setenv("PULSE_TENANT_ID", "")
- t.Setenv("PULSE_PUBLIC_URL", "")
token := signHandoffToken(t, key, cloudHandoffClaims{
AccountID: "acct-contract",
@@ -2519,7 +2540,9 @@ func TestContract_HandoffExchangeJSONSnapshot(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/cloud/handoff/exchange?token="+token+"&format=json", nil)
req.Host = tenantID + ".cloud.pulserelay.pro"
req.Header.Set("Accept", "application/json")
- req.RemoteAddr = "198.51.100.20:1234"
+ req.Header.Set("X-Forwarded-Host", req.Host)
+ req.Header.Set("X-Forwarded-For", "127.0.0.1")
+ req.RemoteAddr = "127.0.0.1:1234"
rec := httptest.NewRecorder()
handler(rec, req)
diff --git a/internal/api/router.go b/internal/api/router.go
index 37fd6895b8..ff01c659ac 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -218,6 +218,9 @@ func NewRouter(cfg *config.Config, monitor *monitoring.Monitor, mtMonitor *monit
monitorSupplementalRecords: make(map[unifiedresources.DataSource]monitoring.MonitorSupplementalRecordsProvider),
startedPatrolOrgs: make(map[string]bool),
}
+ if r.wsHub != nil {
+ r.wsHub.SetTrustedProxyChecker(isTrustedProxyIP)
+ }
if r.hostedMode {
// Use defaults: 2000 req/min per org.
r.tenantRateLimiter = NewTenantRateLimiter(0, 0)
diff --git a/internal/api/websocket_origin_security_test.go b/internal/api/websocket_origin_security_test.go
index 8d28bc7825..aab7efc8ad 100644
--- a/internal/api/websocket_origin_security_test.go
+++ b/internal/api/websocket_origin_security_test.go
@@ -4,6 +4,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync"
"testing"
"github.com/gorilla/websocket"
@@ -11,6 +12,11 @@ import (
pulsews "github.com/rcourtman/pulse-go-rewrite/internal/websocket"
)
+func resetTrustedProxyCIDRsForTests() {
+ trustedProxyCIDRs = nil
+ trustedProxyOnce = sync.Once{}
+}
+
func newWebSocketRouter(t *testing.T, allowedOrigins []string, tokenRecord config.APITokenRecord) (*httptest.Server, func()) {
t.Helper()
@@ -124,3 +130,31 @@ func TestWebSocketOriginAllowsPrivateWhenNoAllowedOrigins(t *testing.T) {
}
conn.Close()
}
+
+func TestWebSocketOriginAllowsTrustedForwardedHostedOrigin(t *testing.T) {
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "127.0.0.1/32")
+ resetTrustedProxyCIDRsForTests()
+
+ rawToken := "ws-origin-forwarded-allow-123.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeMonitoringRead}, nil)
+
+ server, cleanup := newWebSocketRouter(t, []string{}, record)
+ defer cleanup()
+
+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws?org_id=default"
+ headers := http.Header{}
+ headers.Set("X-API-Token", rawToken)
+ headers.Set("Origin", "https://tenant.example.com")
+ headers.Set("X-Forwarded-Proto", "https")
+ headers.Set("X-Forwarded-Host", "tenant.example.com")
+
+ conn, resp, err := websocket.DefaultDialer.Dial(wsURL, headers)
+ if err != nil {
+ t.Fatalf("expected websocket connection behind trusted proxy, got %v", err)
+ }
+ if resp == nil || resp.StatusCode != http.StatusSwitchingProtocols {
+ conn.Close()
+ t.Fatalf("expected 101 switching protocols, got %v", resp)
+ }
+ conn.Close()
+}
diff --git a/internal/cloudcp/config.go b/internal/cloudcp/config.go
index a387aa4405..6950cd1709 100644
--- a/internal/cloudcp/config.go
+++ b/internal/cloudcp/config.go
@@ -29,6 +29,7 @@ type CPConfig struct {
PortalAPIRateLimitPerMinute int
PulseImage string
DockerNetwork string
+ TrustedProxyCIDRs []string
TenantMemoryLimit int64 // bytes
TenantCPUShares int64
AllowDockerlessProvisioning bool
@@ -113,6 +114,7 @@ func LoadConfig() (*CPConfig, error) {
PortalAPIRateLimitPerMinute: portalRPS,
PulseImage: envOrDefault("CP_PULSE_IMAGE", "ghcr.io/rcourtman/pulse:latest"),
DockerNetwork: envOrDefault("CP_DOCKER_NETWORK", "pulse-cloud"),
+ TrustedProxyCIDRs: parseTrustedProxyCIDRValues("CP_TRUSTED_PROXY_CIDRS", "PULSE_TRUSTED_PROXY_CIDRS"),
TenantMemoryLimit: tenantMemoryLimit,
TenantCPUShares: tenantCPUShares,
AllowDockerlessProvisioning: envOrDefaultBool("CP_ALLOW_DOCKERLESS_PROVISIONING", false),
@@ -285,3 +287,26 @@ func envOrDefaultBool(key string, fallback bool) bool {
return fallback
}
}
+
+func parseTrustedProxyCIDRValues(keys ...string) []string {
+ values := make([]string, 0)
+ seen := make(map[string]struct{})
+ for _, key := range keys {
+ raw := strings.TrimSpace(os.Getenv(key))
+ if raw == "" {
+ continue
+ }
+ for _, entry := range strings.Split(raw, ",") {
+ entry = strings.TrimSpace(entry)
+ if entry == "" {
+ continue
+ }
+ if _, ok := seen[entry]; ok {
+ continue
+ }
+ seen[entry] = struct{}{}
+ values = append(values, entry)
+ }
+ }
+ return values
+}
diff --git a/internal/cloudcp/config_test.go b/internal/cloudcp/config_test.go
index 7b69b4f54c..732566c87f 100644
--- a/internal/cloudcp/config_test.go
+++ b/internal/cloudcp/config_test.go
@@ -94,6 +94,27 @@ func TestLoadConfig_CustomValues(t *testing.T) {
}
}
+func TestLoadConfig_TrustedProxyCIDRs(t *testing.T) {
+ setRequiredCPEnv(t)
+ t.Setenv("CP_TRUSTED_PROXY_CIDRS", "172.18.0.0/16, 127.0.0.1/32")
+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "192.168.0.0/16")
+
+ cfg, err := LoadConfig()
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+
+ want := []string{"172.18.0.0/16", "127.0.0.1/32", "192.168.0.0/16"}
+ if len(cfg.TrustedProxyCIDRs) != len(want) {
+ t.Fatalf("len(TrustedProxyCIDRs) = %d, want %d (%v)", len(cfg.TrustedProxyCIDRs), len(want), cfg.TrustedProxyCIDRs)
+ }
+ for i, expected := range want {
+ if cfg.TrustedProxyCIDRs[i] != expected {
+ t.Fatalf("TrustedProxyCIDRs[%d] = %q, want %q", i, cfg.TrustedProxyCIDRs[i], expected)
+ }
+ }
+}
+
func TestLoadConfig_InvalidPortParse(t *testing.T) {
setRequiredCPEnv(t)
t.Setenv("CP_PORT", "not-a-number")
diff --git a/internal/cloudcp/docker/manager.go b/internal/cloudcp/docker/manager.go
index 7676d3a1b5..7918e0a106 100644
--- a/internal/cloudcp/docker/manager.go
+++ b/internal/cloudcp/docker/manager.go
@@ -5,8 +5,10 @@ import (
"fmt"
"io"
"net/http"
+ "net/netip"
"os"
"path/filepath"
+ "sort"
"strings"
"time"
@@ -19,12 +21,13 @@ import (
// ManagerConfig holds Docker manager settings.
type ManagerConfig struct {
- Image string
- Network string
- BaseDomain string
- MemoryLimit int64 // bytes
- CPUShares int64
- ContainerPort int // port inside the container (default 7655)
+ Image string
+ Network string
+ BaseDomain string
+ TrustedProxyCIDRs []string
+ MemoryLimit int64 // bytes
+ CPUShares int64
+ ContainerPort int // port inside the container (default 7655)
}
// Manager orchestrates Docker containers for tenant lifecycle.
@@ -89,7 +92,7 @@ func (m *Manager) CreateAndStart(ctx context.Context, tenantID, tenantDataDir st
&container.Config{
Image: m.cfg.Image,
Labels: labels,
- Env: tenantEnv(tenantID, m.cfg.BaseDomain),
+ Env: tenantEnv(tenantID, m.cfg.BaseDomain, m.tenantTrustedProxyCIDRs(ctx)),
},
&container.HostConfig{
RestartPolicy: container.RestartPolicy{Name: "unless-stopped"},
@@ -139,7 +142,7 @@ func tenantRuntimeOwnershipPaths() []string {
}
}
-func tenantEnv(tenantID, baseDomain string) []string {
+func tenantEnv(tenantID, baseDomain string, trustedProxyCIDRs []string) []string {
publicURL := ""
tenantID = strings.TrimSpace(tenantID)
baseDomain = strings.TrimSpace(baseDomain)
@@ -159,9 +162,65 @@ func tenantEnv(tenantID, baseDomain string) []string {
if publicURL != "" {
env = append(env, "PULSE_PUBLIC_URL="+publicURL)
}
+ if len(trustedProxyCIDRs) > 0 {
+ env = append(env, "PULSE_TRUSTED_PROXY_CIDRS="+strings.Join(trustedProxyCIDRs, ","))
+ }
return env
}
+func (m *Manager) tenantTrustedProxyCIDRs(ctx context.Context) []string {
+ values := make([]string, 0, len(m.cfg.TrustedProxyCIDRs)+1)
+ seen := make(map[string]struct{})
+ appendCIDR := func(raw string) {
+ canonical := canonicalTrustedProxyCIDR(raw)
+ if canonical == "" {
+ return
+ }
+ if _, ok := seen[canonical]; ok {
+ return
+ }
+ seen[canonical] = struct{}{}
+ values = append(values, canonical)
+ }
+
+ for _, cidr := range m.cfg.TrustedProxyCIDRs {
+ appendCIDR(cidr)
+ }
+
+ if m != nil && m.cli != nil && strings.TrimSpace(m.cfg.Network) != "" {
+ networkName := strings.TrimSpace(m.cfg.Network)
+ inspect, err := m.cli.NetworkInspect(ctx, networkName, network.InspectOptions{})
+ if err != nil {
+ log.Warn().Err(err).Str("network", networkName).Msg("Failed to inspect tenant network for trusted proxy CIDRs")
+ } else {
+ for _, cfg := range inspect.IPAM.Config {
+ appendCIDR(cfg.Subnet)
+ }
+ }
+ }
+
+ sort.Strings(values)
+ return values
+}
+
+func canonicalTrustedProxyCIDR(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return ""
+ }
+ if prefix, err := netip.ParsePrefix(raw); err == nil {
+ return prefix.Masked().String()
+ }
+ if addr, err := netip.ParseAddr(raw); err == nil {
+ bits := 32
+ if addr.Is6() {
+ bits = 128
+ }
+ return netip.PrefixFrom(addr, bits).Masked().String()
+ }
+ return ""
+}
+
func tenantMounts(tenantDataDir string) []mount.Mount {
return []mount.Mount{
{
diff --git a/internal/cloudcp/docker/manager_test.go b/internal/cloudcp/docker/manager_test.go
index 667c0e3097..e5a7142fff 100644
--- a/internal/cloudcp/docker/manager_test.go
+++ b/internal/cloudcp/docker/manager_test.go
@@ -70,7 +70,7 @@ func TestTenantMountsKeepImmutableFilesReadOnly(t *testing.T) {
func TestTenantEnvIncludesImmutableOwnershipContract(t *testing.T) {
t.Parallel()
- env := tenantEnv("t-example", "cloud.pulserelay.pro")
+ env := tenantEnv("t-example", "cloud.pulserelay.pro", []string{"172.18.0.0/16", "127.0.0.1/32"})
want := map[string]bool{
"PULSE_DATA_DIR=/etc/pulse": true,
"PULSE_HOSTED_MODE=true": true,
@@ -79,6 +79,7 @@ func TestTenantEnvIncludesImmutableOwnershipContract(t *testing.T) {
"PUID=1000": true,
"PGID=1000": true,
"PULSE_PUBLIC_URL=https://t-example.cloud.pulserelay.pro": true,
+ "PULSE_TRUSTED_PROXY_CIDRS=172.18.0.0/16,127.0.0.1/32": true,
immutableOwnershipPathsEnv + "=/etc/pulse/secrets/handoff.key:/etc/pulse/.cloud_handoff_key": true,
}
if len(env) != len(want) {
@@ -94,7 +95,7 @@ func TestTenantEnvIncludesImmutableOwnershipContract(t *testing.T) {
func TestTenantEnvOmitsPublicURLWithoutTenantContext(t *testing.T) {
t.Parallel()
- env := tenantEnv("", "")
+ env := tenantEnv("", "", nil)
sawTenantID := false
for _, item := range env {
if strings.HasPrefix(item, "PULSE_PUBLIC_URL=") {
@@ -109,6 +110,29 @@ func TestTenantEnvOmitsPublicURLWithoutTenantContext(t *testing.T) {
}
}
+func TestCanonicalTrustedProxyCIDR(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ input string
+ want string
+ }{
+ {input: "172.18.0.0/16", want: "172.18.0.0/16"},
+ {input: "172.18.12.34/16", want: "172.18.0.0/16"},
+ {input: "127.0.0.1", want: "127.0.0.1/32"},
+ {input: "2001:db8::1", want: "2001:db8::1/128"},
+ {input: "not-a-cidr", want: ""},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.input, func(t *testing.T) {
+ if got := canonicalTrustedProxyCIDR(tc.input); got != tc.want {
+ t.Fatalf("canonicalTrustedProxyCIDR(%q) = %q, want %q", tc.input, got, tc.want)
+ }
+ })
+ }
+}
+
func TestPrepareTenantRuntimeMountSourcesAlignsOwnershipAndPermissions(t *testing.T) {
t.Parallel()
diff --git a/internal/cloudcp/server.go b/internal/cloudcp/server.go
index ba5754f058..09474b8af7 100644
--- a/internal/cloudcp/server.go
+++ b/internal/cloudcp/server.go
@@ -53,11 +53,12 @@ func Run(ctx context.Context, version string) error {
// Initialize Docker manager (best-effort — control plane can run without Docker for dev/testing)
var dockerMgr *cpDocker.Manager
dockerMgr, err = cpDocker.NewManager(cpDocker.ManagerConfig{
- Image: cfg.PulseImage,
- Network: cfg.DockerNetwork,
- BaseDomain: baseDomainFromURL(cfg.BaseURL),
- MemoryLimit: cfg.TenantMemoryLimit,
- CPUShares: cfg.TenantCPUShares,
+ Image: cfg.PulseImage,
+ Network: cfg.DockerNetwork,
+ BaseDomain: baseDomainFromURL(cfg.BaseURL),
+ TrustedProxyCIDRs: cfg.TrustedProxyCIDRs,
+ MemoryLimit: cfg.TenantMemoryLimit,
+ CPUShares: cfg.TenantCPUShares,
})
if err != nil {
log.Warn().Err(err).Msg("Docker unavailable — container management disabled")