From ea4c3b8cf626aafa44fb821364dfd719e0b26cdc Mon Sep 17 00:00:00 2001 From: rcourtman <8825017+rcourtman@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:29:14 +0000 Subject: [PATCH] Add opt-in unattended updates for Pulse Pro installations Add an in-process overnight auto-updater for activated Pulse Pro systemd and Proxmox VE installations with deterministic per-install jitter, durable attempt state and failed-version suppression, apply-time version pinning, major-upgrade refusal, Pro edition binary self-test verification, shared installation-directory flock locking, graceful shutdown restart handoff, explicit autoUpdateProConsent gating so dormant configs never self-activate, and a server-side PULSE_DISABLE_AUTO_UPDATE host veto. --- .../v6/internal/subsystems/agent-lifecycle.md | 2 + .../v6/internal/subsystems/api-contracts.md | 2 + .../subsystems/deployment-installability.md | 2 + .../subsystems/frontend-primitives.md | 2 + .../internal/subsystems/security-privacy.md | 2 + .../internal/subsystems/storage-recovery.md | 2 + .../0564c3d7c366bcb6.json | 56 +++ .../Settings/UpdatesSettingsPanel.tsx | 7 + .../UpdatesSettingsPanel.autoUpdate.test.tsx | 59 ++- .../__tests__/settingsArchitecture.test.ts | 12 +- .../__tests__/useSystemSettingsState.test.ts | 52 ++ .../Settings/useSettingsSystemPanels.tsx | 2 + .../Settings/useSystemSettingsState.ts | 76 ++- frontend-modern/src/types/config.ts | 7 + .../__tests__/updatesPresentation.test.ts | 67 +++ .../src/utils/updatesPresentation.ts | 37 +- .../api/configapi/config_system_handlers.go | 1 + internal/api/router.go | 24 +- internal/api/system_settings.go | 51 +- .../api/system_settings_auto_update_test.go | 115 +++++ internal/config/config.go | 45 +- internal/config/config_load_test.go | 13 + internal/config/persistence.go | 1 + internal/updates/auto_update_capability.go | 82 +++- .../updates/auto_update_capability_test.go | 74 ++- internal/updates/history.go | 11 +- internal/updates/install_lock_other.go | 11 + internal/updates/install_lock_unix.go | 63 +++ internal/updates/manager.go | 114 ++++- internal/updates/pro_auto_update.go | 443 ++++++++++++++++++ internal/updates/pro_auto_update_test.go | 208 ++++++++ internal/updates/selftest.go | 14 + internal/updates/selftest_test.go | 12 + pkg/server/server.go | 13 + .../pulse_auto_update_consent_test.go | 23 + scripts/pulse-auto-update.sh | 4 + 36 files changed, 1640 insertions(+), 69 deletions(-) create mode 100644 frontend-modern/browser-verification/0564c3d7c366bcb6.json create mode 100644 internal/updates/install_lock_other.go create mode 100644 internal/updates/install_lock_unix.go create mode 100644 internal/updates/pro_auto_update.go create mode 100644 internal/updates/pro_auto_update_test.go diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md index 2bbba643f3..3619e0b461 100644 --- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md +++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md @@ -5807,6 +5807,8 @@ Agent` secondary handoff against the live setup wizard instead of relying ## Current State +- Server update coordination touchpoint (2026-11-30): `internal/api/router.go`, `internal/api/system_settings.go`, and `internal/api/configapi/config_system_handlers.go` wire Pulse Pro update capability detection, `SetUpdateRestartHook`, and `StartProAutoUpdater` without altering agent registration, transport, or host-agent lifecycle behavior. + `internal/api/router.go` now gives Patrol a read of a Proxmox node's task log (`newProxmoxGuestTaskReader`, `internal/api/proxmox_guest_stop_tasks.go`), and `internal/api/patrol_action_broker.go` can add one sentence to a start diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md index 94d96bc9be..9fc2d7618e 100644 --- a/docs/release-control/v6/internal/subsystems/api-contracts.md +++ b/docs/release-control/v6/internal/subsystems/api-contracts.md @@ -6443,6 +6443,8 @@ auto-register mutation boundary. ## Current State +- Unattended Pulse Pro settings contract (2026-11-30): `GET /api/system/settings`, `POST /api/system/settings/update`, `/api/config`, and `configapi` now carry `autoUpdateProConsent`, report `autoUpdateCapability.mechanism` (`systemd_timer` or `in_app`) plus `env_disabled`, `pro_not_activated`, and `binary_not_writable` reasons, normalize dormant Pro `autoUpdateEnabled: true` configs off without explicit `autoUpdateProConsent`, expose `envOverrides.autoUpdateEnabled` when `PULSE_DISABLE_AUTO_UPDATE` is active, and return HTTP 409 `env_locked` if a request attempts to enable auto-updates while the host env veto is set. + ### Token revocation preserves its saved inventory position Closing the existing revoke confirmation does not make its trigger a durable diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md index 99fb3d6064..5ecb39c246 100644 --- a/docs/release-control/v6/internal/subsystems/deployment-installability.md +++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md @@ -4888,6 +4888,8 @@ installed removal, credential revocation, publication or whole-issue recovery. ## Current State +- Unattended Pulse Pro updates (2026-11-30): Activated Pulse Pro systemd and Proxmox VE installations now support opt-in overnight in-app updates via `internal/updates/pro_auto_update.go` (02:00 to 06:00 local time with deterministic per-install jitter, durable state and failed-version suppression in `/pro-auto-update-state.json`, and startup reconciliation via `ReconcilePendingProAutoUpdate`). `ApplyUpdate` pins `ExpectedVersion`, enforces `RejectMajorUpgrade`, verifies the `Pulse Pro ` version prefix in `selfTestNewBinaryWithOptions`, acquires the shared installation-directory `flock` (`internal/updates/install_lock_unix.go`) also used by `RollbackToBackup` and `scripts/pulse-auto-update.sh`, runs `PreApplyCheck` before backup or binary mutation, and hands off restart through `SetRestartHook` into `pkg/server/server.go`'s graceful shutdown drain while keeping operation admission closed. `PULSE_DISABLE_AUTO_UPDATE` acts as a server-side and script-side host veto. + ### Opt-in Preview channel automatic updates and host capability detection (30 November 2026) `scripts/pulse-auto-update.sh` now supports explicit opt-in unattended updates on the `rc` (Preview) channel in addition to `stable`, while preserving all existing stable-only, signature, edition, lock, and rollback gates: diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md index d7365f7549..572a890e01 100644 --- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md +++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md @@ -5643,6 +5643,8 @@ resolves late` in ## Current State +- Unattended Pulse Pro Settings UI (2026-11-30): `UpdatesSettingsPanel`, `useSystemSettingsState`, `useSettingsSystemPanels`, `types/config.ts`, and `updatesPresentation.ts` now support activated Pulse Pro in-app overnight updates on Stable and Preview, track `autoUpdateProConsent` and `autoUpdateEnvLocked`, keep dormant Pro configs off until explicitly opted in, show Pulse Pro's built-in overnight schedule note when active, omit auto-update fields on unrelated saves under `PULSE_DISABLE_AUTO_UPDATE`, and explain `env_disabled`, `pro_not_activated`, and `binary_not_writable` states clearly. + ### Infrastructure Map live glanceable visual encodings and real-estate host diagram polish (27 November 2026) `renderMapSceneBody` (`infrastructureMapRender.ts`) and `infrastructureMap.css` now scale active connector flow speed smoothly from live throughput (`flowDurationForBytes`, 3.4s at 10 KB/s down to 0.45s at 100 MB/s+), add a soft outer glow (`.pulse-map-flow-glow`) on heavy connectors carrying at least 5 MB/s, and render `.pulse-map-spike` on spiking service tiles (omitted in static SVG/PNG exports and stopped under `prefers-reduced-motion: reduce`). `layoutHostDiagram` (`infrastructureMapHostDiagram.ts`) adds 2px proportional bottom traffic bars on active service cards, elevated-only 2px top load heat bars (`attention` at 75%+ CPU/RAM or 75°C+, `critical` at 90%+ or 85°C+, silent when calm) on hosts and workloads, bounded log-scaled proportional storage track widths (`proportionalStorageTrackWidth`) backed by `DiagramTile.totalBytes`, increased vertical bus drop clearance (`BUS_DROP = 32`, `LAYER_GAP = 44`, `FRAME_ROW_GAP = 44`), dashed orthogonal elbows from beside-positioned default gateways into the network trunk, bottom-aligned cluster `STORAGE` + `DISKS` footers, suffix-preserving card title truncation (`fitCardTitle`), and workload-aware host counts (`containers`, `guests`, `workloads`) on generic machine hosts. diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md index 0c352eaf36..0ba0b907e5 100644 --- a/docs/release-control/v6/internal/subsystems/security-privacy.md +++ b/docs/release-control/v6/internal/subsystems/security-privacy.md @@ -2783,6 +2783,8 @@ database grew past it. `TestSQLiteLoggerUsesSharedPageCacheBound` and ## Current State +- Unattended Pulse Pro consent and host veto boundary (2026-11-30): `internal/config/config.go` and `internal/api/system_settings.go` enforce `PULSE_DISABLE_AUTO_UPDATE` as a host-level veto that cannot be bypassed through the UI or API (HTTP 409 `env_locked`), require explicit `autoUpdateProConsent` so dormant Pro configs never self-activate on upgrade, re-verify consent and credentials right before binary mutation inside `PreApplyCheck`, and persist Pro updater state with `0600` permissions via atomic temp-file sync and rename. + ### Docker update step codes add no new data to the agent boundary A typed Docker update that stops before changing the container now reports diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md index 481960d28c..310a5f713c 100644 --- a/docs/release-control/v6/internal/subsystems/storage-recovery.md +++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md @@ -5171,6 +5171,8 @@ vdev layout is reported` in ## Current State +- Persisted system settings and graceful shutdown touchpoint (2026-11-30): `system.json` adds `autoUpdateProConsent` through `internal/api/system_settings.go` and `configapi`, while `internal/api/router.go` routes in-app update restarts through `pkg/server/server.go`'s graceful shutdown drain so open stores and background workers flush cleanly before restart. + ### Docker update pull truth opens no storage or recovery path The telemetry change under `internal/api/` maps the new Docker update step diff --git a/frontend-modern/browser-verification/0564c3d7c366bcb6.json b/frontend-modern/browser-verification/0564c3d7c366bcb6.json new file mode 100644 index 0000000000..eebb0dd877 --- /dev/null +++ b/frontend-modern/browser-verification/0564c3d7c366bcb6.json @@ -0,0 +1,56 @@ +{ + "version": 1, + "base_sha": "a735ba03e0dc677d6667f7b263afd98d2c23590d", + "verified_at": "2026-11-30T12:29:10Z", + "result": "passed", + "changed_paths": [ + "frontend-modern/src/components/Settings/UpdatesSettingsPanel.tsx", + "frontend-modern/src/components/Settings/useSettingsSystemPanels.tsx", + "frontend-modern/src/components/Settings/useSystemSettingsState.ts", + "frontend-modern/src/types/config.ts", + "frontend-modern/src/utils/updatesPresentation.ts" + ], + "content_sha256": { + "frontend-modern/src/components/Settings/UpdatesSettingsPanel.tsx": "952bc561328aa9639abd2fb1a01fed1d0e7eadc68bb53e38ae2022d4d871dc05", + "frontend-modern/src/components/Settings/useSettingsSystemPanels.tsx": "8354caa1fd41b40c7640f3b913d9de44edcadb14cbde45e89be1400dc6fc6711", + "frontend-modern/src/components/Settings/useSystemSettingsState.ts": "4315417a23038ddb727789c5881c22c5dbf8841c0023f6ad21db63d1fea20e31", + "frontend-modern/src/types/config.ts": "b05b078ac778e86c0af5ed0b81204228dddef84ec8709187f199760145873f0f", + "frontend-modern/src/utils/updatesPresentation.ts": "a22b4e6530b62088f7fa679a025dd1eaca2c734f55e5af803244952c60b0f3e1" + }, + "routes": [ + "/settings/system-updates" + ], + "viewports": [ + { + "width": 1440, + "height": 900 + }, + { + "width": 390, + "height": 844 + } + ], + "states": [ + "replace with every state inspected" + ], + "interactions": [ + "replace with every interaction exercised" + ], + "tool": "playwright", + "states_checked": [ + "dormant Pro autoUpdateEnabled:true without autoUpdateProConsent renders toggle OFF and enabled", + "activated Pro Stable explicit opt-in saves autoUpdateProConsent:true and survives reload with Pro overnight schedule note", + "switching Pro Stable to Preview resets toggle OFF, explicit Preview opt-in saves autoUpdateProConsent:true and autoUpdatePreviewConsent:true and survives reload", + "mobile 390x844 layout stacks cleanly with zero horizontal overflow", + "pro_not_activated disables toggle with license activation notice", + "binary_not_writable disables toggle with binary directory permission notice", + "PULSE_DISABLE_AUTO_UPDATE env_disabled locks toggle OFF with env veto notice" + ], + "interactions_checked": [ + "toggled Automatic Updates ON on Pro Stable, clicked Save, verified POST payload and system.json on disk, reloaded page", + "clicked Preview channel card, verified toggle reset OFF, toggled Automatic Updates ON on Pro Preview, clicked Save, verified POST payload and system.json on disk, reloaded page", + "resized viewport to 390x844 and verified zero horizontal overflow", + "inspected all 7 desktop and mobile screenshots visually with zero pageerror or console error events" + ], + "notes": "Verified against a compiled edition.Pro Pulse binary embedding the current production frontend build at /settings/system-updates across desktop 1440x900 and mobile 390x844 with zero page or console errors." +} diff --git a/frontend-modern/src/components/Settings/UpdatesSettingsPanel.tsx b/frontend-modern/src/components/Settings/UpdatesSettingsPanel.tsx index f4c688f56f..3e4a7763df 100644 --- a/frontend-modern/src/components/Settings/UpdatesSettingsPanel.tsx +++ b/frontend-modern/src/components/Settings/UpdatesSettingsPanel.tsx @@ -54,6 +54,8 @@ export interface UpdatesSettingsPanelProps { autoUpdateEnabled: Accessor; setAutoUpdateEnabled: Setter; setAutoUpdatePreviewConsent?: Setter; + setAutoUpdateProConsent?: Setter; + autoUpdateEnvLocked?: Accessor; autoUpdateCapability?: Accessor; checkForUpdates: () => Promise; setHasUnsavedChanges: Setter; @@ -79,12 +81,15 @@ export const UpdatesSettingsPanel: Component = (props // a Pro-runtime install must never be shown community pull commands. const isProRuntime = () => runtimeCapabilities()?.runtime?.build === 'pro'; const isPreviewChannel = () => props.updateChannel() === 'rc'; + const isInAppProAutoUpdate = () => + isProRuntime() || props.autoUpdateCapability?.()?.mechanism === 'in_app'; const autoUpdateControl = () => getAutoUpdateControlState({ channel: props.updateChannel(), versionInfo: props.versionInfo(), isProRuntime: isProRuntime(), capability: props.autoUpdateCapability?.(), + envLocked: props.autoUpdateEnvLocked?.(), }); const autoUpdateLocked = () => !autoUpdateControl().supported; const updateChannelOptions = (): SelectionCardOption[] => @@ -360,6 +365,7 @@ export const UpdatesSettingsPanel: Component = (props props.setAutoUpdatePreviewConsent?.(false); if (value === 'rc') { props.setAutoUpdateEnabled(false); + props.setAutoUpdateProConsent?.(false); } } props.setUpdateChannel(value); @@ -416,6 +422,7 @@ export const UpdatesSettingsPanel: Component = (props const checked = e.currentTarget.checked; props.setAutoUpdateEnabled(checked); props.setAutoUpdatePreviewConsent?.(isPreviewChannel() && checked); + props.setAutoUpdateProConsent?.(isInAppProAutoUpdate() && checked); props.setHasUnsavedChanges(true); }} disabled={autoUpdateLocked()} diff --git a/frontend-modern/src/components/Settings/__tests__/UpdatesSettingsPanel.autoUpdate.test.tsx b/frontend-modern/src/components/Settings/__tests__/UpdatesSettingsPanel.autoUpdate.test.tsx index db3ebb569d..7ef74e0894 100644 --- a/frontend-modern/src/components/Settings/__tests__/UpdatesSettingsPanel.autoUpdate.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/UpdatesSettingsPanel.autoUpdate.test.tsx @@ -15,6 +15,7 @@ describe('UpdatesSettingsPanel automatic update controls', () => { initialChannel?: 'stable' | 'rc'; initialAutoUpdate?: boolean; capability?: AutoUpdateCapability | null; + envLocked?: boolean; } = {}, ) => { const [updateChannel, setUpdateChannel] = createSignal<'stable' | 'rc'>( @@ -24,6 +25,7 @@ describe('UpdatesSettingsPanel automatic update controls', () => { options.initialAutoUpdate ?? false, ); const [previewConsent, setPreviewConsent] = createSignal(false); + const [proConsent, setProConsent] = createSignal(false); const setHasUnsavedChanges = vi.fn(); render(() => ( @@ -44,6 +46,8 @@ describe('UpdatesSettingsPanel automatic update controls', () => { autoUpdateEnabled={autoUpdateEnabled} setAutoUpdateEnabled={setAutoUpdateEnabled} setAutoUpdatePreviewConsent={setPreviewConsent} + setAutoUpdateProConsent={setProConsent} + autoUpdateEnvLocked={() => Boolean(options.envLocked)} autoUpdateCapability={() => options.capability !== undefined ? options.capability @@ -57,7 +61,7 @@ describe('UpdatesSettingsPanel automatic update controls', () => { /> )); - return { updateChannel, autoUpdateEnabled, previewConsent, setHasUnsavedChanges }; + return { updateChannel, autoUpdateEnabled, previewConsent, proConsent, setHasUnsavedChanges }; }; it('resets auto-update off when switching from Stable to Preview and allows explicit Preview opt-in', () => { @@ -112,4 +116,57 @@ describe('UpdatesSettingsPanel automatic update controls', () => { UPDATES_PANEL_COPY.autoUpdatePreviewHelperOutdated, ); }); + + it('enables explicit Pulse Pro in-app opt-in and shows Pro overnight schedule note', () => { + const state = mountPanel({ + initialChannel: 'rc', + initialAutoUpdate: false, + capability: { supported: true, previewSupported: true, mechanism: 'in_app' }, + }); + + const toggle = screen.getByTestId('updates-auto-check-toggle') as HTMLInputElement; + expect(toggle.disabled).toBe(false); + expect(toggle.checked).toBe(false); + + fireEvent.click(toggle); + + expect(state.autoUpdateEnabled()).toBe(true); + expect(state.proConsent()).toBe(true); + expect(state.previewConsent()).toBe(true); + expect( + screen.getByText(UPDATES_PANEL_COPY.autoUpdateProPreviewScheduleNote), + ).toBeInTheDocument(); + }); + + it('locks the toggle when PULSE_DISABLE_AUTO_UPDATE or Pro activation blocks updates', () => { + mountPanel({ + initialChannel: 'stable', + initialAutoUpdate: true, + capability: { supported: true, previewSupported: true, mechanism: 'in_app' }, + envLocked: true, + }); + const envToggle = screen.getByTestId('updates-auto-check-toggle') as HTMLInputElement; + expect(envToggle.disabled).toBe(true); + expect(envToggle.checked).toBe(false); + expect(screen.getByTestId('updates-auto-update-unsupported-notice')).toHaveTextContent( + UPDATES_PANEL_COPY.autoUpdateUnsupportedEnvDisabled, + ); + + cleanup(); + mountPanel({ + initialChannel: 'stable', + initialAutoUpdate: false, + capability: { + supported: false, + previewSupported: false, + mechanism: 'in_app', + reason: 'pro_not_activated', + }, + }); + const unactivatedToggle = screen.getByTestId('updates-auto-check-toggle') as HTMLInputElement; + expect(unactivatedToggle.disabled).toBe(true); + expect(screen.getByTestId('updates-auto-update-unsupported-notice')).toHaveTextContent( + UPDATES_PANEL_COPY.autoUpdateUnsupportedProNotActivated, + ); + }); }); diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts index 7c16085c6a..5053a61f86 100644 --- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts +++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts @@ -369,7 +369,13 @@ describe('settings architecture guardrails', () => { it('wires preview auto-update consent and host capability through useSettingsSystemPanels', () => { const setAutoUpdatePreviewConsent = () => false; - const autoUpdateCapability = () => ({ supported: true, previewSupported: true }); + const setAutoUpdateProConsent = () => false; + const autoUpdateEnvLocked = () => false; + const autoUpdateCapability = () => ({ + supported: true, + previewSupported: true, + mechanism: 'in_app' as const, + }); const panels = useSettingsSystemPanels({ systemSettings: { versionInfo: () => null, @@ -380,6 +386,8 @@ describe('settings architecture guardrails', () => { autoUpdateEnabled: () => false, setAutoUpdateEnabled: () => false, setAutoUpdatePreviewConsent, + setAutoUpdateProConsent, + autoUpdateEnvLocked, autoUpdateCapability, checkForUpdates: async () => {}, setHasUnsavedChanges: () => false, @@ -395,6 +403,8 @@ describe('settings architecture guardrails', () => { }); const updatesProps = panels.getUpdatesPanelProps(); expect(updatesProps.setAutoUpdatePreviewConsent).toBe(setAutoUpdatePreviewConsent); + expect(updatesProps.setAutoUpdateProConsent).toBe(setAutoUpdateProConsent); + expect(updatesProps.autoUpdateEnvLocked).toBe(autoUpdateEnvLocked); expect(updatesProps.autoUpdateCapability).toBe(autoUpdateCapability); }); diff --git a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts index b618632486..fe7b8b8ece 100644 --- a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts +++ b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts @@ -667,6 +667,58 @@ describe('useSystemSettingsState', () => { dispose(); }); + it('keeps dormant Pulse Pro autoUpdateEnabled off until explicit Pro consent is granted', async () => { + getSystemSettingsMock.mockResolvedValue({ + updateChannel: 'stable', + autoUpdateEnabled: true, + autoUpdateProConsent: false, + autoUpdateCapability: { supported: true, previewSupported: true, mechanism: 'in_app' }, + }); + + const { hookState, dispose } = mountHook(); + await hookState.initializeSystemSettingsState(); + await flushAsync(); + + expect(hookState.autoUpdateEnabled()).toBe(false); + expect(hookState.autoUpdateProConsent()).toBe(false); + + hookState.setAutoUpdateEnabled(true); + hookState.setAutoUpdateProConsent(true); + await hookState.saveSettings(); + await flushAsync(); + + expect(updateSystemSettingsMock).toHaveBeenCalledWith( + expect.objectContaining({ + updateChannel: 'stable', + autoUpdateEnabled: true, + autoUpdateProConsent: true, + }), + ); + dispose(); + }); + + it('omits auto-update fields when saving unrelated settings under PULSE_DISABLE_AUTO_UPDATE', async () => { + getSystemSettingsMock.mockResolvedValue({ + updateChannel: 'stable', + autoUpdateEnabled: false, + envOverrides: { autoUpdateEnabled: true }, + autoUpdateCapability: { supported: false, previewSupported: false, reason: 'env_disabled' }, + }); + + const { hookState, dispose } = mountHook(); + await hookState.initializeSystemSettingsState(); + await flushAsync(); + + expect(hookState.autoUpdateEnvLocked()).toBe(true); + await hookState.saveSettings(); + await flushAsync(); + + const payload = updateSystemSettingsMock.mock.calls.at(-1)?.[0] as Record; + expect(payload).not.toHaveProperty('autoUpdateEnabled'); + expect(payload).not.toHaveProperty('autoUpdateProConsent'); + dispose(); + }); + it.each([true, false])( 'loads the full telemetry preview on demand (reporting available: %s)', async (reportingAvailable) => { diff --git a/frontend-modern/src/components/Settings/useSettingsSystemPanels.tsx b/frontend-modern/src/components/Settings/useSettingsSystemPanels.tsx index ce89db41b6..efc73ec14c 100644 --- a/frontend-modern/src/components/Settings/useSettingsSystemPanels.tsx +++ b/frontend-modern/src/components/Settings/useSettingsSystemPanels.tsx @@ -105,6 +105,8 @@ export function useSettingsSystemPanels( autoUpdateEnabled: params.systemSettings.autoUpdateEnabled, setAutoUpdateEnabled: params.systemSettings.setAutoUpdateEnabled, setAutoUpdatePreviewConsent: params.systemSettings.setAutoUpdatePreviewConsent, + setAutoUpdateProConsent: params.systemSettings.setAutoUpdateProConsent, + autoUpdateEnvLocked: params.systemSettings.autoUpdateEnvLocked, autoUpdateCapability: params.systemSettings.autoUpdateCapability, checkForUpdates: params.systemSettings.checkForUpdates, setHasUnsavedChanges: params.systemSettings.setHasUnsavedChanges, diff --git a/frontend-modern/src/components/Settings/useSystemSettingsState.ts b/frontend-modern/src/components/Settings/useSystemSettingsState.ts index ac9c344095..5ac1bc8fce 100644 --- a/frontend-modern/src/components/Settings/useSystemSettingsState.ts +++ b/frontend-modern/src/components/Settings/useSystemSettingsState.ts @@ -44,7 +44,13 @@ export function useSystemSettingsState({ channel: 'stable' | 'rc', enabled: boolean, previewConsent: boolean, - ) => (channel === 'stable' ? enabled : enabled && previewConsent); + isProInApp = false, + proConsent = false, + ) => { + if (!enabled) return false; + if (isProInApp && !proConsent) return false; + return channel === 'stable' ? true : previewConsent; + }; const [hasUnsavedChanges, setHasUnsavedChanges] = createSignal(false); const [pvePollingInterval, setPVEPollingInterval] = createSignal(PVE_POLLING_MIN_SECONDS); const [pvePollingSelection, setPVEPollingSelection] = createSignal( @@ -83,6 +89,7 @@ export function useSystemSettingsState({ const [updateChannel, setUpdateChannel] = createSignal<'stable' | 'rc'>('stable'); const [autoUpdateEnabled, setAutoUpdateEnabled] = createSignal(false); const [autoUpdatePreviewConsent, setAutoUpdatePreviewConsent] = createSignal(false); + const [autoUpdateProConsent, setAutoUpdateProConsent] = createSignal(false); const [autoUpdateCapability, setAutoUpdateCapability] = createSignal( null, ); @@ -99,6 +106,8 @@ export function useSystemSettingsState({ envOverrides().temperatureMonitoringEnabled || envOverrides()['ENABLE_TEMPERATURE_MONITORING'], ); + const autoUpdateEnvLocked = () => + Boolean(envOverrides().autoUpdateEnabled || envOverrides()['PULSE_DISABLE_AUTO_UPDATE']); const hideLocalLoginLocked = () => Boolean(envOverrides().hideLocalLogin || envOverrides()['PULSE_AUTH_HIDE_LOCAL_LOGIN']); const disableDockerUpdateActionsLocked = () => @@ -192,20 +201,38 @@ export function useSystemSettingsState({ setBackupPollingUseCustom(!isPresetInterval && intervalSeconds > 0); const savedUpdateChannel = systemSettings.updateChannel === 'rc' ? ('rc' as const) : ('stable' as const); + const savedCapability = systemSettings.autoUpdateCapability ?? null; + const savedIsProInApp = savedCapability?.mechanism === 'in_app'; + const savedEnvLocked = Boolean( + systemSettings.envOverrides?.autoUpdateEnabled || + systemSettings.envOverrides?.['PULSE_DISABLE_AUTO_UPDATE'], + ); + const savedProConsent = + !savedEnvLocked && + savedIsProInApp && + Boolean(systemSettings.autoUpdateEnabled) && + Boolean(systemSettings.autoUpdateProConsent); const savedPreviewConsent = + !savedEnvLocked && savedUpdateChannel === 'rc' && Boolean(systemSettings.autoUpdateEnabled) && - Boolean(systemSettings.autoUpdatePreviewConsent); + Boolean(systemSettings.autoUpdatePreviewConsent) && + (!savedIsProInApp || savedProConsent); setUpdateChannel(savedUpdateChannel); + setAutoUpdateProConsent(savedProConsent); setAutoUpdatePreviewConsent(savedPreviewConsent); setAutoUpdateEnabled( - normalizeAutoUpdateEnabled( - savedUpdateChannel, - systemSettings.autoUpdateEnabled || false, - savedPreviewConsent, - ), + savedEnvLocked + ? false + : normalizeAutoUpdateEnabled( + savedUpdateChannel, + systemSettings.autoUpdateEnabled || false, + savedPreviewConsent, + savedIsProInApp, + savedProConsent, + ), ); - setAutoUpdateCapability(systemSettings.autoUpdateCapability ?? null); + setAutoUpdateCapability(savedCapability); if (systemSettings.envOverrides) { setEnvOverrides(systemSettings.envOverrides); @@ -267,13 +294,29 @@ export function useSystemSettingsState({ pvePollingInterval: pvePollingInterval(), allowedOrigins: allowedOrigins(), updateChannel: updateChannel(), - autoUpdateEnabled: normalizeAutoUpdateEnabled( - updateChannel(), - autoUpdateEnabled(), - autoUpdatePreviewConsent(), - ), - autoUpdatePreviewConsent: - updateChannel() === 'rc' && autoUpdateEnabled() && autoUpdatePreviewConsent(), + ...(autoUpdateEnvLocked() + ? {} + : (() => { + const isProInApp = autoUpdateCapability()?.mechanism === 'in_app'; + const effectiveProConsent = + isProInApp && autoUpdateEnabled() && autoUpdateProConsent(); + const effectivePreviewConsent = + updateChannel() === 'rc' && + autoUpdateEnabled() && + autoUpdatePreviewConsent() && + (!isProInApp || effectiveProConsent); + return { + autoUpdateEnabled: normalizeAutoUpdateEnabled( + updateChannel(), + autoUpdateEnabled(), + effectivePreviewConsent, + isProInApp, + effectiveProConsent, + ), + autoUpdatePreviewConsent: effectivePreviewConsent, + autoUpdateProConsent: effectiveProConsent, + }; + })()), backupPollingEnabled: backupPollingEnabled(), backupPollingInterval: backupPollingInterval(), allowEmbedding: allowEmbedding(), @@ -631,6 +674,9 @@ export function useSystemSettingsState({ setAutoUpdateEnabled, autoUpdatePreviewConsent, setAutoUpdatePreviewConsent, + autoUpdateProConsent, + setAutoUpdateProConsent, + autoUpdateEnvLocked, autoUpdateCapability, updatePlan, isInstallingUpdate, diff --git a/frontend-modern/src/types/config.ts b/frontend-modern/src/types/config.ts index 02f7282e98..019ab3453b 100644 --- a/frontend-modern/src/types/config.ts +++ b/frontend-modern/src/types/config.ts @@ -31,9 +31,12 @@ export interface ReportBrandSettings { } export type AutoUpdateUnsupportedReason = + | 'env_disabled' | 'source_build' | 'docker' | 'pro' + | 'pro_not_activated' + | 'binary_not_writable' | 'unsupported_deployment' | 'timer_not_installed' | 'timer_disabled' @@ -41,9 +44,12 @@ export type AutoUpdateUnsupportedReason = export type AutoUpdatePreviewUnsupportedReason = 'helper_outdated'; +export type AutoUpdateMechanism = 'systemd_timer' | 'in_app'; + export interface AutoUpdateCapability { supported: boolean; previewSupported: boolean; + mechanism?: AutoUpdateMechanism | string; reason?: AutoUpdateUnsupportedReason | string; previewReason?: AutoUpdatePreviewUnsupportedReason | string; } @@ -55,6 +61,7 @@ export interface SystemConfig { connectionTimeout?: number; // Seconds before timeout (default: 10) autoUpdateEnabled: boolean; // Enable auto-updates autoUpdatePreviewConsent?: boolean; // Explicit opt-in for unattended Preview channel updates + autoUpdateProConsent?: boolean; // Explicit opt-in for unattended Pulse Pro updates updateChannel?: UpdateChannel; // Update channel: 'stable' | 'rc' backupPollingInterval?: number; // Backup polling interval in seconds (0 = default cadence) backupPollingEnabled?: boolean; // Enable backup polling of PVE/PBS data diff --git a/frontend-modern/src/utils/__tests__/updatesPresentation.test.ts b/frontend-modern/src/utils/__tests__/updatesPresentation.test.ts index b29495757a..82290594a2 100644 --- a/frontend-modern/src/utils/__tests__/updatesPresentation.test.ts +++ b/frontend-modern/src/utils/__tests__/updatesPresentation.test.ts @@ -10,6 +10,7 @@ import { getUpdateCheckedLabel, getUpdateCheckModeLabel, getUpdatePrimaryStatusLabel, + getAutoUpdateControlState, UPDATES_PANEL_COPY, } from '../updatesPresentation'; @@ -126,3 +127,69 @@ it('omits unknown and invalid release dates while formatting known dates', () => const date = '2026-09-10T14:06:01Z'; expect(formatUpdateReleaseDate(date)).toBe(new Date(date).toLocaleDateString()); }); + +describe('getAutoUpdateControlState', () => { + it('supports activated Pulse Pro in-app overnight updates on Stable and Preview', () => { + const cap = { supported: true, previewSupported: true, mechanism: 'in_app' as const }; + const stable = getAutoUpdateControlState({ + channel: 'stable', + isProRuntime: true, + capability: cap, + }); + expect(stable.supported).toBe(true); + expect(stable.disabledReason).toBeNull(); + expect(stable.scheduleNote).toBe(UPDATES_PANEL_COPY.autoUpdateProScheduleNote); + + const preview = getAutoUpdateControlState({ + channel: 'rc', + isProRuntime: true, + capability: cap, + }); + expect(preview.supported).toBe(true); + expect(preview.disabledReason).toBeNull(); + expect(preview.scheduleNote).toBe(UPDATES_PANEL_COPY.autoUpdateProPreviewScheduleNote); + }); + + it('explains env veto, unactivated Pro license, and non-writable binary directory', () => { + expect( + getAutoUpdateControlState({ + channel: 'stable', + capability: { supported: true, previewSupported: true, mechanism: 'in_app' }, + envLocked: true, + }), + ).toMatchObject({ + supported: false, + disabledReason: UPDATES_PANEL_COPY.autoUpdateUnsupportedEnvDisabled, + }); + + expect( + getAutoUpdateControlState({ + channel: 'stable', + capability: { + supported: false, + previewSupported: false, + mechanism: 'in_app', + reason: 'pro_not_activated', + }, + }), + ).toMatchObject({ + supported: false, + disabledReason: UPDATES_PANEL_COPY.autoUpdateUnsupportedProNotActivated, + }); + + expect( + getAutoUpdateControlState({ + channel: 'stable', + capability: { + supported: false, + previewSupported: false, + mechanism: 'in_app', + reason: 'binary_not_writable', + }, + }), + ).toMatchObject({ + supported: false, + disabledReason: UPDATES_PANEL_COPY.autoUpdateUnsupportedBinaryNotWritable, + }); + }); +}); diff --git a/frontend-modern/src/utils/updatesPresentation.ts b/frontend-modern/src/utils/updatesPresentation.ts index 80f8e5c8b5..8347baaa0b 100644 --- a/frontend-modern/src/utils/updatesPresentation.ts +++ b/frontend-modern/src/utils/updatesPresentation.ts @@ -29,6 +29,16 @@ export const UPDATES_PANEL_COPY = { 'Runs once daily overnight via the host systemd timer (stable releases only).', autoUpdatePreviewScheduleNote: 'Runs once daily overnight via the host systemd timer (Preview and newer stable releases).', + autoUpdateProScheduleNote: + "Runs once daily overnight between 02:00 and 06:00 local time via Pulse Pro's built-in updater (stable releases only).", + autoUpdateProPreviewScheduleNote: + "Runs once daily overnight between 02:00 and 06:00 local time via Pulse Pro's built-in updater (Preview and newer stable releases).", + autoUpdateUnsupportedEnvDisabled: + 'Automatic updates are disabled by the PULSE_DISABLE_AUTO_UPDATE environment variable on this host.', + autoUpdateUnsupportedProNotActivated: + 'Activate your Pulse Pro license before enabling automatic updates.', + autoUpdateUnsupportedBinaryNotWritable: + 'The Pulse binary directory is not writable by the service user, so Pulse Pro cannot install updates automatically.', autoUpdateUnsupportedDocker: 'Automatic updates are managed by your container deployment. Update the image and recreate the container.', autoUpdateUnsupportedPro: @@ -58,21 +68,33 @@ export function getAutoUpdateControlState(params: { versionInfo?: Pick | null; isProRuntime?: boolean; capability?: AutoUpdateCapability | null; + envLocked?: boolean; }): AutoUpdateControlState { const isPreview = params.channel === 'rc'; + const isInAppPro = params.capability?.mechanism === 'in_app' || Boolean(params.isProRuntime); const description = isPreview ? UPDATES_PANEL_COPY.autoUpdatePreviewDescription : UPDATES_PANEL_COPY.autoUpdateDescription; - const scheduleNote = isPreview - ? UPDATES_PANEL_COPY.autoUpdatePreviewScheduleNote - : UPDATES_PANEL_COPY.autoUpdateScheduleNote; + const scheduleNote = isInAppPro + ? isPreview + ? UPDATES_PANEL_COPY.autoUpdateProPreviewScheduleNote + : UPDATES_PANEL_COPY.autoUpdateProScheduleNote + : isPreview + ? UPDATES_PANEL_COPY.autoUpdatePreviewScheduleNote + : UPDATES_PANEL_COPY.autoUpdateScheduleNote; const reasonToCopy = (reason?: string): string => { switch (reason) { + case 'env_disabled': + return UPDATES_PANEL_COPY.autoUpdateUnsupportedEnvDisabled; case 'docker': return UPDATES_PANEL_COPY.autoUpdateUnsupportedDocker; case 'pro': return UPDATES_PANEL_COPY.autoUpdateUnsupportedPro; + case 'pro_not_activated': + return UPDATES_PANEL_COPY.autoUpdateUnsupportedProNotActivated; + case 'binary_not_writable': + return UPDATES_PANEL_COPY.autoUpdateUnsupportedBinaryNotWritable; case 'source_build': return UPDATES_PANEL_COPY.autoUpdateUnsupportedSource; case 'timer_not_installed': @@ -86,6 +108,15 @@ export function getAutoUpdateControlState(params: { } }; + if (params.envLocked) { + return { + supported: false, + disabledReason: UPDATES_PANEL_COPY.autoUpdateUnsupportedEnvDisabled, + description, + scheduleNote, + }; + } + if (params.capability) { if (!params.capability.supported) { return { diff --git a/internal/api/configapi/config_system_handlers.go b/internal/api/configapi/config_system_handlers.go index e0f6c416a7..a03497473e 100644 --- a/internal/api/configapi/config_system_handlers.go +++ b/internal/api/configapi/config_system_handlers.go @@ -66,6 +66,7 @@ func (h *ConfigHandlers) handleGetSystemSettings(w http.ResponseWriter, r *http. settings.UpdateChannel = cfg.UpdateChannel settings.AutoUpdateEnabled = cfg.AutoUpdateEnabled settings.AutoUpdatePreviewConsent = cfg.AutoUpdatePreviewConsent + settings.AutoUpdateProConsent = cfg.AutoUpdateProConsent settings.LogLevel = cfg.LogLevel settings.DiscoveryEnabled = cfg.DiscoveryEnabled settings.DiscoverySubnet = cfg.DiscoverySubnet diff --git a/internal/api/router.go b/internal/api/router.go index 95f3c2cfd7..b33f91940b 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -62,6 +62,7 @@ import ( "github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts" "github.com/rcourtman/pulse-go-rewrite/pkg/auth" "github.com/rcourtman/pulse-go-rewrite/pkg/diskinventory" + "github.com/rcourtman/pulse-go-rewrite/pkg/edition" "github.com/rcourtman/pulse-go-rewrite/pkg/extensions" metricstore "github.com/rcourtman/pulse-go-rewrite/pkg/metrics" "github.com/rcourtman/pulse-go-rewrite/pkg/reporting" @@ -619,6 +620,11 @@ func (r *Router) setupRoutes() { InstanceFingerprint: state.InstanceFingerprint, }, true }) + if r.systemSettingsHandler != nil { + r.systemSettingsHandler.autoUpdateCapabilityFunc = func() updates.AutoUpdateCapability { + return updates.DetectAutoUpdateCapabilityWithOptions(r.updateManager.HasProUpdateCredentials) + } + } rbacProvider := r.rbacProvider orgHandlers := NewOrgHandlers(r.multiTenant, r.mtMonitor, rbacProvider) orgHandlers.SetHostedMode(r.hostedMode) @@ -1450,6 +1456,22 @@ func (r *Router) Handler() http.Handler { // StartBackgroundWorkers starts router-owned background workers for the API // server lifecycle. Unit tests that only need the HTTP handler can construct a // router without starting update checks or WebSocket forwarding loops. +// SetUpdateRestartHook registers a graceful shutdown callback for in-app +// updates so binary replacement drains active server work before exiting. +func (r *Router) SetUpdateRestartHook(fn func()) { + if r.updateManager != nil { + r.updateManager.SetRestartHook(fn) + } +} + +// StartProAutoUpdater starts the overnight unattended Pulse Pro updater loop +// on supported Pulse Pro systemd and Proxmox VE installations. +func (r *Router) StartProAutoUpdater(ctx context.Context) { + if r.updateManager != nil { + r.updateManager.StartProAutoUpdater(ctx) + } +} + func (r *Router) StartBackgroundWorkers() { if r == nil { return @@ -7993,7 +8015,7 @@ func (r *Router) handleConfig(w http.ResponseWriter, req *http.Request) { // Return public configuration payload := map[string]interface{}{ "csrfProtection": false, // Not implemented yet - "autoUpdateEnabled": config.EffectiveAutoUpdateEnabledForChannel(r.config.UpdateChannel, r.config.AutoUpdateEnabled, r.config.AutoUpdatePreviewConsent), + "autoUpdateEnabled": config.EffectiveAutoUpdateEnabledForEdition(r.config.UpdateChannel, r.config.AutoUpdateEnabled, r.config.AutoUpdatePreviewConsent, edition.IsPro(), r.config.AutoUpdateProConsent), "updateChannel": config.EffectiveUpdateChannel(r.config.UpdateChannel, ""), } diff --git a/internal/api/system_settings.go b/internal/api/system_settings.go index da0adf836c..2770cc9367 100644 --- a/internal/api/system_settings.go +++ b/internal/api/system_settings.go @@ -24,6 +24,7 @@ import ( pulseupdates "github.com/rcourtman/pulse-go-rewrite/internal/updates" "github.com/rcourtman/pulse-go-rewrite/internal/utils" "github.com/rcourtman/pulse-go-rewrite/internal/websocket" + "github.com/rcourtman/pulse-go-rewrite/pkg/edition" "github.com/rs/zerolog/log" ) @@ -65,6 +66,7 @@ type SystemSettingsHandler struct { } defaultMonitor SystemSettingsMonitor autoUpdateCapabilityFunc func() pulseupdates.AutoUpdateCapability + isProEditionFunc func() bool } type SystemSettingsResponse struct { @@ -518,6 +520,11 @@ func validateSystemSettings(_ *config.SystemSettings, rawRequest map[string]inte return fmt.Errorf("autoUpdatePreviewConsent must be a boolean") } } + if val, ok := rawRequest["autoUpdateProConsent"]; ok { + if _, ok := val.(bool); !ok { + return fmt.Errorf("autoUpdateProConsent must be a boolean") + } + } if val, ok := rawRequest["discoveryEnabled"]; ok { if _, ok := val.(bool); !ok { @@ -787,8 +794,16 @@ func (h *SystemSettingsHandler) HandleGetSystemSettings(w http.ResponseWriter, r // Expose effective telemetry value (respects env override) effectiveTelemetry := h.config.TelemetryEnabled settings.TelemetryEnabled = &effectiveTelemetry + proEdition := edition.IsPro() + if h.isProEditionFunc != nil { + proEdition = h.isProEditionFunc() + } + settings.AutoUpdateProConsent = config.EffectiveAutoUpdateProConsent(settings.AutoUpdateEnabled, proEdition, settings.AutoUpdateProConsent) settings.AutoUpdatePreviewConsent = config.EffectiveAutoUpdatePreviewConsent(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent) - settings.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForChannel(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent) + if proEdition && !settings.AutoUpdateProConsent { + settings.AutoUpdatePreviewConsent = false + } + settings.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForEdition(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent, proEdition, settings.AutoUpdateProConsent) } // Include env override information @@ -796,7 +811,17 @@ func (h *SystemSettingsHandler) HandleGetSystemSettings(w http.ResponseWriter, r if settings != nil { response.SystemSettings = *settings } - response.EnvOverrides = h.config.EnvOverrides + if len(h.config.EnvOverrides) > 0 || config.IsAutoUpdateDisabledByEnv() { + copied := make(map[string]bool, len(h.config.EnvOverrides)+2) + for k, v := range h.config.EnvOverrides { + copied[k] = v + } + if config.IsAutoUpdateDisabledByEnv() { + copied["autoUpdateEnabled"] = true + copied["PULSE_DISABLE_AUTO_UPDATE"] = true + } + response.EnvOverrides = copied + } detectCapability := h.autoUpdateCapabilityFunc if detectCapability == nil { detectCapability = pulseupdates.DetectAutoUpdateCapability @@ -945,6 +970,12 @@ func (h *SystemSettingsHandler) HandleUpdateSystemSettings(w http.ResponseWriter writeErrorResponse(w, http.StatusConflict, "env_locked", "allowedOrigins is locked by the ALLOWED_ORIGINS environment variable", nil) return } + _, autoUpdateUpdated := rawRequest["autoUpdateEnabled"] + autoUpdateEnvLocked := config.IsAutoUpdateDisabledByEnv() || h.config.EnvOverrides["autoUpdateEnabled"] || h.config.EnvOverrides["PULSE_DISABLE_AUTO_UPDATE"] + if autoUpdateUpdated && autoUpdateEnvLocked && updates.AutoUpdateEnabled { + writeErrorResponse(w, http.StatusConflict, "env_locked", "autoUpdateEnabled is locked by the PULSE_DISABLE_AUTO_UPDATE environment variable", nil) + return + } // Start with existing settings settings := *existingSettings @@ -1016,6 +1047,9 @@ func (h *SystemSettingsHandler) HandleUpdateSystemSettings(w http.ResponseWriter if _, ok := rawRequest["autoUpdatePreviewConsent"]; ok { settings.AutoUpdatePreviewConsent = updates.AutoUpdatePreviewConsent } + if _, ok := rawRequest["autoUpdateProConsent"]; ok { + settings.AutoUpdateProConsent = updates.AutoUpdateProConsent + } if _, ok := rawRequest["discoveryEnabled"]; ok { settings.DiscoveryEnabled = updates.DiscoveryEnabled } @@ -1059,8 +1093,16 @@ func (h *SystemSettingsHandler) HandleUpdateSystemSettings(w http.ResponseWriter settings.FullWidthMode = updates.FullWidthMode } settings.UpdateChannel = config.EffectiveUpdateChannel(settings.UpdateChannel, h.config.UpdateChannel) + proEdition := edition.IsPro() + if h.isProEditionFunc != nil { + proEdition = h.isProEditionFunc() + } + settings.AutoUpdateProConsent = config.EffectiveAutoUpdateProConsent(settings.AutoUpdateEnabled, proEdition, settings.AutoUpdateProConsent) settings.AutoUpdatePreviewConsent = config.EffectiveAutoUpdatePreviewConsent(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent) - settings.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForChannel(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent) + if proEdition && !settings.AutoUpdateProConsent { + settings.AutoUpdatePreviewConsent = false + } + settings.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForEdition(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent, proEdition, settings.AutoUpdateProConsent) // Pre-save validation (may return errors before anything is persisted) if settings.Theme != "" && settings.Theme != "light" && settings.Theme != "dark" { @@ -1140,8 +1182,9 @@ func (h *SystemSettingsHandler) HandleUpdateSystemSettings(w http.ResponseWriter // selection; the ordinary settings writer must publish on it too. config.Mu.Lock() h.config.UpdateChannel = settings.UpdateChannel + h.config.AutoUpdateProConsent = settings.AutoUpdateProConsent h.config.AutoUpdatePreviewConsent = settings.AutoUpdatePreviewConsent - h.config.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForChannel(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent) + h.config.AutoUpdateEnabled = config.EffectiveAutoUpdateEnabledForEdition(settings.UpdateChannel, settings.AutoUpdateEnabled, settings.AutoUpdatePreviewConsent, proEdition, settings.AutoUpdateProConsent) config.Mu.Unlock() h.config.DiscoveryEnabled = settings.DiscoveryEnabled if settings.DiscoverySubnet != "" { diff --git a/internal/api/system_settings_auto_update_test.go b/internal/api/system_settings_auto_update_test.go index 4278c476b5..bc57c392cc 100644 --- a/internal/api/system_settings_auto_update_test.go +++ b/internal/api/system_settings_auto_update_test.go @@ -113,3 +113,118 @@ func TestSystemSettingsAutoUpdatePreviewConsent(t *testing.T) { t.Fatalf("expected 400 for non-boolean autoUpdatePreviewConsent, got %d", postRec.Code) } } + +func TestSystemSettingsAutoUpdateProConsentAndEnvVeto(t *testing.T) { + dir := t.TempDir() + p := config.NewConfigPersistence(dir) + const tokenVal = "test-pro-settings-token-0123456789abcdef" + cfg := &config.Config{ + ConfigPath: dir, + UpdateChannel: "stable", + APITokens: []config.APITokenRecord{ + { + ID: "test-token", + Name: "test", + Hash: auth.HashAPIToken(tokenVal), + Scopes: []string{config.ScopeSettingsRead, config.ScopeSettingsWrite}, + }, + }, + } + h := NewSystemSettingsHandler(cfg, p, nil, nil, nil, nil, nil) + h.mtMonitor = nil + h.isProEditionFunc = func() bool { return true } + h.autoUpdateCapabilityFunc = func() pulseupdates.AutoUpdateCapability { + return pulseupdates.AutoUpdateCapability{ + Supported: true, + PreviewSupported: true, + Mechanism: pulseupdates.AutoUpdateMechanismInApp, + } + } + + doGet := func() SystemSettingsResponse { + req := httptest.NewRequest(http.MethodGet, "/api/system/settings", nil) + req.Header.Set("X-API-Token", tokenVal) + rec := httptest.NewRecorder() + h.HandleGetSystemSettings(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET status=%d body=%s", rec.Code, rec.Body.String()) + } + var got SystemSettingsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode GET: %v", err) + } + return got + } + + doPost := func(raw string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", bytes.NewBufferString(raw)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Token", tokenVal) + rec := httptest.NewRecorder() + h.HandleUpdateSystemSettings(rec, req) + return rec + } + + // Dormant Pro stable config (autoUpdateEnabled:true, autoUpdateProConsent:false) stays disabled. + if err := p.SaveSystemSettings(config.SystemSettings{ + UpdateChannel: "stable", + AutoUpdateEnabled: true, + }); err != nil { + t.Fatalf("seed settings: %v", err) + } + got := doGet() + if got.AutoUpdateEnabled || got.AutoUpdateProConsent { + t.Fatalf("dormant Pro config must stay disabled on GET, got enabled=%t proConsent=%t", got.AutoUpdateEnabled, got.AutoUpdateProConsent) + } + if got.AutoUpdateCapability == nil || got.AutoUpdateCapability.Mechanism != pulseupdates.AutoUpdateMechanismInApp { + t.Fatalf("expected in_app capability, got %+v", got.AutoUpdateCapability) + } + + // Explicit Pro opt-in activates Stable unattended updates. + rec := doPost(`{"updateChannel":"stable","autoUpdateEnabled":true,"autoUpdateProConsent":true}`) + if rec.Code != http.StatusOK { + t.Fatalf("POST Pro stable opt-in status=%d body=%s", rec.Code, rec.Body.String()) + } + if !cfg.AutoUpdateEnabled || !cfg.AutoUpdateProConsent { + t.Fatalf("expected Pro stable opt-in active, got enabled=%t proConsent=%t", cfg.AutoUpdateEnabled, cfg.AutoUpdateProConsent) + } + + // Switching to Preview without previewConsent still disables auto-updates on Pro. + rec = doPost(`{"updateChannel":"rc","autoUpdateEnabled":true,"autoUpdateProConsent":true,"autoUpdatePreviewConsent":false}`) + if rec.Code != http.StatusOK { + t.Fatalf("POST Pro preview without previewConsent status=%d body=%s", rec.Code, rec.Body.String()) + } + if cfg.AutoUpdateEnabled || cfg.AutoUpdatePreviewConsent { + t.Fatalf("Pro preview without previewConsent must disable auto-updates") + } + + // Explicit Pro + Preview opt-in activates Preview unattended updates. + rec = doPost(`{"updateChannel":"rc","autoUpdateEnabled":true,"autoUpdateProConsent":true,"autoUpdatePreviewConsent":true}`) + if rec.Code != http.StatusOK { + t.Fatalf("POST Pro preview opt-in status=%d body=%s", rec.Code, rec.Body.String()) + } + if !cfg.AutoUpdateEnabled || !cfg.AutoUpdateProConsent || !cfg.AutoUpdatePreviewConsent { + t.Fatalf("expected Pro + Preview opt-in active") + } + + // Non-boolean autoUpdateProConsent is rejected. + rec = doPost(`{"autoUpdateProConsent":"yes"}`) + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400 for non-boolean autoUpdateProConsent, got %d", rec.Code) + } + + // Host env veto forces autoUpdateEnabled off, reports envOverrides, and rejects enabling with 409. + t.Setenv("PULSE_DISABLE_AUTO_UPDATE", "true") + got = doGet() + if got.AutoUpdateEnabled || !got.EnvOverrides["autoUpdateEnabled"] { + t.Fatalf("expected env veto on GET, got enabled=%t overrides=%+v", got.AutoUpdateEnabled, got.EnvOverrides) + } + rec = doPost(`{"autoUpdateEnabled":true,"autoUpdateProConsent":true}`) + if rec.Code != http.StatusConflict { + t.Fatalf("expected 409 when enabling under PULSE_DISABLE_AUTO_UPDATE, got %d body=%s", rec.Code, rec.Body.String()) + } + rec = doPost(`{"theme":"dark","autoUpdateEnabled":false}`) + if rec.Code != http.StatusOK { + t.Fatalf("expected unrelated save with autoUpdateEnabled:false to succeed under env veto, got %d body=%s", rec.Code, rec.Body.String()) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 2683e52f35..f04c0d5c42 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -26,6 +26,7 @@ import ( "github.com/rcourtman/pulse-go-rewrite/internal/logging" "github.com/rcourtman/pulse-go-rewrite/internal/utils" "github.com/rcourtman/pulse-go-rewrite/pkg/auth" + "github.com/rcourtman/pulse-go-rewrite/pkg/edition" pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing" "github.com/rcourtman/pulse-go-rewrite/pkg/tlsutil" "github.com/rs/zerolog/log" @@ -96,12 +97,30 @@ func EffectiveAutoUpdatePreviewConsent(channel string, enabled bool, previewCons return EffectiveUpdateChannel(channel, "") == "rc" && enabled && previewConsent } +// IsAutoUpdateDisabledByEnv reports whether the host environment explicitly +// vetoes unattended server auto-updates via PULSE_DISABLE_AUTO_UPDATE. +func IsAutoUpdateDisabledByEnv() bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv("PULSE_DISABLE_AUTO_UPDATE"))) { + case "1", "true", "yes": + return true + default: + return false + } +} + +// EffectiveAutoUpdateProConsent returns true only on Pulse Pro builds when +// unattended updates were explicitly adopted after in-app Pro scheduling was +// introduced, preventing dormant stable or preview configs from self-activating. +func EffectiveAutoUpdateProConsent(enabled bool, proEdition bool, proConsent bool) bool { + return proEdition && enabled && proConsent && !IsAutoUpdateDisabledByEnv() +} + // EffectiveAutoUpdateEnabledForChannel resolves whether unattended updates are // enabled for the active channel. Stable requires enabled; Preview (rc) // requires both enabled and explicit previewConsent so dormant rc+true configs // never self-activate. func EffectiveAutoUpdateEnabledForChannel(channel string, enabled bool, previewConsent bool) bool { - if !enabled { + if IsAutoUpdateDisabledByEnv() || !enabled { return false } switch EffectiveUpdateChannel(channel, "") { @@ -114,6 +133,16 @@ func EffectiveAutoUpdateEnabledForChannel(channel string, enabled bool, previewC } } +// EffectiveAutoUpdateEnabledForEdition resolves whether unattended updates are +// active for the active channel and compiled edition. On Pulse Pro, explicit +// proConsent is also required so previously ignored configs never self-activate. +func EffectiveAutoUpdateEnabledForEdition(channel string, enabled bool, previewConsent bool, proEdition bool, proConsent bool) bool { + if proEdition && !proConsent { + return false + } + return EffectiveAutoUpdateEnabledForChannel(channel, enabled, previewConsent) +} + // IsPasswordHashed checks if a string looks like a bcrypt hash func IsPasswordHashed(password string) bool { // Bcrypt hashes start with $2a$, $2b$, or $2y$ and are 60 characters long @@ -267,6 +296,7 @@ type Config struct { UpdateChannel string AutoUpdateEnabled bool AutoUpdatePreviewConsent bool + AutoUpdateProConsent bool // Discovery settings DiscoveryEnabled bool `envconfig:"DISCOVERY_ENABLED" default:"false"` @@ -949,8 +979,19 @@ func load(initLogging bool) (*Config, error) { } cfg.UpdateChannel = EffectiveUpdateChannel(systemSettings.UpdateChannel, cfg.UpdateChannel) + proEdition := edition.IsPro() + cfg.AutoUpdateProConsent = EffectiveAutoUpdateProConsent(systemSettings.AutoUpdateEnabled, proEdition, systemSettings.AutoUpdateProConsent) cfg.AutoUpdatePreviewConsent = EffectiveAutoUpdatePreviewConsent(cfg.UpdateChannel, systemSettings.AutoUpdateEnabled, systemSettings.AutoUpdatePreviewConsent) - cfg.AutoUpdateEnabled = EffectiveAutoUpdateEnabledForChannel(cfg.UpdateChannel, systemSettings.AutoUpdateEnabled, systemSettings.AutoUpdatePreviewConsent) + if proEdition && !cfg.AutoUpdateProConsent { + cfg.AutoUpdatePreviewConsent = false + } + cfg.AutoUpdateEnabled = EffectiveAutoUpdateEnabledForEdition(cfg.UpdateChannel, systemSettings.AutoUpdateEnabled, systemSettings.AutoUpdatePreviewConsent, proEdition, systemSettings.AutoUpdateProConsent) + if IsAutoUpdateDisabledByEnv() { + if cfg.EnvOverrides == nil { + cfg.EnvOverrides = make(map[string]bool) + } + cfg.EnvOverrides["autoUpdateEnabled"] = true + } if systemSettings.AllowedOrigins != "" { cfg.AllowedOrigins = systemSettings.AllowedOrigins } diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go index 082a7e0260..fe33bd902c 100644 --- a/internal/config/config_load_test.go +++ b/internal/config/config_load_test.go @@ -551,6 +551,19 @@ func TestLoad_ClearsPreviewConsentOnStableChannel(t *testing.T) { assert.False(t, cfg.AutoUpdatePreviewConsent) } +func TestEffectiveAutoUpdateEnabledForEditionAndEnvVeto(t *testing.T) { + assert.False(t, EffectiveAutoUpdateEnabledForEdition("stable", true, false, true, false), "dormant Pro stable config must stay disabled") + assert.True(t, EffectiveAutoUpdateEnabledForEdition("stable", true, false, true, true), "explicit Pro stable consent must activate") + assert.False(t, EffectiveAutoUpdateEnabledForEdition("rc", true, false, true, true), "Pro preview still requires preview consent") + assert.False(t, EffectiveAutoUpdateEnabledForEdition("rc", true, true, true, false), "Pro preview still requires Pro consent") + assert.True(t, EffectiveAutoUpdateEnabledForEdition("rc", true, true, true, true), "explicit Pro + Preview consent must activate") + + t.Setenv("PULSE_DISABLE_AUTO_UPDATE", "true") + assert.True(t, IsAutoUpdateDisabledByEnv()) + assert.False(t, EffectiveAutoUpdateEnabledForEdition("stable", true, false, false, false)) + assert.False(t, EffectiveAutoUpdateEnabledForEdition("rc", true, true, true, true)) +} + func TestLoad_ReadErrors(t *testing.T) { if os.Getuid() == 0 { t.Skip("Skipping permission tests as root") diff --git a/internal/config/persistence.go b/internal/config/persistence.go index 1ce3e48567..507de4dbf5 100644 --- a/internal/config/persistence.go +++ b/internal/config/persistence.go @@ -1608,6 +1608,7 @@ type SystemSettings struct { UpdateChannel string `json:"updateChannel,omitempty"` AutoUpdateEnabled bool `json:"autoUpdateEnabled"` // Removed omitempty so false is saved AutoUpdatePreviewConsent bool `json:"autoUpdatePreviewConsent,omitempty"` + AutoUpdateProConsent bool `json:"autoUpdateProConsent,omitempty"` LogLevel string `json:"logLevel,omitempty"` DiscoveryEnabled bool `json:"discoveryEnabled"` DiscoverySubnet string `json:"discoverySubnet,omitempty"` diff --git a/internal/updates/auto_update_capability.go b/internal/updates/auto_update_capability.go index bd15e29d6e..9ec2cc76db 100644 --- a/internal/updates/auto_update_capability.go +++ b/internal/updates/auto_update_capability.go @@ -8,18 +8,24 @@ import ( "strings" "time" + "github.com/rcourtman/pulse-go-rewrite/internal/config" "github.com/rcourtman/pulse-go-rewrite/pkg/edition" ) const ( + AutoUpdateReasonEnvDisabled = "env_disabled" AutoUpdateReasonSourceBuild = "source_build" AutoUpdateReasonDocker = "docker" AutoUpdateReasonPro = "pro" + AutoUpdateReasonProNotActivated = "pro_not_activated" + AutoUpdateReasonBinaryNotWritable = "binary_not_writable" AutoUpdateReasonUnsupportedDeployment = "unsupported_deployment" AutoUpdateReasonTimerNotInstalled = "timer_not_installed" AutoUpdateReasonTimerDisabled = "timer_disabled" AutoUpdateReasonHelperMissing = "helper_missing" AutoUpdatePreviewReasonHelperOutdated = "helper_outdated" + AutoUpdateMechanismSystemdTimer = "systemd_timer" + AutoUpdateMechanismInApp = "in_app" autoUpdatePreviewChannelsMarker = `PULSE_AUTO_UPDATE_CHANNELS="stable rc"` ) @@ -28,6 +34,7 @@ const ( type AutoUpdateCapability struct { Supported bool `json:"supported"` PreviewSupported bool `json:"previewSupported"` + Mechanism string `json:"mechanism,omitempty"` Reason string `json:"reason,omitempty"` PreviewReason string `json:"previewReason,omitempty"` } @@ -35,16 +42,38 @@ type AutoUpdateCapability struct { type autoUpdateProbe struct { getCurrentVersion func() (*VersionInfo, error) isPro func() bool + isEnvDisabled func() bool + hasProCredentials func() bool + binaryDirWritable func() bool getenv func(string) string stat func(string) (os.FileInfo, error) readFile func(string) ([]byte, error) timerState func(unit string) (string, error) } -func defaultAutoUpdateProbe() autoUpdateProbe { +func defaultBinaryDirWritable() bool { + exePath, err := os.Executable() + if err != nil || strings.TrimSpace(exePath) == "" { + return false + } + dir := filepath.Dir(exePath) + f, err := os.CreateTemp(dir, ".pulse-auto-update-write-check-*") + if err != nil { + return false + } + name := f.Name() + _ = f.Close() + _ = os.Remove(name) + return true +} + +func defaultAutoUpdateProbe(hasProCredentials func() bool) autoUpdateProbe { return autoUpdateProbe{ getCurrentVersion: GetCurrentVersion, isPro: edition.IsPro, + isEnvDisabled: config.IsAutoUpdateDisabledByEnv, + hasProCredentials: hasProCredentials, + binaryDirWritable: defaultBinaryDirWritable, getenv: os.Getenv, stat: os.Stat, readFile: os.ReadFile, @@ -62,10 +91,23 @@ func readSystemdTimerEnabledState(unit string) (string, error) { // DetectAutoUpdateCapability inspects the running edition, deployment type, // systemd update timer, and installed host auto-update helper. func DetectAutoUpdateCapability() AutoUpdateCapability { - return detectAutoUpdateCapabilityWithProbe(defaultAutoUpdateProbe()) + return DetectAutoUpdateCapabilityWithOptions(nil) +} + +// DetectAutoUpdateCapabilityWithOptions inspects host auto-update support, +// consulting hasProCredentials on Pulse Pro builds to verify license activation. +func DetectAutoUpdateCapabilityWithOptions(hasProCredentials func() bool) AutoUpdateCapability { + return detectAutoUpdateCapabilityWithProbe(defaultAutoUpdateProbe(hasProCredentials)) } func detectAutoUpdateCapabilityWithProbe(p autoUpdateProbe) AutoUpdateCapability { + if p.isEnvDisabled != nil && p.isEnvDisabled() { + return AutoUpdateCapability{ + Supported: false, + Reason: AutoUpdateReasonEnvDisabled, + } + } + versionInfo, err := p.getCurrentVersion() if err != nil || versionInfo == nil { return AutoUpdateCapability{ @@ -85,12 +127,7 @@ func detectAutoUpdateCapabilityWithProbe(p autoUpdateProbe) AutoUpdateCapability Reason: AutoUpdateReasonDocker, } } - if p.isPro() { - return AutoUpdateCapability{ - Supported: false, - Reason: AutoUpdateReasonPro, - } - } + deployment := strings.ToLower(strings.TrimSpace(versionInfo.DeploymentType)) if deployment != "systemd" && deployment != "proxmoxve" { return AutoUpdateCapability{ @@ -99,6 +136,30 @@ func detectAutoUpdateCapabilityWithProbe(p autoUpdateProbe) AutoUpdateCapability } } + // Compiled Pulse Pro systemd/Proxmox VE builds update in-process through + // the authenticated license download broker rather than pulse-auto-update.sh. + if p.isPro != nil && p.isPro() { + if p.binaryDirWritable != nil && !p.binaryDirWritable() { + return AutoUpdateCapability{ + Supported: false, + Mechanism: AutoUpdateMechanismInApp, + Reason: AutoUpdateReasonBinaryNotWritable, + } + } + if p.hasProCredentials == nil || !p.hasProCredentials() { + return AutoUpdateCapability{ + Supported: false, + Mechanism: AutoUpdateMechanismInApp, + Reason: AutoUpdateReasonProNotActivated, + } + } + return AutoUpdateCapability{ + Supported: true, + PreviewSupported: true, + Mechanism: AutoUpdateMechanismInApp, + } + } + serviceName := strings.TrimSpace(p.getenv("PULSE_SERVICE_NAME")) if serviceName == "" { _, hasBackend := p.stat("/etc/systemd/system/pulse-backend.service") @@ -135,6 +196,7 @@ func detectAutoUpdateCapabilityWithProbe(p autoUpdateProbe) AutoUpdateCapability if !timerFound { return AutoUpdateCapability{ Supported: false, + Mechanism: AutoUpdateMechanismSystemdTimer, Reason: AutoUpdateReasonTimerNotInstalled, } } @@ -145,6 +207,7 @@ func detectAutoUpdateCapabilityWithProbe(p autoUpdateProbe) AutoUpdateCapability case "disabled", "masked", "masked-runtime": return AutoUpdateCapability{ Supported: false, + Mechanism: AutoUpdateMechanismSystemdTimer, Reason: AutoUpdateReasonTimerDisabled, } } @@ -162,6 +225,7 @@ func detectAutoUpdateCapabilityWithProbe(p autoUpdateProbe) AutoUpdateCapability if err != nil { return AutoUpdateCapability{ Supported: false, + Mechanism: AutoUpdateMechanismSystemdTimer, Reason: AutoUpdateReasonHelperMissing, } } @@ -170,11 +234,13 @@ func detectAutoUpdateCapabilityWithProbe(p autoUpdateProbe) AutoUpdateCapability return AutoUpdateCapability{ Supported: true, PreviewSupported: true, + Mechanism: AutoUpdateMechanismSystemdTimer, } } return AutoUpdateCapability{ Supported: true, PreviewSupported: false, + Mechanism: AutoUpdateMechanismSystemdTimer, PreviewReason: AutoUpdatePreviewReasonHelperOutdated, } } diff --git a/internal/updates/auto_update_capability_test.go b/internal/updates/auto_update_capability_test.go index 251d25d0d6..18e3507d96 100644 --- a/internal/updates/auto_update_capability_test.go +++ b/internal/updates/auto_update_capability_test.go @@ -17,8 +17,11 @@ func TestDetectAutoUpdateCapability(t *testing.T) { getCurrentVersion: func() (*VersionInfo, error) { return &VersionInfo{Version: "6.10.0-beta.3", DeploymentType: "systemd"}, nil }, - isPro: func() bool { return false }, - getenv: func(string) string { return "" }, + isPro: func() bool { return false }, + isEnvDisabled: func() bool { return false }, + hasProCredentials: func() bool { return false }, + binaryDirWritable: func() bool { return true }, + getenv: func(string) string { return "" }, stat: func(path string) (os.FileInfo, error) { if path == "/etc/systemd/system/pulse-update.timer" || path == "/etc/systemd/system/pulse.service" { return fakeFileInfo{}, nil @@ -35,9 +38,18 @@ func TestDetectAutoUpdateCapability(t *testing.T) { } } + t.Run("env veto disables auto-updates on any edition", func(t *testing.T) { + p := baseSystemd() + p.isEnvDisabled = func() bool { return true } + got := detectAutoUpdateCapabilityWithProbe(p) + if got.Supported || got.PreviewSupported || got.Reason != AutoUpdateReasonEnvDisabled { + t.Fatalf("unexpected capability: %+v", got) + } + }) + t.Run("community systemd with modern helper supports stable and preview", func(t *testing.T) { got := detectAutoUpdateCapabilityWithProbe(baseSystemd()) - if !got.Supported || !got.PreviewSupported || got.Reason != "" || got.PreviewReason != "" { + if !got.Supported || !got.PreviewSupported || got.Mechanism != AutoUpdateMechanismSystemdTimer || got.Reason != "" { t.Fatalf("unexpected capability: %+v", got) } }) @@ -51,8 +63,40 @@ func TestDetectAutoUpdateCapability(t *testing.T) { } }) - t.Run("docker deployment is unsupported", func(t *testing.T) { + t.Run("activated Pro systemd install supports in-app stable and preview updates", func(t *testing.T) { p := baseSystemd() + p.isPro = func() bool { return true } + p.hasProCredentials = func() bool { return true } + got := detectAutoUpdateCapabilityWithProbe(p) + if !got.Supported || !got.PreviewSupported || got.Mechanism != AutoUpdateMechanismInApp || got.Reason != "" { + t.Fatalf("unexpected capability: %+v", got) + } + }) + + t.Run("unactivated Pro install reports pro_not_activated", func(t *testing.T) { + p := baseSystemd() + p.isPro = func() bool { return true } + p.hasProCredentials = func() bool { return false } + got := detectAutoUpdateCapabilityWithProbe(p) + if got.Supported || got.Reason != AutoUpdateReasonProNotActivated || got.Mechanism != AutoUpdateMechanismInApp { + t.Fatalf("unexpected capability: %+v", got) + } + }) + + t.Run("Pro install with read-only binary dir reports binary_not_writable", func(t *testing.T) { + p := baseSystemd() + p.isPro = func() bool { return true } + p.hasProCredentials = func() bool { return true } + p.binaryDirWritable = func() bool { return false } + got := detectAutoUpdateCapabilityWithProbe(p) + if got.Supported || got.Reason != AutoUpdateReasonBinaryNotWritable { + t.Fatalf("unexpected capability: %+v", got) + } + }) + + t.Run("docker deployment is unsupported on Pro and Community", func(t *testing.T) { + p := baseSystemd() + p.isPro = func() bool { return true } p.getCurrentVersion = func() (*VersionInfo, error) { return &VersionInfo{Version: "6.10.0-beta.3", IsDocker: true, DeploymentType: "docker"}, nil } @@ -62,15 +106,6 @@ func TestDetectAutoUpdateCapability(t *testing.T) { } }) - t.Run("pro edition is unsupported", func(t *testing.T) { - p := baseSystemd() - p.isPro = func() bool { return true } - got := detectAutoUpdateCapabilityWithProbe(p) - if got.Supported || got.PreviewSupported || got.Reason != AutoUpdateReasonPro { - t.Fatalf("unexpected capability: %+v", got) - } - }) - t.Run("source build is unsupported", func(t *testing.T) { p := baseSystemd() p.getCurrentVersion = func() (*VersionInfo, error) { @@ -82,7 +117,7 @@ func TestDetectAutoUpdateCapability(t *testing.T) { } }) - t.Run("missing timer reports timer_not_installed", func(t *testing.T) { + t.Run("missing timer reports timer_not_installed on Community", func(t *testing.T) { p := baseSystemd() p.stat = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist } got := detectAutoUpdateCapabilityWithProbe(p) @@ -91,7 +126,7 @@ func TestDetectAutoUpdateCapability(t *testing.T) { } }) - t.Run("disabled timer reports timer_disabled", func(t *testing.T) { + t.Run("disabled timer reports timer_disabled on Community", func(t *testing.T) { p := baseSystemd() p.timerState = func(string) (string, error) { return "disabled", errors.New("exit 1") } got := detectAutoUpdateCapabilityWithProbe(p) @@ -99,13 +134,4 @@ func TestDetectAutoUpdateCapability(t *testing.T) { t.Fatalf("unexpected capability: %+v", got) } }) - - t.Run("missing helper reports helper_missing", func(t *testing.T) { - p := baseSystemd() - p.readFile = func(string) ([]byte, error) { return nil, os.ErrNotExist } - got := detectAutoUpdateCapabilityWithProbe(p) - if got.Supported || got.Reason != AutoUpdateReasonHelperMissing { - t.Fatalf("unexpected capability: %+v", got) - } - }) } diff --git a/internal/updates/history.go b/internal/updates/history.go index 52021c448d..69bbf1fc1d 100644 --- a/internal/updates/history.go +++ b/internal/updates/history.go @@ -42,11 +42,12 @@ const ( type InitiatedVia string const ( - InitiatedViaUI InitiatedVia = "ui" - InitiatedViaAPI InitiatedVia = "api" - InitiatedViaCLI InitiatedVia = "cli" - InitiatedViaScript InitiatedVia = "script" - InitiatedViaWebhook InitiatedVia = "webhook" + InitiatedViaUI InitiatedVia = "ui" + InitiatedViaAPI InitiatedVia = "api" + InitiatedViaCLI InitiatedVia = "cli" + InitiatedViaScript InitiatedVia = "script" + InitiatedViaWebhook InitiatedVia = "webhook" + InitiatedViaProScheduler InitiatedVia = "pro_scheduler" ) // UpdateHistoryEntry represents a single update event diff --git a/internal/updates/install_lock_other.go b/internal/updates/install_lock_other.go new file mode 100644 index 0000000000..917a81eedb --- /dev/null +++ b/internal/updates/install_lock_other.go @@ -0,0 +1,11 @@ +//go:build !unix + +package updates + +func resolveInstallLockDir() string { + return "" +} + +func acquireInstallDirLock(_ string) (func(), error) { + return func() {}, nil +} diff --git a/internal/updates/install_lock_unix.go b/internal/updates/install_lock_unix.go new file mode 100644 index 0000000000..f75f16d863 --- /dev/null +++ b/internal/updates/install_lock_unix.go @@ -0,0 +1,63 @@ +//go:build unix + +package updates + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "syscall" +) + +// resolveInstallLockDir returns the installation directory inode shared with +// scripts/pulse-auto-update.sh so Go-managed updates and host script updates +// serialize on the same directory flock. +func resolveInstallLockDir() string { + if envDir := strings.TrimSpace(os.Getenv("PULSE_INSTALL_DIR")); envDir != "" { + if info, err := os.Stat(envDir); err == nil && info.IsDir() { + return envDir + } + } + exePath, err := os.Executable() + if err != nil || strings.TrimSpace(exePath) == "" { + return "" + } + dir := filepath.Dir(exePath) + // Default /opt/pulse/bin/pulse lives under /opt/pulse; lock the install root + // so it matches scripts/pulse-auto-update.sh's INSTALL_DIR (/opt/pulse). + if filepath.Base(dir) == "bin" { + parent := filepath.Dir(dir) + if info, err := os.Stat(parent); err == nil && info.IsDir() { + return parent + } + } + if info, err := os.Stat(dir); err == nil && info.IsDir() { + return dir + } + return "" +} + +// acquireInstallDirLock acquires a non-blocking exclusive flock on dir with +// O_CLOEXEC so child processes (such as selfTestNewBinary) never inherit it. +func acquireInstallDirLock(dir string) (func(), error) { + if strings.TrimSpace(dir) == "" { + return func() {}, nil + } + fd, err := syscall.Open(dir, syscall.O_RDONLY|syscall.O_CLOEXEC, 0) + if err != nil { + return nil, fmt.Errorf("cannot open installation directory %q for locking: %w", dir, err) + } + if err := syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + _ = syscall.Close(fd) + if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) { + return nil, fmt.Errorf("another update transaction holds the installation directory lock (%s)", dir) + } + return nil, fmt.Errorf("failed to acquire installation directory lock (%s): %w", dir, err) + } + return func() { + _ = syscall.Flock(fd, syscall.LOCK_UN) + _ = syscall.Close(fd) + }, nil +} diff --git a/internal/updates/manager.go b/internal/updates/manager.go index 7ab90b426f..718efcd69a 100644 --- a/internal/updates/manager.go +++ b/internal/updates/manager.go @@ -250,6 +250,10 @@ type Manager struct { // compiled Pro binary (SetProUpdateCredentialSource, wired at startup). // Nil on the community binary. proCredentialSource func() (ProUpdateCredentials, bool) + restartHook func() + installLockDirFn func() string + proSchedulerStopMu sync.Mutex + proSchedulerStarted bool // operationGeneration advances, under updateMu, each time an apply or // rollback is admitted. An update check may publish statuses only while @@ -291,6 +295,16 @@ type ApplyUpdateRequest struct { // server download broker over this community binary (see // ApplyProRuntimeSwitch). DownloadURL is not used. SwitchToProRuntime bool + // ExpectedVersion pins apply-time broker resolution to the checked version. + // If the broker now points at a different release, ApplyUpdate aborts. + ExpectedVersion string + // RejectMajorUpgrade refuses an apply when the freshly resolved artifact + // crosses a major version boundary (used by unattended updates). + RejectMajorUpgrade bool + // PreApplyCheck runs after download, signature verification, and binary + // self-test, immediately before backup and replacement, while the install + // directory flock is held. Returning an error aborts with zero mutation. + PreApplyCheck func(ctx context.Context, resolvedVersion string) error } // RollbackRequest describes a rollback of a recorded update, restoring the @@ -332,6 +346,21 @@ func (m *Manager) SetHistory(history *UpdateHistory) { m.history = history } +// SetRestartHook wires a graceful process-shutdown trigger used after binary +// replacement instead of an abrupt os.Exit(0). +func (m *Manager) SetRestartHook(fn func()) { + m.lifecycleMu.Lock() + defer m.lifecycleMu.Unlock() + m.restartHook = fn +} + +// HasProUpdateCredentials reports whether usable Pulse Pro activation +// credentials are currently available for the private download broker. +func (m *Manager) HasProUpdateCredentials() bool { + _, ok := m.proUpdateCredentials() + return ok +} + // GetProgressChannel returns the channel for update progress func (m *Manager) GetProgressChannel() <-chan UpdateStatus { return m.progressChan @@ -738,11 +767,17 @@ func (m *Manager) ApplyUpdate(ctx context.Context, req ApplyUpdateRequest) error return fmt.Errorf("manual migration required: Pulse v4 is a complete rewrite. Please create a fresh installation. See %s", updateReleaseMigrationURL()) } - // Ensure only one update runs at a time. + // Ensure only one update runs at a time. When binary replacement succeeds + // and restart is scheduled, keep admission closed through process shutdown. if !m.admitUpdateOperation() { return fmt.Errorf("update already in progress") } - defer m.releaseUpdateOperation() + keepOperationLocked := false + defer func() { + if !keepOperationLocked { + m.releaseUpdateOperation() + } + }() m.updateStatus("downloading", 10, "Downloading update...") @@ -783,6 +818,28 @@ func (m *Manager) ApplyUpdate(ctx context.Context, req ApplyUpdateRequest) error return err } } + if expected := strings.TrimPrefix(strings.TrimSpace(req.ExpectedVersion), "v"); expected != "" { + resolved := strings.TrimPrefix(strings.TrimSpace(artifact.version), "v") + if resolved != expected { + driftErr := fmt.Errorf("resolved update target %s does not match approved version %s", artifact.version, req.ExpectedVersion) + m.updateStatus("error", 10, "Update target changed before apply", driftErr) + return driftErr + } + } + if req.RejectMajorUpgrade { + curVer, curErr := ParseVersion(currentInfo.Version) + tgtVer, tgtErr := ParseVersion(artifact.version) + if curErr != nil || tgtErr != nil { + majorErr := fmt.Errorf("cannot verify major version boundary for %s -> %s", currentInfo.Version, artifact.version) + m.updateStatus("error", 10, "Update rejected", majorErr) + return majorErr + } + if tgtVer.Major > curVer.Major { + majorErr := fmt.Errorf("major version upgrade (%s -> %s) requires manual approval", currentInfo.Version, artifact.version) + m.updateStatus("error", 10, "Major upgrade skipped", majorErr) + return majorErr + } + } initiatedBy := req.InitiatedBy if initiatedBy == "" { @@ -925,13 +982,39 @@ func (m *Manager) ApplyUpdate(ctx context.Context, req ApplyUpdateRequest) error runErr = err return runErr } - if err := selfTestNewBinary(ctx, newBinary, extractDir, artifact.version); err != nil { + if err := selfTestNewBinaryWithOptions(ctx, newBinary, extractDir, artifact.version, useBroker); err != nil { selfTestErr := fmt.Errorf("new binary failed pre-install validation: %w", err) m.updateStatus("error", 50, "New binary failed pre-install validation", selfTestErr) runErr = selfTestErr return runErr } - log.Info().Str("version", artifact.version).Msg("New binary passed pre-install self-test") + log.Info().Str("version", artifact.version).Bool("proEdition", useBroker).Msg("New binary passed pre-install self-test") + + // Coordinate with scripts/pulse-auto-update.sh and manual installer runs via + // the shared installation directory inode flock before mutating files. + lockDirFn := m.installLockDirFn + if lockDirFn == nil { + lockDirFn = resolveInstallLockDir + } + unlockInstallDir, lockErr := acquireInstallDirLock(lockDirFn()) + if lockErr != nil { + m.updateStatus("error", 55, "Another update is already in progress", lockErr) + runErr = lockErr + return runErr + } + defer func() { + if !keepOperationLocked { + unlockInstallDir() + } + }() + + if req.PreApplyCheck != nil { + if err := req.PreApplyCheck(ctx, artifact.version); err != nil { + m.updateStatus("error", 58, "Update cancelled before installation", err) + runErr = err + return runErr + } + } m.updateStatus("backing-up", 60, "Creating backup...") @@ -967,10 +1050,21 @@ func (m *Manager) ApplyUpdate(ctx context.Context, req ApplyUpdateRequest) error m.updateStatus("restarting", 95, "Restarting service...") - // Schedule a clean exit after a short delay - systemd will restart us + // Schedule a graceful shutdown after a short delay so SSE clients observe + // completion and systemd restarts Pulse on the new binary. Keep operation + // admission and the install-directory flock closed through shutdown. if !dockerUpdatesAllowed() { + keepOperationLocked = true + m.lifecycleMu.RLock() + restartFn := m.restartHook + m.lifecycleMu.RUnlock() go func() { time.Sleep(2 * time.Second) + if restartFn != nil { + log.Info().Msg("Triggering graceful shutdown for restart after update") + restartFn() + return + } log.Info().Msg("Exiting for restart after update") os.Exit(0) }() @@ -2113,6 +2207,16 @@ func (m *Manager) RollbackToBackup(ctx context.Context, req RollbackRequest) err } defer m.releaseUpdateOperation() + lockDirFn := m.installLockDirFn + if lockDirFn == nil { + lockDirFn = resolveInstallLockDir + } + unlockInstallDir, lockErr := acquireInstallDirLock(lockDirFn()) + if lockErr != nil { + return lockErr + } + defer unlockInstallDir() + initiatedBy := req.InitiatedBy if initiatedBy == "" { initiatedBy = InitiatedByUser diff --git a/internal/updates/pro_auto_update.go b/internal/updates/pro_auto_update.go new file mode 100644 index 0000000000..01a164f8a3 --- /dev/null +++ b/internal/updates/pro_auto_update.go @@ -0,0 +1,443 @@ +package updates + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/rcourtman/pulse-go-rewrite/internal/config" + "github.com/rcourtman/pulse-go-rewrite/pkg/edition" + "github.com/rs/zerolog/log" +) + +const ( + proAutoUpdateStateFileName = "pro-auto-update-state.json" + proAutoUpdateWindowStartHr = 2 + proAutoUpdateWindowEndHr = 6 + proAutoUpdateWindowMinutes = (proAutoUpdateWindowEndHr - proAutoUpdateWindowStartHr) * 60 + proAutoUpdatePollInterval = 1 * time.Minute + proAutoUpdateCheckTimeout = 2 * time.Minute + proAutoUpdateApplyTimeout = 15 * time.Minute +) + +// ProAutoUpdatePending tracks an in-flight unattended Pro replacement so the +// next boot can confirm whether the target version came up cleanly or suppress +// a broken release from retrying every night. +type ProAutoUpdatePending struct { + TargetVersion string `json:"targetVersion"` + PreviousVersion string `json:"previousVersion"` + Channel string `json:"channel"` + StartedAt time.Time `json:"startedAt"` +} + +// ProAutoUpdateState is persisted atomically under DataPath. +type ProAutoUpdateState struct { + InstallID string `json:"installId"` + LastAttemptDate string `json:"lastAttemptDate,omitempty"` + SuppressedVersion string `json:"suppressedVersion,omitempty"` + SuppressedReason string `json:"suppressedReason,omitempty"` + Pending *ProAutoUpdatePending `json:"pending,omitempty"` +} + +// ProAutoUpdateDeps bundles injectable dependencies for deterministic testing. +type ProAutoUpdateDeps struct { + Now func() time.Time + IsPro func() bool + IsEnvDisabled func() bool + GetVersion func() (*VersionInfo, error) + CheckForUpdate func(ctx context.Context, channel string) (*UpdateInfo, error) + ApplyUpdate func(ctx context.Context, req ApplyUpdateRequest) error + DrainBeforeApply func(ctx context.Context) error +} + +func (m *Manager) proAutoUpdateStatePath() string { + dataDir := "" + if m.config != nil { + dataDir = strings.TrimSpace(m.config.DataPath) + } + if dataDir == "" { + dataDir = defaultUpdateHistoryDataDir + } + return filepath.Join(dataDir, proAutoUpdateStateFileName) +} + +func loadProAutoUpdateState(path string) (ProAutoUpdateState, error) { + var state ProAutoUpdateState + raw, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return state, nil + } + return state, err + } + if len(strings.TrimSpace(string(raw))) == 0 { + return state, nil + } + if err := json.Unmarshal(raw, &state); err != nil { + return ProAutoUpdateState{}, fmt.Errorf("parse %s: %w", proAutoUpdateStateFileName, err) + } + return state, nil +} + +func saveProAutoUpdateState(path string, state ProAutoUpdateState) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("prepare pro auto-update state directory: %w", err) + } + encoded, err := json.MarshalIndent(state, "", " ") + if err != nil { + return err + } + encoded = append(encoded, '\n') + + tmp, err := os.CreateTemp(dir, ".pro-auto-update-state-*.tmp") + if err != nil { + return fmt.Errorf("stage pro auto-update state: %w", err) + } + tmpPath := tmp.Name() + cleanup := true + defer func() { + if cleanup { + _ = os.Remove(tmpPath) + } + }() + if err := tmp.Chmod(0o600); err != nil { + _ = tmp.Close() + return err + } + if _, err := tmp.Write(encoded); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Rename(tmpPath, path); err != nil { + return fmt.Errorf("commit pro auto-update state: %w", err) + } + cleanup = false + return nil +} + +func ensureProInstallID(state *ProAutoUpdateState) bool { + if strings.TrimSpace(state.InstallID) != "" { + return false + } + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + // Fallback to timestamp entropy if rand.Read fails unexpectedly. + binary.BigEndian.PutUint64(b[:8], uint64(time.Now().UnixNano())) + } + state.InstallID = hex.EncodeToString(b[:]) + return true +} + +// proAutoUpdateSlotMinute deterministically maps an install ID into the daily +// 02:00..05:59 local overnight window (offset 0..239 minutes after 02:00). +func proAutoUpdateSlotMinute(installID string) int { + sum := sha256.Sum256([]byte("pulse-pro-auto-update:" + installID)) + return int(binary.BigEndian.Uint32(sum[:4]) % proAutoUpdateWindowMinutes) +} + +func isWithinOvernightSlot(now time.Time, slotOffsetMinutes int) bool { + localNow := now.Local() + minuteOfDay := localNow.Hour()*60 + localNow.Minute() + slotStart := proAutoUpdateWindowStartHr*60 + slotOffsetMinutes + windowEnd := proAutoUpdateWindowEndHr * 60 + return minuteOfDay >= slotStart && minuteOfDay < windowEnd +} + +func (m *Manager) defaultProAutoUpdateDeps() ProAutoUpdateDeps { + return ProAutoUpdateDeps{ + Now: time.Now, + IsPro: edition.IsPro, + IsEnvDisabled: config.IsAutoUpdateDisabledByEnv, + GetVersion: GetCurrentVersion, + CheckForUpdate: func(ctx context.Context, channel string) (*UpdateInfo, error) { + return m.CheckForUpdatesWithOptions(ctx, UpdateCheckOptions{ + Channel: channel, + Force: true, + }) + }, + ApplyUpdate: m.ApplyUpdate, + } +} + +// ReconcilePendingProAutoUpdate inspects any persisted in-flight Pro update +// from before restart. Matching running version confirms startup; mismatch +// suppresses the failed target version so it never loops nightly. +func (m *Manager) ReconcilePendingProAutoUpdate() { + m.reconcilePendingProAutoUpdateWithDeps(m.defaultProAutoUpdateDeps()) +} + +func (m *Manager) reconcilePendingProAutoUpdateWithDeps(deps ProAutoUpdateDeps) { + if deps.IsPro != nil && !deps.IsPro() { + return + } + statePath := m.proAutoUpdateStatePath() + state, err := loadProAutoUpdateState(statePath) + if err != nil { + log.Warn().Err(err).Msg("Failed to read Pro auto-update state during startup reconciliation") + return + } + dirty := ensureProInstallID(&state) + if state.Pending != nil { + currentInfo, vErr := deps.GetVersion() + runningVer := "" + if vErr == nil && currentInfo != nil { + runningVer = strings.TrimPrefix(strings.TrimSpace(currentInfo.Version), "v") + } + targetVer := strings.TrimPrefix(strings.TrimSpace(state.Pending.TargetVersion), "v") + if runningVer != "" && runningVer == targetVer { + log.Info(). + Str("version", targetVer). + Str("channel", state.Pending.Channel). + Msg("Confirmed unattended Pulse Pro update after restart") + state.SuppressedVersion = "" + state.SuppressedReason = "" + } else { + log.Warn(). + Str("expectedVersion", targetVer). + Str("runningVersion", runningVer). + Msg("Unattended Pulse Pro update did not activate on restart; suppressing version until a newer release is published") + state.SuppressedVersion = targetVer + state.SuppressedReason = "startup_mismatch_or_interrupted" + } + state.Pending = nil + dirty = true + } + if dirty { + if err := saveProAutoUpdateState(statePath, state); err != nil { + log.Warn().Err(err).Msg("Failed to persist Pro auto-update state during startup reconciliation") + } + } +} + +func (m *Manager) snapshotProAutoUpdatePolicy(isEnvDisabled func() bool) (channel string, allowed bool) { + if isEnvDisabled != nil && isEnvDisabled() { + return "stable", false + } + if m.config == nil { + return "stable", false + } + config.Mu.RLock() + channel = config.EffectiveUpdateChannel(m.config.UpdateChannel, "") + enabled := m.config.AutoUpdateEnabled + previewConsent := m.config.AutoUpdatePreviewConsent + proConsent := m.config.AutoUpdateProConsent + config.Mu.RUnlock() + allowed = config.EffectiveAutoUpdateEnabledForEdition(channel, enabled, previewConsent, true, proConsent) + return channel, allowed +} + +// StartProAutoUpdater launches the single cancellable overnight auto-update +// loop for supported Pulse Pro systemd/Proxmox VE installations. +func (m *Manager) StartProAutoUpdater(ctx context.Context) { + if !edition.IsPro() { + return + } + currentInfo, err := GetCurrentVersion() + if err != nil || currentInfo == nil || currentInfo.IsDocker || currentInfo.IsSourceBuild { + return + } + deployment := strings.ToLower(strings.TrimSpace(currentInfo.DeploymentType)) + if deployment != "systemd" && deployment != "proxmoxve" { + return + } + m.proSchedulerStopMu.Lock() + if m.proSchedulerStarted { + m.proSchedulerStopMu.Unlock() + return + } + m.proSchedulerStarted = true + m.proSchedulerStopMu.Unlock() + + m.ReconcilePendingProAutoUpdate() + + deps := m.defaultProAutoUpdateDeps() + go func() { + ticker := time.NewTicker(proAutoUpdatePollInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-m.shutdownCh: + return + case <-ticker.C: + m.maybeRunProAutoUpdate(ctx, deps) + } + } + }() +} + +func (m *Manager) maybeRunProAutoUpdate(ctx context.Context, deps ProAutoUpdateDeps) { + now := deps.Now() + statePath := m.proAutoUpdateStatePath() + state, err := loadProAutoUpdateState(statePath) + if err != nil { + log.Warn().Err(err).Msg("Skipping unattended Pulse Pro update: state file unreadable") + return + } + if ensureProInstallID(&state) { + if err := saveProAutoUpdateState(statePath, state); err != nil { + log.Warn().Err(err).Msg("Skipping unattended Pulse Pro update: could not initialize state file") + return + } + } + today := now.Local().Format("2006-01-02") + if state.LastAttemptDate == today { + return + } + if !isWithinOvernightSlot(now, proAutoUpdateSlotMinute(state.InstallID)) { + return + } + _ = m.runProAutoUpdateOnce(ctx, deps) +} + +// runProAutoUpdateOnce executes one gated Pro unattended check and apply cycle. +func (m *Manager) runProAutoUpdateOnce(ctx context.Context, deps ProAutoUpdateDeps) error { + if deps.IsPro != nil && !deps.IsPro() { + return nil + } + channel, allowed := m.snapshotProAutoUpdatePolicy(deps.IsEnvDisabled) + if !allowed { + return nil + } + if !m.HasProUpdateCredentials() { + log.Debug().Msg("Skipping unattended Pulse Pro update: activation credentials unavailable") + return nil + } + + currentInfo, err := deps.GetVersion() + if err != nil || currentInfo == nil { + return fmt.Errorf("cannot verify current version for unattended Pro update: %w", err) + } + if currentInfo.IsDocker || currentInfo.IsSourceBuild { + return nil + } + + statePath := m.proAutoUpdateStatePath() + state, err := loadProAutoUpdateState(statePath) + if err != nil { + return fmt.Errorf("load pro auto-update state: %w", err) + } + ensureProInstallID(&state) + today := deps.Now().Local().Format("2006-01-02") + + checkCtx, checkCancel := context.WithTimeout(ctx, proAutoUpdateCheckTimeout) + info, err := deps.CheckForUpdate(checkCtx, channel) + checkCancel() + if err != nil { + log.Warn().Err(err).Str("channel", channel).Msg("Unattended Pulse Pro update check failed") + return err + } + + state.LastAttemptDate = today + if info == nil || !info.Available || strings.TrimSpace(info.DownloadURL) == "" { + _ = saveProAutoUpdateState(statePath, state) + return nil + } + + targetVersion := strings.TrimPrefix(strings.TrimSpace(info.LatestVersion), "v") + if info.IsMajorUpgrade { + log.Info(). + Str("current", currentInfo.Version). + Str("latest", targetVersion). + Msg("Skipping unattended Pulse Pro major upgrade") + _ = saveProAutoUpdateState(statePath, state) + return nil + } + if state.SuppressedVersion != "" && state.SuppressedVersion == targetVersion { + log.Info(). + Str("version", targetVersion). + Str("reason", state.SuppressedReason). + Msg("Skipping suppressed Pulse Pro update version until a newer release ships") + _ = saveProAutoUpdateState(statePath, state) + return nil + } + + applyCtx, applyCancel := context.WithTimeout(ctx, proAutoUpdateApplyTimeout) + defer applyCancel() + + applyErr := deps.ApplyUpdate(applyCtx, ApplyUpdateRequest{ + DownloadURL: info.DownloadURL, + Channel: channel, + ExpectedVersion: targetVersion, + RejectMajorUpgrade: true, + InitiatedBy: InitiatedByAuto, + InitiatedVia: InitiatedViaProScheduler, + Notes: "Scheduled overnight Pulse Pro update", + PreApplyCheck: func(checkCtx context.Context, resolvedVersion string) error { + // Re-verify consent, channel, env veto, and Pro activation right before mutation. + latestChannel, stillAllowed := m.snapshotProAutoUpdatePolicy(deps.IsEnvDisabled) + if !stillAllowed || latestChannel != channel { + return fmt.Errorf("auto-update consent or channel changed before installation") + } + if !m.HasProUpdateCredentials() { + return fmt.Errorf("Pulse Pro activation credentials are no longer available") + } + if deps.DrainBeforeApply != nil { + if err := deps.DrainBeforeApply(checkCtx); err != nil { + return fmt.Errorf("deferring unattended update because active work did not drain: %w", err) + } + } + // Durably record pending attempt BEFORE mutating binary; fail closed on write error. + state.LastAttemptDate = today + state.Pending = &ProAutoUpdatePending{ + TargetVersion: strings.TrimPrefix(strings.TrimSpace(resolvedVersion), "v"), + PreviousVersion: strings.TrimPrefix(strings.TrimSpace(currentInfo.Version), "v"), + Channel: channel, + StartedAt: deps.Now().UTC(), + } + if err := saveProAutoUpdateState(statePath, state); err != nil { + return fmt.Errorf("failed to persist pending Pro update state: %w", err) + } + return nil + }, + }) + if applyErr != nil { + log.Warn().Err(applyErr).Str("targetVersion", targetVersion).Msg("Unattended Pulse Pro update failed") + state.Pending = nil + state.LastAttemptDate = today + if shouldSuppressFailedProVersion(applyErr) { + state.SuppressedVersion = targetVersion + state.SuppressedReason = "apply_failed" + } + _ = saveProAutoUpdateState(statePath, state) + return applyErr + } + return nil +} + +func shouldSuppressFailedProVersion(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + for _, marker := range []string{ + "pre-install validation", + "expected pulse pro edition", + "signature verification failed", + "checksum", + "failed to apply update", + } { + if strings.Contains(msg, marker) { + return true + } + } + return false +} diff --git a/internal/updates/pro_auto_update_test.go b/internal/updates/pro_auto_update_test.go new file mode 100644 index 0000000000..f90528b3a7 --- /dev/null +++ b/internal/updates/pro_auto_update_test.go @@ -0,0 +1,208 @@ +package updates + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/rcourtman/pulse-go-rewrite/internal/config" +) + +func TestProAutoUpdate_ReconcilePendingStartup(t *testing.T) { + dir := t.TempDir() + cfg := &config.Config{DataPath: dir} + m := NewManager(cfg) + defer m.Close() + + statePath := m.proAutoUpdateStatePath() + seed := ProAutoUpdateState{ + InstallID: "install-abc", + Pending: &ProAutoUpdatePending{ + TargetVersion: "6.10.0-beta.4", + PreviousVersion: "6.10.0-beta.3", + Channel: "rc", + StartedAt: time.Now().UTC(), + }, + } + if err := saveProAutoUpdateState(statePath, seed); err != nil { + t.Fatal(err) + } + + // Startup mismatch (previous version still running) suppresses target version. + m.reconcilePendingProAutoUpdateWithDeps(ProAutoUpdateDeps{ + IsPro: func() bool { return true }, + GetVersion: func() (*VersionInfo, error) { + return &VersionInfo{Version: "6.10.0-beta.3"}, nil + }, + }) + got, err := loadProAutoUpdateState(statePath) + if err != nil { + t.Fatal(err) + } + if got.Pending != nil || got.SuppressedVersion != "6.10.0-beta.4" { + t.Fatalf("expected mismatch to suppress 6.10.0-beta.4, got %+v", got) + } + + // Matching version on restart confirms startup and clears suppression. + seed.Pending.TargetVersion = "6.10.0-beta.5" + seed.SuppressedVersion = "6.10.0-beta.4" + if err := saveProAutoUpdateState(statePath, seed); err != nil { + t.Fatal(err) + } + m.reconcilePendingProAutoUpdateWithDeps(ProAutoUpdateDeps{ + IsPro: func() bool { return true }, + GetVersion: func() (*VersionInfo, error) { + return &VersionInfo{Version: "6.10.0-beta.5"}, nil + }, + }) + got, err = loadProAutoUpdateState(statePath) + if err != nil { + t.Fatal(err) + } + if got.Pending != nil || got.SuppressedVersion != "" { + t.Fatalf("expected matching boot to confirm and clear suppression, got %+v", got) + } +} + +func TestProAutoUpdate_EnforcesConsentEnvVetoMajorUpgradeAndSuppression(t *testing.T) { + dir := t.TempDir() + cfg := &config.Config{ + DataPath: dir, + UpdateChannel: "rc", + AutoUpdateEnabled: true, + AutoUpdatePreviewConsent: true, + AutoUpdateProConsent: false, // dormant Pro config! + } + m := NewManager(cfg) + defer m.Close() + m.SetProUpdateCredentialSource(func() (ProUpdateCredentials, bool) { + return ProUpdateCredentials{ + LicenseServerURL: "https://license.pulserelay.pro", + InstallationToken: "tok", + }, true + }) + + applyCalled := 0 + baseDeps := func(info *UpdateInfo, applyErr error) ProAutoUpdateDeps { + return ProAutoUpdateDeps{ + Now: func() time.Time { return time.Date(2026, 11, 30, 3, 15, 0, 0, time.Local) }, + IsPro: func() bool { return true }, + IsEnvDisabled: func() bool { return false }, + GetVersion: func() (*VersionInfo, error) { + return &VersionInfo{Version: "6.10.0-beta.3", DeploymentType: "systemd"}, nil + }, + CheckForUpdate: func(context.Context, string) (*UpdateInfo, error) { return info, nil }, + ApplyUpdate: func(ctx context.Context, req ApplyUpdateRequest) error { + applyCalled++ + if req.PreApplyCheck != nil { + if err := req.PreApplyCheck(ctx, req.ExpectedVersion); err != nil { + return err + } + } + return applyErr + }, + } + } + + offer := &UpdateInfo{ + Available: true, + LatestVersion: "6.10.0-beta.4", + DownloadURL: "https://license.pulserelay.pro/v1/downloads/pulse-pro?version=6.10.0-beta.4", + } + + // 1. Dormant Pro config (AutoUpdateProConsent=false) must NOT run. + if err := m.runProAutoUpdateOnce(context.Background(), baseDeps(offer, nil)); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if applyCalled != 0 { + t.Fatalf("dormant Pro config must not apply updates, got %d calls", applyCalled) + } + + // 2. Enable explicit Pro consent -> major upgrade must still be skipped. + cfg.AutoUpdateProConsent = true + majorOffer := &UpdateInfo{Available: true, LatestVersion: "7.0.0", DownloadURL: offer.DownloadURL, IsMajorUpgrade: true} + if err := m.runProAutoUpdateOnce(context.Background(), baseDeps(majorOffer, nil)); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if applyCalled != 0 { + t.Fatalf("major upgrade must be skipped, got %d calls", applyCalled) + } + + // 3. Consent revocation during download aborts inside PreApplyCheck with zero apply. + depsRevoked := baseDeps(offer, nil) + depsRevoked.ApplyUpdate = func(ctx context.Context, req ApplyUpdateRequest) error { + config.Mu.Lock() + cfg.AutoUpdateEnabled = false + config.Mu.Unlock() + return req.PreApplyCheck(ctx, req.ExpectedVersion) + } + if err := m.runProAutoUpdateOnce(context.Background(), depsRevoked); err == nil || !strings.Contains(err.Error(), "consent or channel changed") { + t.Fatalf("expected consent-changed abort, got: %v", err) + } + + // 4. Failed binary self-test suppresses the target version so a second run skips it. + cfg.AutoUpdateEnabled = true + applyCalled = 0 + badErr := errors.New("new binary failed pre-install validation: expected Pulse Pro edition") + if err := m.runProAutoUpdateOnce(context.Background(), baseDeps(offer, badErr)); err == nil { + t.Fatal("expected self-test error") + } + if applyCalled != 1 { + t.Fatalf("expected 1 apply call, got %d", applyCalled) + } + // Subsequent run for same version must skip it. + if err := m.runProAutoUpdateOnce(context.Background(), baseDeps(offer, nil)); err != nil { + t.Fatalf("unexpected error on suppressed version: %v", err) + } + if applyCalled != 1 { + t.Fatalf("suppressed version must not retry, got %d calls", applyCalled) + } + + // 5. Drain timeout defers unattended update cleanly without suppressing the release. + newerOffer := &UpdateInfo{Available: true, LatestVersion: "6.10.0-beta.5", DownloadURL: offer.DownloadURL} + depsDrain := baseDeps(newerOffer, nil) + depsDrain.DrainBeforeApply = func(context.Context) error { return context.DeadlineExceeded } + if err := m.runProAutoUpdateOnce(context.Background(), depsDrain); err == nil || !strings.Contains(err.Error(), "did not drain") { + t.Fatalf("expected drain deferral error, got: %v", err) + } + state, _ := loadProAutoUpdateState(m.proAutoUpdateStatePath()) + if state.SuppressedVersion == "6.10.0-beta.5" { + t.Fatalf("drain deferral must not permanently suppress version: %+v", state) + } +} + +func TestProAutoUpdate_InstallDirLockAndOvernightSlot(t *testing.T) { + lockDir := t.TempDir() + unlock, err := acquireInstallDirLock(lockDir) + if err != nil { + t.Fatalf("first lock acquisition failed: %v", err) + } + if _, err := acquireInstallDirLock(lockDir); err == nil || !strings.Contains(err.Error(), "holds the installation directory lock") { + t.Fatalf("expected second lock acquisition to fail while held, got: %v", err) + } + unlock() + unlock2, err := acquireInstallDirLock(lockDir) + if err != nil { + t.Fatalf("re-acquiring lock after release failed: %v", err) + } + unlock2() + + slot := proAutoUpdateSlotMinute("install-id-12345") + if slot < 0 || slot >= proAutoUpdateWindowMinutes { + t.Fatalf("slot out of bounds: %d", slot) + } + before := time.Date(2026, 11, 30, 1, 59, 0, 0, time.Local) + if isWithinOvernightSlot(before, slot) { + t.Fatal("01:59 must never be inside overnight window") + } + atSlot := time.Date(2026, 11, 30, 2, 0, 0, 0, time.Local).Add(time.Duration(slot) * time.Minute) + if !isWithinOvernightSlot(atSlot, slot) { + t.Fatalf("exact slot minute %v must be inside overnight window", atSlot) + } + after := time.Date(2026, 11, 30, 6, 0, 0, 0, time.Local) + if isWithinOvernightSlot(after, slot) { + t.Fatal("06:00 must be outside overnight window") + } +} diff --git a/internal/updates/selftest.go b/internal/updates/selftest.go index ca50529846..a410a62096 100644 --- a/internal/updates/selftest.go +++ b/internal/updates/selftest.go @@ -31,6 +31,10 @@ var selfTestVersionTokenRegex = regexp.MustCompile(`v?\d+\.\d+\.\d+(?:-[A-Za-z0- // is the version the user approved. --version exits before any server // startup, so the probe is side-effect free. func selfTestNewBinary(ctx context.Context, binaryPath, workDir, expectedVersion string) error { + return selfTestNewBinaryWithOptions(ctx, binaryPath, workDir, expectedVersion, false) +} + +func selfTestNewBinaryWithOptions(ctx context.Context, binaryPath, workDir, expectedVersion string, requireProEdition bool) error { if err := os.Chmod(binaryPath, 0o755); err != nil { return fmt.Errorf("failed to mark new binary executable for self-test: %w", err) } @@ -51,6 +55,16 @@ func selfTestNewBinary(ctx context.Context, binaryPath, workDir, expectedVersion return fmt.Errorf("new pulse binary failed --version self-test: %w (output: %q)", err, probeOutput) } + if requireProEdition { + firstLine := probeOutput + if idx := strings.IndexByte(firstLine, '\n'); idx >= 0 { + firstLine = strings.TrimSpace(firstLine[:idx]) + } + if !strings.HasPrefix(firstLine, "Pulse Pro ") { + return fmt.Errorf("new binary self-test reported %q, expected Pulse Pro edition", firstLine) + } + } + expected := strings.TrimPrefix(strings.TrimSpace(expectedVersion), "v") if expected == "" { return nil diff --git a/internal/updates/selftest_test.go b/internal/updates/selftest_test.go index 04aff92823..9c6257983b 100644 --- a/internal/updates/selftest_test.go +++ b/internal/updates/selftest_test.go @@ -152,3 +152,15 @@ func buildTarballWithPulseBinary(t *testing.T, binary []byte) []byte { return buf.Bytes() } + +func TestSelfTestNewBinaryRequiresProEditionWhenRequested(t *testing.T) { + commBin := writeFakeVersionScript(t, "echo 'Pulse v6.10.0-beta.4'") + if err := selfTestNewBinaryWithOptions(context.Background(), commBin, t.TempDir(), "6.10.0-beta.4", true); err == nil { + t.Fatal("expected community binary output to fail Pro edition self-test") + } + + proBin := writeFakeVersionScript(t, "echo 'Pulse Pro v6.10.0-beta.4'") + if err := selfTestNewBinaryWithOptions(context.Background(), proBin, t.TempDir(), "6.10.0-beta.4", true); err != nil { + t.Fatalf("expected Pro binary output to pass self-test, got: %v", err) + } +} diff --git a/pkg/server/server.go b/pkg/server/server.go index 6db5881c88..e18c119186 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -494,6 +494,15 @@ func Run(ctx context.Context, version string) (runErr error) { // Start AI patrol service for background infrastructure monitoring router.StartPatrol(ctx) + updateRestartChan := make(chan struct{}, 1) + router.SetUpdateRestartHook(func() { + select { + case updateRestartChan <- struct{}{}: + default: + } + }) + router.StartProAutoUpdater(ctx) + // Start AI chat service router.StartAIChat(ctx) startup.mark("AI services started") @@ -919,6 +928,10 @@ func Run(ctx context.Context, version string) (runErr error) { log.Info().Msg("Runtime configuration reloaded") } + case <-updateRestartChan: + log.Info().Msg("Shutting down server cleanly for update restart...") + goto shutdown + case <-sigChan: log.Info().Msg("Shutting down server...") goto shutdown diff --git a/scripts/installtests/pulse_auto_update_consent_test.go b/scripts/installtests/pulse_auto_update_consent_test.go index b860b3bd37..38971d5954 100644 --- a/scripts/installtests/pulse_auto_update_consent_test.go +++ b/scripts/installtests/pulse_auto_update_consent_test.go @@ -687,3 +687,26 @@ func TestAutoUpdateVersionProbeHasHardDeadline(t *testing.T) { t.Fatalf("deadline: %v, duration %s, output %s", err, time.Since(start), out) } } + +func TestAutoUpdateEnvVetoExitsCleanly(t *testing.T) { + t.Parallel() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "system.json"), []byte(`{"autoUpdateEnabled":true,"updateChannel":"stable"}`), 0600); err != nil { + t.Fatal(err) + } + script := "set -euo pipefail\nlog() { printf '%s: %s\n' \"$1\" \"$2\"; }\n" + + extractAutoUpdateAdmissionFunction(t, "check_auto_updates_enabled") + + "\ncheck_auto_updates_enabled\necho STILL_RUNNING\n" + cmd := exec.Command("bash", "-c", script) + cmd.Env = append(os.Environ(), "CONFIG_DIR="+dir, "PULSE_DISABLE_AUTO_UPDATE=true") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("env veto should exit 0, got %v output=%q", err, out) + } + if strings.Contains(string(out), "STILL_RUNNING") { + t.Fatalf("env veto must exit before proceeding, got output=%q", out) + } + if !strings.Contains(string(out), "PULSE_DISABLE_AUTO_UPDATE") { + t.Fatalf("expected env veto log line, got output=%q", out) + } +} diff --git a/scripts/pulse-auto-update.sh b/scripts/pulse-auto-update.sh index a31d8b0e36..ea44b603ab 100755 --- a/scripts/pulse-auto-update.sh +++ b/scripts/pulse-auto-update.sh @@ -111,6 +111,10 @@ verify_release_signature() { # Check if auto-updates are enabled and resolve the admitted channel check_auto_updates_enabled() { AUTO_UPDATE_CHANNEL="stable" + if [[ "${PULSE_DISABLE_AUTO_UPDATE:-}" =~ ^([Tt][Rr][Uu][Ee]|1|[Yy][Ee][Ss])$ ]]; then + log info "Auto-updates disabled by PULSE_DISABLE_AUTO_UPDATE environment variable" + exit 0 + fi # Consent must come from one complete object, not matching text in a # truncated file, nested setting or quoted string. jq is already an # installer dependency; without it, leave manual updates available but