//go:build windows package plugin import ( "archive/zip" "crypto/sha256" "encoding/hex" "errors" "fmt" "os" "path/filepath" "slices" "strings" "testing" "time" "golang.org/x/sys/windows" ) func TestRenamePackageDirWithOpenWindowsHandle(t *testing.T) { root := t.TempDir() stageDir := filepath.Join(root, "stage") finalDir := filepath.Join(root, "final") if err := os.Mkdir(stageDir, 0o755); err != nil { t.Fatal(err) } payload := filepath.Join(stageDir, "sidecar.exe") if err := os.WriteFile(payload, []byte("sidecar contents"), 0o644); err != nil { t.Fatal(err) } path, err := windows.UTF16PtrFromString(payload) if err != nil { t.Fatal(err) } handle, err := windows.CreateFile(path, windows.GENERIC_READ, windows.FILE_SHARE_READ, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0) if err != nil { t.Fatal(err) } oldSleep := sleepRetryFn retries := 0 closed := false t.Cleanup(func() { sleepRetryFn = oldSleep if !closed { if err := windows.CloseHandle(handle); err != nil { t.Error(err) } } }) sleepRetryFn = func(delay time.Duration) { retries++ if retries == 1 { if err := windows.CloseHandle(handle); err != nil { t.Fatal(err) } closed = true } oldSleep(delay) } if err := renamePackageDir(stageDir, finalDir); err != nil { t.Fatal(err) } if retries < 1 { t.Fatal("rename did not retry while the Windows handle was open") } assertRenameTestContents(t, filepath.Join(finalDir, "sidecar.exe"), "sidecar contents") if _, err := os.Stat(stageDir); !errors.Is(err, os.ErrNotExist) { t.Errorf("stage directory after rename: %v, want absent", err) } } func TestInstallArchiveRenameRetry(t *testing.T) { const ( id = "test.rename" version = "1.0.0" entry = "bin/sidecar.exe" ) opts := PackageInstallOptions{HostVersion: "0.3.0", AllowUnsigned: true} for _, tc := range []struct { name string existingVersion string activationLockRetries int wantErr error wantAttempts int }{ {name: "retry then activate", activationLockRetries: 2, wantAttempts: 3}, {name: "first install exhausts retries", wantErr: windows.ERROR_ACCESS_DENIED, wantAttempts: 16}, {name: "same version rolls back", existingVersion: version, wantErr: windows.ERROR_ACCESS_DENIED, wantAttempts: 16}, {name: "other version stays installed", existingVersion: "0.9.0", wantErr: windows.ERROR_ACCESS_DENIED, wantAttempts: 16}, {name: "missing path fails immediately", wantErr: os.ErrNotExist, wantAttempts: 1}, {name: "successful swap removes backup", existingVersion: version, wantAttempts: 1}, } { t.Run(tc.name, func(t *testing.T) { layout := NewPluginsLayout(t.TempDir()) parent := filepath.Join(layout.PkgsDir(), id) finalDir := filepath.Join(parent, version) if tc.existingVersion != "" { archive := packRenameTestPlugin(t, id, tc.existingVersion, entry, "old sidecar") if _, err := InstallArchive(layout, archive, opts); err != nil { t.Fatalf("install existing version: %v", err) } } archive := packRenameTestPlugin(t, id, version, entry, "new sidecar") oldRename, oldRemove, oldSleep := renameDirFn, removeDirFn, sleepRetryFn t.Cleanup(func() { renameDirFn, removeDirFn, sleepRetryFn = oldRename, oldRemove, oldSleep }) var sleeps []time.Duration sleepRetryFn = func(delay time.Duration) { sleeps = append(sleeps, delay) } var activationAttempts, backupAttempts, rollbackAttempts, cleanupAttempts int renameDirFn = func(oldPath, newPath string) error { switch { case filepath.Dir(oldPath) == layout.TmpDir() && newPath == finalDir: activationAttempts++ if tc.wantErr != nil { return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: tc.wantErr} } if activationAttempts <= tc.activationLockRetries { return windows.ERROR_ACCESS_DENIED } case oldPath == finalDir && strings.HasPrefix(newPath, finalDir+".prev-"): backupAttempts++ if backupAttempts == 1 { return windows.ERROR_SHARING_VIOLATION } case strings.HasPrefix(oldPath, finalDir+".prev-") && newPath == finalDir: rollbackAttempts++ if rollbackAttempts == 1 { return windows.ERROR_LOCK_VIOLATION } default: t.Fatalf("unexpected rename from %q to %q", oldPath, newPath) } return oldRename(oldPath, newPath) } removeDirFn = func(path string) error { cleanupAttempts++ if tc.wantErr != nil && filepath.Dir(path) != layout.TmpDir() || tc.wantErr == nil && !strings.HasPrefix(path, finalDir+".prev-") { t.Fatalf("unexpected cleanup of %q", path) } if cleanupAttempts == 1 { return &os.PathError{Op: "remove", Path: path, Err: windows.ERROR_SHARING_VIOLATION} } return oldRemove(path) } installed, err := InstallArchive(layout, archive, opts) if !errors.Is(err, tc.wantErr) { t.Fatalf("InstallArchive error = %v, want %v", err, tc.wantErr) } if activationAttempts != tc.wantAttempts { t.Errorf("activation attempts = %d, want %d", activationAttempts, tc.wantAttempts) } var wantSleeps []time.Duration if tc.existingVersion == version { wantSleeps = append(wantSleeps, 50*time.Millisecond) if backupAttempts != 2 { t.Errorf("backup attempts = %d, want 2", backupAttempts) } } switch tc.wantErr { case nil: if installed.InstallDir != finalDir { t.Errorf("installed directory = %q, want %q", installed.InstallDir, finalDir) } assertRenameTestContents(t, filepath.Join(finalDir, entry), "new sidecar") if tc.activationLockRetries > 0 { wantSleeps = append(wantSleeps, 50*time.Millisecond, 100*time.Millisecond) } case windows.ERROR_ACCESS_DENIED: if !strings.Contains(err.Error(), "directory may be temporarily locked by antivirus or another process") { t.Errorf("missing lock hint in %v", err) } wantSleeps = append(wantSleeps, renameDirBackoff...) default: if !strings.HasPrefix(err.Error(), "activate plugin package: ") { t.Errorf("unexpected error for missing path: %v", err) } } if tc.wantErr != nil && tc.existingVersion == version { wantSleeps = append(wantSleeps, 50*time.Millisecond) if rollbackAttempts != 2 { t.Errorf("rollback attempts = %d, want 2", rollbackAttempts) } } if tc.wantErr != nil || tc.existingVersion == version { wantSleeps = append(wantSleeps, 50*time.Millisecond) if cleanupAttempts != 2 { t.Errorf("cleanup attempts = %d, want 2", cleanupAttempts) } } if !slices.Equal(sleeps, wantSleeps) { t.Errorf("retry delays = %v, want %v", sleeps, wantSleeps) } staged, err := os.ReadDir(layout.TmpDir()) if err != nil || len(staged) != 0 { t.Errorf("staging contents = %v, error = %v, want empty", staged, err) } if tc.wantErr != nil && tc.existingVersion == "" { if _, err := os.Stat(parent); !errors.Is(err, os.ErrNotExist) { t.Errorf("empty package parent: %v, want absent", err) } return } wantVersion := version if tc.wantErr != nil { wantVersion = tc.existingVersion assertRenameTestContents(t, filepath.Join(parent, wantVersion, entry), "old sidecar") } versions, err := os.ReadDir(parent) if err != nil || len(versions) != 1 || versions[0].Name() != wantVersion { t.Errorf("package versions = %v, error = %v, want only %s", versions, err, wantVersion) } }) } } func TestInstallArchiveRenameAndRollbackFail(t *testing.T) { const ( id = "test.rename" version = "1.0.0" entry = "bin/sidecar.exe" ) layout := NewPluginsLayout(t.TempDir()) opts := PackageInstallOptions{HostVersion: "0.3.0", AllowUnsigned: true} archive := packRenameTestPlugin(t, id, version, entry, "old sidecar") installed, err := InstallArchive(layout, archive, opts) if err != nil { t.Fatalf("install existing version: %v", err) } oldFiles := make(map[string]string) for _, name := range []string{"plugin.json", "SHA256SUMS", entry} { data, err := os.ReadFile(filepath.Join(installed.InstallDir, name)) if err != nil { t.Fatal(err) } oldFiles[name] = string(data) } archive = packRenameTestPlugin(t, id, version, entry, "new sidecar") oldRename, oldSleep := renameDirFn, sleepRetryFn t.Cleanup(func() { renameDirFn, sleepRetryFn = oldRename, oldSleep }) sleepRetryFn = func(time.Duration) {} activateErr, rollbackErr := windows.ERROR_ACCESS_DENIED, windows.ERROR_LOCK_VIOLATION var backupDir string renameDirFn = func(oldPath, newPath string) error { if newPath == installed.InstallDir { if oldPath == backupDir { return rollbackErr } return activateErr } backupDir = newPath return oldRename(oldPath, newPath) } _, err = InstallArchive(layout, archive, opts) if !errors.Is(err, activateErr) || !errors.Is(err, rollbackErr) { t.Fatalf("InstallArchive error = %v, want activation and rollback errors", err) } if !strings.HasPrefix(backupDir, installed.InstallDir+".prev-") || !strings.Contains(err.Error(), backupDir) { t.Errorf("InstallArchive error = %v, want .prev- backup path %q", err, backupDir) } if !strings.Contains(err.Error(), "directory may be temporarily locked by antivirus or another process") { t.Errorf("missing activation lock hint in %v", err) } for name, contents := range oldFiles { assertRenameTestContents(t, filepath.Join(backupDir, name), contents) } } func TestRemovePackageDirRenameLockRetry(t *testing.T) { oldRemove, oldSleep := removeDirFn, sleepRetryFn t.Cleanup(func() { removeDirFn, sleepRetryFn = oldRemove, oldSleep }) var sleeps []time.Duration sleepRetryFn = func(delay time.Duration) { sleeps = append(sleeps, delay) } attempts := 0 removeDirFn = func(path string) error { attempts++ return &os.PathError{Op: "remove", Path: path, Err: windows.ERROR_LOCK_VIOLATION} } if err := removePackageDir("stage"); !errors.Is(err, windows.ERROR_LOCK_VIOLATION) { t.Errorf("removePackageDir error = %v, want ERROR_LOCK_VIOLATION", err) } wantSleeps := []time.Duration{50 * time.Millisecond, 100 * time.Millisecond, 200 * time.Millisecond, 400 * time.Millisecond} if attempts != 5 || !slices.Equal(sleeps, wantSleeps) { t.Errorf("remove attempts = %d, delays = %v, want 5 attempts and %v", attempts, sleeps, wantSleeps) } } func packRenameTestPlugin(t *testing.T, id, version, entry, contents string) string { t.Helper() source := t.TempDir() payload := filepath.Join(source, entry) if err := os.MkdirAll(filepath.Dir(payload), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(payload, []byte(contents), 0o644); err != nil { t.Fatal(err) } manifest := fmt.Sprintf(`{"schema":1,"id":%q,"version":%q,"name":{"en-US":"Rename test"},"entry":{"sidecar":%q}}`, id, version, entry) if err := os.WriteFile(filepath.Join(source, "plugin.json"), []byte(manifest), 0o644); err != nil { t.Fatal(err) } archive := filepath.Join(t.TempDir(), "plugin.zip") f, err := os.Create(archive) if err != nil { t.Fatal(err) } zw := zip.NewWriter(f) entryRel := filepath.ToSlash(entry) files := map[string][]byte{ "plugin.json": []byte(manifest), entryRel: []byte(contents), } var sums strings.Builder for _, name := range []string{entryRel, "plugin.json"} { data := files[name] w, err := zw.Create(name) if err != nil { t.Fatal(err) } if _, err := w.Write(data); err != nil { t.Fatal(err) } h := sha256.Sum256(data) fmt.Fprintf(&sums, "%s %s\n", hex.EncodeToString(h[:]), name) } sw, err := zw.Create("SHA256SUMS") if err != nil { t.Fatal(err) } if _, err := sw.Write([]byte(sums.String())); err != nil { t.Fatal(err) } if err := zw.Close(); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } return archive } func assertRenameTestContents(t *testing.T, path, want string) { t.Helper() got, err := os.ReadFile(path) if err != nil || string(got) != want { t.Fatalf("read %q = %q, error = %v, want %q", path, got, err, want) } }