mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 16:27:33 -10:00
devvm upgrade [--check] [--to VERSION] [-f/--force] [--json] installs devvm's newest release the way this devvm was installed, asking first (upgrade_confirm, answered by --force). upgrade is a top-level exception in the cli skill: it acts on devvm itself, not this folder's VM, and it's the name other tools give the verb. It skips the layout check, as a layout a newer devvm wrote is a reason to run it. - install.sh's (<prefix>/lib/devvm/<version>/devvm, which <prefix>/bin/devvm links to): SHA256SUMS and its .minisig over HTTPS, the signature checked against the key built in from packaging/minisign.pub (packaging/key.go embeds the folder; no file, no key, and upgrade_no_key), the archive's SHA-256, unpacked into lib/.<v>.new.<pid>, run (--version), renamed to lib/<v>, the link switched atomically (symlink beside, rename over), run again through the link, rolled back on any failure; then older versions pruned as install.sh does (kept: the one that ran, any a running process names, another upgrade's staging folder). - Homebrew's (a Cellar/devvm/ keg): brew upgrade devvm, asked first, through the run log; --to refused. - Anything else: says how it was installed (a checkout build, go install, a copy elsewhere) and fails. - Already latest says so; a newest release older than this devvm is refused even with --force (rollback); --to installs a named one, older asked about (upgrade_confirm_older). --check and --json install nothing. minisign verification is Go's: ed25519 over blake2b.Sum512 for the default prehashed ED signature (legacy Ed refused), the key ID, the global signature over signature||trusted comment, and the trusted comment "devvm <version>" as scripts/release.sh writes it. Verified against a signature minisign 0.12 made. golang.org/x/crypto v0.58.0 added for blake2b only (approved; depguard allows only golang.org/x/crypto/blake2b); MVS raised x/text to v0.43.0 and x/tools to v0.51.0. mise run vuln: no vulnerability reached; the module-level GO-2026-5932 is x/crypto/openpgp, which devvm doesn't import. New: internal/upgrade (Detect, Source: Latest, Check for the release notice to call, Fetch; ParsePublicKey/Verify; Valid/Compare; Upgrader), internal/upgrade/upgradetest (TLS release server, minisign signer; tests only, a structure layer), fetch.Resolve (where a HEAD's redirects end), fetch.Download's size cap (mise's 256 MiB too). Test-build overrides: DEVVM_REPO_URL, DEVVM_RELEASE_KEY, DEVVM_RELEASE_CA, DEVVM_TEST_VERSION; script command release_server [-badsig]. Security review (security-audit skill, guidance mode, a fresh reviewer): - Prerelease order compared suffixes as text (rc.10 < rc.9), which let an older signed prerelease past the rollback refusal: fixed, semver precedence, with table cases. - No cap on the archive download (a host could fill TMPDIR before the checksum failed): fixed, fetch.Download takes a limit. - Two upgrades at once: prune removed another's staging folder: fixed, .<v>.new/old.<pid> folders are kept while that pid runs. - A failed rollback of the link was silent: fixed, upgrade_rollback_failed names the link and the old devvm, and the new folder stays so the link isn't left dangling. - QEMU's guestfwd names devvm with commas doubled, which the in-use check missed: fixed. - Freeze (a host serving the current version as newest forever): no boundary crossed, inherent without signed expiring metadata; documented in internals/install.md. Checked sound: nothing untrusted runs or unpacks before the signature and SHA-256; versions from the redirect and --to pass Valid before any URL or path; tar takes only regular files in its one folder (no links, subfolders, ..), 512 MiB cap, fixed modes; test overrides are read only by test builds. Tests: minisign (real minisign fixture, tampering, legacy, other key), each install kind against the fake TLS server, bad signature, wrong trusted comment, replaced archive (wrong SHA), bad archives, a new devvm that fails before and after the switch, a failed switch (old kept), a failed rollback, downgrade refused and --to, pruning, Homebrew via a brew script, Check, Latest's failures, Compare; CLI test upgrade.txtar. Docs: getting-started/install.md (Upgrading: how, what it checks, an older release, --json), getting-started/commands.md (This machine row, Upgrading devvm, questions, output for scripts), internals/install.md (devvm upgrade), contributing (release_server), the CLI reference. Co-Authored-By: Claude Opus 5.5 <[email protected]>
296 lines
9.2 KiB
Go
296 lines
9.2 KiB
Go
// Package fetch is how devvm reaches the web: an HTTP client with a
|
|
// timeout and a redirect policy, retries of the failures that may pass,
|
|
// reads capped at a size, and downloads checked against their SHA-256.
|
|
// It is the standard library only.
|
|
package fetch
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Client is the HTTP client devvm uses: other packages name this type, not
|
|
// net/http's. Only NewClient makes one that works, so every request has its
|
|
// timeout and its redirect policy; any other, such as &Client{}, fails
|
|
// every request with ErrNoClient.
|
|
type Client struct {
|
|
hc *http.Client
|
|
t *http.Transport
|
|
}
|
|
|
|
// Redirects is the redirects a client follows.
|
|
type Redirects int
|
|
|
|
const (
|
|
// HTTPSOnly follows redirects to https addresses only.
|
|
HTTPSOnly Redirects = iota
|
|
// SameScheme follows redirects on the first request's scheme only, so
|
|
// a server can't send a client that reads file:// addresses to a file.
|
|
SameScheme
|
|
)
|
|
|
|
// maxRedirects is how many redirects a client follows, as net/http's own
|
|
// client does.
|
|
const maxRedirects = 10
|
|
|
|
var (
|
|
// ErrRedirect is a redirect refused: trying again won't help.
|
|
ErrRedirect = errors.New("redirect refused")
|
|
// ErrTooLarge is a body over its cap.
|
|
ErrTooLarge = errors.New("too large")
|
|
// ErrChecksum is a download whose SHA-256 isn't the one asked for.
|
|
ErrChecksum = errors.New("the SHA-256 doesn't match")
|
|
// ErrNoClient is a request on a Client that NewClient didn't make.
|
|
ErrNoClient = errors.New("not a client NewClient made")
|
|
// ErrProxy is a proxy its caller set (Transport's Proxy) that can't
|
|
// be gone through, such as a company proxy whose password isn't
|
|
// saved: trying again won't help.
|
|
ErrProxy = errors.New("no proxy to go through")
|
|
// errRequest is a request that can't be made, such as one for an
|
|
// address that isn't one.
|
|
errRequest = errors.New("no request")
|
|
)
|
|
|
|
// NewClient returns a client whose every request, its body included, takes
|
|
// at most timeout, following redirects as r says, on its own copy of
|
|
// net/http's default transport (environment proxies included), which a
|
|
// caller can change: config.toml's company proxy is its caller's to set
|
|
// (settings.CompanyProxy.Route), as fetch reads no settings.
|
|
func NewClient(timeout time.Duration, r Redirects) *Client {
|
|
t := &http.Transport{}
|
|
if d, ok := http.DefaultTransport.(*http.Transport); ok {
|
|
t = d.Clone()
|
|
}
|
|
check := httpsOnly
|
|
if r == SameScheme {
|
|
check = sameScheme
|
|
}
|
|
return &Client{hc: &http.Client{Transport: t, Timeout: timeout, CheckRedirect: check}, t: t}
|
|
}
|
|
|
|
// Do sends req as net/http's Client.Do does, with the client's timeout and
|
|
// redirect policy.
|
|
func (c *Client) Do(req *http.Request) (*http.Response, error) {
|
|
if c == nil || c.hc == nil {
|
|
return nil, ErrNoClient
|
|
}
|
|
return c.hc.Do(req)
|
|
}
|
|
|
|
// Transport is the client's own transport, which a caller may change
|
|
// before its first request: a dialer, a proxy, another scheme. It is nil
|
|
// for a Client NewClient didn't make.
|
|
func (c *Client) Transport() *http.Transport {
|
|
if c == nil {
|
|
return nil
|
|
}
|
|
return c.t
|
|
}
|
|
|
|
// Trust makes the client's TLS connections trust roots instead of the
|
|
// system's roots, before its first request: nil keeps the system's.
|
|
func (c *Client) Trust(roots *x509.CertPool) {
|
|
if c == nil || c.t == nil || roots == nil {
|
|
return
|
|
}
|
|
if c.t.TLSClientConfig == nil {
|
|
c.t.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12}
|
|
}
|
|
c.t.TLSClientConfig.RootCAs = roots
|
|
}
|
|
|
|
func httpsOnly(req *http.Request, via []*http.Request) error {
|
|
if len(via) >= maxRedirects {
|
|
return fmt.Errorf("%w: too many", ErrRedirect)
|
|
}
|
|
if req.URL.Scheme != "https" {
|
|
return fmt.Errorf("%w: to %s", ErrRedirect, req.URL.Scheme)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func sameScheme(req *http.Request, via []*http.Request) error {
|
|
if len(via) >= maxRedirects {
|
|
return fmt.Errorf("%w: too many", ErrRedirect)
|
|
}
|
|
if req.URL.Scheme != via[0].URL.Scheme {
|
|
return fmt.Errorf("%w: from %s to %s", ErrRedirect, via[0].URL.Scheme, req.URL.Scheme)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// StatusError is an answer other than 200 OK.
|
|
type StatusError struct {
|
|
URL string
|
|
Code int
|
|
Status string // the status line's text, such as "404 Not Found"
|
|
}
|
|
|
|
func (e *StatusError) Error() string { return e.URL + ": " + e.Status }
|
|
|
|
// TransientStatus reports whether an answer with this status code may be
|
|
// different when asked again: 408, 429 or a server error.
|
|
func TransientStatus(code int) bool {
|
|
return code == http.StatusRequestTimeout || code == http.StatusTooManyRequests || code >= 500
|
|
}
|
|
|
|
// Transient reports whether a request that failed with err may succeed
|
|
// when tried again: one that got no answer or lost it partway, or got a
|
|
// status TransientStatus names. A refused redirect, a request that can't
|
|
// be made, a client NewClient didn't make, a proxy that can't be gone
|
|
// through, a body over its cap and a SHA-256 that doesn't match are not.
|
|
func Transient(err error) bool {
|
|
var se *StatusError
|
|
switch {
|
|
case err == nil:
|
|
return false
|
|
case errors.As(err, &se):
|
|
return TransientStatus(se.Code)
|
|
case errors.Is(err, ErrRedirect), errors.Is(err, errRequest), errors.Is(err, ErrNoClient),
|
|
errors.Is(err, ErrProxy), errors.Is(err, ErrTooLarge), errors.Is(err, ErrChecksum):
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Retry runs try until it succeeds, it fails and says not to try again,
|
|
// the context ends, or it has been tried again retries times. It waits
|
|
// delay before the first retry and twice as long before each one after.
|
|
// It returns try's last error, or the context's once it has ended.
|
|
func Retry(ctx context.Context, retries int, delay time.Duration, try func() (again bool, err error)) error {
|
|
for n := 0; ; n++ {
|
|
if err := ctx.Err(); err != nil { // file:// reads don't watch the context
|
|
return err
|
|
}
|
|
again, err := try()
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
if !again || n == retries {
|
|
return err
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case <-time.After(delay):
|
|
}
|
|
delay *= 2
|
|
}
|
|
}
|
|
|
|
// ReadCapped reads r to its end, failing with ErrTooLarge when it holds
|
|
// more than limit bytes.
|
|
func ReadCapped(r io.Reader, limit int64) ([]byte, error) {
|
|
data, err := io.ReadAll(io.LimitReader(r, limit+1))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if int64(len(data)) > limit {
|
|
return nil, fmt.Errorf("%w: more than %d bytes", ErrTooLarge, limit)
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
// Open GETs url and returns the body of a 200 OK answer, which the caller
|
|
// closes; any other answer is a *StatusError.
|
|
func Open(ctx context.Context, c *Client, url string) (io.ReadCloser, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%w: %w", errRequest, err)
|
|
}
|
|
resp, err := c.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
_ = resp.Body.Close()
|
|
return nil, &StatusError{URL: url, Code: resp.StatusCode, Status: resp.Status}
|
|
}
|
|
return resp.Body, nil
|
|
}
|
|
|
|
// Resolve returns the address a HEAD of url ends at once the client has
|
|
// followed its redirects, as GitHub's releases/latest goes to its newest
|
|
// release's page, when the answer there is 200 OK; any other answer is a
|
|
// *StatusError.
|
|
func Resolve(ctx context.Context, c *Client, url string) (string, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodHead, url, http.NoBody)
|
|
if err != nil {
|
|
return "", fmt.Errorf("%w: %w", errRequest, err)
|
|
}
|
|
resp, err := c.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
_ = resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return "", &StatusError{URL: url, Code: resp.StatusCode, Status: resp.Status}
|
|
}
|
|
return resp.Request.URL.String(), nil
|
|
}
|
|
|
|
// Get returns the body of a 200 OK answer to a GET of url, failing with
|
|
// ErrTooLarge when it's more than limit bytes.
|
|
func Get(ctx context.Context, c *Client, url string, limit int64) ([]byte, error) {
|
|
body, err := Open(ctx, c, url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = body.Close() }()
|
|
data, err := ReadCapped(body, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s: %w", url, err)
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
// Download writes the body of a GET of url to path, mode 600, and keeps
|
|
// it only when its SHA-256 is sum (hex): one that isn't fails with
|
|
// ErrChecksum, before anything can use it, and one over limit bytes with
|
|
// ErrTooLarge, before it fills the disk. On any failure nothing is left
|
|
// at path.
|
|
func Download(ctx context.Context, c *Client, url, path, sum string, limit int64) (err error) {
|
|
body, err := Open(ctx, c, url)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = body.Close() }()
|
|
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) //nolint:forbidigo,gosec // the caller's own path, a download streamed into it, removed on any failure
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() {
|
|
if err != nil {
|
|
_ = os.Remove(path)
|
|
}
|
|
}()
|
|
h := sha256.New()
|
|
n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(body, limit+1))
|
|
if cerr := f.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n > limit {
|
|
return fmt.Errorf("%s: %w: more than %d bytes", url, ErrTooLarge, limit)
|
|
}
|
|
if got := hex.EncodeToString(h.Sum(nil)); sum == "" || !strings.EqualFold(got, sum) {
|
|
return fmt.Errorf("%s: %w: %s", url, ErrChecksum, got)
|
|
}
|
|
return nil
|
|
}
|