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(auth): honor hosted sessions before api-only fallback

rcourtmanb4c99a182d19
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f45f90e93f..400800e3de 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -219,8 +219,10 @@ That same hosted setup boundary also depends on tenant browser sessions staying
canonical after cloud handoff. Lifecycle-adjacent mobile pairing and hosted
admin setup routes may run without local credentials configured, but shared
`internal/api/auth.go` helpers must still honor a valid hosted `pulse_session`
-before any optional-auth anonymous fallback so operators can mint relay-mobile
-credentials and continue onboarding from the hosted runtime itself.
+before any API-only token fallback or optional-auth anonymous fallback so
+operators can mint relay-mobile credentials and continue onboarding from the
+hosted runtime itself even after that tenant has already minted managed API
+tokens.
The same setup boundary also depends on canonical org-management privilege
surviving the next step: once the request is scoped to a hosted tenant org,
shared `internal/api/security_setup_fix.go` helpers must allow that org's
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index a838f1292d..2def7e6e0e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -139,7 +139,7 @@ Own canonical runtime payload shapes between backend and frontend.
14. Keep Patrol quickstart transport semantics explicit as well: zero remaining quickstart credits are inventory data, not a standalone runtime-state override, so frontend consumers may only present the exhausted quickstart warning when the payload still reports `using_quickstart` or a runtime state that is blocked by quickstart exhaustion.
15. Keep Patrol intelligence summary transport semantics single-voiced: the canonical overall-health payload and Patrol run-history payload together must support one primary assessment plus one explicit verification explanation, and frontend consumers must not need to derive a second compact assessment or verification verdict row from the same payloads beneath the primary summary card.
16. Keep Pulse Mobile relay credential minting and permission ownership on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, `internal/api/auth.go`, `internal/api/router_routes_ai_relay.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator and governed route gates, but browser callers must only consume that route and must not define the mobile runtime scope, compatibility gate list, or token-purpose metadata locally.
-17. Keep hosted tenant browser-session precedence on the shared auth boundary: `internal/api/auth.go`, `internal/api/contract_test.go`, and hosted tenant callers must treat a valid `pulse_session` as authoritative before any no-local-auth anonymous fallback, so cloud handoff can continue into protected hosted routes without flattening the operator back to `anonymous`.
+17. Keep hosted tenant browser-session precedence on the shared auth boundary: `internal/api/auth.go`, `internal/api/contract_test.go`, and hosted tenant callers must treat a valid `pulse_session` as authoritative before any API-only token fallback or no-local-auth anonymous fallback, so cloud handoff can continue into protected hosted routes without flattening the operator back to `anonymous` or forcing a browser session through bearer-token-only mode after the tenant has minted API tokens.
18. Keep tenant settings-scope authorization aligned with org management: `internal/api/security_setup_fix.go`, `internal/api/contract_test.go`, and settings-bound hosted callers must allow the current non-default org owner/admin membership to exercise privileged tenant routes, rather than requiring a separate configured local admin identity after hosted handoff.
19. Keep mobile onboarding payload reads aligned with the server-owned relay-mobile credential: `internal/api/router_routes_ai_relay.go`, `internal/api/onboarding_handlers.go`, and `internal/api/contract_test.go` must allow the dedicated `relay:mobile:access` scope to reach the governed QR, deep-link, and connection-validation payloads without reintroducing a broader `settings:read` requirement for token-authenticated pairing clients.
@@ -1580,10 +1580,11 @@ org-local billing state of its own, rather than failing closed into
That same hosted browser-session contract must also remain authoritative once
the handoff lands on the tenant runtime: when a valid `pulse_session` cookie
is present, shared `internal/api/auth.go` helpers must authenticate that
-session before any no-local-auth anonymous fallback is considered, so hosted
-protected routes such as relay-mobile token minting, onboarding reads, and
-billing-admin/API surfaces stay reachable after cloud handoff instead of
-flattening the operator back to `anonymous`.
+session before any API-only token fallback or no-local-auth anonymous fallback
+is considered, so hosted protected routes such as relay-mobile token minting,
+onboarding reads, and billing-admin/API surfaces stay reachable after cloud
+handoff instead of flattening the operator back to `anonymous` or demanding a
+bearer token from the browser as soon as the tenant has minted one.
That same shared settings-scope contract must then preserve canonical
org-management privilege on the tenant side: when a hosted or multi-tenant
request is scoped to a non-default org, `internal/api/security_setup_fix.go`
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index a4aaee080e..207ee67790 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -867,9 +867,10 @@ fallback bootstrap or disable heuristics.
That same shared `internal/api/` boundary also owns hosted browser-session
precedence for adjacent protected reads. Storage- and recovery-adjacent hosted
surfaces may run without local auth configured, but a valid tenant
-`pulse_session` must still authenticate before the anonymous optional-auth
-fallback so hosted recovery, onboarding, and support flows do not silently
-degrade into unauthenticated state after cloud handoff.
+`pulse_session` must still authenticate before any API-only token fallback or
+the anonymous optional-auth fallback so hosted recovery, onboarding, and
+support flows do not silently degrade into unauthenticated state or bearer-
+token-only mode after cloud handoff.
That same shared settings helper layer must then preserve canonical
org-management privilege for non-default tenant requests. Storage- and
recovery-adjacent hosted flows that reuse settings-bound helpers must allow
diff --git a/internal/api/auth.go b/internal/api/auth.go
index 8083bb97d2..81acc5e5f6 100644
--- a/internal/api/auth.go
+++ b/internal/api/auth.go
@@ -511,31 +511,6 @@ func CheckAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request) bool
}
}
- // API-only mode: when only API token is configured (no password auth)
- if cfg.AuthUser == "" && cfg.AuthPass == "" && cfg.HasAPITokens() {
- if providedToken, provided := explicitAPITokenFromRequest(r); provided {
- if record, ok := validateGlobalAPITokenLocked(cfg, providedToken); ok {
- attachAPITokenRecord(r, record)
- if authenticatedUser := apiTokenAuthenticatedUser(record); authenticatedUser != "" {
- w.Header().Set("X-Authenticated-User", authenticatedUser)
- }
- w.Header().Set("X-Auth-Method", "api_token")
- return true
- }
- if w != nil {
- http.Error(w, "Invalid API token", http.StatusUnauthorized)
- }
- return false
- }
-
- // Require a valid token for all requests in API-only mode
- if w != nil {
- w.Header().Set("WWW-Authenticate", `Bearer realm="API token required; supply via Authorization header or X-API-Token header"`)
- http.Error(w, "API token required via Authorization header or X-API-Token header", http.StatusUnauthorized)
- }
- return false
- }
-
log.Debug().
Str("configured_user", cfg.AuthUser).
Bool("has_pass", cfg.AuthPass != "").
@@ -568,7 +543,9 @@ func CheckAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request) bool
}
}
- // Check session cookie (for WebSocket and UI)
+ // Check session cookie (for WebSocket and UI). Hosted cloud-handoff and
+ // other browser-session flows must stay authoritative even when the runtime
+ // also has API tokens configured.
if cookie, err := readSessionCookie(r); err == nil && cookie.Value != "" {
// Use ValidateAndExtendSession for sliding expiration
if ValidateAndExtendSession(cookie.Value) {
@@ -604,6 +581,18 @@ func CheckAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request) bool
Msg("No session cookie found")
}
+ // API-only mode: when only API tokens are configured (no password auth),
+ // explicit token credentials still win above and a valid session still wins
+ // above for hosted/cloud-handoff browser flows. If neither is present, fail
+ // closed and require a token.
+ if cfg.AuthUser == "" && cfg.AuthPass == "" && cfg.HasAPITokens() {
+ if w != nil {
+ w.Header().Set("WWW-Authenticate", `Bearer realm="API token required; supply via Authorization header or X-API-Token header"`)
+ http.Error(w, "API token required via Authorization header or X-API-Token header", http.StatusUnauthorized)
+ }
+ return false
+ }
+
// If no auth is configured at all, allow access unless SSO is enabled.
// A valid session still wins above, so hosted/cloud-handoff browser sessions
// do not get flattened into anonymous access.
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 9942baa835..8abba265e2 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -856,6 +856,13 @@ func TestContract_HostedSessionAuthPrecedesAnonymousFallback(t *testing.T) {
store := GetSessionStore()
sessionToken := generateSessionToken()
store.CreateSession(sessionToken, 24*time.Hour, "contract-test", "127.0.0.1", "[email protected]")
+ record, err := config.NewAPITokenRecord("hosted-contract-token.12345678", "hosted-contract", []string{config.ScopeSettingsWrite})
+ if err != nil {
+ t.Fatalf("NewAPITokenRecord: %v", err)
+ }
+ cfg := &config.Config{
+ APITokens: []config.APITokenRecord{*record},
+ }
req := httptest.NewRequest(http.MethodGet, "/api/security/tokens/relay-mobile", nil)
req.AddCookie(&http.Cookie{
@@ -864,7 +871,7 @@ func TestContract_HostedSessionAuthPrecedesAnonymousFallback(t *testing.T) {
})
rec := httptest.NewRecorder()
- if !CheckAuth(&config.Config{}, rec, req) {
+ if !CheckAuth(cfg, rec, req) {
t.Fatal("CheckAuth() = false, want true for valid hosted browser session")
}
if got := rec.Header().Get("X-Authenticated-User"); got != "[email protected]" {