From 6d8d122572e9fe19ae2721c7c30ef682092afa3a Mon Sep 17 00:00:00 2001 From: Ben Firestone Date: Tue, 8 Sep 2026 20:22:01 -0700 Subject: [PATCH 1/3] fix(managed): anchor Cellar and add sbin, lib64, libexec An unanchored /Cellar/ refused any path with a directory of that name, and dpkg and rpm also own /usr/sbin, /usr/lib64 and /usr/libexec. The Cellar pattern requires the formula and version segments and nothing below them, so sbin and libexec installs stay refused. --- README.md | 2 +- managed.go | 16 +++++++++++----- managed_test.go | 22 +++++++++++++++++----- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index b197ab5..cf07b53 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ The zero value works for a goreleaser project with default archive names. | `ChecksumAsset` | `checksums.txt` | goreleaser checksum file | | `SkipChecksum` | `false` | set when the repo publishes no checksum file | | `TargetPath` | running executable, symlinks resolved | file to replace | -| `Managed` | Homebrew Cellar, `/usr/bin`, `/usr/lib`, Nix store | locations owned by a package manager | +| `Managed` | Homebrew Cellar, `/usr/{s,}bin`, `/usr/lib{,64,exec}`, Nix store | locations owned by a package manager | | `Client` | default transport with a 30s response header timeout | HTTP client | | `Out` | `os.Stdout` | progress lines | diff --git a/managed.go b/managed.go index cdc3940..7b88dae 100644 --- a/managed.go +++ b/managed.go @@ -16,17 +16,23 @@ type ManagedInstall struct { Hint string // "{name}" is replaced with the binary name } -// DefaultManagedInstalls covers Homebrew (any /Cellar/ path), system -// package directories (/usr/bin, /usr/lib) and the Nix store. -// /usr/local/bin and ~/.local/bin are not managed. +// DefaultManagedInstalls covers Homebrew and Linuxbrew (a Cellar formula +// directory), system package directories (/usr/bin, /usr/sbin, /usr/lib, +// /usr/lib64, /usr/libexec) and the Nix store. /usr/local/bin and +// ~/.local/bin are not managed. Patterns are case-sensitive; the target +// comes from EvalSymlinks and so carries on-disk casing. var DefaultManagedInstalls = []ManagedInstall{ { - Pattern: regexp.MustCompile(`/Cellar/`), + // /Cellar///... Anything below the + // version directory is Homebrew's, whether bin, sbin or libexec. + // Requiring the two segments keeps a project directory that + // happens to be named Cellar from being refused. + Pattern: regexp.MustCompile(`/Cellar/[^/]+/[^/]+/`), Manager: "Homebrew", Hint: "brew upgrade {name}", }, { - Pattern: regexp.MustCompile(`^/usr/(bin|lib)/`), + Pattern: regexp.MustCompile(`^/usr/(s?bin|lib(64|exec)?)/`), Manager: "dpkg/rpm", Hint: "upgrade {name} with your system package manager (apt, dnf, pacman)", }, diff --git a/managed_test.go b/managed_test.go index 1111045..a1e1ad9 100644 --- a/managed_test.go +++ b/managed_test.go @@ -8,9 +8,12 @@ import ( "testing" ) -// managerHomebrew names the literal repeated across the fixtures below so -// its reuse doesn't trip goconst. -const managerHomebrew = "Homebrew" +// managerHomebrew and managerSystem name the literals repeated across the +// fixtures below so their reuse doesn't trip goconst. +const ( + managerHomebrew = "Homebrew" + managerSystem = "dpkg/rpm" +) func TestDetectManaged_Defaults(t *testing.T) { cases := []struct { @@ -19,12 +22,21 @@ func TestDetectManaged_Defaults(t *testing.T) { }{ {"/opt/homebrew/Cellar/arc/0.15.0/bin/arc", managerHomebrew}, {"/usr/local/Cellar/arc/0.15.0/bin/arc", managerHomebrew}, - {"/usr/bin/arc", "dpkg/rpm"}, - {"/usr/lib/arc/arc", "dpkg/rpm"}, + {"/home/linuxbrew/.linuxbrew/Cellar/arc/0.15.0/bin/arc", managerHomebrew}, + {"/opt/homebrew/Cellar/arc/0.15.0/sbin/arc", managerHomebrew}, + {"/opt/homebrew/Cellar/arc/0.15.0/libexec/bin/arc", managerHomebrew}, + {"/usr/bin/arc", managerSystem}, + {"/usr/sbin/arc", managerSystem}, + {"/usr/lib/arc/arc", managerSystem}, + {"/usr/lib64/arc/arc", managerSystem}, + {"/usr/libexec/arc/arc", managerSystem}, {"/nix/store/abc123-arc-0.15.0/bin/arc", "Nix"}, {"/usr/local/bin/arc", ""}, + {"/usr/local/lib/arc/arc", ""}, + {"/usr/libx/arc", ""}, {"/home/u/.local/bin/arc", ""}, {"/home/u/go/bin/arc", ""}, + {"/home/u/projects/Cellar/bin/arc", ""}, {"/opt/arc/bin/arc", ""}, } for _, tc := range cases { From ac53966e4ee27e8c64a69a08a15258dab073a395 Mon Sep 17 00:00:00 2001 From: Ben Firestone Date: Tue, 8 Sep 2026 20:22:10 -0700 Subject: [PATCH 2/3] fix(replace)!: rename .new over the target in one step Moving the target to .old first opened a two-syscall window in which a crash left no binary at all. The next update then could not even start, since the missing file is the one that runs it. rename(2) replaces a running executable atomically on Linux and macOS, so the .old step is gone and RollbackError is removed with it. BREAKING CHANGE: RollbackError is removed. No caller used it. --- replace.go | 35 ++++--------------- replace_test.go | 89 +++++++++---------------------------------------- 2 files changed, 21 insertions(+), 103 deletions(-) diff --git a/replace.go b/replace.go index a64a2e7..28241c9 100644 --- a/replace.go +++ b/replace.go @@ -15,20 +15,6 @@ var ErrTargetNotWritable = errors.New("selfupdate: target directory is not writa // renameFile is os.Rename. Tests swap it to simulate a failed install. var renameFile = os.Rename -// RollbackError reports that the update failed and the original binary -// could not be restored. The install directory needs manual repair. -type RollbackError struct { - Update error - Rollback error -} - -func (e *RollbackError) Error() string { - return fmt.Sprintf("selfupdate: update failed (%v) and rollback failed (%v)", e.Update, e.Rollback) -} - -// Unwrap exposes the update error to errors.Is and errors.As. -func (e *RollbackError) Unwrap() error { return e.Update } - // preflightWritable creates and removes a temp file in dir. A permission // error is wrapped with ErrTargetNotWritable so callers can print a // specific hint. Other errors are returned as they are. @@ -45,29 +31,20 @@ func preflightWritable(dir string) error { return os.Remove(name) } -// replaceFile installs src at target. It writes .new, renames -// target to .old, renames .new over target and removes .old. When -// the final rename fails it moves .old back and returns the rename error. -// If that restore fails too it returns a *RollbackError. +// replaceFile installs src at target. It writes .new beside the +// target and renames it over target. rename(2) replaces the file in one +// step on Linux and macOS, so a failed rename leaves the original in +// place and a crash at any point leaves the target present. The running +// process keeps its unlinked inode and is unaffected. func replaceFile(target string, src io.Reader, mode os.FileMode) error { - newPath, oldPath := target+".new", target+".old" + newPath := target + ".new" if err := writeFile(newPath, src, mode); err != nil { return err } - if err := renameFile(target, oldPath); err != nil { - _ = os.Remove(newPath) - return fmt.Errorf("selfupdate: move old binary aside: %w", err) - } if err := renameFile(newPath, target); err != nil { _ = os.Remove(newPath) - if rbErr := renameFile(oldPath, target); rbErr != nil { - return &RollbackError{Update: err, Rollback: rbErr} - } return fmt.Errorf("selfupdate: install new binary: %w", err) } - if err := os.Remove(oldPath); err != nil { - return fmt.Errorf("selfupdate: binary was updated but %s could not be removed: %w", oldPath, err) - } return nil } diff --git a/replace_test.go b/replace_test.go index f23c051..e714e4a 100644 --- a/replace_test.go +++ b/replace_test.go @@ -69,46 +69,35 @@ func TestReplaceFile_ReplacesAndCleansUp(t *testing.T) { assertNoLeftovers(t, target) } -func TestReplaceFile_FinalRenameFailureRestoresOriginal(t *testing.T) { +func TestReplaceFile_RenameFailureLeavesOriginal(t *testing.T) { target := writeTarget(t, contentOld) - swapRename(t, func(from, to string) error { - if from == target+".new" { - return errors.New("simulated rename failure") - } - return os.Rename(from, to) + swapRename(t, func(_, _ string) error { + return errors.New("simulated rename failure") }) err := replaceFile(target, strings.NewReader(contentNew), 0o755) - if err == nil { - t.Fatal("expected error") - } - var rb *RollbackError - if errors.As(err, &rb) { - t.Fatalf("rollback succeeded, so the error must not be a RollbackError: %v", err) + if err == nil || !strings.Contains(err.Error(), "install new binary") { + t.Fatalf("got %v", err) } if got := readTarget(t, target); got != contentOld { - t.Fatalf("original not restored: %q", got) + t.Fatalf("original changed: %q", got) } assertNoLeftovers(t, target) } -func TestReplaceFile_RollbackFailureIsRollbackError(t *testing.T) { +// TestReplaceFile_NeverMovesTargetAside pins the single-rename design: the +// only rename is .new over target, so no crash can leave the target missing. +func TestReplaceFile_NeverMovesTargetAside(t *testing.T) { target := writeTarget(t, contentOld) + var renames [][2]string swapRename(t, func(from, to string) error { - if to == target { - return errors.New("simulated: nothing may land on target") - } + renames = append(renames, [2]string{from, to}) return os.Rename(from, to) }) - err := replaceFile(target, strings.NewReader(contentNew), 0o755) - var rb *RollbackError - if !errors.As(err, &rb) { - t.Fatalf("want *RollbackError, got %v", err) - } - if rb.Update == nil || rb.Rollback == nil { - t.Fatalf("both errors must be set: %+v", rb) + if err := replaceFile(target, strings.NewReader(contentNew), 0o755); err != nil { + t.Fatal(err) } - if !strings.Contains(err.Error(), "rollback failed") { - t.Fatalf("message must say rollback failed: %v", err) + if len(renames) != 1 || renames[0] != [2]string{target + ".new", target} { + t.Fatalf("renames %v, want exactly .new over target", renames) } } @@ -151,28 +140,6 @@ func TestPreflightWritable_MissingDir(t *testing.T) { } } -func TestReplaceFile_FirstRenameFailureLeavesOriginal(t *testing.T) { - target := writeTarget(t, contentOld) - swapRename(t, func(from, to string) error { - if from == target { - return errors.New("simulated: cannot move target aside") - } - return os.Rename(from, to) - }) - err := replaceFile(target, strings.NewReader(contentNew), 0o755) - if err == nil || !strings.Contains(err.Error(), "move old binary aside") { - t.Fatalf("got %v", err) - } - var rb *RollbackError - if errors.As(err, &rb) { - t.Fatalf("nothing to roll back, must not be RollbackError: %v", err) - } - if got := readTarget(t, target); got != contentOld { - t.Fatalf("original changed: %q", got) - } - assertNoLeftovers(t, target) -} - // failingReader errors after yielding a few bytes. type failingReader struct{ n int } @@ -232,29 +199,3 @@ func TestReplaceFile_CreateFailureIsNotSentinel(t *testing.T) { t.Fatalf("original changed: %q", got) } } - -func TestReplaceFile_LeftoverRemovalFailureIsReported(t *testing.T) { - if os.Geteuid() == 0 { - t.Skip("root ignores directory permissions") - } - target := writeTarget(t, contentOld) - dir := filepath.Dir(target) - t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) - swapRename(t, func(from, to string) error { - if err := os.Rename(from, to); err != nil { - return err - } - if to == target { - // The new binary landed. Freeze the directory so the .old cleanup fails. - _ = os.Chmod(dir, 0o500) - } - return nil - }) - err := replaceFile(target, strings.NewReader(contentNew), 0o755) - if err == nil || !strings.Contains(err.Error(), "could not be removed") { - t.Fatalf("got %v", err) - } - if got := readTarget(t, target); got != contentNew { - t.Fatalf("update did not land: %q", got) - } -} From 3a6a2f5acdffc0611a5659bfcba71c5166f52058 Mon Sep 17 00:00:00 2001 From: Ben Firestone Date: Tue, 8 Sep 2026 20:22:25 -0700 Subject: [PATCH 3/3] fix(archive): share the default client and cap the download client() used to assign the lazily built default to the exported field, which raced when one installer served several goroutines. The download also had no size bound, so a hostile payload could fill the temp dir before the checksum rejected it. --- archive.go | 40 +++++++++++++++++++++----- archive_test.go | 75 +++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 103 insertions(+), 12 deletions(-) diff --git a/archive.go b/archive.go index f675c3e..85f2555 100644 --- a/archive.go +++ b/archive.go @@ -10,6 +10,7 @@ import ( "path/filepath" "runtime" "strings" + "sync" "time" ) @@ -37,10 +38,15 @@ type ArchiveInstaller struct { SkipChecksum bool // disable verification for repos that publish no checksum file TargetPath string // default: os.Executable(); symlinks are always resolved Managed []ManagedInstall // nil means DefaultManagedInstalls; empty slice disables the check - Client *http.Client // default: DefaultTransport clone with a 30s ResponseHeaderTimeout + Client *http.Client // default: a shared DefaultTransport clone with a 30s ResponseHeaderTimeout Out io.Writer // progress lines; default os.Stdout } +// defaultClient is built on first use and shared by every ArchiveInstaller +// without an explicit Client. Prepare never writes to the installer, so one +// value may serve concurrent goroutines. +var defaultClient = sync.OnceValue(newDefaultClient) + // archiveStaged holds a verified, extracted binary waiting to be renamed // over the target. type archiveStaged struct { @@ -103,7 +109,8 @@ func (a *ArchiveInstaller) stage( } // download streams asset.URL to path, drawing a progress bar on a -// terminal, and returns the SHA-256 of the bytes written. +// terminal, and returns the SHA-256 of the bytes written. When the release +// lists a size the body must match it exactly. func (a *ArchiveInstaller) download(ctx context.Context, asset Asset, path string) ([]byte, error) { a.printf("Downloading %s (%s)...\n", asset.Name, formatMB(asset.Size)) hash := sha256.New() @@ -113,7 +120,7 @@ func (a *ArchiveInstaller) download(ctx context.Context, asset Asset, path strin return fmt.Errorf("selfupdate: create download: %w", err) } progress := newProgressWriter(a.out(), resp.ContentLength) - _, copyErr := io.Copy(io.MultiWriter(f, hash, progress), resp.Body) + copyErr := copyBounded(io.MultiWriter(f, hash, progress), resp.Body, asset.Size) progress.Finish() if closeErr := f.Close(); copyErr == nil { copyErr = closeErr @@ -129,6 +136,25 @@ func (a *ArchiveInstaller) download(ctx context.Context, asset Asset, path strin return hash.Sum(nil), nil } +// copyBounded streams body into dst. A positive size caps the read one +// byte past it, so a hostile payload cannot fill the temp dir before the +// checksum rejects it, and a body of any other length is an error. A zero +// or negative size means the release listed none and the body is unbounded. +func copyBounded(dst io.Writer, body io.Reader, size int64) error { + if size <= 0 { + _, err := io.Copy(dst, body) + return err + } + n, err := io.Copy(dst, io.LimitReader(body, size+1)) + if err != nil { + return err + } + if n != size { + return fmt.Errorf("body is %d bytes, release lists %d", n, size) + } + return nil +} + // verify downloads the checksum asset and checks sum against assetName's entry. func (a *ArchiveInstaller) verify(ctx context.Context, rel Release, assetName string, sum []byte) error { checksums, err := selectAsset(rel, a.checksumAsset()) @@ -243,12 +269,12 @@ func (a *ArchiveInstaller) checksumAsset() string { return DefaultChecksumAsset } -// client returns Client, creating the default one on first use. +// client returns Client, or the shared default. It never writes to a. func (a *ArchiveInstaller) client() *http.Client { - if a.Client == nil { - a.Client = newDefaultClient() + if a.Client != nil { + return a.Client } - return a.Client + return defaultClient() } // newDefaultClient clones the default transport and bounds the wait for diff --git a/archive_test.go b/archive_test.go index ea0cc67..36dd5c5 100644 --- a/archive_test.go +++ b/archive_test.go @@ -27,7 +27,10 @@ var ( _ Staged = (*archiveStaged)(nil) ) -const newBinary = "#!/bin/sh\necho new\n" +const ( + newBinary = "#!/bin/sh\necho new\n" + checksumsPath = "/checksums.txt" +) // archiveFixture serves one release: a tarball for the running platform, // a checksums.txt, and decoys that must never be selected. @@ -67,7 +70,7 @@ func newArchiveFixture(t *testing.T, body string, tamper bool) *archiveFixture { w.Header().Set("Content-Length", strconv.Itoa(len(archive))) _, _ = w.Write(archive) }) - mux.HandleFunc("/checksums.txt", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc(checksumsPath, func(w http.ResponseWriter, r *http.Request) { fx.record(r.URL.Path) _, _ = io.WriteString(w, checksums) }) @@ -82,7 +85,7 @@ func newArchiveFixture(t *testing.T, body string, tamper bool) *archiveFixture { {Name: fx.assetName + ".sig", URL: fx.srv.URL + "/never.sig", Size: 1}, {Name: "tool_1.2.3_linux_amd64.deb", URL: fx.srv.URL + "/never.deb", Size: 1}, {Name: fx.assetName, URL: fx.srv.URL + "/" + fx.assetName, Size: int64(len(archive))}, - {Name: DefaultChecksumAsset, URL: fx.srv.URL + "/checksums.txt", Size: int64(len(checksums))}, + {Name: DefaultChecksumAsset, URL: fx.srv.URL + checksumsPath, Size: int64(len(checksums))}, }} return fx } @@ -110,7 +113,7 @@ func TestArchiveInstaller_PrepareThenCommit(t *testing.T) { if got := readTarget(t, target); got != contentOld { t.Fatalf("Prepare must not touch the target, got %q", got) } - if got := fx.requested(); len(got) != 2 || got[0] != "/"+fx.assetName || got[1] != "/checksums.txt" { + if got := fx.requested(); len(got) != 2 || got[0] != "/"+fx.assetName || got[1] != checksumsPath { t.Fatalf("requests %v", got) } @@ -194,7 +197,7 @@ func TestArchiveInstaller_SkipChecksum(t *testing.T) { } defer func() { _ = staged.Close() }() for _, p := range fx.requested() { - if p == "/checksums.txt" { + if p == checksumsPath { t.Fatal("checksums must not be fetched when SkipChecksum is set") } } @@ -322,3 +325,65 @@ func TestArchiveInstaller_DefaultClientHeaderTimeout(t *testing.T) { t.Fatal("an explicit Client must be used as is") } } + +// TestArchiveInstaller_ClientIsConcurrencySafe runs under -race: a shared +// installer must not be mutated by client(). +func TestArchiveInstaller_ClientIsConcurrencySafe(t *testing.T) { + inst := &ArchiveInstaller{} + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { _ = inst.client() }) + } + wg.Wait() + if inst.Client != nil { + t.Fatal("client() must leave the exported field untouched") + } +} + +func TestArchiveInstaller_DownloadSizeMismatchIsRejected(t *testing.T) { + fx := newArchiveFixture(t, newBinary, false) + declared := fx.rel.Assets[2].Size + cases := []struct { + name string + size int64 + }{ + {"body longer than listed", declared - 1}, + {"body shorter than listed", declared + 10}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assets := append([]Asset(nil), fx.rel.Assets...) + assets[2].Size = tc.size + rel := Release{Tag: fx.rel.Tag, Assets: assets} + target := writeTarget(t, contentOld) + staged, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), rel) + if err == nil || !strings.Contains(err.Error(), "release lists") { + t.Fatalf("got %v", err) + } + if staged != nil { + t.Fatal("no staged update may be returned on failure") + } + if got := readTarget(t, target); got != contentOld { + t.Fatalf("target changed: %q", got) + } + }) + } + for _, path := range fx.requested() { + if path == checksumsPath { + t.Fatal("the size check must fail before the checksum file is fetched") + } + } +} + +func TestArchiveInstaller_UnknownSizeIsUnbounded(t *testing.T) { + fx := newArchiveFixture(t, newBinary, false) + assets := append([]Asset(nil), fx.rel.Assets...) + assets[2].Size = 0 + rel := Release{Tag: fx.rel.Tag, Assets: assets} + target := writeTarget(t, contentOld) + staged, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), rel) + if err != nil { + t.Fatal(err) + } + _ = staged.Close() +}