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.

Enforce collector credential scope allowlists

Richard Courtman34849268e586
diff --git a/docs/AGENT_SECURITY.md b/docs/AGENT_SECURITY.md
index a1cd323d35..45288f7457 100644
--- a/docs/AGENT_SECURITY.md
+++ b/docs/AGENT_SECURITY.md
@@ -235,6 +235,10 @@ show whether the collector credential is known and execution-scoped, whether
a host-bound runner credential is active, and whether a compatible
`action-runner` / `typed_actions.v1` session is actually connected. Missing
evidence remains unknown; collector health never proves remediation readiness.
+Role-marked monitoring credentials are also checked against the complete
+collector allowlist: `agent:report` and `agent:config:read` are mandatory, while
+`docker:report` and `kubernetes:report` are the only optional provider scopes.
+Any other scope is a critical credential-authority diagnostic.
Runner enrollment is one host at a time. The issuance request must resolve to
exactly one non-conflicted monitored agent ID and normalized hostname in the
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index d1ad006c64..b7d896a277 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -50,12 +50,17 @@ the fail-closed behavior, residual owner, and concrete removal condition.
Implemented or mocked behavior is never promoted to live-provider
qualification, and the safe profile cannot become the general default while a
matrix row required by that default remains unqualified.
-Safe-profile collector credentials carry only `agent:report` and the
-host-bound `agent:config:read` capability; they carry neither `agent:exec` nor
-the broader `agent:manage` scope. Migration to that profile must durably remove
-both scopes from the exact collector token before local privilege separation,
-close only the matching live collector session, and fail closed if persistence
-does not complete. Once the remote authority reduction succeeds, every local
+Safe-profile collector credentials always carry `agent:report` and the
+host-bound `agent:config:read` capability. Host collectors may additionally
+carry only the provider-report capabilities they actively need:
+`docker:report` and `kubernetes:report`. No collector credential may carry
+`agent:exec`, `agent:manage`, an operator scope, an action scope, wildcard, or
+any future scope until that scope is deliberately added to this allowlist.
+Issuance, persisted-token loading, request admission, and Agent Doctor consume
+the same role policy. Migration to that profile must durably reduce the exact
+collector token to this allowlist before local privilege separation, close
+only the matching live collector session, and fail closed if persistence does
+not complete. Once the remote authority reduction succeeds, every local
rollback path must retain a monitoring-only collector service rather than
restoring `--enable-commands` or otherwise recreating command authority.
When that helper socket is configured, collector startup must complete a
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 088c5e013d..bdf8e351c5 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -198,9 +198,14 @@ TLS for the installer download and passes `--insecure` to the agent; omission
or false preserves certificate verification. The server, not the browser,
continues to mint and quote the enrollment token.
Install-command credentials are monitoring-only unless the request explicitly
-selects command execution. Monitoring credentials carry report and config-read
-scope without `agent:exec` or `agent:manage`; explicit command-capable
-credentials add `agent:exec` only. Hosted PVE, PBS, and PMG commands do not
+selects command execution. Monitoring credentials require `agent:report` and
+`agent:config:read`; host collectors may additionally carry only
+`docker:report` and `kubernetes:report`. They carry no wildcard, operator,
+action, `agent:exec`, or `agent:manage` authority. Issuance and admission reject
+any role-marked credential outside that exact allowlist, while persisted-load
+migration durably removes historical excess authority before admitting the
+inventory. Explicit command-capable credentials add `agent:exec` only. Hosted
+PVE, PBS, and PMG commands do not
infer execution authority from the target platform. Agent Doctor exposes the
local command-authority profile and the server-derived credential execution
scope as separate fields, and reports an over-scoped monitoring credential
@@ -208,10 +213,11 @@ rather than hiding it behind the current command-enabled boolean.
`POST /api/agents/collector/reduce-authority` is the authenticated, idempotent
safe-profile migration boundary. Its JSON body identifies the caller's agent
and canonical hostname; both must match the attached report credential and its
-organization. The transition rejects wildcard credentials, removes
-`agent:exec` and `agent:manage` from that exact token, persists before success,
-restores the full token inventory on persistence failure, and invalidates only
-the exact matching collector session after persistence.
+organization. The transition rejects credentials missing the mandatory
+collector baseline, removes every scope outside the exact collector allowlist
+from that token, persists before success, restores the full token inventory on
+persistence failure, and invalidates only the exact matching collector session
+after persistence.
## Canonical Files
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index f97a78705e..3f645d35da 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -38,6 +38,12 @@ command-capable runtime whose monitoring credential cannot re-enable commands
is a scope-mismatch warning; an actively command-enabled runtime without
`agent:exec` remains critical. These facts do not change collection truth or
make a least-privilege service unhealthy by themselves.
+For a credential explicitly marked `monitoring-collector`, Doctor also compares
+the complete scope set against the canonical role allowlist. Any wildcard,
+operator, action, management, execution, or unknown scope is surfaced as the
+critical `agent_credential_scope_excess` reason with only the unexpected scope
+names as evidence; a current heartbeat never hides that server-side authority
+violation.
Action-runner posture is a server-side join, not collector-reported monitoring
truth. The collector may report only that its typed local helper is configured;
Agent Doctor separately overlays the current tenant's host-bound runner-token
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 4d6902bc4a..cb1c13670b 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -7193,6 +7193,7 @@
"pkg/audit/async_logger.go",
"pkg/audit/audit.go",
"pkg/audit/sqlite_logger.go",
+ "pkg/auth/agent_credentials.go",
"pkg/auth/rbac.go",
"pkg/auth/rbac_manager.go",
"pkg/auth/sqlite_manager.go",
@@ -7441,6 +7442,24 @@
"internal/api/system_settings_telemetry_test.go"
]
},
+ {
+ "id": "agent-credential-role-authority",
+ "label": "agent credential role authority proof",
+ "match_prefixes": [],
+ "match_files": [
+ "pkg/auth/agent_credentials.go"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "internal/api/agenttokens/install_test.go",
+ "internal/api/collector_authority_test.go",
+ "internal/config/api_token_migration_atomic_test.go",
+ "internal/config/api_tokens_additional_test.go",
+ "internal/monitoring/agent_fleet_doctor_test.go",
+ "pkg/auth/agent_credentials_test.go"
+ ]
+ },
{
"id": "rbac-runtime-persistence",
"label": "RBAC runtime persistence and upgrade proof",
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index eaa5943d3e..28d0a6d892 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -29,9 +29,14 @@ state; `TestConfigWatcher_ReloadAPITokensDoesNotOverwriteConcurrentMutation`
is the required concurrency proof.
Pulse-minted Unified Agent credentials follow least authority at issuance.
-Implicit and ordinary monitoring installs receive `agent:report` and
-`agent:config:read`, never `agent:exec` or `agent:manage`. Execution scope is
-added only for an explicit command-capable installer choice. Local runtime
+Implicit and ordinary monitoring installs require `agent:report` and
+`agent:config:read`; host collectors may additionally receive only
+`docker:report` and `kubernetes:report`. The role policy denies wildcard,
+operator, action, `agent:exec`, `agent:manage`, and unknown future scopes.
+Issuance and runtime admission reject non-canonical role credentials;
+persisted-token loading durably subtracts historical excess scopes and rejects
+a credential missing its mandatory baseline. Execution scope is added only for
+an explicit command-capable installer choice. Local runtime
authority remains an independent ceiling: a credential with `agent:exec`
cannot promote a service installed as `monitoring-only`, and Agent Doctor must
warn when such excess scope remains attached to that runtime.
@@ -212,10 +217,11 @@ invisible to operators reviewing exactly what Pulse sends.
48. `frontend-modern/src/components/Settings/dataHandlingPanelModel.ts`
49. `internal/api/agent_exec_token_binding.go`
50. `internal/logging/logging.go`
-51. `pkg/auth/rbac.go`
-52. `pkg/auth/rbac_manager.go`
-53. `pkg/auth/sqlite_manager.go`
-54. `pkg/server/server.go`
+51. `pkg/auth/agent_credentials.go`
+52. `pkg/auth/rbac.go`
+53. `pkg/auth/rbac_manager.go`
+54. `pkg/auth/sqlite_manager.go`
+55. `pkg/server/server.go`
## Shared Boundaries
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 5b29871080..8e6517732b 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -293,6 +293,13 @@ recovery-point loss, restore readiness, datastore health, or provider
identity. Token inventory that is unavailable or deliberately synthetic stays
unknown rather than fabricating storage or agent incidents.
+Collector role-scope enforcement under `internal/api/agenttokens/`,
+`internal/api/collector_authority.go`, `internal/config/`, and `pkg/auth/` is
+likewise an authentication boundary, not storage or recovery evidence. Its
+exact monitoring allowlist and durable excess-scope reduction must not be
+reinterpreted as backup coverage, restore authority, protection health, or
+permission to broaden provider credentials.
+
Docker / Podman report ingress under `internal/api/docker_agents.go` is outside
storage/recovery ownership even though storage/recovery routes share the broad
`internal/api/` extension boundary. Encoded/decoded report ceilings,
diff --git a/frontend-modern/public/docs/AGENT_SECURITY.md b/frontend-modern/public/docs/AGENT_SECURITY.md
index a1cd323d35..45288f7457 100644
--- a/frontend-modern/public/docs/AGENT_SECURITY.md
+++ b/frontend-modern/public/docs/AGENT_SECURITY.md
@@ -235,6 +235,10 @@ show whether the collector credential is known and execution-scoped, whether
a host-bound runner credential is active, and whether a compatible
`action-runner` / `typed_actions.v1` session is actually connected. Missing
evidence remains unknown; collector health never proves remediation readiness.
+Role-marked monitoring credentials are also checked against the complete
+collector allowlist: `agent:report` and `agent:config:read` are mandatory, while
+`docker:report` and `kubernetes:report` are the only optional provider scopes.
+Any other scope is a critical credential-authority diagnostic.
Runner enrollment is one host at a time. The issuance request must resolve to
exactly one non-conflicted monitored agent ID and normalized hostname in the
diff --git a/internal/api/agenttokens/install.go b/internal/api/agenttokens/install.go
index 753bc4c1fc..e3d27adcc9 100644
--- a/internal/api/agenttokens/install.go
+++ b/internal/api/agenttokens/install.go
@@ -19,11 +19,11 @@ const (
CommandPolicyAppliedAgentIDMetadataKey = "command_policy_applied_agent_id"
CommandPolicyIntentEnabled = "enabled"
CommandPolicyIntentDisabled = "disabled"
- RuntimeRoleMetadataKey = "runtime_role"
+ RuntimeRoleMetadataKey = internalauth.RuntimeRoleMetadataKey
CredentialKindMetadataKey = RuntimeRoleMetadataKey
- CredentialKindMonitoringCollector = "monitoring-collector"
- CredentialKindActionRunner = "action-runner"
- CredentialKindLegacyFullTrust = "legacy-full-trust"
+ CredentialKindMonitoringCollector = internalauth.RuntimeRoleMonitoringCollector
+ CredentialKindActionRunner = internalauth.RuntimeRoleActionRunner
+ CredentialKindLegacyFullTrust = internalauth.RuntimeRoleLegacyFullTrust
ActionCapabilityMetadataKey = "agent_action_capability"
ActionCapabilityTypedV1 = "typed_actions.v1"
ActionBindingVersionMetadataKey = "action_runner_binding_version"
@@ -256,22 +256,24 @@ func normalizeCredentialKind(record *config.APITokenRecord) error {
}
kind := strings.TrimSpace(record.Metadata[CredentialKindMetadataKey])
hasExec := record.HasScope(config.ScopeAgentExec)
- switch kind {
- case "":
+ if kind == "" {
if hasExec {
// Existing combined collector/command issuance remains available only
// as an explicit compatibility class while deployments migrate.
- record.Metadata[CredentialKindMetadataKey] = CredentialKindLegacyFullTrust
+ kind = CredentialKindLegacyFullTrust
} else {
- record.Metadata[CredentialKindMetadataKey] = CredentialKindMonitoringCollector
+ kind = CredentialKindMonitoringCollector
}
+ record.Metadata[CredentialKindMetadataKey] = kind
+ }
+ switch kind {
case CredentialKindMonitoringCollector:
- if hasExec {
- return errors.New("monitoring collector credential cannot carry agent:exec")
+ if err := internalauth.ValidateRoleScopes(kind, record.Scopes); err != nil {
+ return err
}
case CredentialKindActionRunner:
- if !hasExec {
- return errors.New("action runner credential requires agent:exec")
+ if err := internalauth.ValidateRoleScopes(kind, record.Scopes); err != nil {
+ return err
}
if strings.TrimSpace(record.Metadata[ActionCapabilityMetadataKey]) != ActionCapabilityTypedV1 {
return errors.New("action runner credential requires the typed action capability")
diff --git a/internal/api/agenttokens/install_test.go b/internal/api/agenttokens/install_test.go
index a691ddc7f7..028ddbc171 100644
--- a/internal/api/agenttokens/install_test.go
+++ b/internal/api/agenttokens/install_test.go
@@ -189,6 +189,32 @@ func TestIssueAndPersistRejectsMonitoringRoleWithExecAuthority(t *testing.T) {
}
}
+func TestIssueAndPersistRejectsMonitoringRoleWithUnrelatedAuthority(t *testing.T) {
+ for _, scopes := range [][]string{
+ {config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeSettingsWrite},
+ {config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeActionsExecute},
+ } {
+ _, _, err := IssueAndPersist(&config.Config{}, nil, IssueOptions{
+ TokenName: "invalid",
+ Scopes: scopes,
+ Metadata: map[string]string{RuntimeRoleMetadataKey: CredentialKindMonitoringCollector},
+ })
+ if !errors.Is(err, ErrRecord) {
+ t.Fatalf("monitoring role with scopes %v error = %v, want ErrRecord", scopes, err)
+ }
+ }
+}
+
+func TestIssueAndPersistRejectsInferredMonitoringRoleWithUnrelatedAuthority(t *testing.T) {
+ _, _, err := IssueAndPersist(&config.Config{}, nil, IssueOptions{
+ TokenName: "invalid inferred collector",
+ Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeSettingsWrite},
+ })
+ if !errors.Is(err, ErrRecord) {
+ t.Fatalf("inferred monitoring role with unrelated authority error = %v, want ErrRecord", err)
+ }
+}
+
func TestProxmoxScopesRequireExplicitCommandAuthority(t *testing.T) {
monitoringScopes := ProxmoxScopes(false)
if (&config.APITokenRecord{Scopes: monitoringScopes}).HasScope(config.ScopeAgentExec) {
diff --git a/internal/api/collector_authority.go b/internal/api/collector_authority.go
index cfa0fcd48a..bc61abc740 100644
--- a/internal/api/collector_authority.go
+++ b/internal/api/collector_authority.go
@@ -10,6 +10,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/api/agenttokens"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
const maxCollectorAuthorityRequestBytes int64 = 16 << 10
@@ -89,24 +90,14 @@ func (r *Router) handleReduceCollectorAuthority(w http.ResponseWriter, req *http
return
}
record := &r.config.APITokens[index]
- nextScopes := make([]string, 0, len(record.Scopes))
- for _, scope := range record.Scopes {
- if scope == config.ScopeWildcard {
- config.Mu.Unlock()
- http.Error(w, "Wildcard credentials cannot be reduced through the collector route", http.StatusForbidden)
- return
- }
- if scope != config.ScopeAgentExec && scope != config.ScopeAgentManage {
- nextScopes = append(nextScopes, scope)
- }
- }
- record.Scopes = nextScopes
- if record.HasScope(config.ScopeAgentExec) || !record.HasScope(config.ScopeAgentReport) {
+ nextScopes, _, err := internalauth.CanonicalizeRoleScopes(internalauth.RuntimeRoleMonitoringCollector, record.Scopes)
+ if err != nil {
r.config.APITokens = previous
config.Mu.Unlock()
http.Error(w, "Collector credential scopes cannot be reduced safely", http.StatusForbidden)
return
}
+ record.Scopes = nextScopes
if record.Metadata == nil {
record.Metadata = make(map[string]string)
}
@@ -130,6 +121,6 @@ func (r *Router) handleReduceCollectorAuthority(w http.ResponseWriter, req *http
RuntimeRole: agentexec.RuntimeRoleLegacyFullTrust,
})
}
- LogAuditEventForTenant(organizationID, "collector_authority_reduced", caller.Name, GetClientIP(req), req.URL.Path, true, "Removed execution and cross-host management scopes from collector credential")
+ LogAuditEventForTenant(organizationID, "collector_authority_reduced", caller.Name, GetClientIP(req), req.URL.Path, true, "Reduced collector credential to its exact monitoring scope allowlist")
w.WriteHeader(http.StatusNoContent)
}
diff --git a/internal/api/collector_authority_test.go b/internal/api/collector_authority_test.go
index 4c55e190ac..fa331ca9a0 100644
--- a/internal/api/collector_authority_test.go
+++ b/internal/api/collector_authority_test.go
@@ -15,7 +15,8 @@ import (
func TestReduceCollectorAuthorityRemovesExecutionScopeIrreversibly(t *testing.T) {
raw := "collector-authority-test.12345678"
record, err := config.NewAPITokenRecord(raw, "legacy collector", []string{
- config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentManage, config.ScopeAgentExec,
+ config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeDockerReport, config.ScopeKubernetesReport,
+ config.ScopeAgentManage, config.ScopeAgentExec, config.ScopeSettingsWrite, config.ScopeActionsExecute,
})
if err != nil {
t.Fatal(err)
@@ -42,6 +43,12 @@ func TestReduceCollectorAuthorityRemovesExecutionScopeIrreversibly(t *testing.T)
if cfg.APITokens[0].HasScope(config.ScopeAgentManage) {
t.Fatalf("reduced collector retained cross-host management scope: %v", cfg.APITokens[0].Scopes)
}
+ if cfg.APITokens[0].HasScope(config.ScopeSettingsWrite) || cfg.APITokens[0].HasScope(config.ScopeActionsExecute) {
+ t.Fatalf("reduced collector retained unrelated authority: %v", cfg.APITokens[0].Scopes)
+ }
+ if !cfg.APITokens[0].HasScope(config.ScopeDockerReport) || !cfg.APITokens[0].HasScope(config.ScopeKubernetesReport) {
+ t.Fatalf("reduced host collector lost provider reporting authority: %v", cfg.APITokens[0].Scopes)
+ }
if got := cfg.APITokens[0].Metadata[agenttokens.RuntimeRoleMetadataKey]; got != agenttokens.CredentialKindMonitoringCollector {
t.Fatalf("runtime role = %q", got)
}
@@ -84,7 +91,7 @@ func TestReduceCollectorAuthorityRejectsUnboundCredential(t *testing.T) {
func TestReduceCollectorAuthorityRollsBackMemoryWhenPersistenceFails(t *testing.T) {
raw := "collector-authority-persistence.12345678"
- record, err := config.NewAPITokenRecord(raw, "legacy collector", []string{config.ScopeAgentReport, config.ScopeAgentExec})
+ record, err := config.NewAPITokenRecord(raw, "legacy collector", []string{config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeAgentExec})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 7dd8bb1604..d65a5bcd27 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -93,6 +93,31 @@ func TestContractProxmoxInstallScopesRequireExplicitCommandChoice(t *testing.T)
}
}
+func TestContractCollectorCredentialUsesClosedScopeAllowlist(t *testing.T) {
+ allowed := []string{
+ config.ScopeAgentReport,
+ config.ScopeAgentConfigRead,
+ config.ScopeDockerReport,
+ config.ScopeKubernetesReport,
+ }
+ if err := authpkg.ValidateRoleScopes(authpkg.RuntimeRoleMonitoringCollector, allowed); err != nil {
+ t.Fatalf("canonical host collector scopes rejected: %v", err)
+ }
+
+ for _, excess := range []string{
+ config.ScopeWildcard,
+ config.ScopeAgentExec,
+ config.ScopeAgentManage,
+ config.ScopeSettingsWrite,
+ config.ScopeActionsExecute,
+ } {
+ scopes := append(append([]string(nil), allowed...), excess)
+ if err := authpkg.ValidateRoleScopes(authpkg.RuntimeRoleMonitoringCollector, scopes); err == nil {
+ t.Fatalf("collector role admitted excess scope %q: %v", excess, scopes)
+ }
+ }
+}
+
func TestContractPatrolInternalBridgePreservesBoundedToolAuthority(t *testing.T) {
allowed := []string{
agentcapabilities.PatrolGetFindingsToolName,
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 807ce89caa..00561deade 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -47,6 +47,26 @@ func TestSecurityImplicitAgentCredentialOmitsExecutionScope(t *testing.T) {
}
}
+func TestSecurityRejectsCollectorRoleWithNonMonitoringScope(t *testing.T) {
+ rawToken := "security-over-scoped-collector.12345678"
+ record, err := config.NewAPITokenRecord(rawToken, "collector", []string{
+ config.ScopeAgentReport,
+ config.ScopeAgentConfigRead,
+ config.ScopeSettingsWrite,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ record.Metadata = map[string]string{
+ auth.RuntimeRoleMetadataKey: auth.RuntimeRoleMonitoringCollector,
+ }
+ cfg := &config.Config{APITokens: []config.APITokenRecord{*record}}
+
+ if admitted, ok := cfg.ValidateAPIToken(rawToken); ok || admitted != nil {
+ t.Fatalf("over-scoped collector authenticated: %#v", admitted)
+ }
+}
+
func TestSecurityGenericExecTokenCannotApplyInstallCommandPolicy(t *testing.T) {
token := config.APITokenRecord{
ID: "generic-exec-token",
diff --git a/internal/config/api_token_migration_atomic_test.go b/internal/config/api_token_migration_atomic_test.go
index 4db83a9a16..56d525e1cd 100644
--- a/internal/config/api_token_migration_atomic_test.go
+++ b/internal/config/api_token_migration_atomic_test.go
@@ -9,6 +9,7 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/stretchr/testify/require"
)
@@ -25,6 +26,70 @@ func writeLegacyEncryptedAPITokens(t *testing.T, persistence *ConfigPersistence,
return data
}
+func TestLoadAPITokensDurablyReducesRoleScopeExcess(t *testing.T) {
+ persistence := NewConfigPersistence(t.TempDir())
+ writeLegacyEncryptedAPITokens(t, persistence, []APITokenRecord{{
+ ID: "collector-token",
+ Name: "collector",
+ Hash: "collector-hash",
+ CreatedAt: time.Now().UTC(),
+ Scopes: []string{
+ ScopeSettingsWrite,
+ ScopeAgentReport,
+ ScopeAgentConfigRead,
+ ScopeDockerReport,
+ ScopeActionsExecute,
+ },
+ OrgID: "default",
+ Metadata: map[string]string{
+ auth.RuntimeRoleMetadataKey: auth.RuntimeRoleMonitoringCollector,
+ },
+ }})
+
+ loaded, err := persistence.LoadAPITokens()
+ require.NoError(t, err)
+ require.Equal(t, []string{ScopeAgentReport, ScopeAgentConfigRead, ScopeDockerReport}, loaded[0].Scopes)
+
+ reloaded, err := persistence.LoadAPITokens()
+ require.NoError(t, err)
+ require.Equal(t, loaded[0].Scopes, reloaded[0].Scopes)
+}
+
+func TestLoadAPITokensRejectsRoleMissingMandatoryScope(t *testing.T) {
+ persistence := NewConfigPersistence(t.TempDir())
+ writeLegacyEncryptedAPITokens(t, persistence, []APITokenRecord{{
+ ID: "collector-token",
+ Name: "collector",
+ Hash: "collector-hash",
+ CreatedAt: time.Now().UTC(),
+ Scopes: []string{ScopeAgentReport},
+ OrgID: "default",
+ Metadata: map[string]string{
+ auth.RuntimeRoleMetadataKey: auth.RuntimeRoleMonitoringCollector,
+ },
+ }})
+
+ loaded, err := persistence.LoadAPITokens()
+ require.ErrorContains(t, err, ScopeAgentConfigRead)
+ require.Nil(t, loaded)
+}
+
+func TestSaveAPITokensRejectsNonCanonicalRoleAuthority(t *testing.T) {
+ persistence := NewConfigPersistence(t.TempDir())
+ err := persistence.SaveAPITokens([]APITokenRecord{{
+ ID: "collector-token",
+ Name: "collector",
+ Hash: "collector-hash",
+ CreatedAt: time.Now().UTC(),
+ Scopes: []string{ScopeAgentReport, ScopeAgentConfigRead, ScopeSettingsWrite},
+ OrgID: "default",
+ Metadata: map[string]string{
+ auth.RuntimeRoleMetadataKey: auth.RuntimeRoleMonitoringCollector,
+ },
+ }})
+ require.ErrorContains(t, err, "non-canonical scopes")
+}
+
func TestLoadAPITokensPersistsCanonicalAuthorizationStateBeforeReturning(t *testing.T) {
persistence := NewConfigPersistence(t.TempDir())
createdAt := time.Now().UTC().Add(-time.Hour)
diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.go
index 27dc454330..cc3c57e835 100644
--- a/internal/config/api_tokens.go
+++ b/internal/config/api_tokens.go
@@ -2,6 +2,7 @@ package config
import (
"errors"
+ "fmt"
"slices"
"sort"
"strings"
@@ -244,20 +245,21 @@ func bindMissingAPITokenIDs(tokens []APITokenRecord) int {
}
type apiTokenMigrationSummary struct {
- missingIDs int
- legacyScopes int
- legacyOrgBindings int
+ missingIDs int
+ legacyScopes int
+ legacyOrgBindings int
+ roleScopeReductions int
}
func (s apiTokenMigrationSummary) changed() bool {
- return s.missingIDs > 0 || s.legacyScopes > 0 || s.legacyOrgBindings > 0
+ return s.missingIDs > 0 || s.legacyScopes > 0 || s.legacyOrgBindings > 0 || s.roleScopeReductions > 0
}
// canonicalizeAPITokens applies every migration required before token records
// are safe to admit to live configuration. Callers must persist the resulting
// inventory successfully before using it: IDs are revocation handles, scopes
// are authorization state, and organization bindings constrain tenancy.
-func canonicalizeAPITokens(tokens []APITokenRecord) apiTokenMigrationSummary {
+func canonicalizeAPITokens(tokens []APITokenRecord) (apiTokenMigrationSummary, error) {
summary := apiTokenMigrationSummary{
missingIDs: bindMissingAPITokenIDs(tokens),
legacyOrgBindings: bindLegacyAPITokensToDefault(tokens),
@@ -268,8 +270,17 @@ func canonicalizeAPITokens(tokens []APITokenRecord) apiTokenMigrationSummary {
summary.legacyScopes++
}
tokens[i].Scopes = normalizedScopes
+ role := strings.TrimSpace(tokens[i].Metadata[auth.RuntimeRoleMetadataKey])
+ canonicalScopes, changed, err := auth.CanonicalizeRoleScopes(role, tokens[i].Scopes)
+ if err != nil {
+ return summary, fmt.Errorf("token %q has invalid %s authority: %w", tokens[i].ID, role, err)
+ }
+ if changed {
+ tokens[i].Scopes = canonicalScopes
+ summary.roleScopeReductions++
+ }
}
- return summary
+ return summary, nil
}
// tokenPrefix returns the first six characters suitable for hints.
@@ -354,9 +365,13 @@ func (c *Config) ValidateAPIToken(rawToken string) (*APITokenRecord, bool) {
return nil, false
}
c.APITokens[idx].ensureID()
+ c.APITokens[idx].ensureScopes()
+ role := strings.TrimSpace(c.APITokens[idx].Metadata[auth.RuntimeRoleMetadataKey])
+ if err := auth.ValidateRoleScopes(role, c.APITokens[idx].Scopes); err != nil {
+ return nil, false
+ }
now := time.Now().UTC()
c.APITokens[idx].LastUsedAt = &now
- c.APITokens[idx].ensureScopes()
return &c.APITokens[idx], true
}
}
@@ -376,6 +391,11 @@ func (c *Config) IsValidAPIToken(rawToken string) bool {
if record.IsExpired() {
return false
}
+ record.ensureScopes()
+ role := strings.TrimSpace(record.Metadata[auth.RuntimeRoleMetadataKey])
+ if err := auth.ValidateRoleScopes(role, record.Scopes); err != nil {
+ return false
+ }
return true
}
}
diff --git a/internal/config/api_tokens_additional_test.go b/internal/config/api_tokens_additional_test.go
index a24261f1be..8431d626db 100644
--- a/internal/config/api_tokens_additional_test.go
+++ b/internal/config/api_tokens_additional_test.go
@@ -3,8 +3,44 @@ package config
import (
"testing"
"time"
+
+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
+func TestValidateAPITokenRejectsNonCanonicalRoleAuthority(t *testing.T) {
+ rawToken := "collector-invalid-scope.12345678"
+ record, err := NewAPITokenRecord(rawToken, "collector", []string{ScopeAgentReport, ScopeAgentConfigRead, ScopeSettingsWrite})
+ if err != nil {
+ t.Fatal(err)
+ }
+ record.Metadata = map[string]string{auth.RuntimeRoleMetadataKey: auth.RuntimeRoleMonitoringCollector}
+ cfg := &Config{APITokens: []APITokenRecord{*record}}
+
+ if got, ok := cfg.ValidateAPIToken(rawToken); ok || got != nil {
+ t.Fatalf("ValidateAPIToken admitted non-canonical role authority: %#v", got)
+ }
+ if cfg.IsValidAPIToken(rawToken) {
+ t.Fatal("IsValidAPIToken admitted non-canonical role authority")
+ }
+ if cfg.APITokens[0].LastUsedAt != nil {
+ t.Fatal("rejected credential updated last-used metadata")
+ }
+}
+
+func TestValidateAPITokenRejectsUnknownRuntimeRole(t *testing.T) {
+ rawToken := "collector-unknown-role.12345678"
+ record, err := NewAPITokenRecord(rawToken, "collector", []string{ScopeAgentReport})
+ if err != nil {
+ t.Fatal(err)
+ }
+ record.Metadata = map[string]string{auth.RuntimeRoleMetadataKey: "future-unreviewed-role"}
+ cfg := &Config{APITokens: []APITokenRecord{*record}}
+
+ if got, ok := cfg.ValidateAPIToken(rawToken); ok || got != nil {
+ t.Fatalf("ValidateAPIToken admitted unknown runtime role: %#v", got)
+ }
+}
+
func TestAPITokenRecord_IsLegacyToken(t *testing.T) {
record := &APITokenRecord{}
if !record.IsLegacyToken() {
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index 92aa33496d..b0e8fdee7b 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -20,6 +20,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/notifications"
"github.com/rcourtman/pulse-go-rewrite/internal/securityutil"
"github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/rs/zerolog/log"
)
@@ -699,7 +700,10 @@ func (c *ConfigPersistence) LoadAPITokens() ([]APITokenRecord, error) {
return nil, fmt.Errorf("decode api tokens file %s: %w", c.apiTokensFile, err)
}
- migrations := canonicalizeAPITokens(tokens)
+ migrations, err := canonicalizeAPITokens(tokens)
+ if err != nil {
+ return nil, fmt.Errorf("validate api token authority in %s: %w", c.apiTokensFile, err)
+ }
if migratedPlaintext || migrations.changed() {
if err := c.persistAPITokensLocked(tokens); err != nil {
return nil, fmt.Errorf("persist canonical api tokens file %s: %w", c.apiTokensFile, err)
@@ -709,6 +713,7 @@ func (c *ConfigPersistence) LoadAPITokens() ([]APITokenRecord, error) {
Int("missing_ids", migrations.missingIDs).
Int("legacy_scopes", migrations.legacyScopes).
Int("legacy_org_bindings", migrations.legacyOrgBindings).
+ Int("role_scope_reductions", migrations.roleScopeReductions).
Msg("Migrated API token metadata before loading")
}
@@ -786,6 +791,10 @@ func (c *ConfigPersistence) persistAPITokensLocked(tokens []APITokenRecord) erro
record := tokens[i]
record.ensureID()
record.ensureScopes()
+ role := strings.TrimSpace(record.Metadata[auth.RuntimeRoleMetadataKey])
+ if err := auth.ValidateRoleScopes(role, record.Scopes); err != nil {
+ return fmt.Errorf("validate api token %q authority before persistence: %w", record.ID, err)
+ }
sanitized[i] = record
}
diff --git a/internal/monitoring/agent_fleet_doctor.go b/internal/monitoring/agent_fleet_doctor.go
index f14d9898cc..3b5a308870 100644
--- a/internal/monitoring/agent_fleet_doctor.go
+++ b/internal/monitoring/agent_fleet_doctor.go
@@ -17,6 +17,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/platformsupport"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/internal/updates"
+ internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/rs/zerolog/log"
)
@@ -40,6 +41,7 @@ const (
AgentFleetReasonCredentialUnlisted = "agent_credential_registry_stale"
AgentFleetReasonExecScopeMissing = "agent_exec_scope_missing"
AgentFleetReasonExecScopeExcess = "agent_exec_scope_excess"
+ AgentFleetReasonCredentialScopeExcess = "agent_credential_scope_excess"
AgentFleetReasonDuplicateInstallation = "duplicate_host_agent_installation"
AgentFleetActionAllowReenroll = "allow_reenroll"
@@ -516,6 +518,7 @@ func diagnoseAgentFleetSubject(
result.Reasons,
AgentFleetReasonCredentialMissing,
AgentFleetReasonCredentialExpired,
+ AgentFleetReasonCredentialScopeExcess,
AgentFleetReasonExecScopeMissing,
) {
platform, supported := safeAgentUpdatePlatform(subject)
@@ -587,7 +590,19 @@ func diagnoseAgentCredential(subject agentFleetSubject, inventory agentFleetToke
return nil
}
if record, ok := inventory.active[tokenID]; ok {
- reasons := make([]AgentFleetDiagnosticReason, 0, 2)
+ reasons := make([]AgentFleetDiagnosticReason, 0, 3)
+ role := strings.TrimSpace(record.Metadata[internalauth.RuntimeRoleMetadataKey])
+ if unexpected := internalauth.UnexpectedScopes(role, record.Scopes); len(unexpected) > 0 {
+ reasons = append(reasons, AgentFleetDiagnosticReason{
+ Code: AgentFleetReasonCredentialScopeExcess,
+ Severity: AgentFleetStatusCritical,
+ Message: "This collector credential carries authority outside its runtime role allowlist.",
+ Evidence: []string{
+ "Credential runtime role: " + role,
+ "Unexpected scopes: " + strings.Join(unexpected, ", "),
+ },
+ })
+ }
if subject.host != nil && subject.host.CommandsEnabled && !record.HasScope(config.ScopeAgentExec) {
reasons = append(reasons, AgentFleetDiagnosticReason{
Code: AgentFleetReasonExecScopeMissing,
diff --git a/internal/monitoring/agent_fleet_doctor_test.go b/internal/monitoring/agent_fleet_doctor_test.go
index 95ae01866d..45573c88bc 100644
--- a/internal/monitoring/agent_fleet_doctor_test.go
+++ b/internal/monitoring/agent_fleet_doctor_test.go
@@ -9,6 +9,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/platformsupport"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
func TestAgentFleetDiagnosticsDetectsStaleAgentVersion(t *testing.T) {
@@ -37,6 +38,33 @@ func TestAgentFleetDiagnosticsDetectsStaleAgentVersion(t *testing.T) {
}
}
+func TestAgentFleetDiagnosticsExposesCollectorRoleScopeExcess(t *testing.T) {
+ now := time.Date(2026, 8, 29, 12, 0, 0, 0, time.UTC)
+ monitor := newAgentFleetDoctorTestMonitor(t)
+ monitor.config.APITokens = []config.APITokenRecord{{
+ ID: "collector-token",
+ Scopes: []string{config.ScopeAgentReport, config.ScopeAgentConfigRead, config.ScopeSettingsWrite},
+ Metadata: map[string]string{
+ auth.RuntimeRoleMetadataKey: auth.RuntimeRoleMonitoringCollector,
+ },
+ }}
+ monitor.state.UpsertHost(models.Host{
+ ID: "collector-agent",
+ Hostname: "collector-node",
+ Platform: "linux",
+ Status: "online",
+ LastSeen: now,
+ AgentVersion: "6.2.0",
+ TokenID: "collector-token",
+ })
+
+ agent := requireAgentDiagnostic(t, monitor.GetAgentFleetDiagnostics("6.2.0", now), "agent-collector-agent")
+ requireReasonCode(t, agent, AgentFleetReasonCredentialScopeExcess)
+ if agent.Status != AgentFleetStatusCritical {
+ t.Fatalf("status = %q, want %q", agent.Status, AgentFleetStatusCritical)
+ }
+}
+
func TestAgentFleetDiagnosticsDetectsMissingAndExpiredCredentials(t *testing.T) {
now := time.Date(2026, 8, 9, 12, 0, 0, 0, time.UTC)
expiredAt := now.Add(-time.Hour)
diff --git a/pkg/auth/agent_credentials.go b/pkg/auth/agent_credentials.go
new file mode 100644
index 0000000000..905854c437
--- /dev/null
+++ b/pkg/auth/agent_credentials.go
@@ -0,0 +1,125 @@
+package auth
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+)
+
+const (
+ RuntimeRoleMetadataKey = "runtime_role"
+ RuntimeRoleMonitoringCollector = "monitoring-collector"
+ RuntimeRoleActionRunner = "action-runner"
+ RuntimeRoleLegacyFullTrust = "legacy-full-trust"
+)
+
+var monitoringCollectorScopeOrder = []string{
+ ScopeAgentReport,
+ ScopeAgentConfigRead,
+ ScopeDockerReport,
+ ScopeKubernetesReport,
+}
+
+// MonitoringCollectorScopes returns the complete allowed collector scope
+// vocabulary. Report and config-read are mandatory; provider report scopes are
+// optional because Proxmox-only collectors do not need them.
+func MonitoringCollectorScopes() []string {
+ return append([]string(nil), monitoringCollectorScopeOrder...)
+}
+
+// CanonicalizeRoleScopes reduces a role credential to its canonical authority.
+// It never adds a scope. Missing mandatory scopes fail closed because silently
+// adding them would be an authority increase and accepting the credential
+// would violate the role contract.
+func CanonicalizeRoleScopes(role string, scopes []string) ([]string, bool, error) {
+ role = strings.TrimSpace(role)
+ switch role {
+ case RuntimeRoleMonitoringCollector:
+ present := scopeSet(scopes)
+ for _, required := range []string{ScopeAgentReport, ScopeAgentConfigRead} {
+ if _, ok := present[required]; !ok {
+ return nil, false, fmt.Errorf("monitoring collector credential requires %s", required)
+ }
+ }
+ canonical := make([]string, 0, len(monitoringCollectorScopeOrder))
+ for _, allowed := range monitoringCollectorScopeOrder {
+ if _, ok := present[allowed]; ok {
+ canonical = append(canonical, allowed)
+ }
+ }
+ return canonical, !slices.Equal(scopes, canonical), nil
+
+ case RuntimeRoleActionRunner:
+ present := scopeSet(scopes)
+ if _, ok := present[ScopeAgentExec]; !ok {
+ return nil, false, fmt.Errorf("action runner credential requires %s", ScopeAgentExec)
+ }
+ canonical := []string{ScopeAgentExec}
+ return canonical, !slices.Equal(scopes, canonical), nil
+
+ case RuntimeRoleLegacyFullTrust:
+ present := scopeSet(scopes)
+ if _, ok := present[ScopeAgentExec]; !ok {
+ return nil, false, fmt.Errorf("legacy full-trust credential requires %s", ScopeAgentExec)
+ }
+ return append([]string(nil), scopes...), false, nil
+
+ case "":
+ return append([]string(nil), scopes...), false, nil
+
+ default:
+ return nil, false, fmt.Errorf("unsupported agent credential role %q", role)
+ }
+}
+
+// ValidateRoleScopes reports whether a role credential already has canonical,
+// bounded authority. It is used at admission even though load-time migration
+// normally repairs excess authority, providing defense against in-memory
+// mutation and stale configuration snapshots.
+func ValidateRoleScopes(role string, scopes []string) error {
+ _, _, err := CanonicalizeRoleScopes(role, scopes)
+ if err != nil {
+ return err
+ }
+ if unexpected := UnexpectedScopes(role, scopes); len(unexpected) > 0 {
+ return fmt.Errorf("%s credential has non-canonical scopes", strings.TrimSpace(role))
+ }
+ return nil
+}
+
+// UnexpectedScopes returns scopes that are outside the role's allowlist. It is
+// diagnostics-only and never treats missing mandatory scopes as unexpected.
+func UnexpectedScopes(role string, scopes []string) []string {
+ var allowed map[string]struct{}
+ switch strings.TrimSpace(role) {
+ case RuntimeRoleMonitoringCollector:
+ allowed = scopeSet(monitoringCollectorScopeOrder)
+ case RuntimeRoleActionRunner:
+ allowed = scopeSet([]string{ScopeAgentExec})
+ default:
+ return nil
+ }
+ unexpected := make([]string, 0)
+ seen := make(map[string]struct{})
+ for _, scope := range scopes {
+ scope = strings.TrimSpace(scope)
+ if _, ok := allowed[scope]; ok {
+ continue
+ }
+ if _, ok := seen[scope]; ok {
+ continue
+ }
+ seen[scope] = struct{}{}
+ unexpected = append(unexpected, scope)
+ }
+ slices.Sort(unexpected)
+ return unexpected
+}
+
+func scopeSet(scopes []string) map[string]struct{} {
+ result := make(map[string]struct{}, len(scopes))
+ for _, scope := range scopes {
+ result[strings.TrimSpace(scope)] = struct{}{}
+ }
+ return result
+}
diff --git a/pkg/auth/agent_credentials_test.go b/pkg/auth/agent_credentials_test.go
new file mode 100644
index 0000000000..a81d26f87e
--- /dev/null
+++ b/pkg/auth/agent_credentials_test.go
@@ -0,0 +1,57 @@
+package auth
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestCanonicalizeMonitoringCollectorScopes(t *testing.T) {
+ t.Run("minimal collector", func(t *testing.T) {
+ scopes := []string{ScopeAgentReport, ScopeAgentConfigRead}
+ canonical, changed, err := CanonicalizeRoleScopes(RuntimeRoleMonitoringCollector, scopes)
+ require.NoError(t, err)
+ require.False(t, changed)
+ require.Equal(t, scopes, canonical)
+ })
+
+ t.Run("host collector", func(t *testing.T) {
+ scopes := []string{ScopeAgentReport, ScopeAgentConfigRead, ScopeDockerReport, ScopeKubernetesReport}
+ canonical, changed, err := CanonicalizeRoleScopes(RuntimeRoleMonitoringCollector, scopes)
+ require.NoError(t, err)
+ require.False(t, changed)
+ require.Equal(t, scopes, canonical)
+ })
+
+ t.Run("excess authority removed", func(t *testing.T) {
+ canonical, changed, err := CanonicalizeRoleScopes(RuntimeRoleMonitoringCollector, []string{
+ ScopeSettingsWrite, ScopeAgentConfigRead, ScopeAgentReport, ScopeActionsExecute,
+ })
+ require.NoError(t, err)
+ require.True(t, changed)
+ require.Equal(t, []string{ScopeAgentReport, ScopeAgentConfigRead}, canonical)
+ })
+
+ t.Run("missing baseline rejected", func(t *testing.T) {
+ _, _, err := CanonicalizeRoleScopes(RuntimeRoleMonitoringCollector, []string{ScopeAgentReport})
+ require.ErrorContains(t, err, ScopeAgentConfigRead)
+ })
+}
+
+func TestCanonicalizeActionRunnerScopes(t *testing.T) {
+ canonical, changed, err := CanonicalizeRoleScopes(RuntimeRoleActionRunner, []string{ScopeAgentExec, ScopeAgentReport})
+ require.NoError(t, err)
+ require.True(t, changed)
+ require.Equal(t, []string{ScopeAgentExec}, canonical)
+ require.Error(t, ValidateRoleScopes(RuntimeRoleActionRunner, []string{ScopeAgentExec, ScopeAgentReport}))
+}
+
+func TestValidateRoleScopesRejectsUnknownRole(t *testing.T) {
+ require.Error(t, ValidateRoleScopes("future-unreviewed-role", []string{ScopeAgentReport}))
+}
+
+func TestValidateRoleScopesAcceptsAllowedScopesInAnyOrder(t *testing.T) {
+ require.NoError(t, ValidateRoleScopes(RuntimeRoleMonitoringCollector, []string{
+ ScopeDockerReport, ScopeAgentConfigRead, ScopeAgentReport,
+ }))
+}