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.

Keep public-URL token validation under authentication ownership

pulse-triage[bot]6f16061fd63f
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f46336f4d5..8ed9f46697 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -15,6 +15,24 @@
## Purpose
+### Public-URL token checks share authentication ownership
+
+The pre-route public-URL authority check uses the existing locked token
+validator and detached snapshot. Normalisation and last-used metadata updates
+hold the same exclusive configuration ownership as ordinary authentication;
+subsequent scope checks never mutate the live record outside it. Both supported
+token headers retain the existing settings-write requirement. Expired, invalid,
+wrong-role and monitoring-only credentials gain no capture authority. Sessions,
+proxy/basic administration and URL/origin selection are unchanged.
+
+`TestPublicURLTokenCaptureUsesAuthenticationOwnership` covers concurrent capture
+and ordinary authentication, retained scope/identity and successful last-use
+updates; `TestPublicURLTokenCapturePreservesTokenRefusals` pins both headers and
+refused metadata. The real concurrent history HTTP test remains unchanged and
+must pass with the race detector; the observed race is not warmed away or
+suppressed. No new rendered state, token grant or runtime action is introduced.
+
+
### Execution history uses a typed read-only projection
The recent-change read keeps kind-specific scalar status facts, not arbitrary
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 5b57c9a0e9..2228db1611 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -21,6 +21,24 @@
## Purpose
+### Public-URL token checks share authentication ownership
+
+The pre-route public-URL authority check uses the existing locked token
+validator and detached snapshot. Normalisation and last-used metadata updates
+hold the same exclusive configuration ownership as ordinary authentication;
+subsequent scope checks never mutate the live record outside it. Both supported
+token headers retain the existing settings-write requirement. Expired, invalid,
+wrong-role and monitoring-only credentials gain no capture authority. Sessions,
+proxy/basic administration and URL/origin selection are unchanged.
+
+`TestPublicURLTokenCaptureUsesAuthenticationOwnership` covers concurrent capture
+and ordinary authentication, retained scope/identity and successful last-use
+updates; `TestPublicURLTokenCapturePreservesTokenRefusals` pins both headers and
+refused metadata. The real concurrent history HTTP test remains unchanged and
+must pass with the race detector; the observed race is not warmed away or
+suppressed. No new rendered state, token grant or runtime action is introduced.
+
+
### Recent-change execution facts are a restricted projection
Monitoring-read history uses kind-specific scalar facts and fixed reasons;
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 355e3a8d35..faaacb3afe 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -18,6 +18,24 @@
## Purpose
+### Public-URL token checks share authentication ownership
+
+The pre-route public-URL authority check uses the existing locked token
+validator and detached snapshot. Normalisation and last-used metadata updates
+hold the same exclusive configuration ownership as ordinary authentication;
+subsequent scope checks never mutate the live record outside it. Both supported
+token headers retain the existing settings-write requirement. Expired, invalid,
+wrong-role and monitoring-only credentials gain no capture authority. Sessions,
+proxy/basic administration and URL/origin selection are unchanged.
+
+`TestPublicURLTokenCaptureUsesAuthenticationOwnership` covers concurrent capture
+and ordinary authentication, retained scope/identity and successful last-use
+updates; `TestPublicURLTokenCapturePreservesTokenRefusals` pins both headers and
+refused metadata. The real concurrent history HTTP test remains unchanged and
+must pass with the race detector; the observed race is not warmed away or
+suppressed. No new rendered state, token grant or runtime action is introduced.
+
+
### Execution history metadata is typed, not trusted by its key name
A monitoring-read recent-change response projects command and runbook history
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 677e1710f6..b6400ae922 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -21,6 +21,24 @@
## Purpose
+### Public-URL token checks share authentication ownership
+
+The pre-route public-URL authority check uses the existing locked token
+validator and detached snapshot. Normalisation and last-used metadata updates
+hold the same exclusive configuration ownership as ordinary authentication;
+subsequent scope checks never mutate the live record outside it. Both supported
+token headers retain the existing settings-write requirement. Expired, invalid,
+wrong-role and monitoring-only credentials gain no capture authority. Sessions,
+proxy/basic administration and URL/origin selection are unchanged.
+
+`TestPublicURLTokenCaptureUsesAuthenticationOwnership` covers concurrent capture
+and ordinary authentication, retained scope/identity and successful last-use
+updates; `TestPublicURLTokenCapturePreservesTokenRefusals` pins both headers and
+refused metadata. The real concurrent history HTTP test remains unchanged and
+must pass with the race detector; the observed race is not warmed away or
+suppressed. No new rendered state, token grant or runtime action is introduced.
+
+
### Execution history uses a typed read-only projection
The recent-change read keeps kind-specific scalar status facts, not arbitrary
diff --git a/internal/api/router.go b/internal/api/router.go
index 3693dfe91a..45aa37cd9d 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -4978,17 +4978,23 @@ func canCapturePublicURL(cfg *config.Config, req *http.Request) bool {
}
}
- // API Tokens: Require settings:write scope
- if cfg.HasAPITokens() {
- if token := strings.TrimSpace(req.Header.Get("X-API-Token")); token != "" {
- if record, ok := cfg.ValidateAPIToken(token); ok && record.HasScope(config.ScopeSettingsWrite) {
- return true
- }
+ // API Tokens: Require settings:write scope. This pre-route check runs
+ // concurrently with authentication. Metadata normalization and LastUsedAt
+ // need the same exclusive ownership; scope checks use a detached snapshot.
+ tokenAllowsCapture := func(token string) bool {
+ config.Mu.RLock()
+ defer config.Mu.RUnlock()
+ record, ok := validateAPITokenLocked(cfg, token)
+ return ok && record.HasScope(config.ScopeSettingsWrite)
+ }
+ if token := strings.TrimSpace(req.Header.Get("X-API-Token")); token != "" {
+ if tokenAllowsCapture(token) {
+ return true
}
- if authHeader := strings.TrimSpace(req.Header.Get("Authorization")); strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
- if record, ok := cfg.ValidateAPIToken(strings.TrimSpace(authHeader[7:])); ok && record.HasScope(config.ScopeSettingsWrite) {
- return true
- }
+ }
+ if authHeader := strings.TrimSpace(req.Header.Get("Authorization")); strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
+ if tokenAllowsCapture(strings.TrimSpace(authHeader[7:])) {
+ return true
}
}
diff --git a/internal/api/router_helpers_more_test.go b/internal/api/router_helpers_more_test.go
index ed3c3a7a87..84f218cade 100644
--- a/internal/api/router_helpers_more_test.go
+++ b/internal/api/router_helpers_more_test.go
@@ -4,6 +4,8 @@ import (
"context"
"net/http"
"net/http/httptest"
+ "reflect"
+ "sync"
"testing"
"time"
@@ -12,6 +14,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
func TestRouterGetMonitor_Defaults(t *testing.T) {
@@ -474,3 +477,113 @@ func TestStartPatrolForContext_RejectsMismatchedAIServiceOrg(t *testing.T) {
t.Fatal("expected patrol start to fail when AI service org scope mismatches tenant org")
}
}
+
+// Public URL detection runs before the route handler on every request. Its
+// token lookup must share authentication's metadata writer ownership, not
+// mutate a live record concurrently with auth readers or normalize its scopes
+// again after dropping the writer lock.
+func TestPublicURLTokenCaptureUsesAuthenticationOwnership(t *testing.T) {
+ t.Setenv("PULSE_AUTH_BYPASS", "false")
+ cases := []struct {
+ raw string
+ scopes []string
+ want bool
+ }{
+ {"capture-monitoring-fixture.12345678", []string{config.ScopeMonitoringRead}, false},
+ {"capture-settings-fixture.12345678", []string{config.ScopeSettingsWrite}, true},
+ }
+ cfg := &config.Config{}
+ for _, tc := range cases {
+ record, err := config.NewAPITokenRecord(tc.raw, "capture fixture", tc.scopes)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg.APITokens = append(cfg.APITokens, *record)
+ }
+ before := make([]config.APITokenRecord, len(cfg.APITokens))
+ for i := range cfg.APITokens {
+ before[i] = cfg.APITokens[i].Clone()
+ }
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ for _, tc := range cases {
+ for _, header := range []string{"X-API-Token", "Authorization"} {
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ <-start
+ for i := 0; i < 32; i++ {
+ req := httptest.NewRequest(http.MethodGet, "http://localhost/api/agent/changes", nil)
+ value := tc.raw
+ if header == "Authorization" {
+ value = "Bearer " + value
+ }
+ req.Header.Set(header, value)
+ if got := canCapturePublicURL(cfg, req); got != tc.want {
+ t.Errorf("capture permission = %v, want %v", got, tc.want)
+ }
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ <-start
+ for i := 0; i < 32; i++ {
+ req := httptest.NewRequest(http.MethodGet, "/api/agent/changes", nil)
+ req.Header.Set("Authorization", "Bearer "+tc.raw)
+ if !CheckAuth(cfg, httptest.NewRecorder(), req) {
+ t.Error("valid token lost authentication")
+ }
+ }
+ }()
+ }
+ }
+ close(start)
+ wg.Wait()
+ config.Mu.RLock()
+ defer config.Mu.RUnlock()
+ for i, record := range cfg.APITokens {
+ if record.ID != before[i].ID || record.Hash != before[i].Hash || !reflect.DeepEqual(record.Scopes, before[i].Scopes) {
+ t.Fatal("capture changed credential identity or scope")
+ }
+ if record.LastUsedAt == nil {
+ t.Fatal("successful validation lost last-used metadata")
+ }
+ }
+}
+
+func TestPublicURLTokenCapturePreservesTokenRefusals(t *testing.T) {
+ for _, kind := range []string{"expired", "invalid_role", "wrong_token"} {
+ t.Run(kind, func(t *testing.T) {
+ const raw = "capture-refusal-fixture.12345678"
+ record, err := config.NewAPITokenRecord(raw, "capture refusal", []string{config.ScopeSettingsWrite})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if kind == "expired" {
+ expired := time.Now().Add(-time.Hour)
+ record.ExpiresAt = &expired
+ }
+ if kind == "invalid_role" {
+ record.Metadata = map[string]string{auth.RuntimeRoleMetadataKey: auth.RuntimeRoleMonitoringCollector}
+ }
+ cfg := &config.Config{APITokens: []config.APITokenRecord{*record}}
+ for _, header := range []string{"X-API-Token", "Authorization"} {
+ req := httptest.NewRequest(http.MethodGet, "http://localhost/api/agent/changes", nil)
+ value := raw
+ if kind == "wrong_token" {
+ value = "different-fixture-token.12345678"
+ }
+ if header == "Authorization" {
+ value = "Bearer " + value
+ }
+ req.Header.Set(header, value)
+ if canCapturePublicURL(cfg, req) {
+ t.Fatal("rejected credential gained URL capture authority")
+ }
+ }
+ if cfg.APITokens[0].LastUsedAt != nil || !reflect.DeepEqual(cfg.APITokens[0].Scopes, record.Scopes) {
+ t.Fatal("refused capture mutated token metadata")
+ }
+ })
+ }
+}