Files
w3cjandClaude Opus 5.5 b5c58d82b8 fix(tools): a platform's missing download (a 404) steps the tool back, not failing the resolve
mise 2026.11 (devvm's host mise since 0.2.0-rc.1) downloads some files as
it locks them and fails the whole `mise lock`, writing nothing, when one is
a 404. So while Node 24.23.0 had no musl builds on unofficial-builds,
Versions.Resolve returned tools_resolve_failed: a first run stopped, and
the daily check and devvm tools update kept their versions. The step back
only handled a lock that succeeded with an entry lacking a download.

- lockAll: after a full lock whose own log shows a 404, lock each tool on
  its own, and a tool that still fails one platform at a time, so its entry
  lacks only the missing platform and stepBack steps it back. Any other
  failure in the fallback is resolveFailed's.
- lockTool: one lock, its log started again, missing only on its own 404.
- olderWithDownload/lockVersions: when the step back's lock of its older
  versions 404s, lock them one at a time.
- logSays: shared by resolveFailed.
- Stub mise: MISE_STUB_FAIL=404 and MISE_STUB_OFFLINE_TOOL; per-tool,
  per-platform merging checked against real mise 2026.11.14.
- Tests: TestRefreshStepsBackPastA404, TestMise404.

Checked against real mise 2026.11.14: node steps back to 24.22.3, the
other 12 tools at their newest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 07:35:02 -07:00

587 lines
20 KiB
Go

package tools
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"maps"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"time"
"github.com/devvmhq/devvm/internal/backend"
"github.com/devvmhq/devvm/internal/fetch"
"github.com/devvmhq/devvm/internal/image"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/state"
"github.com/devvmhq/devvm/internal/trust"
)
// The mise devvm resolves the tools lock with, on the host: pinned, and
// checked against its checksum before it runs.
const miseVersion = "2026.11.14"
// miseSHA256 are the SHA-256s of mise's .tar.gz for each host, which is a
// third of its binary's size.
var miseSHA256 = map[string]string{
"macos-arm64": "76ff289e5ef2ffdeec54ad75275795d3e05699cb74b9f2f656652d3d1ddd7d11",
"macos-x64": "4ad598c502813f63cb9a82518f60e66f25d2c715e5bd5b949ca66323e94bd154",
"linux-arm64": "6afd537b39e2b1fe6594d4448318293d7e8c85469cbb51a6a01b28a6f26fbaf5",
"linux-x64": "42a3ff51c24b4315d679a07bbc598e299dda12fea0dfc0d6f90a543495834831",
}
const miseURL = "https://github.com/jdx/mise/releases/download/v%[1]s/mise-v%[1]s-%[2]s.tar.gz"
// miseInArchive is mise's binary in its .tar.gz.
const miseInArchive = "mise/bin/mise"
// downloadTimeout bounds mise's download, start to end.
const downloadTimeout = 10 * time.Minute
// downloadRetries is how many times mise's download is tried again after
// a failure that may pass.
const downloadRetries = 3
// miseCap caps mise's download and its binary: both are far less.
const miseCap = 256 << 20
// newClient is the client mise is downloaded with: redirects to https
// only.
func newClient() *fetch.Client { return fetch.NewClient(downloadTimeout, fetch.HTTPSOnly) }
// HostMise returns the path of the host's mise: a test build's stand-in
// (Mise) when it has one, else devvm's pinned mise, downloaded once and
// checked.
func (t Versions) HostMise(ctx context.Context) (string, error) {
if t.Mise != "" {
return t.Mise, nil
}
var osName string
switch t.OS {
case "darwin":
osName = "macos"
case "linux":
osName = "linux"
default:
return "", fmt.Errorf("no mise for %s", t.OS)
}
plat := osName + "-" + MiseArch(t.Arch)
dir := filepath.Join(t.Dirs.Mise(), miseVersion)
path := filepath.Join(dir, "mise")
if executable(path) {
return path, nil
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
// One devvm downloads it at a time: another that needs it meanwhile
// waits, then takes what that one kept.
unlock, err := platform.LockFile(ctx, t.Dirs.MiseDownloadLock(), msg.Waiting(t.Status, msg.MiseWaiting(miseVersion)))
if err != nil {
return "", err
}
defer unlock()
if executable(path) {
return path, nil
}
// What a killed download left in its own folder: no devvm downloads
// into one while this one holds the lock.
left, err := filepath.Glob(filepath.Join(dir, ".download-*"))
if err != nil {
return "", err
}
for _, d := range left {
if err := os.RemoveAll(d); err != nil {
return "", err
}
}
if err := t.trustCAs(); err != nil {
return "", err
}
return path, t.downloadMise(ctx, plat, dir, path)
}
// executable reports whether path is a regular file its owner can run.
func executable(path string) bool {
fi, err := os.Lstat(path)
return err == nil && fi.Mode().IsRegular() && fi.Mode()&0o100 != 0
}
// downloadMise downloads mise's .tar.gz for plat into a folder of its own
// in dir, and moves its binary to path once it checks out. fetch keeps
// the archive only once its SHA-256 is the pin's, and leaves nothing when
// it fails; a failure that may pass (no answer, 408, 429, 5xx) is tried
// again. The binary comes out of the archive as it was hashed again,
// through the descriptor it's read by (unpackMise).
func (t Versions) downloadMise(ctx context.Context, plat, dir, path string) error {
stop := t.Status(msg.DownloadingMise(miseVersion))
defer stop()
work, err := os.MkdirTemp(dir, ".download-")
if err != nil {
return err
}
defer func() { _ = os.RemoveAll(work) }()
tmp, archive := filepath.Join(work, "mise"), filepath.Join(work, "mise.tar.gz")
url := fmt.Sprintf(t.miseURL, miseVersion, plat)
err = fetch.Retry(ctx, downloadRetries, t.RetryDelay, func() (bool, error) {
err := fetch.Download(ctx, t.Client, url, archive, t.miseSums[plat], miseCap)
return fetch.Transient(err), err
})
if err == nil {
err = unpackMise(archive, t.miseSums[plat], tmp)
}
if err := miseFailed(ctx, t.Dirs.TrustedCAs(), err); err != nil {
_, _ = fmt.Fprintf(t.LogWriter(), "mise %s: %v\n", miseVersion, err)
return err
}
if err := os.Chmod(tmp, 0o700); err != nil { //nolint:gosec // a program: the user runs it
return err
}
return os.Rename(tmp, path)
}
// miseFailed is the message for mise's download that failed with err,
// nil for none; cas is the folder of the user's CAs.
func miseFailed(ctx context.Context, cas string, err error) error {
m, isMsg := errors.AsType[msg.M](err)
switch {
case err == nil:
return nil
case errors.Is(err, fetch.ErrChecksum):
return msg.MiseChecksum(miseVersion)
case errors.Is(err, fetch.ErrProxy) && isMsg:
// The company proxy's own refusal, such as its password unsaved.
return m
case fetch.Untrusted(err):
// A network that inspects TLS, whose CA this machine doesn't have.
return msg.ToolsUntrusted(cas).Because(err)
case ctx.Err() != nil:
return ctx.Err()
}
return msg.MiseDownloadFailed(miseVersion).Because(err)
}
// errNoMise is a mise archive without its binary (miseInArchive).
var errNoMise = errors.New("no " + miseInArchive + " in mise's archive")
// unpackMise writes the binary in mise's .tar.gz at archive to a new file
// out, no more than miseCap bytes of it, once the archive is the one its
// pin names (sum): hashed again through the descriptor it's then read by,
// so the bytes it unpacks are the ones it checked.
func unpackMise(archive, sum, out string) error {
f, err := os.Open(archive) //nolint:gosec // devvm's own download, in a folder of its own
if err != nil {
return err
}
defer func() { _ = f.Close() }()
h := sha256.New()
if _, err := io.Copy(h, io.LimitReader(f, miseCap+1)); err != nil {
return err
}
if got := hex.EncodeToString(h.Sum(nil)); got != sum {
return fmt.Errorf("unpacking mise: %w: %s", fetch.ErrChecksum, got)
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return err
}
gz, err := gzip.NewReader(f)
if err != nil {
return fmt.Errorf("unpacking mise: %w", err)
}
tr := tar.NewReader(gz)
for {
h, err := tr.Next()
if errors.Is(err, io.EOF) {
return errNoMise
} else if err != nil {
return fmt.Errorf("unpacking mise: %w", err)
}
if h.Name != miseInArchive || h.Typeflag != tar.TypeReg {
continue
}
if h.Size > miseCap {
return fmt.Errorf("unpacking mise: %w: %d bytes", fetch.ErrTooLarge, h.Size)
}
// What a killed run left goes first.
_ = os.Remove(out)
w, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) //nolint:gosec // devvm's own folder
if err != nil {
return err
}
_, err = io.Copy(w, io.LimitReader(tr, miseCap))
if cerr := w.Close(); err == nil {
err = cerr
}
return err
}
}
// miseCmd returns mise running in dir, a folder of devvm's own, with its
// state there too. mise also reads config files in the folders above (a
// shared temporary folder: anyone's): MISE_CEILING_PATHS, which needs the
// physical path, stops it at dir. It goes through config.toml's company
// proxy when devvm's environment sets none (Proxy's Env): its
// environment, never its arguments, holds the proxy's password, as mise
// takes it only in the proxy's URL. It trusts the user's CAs (caEnv), and
// logs to a file in dir too (miseLog).
func (t Versions) miseCmd(ctx context.Context, mise, dir string, args ...string) (*exec.Cmd, error) {
dir, err := filepath.EvalSymlinks(dir)
if err != nil {
return nil, err
}
proxyEnv, err := t.Proxy.Env(ctx)
if err != nil {
return nil, err
}
caEnv, err := t.caEnv(dir)
if err != nil {
return nil, err
}
cmd := exec.CommandContext(ctx, mise, args...) //nolint:gosec // devvm's own mise
cmd.Dir = dir
cmd.Env = append(os.Environ(),
"MISE_DATA_DIR="+filepath.Join(dir, "data"),
"MISE_CACHE_DIR="+filepath.Join(dir, "cache"),
"MISE_STATE_DIR="+filepath.Join(dir, "state"),
"MISE_CONFIG_DIR="+filepath.Join(dir, "config"),
"MISE_GLOBAL_CONFIG_FILE="+filepath.Join(dir, "config", "none.toml"),
"MISE_TRUSTED_CONFIG_PATHS="+dir,
"MISE_CEILING_PATHS="+filepath.Dir(dir),
"MISE_LOG_FILE="+filepath.Join(dir, miseLog),
// Six retries, as the tool builds' (shared-tools/build.sh): mise's
// three end within a two-minute stall.
"MISE_HTTP_RETRIES=6",
)
cmd.Env = append(cmd.Env, proxyEnv...)
cmd.Env = append(cmd.Env, caEnv...)
return cmd, nil
}
// miseLog is the file in its folder that the host's mise logs to as well
// (MISE_LOG_FILE), which resolveFailed reads.
const miseLog = "mise.log"
// untrustedCert is what mise's log says of a server's certificate that
// mise doesn't trust: rustls' error, which mise's TLS is on every host.
const untrustedCert = "invalid peer certificate"
// errUntrusted is what tools_untrusted carries, so Lock keeps it.
var errUntrusted = errors.New("a server's certificate isn't trusted")
// caEnv is what makes the host's mise trust the user's CAs (trust.Read)
// as well as this machine's own, in files in dir, mise's own folder.
// MISE_EXTRA_CA_CERTS names their bundle, which mise adds to its roots on
// every platform, but only in its own HTTP client: its Sigstore client,
// which fetches the trust root that its provenance checks need, ignores
// it. That client reads the system's roots as the rest of mise does, from
// files on Linux, so there SSL_CERT_FILE names a bundle of the system's
// and the user's CAs too (trust.CAs.Host), which every client reads.
// macOS's mise asks the Keychain, which no variable adds to. None without
// CAs.
func (t Versions) caEnv(dir string) ([]string, error) {
cas, err := trust.Read(t.Dirs.TrustedCAs())
if err != nil || len(cas) == 0 {
return nil, err
}
extra := filepath.Join(dir, "devvm-ca.pem")
if err := state.WriteFile(extra, cas.Bundle()); err != nil {
return nil, err
}
env := []string{"MISE_EXTRA_CA_CERTS=" + extra}
if t.OS != "linux" {
return env, nil
}
roots := filepath.Join(dir, "devvm-roots.pem")
bundle, rootsEnv, err := cas.Host(roots, t.Getenv)
if err != nil {
return nil, err
}
return append(env, rootsEnv...), state.WriteFile(roots, bundle)
}
// trustCAs makes the client that downloads the host's mise trust the
// user's CAs (trust.Read) as well as this machine's own.
func (t Versions) trustCAs() error {
pool, err := trust.Pool(t.Dirs.TrustedCAs())
if err != nil {
return err
}
t.Client.Trust(pool) // nil keeps this machine's own
return nil
}
// Resolve resolves shared-tools/mise.toml to the newest matching releases, for
// every platform VMs run, into out (and out.toml, the mise.toml it's
// from). Every tool, or nothing: offline, or with a tool mise can't
// resolve, it writes nothing and returns tools_resolve_failed
// (tools_untrusted for a certificate mise doesn't trust), with the
// details in the run log. mise's version lists come from its versions
// host (no GitHub rate limit). It returns the lock it wrote.
func (t Versions) Resolve(ctx context.Context, out string) (Lock, error) {
mise, err := t.HostMise(ctx)
if err != nil {
return Lock{}, err
}
tmp, err := os.MkdirTemp("", "devvm-tools.")
if err != nil {
return Lock{}, err
}
defer func() { _ = os.RemoveAll(tmp) }()
config, err := t.config()
if err != nil {
return Lock{}, err
}
if err := state.WriteFile(filepath.Join(tmp, "mise.toml"), config); err != nil {
return Lock{}, err
}
names, specs := configTools(config)
if err := t.lockAll(ctx, mise, tmp, names); err != nil {
return Lock{}, err
}
lock, err := parseLockFile(filepath.Join(tmp, "mise.lock"))
if err != nil {
return Lock{}, t.resolveFailed(ctx, tmp)
}
if lock, err = t.withSDKDownloads(ctx, lock); err != nil {
_, _ = fmt.Fprintln(t.LogWriter(), err)
return Lock{}, t.resolveFailed(ctx, tmp)
}
for _, n := range names {
if !lock.Has(n) {
return Lock{}, t.resolveFailed(ctx, tmp)
}
}
if lock, err = t.stepBack(ctx, mise, lock, names, specs); err != nil {
return Lock{}, err
}
if err := state.WriteFile(out+".toml", config); err != nil {
return Lock{}, err
}
return lock, state.WriteFile(out, lock.Bytes())
}
// notFound is what mise's log says of a download that isn't there: an
// HTTP 404.
const notFound = "(404 Not Found)"
// lockAll locks the tools of dir's mise.toml (names) for every platform
// into dir's mise.lock. mise fails the whole lock, writing nothing, when
// one platform's download of a tool's newest version isn't there (a 404,
// as node's musl builds for days after a node release), so then it locks
// each tool on its own, which mise adds to the lock, and it locks a tool
// that still fails one platform at a time, which mise adds to the tool's
// entry: the platforms whose download is there, leaving the rest for
// stepBack. Any other failure, the first lock's or one of these, is the
// resolve's (resolveFailed).
func (t Versions) lockAll(ctx context.Context, mise, dir string, names []string) error {
missing, err := t.lockTool(ctx, mise, dir, "", t.platforms()...)
if !missing {
return err
}
for _, tool := range names {
missing, err := t.lockTool(ctx, mise, dir, tool, t.platforms()...)
if !missing {
if err != nil {
return err
}
continue
}
for _, p := range t.platforms() {
if _, err := t.lockTool(ctx, mise, dir, tool, p); err != nil {
return err
}
}
}
return nil
}
// lockTool locks a tool ("" for all of them) for these platforms into
// dir's mise.lock, which keeps the other tools' entries and platforms.
// missing is a failure that its own log says was a download that isn't
// there (a 404), which isn't an error; any other failure is
// resolveFailed's. It starts the log in dir again, so it reads only this
// run's.
func (t Versions) lockTool(ctx context.Context, mise, dir, tool string, platforms ...string) (missing bool, err error) {
args := []string{"lock", "--platform", strings.Join(platforms, ",")}
if tool != "" {
args = append(args, tool)
}
cmd, err := t.miseCmd(ctx, mise, dir, args...)
if err != nil {
return false, err
}
if err := os.Remove(filepath.Join(dir, miseLog)); err != nil && !errors.Is(err, fs.ErrNotExist) {
return false, err
}
if err := t.LoggedCmd(ctx, msg.ResolvingTools(), cmd); err == nil {
return false, nil
}
if ctx.Err() == nil && logSays(dir, notFound) {
return true, nil
}
return false, t.resolveFailed(ctx, dir)
}
// logSays reports whether the log of mise's runs in dir has text.
func logSays(dir, text string) bool {
log, err := os.ReadFile(filepath.Join(dir, miseLog)) //nolint:gosec // mise's log, in devvm's own folder
return err == nil && bytes.Contains(log, []byte(text))
}
// resolveFailed is the failure of mise's run in dir: tools_untrusted when
// its log says a server's certificate wasn't trusted, as on a network
// that inspects TLS, else tools_resolve_failed.
func (t Versions) resolveFailed(ctx context.Context, dir string) error {
if ctx.Err() != nil {
return ctx.Err()
}
if logSays(dir, untrustedCert) {
return backend.Logged(msg.ToolsUntrusted(t.Dirs.TrustedCAs()).Because(errUntrusted))
}
return backend.Logged(msg.ToolsResolveFailed())
}
// candidates is how many older versions a step back tries.
const candidates = 5
// stepBack gives a tool whose newest entry has no download for some
// platform (a release without its files yet, a tag with none, node's musl
// builds for days after a release) the newest of its next older versions
// that has them, keeping its specifiers so it still matches mise.toml.
// Older versions come from the tool's backend (GitHub releases for aqua
// tools), not mise's versions host, which can list tags with no release.
// The next daily check tries the newest again.
func (t Versions) stepBack(ctx context.Context, mise string, lock Lock, names []string, specs map[string]string) (Lock, error) {
defer t.Status(msg.ResolvingTools())()
for _, tool := range names {
if lock.HasDownload(tool, t.platforms()) {
continue
}
v, backendName := lock.Version(tool), lock.Backend(tool)
older := t.olderVersions(ctx, mise, backendName, specs[tool], v)
one, c := t.olderWithDownload(ctx, mise, tool, backendName, older)
if one == nil {
t.Warn(msg.ToolNoDownload(tool, v))
continue
}
one = maps.Clone(one)
delete(one, "specifiers")
if s, ok := lock.first(tool)["specifiers"]; ok {
one["specifiers"] = s
}
var err error
if lock, err = lock.withEntry(tool, one); err != nil {
return Lock{}, err
}
t.Warn(msg.ToolSteppedBack(c, tool, v))
}
return lock, nil
}
// olderWithDownload returns the entry of the newest of these older
// versions of a tool (newest first) that has a download for every
// platform, and its version: nil when none has. mise fails the lock of
// them all when one has a download that isn't there (a 404), so then it
// locks them one at a time.
func (t Versions) olderWithDownload(ctx context.Context, mise, tool, backendName string, older []string) (lockEntry, string) {
entries, ok, missing := t.lockVersions(ctx, mise, tool, backendName, older)
if !ok && missing && len(older) > 1 {
for _, c := range older {
if one, v := t.olderWithDownload(ctx, mise, tool, backendName, []string{c}); one != nil {
return one, v
}
}
return nil, ""
}
if !ok {
return nil, ""
}
for _, c := range older {
if one := entries.versionEntry(tool, c); hasDownload(one, t.platforms()) {
return one, c
}
}
return nil, ""
}
// olderVersions lists up to five versions of a tool older than v, newest
// first: those its backend lists before v (all of them when v isn't
// listed), with spec's prefix ("24") unless it's latest.
func (t Versions) olderVersions(ctx context.Context, mise, backendName, spec, v string) []string {
dir, err := os.MkdirTemp("", "devvm-tools.")
if err != nil {
return nil
}
defer func() { _ = os.RemoveAll(dir) }()
args := []string{"ls-remote", backendName}
if spec != "" && spec != "latest" {
args = append(args, spec)
}
cmd, err := t.miseCmd(ctx, mise, dir, args...)
if err != nil {
return nil
}
out, err := cmd.Output()
if err != nil {
return nil
}
var vs []string
for _, line := range lines(out) {
if line == v {
break
}
if image.ToolVersion(line) { // it goes into a TOML list
vs = append(vs, line)
}
}
vs = vs[max(0, len(vs)-candidates):]
slices.Reverse(vs)
return vs
}
// lockVersions locks these versions of a tool, all in one lock (mise
// takes a list of versions), from the backend its newest came from (the
// name mise's registry gives it may stand for another), in a folder of
// its own: mise also reads the mise.toml of the folders above. False when
// there are none, or mise fails, and then missing when mise's log says a
// download wasn't there (a 404).
func (t Versions) lockVersions(ctx context.Context, mise, tool, backendName string, versions []string) (l Lock, ok, missing bool) {
if len(versions) == 0 {
return Lock{}, false, false
}
dir, err := os.MkdirTemp("", "devvm-tools.")
if err != nil {
return Lock{}, false, false
}
defer func() { _ = os.RemoveAll(dir) }()
list := `"` + strings.Join(versions, `","`) + `"`
config := []byte("[tools]\n" + tool + " = [" + list + "]\n")
if backendName != "" {
config = append(append(aliasTable(map[string]string{tool: backendName}), '\n'), config...)
}
if err := state.WriteFile(filepath.Join(dir, "mise.toml"), config); err != nil {
return Lock{}, false, false
}
cmd, err := t.miseCmd(ctx, mise, dir, "lock", "--platform", strings.Join(t.platforms(), ","))
if err != nil {
return Lock{}, false, false
}
lockErr := t.LoggedCmd(ctx, msg.ResolvingTools(), cmd) // what it locked is checked below
missing = lockErr != nil && ctx.Err() == nil && logSays(dir, notFound)
if l, err = parseLockFile(filepath.Join(dir, "mise.lock")); err == nil {
l, err = t.withSDKDownloads(ctx, l)
}
return l, err == nil, missing
}