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.

Harden session and setup token auth flows

rcourtman5ebb3d995212
diff --git a/internal/api/auth.go b/internal/api/auth.go
index 4866a6fea0..54e3469ce1 100644
--- a/internal/api/auth.go
+++ b/internal/api/auth.go
@@ -337,14 +337,20 @@ func sessionCookieName(secure bool) string {
return cookieNameSession
}
-// readSessionCookie reads the session cookie from the request, checking for the
-// __Host- prefixed name first (HTTPS) then falling back to the unprefixed name
-// (HTTP or upgrade transition). This ensures sessions survive an HTTP→HTTPS migration.
+// readSessionCookie reads the session cookie from the request. Secure requests
+// must present the __Host- prefixed cookie; insecure requests continue to use
+// the legacy unprefixed name.
func readSessionCookie(r *http.Request) (*http.Cookie, error) {
- if c, err := r.Cookie(cookieNameSessionSecure); err == nil {
+ if r == nil {
+ return nil, http.ErrNoCookie
+ }
+ if isConnectionSecure(r) {
+ return r.Cookie(cookieNameSessionSecure)
+ }
+ if c, err := r.Cookie(cookieNameSession); err == nil {
return c, nil
}
- return r.Cookie(cookieNameSession)
+ return r.Cookie(cookieNameSessionSecure)
}
// generateSessionToken creates a cryptographically secure session token
diff --git a/internal/api/auth_helpers_test.go b/internal/api/auth_helpers_test.go
index 4018c00f96..7a3ef8f798 100644
--- a/internal/api/auth_helpers_test.go
+++ b/internal/api/auth_helpers_test.go
@@ -921,6 +921,36 @@ func TestCheckAuth_ValidSessionWithSlidingExpiration(t *testing.T) {
}
}
+func TestReadSessionCookie_SecureRequestRequiresHostPrefix(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "https://pulse.example.test/api/test", nil)
+ req.TLS = &tls.ConnectionState{}
+ req.AddCookie(&http.Cookie{
+ Name: cookieNameSession,
+ Value: "legacy-session",
+ })
+
+ if _, err := readSessionCookie(req); err == nil {
+ t.Fatalf("expected secure request to reject legacy session cookie")
+ }
+}
+
+func TestReadSessionCookie_SecureRequestAcceptsHostPrefix(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "https://pulse.example.test/api/test", nil)
+ req.TLS = &tls.ConnectionState{}
+ req.AddCookie(&http.Cookie{
+ Name: cookieNameSessionSecure,
+ Value: "secure-session",
+ })
+
+ cookie, err := readSessionCookie(req)
+ if err != nil {
+ t.Fatalf("expected secure request to accept __Host- session cookie: %v", err)
+ }
+ if cookie.Value != "secure-session" {
+ t.Fatalf("unexpected cookie value %q", cookie.Value)
+ }
+}
+
func TestCheckAuth_NoAuthConfigured(t *testing.T) {
cfg := &config.Config{
// No auth configured at all
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 7b0e6faeed..f2c2db0870 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/ed25519"
+ "crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
@@ -4086,6 +4087,58 @@ func TestContract_HostedSessionAuthPrecedesAnonymousFallback(t *testing.T) {
}
}
+func TestContract_SecureHostedSessionRequiresHostPrefixedCookie(t *testing.T) {
+ resetPersistentAuthStoresForTests()
+ t.Cleanup(resetPersistentAuthStoresForTests)
+
+ InitSessionStore(t.TempDir())
+
+ store := GetSessionStore()
+ sessionToken := generateSessionToken()
+ store.CreateSession(sessionToken, 24*time.Hour, "contract-test", "127.0.0.1", "[email protected]")
+ record, err := config.NewAPITokenRecord("hosted-secure-session-token.12345678", "hosted-secure-session", []string{config.ScopeSettingsWrite})
+ if err != nil {
+ t.Fatalf("NewAPITokenRecord: %v", err)
+ }
+ cfg := &config.Config{
+ APITokens: []config.APITokenRecord{*record},
+ }
+
+ t.Run("legacy cookie is rejected on secure requests", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "https://pulse.example.test/api/security/tokens/relay-mobile", nil)
+ req.TLS = &tls.ConnectionState{}
+ req.AddCookie(&http.Cookie{
+ Name: cookieNameSession,
+ Value: sessionToken,
+ })
+ rec := httptest.NewRecorder()
+
+ if CheckAuth(cfg, rec, req) {
+ t.Fatal("CheckAuth() = true, want false for legacy session cookie on secure request")
+ }
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d when secure request only presents legacy cookie", rec.Code, http.StatusUnauthorized)
+ }
+ })
+
+ t.Run("host-prefixed cookie remains valid on secure requests", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "https://pulse.example.test/api/security/tokens/relay-mobile", nil)
+ req.TLS = &tls.ConnectionState{}
+ req.AddCookie(&http.Cookie{
+ Name: cookieNameSessionSecure,
+ Value: sessionToken,
+ })
+ rec := httptest.NewRecorder()
+
+ if !CheckAuth(cfg, rec, req) {
+ t.Fatal("CheckAuth() = false, want true for __Host- session cookie on secure request")
+ }
+ if got := rec.Header().Get("X-Authenticated-User"); got != "[email protected]" {
+ t.Fatalf("X-Authenticated-User = %q, want [email protected]", got)
+ }
+ })
+}
+
func TestContract_UniversalRateLimitStateIsScopedPerRouterConfig(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
@@ -4274,6 +4327,71 @@ func TestContract_RelayMobileScopeCanReadOnboardingDeepLink(t *testing.T) {
}
}
+func TestContract_OnboardingDeepLinkIgnoresQueryAuthToken(t *testing.T) {
+ rawToken := "relay-mobile-onboarding-query-token.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeRelayMobileAccess}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ req := httptest.NewRequest(http.MethodGet, "/api/onboarding/deep-link?auth_token="+url.QueryEscape(rawToken), nil)
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d when auth token is only provided in query string", rec.Code, http.StatusUnauthorized)
+ }
+}
+
+func TestContract_SetupTokenRoutesRejectQueryAuthToken(t *testing.T) {
+ cfg := newTestConfigWithTokens(t, newTokenRecord(t, "settings-write-token", []string{config.ScopeSettingsWrite}, nil))
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+ t.Setenv("HOME", t.TempDir())
+
+ token := "fedcba9876543210fedcba9876543210"
+ tokenHash := authpkg.HashAPIToken(token)
+ router.configHandlers.codeMutex.Lock()
+ router.configHandlers.setupTokens[tokenHash] = &SetupTokenRecord{ExpiresAt: time.Now().Add(time.Minute)}
+ router.configHandlers.codeMutex.Unlock()
+
+ t.Run("verify-temperature-ssh requires header token transport", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, "/api/system/verify-temperature-ssh?auth_token="+token, strings.NewReader(`{"nodes":""}`))
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d when setup token is only in query string", rec.Code, http.StatusUnauthorized)
+ }
+
+ req = httptest.NewRequest(http.MethodPost, "/api/system/verify-temperature-ssh", strings.NewReader(`{"nodes":""}`))
+ req.Header.Set("X-Setup-Token", token)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d when setup token is provided in header", rec.Code, http.StatusOK)
+ }
+ })
+
+ t.Run("ssh-config requires header token transport", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, "/api/system/ssh-config?auth_token="+token, strings.NewReader("Host example\nHostname example\n"))
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d when setup token is only in query string", rec.Code, http.StatusUnauthorized)
+ }
+
+ req = httptest.NewRequest(http.MethodPost, "/api/system/ssh-config", strings.NewReader("Host example\nHostname example\n"))
+ req.Header.Set("X-Setup-Token", token)
+ rec = httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d when setup token is provided in header", rec.Code, http.StatusOK)
+ }
+ })
+}
+
func TestContract_RelayMobileScopeCannotReadApprovalDetail(t *testing.T) {
rawToken := "relay-mobile-approval-detail-token-123.12345678"
record := newTokenRecord(t, rawToken, []string{config.ScopeRelayMobileAccess}, nil)
diff --git a/internal/api/onboarding_handlers.go b/internal/api/onboarding_handlers.go
index 8ba9390385..ba10ee71aa 100644
--- a/internal/api/onboarding_handlers.go
+++ b/internal/api/onboarding_handlers.go
@@ -350,9 +350,6 @@ func onboardingAuthTokenFromRequest(req *http.Request) string {
if token := extractBearerToken(req.Header.Get("Authorization")); token != "" {
return token
}
- if token := strings.TrimSpace(req.URL.Query().Get("auth_token")); token != "" {
- return token
- }
return ""
}
diff --git a/internal/api/onboarding_handlers_test.go b/internal/api/onboarding_handlers_test.go
index 0444e875fc..c4be894688 100644
--- a/internal/api/onboarding_handlers_test.go
+++ b/internal/api/onboarding_handlers_test.go
@@ -209,6 +209,35 @@ func TestNormalizeOnboardingRelayAppURL(t *testing.T) {
}
}
+func TestOnboardingAuthTokenFromRequest(t *testing.T) {
+ t.Run("prefers X-API-Token header", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/onboarding/qr?auth_token=query-token", nil)
+ req.Header.Set("X-API-Token", " header-token ")
+ req.Header.Set("Authorization", "Bearer bearer-token")
+
+ if got := onboardingAuthTokenFromRequest(req); got != "header-token" {
+ t.Fatalf("expected X-API-Token header, got %q", got)
+ }
+ })
+
+ t.Run("falls back to bearer token", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/onboarding/qr?auth_token=query-token", nil)
+ req.Header.Set("Authorization", "Bearer bearer-token")
+
+ if got := onboardingAuthTokenFromRequest(req); got != "bearer-token" {
+ t.Fatalf("expected bearer token, got %q", got)
+ }
+ })
+
+ t.Run("ignores query auth_token", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/onboarding/qr?auth_token=query-token", nil)
+
+ if got := onboardingAuthTokenFromRequest(req); got != "" {
+ t.Fatalf("expected empty auth token, got %q", got)
+ }
+ })
+}
+
func newOnboardingContractRouter(t *testing.T) (*Router, string, relay.Config) {
t.Helper()
diff --git a/internal/api/router.go b/internal/api/router.go
index 96674815e8..cd7f8af21b 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -1018,9 +1018,6 @@ func extractSetupToken(req *http.Request) string {
if token := extractBearerToken(req.Header.Get("Authorization")); token != "" {
return token
}
- if token := strings.TrimSpace(req.URL.Query().Get("auth_token")); token != "" {
- return token
- }
return ""
}
diff --git a/internal/api/router_helpers_additional_test.go b/internal/api/router_helpers_additional_test.go
index 5100bfdca7..4cdf9514d2 100644
--- a/internal/api/router_helpers_additional_test.go
+++ b/internal/api/router_helpers_additional_test.go
@@ -81,11 +81,11 @@ func TestExtractSetupToken(t *testing.T) {
}
})
- t.Run("falls back to query", func(t *testing.T) {
+ t.Run("ignores query auth_token", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/setup?auth_token=query-token", nil)
- if got := extractSetupToken(req); got != "query-token" {
- t.Fatalf("expected query token, got %q", got)
+ if got := extractSetupToken(req); got != "" {
+ t.Fatalf("expected empty token, got %q", got)
}
})
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index dbbd58118e..34526b04a8 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -4302,8 +4302,8 @@ func TestSSHConfigRejectsSetupTokenOrgMismatch(t *testing.T) {
}
}
-func TestVerifyTemperatureSSHAllowsSetupTokenQueryParam(t *testing.T) {
- cfg := newTestConfigWithTokens(t)
+func TestVerifyTemperatureSSHRejectsSetupTokenQueryParam(t *testing.T) {
+ cfg := newTestConfigWithTokens(t, newTokenRecord(t, "settings-write-token", []string{config.ScopeSettingsWrite}, nil))
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
token := "abcdefabcdefabcdefabcdefabcdefab"
@@ -4315,16 +4315,13 @@ func TestVerifyTemperatureSSHAllowsSetupTokenQueryParam(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/system/verify-temperature-ssh?auth_token="+token, strings.NewReader(`{"nodes":""}`))
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("expected 200 with setup token query param, got %d", rec.Code)
- }
- if !strings.Contains(rec.Body.String(), "No nodes to verify") {
- t.Fatalf("expected verify response, got %q", rec.Body.String())
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401 when setup token is only provided in query string, got %d", rec.Code)
}
}
-func TestSSHConfigAllowsSetupTokenQueryParam(t *testing.T) {
- cfg := newTestConfigWithTokens(t)
+func TestSSHConfigRejectsSetupTokenQueryParam(t *testing.T) {
+ cfg := newTestConfigWithTokens(t, newTokenRecord(t, "settings-write-token", []string{config.ScopeSettingsWrite}, nil))
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
t.Setenv("HOME", t.TempDir())
@@ -4337,10 +4334,7 @@ func TestSSHConfigAllowsSetupTokenQueryParam(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/system/ssh-config?auth_token="+token, strings.NewReader("Host example\nHostname example\n"))
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("expected 200 with setup token query param, got %d", rec.Code)
- }
- if !strings.Contains(rec.Body.String(), `"success":true`) {
- t.Fatalf("expected success response, got %q", rec.Body.String())
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401 when setup token is only provided in query string, got %d", rec.Code)
}
}