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.

Split audit log access into dedicated token scope

rcourtman2806cc6c9eca
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index ef8e942dd7..6b8d1c12e5 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -765,6 +765,10 @@ and export audit reads alongside the enterprise audit surface. That read path
belongs to the API and unified-resource contracts, not to lifecycle ownership,
so the agent-install and registration lane stays focused on fleet continuity
instead of adopting execution-history persistence as a side effect.
+That shared audit-read path also now requires the dedicated `audit:read`
+token scope instead of inheriting broader `settings:read` access, so
+lifecycle-adjacent install and registration surfaces cannot regain enterprise
+audit history just by holding general settings visibility.
The connected-infrastructure reporting workspace also now treats API-backed
platform surfaces as platform-connection-managed capabilities, not host-managed
agent extensions. `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`,
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 05b52e00f2..b330c8a814 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -204,6 +204,7 @@ the canonical monitored-system blocked payload.
and the Patrol route-shell destination itself, so the thin page shell at `frontend-modern/src/pages/AIIntelligence.tsx` may continue to bridge the shared AI-runtime payload boundary while exposing `/patrol` as the canonical product route and preserving `/ai` only as a compatibility redirect
9. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`
10. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`, `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`, and `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`
+ That same shared token contract also owns audit scope separation: audit event, verification, summary, export, and unified action/export audit reads must require the dedicated `audit:read` scope instead of reusing broader monitoring or settings-read token grants.
11. Add or change infrastructure operations token generation, lookup, assignment, the pure unified-agent inventory/install model, the split infrastructure install state owner, the split direct-node/discovery infrastructure settings owners, the shared infrastructure-operations state provider/context shell, and install presentation through `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, and `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`. Phase 9 retired the InfrastructureOperationsController shell and the useInfrastructureReportingState reporting path; they must not be reintroduced, and aggregator-backed reporting reads are owned by `frontend-modern/src/components/Settings/useConnectionsLedger.ts` under the frontend-primitives contract.
That same governed infrastructure-operations API boundary also owns discovery polling activation: the shared discovery runtime may only poll `/api/discover` while the settings shell has the `infrastructure-connections` route active, so route-level IA changes cannot silently keep discovery traffic alive on unrelated systems or install screens.
12. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index fba00d4866..086296297c 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -290,6 +290,10 @@ That same trust boundary also governs API token scope identity: legacy
migration boundaries, where they must be rewritten immediately into canonical
`agent:*` scopes. Live token records and runtime scope checks may not keep the
legacy scope names as an active second contract.
+That same token-scope boundary also owns audit-log least privilege: audit
+event, verification, summary, export, and unified action/export audit reads
+must require the dedicated `audit:read` scope instead of inheriting broader
+monitoring or settings-read token access.
That same token-scope boundary now also governs Pulse Mobile relay runtime
credentials: `internal/api/security_tokens.go` must mint only the dedicated
backend-owned `relay:mobile:access` scope for new mobile relay tokens, and the
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index bb42659a16..44f9b522c1 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1079,6 +1079,10 @@ as adjacent governed API ownership rather than timeline-store ownership. The
storage and recovery lanes still own their own persistence and query
contracts, while the control-plane execution trail remains governed by the
unified-resource and audit contracts.
+That adjacent audit-read surface also now requires the dedicated `audit:read`
+token scope rather than the broader `settings:read` scope, so storage- and
+recovery-adjacent settings visibility cannot silently expand into enterprise
+audit history reads.
That same shared `internal/api/` dependency now also includes monitored-system
ledger explanation reads: storage- and recovery-adjacent surfaces may coexist
with counted monitored-system inventory, but any support-facing count
diff --git a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
index 84f958236f..be61114106 100644
--- a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
@@ -3,7 +3,12 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/te
import type { APITokenRecord } from '@/api/security';
import type { Resource } from '@/types/resource';
-import { AGENT_REPORT_SCOPE, DOCKER_MANAGE_SCOPE, DOCKER_REPORT_SCOPE } from '@/constants/apiScopes';
+import {
+ AGENT_REPORT_SCOPE,
+ AUDIT_READ_SCOPE,
+ DOCKER_MANAGE_SCOPE,
+ DOCKER_REPORT_SCOPE,
+} from '@/constants/apiScopes';
import { APITokenManager } from '../APITokenManager';
const listTokensMock = vi.fn();
@@ -168,6 +173,39 @@ describe('APITokenManager', () => {
});
});
+ it('surfaces the dedicated audit scope in presets and grouped custom scopes', async () => {
+ createTokenMock.mockResolvedValueOnce({
+ token: 'pulse_audit_secret',
+ record: makeToken({
+ id: 'token-audit',
+ name: 'Audit export',
+ scopes: [AUDIT_READ_SCOPE],
+ }),
+ });
+
+ render(() => <APITokenManager onTokensChanged={vi.fn()} canManage />);
+
+ await waitFor(() => {
+ expect(listTokensMock).toHaveBeenCalledTimes(1);
+ });
+
+ expect(screen.getByRole('button', { name: 'Audit read' })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Custom scopes'));
+ expect(screen.getByText('Security')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Audit logs (read)' })).toBeInTheDocument();
+
+ fireEvent.input(screen.getByPlaceholderText('e.g. Container pipeline'), {
+ target: { value: 'Audit export' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Audit read' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Generate' }));
+
+ await waitFor(() => {
+ expect(createTokenMock).toHaveBeenCalledWith('Audit export', [AUDIT_READ_SCOPE]);
+ });
+ });
+
it('maps token usage from unified resources and fans revocation out to affected runtimes and agents', async () => {
listTokensMock.mockResolvedValue([
makeToken({
@@ -217,10 +255,10 @@ describe('APITokenManager', () => {
const runtimeName = await screen.findByText('Runtime token');
const row = runtimeName.closest('tr');
expect(row).toBeTruthy();
- expect(within(row as HTMLTableRowElement).getByText('Docker Edge • Edge Agent')).toBeInTheDocument();
expect(
- within(row as HTMLTableRowElement).getByText('Agent reporting'),
+ within(row as HTMLTableRowElement).getByText('Docker Edge • Edge Agent'),
).toBeInTheDocument();
+ expect(within(row as HTMLTableRowElement).getByText('Agent reporting')).toBeInTheDocument();
fireEvent.click(within(row as HTMLTableRowElement).getByRole('button', { name: 'Revoke' }));
@@ -291,9 +329,12 @@ describe('APITokenManager', () => {
it('surfaces scope denial when token generation is blocked by caller scope', async () => {
createTokenMock.mockRejectedValueOnce(
- Object.assign(new Error('Cannot grant scope "monitoring:read": your token does not have this scope'), {
- status: 403,
- }),
+ Object.assign(
+ new Error('Cannot grant scope "monitoring:read": your token does not have this scope'),
+ {
+ status: 403,
+ },
+ ),
);
render(() => <APITokenManager onTokensChanged={vi.fn()} canManage />);
diff --git a/frontend-modern/src/components/Settings/apiTokenManagerModel.ts b/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
index ff67b72455..f3750a1222 100644
--- a/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
+++ b/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
@@ -1,6 +1,7 @@
import { unwrap } from 'solid-js/store';
import type { APITokenRecord } from '@/api/security';
import {
+ AUDIT_READ_SCOPE,
AGENT_REPORT_SCOPE,
API_SCOPE_OPTIONS,
DOCKER_MANAGE_SCOPE,
@@ -35,7 +36,7 @@ export interface APITokenUsageEntry {
type ScopeGroup = (typeof API_SCOPE_OPTIONS)[number]['group'];
type ScopeOption = (typeof API_SCOPE_OPTIONS)[number];
-const API_TOKEN_SCOPE_GROUP_ORDER: ScopeGroup[] = ['Monitoring', 'Agents', 'Settings'];
+const API_TOKEN_SCOPE_GROUP_ORDER: ScopeGroup[] = ['Monitoring', 'Agents', 'Settings', 'Security'];
export const getAPITokenScopePresets = (): APITokenPreset[] => [
{
@@ -70,6 +71,11 @@ export const getAPITokenScopePresets = (): APITokenPreset[] => [
scopes: [SETTINGS_READ_SCOPE, SETTINGS_WRITE_SCOPE],
description: 'Full settings read/write – equivalent to automation with admin privileges.',
},
+ {
+ label: 'Audit read',
+ scopes: [AUDIT_READ_SCOPE],
+ description: 'Read audit events, verification history, summaries, and export activity.',
+ },
];
export const hasAgentScopeResource = (resource: Resource): boolean => {
@@ -192,6 +198,7 @@ export const groupAPITokenScopes = (): [ScopeGroup, ScopeOption[]][] => {
Monitoring: [],
Agents: [],
Settings: [],
+ Security: [],
};
for (const option of API_SCOPE_OPTIONS) {
grouped[option.group].push(option);
diff --git a/frontend-modern/src/constants/apiScopes.ts b/frontend-modern/src/constants/apiScopes.ts
index e6bb7bcc08..8a9972ab3d 100644
--- a/frontend-modern/src/constants/apiScopes.ts
+++ b/frontend-modern/src/constants/apiScopes.ts
@@ -2,7 +2,7 @@ export interface APIScopeOption {
value: string;
label: string;
description?: string;
- group: 'Monitoring' | 'Agents' | 'Settings';
+ group: 'Monitoring' | 'Agents' | 'Settings' | 'Security';
}
export const AGENT_REPORT_SCOPE = 'agent:report';
@@ -16,6 +16,7 @@ export const MONITORING_READ_SCOPE = 'monitoring:read';
export const MONITORING_WRITE_SCOPE = 'monitoring:write';
export const SETTINGS_READ_SCOPE = 'settings:read';
export const SETTINGS_WRITE_SCOPE = 'settings:write';
+export const AUDIT_READ_SCOPE = 'audit:read';
export const API_SCOPE_OPTIONS: APIScopeOption[] = [
{
@@ -84,6 +85,12 @@ export const API_SCOPE_OPTIONS: APIScopeOption[] = [
description: 'Modify configuration, manage tokens, and trigger updates.',
group: 'Settings',
},
+ {
+ value: AUDIT_READ_SCOPE,
+ label: 'Audit logs (read)',
+ description: 'Read audit events, verification status, summaries, and export history.',
+ group: 'Security',
+ },
];
export const API_SCOPE_LABELS = API_SCOPE_OPTIONS.reduce<Record<string, string>>((acc, option) => {
diff --git a/internal/api/audit_reporting_scope_test.go b/internal/api/audit_reporting_scope_test.go
index 87b707a269..1680d738dc 100644
--- a/internal/api/audit_reporting_scope_test.go
+++ b/internal/api/audit_reporting_scope_test.go
@@ -9,7 +9,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
-func TestAuditEndpointsRequireSettingsReadScope(t *testing.T) {
+func TestAuditEndpointsRequireAuditReadScope(t *testing.T) {
t.Setenv("PULSE_DEV", "true")
rawToken := "audit-scope-token-123.12345678"
@@ -30,10 +30,10 @@ func TestAuditEndpointsRequireSettingsReadScope(t *testing.T) {
rec := httptest.NewRecorder()
router.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
- t.Fatalf("expected 403 for missing settings:read scope on %s, got %d", path, rec.Code)
+ t.Fatalf("expected 403 for missing audit:read scope on %s, got %d", path, rec.Code)
}
- if !strings.Contains(rec.Body.String(), config.ScopeSettingsRead) {
- t.Fatalf("expected missing scope response to mention %q, got %q", config.ScopeSettingsRead, rec.Body.String())
+ if !strings.Contains(rec.Body.String(), config.ScopeAuditRead) {
+ t.Fatalf("expected missing scope response to mention %q, got %q", config.ScopeAuditRead, rec.Body.String())
}
}
}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 6eff529e88..2ad627e7df 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -8471,6 +8471,76 @@ func TestContract_SecurityStatusPresentationPolicyDefaultsClosedOutsideDemo(t *t
}
}
+func TestContract_SecurityStatusSplitsAuditLogCapabilityFromSettingsRead(t *testing.T) {
+ prevAuthorizer := authpkg.GetAuthorizer()
+ authpkg.SetAuthorizer(&allowRulesAuthorizer{
+ rules: map[string]bool{
+ "read:audit_logs": true,
+ "admin:audit_logs": true,
+ },
+ })
+ defer authpkg.SetAuthorizer(prevAuthorizer)
+
+ cases := []struct {
+ name string
+ scopes []string
+ wantAuditLog bool
+ wantAuditWebhooksRead bool
+ }{
+ {
+ name: "settings read stays limited to audit webhooks",
+ scopes: []string{config.ScopeSettingsRead},
+ wantAuditLog: false,
+ wantAuditWebhooksRead: true,
+ },
+ {
+ name: "audit read unlocks audit log capability",
+ scopes: []string{config.ScopeSettingsRead, config.ScopeAuditRead},
+ wantAuditLog: true,
+ wantAuditWebhooksRead: true,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ rawToken := fmt.Sprintf("contract-audit-scope-%s.12345678", strings.ReplaceAll(tc.name, " ", "-"))
+ record := newTokenRecord(t, rawToken, tc.scopes, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ req := httptest.NewRequest(http.MethodGet, "/api/security/status", nil)
+ req.Header.Set("X-API-Token", rawToken)
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("security status = %d, want 200 (%s)", rec.Code, rec.Body.String())
+ }
+
+ var payload struct {
+ SettingsCapabilities securityStatusSettingsCapabilities `json:"settingsCapabilities"`
+ TokenScopes []string `json:"tokenScopes"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode security status payload: %v", err)
+ }
+
+ if payload.SettingsCapabilities.AuditLog != tc.wantAuditLog {
+ t.Fatalf("settingsCapabilities.auditLog = %v, want %v", payload.SettingsCapabilities.AuditLog, tc.wantAuditLog)
+ }
+ if payload.SettingsCapabilities.AuditWebhooksRead != tc.wantAuditWebhooksRead {
+ t.Fatalf(
+ "settingsCapabilities.auditWebhooksRead = %v, want %v",
+ payload.SettingsCapabilities.AuditWebhooksRead,
+ tc.wantAuditWebhooksRead,
+ )
+ }
+ if !reflect.DeepEqual(payload.TokenScopes, tc.scopes) {
+ t.Fatalf("tokenScopes = %#v, want %#v", payload.TokenScopes, tc.scopes)
+ }
+ })
+ }
+}
+
func TestContract_SetupScriptURLRejectsNonCanonicalRequestJSON(t *testing.T) {
handler := newTestConfigHandlers(t, &config.Config{DataPath: t.TempDir()})
diff --git a/internal/api/license_expiry_integration_test.go b/internal/api/license_expiry_integration_test.go
index 5846fa5aef..1d4b90e152 100644
--- a/internal/api/license_expiry_integration_test.go
+++ b/internal/api/license_expiry_integration_test.go
@@ -36,7 +36,7 @@ func TestExpiredLicenseBlocksProFeature(t *testing.T) {
handler := createTestHandler(t)
// Activate a Pro license with a 24h expiry.
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("generate test license: %v", err)
}
@@ -93,7 +93,7 @@ func TestGracePeriodAllowsProFeature(t *testing.T) {
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("generate test license: %v", err)
}
@@ -134,7 +134,7 @@ func TestExpiredLicenseFeaturesEndpoint(t *testing.T) {
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("generate test license: %v", err)
}
@@ -278,7 +278,7 @@ func TestLicenseGatedEmptyResponseOnExpiry(t *testing.T) {
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("generate test license: %v", err)
}
diff --git a/internal/api/license_handlers_test.go b/internal/api/license_handlers_test.go
index 3039b14010..4f7fa2f575 100644
--- a/internal/api/license_handlers_test.go
+++ b/internal/api/license_handlers_test.go
@@ -156,7 +156,7 @@ func TestHandleLicenseFeatures_WithActiveLicense(t *testing.T) {
t.Setenv("PULSE_LICENSE_DEV_MODE", "true")
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("failed to generate test license: %v", err)
}
@@ -245,7 +245,7 @@ func TestHandleLicenseStatus_WithActiveLicense(t *testing.T) {
t.Setenv("PULSE_LICENSE_DEV_MODE", "true")
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("failed to generate test license: %v", err)
}
@@ -450,7 +450,7 @@ func TestHandleActivateLicense_ExchangesLegacyJWTInStrictV6(t *testing.T) {
t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("failed to generate test license: %v", err)
}
@@ -644,7 +644,7 @@ func TestHandleActivateLicense_ActivationKeyClearsStaleLegacyPersistence(t *test
t.Fatalf("new license persistence: %v", err)
}
- legacyKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ legacyKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("generate stale legacy license: %v", err)
}
@@ -697,7 +697,7 @@ func TestHandleActivateLicense_ValidKey(t *testing.T) {
t.Setenv("PULSE_LICENSE_DEV_MODE", "true")
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("failed to generate test license: %v", err)
}
@@ -1434,7 +1434,7 @@ func TestHandleClearLicense_WithActiveLicense(t *testing.T) {
t.Setenv("PULSE_LICENSE_DEV_MODE", "true")
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("failed to generate test license: %v", err)
}
@@ -1570,7 +1570,7 @@ func TestRequireLicenseFeature_WithLicense(t *testing.T) {
t.Setenv("PULSE_LICENSE_DEV_MODE", "true")
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("failed to generate test license: %v", err)
}
@@ -1719,7 +1719,7 @@ func TestLicenseGatedEmptyResponse_WithLicense(t *testing.T) {
t.Setenv("PULSE_LICENSE_DEV_MODE", "true")
handler := createTestHandler(t)
- licenseKey, err := license.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
+ licenseKey, err := pkglicensing.GenerateLicenseForTesting("[email protected]", license.TierPro, 24*time.Hour)
if err != nil {
t.Fatalf("failed to generate test license: %v", err)
}
diff --git a/internal/api/router_routes_licensing.go b/internal/api/router_routes_licensing.go
index f73741f009..27a7b6058e 100644
--- a/internal/api/router_routes_licensing.go
+++ b/internal/api/router_routes_licensing.go
@@ -93,49 +93,49 @@ func (r *Router) registerOrgLicenseRoutesGroup(orgHandlers *OrgHandlers, rbacHan
if !ensureAdminSession(r.config, w, req) {
return
}
- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditAdminEndpoints.HandleListEvents))(w, req)
+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditAdminEndpoints.HandleListEvents))(w, req)
}))
r.mux.HandleFunc("GET /api/audit/", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {
if !ensureAdminSession(r.config, w, req) {
return
}
- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditAdminEndpoints.HandleListEvents))(w, req)
+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditAdminEndpoints.HandleListEvents))(w, req)
}))
r.mux.HandleFunc("GET /api/audit/{id}/verify", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {
if !ensureAdminSession(r.config, w, req) {
return
}
- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditAdminEndpoints.HandleVerifyEvent))(w, req)
+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditAdminEndpoints.HandleVerifyEvent))(w, req)
}))
r.mux.HandleFunc("GET /api/audit/export", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {
if !ensureAdminSession(r.config, w, req) {
return
}
- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditAdminEndpoints.HandleExportEvents))(w, req)
+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditAdminEndpoints.HandleExportEvents))(w, req)
}))
r.mux.HandleFunc("GET /api/audit/summary", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {
if !ensureAdminSession(r.config, w, req) {
return
}
- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditAdminEndpoints.HandleSummary))(w, req)
+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditAdminEndpoints.HandleSummary))(w, req)
}))
r.mux.HandleFunc("GET /api/audit/actions", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {
if !ensureAdminSession(r.config, w, req) {
return
}
- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListUnifiedActionAudits))(w, req)
+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditHandlers.HandleListUnifiedActionAudits))(w, req)
}))
r.mux.HandleFunc("GET /api/audit/actions/{id}/events", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {
if !ensureAdminSession(r.config, w, req) {
return
}
- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListUnifiedActionLifecycleEvents))(w, req)
+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditHandlers.HandleListUnifiedActionLifecycleEvents))(w, req)
}))
r.mux.HandleFunc("GET /api/audit/exports", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceAuditLogs, func(w http.ResponseWriter, req *http.Request) {
if !ensureAdminSession(r.config, w, req) {
return
}
- RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeSettingsRead, auditHandlers.HandleListUnifiedExportAudits))(w, req)
+ RequireLicenseFeature(r.licenseHandlers, featureAuditLoggingValue, RequireScope(config.ScopeAuditRead, auditHandlers.HandleListUnifiedExportAudits))(w, req)
}))
// RBAC routes (Phase 2 - Enterprise feature)
diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.go
index 8d9e254f03..01a277b6c0 100644
--- a/internal/api/security_regression_test.go
+++ b/internal/api/security_regression_test.go
@@ -2975,7 +2975,7 @@ func TestAIChatEndpointsRequireAIChatScope(t *testing.T) {
func TestAuditEndpointsRequireLicenseFeature(t *testing.T) {
rawToken := "audit-license-token-123.12345678"
- record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)
+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead, config.ScopeAuditRead}, nil)
cfg := newTestConfigWithTokens(t, record)
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
@@ -2990,7 +2990,7 @@ func TestAuditEndpointsRequireLicenseFeature(t *testing.T) {
func TestAuditVerifyRequiresLicenseFeature(t *testing.T) {
rawToken := "audit-verify-license-token-123.12345678"
- record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)
+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead, config.ScopeAuditRead}, nil)
cfg := newTestConfigWithTokens(t, record)
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
@@ -3264,7 +3264,7 @@ func TestPermissionProtectedEndpointsDenyWhenAuthorizerBlocks(t *testing.T) {
defer auth.SetAuthorizer(prevAuthorizer)
rawToken := "perm-deny-token-123.12345678"
- record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)
+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead, config.ScopeAuditRead}, nil)
cfg := newTestConfigWithTokens(t, record)
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
diff --git a/internal/api/security_status_additional_test.go b/internal/api/security_status_additional_test.go
index 8eb59204b7..d37fc4cc07 100644
--- a/internal/api/security_status_additional_test.go
+++ b/internal/api/security_status_additional_test.go
@@ -144,7 +144,7 @@ func TestSecurityStatusExposesSettingsCapabilitiesForScopedToken(t *testing.T) {
defer auth.SetAuthorizer(prevAuthorizer)
rawToken := "status-cap-token-123.12345678"
- record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead, config.ScopeSettingsWrite}, nil)
+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead, config.ScopeSettingsWrite, config.ScopeAuditRead}, nil)
cfg := newTestConfigWithTokens(t, record)
router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
@@ -192,7 +192,7 @@ func TestSecurityStatusExposesSettingsCapabilitiesForScopedToken(t *testing.T) {
if payload.SettingsCapabilities.BillingAdmin {
t.Fatalf("did not expect billingAdmin capability for API token")
}
- if len(payload.TokenScopes) != 2 {
+ if len(payload.TokenScopes) != 3 {
t.Fatalf("expected token scopes in response, got %#v", payload.TokenScopes)
}
}
@@ -246,6 +246,45 @@ func TestSecurityStatusSplitsReadAndWriteSettingsCapabilities(t *testing.T) {
}
}
+func TestSecurityStatusRequiresAuditReadScopeForAuditLogCapability(t *testing.T) {
+ prevAuthorizer := auth.GetAuthorizer()
+ auth.SetAuthorizer(&allowRulesAuthorizer{
+ rules: map[string]bool{
+ "read:audit_logs": true,
+ "admin:audit_logs": true,
+ },
+ })
+ defer auth.SetAuthorizer(prevAuthorizer)
+
+ rawToken := "status-audit-split-token-123.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ req := httptest.NewRequest(http.MethodGet, "/api/security/status", nil)
+ req.Header.Set("X-API-Token", rawToken)
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200 for security status, got %d", rec.Code)
+ }
+
+ var payload struct {
+ SettingsCapabilities securityStatusSettingsCapabilities `json:"settingsCapabilities"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+
+ if payload.SettingsCapabilities.AuditLog {
+ t.Fatalf("did not expect audit log capability without audit:read scope")
+ }
+ if !payload.SettingsCapabilities.AuditWebhooksRead {
+ t.Fatalf("expected audit webhook read capability to remain settings-scoped")
+ }
+}
+
func TestSecurityStatusUsesOwnerBoundTokenPrincipalForRBAC(t *testing.T) {
prevAuthorizer := auth.GetAuthorizer()
auth.SetAuthorizer(&mockAuthorizerFn{
diff --git a/internal/api/security_status_capabilities.go b/internal/api/security_status_capabilities.go
index efd676d124..d887941621 100644
--- a/internal/api/security_status_capabilities.go
+++ b/internal/api/security_status_capabilities.go
@@ -215,7 +215,7 @@ func (r *Router) securityStatusSettingsCapabilitiesFromSnapshot(snapshot securit
canReadSettings := snapshot.canAccessAdminSurface(config.ScopeSettingsRead)
canManageUsers := r.canAccessPermissionSurface(snapshot, internalauth.ActionAdmin, internalauth.ResourceUsers)
canReadAudit := snapshot.passesPrivilegedSessionGate() &&
- r.canAccessPermissionSurface(snapshot, internalauth.ActionRead, internalauth.ResourceAuditLogs, config.ScopeSettingsRead)
+ r.canAccessPermissionSurface(snapshot, internalauth.ActionRead, internalauth.ResourceAuditLogs, config.ScopeAuditRead)
canManageRoles := snapshot.passesPrivilegedSessionGate() && canManageUsers
return securityStatusSettingsCapabilities{
diff --git a/internal/config/api_tokens.go b/internal/config/api_tokens.go
index d0e6f34194..bea32eb318 100644
--- a/internal/config/api_tokens.go
+++ b/internal/config/api_tokens.go
@@ -12,44 +12,28 @@ import (
// Canonical API token scope strings.
const (
- ScopeWildcard = "*"
- ScopeMonitoringRead = "monitoring:read"
- ScopeMonitoringWrite = "monitoring:write"
- ScopeDockerReport = "docker:report"
- ScopeDockerManage = "docker:manage"
- ScopeKubernetesReport = "kubernetes:report"
- ScopeKubernetesManage = "kubernetes:manage"
- ScopeAgentReport = "agent:report"
- ScopeAgentConfigRead = "agent:config:read"
- ScopeAgentManage = "agent:manage"
- ScopeSettingsRead = "settings:read"
- ScopeSettingsWrite = "settings:write"
- ScopeAIExecute = "ai:execute" // Allows executing AI commands and remediation plans
- ScopeAIChat = "ai:chat" // Allows AI chat participation
- ScopeRelayMobileAccess = "relay:mobile:access" // Allows the governed Pulse Mobile relay runtime surface
- ScopeAgentExec = "agent:exec" // Allows agent execution WebSocket connections
- ScopeAgentEnroll = "agent:enroll" // Bootstrap enrollment only
+ ScopeWildcard = auth.ScopeWildcard
+ ScopeMonitoringRead = auth.ScopeMonitoringRead
+ ScopeMonitoringWrite = auth.ScopeMonitoringWrite
+ ScopeDockerReport = auth.ScopeDockerReport
+ ScopeDockerManage = auth.ScopeDockerManage
+ ScopeKubernetesReport = auth.ScopeKubernetesReport
+ ScopeKubernetesManage = auth.ScopeKubernetesManage
+ ScopeAgentReport = auth.ScopeAgentReport
+ ScopeAgentConfigRead = auth.ScopeAgentConfigRead
+ ScopeAgentManage = auth.ScopeAgentManage
+ ScopeSettingsRead = auth.ScopeSettingsRead
+ ScopeSettingsWrite = auth.ScopeSettingsWrite
+ ScopeAuditRead = auth.ScopeAuditRead
+ ScopeAIExecute = auth.ScopeAIExecute
+ ScopeAIChat = auth.ScopeAIChat
+ ScopeRelayMobileAccess = auth.ScopeRelayMobileAccess
+ ScopeAgentExec = auth.ScopeAgentExec
+ ScopeAgentEnroll = auth.ScopeAgentEnroll
)
// AllKnownScopes enumerates scopes recognized by the backend (excluding the wildcard sentinel).
-var AllKnownScopes = []string{
- ScopeMonitoringRead,
- ScopeMonitoringWrite,
- ScopeDockerReport,
- ScopeDockerManage,
- ScopeKubernetesReport,
- ScopeKubernetesManage,
- ScopeAgentReport,
- ScopeAgentConfigRead,
- ScopeAgentManage,
- ScopeSettingsRead,
- ScopeSettingsWrite,
- ScopeAIExecute,
- ScopeAIChat,
- ScopeRelayMobileAccess,
- ScopeAgentExec,
- ScopeAgentEnroll,
-}
+var AllKnownScopes = append([]string(nil), auth.AllKnownScopes...)
var scopeLookup = func() map[string]struct{} {
lookup := make(map[string]struct{}, len(AllKnownScopes))
diff --git a/pkg/auth/scopes.go b/pkg/auth/scopes.go
new file mode 100644
index 0000000000..de0a8c9065
--- /dev/null
+++ b/pkg/auth/scopes.go
@@ -0,0 +1,44 @@
+package auth
+
+// Canonical API token scopes shared across Pulse repos.
+const (
+ ScopeWildcard = "*"
+ ScopeMonitoringRead = "monitoring:read"
+ ScopeMonitoringWrite = "monitoring:write"
+ ScopeDockerReport = "docker:report"
+ ScopeDockerManage = "docker:manage"
+ ScopeKubernetesReport = "kubernetes:report"
+ ScopeKubernetesManage = "kubernetes:manage"
+ ScopeAgentReport = "agent:report"
+ ScopeAgentConfigRead = "agent:config:read"
+ ScopeAgentManage = "agent:manage"
+ ScopeSettingsRead = "settings:read"
+ ScopeSettingsWrite = "settings:write"
+ ScopeAuditRead = "audit:read"
+ ScopeAIExecute = "ai:execute"
+ ScopeAIChat = "ai:chat"
+ ScopeRelayMobileAccess = "relay:mobile:access"
+ ScopeAgentExec = "agent:exec"
+ ScopeAgentEnroll = "agent:enroll"
+)
+
+// AllKnownScopes enumerates canonical scopes, excluding the wildcard sentinel.
+var AllKnownScopes = []string{
+ ScopeMonitoringRead,
+ ScopeMonitoringWrite,
+ ScopeDockerReport,
+ ScopeDockerManage,
+ ScopeKubernetesReport,
+ ScopeKubernetesManage,
+ ScopeAgentReport,
+ ScopeAgentConfigRead,
+ ScopeAgentManage,
+ ScopeSettingsRead,
+ ScopeSettingsWrite,
+ ScopeAuditRead,
+ ScopeAIExecute,
+ ScopeAIChat,
+ ScopeRelayMobileAccess,
+ ScopeAgentExec,
+ ScopeAgentEnroll,
+}