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.

Retain Windows agent recovery state until unregistration is confirmed

pulse-triage[bot]e3effcb9fef5
diff --git a/docs/UNIFIED_AGENT.md b/docs/UNIFIED_AGENT.md
index d6045c6ea6..cd21a4d714 100644
--- a/docs/UNIFIED_AGENT.md
+++ b/docs/UNIFIED_AGENT.md
@@ -967,9 +967,22 @@ session, or set `$installerFile` to the already inspected private script path:
& $installerFile -Uninstall $true
```
-Windows removes the service first and attempts server unregistration before
-local binary/state cleanup. A failed server notification can still be followed
-by local removal; its completion message does not prove server-side revocation.
+Windows removes the service first, then requires Pulse to confirm removal of
+the **exact saved agent ID** before erasing the binary or local state. It reuses
+the saved credential and TLS settings; it does not select an agent by hostname.
+If the server rejects the request, cannot be reached, or returns an unconfirmed
+result, removal exits unsuccessfully and retains the binary, saved identity,
+credentials and logs. **The service may already be removed; retained files do
+not mean monitoring is still running.**
+
+Keep that recovery material private. Check the original connection and exact
+agent ID on the same Pulse instance before deciding on recovery; do not delete
+the state, generate a new token or bypass TLS to force removal. A missing saved
+URL or agent ID also refuses unregistration. When no saved connection,
+credential or identity remains, repeated local cleanup is allowed, but cannot
+confirm server-side revocation. An older served or prepared Windows script may
+ignore a failed server notification and still erase local state; do not rerun
+uninstall just to test which behaviour it has.
### Remove only the separate Linux action runner
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 7e8a6ac236..8977535063 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -4134,6 +4134,30 @@ rejection; they establish neither receiver delivery nor installed recovery.
## Completion Obligations
+### Windows exact-ID unregistration before local erasure
+
+After independent SCM absence, `scripts/install.ps1` must recover the existing
+connection/credential/identity and confirm one unregistration response with
+Boolean `success: true` and the exact, case-sensitive requested `agentId`.
+A hostname lookup, HTTP success alone, malformed acknowledgement, credential
+read error or failed configured CA must not authorise erasure. A failure exits
+nonzero and retains binary, identity, credentials and logs; the service can
+already be absent. Do not print private HTTP exceptions or create a new token.
+Only state without saved connection, identity or credentials permits local-only
+repeat cleanup, which is not server revocation. Optional-auth servers remain
+supported without inventing a credential.
+
+`TestInstallPS1UninstallRequiresExactServerConfirmationBeforeErasure` binds the
+caller ordering and refusal, and `TestInstallPS1UninstallRegistrationRuntime`
+executes the actual complete branch with confined service/filesystem/request
+controls in the existing native Windows job. Linux skips of PowerShell controls
+are explicit, not runtime acceptance. The native lifecycle server must return
+the product's exact-ID acknowledgement rather than generic success. Shipped
+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.
+
+
`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.
### VM command results describe the guest, not transport success
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index 00a7536107..02e98bcca4 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -3983,6 +3983,30 @@ artifact-selection behaviour.
## Completion Obligations
+### Windows exact-ID unregistration before local erasure
+
+After independent SCM absence, `scripts/install.ps1` must recover the existing
+connection/credential/identity and confirm one unregistration response with
+Boolean `success: true` and the exact, case-sensitive requested `agentId`.
+A hostname lookup, HTTP success alone, malformed acknowledgement, credential
+read error or failed configured CA must not authorise erasure. A failure exits
+nonzero and retains binary, identity, credentials and logs; the service can
+already be absent. Do not print private HTTP exceptions or create a new token.
+Only state without saved connection, identity or credentials permits local-only
+repeat cleanup, which is not server revocation. Optional-auth servers remain
+supported without inventing a credential.
+
+`TestInstallPS1UninstallRequiresExactServerConfirmationBeforeErasure` binds the
+caller ordering and refusal, and `TestInstallPS1UninstallRegistrationRuntime`
+executes the actual complete branch with confined service/filesystem/request
+controls in the existing native Windows job. Linux skips of PowerShell controls
+are explicit, not runtime acceptance. The native lifecycle server must return
+the product's exact-ID acknowledgement rather than generic success. Shipped
+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.
+
+
`scripts/installtests/safe_profile_migration_test.go` covers activation ordering, old-helper replacement, effective-unit failure, restart failure and fixed-target refusal in a disposable shell harness, alongside isolation rendering/admission for 386 and unknown platforms. Actual active-helper forward/reverse migration, protected state/identity and prior-active restoration still require authorized native execution; shell stubs are not that proof.
1. Update this contract when canonical deployment or installer entry points move
diff --git a/frontend-modern/public/docs/UNIFIED_AGENT.md b/frontend-modern/public/docs/UNIFIED_AGENT.md
index d6045c6ea6..cd21a4d714 100644
--- a/frontend-modern/public/docs/UNIFIED_AGENT.md
+++ b/frontend-modern/public/docs/UNIFIED_AGENT.md
@@ -967,9 +967,22 @@ session, or set `$installerFile` to the already inspected private script path:
& $installerFile -Uninstall $true
```
-Windows removes the service first and attempts server unregistration before
-local binary/state cleanup. A failed server notification can still be followed
-by local removal; its completion message does not prove server-side revocation.
+Windows removes the service first, then requires Pulse to confirm removal of
+the **exact saved agent ID** before erasing the binary or local state. It reuses
+the saved credential and TLS settings; it does not select an agent by hostname.
+If the server rejects the request, cannot be reached, or returns an unconfirmed
+result, removal exits unsuccessfully and retains the binary, saved identity,
+credentials and logs. **The service may already be removed; retained files do
+not mean monitoring is still running.**
+
+Keep that recovery material private. Check the original connection and exact
+agent ID on the same Pulse instance before deciding on recovery; do not delete
+the state, generate a new token or bypass TLS to force removal. A missing saved
+URL or agent ID also refuses unregistration. When no saved connection,
+credential or identity remains, repeated local cleanup is allowed, but cannot
+confirm server-side revocation. An older served or prepared Windows script may
+ignore a failed server notification and still erase local state; do not rerun
+uninstall just to test which behaviour it has.
### Remove only the separate Linux action runner
diff --git a/frontend-modern/src/features/docs/__tests__/windowsUninstallGuide.test.ts b/frontend-modern/src/features/docs/__tests__/windowsUninstallGuide.test.ts
new file mode 100644
index 0000000000..5cc4a44286
--- /dev/null
+++ b/frontend-modern/src/features/docs/__tests__/windowsUninstallGuide.test.ts
@@ -0,0 +1,51 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { renderDocMarkdown } from '../docMarkdown';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../..');
+const guide = readFileSync(path.join(root, 'docs/UNIFIED_AGENT.md'), 'utf8');
+
+function uninstallArticle(): HTMLElement {
+ const article = document.createElement('article');
+ article.innerHTML = renderDocMarkdown(guide, 'UNIFIED_AGENT');
+ return article;
+}
+
+describe('shipped Windows removal guidance', () => {
+ it('keeps the served producer equal to the source guide', () => {
+ expect(readFileSync(path.join(root, 'frontend-modern/public/docs/UNIFIED_AGENT.md'), 'utf8')).toBe(guide);
+ });
+
+ it('renders exact-ID confirmation and partial-service recovery without asking for a new token', () => {
+ const article = uninstallArticle();
+ const heading = article.querySelector('#remove-the-whole-agent')!;
+ const parts = [];
+ for (let item = heading.nextElementSibling; item && item.tagName !== 'H3'; item = item.nextElementSibling) {
+ parts.push(item.textContent);
+ }
+ const text = parts.join(' ').replace(/\s+/g, ' ');
+ for (const fact of [
+ 'exact saved agent ID',
+ 'saved credential and TLS settings',
+ 'does not select an agent by hostname',
+ 'retains the binary, saved identity, credentials and logs',
+ 'retained files do not mean monitoring is still running',
+ 'generate a new token or bypass TLS',
+ 'cannot confirm server-side revocation',
+ 'older served or prepared Windows script',
+ 'do not rerun uninstall just to test',
+ ]) expect(text).toContain(fact);
+ const commands = Array.from(article.querySelectorAll('pre code')).map((node) => node.textContent);
+ expect(commands).toContain('& $installerFile -Uninstall $true\n');
+ });
+
+ it('keeps the existing safe-preparation and private-log links inside shipped documentation', () => {
+ const article = uninstallArticle();
+ for (const id of ['windows-powershell-run-as-administrator', 'collect-agent-logs-safely']) {
+ expect(article.querySelector(`a[href="/docs/UNIFIED_AGENT#${id}"]`)).not.toBeNull();
+ expect(article.querySelector(`#${id}`)).not.toBeNull();
+ }
+ });
+});
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 4ffcc71d22..a441611092 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -577,20 +577,9 @@ function Remove-PulseService {
} while ($true)
}
-# --- Uninstall Logic ---
-if ($Uninstall) {
- Write-Host "Uninstalling $AgentName..." -ForegroundColor Cyan
-
- # Refuse remote deregistration and local erasure while runtime state is
- # unknown. On failure keep the identity, token, logs and executable intact.
- try {
- Remove-PulseService
- } catch {
- Show-Error "Cannot uninstall '$AgentName'; binary and agent state have been retained. $_"
- Exit 1
- }
-
- # Try to notify the Pulse server about uninstallation if we have connection details
+function Remove-PulseAgentRegistration {
+ # Recover the existing connection; removal must not require a new token.
+ # Read failures propagate before any local binary or state is erased.
if ([string]::IsNullOrWhiteSpace($Url)) {
$Url = Get-ConnectionStateValue "PULSE_URL"
}
@@ -598,17 +587,38 @@ if ($Uninstall) {
$Token = Get-ConnectionStateValue "PULSE_TOKEN"
}
if ([string]::IsNullOrWhiteSpace($Token)) {
- $savedTokenFile = Get-ConnectionStateValue "PULSE_TOKEN_FILE"
- if (-not [string]::IsNullOrWhiteSpace($savedTokenFile) -and (Test-Path $savedTokenFile)) {
- $Token = (Get-Content -Path $savedTokenFile -Raw).Trim()
+ $savedTokenFile = $TokenFile
+ if ([string]::IsNullOrWhiteSpace($savedTokenFile)) {
+ $savedTokenFile = Get-ConnectionStateValue "PULSE_TOKEN_FILE"
+ }
+ if (-not [string]::IsNullOrWhiteSpace($savedTokenFile)) {
+ $Token = (Get-Content -LiteralPath $savedTokenFile -Raw -ErrorAction Stop).Trim()
+ if ([string]::IsNullOrWhiteSpace($Token)) {
+ throw "The saved credential file is empty."
+ }
}
}
if ([string]::IsNullOrWhiteSpace($AgentId)) {
$AgentId = Get-ConnectionStateValue "PULSE_AGENT_ID"
}
- if ([string]::IsNullOrWhiteSpace($Hostname)) {
- $Hostname = Get-ConnectionStateValue "PULSE_HOSTNAME"
+ if ([string]::IsNullOrWhiteSpace($AgentId) -and (Test-Path -LiteralPath "$StateDir\agent-id")) {
+ $AgentId = (Get-Content -LiteralPath "$StateDir\agent-id" -Raw -ErrorAction Stop).Trim()
}
+
+ if ([string]::IsNullOrWhiteSpace($Url)) {
+ if (-not [string]::IsNullOrWhiteSpace($Token) -or
+ -not [string]::IsNullOrWhiteSpace($AgentId) -or
+ (Test-Path -LiteralPath $ConnectionStatePath) -or (Test-Path -LiteralPath $TokenFilePath)) {
+ throw "The original Pulse URL is missing."
+ }
+ Write-Host "No saved Pulse connection was found; local cleanup cannot confirm server unregistration." -ForegroundColor Yellow
+ return
+ }
+ if ([string]::IsNullOrWhiteSpace($AgentId)) {
+ # A hostname is not an exact identity, especially in mixed fleets.
+ throw "The saved agent ID is missing; do not select another agent by hostname."
+ }
+ $AgentId = $AgentId.Trim()
if (-not $Insecure) {
$Insecure = Parse-Bool (Get-ConnectionStateValue "PULSE_INSECURE_SKIP_VERIFY") $Insecure
}
@@ -621,74 +631,53 @@ if ($Uninstall) {
$customCaCertificate = $null
if (-not [string]::IsNullOrWhiteSpace($CACertPath)) {
- try {
- $customCaCertificate = Load-CustomCaCertificate $CACertPath
- } catch {
- Write-Host "Warning: Failed to load custom CA certificate from $CACertPath during uninstall: $_" -ForegroundColor Yellow
- $customCaCertificate = $null
- }
+ $customCaCertificate = Load-CustomCaCertificate $CACertPath
}
-
- if (-not [string]::IsNullOrWhiteSpace($Url)) {
- # Try to recover agent ID if not provided
- $detectedAgentId = $AgentId
- $stateFile = "$StateDir\agent-id"
- if ([string]::IsNullOrWhiteSpace($detectedAgentId) -and (Test-Path $stateFile)) {
- $detectedAgentId = Get-Content $stateFile -Raw
- if ($detectedAgentId) { $detectedAgentId = $detectedAgentId.Trim() }
+ try {
+ $body = @{ agentId = $AgentId } | ConvertTo-Json
+ $invokeArgs = @{
+ Uri = "$($Url.TrimEnd('/'))/api/agents/agent/uninstall"
+ Method = "Post"
+ Body = $body
+ ContentType = "application/json"
+ TimeoutSec = 5
+ ErrorAction = "Stop"
}
- if ([string]::IsNullOrWhiteSpace($detectedAgentId)) {
- $lookupHostname = $Hostname
- if ([string]::IsNullOrWhiteSpace($lookupHostname)) {
- $lookupHostname = $env:COMPUTERNAME
- }
- if (-not [string]::IsNullOrWhiteSpace($lookupHostname)) {
- try {
- $lookupArgs = @{
- Uri = "$Url/api/agents/agent/lookup?hostname=$([System.Uri]::EscapeDataString($lookupHostname))"
- Method = "Get"
- TimeoutSec = 5
- ErrorAction = "SilentlyContinue"
- }
- if (-not [string]::IsNullOrWhiteSpace($Token)) {
- $lookupArgs.Headers = @{ "X-API-Token" = $Token }
- }
-
- $lookupResult = Invoke-WithOptionalInsecureTls -AllowInsecure $Insecure -CustomCaCertificate $customCaCertificate -Action {
- Invoke-RestMethod @lookupArgs
- }
- if ($lookupResult -and $lookupResult.agent -and -not [string]::IsNullOrWhiteSpace($lookupResult.agent.id)) {
- $detectedAgentId = $lookupResult.agent.id.Trim()
- }
- } catch {
- # Ignore lookup errors during uninstall
- }
- }
+ if (-not [string]::IsNullOrWhiteSpace($Token)) {
+ $invokeArgs.Headers = @{ "X-API-Token" = $Token }
+ }
+ $result = Invoke-WithOptionalInsecureTls -AllowInsecure $Insecure -CustomCaCertificate $customCaCertificate -Action {
+ Invoke-RestMethod @invokeArgs
+ }
+ if ($null -eq $result -or $result.success -isnot [bool] -or $result.success -ne $true -or
+ $result.agentId -isnot [string] -or $result.agentId -cne $AgentId) {
+ throw "Pulse did not confirm removal of the exact agent ID."
}
+ } finally {
+ if ($null -ne $customCaCertificate) { $customCaCertificate.Dispose() }
+ }
+}
- if (-not [string]::IsNullOrWhiteSpace($detectedAgentId)) {
- Write-Host "Notifying Pulse server to unregister agent ID: $detectedAgentId..." -ForegroundColor Gray
- try {
- $body = @{ agentId = $detectedAgentId } | ConvertTo-Json
- $invokeArgs = @{
- Uri = "$Url/api/agents/agent/uninstall"
- Method = "Post"
- Body = $body
- ContentType = "application/json"
- TimeoutSec = 5
- ErrorAction = "SilentlyContinue"
- }
- if (-not [string]::IsNullOrWhiteSpace($Token)) {
- $invokeArgs.Headers = @{ "X-API-Token" = $Token }
- }
+# --- Uninstall Logic ---
+if ($Uninstall) {
+ Write-Host "Uninstalling $AgentName..." -ForegroundColor Cyan
- Invoke-WithOptionalInsecureTls -AllowInsecure $Insecure -CustomCaCertificate $customCaCertificate -Action {
- Invoke-RestMethod @invokeArgs | Out-Null
- }
- } catch {
- # Ignore errors during uninstall
- }
- }
+ # Refuse remote deregistration and local erasure while runtime state is
+ # unknown. On failure keep the identity, token, logs and executable intact.
+ try {
+ Remove-PulseService
+ } catch {
+ Show-Error "Cannot uninstall '$AgentName'; binary and agent state have been retained. $_"
+ Exit 1
+ }
+
+ # Try to notify the Pulse server only after the service is confirmed absent.
+ try {
+ Remove-PulseAgentRegistration
+ } catch {
+ # Do not print an HTTP exception: it can contain private response data.
+ Show-Error "The service was removed, but Pulse server unregistration could not be confirmed. The binary, saved identity, credentials and logs have been retained. Check the saved connection, exact agent ID and TLS settings for the same Pulse instance before deciding how to recover; do not delete this state or generate a new token to force removal."
+ Exit 1
}
try {
diff --git a/scripts/installtests/install_ps1_test.go b/scripts/installtests/install_ps1_test.go
index cbb61e774b..36f73ec028 100644
--- a/scripts/installtests/install_ps1_test.go
+++ b/scripts/installtests/install_ps1_test.go
@@ -310,11 +310,10 @@ func TestInstallPS1AllowsOptionalAuthUninstallWithoutToken(t *testing.T) {
script := string(content)
required := []string{
- `if (-not [string]::IsNullOrWhiteSpace($Url)) {`,
`$invokeArgs = @{`,
`if (-not [string]::IsNullOrWhiteSpace($Token)) {`,
`$invokeArgs.Headers = @{ "X-API-Token" = $Token }`,
- `Invoke-RestMethod @invokeArgs | Out-Null`,
+ `Invoke-RestMethod @invokeArgs`,
}
for _, needle := range required {
if !strings.Contains(script, needle) {
@@ -323,6 +322,85 @@ func TestInstallPS1AllowsOptionalAuthUninstallWithoutToken(t *testing.T) {
}
}
+func windowsUninstallRegistrationContract(script string) error {
+ start := strings.Index(script, "function Remove-PulseAgentRegistration {")
+ end := strings.Index(script, "# --- Uninstall Logic ---")
+ if start < 0 || end <= start {
+ return fmt.Errorf("missing production unregistration boundary")
+ }
+ registration := script[start:end]
+ for _, needle := range []string{
+ `$savedTokenFile = $TokenFile`,
+ `$Token = (Get-Content -LiteralPath $savedTokenFile -Raw -ErrorAction Stop).Trim()`,
+ `$AgentId = (Get-Content -LiteralPath "$StateDir\agent-id" -Raw -ErrorAction Stop).Trim()`,
+ `throw "The original Pulse URL is missing."`,
+ `throw "The saved agent ID is missing; do not select another agent by hostname."`,
+ `$customCaCertificate = Load-CustomCaCertificate $CACertPath`,
+ `$body = @{ agentId = $AgentId } | ConvertTo-Json`,
+ `ErrorAction = "Stop"`,
+ `$result.success -isnot [bool]`,
+ `$result.success -ne $true`,
+ `$result.agentId -isnot [string]`,
+ `$result.agentId -cne $AgentId`,
+ `$customCaCertificate.Dispose()`,
+ } {
+ if !strings.Contains(registration, needle) {
+ return fmt.Errorf("missing exact-ID unregistration boundary %q", needle)
+ }
+ }
+ if strings.Contains(registration, "SilentlyContinue") || strings.Contains(registration, "/lookup?") ||
+ strings.Count(registration, "Invoke-RestMethod @invokeArgs") != 1 {
+ return fmt.Errorf("unregistration can suppress errors, select by hostname or repeat a POST")
+ }
+ branch := script[end:]
+ service := strings.Index(branch, "Remove-PulseService")
+ call := strings.Index(branch, "Remove-PulseAgentRegistration")
+ cleanup := strings.Index(branch, `Remove-Item "$InstallDir\$BinaryName"`)
+ if service < 0 || call <= service || cleanup <= call {
+ return fmt.Errorf("unregistration must follow service absence and precede erasure")
+ }
+ failure := branch[call:cleanup]
+ if !strings.Contains(failure, "} catch {") || !strings.Contains(failure, "Exit 1") ||
+ !strings.Contains(failure, "credentials and logs have been retained") || strings.Contains(failure, "$_") {
+ return fmt.Errorf("unregistration failure must preserve local state and withhold private HTTP errors")
+ }
+ return nil
+}
+
+func TestInstallPS1UninstallRequiresExactServerConfirmationBeforeErasure(t *testing.T) {
+ content, err := os.ReadFile(repoFile("scripts", "install.ps1"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ script := string(content)
+ if err := windowsUninstallRegistrationContract(script); err != nil {
+ t.Fatal(err)
+ }
+ for _, boundary := range []string{
+ `$result.success -isnot [bool]`, `$result.success -ne $true`,
+ `$result.agentId -isnot [string]`, `$result.agentId -cne $AgentId`,
+ `throw "The original Pulse URL is missing."`,
+ `throw "The saved agent ID is missing; do not select another agent by hostname."`,
+ `ErrorAction = "Stop"`, "Remove-PulseAgentRegistration\n",
+ } {
+ t.Run(boundary, func(t *testing.T) {
+ if err := windowsUninstallRegistrationContract(strings.Replace(script, boundary, "", 1)); err == nil {
+ t.Fatal("accepted missing unregistration boundary")
+ }
+ })
+ }
+ if path := os.Getenv("PULSE_WINDOWS_UNREGISTRATION_PARENT"); path != "" {
+ parent, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := windowsUninstallRegistrationContract(string(parent)); err == nil {
+ t.Fatal("accepted the actual parent's ignored unregistration failures")
+ }
+ t.Log("rejected the complete supplied parent installer")
+ }
+}
+
func TestInstallPS1PreservesProxmoxProfileParity(t *testing.T) {
content, err := os.ReadFile(repoFile("scripts", "install.ps1"))
if err != nil {
diff --git a/scripts/installtests/windows_uninstall_registration_controls.ps1 b/scripts/installtests/windows_uninstall_registration_controls.ps1
new file mode 100644
index 0000000000..778552ade3
--- /dev/null
+++ b/scripts/installtests/windows_uninstall_registration_controls.ps1
@@ -0,0 +1,139 @@
+param(
+ [Parameter(Mandatory = $true)][string]$InstallerPath,
+ [Parameter(Mandatory = $true)][string]$Scenario
+)
+
+$ErrorActionPreference = 'Stop'
+$AgentName = 'PulseAgent'
+$BinaryName = 'pulse-agent.exe'
+$InstallDir = 'C:\synthetic-install'
+$StateDir = 'C:\synthetic-state'
+$ConnectionStatePath = "$StateDir\connection.env"
+$TokenFilePath = "$StateDir\token"
+$Uninstall = $true
+$Url = ''
+$Token = ''
+$TokenFile = ''
+$AgentId = ''
+$Insecure = $false
+$CACertPath = ''
+$ServerFingerprint = ''
+$script:secret = 'synthetic-private-token-never-print'
+$script:hasState = $Scenario -ne 'repeated'
+$script:state = @{
+ PULSE_URL = 'https://same-instance.invalid/'
+ PULSE_TOKEN_FILE = $TokenFilePath
+ PULSE_AGENT_ID = 'exact-agent:42'
+ PULSE_SERVER_FINGERPRINT = 'synthetic-saved-fingerprint'
+}
+if ($Scenario -eq 'repeated') { $script:state.Clear() }
+if ($Scenario -eq 'missing-url') { $script:state.PULSE_URL = '' }
+if ($Scenario -in @('agent-id-file', 'missing-id')) { $script:state.PULSE_AGENT_ID = '' }
+if ($Scenario -eq 'optional-auth') { $script:state.PULSE_TOKEN_FILE = '' }
+if ($Scenario -eq 'legacy-inline-token') {
+ $script:state.PULSE_TOKEN_FILE = ''
+ $script:state.PULSE_TOKEN = $script:secret
+}
+if ($Scenario -eq 'explicit-token-file') { $TokenFile = 'C:\explicit-private-token' }
+if ($Scenario -eq 'explicit-identity') {
+ $AgentId = 'explicit-agent:42'
+ $Token = $script:secret
+ $Url = 'https://same-instance.invalid/'
+}
+if ($Scenario -eq 'saved-ca' -or $Scenario -eq 'invalid-ca') { $script:state.PULSE_CACERT = 'C:\synthetic-ca' }
+if ($Scenario -eq 'saved-insecure') { $script:state.PULSE_INSECURE_SKIP_VERIFY = 'true' }
+
+function Event([string]$Name) { [Console]::WriteLine("EVENT $Name") }
+function Remove-PulseService {
+ Event 'service'
+ if ($Scenario -eq 'service-fails') { throw 'controlled service failure' }
+}
+function Show-Error([string]$Message) { [Console]::WriteLine("ERROR $Message") }
+function Get-ConnectionStateValue([string]$Key) { return [string]$script:state[$Key] }
+function Test-Path {
+ param([string]$Path, [string]$LiteralPath)
+ $value = $Path
+ if ($LiteralPath) { $value = $LiteralPath }
+ if ($value -eq "$StateDir\agent-id") { return $Scenario -eq 'agent-id-file' }
+ return $script:hasState
+}
+function Get-Content {
+ [CmdletBinding()]
+ param([string]$LiteralPath, [switch]$Raw)
+ if ($LiteralPath -eq "$StateDir\agent-id") { return "exact-agent:42`r`n" }
+ if ($Scenario -eq 'unreadable-token') { throw $script:secret }
+ if ($Scenario -eq 'empty-token') { return ' ' }
+ $expectedPath = $TokenFilePath
+ if ($Scenario -eq 'explicit-token-file') { $expectedPath = 'C:\explicit-private-token' }
+ if ($LiteralPath -cne $expectedPath) { throw 'wrong credential path' }
+ Event 'credential-read'
+ return $script:secret
+}
+function Load-CustomCaCertificate([string]$Path) {
+ Event 'ca-load'
+ if ($Scenario -eq 'invalid-ca') { throw $script:secret }
+ $certificate = New-Object PSObject
+ $certificate | Add-Member -MemberType ScriptMethod -Name Dispose -Value { Event 'ca-dispose' }
+ return $certificate
+}
+function Invoke-WithOptionalInsecureTls {
+ param([bool]$AllowInsecure, $CustomCaCertificate, [scriptblock]$Action)
+ if ($AllowInsecure -ne ($Scenario -eq 'saved-insecure')) { throw 'changed TLS verification posture' }
+ if ($ServerFingerprint -cne 'synthetic-saved-fingerprint') { throw 'lost saved fingerprint' }
+ if ($Scenario -eq 'saved-ca' -and $null -eq $CustomCaCertificate) { throw 'lost saved CA' }
+ if ($Scenario -eq 'tls-fails') { throw $script:secret }
+ & $Action
+}
+function Invoke-RestMethod {
+ [CmdletBinding()]
+ param([string]$Uri, [string]$Method, [string]$Body, [string]$ContentType, [int]$TimeoutSec, $Headers)
+ Event 'request'
+ if ($Uri -cne 'https://same-instance.invalid/api/agents/agent/uninstall' -or
+ $Method -cne 'Post' -or $ContentType -cne 'application/json' -or $TimeoutSec -ne 5 -or
+ $ErrorActionPreference -ne 'Stop') { throw 'wrong request boundary' }
+ $id = 'exact-agent:42'
+ if ($Scenario -eq 'explicit-identity') { $id = 'explicit-agent:42' }
+ $parsed = $Body | ConvertFrom-Json
+ if ($parsed.agentId -cne $id -or @($parsed.PSObject.Properties).Count -ne 1) { throw 'wrong request identity' }
+ if ($Scenario -eq 'optional-auth') {
+ if ($null -ne $Headers) { throw 'optional authentication gained a header' }
+ } elseif ($Headers['X-API-Token'] -cne $script:secret) { throw 'wrong saved credential' }
+ if ($Scenario -in @('http-401', 'http-403', 'http-500', 'timeout')) { throw $script:secret }
+ switch ($Scenario) {
+ 'wrong-id' { return [pscustomobject]@{ success = $true; agentId = 'other-agent:42' } }
+ 'wrong-case-id' { return [pscustomobject]@{ success = $true; agentId = 'EXACT-agent:42' } }
+ 'false-success' { return [pscustomobject]@{ success = $false; agentId = $id } }
+ 'string-success' { return [pscustomobject]@{ success = 'true'; agentId = $id } }
+ 'missing-id-response' { return [pscustomobject]@{ success = $true } }
+ 'empty-response' { return $null }
+ 'array-response' { return @([pscustomobject]@{ success = $true; agentId = $id }, [pscustomobject]@{ success = $true; agentId = $id }) }
+ default { return [pscustomobject]@{ success = $true; agentId = $id } }
+ }
+}
+function Remove-Item {
+ [CmdletBinding()]
+ param([string]$Path, [switch]$Force, [switch]$Recurse)
+ Event 'erase'
+ if ($Scenario -eq 'cleanup-fails') { throw 'controlled local cleanup failure' }
+}
+
+# Execute the actual complete uninstall branch in this disposable child engine.
+# All OS, credential, filesystem and network operations above are private doubles;
+# production Exit statements, sequencing, catch/cleanup and success stay intact.
+$errors = $null
+$ast = [System.Management.Automation.Language.Parser]::ParseFile($InstallerPath, [ref]$null, [ref]$errors)
+if ($errors.Count) { throw "Installer parse failed: $errors" }
+foreach ($name in @('Parse-Bool', 'Remove-PulseAgentRegistration')) {
+ $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
+}
+$branches = @($ast.FindAll({ param($node)
+ $node -is [System.Management.Automation.Language.IfStatementAst] -and
+ $node.Clauses[0].Item1.Extent.Text -eq '$Uninstall'
+}, $true))
+if ($branches.Count -ne 1) { throw 'Expected one complete production uninstall branch' }
+Invoke-Expression $branches[0].Extent.Text
+throw 'Production uninstall failed to exit'
diff --git a/scripts/installtests/windows_uninstall_registration_test.go b/scripts/installtests/windows_uninstall_registration_test.go
new file mode 100644
index 0000000000..af98dbfae7
--- /dev/null
+++ b/scripts/installtests/windows_uninstall_registration_test.go
@@ -0,0 +1,83 @@
+package installtests
+
+import (
+ "context"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestInstallPS1UninstallRegistrationRuntime(t *testing.T) {
+ powerShell := nativeInstallerPowerShell(t)
+ for _, test := range []struct {
+ name string
+ ok bool
+ requests int
+ credentialRead bool
+ }{
+ {"saved-success", true, 1, true},
+ {"legacy-inline-token", true, 1, false},
+ {"agent-id-file", true, 1, true},
+ {"explicit-identity", true, 1, false},
+ {"explicit-token-file", true, 1, true},
+ {"optional-auth", true, 1, false},
+ {"repeated", true, 0, false},
+ {"saved-ca", true, 1, true},
+ {"saved-insecure", true, 1, true},
+ {"service-fails", false, 0, false},
+ {"missing-url", false, 0, true},
+ {"missing-id", false, 0, true},
+ {"unreadable-token", false, 0, false},
+ {"empty-token", false, 0, false},
+ {"invalid-ca", false, 0, true},
+ {"tls-fails", false, 0, true},
+ {"http-401", false, 1, true},
+ {"http-403", false, 1, true},
+ {"http-500", false, 1, true},
+ {"timeout", false, 1, true},
+ {"wrong-id", false, 1, true},
+ {"wrong-case-id", false, 1, true},
+ {"false-success", false, 1, true},
+ {"string-success", false, 1, true},
+ {"missing-id-response", false, 1, true},
+ {"empty-response", false, 1, true},
+ {"array-response", false, 1, true},
+ {"cleanup-fails", false, 1, true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, powerShell, "-NoLogo", "-NoProfile", "-NonInteractive", "-File",
+ repoFile("scripts", "installtests", "windows_uninstall_registration_controls.ps1"),
+ "-InstallerPath", repoFile("scripts", "install.ps1"), "-Scenario", test.name)
+ output, err := cmd.CombinedOutput()
+ text := string(output)
+ if (err == nil) != test.ok || (strings.Contains(text, "Uninstallation complete.")) != test.ok {
+ t.Fatalf("unexpected complete-branch outcome: %v\n%s", err, text)
+ }
+ if !test.ok {
+ if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
+ t.Fatalf("failure did not retain exit 1: %v\n%s", err, text)
+ }
+ }
+ if strings.Count(text, "EVENT request") != test.requests || strings.Count(text, "EVENT service") != 1 ||
+ strings.Contains(text, "EVENT credential-read") != test.credentialRead {
+ t.Fatalf("wrong service, identity/credential or one-POST boundary: %s", text)
+ }
+ if strings.Contains(text, "synthetic-private-token-never-print") {
+ t.Fatal("private credential or remote exception was printed")
+ }
+ if !test.ok && test.name != "cleanup-fails" && strings.Contains(text, "EVENT erase") {
+ t.Fatalf("erased recovery material after a refusal: %s", text)
+ }
+ if test.ok && test.name != "repeated" && strings.Count(text, "EVENT erase") != 2 {
+ t.Fatalf("confirmed removal did not clean binary and state: %s", text)
+ }
+ if test.name == "saved-ca" && strings.Count(text, "EVENT ca-dispose") != 1 {
+ t.Fatalf("saved CA was not disposed: %s", text)
+ }
+ t.Logf("%s: expected complete-branch outcome, one-POST/retention/secret controls pass", test.name)
+ })
+ }
+}
diff --git a/scripts/installtests/windowslifecycleserver/main.go b/scripts/installtests/windowslifecycleserver/main.go
index e8c4510a55..cf7f2f3901 100644
--- a/scripts/installtests/windowslifecycleserver/main.go
+++ b/scripts/installtests/windowslifecycleserver/main.go
@@ -63,6 +63,7 @@ func main() {
}
_, _ = w.Write(binary)
})
+ mux.HandleFunc("/api/agents/agent/uninstall", confirmUninstall)
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true}`))
@@ -81,3 +82,21 @@ func main() {
log.Fatal(err)
}
}
+
+// 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) {
+ if r.Method != http.MethodPost {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ return
+ }
+ var request struct {
+ AgentID string `json:"agentId"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&request); err != nil || request.AgentID == "" {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "agentId": request.AgentID})
+}
diff --git a/scripts/installtests/windowslifecycleserver/main_test.go b/scripts/installtests/windowslifecycleserver/main_test.go
new file mode 100644
index 0000000000..0b000bf9cf
--- /dev/null
+++ b/scripts/installtests/windowslifecycleserver/main_test.go
@@ -0,0 +1,30 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "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)
+ }
+ }
+ 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)
+ }
+ }
+}
diff --git a/scripts/tests/test_agent_uninstall_docs.py b/scripts/tests/test_agent_uninstall_docs.py
index 3f2058b502..100b97930f 100644
--- a/scripts/tests/test_agent_uninstall_docs.py
+++ b/scripts/tests/test_agent_uninstall_docs.py
@@ -136,7 +136,9 @@ class AgentUninstallDocsTest(unittest.TestCase):
def test_partial_failures_platform_differences_and_unknowns_remain_explicit(self):
for fact in ("Windows removes the service first", "failed server notification",
- "completion message does not prove server-side revocation",
+ "exact saved agent ID", "retains the binary, saved identity, credentials and logs",
+ "retained files do not mean monitoring is still running",
+ "cannot confirm server-side revocation",
"failure can leave a partial result", "before a later runner-revocation failure",
"host's service manager", "same-instance", "Settings → Infrastructure",
"before deciding on another action", "Retained-state warnings",
@@ -144,9 +146,12 @@ class AgentUninstallDocsTest(unittest.TestCase):
self.assertIn(fact, self.words)
source = (ROOT / "scripts/install.ps1").read_text().split(
"# --- Uninstall Logic ---", 1)[1].split("# --- Validation", 1)[0]
- self.assertLess(source.index("Remove-PulseService"), source.index('Uri = "$Url/api/agents/agent/uninstall"'))
- self.assertLess(source.index('# Ignore errors during uninstall', source.index('Uri = "$Url/api/agents/agent/uninstall"')),
+ self.assertLess(source.index("Remove-PulseService"), source.index('Remove-PulseAgentRegistration'))
+ self.assertLess(source.index('Remove-PulseAgentRegistration'),
source.index('Remove-Item $StateDir -Recurse -Force'))
+ refusal = source.split('Remove-PulseAgentRegistration', 1)[1].split('Remove-Item', 1)[0]
+ self.assertIn('Exit 1', refusal)
+ self.assertIn('credentials and logs have been retained', refusal)
commands = re.findall(r"```powershell\n(.*?)```", self.help, re.DOTALL)
self.assertEqual(commands, ['& $installerFile -Uninstall $true\n'])
self.assertIn('[bool]$Uninstall = $false', (ROOT / "scripts/install.ps1").read_text())