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.

Stop token callers widening or bypassing their scopes

rcourtman9718555e3194
diff --git a/internal/api/resources_mutation_scope_test.go b/internal/api/resources_mutation_scope_test.go
new file mode 100644
index 0000000000..e3e4371086
--- /dev/null
+++ b/internal/api/resources_mutation_scope_test.go
@@ -0,0 +1,64 @@
+package api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// /api/resources/ is one prefix route. Its POST sub-paths (link, unlink,
+// report-merge) persist resource identity changes, so a read-only token must
+// be refused while reads stay available to it.
+func TestResourceRoutesRequireWriteScopeForMutations(t *testing.T) {
+ const readToken = "resources-read-only-scope.12345678"
+ const writeToken = "resources-write-scope.12345678"
+ cfg := newTestConfigWithTokens(t,
+ newTokenRecord(t, readToken, []string{config.ScopeMonitoringRead}, nil),
+ newTokenRecord(t, writeToken, []string{config.ScopeMonitoringWrite}, nil),
+ )
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ do := func(token, method, path, body string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, path, strings.NewReader(body))
+ req.Header.Set("X-API-Token", token)
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ return rec
+ }
+
+ mutations := []struct{ path, body string }{
+ {"/api/resources/vm-1/link", `{"targetId":"agent-1"}`},
+ {"/api/resources/vm-1/unlink", `{"targetId":"agent-1"}`},
+ {"/api/resources/vm-1/report-merge", `{}`},
+ }
+ for _, m := range mutations {
+ rec := do(readToken, http.MethodPost, m.path, m.body)
+ if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), config.ScopeMonitoringWrite) {
+ t.Errorf("read-only token POST %s = %d %q, want 403 naming %s", m.path, rec.Code, rec.Body.String(), config.ScopeMonitoringWrite)
+ }
+ rec = do(writeToken, http.MethodPost, m.path, m.body)
+ if rec.Code == http.StatusForbidden || rec.Code == http.StatusUnauthorized {
+ t.Errorf("write-scoped token POST %s refused with %d: %s", m.path, rec.Code, rec.Body.String())
+ }
+ }
+
+ // Reads on the same prefix stay available to a read-only token.
+ rec := do(readToken, http.MethodGet, "/api/resources/vm-1", "")
+ if rec.Code == http.StatusForbidden || rec.Code == http.StatusUnauthorized {
+ t.Errorf("read-only token GET refused with %d: %s", rec.Code, rec.Body.String())
+ }
+ // The operator-state registration is more specific than the prefix and
+ // has its own write requirement; this also refuses the read-only token.
+ rec = do(readToken, http.MethodPut, "/api/resources/vm-1/operator-state", `{}`)
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("read-only token PUT operator-state = %d, want 403", rec.Code)
+ }
+ // A write-only token has no read scope, so reads stay refused.
+ rec = do(writeToken, http.MethodGet, "/api/resources/vm-1", "")
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("write-only token GET = %d, want 403", rec.Code)
+ }
+}
diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.go
index 4bc1fcc6ee..118258e09c 100644
--- a/internal/api/router_routes_monitoring.go
+++ b/internal/api/router_routes_monitoring.go
@@ -81,7 +81,19 @@ func (r *Router) registerMonitoringResourceRoutes(
r.mux.HandleFunc("/api/maintenance-verifications/{reportId}", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.maintenanceVerificationHandlers.HandleGet)))
r.mux.HandleFunc("POST /api/maintenance-verifications/{reportId}/review", RequireAuth(r.config, RequireScope(config.ScopeMonitoringWrite, r.maintenanceVerificationHandlers.HandleReview)))
}
- r.mux.HandleFunc("/api/resources/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.resourceHandlers.HandleResourceRoutes)))
+ // HandleResourceRoutes also dispatches POST link, unlink and report-merge,
+ // which persist resource identity changes, so anything other than a read
+ // needs the write scope.
+ r.mux.HandleFunc("/api/resources/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
+ scope := config.ScopeMonitoringRead
+ if req.Method != http.MethodGet && req.Method != http.MethodHead {
+ scope = config.ScopeMonitoringWrite
+ }
+ if !ensureScope(w, req, scope) {
+ return
+ }
+ r.resourceHandlers.HandleResourceRoutes(w, req)
+ }))
// Agent-consumable bundled context — substrate for any LLM agent
// (in-process Patrol/Assistant or external) that needs the full
// situated picture of a resource in one read instead of chaining
diff --git a/internal/api/security_regenerate_token_scope_test.go b/internal/api/security_regenerate_token_scope_test.go
new file mode 100644
index 0000000000..cb13451aad
--- /dev/null
+++ b/internal/api/security_regenerate_token_scope_test.go
@@ -0,0 +1,157 @@
+package api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "sort"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// Regenerating tokens replaces the whole token inventory, wildcard tokens
+// included, and issues a full-access credential. Token creation refuses to
+// grant scopes the caller lacks, so regeneration must not be a way around it:
+// a token caller needs instance-wide full-access authority.
+const regenerateCallerRaw = "regen-scope-token-123.12345678"
+
+func regenerateAs(t *testing.T, caller *config.APITokenRecord, others ...config.APITokenRecord) (*config.Config, *httptest.ResponseRecorder) {
+ t.Helper()
+ dataDir := t.TempDir()
+ cfg := &config.Config{DataPath: dataDir, ConfigPath: dataDir}
+ if caller != nil {
+ cfg.APITokens = append([]config.APITokenRecord{*caller}, others...)
+ cfg.SortAPITokens()
+ }
+ router := &Router{config: cfg, persistence: config.NewConfigPersistence(cfg.DataPath)}
+
+ authLimiter.Reset("127.0.0.1")
+ req := newLoopbackRequest(http.MethodPost, "/api/security/regenerate-token", nil)
+ if caller != nil {
+ req.Header.Set("X-API-Token", regenerateCallerRaw)
+ }
+ rec := httptest.NewRecorder()
+ router.HandleRegenerateAPIToken(rec, req)
+ return cfg, rec
+}
+
+func newRegenerateCaller(t *testing.T, scopes []string, orgID string) *config.APITokenRecord {
+ t.Helper()
+ record, err := config.NewAPITokenRecord(regenerateCallerRaw, "caller", scopes)
+ if err != nil {
+ t.Fatalf("new caller token record: %v", err)
+ }
+ if orgID != "" {
+ record.OrgID = orgID
+ }
+ return record
+}
+
+func assertInventoryUntouched(t *testing.T, cfg *config.Config, wantIDs ...string) {
+ t.Helper()
+ got := make([]string, 0, len(cfg.APITokens))
+ for _, record := range cfg.APITokens {
+ got = append(got, record.ID)
+ }
+ sort.Strings(got)
+ want := append([]string(nil), wantIDs...)
+ sort.Strings(want)
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("token inventory changed: got %v, want %v", got, wantIDs)
+ }
+}
+
+func TestHandleRegenerateAPITokenRefusesScopedTokenCaller(t *testing.T) {
+ caller := newRegenerateCaller(t, []string{config.ScopeSettingsWrite}, "")
+ wildcard, err := config.NewAPITokenRecord("other-wildcard-token.12345678", "other", []string{config.ScopeWildcard})
+ if err != nil {
+ t.Fatalf("new wildcard record: %v", err)
+ }
+
+ cfg, rec := regenerateAs(t, caller, *wildcard)
+
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d (%s)", rec.Code, http.StatusForbidden, rec.Body.String())
+ }
+ // Nothing was replaced: the scoped caller cannot wipe a wildcard token.
+ assertInventoryUntouched(t, cfg, caller.ID, wildcard.ID)
+}
+
+func TestHandleRegenerateAPITokenRefusesOrganizationBoundWildcardCaller(t *testing.T) {
+ caller := newRegenerateCaller(t, []string{config.ScopeWildcard}, "org-a")
+
+ cfg, rec := regenerateAs(t, caller)
+
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d (%s)", rec.Code, http.StatusForbidden, rec.Body.String())
+ }
+ assertInventoryUntouched(t, cfg, caller.ID)
+}
+
+func TestTokenHasInstanceWideAuthority(t *testing.T) {
+ wildcard := []string{config.ScopeWildcard}
+ cases := []struct {
+ name string
+ scopes []string
+ orgID string
+ orgIDs []string
+ want bool
+ }{
+ {"full access, default org", wildcard, "default", nil, true},
+ {"full access, unbound", wildcard, "", nil, true},
+ {"full access, default-only org list", wildcard, "", []string{"default"}, true},
+ {"org list takes precedence over a stale org id", wildcard, "org-a", []string{"default"}, true},
+ {"full access, other org", wildcard, "org-a", nil, false},
+ {"full access, other org list", wildcard, "default", []string{"org-a"}, false},
+ {"full access, default plus other org", wildcard, "", []string{"default", "org-a"}, false},
+ {"scoped, default org", []string{config.ScopeSettingsWrite}, "default", nil, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ record, err := config.NewAPITokenRecord("instance-wide-"+tc.name+".12345678", tc.name, tc.scopes)
+ if err != nil {
+ t.Fatalf("new token record: %v", err)
+ }
+ record.OrgID = tc.orgID
+ record.OrgIDs = tc.orgIDs
+ if got := tokenHasInstanceWideAuthority(record); got != tc.want {
+ t.Fatalf("tokenHasInstanceWideAuthority = %v, want %v", got, tc.want)
+ }
+ })
+ }
+ if tokenHasInstanceWideAuthority(nil) {
+ t.Fatal("a nil record must not have instance-wide authority")
+ }
+}
+
+func TestHandleRegenerateAPITokenAllowsInstanceWideWildcardCaller(t *testing.T) {
+ caller := newRegenerateCaller(t, []string{config.ScopeWildcard}, "")
+ other, err := config.NewAPITokenRecord("other-scoped-token.12345678", "other", []string{config.ScopeMonitoringRead})
+ if err != nil {
+ t.Fatalf("new scoped record: %v", err)
+ }
+
+ cfg, rec := regenerateAs(t, caller, *other)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d (%s)", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ if len(cfg.APITokens) != 1 {
+ t.Fatalf("regeneration should leave exactly one token, got %d", len(cfg.APITokens))
+ }
+ if !reflect.DeepEqual(cfg.APITokens[0].Scopes, []string{config.ScopeWildcard}) {
+ t.Fatalf("regenerated scopes = %v, want full access", cfg.APITokens[0].Scopes)
+ }
+}
+
+func TestHandleRegenerateAPITokenWithoutCallerTokenStillIssuesFullAccess(t *testing.T) {
+ cfg, rec := regenerateAs(t, nil)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d (%s)", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ if len(cfg.APITokens) != 1 || !reflect.DeepEqual(cfg.APITokens[0].Scopes, []string{config.ScopeWildcard}) {
+ t.Fatalf("a caller without a token should still receive a full-access token: %+v", cfg.APITokens)
+ }
+}
diff --git a/internal/api/security_setup_fix.go b/internal/api/security_setup_fix.go
index 131b5cc4b2..e0517b1247 100644
--- a/internal/api/security_setup_fix.go
+++ b/internal/api/security_setup_fix.go
@@ -679,6 +679,28 @@ func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {
}
}
+// tokenHasInstanceWideAuthority reports whether a token holds full-access scope
+// and is not bound to any organization other than the default one. OrgIDs
+// takes precedence over OrgID, as it does for tenant access checks.
+func tokenHasInstanceWideAuthority(record *config.APITokenRecord) bool {
+ if record == nil || !record.HasScope(config.ScopeWildcard) {
+ return false
+ }
+ isDefault := func(orgID string) bool {
+ orgID = strings.TrimSpace(orgID)
+ return orgID == "" || orgID == "default"
+ }
+ if len(record.OrgIDs) > 0 {
+ for _, orgID := range record.OrgIDs {
+ if !isDefault(orgID) {
+ return false
+ }
+ }
+ return true
+ }
+ return isDefault(record.OrgID)
+}
+
// HandleRegenerateAPIToken generates and persists a new API token.
func (r *Router) HandleRegenerateAPIToken(w http.ResponseWriter, rq *http.Request) {
if rq.Method != http.MethodPost {
@@ -706,6 +728,19 @@ func (r *Router) HandleRegenerateAPIToken(w http.ResponseWriter, rq *http.Reques
return
}
+ // Regeneration replaces the whole token inventory, wildcard tokens
+ // included, and issues a full-access credential. A token caller therefore
+ // needs instance-wide full-access authority; a scoped or organization-bound
+ // token replaces just itself through /api/security/tokens/{id}/rotate.
+ if callerToken := getAPITokenRecordFromRequest(rq); callerToken != nil && !tokenHasInstanceWideAuthority(callerToken) {
+ log.Warn().
+ Str("token_id", callerToken.ID).
+ Str("ip", GetClientIP(rq)).
+ Msg("API token without instance-wide authority attempted to regenerate every token")
+ http.Error(w, "Regenerating API tokens replaces every token, so it needs a full-access token that is not bound to any non-default organization. Use POST /api/security/tokens/{id}/rotate to replace one token.", http.StatusForbidden)
+ return
+ }
+
// Apply rate limiting to prevent abuse
clientIP := GetClientIP(rq)
if !authLimiter.Allow(clientIP) {
diff --git a/internal/api/security_setup_fix_additional_test.go b/internal/api/security_setup_fix_additional_test.go
index 0eaf450f3a..d95d571d4a 100644
--- a/internal/api/security_setup_fix_additional_test.go
+++ b/internal/api/security_setup_fix_additional_test.go
@@ -106,7 +106,7 @@ func TestHandleRegenerateAPIToken_DoesNotRequireEnvFile(t *testing.T) {
func TestHandleRegenerateAPITokenInheritsOwnerFromCallerToken(t *testing.T) {
dataDir := t.TempDir()
rawCallerToken := "regen-owner-token-123.12345678"
- callerRecord, err := config.NewAPITokenRecord(rawCallerToken, "admin-token", []string{config.ScopeSettingsWrite})
+ callerRecord, err := config.NewAPITokenRecord(rawCallerToken, "admin-token", []string{config.ScopeWildcard})
if err != nil {
t.Fatalf("new caller token record: %v", err)
}
@@ -147,7 +147,7 @@ func TestHandleRegenerateAPITokenInheritsOwnerFromCallerToken(t *testing.T) {
func TestHandleRegenerateAPITokenRollsBackWhenPersistenceFails(t *testing.T) {
dataDir := filepath.Join(t.TempDir(), "state")
rawCallerToken := "regen-persistence-token-123.12345678"
- callerRecord, err := config.NewAPITokenRecord(rawCallerToken, "existing-admin-token", []string{config.ScopeSettingsWrite})
+ callerRecord, err := config.NewAPITokenRecord(rawCallerToken, "existing-admin-token", []string{config.ScopeWildcard})
if err != nil {
t.Fatalf("new caller token record: %v", err)
}