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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Harden first-run security boundaries
rcourtmaneb63de0b75e2
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 939965fbf9..6dd6cc66e6 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -697,6 +697,15 @@ identity. The scoped Patrol request carries resource identity only and reusesthe existing Patrol scoped engine, so it adds no agent lifecycle controlsurface and no new `internal/api/` lifecycle handler.+First-run security discovery under shared `internal/api/` is likewise an+adjacent API/security boundary, not an agent-lifecycle discovery surface.+Unauthenticated `/api/security/status` responses must stay on the public tier+and must not disclose bootstrap-token paths, container/runtime identity,+credential state, token diagnostics, or agent URL configuration. Agent setup+may consume those details only after the caller reaches the authenticated or+privileged security-status tier; it must not infer lifecycle readiness from+the intentionally sparse public response.+1. Add or change install-command generation, canonical /api/auto-register behavior, or installer download behavior through the owned `internal/api/` files above.Canonical `/api/auto-register` auth is split by intent: when the setup-tokenbootstrap path succeeds, lifecycle clients must complete registration withdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex c4d8f7c548..16625d55ae 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1545,6 +1545,16 @@ payload shape change when the portal presents compact client rows.from SSO claims for app chrome. Frontend consumers may display the label,but API, organization, token, and permission checks must continue to bindto the stable principal.+ `/api/security/status` also owns an explicit three-tier disclosure+ contract. Unauthenticated callers receive only the public login/setup+ allowlist (`detailLevel=public`): authentication presence, login routing,+ SSO provider discovery, and browser presentation policy. Authenticated+ callers may additionally receive their own session identity, token scopes,+ and capability projection (`detailLevel=authenticated`). Deployment,+ network, credential, token-hint, audit, proxy-configuration, and agent URL+ details require an admin/session boundary or an API token carrying+ `settings:read` (`detailLevel=privileged`). Bootstrap token paths, LXC IDs,+ and Docker container names are not part of any security-status tier.79. `internal/api/security_tokens.go` shared with `security-privacy`: the security token handlers are both a security/privacy control surface and a canonical API payload contract boundary.Token owner identity is reserved for the server-authenticated principal:shared token-minting helpers must derive `owner_user_id` from the current@@ -2453,10 +2463,12 @@ a new API state machine, queue contract, or verification-accounting field.`internal/api/router_routes_auth_security.go`,`internal/api/security_status_capabilities.go`, frontend security-statusconsumers, and shared demo-mode stores must treat- `/api/security/status.sessionCapabilities.demoMode` as the canonical- browser bootstrap signal for public demo posture instead of asking+ `/api/security/status.presentationPolicy.demoMode` as the canonical public+ browser bootstrap signal for demo posture instead of askingfrontend callers to infer demo state from response headers, `/api/health`- probes, or hostname heuristics. Shared browser stores that consume+ probes, or hostname heuristics. The more detailed+ `sessionCapabilities.demoMode` projection is authenticated caller context,+ not part of the unauthenticated response. Shared browser stores that consumePatrol approvals must also fail closed from that resolved demo policy atthe store boundary, so public demo shells do not probe `/api/ai/approvals`or `/api/ai/remediation/plans` after the read-only demo posture is already@@ -3143,11 +3155,13 @@ a new API state machine, queue contract, or verification-accounting field.30. Keep `/api/security/dev/reset-first-run` transport-backed and genuinelyunauthenticated: when the dev reset route clears first-run auth it mustalso clear any env-backed auth state that feeds `/api/security/status`, so- the status payload flips `hasAuthentication` to `false`, preserves- `bootstrapTokenPath`, and allows browser-owned first-session proof to+ the public status payload flips `hasAuthentication` to `false` without+ disclosing the bootstrap token path or deployment fingerprint, and allows+ browser-owned first-session proof tore-enter the real setup wizard instead of silently falling back to an- already-authenticated app state. That recovery transport may expose the- bootstrap token file path, but it must not emit the token value into+ already-authenticated app state. The explicitly dev-gated reset response+ may expose the newly created bootstrap token and file path to its authorized+ caller, but it must not emit the token value intoautomatic runtime logs.31. Keep shared SSO test and metadata-preview transport fail-closed: SAMLmetadata URLs and OIDC issuer URLs must reject non-HTTP or userinfo-bearing@@ -3976,6 +3990,13 @@ unbounded growth, bootstrap token validation must enforce a per-client retrylimit with an explicit `Retry-After` contract, and incoming `X-Request-ID`headers may only round-trip when they fit the bounded safe character set usedfor logs and response headers.+The same fail-closed auth boundary requires `/api/security/apply-restart` to+prove normal admin/settings-write authorization after setup or a valid+rate-limited bootstrap token during first-run state; absence of configured+authentication is never restart authority. Quick security setup validates the+local admin username before any runtime mutation and renders `.env` plus+systemd assignments through structural encoders, so request text cannot create+new environment keys, unit sections, or service directives.That same shared settings/licensing contract now also owns the split usage-datapayload model. `frontend-modern/src/api/settings.ts`,`internal/api/router_routes_licensing.go`, and adjacent settings callers must@@ -4292,10 +4313,8 @@ internal-versus-external navigation behavior inside API-adjacent page or hookowners once the contract can resolve to both in-app and public destinations.That same shared `internal/api/` boundary now also owns browser presentationpolicy for public-demo and commercial suppression. `/api/security/status` must-continue to expose the raw session capability fact-`sessionCapabilities.demoMode`, but browser shells and shared frontend stores-now consume the explicit `presentationPolicy` payload from that same response-as the canonical runtime contract for `demoMode`, `readOnly`,+expose `presentationPolicy` on the public response as the canonical browser+runtime contract for `demoMode`, `readOnly`,`hideCommercial`, and `hideUpgrade`. Commercial posture and billing storesmust therefore defer their first read until that policy has resolved, sopublic demos fail closed without probing hidden commercial routes duringdiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 5ec8f69bc5..c313ef40b4 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -533,6 +533,13 @@ AGENT_SURFACE_ID_PULSE_MCP)` and `getAgentSurfaceToolPosturePresentation`,stay explicitly excluded.7. `frontend-modern/src/components/Settings/SecurityAuthPanel.tsx` shared with `security-privacy`: the authentication settings surface is both a security/privacy control surface and a canonical settings-shell presentation boundary.8. `frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx` shared with `security-privacy`: the security overview settings surface is both a security/privacy control surface and a canonical settings-shell presentation boundary.+ These settings panels consume the privileged security-status projection,+ while the shared status type also represents intentionally sparse public and+ authenticated tiers. Privileged posture booleans therefore remain optional+ at the transport boundary and must be normalized fail-closed before the+ settings shell derives posture summaries or hardening actions. The first-run+ shell must use generic host, Docker, and LXC bootstrap commands rather than+ probing public status for deployment identity.9. `frontend-modern/src/routing/routePreload.ts` shared with `performance-and-scalability`: the app-shell route preload registry is both a canonical frontend shell boundary and an authenticated hot-path performance boundary.10. `frontend-modern/src/stores/aiChat.ts` shared with `ai-runtime`: the assistant drawer and session store is both an AI runtime control surface and a canonical app-shell presentation boundary.Assistant session pickers and reloads must restore only safediff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex e2440d07e5..e460cdc698 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -1195,16 +1195,26 @@ shows no `lastUsedAt`. Refreshing or hiding a QR payload must not delete atoken that an already paired device is actively depending on.That same auth/security boundary also owns browser session-capability posture:`internal/api/router_routes_auth_security.go` together with-`internal/api/security_status_capabilities.go` must expose-`/api/security/status.sessionCapabilities.demoMode` as the backend-owned-public-demo posture signal, and security/privacy consumers must not infer demo-state from response headers, `/api/health`, or hostname heuristics. That same+`internal/api/security_status_capabilities.go` must expose public demo posture+through `/api/security/status.presentationPolicy.demoMode`; authenticated+responses may additionally expose `sessionCapabilities.demoMode` as caller+context. Security/privacy consumers must not infer demo state from response+headers, `/api/health`, or hostname heuristics. That authenticatedsession-capability contract now also carries the closed-shell assistantavailability fact through`/api/security/status.sessionCapabilities.assistantEnabled`, so generalsettings or security surfaces do not probe `/api/settings/ai` or otherassistant endpoints merely to decide whether dormant assistant chrome may beopened.+Security status disclosure is tiered by construction: public callers receive+only login/setup discovery, authenticated callers receive their own identity+and capability context, and deployment, network, credential, token-hint,+audit, proxy-configuration, and agent URL details require an admin session or+a `settings:read` API token. Bootstrap paths and container identifiers are not+security-status fields. Initial service restart requires either normal+admin/settings-write authorization or the rate-limited bootstrap token, and+quick security setup rejects structurally unsafe local usernames before it+mutates runtime state or renders `.env` and systemd configuration.That same token-management boundary now also depends on one neutralapp-runtime context owner. `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`may consume websocket-backed revocation fan-out throughdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex d8546b5ef7..bbb477230b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -1361,6 +1361,13 @@ recovery scope, or a storage/recovery-owned secret source.coverage, storage-health proof, restore readiness, recovery-job state, orevidence that any storage or recovery endpoint was read, changed, orverified.+ Public first-run security status under the same shared API tree is also+ adjacent-only. Its sparse login-routing and presentation-policy fields are+ not recovery configuration, and storage/recovery consumers must not expect+ bootstrap-token paths, deployment/container identity, credential state,+ token diagnostics, or agent URLs before authenticated privileged access.+ Bootstrap-token authorization for the unconfigured server restart path is a+ security boundary, not a restore credential or recovery-control primitive.External-agent activity may be counted for narrow tokens that satisfy thecalled manifest capability scope, including read-only context calls. Thatkeeps MCP collaboration measurable, but storage and recovery must not treatdiff --git a/frontend-modern/src/components/Settings/SecurityAuthPanel.tsx b/frontend-modern/src/components/Settings/SecurityAuthPanel.tsxindex 7552b8aaa2..4ee701430c 100644--- a/frontend-modern/src/components/Settings/SecurityAuthPanel.tsx+++ b/frontend-modern/src/components/Settings/SecurityAuthPanel.tsx@@ -22,7 +22,7 @@ import type { VersionInfo } from '@/api/updates';interface SecurityStatusInfo {hasAuthentication: boolean;- apiTokenConfigured: boolean;+ apiTokenConfigured?: boolean;authUsername?: string;configuredButPendingRestart?: boolean;hasProxyAuth?: boolean;diff --git a/frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx b/frontend-modern/src/components/Settings/SecurityOverviewPanel.tsxindex b038b05f3d..6b013cadc6 100644--- a/frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx+++ b/frontend-modern/src/components/Settings/SecurityOverviewPanel.tsx@@ -16,17 +16,18 @@ import AlertTriangle from 'lucide-solid/icons/alert-triangle';import {getSecurityHardeningActions,type SecurityHardeningAction,+ type SecurityPostureStatus,} from '@/utils/securityScorePresentation';interface SecurityStatusInfo {hasAuthentication: boolean;ssoEnabled?: boolean;hasProxyAuth?: boolean;- apiTokenConfigured: boolean;- exportProtected: boolean;+ apiTokenConfigured?: boolean;+ exportProtected?: boolean;unprotectedExportAllowed?: boolean;hasHTTPS?: boolean;- hasAuditLogging: boolean;+ hasAuditLogging?: boolean;requiresAuth: boolean;publicAccess?: boolean;isPrivateNetwork?: boolean;@@ -42,8 +43,18 @@ interface SecurityOverviewPanelProps {}export const SecurityOverviewPanel: Component<SecurityOverviewPanelProps> = (props) => {+ const postureStatus = createMemo<SecurityPostureStatus | null>(() => {+ const status = props.securityStatus();+ if (!status) return null;+ return {+ ...status,+ apiTokenConfigured: status.apiTokenConfigured === true,+ exportProtected: status.exportProtected === true,+ hasAuditLogging: status.hasAuditLogging === true,+ };+ });const hardeningActions = createMemo(() =>- props.securityStatus() ? getSecurityHardeningActions(props.securityStatus()!) : [],+ postureStatus() ? getSecurityHardeningActions(postureStatus()!) : [],);const criticalHardeningActions = createMemo(() => hardeningActions().filter((action) => action.severity === 'critical').length,@@ -120,8 +131,8 @@ export const SecurityOverviewPanel: Component<SecurityOverviewPanelProps> = (pro</SettingsLoadingSkeleton></Show>- <Show when={!props.securityStatusLoading() && props.securityStatus()}>- <SecurityPostureSummary status={props.securityStatus()!} embedded />+ <Show when={!props.securityStatusLoading() && postureStatus()}>+ <SecurityPostureSummary status={postureStatus()!} embedded /></Show><Show when={!props.securityStatusLoading() && hardeningActions().length > 0}>diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex 8b958a92ec..ac90aa638b 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -547,6 +547,25 @@ describe('settings architecture guardrails', () => {}});+ it('normalizes sparse security status before deriving privileged posture', () => {+ expect(securityAuthPanelSource).toContain('apiTokenConfigured?: boolean;');+ expect(securityOverviewPanelSource).toContain(+ 'const postureStatus = createMemo<SecurityPostureStatus | null>',+ );+ expect(securityOverviewPanelSource).toContain(+ 'apiTokenConfigured: status.apiTokenConfigured === true',+ );+ expect(securityOverviewPanelSource).toContain(+ 'exportProtected: status.exportProtected === true',+ );+ expect(securityOverviewPanelSource).toContain(+ 'hasAuditLogging: status.hasAuditLogging === true',+ );+ expect(securityOverviewPanelSource).toContain(+ 'postureStatus() ? getSecurityHardeningActions(postureStatus()!) : []',+ );+ });+it('keeps settings loading spinners on the shared spinner primitive', () => {const spinnerConsumers: Array<[string, string[]]> = [[diff --git a/frontend-modern/src/components/SetupWizard/__tests__/SetupWizard.localization.test.tsx b/frontend-modern/src/components/SetupWizard/__tests__/SetupWizard.localization.test.tsxindex f5003e1833..0076a1fc7f 100644--- a/frontend-modern/src/components/SetupWizard/__tests__/SetupWizard.localization.test.tsx+++ b/frontend-modern/src/components/SetupWizard/__tests__/SetupWizard.localization.test.tsx@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { cleanup, render, screen, waitFor } from '@solidjs/testing-library';+import { cleanup, render, screen } from '@solidjs/testing-library';import { DEFAULT_LOCALE, setActiveLocale } from '@/i18n';import RuntimeHome from '@/pages/RuntimeHome';import { SetupCompletionPanel } from '../SetupCompletionPanel';@@ -69,10 +69,6 @@ describe('localized setup wizard journey', () => {/>));- await waitFor(() => {- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/security/status');- });-expect(screen.getByText('Bienvenido a Pulse')).toBeInTheDocument();expect(screen.getByText('Desbloquear configuración')).toBeInTheDocument();expect(screen.getByText(/Conecta una API de plataforma/)).toBeInTheDocument();diff --git a/frontend-modern/src/components/SetupWizard/__tests__/WelcomeStep.test.tsx b/frontend-modern/src/components/SetupWizard/__tests__/WelcomeStep.test.tsxindex 43a1b60f15..cbfca55bf2 100644--- a/frontend-modern/src/components/SetupWizard/__tests__/WelcomeStep.test.tsx+++ b/frontend-modern/src/components/SetupWizard/__tests__/WelcomeStep.test.tsx@@ -59,9 +59,7 @@ describe('WelcomeStep', () => {/>));- await waitFor(() => {- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/security/status');- });+ expect(apiFetchJSONMock).not.toHaveBeenCalled();expect(screen.getByText('Unlock this Pulse server')).toBeInTheDocument();expect(screen.getByText('Create the admin account')).toBeInTheDocument();@@ -82,13 +80,13 @@ describe('WelcomeStep', () => {expect(screen.getByText('What this token does')).toBeInTheDocument();expect(screen.getByText(- 'This one-time bootstrap token only unlocks first-run setup on this Pulse server. Run the command above and paste the token string it prints. It is not your admin password and it is not the API token you will use after setup.',+ 'This one-time bootstrap token only unlocks first-run setup on this Pulse server. Run the matching command above and paste the token string it prints. It is not your admin password or long-lived API token.',),).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Verify bootstrap token →' })).toBeInTheDocument();});- it('renders environment-aware Docker unlock guidance when the runtime reports a container name', async () => {+ it('offers generic commands without requesting deployment details from the server', () => {apiFetchJSONMock.mockResolvedValue({bootstrapTokenPath: '/srv/pulse/bootstrap.token',isDocker: true,@@ -107,18 +105,18 @@ describe('WelcomeStep', () => {/>));- await waitFor(() => {- expect(screen.getByText('Docker deployment')).toBeInTheDocument();- });-expect(screen.getByText(- 'Pulse appears to be running in Docker as container "pulse-main". Run the command on the Docker host to print the one-time setup token from that container.',+ 'Run the command that matches how Pulse is installed. The server does not reveal deployment details before setup is unlocked.',),).toBeInTheDocument();+ expect(screen.getByText('sudo pulse bootstrap-token')).toBeInTheDocument();expect(- screen.getByText('docker exec pulse-main /app/pulse bootstrap-token'),+ screen.getByText('docker exec <pulse-container> /app/pulse bootstrap-token'),).toBeInTheDocument();+ expect(screen.getByText('pct exec <ctid> -- pulse bootstrap-token')).toBeInTheDocument();+ expect(screen.queryByText(/pulse-main/)).not.toBeInTheDocument();+ expect(apiFetchJSONMock).not.toHaveBeenCalled();});it('validates raw bootstrap tokens with an unauthenticated JSON request', async () => {@@ -138,10 +136,6 @@ describe('WelcomeStep', () => {/>));- await waitFor(() => {- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/security/status');- });-fireEvent.click(screen.getByRole('button', { name: 'Verify bootstrap token →' }));await waitFor(() => {@@ -173,14 +167,10 @@ describe('WelcomeStep', () => {/>));- await waitFor(() => {- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/security/status');- });-fireEvent.click(screen.getByRole('button', { name: 'Verify bootstrap token →' }));expect(showErrorMock).toHaveBeenCalledWith(- 'That looks like the encrypted .bootstrap_token file contents, not the raw setup token. Run the command above and paste the token string it prints.',+ 'That looks like the encrypted .bootstrap_token file contents, not the raw setup token. Run the matching command above and paste the token string it prints.',);expect(apiFetchMock).not.toHaveBeenCalled();expect(onNext).not.toHaveBeenCalled();diff --git a/frontend-modern/src/components/SetupWizard/steps/WelcomeStep.tsx b/frontend-modern/src/components/SetupWizard/steps/WelcomeStep.tsxindex e25d89b367..2a66b811ad 100644--- a/frontend-modern/src/components/SetupWizard/steps/WelcomeStep.tsx+++ b/frontend-modern/src/components/SetupWizard/steps/WelcomeStep.tsx@@ -1,8 +1,7 @@-import { Component, createMemo, createSignal, onMount, onCleanup, Show } from 'solid-js';+import { Component, createSignal, onCleanup, For, Show } from 'solid-js';import { t } from '@/i18n';import { showError, showSuccess } from '@/utils/toast';-import { apiFetch, apiFetchJSON } from '@/utils/apiClient';-import { logger } from '@/utils/logger';+import { apiFetch } from '@/utils/apiClient';import { copyToClipboard } from '@/utils/clipboard';import { ExternalTextLink } from '@/components/shared/ExternalTextLink';import { PRIVACY_DOC_URL } from '@/utils/docsLinks';@@ -18,52 +17,43 @@ interface WelcomeStepProps {export const WelcomeStep: Component<WelcomeStepProps> = (props) => {const [isValidating, setIsValidating] = createSignal(false);- const [isDocker, setIsDocker] = createSignal(false);- const [inContainer, setInContainer] = createSignal(false);- const [lxcCtid, setLxcCtid] = createSignal('');- const [dockerContainerName, setDockerContainerName] = createSignal('');- const [copied, setCopied] = createSignal(false);+ const [copiedCommand, setCopiedCommand] = createSignal<string | null>(null);let copiedTimer: ReturnType<typeof setTimeout> | undefined;onCleanup(() => {if (copiedTimer) clearTimeout(copiedTimer);});- const copyCommand = async () => {- const copied = await copyToClipboard(getTokenCommand());+ const bootstrapCommands = () => [+ {+ id: 'host',+ label: t('setup.welcome.deploymentLabel.direct'),+ command: 'sudo pulse bootstrap-token',+ },+ {+ id: 'docker',+ label: t('setup.welcome.deploymentLabel.docker'),+ command: 'docker exec <pulse-container> /app/pulse bootstrap-token',+ },+ {+ id: 'lxc',+ label: t('setup.welcome.deploymentLabel.lxc'),+ command: 'pct exec <ctid> -- pulse bootstrap-token',+ },+ ];++ const copyCommand = async (id: string, command: string) => {+ const copied = await copyToClipboard(command);if (copied) {- setCopied(true);+ setCopiedCommand(id);if (copiedTimer) clearTimeout(copiedTimer);- copiedTimer = setTimeout(() => setCopied(false), 2000);+ copiedTimer = setTimeout(() => setCopiedCommand(null), 2000);showSuccess(t('setup.welcome.success.commandCopied'));} else {showError(t('setup.welcome.error.copyCommandFailed'));}};- // Fetch bootstrap info on mount- const fetchBootstrapInfo = async () => {- try {- const data = await apiFetchJSON<{- bootstrapTokenPath?: string;- isDocker?: boolean;- inContainer?: boolean;- lxcCtid?: string;- dockerContainerName?: string;- }>('/api/security/status');- setIsDocker(data?.isDocker || false);- setInContainer(data?.inContainer || false);- setLxcCtid(data?.lxcCtid || '');- setDockerContainerName(data?.dockerContainerName || '');- } catch (error) {- logger.error('Failed to fetch bootstrap info:', error);- }- };-- onMount(() => {- void fetchBootstrapInfo();- });-const looksLikeBootstrapTokenSnapshot = (value: string) => {const trimmed = value.trim();if (!trimmed.startsWith('{')) {@@ -123,56 +113,6 @@ export const WelcomeStep: Component<WelcomeStepProps> = (props) => {}};- const getTokenCommand = () => {- if (isDocker()) {- return `docker exec ${dockerContainerName() || '<pulse-container>'} /app/pulse bootstrap-token`;- }- if (inContainer() && lxcCtid()) {- return `pct exec ${lxcCtid()} -- pulse bootstrap-token`;- }- if (inContainer()) {- return `pct exec <ctid> -- pulse bootstrap-token`;- }- return `sudo pulse bootstrap-token`;- };-- const deploymentLabel = createMemo(() => {- if (isDocker()) {- return t('setup.welcome.deploymentLabel.docker');- }- if (inContainer() && lxcCtid()) {- return t('setup.welcome.deploymentLabel.lxc');- }- if (inContainer()) {- return t('setup.welcome.deploymentLabel.containerized');- }- return t('setup.welcome.deploymentLabel.direct');- });-- const deploymentHint = createMemo(() => {- if (isDocker()) {- return dockerContainerName()- ? t('setup.welcome.deploymentHint.dockerNamed', {- containerName: dockerContainerName(),- })- : t('setup.welcome.deploymentHint.dockerUnnamed');- }- if (inContainer() && lxcCtid()) {- return t('setup.welcome.deploymentHint.lxc', { ctid: lxcCtid() });- }- if (inContainer()) {- return t('setup.welcome.deploymentHint.containerized');- }- return t('setup.welcome.deploymentHint.direct');- });-- const unlockHelp = createMemo(() => {- if (isDocker()) {- return t('setup.welcome.tokenHelp.docker');- }- return t('setup.welcome.tokenHelp.host');- });-return (<div class="text-center relative"><div class="mb-8 relative z-10">@@ -218,36 +158,38 @@ export const WelcomeStep: Component<WelcomeStepProps> = (props) => {<h3 class="text-lg font-semibold text-base-content mb-2 tracking-tight">{t('setup.welcome.unlockTitle')}</h3>- <p class="text-sm text-muted mb-5">{deploymentHint()}</p>+ <p class="text-sm text-muted mb-5">{t('setup.welcome.deploymentHint.choose')}</p>- <div class="mb-5">- <div class="bg-base rounded-md p-4 font-mono text-sm text-emerald-400 border border-border-subtle flex items-center justify-between">- <div class="flex items-center space-x-3 overflow-x-auto scrollbar-hide">- <Terminal class="w-4 h-4 flex-shrink-0" />- <code class="whitespace-nowrap select-all">{getTokenCommand()}</code>- </div>- <button- onClick={copyCommand}- class="ml-4 flex-shrink-0 p-2 rounded-md bg-surface hover:bg-slate-700 text-slate-300 hover:text-white transition-colors focus:outline-none focus:ring-0"- title={t('setup.welcome.copyCommandTitle')}- >- <Show when={copied()} fallback={<Copy class="w-4 h-4" />}>- <Check class="w-4 h-4 text-emerald-400" />- </Show>- </button>- </div>- <div class="mt-2 flex items-center gap-2 text-[11px] text-muted">- <span class="inline-flex items-center rounded-full bg-blue-50 px-2 py-0.5 font-semibold text-blue-700 dark:bg-blue-950/40 dark:text-blue-300">- {deploymentLabel()}- </span>- </div>+ <div class="mb-5 space-y-2">+ <For each={bootstrapCommands()}>+ {(item) => (+ <div class="bg-base rounded-md border border-border-subtle px-3 py-2.5">+ <div class="mb-1.5 text-[11px] font-semibold text-muted">{item.label}</div>+ <div class="flex items-center justify-between gap-3 font-mono text-sm text-emerald-400">+ <div class="flex min-w-0 items-center space-x-3 overflow-x-auto scrollbar-hide">+ <Terminal class="h-4 w-4 flex-shrink-0" />+ <code class="whitespace-nowrap select-all">{item.command}</code>+ </div>+ <button+ onClick={() => void copyCommand(item.id, item.command)}+ class="flex-shrink-0 rounded-md bg-surface p-2 text-slate-300 transition-colors hover:bg-slate-700 hover:text-white focus:outline-none focus:ring-0"+ title={`${t('setup.welcome.copyCommandTitle')}: ${item.label}`}+ >+ <Show when={copiedCommand() === item.id} fallback={<Copy class="h-4 w-4" />}>+ <Check class="h-4 w-4 text-emerald-400" />+ </Show>+ </button>+ </div>+ </div>+ )}+ </For></div><div class="mb-5 text-left"><div class="text-[11px] font-semibold uppercase tracking-wide text-muted">{t('setup.welcome.tokenHelp.title')}</div>- <p class="mt-1 text-sm text-muted">{unlockHelp()}</p>+ <p class="mt-1 text-sm text-muted">{t('setup.welcome.tokenHelp.generic')}</p></div><div class="space-y-3">diff --git a/frontend-modern/src/i18n/__tests__/i18n.test.ts b/frontend-modern/src/i18n/__tests__/i18n.test.tsindex 43060e0d2e..0a6c383654 100644--- a/frontend-modern/src/i18n/__tests__/i18n.test.ts+++ b/frontend-modern/src/i18n/__tests__/i18n.test.ts@@ -233,10 +233,17 @@ describe('i18n foundation', () => {it('keeps machine-facing identifiers unchanged in first-session monitoring catalog copy', () => {for (const locale of FIRST_LOCALIZATION_LOCALES) {const telemetryNotice = I18N_MESSAGES[locale]['setup.welcome.telemetryNotice.description'];+ const deploymentChoice = I18N_MESSAGES[locale]['setup.welcome.deploymentHint.choose'];+ const genericTokenHelp = I18N_MESSAGES[locale]['setup.welcome.tokenHelp.generic'];expect(telemetryNotice).toContain('Pulse');expect(telemetryNotice).toContain('PULSE_TELEMETRY=false');expect(telemetryNotice).not.toMatch(/anonymous/i);+ expect(deploymentChoice).toContain('Pulse');+ expect(deploymentChoice).not.toContain('Docker');+ expect(deploymentChoice).not.toContain('LXC');+ expect(genericTokenHelp).toContain('Pulse');+ expect(genericTokenHelp).toContain('API');expect(I18N_MESSAGES[locale]['setup.welcome.deploymentHint.dockerUnnamed']).toContain('<pulse-container>',);diff --git a/frontend-modern/src/i18n/messages.de.ts b/frontend-modern/src/i18n/messages.de.tsindex 7c3cdde9e1..057640a91e 100644--- a/frontend-modern/src/i18n/messages.de.ts+++ b/frontend-modern/src/i18n/messages.de.ts@@ -245,6 +245,8 @@ export const DE_MESSAGE_OVERRIDES = {'setup.welcome.action.verifyToken': 'Bootstrap-Token pruefen','setup.welcome.action.verifyingToken': 'Bootstrap-Token wird geprueft...','setup.welcome.copyCommandTitle': 'Befehl kopieren',+ 'setup.welcome.deploymentHint.choose':+ 'Fuehren Sie den Befehl aus, der zur Pulse-Installation passt. Der Server legt vor dem Entsperren der Einrichtung keine Bereitstellungsdetails offen.','setup.welcome.deploymentHint.containerized':'Pulse scheint in einer containerisierten Umgebung zu laufen. Fuehren Sie den Befehl auf dem Host aus, der den Container verwaltet, damit Sie das einmalige Setup-Token ausgeben koennen.','setup.welcome.deploymentHint.direct':@@ -265,7 +267,7 @@ export const DE_MESSAGE_OVERRIDES = {'setup.welcome.error.invalidBootstrapTokenResponse': 'Ungueltiges Bootstrap-Token','setup.welcome.error.missingBootstrapToken': 'Bitte geben Sie das Bootstrap-Token ein','setup.welcome.error.snapshotPaste':- 'Das sieht nach dem verschluesselten Inhalt der Datei .bootstrap_token aus, nicht nach dem rohen Setup-Token. Fuehren Sie den obigen Befehl aus und fuegen Sie die ausgegebene Token-Zeichenfolge ein.',+ 'Das sieht nach dem verschluesselten Inhalt der Datei .bootstrap_token aus, nicht nach dem rohen Setup-Token. Fuehren Sie den passenden Befehl aus und fuegen Sie die ausgegebene Token-Zeichenfolge ein.','setup.welcome.hero.coverage':'Verbinden Sie eine Plattform-API, installieren Sie Pulse Agent oder verwenden Sie beides fuer vollstaendige Abdeckung.','setup.welcome.hero.step.admin': 'Admin-Konto erstellen',@@ -286,6 +288,8 @@ export const DE_MESSAGE_OVERRIDES = {'Dieses einmalige Bootstrap-Token entsperrt nur die Ersteinrichtung. Fuehren Sie den obigen Befehl aus und fuegen Sie die ausgegebene Token-Zeichenfolge ein. Nach der Pruefung erstellen Sie das Admin-Konto, und Pulse erzeugt das langlebige API-Token separat.','setup.welcome.tokenHelp.host':'Dieses einmalige Bootstrap-Token entsperrt nur die Ersteinrichtung auf diesem Pulse-Server. Fuehren Sie den obigen Befehl aus und fuegen Sie die ausgegebene Token-Zeichenfolge ein. Es ist nicht Ihr Admin-Passwort und nicht das API-Token, das Sie nach der Einrichtung verwenden.',+ 'setup.welcome.tokenHelp.generic':+ 'Dieses einmalige Bootstrap-Token entsperrt nur die Ersteinrichtung auf diesem Pulse-Server. Fuehren Sie den passenden Befehl aus und fuegen Sie die ausgegebene Zeichenfolge ein. Es ist weder Ihr Admin-Passwort noch ein langlebiges API-Token.','setup.welcome.tokenHelp.title': 'Was dieses Token macht','setup.welcome.unlockTitle': 'Einrichtung entsperren','settings.general.appearance.title': 'Darstellung',diff --git a/frontend-modern/src/i18n/messages.es.ts b/frontend-modern/src/i18n/messages.es.tsindex 1e08da4112..495cee0b7c 100644--- a/frontend-modern/src/i18n/messages.es.ts+++ b/frontend-modern/src/i18n/messages.es.ts@@ -237,6 +237,8 @@ export const ES_MESSAGE_OVERRIDES = {'setup.welcome.action.verifyToken': 'Verificar token de bootstrap','setup.welcome.action.verifyingToken': 'Verificando token de bootstrap...','setup.welcome.copyCommandTitle': 'Copiar comando',+ 'setup.welcome.deploymentHint.choose':+ 'Ejecuta el comando que corresponda a cómo está instalado Pulse. El servidor no revela detalles del despliegue antes de desbloquear la configuración.','setup.welcome.deploymentHint.containerized':'Pulse parece ejecutarse en un entorno contenedorizado. Ejecuta el comando desde el host que administra el contenedor para imprimir el token de configuración de un solo uso.','setup.welcome.deploymentHint.direct':@@ -257,7 +259,7 @@ export const ES_MESSAGE_OVERRIDES = {'setup.welcome.error.invalidBootstrapTokenResponse': 'Token de bootstrap no válido','setup.welcome.error.missingBootstrapToken': 'Ingresa el token de bootstrap','setup.welcome.error.snapshotPaste':- 'Eso parece el contenido cifrado del archivo .bootstrap_token, no el token de configuración sin procesar. Ejecuta el comando anterior y pega la cadena de token que imprime.',+ 'Eso parece el contenido cifrado del archivo .bootstrap_token, no el token de configuración sin procesar. Ejecuta el comando correspondiente y pega la cadena de token que imprime.','setup.welcome.hero.coverage':'Conecta una API de plataforma, instala Pulse Agent o usa ambos para cobertura completa.','setup.welcome.hero.step.admin': 'Crear la cuenta de administrador',@@ -278,6 +280,8 @@ export const ES_MESSAGE_OVERRIDES = {'Este token de bootstrap de un solo uso solo desbloquea la configuración inicial. Ejecuta el comando anterior y pega la cadena de token que imprime. Después de la verificación, crearás la cuenta de administrador y Pulse generará el token de API de larga duración por separado.','setup.welcome.tokenHelp.host':'Este token de bootstrap de un solo uso solo desbloquea la configuración inicial en este servidor Pulse. Ejecuta el comando anterior y pega la cadena de token que imprime. No es tu contraseña de administrador ni el token de API que usarás después de la configuración.',+ 'setup.welcome.tokenHelp.generic':+ 'Este token de bootstrap de un solo uso solo desbloquea la configuración inicial en este servidor Pulse. Ejecuta el comando correspondiente y pega la cadena que imprime. No es tu contraseña de administrador ni un token de API de larga duración.','setup.welcome.tokenHelp.title': 'Qué hace este token','setup.welcome.unlockTitle': 'Desbloquear configuración','settings.general.appearance.title': 'Apariencia',diff --git a/frontend-modern/src/i18n/messages.ts b/frontend-modern/src/i18n/messages.tsindex 2f60256a4a..6084bc81fc 100644--- a/frontend-modern/src/i18n/messages.ts+++ b/frontend-modern/src/i18n/messages.ts@@ -231,6 +231,8 @@ export const EN_MESSAGES = {'setup.welcome.action.verifyToken': 'Verify bootstrap token','setup.welcome.action.verifyingToken': 'Verifying bootstrap token...','setup.welcome.copyCommandTitle': 'Copy command',+ 'setup.welcome.deploymentHint.choose':+ 'Run the command that matches how Pulse is installed. The server does not reveal deployment details before setup is unlocked.','setup.welcome.deploymentHint.containerized':'Pulse appears to be running in a containerized environment. Run the command from the host that manages the container so you can print the one-time setup token.','setup.welcome.deploymentHint.direct':@@ -251,7 +253,7 @@ export const EN_MESSAGES = {'setup.welcome.error.invalidBootstrapTokenResponse': 'Invalid bootstrap token','setup.welcome.error.missingBootstrapToken': 'Please enter the bootstrap token','setup.welcome.error.snapshotPaste':- 'That looks like the encrypted .bootstrap_token file contents, not the raw setup token. Run the command above and paste the token string it prints.',+ 'That looks like the encrypted .bootstrap_token file contents, not the raw setup token. Run the matching command above and paste the token string it prints.','setup.welcome.hero.coverage':'Connect a platform API, install Pulse Agent, or use both for full coverage.','setup.welcome.hero.step.admin': 'Create the admin account',@@ -272,6 +274,8 @@ export const EN_MESSAGES = {'This one-time bootstrap token only unlocks first-run setup. Run the command above and paste the token string it prints. After verification, you will create the admin account and Pulse will generate the long-lived API token separately.','setup.welcome.tokenHelp.host':'This one-time bootstrap token only unlocks first-run setup on this Pulse server. Run the command above and paste the token string it prints. It is not your admin password and it is not the API token you will use after setup.',+ 'setup.welcome.tokenHelp.generic':+ 'This one-time bootstrap token only unlocks first-run setup on this Pulse server. Run the matching command above and paste the token string it prints. It is not your admin password or long-lived API token.','setup.welcome.tokenHelp.title': 'What this token does','setup.welcome.unlockTitle': 'Unlock setup','settings.general.appearance.title': 'Appearance',@@ -613,6 +617,7 @@ export const FIRST_SESSION_MONITORING_MIGRATED_MESSAGE_KEYS = ['setup.welcome.action.verifyingToken','setup.welcome.copyCommandTitle','setup.welcome.deploymentHint.containerized',+ 'setup.welcome.deploymentHint.choose','setup.welcome.deploymentHint.direct','setup.welcome.deploymentHint.dockerNamed','setup.welcome.deploymentHint.dockerUnnamed',@@ -641,6 +646,7 @@ export const FIRST_SESSION_MONITORING_MIGRATED_MESSAGE_KEYS = ['setup.welcome.tokenHelp.afterVerify','setup.welcome.tokenHelp.docker','setup.welcome.tokenHelp.host',+ 'setup.welcome.tokenHelp.generic','setup.welcome.tokenHelp.title',] as const satisfies readonly I18nMessageKey[];diff --git a/frontend-modern/src/types/config.ts b/frontend-modern/src/types/config.tsindex 4cae62981a..7462ef9ce5 100644--- a/frontend-modern/src/types/config.ts+++ b/frontend-modern/src/types/config.ts@@ -120,19 +120,24 @@ export interface SecurityStatusPresentationPolicy {}export interface SecurityStatus {+ detailLevel?: 'public' | 'authenticated' | 'privileged';hasAuthentication: boolean;- apiTokenConfigured: boolean;- apiTokenHint: string;requiresAuth: boolean;- credentialsEncrypted: boolean;- exportProtected: boolean;- hasAuditLogging: boolean;- configuredButPendingRestart: boolean;+ ssoEnabled?: boolean;+ hideLocalLogin?: boolean; // Login discovery metadata+ ssoProviders?: SSOProviderInfo[];+ presentationPolicy?: SecurityStatusPresentationPolicy;+ apiTokenConfigured?: boolean;+ apiTokenHint?: string;+ credentialsEncrypted?: boolean;+ exportProtected?: boolean;+ hasAuditLogging?: boolean;+ configuredButPendingRestart?: boolean;unprotectedExportAllowed?: boolean;hasHTTPS?: boolean;- ssoEnabled?: boolean;publicAccess?: boolean;isPrivateNetwork?: boolean;+ isTrustedNetwork?: boolean;clientIP?: string;hasProxyAuth?: boolean;proxyAuthUsername?: string;@@ -144,20 +149,10 @@ export interface SecurityStatus {ssoSessionUsername?: string;ssoSessionDisplayName?: string;ssoLogoutURL?: string;- hideLocalLogin?: boolean; // Hide local login formagentUrl?: string; // URL for agent install commands (from PULSE_PUBLIC_URL or auto-detected)- // First run setup fields- bootstrapTokenPath?: string;- isDocker?: boolean;- inContainer?: boolean;- lxcCtid?: string;- dockerContainerName?: string;- // Multi-provider SSO- ssoProviders?: SSOProviderInfo[];// Token auth scopes (for kiosk/limited-access mode)tokenScopes?: string[];sessionCapabilities?: SecurityStatusSessionCapabilities;- presentationPolicy?: SecurityStatusPresentationPolicy;settingsCapabilities?: SecurityStatusSettingsCapabilities;}diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 838abf96d7..b066355528 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -10200,8 +10200,11 @@ func TestContract_ResetFirstRunSecurityClearsEnvBackedStatus(t *testing.T) {if got, _ := payload["hasAuthentication"].(bool); got {t.Fatalf("hasAuthentication = %v, want false", payload["hasAuthentication"])}- if got, _ := payload["bootstrapTokenPath"].(string); strings.TrimSpace(got) == "" {- t.Fatalf("bootstrapTokenPath = %v, want non-empty", payload["bootstrapTokenPath"])+ if _, ok := payload["bootstrapTokenPath"]; ok {+ t.Fatalf("unauthenticated status exposed bootstrapTokenPath = %v", payload["bootstrapTokenPath"])+ }+ if got := payload["detailLevel"]; got != securityStatusDetailPublic {+ t.Fatalf("detailLevel = %v, want %q", got, securityStatusDetailPublic)}}@@ -10242,7 +10245,7 @@ func TestContract_SetupScriptURLResponseJSONSnapshot(t *testing.T) {assertJSONSnapshot(t, got, want)}-func TestContract_SecurityStatusIncludesSessionCapabilitiesDemoMode(t *testing.T) {+func TestContract_PublicSecurityStatusIncludesDemoPresentationPolicy(t *testing.T) {cfg := newTestConfigWithTokens(t)cfg.DemoMode = true@@ -10260,12 +10263,11 @@ func TestContract_SecurityStatusIncludesSessionCapabilitiesDemoMode(t *testing.Tt.Fatalf("decode security status payload: %v", err)}- sessionCapabilities, ok := payload["sessionCapabilities"].(map[string]any)- if !ok {- t.Fatalf("sessionCapabilities = %#v, want object", payload["sessionCapabilities"])+ if got := payload["detailLevel"]; got != securityStatusDetailPublic {+ t.Fatalf("detailLevel = %v, want %q", got, securityStatusDetailPublic)}- if got, _ := sessionCapabilities["demoMode"].(bool); !got {- t.Fatalf("sessionCapabilities.demoMode = %v, want true", sessionCapabilities["demoMode"])+ if _, ok := payload["sessionCapabilities"]; ok {+ t.Fatalf("public security status exposed sessionCapabilities = %#v", payload["sessionCapabilities"])}presentationPolicy, ok := payload["presentationPolicy"].(map[string]any)diff --git a/internal/api/router_routes_auth_security.go b/internal/api/router_routes_auth_security.goindex 676838ecd1..918318fdf6 100644--- a/internal/api/router_routes_auth_security.go+++ b/internal/api/router_routes_auth_security.go@@ -13,7 +13,6 @@ import ("github.com/crewjam/saml""github.com/rcourtman/pulse-go-rewrite/internal/config"- "github.com/rcourtman/pulse-go-rewrite/internal/system""github.com/rcourtman/pulse-go-rewrite/pkg/auth""github.com/rcourtman/pulse-go-rewrite/pkg/extensions""github.com/rs/zerolog/log"@@ -21,6 +20,129 @@ import (const featureSSOKey = "sso"+const (+ securityStatusDetailPublic = "public"+ securityStatusDetailAuthenticated = "authenticated"+ securityStatusDetailPrivileged = "privileged"+)++type securityStatusSSOProvider struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Type string `json:"type"`+ DisplayName string `json:"displayName,omitempty"`+ IconURL string `json:"iconUrl,omitempty"`+ LoginURL string `json:"loginUrl"`+}++// publicSecurityStatusResponse is the intentional unauthenticated contract for+// login and first-run routing. Deployment, network, credential, and operator+// configuration details must never be added to this type.+type publicSecurityStatusResponse struct {+ DetailLevel string `json:"detailLevel"`+ HasAuthentication bool `json:"hasAuthentication"`+ RequiresAuth bool `json:"requiresAuth"`+ SSOEnabled bool `json:"ssoEnabled"`+ HideLocalLogin bool `json:"hideLocalLogin"`+ SSOProviders []securityStatusSSOProvider `json:"ssoProviders,omitempty"`+ PresentationPolicy securityStatusPresentationPolicy `json:"presentationPolicy"`+}++type authenticatedSecurityStatusResponse struct {+ publicSecurityStatusResponse+ HasProxyAuth bool `json:"hasProxyAuth"`+ ProxyAuthLogoutURL string `json:"proxyAuthLogoutURL"`+ ProxyAuthUsername string `json:"proxyAuthUsername"`+ ProxyAuthIsAdmin bool `json:"proxyAuthIsAdmin"`+ SSOSessionUsername string `json:"ssoSessionUsername"`+ SSOSessionDisplayName string `json:"ssoSessionDisplayName"`+ SSOLogoutURL string `json:"ssoLogoutURL,omitempty"`+ TokenScopes []string `json:"tokenScopes,omitempty"`+ SessionCapabilities securityStatusSessionCapabilities `json:"sessionCapabilities"`+ SettingsCapabilities securityStatusSettingsCapabilities `json:"settingsCapabilities"`+}++type privilegedSecurityStatusResponse struct {+ authenticatedSecurityStatusResponse+ APITokenConfigured bool `json:"apiTokenConfigured"`+ APITokenHint string `json:"apiTokenHint"`+ ExportProtected bool `json:"exportProtected"`+ UnprotectedExportAllowed bool `json:"unprotectedExportAllowed"`+ ConfiguredButPendingRestart bool `json:"configuredButPendingRestart"`+ HasAuditLogging bool `json:"hasAuditLogging"`+ CredentialsEncrypted bool `json:"credentialsEncrypted"`+ HasHTTPS bool `json:"hasHTTPS"`+ ClientIP string `json:"clientIP"`+ IsPrivateNetwork bool `json:"isPrivateNetwork"`+ IsTrustedNetwork bool `json:"isTrustedNetwork"`+ PublicAccess bool `json:"publicAccess"`+ AuthUsername string `json:"authUsername"`+ AuthLastModified string `json:"authLastModified"`+ AgentURL string `json:"agentUrl"`+}++func (r *Router) securityAuthenticationConfigured() bool {+ if r == nil || r.config == nil {+ return false+ }+ if (r.config.AuthUser != "" && r.config.AuthPass != "") ||+ r.config.HasAPITokens() ||+ r.config.ProxyAuthSecret != "" ||+ r.hostedMode {+ return true+ }+ ssoCfg := r.ensureSSOConfig()+ return ssoCfg != nil && ssoCfg.HasEnabledProviders()+}++func (r *Router) authorizeSecurityRestart(w http.ResponseWriter, req *http.Request) bool {+ clientIP := GetClientIP(req)+ if r.securityAuthenticationConfigured() {+ if !CheckAuth(r.config, w, req) {+ log.Warn().Str("ip", clientIP).Msg("Unauthenticated apply-restart attempt blocked")+ return false+ }+ if r.config.ProxyAuthSecret != "" {+ if valid, username, isAdmin := CheckProxyAuth(r.config, req); valid && !isAdmin {+ log.Warn().+ Str("ip", clientIP).+ Str("username", username).+ Msg("Non-admin user attempted service restart")+ http.Error(w, "Admin privileges required", http.StatusForbidden)+ return false+ }+ }+ return ensureSettingsWriteScope(r.config, w, req)+ }++ if r.bootstrapTokenHash == "" {+ log.Error().Msg("Bootstrap setup token unavailable; refusing unauthenticated service restart")+ http.Error(w, "Bootstrap token unavailable", http.StatusServiceUnavailable)+ return false+ }++ if limiter := r.bootstrapTokenLimiter(); limiter != nil {+ if allowed, retryAfter := limiter.allowAt(clientIP, time.Now()); !allowed {+ retrySeconds := int(retryAfter.Round(time.Second) / time.Second)+ if retrySeconds < 1 {+ retrySeconds = 1+ }+ w.Header().Set("Retry-After", fmt.Sprintf("%d", retrySeconds))+ http.Error(w, "Too many bootstrap token attempts", http.StatusTooManyRequests)+ return false+ }+ }++ providedToken := strings.TrimSpace(req.Header.Get(bootstrapTokenHeader))+ if providedToken == "" || !r.bootstrapTokenValid(providedToken) {+ log.Warn().Str("ip", clientIP).Msg("Rejected apply-restart attempt without a valid bootstrap token")+ http.Error(w, "Valid bootstrap token required", http.StatusUnauthorized)+ return false+ }++ return true+}+func (r *Router) registerAuthSecurityInstallRoutes() {// API routesr.mux.HandleFunc("/api/health", r.handleHealth)@@ -177,213 +299,158 @@ func (r *Router) registerAuthSecurityInstallRoutes() {r.handleDeleteAPIToken(w, req)}))r.mux.HandleFunc("/api/security/status", func(w http.ResponseWriter, req *http.Request) {- if req.Method == http.MethodGet {- w.Header().Set("Content-Type", "application/json")-- // Check for basic auth configuration- // Check both environment variables and loaded config- ssoCfg := r.ensureSSOConfig()- enabledProviders := []config.SSOProvider{}- if ssoCfg != nil {- enabledProviders = ssoCfg.GetEnabledProviders()- }- hasEnabledSSO := len(enabledProviders) > 0- var primaryOIDCConfig *config.OIDCProviderConfig- for i := range enabledProviders {- if enabledProviders[i].Type == config.SSOProviderTypeOIDC && enabledProviders[i].OIDC != nil {- primaryOIDCConfig = enabledProviders[i].OIDC- break- }- }- hasAuthentication := os.Getenv("PULSE_AUTH_USER") != "" ||- os.Getenv("REQUIRE_AUTH") == "true" ||- r.config.AuthUser != "" ||- r.config.AuthPass != "" ||- r.config.HasAPITokens() ||- r.config.ProxyAuthSecret != "" ||- r.hostedMode ||- hasEnabledSSO-- // Check if .env file exists but hasn't been loaded yet (pending restart)- configuredButPendingRestart := false- envPath := resolveAuthEnvPath(r.config.ConfigPath)-- authLastModified := ""- if stat, err := os.Stat(envPath); err == nil {- authLastModified = stat.ModTime().UTC().Format(time.RFC3339)- if !hasAuthentication && r.config.AuthUser == "" && r.config.AuthPass == "" {- configuredButPendingRestart = true- }- }-- // Check for audit logging- hasAuditLogging := os.Getenv("PULSE_AUDIT_LOG") == "true" || os.Getenv("AUDIT_LOG_ENABLED") == "true"-- // Credentials are always encrypted in current implementation- credentialsEncrypted := true+ if req.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }- // Check network context- clientIP := GetClientIP(req)- isPrivateNetwork := isPrivateIP(clientIP)+ w.Header().Set("Content-Type", "application/json")- // Get trusted networks from environment- trustedNetworks := []string{}- if nets := os.Getenv("PULSE_TRUSTED_NETWORKS"); nets != "" {- trustedNetworks = strings.Split(nets, ",")- }- isTrustedNetwork := isTrustedNetwork(clientIP, trustedNetworks)-- // Determine whether the caller is authenticated before exposing sensitive fields.- // SECURITY: Do NOT check bearer or query-string tokens here. This endpoint is- // intentionally limited to session cookies, proxy auth, and X-API-Token.- authSnapshot := r.buildSecurityStatusAuthSnapshot(req)- isAuthenticated := authSnapshot.authenticated- tokenScopes := authSnapshot.tokenScopes()-- // Create token hint if token exists (only revealed to authenticated callers)- apiTokenHint := ""- if isAuthenticated {- apiTokenHint = r.config.PrimaryAPITokenHint()+ ssoCfg := r.ensureSSOConfig()+ enabledProviders := []config.SSOProvider{}+ if ssoCfg != nil {+ enabledProviders = ssoCfg.GetEnabledProviders()+ }+ hasEnabledSSO := len(enabledProviders) > 0+ var primaryOIDCConfig *config.OIDCProviderConfig+ ssoProviders := make([]securityStatusSSOProvider, 0, len(enabledProviders))+ for i := range enabledProviders {+ provider := enabledProviders[i]+ if primaryOIDCConfig == nil && provider.Type == config.SSOProviderTypeOIDC && provider.OIDC != nil {+ primaryOIDCConfig = provider.OIDC}-- // Check for proxy auth- hasProxyAuth := r.config.ProxyAuthSecret != ""- proxyAuthUsername := ""- proxyAuthIsAdmin := false- if hasProxyAuth {- // Check if current request has valid proxy auth- if valid, username, isAdmin := CheckProxyAuth(r.config, req); valid {- proxyAuthUsername = username- proxyAuthIsAdmin = isAdmin- }+ info := securityStatusSSOProvider{+ ID: provider.ID,+ Name: provider.Name,+ Type: string(provider.Type),+ DisplayName: provider.DisplayName,+ IconURL: provider.IconURL,}-- // Check for SSO-backed session- ssoSessionUsername := ""- ssoSessionDisplayName := ""- if hasEnabledSSO {- if cookie, err := readSessionCookie(req); err == nil && cookie.Value != "" {- if ValidateSession(cookie.Value) {- session := GetSessionStore().GetSession(cookie.Value)- if session != nil && (strings.TrimSpace(session.OIDCIssuer) != "" || strings.TrimSpace(session.SAMLProviderID) != "") {- ssoSessionUsername = GetSessionUsername(cookie.Value)- ssoSessionDisplayName = GetSessionDisplayUsername(cookie.Value)- }- }- }+ if info.DisplayName == "" {+ info.DisplayName = provider.Name}-- requiresAuth := r.config.HasAPITokens() ||- (r.config.AuthUser != "" && r.config.AuthPass != "") ||- r.config.ProxyAuthSecret != "" ||- hasEnabledSSO-- // Resolve the public URL for agent install commands- // If PULSE_PUBLIC_URL is configured, use that; otherwise derive from request- agentURL := r.resolvePublicURL(req)-- status := map[string]interface{}{- "apiTokenConfigured": r.config.HasAPITokens(),- "apiTokenHint": apiTokenHint,- "requiresAuth": requiresAuth,- "exportProtected": r.config.HasAPITokens() || os.Getenv("ALLOW_UNPROTECTED_EXPORT") != "true",- "unprotectedExportAllowed": os.Getenv("ALLOW_UNPROTECTED_EXPORT") == "true",- "hasAuthentication": hasAuthentication,- "configuredButPendingRestart": configuredButPendingRestart,- "hasAuditLogging": hasAuditLogging,- "credentialsEncrypted": credentialsEncrypted,- "hasHTTPS": req.TLS != nil || strings.EqualFold(req.Header.Get("X-Forwarded-Proto"), "https"),- "clientIP": clientIP,- "isPrivateNetwork": isPrivateNetwork,- "isTrustedNetwork": isTrustedNetwork,- "publicAccess": !isPrivateNetwork,- "hasProxyAuth": hasProxyAuth,- "proxyAuthLogoutURL": r.config.ProxyAuthLogoutURL,- "proxyAuthUsername": proxyAuthUsername,- "proxyAuthIsAdmin": proxyAuthIsAdmin,- "authUsername": "",- "authLastModified": "",- "ssoEnabled": hasEnabledSSO,- "ssoSessionUsername": ssoSessionUsername,- "ssoSessionDisplayName": ssoSessionDisplayName,- "hideLocalLogin": r.config.HideLocalLogin,- "agentUrl": agentURL,- "sessionCapabilities": r.securityStatusSessionCapabilities(req.Context()),- "presentationPolicy": r.securityStatusPresentationPolicy(),- "settingsCapabilities": r.securityStatusSettingsCapabilitiesFromSnapshot(authSnapshot),+ switch provider.Type {+ case config.SSOProviderTypeOIDC:+ info.LoginURL = "/api/oidc/" + provider.ID + "/login"+ case config.SSOProviderTypeSAML:+ info.LoginURL = "/api/saml/" + provider.ID + "/login"}+ ssoProviders = append(ssoProviders, info)+ }- if isAuthenticated {- status["authUsername"] = r.config.AuthUser- status["authLastModified"] = authLastModified- }+ hasAuthentication := os.Getenv("PULSE_AUTH_USER") != "" ||+ os.Getenv("REQUIRE_AUTH") == "true" ||+ r.config.AuthUser != "" ||+ r.config.AuthPass != "" ||+ r.config.HasAPITokens() ||+ r.config.ProxyAuthSecret != "" ||+ r.hostedMode ||+ hasEnabledSSO+ requiresAuth := r.config.HasAPITokens() ||+ (r.config.AuthUser != "" && r.config.AuthPass != "") ||+ r.config.ProxyAuthSecret != "" ||+ hasEnabledSSO++ publicStatus := publicSecurityStatusResponse{+ DetailLevel: securityStatusDetailPublic,+ HasAuthentication: hasAuthentication,+ RequiresAuth: requiresAuth,+ SSOEnabled: hasEnabledSSO,+ HideLocalLogin: r.config.HideLocalLogin,+ SSOProviders: ssoProviders,+ PresentationPolicy: r.securityStatusPresentationPolicy(),+ }- // Include token scopes when authenticated via API token (for kiosk mode UI)- if len(tokenScopes) > 0 {- status["tokenScopes"] = tokenScopes- }+ // Bearer and query-string tokens are intentionally not accepted here. The+ // public endpoint exposes only login discovery until a session, proxy+ // identity, or X-API-Token proves the caller's authority.+ authSnapshot := r.buildSecurityStatusAuthSnapshot(req)+ if !authSnapshot.authenticated {+ _ = json.NewEncoder(w).Encode(publicStatus)+ return+ }- if primaryOIDCConfig != nil {- status["ssoLogoutURL"] = primaryOIDCConfig.LogoutURL+ hasProxyAuth := r.config.ProxyAuthSecret != ""+ proxyAuthUsername := ""+ proxyAuthIsAdmin := false+ if authSnapshot.authMethod == "proxy" {+ if valid, username, isAdmin := CheckProxyAuth(r.config, req); valid {+ proxyAuthUsername = username+ proxyAuthIsAdmin = isAdmin}+ }- // Include SSO providers for login page discovery- if len(enabledProviders) > 0 {- baseURL := r.config.PublicURL- if baseURL == "" {- baseURL = ""- }- type ssoProviderInfo struct {- ID string `json:"id"`- Name string `json:"name"`- Type string `json:"type"`- DisplayName string `json:"displayName,omitempty"`- IconURL string `json:"iconUrl,omitempty"`- LoginURL string `json:"loginUrl"`- }- var ssoProviders []ssoProviderInfo- for _, p := range enabledProviders {- info := ssoProviderInfo{- ID: p.ID,- Name: p.Name,- Type: string(p.Type),- DisplayName: p.DisplayName,- IconURL: p.IconURL,- }- if info.DisplayName == "" {- info.DisplayName = p.Name- }- switch p.Type {- case config.SSOProviderTypeOIDC:- info.LoginURL = "/api/oidc/" + p.ID + "/login"- case config.SSOProviderTypeSAML:- info.LoginURL = "/api/saml/" + p.ID + "/login"- }- ssoProviders = append(ssoProviders, info)+ ssoSessionUsername := ""+ ssoSessionDisplayName := ""+ if hasEnabledSSO {+ if cookie, err := readSessionCookie(req); err == nil && cookie.Value != "" && ValidateSession(cookie.Value) {+ session := GetSessionStore().GetSession(cookie.Value)+ if session != nil && (strings.TrimSpace(session.OIDCIssuer) != "" || strings.TrimSpace(session.SAMLProviderID) != "") {+ ssoSessionUsername = GetSessionUsername(cookie.Value)+ ssoSessionDisplayName = GetSessionDisplayUsername(cookie.Value)}- status["ssoProviders"] = ssoProviders}+ }- // Add bootstrap token location for first-run setup UI- if r.bootstrapTokenHash != "" {- status["bootstrapTokenPath"] = r.bootstrapTokenPath- status["isDocker"] = os.Getenv("PULSE_DOCKER") == "true"- status["inContainer"] = system.InContainer()- // Try auto-detection first, then fall back to env override- if ctid := system.DetectLXCCTID(); ctid != "" {- status["lxcCtid"] = ctid- } else if envCtid := os.Getenv("PULSE_LXC_CTID"); envCtid != "" {- status["lxcCtid"] = envCtid- }- if containerName := system.DetectDockerContainerName(); containerName != "" {- status["dockerContainerName"] = containerName- }+ publicStatus.DetailLevel = securityStatusDetailAuthenticated+ authenticatedStatus := authenticatedSecurityStatusResponse{+ publicSecurityStatusResponse: publicStatus,+ HasProxyAuth: authSnapshot.authMethod == "proxy",+ ProxyAuthLogoutURL: r.config.ProxyAuthLogoutURL,+ ProxyAuthUsername: proxyAuthUsername,+ ProxyAuthIsAdmin: proxyAuthIsAdmin,+ SSOSessionUsername: ssoSessionUsername,+ SSOSessionDisplayName: ssoSessionDisplayName,+ TokenScopes: authSnapshot.tokenScopes(),+ SessionCapabilities: r.securityStatusSessionCapabilities(req.Context()),+ SettingsCapabilities: r.securityStatusSettingsCapabilitiesFromSnapshot(authSnapshot),+ }+ if primaryOIDCConfig != nil && ssoSessionUsername != "" {+ authenticatedStatus.SSOLogoutURL = primaryOIDCConfig.LogoutURL+ }+ if !authSnapshot.canAccessAdminSurface(config.ScopeSettingsRead) {+ _ = json.NewEncoder(w).Encode(authenticatedStatus)+ return+ }++ configuredButPendingRestart := false+ authLastModified := ""+ if stat, err := os.Stat(resolveAuthEnvPath(r.config.ConfigPath)); err == nil {+ authLastModified = stat.ModTime().UTC().Format(time.RFC3339)+ if !hasAuthentication && r.config.AuthUser == "" && r.config.AuthPass == "" {+ configuredButPendingRestart = true}+ }- json.NewEncoder(w).Encode(status)- } else {- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ clientIP := GetClientIP(req)+ isPrivateNetwork := isPrivateIP(clientIP)+ trustedNetworks := []string{}+ if nets := os.Getenv("PULSE_TRUSTED_NETWORKS"); nets != "" {+ trustedNetworks = strings.Split(nets, ",")}++ authenticatedStatus.DetailLevel = securityStatusDetailPrivileged+ authenticatedStatus.HasProxyAuth = hasProxyAuth+ status := privilegedSecurityStatusResponse{+ authenticatedSecurityStatusResponse: authenticatedStatus,+ APITokenConfigured: r.config.HasAPITokens(),+ APITokenHint: r.config.PrimaryAPITokenHint(),+ ExportProtected: r.config.HasAPITokens() || os.Getenv("ALLOW_UNPROTECTED_EXPORT") != "true",+ UnprotectedExportAllowed: os.Getenv("ALLOW_UNPROTECTED_EXPORT") == "true",+ ConfiguredButPendingRestart: configuredButPendingRestart,+ HasAuditLogging: os.Getenv("PULSE_AUDIT_LOG") == "true" || os.Getenv("AUDIT_LOG_ENABLED") == "true",+ CredentialsEncrypted: true,+ HasHTTPS: req.TLS != nil || strings.EqualFold(req.Header.Get("X-Forwarded-Proto"), "https"),+ ClientIP: clientIP,+ IsPrivateNetwork: isPrivateNetwork,+ IsTrustedNetwork: isTrustedNetwork(clientIP, trustedNetworks),+ PublicAccess: !isPrivateNetwork,+ AuthUsername: r.config.AuthUser,+ AuthLastModified: authLastModified,+ AgentURL: r.resolvePublicURL(req),+ }++ _ = json.NewEncoder(w).Encode(status)})// Quick security setup route - using fixed version@@ -397,40 +464,10 @@ func (r *Router) registerAuthSecurityInstallRoutes() {r.mux.HandleFunc("/api/security/validate-token", r.HandleValidateAPIToken)// Apply security restart endpoint- // SECURITY: Require admin auth to prevent DoS via unauthenticated service restartsr.mux.HandleFunc("/api/security/apply-restart", func(w http.ResponseWriter, req *http.Request) {if req.Method == http.MethodPost {- // SECURITY: Require authentication - this endpoint can trigger service restart (DoS risk)- // Allow if: (1) auth is not configured yet (initial setup), or (2) caller is admin-authenticated- authConfigured := (r.config.AuthUser != "" && r.config.AuthPass != "") ||- r.config.HasAPITokens() ||- r.config.ProxyAuthSecret != "" ||- (func() bool {- ssoCfg := r.ensureSSOConfig()- return ssoCfg != nil && ssoCfg.HasEnabledProviders()- })()- if authConfigured {- if !CheckAuth(r.config, w, req) {- log.Warn().- Str("ip", GetClientIP(req)).- Msg("Unauthenticated apply-restart attempt blocked")- return // CheckAuth already wrote the error- }- // Check proxy auth for admin status (session users with basic auth are implicitly admin)- if r.config.ProxyAuthSecret != "" {- if valid, username, isAdmin := CheckProxyAuth(r.config, req); valid && !isAdmin {- log.Warn().- Str("ip", GetClientIP(req)).- Str("username", username).- Msg("Non-admin user attempted service restart")- http.Error(w, "Admin privileges required", http.StatusForbidden)- return- }- }- // Require settings:write scope for API tokens- if !ensureSettingsWriteScope(r.config, w, req) {- return- }+ if !r.authorizeSecurityRestart(w, req) {+ return}// Only allow restart if we're running under systemd (safer)diff --git a/internal/api/security_first_run_reset_test.go b/internal/api/security_first_run_reset_test.goindex 84eaff08c9..d7db86e515 100644--- a/internal/api/security_first_run_reset_test.go+++ b/internal/api/security_first_run_reset_test.go@@ -125,7 +125,10 @@ func TestResetFirstRunSecurityClearsEnvBackedAuthFromStatus(t *testing.T) {if got, _ := payload["hasAuthentication"].(bool); got {t.Fatalf("expected hasAuthentication=false after reset, got %v", payload["hasAuthentication"])}- if got, _ := payload["bootstrapTokenPath"].(string); strings.TrimSpace(got) == "" {- t.Fatalf("expected bootstrapTokenPath in unauthenticated status, got %v", payload["bootstrapTokenPath"])+ if _, ok := payload["bootstrapTokenPath"]; ok {+ t.Fatalf("unauthenticated status exposed bootstrapTokenPath: %v", payload["bootstrapTokenPath"])+ }+ if got := payload["detailLevel"]; got != securityStatusDetailPublic {+ t.Fatalf("detailLevel = %v, want %q", got, securityStatusDetailPublic)}}diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex c46a7dd7ba..1aee9b1617 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -5,6 +5,7 @@ import ("context""encoding/json""errors"+ "fmt""net/http""net/http/httptest""os"@@ -3705,6 +3706,50 @@ func TestApplyRestartRequiresAuthInAPIMode(t *testing.T) {}}+func TestApplyRestartRequiresBootstrapTokenBeforeAuthentication(t *testing.T) {+ t.Setenv("INVOCATION_ID", "")+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")+ resetTrustedProxyConfig()++ cfg := newTestConfigWithTokens(t)+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")+ bootstrapToken, _, _, err := loadOrCreateBootstrapToken(cfg.DataPath)+ if err != nil {+ t.Fatalf("load bootstrap token: %v", err)+ }++ tests := []struct {+ name string+ token string+ wantStatus int+ }{+ {name: "missing token", wantStatus: http.StatusUnauthorized},+ {name: "invalid token", token: "invalid-token", wantStatus: http.StatusUnauthorized},+ {name: "valid token", token: bootstrapToken, wantStatus: http.StatusOK},+ }++ for i, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := httptest.NewRequest(http.MethodPost, "/api/security/apply-restart", nil)+ if tt.token == bootstrapToken {+ req.RemoteAddr = "127.0.0.1:54321"+ } else {+ req.RemoteAddr = fmt.Sprintf("198.51.100.%d:54321", 101+i)+ }+ if tt.token != "" {+ req.Header.Set(bootstrapTokenHeader, tt.token)+ }+ rec := httptest.NewRecorder()++ router.Handler().ServeHTTP(rec, req)++ if rec.Code != tt.wantStatus {+ t.Fatalf("status = %d, want %d (%s)", rec.Code, tt.wantStatus, rec.Body.String())+ }+ })+ }+}+func TestApplyRestartRequiresSettingsWriteScope(t *testing.T) {rawToken := "apply-restart-scope-token-123.12345678"record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)@@ -4181,7 +4226,7 @@ func TestSecurityStatusHidesBootstrapTokenWhenAuthConfigured(t *testing.T) {}}-func TestSecurityStatusIncludesBootstrapTokenWhenUnauthenticated(t *testing.T) {+func TestSecurityStatusOmitsPrivilegedDetailsWhenUnauthenticated(t *testing.T) {cfg := newTestConfigWithTokens(t)router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")@@ -4198,9 +4243,30 @@ func TestSecurityStatusIncludesBootstrapTokenWhenUnauthenticated(t *testing.T) {if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {t.Fatalf("decode response: %v", err)}- path, ok := payload["bootstrapTokenPath"].(string)- if !ok || path == "" {- t.Fatalf("expected bootstrapTokenPath to be present for unauthenticated setup")+ if got := payload["detailLevel"]; got != securityStatusDetailPublic {+ t.Fatalf("detailLevel = %v, want %q", got, securityStatusDetailPublic)+ }+ if got, _ := payload["hasAuthentication"].(bool); got {+ t.Fatalf("hasAuthentication = %v, want false", payload["hasAuthentication"])+ }+ privilegedKeys := []string{+ "apiTokenConfigured",+ "apiTokenHint",+ "authLastModified",+ "bootstrapTokenPath",+ "clientIP",+ "agentUrl",+ "hasAuditLogging",+ "isDocker",+ "inContainer",+ "lxcCtid",+ "dockerContainerName",+ "settingsCapabilities",+ }+ for _, key := range privilegedKeys {+ if _, ok := payload[key]; ok {+ t.Errorf("unauthenticated status exposed privileged field %q", key)+ }}}@@ -4260,12 +4326,51 @@ func TestSecurityStatusAcceptsTokenHeader(t *testing.T) {if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {t.Fatalf("decode response: %v", err)}- if hint, ok := payload["apiTokenHint"].(string); !ok || hint != cfg.PrimaryAPITokenHint() {- t.Fatalf("expected apiTokenHint %q, got %v", cfg.PrimaryAPITokenHint(), payload["apiTokenHint"])+ if _, ok := payload["apiTokenHint"]; ok {+ t.Fatalf("scoped token status exposed apiTokenHint: %v", payload["apiTokenHint"])}if scopes, ok := payload["tokenScopes"].([]interface{}); !ok || len(scopes) == 0 {t.Fatalf("expected tokenScopes to be present when authenticated via API token")}+ if got := payload["detailLevel"]; got != securityStatusDetailAuthenticated {+ t.Fatalf("detailLevel = %v, want %q", got, securityStatusDetailAuthenticated)+ }+ if _, ok := payload["clientIP"]; ok {+ t.Fatalf("scoped token status exposed privileged clientIP: %v", payload["clientIP"])+ }+}++func TestSecurityStatusExposesPrivilegedDetailsToSettingsReadToken(t *testing.T) {+ rawToken := "status-privileged-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.RemoteAddr = "198.51.100.63:54321"+ req.Header.Set("X-API-Token", rawToken)+ rec := httptest.NewRecorder()+ router.Handler().ServeHTTP(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200 (%s)", rec.Code, rec.Body.String())+ }++ var payload map[string]interface{}+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if got := payload["detailLevel"]; got != securityStatusDetailPrivileged {+ t.Fatalf("detailLevel = %v, want %q", got, securityStatusDetailPrivileged)+ }+ if got, _ := payload["clientIP"].(string); got != "198.51.100.63" {+ t.Fatalf("clientIP = %q, want %q", got, "198.51.100.63")+ }+ if _, ok := payload["apiTokenConfigured"]; !ok {+ t.Fatal("privileged status omitted apiTokenConfigured")+ }+ if got, _ := payload["apiTokenHint"].(string); got != cfg.PrimaryAPITokenHint() {+ t.Fatalf("apiTokenHint = %q, want %q", got, cfg.PrimaryAPITokenHint())+ }}func TestAuditVerifyRequiresAuthInAPIMode(t *testing.T) {diff --git a/internal/api/security_setup_fix.go b/internal/api/security_setup_fix.goindex ec99456d40..4321eed279 100644--- a/internal/api/security_setup_fix.go+++ b/internal/api/security_setup_fix.go@@ -7,8 +7,11 @@ import ("os""os/exec""path/filepath"+ "strconv""strings""time"+ "unicode"+ "unicode/utf8""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/updates"@@ -47,6 +50,85 @@ func validateBcryptHash(hash string) error {return nil}+const maxLocalAuthUsernameRunes = 128++func validateLocalAuthUsername(username string) error {+ if username == "" {+ return fmt.Errorf("username is required")+ }+ if username != strings.TrimSpace(username) {+ return fmt.Errorf("username must not begin or end with whitespace")+ }+ if utf8.RuneCountInString(username) > maxLocalAuthUsernameRunes {+ return fmt.Errorf("username must be at most %d characters", maxLocalAuthUsernameRunes)+ }++ for _, r := range username {+ if unicode.IsLetter(r) || unicode.IsDigit(r) || strings.ContainsRune("._@+-", r) {+ continue+ }+ return fmt.Errorf("username may contain only letters, numbers, periods, underscores, hyphens, plus signs, and @")+ }++ return nil+}++func quoteAuthEnvValue(value string) (string, error) {+ if strings.ContainsAny(value, "'\r\n\x00") {+ return "", fmt.Errorf("auth environment value contains unsupported characters")+ }+ return "'" + value + "'", nil+}++func renderAuthEnvFile(generatedAt time.Time, username, hashedPassword string) ([]byte, error) {+ quotedUsername, err := quoteAuthEnvValue(username)+ if err != nil {+ return nil, err+ }+ quotedPassword, err := quoteAuthEnvValue(hashedPassword)+ if err != nil {+ return nil, err+ }++ return []byte(fmt.Sprintf(`# Auto-generated by Pulse Quick Security Setup+# Generated on %s+# IMPORTANT: Keep authentication values quoted.+PULSE_AUTH_USER=%s+PULSE_AUTH_PASS=%s+PULSE_AUDIT_LOG=true+`, generatedAt.Format(time.RFC3339), quotedUsername, quotedPassword)), nil+}++func quoteSystemdEnvironment(name, value string) (string, error) {+ if strings.ContainsAny(name, "=\r\n\x00") || strings.ContainsAny(value, "\r\n\x00") {+ return "", fmt.Errorf("systemd environment value contains unsupported characters")+ }+ return "Environment=" + strconv.Quote(name+"="+value), nil+}++func renderSystemdAuthOverride(generatedAt time.Time, username, hashedPassword string) ([]byte, error) {+ usernameLine, err := quoteSystemdEnvironment("PULSE_AUTH_USER", username)+ if err != nil {+ return nil, err+ }+ passwordLine, err := quoteSystemdEnvironment("PULSE_AUTH_PASS", hashedPassword)+ if err != nil {+ return nil, err+ }+ auditLine, err := quoteSystemdEnvironment("PULSE_AUDIT_LOG", "true")+ if err != nil {+ return nil, err+ }++ return []byte(fmt.Sprintf(`# Auto-generated by Pulse Quick Security Setup+# Generated on %s+[Service]+%s+%s+%s+`, generatedAt.Format(time.RFC3339), usernameLine, passwordLine, auditLine)), nil+}+// isRunningAsRoot checks if the process has root privilegesfunc isRunningAsRoot() bool {return os.Geteuid() == 0@@ -280,11 +362,15 @@ func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {log.Info().Msg("Quick security setup invoked with force=true - rotating credentials")}- // Validate inputs+ // Validate inputs before any runtime or persistent security state changes.if setupRequest.Username == "" || setupRequest.Password == "" || setupRequest.APIToken == "" {http.Error(w, "Username, password, and API token are required", http.StatusBadRequest)return}+ if err := validateLocalAuthUsername(setupRequest.Username); err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }// Validate password complexityif err := internalauth.ValidatePasswordComplexity(setupRequest.Password); err != nil {@@ -306,6 +392,12 @@ func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {http.Error(w, "Failed to process password", http.StatusInternalServerError)return}+ authEnvContent, err := renderAuthEnvFile(time.Now(), setupRequest.Username, hashedPassword)+ if err != nil {+ log.Error().Err(err).Msg("Failed to encode authentication configuration")+ http.Error(w, "Failed to save security configuration", http.StatusInternalServerError)+ return+ }// Store the raw API token for displaying to the userrawAPIToken := setupRequest.APIToken@@ -379,16 +471,7 @@ func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {// Choose appropriate method based on environmentif isDocker {- // CRITICAL: Use single quotes to prevent shell expansion of $ in bcrypt hash- envContent := fmt.Sprintf(`# Auto-generated by Pulse Quick Security Setup-# Generated on %s-# IMPORTANT: Do not remove the single quotes around the password hash!-PULSE_AUTH_USER='%s'-PULSE_AUTH_PASS='%s'-PULSE_AUDIT_LOG=true-`, time.Now().Format(time.RFC3339), setupRequest.Username, hashedPassword)-- envPath, err := writeAuthEnvFile(r.config.ConfigPath, r.config.DataPath, []byte(envContent))+ envPath, err := writeAuthEnvFile(r.config.ConfigPath, r.config.DataPath, authEnvContent)if err != nil {log.Error().Err(err).Msg("Failed to write .env file in Docker")http.Error(w, "Failed to save security configuration", http.StatusInternalServerError)@@ -414,14 +497,7 @@ PULSE_AUDIT_LOG=true// Systemd but not root (ProxmoxVE script scenario)// Don't attempt sudo, just save config and provide instructions- envContent := fmt.Sprintf(`# Auto-generated by Pulse Quick Security Setup-# Generated on %s-PULSE_AUTH_USER='%s'-PULSE_AUTH_PASS='%s'-PULSE_AUDIT_LOG=true-`, time.Now().Format(time.RFC3339), setupRequest.Username, hashedPassword)-- envPath, err := writeAuthEnvFile(r.config.ConfigPath, r.config.DataPath, []byte(envContent))+ envPath, err := writeAuthEnvFile(r.config.ConfigPath, r.config.DataPath, authEnvContent)if err != nil {log.Error().Err(err).Msg("Failed to write .env file")http.Error(w, "Failed to save security configuration", http.StatusInternalServerError)@@ -457,15 +533,14 @@ PULSE_AUDIT_LOG=truereturn}- overrideContent := fmt.Sprintf(`# Auto-generated by Pulse Quick Security Setup-# Generated on %s-[Service]-Environment="PULSE_AUTH_USER=%s"-Environment="PULSE_AUTH_PASS=%s"-Environment="PULSE_AUDIT_LOG=true"-`, time.Now().Format(time.RFC3339), setupRequest.Username, hashedPassword)+ overrideContent, err := renderSystemdAuthOverride(time.Now(), setupRequest.Username, hashedPassword)+ if err != nil {+ log.Error().Err(err).Msg("Failed to encode systemd authentication configuration")+ http.Error(w, "Failed to save security configuration", http.StatusInternalServerError)+ return+ }- if err := os.WriteFile(overridePath, []byte(overrideContent), 0644); err != nil {+ if err := os.WriteFile(overridePath, overrideContent, 0644); err != nil {log.Error().Err(err).Msg("Failed to write systemd override")http.Error(w, "Failed to write systemd override", http.StatusInternalServerError)return@@ -493,14 +568,7 @@ Environment="PULSE_AUDIT_LOG=true"} else {// Manual installation or development- envContent := fmt.Sprintf(`# Auto-generated by Pulse Quick Security Setup-# Generated on %s-PULSE_AUTH_USER='%s'-PULSE_AUTH_PASS='%s'-PULSE_AUDIT_LOG=true-`, time.Now().Format(time.RFC3339), setupRequest.Username, hashedPassword)-- envPath, err := writeAuthEnvFile(r.config.ConfigPath, r.config.DataPath, []byte(envContent))+ envPath, err := writeAuthEnvFile(r.config.ConfigPath, r.config.DataPath, authEnvContent)if err != nil {log.Error().Err(err).Msg("Failed to write .env file")// Still return success with manual instructionsdiff --git a/internal/api/security_setup_fix_test.go b/internal/api/security_setup_fix_test.goindex a602e71996..c32fe659eb 100644--- a/internal/api/security_setup_fix_test.go+++ b/internal/api/security_setup_fix_test.go@@ -2,6 +2,7 @@ package apiimport ("context"+ "encoding/json""errors""net/http""net/http/httptest"@@ -148,6 +149,87 @@ func TestQuickSecuritySetupRequiresBootstrapToken(t *testing.T) {}}+func TestQuickSecuritySetupRejectsUnsafeUsernamesBeforeStateChanges(t *testing.T) {+ tests := []struct {+ name string+ username string+ }{+ {name: "systemd directive injection", username: "admin\n[Service]\nExecStartPre=/bin/false"},+ {name: "environment quote injection", username: "admin'\nPULSE_AUTH_PASS='attacker"},+ {name: "leading whitespace", username: " admin"},+ {name: "unsupported punctuation", username: "admin;restart"},+ {name: "too long", username: strings.Repeat("a", maxLocalAuthUsernameRunes+1)},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")+ resetTrustedProxyConfig()++ dataDir := t.TempDir()+ cfg := &config.Config{DataPath: dataDir, ConfigPath: dataDir}+ router := &Router{+ config: cfg,+ persistence: config.NewConfigPersistence(dataDir),+ }+ router.initializeBootstrapToken()+ InitPersistentAuthStores(dataDir)+ bootstrapToken, _, _, err := bootstrap.Load(dataDir)+ if err != nil {+ t.Fatalf("load bootstrap token: %v", err)+ }++ body, err := json.Marshal(map[string]string{+ "username": tt.username,+ "password": "StrongPass!1",+ "apiToken": strings.Repeat("ab", 24),+ })+ if err != nil {+ t.Fatalf("marshal request: %v", err)+ }++ authLimiter.Reset("198.51.100.91")+ req := httptest.NewRequest(http.MethodPost, "/api/security/quick-setup", strings.NewReader(string(body)))+ req.RemoteAddr = "198.51.100.91:54321"+ req.Header.Set(bootstrapTokenHeader, bootstrapToken)+ rec := httptest.NewRecorder()++ handleQuickSecuritySetupFixed(router)(rec, req)++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400 (%s)", rec.Code, rec.Body.String())+ }+ if !strings.Contains(strings.ToLower(rec.Body.String()), "username") {+ t.Fatalf("response = %q, want username validation error", rec.Body.String())+ }+ if cfg.AuthUser != "" || cfg.AuthPass != "" || cfg.HasAPITokens() {+ t.Fatalf("unsafe username changed runtime auth state: user=%q pass_set=%v tokens=%d", cfg.AuthUser, cfg.AuthPass != "", len(cfg.APITokens))+ }+ if _, err := os.Stat(resolveAuthEnvPath(dataDir)); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("unsafe username created auth env file: %v", err)+ }+ })+ }+}++func TestAuthConfigurationRenderersRejectStructuralInjection(t *testing.T) {+ if _, err := quoteAuthEnvValue("admin'\nPULSE_AUTH_PASS='attacker"); err == nil {+ t.Fatal("quoteAuthEnvValue accepted structural injection")+ }+ if _, err := quoteSystemdEnvironment("PULSE_AUTH_USER", "admin\nExecStartPre=/bin/false"); err == nil {+ t.Fatal("quoteSystemdEnvironment accepted structural injection")+ }++ generatedAt := time.Date(2026, time.July, 10, 0, 0, 0, 0, time.UTC)+ content, err := renderSystemdAuthOverride(generatedAt, "[email protected]", "$2a$10$abcdefghijklmnopqrstuvwxyzABCDE1234567890123456789012")+ if err != nil {+ t.Fatalf("renderSystemdAuthOverride: %v", err)+ }+ if strings.Count(string(content), "\nEnvironment=") != 3 {+ t.Fatalf("rendered override does not contain exactly three environment directives:\n%s", content)+ }+}+func TestValidateBootstrapTokenEndpoint(t *testing.T) {t.Setenv("PULSE_TRUSTED_PROXY_CIDRS", "")resetTrustedProxyConfig()diff --git a/internal/api/security_status_additional_test.go b/internal/api/security_status_additional_test.goindex b232c2bd03..a2428779c2 100644--- a/internal/api/security_status_additional_test.go+++ b/internal/api/security_status_additional_test.go@@ -533,10 +533,13 @@ func TestSecurityStatusRestrictsSessionCapabilitiesToConfiguredAdmin(t *testing.func TestSecurityStatusIncludesDemoModeSessionCapabilities(t *testing.T) {t.Setenv("PULSE_DATA_DIR", t.TempDir())- cfg := &config.Config{DemoMode: true}+ rawToken := "status-demo-capabilities-token-123.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)+ cfg := &config.Config{DemoMode: true, APITokens: []config.APITokenRecord{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)@@ -568,7 +571,9 @@ func TestSecurityStatusIncludesDemoModeSessionCapabilities(t *testing.T) {func TestSecurityStatusIncludesAssistantAvailability(t *testing.T) {t.Setenv("PULSE_DATA_DIR", t.TempDir())- cfg := &config.Config{}+ rawToken := "status-assistant-capabilities-token-123.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsRead}, nil)+ cfg := &config.Config{APITokens: []config.APITokenRecord{record}}router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")persistence := router.aiSettingsHandler.getPersistence(context.Background())@@ -583,6 +588,7 @@ func TestSecurityStatusIncludesAssistantAvailability(t *testing.T) {}req := httptest.NewRequest(http.MethodGet, "/api/security/status", nil)+ req.Header.Set("X-API-Token", rawToken)rec := httptest.NewRecorder()router.Handler().ServeHTTP(rec, req)