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
Fix Agent Doctor credential recovery
rcourtman6c150973b4b8
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 3a7fa898ce..3bef267635 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -703,10 +703,14 @@ by Infrastructure.Authentication repair is a distinct lifecycle handoff, not a successfulupgrade. When a reported host still names a token record that is absent from-the server inventory or has expired, Agent Doctor must raise a critical-credential reason and may offer `repair_authentication` only for a recognized,-unambiguous local runtime. The copied Unix repair command mints a fresh scoped-agent credential and transports it through an ephemeral `--token-file`; an+the server inventory, has expired, or lacks `agent:exec` while that host reports+Pulse command execution enabled, Agent Doctor must raise a critical typed+credential reason (`agent_credential_missing`, `agent_credential_expired`, or+`agent_exec_scope_missing`) and may offer `repair_authentication` only for a+recognized, unambiguous local runtime. A disconnected command channel alone is+not proof of a scope defect. The copied Unix repair command mints a fresh scoped+agent credential—including command scope when the affected host reports it+enabled—and transports it through an ephemeral `--token-file`; anordinary version-only Unix update stays tokenless and recovers the installedcredential from installer-owned state. If two different host agent IDs reportthe same non-empty machine ID and equivalent hostname, both installations stay@@ -715,8 +719,11 @@ not collapse them into one apparent agent or choose one generic local service:authentication and upgrade handoffs fail closed until the duplicateinstallation is resolved or an installation-specific path exists. Finally,local process health cannot override server authentication: a definitive-registration 401/403 makes `scripts/install.sh` complete with the non-zero-`auth_rejected` result instead of printing installation or upgrade success.+registration 401 or missing-scope 403 makes `scripts/install.sh` complete with+the non-zero `auth_rejected` result instead of printing installation or upgrade+success. An ownership-mismatch 403 is not definitive during first-use binding;+the installer must prefer the persisted agent ID and continue its bounded+verification window rather than mislabeling a fresh token.Agent lifecycle and fleet-operation surfaces may consume`POST /api/actions/plan` for resource capability planning, but the action plan@@ -2186,6 +2193,13 @@ command transport, update policy, or fleet lifecycle authority.execution is granted only by backend-issued host-bound runtime tokens or byfirst-use Proxmox install-command tokens carrying the governed installmetadata that the command websocket can bind to one agent identity.+ The browser must treat the chosen command-execution option and the minted+ token as one atomic copy state. Changing that option after minting locks all+ copyable commands, requests the matching replacement scope, and unlocks only+ after the replacement arrives; failure restores the complete previous+ option/token pair. It must never render `--enable-commands` with the prior+ non-exec token, even briefly, and must not accept another option change while+ a token request is in flight.7. Keep first-session lifecycle handoff explicit: the live setup completionsurface in `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`must route the primary CTA into `/settings/infrastructure?add=pick`, framediff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 37042c83e2..f4e4667333 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -6196,10 +6196,13 @@ The canonical connections projection must validate a host's non-empty`status/rotation="invalid"`; expired records project invalid top-level statuswith expired health and rotation. Agent Doctor preserves those ledger factseven when its structured snapshot lags. Structured diagnostics add the stable-`agent_credential_missing`, `agent_credential_expired`, and-`duplicate_host_agent_installation` reason codes plus the+`agent_credential_missing`, `agent_credential_expired`,+`agent_exec_scope_missing`, and `duplicate_host_agent_installation` reason codes plus the`repair_authentication` handoff. The browser may render a fresh scoped-token-file repair only when that action is supported. A duplicate-installation+token-file repair only when that action is supported. The exec-scope reason is+emitted only when an active token record lacks `agent:exec` while the host's+reported `commandsEnabled` state is true; command-channel disconnection by+itself remains transport evidence rather than credential evidence. A duplicate-installationreason always blocks generic repair command rendering, while retaining eachconnection row and its peer evidence so UI composition never selects one staleidentity as the machine's sole agent. When the token inventory is deliberatelydiff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex 04c4da2895..e620ebfd81 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -348,8 +348,13 @@ upgrade, update, release, or artifact-selection behavior.Post-install verification must not declare server registrationunconfirmed from a single lookup: the local `/readyz` gate flips before theagent's first report cycle completes, so the installer polls the server- lookup for a bounded retry window before warning, while a definitive- 401/403 token rejection still short-circuits immediately (#1644).+ lookup for a bounded retry window before warning. Once the canonical local+ agent ID exists, verification must prefer it over hostname so a previous+ registration cannot impersonate the just-installed process. A 401 or a 403+ caused by missing reporting scope is definitive and short-circuits; a 403+ `agent_lookup_forbidden` during post-start verification is a transient+ first-use ownership race and must keep polling for the new ownership rather+ than falsely rejecting the fresh install credential (#1644).When Proxmox integration is enabled, the installer must also report theagent's Proxmox registration outcome in its own output: it waits a boundedwindow on the agent state directory, surfaces the reason recorded in adiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 11988ba12d..99d0976276 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -2611,6 +2611,13 @@ last successful heartbeat alone. A live host whose reported `TokenID` nolonger resolves emits `agent_credential_missing`; a resolved but expired recordemits `agent_credential_expired`; both are critical and expose a boundedauthentication-repair handoff only when the runtime family is safely known.+An active record is not sufficient when the host reports Pulse command+execution enabled: if that record lacks `agent:exec`, the diagnostic emits the+critical `agent_exec_scope_missing` reason and exposes the same bounded+authentication-repair handoff. Command-channel disconnection alone is not+credential evidence and must not synthesize this reason. The token inventory+therefore retains the active record's normalized scopes for read-only+diagnosis rather than reducing active credentials to an existence set.Monitoring also compares live host-agent generations without merging them: twodifferent host IDs with the same non-empty machine ID and equivalent hostnameeach receive `duplicate_host_agent_installation` plus bounded peer evidence.diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.jsonindex 0cd81e97fe..5d7a8b0e37 100644--- a/frontend-modern/browser-verification.json+++ b/frontend-modern/browser-verification.json@@ -1,26 +1,23 @@{"version": 1,- "base_sha": "70f7ca9f6f2b1b176d117a8f4f3315e3538847ac",- "verified_at": "2026-08-09T12:25:13Z",+ "base_sha": "cd63e0848abe224967ff5429e56bfcf06c5860c6",+ "verified_at": "2026-08-09T19:42:00Z","result": "passed","changed_paths": [- "frontend-modern/src/api/rbac.ts",- "frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx",- "frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx",- "frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts",- "frontend-modern/src/types/rbac.ts",- "frontend-modern/src/utils/rbacPresentation.ts"+ "frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx",+ "frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx",+ "frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts",+ "frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx"],"content_sha256": {- "frontend-modern/src/api/rbac.ts": "9e4c2366443ba770e4b0755aa095686c44c44ec9d4b7a6bb90fb5359082982ba",- "frontend-modern/src/components/Settings/UserAssignmentsDialog.tsx": "1a7990c833e6ddd98a5cceb6476f894745674b957cfa26d1fdfa820299a8a68b",- "frontend-modern/src/components/Settings/UserAssignmentsPanel.tsx": "8e2a89c845572591a73eac622effd137e5e9e96741ce700a4168f9b8e58a3ca2",- "frontend-modern/src/components/Settings/useUserAssignmentsPanelState.ts": "8497e59dffc7f19a50aff30b787ca1236b354b7404890774871712efbc4bea15",- "frontend-modern/src/types/rbac.ts": "1c08ceffc1aea3f4975455db2c4d92774060fa2d0ce7088e116930b85b5c2fbc",- "frontend-modern/src/utils/rbacPresentation.ts": "07b2affbeda8921da3def1063141fd4d1074ed02a8939288d06644376ed768ba"+ "frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx": "99368f451d9153a735180d0f3889bf0d7983af6bce2f9e3012f87b7ad594d265",+ "frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx": "595c0509e2c93574ccea5669f06c5143d4ece7e4772906b8d41d04392e0431cc",+ "frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts": "baf908e004f6805b4dfcd013a139ee822a7e91589fa4d086a9440cabfb6c812a",+ "frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx": "9a1a2c2d9f7712e1fbf4dbc462d75fe56c79c63aed809196e780b74e2cbd0381"},"routes": [- "/settings/security-users"+ "/settings/infrastructure?add=linux-host",+ "/settings/infrastructure?agentDoctor=1"],"viewports": [{@@ -33,18 +30,16 @@}],"states": [- "An isolated Pro development runtime showed an OIDC user by the mutable display name Alice Example, with [email protected] and OIDC · okta as secondary identity context while retaining the stable sso:oidc:okta:browser-subject authorization principal.",- "The Manage Access dialog used the readable identity in its title and exposed email and provider context while preserving the current Viewer role and effective-permissions preview.",- "The removal confirmation clearly stated that roles and active Pulse sessions are removed, that the upstream identity-provider account is not disabled, and that a later authorized SSO login can recreate the Pulse identity.",- "A successful removal returned the filtered list to no matching SSO user and displayed User access removed for Alice Example; an attempted self-removal retained the admin row and displayed You cannot remove your own user access.",- "At 390x844 the page remained exactly 390 pixels wide, the shared table shell provided horizontal access to both actions, and the 358-pixel confirmation dialog stayed inside the viewport without clipping or horizontal document overflow."+ "The host installer started with a reporting-only token and copy-ready commands, then immediately locked and removed the previous credential from every rendered command while a command-enabled replacement token was pending.",+ "Successful replacement restored the advanced options with Pulse command execution checked and exposed only commands containing the new exec-scoped token.",+ "A failed attempt to remove command execution restored the complete prior checked option and exec-scoped token pair, retained copy-ready commands, and surfaced the minting error instead of composing mixed state.",+ "Agent Doctor rendered agent_exec_scope_missing as a critical credential diagnosis with explicit agent:exec evidence and a token-gated host-local authentication repair.",+ "After Agent Doctor generated the repair credential, the request carried enableCommands=true and the unlocked repair command used an ephemeral token file plus --enable-commands."],"interactions": [- "Searched by the mutable SSO email claim and confirmed the readable identity, provider label, stable principal, Viewer role, Manage Access action, and Remove action at 1440x900.",- "Opened Manage Access, inspected the readable identity and role state, dismissed it with Escape, and confirmed focus returned to Manage Access.",- "Opened Remove, clicked the backdrop and confirmed the non-dismissible destructive dialog remained open, then dismissed it with Escape and confirmed focus returned to Remove.",- "At 390x844 horizontally scrolled the shared data-grid shell to reach Manage Access and Remove, opened the confirmation, verified initial focus on Cancel and in-viewport placement, cancelled it, and confirmed focus returned to Remove.",- "Reopened the narrow confirmation and removed Alice Example through the live DELETE endpoint, then verified the row disappeared and the success notification appeared.",- "Seeded the current admin identity in the isolated fixture, attempted self-removal through the same confirmation, and verified the backend denial remained non-destructive and surfaced the specific self-removal message."+ "At 1440x900 generated a reporting token, opened advanced install options, enabled Pulse command execution, held the replacement API response, and confirmed the command surface locked with no old token visible before releasing the exec-scoped replacement.",+ "At 390x844 forced the next replacement request to fail, confirmed the checkbox and prior token rolled back atomically, and verified the page had no document-level horizontal overflow and the error remained visible.",+ "Opened Agent Doctor against a structured agent_exec_scope_missing response, expanded the critical agent row, verified the typed reason and evidence, generated its repair token, and confirmed the backend request explicitly selected command scope.",+ "Verified the unlocked Agent Doctor authentication-repair command contained the fresh credential, token-file transport, and --enable-commands, then repeated the critical row inspection at 390x844 with no document-level horizontal overflow."]}diff --git a/frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx b/frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsxindex b8755a1365..d572d732c1 100644--- a/frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx+++ b/frontend-modern/src/components/Settings/InfrastructureAgentDoctorPage.tsx@@ -137,8 +137,10 @@ export const InfrastructureAgentDoctorPage: Component<InfrastructureAgentDoctorPconst target = selectedTokenTarget();if (!target) return;const previousToken = operations.currentToken();- operations.setEnableCommands(Boolean(target.connection?.agentIdentity?.commandsEnabled));- await operations.handleGenerateToken();+ await operations.setEnableCommands(Boolean(target.connection?.agentIdentity?.commandsEnabled));+ if (!operations.currentToken() || operations.currentToken() === previousToken) {+ await operations.handleGenerateToken();+ }const generatedToken = operations.currentToken();if (generatedToken && generatedToken !== previousToken) {setTokenMintedForTargetKey(target.key);diff --git a/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx b/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsxindex 2036f0f129..16fca61e13 100644--- a/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx+++ b/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx@@ -541,7 +541,7 @@ export const InfrastructureInstallerSection: Component<InfrastructureInstallerSe</Show><label- class="inline-flex cursor-pointer items-center gap-2 text-sm text-base-content"+ class={`inline-flex items-center gap-2 text-sm text-base-content ${state.isGeneratingToken() ? 'cursor-wait opacity-70' : 'cursor-pointer'}`}title="Skip TLS certificate verification (for self-signed certificates)"><input@@ -560,7 +560,10 @@ export const InfrastructureInstallerSection: Component<InfrastructureInstallerSe<inputtype="checkbox"checked={state.enableCommands()}- onChange={(event) => state.setEnableCommands(event.currentTarget.checked)}+ disabled={state.isGeneratingToken()}+ onChange={(event) =>+ void state.setEnableCommands(event.currentTarget.checked)+ }class="rounded text-blue-600 focus:ring-blue-500"/>Enable Pulse command execution (Patrol actions and Proxmox LXC Docker inventory)diff --git a/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsModel.test.tsx b/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsModel.test.tsxindex 007c9fdee5..574f618f33 100644--- a/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsModel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/InfrastructureOperationsModel.test.tsx@@ -365,6 +365,21 @@ describe('infrastructure operations model', () => {expect(useInfrastructureInstallStateSource).not.toContain('AGENT_REPORT_SCOPE');});+ it('keeps install token scope and rendered command options atomic', () => {+ const lockIndex = useInfrastructureInstallStateSource.indexOf('setCurrentToken(null);');+ const replacementIndex = useInfrastructureInstallStateSource.indexOf(+ 'generateInstallToken(source, { notifySuccess: false })',+ );++ expect(lockIndex).toBeGreaterThan(-1);+ expect(replacementIndex).toBeGreaterThan(lockIndex);+ expect(useInfrastructureInstallStateSource).toContain(+ 'setEnableCommands(previousEnableCommands);',+ );+ expect(useInfrastructureInstallStateSource).toContain('setCurrentToken(supersededToken);');+ expect(infrastructureInstallerSectionSource).toContain('disabled={state.isGeneratingToken()}');+ });+it('keeps infrastructure install and operations surfaces free of retired commercial telemetry wrappers', () => {for (const source of [infrastructureOperationsModelSource,diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.tsindex 5f85d1e64e..b5d8d6008b 100644--- a/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureAgentDoctorModel.test.ts@@ -174,6 +174,57 @@ describe('Agent Doctor model', () => {expect(target.commandBlockedReason).toBeUndefined();});+ it('turns a command credential without exec scope into a token-gated repair', () => {+ const connection = connectionFixture({+ agentUpdateAvailable: false,+ agentVersion: '6.2.0',+ expectedAgentVersion: '6.2.0',+ agentIdentity: {+ hostname: 'host-1',+ platform: 'ubuntu',+ architecture: 'amd64',+ commandsEnabled: true,+ },+ fleet: { versionDrift: 'current' } as Connection['fleet'],+ });+ const [target] = collectInfrastructureAgentDoctorTargets({+ rows: [rowFixture(connection)],+ connections: [connection],+ diagnostics: [+ diagnosticFixture({+ status: 'critical',+ version: '6.2.0',+ reasons: [+ {+ code: 'agent_exec_scope_missing',+ severity: 'critical',+ message: 'Command execution is enabled but agent:exec is missing.',+ },+ ],+ repairActions: [+ {+ code: 'repair_authentication',+ label: 'Repair authentication',+ description: 'Generate a command-enabled scoped credential.',+ supported: true,+ platform: 'linux',+ },+ ],+ }),+ ],+ diagnosticsAvailable: true,+ targetVersion: '6.2.0',+ });++ expect(target).toMatchObject({+ status: 'critical',+ needsUpdate: false,+ needsCredentialRepair: true,+ commandPlatform: 'linux',+ });+ expect(target.commandBlockedReason).toBeUndefined();+ });+it('fails closed when duplicate host installations make the repair target ambiguous', () => {const connection = connectionFixture();const [target] = collectInfrastructureAgentDoctorTargets({diff --git a/frontend-modern/src/components/Settings/__tests__/useInfrastructureOperationsState.branchcov0722pm.test.tsx b/frontend-modern/src/components/Settings/__tests__/useInfrastructureOperationsState.branchcov0722pm.test.tsxindex 8e89884577..5680268886 100644--- a/frontend-modern/src/components/Settings/__tests__/useInfrastructureOperationsState.branchcov0722pm.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/useInfrastructureOperationsState.branchcov0722pm.test.tsx@@ -404,6 +404,73 @@ describe('useInfrastructureOperationsState command-building closures', () => {});});+ describe('install token and command-option atomicity', () => {+ it('locks copyable commands until a command-enabled replacement token is ready', async () => {+ const { state, dispose } = mountHook();+ await flushAsync();+ await state.handleGenerateToken();++ let resolveReplacement!: (value: {+ token: string;+ record: {+ id: string;+ name: string;+ prefix: string;+ suffix: string;+ createdAt: string;+ };+ }) => void;+ mocks.createHostAgentInstallToken.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveReplacement = resolve;+ }),+ );++ const replacement = state.setEnableCommands(true);++ expect(state.enableCommands()).toBe(true);+ expect(state.currentToken()).toBeNull();+ expect(state.commandsUnlocked()).toBe(false);+ expect(mocks.createHostAgentInstallToken).toHaveBeenLastCalledWith({+ enableCommands: true,+ name: expect.any(String),+ });++ resolveReplacement({+ token: 'tok-command',+ record: {+ id: 'rec-command',+ name: 'Agent',+ prefix: 'pul',+ suffix: 'exec',+ createdAt: '2026-01-01',+ },+ });+ await replacement;++ expect(state.currentToken()).toBe('tok-command');+ expect(state.commandsUnlocked()).toBe(true);+ expect(mocks.securityDeleteToken).toHaveBeenCalledWith('rec-1');+ dispose();+ });++ it('restores the previous complete command state when replacement minting fails', async () => {+ const { state, dispose } = mountHook();+ await flushAsync();+ await state.handleGenerateToken();+ mocks.createHostAgentInstallToken.mockRejectedValueOnce(new Error('mint failed'));++ await state.setEnableCommands(true);++ expect(state.enableCommands()).toBe(false);+ expect(state.currentToken()).toBe('tok-1');+ expect(state.commandsUnlocked()).toBe(true);+ expect(mocks.securityDeleteToken).not.toHaveBeenCalled();+ dispose();+ });+ });+describe('getCanonicalConnectionAgentId (via getAgentConnectionUpgradeCommand windows arm)', () => {it('resolves to empty for a non-agent connection (no PULSE_AGENT_ID env)', async () => {const { state, dispose } = mountHook();diff --git a/frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts b/frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.tsindex b46af57830..f2d794a238 100644--- a/frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts+++ b/frontend-modern/src/components/Settings/infrastructureAgentUpdateCommandsModel.ts@@ -541,6 +541,7 @@ const doctorTargetFromBinding = (['agent_credential_missing','agent_credential_expired',+ 'agent_exec_scope_missing','ledger_credential_invalid','ledger_unauthorized',].includes(reason.code),diff --git a/frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx b/frontend-modern/src/components/Settings/useInfrastructureInstallState.tsxindex 2ebf7153a2..015c65ce3b 100644--- a/frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx+++ b/frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx@@ -248,7 +248,7 @@ Pulse prepares the first-host install token from setup so you can move straightconst generateInstallToken = async (source: 'manual' | 'setup_handoff',options: { notifySuccess?: boolean } = {},- ) => {+ ): Promise<boolean> => {setIsGeneratingToken(true);try {// The server owns install-token semantics. It decides the scopes from@@ -263,7 +263,7 @@ Pulse prepares the first-host install token from setup so you can move straight});if (disposed) {- return;+ return false;}setCurrentToken(token);setLatestRecord(record);@@ -279,9 +279,10 @@ Pulse prepares the first-host install token from setup so you can move straight4000,);}+ return true;} catch (err) {if (disposed) {- return;+ return false;}logger.error('Failed to generate agent token', err);if (source === 'setup_handoff') {@@ -292,6 +293,7 @@ Pulse prepares the first-host install token from setup so you can move straight6000,);}+ return false;} finally {if (!disposed) {setIsGeneratingToken(false);@@ -311,27 +313,52 @@ Pulse prepares the first-host install token from setup so you can move straight// Toggling command execution changes which scopes the token needs, and an// already-minted token cannot be upgraded. Regenerate it so the copied// command always carries a token that matches the checkbox (#1586).- const handleEnableCommandsChange = (value: boolean) => {+ const handleEnableCommandsChange = async (value: boolean): Promise<void> => {if (value === enableCommands()) return;+ if (isGeneratingToken()) {+ notificationStore.info(+ 'Wait for the current token to finish generating, then try again.',+ 4000,+ );+ return;+ }++ const previousEnableCommands = enableCommands();+ const supersededToken = currentToken();+ const supersededRecord = latestRecord();+ const source = latestTokenSource() ?? 'manual';setEnableCommands(value);- if (currentToken() && !isGeneratingToken()) {- const source = latestTokenSource() ?? 'manual';- const supersededTokenId = latestRecord()?.id;- void generateInstallToken(source, { notifySuccess: false }).then(() => {- if (disposed || !currentToken()) return;- notificationStore.info(- value- ? 'Token regenerated with command execution permission. Copy the install command again.'- : 'Token regenerated without command execution permission. Copy the install command again.',- 5000,- );- // The superseded token was never handed to an agent; revoke it so- // toggling does not accumulate orphaned install tokens.- if (supersededTokenId && supersededTokenId !== latestRecord()?.id) {- SecurityAPI.deleteToken(supersededTokenId).catch((err) => {- logger.warn('Failed to revoke superseded install token', err);- });- }+ if (!supersededToken) return;++ // Token scope and rendered flags are one atomic command state. Lock the+ // command surface before minting so --enable-commands can never be copied+ // with the previous non-exec token (or the inverse).+ setCurrentToken(null);+ setLatestRecord(null);+ const generated = await generateInstallToken(source, { notifySuccess: false });+ if (disposed) return;++ if (!generated) {+ // Restore the complete previous state; never leave new flags paired with+ // the old credential after a failed replacement.+ setEnableCommands(previousEnableCommands);+ setCurrentToken(supersededToken);+ setLatestRecord(supersededRecord);+ return;+ }++ notificationStore.info(+ value+ ? 'Token regenerated with command execution permission. Copy the install command again.'+ : 'Token regenerated without command execution permission. Copy the install command again.',+ 5000,+ );+ // The superseded token was never handed to an agent; revoke it so+ // toggling does not accumulate orphaned install tokens.+ const supersededTokenId = supersededRecord?.id;+ if (supersededTokenId && supersededTokenId !== latestRecord()?.id) {+ SecurityAPI.deleteToken(supersededTokenId).catch((err) => {+ logger.warn('Failed to revoke superseded install token', err);});}};diff --git a/internal/monitoring/agent_fleet_doctor.go b/internal/monitoring/agent_fleet_doctor.goindex 75c4c03355..ff8a04cf31 100644--- a/internal/monitoring/agent_fleet_doctor.go+++ b/internal/monitoring/agent_fleet_doctor.go@@ -37,6 +37,7 @@ const (AgentFleetReasonModuleDegraded = "agent_module_degraded"AgentFleetReasonCredentialMissing = "agent_credential_missing"AgentFleetReasonCredentialExpired = "agent_credential_expired"+ AgentFleetReasonExecScopeMissing = "agent_exec_scope_missing"AgentFleetReasonDuplicateInstallation = "duplicate_host_agent_installation"AgentFleetActionAllowReenroll = "allow_reenroll"@@ -151,7 +152,7 @@ type agentFleetSubject struct {type agentFleetTokenInventory struct {known bool- active map[string]struct{}+ active map[string]config.APITokenRecordexpired map[string]struct{}}@@ -224,7 +225,7 @@ func (m *Monitor) agentFleetTokenInventory(now time.Time) agentFleetTokenInventoinventory := agentFleetTokenInventory{known: true,- active: make(map[string]struct{}),+ active: make(map[string]config.APITokenRecord),expired: make(map[string]struct{}),}config.Mu.RLock()@@ -238,7 +239,7 @@ func (m *Monitor) agentFleetTokenInventory(now time.Time) agentFleetTokenInventoinventory.expired[id] = struct{}{}continue}- inventory.active[id] = struct{}{}+ inventory.active[id] = record.Clone()}return inventory}@@ -480,7 +481,12 @@ func diagnoseAgentFleetSubject(}}- if diagnosticHasAnyReason(result.Reasons, AgentFleetReasonCredentialMissing, AgentFleetReasonCredentialExpired) {+ if diagnosticHasAnyReason(+ result.Reasons,+ AgentFleetReasonCredentialMissing,+ AgentFleetReasonCredentialExpired,+ AgentFleetReasonExecScopeMissing,+ ) {platform, supported := safeAgentUpdatePlatform(subject)if platform == platformsupport.RuntimePlatformFreeBSD || diagnosticHasAnyReason(result.Reasons, AgentFleetReasonDuplicateInstallation) {supported = false@@ -549,7 +555,18 @@ func diagnoseAgentCredential(subject agentFleetSubject, inventory agentFleetTokeif subject.removed || !inventory.known || tokenID == "" {return nil}- if _, ok := inventory.active[tokenID]; ok {+ if record, ok := inventory.active[tokenID]; ok {+ if subject.host != nil && subject.host.CommandsEnabled && !record.HasScope(config.ScopeAgentExec) {+ return []AgentFleetDiagnosticReason{{+ Code: AgentFleetReasonExecScopeMissing,+ Severity: AgentFleetStatusCritical,+ Message: "The agent is configured to accept Pulse commands, but its credential does not grant command execution.",+ Evidence: []string{+ "Agent command execution: enabled",+ "Credential scope: agent:exec missing",+ },+ }}+ }return nil}if _, ok := inventory.expired[tokenID]; ok {diff --git a/internal/monitoring/agent_fleet_doctor_test.go b/internal/monitoring/agent_fleet_doctor_test.goindex 5980a4ee1d..ee3d8062fe 100644--- a/internal/monitoring/agent_fleet_doctor_test.go+++ b/internal/monitoring/agent_fleet_doctor_test.go@@ -111,6 +111,63 @@ func TestAgentFleetDiagnosticsAcceptsActiveCredential(t *testing.T) {}}+func TestAgentFleetDiagnosticsRepairsCommandCredentialWithoutExecScope(t *testing.T) {+ now := time.Date(2026, 8, 9, 12, 0, 0, 0, time.UTC)+ monitor := newAgentFleetDoctorTestMonitor(t)+ monitor.config.APITokens = []config.APITokenRecord{{+ ID: "report-only-token",+ Scopes: []string{+ config.ScopeAgentReport,+ config.ScopeAgentConfigRead,+ },+ }}+ monitor.state.UpsertHost(models.Host{+ ID: "agent-command-scope",+ Hostname: "pve-command-scope",+ Platform: "linux",+ Status: "online",+ LastSeen: now,+ AgentVersion: "6.2.0",+ TokenID: "report-only-token",+ CommandsEnabled: true,+ })++ agent := requireAgentDiagnostic(t, monitor.GetAgentFleetDiagnostics("6.2.0", now), "agent-agent-command-scope")+ requireReasonCode(t, agent, AgentFleetReasonExecScopeMissing)+ if agent.Status != AgentFleetStatusCritical {+ t.Fatalf("status = %q, want %q", agent.Status, AgentFleetStatusCritical)+ }+ if !hasSupportedRepair(agent, AgentFleetActionRepairAuthentication) {+ t.Fatalf("expected command-scope mismatch to expose authentication repair: %#v", agent.RepairActions)+ }+}++func TestAgentFleetDiagnosticsAcceptsCommandCredentialWithExecScope(t *testing.T) {+ now := time.Date(2026, 8, 9, 12, 0, 0, 0, time.UTC)+ monitor := newAgentFleetDoctorTestMonitor(t)+ monitor.config.APITokens = []config.APITokenRecord{{+ ID: "command-token",+ Scopes: []string{config.ScopeAgentReport, config.ScopeAgentExec},+ }}+ monitor.state.UpsertHost(models.Host{+ ID: "agent-command-scope",+ Hostname: "pve-command-scope",+ Platform: "linux",+ Status: "online",+ LastSeen: now,+ AgentVersion: "6.2.0",+ TokenID: "command-token",+ CommandsEnabled: true,+ })++ agent := requireAgentDiagnostic(t, monitor.GetAgentFleetDiagnostics("6.2.0", now), "agent-agent-command-scope")+ for _, reason := range agent.Reasons {+ if reason.Code == AgentFleetReasonExecScopeMissing {+ t.Fatalf("exec-scoped credential produced repair reason: %#v", agent.Reasons)+ }+ }+}+func TestAgentFleetDiagnosticsDoesNotValidateSyntheticMockCredentials(t *testing.T) {now := time.Date(2026, 8, 9, 12, 0, 0, 0, time.UTC)mustSetMockEnabled(t, true)diff --git a/scripts/install.sh b/scripts/install.shindex 37a5f9a4ee..26c867c77f 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -501,16 +501,19 @@ restore_selinux_contexts() {# server rejects the agent's token. Keeps the message in one place so both# health-check paths report it identically.warn_agent_token_rejected() {- log_warn "Pulse rejected this agent's API token (HTTP 401/403). The saved token is no longer valid on the server, which usually means Pulse was restored/reinstalled or upgraded (for example v5 -> v6) without carrying the token across."- log_warn "Re-run the full agent install command from the Pulse UI to mint a fresh token. The agent will keep reporting 401 until the token is replaced."+ log_warn "Pulse rejected this agent's API token or required reporting scope (HTTP 401/403). The saved credential cannot authenticate this agent on the server, which usually means Pulse was restored/reinstalled or upgraded (for example v5 -> v6) without carrying the token across."+ log_warn "Re-run the full agent install command from the Pulse UI to mint a fresh token. The agent will keep reporting 401/403 until the credential is replaced."}# verify_agent_server_registration returns:# 0 - the server confirmed this agent's registration# 1 - registration not confirmed yet (transient: agent not reported, network)-# 2 - the server rejected the token (HTTP 401/403 - actionable, permanent)+# 2 - the server rejected the credential (401, or 403 other than a stale+# hostname ownership match - actionable, permanent)verify_agent_server_registration() {+ local lookup_id="${AGENT_ID}"local lookup_hostname="${HOSTNAME_OVERRIDE}"+ local lookup_query=""local lookup_out=""local lookup_status=""local lookup_body=""@@ -522,25 +525,42 @@ verify_agent_server_registration() {if [[ -z "$PULSE_URL" ]]; thenreturn 1fi- if [[ -z "$lookup_hostname" ]]; then+ if [[ -z "$lookup_id" ]] && declare -F recover_agent_id_from_state_file >/dev/null 2>&1; then+ lookup_id=$(recover_agent_id_from_state_file || true)+ if [[ -n "$lookup_id" ]]; then+ AGENT_ID="$lookup_id"+ fi+ fi+ if [[ -z "$lookup_id" && -z "$lookup_hostname" ]]; thenlookup_hostname=$(hostname 2>/dev/null || true)fi- if [[ -z "$lookup_hostname" ]]; then+ if [[ -n "$lookup_id" ]]; then+ lookup_query="id=$(url_encode "$lookup_id")"+ elif [[ -n "$lookup_hostname" ]]; then+ lookup_query="hostname=$(url_encode "$lookup_hostname")"+ elsereturn 1fiif [[ "$INSECURE" == "true" ]]; then lookup_args+=(-k); fiif [[ -n "$CURL_CA_BUNDLE" ]]; then lookup_args+=(--cacert "$CURL_CA_BUNDLE"); fi- lookup_out=$(curl_with_pulse_token "${lookup_args[@]}" "${PULSE_URL}/api/agents/agent/lookup?hostname=$(url_encode "$lookup_hostname")" 2>/dev/null || true)+ lookup_out=$(curl_with_pulse_token "${lookup_args[@]}" "${PULSE_URL}/api/agents/agent/lookup?${lookup_query}" 2>/dev/null || true)lookup_status="${lookup_out##*$'\n'}"lookup_body="${lookup_out%$'\n'*}"- # A rejected token is a definitive, actionable failure distinct from "the- # agent has not reported yet"; signal it so the caller can tell the operator- # the token needs replacing instead of leaving a silent 401 loop behind.+ # Authentication failure and missing reporting scope are definitive. A+ # lookup can instead hit the previous registration during first-use token+ # binding; agent_lookup_forbidden is transient until the new ownership is+ # visible, so keep polling rather than falsely condemning the fresh token.case "$lookup_status" in- 401|403) return 2 ;;+ 401) return 2 ;;+ 403)+ if echo "$lookup_body" | grep -q '"code"[[:space:]]*:[[:space:]]*"agent_lookup_forbidden"'; then+ return 1+ fi+ return 2+ ;;esacif echo "$lookup_body" | grep -q '"agent"[[:space:]]*:' && echo "$lookup_body" | grep -q '"id"[[:space:]]*:'; thendiff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.goindex 16adeb6881..8c2c74d39d 100644--- a/scripts/installtests/install_sh_test.go+++ b/scripts/installtests/install_sh_test.go@@ -4748,6 +4748,7 @@ func TestInstallSHVerifyAgentServerRegistrationDetectsRejectedToken(t *testing.T}{{"rejected token 401", http.StatusUnauthorized, `{"error":"Authentication required"}`, "rc=2"},{"rejected token 403", http.StatusForbidden, `{"error":"missing_scope"}`, "rc=2"},+ {"previous hostname owner during binding", http.StatusForbidden, `{"error":{"code":"agent_lookup_forbidden","message":"Agent does not belong to this API token"}}`, "rc=1"},{"registered", http.StatusOK, `{"success":true,"agent":{"id":"agent-omv"}}`, "rc=0"},{"not reported yet", http.StatusNotFound, `{"error":"agent_not_found"}`, "rc=1"},}@@ -4768,6 +4769,7 @@ func TestInstallSHVerifyAgentServerRegistrationDetectsRejectedToken(t *testing.Tscript := `PULSE_URL="` + server.URL + `"PULSE_TOKEN="stale-token"+ AGENT_ID=""HOSTNAME_OVERRIDE="omv"INSECURE="false"CURL_CA_BUNDLE=""@@ -4788,6 +4790,44 @@ func TestInstallSHVerifyAgentServerRegistrationDetectsRejectedToken(t *testing.T}}+func TestInstallSHVerifyAgentServerRegistrationPrefersCanonicalAgentID(t *testing.T) {+ urlEncode := extractInstallShellFunction(t, "url_encode")+ curlWithPulseToken := extractInstallShellFunction(t, "curl_with_pulse_token")+ verifyFn := extractInstallShellFunction(t, "verify_agent_server_registration")++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if got := r.URL.Query().Get("id"); got != "agent-current" {+ t.Errorf("lookup id = %q, want canonical agent ID", got)+ }+ if got := r.URL.Query().Get("hostname"); got != "" {+ t.Errorf("hostname lookup = %q, want ID-only lookup", got)+ }+ _, _ = w.Write([]byte(`{"success":true,"agent":{"id":"agent-current"}}`))+ }))+ defer server.Close()++ script := `+ PULSE_URL="` + server.URL + `"+ PULSE_TOKEN="install-token"+ AGENT_ID="agent-current"+ HOSTNAME_OVERRIDE="hostname-owned-by-previous-token"+ INSECURE="false"+ CURL_CA_BUNDLE=""+` + curlWithPulseToken + `+` + urlEncode + `+` + verifyFn + `+ verify_agent_server_registration+ echo "rc=$?"+ `+ out, err := exec.Command("bash", "-c", script).CombinedOutput()+ if err != nil {+ t.Fatalf("bash: %v\n%s", err, out)+ }+ if !strings.Contains(string(out), "rc=0") {+ t.Fatalf("canonical ID lookup failed:\n%s", out)+ }+}+// TestInstallSHRegistrationRetryWindowOutlastsFirstReportCycle verifies that// the post-install registration check polls for a window instead of warning// after a single lookup: /readyz flips before the agent's first report cycle@@ -4844,6 +4884,7 @@ func TestInstallSHRegistrationRetryWindowOutlastsFirstReportCycle(t *testing.T)script := `PULSE_URL="` + server.URL + `"PULSE_TOKEN="install-token"+ AGENT_ID=""HOSTNAME_OVERRIDE="pve-1644"INSECURE="false"CURL_CA_BUNDLE=""