Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 25 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,20 @@ The zero value works for a goreleaser project with default archive names.
| `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 |
| `VerifyChecksums` | `nil` | runs on the downloaded checksum file before it is trusted, e.g. to check a signature |
| `TargetPath` | running executable, symlinks resolved | file to replace |
| `Managed` | Homebrew Cellar, `/usr/{s,}bin`, `/usr/lib{,64,exec}`, Nix store | locations owned by a package manager |
| `Client` | default transport with a 30s response header timeout | HTTP client |
| `Out` | `os.Stdout` | progress lines |

`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.
`Prepare` runs before `PreInstall`. When `VerifyChecksums` is set, it runs
inside `Prepare`, before the archive is downloaded. `Prepare` 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.

Replacement binaries are written through an exclusively created temporary
file beside the target, then atomically renamed into place. Existing
Expand All @@ -84,8 +86,22 @@ leftover cannot safely be distinguished from another update's active file.
The installation directory must be trusted against modification by other users.

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.
Verification proves the download matches what the release page lists. The
library checks no signature itself. Set `VerifyChecksums` to check one, as
below.

## Verifying checksums

`VerifyChecksums` runs before the archive is downloaded, and its error stops
the update. A checksum file the release lists no size for is capped at 1 MiB.

```go
installer.VerifyChecksums = func(ctx context.Context, rel selfupdate.Release, path string) error {
return exec.CommandContext(ctx, "gh", "attestation", "verify", path,
"--repo", "acme/mytool",
"--signer-workflow", "acme/mytool/.github/workflows/release.yml").Run()
}
```

## Hooks

Expand Down
153 changes: 135 additions & 18 deletions archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package selfupdate
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
Expand All @@ -20,6 +21,14 @@ const DefaultAssetTemplate = "{name}_{version}_{os}_{arch}.tar.gz"
// DefaultChecksumAsset is goreleaser's default checksum file name.
const DefaultChecksumAsset = "checksums.txt"

// maxChecksumBytes caps a checksum file the release lists no size for,
// on the VerifyChecksums path.
const maxChecksumBytes = 1 << 20

// verifyDirMode is the permission set on the subdirectory of Prepare's
// temp dir that holds the checksum file passed to VerifyChecksums.
const verifyDirMode os.FileMode = 0o700

// responseHeaderTimeout bounds how long the default client waits for
// response headers. Bodies stream until ctx is cancelled.
const responseHeaderTimeout = 30 * time.Second
Expand All @@ -32,14 +41,20 @@ const binaryMode os.FileMode = 0o755
// 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: a shared DefaultTransport clone with a 30s ResponseHeaderTimeout
Out io.Writer // progress lines; default os.Stdout
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
// VerifyChecksums, when set, runs on the downloaded checksum file
// before it is trusted, for example to check a signature or an
// attestation. path is the file inside Prepare's temp dir. An error
// stops the update before the archive is downloaded. A checksum file
// the release lists no size for is capped at 1 MiB.
VerifyChecksums func(ctx context.Context, rel Release, path string) error
TargetPath string // default: os.Executable(); symlinks are always resolved
Managed []ManagedInstall // nil means DefaultManagedInstalls; empty slice disables the check
Client *http.Client // default: a shared DefaultTransport clone with a 30s ResponseHeaderTimeout
Out io.Writer // progress lines; default os.Stdout
}

// defaultClient is built on first use and shared by every ArchiveInstaller
Expand All @@ -59,8 +74,12 @@ type archiveStaged struct {

// 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.
// directory. The running binary is untouched. VerifyChecksums together
// with SkipChecksum is refused before anything else.
func (a *ArchiveInstaller) Prepare(ctx context.Context, rel Release) (Staged, error) {
if a.VerifyChecksums != nil && a.SkipChecksum {
return nil, errors.New("selfupdate: VerifyChecksums needs the checksum file, but SkipChecksum is set")
}
target, err := a.target()
if err != nil {
return nil, err
Expand Down Expand Up @@ -98,12 +117,29 @@ func (a *ArchiveInstaller) Sweep() error {
}

// stage downloads asset into staged.dir, verifies it unless SkipChecksum,
// and extracts name beside it.
// and extracts name beside it. With VerifyChecksums set, the checksum file
// is downloaded and passed to the hook before the archive is requested.
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)
var err error
if a.VerifyChecksums != nil {
err = a.downloadTrusted(ctx, rel, asset, archivePath, staged.dir)
} else {
err = a.downloadChecked(ctx, rel, asset, archivePath)
}
if err != nil {
return err
}
staged.binary = filepath.Join(staged.dir, name)
return extractTo(archivePath, name, staged.binary)
}

// downloadChecked downloads asset to path, then streams the checksum file
// to verify it unless SkipChecksum. It is the path without VerifyChecksums.
func (a *ArchiveInstaller) downloadChecked(ctx context.Context, rel Release, asset Asset, path string) error {
sum, err := a.download(ctx, asset, path)
if err != nil {
return err
}
Expand All @@ -113,23 +149,67 @@ func (a *ArchiveInstaller) stage(
}
a.printf("Verified %s\n", asset.Name)
}
staged.binary = filepath.Join(staged.dir, name)
return extractTo(archivePath, name, staged.binary)
return nil
}

// download streams asset.URL to path, drawing a progress bar on a
// terminal, and returns the SHA-256 of the bytes written. When the release
// lists a size the body must match it exactly.
// downloadTrusted saves the checksum file into a verify subdirectory of
// dir and passes it to VerifyChecksums. Only after the hook accepts it is
// asset downloaded to path and checked against the saved file, so the
// bytes the hook checked are the bytes the archive is verified against.
// The saved file keeps only the base of the asset name, so it can neither
// escape dir nor collide with the archive.
func (a *ArchiveInstaller) downloadTrusted(
ctx context.Context, rel Release, asset Asset, path, dir string,
) error {
checksums, err := selectAsset(rel, a.checksumAsset())
if err != nil {
return err
}
verifyDir := filepath.Join(dir, "verify")
if err := os.Mkdir(verifyDir, verifyDirMode); err != nil {
return fmt.Errorf("selfupdate: create verify dir: %w", err)
}
checksumsPath := filepath.Join(verifyDir, filepath.Base(checksums.Name))
if _, err := a.downloadTo(ctx, checksums, checksumsPath, io.Discard, maxChecksumBytes); err != nil {
return err
}
if err := a.VerifyChecksums(ctx, rel, checksumsPath); err != nil {
return fmt.Errorf("selfupdate: verify %s: %w", checksums.Name, err)
}
sum, err := a.download(ctx, asset, path)
if err != nil {
return err
}
if err := verifySaved(checksumsPath, asset.Name, sum); err != nil {
return err
}
a.printf("Verified %s\n", asset.Name)
return nil
}

// download prints the download line and streams asset to path with a
// progress bar on a terminal. It 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))
return a.downloadTo(ctx, asset, path, a.out(), 0)
}

// downloadTo streams asset.URL to path, drawing progress to progressOut
// when it is a terminal, and returns the SHA-256 of the bytes written.
// When the release lists a size the body must match it exactly. When it
// lists none, a positive maxUnlisted caps the body and zero leaves it
// unbounded.
func (a *ArchiveInstaller) downloadTo(
ctx context.Context, asset Asset, path string, progressOut io.Writer, maxUnlisted int64,
) ([]byte, error) {
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 := copyBounded(io.MultiWriter(f, hash, progress), resp.Body, asset.Size)
progress := newProgressWriter(progressOut, resp.ContentLength)
copyErr := copyBody(io.MultiWriter(f, hash, progress), resp.Body, asset.Size, maxUnlisted)
progress.Finish()
if closeErr := f.Close(); copyErr == nil {
copyErr = closeErr
Expand All @@ -145,6 +225,28 @@ func (a *ArchiveInstaller) download(ctx context.Context, asset Asset, path strin
return hash.Sum(nil), nil
}

// copyBody streams body into dst. It applies copyBounded when size is
// listed, and copyCapped when size is not and maxUnlisted is positive.
func copyBody(dst io.Writer, body io.Reader, size, maxUnlisted int64) error {
if size <= 0 && maxUnlisted > 0 {
return copyCapped(dst, body, maxUnlisted)
}
return copyBounded(dst, body, size)
}

// copyCapped streams body into dst and reads at most limit+1 bytes. A
// body longer than limit is an error.
func copyCapped(dst io.Writer, body io.Reader, limit int64) error {
n, err := io.Copy(dst, io.LimitReader(body, limit+1))
if err != nil {
return err
}
if n > limit {
return fmt.Errorf("body exceeds %d bytes", limit)
}
return nil
}

// copyBounded streams body into dst. A positive size caps the read one
// byte past it, so a hostile payload cannot fill the temp dir before the
// checksum rejects it, and a body of any other length is an error. A zero
Expand Down Expand Up @@ -179,6 +281,21 @@ func (a *ArchiveInstaller) verify(ctx context.Context, rel Release, assetName st
})
}

// verifySaved checks sum against assetName's entry in the checksum file
// saved at path.
func verifySaved(path, assetName string, sum []byte) error {
f, err := os.Open(path) // path is inside the temp dir created by Prepare
if err != nil {
return fmt.Errorf("selfupdate: open checksums: %w", err)
}
defer func() { _ = f.Close() }()
sums, err := parseChecksums(f)
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 {
Expand Down
Loading
Loading