Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Guard infrastructure import plan approvals

rcourtman97b936933391
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f31c2cf832..001c3e4893 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -111,6 +111,13 @@ shared `/api/resources` payload carries a backend-authored Proxmox workload
target linked to that node agent. Suppressing an inside-guest install cue for
that case means governed actions have a node-agent path; it must not be
presented as proof that a guest-local agent is installed.
+Candidate-sourced PVE/PBS/PMG onboarding remains lifecycle-owned even when the
+candidate starts in Discovery or a platform probe: the settings connection flow
+may preview the monitored-system impact and credential path, but setup
+commands, downloaded scripts, manual token command copies, and manual saves
+must stay blocked until the operator explicitly approves the candidate import
+plan. Type-first manual adds without a candidate must stay on the normal
+credential-entry path and must not synthesize a discovery import plan.
Agent-facing operations-loop status wiring in `internal/api/router.go` and
`internal/api/agent_resource_context.go` is lifecycle-adjacent only because it
shares agent route infrastructure. Other handlers in `internal/api/` such as
@@ -3173,6 +3180,16 @@ That same node setup modal owner must also stay on the direct
`NodeModalStatusFooter.tsx`, `nodeModalModel.ts`, and `useNodeModalState.ts`,
rather than relying only on broad lane ownership or downstream command tests
to catch lifecycle drift in the settings surface.
+Candidate-sourced PVE/PBS/PMG node setup is part of that same node setup
+owner. When a connection originates from Discovery or the API platform probe,
+`InfrastructureWorkspace.tsx` must pass the candidate into
+`NodeCredentialSlot.tsx`, `infrastructureImportPlanModel.ts` must derive the
+endpoint, identity, credential path, collection scope, monitored-system preview
+request, and reset signature, and the setup surface must require explicit
+operator approval before any assisted setup command, downloaded setup script,
+manual token command copy, or manual save can proceed. Direct type-first adds
+with no candidate remain normal credential entry and must not fabricate an
+import plan.
That same Proxmox lifecycle transport now explicitly includes the shared
`frontend-modern/src/api/nodes.ts` client boundary itself: changes to setup
command or install-command request transport must carry both lifecycle proof
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 7c726e4e59..2b51bcbd0c 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -151,6 +151,23 @@ configured admin role may pass admin gates. Installations that intentionally
make every proxy-authenticated user an admin must do that by leaving the role
header unset and protecting Pulse at the proxy/IdP layer.
+Local credential auth reads are also part of this shared boundary. Handlers in
+`internal/api/auth.go` and `internal/api/router.go` that compare `AuthUser` and
+`AuthPass` must snapshot those mutable config fields while holding
+`config.Mu.RLock()` before running constant-time username or password-hash
+checks. CSRF bootstrap checks may snapshot local auth, API-token, and proxy
+secret presence under that same lock, then evaluate SSO provider state outside
+the config lock.
+
+Candidate import plans for PVE/PBS/PMG onboarding are API-contract consumers,
+not local UI estimates. Probe and Discovery candidates must build their
+preview through `frontend-modern/src/api/monitoredSystemLedger.ts` and
+`POST /api/license/monitored-system-ledger/preview`, preserving source,
+resource type, name, hostname, host URL, and resource id in the request. The
+frontend may render the preview and approval state, but it must not persist a
+candidate or call node setup/save APIs until the operator has approved the
+current endpoint, credential path, and collection scope.
+
Assistant chat `workflow_state` events are a shared AI/API payload boundary.
The backend source of truth is `internal/ai/chat.WorkflowStateData`, generated
to `frontend-modern/src/api/generated/aiChatEvents.ts` by
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index c000bf5f5a..9610961950 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -193,6 +193,15 @@ deep-link flow. The self-hosted `Plans` page is not a deep-link-only flow:
`system-billing` stays visible whenever commercial presentation is allowed,
while demo or commercial-suppressed sessions may still hide it.
+Candidate import-plan presentation inside the Infrastructure settings dialog is
+a shared primitive composition boundary. `NodeCandidateImportPlan.tsx` may use
+shared `Button`, checkbox styling, lucide icons, and
+`MonitoredSystemImpactPreview`, while `InfrastructureWorkspace.tsx` owns the
+route-backed dialog state that feeds probe or Discovery candidates into the
+credential slot. That surface must keep the approval card readable inside the
+existing dialog body and must not introduce a second nested modal, detached
+wizard shell, or page-local preview renderer for monitored-system impact.
+
Frontend localization is a shared primitive boundary. Locale support must flow
through typed message catalogs with an English fallback and explicit seed
locale coverage rather than page-local string switches.
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 95134b8a19..ffbb74c6e1 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -371,6 +371,14 @@ truth for live infrastructure data.
## Current State
+The monitoring-owned storage metrics runtime must preserve store-backed storage
+chart continuity during resolver warm-up. `syncUnifiedStorageMetrics` must
+prefer the resolver's canonical storage metrics target when it exists, but must
+fall back to the storage resource id instead of dropping the resource when the
+resolver has not yet produced a storage target. The fallback is a metrics
+continuity path for canonical storage resources, not a second storage identity
+or recovery-source model.
+
That same reloadable multi-tenant monitor boundary also owns instance-wide
notification settings fan-out. `ForEachMonitor` visits every live tenant
monitor so callers can propagate the webhook security allowlist and public
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 5ac2eac1d3..648a684bb8 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -204,6 +204,12 @@ regression protection.
fetches, Discovery probes, or page-local external-link logic on the table
hot path.
4. Keep shared auth gating in `internal/api/router.go` cheap and local: pre-auth quick-setup and recovery routing may short-circuit on loopback/session/token checks, but they must not trigger chart, metrics, or broad persistence fan-out on the protected request hot path.
+ Reading mutable auth configuration for CSRF bootstrap and login checks must
+ stay a short in-memory snapshot under `config.Mu.RLock()`: local
+ username/password presence, API-token presence, and proxy-auth secret
+ presence may be copied while locked, while SSO provider presence is checked
+ after the lock is released. This preserves the protected hot path and avoids
+ holding the config lock across provider/state work.
The same rule applies to public setup-script lifecycle routes: `/api/auto-register`
and `/api/auto-unregister` may bypass the global auth wall so their handlers can
validate request-body setup tokens, but the router-level public-path check must
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 6fbbbc6855..0233a1579f 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -234,6 +234,12 @@ existing resource-policy redaction still governs any model-bound context.
Pulse Mobile token scopes, bypass the server-minted credential requirement,
or expose relay secrets beyond the existing public onboarding diagnostics.
4. Change security/auth/token transport behavior through the shared `frontend-modern/src/api/security.ts`, `frontend-modern/src/components/Settings/APITokenManager.tsx`, `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`, `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`, `internal/api/security.go`, `internal/api/security_tokens.go`, and `internal/api/system_settings.go` boundary.
+ Local username/password verification in `internal/api/auth.go` and
+ `internal/api/router.go` must snapshot `AuthUser` and `AuthPass` under
+ `config.Mu.RLock()` before comparison. Security/privacy may consume that
+ shared auth result, but it must not read mutable credential fields outside
+ the shared config lock or hold the lock across password hashing, session
+ mutation, SSO provider checks, or response writing.
Release metadata surfaced through `/api/version` remains outside token,
auth, and privacy state. Adding or changing `agentUpdateTargetVersion`
must stay limited to non-secret deployable release identity and must not
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 82f62248f9..4aa4ed7012 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -239,6 +239,11 @@ Storage/recovery auth-adjacent changes may consume SSO-authenticated sessions,
but they must not reinterpret SAML or multi-provider SSO availability as a
storage/recovery entitlement; that provider-route and license truth belongs to
the shared API/security boundary.
+Storage/recovery may consume authenticated chart and report routes through the
+shared API boundary, but it must not own router-level auth configuration reads.
+Those reads stay API/security-owned and must snapshot mutable auth credentials
+under `config.Mu.RLock()` before storage-adjacent routes rely on the resulting
+session or API-token decision.
Storage/recovery may also consume org-scoped session identity from the shared
API boundary, but durable user IDs remain the authorization principal. Contact
email may support display or legacy lookup only; storage and recovery surfaces
diff --git a/frontend-modern/public/docs/CONFIGURATION.md b/frontend-modern/public/docs/CONFIGURATION.md
index c3d58f319d..edb7b1cf77 100644
--- a/frontend-modern/public/docs/CONFIGURATION.md
+++ b/frontend-modern/public/docs/CONFIGURATION.md
@@ -372,6 +372,19 @@ Persistent metrics history uses tiered retention windows. These values are store
See [METRICS_HISTORY.md](METRICS_HISTORY.md) for details.
+### Prometheus Metrics Endpoint
+
+The `/metrics` listener is separate from the main UI/API listener and binds to loopback by default.
+
+| Variable | Description | Default |
+| ---------- | ------------- | --------- |
+| `PULSE_METRICS_PORT` | Metrics listener port | `9091` |
+| `PULSE_METRICS_BIND_ADDRESS` | Metrics listener bind address | `127.0.0.1` |
+| `PULSE_METRICS_TOKEN` | Optional bearer token for `/metrics` | *(empty)* |
+| `PULSE_METRICS_ALLOW_INSECURE_REMOTE` | Explicit opt-in to serve a metrics bearer token over non-loopback plaintext HTTP | `false` |
+
+For remote scraping with `PULSE_METRICS_TOKEN`, prefer a local scraper, tunnel, VPN-private path, or TLS/mTLS reverse proxy. Pulse refuses non-loopback plaintext token scraping unless `PULSE_METRICS_ALLOW_INSECURE_REMOTE=true` is set.
+
---
## 🔔 Alerts (`alerts.json`)
@@ -402,6 +415,47 @@ Pulse uses a powerful alerting engine with hysteresis (separate trigger/clear th
---
+## Availability Checks (`availability_targets.enc`)
+
+Availability checks are agentless probes for devices and services where Pulse
+cannot install an agent or does not need full machine telemetry. Use them for
+simple ping monitoring, TCP service checks, and HTTP/HTTPS status checks.
+
+**Managed via UI**: Settings -> Monitoring -> Availability checks
+
+Supported protocols:
+
+| Protocol | Use case | Required fields |
+| ---------- | ---------- | ---------------- |
+| `icmp` | Ping-only reachability for devices, computers, and appliances | `address` |
+| `ping` | API input alias for `icmp`; saved targets return `icmp` | `address` |
+| `tcp` | A reachable port such as MQTT, SSH, or a custom service | `address`, `port` |
+| `http` / `https` | Web UI or health endpoint availability | `address`, optional `port`, optional `path` |
+
+Saved targets include `name`, `targetKind` (`machine`, `service`, or
+`device`), `address`, `protocol`, `enabled`, polling interval, timeout,
+failure threshold, and an optional `linkedResourceId`. ICMP ping is the
+default probe for new targets. Availability targets publish
+`network-endpoint` resources and can raise downtime alerts after the configured
+failure threshold.
+
+Example API payload for simple ping monitoring:
+
+```json
+{
+ "name": "Garage temperature sensor",
+ "targetKind": "device",
+ "address": "garage-sensor.local",
+ "protocol": "ping",
+ "enabled": true
+}
+```
+
+Pulse stores and returns that target as `protocol: "icmp"` so dashboards,
+alerts, and resource projections keep one canonical protocol value.
+
+---
+
## 🔒 HTTPS / TLS
Enable HTTPS by providing certificate files via environment variables.
diff --git a/frontend-modern/public/docs/PROXY_AUTH.md b/frontend-modern/public/docs/PROXY_AUTH.md
index b7a22064df..03cd415105 100644
--- a/frontend-modern/public/docs/PROXY_AUTH.md
+++ b/frontend-modern/public/docs/PROXY_AUTH.md
@@ -23,6 +23,10 @@ Authenticate users via your existing reverse proxy (Authentik, Authelia, Cloudfl
| `PROXY_AUTH_ADMIN_ROLE` | Role name that grants admin access. | `admin` |
| `PROXY_AUTH_LOGOUT_URL` | URL to redirect to after logout. | - |
+If `PROXY_AUTH_ROLE_HEADER` and `PROXY_AUTH_ADMIN_ROLE` are configured, admin access fails closed unless the role header is present and contains the configured admin role. A missing or blank role header still authenticates the user, but the user is treated as non-admin.
+
+If you intentionally want every proxy-authenticated user to be an admin, leave `PROXY_AUTH_ROLE_HEADER` unset and protect Pulse entirely at the proxy/IdP layer.
+
## 📦 Examples
### Authentik (with Traefik)
diff --git a/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCandidateImportPlan.tsx b/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCandidateImportPlan.tsx
new file mode 100644
index 0000000000..04fee9dcae
--- /dev/null
+++ b/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCandidateImportPlan.tsx
@@ -0,0 +1,118 @@
+import { For, Show, type Component } from 'solid-js';
+import CheckCircle2 from 'lucide-solid/icons/check-circle-2';
+import ClipboardCheck from 'lucide-solid/icons/clipboard-check';
+import KeyRound from 'lucide-solid/icons/key-round';
+import Search from 'lucide-solid/icons/search';
+import ShieldCheck from 'lucide-solid/icons/shield-check';
+
+import type { MonitoredSystemLedgerPreviewResponse } from '@/api/monitoredSystemLedger';
+import { Button } from '@/components/shared/Button';
+import { formCheckbox } from '@/components/shared/Form';
+import type { NodeImportPlan, NodeImportPlanStep } from '../../infrastructureImportPlanModel';
+import { MonitoredSystemImpactPreview } from '../../MonitoredSystemImpactPreview';
+
+interface NodeCandidateImportPlanProps {
+ plan: NodeImportPlan;
+ approved: boolean;
+ onApprovedChange: (approved: boolean) => void;
+ onPreviewImpact: () => void;
+ preview: MonitoredSystemLedgerPreviewResponse | null;
+ previewing: boolean;
+ previewError: string | null;
+}
+
+const stepIcon = (step: NodeImportPlanStep) => {
+ switch (step.id) {
+ case 'candidate':
+ return Search;
+ case 'credentials':
+ return KeyRound;
+ case 'dry-run':
+ return ClipboardCheck;
+ case 'approval':
+ return ShieldCheck;
+ case 'verification':
+ return CheckCircle2;
+ }
+};
+
+export const NodeCandidateImportPlan: Component<NodeCandidateImportPlanProps> = (props) => {
+ return (
+ <section
+ aria-label="Candidate import plan"
+ class="rounded-md border border-blue-200 bg-blue-50/70 px-4 py-4 dark:border-blue-900/60 dark:bg-blue-950/30"
+ >
+ <div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
+ <div class="space-y-1">
+ <div class="flex flex-wrap items-center gap-2">
+ <h3 class="text-sm font-semibold text-base-content">Candidate import plan</h3>
+ <span class="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-medium text-blue-800 dark:bg-blue-900/70 dark:text-blue-200">
+ {props.plan.sourceLabel}
+ </span>
+ </div>
+ <p class="text-xs leading-5 text-muted">
+ {props.plan.name} · {props.plan.endpoint}
+ </p>
+ <Show when={props.plan.detectedVersion}>
+ {(version) => <p class="text-xs text-muted">{version()}</p>}
+ </Show>
+ </div>
+ <Button
+ type="button"
+ variant="secondary"
+ size="settingsAction"
+ onClick={props.onPreviewImpact}
+ disabled={!props.plan.previewRequest || props.previewing}
+ class="self-start gap-2"
+ >
+ <ClipboardCheck class="h-4 w-4" aria-hidden="true" />
+ {props.previewing ? 'Previewing...' : 'Preview impact'}
+ </Button>
+ </div>
+
+ <div class="mt-4 grid gap-3 md:grid-cols-5">
+ <For each={props.plan.steps}>
+ {(step) => {
+ const Icon = stepIcon(step);
+ return (
+ <div class="rounded-md border border-blue-200 bg-surface px-3 py-3 text-xs dark:border-blue-900/70">
+ <div class="flex items-center gap-2 font-medium text-base-content">
+ <Icon class="h-3.5 w-3.5 text-blue-600 dark:text-blue-300" aria-hidden="true" />
+ {step.title}
+ </div>
+ <p class="mt-1 leading-5 text-muted">{step.detail}</p>
+ </div>
+ );
+ }}
+ </For>
+ </div>
+
+ <div class="mt-4">
+ <MonitoredSystemImpactPreview
+ preview={props.preview}
+ loading={props.previewing}
+ error={props.previewError}
+ errorTitle="Could not preview import impact"
+ />
+ </div>
+
+ <label class="mt-4 flex items-start gap-3 rounded-md border border-blue-200 bg-surface px-3 py-3 text-sm dark:border-blue-900/70">
+ <input
+ type="checkbox"
+ checked={props.approved}
+ onChange={(event) => props.onApprovedChange(event.currentTarget.checked)}
+ class={`${formCheckbox} mt-0.5`}
+ />
+ <span>
+ <span class="block font-medium text-base-content">Approve this import plan</span>
+ <span class="mt-1 block text-xs leading-5 text-muted">
+ Approving allows this {props.plan.sourceLabel} source to be added with the current
+ endpoint, credential path, and collection scope: {props.plan.coverageLabel}.
+ </span>
+ </span>
+ </label>
+ </section>
+ );
+};
+
+export default NodeCandidateImportPlan;
diff --git a/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx b/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx
index 9129c91a43..07467bfb8a 100644
--- a/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx
+++ b/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx
@@ -1,4 +1,8 @@
-import { Component } from 'solid-js';
+import { Component, createEffect, createMemo, createSignal } from 'solid-js';
+import {
+ MonitoredSystemLedgerAPI,
+ type MonitoredSystemLedgerPreviewResponse,
+} from '@/api/monitoredSystemLedger';
import type { NodeConfig, NodeConfigWithStatus } from '@/types/nodes';
import { NodeModalAuthenticationSection } from '@/components/Settings/NodeModalAuthenticationSection';
import { NodeModalBasicInfoSection } from '@/components/Settings/NodeModalBasicInfoSection';
@@ -7,6 +11,13 @@ import { NodeModalStatusFooter } from '@/components/Settings/NodeModalStatusFoot
import { useNodeModalState } from '@/components/Settings/useNodeModalState';
import type { NodeModalProps } from '@/components/Settings/nodeModalModel';
import type { InfrastructurePlatformSettingsProps } from '@/components/Settings/proxmoxSettingsModel';
+import { notificationStore } from '@/stores/notifications';
+import { logger } from '@/utils/logger';
+import {
+ buildNodeImportPlan,
+ type NodeImportPlanCandidate,
+} from '../../infrastructureImportPlanModel';
+import { NodeCandidateImportPlan } from './NodeCandidateImportPlan';
export type NodeSlotType = 'pve' | 'pbs' | 'pmg';
@@ -15,6 +26,7 @@ export interface NodeCredentialSlotProps {
settings: InfrastructurePlatformSettingsProps;
editingNode?: NodeConfigWithStatus | null;
prefillNode?: Partial<NodeConfig>;
+ importCandidate?: NodeImportPlanCandidate | null;
initialAddress?: string;
onCancel: () => void;
onSaved: () => void;
@@ -30,6 +42,13 @@ export interface NodeCredentialSlotProps {
export const NodeCredentialSlot: Component<NodeCredentialSlotProps> = (props) => {
const prefill: Partial<NodeConfig> | undefined =
props.prefillNode ?? (props.initialAddress ? { host: props.initialAddress } : undefined);
+ const importApprovalRequiredMessage =
+ 'Approve the import plan before generating setup commands or adding this source.';
+ const [importApproved, setImportApproved] = createSignal(false);
+ const [previewingImportImpact, setPreviewingImportImpact] = createSignal(false);
+ const [importImpactPreview, setImportImpactPreview] =
+ createSignal<MonitoredSystemLedgerPreviewResponse | null>(null);
+ const [importImpactPreviewError, setImportImpactPreviewError] = createSignal<string | null>(null);
const handleSave = async (nodeData: Partial<NodeConfig>) => {
await props.settings.saveNode(nodeData);
@@ -49,6 +68,8 @@ export const NodeCredentialSlot: Component<NodeCredentialSlotProps> = (props) =>
),
temperatureMonitoringLocked: props.settings.temperatureMonitoringLocked(),
savingTemperatureSetting: props.settings.savingTemperatureSetting(),
+ setupHandoffDisabled: () => Boolean(props.importCandidate && !importApproved()),
+ setupHandoffDisabledReason: importApprovalRequiredMessage,
onToggleTemperatureMonitoring: async (enabled) => {
const target = props.editingNode;
if (target?.id) {
@@ -60,9 +81,59 @@ export const NodeCredentialSlot: Component<NodeCredentialSlotProps> = (props) =>
};
const state = useNodeModalState(modalProps);
+ const importPlan = createMemo(() =>
+ buildNodeImportPlan(props.nodeType, state.formData(), props.importCandidate),
+ );
+
+ let previousImportPlanSignature = '';
+
+ createEffect(() => {
+ const signature = importPlan()?.signature ?? '';
+ if (signature === previousImportPlanSignature) {
+ return;
+ }
+ previousImportPlanSignature = signature;
+ setImportApproved(false);
+ setImportImpactPreview(null);
+ setImportImpactPreviewError(null);
+ });
+
+ const saveBlockedByImportPlan = () => Boolean(importPlan() && !importApproved());
+
+ const handlePreviewImportImpact = async () => {
+ const plan = importPlan();
+ if (!plan?.previewRequest) {
+ setImportImpactPreviewError('Enter an endpoint before previewing impact.');
+ return;
+ }
+
+ setPreviewingImportImpact(true);
+ setImportImpactPreviewError(null);
+ try {
+ const preview = await MonitoredSystemLedgerAPI.preview(plan.previewRequest);
+ setImportImpactPreview(preview);
+ } catch (error) {
+ logger.error('[Infrastructure Import Plan] Impact preview failed', error);
+ setImportImpactPreview(null);
+ setImportImpactPreviewError(
+ error instanceof Error ? error.message : 'Unable to calculate import impact right now.',
+ );
+ } finally {
+ setPreviewingImportImpact(false);
+ }
+ };
+
+ const handleSubmit = (event: Event) => {
+ if (saveBlockedByImportPlan()) {
+ event.preventDefault();
+ notificationStore.error(importApprovalRequiredMessage);
+ return;
+ }
+ state.handleSubmit(event);
+ };
return (
- <form onSubmit={state.handleSubmit} class="space-y-6">
+ <form onSubmit={handleSubmit} class="space-y-6">
<section
aria-label="Infrastructure connection sequence"
class="rounded-md border border-border bg-surface-alt px-4 py-3"
@@ -97,6 +168,17 @@ export const NodeCredentialSlot: Component<NodeCredentialSlotProps> = (props) =>
</div>
</div>
</section>
+ {importPlan() && (
+ <NodeCandidateImportPlan
+ plan={importPlan()!}
+ approved={importApproved()}
+ onApprovedChange={setImportApproved}
+ onPreviewImpact={handlePreviewImportImpact}
+ preview={importImpactPreview()}
+ previewing={previewingImportImpact()}
+ previewError={importImpactPreviewError()}
+ />
+ )}
<NodeModalBasicInfoSection modalProps={modalProps} state={state} />
<NodeModalAuthenticationSection modalProps={modalProps} state={state} />
<NodeModalMonitoringSection modalProps={modalProps} state={state} />
@@ -110,6 +192,8 @@ export const NodeCredentialSlot: Component<NodeCredentialSlotProps> = (props) =>
deletePending={props.deletePending}
deleteConfirming={props.deleteConfirming}
deleteError={props.deleteError}
+ saveDisabled={saveBlockedByImportPlan()}
+ saveDisabledReason={importApprovalRequiredMessage}
/>
</form>
);
diff --git a/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/__tests__/NodeCredentialSlot.test.tsx b/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/__tests__/NodeCredentialSlot.test.tsx
new file mode 100644
index 0000000000..94ec137b45
--- /dev/null
+++ b/frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/__tests__/NodeCredentialSlot.test.tsx
@@ -0,0 +1,68 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { InfrastructurePlatformSettingsProps } from '@/components/Settings/proxmoxSettingsModel';
+import { NodeCredentialSlot } from '../NodeCredentialSlot';
+
+const importApprovalRequiredMessage =
+ 'Approve the import plan before generating setup commands or adding this source.';
+
+const createSettings = (): InfrastructurePlatformSettingsProps =>
+ ({
+ securityStatus: () => null,
+ resolveTemperatureMonitoringEnabled: () => true,
+ temperatureMonitoringLocked: () => false,
+ savingTemperatureSetting: () => false,
+ handleNodeTemperatureMonitoringChange: vi.fn().mockResolvedValue(undefined),
+ handleTemperatureMonitoringChange: vi.fn().mockResolvedValue(undefined),
+ saveNode: vi.fn().mockResolvedValue(undefined),
+ }) as unknown as InfrastructurePlatformSettingsProps;
+
+describe('NodeCredentialSlot', () => {
+ afterEach(() => cleanup());
+
+ it('requires candidate import plan approval before guided setup handoff or manual save', () => {
+ render(() => (
+ <NodeCredentialSlot
+ nodeType="pve"
+ settings={createSettings()}
+ prefillNode={{
+ type: 'pve',
+ name: 'tower',
+ host: 'https://tower.local:8006',
+ }}
+ importCandidate={{
+ kind: 'discovery',
+ server: {
+ type: 'pve',
+ ip: '10.0.0.10',
+ hostname: 'tower.local',
+ port: 8006,
+ version: 'Proxmox VE',
+ release: '9.0',
+ },
+ }}
+ onCancel={vi.fn()}
+ onSaved={vi.fn()}
+ />
+ ));
+
+ expect(screen.getByText('Candidate import plan')).toBeInTheDocument();
+ expect(screen.getByText('Proxmox VE 9.0')).toBeInTheDocument();
+
+ const blockedSetupButton = screen.getAllByTitle(importApprovalRequiredMessage)[0];
+ expect(blockedSetupButton).toBeDisabled();
+
+ fireEvent.click(screen.getByLabelText(/Approve this import plan/i));
+
+ expect(screen.getByTitle('Copy command')).not.toBeDisabled();
+
+ fireEvent.click(screen.getByRole('button', { name: /^Manual Token Setup$/i }));
+
+ const addButton = screen.getByRole('button', { name: 'Add node' });
+ expect(addButton).toBeDisabled();
+
+ fireEvent.click(screen.getByLabelText(/Approve this import plan/i));
+
+ expect(addButton).not.toBeDisabled();
+ });
+});
diff --git a/frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx b/frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx
index f7960403eb..1b00c44698 100644
--- a/frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx
+++ b/frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx
@@ -58,6 +58,7 @@ import {
filterRepresentedDiscoveredServers,
type DiscoveredServer,
} from './infrastructureSettingsModel';
+import type { NodeImportPlanCandidate } from './infrastructureImportPlanModel';
export type InfrastructureWorkspaceProps = InfrastructurePlatformSettingsProps;
@@ -312,13 +313,36 @@ const InfrastructureWorkspaceContent: Component<InfrastructureWorkspaceProps> =
if (selected && activeType && activeType !== selected.type) {
setSelectedDiscoveredSource(null);
}
+
+ const probed = selectedProbeCandidate();
+ if (probed && activeType && activeType !== probed.type) {
+ setSelectedProbeCandidate(null);
+ }
});
+ const importCandidateForNodeType = (
+ type: 'pve' | 'pbs' | 'pmg',
+ candidate?: ProbeCandidate | null,
+ ): NodeImportPlanCandidate | null => {
+ const discovered = selectedDiscoveredSource();
+ if (discovered && discovered.type === type) {
+ return { kind: 'discovery', server: discovered };
+ }
+
+ const probed = candidate ?? selectedProbeCandidate();
+ if (probed && probed.type === type) {
+ return { kind: 'probe', candidate: probed };
+ }
+
+ return null;
+ };
+
const renderNodeSlot = (
type: 'pve' | 'pbs' | 'pmg',
editingNode?: NodeConfigWithStatus | null,
editingRow?: Connection | null,
prefillNode?: Partial<NodeConfig>,
+ importCandidate?: NodeImportPlanCandidate | null,
) => {
const connectionId = editingRow?.id ?? null;
return (
@@ -327,6 +351,7 @@ const InfrastructureWorkspaceContent: Component<InfrastructureWorkspaceProps> =
settings={props}
editingNode={editingNode ?? null}
prefillNode={prefillNode}
+ importCandidate={importCandidate ?? null}
onCancel={editingRow ? closeEditFlow : closeAddFlow}
onSaved={editingRow ? handleEditSaved : handleAddSaved}
onToggleEnabled={
@@ -621,6 +646,7 @@ const InfrastructureWorkspaceContent: Component<InfrastructureWorkspaceProps> =
const renderConnectionSlot = (context: {
mode: 'add' | 'edit';
type: ConnectionType;
+ candidate?: ProbeCandidate | null;
onCancel: () => void;
onSaved: () => void;
}) => {
@@ -756,7 +782,13 @@ const InfrastructureWorkspaceContent: Component<InfrastructureWorkspaceProps> =
case 'pve':
case 'pbs':
case 'pmg':
- return renderNodeSlot(context.type, undefined, undefined, discoveredPrefill());
+ return renderNodeSlot(
+ context.type,
+ undefined,
+ undefined,
+ discoveredPrefill(),
+ importCandidateForNodeType(context.type, context.candidate),
+ );
case 'truenas':
return (
<TrueNASCredentialSlot
@@ -951,8 +983,8 @@ const InfrastructureWorkspaceContent: Component<InfrastructureWorkspaceProps> =
onSelectCandidate={openAddFlowFromProbe}
onClose={closeAddFlow}
onSaved={handleAddSaved}
- renderCredentialSlot={({ type, onCancel, onSaved }) =>
- renderConnectionSlot({ mode: 'add', type, onCancel, onSaved })
+ renderCredentialSlot={({ type, candidate, onCancel, onSaved }) =>
+ renderConnectionSlot({ mode: 'add', type, candidate, onCancel, onSaved })
}
/>
</Match>
@@ -966,8 +998,8 @@ const InfrastructureWorkspaceContent: Component<InfrastructureWorkspaceProps> =
onBackToCatalog={() => openAddFlow('pick')}
onClose={closeAddFlow}
onSaved={handleAddSaved}
- renderCredentialSlot={({ type, onCancel, onSaved }) =>
- renderConnectionSlot({ mode: 'add', type, onCancel, onSaved })
+ renderCredentialSlot={({ type, candidate, onCancel, onSaved }) =>
+ renderConnectionSlot({ mode: 'add', type, candidate, onCancel, onSaved })
}
/>
</Match>
diff --git a/frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx b/frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx
index 9a3721bf13..b6671574c8 100644
--- a/frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx
+++ b/frontend-modern/src/components/Settings/NodeModalSetupGuideSection.tsx
@@ -47,6 +47,14 @@ const setupModeButtonClass = (selected: boolean): string =>
export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionProps> = (props) => {
const { modalProps, state } = props;
+ const setupHandoffDisabled = () => Boolean(modalProps.setupHandoffDisabled?.());
+ const setupHandoffDisabledReason = () =>
+ modalProps.setupHandoffDisabledReason ??
+ 'Complete the required review before generating setup commands.';
+ const setupCommandButtonTitle = () =>
+ setupHandoffDisabled() ? setupHandoffDisabledReason() : 'Copy command';
+ const setupCommandButtonClass = (className: string) =>
+ `${className} disabled:cursor-not-allowed disabled:opacity-50`;
const setupStrategy = () =>
getNodeSetupStrategyPresentation(modalProps.nodeType, state.formData().setupMode);
const setupStrategyPanel = () => (
@@ -107,6 +115,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
Connection Setup
</h5>
{setupStrategyPanel()}
+ <Show when={setupHandoffDisabled()}>
+ <p class="mt-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs leading-5 text-amber-800 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-200">
+ {setupHandoffDisabledReason()}
+ </p>
+ </Show>
<div class="space-y-3 text-xs">
{setupModeControls()}
@@ -152,15 +165,17 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
<div class="relative bg-base rounded-md p-3 font-mono text-xs overflow-x-auto">
<button
type="button"
- disabled={state.loadingAgentCommand()}
+ disabled={state.loadingAgentCommand() || setupHandoffDisabled()}
onClick={async () => {
await state.copyProxmoxAgentInstallCommand(
'pve',
'Command copied! Run it on your Proxmox node.',
);
}}
- class="absolute top-2 right-2 p-1.5 hover:text-slate-200 bg-surface-hover rounded-md transition-colors disabled:opacity-50"
- title="Copy command"
+ class={setupCommandButtonClass(
+ 'absolute top-2 right-2 p-1.5 hover:text-slate-200 bg-surface-hover rounded-md transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<Show
when={state.loadingAgentCommand()}
@@ -258,7 +273,10 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
);
}}
class="absolute top-2 right-2 p-1.5 text-slate-400 hover:text-slate-200 bg-surface-hover rounded-md transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ title={
+ setupHandoffDisabled() ? setupHandoffDisabledReason() : 'Copy command'
+ }
>
<svg
width="16"
@@ -334,7 +352,9 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
onClick={async () => {
await state.downloadProxmoxSetupScript('pve', true);
}}
- class="w-full px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors text-sm font-medium"
+ disabled={setupHandoffDisabled()}
+ title={setupHandoffDisabled() ? setupHandoffDisabledReason() : undefined}
+ class="w-full px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors text-sm font-medium disabled:cursor-not-allowed disabled:opacity-50"
>
Download setup script
</button>
@@ -409,8 +429,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
'pveum user add pulse-monitor@pve --comment "Pulse monitoring service"';
await state.copyCommand(command);
}}
- class="absolute top-1 right-1 p-1 text-slate-500 hover:text-base-content transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ class={setupCommandButtonClass(
+ 'absolute top-1 right-1 p-1 text-slate-500 hover:text-base-content transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<svg
width="14"
@@ -442,8 +465,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
'pveum user token add pulse-monitor@pve pulse-token --privsep 0';
await state.copyCommand(command);
}}
- class="absolute top-1 right-1 p-1 text-slate-500 hover:text-base-content transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ class={setupCommandButtonClass(
+ 'absolute top-1 right-1 p-1 text-slate-500 hover:text-base-content transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<svg
width="14"
@@ -476,8 +502,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
onClick={async () => {
await state.copyCommand(PVE_MANUAL_PERMISSION_COMMAND);
}}
- class="absolute top-1 right-1 p-1 hover:text-muted transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ class={setupCommandButtonClass(
+ 'absolute top-1 right-1 p-1 hover:text-muted transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<svg
width="14"
@@ -503,8 +532,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
'pveum aclmod /storage -user pulse-monitor@pve -role PVEDatastoreAdmin';
await state.copyCommand(command);
}}
- class="absolute top-1 right-1 p-1 hover:text-muted transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ class={setupCommandButtonClass(
+ 'absolute top-1 right-1 p-1 hover:text-muted transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<svg
width="14"
@@ -572,6 +604,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
Connection Setup
</h5>
{setupStrategyPanel()}
+ <Show when={setupHandoffDisabled()}>
+ <p class="mt-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs leading-5 text-amber-800 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-200">
+ {setupHandoffDisabledReason()}
+ </p>
+ </Show>
<div class="space-y-3 text-xs">
{setupModeControls()}
@@ -601,8 +638,10 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
state.copyProxmoxAgentInstallCommand('pbs', 'Command copied to clipboard')
}
class="absolute top-2 right-2 p-1.5 text-slate-400 hover:text-white rounded bg-surface hover:bg-slate-700 transition-colors"
- title="Copy to clipboard"
- disabled={state.loadingAgentCommand()}
+ title={
+ setupHandoffDisabled() ? setupHandoffDisabledReason() : 'Copy to clipboard'
+ }
+ disabled={state.loadingAgentCommand() || setupHandoffDisabled()}
>
<Show
when={state.loadingAgentCommand()}
@@ -687,7 +726,10 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
);
}}
class="absolute top-2 right-2 p-1.5 text-slate-400 hover:text-slate-200 bg-surface-hover rounded-md transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ title={
+ setupHandoffDisabled() ? setupHandoffDisabledReason() : 'Copy command'
+ }
>
<svg
width="16"
@@ -764,7 +806,9 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
onClick={async () => {
await state.downloadProxmoxSetupScript('pbs');
}}
- class="w-full px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors text-sm font-medium"
+ disabled={setupHandoffDisabled()}
+ title={setupHandoffDisabled() ? setupHandoffDisabledReason() : undefined}
+ class="w-full px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors text-sm font-medium disabled:cursor-not-allowed disabled:opacity-50"
>
Download setup script
</button>
@@ -837,8 +881,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
const command = 'proxmox-backup-manager user create pulse-monitor@pbs';
await state.copyCommand(command);
}}
- class="absolute top-1 right-1 p-1 text-slate-500 hover:text-base-content transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ class={setupCommandButtonClass(
+ 'absolute top-1 right-1 p-1 text-slate-500 hover:text-base-content transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<svg
width="14"
@@ -870,8 +917,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
'proxmox-backup-manager user generate-token pulse-monitor@pbs pulse-token';
await state.copyCommand(command);
}}
- class="absolute top-1 right-1 p-1 text-slate-500 hover:text-base-content transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ class={setupCommandButtonClass(
+ 'absolute top-1 right-1 p-1 text-slate-500 hover:text-base-content transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<svg
width="14"
@@ -906,8 +956,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
'proxmox-backup-manager acl update / Audit --auth-id pulse-monitor@pbs';
await state.copyCommand(command);
}}
- class="absolute top-1 right-1 p-1 hover:text-muted transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ class={setupCommandButtonClass(
+ 'absolute top-1 right-1 p-1 hover:text-muted transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<svg
width="14"
@@ -933,8 +986,11 @@ export const NodeModalSetupGuideSection: Component<NodeModalSetupGuideSectionPro
"proxmox-backup-manager acl update / Audit --auth-id 'pulse-monitor@pbs!pulse-token'";
await state.copyCommand(command);
}}
- class="absolute top-1 right-1 p-1 hover:text-muted transition-colors"
- title="Copy command"
+ disabled={setupHandoffDisabled()}
+ class={setupCommandButtonClass(
+ 'absolute top-1 right-1 p-1 hover:text-muted transition-colors',
+ )}
+ title={setupCommandButtonTitle()}
>
<svg
width="14"
diff --git a/frontend-modern/src/components/Settings/NodeModalStatusFooter.tsx b/frontend-modern/src/components/Settings/NodeModalStatusFooter.tsx
index 04d39b3b14..da358aa00d 100644
--- a/frontend-modern/src/components/Settings/NodeModalStatusFooter.tsx
+++ b/frontend-modern/src/components/Settings/NodeModalStatusFooter.tsx
@@ -13,6 +13,8 @@ interface NodeModalStatusFooterProps {
deletePending?: boolean;
deleteConfirming?: boolean;
deleteError?: string | null;
+ saveDisabled?: boolean;
+ saveDisabledReason?: string;
}
export const NodeModalStatusFooter: Component<NodeModalStatusFooterProps> = (props) => {
@@ -210,7 +212,8 @@ export const NodeModalStatusFooter: Component<NodeModalStatusFooterProps> = (pro
<Show when={!guidedSetupOnlyMode()}>
<button
type="submit"
- disabled={props.togglePending || props.deletePending}
+ disabled={props.togglePending || props.deletePending || props.saveDisabled}
+ title={props.saveDisabled ? props.saveDisabledReason : undefined}
class="px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{state.isEditingExistingNode() ? 'Save changes' : 'Add node'}
diff --git a/frontend-modern/src/components/Settings/__tests__/NodeModalSetupGuideSection.test.tsx b/frontend-modern/src/components/Settings/__tests__/NodeModalSetupGuideSection.test.tsx
index cb13799cf6..d9b47f5f51 100644
--- a/frontend-modern/src/components/Settings/__tests__/NodeModalSetupGuideSection.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/NodeModalSetupGuideSection.test.tsx
@@ -7,8 +7,14 @@ import { NodeModalSetupGuideSection } from '../NodeModalSetupGuideSection';
const renderSetupGuide = (
nodeType: NodeModalNodeType = 'pve',
- options: { isEditingExistingNode?: boolean } = {},
+ options: {
+ isEditingExistingNode?: boolean;
+ setupHandoffDisabled?: boolean;
+ setupHandoffDisabledReason?: string;
+ } = {},
) => {
+ const copyCommand = vi.fn();
+ const copyQuickSetupCommand = vi.fn();
const Harness = () => {
const [setupMode, setSetupMode] = createSignal<NodeModalSetupMode>('auto');
const updateField = vi.fn((field: string, value: string | boolean | number) => {
@@ -20,9 +26,9 @@ const renderSetupGuide = (
const state = {
agentCommandError: () => null,
agentInstallCommand: () => '',
- copyCommand: vi.fn(),
+ copyCommand,
copyProxmoxAgentInstallCommand: vi.fn(),
- copyQuickSetupCommand: vi.fn(),
+ copyQuickSetupCommand,
downloadProxmoxSetupScript: vi.fn(),
formData: () => ({ setupMode: setupMode(), host: '' }),
isAdvancedSetupMode: () => setupMode() === 'manual',
@@ -35,10 +41,25 @@ const renderSetupGuide = (
updateField,
} as unknown as NodeModalState;
- return <NodeModalSetupGuideSection modalProps={{ nodeType } as any} state={state} />;
+ return (
+ <NodeModalSetupGuideSection
+ modalProps={
+ {
+ nodeType,
+ setupHandoffDisabled:
+ options.setupHandoffDisabled === undefined
+ ? undefined
+ : () => Boolean(options.setupHandoffDisabled),
+ setupHandoffDisabledReason: options.setupHandoffDisabledReason,
+ } as any
+ }
+ state={state}
+ />
+ );
};
render(() => <Harness />);
+ return { copyCommand, copyQuickSetupCommand };
};
describe('NodeModalSetupGuideSection', () => {
@@ -103,4 +124,47 @@ describe('NodeModalSetupGuideSection', () => {
expect(screen.getByText(/creates the Proxmox Backup Server API token/i)).toBeInTheDocument();
expect(screen.getAllByText(/without installing a root agent/i).length).toBeGreaterThan(0);
});
+
+ it('blocks guided setup handoff actions until an import plan is approved', () => {
+ const reason = 'Approve the import plan before generating setup commands.';
+ const { copyQuickSetupCommand } = renderSetupGuide('pve', {
+ setupHandoffDisabled: true,
+ setupHandoffDisabledReason: reason,
+ });
+
+ expect(screen.getByText(reason)).toBeInTheDocument();
+ const copyButton = screen.getAllByTitle(reason)[0];
+ expect(copyButton).toBeDisabled();
+
+ fireEvent.click(copyButton);
+
+ expect(copyQuickSetupCommand).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['pve' as const, /pveum user add pulse-monitor@pve/i],
+ ['pbs' as const, /proxmox-backup-manager user create pulse-monitor@pbs/i],
+ ])(
+ 'blocks %s manual token command copies until an import plan is approved',
+ (nodeType, command) => {
+ const reason = 'Approve the import plan before generating setup commands.';
+ const { copyCommand } = renderSetupGuide(nodeType, {
+ setupHandoffDisabled: true,
+ setupHandoffDisabledReason: reason,
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /^Manual Token Setup$/i }));
+
+ expect(screen.getByText(command)).toBeInTheDocument();
+ const disabledCopyButtons = screen.getAllByTitle(reason);
+ expect(disabledCopyButtons.length).toBeGreaterThanOrEqual(4);
+ for (const button of disabledCopyButtons) {
+ expect(button).toBeDisabled();
+ }
+
+ fireEvent.click(disabledCopyButtons[0]);
+
+ expect(copyCommand).not.toHaveBeenCalled();
+ },
+ );
});
diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureImportPlanModel.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureImportPlanModel.test.ts
new file mode 100644
index 0000000000..edc27b81e4
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureImportPlanModel.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+import type { ProbeCandidate } from '@/api/connections';
+import { getNodeModalDefaultFormData } from '@/utils/nodeModalPresentation';
+import type { DiscoveredServer } from '../infrastructureSettingsModel';
+import { buildNodeImportPlan } from '../infrastructureImportPlanModel';
+
+describe('infrastructureImportPlanModel', () => {
+ it('maps discovered Proxmox nodes to the monitored-system preview contract', () => {
+ const discovered: DiscoveredServer = {
+ type: 'pve',
+ ip: '10.0.0.10',
+ hostname: 'tower.local',
+ port: 8006,
+ version: 'Proxmox VE',
+ release: '9.0',
+ };
+ const formData = {
+ ...getNodeModalDefaultFormData('pve'),
+ name: 'tower',
+ host: 'https://tower.local:8006',
+ authType: 'token',
+ setupMode: 'auto',
+ } as const;
+
+ const plan = buildNodeImportPlan('pve', formData, {
+ kind: 'discovery',
+ server: discovered,
+ });
+
+ expect(plan).not.toBeNull();
+ expect(plan?.source).toBe('proxmox');
+ expect(plan?.sourceLabel).toBe('Proxmox VE');
+ expect(plan?.endpoint).toBe('https://tower.local:8006');
+ expect(plan?.detectedVersion).toBe('Proxmox VE 9.0');
+ expect(plan?.previewRequest).toEqual({
+ candidate: {
+ source: 'proxmox',
+ type: 'agent',
+ name: 'tower',
+ hostname: 'tower.local',
+ host_url: 'https://tower.local:8006',
+ resource_id: 'tower',
+ },
+ });
+ });
+
+ it('builds PBS probe import plans with explicit coverage and source identity', () => {
+ const candidate: ProbeCandidate = {
+ type: 'pbs',
+ host: 'https://backup.local:8007',
+ port: 8007,
+ hints: {
+ product: 'Proxmox Backup Server',
+ version: '3.2',
+ },
+ };
+ const formData = {
+ ...getNodeModalDefaultFormData('pbs'),
+ name: 'backup',
+ host: 'https://backup.local:8007',
+ authType: 'token',
+ setupMode: 'auto',
+ monitorVerifyJobs: false,
+ monitorGarbageJobs: false,
+ } as const;
+
+ const plan = buildNodeImportPlan('pbs', formData, {
+ kind: 'probe',
+ candidate,
+ });
+
+ expect(plan).not.toBeNull();
+ expect(plan?.source).toBe('pbs');
+ expect(plan?.detectedVersion).toBe('Proxmox Backup Server 3.2');
+ expect(plan?.coverageLabel).toBe('datastores, sync jobs, prune jobs');
+ expect(plan?.previewRequest?.candidate).toMatchObject({
+ source: 'pbs',
+ type: 'pbs',
+ name: 'backup',
+ hostname: 'backup.local',
+ host_url: 'https://backup.local:8007',
+ resource_id: 'backup',
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 7c05cd06f5..3bd18f49ca 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -52,10 +52,12 @@ import infrastructureWorkspaceModelSource from '../infrastructureWorkspaceModel.
import useConnectionsLedgerSource from '../useConnectionsLedger.ts?raw';
import agentProfileSettingsSource from '../agentProfileSettings.ts?raw';
import monitoredSystemImpactPreviewSource from '../MonitoredSystemImpactPreview.tsx?raw';
+import infrastructureImportPlanModelSource from '../infrastructureImportPlanModel.ts?raw';
import connectionEditorSource from '../ConnectionEditor/ConnectionEditor.tsx?raw';
import addressProbeStepSource from '../ConnectionEditor/AddressProbeStep.tsx?raw';
import connectionEditorStateSource from '../ConnectionEditor/useConnectionEditor.ts?raw';
import nodeCredentialSlotSource from '../ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx?raw';
+import nodeCandidateImportPlanSource from '../ConnectionEditor/CredentialSlots/NodeCandidateImportPlan.tsx?raw';
import networkBoundarySettingsSectionSource from '../NetworkBoundarySettingsSection.tsx?raw';
import nodeModalBasicInfoSectionSource from '../NodeModalBasicInfoSection.tsx?raw';
import nodeModalAuthenticationSectionSource from '../NodeModalAuthenticationSection.tsx?raw';
@@ -1075,6 +1077,13 @@ describe('settings architecture guardrails', () => {
);
expect(infrastructureWorkspaceSource).toContain('reviewDiscoveredSource');
expect(infrastructureWorkspaceSource).toContain('selectedDiscoveredSource');
+ expect(infrastructureWorkspaceSource).toContain('selectedProbeCandidate');
+ expect(infrastructureWorkspaceSource).toContain('importCandidateForNodeType');
+ expect(infrastructureWorkspaceSource).toContain('importCandidate={importCandidate ?? null}');
+ expect(infrastructureWorkspaceSource).toContain(
+ "return { kind: 'discovery', server: discovered };",
+ );
+ expect(infrastructureWorkspaceSource).toContain("return { kind: 'probe', candidate: probed };");
expect(infrastructureWorkspaceSource).toContain(
"import { InfrastructureDiscoverySettingsDialog } from './InfrastructureDiscoverySettingsDialog';",
);
@@ -1123,6 +1132,10 @@ describe('settings architecture guardrails', () => {
'reuses your current monitored-system allowance',
);
expect(monitoredSystemImpactPreviewSource).not.toContain('frees monitored-system allowance');
+ expect(nodeCandidateImportPlanSource).toContain('aria-label="Candidate import plan"');
+ expect(nodeCandidateImportPlanSource).toContain('MonitoredSystemImpactPreview');
+ expect(nodeCandidateImportPlanSource).toContain('Preview impact');
+ expect(nodeCandidateImportPlanSource).toContain('Approve this import plan');
// Card-level description was dropped; the page-level subtitle from
// SETTINGS_HEADER_META carries the same intent without duplication.
expect(infrastructureSourceManagerSource).toContain('onReviewDiscoveredSource');
@@ -1257,6 +1270,15 @@ describe('settings architecture guardrails', () => {
expect(nodeCredentialSlotSource).toContain('<NodeModalMonitoringSection');
expect(nodeCredentialSlotSource).toContain('<NodeModalStatusFooter');
expect(nodeCredentialSlotSource).not.toContain('<Dialog');
+ expect(nodeCredentialSlotSource).toContain('buildNodeImportPlan');
+ expect(nodeCredentialSlotSource).toContain('MonitoredSystemLedgerAPI.preview');
+ expect(nodeCredentialSlotSource).toContain('<NodeCandidateImportPlan');
+ expect(nodeCredentialSlotSource).toContain('setupHandoffDisabled');
+ expect(nodeCredentialSlotSource).toContain('saveDisabled={saveBlockedByImportPlan()}');
+ expect(infrastructureImportPlanModelSource).toContain('MonitoredSystemLedgerPreviewRequest');
+ expect(infrastructureImportPlanModelSource).toContain('nodeTypeToMonitoredSource');
+ expect(infrastructureImportPlanModelSource).toContain('previewRequest');
+ expect(infrastructureImportPlanModelSource).toContain('resource_id: name');
expect(nodeModalAuthenticationSectionSource).toContain(
"state.formData().setupMode === 'manual'",
);
@@ -1273,7 +1295,10 @@ describe('settings architecture guardrails', () => {
expect(nodeModalSetupGuideSectionSource).toContain(
'PULSE_ENABLE_PROXMOX_GUEST_DOCKER_INVENTORY=true',
);
+ expect(nodeModalSetupGuideSectionSource).toContain('setupCommandButtonTitle');
+ expect(nodeModalSetupGuideSectionSource).toContain('disabled={setupHandoffDisabled()}');
expect(nodeModalStatusFooterSource).toContain('guidedSetupOnlyMode');
+ expect(nodeModalStatusFooterSource).toContain('props.saveDisabled');
expect(nodeModalStateSource).toContain("enableCommands: type === 'pve'");
expect(nodeModalStateSource).toContain('data.setupMode !==');
diff --git a/frontend-modern/src/components/Settings/infrastructureImportPlanModel.ts b/frontend-modern/src/components/Settings/infrastructureImportPlanModel.ts
new file mode 100644
index 0000000000..6e9d1ae764
--- /dev/null
+++ b/frontend-modern/src/components/Settings/infrastructureImportPlanModel.ts
@@ -0,0 +1,235 @@
+import type { ProbeCandidate } from '@/api/connections';
+import type { MonitoredSystemLedgerPreviewRequest } from '@/api/monitoredSystemLedger';
+import type { NodeModalFormData, NodeModalNodeType } from '@/utils/nodeModalPresentation';
+import { getNodeProductName } from '@/utils/nodeModalPresentation';
+import type { DiscoveredServer } from './infrastructureSettingsModel';
+import { deriveNameFromHost } from './nodeModalModel';
+
+export type NodeImportPlanCandidate =
+ | {
+ kind: 'discovery';
+ server: DiscoveredServer;
+ }
+ | {
+ kind: 'probe';
+ candidate: ProbeCandidate;
+ };
+
+export interface NodeImportPlanStep {
+ id: 'candidate' | 'credentials' | 'dry-run' | 'approval' | 'verification';
+ title: string;
+ detail: string;
+}
+
+export interface NodeImportPlan {
+ signature: string;
+ nodeType: NodeModalNodeType;
+ source: 'proxmox' | 'pbs' | 'pmg';
+ sourceLabel: string;
+ endpoint: string;
+ hostname: string;
+ name: string;
+ detectedVersion: string;
+ candidateLabel: string;
+ credentialLabel: string;
+ coverageLabel: string;
+ steps: NodeImportPlanStep[];
+ previewRequest: MonitoredSystemLedgerPreviewRequest | null;
+}
+
+const nodeTypeToMonitoredSource = (nodeType: NodeModalNodeType): NodeImportPlan['source'] => {
+ switch (nodeType) {
+ case 'pve':
+ return 'proxmox';
+ case 'pbs':
+ return 'pbs';
+ case 'pmg':
+ return 'pmg';
+ }
+};
+
+const nodeTypeToResourceType = (nodeType: NodeModalNodeType): string => {
+ switch (nodeType) {
+ case 'pve':
+ return 'agent';
+ case 'pbs':
+ return 'pbs';
+ case 'pmg':
+ return 'pmg';
+ }
+};
+
+const normalizeEndpoint = (endpoint: string): string => endpoint.trim();
+
+const hostnameFromEndpoint = (endpoint: string): string => {
+ const trimmed = endpoint.trim();
+ if (!trimmed) return '';
+
+ try {
+ const url = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://${trimmed}`);
+ return url.hostname || trimmed;
+ } catch {
+ return (
+ trimmed
+ .replace(/^https?:\/\//i, '')
+ .split('/')[0]
+ ?.split(':')[0] ?? trimmed
+ );
+ }
+};
+
+const endpointFromCandidate = (candidate: NodeImportPlanCandidate): string => {
+ if (candidate.kind === 'probe') {
+ return normalizeEndpoint(candidate.candidate.host);
+ }
+ const host = candidate.server.hostname?.trim() || candidate.server.ip.trim();
+ return `https://${host}:${candidate.server.port}`;
+};
+
+const versionFromCandidate = (candidate: NodeImportPlanCandidate): string => {
+ if (candidate.kind === 'probe') {
+ const product = candidate.candidate.hints?.product?.trim();
+ const version = candidate.candidate.hints?.version?.trim();
+ return [product, version].filter(Boolean).join(' ') || 'Detected API endpoint';
+ }
+ return [candidate.server.version, candidate.server.release].filter(Boolean).join(' ');
+};
+
+const candidateLabel = (candidate: NodeImportPlanCandidate): string => {
+ if (candidate.kind === 'probe') {
+ return `Detected API probe at ${candidate.candidate.host}`;
+ }
+ const host = candidate.server.hostname?.trim() || candidate.server.ip;
+ return `Discovery candidate at ${host}:${candidate.server.port}`;
+};
+
+const credentialLabel = (formData: NodeModalFormData): string => {
+ if (formData.authType === 'password') {
+ return 'Validate username and password credentials before saving.';
+ }
+ if (formData.setupMode === 'manual') {
+ return 'Validate the supplied API token before saving.';
+ }
+ if (formData.setupMode === 'agent') {
+ return 'Run the Host Telemetry Agent handoff; Pulse will add the source after the agent reports.';
+ }
+ return 'Run the API Inventory setup handoff; Pulse will add the source after setup completes.';
+};
+
+const coverageLabel = (nodeType: NodeModalNodeType, formData: NodeModalFormData): string => {
+ if (nodeType === 'pve') {
+ const enabled = [
+ formData.monitorVMs ? 'VMs' : '',
+ formData.monitorContainers ? 'containers' : '',
+ formData.monitorStorage ? 'storage' : '',
+ formData.monitorBackups ? 'backups' : '',
+ formData.monitorPhysicalDisks ? 'SMART disks' : '',
+ ].filter(Boolean);
+ return enabled.length > 0 ? enabled.join(', ') : 'No Proxmox collectors selected';
+ }
+ if (nodeType === 'pbs') {
+ const enabled = [
+ formData.monitorDatastores ? 'datastores' : '',
+ formData.monitorSyncJobs ? 'sync jobs' : '',
+ formData.monitorVerifyJobs ? 'verify jobs' : '',
+ formData.monitorPruneJobs ? 'prune jobs' : '',
+ formData.monitorGarbageJobs ? 'garbage collection' : '',
+ ].filter(Boolean);
+ return enabled.length > 0 ? enabled.join(', ') : 'No PBS collectors selected';
+ }
+ const enabled = [
+ formData.monitorMailStats ? 'mail stats' : '',
+ formData.monitorQueues ? 'queues' : '',
+ formData.monitorQuarantine ? 'quarantine' : '',
+ formData.monitorDomainStats ? 'domain stats' : '',
+ ].filter(Boolean);
+ return enabled.length > 0 ? enabled.join(', ') : 'No PMG collectors selected';
+};
+
+const buildSteps = (plan: Omit<NodeImportPlan, 'steps'>): NodeImportPlanStep[] => [
+ {
+ id: 'candidate',
+ title: 'Candidate',
+ detail: plan.candidateLabel,
+ },
+ {
+ id: 'credentials',
+ title: 'Credentials',
+ detail: plan.credentialLabel,
+ },
+ {
+ id: 'dry-run',
+ title: 'Dry-run impact',
+ detail:
+ 'Preview whether this source creates a new monitored system or attaches to an existing one.',
+ },
+ {
+ id: 'approval',
+ title: 'Approval',
+ detail:
+ 'Approve the current endpoint, credential path, and collection scope before any setup handoff or manual save.',
+ },
+ {
+ id: 'verification',
+ title: 'Verification',
+ detail:
+ 'After the handoff or save, Pulse refreshes connected systems and discovery candidates.',
+ },
+];
+
+export const buildNodeImportPlan = (
+ nodeType: NodeModalNodeType,
+ formData: NodeModalFormData,
+ candidate: NodeImportPlanCandidate | null | undefined,
+): NodeImportPlan | null => {
+ if (!candidate) return null;
+
+ const endpoint = normalizeEndpoint(formData.host) || endpointFromCandidate(candidate);
+ const hostname = hostnameFromEndpoint(endpoint);
+ const name = formData.name.trim() || deriveNameFromHost(endpoint) || hostname;
+ const source = nodeTypeToMonitoredSource(nodeType);
+ const sourceLabel = getNodeProductName(nodeType);
+ const detectedVersion = versionFromCandidate(candidate);
+ const candidateSummary = candidateLabel(candidate);
+ const coverageSummary = coverageLabel(nodeType, formData);
+ const basePlan = {
+ signature: [
+ source,
+ candidateSummary,
+ detectedVersion,
+ name,
+ endpoint,
+ formData.authType,
+ formData.setupMode,
+ coverageSummary,
+ ].join('|'),
+ nodeType,
+ source,
+ sourceLabel,
+ endpoint,
+ hostname,
+ name,
+ detectedVersion,
+ candidateLabel: candidateSummary,
+ credentialLabel: credentialLabel(formData),
+ coverageLabel: coverageSummary,
+ previewRequest:
+ endpoint && name
+ ? {
+ candidate: {
+ source,
+ type: nodeTypeToResourceType(nodeType),
+ name,
+ hostname,
+ host_url: endpoint,
+ resource_id: name,
+ },
+ }
+ : null,
+ };
+
+ return {
+ ...basePlan,
+ steps: buildSteps(basePlan),
+ };
+};
diff --git a/frontend-modern/src/components/Settings/nodeModalModel.ts b/frontend-modern/src/components/Settings/nodeModalModel.ts
index a92921b542..f562ca6387 100644
--- a/frontend-modern/src/components/Settings/nodeModalModel.ts
+++ b/frontend-modern/src/components/Settings/nodeModalModel.ts
@@ -17,6 +17,8 @@ export interface NodeModalProps {
temperatureMonitoringLocked?: boolean;
savingTemperatureSetting?: boolean;
onToggleTemperatureMonitoring?: (enabled: boolean) => Promise<void> | void;
+ setupHandoffDisabled?: () => boolean;
+ setupHandoffDisabledReason?: string;
}
export const deriveNameFromHost = (host: string): string => {
diff --git a/internal/api/auth.go b/internal/api/auth.go
index 6fce974edd..66868d5583 100644
--- a/internal/api/auth.go
+++ b/internal/api/auth.go
@@ -825,16 +825,16 @@ func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, write
}
return false
}
- // Check username
- userMatch := constantTimeStringEqual(parts[0], cfg.AuthUser)
-
- // Check password - support both hashed and plain text for migration
- // Config always has hashed password now (auto-hashed on load)
- passMatch := internalauth.CheckPasswordHash(parts[1], cfg.AuthPass)
+ config.Mu.RLock()
+ cfgAuthUser := cfg.AuthUser
+ cfgAuthPass := cfg.AuthPass
+ config.Mu.RUnlock()
+ userMatch := constantTimeStringEqual(parts[0], cfgAuthUser)
+ passMatch := internalauth.CheckPasswordHash(parts[1], cfgAuthPass)
log.Debug().
Str("provided_user", parts[0]).
- Str("expected_user", cfg.AuthUser).
+ Str("expected_user", cfgAuthUser).
Bool("user_match", userMatch).
Bool("pass_match", passMatch).
Msg("Auth check")
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index c977828b73..761f885171 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -19622,3 +19622,36 @@ func TestContract_ProxyAuthConfiguredRoleHeaderMissingIsNonAdmin(t *testing.T) {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden)
}
}
+
+// TestContract_LocalAuthConfigReadsUseSharedLock pins the shared mutable-config
+// boundary for local username/password checks. Auth handlers may snapshot
+// credentials under the config lock, but must not read mutable auth fields
+// directly while hashing passwords or mutating sessions.
+func TestContract_LocalAuthConfigReadsUseSharedLock(t *testing.T) {
+ expectations := map[string][]string{
+ "auth.go": {
+ "config.Mu.RLock()\n\t\t\t\t\t\tcfgAuthUser := cfg.AuthUser\n\t\t\t\t\t\tcfgAuthPass := cfg.AuthPass\n\t\t\t\t\t\tconfig.Mu.RUnlock()",
+ "constantTimeStringEqual(parts[0], cfgAuthUser)",
+ "internalauth.CheckPasswordHash(parts[1], cfgAuthPass)",
+ },
+ "router.go": {
+ "config.Mu.RLock()\n\t\tauthConfigured := (r.config.AuthUser != \"\" && r.config.AuthPass != \"\")",
+ "r.config.ProxyAuthSecret != \"\"\n\t\tconfig.Mu.RUnlock()",
+ "cfgAuthUser := r.config.AuthUser\n\tcfgAuthPass := r.config.AuthPass",
+ "constantTimeStringEqual(loginReq.Username, cfgAuthUser) && auth.CheckPasswordHash(loginReq.Password, cfgAuthPass)",
+ },
+ }
+
+ for file, snippets := range expectations {
+ sourceBytes, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatalf("read %s: %v", file, err)
+ }
+ source := string(sourceBytes)
+ for _, snippet := range snippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("%s must contain %q", file, snippet)
+ }
+ }
+ }
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 5f7c2e9a20..84e7a686ee 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -4098,13 +4098,17 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
skipCSRF := false
// Quick setup can run before auth exists. Keep bootstrap/recovery flows usable
// without a prior session+CSRF pair, but enforce CSRF once auth is configured.
+ config.Mu.RLock()
authConfigured := (r.config.AuthUser != "" && r.config.AuthPass != "") ||
r.config.HasAPITokens() ||
- r.config.ProxyAuthSecret != "" ||
- (func() bool {
- ssoCfg := r.ensureSSOConfig()
- return ssoCfg != nil && ssoCfg.HasEnabledProviders()
- })()
+ r.config.ProxyAuthSecret != ""
+ config.Mu.RUnlock()
+ if !authConfigured {
+ ssoCfg := r.ensureSSOConfig()
+ if ssoCfg != nil && ssoCfg.HasEnabledProviders() {
+ authConfigured = true
+ }
+ }
validRecoveryToken := false
if recoveryToken := strings.TrimSpace(req.Header.Get("X-Recovery-Token")); recoveryToken != "" {
validRecoveryToken = GetRecoveryTokenStore().IsRecoveryTokenValidConstantTime(recoveryToken, clientIP)
@@ -5103,7 +5107,11 @@ func (r *Router) handleLogin(w http.ResponseWriter, req *http.Request) {
}
// Verify credentials (or accept any credentials when admin bypass is enabled)
- credentialsValid := constantTimeStringEqual(loginReq.Username, r.config.AuthUser) && auth.CheckPasswordHash(loginReq.Password, r.config.AuthPass)
+ config.Mu.RLock()
+ cfgAuthUser := r.config.AuthUser
+ cfgAuthPass := r.config.AuthPass
+ config.Mu.RUnlock()
+ credentialsValid := constantTimeStringEqual(loginReq.Username, cfgAuthUser) && auth.CheckPasswordHash(loginReq.Password, cfgAuthPass)
effectiveUsername := loginReq.Username
if adminBypassEnabled() {
credentialsValid = true
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index a7114b6450..19b6aef130 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -2232,6 +2232,24 @@ func TestReloadAndRuntimeContextStayOnCanonicalMonitoringPath(t *testing.T) {
}
}
+func TestUnifiedStorageMetricsFallbackToResourceIDWhenResolverTargetMissing(t *testing.T) {
+ data, err := os.ReadFile("monitor.go")
+ if err != nil {
+ t.Fatalf("failed to read monitor.go: %v", err)
+ }
+ source := string(data)
+ for _, snippet := range []string{
+ "target := resolver.MetricsTargetForResource(resource.ID)",
+ "if target != nil && target.ResourceType == \"storage\" && strings.TrimSpace(target.ResourceID) != \"\" {",
+ "targetID = strings.TrimSpace(target.ResourceID)",
+ "} else {\n\t\t\ttargetID = resource.ID\n\t\t}",
+ } {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("monitor.go must contain %q", snippet)
+ }
+ }
+}
+
// TestPollersHonorDisabledInstanceFlag asserts that the PVE, PBS, and PMG
// pollers skip instances whose `Disabled` flag is set, both at client
// initialization/reconnect time and on every per-instance iteration of the
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 6971f79acb..0f3101ebae 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -4813,10 +4813,12 @@ func (m *Monitor) syncUnifiedStorageMetrics(store ResourceStoreInterface) {
}
target := resolver.MetricsTargetForResource(resource.ID)
- if target == nil || target.ResourceType != "storage" || strings.TrimSpace(target.ResourceID) == "" {
- continue
+ var targetID string
+ if target != nil && target.ResourceType == "storage" && strings.TrimSpace(target.ResourceID) != "" {
+ targetID = strings.TrimSpace(target.ResourceID)
+ } else {
+ targetID = resource.ID
}
- targetID := strings.TrimSpace(target.ResourceID)
if _, ok := seenTargets[targetID]; ok {
continue
}
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index d94cea72cb..70d5c5b512 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -2917,7 +2917,7 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Shared Boundaries",
"path": "internal/api/access_control_handlers.go",
- "line": 1114,
+ "line": 1131,
"heading_line": 137,
}
],