From 84a84b5f50279dbd52ca8c39980b321b5f1de23e Mon Sep 17 00:00:00 2001 From: David Grieser Date: Wed, 25 Nov 2026 17:24:59 +0100 Subject: [PATCH 1/2] feat(selfupdate): update .deb installs through a registered APT repository An executable a .deb installed was always refused with ErrManaged. With Updater.APT set, one whose package comes from an APT repository that is registered on the system is updated through APT instead: - Check, Update and Install read the latest version from that repository, not from Source, so no Source credential is needed. - The repository's index and the package are fetched without root into a temporary directory, limited to the repository's sources file; APT verifies both against the repository key. - APT.Confirm is shown the exact commands (apt-get update, apt-get install of the downloaded file) before they run as root, through sudo when the process is not root. Nil Confirm installs without asking, for --yes. Anything else (no sources file, no single dpkg owner, not Linux) is still refused with ErrManaged. Co-Authored-By: Claude Opus 5.5 --- README.md | 26 +++ selfupdate/apt.go | 486 +++++++++++++++++++++++++++++++++++++++++ selfupdate/apt_test.go | 418 +++++++++++++++++++++++++++++++++++ selfupdate/doc.go | 7 + selfupdate/update.go | 80 ++++++- 5 files changed, 1010 insertions(+), 7 deletions(-) create mode 100644 selfupdate/apt.go create mode 100644 selfupdate/apt_test.go diff --git a/README.md b/README.md index 692d65d..2a709e3 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,32 @@ documentation shows the GoReleaser `signs` entry. The archive must hold an executable for the platform, and a credential is only sent to an `https` API address. +A `.deb` install is refused by default. If the package comes from an APT +repository that is registered on the system, `Updater.APT` updates it through +APT instead. `Check` and `Update` then read the latest version from that +repository, so the `Source` and its token are not needed. The repository's +index and the package are fetched without root privileges into a temporary +directory. Only `apt-get update` and `apt-get install` of the downloaded file +run as root, through sudo when needed, so dependencies come from all of the +system's repositories. `Confirm` sees the exact commands first, so a command +can ask before it runs them, or skip the question for `--yes`: + +```go +u.APT = &selfupdate.APT{ + Sources: "/etc/apt/sources.list.d/example.sources", // the file the package registers + Confirm: func(ctx context.Context, plan selfupdate.APTPlan) (bool, error) { + if yes { + return true, nil + } + fmt.Fprintf(os.Stderr, "Update %s %s to %s with:\n%s\n", plan.Package, plan.Installed, plan.Version, plan) + return askYesNo("Continue?") // the tool's own prompt + }, +} +``` + +APT verifies the index with the repository key, and the package against the +index. + ### Files, browser and logs ```go diff --git a/selfupdate/apt.go b/selfupdate/apt.go new file mode 100644 index 0000000..9a3d0ec --- /dev/null +++ b/selfupdate/apt.go @@ -0,0 +1,486 @@ +package selfupdate + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" +) + +// ErrDeclined reports that [APT.Confirm] declined the update, so nothing +// was installed. +var ErrDeclined = errors.New("selfupdate: update declined") + +// The programs an [APT] update runs, by absolute path, so that PATH cannot +// lead a command run as root to another program. +const ( + aptGet = "/usr/bin/apt-get" + aptCache = "/usr/bin/apt-cache" + dpkgQuery = "/usr/bin/dpkg-query" + sudo = "/usr/bin/sudo" +) + +// APT updates an executable that a .deb installed while the APT repository +// that publishes the package is registered on the system, through APT +// rather than by replacing the file. Set it as [Updater.APT]. +// +// It applies only on Linux, only to an executable that [Updater.Managed] +// reports as managed, only while the Sources file exists, and only when +// dpkg names exactly one package as the owner of the executable. Anything +// else is refused with [ErrManaged] as before: an executable a .deb +// installed without the repository, or another package manager's. +// +// Where it applies, the repository is the source of releases, not +// [Updater.Source], which is never asked: [Updater.Check] and +// [Updater.Update] read the latest version from the repository, so no +// credential for the Source is needed. The repository's index is fetched +// into a temporary directory without root privileges, leaving the +// system's package lists as they are, and the package is downloaded from +// it the same way; APT checks both against the repository's signing key. +// Only the install of the downloaded file needs root: it runs apt-get +// update and apt-get install with the file, so that dependencies come from +// all of the system's repositories, freshly fetched. Without root privileges it runs through sudo, +// which asks for a password on the terminal itself; the process never +// sees it. The release's archive, checksums file and [Updater.Verifier] +// are not used. +type APT struct { + // Sources is the file that registers the repository, as a deb822 + // ".sources" or a one-line ".list" file, such as + // "/etc/apt/sources.list.d/example.sources". It is required. + Sources string + // Confirm is asked before the package is installed, with the plan of + // what will run. When it returns false, the update ends with + // [ErrDeclined]. Nil installs without asking, for a command's --yes. + Confirm func(ctx context.Context, plan APTPlan) (bool, error) + // Stdin, Stdout and Stderr are given to the install command, so that + // sudo can ask for a password and apt-get can report its progress. Nil + // means the process's own. + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer + + // Set by tests to fake the system. + goos string + euid func() int + output func(ctx context.Context, dir string, argv []string) ([]byte, error) + run func(ctx context.Context, argv []string, stdin io.Reader, stdout, stderr io.Writer) error +} + +// APTPlan is what an [APT] update is about to do, for [APT.Confirm] to +// show. +type APTPlan struct { + // Package is the package that owns the executable, qualified with its + // architecture, as in "tool:amd64", when dpkg qualifies it. + Package string + // Installed is the version of Package that is installed. + Installed string + // Version is the version that will be installed. + Version string + // File is the downloaded package that will be installed. + File string + // Sudo reports whether Commands run through sudo. + Sudo bool + // Commands are the commands that will run, in order, each as its + // arguments with the program first. + Commands [][]string +} + +// String returns the commands one per line, quoted for a POSIX shell, so +// that a user can read them or run them by hand. +func (p APTPlan) String() string { + lines := make([]string, len(p.Commands)) + for i, argv := range p.Commands { + quoted := make([]string, len(argv)) + for j, arg := range argv { + quoted[j] = shellQuote(arg) + } + lines[i] = strings.Join(quoted, " ") + } + return strings.Join(lines, "\n") +} + +// shellQuote quotes s for a POSIX shell when it needs quoting. +func shellQuote(s string) string { + if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./:=+,@") == "" { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + +// owner returns the package that installed path when the APT update +// applies to it, and "" when it does not. +func (a *APT) owner(ctx context.Context, path string) string { + if a.os() != "linux" || a.Sources == "" { + return "" + } + if info, err := os.Stat(a.Sources); err != nil || !info.Mode().IsRegular() { + return "" + } + for _, file := range dpkgPaths(path) { + out, err := a.query(ctx, "", []string{dpkgQuery, "--search", "--", file}) + if err != nil { + continue + } + return dpkgOwner(out, file) + } + return "" +} + +// dpkgPaths returns the paths dpkg may know the executable at path by: +// path itself and, on a system with merged /usr, the path without "/usr" +// when that leads to the same file, since a package may install to /bin or +// /sbin. +func dpkgPaths(path string) []string { + paths := []string{path} + if alias, ok := strings.CutPrefix(path, "/usr"); ok && strings.HasPrefix(alias, "/") { + if resolved, err := filepath.EvalSymlinks(alias); err == nil && resolved == path { + paths = append(paths, alias) + } + } + return paths +} + +// dpkgOwner reads what "dpkg-query --search PATH" printed and returns the +// one package it names as the owner of path, with the architecture dpkg +// qualified it with, if any. It returns "" when no package or more than +// one owns path, or when a diversion moved what the package installed. +func dpkgOwner(out []byte, path string) string { + owner := "" + for line := range strings.Lines(string(out)) { + line = strings.TrimRight(line, "\n") + if strings.HasPrefix(line, "diversion by ") { + return "" + } + packages, file, ok := strings.Cut(line, ": ") + if !ok || file != path || owner != "" || strings.Contains(packages, ", ") { + return "" + } + name, arch, qualified := strings.Cut(packages, ":") + if !debName(name) || qualified && !debArch(arch) { + return "" + } + owner = packages + } + return owner +} + +// debName reports whether s is a valid Debian package name. +func debName(s string) bool { + if len(s) < 2 || !isLowerAlnum(s[0]) { + return false + } + for i := 1; i < len(s); i++ { + if c := s[i]; !isLowerAlnum(c) && c != '+' && c != '-' && c != '.' { + return false + } + } + return true +} + +// debArch reports whether s is a valid Debian architecture name. +func debArch(s string) bool { + if s == "" { + return false + } + for i := 0; i < len(s); i++ { + if c := s[i]; !isLowerAlnum(c) && c != '-' { + return false + } + } + return true +} + +// debVersion reports whether s can be a Debian version: it starts with a +// digit and holds only the characters a version may hold. +func debVersion(s string) bool { + if s == "" || s[0] < '0' || s[0] > '9' { + return false + } + for i := 0; i < len(s); i++ { + if c := s[i]; !isLowerAlnum(c) && (c < 'A' || c > 'Z') && !strings.ContainsRune(".+-~:", rune(c)) { + return false + } + } + return true +} + +func isLowerAlnum(c byte) bool { return c >= 'a' && c <= 'z' || c >= '0' && c <= '9' } + +// installed returns the version of pkg dpkg has installed. +func (a *APT) installed(ctx context.Context, pkg string) (string, error) { + out, err := a.query(ctx, "", []string{dpkgQuery, "--show", "--showformat=${Version}", "--", pkg}) + if err != nil { + return "", fmt.Errorf("selfupdate: read installed version of %s: %w", pkg, err) + } + return strings.TrimSpace(string(out)), nil +} + +// aptRepo is the repository's index, fetched into a directory of its own. +type aptRepo struct { + a *APT + dir string + opts []string +} + +// fetch fetches the repository's index into a new temporary directory, +// which close removes. It needs no root privileges and leaves the system's +// package lists alone. +func (a *APT) fetch(ctx context.Context) (*aptRepo, error) { + sources, err := filepath.Abs(a.Sources) + if err != nil { + return nil, fmt.Errorf("selfupdate: locate %s: %w", a.Sources, err) + } + dir, err := os.MkdirTemp("", "selfupdate-apt-") + if err != nil { + return nil, fmt.Errorf("selfupdate: create directory for the package index: %w", err) + } + repo := &aptRepo{a: a, dir: dir} + // root, who installs the downloaded file, reads it, and so does the + // user APT downloads as when it runs as root. Nobody else may write. + if err := os.Chmod(dir, 0o755); err != nil { // #nosec G302 -- a directory others may read, not write + repo.close() + return nil, fmt.Errorf("selfupdate: create directory for the package index: %w", err) + } + for _, sub := range []string{"lists/partial", "cache/archives/partial"} { + if err := os.MkdirAll(filepath.Join(dir, sub), 0o755); err != nil { // #nosec G301 -- as above + repo.close() + return nil, fmt.Errorf("selfupdate: create directory for the package index: %w", err) + } + } + repo.opts = []string{ + "-o", "Dir::Etc::sourcelist=" + sources, + "-o", "Dir::Etc::sourceparts=-", + "-o", "Dir::State::Lists=" + filepath.Join(dir, "lists"), + "-o", "Dir::Cache=" + filepath.Join(dir, "cache"), + // A default release the system sets names a release of its own + // repositories, which APT rejects when they are not listed. + "-o", "APT::Default-Release=", + } + if a.uid() == 0 { + // The directory is root's; the user APT would otherwise download + // as cannot write to it. + repo.opts = append(repo.opts, "-o", "APT::Sandbox::User=root") + } + // Error-Mode makes an index that could not be fetched an error rather + // than a warning; an APT older than 2.1.16 ignores it. + if _, err := a.query(ctx, dir, repo.argv(aptGet, "-o", "APT::Update::Error-Mode=any", "update")); err != nil { + repo.close() + return nil, fmt.Errorf("selfupdate: fetch the package index of %s: %w", a.Sources, err) + } + // Without any index, the installed version would pass for the latest. + if indexes, _ := filepath.Glob(filepath.Join(dir, "lists", "*_Packages*")); len(indexes) == 0 { + repo.close() + return nil, fmt.Errorf("selfupdate: fetch the package index of %s: no index was fetched", a.Sources) + } + return repo, nil +} + +// argv returns the command line of program with the options that limit it +// to the repository, followed by args. +func (r *aptRepo) argv(program string, args ...string) []string { + argv := append([]string{program, "-q"}, r.opts...) + return append(argv, args...) +} + +func (r *aptRepo) close() { _ = os.RemoveAll(r.dir) } + +// candidate returns the version of pkg that APT would install from the +// repository: its latest, unless a pin on the system says otherwise. A +// package that is installed in a version newer than any the repository +// has is its own candidate. A repository that does not offer pkg at all is +// an error, so that the installed version cannot pass for the latest. +func (r *aptRepo) candidate(ctx context.Context, pkg string) (string, error) { + // madison lists the versions in the repository's index only, unlike + // policy, which counts the installed one too. + out, err := r.a.query(ctx, r.dir, r.argv(aptCache, "madison", "--", pkg)) + if err != nil { + return "", fmt.Errorf("selfupdate: read the versions of %s: %w", pkg, err) + } + offered := false + for line := range strings.Lines(string(out)) { + if fields := strings.Split(line, "|"); len(fields) == 3 && debVersion(strings.TrimSpace(fields[1])) { + offered = true + break + } + } + if !offered { + return "", fmt.Errorf("selfupdate: %s does not offer %s", r.a.Sources, pkg) + } + out, err = r.a.query(ctx, r.dir, r.argv(aptCache, "policy", "--", pkg)) + if err != nil { + return "", fmt.Errorf("selfupdate: read the versions of %s: %w", pkg, err) + } + scanner := bufio.NewScanner(bytes.NewReader(out)) + for scanner.Scan() { + if value, ok := strings.CutPrefix(strings.TrimSpace(scanner.Text()), "Candidate:"); ok { + if version := strings.TrimSpace(value); debVersion(version) { + return version, nil + } + break + } + } + return "", fmt.Errorf("selfupdate: %s does not offer %s", r.a.Sources, pkg) +} + +// download downloads version of pkg and returns the file. +func (r *aptRepo) download(ctx context.Context, pkg, version string) (string, error) { + if _, err := r.a.query(ctx, r.dir, r.argv(aptGet, "download", "--", pkg+"="+version)); err != nil { + return "", fmt.Errorf("selfupdate: download %s %s: %w", pkg, version, err) + } + files, err := filepath.Glob(filepath.Join(r.dir, "*.deb")) + if err != nil || len(files) != 1 { + return "", fmt.Errorf("selfupdate: download %s %s: found %d packages, not one", pkg, version, len(files)) + } + return files[0], nil +} + +// check returns the version the repository offers for pkg and the version +// that is installed. +func (a *APT) check(ctx context.Context, pkg string) (latest, installed string, err error) { + installed, err = a.installed(ctx, pkg) + if err != nil { + return "", "", err + } + repo, err := a.fetch(ctx) + if err != nil { + return "", "", err + } + defer repo.close() + latest, err = repo.candidate(ctx, pkg) + return latest, installed, err +} + +// update installs the version of pkg the repository offers, or the one +// rel names when it has a tag, unless that version is +// installed and force is false. It returns the version it found and +// whether it installed it. +func (a *APT) update(ctx context.Context, pkg string, rel Release, force bool) (string, bool, error) { + installed, err := a.installed(ctx, pkg) + if err != nil { + return "", false, err + } + repo, err := a.fetch(ctx) + if err != nil { + return "", false, err + } + defer repo.close() + version := rel.Version() + if rel.Tag == "" { + if version, err = repo.candidate(ctx, pkg); err != nil { + return "", false, err + } + } else if !debVersion(version) { + return "", false, fmt.Errorf("%w: %q", ErrNoVersion, plain(rel.Tag)) + } + if version == installed && !force { + return version, false, nil + } + file, err := repo.download(ctx, pkg, version) + if err != nil { + return version, false, err + } + install := []string{aptGet, "install", "--yes", "--allow-downgrades"} + if version == installed { + install = append(install, "--reinstall") + } + plan := APTPlan{ + Package: pkg, + Installed: installed, + Version: version, + File: file, + Commands: [][]string{ + // The system's lists, refreshed, offer the dependencies the + // new version may need. + {aptGet, "update"}, + append(install, "--", file), + }, + } + if a.uid() != 0 { + plan.Sudo = true + for i, argv := range plan.Commands { + plan.Commands[i] = append([]string{sudo, "--"}, argv...) + } + } + if a.Confirm != nil { + ok, err := a.Confirm(ctx, plan) + if err != nil { + return version, false, err + } + if !ok { + return version, false, ErrDeclined + } + } + for _, argv := range plan.Commands { + if err := a.exec(ctx, argv); err != nil { + return version, false, fmt.Errorf("selfupdate: %s: %w", strings.Join(argv, " "), err) + } + } + now, err := a.installed(ctx, pkg) + if err != nil { + return version, false, err + } + if now != version { + return version, false, fmt.Errorf("selfupdate: %s %s is installed after the update, not %s", pkg, plain(now), version) + } + return version, true, nil +} + +func (a *APT) os() string { + if a.goos != "" { + return a.goos + } + return runtime.GOOS +} + +func (a *APT) uid() int { + if a.euid != nil { + return a.euid() + } + return os.Geteuid() +} + +// query runs argv in dir, or in the current directory when dir is empty, +// and returns what it printed. +func (a *APT) query(ctx context.Context, dir string, argv []string) ([]byte, error) { + if a.output != nil { + return a.output(ctx, dir, argv) + } + cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) // #nosec G204 -- fixed programs, arguments without a shell + cmd.Dir = dir + // The output is parsed, so it must not be translated. + cmd.Env = append(os.Environ(), "LC_ALL=C") + var stderr bytes.Buffer + cmd.Stderr = &stderr + out, err := cmd.Output() + if err != nil && stderr.Len() > 0 { + return out, fmt.Errorf("%w: %s", err, plain(strings.TrimSpace(stderr.String()))) + } + return out, err +} + +// exec runs argv with the streams of a. +func (a *APT) exec(ctx context.Context, argv []string) error { + stdin, stdout, stderr := a.Stdin, a.Stdout, a.Stderr + if stdin == nil { + stdin = os.Stdin + } + if stdout == nil { + stdout = os.Stdout + } + if stderr == nil { + stderr = os.Stderr + } + if a.run != nil { + return a.run(ctx, argv, stdin, stdout, stderr) + } + cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) // #nosec G204 -- fixed programs, arguments without a shell + cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr + return cmd.Run() +} diff --git a/selfupdate/apt_test.go b/selfupdate/apt_test.go new file mode 100644 index 0000000..d650b17 --- /dev/null +++ b/selfupdate/apt_test.go @@ -0,0 +1,418 @@ +package selfupdate + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +// fakeDpkg plays dpkg-query, apt-get and apt-cache for an [APT]: one +// package owns one file, the repository offers some versions of it, and an +// install of a downloaded file changes the installed version. +type fakeDpkg struct { + file string + pkg string + version string // installed + offered []string // in the repository, the last one is the candidate + search string // what dpkg-query --search prints; empty means file's owner + searchErr error + fetchErr error + // unreachable makes apt-get update fetch nothing yet succeed, as it + // does when it cannot reach the repository. + unreachable bool + runErr error + queried [][]string + ran [][]string + dirs []string +} + +func (f *fakeDpkg) output(_ context.Context, dir string, argv []string) ([]byte, error) { + f.queried = append(f.queried, argv) + switch { + case argv[0] == dpkgQuery && slices.Contains(argv, "--search"): + if f.searchErr != nil { + return nil, f.searchErr + } + if f.search != "" { + return []byte(f.search), nil + } + if argv[len(argv)-1] != f.file { + return nil, errors.New("exit status 1") + } + return []byte(f.pkg + ": " + f.file + "\n"), nil + case argv[0] == dpkgQuery && slices.Contains(argv, "--show"): + return []byte(f.version), nil + case argv[0] == aptGet && slices.Contains(argv, "update"): + f.dirs = append(f.dirs, dir) + if f.fetchErr != nil || f.unreachable { + return nil, f.fetchErr + } + return nil, os.WriteFile(filepath.Join(dir, "lists", "example.org_dists_stable_main_binary-amd64_Packages"), nil, 0o644) + case argv[0] == aptCache && slices.Contains(argv, "madison"): + var out strings.Builder + for _, v := range slices.Backward(f.offered) { + out.WriteString(f.pkg + " | " + v + " | https://example.org stable/main amd64 Packages\n") + } + return []byte(out.String()), nil + case argv[0] == aptCache && slices.Contains(argv, "policy"): + // As APT: the installed version counts unless the repository has + // a newer one. + candidate := f.version + if len(f.offered) > 0 && f.offered[len(f.offered)-1] > f.version { + candidate = f.offered[len(f.offered)-1] + } + return []byte(f.pkg + ":\n Installed: " + f.version + "\n Candidate: " + candidate + "\n Version table:\n"), nil + case argv[0] == aptGet && slices.Contains(argv, "download"): + _, version, _ := strings.Cut(argv[len(argv)-1], "=") + if !slices.Contains(f.offered, version) { + return nil, errors.New("exit status 100: E: Version '" + version + "' was not found") + } + name := strings.ReplaceAll(f.pkg, ":", "_") + "_" + strings.ReplaceAll(version, ":", "%3a") + "_amd64.deb" + return nil, os.WriteFile(filepath.Join(dir, name), []byte("!\n"), 0o644) + } + return nil, errors.New("unexpected query") +} + +func (f *fakeDpkg) run(_ context.Context, argv []string, _ io.Reader, _, _ io.Writer) error { + f.ran = append(f.ran, argv) + if f.runErr != nil { + return f.runErr + } + if argv[len(argv)-1] == "update" { + return nil + } + file := argv[len(argv)-1] + if _, err := os.Stat(file); err != nil { + return err + } + parts := strings.Split(filepath.Base(file), "_") + f.version = strings.ReplaceAll(parts[len(parts)-2], "%3a", ":") + return nil +} + +func newAPTUpdater(t *testing.T, dpkg *fakeDpkg, euid int) (*Updater, *APT) { + t.Helper() + sources := filepath.Join(t.TempDir(), "example.sources") + if err := os.WriteFile(sources, []byte("Types: deb\n"), 0o644); err != nil { + t.Fatal(err) + } + apt := &APT{ + Sources: sources, + goos: "linux", + euid: func() int { return euid }, + output: dpkg.output, + run: dpkg.run, + } + u := &Updater{ + // The repository is the source of releases; this one fails when + // it is asked. + Source: &memorySource{latestErr: errors.New("source asked")}, + Current: "v1.2.0", + Asset: DefaultAssets("example"), + Executable: dpkg.file, + Managed: func(string) bool { return true }, + APT: apt, + } + return u, apt +} + +func newFakeDpkg() *fakeDpkg { + return &fakeDpkg{file: "/usr/bin/example", pkg: "example", version: "1.2.0", offered: []string{"1.2.0", "1.3.0"}} +} + +func TestAPTUpdateAsUser(t *testing.T) { + dpkg := newFakeDpkg() + u, apt := newAPTUpdater(t, dpkg, 1000) + var shown APTPlan + apt.Confirm = func(_ context.Context, plan APTPlan) (bool, error) { + shown = plan + return true, nil + } + res, err := u.Update(context.Background(), false) + if err != nil { + t.Fatal(err) + } + if !res.Updated || res.Package != "example" || res.Asset != "" || res.Release.Tag != "1.3.0" { + t.Fatalf("result = %+v", res) + } + if shown.Package != "example" || shown.Installed != "1.2.0" || shown.Version != "1.3.0" || !shown.Sudo { + t.Fatalf("plan = %+v", shown) + } + if !slices.EqualFunc(dpkg.ran, shown.Commands, slices.Equal) { + t.Fatalf("ran %q, showed %q", dpkg.ran, shown.Commands) + } + want := "/usr/bin/sudo -- /usr/bin/apt-get update\n" + + "/usr/bin/sudo -- /usr/bin/apt-get install --yes --allow-downgrades -- " + shown.File + if got := shown.String(); got != want { + t.Fatalf("plan:\n%s\nwant:\n%s", got, want) + } + // The index was fetched without sudo into a directory of its own, + // which is gone with the downloaded file. + for _, argv := range dpkg.queried { + if argv[0] == sudo { + t.Fatalf("queried %q", argv) + } + if argv[0] == aptGet && !slices.Contains(argv, "Dir::State::Lists="+filepath.Join(dpkg.dirs[0], "lists")) { + t.Fatalf("queried %q without its own lists", argv) + } + if slices.Contains(argv, "APT::Sandbox::User=root") { + t.Fatalf("queried %q as user", argv) + } + } + if _, err := os.Stat(dpkg.dirs[0]); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("index directory left behind: %v", err) + } +} + +func TestAPTUpdateAsRoot(t *testing.T) { + dpkg := newFakeDpkg() + u, _ := newAPTUpdater(t, dpkg, 0) + if _, err := u.Update(context.Background(), false); err != nil { + t.Fatal(err) + } + if len(dpkg.ran) != 2 || dpkg.ran[0][0] != aptGet || dpkg.ran[1][0] != aptGet { + t.Fatalf("ran %q", dpkg.ran) + } + for _, argv := range dpkg.queried { + if argv[0] == aptGet && !slices.Contains(argv, "APT::Sandbox::User=root") { + t.Fatalf("queried %q as root", argv) + } + } +} + +func TestAPTCheck(t *testing.T) { + dpkg := newFakeDpkg() + u, _ := newAPTUpdater(t, dpkg, 1000) + rel, newer, err := u.Check(context.Background()) + if err != nil || !newer || rel.Tag != "1.3.0" { + t.Fatalf("Check = %+v, %v, %v", rel, newer, err) + } + dpkg.version = "1.3.0" + if rel, newer, err = u.Check(context.Background()); err != nil || newer || rel.Tag != "1.3.0" { + t.Fatalf("Check = %+v, %v, %v", rel, newer, err) + } + if len(dpkg.ran) != 0 { + t.Fatalf("ran %q", dpkg.ran) + } + // Installed in a version newer than the repository's. + dpkg.version = "1.4.0" + if rel, newer, err = u.Check(context.Background()); err != nil || newer || rel.Tag != "1.4.0" { + t.Fatalf("Check = %+v, %v, %v", rel, newer, err) + } + // Not offered at all: the installed version is no candidate then. + dpkg.offered = nil + if _, _, err := u.Check(context.Background()); err == nil || !strings.Contains(err.Error(), "does not offer example") { + t.Fatalf("err = %v", err) + } + dpkg.offered = []string{"1.3.0"} + dpkg.unreachable = true + if _, _, err := u.Check(context.Background()); err == nil || !strings.Contains(err.Error(), "no index was fetched") { + t.Fatalf("err = %v", err) + } + dpkg.fetchErr = errors.New("exit status 100") + if _, _, err := u.Check(context.Background()); err == nil || !strings.Contains(err.Error(), "fetch the package index") { + t.Fatalf("err = %v", err) + } +} + +func TestAPTCheckThenInstall(t *testing.T) { + dpkg := newFakeDpkg() + u, _ := newAPTUpdater(t, dpkg, 0) + rel, _, err := u.Check(context.Background()) + if err != nil { + t.Fatal(err) + } + // Published since the check, but Install keeps to what Check found. + dpkg.offered = append(dpkg.offered, "1.4.0") + res, err := u.Install(context.Background(), rel) + if err != nil { + t.Fatal(err) + } + if !res.Updated || dpkg.version != "1.3.0" { + t.Fatalf("result = %+v, installed %s", res, dpkg.version) + } + // A release tag from elsewhere names the package version without "v". + if _, err := u.Install(context.Background(), Release{Tag: "v1.4.0"}); err != nil || dpkg.version != "1.4.0" { + t.Fatalf("err = %v, installed %s", err, dpkg.version) + } + // One the repository lacks fails to download. + if _, err := u.Install(context.Background(), Release{Tag: "v9.0.0"}); err == nil || !strings.Contains(err.Error(), "download example 9.0.0") { + t.Fatalf("err = %v", err) + } +} + +func TestAPTUpdateCurrent(t *testing.T) { + dpkg := newFakeDpkg() + dpkg.version = "1.3.0" + u, _ := newAPTUpdater(t, dpkg, 0) + u.Current = "v1.3.0" + res, err := u.Update(context.Background(), false) + if err != nil { + t.Fatal(err) + } + if res.Updated || res.Package != "example" || len(dpkg.ran) != 0 { + t.Fatalf("result = %+v, ran %q", res, dpkg.ran) + } + // Forced, the same version is installed again. + if _, err := u.Update(context.Background(), true); err != nil { + t.Fatal(err) + } + if install := dpkg.ran[len(dpkg.ran)-1]; !slices.Contains(install, "--reinstall") { + t.Fatalf("install = %q", install) + } +} + +func TestAPTArchitectureQualified(t *testing.T) { + dpkg := newFakeDpkg() + dpkg.pkg = "example:arm64" + u, _ := newAPTUpdater(t, dpkg, 0) + res, err := u.Update(context.Background(), false) + if err != nil { + t.Fatal(err) + } + if res.Package != "example:arm64" { + t.Fatalf("result = %+v", res) + } + if !slices.ContainsFunc(dpkg.queried, func(argv []string) bool { return argv[len(argv)-1] == "example:arm64=1.3.0" }) { + t.Fatalf("queried %q", dpkg.queried) + } +} + +func TestAPTEpochVersion(t *testing.T) { + dpkg := newFakeDpkg() + dpkg.version, dpkg.offered = "1:1.2.0-1", []string{"1:1.3.0-1"} + u, _ := newAPTUpdater(t, dpkg, 0) + res, err := u.Update(context.Background(), false) + if err != nil || dpkg.version != "1:1.3.0-1" || res.Release.Tag != "1:1.3.0-1" { + t.Fatalf("result = %+v, err = %v, installed %s", res, err, dpkg.version) + } +} + +func TestAPTWithoutSource(t *testing.T) { + dpkg := newFakeDpkg() + u, _ := newAPTUpdater(t, dpkg, 0) + u.Source, u.Asset = nil, nil + if _, _, err := u.Check(context.Background()); err != nil { + t.Fatal(err) + } + if res, err := u.Update(context.Background(), false); err != nil || !res.Updated { + t.Fatalf("result = %+v, err = %v", res, err) + } + if _, err := u.Install(context.Background(), Release{Tag: "1.2.0"}); err != nil { + t.Fatal(err) + } +} + +func TestAPTDeclined(t *testing.T) { + dpkg := newFakeDpkg() + u, apt := newAPTUpdater(t, dpkg, 1000) + apt.Confirm = func(context.Context, APTPlan) (bool, error) { return false, nil } + if _, err := u.Update(context.Background(), false); !errors.Is(err, ErrDeclined) { + t.Fatalf("err = %v", err) + } + if len(dpkg.ran) != 0 { + t.Fatalf("ran %q", dpkg.ran) + } + sentinel := errors.New("no terminal") + apt.Confirm = func(context.Context, APTPlan) (bool, error) { return false, sentinel } + if _, err := u.Update(context.Background(), false); !errors.Is(err, sentinel) { + t.Fatalf("err = %v", err) + } +} + +func TestAPTCommandFails(t *testing.T) { + dpkg := newFakeDpkg() + dpkg.runErr = errors.New("exit status 100") + u, _ := newAPTUpdater(t, dpkg, 0) + _, err := u.Update(context.Background(), false) + if err == nil || !strings.Contains(err.Error(), "apt-get update") || len(dpkg.ran) != 1 { + t.Fatalf("err = %v, ran %q", err, dpkg.ran) + } +} + +func TestAPTVersionNotInstalled(t *testing.T) { + dpkg := newFakeDpkg() + u, apt := newAPTUpdater(t, dpkg, 0) + apt.run = func(context.Context, []string, io.Reader, io.Writer, io.Writer) error { return nil } + if _, err := u.Update(context.Background(), false); err == nil || !strings.Contains(err.Error(), "1.2.0 is installed") { + t.Fatalf("err = %v", err) + } +} + +func TestAPTNotApplicable(t *testing.T) { + cases := map[string]func(u *Updater, apt *APT, dpkg *fakeDpkg){ + "no repository": func(_ *Updater, apt *APT, _ *fakeDpkg) { + apt.Sources = filepath.Join(filepath.Dir(apt.Sources), "missing") + }, + "no Sources": func(_ *Updater, apt *APT, _ *fakeDpkg) { apt.Sources = "" }, + "not Linux": func(_ *Updater, apt *APT, _ *fakeDpkg) { apt.goos = "darwin" }, + "no owner": func(_ *Updater, _ *APT, dpkg *fakeDpkg) { dpkg.searchErr = errors.New("exit status 1") }, + "other file": func(u *Updater, _ *APT, _ *fakeDpkg) { u.Executable = "/usr/bin/other" }, + "diverted": func(_ *Updater, _ *APT, dpkg *fakeDpkg) { dpkg.search = "diversion by x from: /usr/bin/example\n" }, + "two owners": func(_ *Updater, _ *APT, dpkg *fakeDpkg) { dpkg.search = "a, b: /usr/bin/example\n" }, + "no APT": func(u *Updater, _ *APT, _ *fakeDpkg) { u.APT = nil }, + "bad name": func(_ *Updater, _ *APT, dpkg *fakeDpkg) { dpkg.search = "-x: /usr/bin/example\n" }, + "directory found": func(_ *Updater, apt *APT, _ *fakeDpkg) { apt.Sources = filepath.Dir(apt.Sources) }, + } + for name, change := range cases { + t.Run(name, func(t *testing.T) { + dpkg := newFakeDpkg() + u, apt := newAPTUpdater(t, dpkg, 0) + change(u, apt, dpkg) + if _, err := u.Update(context.Background(), false); !errors.Is(err, ErrManaged) { + t.Fatalf("err = %v", err) + } + // Check falls back to Source, which fails here. + if _, _, err := u.Check(context.Background()); err == nil || err.Error() != "source asked" { + t.Fatalf("Check err = %v", err) + } + if len(dpkg.ran) != 0 { + t.Fatalf("ran %q", dpkg.ran) + } + }) + } +} + +func TestAPTInstallNoVersion(t *testing.T) { + dpkg := newFakeDpkg() + u, _ := newAPTUpdater(t, dpkg, 0) + for _, tag := range []string{"release-2", "v1.0 --x", ""} { + if _, err := u.Install(context.Background(), Release{Tag: tag}); !errors.Is(err, ErrNoVersion) { + t.Fatalf("%q: err = %v", tag, err) + } + } + if len(dpkg.ran) != 0 { + t.Fatalf("ran %q", dpkg.ran) + } +} + +func TestDpkgOwner(t *testing.T) { + cases := []struct{ out, want string }{ + {"example: /usr/bin/example\n", "example"}, + {"example:arm64: /usr/bin/example", "example:arm64"}, + {"example:ARM: /usr/bin/example", ""}, + {"example:: /usr/bin/example", ""}, + {"lib+x.y-1: /usr/bin/example\n", "lib+x.y-1"}, + {"example: /usr/bin/example2\n", ""}, + {"example: /usr/bin/example\nother: /usr/bin/example\n", ""}, + {"Example: /usr/bin/example\n", ""}, + {"", ""}, + } + for _, c := range cases { + if got := dpkgOwner([]byte(c.out), "/usr/bin/example"); got != c.want { + t.Errorf("dpkgOwner(%q) = %q, want %q", c.out, got, c.want) + } + } +} + +func TestShellQuote(t *testing.T) { + plan := APTPlan{Commands: [][]string{{"a b", "it's", "", "x=1.0~rc1"}}} + if got, want := plan.String(), `'a b' 'it'\''s' '' 'x=1.0~rc1'`; got != want { + t.Fatalf("got %s, want %s", got, want) + } +} diff --git a/selfupdate/doc.go b/selfupdate/doc.go index e2e5437..e482c7d 100644 --- a/selfupdate/doc.go +++ b/selfupdate/doc.go @@ -78,6 +78,13 @@ // links are resolved first, so the file a link leads to is the one that is // judged and replaced. See [PackageManaged] for what is recognized. // +// The one exception is a .deb from an APT repository that is registered on +// the system, such as one whose package adds the repository when it is +// installed. With [Updater.APT] set, such an executable is checked +// against that repository and updated from it through APT, with sudo +// when the process is not root, after [APT.Confirm] agreed to the +// commands it was shown. +// // # Requests and credentials // // Requests are bounded by the context they are given. A source without an diff --git a/selfupdate/update.go b/selfupdate/update.go index dce429f..eda501e 100644 --- a/selfupdate/update.go +++ b/selfupdate/update.go @@ -75,6 +75,12 @@ type Updater struct { // means [PackageManaged]; a tool that ships no OS package and may // replace itself anywhere sets a function that always returns false. Managed func(path string) bool + // APT, when set, updates a managed executable that a .deb installed + // from a registered APT repository through APT, instead of refusing + // it; the repository then also replaces Source as where the latest + // version is read. See [APT] for when it applies. Nil refuses every + // managed executable. + APT *APT // MaxDownload bounds the archive size in bytes; zero means // [DefaultMaxDownload]. The archive is held in memory. MaxDownload int64 @@ -84,10 +90,17 @@ type Updater struct { type Result struct { // From is the version that ran before the update. From string - // Release is the latest release, or the one Install was given. + // Release is the latest release, or the one Install was given. When + // [APT] updates the executable, its Tag is the package's version in + // the repository, such as "1.2.3". Release Release - // Asset is the archive that was installed; empty when nothing was. + // Asset is the archive that was installed; empty when nothing was, or + // when APT installed the release. Asset string + // Package is the Debian package that owns the executable, as + // [APTPlan.Package] names it, when [APT] updates it, whether or not it + // installed anything; empty otherwise. + Package string // Path is the executable that was, or would have been, replaced. Path string // Updated is false when the running version was already current. @@ -97,8 +110,20 @@ type Result struct { // Check returns the latest release and whether it is newer than Current. // When the release's tag is no version, such as "release-2", it cannot // tell: it returns the release with an error wrapping [ErrNoVersion] -// rather than report the running version as current forever. +// rather than report the running version as current forever. An +// executable that [Updater.APT] applies to is checked against the APT +// repository instead, and newer means the repository offers a version +// other than the installed one. func (u *Updater) Check(ctx context.Context) (Release, bool, error) { + if _, pkg, err := u.aptPackage(ctx); err != nil { + return Release{}, false, err + } else if pkg != "" { + latest, installed, err := u.APT.check(ctx, pkg) + if err != nil { + return Release{}, false, err + } + return Release{Tag: latest}, latest != installed, nil + } if u.Source == nil { return Release{}, false, errors.New("selfupdate: Updater.Source is required") } @@ -118,10 +143,15 @@ func (u *Updater) Check(ctx context.Context) (Release, bool, error) { // release whose tag is no version is an error wrapping [ErrNoVersion], // with force too; [Updater.Install] installs such a release. func (u *Updater) Update(ctx context.Context, force bool) (Result, error) { - result, err := u.prepare() + result, err := u.prepare(ctx) if err != nil { return result, err } + if result.Package != "" { + version, updated, err := u.APT.update(ctx, result.Package, Release{}, force) + result.Release, result.Updated = Release{Tag: version}, updated + return result, err + } rel, newer, err := u.Check(ctx) if err != nil { return result, err @@ -142,12 +172,21 @@ func (u *Updater) Update(ctx context.Context, force bool) (Result, error) { // writable. The archive is verified against the release's checksums file // unless SkipChecksum is set; see [VerifyChecksum] for what that proves. // With a Verifier, the checksums file has to carry a valid signature too. +// An executable that [Updater.APT] applies to is updated through APT +// instead, to the version of the package rel's version names. func (u *Updater) Install(ctx context.Context, rel Release) (Result, error) { - result, err := u.prepare() + result, err := u.prepare(ctx) if err != nil { return result, err } result.Release = rel + if result.Package != "" { + if rel.Tag == "" { + return result, fmt.Errorf("%w: %q", ErrNoVersion, rel.Tag) + } + _, result.Updated, err = u.APT.update(ctx, result.Package, rel, true) + return result, err + } return u.install(ctx, result) } @@ -161,8 +200,15 @@ func (u *Updater) AssetName(rel Release) string { return u.Asset(rel, u.platform()) } -// prepare locates the executable and makes sure it may be replaced. -func (u *Updater) prepare() (Result, error) { +// prepare locates the executable and makes sure it may be replaced, or +// that APT updates it. +func (u *Updater) prepare(ctx context.Context) (Result, error) { + // APT needs neither an archive nor a Source. + if path, pkg, err := u.aptPackage(ctx); err != nil { + return Result{}, err + } else if pkg != "" { + return Result{From: u.Current, Path: path, Package: pkg}, nil + } if u.Asset == nil { return Result{}, errors.New("selfupdate: Updater.Asset is required") } @@ -193,6 +239,26 @@ func (u *Updater) prepare() (Result, error) { return result, nil } +// aptPackage returns the executable and the package APT updates it +// through, or no package when APT does not apply to it. +func (u *Updater) aptPackage(ctx context.Context) (path, pkg string, err error) { + if u.APT == nil { + return "", "", nil + } + path, err = u.executable() + if err != nil { + return "", "", err + } + managed := u.Managed + if managed == nil { + managed = PackageManaged + } + if !managed(path) { + return path, "", nil + } + return path, u.APT.owner(ctx, path), nil +} + // install downloads, verifies and installs result.Release over result.Path. func (u *Updater) install(ctx context.Context, result Result) (Result, error) { rel := result.Release From 7344d034d9fcce4e02d9d5f170b9ec907a9aa139 Mon Sep 17 00:00:00 2001 From: David Grieser Date: Wed, 25 Nov 2026 17:27:19 +0100 Subject: [PATCH 2/2] test(selfupdate): quote the downloaded file in the expected plan Windows temporary paths hold backslashes, which APTPlan.String quotes. Co-Authored-By: Claude Opus 5.5 --- selfupdate/apt_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selfupdate/apt_test.go b/selfupdate/apt_test.go index d650b17..058b9c0 100644 --- a/selfupdate/apt_test.go +++ b/selfupdate/apt_test.go @@ -147,7 +147,7 @@ func TestAPTUpdateAsUser(t *testing.T) { t.Fatalf("ran %q, showed %q", dpkg.ran, shown.Commands) } want := "/usr/bin/sudo -- /usr/bin/apt-get update\n" + - "/usr/bin/sudo -- /usr/bin/apt-get install --yes --allow-downgrades -- " + shown.File + "/usr/bin/sudo -- /usr/bin/apt-get install --yes --allow-downgrades -- " + shellQuote(shown.File) if got := shown.String(); got != want { t.Fatalf("plan:\n%s\nwant:\n%s", got, want) }