diff --git a/README.md b/README.md index 7a8c0bc..c236689 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ -# go-selfupdate +# selfupdate-go Self-update with release channels (stable, rc, nightly) for Go CLIs that publish GitHub releases. Used by [arc](https://github.com/SentioLabs/arc) and -[envctl](https://github.com/SentioLabs/envctl). +[envctl](https://github.com/SentioLabs/envctl). A Rust port lives at +[selfupdate-rs](https://github.com/SentioLabs/selfupdate-rs). ## What it does @@ -11,8 +12,11 @@ publish GitHub releases. Used by [arc](https://github.com/SentioLabs/arc) and patterns (`v1.2.3-rc.1`, `v1.2.3-nightly.20260903`). A newer stable release always wins over an older prerelease. - Compares against the running version, including `dev` builds. -- Prints status and asks for confirmation. Runs an optional pre-install hook, - then replaces the binary through your existing install script. +- Downloads the release archive for the running OS and architecture, verifies + it against `checksums.txt`, extracts the binary, and renames it over the + running executable. No shell, curl, or install script is involved. +- Runs `PreInstall` after the download is verified and `PostInstall` after the + binary is replaced, so a CLI can stop and restart a daemon around the swap. - Persists the chosen channel wherever you keep config, through a two-method `Store` interface. @@ -20,8 +24,8 @@ publish GitHub releases. Used by [arc](https://github.com/SentioLabs/arc) and ```go import ( - "github.com/sentiolabs/go-selfupdate" - "github.com/sentiolabs/go-selfupdate/cobracmd" + "github.com/sentiolabs/selfupdate-go" + "github.com/sentiolabs/selfupdate-go/cobracmd" ) updater := &selfupdate.Updater{ @@ -29,7 +33,7 @@ updater := &selfupdate.Updater{ Version: version.Version, // "v1.2.3", "1.2.3" or "dev" Source: &selfupdate.GitHubSource{Owner: "acme", Repo: "mytool"}, Store: myChannelStore(), // implements selfupdate.Store - Installer: &selfupdate.ScriptInstaller{ScriptURL: "https://raw.githubusercontent.com/acme/mytool/main/scripts/install.sh"}, + Installer: &selfupdate.ArchiveInstaller{}, } rootCmd.AddCommand(cobracmd.New(updater)) ``` @@ -44,7 +48,55 @@ mytool self channel [stable|rc|nightly] [-y] `--check` has no shorthand by default. Pass `cobracmd.WithCheckShorthand("c")` if your root command does not already use `-c`. -### Store +## ArchiveInstaller + +The zero value works for a goreleaser project with default archive names. + +| Field | Default | Purpose | +|---|---|---| +| `Name` | base name of the running executable | binary name inside the archive | +| `AssetTemplate` | `{name}_{version}_{os}_{arch}.tar.gz` | archive asset name. `{version}` has no leading `v` | +| `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 | +| `Client` | default transport with a 30s response header timeout | HTTP client | +| `Out` | `os.Stdout` | progress lines | + +`Prepare` runs before any hook. It resolves the target, refuses a binary that +lives under a package manager (the error names the manager and its upgrade +command), refuses an unwritable directory, then downloads and verifies the +archive into a temp directory. Nothing is downloaded when a check fails. +`Commit` renames the extracted binary over the target and, on macOS, re-signs +it ad hoc. On a terminal the download line shows a progress bar. Elsewhere it +is a single line. + +Linux and macOS with `.tar.gz` assets are supported. Windows is not. +Verification proves the download matches what the release page lists. It +does not prove who published it. Signature checking is out of scope. + +## Hooks + +`PreInstall` runs after the new binary is downloaded and verified, right +before it replaces the running one. `PostInstall` runs after the replace. +A `PostInstall` error is returned with a note that the binary was already +updated. + +```go +updater.PreInstall = func(ctx context.Context, current, latest string) error { + if semver.MajorMinor(latest) != semver.MajorMinor(current) { + if err := backupDatabase(); err != nil { + return err + } + } + return stopServer(ctx) +} +updater.PostInstall = func(ctx context.Context, current, latest string) error { + return startServer(ctx) +} +``` + +## Store ```go store := selfupdate.FuncStore{ @@ -56,15 +108,17 @@ store := selfupdate.FuncStore{ `selfupdate.MemStore` is available for tests and for CLIs that do not persist a channel. -### Pre-install hook +## ScriptInstaller + +`ScriptInstaller` runs `curl -fsSL | bash -s -- --force --tag=` +and is kept for CLIs that have not moved to `ArchiveInstaller` yet. It needs +`bash` and `curl` on PATH, and the script must accept `--force --tag=` and +download the archive for that tag. ```go -updater.PreInstall = func(ctx context.Context, current, latest string) error { - if semver.MajorMinor(latest) != semver.MajorMinor(current) { - return backupDatabase() - } - return nil -} +Installer: &selfupdate.ScriptInstaller{ + ScriptURL: "https://raw.githubusercontent.com/acme/mytool/main/scripts/install.sh", +}, ``` ## Tagging releases so channels work @@ -73,14 +127,22 @@ updater.PreInstall = func(ctx context.Context, current, latest string) error { - Release candidates: tag the *next* version with a dotted counter, `v1.4.0-rc.1`, `v1.4.0-rc.2`. For compatibility, the updater compares legacy counters numerically too: `rc9` sorts below `rc10`, and `rc10` - compares equal to `rc.10`. Displayed tags, pre-install hook arguments, and - installer tags retain their original spelling. + compares equal to `rc.10`. Displayed tags, hook arguments, and asset names + retain their original spelling. - Nightlies: tag the *next patch* version, `v1.3.1-nightly.20260904`. A nightly tagged with the current released version sorts below that release and is never offered. -The install script must accept `--force --tag=` and download the -archive for that tag. +## Migrating from 0.1 + +- The import path is `github.com/sentiolabs/selfupdate-go`. The package name + is still `selfupdate`. +- `Installer` is two-phase. `Install(ctx, tag)` became + `Prepare(ctx, rel) (Staged, error)`, and `Staged` has `Commit(ctx)` and + `Close()`. Custom installers implement both. `ScriptInstaller` already does. +- `Resolve` returns a `Release` instead of a tag string. `CheckResult` has a + `Release` field. `Latest` still holds the tag. +- `Release` carries `Assets`. `Updater` gains `PostInstall`. ## Compatibility diff --git a/archive.go b/archive.go new file mode 100644 index 0000000..f675c3e --- /dev/null +++ b/archive.go @@ -0,0 +1,305 @@ +package selfupdate + +import ( + "context" + "crypto/sha256" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + "time" +) + +// DefaultAssetTemplate matches goreleaser's default archive name. +const DefaultAssetTemplate = "{name}_{version}_{os}_{arch}.tar.gz" + +// DefaultChecksumAsset is goreleaser's default checksum file name. +const DefaultChecksumAsset = "checksums.txt" + +// responseHeaderTimeout bounds how long the default client waits for +// response headers. Bodies stream until ctx is cancelled. +const responseHeaderTimeout = 30 * time.Second + +// binaryMode is the permission set on the installed binary. +const binaryMode os.FileMode = 0o755 + +// ArchiveInstaller downloads the release asset for the running platform, +// verifies it against the release's checksum file, extracts the binary and +// replaces the running executable in place. It needs no shell, curl or +// install script. +type ArchiveInstaller struct { + Name string // binary name inside the archive; default: base name of the resolved target + AssetTemplate string // default DefaultAssetTemplate; {version} has no leading v + ChecksumAsset string // default DefaultChecksumAsset + 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 + Out io.Writer // progress lines; default os.Stdout +} + +// archiveStaged holds a verified, extracted binary waiting to be renamed +// over the target. +type archiveStaged struct { + installer *ArchiveInstaller + tag string + target string + dir string // temp dir holding the download and the extracted binary + binary string // extracted binary inside dir +} + +// Prepare resolves the target, refuses managed or unwritable locations, +// then downloads, verifies and extracts the platform asset into a temp +// directory. The running binary is untouched. +func (a *ArchiveInstaller) Prepare(ctx context.Context, rel Release) (Staged, error) { + target, err := a.target() + if err != nil { + return nil, err + } + name := a.name(target) + if m, ok := detectManaged(target, a.Managed); ok { + return nil, managedError(m, name, target) + } + if err := preflightWritable(filepath.Dir(target)); err != nil { + return nil, err + } + asset, err := selectAsset(rel, a.assetName(name, rel.Tag)) + if err != nil { + return nil, err + } + dir, err := os.MkdirTemp("", "selfupdate-*") + if err != nil { + return nil, fmt.Errorf("selfupdate: create temp dir: %w", err) + } + staged := &archiveStaged{installer: a, tag: rel.Tag, target: target, dir: dir} + if err := a.stage(ctx, rel, asset, name, staged); err != nil { + _ = staged.Close() + return nil, err + } + return staged, nil +} + +// stage downloads asset into staged.dir, verifies it unless SkipChecksum, +// and extracts name beside it. +func (a *ArchiveInstaller) stage( + ctx context.Context, rel Release, asset Asset, name string, staged *archiveStaged, +) error { + archivePath := filepath.Join(staged.dir, asset.Name) + sum, err := a.download(ctx, asset, archivePath) + if err != nil { + return err + } + if !a.SkipChecksum { + if err := a.verify(ctx, rel, asset.Name, sum); err != nil { + return err + } + a.printf("Verified %s\n", asset.Name) + } + staged.binary = filepath.Join(staged.dir, name) + return extractTo(archivePath, name, staged.binary) +} + +// download streams asset.URL to path, drawing a progress bar on a +// terminal, and returns the SHA-256 of the bytes written. +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() + err := a.fetch(ctx, asset.URL, func(resp *http.Response) error { + f, err := os.Create(path) // path is inside the temp dir created by Prepare + if err != nil { + return fmt.Errorf("selfupdate: create download: %w", err) + } + progress := newProgressWriter(a.out(), resp.ContentLength) + _, copyErr := io.Copy(io.MultiWriter(f, hash, progress), resp.Body) + progress.Finish() + if closeErr := f.Close(); copyErr == nil { + copyErr = closeErr + } + if copyErr != nil { + return fmt.Errorf("selfupdate: download %s: %w", asset.Name, copyErr) + } + return nil + }) + if err != nil { + return nil, err + } + return hash.Sum(nil), 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()) + if err != nil { + return err + } + return a.fetch(ctx, checksums.URL, func(resp *http.Response) error { + sums, err := parseChecksums(resp.Body) + if err != nil { + return err + } + return verifyChecksum(sums, assetName, sum) + }) +} + +// fetch GETs url and hands the 200 response to fn. The body is closed +// when fn returns. Any other status is an error. +func (a *ArchiveInstaller) fetch(ctx context.Context, url string, fn func(*http.Response) error) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return fmt.Errorf("selfupdate: build request: %w", err) + } + resp, err := a.client().Do(req) + if err != nil { + return fmt.Errorf("selfupdate: %w", err) + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("selfupdate: GET %s returned status %d", url, resp.StatusCode) + } + return fn(resp) +} + +// extractTo pulls entry name out of the tar.gz at archivePath into dst. +func extractTo(archivePath, name, dst string) error { + in, err := os.Open(archivePath) // path is inside the temp dir created by Prepare + if err != nil { + return fmt.Errorf("selfupdate: open archive: %w", err) + } + defer func() { _ = in.Close() }() + out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, binaryMode) // same temp dir + if err != nil { + return fmt.Errorf("selfupdate: create extracted binary: %w", err) + } + if err := extractFile(in, name, out); err != nil { + _ = out.Close() + return err + } + return out.Close() +} + +// selectAsset returns the asset named exactly name. Substring matches are +// rejected on purpose: tool_1.2.3_linux_amd64.tar.gz.sig must not shadow +// the tarball. The error lists the available names. +func selectAsset(rel Release, name string) (Asset, error) { + names := make([]string, 0, len(rel.Assets)) + for _, a := range rel.Assets { + if a.Name == name { + return a, nil + } + names = append(names, a.Name) + } + return Asset{}, fmt.Errorf("selfupdate: release %s has no asset %s (available: %s)", + rel.Tag, name, strings.Join(names, ", ")) +} + +// assetName renders AssetTemplate for name, tag and the running platform. +func (a *ArchiveInstaller) assetName(name, tag string) string { + tmpl := a.AssetTemplate + if tmpl == "" { + tmpl = DefaultAssetTemplate + } + return strings.NewReplacer( + "{name}", name, + "{version}", strings.TrimPrefix(tag, "v"), + "{os}", runtime.GOOS, + "{arch}", runtime.GOARCH, + ).Replace(tmpl) +} + +// target returns TargetPath, or the running executable, with symlinks +// resolved so a Homebrew or ~/.local/bin link is followed to the real file. +func (a *ArchiveInstaller) target() (string, error) { + p := a.TargetPath + if p == "" { + exe, err := os.Executable() + if err != nil { + return "", fmt.Errorf("selfupdate: locate running binary: %w", err) + } + p = exe + } + resolved, err := filepath.EvalSymlinks(p) + if err != nil { + return "", fmt.Errorf("selfupdate: resolve %s: %w", p, err) + } + return resolved, nil +} + +// name returns Name, or the base name of the resolved target. +func (a *ArchiveInstaller) name(target string) string { + if a.Name != "" { + return a.Name + } + return filepath.Base(target) +} + +// checksumAsset returns ChecksumAsset, or goreleaser's default name. +func (a *ArchiveInstaller) checksumAsset() string { + if a.ChecksumAsset != "" { + return a.ChecksumAsset + } + return DefaultChecksumAsset +} + +// client returns Client, creating the default one on first use. +func (a *ArchiveInstaller) client() *http.Client { + if a.Client == nil { + a.Client = newDefaultClient() + } + return a.Client +} + +// newDefaultClient clones the default transport and bounds the wait for +// response headers so a dead connection fails instead of hanging forever. +func newDefaultClient() *http.Client { + tr, ok := http.DefaultTransport.(*http.Transport) + if !ok { + return &http.Client{Transport: &http.Transport{ResponseHeaderTimeout: responseHeaderTimeout}} + } + tr = tr.Clone() + tr.ResponseHeaderTimeout = responseHeaderTimeout + return &http.Client{Transport: tr} +} + +// out returns Out, or os.Stdout. +func (a *ArchiveInstaller) out() io.Writer { + if a.Out != nil { + return a.Out + } + return os.Stdout +} + +// printf writes one progress line to out. +func (a *ArchiveInstaller) printf(format string, args ...any) { + _, _ = fmt.Fprintf(a.out(), format, args...) +} + +// Commit renames the extracted binary over the target and re-signs it on +// macOS. A signing failure is a warning, not an error. +func (s *archiveStaged) Commit(_ context.Context) error { + f, err := os.Open(s.binary) // path is inside our own temp dir + if err != nil { + return fmt.Errorf("selfupdate: open staged binary: %w", err) + } + defer func() { _ = f.Close() }() + if err := replaceFile(s.target, f, binaryMode); err != nil { + return err + } + if err := signBinary(s.target); err != nil { + s.installer.printf("Warning: could not re-sign %s: %v\n", s.target, err) + } + s.installer.printf("Installed %s %s to %s\n", filepath.Base(s.target), s.tag, s.target) + return nil +} + +// Close removes the temp directory. It is safe to call more than once. +func (s *archiveStaged) Close() error { + if s.dir == "" { + return nil + } + err := os.RemoveAll(s.dir) + s.dir = "" + return err +} diff --git a/archive_test.go b/archive_test.go new file mode 100644 index 0000000..ea0cc67 --- /dev/null +++ b/archive_test.go @@ -0,0 +1,324 @@ +//nolint:testpackage // exercises the unexported staged type and helpers +package selfupdate + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "sync" + "testing" +) + +// --- Contract assertions --- +var ( + _ Installer = (*ArchiveInstaller)(nil) + _ Staged = (*archiveStaged)(nil) +) + +const newBinary = "#!/bin/sh\necho new\n" + +// archiveFixture serves one release: a tarball for the running platform, +// a checksums.txt, and decoys that must never be selected. +type archiveFixture struct { + srv *httptest.Server + rel Release + assetName string + mu sync.Mutex + requests []string +} + +func (fx *archiveFixture) record(path string) { + fx.mu.Lock() + defer fx.mu.Unlock() + fx.requests = append(fx.requests, path) +} + +func (fx *archiveFixture) requested() []string { + fx.mu.Lock() + defer fx.mu.Unlock() + return append([]string(nil), fx.requests...) +} + +func newArchiveFixture(t *testing.T, body string, tamper bool) *archiveFixture { + t.Helper() + fx := &archiveFixture{assetName: fmt.Sprintf("tool_1.2.3_%s_%s.tar.gz", runtime.GOOS, runtime.GOARCH)} + archive := tarGz(t, tarEntry{name: "LICENSE.txt", body: "license text"}, tarEntry{name: testRepo, body: body}) + sum := sha256.Sum256(archive) + if tamper { + sum[0] ^= 0xff + } + checksums := hex.EncodeToString(sum[:]) + " " + fx.assetName + "\n" + + mux := http.NewServeMux() + mux.HandleFunc("/"+fx.assetName, func(w http.ResponseWriter, r *http.Request) { + fx.record(r.URL.Path) + w.Header().Set("Content-Length", strconv.Itoa(len(archive))) + _, _ = w.Write(archive) + }) + mux.HandleFunc("/checksums.txt", func(w http.ResponseWriter, r *http.Request) { + fx.record(r.URL.Path) + _, _ = io.WriteString(w, checksums) + }) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + fx.record(r.URL.Path) + w.WriteHeader(http.StatusNotFound) + }) + fx.srv = httptest.NewServer(mux) + t.Cleanup(fx.srv.Close) + + fx.rel = Release{Tag: tagV123, Assets: []Asset{ + {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))}, + }} + return fx +} + +// newTestInstaller targets an explicit file and disables managed-path +// detection so an unusual TMPDIR cannot trip the defaults. +func newTestInstaller(target string, out io.Writer) *ArchiveInstaller { + return &ArchiveInstaller{Name: testRepo, TargetPath: target, Out: out, Managed: []ManagedInstall{}} +} + +func TestArchiveInstaller_PrepareThenCommit(t *testing.T) { + fx := newArchiveFixture(t, newBinary, false) + target := writeTarget(t, contentOld) + resolvedTarget, err := filepath.EvalSymlinks(target) + if err != nil { + t.Fatal(err) + } + var out bytes.Buffer + inst := newTestInstaller(target, &out) + + staged, err := inst.Prepare(context.Background(), fx.rel) + if err != nil { + t.Fatal(err) + } + 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" { + t.Fatalf("requests %v", got) + } + + if err := staged.Commit(context.Background()); err != nil { + t.Fatal(err) + } + if got := readTarget(t, target); got != newBinary { + t.Fatalf("target after Commit: %q", got) + } + info, err := os.Stat(target) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o755 { + t.Fatalf("mode %v", info.Mode().Perm()) + } + assertNoLeftovers(t, target) + + dir := staged.(*archiveStaged).dir + if err := staged.Close(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("temp dir %s must be removed by Close", dir) + } + + wants := []string{ + "Downloading " + fx.assetName, + "Verified " + fx.assetName, + "Installed tool " + tagV123 + " to " + resolvedTarget, + } + for _, want := range wants { + if !strings.Contains(out.String(), want) { + t.Errorf("output missing %q:\n%s", want, out.String()) + } + } + if strings.Count(out.String(), "Downloading") != 1 || strings.Contains(out.String(), "\r") { + t.Fatalf("non-terminal output must be one download line with no redraws:\n%q", out.String()) + } +} + +func TestArchiveInstaller_ChecksumMismatchLeavesTarget(t *testing.T) { + fx := newArchiveFixture(t, newBinary, true) + target := writeTarget(t, contentOld) + staged, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), fx.rel) + if !errors.Is(err, ErrChecksumMismatch) { + 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) + } +} + +func TestArchiveInstaller_MissingChecksumAsset(t *testing.T) { + fx := newArchiveFixture(t, newBinary, false) + rel := fx.rel + rel.Assets = rel.Assets[:3] // drop checksums.txt + target := writeTarget(t, contentOld) + _, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), rel) + if err == nil || !strings.Contains(err.Error(), DefaultChecksumAsset) { + t.Fatalf("got %v", err) + } + if got := readTarget(t, target); got != contentOld { + t.Fatalf("target changed: %q", got) + } +} + +func TestArchiveInstaller_SkipChecksum(t *testing.T) { + fx := newArchiveFixture(t, newBinary, true) // tampered checksum file, never read + rel := fx.rel + rel.Assets = rel.Assets[:3] + target := writeTarget(t, contentOld) + inst := newTestInstaller(target, io.Discard) + inst.SkipChecksum = true + staged, err := inst.Prepare(context.Background(), rel) + if err != nil { + t.Fatal(err) + } + defer func() { _ = staged.Close() }() + for _, p := range fx.requested() { + if p == "/checksums.txt" { + t.Fatal("checksums must not be fetched when SkipChecksum is set") + } + } + if err := staged.Commit(context.Background()); err != nil { + t.Fatal(err) + } + if got := readTarget(t, target); got != newBinary { + t.Fatalf("target: %q", got) + } +} + +func TestArchiveInstaller_MissingPlatformAssetMakesNoRequest(t *testing.T) { + fx := newArchiveFixture(t, newBinary, false) + rel := Release{Tag: fx.rel.Tag, Assets: []Asset{fx.rel.Assets[0], fx.rel.Assets[1], fx.rel.Assets[3]}} + target := writeTarget(t, contentOld) + _, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), rel) + if err == nil || !strings.Contains(err.Error(), fx.assetName) || !strings.Contains(err.Error(), "available:") { + t.Fatalf("got %v", err) + } + if got := fx.requested(); len(got) != 0 { + t.Fatalf("no request may be made before an asset is selected: %v", got) + } +} + +func TestArchiveInstaller_ManagedTargetRefused(t *testing.T) { + fx := newArchiveFixture(t, newBinary, false) + target := writeTarget(t, contentOld) + inst := newTestInstaller(target, io.Discard) + inst.Managed = []ManagedInstall{{ + Pattern: regexp.MustCompile(regexp.QuoteMeta(filepath.Dir(target))), + Manager: "testpm", + Hint: "testpm upgrade {name}", + }} + _, err := inst.Prepare(context.Background(), fx.rel) + if !errors.Is(err, ErrManagedInstall) || !strings.Contains(err.Error(), "testpm upgrade tool") { + t.Fatalf("got %v", err) + } + if got := fx.requested(); len(got) != 0 { + t.Fatalf("managed check must run before any request: %v", got) + } +} + +func TestArchiveInstaller_UnwritableDirMakesNoRequest(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + fx := newArchiveFixture(t, newBinary, false) + target := writeTarget(t, contentOld) + dir := filepath.Dir(target) + if err := os.Chmod(dir, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + _, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), fx.rel) + if !errors.Is(err, ErrTargetNotWritable) { + t.Fatalf("got %v", err) + } + if got := fx.requested(); len(got) != 0 { + t.Fatalf("writable check must run before any request: %v", got) + } +} + +func TestArchiveInstaller_ResolvesSymlinkAndDefaultsName(t *testing.T) { + fx := newArchiveFixture(t, newBinary, false) + realPath := writeTarget(t, contentOld) + link := filepath.Join(t.TempDir(), "tool-link") + if err := os.Symlink(realPath, link); err != nil { + t.Fatal(err) + } + inst := &ArchiveInstaller{TargetPath: link, Out: io.Discard, Managed: []ManagedInstall{}} + staged, err := inst.Prepare(context.Background(), fx.rel) + if err != nil { + t.Fatal(err) + } + defer func() { _ = staged.Close() }() + if err := staged.Commit(context.Background()); err != nil { + t.Fatal(err) + } + if got := readTarget(t, realPath); got != newBinary { + t.Fatalf("real file: %q", got) + } + info, err := os.Lstat(link) + if err != nil { + t.Fatal(err) + } + if info.Mode()&os.ModeSymlink == 0 { + t.Fatal("the symlink must survive; only its target is replaced") + } +} + +func TestArchiveInstaller_Non200IsError(t *testing.T) { + fx := newArchiveFixture(t, newBinary, false) + assets := append([]Asset(nil), fx.rel.Assets...) + assets[2].URL = fx.srv.URL + "/missing.tar.gz" + rel := Release{Tag: fx.rel.Tag, Assets: assets} + target := writeTarget(t, contentOld) + _, err := newTestInstaller(target, io.Discard).Prepare(context.Background(), rel) + if err == nil || !strings.Contains(err.Error(), "status 404") { + t.Fatalf("got %v", err) + } +} + +func TestArchiveInstaller_AssetName(t *testing.T) { + inst := &ArchiveInstaller{} + want := fmt.Sprintf("tool_1.2.3_%s_%s.tar.gz", runtime.GOOS, runtime.GOARCH) + if got := inst.assetName(testRepo, tagV123); got != want { + t.Fatalf("default template: got %q, want %q", got, want) + } + inst.AssetTemplate = "{name}-{os}-{arch}-v{version}.tgz" + want = fmt.Sprintf("tool-%s-%s-v1.2.3.tgz", runtime.GOOS, runtime.GOARCH) + if got := inst.assetName(testRepo, tagV123); got != want { + t.Fatalf("custom template: got %q, want %q", got, want) + } +} + +func TestArchiveInstaller_DefaultClientHeaderTimeout(t *testing.T) { + inst := &ArchiveInstaller{} + tr, ok := inst.client().Transport.(*http.Transport) + if !ok || tr.ResponseHeaderTimeout != responseHeaderTimeout { + t.Fatalf("default transport: %+v", inst.client().Transport) + } + custom := &http.Client{} + inst = &ArchiveInstaller{Client: custom} + if inst.client() != custom { + t.Fatal("an explicit Client must be used as is") + } +} diff --git a/channel.go b/channel.go index 05af317..6df9892 100644 --- a/channel.go +++ b/channel.go @@ -57,14 +57,14 @@ func LookupChannel(specs []ChannelSpec, channel Channel) (ChannelSpec, bool) { return ChannelSpec{}, false } -// Resolve returns the tag a user on channel should be offered. An empty +// Resolve returns the release a user on channel should be offered. An empty // channel means stable, which uses the forge's latest release. A patterned -// channel returns its newest matching tag unless the newest stable release -// is newer, in which case the stable tag is returned. A patterned channel -// with no match falls back to the newest stable release. An unknown channel -// is an error, as is a channel with no release at all. When the listed page -// holds no stable release, Resolve asks Latest for one. -func Resolve(ctx context.Context, src Source, channel Channel, specs []ChannelSpec) (string, error) { +// channel returns its newest matching release unless the newest stable +// release is newer, in which case the stable release is returned. A patterned +// channel with no match falls back to the newest stable release. An unknown +// channel is an error, as is a channel with no release at all. When the +// listed page holds no stable release, Resolve asks Latest for one. +func Resolve(ctx context.Context, src Source, channel Channel, specs []ChannelSpec) (Release, error) { if specs == nil { specs = DefaultChannels } @@ -73,59 +73,55 @@ func Resolve(ctx context.Context, src Source, channel Channel, specs []ChannelSp } spec, ok := LookupChannel(specs, channel) if !ok { - return "", fmt.Errorf("unknown channel %q", channel) + return Release{}, fmt.Errorf("unknown channel %q", channel) } if spec.Pattern == nil { - rel, err := src.Latest(ctx) - if err != nil { - return "", err - } - return rel.Tag, nil + return src.Latest(ctx) } releases, err := src.List(ctx, maxPerPage) if err != nil { - return "", err + return Release{}, err } - channelTag, stableTag := newestMatch(releases, spec.Pattern) - if channelTag != "" && stableTag == "" { + channelRel, stableRel := newestMatch(releases, spec.Pattern) + if channelRel.Tag != "" && stableRel.Tag == "" { rel, err := src.Latest(ctx) if err != nil { - return "", err + return Release{}, err } if rel.Tag != "" && !rel.Prerelease { - stableTag = rel.Tag + stableRel = rel } } switch { - case channelTag != "" && stableTag != "": - if semver.Compare(stableTag, channelTag) > 0 { - return stableTag, nil + case channelRel.Tag != "" && stableRel.Tag != "": + if semver.Compare(stableRel.Tag, channelRel.Tag) > 0 { + return stableRel, nil } - return channelTag, nil - case channelTag != "": - return channelTag, nil - case stableTag != "": - return stableTag, nil + return channelRel, nil + case channelRel.Tag != "": + return channelRel, nil + case stableRel.Tag != "": + return stableRel, nil default: - return "", fmt.Errorf("no %s release found", channel) + return Release{}, fmt.Errorf("no %s release found", channel) } } // newestMatch scans releases, which List returns newest first, and returns -// the first tag matching pattern and the first non-prerelease tag. -func newestMatch(releases []Release, pattern *regexp.Regexp) (channelTag, stableTag string) { +// the first release matching pattern and the first non-prerelease. +func newestMatch(releases []Release, pattern *regexp.Regexp) (channelRel, stableRel Release) { for _, r := range releases { - if channelTag == "" && pattern.MatchString(r.Tag) { - channelTag = r.Tag + if channelRel.Tag == "" && pattern.MatchString(r.Tag) { + channelRel = r } - if stableTag == "" && !r.Prerelease { - stableTag = r.Tag + if stableRel.Tag == "" && !r.Prerelease { + stableRel = r } - if channelTag != "" && stableTag != "" { + if channelRel.Tag != "" && stableRel.Tag != "" { break } } - return channelTag, stableTag + return channelRel, stableRel } diff --git a/channel_test.go b/channel_test.go index 062f15a..f4c37f5 100644 --- a/channel_test.go +++ b/channel_test.go @@ -74,9 +74,9 @@ func fixtureReleases() []Release { func TestResolve_StableUsesLatest(t *testing.T) { src := &fakeSource{latest: Release{Tag: tagV0100}, list: fixtureReleases()} for _, ch := range []Channel{ChannelStable, ""} { - tag, err := Resolve(context.Background(), src, ch, DefaultChannels) - if err != nil || tag != tagV0100 { - t.Fatalf("channel %q: got %q, %v", ch, tag, err) + rel, err := Resolve(context.Background(), src, ch, DefaultChannels) + if err != nil || rel.Tag != tagV0100 { + t.Fatalf("channel %q: got %q, %v", ch, rel.Tag, err) } } if src.listCalls != 0 { @@ -86,9 +86,9 @@ func TestResolve_StableUsesLatest(t *testing.T) { func TestResolve_RC(t *testing.T) { src := &fakeSource{list: fixtureReleases()} - tag, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) - if err != nil || tag != tagV0110RC3 { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) + if err != nil || rel.Tag != tagV0110RC3 { + t.Fatalf("got %q, %v", rel.Tag, err) } } @@ -98,17 +98,17 @@ func TestResolve_RCStableIsNewer(t *testing.T) { {Tag: tagV0110RC3, Prerelease: true}, {Tag: tagV0100}, }} - tag, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) - if err != nil || tag != "v0.12.0" { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) + if err != nil || rel.Tag != "v0.12.0" { + t.Fatalf("got %q, %v", rel.Tag, err) } } func TestResolve_Nightly(t *testing.T) { src := &fakeSource{list: fixtureReleases()} - tag, err := Resolve(context.Background(), src, ChannelNightly, DefaultChannels) - if err != nil || tag != "v0.11.0-nightly.20260302" { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelNightly, DefaultChannels) + if err != nil || rel.Tag != "v0.11.0-nightly.20260302" { + t.Fatalf("got %q, %v", rel.Tag, err) } } @@ -117,17 +117,17 @@ func TestResolve_NightlyStableIsNewer(t *testing.T) { {Tag: "v0.11.0"}, {Tag: "v0.10.0-nightly.20260302", Prerelease: true}, }} - tag, err := Resolve(context.Background(), src, ChannelNightly, DefaultChannels) - if err != nil || tag != "v0.11.0" { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelNightly, DefaultChannels) + if err != nil || rel.Tag != "v0.11.0" { + t.Fatalf("got %q, %v", rel.Tag, err) } } func TestResolve_NoChannelMatchFallsBackToStable(t *testing.T) { src := &fakeSource{list: []Release{{Tag: tagV0100}}} - tag, err := Resolve(context.Background(), src, ChannelNightly, DefaultChannels) - if err != nil || tag != tagV0100 { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelNightly, DefaultChannels) + if err != nil || rel.Tag != tagV0100 { + t.Fatalf("got %q, %v", rel.Tag, err) } } @@ -148,9 +148,9 @@ func TestResolve_UnknownChannel(t *testing.T) { func TestResolve_NilSpecsMeansDefaults(t *testing.T) { src := &fakeSource{list: fixtureReleases()} - tag, err := Resolve(context.Background(), src, ChannelRC, nil) - if err != nil || tag != tagV0110RC3 { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelRC, nil) + if err != nil || rel.Tag != tagV0110RC3 { + t.Fatalf("got %q, %v", rel.Tag, err) } } @@ -167,9 +167,9 @@ func TestResolve_SourceErrorsPropagate(t *testing.T) { func TestResolve_OverflowPageFallsBackToLatest(t *testing.T) { src := &fakeSource{list: manyRCReleases(), latest: Release{Tag: tagV0190}} - tag, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) - if err != nil || tag != tagV0200RC101 { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) + if err != nil || rel.Tag != tagV0200RC101 { + t.Fatalf("got %q, %v", rel.Tag, err) } if src.latestCalls != 1 { t.Fatalf("latestCalls = %d, want 1", src.latestCalls) @@ -178,9 +178,9 @@ func TestResolve_OverflowPageFallsBackToLatest(t *testing.T) { func TestResolve_OverflowPageStableNewerViaLatest(t *testing.T) { src := &fakeSource{list: manyRCReleases(), latest: Release{Tag: tagV0210}} - tag, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) - if err != nil || tag != tagV0210 { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) + if err != nil || rel.Tag != tagV0210 { + t.Fatalf("got %q, %v", rel.Tag, err) } if src.latestCalls != 1 { t.Fatalf("latestCalls = %d, want 1", src.latestCalls) @@ -200,11 +200,23 @@ func TestResolve_OverflowPageIgnoresPrereleaseLatest(t *testing.T) { list: manyRCReleases(), latest: Release{Tag: "v0.21.0-rc.1", Prerelease: true}, } - tag, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) - if err != nil || tag != tagV0200RC101 { - t.Fatalf("got %q, %v", tag, err) + rel, err := Resolve(context.Background(), src, ChannelRC, DefaultChannels) + if err != nil || rel.Tag != tagV0200RC101 { + t.Fatalf("got %q, %v", rel.Tag, err) } if src.latestCalls != 1 { t.Fatalf("latestCalls = %d, want 1", src.latestCalls) } } + +func TestResolve_ReturnsAssets(t *testing.T) { + asset := Asset{Name: "tool.tar.gz", URL: "https://dl.example/tool.tar.gz", Size: 1} + src := &fakeSource{list: []Release{ + {Tag: tagV0110RC3, Prerelease: true, Assets: []Asset{asset}}, + {Tag: tagV0100}, + }} + rel, err := Resolve(context.Background(), src, ChannelRC, nil) + if err != nil || rel.Tag != tagV0110RC3 || len(rel.Assets) != 1 || rel.Assets[0] != asset { + t.Fatalf("got %+v, %v", rel, err) + } +} diff --git a/checksum.go b/checksum.go new file mode 100644 index 0000000..8247dbf --- /dev/null +++ b/checksum.go @@ -0,0 +1,58 @@ +package selfupdate + +import ( + "bufio" + "encoding/hex" + "errors" + "fmt" + "io" + "strings" +) + +// ErrChecksumMismatch is wrapped when a downloaded asset's digest differs +// from the one listed in the checksum file. +var ErrChecksumMismatch = errors.New("selfupdate: checksum mismatch") + +// checksumFields is the field count of a well-formed line: digest and name. +const checksumFields = 2 + +// parseChecksums reads " " lines, as written by goreleaser +// and sha256sum, into a filename -> lowercase hex map. A leading "*" on +// the filename (GNU binary mode) is dropped. Blank lines are skipped. Any +// other shape is an error that names the line. +func parseChecksums(r io.Reader) (map[string]string, error) { + sums := make(map[string]string) + sc := bufio.NewScanner(r) + for line := 1; sc.Scan(); line++ { + text := strings.TrimSpace(sc.Text()) + if text == "" { + continue + } + fields := strings.Fields(text) + if len(fields) != checksumFields { + return nil, fmt.Errorf("selfupdate: checksum line %d: want %d fields, got %d", + line, checksumFields, len(fields)) + } + if _, err := hex.DecodeString(fields[0]); err != nil { + return nil, fmt.Errorf("selfupdate: checksum line %d: %w", line, err) + } + sums[strings.TrimPrefix(fields[1], "*")] = strings.ToLower(fields[0]) + } + if err := sc.Err(); err != nil { + return nil, fmt.Errorf("selfupdate: read checksums: %w", err) + } + return sums, nil +} + +// verifyChecksum compares sum against the entry for name. A missing entry +// is an error distinct from ErrChecksumMismatch. +func verifyChecksum(sums map[string]string, name string, sum []byte) error { + want, ok := sums[name] + if !ok { + return fmt.Errorf("selfupdate: no checksum listed for %s", name) + } + if got := hex.EncodeToString(sum); got != want { + return fmt.Errorf("%w for %s: want %s, got %s", ErrChecksumMismatch, name, want, got) + } + return nil +} diff --git a/checksum_test.go b/checksum_test.go new file mode 100644 index 0000000..b68e88a --- /dev/null +++ b/checksum_test.go @@ -0,0 +1,72 @@ +//nolint:testpackage // exercises unexported helpers +package selfupdate + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "strings" + "testing" +) + +const ( + linuxTarball = "tool_1.2.3_linux_amd64.tar.gz" + darwinTarball = "tool_1.2.3_darwin_arm64.tar.gz" +) + +func TestParseChecksums_GoreleaserAndBinaryMode(t *testing.T) { + in := "0123abcd " + linuxTarball + "\n" + + "\n" + + "ABCD0123 *" + darwinTarball + "\r\n" + sums, err := parseChecksums(strings.NewReader(in)) + if err != nil { + t.Fatal(err) + } + if len(sums) != 2 { + t.Fatalf("got %d entries: %v", len(sums), sums) + } + if sums[linuxTarball] != "0123abcd" { + t.Errorf("two-space separator: %q", sums[linuxTarball]) + } + if sums[darwinTarball] != "abcd0123" { + t.Errorf("binary-mode marker or case folding: %v", sums) + } +} + +func TestParseChecksums_RejectsMalformedLines(t *testing.T) { + for _, in := range []string{"onlyonefield\n", "zz name\n", "0123 two words\n"} { + if _, err := parseChecksums(strings.NewReader(in)); err == nil { + t.Errorf("input %q must be rejected", in) + } + } +} + +func TestParseChecksums_Empty(t *testing.T) { + sums, err := parseChecksums(strings.NewReader("")) + if err != nil || len(sums) != 0 { + t.Fatalf("got %v, %v", sums, err) + } +} + +func TestVerifyChecksum(t *testing.T) { + sum := sha256.Sum256([]byte("hello")) + sums := map[string]string{linuxTarball: hex.EncodeToString(sum[:])} + + if err := verifyChecksum(sums, linuxTarball, sum[:]); err != nil { + t.Fatalf("match: %v", err) + } + + other := sha256.Sum256([]byte("tampered")) + err := verifyChecksum(sums, linuxTarball, other[:]) + if !errors.Is(err, ErrChecksumMismatch) { + t.Fatalf("mismatch: got %v", err) + } + if !strings.Contains(err.Error(), linuxTarball) { + t.Fatalf("mismatch error must name the asset: %v", err) + } + + err = verifyChecksum(sums, darwinTarball, sum[:]) + if err == nil || errors.Is(err, ErrChecksumMismatch) { + t.Fatalf("missing entry must be its own error, got %v", err) + } +} diff --git a/cobracmd/cobracmd.go b/cobracmd/cobracmd.go index 1c7a1e0..0d53e79 100644 --- a/cobracmd/cobracmd.go +++ b/cobracmd/cobracmd.go @@ -6,7 +6,7 @@ import ( "context" "fmt" - "github.com/sentiolabs/go-selfupdate" + "github.com/sentiolabs/selfupdate-go" "github.com/spf13/cobra" ) diff --git a/cobracmd/cobracmd_test.go b/cobracmd/cobracmd_test.go index cd0345e..6898d70 100644 --- a/cobracmd/cobracmd_test.go +++ b/cobracmd/cobracmd_test.go @@ -6,8 +6,8 @@ import ( "strings" "testing" - "github.com/sentiolabs/go-selfupdate" - "github.com/sentiolabs/go-selfupdate/cobracmd" + "github.com/sentiolabs/selfupdate-go" + "github.com/sentiolabs/selfupdate-go/cobracmd" "github.com/spf13/cobra" ) diff --git a/extract.go b/extract.go new file mode 100644 index 0000000..3fcb951 --- /dev/null +++ b/extract.go @@ -0,0 +1,50 @@ +package selfupdate + +import ( + "archive/tar" + "compress/gzip" + "errors" + "fmt" + "io" + "path" +) + +// ErrEntryNotFound is wrapped when the archive has no entry with the +// requested name. +var ErrEntryNotFound = errors.New("selfupdate: entry not found in archive") + +// extractFile copies the tar.gz entry whose cleaned path equals name to +// dst. Both "tool" and "./tool" match "tool"; "bin/tool" does not. Only +// regular files match, so a directory or link with the same name is an +// error. Nothing but dst is ever written, so archive paths never touch +// the filesystem. +func extractFile(archive io.Reader, name string, dst io.Writer) error { + gz, err := gzip.NewReader(archive) + if err != nil { + return fmt.Errorf("selfupdate: open gzip: %w", err) + } + defer func() { _ = gz.Close() }() + + tr := tar.NewReader(gz) + for { + hdr, err := tr.Next() + if errors.Is(err, io.EOF) { + return fmt.Errorf("%w: %s", ErrEntryNotFound, name) + } + if err != nil { + return fmt.Errorf("selfupdate: read tar: %w", err) + } + if path.Clean(hdr.Name) != name { + continue + } + if hdr.Typeflag != tar.TypeReg { + return fmt.Errorf("selfupdate: archive entry %s is not a regular file", name) + } + // The asset was checksum-verified before extraction and a release + // binary is bounded by its asset size, so no decompression cap. + if _, err := io.Copy(dst, tr); err != nil { //nolint:gosec // G110: see comment above + return fmt.Errorf("selfupdate: extract %s: %w", name, err) + } + return nil + } +} diff --git a/extract_test.go b/extract_test.go new file mode 100644 index 0000000..29853f6 --- /dev/null +++ b/extract_test.go @@ -0,0 +1,104 @@ +//nolint:testpackage // exercises unexported helpers +package selfupdate + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "errors" + "strings" + "testing" +) + +// tarEntry is one file in a test archive. +type tarEntry struct { + name string + body string + typ byte // 0 means tar.TypeReg +} + +// tarGz builds a gzip'd tar with the given entries in order. +func tarGz(t *testing.T, entries ...tarEntry) []byte { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for _, e := range entries { + typ := e.typ + if typ == 0 { + typ = tar.TypeReg + } + hdr := &tar.Header{Name: e.name, Mode: 0o755, Size: int64(len(e.body)), Typeflag: typ} + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if _, err := tw.Write([]byte(e.body)); err != nil { + t.Fatal(err) + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +const binaryBody = "#!/bin/sh\necho tool\n" + +func TestExtractFile_ExtractsNamedEntry(t *testing.T) { + archive := tarGz(t, tarEntry{name: "README.md", body: "docs"}, tarEntry{name: "tool", body: binaryBody}) + var out bytes.Buffer + if err := extractFile(bytes.NewReader(archive), "tool", &out); err != nil { + t.Fatal(err) + } + if out.String() != binaryBody { + t.Fatalf("got %q", out.String()) + } +} + +func TestExtractFile_MatchesDotSlashPrefix(t *testing.T) { + archive := tarGz(t, tarEntry{name: "./tool", body: binaryBody}) + var out bytes.Buffer + if err := extractFile(bytes.NewReader(archive), "tool", &out); err != nil { + t.Fatal(err) + } + if out.String() != binaryBody { + t.Fatalf("got %q", out.String()) + } +} + +func TestExtractFile_NestedEntryDoesNotMatch(t *testing.T) { + archive := tarGz(t, tarEntry{name: "bin/tool", body: binaryBody}) + err := extractFile(bytes.NewReader(archive), "tool", &bytes.Buffer{}) + if !errors.Is(err, ErrEntryNotFound) { + t.Fatalf("got %v", err) + } +} + +func TestExtractFile_MissingEntry(t *testing.T) { + archive := tarGz(t, tarEntry{name: "README.md", body: "docs"}) + var out bytes.Buffer + err := extractFile(bytes.NewReader(archive), "tool", &out) + if !errors.Is(err, ErrEntryNotFound) || !strings.Contains(err.Error(), "tool") { + t.Fatalf("got %v", err) + } + if out.Len() != 0 { + t.Fatal("nothing may be written when the entry is missing") + } +} + +func TestExtractFile_RejectsNonRegularEntry(t *testing.T) { + archive := tarGz(t, tarEntry{name: "tool", typ: tar.TypeDir}) + err := extractFile(bytes.NewReader(archive), "tool", &bytes.Buffer{}) + if err == nil || errors.Is(err, ErrEntryNotFound) { + t.Fatalf("a directory named like the binary must be its own error, got %v", err) + } +} + +func TestExtractFile_NotGzip(t *testing.T) { + if err := extractFile(strings.NewReader("plain text"), "tool", &bytes.Buffer{}); err == nil { + t.Fatal("expected gzip error") + } +} diff --git a/go.mod b/go.mod index 0c0436f..306497e 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/sentiolabs/go-selfupdate +module github.com/sentiolabs/selfupdate-go go 1.26.0 diff --git a/installer.go b/installer.go index d3e12c8..415160d 100644 --- a/installer.go +++ b/installer.go @@ -11,21 +11,33 @@ import ( "time" ) -// Installer replaces the running binary with the given release tag. +// Installer replaces the running binary in two phases so that a consumer's +// PreInstall hook runs only after the new binary is downloaded and verified. type Installer interface { - Install(ctx context.Context, tag string) error + // Prepare fetches and verifies rel without touching the running binary. + Prepare(ctx context.Context, rel Release) (Staged, error) +} + +// Staged is a verified update waiting to be applied. +type Staged interface { + // Commit replaces the running binary. It is called at most once. + Commit(ctx context.Context) error + // Close removes any temporary files. It is safe after Commit and after + // a failed Commit. + Close() error } // safeTag is the only shape of tag ScriptInstaller will place on a command // line: a release tag with no shell metacharacters. var safeTag = regexp.MustCompile(`^v?[0-9A-Za-z][0-9A-Za-z.+-]*$`) -// pipelineWaitDelay bounds how long Install waits for the process group to +// pipelineWaitDelay bounds how long run waits for the process group to // exit after a SIGTERM before Go escalates to SIGKILL on the direct child. const pipelineWaitDelay = 5 * time.Second // ScriptInstaller runs `curl -fsSL | bash -s -- --force --tag=` -// with the process's stdio attached. Both arc and envctl install this way. +// with the process's stdio attached when its staged update is committed. Both +// arc and envctl install this way. type ScriptInstaller struct { ScriptURL string Stdout io.Writer // default os.Stdout @@ -59,16 +71,34 @@ func stdinIsTerminal(r io.Reader) bool { return info.Mode()&os.ModeCharDevice != 0 } -// Install runs the install script for tag. It runs under pipefail so a -// curl failure fails the pipeline instead of exiting 0 on empty stdin. -// With a terminal on stdin, the pipeline shares the CLI's process group. -// That keeps prompts such as sudo working and lets Ctrl-C reach every -// process. Without a terminal, cancelling ctx stops the whole pipeline. -func (s *ScriptInstaller) Install(ctx context.Context, tag string) error { - line, err := s.command(tag) +// scriptStaged is a validated command line waiting to run. +type scriptStaged struct { + installer *ScriptInstaller + line string +} + +// Prepare validates rel.Tag and builds the shell line. It runs nothing. +func (s *ScriptInstaller) Prepare(_ context.Context, rel Release) (Staged, error) { + line, err := s.command(rel.Tag) if err != nil { - return err + return nil, err } + return &scriptStaged{installer: s, line: line}, nil +} + +// Commit runs the install script pipeline. +func (st *scriptStaged) Commit(ctx context.Context) error { + return st.installer.run(ctx, st.line) +} + +// Close is a no-op: the script installer stages nothing on disk. +func (*scriptStaged) Close() error { return nil } + +// run executes line under pipefail so a curl failure fails the pipeline +// instead of exiting 0 on empty stdin. With a terminal on stdin, the +// pipeline shares the CLI's process group so sudo prompts and Ctrl-C +// work. Without a terminal, cancelling ctx stops the whole pipeline. +func (s *ScriptInstaller) run(ctx context.Context, line string) error { stdin := s.Stdin if stdin == nil { stdin = os.Stdin diff --git a/installer_test.go b/installer_test.go index cd98a28..8452a80 100644 --- a/installer_test.go +++ b/installer_test.go @@ -13,6 +13,22 @@ import ( "time" ) +// --- Contract assertions --- +var ( + _ Installer = (*ScriptInstaller)(nil) + _ Staged = (*scriptStaged)(nil) +) + +// installScript prepares and commits tag through s, mirroring Updater.Update. +func installScript(ctx context.Context, s *ScriptInstaller, tag string) error { + staged, err := s.Prepare(ctx, Release{Tag: tag}) + if err != nil { + return err + } + defer func() { _ = staged.Close() }() + return staged.Commit(ctx) +} + // requireCurlAndBash skips the test when either tool is missing from PATH. func requireCurlAndBash(t *testing.T) { t.Helper() @@ -42,8 +58,8 @@ func TestScriptInstaller_RejectsUnsafeTag(t *testing.T) { if _, err := s.command(bad); err == nil { t.Errorf("tag %q must be rejected", bad) } - if err := s.Install(context.Background(), bad); err == nil { - t.Errorf("Install with tag %q must fail before running anything", bad) + if err := installScript(context.Background(), s, bad); err == nil { + t.Errorf("Prepare with tag %q must fail before running anything", bad) } } } @@ -59,7 +75,7 @@ func TestScriptInstaller_RunsScriptViaFileURL(t *testing.T) { } var out bytes.Buffer s := &ScriptInstaller{ScriptURL: "file://" + script, Stdout: &out, Stderr: &out} - if err := s.Install(context.Background(), "v9.9.9"); err != nil { + if err := installScript(context.Background(), s, "v9.9.9"); err != nil { t.Fatalf("install: %v, output: %s", err, out.String()) } if !strings.Contains(out.String(), "args: --force --tag=v9.9.9") { @@ -73,7 +89,7 @@ func TestScriptInstaller_CurlFailureIsError(t *testing.T) { missing := filepath.Join(dir, "does-not-exist.sh") var out bytes.Buffer s := &ScriptInstaller{ScriptURL: "file://" + missing, Stdout: &out, Stderr: &out} - if err := s.Install(context.Background(), "v1.0.0"); err == nil { + if err := installScript(context.Background(), s, "v1.0.0"); err == nil { t.Fatalf("expected error when curl fails, got nil, output: %s", out.String()) } } @@ -97,7 +113,7 @@ func TestScriptInstaller_CancelStopsPipeline(t *testing.T) { errCh := make(chan error, 1) go func() { - errCh <- s.Install(ctx, "v1.0.0") + errCh <- installScript(ctx, s, "v1.0.0") }() time.Sleep(200 * time.Millisecond) @@ -153,7 +169,29 @@ func TestScriptInstaller_NonZeroExitIsError(t *testing.T) { } var out bytes.Buffer s := &ScriptInstaller{ScriptURL: "file://" + script, Stdout: &out, Stderr: &out} - if err := s.Install(context.Background(), "v1.0.0"); err == nil { + if err := installScript(context.Background(), s, "v1.0.0"); err == nil { t.Fatal("expected error from exit 3") } } + +func TestScriptInstaller_PrepareRunsNothing(t *testing.T) { + dir := t.TempDir() + marker := filepath.Join(dir, "ran") + script := filepath.Join(dir, "install.sh") + body := "#!/usr/bin/env bash\ntouch " + marker + "\n" + if err := os.WriteFile(script, []byte(body), 0o700); err != nil { //nolint:gosec // script must be executable + t.Fatal(err) + } + var out bytes.Buffer + s := &ScriptInstaller{ScriptURL: "file://" + script, Stdout: &out, Stderr: &out} + staged, err := s.Prepare(context.Background(), Release{Tag: tagV100}) + if err != nil { + t.Fatal(err) + } + if _, statErr := os.Stat(marker); statErr == nil { + t.Fatal("Prepare must not run the script") + } + if err := staged.Close(); err != nil { + t.Fatal(err) + } +} diff --git a/managed.go b/managed.go new file mode 100644 index 0000000..cdc3940 --- /dev/null +++ b/managed.go @@ -0,0 +1,65 @@ +package selfupdate + +import ( + "errors" + "fmt" + "regexp" + "strings" +) + +// ManagedInstall describes a location owned by a package manager. Replacing +// a binary there would desynchronize the manager's file list, and its next +// upgrade would silently revert the binary. +type ManagedInstall struct { + Pattern *regexp.Regexp // matched against the resolved target path + Manager string // "Homebrew", "dpkg/rpm", "Nix" + 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. +var DefaultManagedInstalls = []ManagedInstall{ + { + Pattern: regexp.MustCompile(`/Cellar/`), + Manager: "Homebrew", + Hint: "brew upgrade {name}", + }, + { + Pattern: regexp.MustCompile(`^/usr/(bin|lib)/`), + Manager: "dpkg/rpm", + Hint: "upgrade {name} with your system package manager (apt, dnf, pacman)", + }, + { + Pattern: regexp.MustCompile(`^/nix/store/`), + Manager: "Nix", + Hint: "nix profile upgrade {name}", + }, +} + +// ErrManagedInstall is the sentinel wrapped when the target is managed. +var ErrManagedInstall = errors.New("selfupdate: binary is managed by a package manager") + +// detectManaged returns the first entry in list whose Pattern matches +// target, or false. A nil list means DefaultManagedInstalls; an empty +// non-nil list disables detection. +func detectManaged(target string, list []ManagedInstall) (ManagedInstall, bool) { + if list == nil { + list = DefaultManagedInstalls + } + for _, m := range list { + if m.Pattern != nil && m.Pattern.MatchString(target) { + return m, true + } + } + return ManagedInstall{}, false +} + +// managedError builds the error returned when detectManaged matches. target +// must be the same resolved path that was passed to detectManaged, so the +// message names the file the check examined. +func managedError(m ManagedInstall, name, target string) error { + hint := strings.ReplaceAll(m.Hint, "{name}", name) + return fmt.Errorf("%w: %s is installed by %s at %s; run '%s' instead", + ErrManagedInstall, name, m.Manager, target, hint) +} diff --git a/managed_test.go b/managed_test.go new file mode 100644 index 0000000..1111045 --- /dev/null +++ b/managed_test.go @@ -0,0 +1,76 @@ +//nolint:testpackage // exercises unexported helpers +package selfupdate + +import ( + "errors" + "regexp" + "strings" + "testing" +) + +// managerHomebrew names the literal repeated across the fixtures below so +// its reuse doesn't trip goconst. +const managerHomebrew = "Homebrew" + +func TestDetectManaged_Defaults(t *testing.T) { + cases := []struct { + path string + manager string // "" means not managed + }{ + {"/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"}, + {"/nix/store/abc123-arc-0.15.0/bin/arc", "Nix"}, + {"/usr/local/bin/arc", ""}, + {"/home/u/.local/bin/arc", ""}, + {"/home/u/go/bin/arc", ""}, + {"/opt/arc/bin/arc", ""}, + } + for _, tc := range cases { + m, ok := detectManaged(tc.path, nil) + if ok != (tc.manager != "") || m.Manager != tc.manager { + t.Errorf("%s: got (%q, %v), want manager %q", tc.path, m.Manager, ok, tc.manager) + } + } +} + +func TestDetectManaged_EmptyListDisables(t *testing.T) { + if _, ok := detectManaged("/usr/bin/arc", []ManagedInstall{}); ok { + t.Fatal("an empty non-nil list must disable detection") + } +} + +func TestDetectManaged_CustomList(t *testing.T) { + list := []ManagedInstall{{ + Pattern: regexp.MustCompile(`^/opt/corp/`), + Manager: "corp-pkg", + Hint: "corp-pkg upgrade {name}", + }} + m, ok := detectManaged("/opt/corp/bin/arc", list) + if !ok || m.Manager != "corp-pkg" { + t.Fatalf("got (%+v, %v)", m, ok) + } + if _, ok := detectManaged("/usr/bin/arc", list); ok { + t.Fatal("a custom list replaces the defaults, it does not extend them") + } +} + +func TestManagedError(t *testing.T) { + m, ok := detectManaged("/opt/homebrew/Cellar/arc/0.15.0/bin/arc", nil) + if !ok { + t.Fatal("expected Homebrew match") + } + err := managedError(m, "arc", "/opt/homebrew/Cellar/arc/0.15.0/bin/arc") + if !errors.Is(err, ErrManagedInstall) { + t.Fatalf("must wrap ErrManagedInstall: %v", err) + } + for _, want := range []string{managerHomebrew, "brew upgrade arc", "/opt/homebrew/Cellar/arc/0.15.0/bin/arc"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("message %q must contain %q", err.Error(), want) + } + } + if strings.Contains(err.Error(), "{name}") { + t.Error("placeholder was not substituted") + } +} diff --git a/progress.go b/progress.go new file mode 100644 index 0000000..de73376 --- /dev/null +++ b/progress.go @@ -0,0 +1,93 @@ +package selfupdate + +import ( + "fmt" + "io" + "os" + "strings" +) + +// progressBarWidth is the number of cells in the terminal progress bar. +const progressBarWidth = 30 + +// percentScale converts a fraction to a percentage. +const percentScale = 100 + +// bytesPerMB converts byte counts for display. +const bytesPerMB = 1024 * 1024 + +// progressWriter counts bytes written and, when its output is a terminal +// and the total is known, rewrites one line with a bar and percentage. +// Otherwise it prints nothing, so callers print the single +// "Downloading..." line themselves. +type progressWriter struct { + out io.Writer + total int64 // <= 0 when Content-Length is unknown + n int64 + tty bool + last int // last percentage drawn; -1 before the first draw +} + +// newProgressWriter returns a writer that draws to out only when out is a +// terminal and total is known. +func newProgressWriter(out io.Writer, total int64) *progressWriter { + return &progressWriter{out: out, total: total, tty: isTerminal(out), last: -1} +} + +// Write counts b and redraws the bar when the percentage changed. +func (p *progressWriter) Write(b []byte) (int, error) { + p.n += int64(len(b)) + p.draw() + return len(b), nil +} + +// Finish ends the line on a terminal. It is a no-op otherwise. +func (p *progressWriter) Finish() { + if !p.drawing() { + return + } + p.draw() + _, _ = fmt.Fprintln(p.out) +} + +// drawing reports whether there is a terminal and a known total to draw for. +func (p *progressWriter) drawing() bool { + return p.tty && p.total > 0 +} + +func (p *progressWriter) draw() { + if !p.drawing() { + return + } + pct := min(int(p.n*percentScale/p.total), percentScale) + if pct == p.last { + return + } + p.last = pct + filled := pct * progressBarWidth / percentScale + bar := strings.Repeat("=", filled) + if filled > 0 && filled < progressBarWidth { + bar = bar[:filled-1] + ">" + } + bar += strings.Repeat(" ", progressBarWidth-filled) + _, _ = fmt.Fprintf(p.out, "\r[%s] %3d%% %s/%s", bar, pct, formatMB(p.n), formatMB(p.total)) +} + +// formatMB renders n as megabytes with one decimal. +func formatMB(n int64) string { + return fmt.Sprintf("%.1f MB", float64(n)/bytesPerMB) +} + +// isTerminal reports whether w is an *os.File attached to a character +// device. Buffers, pipes and regular files are not terminals. +func isTerminal(w io.Writer) bool { + f, ok := w.(*os.File) + if !ok || f == nil { + return false + } + info, err := f.Stat() + if err != nil { + return false + } + return info.Mode()&os.ModeCharDevice != 0 +} diff --git a/progress_test.go b/progress_test.go new file mode 100644 index 0000000..a2e517e --- /dev/null +++ b/progress_test.go @@ -0,0 +1,101 @@ +//nolint:testpackage // exercises unexported helpers and the tty flag +package selfupdate + +import ( + "bytes" + "os" + "strings" + "testing" +) + +func TestProgressWriter_NonTerminalIsSilent(t *testing.T) { + var out bytes.Buffer + const total = 100 + p := newProgressWriter(&out, total) + n, err := p.Write(make([]byte, 40)) + if err != nil || n != 40 { + t.Fatalf("Write: %d, %v", n, err) + } + p.Finish() + if out.Len() != 0 { + t.Fatalf("a buffer is not a terminal; got %q", out.String()) + } + if p.n != 40 { + t.Fatalf("counted %d bytes, want 40", p.n) + } +} + +func TestProgressWriter_UnknownTotalNeverDraws(t *testing.T) { + var out bytes.Buffer + p := newProgressWriter(&out, -1) + p.tty = true // force the terminal path; the unknown total must still win + _, _ = p.Write([]byte("data")) + p.Finish() + if out.Len() != 0 { + t.Fatalf("got %q", out.String()) + } +} + +func TestProgressWriter_TerminalDrawsBar(t *testing.T) { + var out bytes.Buffer + const total = 100 + p := &progressWriter{out: &out, total: total, tty: true, last: -1} + _, _ = p.Write(make([]byte, 45)) + first := out.String() + if !strings.HasPrefix(first, "\r[") || !strings.Contains(first, " 45%") || !strings.Contains(first, ">") { + t.Fatalf("first draw: %q", first) + } + out.Reset() + _, _ = p.Write(nil) // same percentage: no redraw + if out.Len() != 0 { + t.Fatalf("redrew without a percentage change: %q", out.String()) + } + _, _ = p.Write(make([]byte, 55)) + p.Finish() + end := out.String() + if !strings.Contains(end, "100%") || !strings.HasSuffix(end, "\n") { + t.Fatalf("final draw: %q", end) + } + if strings.Contains(end, ">") { + t.Fatalf("a full bar has no head marker: %q", end) + } +} + +func TestProgressWriter_ClampsOver100(t *testing.T) { + var out bytes.Buffer + const total = 10 + p := &progressWriter{out: &out, total: total, tty: true, last: -1} + _, _ = p.Write(make([]byte, 25)) + if !strings.Contains(out.String(), "100%") { + t.Fatalf("got %q", out.String()) + } +} + +func TestFormatMB(t *testing.T) { + const twelvePointThree = 12*1024*1024 + 300*1024 + if got := formatMB(twelvePointThree); got != "12.3 MB" { + t.Fatalf("got %q", got) + } + if got := formatMB(0); got != "0.0 MB" { + t.Fatalf("got %q", got) + } +} + +func TestIsTerminal(t *testing.T) { + if isTerminal(&bytes.Buffer{}) { + t.Error("a buffer must not be a terminal") + } + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer func() { _ = r.Close() }() + defer func() { _ = w.Close() }() + if isTerminal(w) { + t.Error("the write end of a pipe must not be a terminal") + } + var nilFile *os.File + if isTerminal(nilFile) { + t.Error("a nil *os.File must not be a terminal") + } +} diff --git a/replace.go b/replace.go new file mode 100644 index 0000000..a64a2e7 --- /dev/null +++ b/replace.go @@ -0,0 +1,100 @@ +package selfupdate + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" +) + +// ErrTargetNotWritable is wrapped when the directory holding the running +// binary refuses a new file. +var ErrTargetNotWritable = errors.New("selfupdate: target directory is not writable") + +// 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. +func preflightWritable(dir string) error { + f, err := os.CreateTemp(dir, ".selfupdate-preflight-*") + if err != nil { + if errors.Is(err, os.ErrPermission) { + return fmt.Errorf("%w: %s", ErrTargetNotWritable, dir) + } + return fmt.Errorf("selfupdate: probe %s: %w", dir, err) + } + name := f.Name() + _ = f.Close() + 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. +func replaceFile(target string, src io.Reader, mode os.FileMode) error { + newPath, oldPath := target+".new", target+".old" + 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 +} + +// writeFile streams src into path with mode, removing the file on failure. +// The mode is applied with Chmod after creation so the process umask cannot +// narrow it. +func writeFile(path string, src io.Reader, mode os.FileMode) error { + f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) + if err != nil { + if errors.Is(err, os.ErrPermission) { + return fmt.Errorf("%w: %s", ErrTargetNotWritable, filepath.Dir(path)) + } + return fmt.Errorf("selfupdate: create %s: %w", path, err) + } + if err := f.Chmod(mode); err != nil { + _ = f.Close() + _ = os.Remove(path) + return fmt.Errorf("selfupdate: set mode on %s: %w", path, err) + } + if _, err := io.Copy(f, src); err != nil { + _ = f.Close() + _ = os.Remove(path) + return fmt.Errorf("selfupdate: write %s: %w", path, err) + } + if err := f.Close(); err != nil { + _ = os.Remove(path) + return fmt.Errorf("selfupdate: close %s: %w", path, err) + } + return nil +} diff --git a/replace_test.go b/replace_test.go new file mode 100644 index 0000000..f23c051 --- /dev/null +++ b/replace_test.go @@ -0,0 +1,260 @@ +//nolint:testpackage // exercises unexported helpers and swaps renameFile +package selfupdate + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// Fixture contents for the binary before and after an update. +const ( + contentOld = "old" + contentNew = "new" +) + +// writeTarget writes an executable fixture named tool in a temp dir. +func writeTarget(t *testing.T, content string) string { + t.Helper() + target := filepath.Join(t.TempDir(), "tool") + if err := os.WriteFile(target, []byte(content), 0o755); err != nil { //nolint:gosec // executable fixture + t.Fatal(err) + } + return target +} + +// swapRename replaces renameFile for the test and restores it afterwards. +func swapRename(t *testing.T, fn func(from, to string) error) { + t.Helper() + orig := renameFile + renameFile = fn + t.Cleanup(func() { renameFile = orig }) +} + +func assertNoLeftovers(t *testing.T, target string) { + t.Helper() + for _, leftover := range []string{target + ".new", target + ".old"} { + if _, err := os.Stat(leftover); !errors.Is(err, os.ErrNotExist) { + t.Errorf("%s must not exist after replaceFile (stat err %v)", leftover, err) + } + } +} + +func readTarget(t *testing.T, target string) string { + t.Helper() + got, err := os.ReadFile(target) + if err != nil { + t.Fatal(err) + } + return string(got) +} + +func TestReplaceFile_ReplacesAndCleansUp(t *testing.T) { + target := writeTarget(t, contentOld) + if err := replaceFile(target, strings.NewReader(contentNew), 0o755); err != nil { + t.Fatal(err) + } + if got := readTarget(t, target); got != contentNew { + t.Fatalf("content %q", got) + } + info, err := os.Stat(target) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o755 { + t.Fatalf("mode %v, want 0755", info.Mode().Perm()) + } + assertNoLeftovers(t, target) +} + +func TestReplaceFile_FinalRenameFailureRestoresOriginal(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) + }) + 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 got := readTarget(t, target); got != contentOld { + t.Fatalf("original not restored: %q", got) + } + assertNoLeftovers(t, target) +} + +func TestReplaceFile_RollbackFailureIsRollbackError(t *testing.T) { + target := writeTarget(t, contentOld) + swapRename(t, func(from, to string) error { + if to == target { + return errors.New("simulated: nothing may land on target") + } + 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 !strings.Contains(err.Error(), "rollback failed") { + t.Fatalf("message must say rollback failed: %v", err) + } +} + +func TestPreflightWritable_LeavesNoProbe(t *testing.T) { + dir := t.TempDir() + if err := preflightWritable(dir); err != nil { + t.Fatal(err) + } + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatalf("probe file left behind: %v", entries) + } +} + +func TestPreflightWritable_PermissionDenied(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + ro := filepath.Join(t.TempDir(), "ro") + if err := os.Mkdir(ro, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(ro, 0o700) }) + err := preflightWritable(ro) + if !errors.Is(err, ErrTargetNotWritable) { + t.Fatalf("got %v", err) + } + if !strings.Contains(err.Error(), ro) { + t.Fatalf("message must name the directory: %v", err) + } +} + +func TestPreflightWritable_MissingDir(t *testing.T) { + err := preflightWritable(filepath.Join(t.TempDir(), "missing")) + if err == nil || errors.Is(err, ErrTargetNotWritable) { + t.Fatalf("a missing directory is not a permission problem: %v", err) + } +} + +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 } + +func (r *failingReader) Read(p []byte) (int, error) { + if r.n > 0 { + r.n-- + p[0] = 'x' + return 1, nil + } + return 0, errors.New("simulated read failure") +} + +func TestReplaceFile_SourceReadFailureLeavesOriginal(t *testing.T) { + target := writeTarget(t, contentOld) + err := replaceFile(target, &failingReader{n: 3}, 0o755) + if err == nil || !strings.Contains(err.Error(), "write") { + t.Fatalf("got %v", err) + } + if got := readTarget(t, target); got != contentOld { + t.Fatalf("original changed: %q", got) + } + assertNoLeftovers(t, target) +} + +func TestReplaceFile_UnwritableDirWrapsSentinel(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions") + } + target := writeTarget(t, contentOld) + dir := filepath.Dir(target) + if err := os.Chmod(dir, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) + err := replaceFile(target, strings.NewReader(contentNew), 0o755) + if !errors.Is(err, ErrTargetNotWritable) { + t.Fatalf("got %v", err) + } + if !strings.Contains(err.Error(), dir) { + t.Fatalf("message must name the directory: %v", err) + } +} + +func TestReplaceFile_CreateFailureIsNotSentinel(t *testing.T) { + target := writeTarget(t, contentOld) + if err := os.Mkdir(target+".new", 0o755); err != nil { + t.Fatal(err) + } + err := replaceFile(target, strings.NewReader(contentNew), 0o755) + if err == nil || !strings.Contains(err.Error(), "create ") { + t.Fatalf("got %v", err) + } + if errors.Is(err, ErrTargetNotWritable) { + t.Fatalf("a directory in the way is not a permission problem: %v", err) + } + if got := readTarget(t, target); got != contentOld { + 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) + } +} diff --git a/replace_unix_test.go b/replace_unix_test.go new file mode 100644 index 0000000..470b9f0 --- /dev/null +++ b/replace_unix_test.go @@ -0,0 +1,30 @@ +//go:build unix + +//nolint:testpackage // exercises unexported replaceFile +package selfupdate + +import ( + "os" + "strings" + "syscall" + "testing" +) + +// TestReplaceFile_ModeIgnoresUmask pins the requested mode even when the +// process umask would strip group and other bits from a freshly created +// file. Package tests are not parallel, so the umask swap is safe. +func TestReplaceFile_ModeIgnoresUmask(t *testing.T) { + old := syscall.Umask(0o077) + t.Cleanup(func() { syscall.Umask(old) }) + target := writeTarget(t, contentOld) + if err := replaceFile(target, strings.NewReader(contentNew), 0o755); err != nil { + t.Fatal(err) + } + info, err := os.Stat(target) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o755 { + t.Fatalf("mode %v, want 0755 regardless of umask", info.Mode().Perm()) + } +} diff --git a/selfupdate.go b/selfupdate.go index acff5a0..40188f8 100644 --- a/selfupdate.go +++ b/selfupdate.go @@ -24,8 +24,12 @@ type Updater struct { Out io.Writer // nil means os.Stdout ErrOut io.Writer // nil means os.Stderr In io.Reader // nil means os.Stdin - // PreInstall runs after the user confirms and before Installer.Install. + // PreInstall runs after the user confirms and after Installer.Prepare has + // downloaded and verified the release, immediately before Staged.Commit. PreInstall func(ctx context.Context, current, latest string) error + // PostInstall runs after Staged.Commit succeeds. Its error is reported + // with a note that the binary was already replaced. + PostInstall func(ctx context.Context, current, latest string) error } // UpdateOptions controls Update. @@ -38,7 +42,8 @@ type UpdateOptions struct { // CheckResult is what Check found. type CheckResult struct { Current string - Latest string + Latest string // Release.Tag, kept for callers that only print + Release Release Channel Channel Cmp int // Compare(Current, Latest): 0 same, >0 update available, <0 current is newer } @@ -93,21 +98,23 @@ func (u *Updater) Check(ctx context.Context) (CheckResult, error) { if err != nil { return CheckResult{}, err } - latest, err := Resolve(ctx, u.Source, ch, u.channels()) + rel, err := Resolve(ctx, u.Source, ch, u.channels()) if err != nil { return CheckResult{}, err } return CheckResult{ Current: NormalizeVersion(u.Version), - Latest: latest, + Latest: rel.Tag, + Release: rel, Channel: ch, - Cmp: Compare(u.Version, latest), + Cmp: Compare(u.Version, rel.Tag), }, nil } // Update checks for a newer release on the current channel and, unless -// opts.Check, installs it after confirmation. PreInstall runs between the -// confirmation and the install. +// opts.Check, installs it after confirmation. The installer prepares the +// release first, then PreInstall runs, then the staged update is committed, +// then PostInstall runs. // //nolint:revive // CLI output writes always succeed func (u *Updater) Update(ctx context.Context, opts UpdateOptions) error { @@ -147,12 +154,31 @@ func (u *Updater) Update(ctx context.Context, opts UpdateOptions) error { if u.Installer == nil { return ErrNoInstaller } + return u.install(ctx, res) +} + +// install runs Prepare, PreInstall, Commit and PostInstall in that order. +// Each step runs only when every earlier step succeeded. +func (u *Updater) install(ctx context.Context, res CheckResult) error { + staged, err := u.Installer.Prepare(ctx, res.Release) + if err != nil { + return fmt.Errorf("prepare update: %w", err) + } + defer func() { _ = staged.Close() }() if u.PreInstall != nil { if err := u.PreInstall(ctx, res.Current, res.Latest); err != nil { return fmt.Errorf("pre-install step failed: %w", err) } } - return u.Installer.Install(ctx, res.Latest) + if err := staged.Commit(ctx); err != nil { + return fmt.Errorf("install update: %w", err) + } + if u.PostInstall != nil { + if err := u.PostInstall(ctx, res.Current, res.Latest); err != nil { + return fmt.Errorf("post-install step failed (binary was updated): %w", err) + } + } + return nil } // SwitchChannel validates channel against the configured specs, shows the diff --git a/selfupdate_test.go b/selfupdate_test.go index 5ee059a..2f3645c 100644 --- a/selfupdate_test.go +++ b/selfupdate_test.go @@ -31,6 +31,7 @@ func TestContracts(t *testing.T) { r := Release{} var _ string = r.Tag var _ bool = r.Prerelease + var _ []Asset = r.Assets u := Updater{} var _ string = u.Name @@ -48,6 +49,16 @@ func TestContracts(t *testing.T) { c := CheckResult{} var _ int = c.Cmp var _ Channel = c.Channel + var _ Release = c.Release + var _ string = c.Latest + + a := Asset{} + var _ string = a.Name + var _ string = a.URL + var _ int64 = a.Size + + var _ func(context.Context, string, string) error = u.PreInstall + var _ func(context.Context, string, string) error = u.PostInstall if len(DefaultChannels) != 3 { t.Fatalf("DefaultChannels: want 3, got %d", len(DefaultChannels)) @@ -91,14 +102,37 @@ func TestDefaultPatterns(t *testing.T) { // already cover "v1.0.0" and "v0.10.0". const tagV200 = "v2.0.0" +// recordingInstaller records Prepare and Commit calls. prepareErr fails +// Prepare; commitErr fails Commit. type recordingInstaller struct { - tags []string - err error + prepared []string + committed []string + closed int + prepareErr error + commitErr error +} + +func (r *recordingInstaller) Prepare(_ context.Context, rel Release) (Staged, error) { + r.prepared = append(r.prepared, rel.Tag) + if r.prepareErr != nil { + return nil, r.prepareErr + } + return &recordingStaged{installer: r, tag: rel.Tag}, nil +} + +type recordingStaged struct { + installer *recordingInstaller + tag string } -func (r *recordingInstaller) Install(_ context.Context, tag string) error { - r.tags = append(r.tags, tag) - return r.err +func (s *recordingStaged) Commit(context.Context) error { + s.installer.committed = append(s.installer.committed, s.tag) + return s.installer.commitErr +} + +func (s *recordingStaged) Close() error { + s.installer.closed++ + return nil } func newTestUpdater(current string, src Source, store Store, in string, @@ -174,8 +208,8 @@ func checkLegacyRCTags(t *testing.T, latest string) { if err := u.Update(t.Context(), UpdateOptions{Yes: true}); err != nil { t.Fatal(err) } - if !hookCalled || len(inst.tags) != 1 || inst.tags[0] != latest { - t.Fatalf("hook called: %v, installed tags: %v", hookCalled, inst.tags) + if !hookCalled || len(inst.committed) != 1 || inst.committed[0] != latest { + t.Fatalf("hook called: %v, installed tags: %v", hookCalled, inst.committed) } if !strings.Contains(out.String(), legacyRC9+" -> "+latest) { t.Fatalf("output did not preserve tags: %s", out.String()) @@ -191,7 +225,7 @@ func TestUpdater_UpdateCheckOnlyPrintsAndDoesNotInstall(t *testing.T) { if !strings.Contains(out.String(), "Update available: v1.0.0 -> v2.0.0 (stable channel)") { t.Fatalf("output: %s", out.String()) } - if len(inst.tags) != 0 { + if len(inst.committed) != 0 { t.Fatal("check must not install") } } @@ -202,8 +236,8 @@ func TestUpdater_UpdateUpToDateInstallsNothing(t *testing.T) { if err := u.Update(context.Background(), UpdateOptions{}); err != nil { t.Fatal(err) } - if !strings.Contains(out.String(), "tool v1.0.0 (stable) is up to date") || len(inst.tags) != 0 { - t.Fatalf("output: %s, installs: %v", out.String(), inst.tags) + if !strings.Contains(out.String(), "tool v1.0.0 (stable) is up to date") || len(inst.committed) != 0 { + t.Fatalf("output: %s, installs: %v", out.String(), inst.committed) } } @@ -213,7 +247,7 @@ func TestUpdater_UpdateCurrentNewerInstallsNothing(t *testing.T) { if err := u.Update(context.Background(), UpdateOptions{}); err != nil { t.Fatal(err) } - if !strings.Contains(out.String(), "is newer than the latest stable release v1.0.0") || len(inst.tags) != 0 { + if !strings.Contains(out.String(), "is newer than the latest stable release v1.0.0") || len(inst.committed) != 0 { t.Fatalf("output: %s", out.String()) } } @@ -229,8 +263,8 @@ func TestUpdater_UpdateYesRunsPreInstallThenInstall(t *testing.T) { if err := u.Update(context.Background(), UpdateOptions{Yes: true}); err != nil { t.Fatal(err) } - if len(inst.tags) != 1 || inst.tags[0] != tagV200 { - t.Fatalf("installs: %v", inst.tags) + if len(inst.committed) != 1 || inst.committed[0] != tagV200 { + t.Fatalf("installs: %v", inst.committed) } if len(order) != 1 || order[0] != "pre:v1.0.0->v2.0.0" { t.Fatalf("PreInstall not called correctly: %v", order) @@ -244,8 +278,9 @@ func TestUpdater_UpdatePreInstallErrorStopsInstall(t *testing.T) { if err := u.Update(context.Background(), UpdateOptions{Yes: true}); err == nil { t.Fatal("expected error") } - if len(inst.tags) != 0 { - t.Fatal("install must not run after PreInstall fails") + if len(inst.prepared) != 1 || len(inst.committed) != 0 { + t.Fatalf("Prepare must run before PreInstall and Commit must not: prepared=%v committed=%v", + inst.prepared, inst.committed) } } @@ -256,8 +291,8 @@ func TestUpdater_UpdatePromptDeclined(t *testing.T) { t.Fatal(err) } if !strings.Contains(out.String(), "Continue? [y/N]") || - !strings.Contains(out.String(), "Update cancelled.") || len(inst.tags) != 0 { - t.Fatalf("output: %s, installs: %v", out.String(), inst.tags) + !strings.Contains(out.String(), "Update cancelled.") || len(inst.committed) != 0 { + t.Fatalf("output: %s, installs: %v", out.String(), inst.committed) } } @@ -267,8 +302,8 @@ func TestUpdater_UpdatePromptAccepted(t *testing.T) { if err := u.Update(context.Background(), UpdateOptions{}); err != nil { t.Fatal(err) } - if len(inst.tags) != 1 { - t.Fatalf("installs: %v", inst.tags) + if len(inst.committed) != 1 { + t.Fatalf("installs: %v", inst.committed) } } @@ -278,8 +313,8 @@ func TestUpdater_UpdateForceReinstallsWhenUpToDate(t *testing.T) { if err := u.Update(context.Background(), UpdateOptions{Force: true, Yes: true}); err != nil { t.Fatal(err) } - if len(inst.tags) != 1 || inst.tags[0] != tagV100 { - t.Fatalf("installs: %v", inst.tags) + if len(inst.committed) != 1 || inst.committed[0] != tagV100 { + t.Fatalf("installs: %v", inst.committed) } } @@ -390,3 +425,84 @@ func TestUpdater_SwitchChannelNoStore(t *testing.T) { t.Fatal("nil store must be an error") } } + +func TestUpdater_UpdatePrepareErrorSkipsPreInstall(t *testing.T) { + src := &fakeSource{latest: Release{Tag: tagV200}} + u, _, _, inst := newTestUpdater(tagV100, src, nil, "") + inst.prepareErr = errors.New("checksum mismatch") + var preRan bool + u.PreInstall = func(context.Context, string, string) error { + preRan = true + return nil + } + err := u.Update(context.Background(), UpdateOptions{Yes: true}) + if err == nil || !strings.Contains(err.Error(), "prepare update") { + t.Fatalf("got %v", err) + } + if preRan || len(inst.committed) != 0 { + t.Fatal("neither PreInstall nor Commit may run when Prepare fails") + } +} + +func TestUpdater_UpdateHookOrder(t *testing.T) { + src := &fakeSource{latest: Release{Tag: tagV200}} + u, _, _, inst := newTestUpdater(tagV100, src, nil, "") + var order []string + u.PreInstall = func(context.Context, string, string) error { + order = append(order, "pre") + if len(inst.prepared) != 1 || len(inst.committed) != 0 { + t.Error("PreInstall must run after Prepare and before Commit") + } + return nil + } + u.PostInstall = func(_ context.Context, current, latest string) error { + order = append(order, "post:"+current+"->"+latest) + if len(inst.committed) != 1 { + t.Error("PostInstall must run after Commit") + } + return nil + } + if err := u.Update(context.Background(), UpdateOptions{Yes: true}); err != nil { + t.Fatal(err) + } + if got := strings.Join(order, ","); got != "pre,post:v1.0.0->v2.0.0" { + t.Fatalf("order: %s", got) + } + if inst.closed != 1 { + t.Fatalf("Close calls = %d, want 1", inst.closed) + } +} + +func TestUpdater_UpdatePostInstallErrorSaysBinaryUpdated(t *testing.T) { + src := &fakeSource{latest: Release{Tag: tagV200}} + u, _, _, inst := newTestUpdater(tagV100, src, nil, "") + u.PostInstall = func(context.Context, string, string) error { return errors.New("server restart failed") } + err := u.Update(context.Background(), UpdateOptions{Yes: true}) + if err == nil || !strings.Contains(err.Error(), "binary was updated") { + t.Fatalf("got %v", err) + } + if len(inst.committed) != 1 { + t.Fatal("Commit must have run before PostInstall") + } +} + +func TestUpdater_UpdateCommitErrorSkipsPostInstall(t *testing.T) { + src := &fakeSource{latest: Release{Tag: tagV200}} + u, _, _, inst := newTestUpdater(tagV100, src, nil, "") + inst.commitErr = errors.New("rename failed") + var postRan bool + u.PostInstall = func(context.Context, string, string) error { + postRan = true + return nil + } + err := u.Update(context.Background(), UpdateOptions{Yes: true}) + if err == nil || !strings.Contains(err.Error(), "install update") { + t.Fatalf("got %v", err) + } + if postRan { + t.Fatal("PostInstall must not run when Commit fails") + } + if inst.closed != 1 { + t.Fatalf("Close calls = %d, want 1", inst.closed) + } +} diff --git a/sign_darwin.go b/sign_darwin.go new file mode 100644 index 0000000..19618d6 --- /dev/null +++ b/sign_darwin.go @@ -0,0 +1,20 @@ +//go:build darwin + +package selfupdate + +import ( + "fmt" + "os/exec" +) + +// signBinary applies an ad-hoc code signature so macOS runs a binary that +// arrived by download rather than through a signed installer. The Go +// linker already ad-hoc signs darwin/arm64 output, so this keeps parity +// with the install script rather than adding a new requirement. +func signBinary(path string) error { + out, err := exec.Command("codesign", "--force", "--sign", "-", path).CombinedOutput() //nolint:gosec // fixed program; path is the resolved target + if err != nil { + return fmt.Errorf("codesign: %w: %s", err, out) + } + return nil +} diff --git a/sign_other.go b/sign_other.go new file mode 100644 index 0000000..c5d3d7d --- /dev/null +++ b/sign_other.go @@ -0,0 +1,6 @@ +//go:build !darwin + +package selfupdate + +// signBinary is a no-op outside macOS. +func signBinary(_ string) error { return nil } diff --git a/source.go b/source.go index dd94725..7aa6621 100644 --- a/source.go +++ b/source.go @@ -9,10 +9,18 @@ import ( "strings" ) +// Asset is one downloadable file attached to a release. +type Asset struct { + Name string + URL string // browser_download_url + Size int64 +} + // Release is the subset of a forge release the library needs. type Release struct { Tag string Prerelease bool + Assets []Asset } // Source lists releases. Implementations must return List newest first. @@ -36,11 +44,28 @@ type GitHubSource struct { Client *http.Client // default http.DefaultClient } +// githubAsset is the subset of GitHub's asset JSON the library reads. +type githubAsset struct { + Name string `json:"name"` + BrowserDownloadURL string `json:"browser_download_url"` + Size int64 `json:"size"` +} + // githubRelease is the subset of GitHub's release JSON the library reads. type githubRelease struct { - TagName string `json:"tag_name"` - Prerelease bool `json:"prerelease"` - Draft bool `json:"draft"` + TagName string `json:"tag_name"` + Prerelease bool `json:"prerelease"` + Draft bool `json:"draft"` + Assets []githubAsset `json:"assets"` +} + +// release converts the GitHub payload into the library's Release. +func (r githubRelease) release() Release { + assets := make([]Asset, 0, len(r.Assets)) + for _, a := range r.Assets { + assets = append(assets, Asset{Name: a.Name, URL: a.BrowserDownloadURL, Size: a.Size}) + } + return Release{Tag: r.TagName, Prerelease: r.Prerelease, Assets: assets} } // Latest returns the release GitHub marks as latest (never a prerelease). @@ -49,7 +74,7 @@ func (g *GitHubSource) Latest(ctx context.Context) (Release, error) { if err := g.get(ctx, "/releases/latest", &rel); err != nil { return Release{}, err } - return Release{Tag: rel.TagName, Prerelease: rel.Prerelease}, nil + return rel.release(), nil } // List returns up to limit releases, newest first, without drafts. A limit @@ -67,7 +92,7 @@ func (g *GitHubSource) List(ctx context.Context, limit int) ([]Release, error) { if r.Draft { continue } - out = append(out, Release{Tag: r.TagName, Prerelease: r.Prerelease}) + out = append(out, r.release()) } return out, nil } diff --git a/source_test.go b/source_test.go index f3c41cd..4cd3671 100644 --- a/source_test.go +++ b/source_test.go @@ -23,10 +23,17 @@ const ( tagV100 = "v1.0.0" ) +type ghAsset struct { + Name string `json:"name"` + BrowserDownloadURL string `json:"browser_download_url"` + Size int64 `json:"size"` +} + type ghFixture struct { - TagName string `json:"tag_name"` - Prerelease bool `json:"prerelease"` - Draft bool `json:"draft"` + TagName string `json:"tag_name"` + Prerelease bool `json:"prerelease"` + Draft bool `json:"draft"` + Assets []ghAsset `json:"assets"` } func newGitHubTestServer(t *testing.T, latest ghFixture, list []ghFixture, wantAuth string) *httptest.Server { @@ -136,3 +143,32 @@ func TestGitHubSource_ContextCancelled(t *testing.T) { t.Fatal("expected context error") } } + +func TestGitHubSource_DecodesAssets(t *testing.T) { + const tarball = "tool_1.2.3_linux_amd64.tar.gz" + const tarballSize, sumsSize, limit = 1234, 99, 10 + latest := ghFixture{TagName: tagV123, Assets: []ghAsset{ + {Name: tarball, BrowserDownloadURL: "https://dl.example/" + tarball, Size: tarballSize}, + {Name: "checksums.txt", BrowserDownloadURL: "https://dl.example/checksums.txt", Size: sumsSize}, + }} + srv := newGitHubTestServer(t, latest, []ghFixture{latest}, "") + defer srv.Close() + src := &GitHubSource{Owner: testOwner, Repo: testRepo, BaseURL: srv.URL} + + rel, err := src.Latest(context.Background()) + if err != nil { + t.Fatal(err) + } + want := Asset{Name: tarball, URL: "https://dl.example/" + tarball, Size: tarballSize} + if len(rel.Assets) != 2 || rel.Assets[0] != want { + t.Fatalf("Latest assets: got %+v, want first %+v", rel.Assets, want) + } + + list, err := src.List(context.Background(), limit) + if err != nil { + t.Fatal(err) + } + if len(list) != 1 || len(list[0].Assets) != 2 || list[0].Assets[1].Name != "checksums.txt" { + t.Fatalf("List assets: %+v", list) + } +}