Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Keep unattended Windows removal failures recoverable

pulse-triage[bot]26b8e9b69f1c
diff --git a/.github/workflows/unified-agent-native.yml b/.github/workflows/unified-agent-native.yml
index a979545d77..785e1262f1 100644
--- a/.github/workflows/unified-agent-native.yml
+++ b/.github/workflows/unified-agent-native.yml
@@ -272,7 +272,7 @@ jobs:
- name: Test native Windows installer contracts
if: ${{ !matrix.unix }}
- run: go test ./scripts/installtests -run '^Test(InstallPS1|WindowsAgentLifecycle)'
+ run: go test ./scripts/installtests ./scripts/installtests/windowslifecycleserver -run '^Test(InstallPS1|WindowsAgentLifecycle|UninstallProof)'
- name: Execute generated command with Windows PowerShell 5.1
if: ${{ !matrix.unix }}
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index a9b93d411f..3b30879f46 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -4163,6 +4163,29 @@ Help must describe both retained-state and older-script limits and have actual
Docs desktop/narrow browser proof; neither Help nor doubles establish native
installed removal, credential revocation, publication or whole-issue recovery.
+The existing native lifecycle must also exercise the installed saved-only path,
+not just an unauthenticated peer that echoes any requested ID. Its loopback-only
+synthetic peer requires the saved fixture token and exact identity, counts each
+POST independently and supplies HTTP refusal, wrong-ID, string-success and
+missing-ID responses. After each refusal the real installer must return exit 1,
+with SCM/listener absence and every installed recovery file's bytes and ACL
+unchanged. Quiescence precedes the snapshot so final agent log writes are not
+mislabelled loss. Only one confirmed POST permits local cleanup; repeated
+removal must independently observe absence without another POST. Child removal
+receives no connection arguments or ambient connection/credential/TLS inputs.
+The peer exposes counts only, never credential or request/response contents.
+
+`-NonInteractive` errors print their diagnostic and return without loading a
+desktop dialogue. Interactive error UI remains available. The saved-removal
+child is deadline-bound, checks exact exits and private-output controls, and
+confirms owned child termination on failure. `TestInstallPS1NonInteractiveErrorsKeepAnUnattendedExit`,
+`TestWindowsAgentLifecycleSavedRemovalRequiresAdverseAndCleanReadback` and
+`TestWindowsAgentLifecycleSavedRemovalInvokerRuntime` cover this route alongside
+the peer's `TestUninstallProof*` HTTP/race controls. The real hosted Windows
+PowerShell 5.1 lifecycle, configured-CA transport, signed shipped installer and
+original customer recovery remain distinct evidence; Linux skips do not prove
+them. No production service or provider is a test target.
+
`cmd/pulse-agent-helper/main_test.go`, `internal/agenthelper/server_test.go`, `internal/hostagent/privilege_helper_client_test.go` and `pkg/agents/host/proxmox_lxc_test.go` must cover version negotiation, successful partial rows, all-failed/global-unavailable distinction, contradictory/overbound identities, degraded health and independent operation recovery. `scripts/installtests/safe_profile_migration_test.go` covers installer-managed helper replacement after effective-unit/socket validation and fatal restart failure. These source controls do not prove an installed upgrade or PVE recovery.
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 02e98bcca4..240f63afad 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -8894,6 +8894,18 @@ owned server teardown fails; an unconfirmed stop fails and retains the handle
rather than reporting clean teardown. Real Windows execution and full terminal
cleanup evidence still have to be returned by the existing native CI job.
+The same native job now runs the saved-removal invoker controls and its
+loopback-only peer tests. Its real installed lifecycle checks four adverse
+unregistration responses before confirmation/repeated cleanup, authenticates
+with the saved synthetic token and exact ID, and compares every recovery
+file's bytes/ACL and state-directory ACL after each refusal. Removal children
+have no supplied or inherited connection selectors and must return within a
+bounded deadline. A `-NonInteractive` installer error prints but opens no modal
+dialogue; interactive behaviour is unchanged. The agent-lifecycle contract
+owns these exact-ID/retention boundaries. Source/HTTP tests and Linux skips
+do not substitute for the containing Windows PowerShell 5.1/SCM job, saved-CA
+transport or installed customer acceptance.
+
### Server-only installer release discovery (9 October 2026)
The server installer uses one selector for its installer-script URL and server
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 1ec967acbc..2843af4518 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -130,6 +130,10 @@ function Show-Error {
param([string]$Message)
Write-Host $Message -ForegroundColor Red
+ # An unattended failure must return its exit, not wait for a desktop user
+ # to dismiss a modal dialogue (including during saved-state recovery).
+ if ($NonInteractive) { return }
+
# Try to show a popup if running in a GUI environment
try {
Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue
diff --git a/scripts/installtests/windows_agent_lifecycle.ps1 b/scripts/installtests/windows_agent_lifecycle.ps1
index 550f00c7bf..beb6d73991 100644
--- a/scripts/installtests/windows_agent_lifecycle.ps1
+++ b/scripts/installtests/windows_agent_lifecycle.ps1
@@ -56,7 +56,11 @@ function Stop-LifecycleServer {
}
function Start-LifecycleServer {
- param([string]$AgentPath)
+ param(
+ [string]$AgentPath,
+ [ValidateSet('confirm', 'http-503', 'wrong-id', 'string-success', 'missing-id')]
+ [string]$UninstallMode = 'confirm'
+ )
Stop-LifecycleServer
$version = ((& $AgentPath --version 2>$null) | Select-Object -First 1).Trim()
if ($LASTEXITCODE -ne 0) { throw "Lifecycle input version check failed (exit $LASTEXITCODE)." }
@@ -66,7 +70,8 @@ function Start-LifecycleServer {
$arguments = @(
'--listen', "127.0.0.1:$Port",
'--agent-binary', ('"{0}"' -f $AgentPath),
- '--version', $version
+ '--version', $version,
+ '--uninstall-mode', $UninstallMode
)
$script:serverProcess = Start-Process -FilePath $script:resolvedServerBinary -ArgumentList $arguments -PassThru -NoNewWindow
for ($i = 0; $i -lt 30; $i++) {
@@ -76,6 +81,7 @@ function Start-LifecycleServer {
try {
$response = Invoke-RestMethod -Uri "$baseUrl/api/version" -TimeoutSec 2
if ($response.version -eq $version) {
+ Assert-UninstallObservation -Mode $UninstallMode -Requests 0
return $version
}
} catch {
@@ -204,12 +210,149 @@ function Assert-LifecycleAgentAbsent {
function Invoke-UninstallAndAssertClean {
foreach ($label in @('uninstall', 'repeated uninstall')) {
- Invoke-Installer -Label $label -Arguments '-Uninstall $true -NonInteractive $true'
+ Invoke-SavedUninstall -Label $label -ExpectFailure $false
Assert-LifecycleAgentAbsent
Write-Host "${label}: independent SCM, binary, state and listener absence confirmed."
}
}
+function Assert-UninstallObservation {
+ param([string]$Mode, [int]$Requests)
+ $observed = Invoke-RestMethod -Uri "$baseUrl/__pulse_lifecycle__/uninstall" -TimeoutSec 2 -ErrorAction Stop
+ if ($observed.mode -cne $Mode -or $observed.requests -ne $Requests -or
+ $observed.authenticated -ne $Requests -or $observed.exactIdentity -ne $Requests) {
+ throw 'Lifecycle peer did not observe the expected single saved-credential/exact-ID request count.'
+ }
+}
+
+function Invoke-SavedUninstall {
+ param([string]$Label, [bool]$ExpectFailure)
+ # No URL, identity, token or TLS arguments and no ambient connection input:
+ # only the real installer's saved connection is available to this child.
+ $start = New-Object System.Diagnostics.ProcessStartInfo
+ $start.FileName = $script:powerShellPath
+ $escapedInstaller = $script:resolvedInstallerPath.Replace("'", "''")
+ $start.Arguments = "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command `"& '$escapedInstaller' -Uninstall `$true -NonInteractive `$true`""
+ $start.UseShellExecute = $false
+ $start.CreateNoWindow = $true
+ $start.RedirectStandardOutput = $true
+ $start.RedirectStandardError = $true
+ foreach ($name in @('PULSE_URL', 'PULSE_TOKEN', 'PULSE_TOKEN_FILE', 'PULSE_AGENT_ID',
+ 'PULSE_HOSTNAME', 'PULSE_CACERT', 'PULSE_SERVER_FINGERPRINT', 'PULSE_INSECURE_SKIP_VERIFY')) {
+ $start.EnvironmentVariables.Remove($name)
+ }
+ $child = New-Object System.Diagnostics.Process
+ $child.StartInfo = $start
+ $started = $false
+ try {
+ $started = $child.Start()
+ if (-not $started) { throw 'Saved removal child did not start.' }
+ $stdout = $child.StandardOutput.ReadToEndAsync()
+ $stderr = $child.StandardError.ReadToEndAsync()
+ if (-not $child.WaitForExit(45000)) {
+ throw 'Saved removal did not return within its bounded unattended deadline.'
+ }
+ $tasks = [System.Threading.Tasks.Task[]]@($stdout, $stderr)
+ if (-not [System.Threading.Tasks.Task]::WaitAll($tasks, 5000)) {
+ throw 'Saved removal output did not close; result remains unverified.'
+ }
+ $output = $stdout.Result + $stderr.Result
+ if ($output.Contains('lifecycle-private-response-must-not-appear') -or
+ $output.Contains('windows-lifecycle-fixture-not-a-secret')) {
+ throw 'Saved removal exposed credential or private-response fixture content.'
+ }
+ $expectedExit = 0
+ if ($ExpectFailure) { $expectedExit = 1 }
+ if ($child.ExitCode -ne $expectedExit) {
+ throw "$Label returned exit $($child.ExitCode); expected $expectedExit."
+ }
+ if ($ExpectFailure -and ($output.Contains('Uninstallation complete.') -or
+ -not $output.Contains('binary, saved identity, credentials and logs have been retained'))) {
+ throw 'Unconfirmed removal lost its truthful retained-state diagnostic.'
+ }
+ Write-Host $output.Trim()
+ } finally {
+ if ($started -and -not $child.HasExited) {
+ # Only this owned child is terminated, never a selected agent PID.
+ $child.Kill()
+ if (-not $child.WaitForExit(5000)) {
+ throw 'Owned removal child cleanup is unconfirmed.'
+ }
+ }
+ $child.Dispose()
+ }
+}
+
+function Get-LifecycleRecoverySnapshot {
+ foreach ($path in @("$env:ProgramFiles\Pulse\pulse-agent.exe", "$stateDir\token", "$stateDir\connection.env", $logFile)) {
+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
+ throw 'Installed recovery fixture is incomplete.'
+ }
+ }
+ $files = @(Get-ChildItem -LiteralPath $stateDir -File -Recurse -Force -ErrorAction Stop)
+ $files += Get-Item -LiteralPath "$env:ProgramFiles\Pulse\pulse-agent.exe" -ErrorAction Stop
+ $snapshot = @{}
+ foreach ($file in $files) {
+ $snapshot[$file.FullName] = @{
+ Hash = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256 -ErrorAction Stop).Hash
+ Acl = (Get-Acl -LiteralPath $file.FullName -ErrorAction Stop).Sddl
+ }
+ }
+ return @{ Files = $snapshot; StateAcl = (Get-Acl -LiteralPath $stateDir -ErrorAction Stop).Sddl }
+}
+
+function Assert-LifecycleRecoveryRetained {
+ param($Before)
+ $service = Get-LifecycleService
+ if ($null -ne $service) {
+ $service.Dispose()
+ throw 'Unconfirmed removal did not independently establish SCM absence.'
+ }
+ $listeners = @(Get-NetTCPConnection -ErrorAction Stop | Where-Object {
+ $_.LocalPort -eq 9191 -and $_.State -eq 'Listen'
+ })
+ if ($listeners.Count -ne 0) { throw 'Agent listener remains after unconfirmed removal.' }
+ $after = Get-LifecycleRecoverySnapshot
+ if ($after.StateAcl -cne $Before.StateAcl -or $after.Files.Count -ne $Before.Files.Count) {
+ throw 'Unconfirmed removal changed recovery files or directory access.'
+ }
+ foreach ($path in $Before.Files.Keys) {
+ if (-not $after.Files.ContainsKey($path) -or
+ $after.Files[$path].Hash -cne $Before.Files[$path].Hash -or
+ $after.Files[$path].Acl -cne $Before.Files[$path].Acl) {
+ throw 'Unconfirmed removal erased or changed installed recovery bytes or file access.'
+ }
+ }
+}
+
+function Invoke-SavedRemovalAcceptance {
+ # Quiesce the owned fixture before taking byte/ACL witnesses, so the
+ # agent's legitimate final log writes cannot look like erased evidence.
+ $service = Get-LifecycleService
+ if ($null -eq $service) { throw 'Installed removal fixture service is missing.' }
+ try {
+ $service.Stop()
+ $service.WaitForStatus([System.ServiceProcess.ServiceControllerStatus]::Stopped,
+ [TimeSpan]::FromSeconds(30))
+ $service.Refresh()
+ if ($service.Status -ne 'Stopped') { throw 'Fixture service is not confirmed stopped.' }
+ } finally {
+ $service.Dispose()
+ }
+ $before = Get-LifecycleRecoverySnapshot
+ foreach ($mode in @('http-503', 'wrong-id', 'string-success', 'missing-id')) {
+ Start-LifecycleServer -AgentPath $script:resolvedAgentV2 -UninstallMode $mode | Out-Null
+ Invoke-SavedUninstall -Label $mode -ExpectFailure $true
+ Assert-UninstallObservation -Mode $mode -Requests 1
+ Assert-LifecycleRecoveryRetained -Before $before
+ Write-Host "PASS saved removal ${mode}: one authenticated exact-ID POST; SCM/listener absent; every recovery byte and ACL retained."
+ }
+ Start-LifecycleServer -AgentPath $script:resolvedAgentV2 -UninstallMode confirm | Out-Null
+ Invoke-UninstallAndAssertClean
+ Assert-UninstallObservation -Mode confirm -Requests 1
+ Write-Host 'PASS saved removal confirmation and repeat: one authenticated exact-ID POST total; independent cleanup after both attempts.'
+}
+
Assert-Administrator
if (-not $ConfirmLifecycleMutation) {
throw 'Pass -ConfirmLifecycleMutation to acknowledge service installation, process termination, and uninstall on this dedicated Windows runner.'
@@ -231,7 +374,7 @@ try {
$restoreAutoUpdateAtExit = $true
$versionV2 = Start-LifecycleServer -AgentPath $resolvedAgentV2
Assert-AgentRuntime -ExpectedVersion $versionV2 | Out-Null
- Invoke-UninstallAndAssertClean
+ Invoke-SavedRemovalAcceptance
Write-Host 'Post-reboot persistence and uninstall proof passed.' -ForegroundColor Green
return
}
@@ -245,11 +388,11 @@ try {
$versionV1 = Start-LifecycleServer -AgentPath $resolvedAgentV1
Invoke-Installer -Label 'preflight' -Arguments "-Url '$baseUrl' -PreflightOnly `$true -NonInteractive `$true"
- Invoke-Installer -Label 'install' -Arguments "-Url '$baseUrl' -AgentId 'windows-lifecycle-agent' -Hostname 'windows-lifecycle-agent' -EnableHost `$true -EnableDocker `$false -EnableKubernetes `$false -EnableProxmox `$false -EnableCommands `$false -NonInteractive `$true"
+ Invoke-Installer -Label 'install' -Arguments "-Url '$baseUrl' -Token 'windows-lifecycle-fixture-not-a-secret' -AgentId 'windows-lifecycle-agent' -Hostname 'windows-lifecycle-agent' -EnableHost `$true -EnableDocker `$false -EnableKubernetes `$false -EnableProxmox `$false -EnableCommands `$false -NonInteractive `$true"
Assert-AgentRuntime -ExpectedVersion $versionV1 | Out-Null
$versionV2 = Start-LifecycleServer -AgentPath $resolvedAgentV2
- Invoke-Installer -Label 'update' -Arguments "-Url '$baseUrl' -AgentId 'windows-lifecycle-agent' -Hostname 'windows-lifecycle-agent' -EnableHost `$true -EnableDocker `$false -EnableKubernetes `$false -EnableProxmox `$false -EnableCommands `$false -NonInteractive `$true"
+ Invoke-Installer -Label 'update' -Arguments "-Url '$baseUrl' -Token 'windows-lifecycle-fixture-not-a-secret' -AgentId 'windows-lifecycle-agent' -Hostname 'windows-lifecycle-agent' -EnableHost `$true -EnableDocker `$false -EnableKubernetes `$false -EnableProxmox `$false -EnableCommands `$false -NonInteractive `$true"
Assert-AgentRuntime -ExpectedVersion $versionV2 | Out-Null
Assert-CrashRecovery -ExpectedVersion $versionV2
@@ -265,7 +408,7 @@ try {
Restart-Service $serviceName -Force
Assert-AgentRuntime -ExpectedVersion $versionV2 | Out-Null
- Invoke-UninstallAndAssertClean
+ Invoke-SavedRemovalAcceptance
Write-Host 'Full Windows service lifecycle proof passed.' -ForegroundColor Green
} finally {
try {
diff --git a/scripts/installtests/windows_lifecycle_observation_controls.ps1 b/scripts/installtests/windows_lifecycle_observation_controls.ps1
index d6ed0dc85f..0521f40b9d 100644
--- a/scripts/installtests/windows_lifecycle_observation_controls.ps1
+++ b/scripts/installtests/windows_lifecycle_observation_controls.ps1
@@ -47,9 +47,9 @@ function Get-NetTCPConnection {
return @([PSCustomObject]@{ LocalPort = 80; State = 'Listen' },
[PSCustomObject]@{ LocalPort = 9191; State = 'Established' })
}
-function Invoke-Installer {
- param([string]$Arguments, [string]$Label)
- if ($Arguments -ne '-Uninstall $true -NonInteractive $true') { throw 'Unexpected installer arguments' }
+function Invoke-SavedUninstall {
+ param([string]$Label, [bool]$ExpectFailure)
+ if ($ExpectFailure) { throw 'Unexpected failure expectation in clean removal' }
$script:labels.Add($Label)
}
$scenarios = @('absent', 'present', 'read-denied', 'wrong-error-id', 'wrong-category',
diff --git a/scripts/installtests/windows_native_acceptance_test.go b/scripts/installtests/windows_native_acceptance_test.go
index e4fd926e01..edfa7c1ddb 100644
--- a/scripts/installtests/windows_native_acceptance_test.go
+++ b/scripts/installtests/windows_native_acceptance_test.go
@@ -25,7 +25,7 @@ func windowsNativeAcceptanceContract(harness string, steps []nativeWindowsExitSt
`if (-not $script:serverProcess.WaitForExit(5000)) {`,
`$listeners = @(Get-NetTCPConnection -ErrorAction Stop | Where-Object {`,
`foreach ($label in @('uninstall', 'repeated uninstall')) {`,
- `Invoke-Installer -Label $label -Arguments '-Uninstall $true -NonInteractive $true'`,
+ `Invoke-SavedUninstall -Label $label -ExpectFailure $false`,
`Assert-LifecycleAgentAbsent`,
} {
if !strings.Contains(harness, needle) {
diff --git a/scripts/installtests/windows_saved_removal_controls.ps1 b/scripts/installtests/windows_saved_removal_controls.ps1
new file mode 100644
index 0000000000..501c11d1cc
--- /dev/null
+++ b/scripts/installtests/windows_saved_removal_controls.ps1
@@ -0,0 +1,77 @@
+param(
+ [Parameter(Mandatory = $true)][string]$HarnessPath,
+ [Parameter(Mandatory = $true)][string]$InstallerPath,
+ [Parameter(Mandatory = $true)][string]$TempDir
+)
+$ErrorActionPreference = 'Stop'
+$powerShellPath = (Get-Process -Id $PID).Path
+foreach ($source in @(
+ @{ Path = $InstallerPath; Name = 'Show-Error' },
+ @{ Path = $HarnessPath; Name = 'Invoke-SavedUninstall' }
+)) {
+ $errors = $null
+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($source.Path, [ref]$null, [ref]$errors)
+ if ($errors.Count) { throw 'Production source did not parse.' }
+ $name = $source.Name
+ $functions = @($ast.FindAll({ param($node)
+ $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq $name
+ }, $true))
+ if ($functions.Count -ne 1) { throw "Expected one production function: $name" }
+ Invoke-Expression $functions[0].Extent.Text
+}
+
+# Observe the real error function without opening any desktop UI. An attempted
+# desktop assembly load is counted then refused by this private control.
+function Add-Type {
+ [CmdletBinding()]
+ param([string]$AssemblyName)
+ $script:desktopAttempts++
+ throw 'Desktop UI disabled by this no-mutation control.'
+}
+foreach ($NonInteractive in @($true, $false)) {
+ $script:desktopAttempts = 0
+ Show-Error 'Controlled installer failure'
+ $expected = 1
+ if ($NonInteractive) { $expected = 0 }
+ if ($script:desktopAttempts -ne $expected) { throw 'NonInteractive error attempted desktop UI, or interactive behaviour changed.' }
+}
+Write-Output 'PASS real installer error function: unattended returns without desktop; interactive behaviour retained'
+
+$names = @('PULSE_URL', 'PULSE_TOKEN', 'PULSE_TOKEN_FILE', 'PULSE_AGENT_ID',
+ 'PULSE_HOSTNAME', 'PULSE_CACERT', 'PULSE_SERVER_FINGERPRINT', 'PULSE_INSECURE_SKIP_VERIFY')
+$before = @{}
+$childInputCheck = ''
+foreach ($name in $names) {
+ $before[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
+ [Environment]::SetEnvironmentVariable($name, 'ambient-fixture-must-not-be-inherited', 'Process')
+ $childInputCheck += "if (-not [string]::IsNullOrEmpty(`$env:$name)) { throw 'Ambient input inherited' }; "
+}
+$resolvedInstallerPath = Join-Path $TempDir "saved removal ' child.ps1"
+$diagnostic = 'The binary, saved identity, credentials and logs have been retained.'
+$controls = @(
+ @{ Name = 'success'; Body = "Write-Host 'Uninstallation complete.'; exit 0"; Failure = $false; Accepted = $true },
+ @{ Name = 'refusal'; Body = "Write-Host '$diagnostic'; exit 1"; Failure = $true; Accepted = $true },
+ @{ Name = 'wrong-exit'; Body = "Write-Host '$diagnostic'; exit 0"; Failure = $true; Accepted = $false },
+ @{ Name = 'unexpected-error'; Body = "Write-Host '$diagnostic'; exit 1"; Failure = $false; Accepted = $false },
+ @{ Name = 'missing-diagnostic'; Body = 'exit 1'; Failure = $true; Accepted = $false },
+ @{ Name = 'false-completion'; Body = "Write-Host '$diagnostic Uninstallation complete.'; exit 1"; Failure = $true; Accepted = $false },
+ @{ Name = 'private-response'; Body = "Write-Host '$diagnostic lifecycle-private-response-must-not-appear'; exit 1"; Failure = $true; Accepted = $false },
+ @{ Name = 'credential'; Body = "Write-Host '$diagnostic windows-lifecycle-fixture-not-a-secret'; exit 1"; Failure = $true; Accepted = $false }
+)
+try {
+ foreach ($control in $controls) {
+ Set-Content -LiteralPath $resolvedInstallerPath -Value ($childInputCheck + $control.Body) -Encoding UTF8
+ $failure = $null
+ try { Invoke-SavedUninstall -Label $control.Name -ExpectFailure $control.Failure } catch { $failure = $_ }
+ if (($null -eq $failure) -ne $control.Accepted) { throw "Saved removal child verdict mismatch: $($control.Name)" }
+ foreach ($name in $names) {
+ if ([Environment]::GetEnvironmentVariable($name, 'Process') -cne 'ambient-fixture-must-not-be-inherited') {
+ throw 'Child environment isolation changed the parent environment.'
+ }
+ }
+ Write-Output "PASS saved removal child $($control.Name): exit, diagnostic, private-output and ambient-input controls"
+ }
+} finally {
+ foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $before[$name], 'Process') }
+}
+Write-Output 'PASS all 10 saved removal controls; no actual SCM, install, deletion or provider request'
diff --git a/scripts/installtests/windows_saved_removal_test.go b/scripts/installtests/windows_saved_removal_test.go
new file mode 100644
index 0000000000..7cb1030561
--- /dev/null
+++ b/scripts/installtests/windows_saved_removal_test.go
@@ -0,0 +1,149 @@
+package installtests
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+func nonInteractiveErrorContract(script string) error {
+ start := strings.Index(script, "function Show-Error {")
+ end := strings.Index(script, "function Write-InstallerEvent {")
+ if start < 0 || end <= start {
+ return fmt.Errorf("missing complete installer error boundary")
+ }
+ function := script[start:end]
+ write := strings.Index(function, "Write-Host $Message")
+ guard := strings.Index(function, "if ($NonInteractive) { return }")
+ desktop := strings.Index(function, "Add-Type -AssemblyName System.Windows.Forms")
+ if write < 0 || guard <= write || desktop <= guard || !strings.Contains(function, "MessageBox]::Show($Message") {
+ return fmt.Errorf("unattended error must print and return before optional desktop UI")
+ }
+ return nil
+}
+
+func TestInstallPS1NonInteractiveErrorsKeepAnUnattendedExit(t *testing.T) {
+ content, err := os.ReadFile(repoFile("scripts", "install.ps1"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := nonInteractiveErrorContract(string(content)); err != nil {
+ t.Fatal(err)
+ }
+ for _, gate := range []string{"Write-Host $Message", "if ($NonInteractive) { return }", "MessageBox]::Show($Message"} {
+ if err := nonInteractiveErrorContract(strings.Replace(string(content), gate, "", 1)); err == nil {
+ t.Fatalf("accepted removed noninteractive/interactive error boundary: %s", gate)
+ }
+ }
+ if path := os.Getenv("PULSE_WINDOWS_ERROR_PARENT"); path != "" {
+ parent, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if nonInteractiveErrorContract(string(parent)) == nil {
+ t.Fatal("accepted actual parent with unconditional modal error")
+ }
+ t.Log("rejected actual parent error function with unconditional desktop UI")
+ }
+}
+
+func savedRemovalAcceptanceContract(script string) error {
+ script = strings.ReplaceAll(script, "\r\n", "\n")
+ for _, gate := range []string{
+ `Invoke-SavedUninstall -Label $label -ExpectFailure $false`,
+ `$start.EnvironmentVariables.Remove($name)`,
+ `if (-not $child.WaitForExit(45000))`,
+ `[System.Threading.Tasks.Task]::WaitAll($tasks, 5000)`,
+ `$child.ExitCode -ne $expectedExit`,
+ `$child.Kill()`, `$child.WaitForExit(5000)`, `$child.Dispose()`,
+ `$output.Contains('lifecycle-private-response-must-not-appear')`,
+ `$output.Contains('windows-lifecycle-fixture-not-a-secret')`,
+ `$after.Files[$path].Hash -cne $Before.Files[$path].Hash`,
+ `$after.Files[$path].Acl -cne $Before.Files[$path].Acl`,
+ `$after.StateAcl -cne $Before.StateAcl`,
+ `$after.Files.Count -ne $Before.Files.Count`,
+ `foreach ($mode in @('http-503', 'wrong-id', 'string-success', 'missing-id'))`,
+ `Invoke-SavedUninstall -Label $mode -ExpectFailure $true`,
+ `Assert-UninstallObservation -Mode $mode -Requests 1`,
+ `Assert-LifecycleRecoveryRetained -Before $before`,
+ `Assert-UninstallObservation -Mode confirm -Requests 1`,
+ `$observed.authenticated -ne $Requests`, `$observed.exactIdentity -ne $Requests`,
+ } {
+ if !strings.Contains(script, gate) {
+ return fmt.Errorf("missing installed saved-removal proof boundary %q", gate)
+ }
+ }
+ if strings.Count(script, "\n Invoke-SavedRemovalAcceptance\n") != 1 ||
+ strings.Count(script, "\n Invoke-SavedRemovalAcceptance\n") != 1 {
+ return fmt.Errorf("both full and post-reboot paths must run saved-removal acceptance")
+ }
+ // Do not allow a supplied connection or credential to substitute for saved
+ // state. This is the actual bounded child command, not a copied recipe.
+ start := strings.Index(script, "function Invoke-SavedUninstall {")
+ end := strings.Index(script, "function Get-LifecycleRecoverySnapshot {")
+ if start < 0 || end <= start {
+ return fmt.Errorf("saved-only invoker missing")
+ }
+ invoker := script[start:end]
+ for _, name := range []string{"PULSE_URL", "PULSE_TOKEN", "PULSE_TOKEN_FILE", "PULSE_AGENT_ID", "PULSE_HOSTNAME", "PULSE_CACERT", "PULSE_SERVER_FINGERPRINT", "PULSE_INSECURE_SKIP_VERIFY"} {
+ if !strings.Contains(invoker, "'"+name+"'") {
+ return fmt.Errorf("ambient %s not isolated", name)
+ }
+ }
+ for _, line := range strings.Split(invoker, "\n") {
+ if strings.Contains(line, "$start.Arguments =") &&
+ (!strings.Contains(line, "-Uninstall `$true -NonInteractive `$true") || strings.Contains(line, "-Token") || strings.Contains(line, "-Url") || strings.Contains(line, "-AgentId")) {
+ return fmt.Errorf("child no longer exercises saved-only removal")
+ }
+ }
+ return nil
+}
+
+func TestWindowsAgentLifecycleSavedRemovalRequiresAdverseAndCleanReadback(t *testing.T) {
+ content, err := os.ReadFile(repoFile("scripts", "installtests", "windows_agent_lifecycle.ps1"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ script := strings.ReplaceAll(string(content), "\r\n", "\n")
+ for _, ending := range []string{"\n", "\r\n"} {
+ if err := savedRemovalAcceptanceContract(strings.ReplaceAll(script, "\n", ending)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, gate := range []string{
+ `$start.EnvironmentVariables.Remove($name)`, `$child.ExitCode -ne $expectedExit`,
+ `$child.WaitForExit(45000)`, `$child.Kill()`, `$child.Dispose()`,
+ `$after.Files[$path].Hash -cne $Before.Files[$path].Hash`,
+ `$after.Files[$path].Acl -cne $Before.Files[$path].Acl`,
+ `Assert-LifecycleRecoveryRetained -Before $before`,
+ `Assert-UninstallObservation -Mode confirm -Requests 1`,
+ `$observed.authenticated -ne $Requests`, `$observed.exactIdentity -ne $Requests`,
+ `'PULSE_TOKEN_FILE'`, `'PULSE_SERVER_FINGERPRINT'`,
+ } {
+ t.Run(gate, func(t *testing.T) {
+ changed := strings.Replace(script, gate, "", 1)
+ if changed == script || savedRemovalAcceptanceContract(changed) == nil {
+ t.Fatal("accepted missing saved-removal boundary")
+ }
+ })
+ }
+}
+
+func TestWindowsAgentLifecycleSavedRemovalInvokerRuntime(t *testing.T) {
+ powerShell := nativeInstallerPowerShell(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, powerShell, "-NoLogo", "-NoProfile", "-NonInteractive", "-File",
+ repoFile("scripts", "installtests", "windows_saved_removal_controls.ps1"),
+ "-HarnessPath", repoFile("scripts", "installtests", "windows_agent_lifecycle.ps1"),
+ "-InstallerPath", repoFile("scripts", "install.ps1"), "-TempDir", t.TempDir())
+ output, err := cmd.CombinedOutput()
+ if err != nil || !strings.Contains(string(output), "PASS all 10 saved removal controls") {
+ t.Fatalf("actual error/saved-removal invoker controls failed: %v\n%s", err, output)
+ }
+ t.Logf("%s", output)
+}
diff --git a/scripts/installtests/windowslifecycleserver/main.go b/scripts/installtests/windowslifecycleserver/main.go
index cf7f2f3901..5014d46ba4 100644
--- a/scripts/installtests/windowslifecycleserver/main.go
+++ b/scripts/installtests/windowslifecycleserver/main.go
@@ -7,10 +7,12 @@ import (
"flag"
"fmt"
"log"
+ "net"
"net/http"
"os"
"path/filepath"
"strings"
+ "sync"
"time"
)
@@ -18,8 +20,16 @@ func main() {
listen := flag.String("listen", "127.0.0.1:17655", "HTTP listen address")
agentBinary := flag.String("agent-binary", "", "Windows agent binary to serve")
version := flag.String("version", "", "Version returned by /api/version")
+ uninstallMode := flag.String("uninstall-mode", "confirm", "Fixed synthetic uninstall response")
flag.Parse()
+ if err := validateListen(*listen); err != nil {
+ log.Fatal(err)
+ }
+ uninstall, err := newUninstallProof(*uninstallMode)
+ if err != nil {
+ log.Fatal(err)
+ }
if strings.TrimSpace(*agentBinary) == "" || strings.TrimSpace(*version) == "" {
log.Fatal("--agent-binary and --version are required")
}
@@ -63,7 +73,8 @@ func main() {
}
_, _ = w.Write(binary)
})
- mux.HandleFunc("/api/agents/agent/uninstall", confirmUninstall)
+ mux.HandleFunc("/api/agents/agent/uninstall", uninstall.confirm)
+ mux.HandleFunc("/__pulse_lifecycle__/uninstall", uninstall.observe)
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true}`))
@@ -83,9 +94,57 @@ func main() {
}
}
-// Match the product's exact-ID acknowledgement; generic success is not proof
-// that an uninstaller removed the identity it requested.
-func confirmUninstall(w http.ResponseWriter, r *http.Request) {
+// Public synthetic data, not a project credential. This peer is loopback-only
+// and accepts exactly the identity and saved token installed by the harness.
+const lifecycleAgentID = "windows-lifecycle-agent"
+const lifecycleToken = "windows-lifecycle-fixture-not-a-secret"
+const privateResponseMarker = "lifecycle-private-response-must-not-appear"
+
+func validateListen(address string) error {
+ host, _, err := net.SplitHostPort(address)
+ ip := net.ParseIP(host)
+ if err != nil || ip == nil || !ip.IsLoopback() {
+ return fmt.Errorf("lifecycle peer requires a literal loopback listen address")
+ }
+ return nil
+}
+
+type uninstallReceipt struct {
+ Mode string `json:"mode"`
+ Requests int `json:"requests"`
+ Authenticated int `json:"authenticated"`
+ ExactIdentity int `json:"exactIdentity"`
+}
+
+type uninstallProof struct {
+ mu sync.Mutex
+ receipt uninstallReceipt
+}
+
+func newUninstallProof(mode string) (*uninstallProof, error) {
+ switch mode {
+ case "confirm", "http-503", "wrong-id", "string-success", "missing-id":
+ return &uninstallProof{receipt: uninstallReceipt{Mode: mode}}, nil
+ default:
+ return nil, fmt.Errorf("unknown lifecycle uninstall mode")
+ }
+}
+
+// Count actual requests, not installer success messages. The observation never
+// returns a token, request body, hostname, binary or private response content.
+func (p *uninstallProof) observe(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ _ = json.NewEncoder(w).Encode(p.receipt)
+}
+
+func (p *uninstallProof) confirm(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
@@ -93,10 +152,40 @@ func confirmUninstall(w http.ResponseWriter, r *http.Request) {
var request struct {
AgentID string `json:"agentId"`
}
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&request); err != nil || request.AgentID == "" {
+ err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&request)
+ authenticated := r.Header.Get("X-API-Token") == lifecycleToken
+ exact := err == nil && request.AgentID == lifecycleAgentID
+ p.mu.Lock()
+ p.receipt.Requests++
+ if authenticated {
+ p.receipt.Authenticated++
+ }
+ if exact {
+ p.receipt.ExactIdentity++
+ }
+ mode := p.receipt.Mode
+ p.mu.Unlock()
+ if !authenticated {
+ http.Error(w, privateResponseMarker, http.StatusUnauthorized)
+ return
+ }
+ if !exact {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "agentId": request.AgentID})
+ w.Header().Set("Cache-Control", "no-store")
+ response := map[string]any{"success": true, "agentId": request.AgentID}
+ switch mode {
+ case "http-503":
+ http.Error(w, privateResponseMarker, http.StatusServiceUnavailable)
+ return
+ case "wrong-id":
+ response["agentId"] = "same-name-other-host"
+ case "string-success":
+ response["success"] = "true"
+ case "missing-id":
+ delete(response, "agentId")
+ }
+ _ = json.NewEncoder(w).Encode(response)
}
diff --git a/scripts/installtests/windowslifecycleserver/main_test.go b/scripts/installtests/windowslifecycleserver/main_test.go
index 0b000bf9cf..20be1843b4 100644
--- a/scripts/installtests/windowslifecycleserver/main_test.go
+++ b/scripts/installtests/windowslifecycleserver/main_test.go
@@ -2,29 +2,173 @@ package main
import (
"encoding/json"
+ "fmt"
+ "io"
"net/http"
"net/http/httptest"
"strings"
+ "sync"
"testing"
)
-func TestUninstallAcknowledgementMatchesExactRequestedIdentity(t *testing.T) {
- for _, id := range []string{"windows-lifecycle-agent", "same-name:other-host"} {
- recorder := httptest.NewRecorder()
- confirmUninstall(recorder, httptest.NewRequest(http.MethodPost, "/api/agents/agent/uninstall", strings.NewReader(`{"agentId":"`+id+`"}`)))
- var response struct {
- Success bool `json:"success"`
- AgentID string `json:"agentId"`
- }
- if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || recorder.Code != http.StatusOK || !response.Success || response.AgentID != id {
- t.Fatalf("wrong acknowledgement: %d %s (%v)", recorder.Code, recorder.Body, err)
- }
+func TestUninstallProofRequiresTheSavedCredentialAndExactIdentity(t *testing.T) {
+ for _, test := range []struct {
+ name, method, token, body string
+ status, requests, auth, exact int
+ }{
+ {"saved", "POST", lifecycleToken, `{"agentId":"windows-lifecycle-agent"}`, 200, 1, 1, 1},
+ {"missing token", "POST", "", `{"agentId":"windows-lifecycle-agent"}`, 401, 1, 0, 1},
+ {"different token", "POST", "wrong", `{"agentId":"windows-lifecycle-agent"}`, 401, 1, 0, 1},
+ {"different identity", "POST", lifecycleToken, `{"agentId":"same-name-other-host"}`, 400, 1, 1, 0},
+ {"different identity case", "POST", lifecycleToken, `{"agentId":"Windows-lifecycle-agent"}`, 400, 1, 1, 0},
+ {"missing identity", "POST", lifecycleToken, `{}`, 400, 1, 1, 0},
+ {"malformed", "POST", lifecycleToken, `{`, 400, 1, 1, 0},
+ {"overbound", "POST", lifecycleToken, `{"agentId":"` + strings.Repeat("x", 17*1024) + `"}`, 400, 1, 1, 0},
+ {"not POST", "GET", lifecycleToken, `{"agentId":"windows-lifecycle-agent"}`, 405, 0, 0, 0},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ peer, err := newUninstallProof("confirm")
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(test.method, "/api/agents/agent/uninstall", strings.NewReader(test.body))
+ req.Header.Set("X-API-Token", test.token)
+ recorder := httptest.NewRecorder()
+ peer.confirm(recorder, req)
+ if recorder.Code != test.status {
+ t.Fatalf("status %d: %s", recorder.Code, recorder.Body)
+ }
+ if test.status == http.StatusOK && recorder.Body.String() != "{\"agentId\":\"windows-lifecycle-agent\",\"success\":true}\n" {
+ t.Fatalf("wrong exact-ID acknowledgement: %s", recorder.Body)
+ }
+ observed := httptest.NewRecorder()
+ peer.observe(observed, httptest.NewRequest(http.MethodGet, "/__pulse_lifecycle__/uninstall", nil))
+ var receipt uninstallReceipt
+ if err := json.Unmarshal(observed.Body.Bytes(), &receipt); err != nil {
+ t.Fatal(err)
+ }
+ want := uninstallReceipt{"confirm", test.requests, test.auth, test.exact}
+ if receipt != want {
+ t.Fatalf("observed %+v, want %+v", receipt, want)
+ }
+ for _, private := range []string{lifecycleToken, lifecycleAgentID, privateResponseMarker} {
+ if strings.Contains(observed.Body.String(), private) {
+ t.Fatal("observation exposed request/response contents")
+ }
+ }
+ })
+ }
+}
+
+func TestUninstallProofServesEveryAdverseResultOverRealHTTP(t *testing.T) {
+ for _, mode := range []string{"confirm", "http-503", "wrong-id", "string-success", "missing-id"} {
+ t.Run(mode, func(t *testing.T) {
+ peer, err := newUninstallProof(mode)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mux := http.NewServeMux()
+ mux.HandleFunc("/api/agents/agent/uninstall", peer.confirm)
+ mux.HandleFunc("/__pulse_lifecycle__/uninstall", peer.observe)
+ server := httptest.NewServer(mux)
+ defer server.Close()
+ req, err := http.NewRequest(http.MethodPost, server.URL+"/api/agents/agent/uninstall", strings.NewReader(`{"agentId":"windows-lifecycle-agent"}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("X-API-Token", lifecycleToken)
+ response, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := io.ReadAll(response.Body)
+ response.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if mode == "http-503" {
+ if response.StatusCode != http.StatusServiceUnavailable || !strings.Contains(string(body), privateResponseMarker) {
+ t.Fatalf("missing deliberate private HTTP failure: %d %s", response.StatusCode, body)
+ }
+ } else {
+ var result map[string]any
+ if err := json.Unmarshal(body, &result); err != nil {
+ t.Fatal(err)
+ }
+ if response.StatusCode != http.StatusOK {
+ t.Fatal(response.StatusCode)
+ }
+ confirmed := result["success"] == true && result["agentId"] == lifecycleAgentID
+ if confirmed != (mode == "confirm") {
+ t.Fatalf("wrong adverse response for %s: %s", mode, body)
+ }
+ if mode == "wrong-id" && result["agentId"] != "same-name-other-host" {
+ t.Fatal("wrong-ID control missing")
+ }
+ if mode == "string-success" && result["success"] != "true" {
+ t.Fatal("string-success control missing")
+ }
+ if mode == "missing-id" && result["agentId"] != nil {
+ t.Fatal("missing-ID control missing")
+ }
+ }
+ observed, err := server.Client().Get(server.URL + "/__pulse_lifecycle__/uninstall")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer observed.Body.Close()
+ var receipt uninstallReceipt
+ if err := json.NewDecoder(observed.Body).Decode(&receipt); err != nil {
+ t.Fatal(err)
+ }
+ if receipt != (uninstallReceipt{mode, 1, 1, 1}) {
+ t.Fatalf("wrong request witness: %+v", receipt)
+ }
+ })
+ }
+}
+
+func TestUninstallProofObservationIsReadOnlyAndRaceSafe(t *testing.T) {
+ peer, err := newUninstallProof("confirm")
+ if err != nil {
+ t.Fatal(err)
}
- for _, test := range []struct{ method, body string }{{http.MethodGet, `{"agentId":"other"}`}, {http.MethodPost, `{}`}, {http.MethodPost, `{`}} {
- recorder := httptest.NewRecorder()
- confirmUninstall(recorder, httptest.NewRequest(test.method, "/api/agents/agent/uninstall", strings.NewReader(test.body)))
- if recorder.Code == http.StatusOK {
- t.Fatalf("invalid request received confirmation: %s %s", test.method, test.body)
+ var workers sync.WaitGroup
+ for i := 0; i < 25; i++ {
+ workers.Add(1)
+ go func() {
+ defer workers.Done()
+ req := httptest.NewRequest(http.MethodPost, "/api/agents/agent/uninstall", strings.NewReader(`{"agentId":"windows-lifecycle-agent"}`))
+ req.Header.Set("X-API-Token", lifecycleToken)
+ peer.confirm(httptest.NewRecorder(), req)
+ peer.observe(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/__pulse_lifecycle__/uninstall", nil))
+ }()
+ }
+ workers.Wait()
+ recorder := httptest.NewRecorder()
+ peer.observe(recorder, httptest.NewRequest(http.MethodPost, "/__pulse_lifecycle__/uninstall", nil))
+ if recorder.Code != http.StatusMethodNotAllowed {
+ t.Fatal("observation accepted mutation")
+ }
+ if peer.receipt != (uninstallReceipt{"confirm", 25, 25, 25}) {
+ t.Fatalf("lost request observations: %+v", peer.receipt)
+ }
+}
+
+func TestUninstallProofAdmissionIsLoopbackAndClosedModes(t *testing.T) {
+ for _, host := range []string{"127.0.0.1:17655", "[::1]:17655"} {
+ if err := validateListen(host); err != nil {
+ t.Fatal(err)
}
}
+ for _, host := range []string{":17655", "0.0.0.0:17655", "[::]:17655", "192.0.2.1:17655", "localhost:17655", "malformed"} {
+ t.Run(fmt.Sprint(host), func(t *testing.T) {
+ if validateListen(host) == nil {
+ t.Fatal("admitted non-literal/non-loopback fixture listener")
+ }
+ })
+ }
+ if _, err := newUninstallProof("arbitrary"); err == nil {
+ t.Fatal("admitted an unknown result mode")
+ }
}