Files
w3cjandClaude Opus 5.5 a8f0517579 feat(lima): devvm downloads Ubuntu's cloud image itself
Lima's download of the cloud image neither retries nor times out: one cut
in its 900 MB fails base's build, and a stall hangs it. devvm now
downloads the pinned image itself through fetch.Resumable
(ubuntu.Download), into images/ubuntu/<sha256>.img (Dirs.UbuntuImage),
resuming across cuts, stalls and runs, and gives Lima that file. Lima
2.3 checks a local file against the digest before it copies it.

- Before downloading, it takes the image from Lima's own download cache
  when that holds it with the pin's SHA-256: copied into a new file of
  devvm's own, mode 600, hashed as it's written, capped, stopped by the
  context, and kept only once it checks out. Lima's cache is never
  changed, and a base whose dated release Ubuntu may have removed still
  builds again.
- One devvm downloads at a time (images/locks/ubuntu-image), another
  waiting under ubuntu_image_waiting and looking again under the lock
  (TestUbuntuImageAfterWait, which fails without that second look).
- The download goes through the company proxy and trusts the user's CAs
  (Lima.Roots, from trust.Pool, which internal/cli passes through the
  registry), as do the Finder's lookups (TestNewTrustsRoots, and the
  registry's TestOverrides). An untrusted certificate is
  ubuntu_untrusted, naming the CAs' folder, one from a trusted CA
  that's for another host, out of date or not valid yet
  ubuntu_bad_certificate (check the clock and what answers for the
  host), and any other that fails to verify (a SHA-1 signature, a CA's
  name constraints, a key for clients alone) ubuntu_certificate_invalid,
  naming Go's reason, for the lookups (the listing, the checksums, their
  signature: TestLookupCertificates) and the download alike
  (TestLocalImageFailsFor), and a release Ubuntu removed (404, 410)
  ubuntu_release_gone, which names devvm rebuild base; none is retried.
  ubuntu_download_failed no longer starts with devvm.
- fetch.Untrusted, fetch.BadCertificate (an x509.HostnameError, or a
  CertificateInvalidError that's Expired) and fetch.Unverified (any
  failure to verify, with its reason, so every error the other two
  name), beside fetch.Gone, are the one
  place that tells a certificate's failures apart: Transient asks
  Unverified, the lookups and the download ask all three, host mise
  asks Untrusted, and a forbidigo rule keeps x509's and tls's
  verification errors in internal/fetch (TestCertificateClasses,
  TestTransient, testdata/lint, the owners doc's row).
- An https address, or a test build's file:// DEVVM_UBUNTU_URL, read
  from disk the same way; anything else is refused. The CLI tests'
  sandbox has a stand-in of this host's image in the store.
- Base's record keeps the image's address, and the key is as it was: it
  hashes the pin (release, file, digest), not the location.
- devvm gc --caches frees devvm's copies that no record names and that
  aren't pinned now, unchanged for an hour, a stopped .part and a killed
  import's .import included, and those of a kept image once its .img is
  there. A pin it can't read fails it.
- Of Lima's cache, it frees only an entry that devvm's own state shows a
  build of devvm's left: a base record names its address, devvm has its
  own copy of the image, and the installed Lima's own templates
  (share/lima/templates beside limactl, Lima.Templates) don't name it.
  An entry no record names may be the user's own Lima's, so it stays,
  and none is freed when the templates can't be read, with a line in
  the run log naming the folder and why. A test build's
  DEVVM_LIMA_TEMPLATES stands in for the templates folder.
- ubuntu.ParseImage reads a record's image as Image.String writes it,
  and ubuntu.IsSHA256 is the one check of a cloud image's SHA-256, in
  place of Lima's own regex.
- devvm space shows the copies as a cloud images row, freed by gc
  --caches, kept as state, as a release Ubuntu removed can't be
  downloaded again.

0.1.0's frozen state runs the new commands (fixture_v010_cloud_image):
devvm looks in Lima's cache under the SHA-256 of the address 0.1.0's
base record keeps and never changes the entry, base builds from devvm's
own copy, and gc --caches keeps that copy, frees Lima's entry the
record names and devvm's own stale copies, and keeps an older entry no
record names.

Docs: images.md (the download, its failures, the import, gc's rules),
space.md, backends/lima.md, settings.md (the lookups and the download
trust your CAs), troubleshooting.md, overview.md, testing.md,
tests.md, structure.md's internal/fetch row; the CHANGELOG's two Fixed
lines, which later commits make highlights, What to do 5 and 6, and the
release page's Ubuntu's cloud image in devvm's folder.

New messages: downloading_ubuntu, importing_ubuntu, ubuntu_image_waiting,
ubuntu_download_failed, ubuntu_release_gone, ubuntu_bad_certificate,
ubuntu_certificate_invalid, ubuntu_image_checksum, ubuntu_untrusted.
Lima.LocalImage is the seam, Lima.ImageClient the client.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 22:53:34 -07:00

400 lines
15 KiB
Go

package lima
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"errors"
"math/big"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
"github.com/devvmhq/devvm/assets"
"github.com/devvmhq/devvm/internal/fetch"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/ubuntu"
)
// imageServer serves body as the cloud image over TLS, counting requests;
// it returns the image as pinned and a client that trusts the server.
func imageServer(t *testing.T, body []byte) (ubuntu.Image, *fetch.Client, *atomic.Int32) {
t.Helper()
var asked atomic.Int32
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked.Add(1)
http.ServeContent(w, r, "img", time.Time{}, bytes.NewReader(body))
}))
t.Cleanup(srv.Close)
c := fetch.NewClient(time.Minute, fetch.HTTPSOnly)
c.Transport().TLSClientConfig = srv.Client().Transport.(*http.Transport).TLSClientConfig
c.Transport().Proxy = nil
sum := sha256.Sum256(body)
img := ubuntu.Image{URL: srv.URL + "/r/release-20260101/" + ubuntu.File("arm64"), Digest: "sha256:" + hex.EncodeToString(sum[:])}
return img, c, &asked
}
// clientOnlyServer is a TLS server whose certificate the client trusts
// and that's for 127.0.0.1 and in date, but whose key may only sign in
// as a client: neither untrusted nor out of date or for another host, so
// only its reason names what's wrong.
func clientOnlyServer(t *testing.T, h http.Handler) (*httptest.Server, *tls.Config) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "client only"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, IsCA: true, BasicConstraintsValid: true,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
cert, err := x509.ParseCertificate(der)
if err != nil {
t.Fatal(err)
}
srv := httptest.NewUnstartedServer(h)
srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}, MinVersion: tls.VersionTLS12}
srv.StartTLS()
t.Cleanup(srv.Close)
roots := x509.NewCertPool()
roots.AddCert(cert)
return srv, &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}
}
// limaCached puts data in Lima's download cache as Lima keeps url's.
func limaCached(t *testing.T, l *Lima, url string, data []byte) string {
t.Helper()
name := sha256.Sum256([]byte(url))
dir := filepath.Join(l.Dirs.UserCache, "lima", "download", "by-url-sha256", hex.EncodeToString(name[:]))
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "url"), []byte(url), 0o600); err != nil {
t.Fatal(err)
}
p := filepath.Join(dir, "data")
if err := os.WriteFile(p, data, 0o600); err != nil {
t.Fatal(err)
}
return p
}
// devvm downloads the pinned cloud image itself, once, into its own
// folder, and gives Lima that file: from Lima's cache when that holds it
// with the pin's digest, which stays there as it was, and otherwise from
// Ubuntu, each under its status line. The copy from Lima's cache is a
// file of devvm's own, only you can read, never a link to Lima's.
func TestLocalImage(t *testing.T) {
body := bytes.Repeat([]byte("ubuntu"), 5000)
const (
downloading = "downloading_ubuntu release=release-20260101"
importing = "importing_ubuntu release=release-20260101"
)
for _, tc := range []struct {
name string
cached []byte // Lima's cache's entry; nil for none
wantAsked int32
wantStatus []string
}{
{name: "downloaded", wantAsked: 1, wantStatus: []string{downloading}},
{name: "from Lima's cache", cached: body, wantAsked: 0, wantStatus: []string{importing}},
{name: "Lima's cache doesn't check out", cached: []byte("not it"), wantAsked: 1, wantStatus: []string{importing, downloading}},
} {
t.Run(tc.name, func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
var showed msg.Recorder
l.Reporter = &msg.Fake{OnStatus: showed.Add}
img, c, asked := imageServer(t, body)
l.ImageClient = c
var cached string
if tc.cached != nil {
cached = limaCached(t, l, img.URL, tc.cached)
}
for range 2 {
got, err := l.localImage(t.Context(), img)
if err != nil {
t.Fatal(err)
}
if want := l.Dirs.UbuntuImage(strings.TrimPrefix(img.Digest, "sha256:")); got != want {
t.Errorf("localImage = %s, want %s", got, want)
}
if data, err := os.ReadFile(got); err != nil || !bytes.Equal(data, body) { //nolint:gosec // the test's own sandbox
t.Errorf("the image: %d bytes, %v", len(data), err)
}
if fi, err := os.Stat(got); err != nil || fi.Mode().Perm() != 0o600 || fi.Sys().(*syscall.Stat_t).Nlink != 1 {
t.Errorf("the image: %v, %v, want a file of its own only you read", fi, err)
}
}
if n := asked.Load(); n != tc.wantAsked {
t.Errorf("Ubuntu was asked %d times, want %d", n, tc.wantAsked)
}
if !slices.Equal(showed.Names(), tc.wantStatus) {
t.Errorf("status lines: %q, want %q", showed.Names(), tc.wantStatus)
}
if cached != "" {
if data, err := os.ReadFile(cached); err != nil || !bytes.Equal(data, tc.cached) { //nolint:gosec // the test's own sandbox
t.Errorf("Lima's cache changed: %q, %v", data, err)
}
}
})
}
t.Run("file://", func(t *testing.T) {
// A test build's DEVVM_UBUNTU_URL: the same way as Ubuntu's, read
// from disk.
l, _, _ := testLima(t, "darwin")
dir := filepath.Join(t.TempDir(), "release-20260101")
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ubuntu.File("arm64")), body, 0o600); err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(body)
img := ubuntu.Image{URL: "file://" + filepath.Join(dir, ubuntu.File("arm64")), Digest: "sha256:" + hex.EncodeToString(sum[:])}
got, err := l.localImage(t.Context(), img)
if want := l.Dirs.UbuntuImage(hex.EncodeToString(sum[:])); err != nil || got != want {
t.Errorf("localImage = %s, %v, want %s", got, err, want)
}
})
t.Run("http://", func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
img := ubuntu.Image{URL: "http://cloud-images.example/release-20260101/" + ubuntu.File("arm64"), Digest: "sha256:" + testUbuntuSum}
if got, err := l.localImage(t.Context(), img); err == nil {
t.Errorf("localImage = %s, want it refused", got)
}
})
t.Run("cancelled", func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
img, c, _ := imageServer(t, body)
l.ImageClient = c
limaCached(t, l, img.URL, body)
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, err := l.localImage(ctx, img); !errors.Is(err, context.Canceled) {
t.Errorf("localImage: %v, want the context's error", err)
}
if regular(l.Dirs.UbuntuImage(strings.TrimPrefix(img.Digest, "sha256:"))) {
t.Error("a cancelled import kept the image")
}
})
t.Run("a download that fails", func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "no", http.StatusForbidden)
}))
defer srv.Close()
l.ImageClient = fetch.NewClient(time.Minute, fetch.HTTPSOnly)
l.ImageClient.Transport().TLSClientConfig = srv.Client().Transport.(*http.Transport).TLSClientConfig
l.ImageClient.Transport().Proxy = nil
img := ubuntu.Image{URL: srv.URL + "/release-20260101/" + ubuntu.File("arm64"), Digest: "sha256:" + testUbuntuSum}
if _, err := l.localImage(t.Context(), img); msg.IDOf(err) != "ubuntu_download_failed" {
t.Errorf("localImage: %v, want ubuntu_download_failed", err)
}
})
t.Run("a part that can't be written", func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
img, c, asked := imageServer(t, body)
l.ImageClient = c
if err := os.MkdirAll(l.Dirs.UbuntuImages(), 0o500); err != nil {
t.Fatal(err)
}
defer func() { _ = os.Chmod(l.Dirs.UbuntuImages(), 0o700) }() //nolint:gosec // a folder, which the test's cleanup deletes
if _, err := l.localImage(t.Context(), img); !errors.Is(err, fetch.ErrWrite) || msg.IDOf(err) != "" {
t.Errorf("localImage: %v, want this machine's own failure, not a download's", err)
}
if n := asked.Load(); n != 1 {
t.Errorf("Ubuntu was asked %d times, want once", n)
}
})
t.Run("the user's CAs", func(t *testing.T) {
// A network that inspects TLS, whose CA is in devvm's folder alone.
l, _, _ := testLima(t, "darwin")
img, c, _ := imageServer(t, body)
roots := c.Transport().TLSClientConfig.RootCAs
l.ImageClient = fetch.NewClient(time.Minute, fetch.HTTPSOnly)
l.ImageClient.Transport().Proxy = nil
if _, err := l.localImage(t.Context(), img); msg.IDOf(err) != "ubuntu_untrusted" {
t.Errorf("localImage without the CA: %v, want ubuntu_untrusted", err)
}
l.Roots = func() (*x509.CertPool, error) { return roots, nil }
l.ImageClient = fetch.NewClient(time.Minute, fetch.HTTPSOnly)
l.ImageClient.Transport().Proxy = nil
l.trusted = sync.OnceValue(func() error { return trustRoots(l.Roots, l.ImageClient) })
if _, err := l.localImage(t.Context(), img); err != nil {
t.Errorf("localImage with the CA: %v", err)
}
})
t.Run("a download that doesn't check out", func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
img, c, _ := imageServer(t, body)
l.ImageClient = c
img.Digest = "sha256:" + testUbuntuSum
if _, err := l.localImage(t.Context(), img); msg.IDOf(err) != "ubuntu_image_checksum" {
t.Errorf("localImage: %v, want ubuntu_image_checksum", err)
}
if _, err := os.Stat(l.Dirs.UbuntuImage(testUbuntuSum)); err == nil {
t.Error("kept an image that doesn't check out")
}
})
}
// A download that trying again can't mend says so: a release Ubuntu
// removed (404, 410) names devvm rebuild base, which pins one Ubuntu has,
// and a certificate from a CA this machine trusts that isn't the
// server's is no CA to add.
func TestLocalImageFailsFor(t *testing.T) {
for _, code := range []int{http.StatusNotFound, http.StatusGone} {
t.Run("a release that's gone: "+strconv.Itoa(code), func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "gone", code)
}))
defer srv.Close()
l.ImageClient = fetch.NewClient(time.Minute, fetch.HTTPSOnly)
l.ImageClient.Transport().TLSClientConfig = srv.Client().Transport.(*http.Transport).TLSClientConfig
l.ImageClient.Transport().Proxy = nil
img := ubuntu.Image{URL: srv.URL + "/release-20260101/" + ubuntu.File("arm64"), Digest: "sha256:" + testUbuntuSum}
if _, err := l.localImage(t.Context(), img); msg.IDOf(err) != "ubuntu_release_gone" {
t.Errorf("localImage: %v, want ubuntu_release_gone", err)
}
})
}
t.Run("a certificate for another host", func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
img, c, asked := imageServer(t, bytes.Repeat([]byte("ubuntu"), 5000))
l.ImageClient = c
img.URL = strings.Replace(img.URL, "127.0.0.1", "localhost", 1)
if _, err := l.localImage(t.Context(), img); msg.IDOf(err) != "ubuntu_bad_certificate" {
t.Errorf("localImage: %v, want ubuntu_bad_certificate", err)
}
if n := asked.Load(); n != 0 {
t.Errorf("the server was asked %d times, want none", n)
}
})
t.Run("a certificate that's otherwise not valid", func(t *testing.T) {
l, _, _ := testLima(t, "darwin")
var asked atomic.Int32
srv, conf := clientOnlyServer(t, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { asked.Add(1) }))
l.ImageClient = fetch.NewClient(time.Minute, fetch.HTTPSOnly)
l.ImageClient.Transport().TLSClientConfig = conf
l.ImageClient.Transport().Proxy = nil
img := ubuntu.Image{URL: srv.URL + "/release-20260101/" + ubuntu.File("arm64"), Digest: "sha256:" + testUbuntuSum}
_, err := l.localImage(t.Context(), img)
if m, _ := errors.AsType[msg.M](err); msg.IDOf(err) != "ubuntu_certificate_invalid" || m.Value("url") != img.URL ||
!strings.Contains(m.Value("reason"), "key usage") {
t.Errorf("localImage: %v, want ubuntu_certificate_invalid naming the key usage", err)
}
if n := asked.Load(); n != 0 {
t.Errorf("the server was asked %d times, want none", n)
}
})
}
// A devvm that finds another downloading the cloud image waits, showing
// why, and downloads nothing meanwhile.
func TestUbuntuImageLockWaits(t *testing.T) {
l, _, _ := testLima(t, "darwin")
img, c, asked := imageServer(t, []byte("ubuntu"))
l.ImageClient = c
if err := os.MkdirAll(l.Dirs.ImageLocks(), 0o700); err != nil {
t.Fatal(err)
}
unlock, err := platform.LockFile(t.Context(), l.Dirs.UbuntuImageLock(), nil)
if err != nil {
t.Fatal(err)
}
defer unlock()
ctx, cancel := context.WithTimeout(t.Context(), time.Minute) // a wait that shows nothing fails, never hangs
defer cancel()
var said msg.Recorder
l.Reporter = &msg.Fake{OnStatus: func(m msg.M) { said.Add(m); cancel() }}
if _, err := l.localImage(ctx, img); !errors.Is(err, context.Canceled) || !slices.Equal(said.Names(), []string{"ubuntu_image_waiting"}) || asked.Load() != 0 {
t.Errorf("held: %v, showed %q, asked %d", err, said.Names(), asked.Load())
}
}
// New makes both of the cloud image's clients, the lookups' and the
// download's, trust Roots once it's set, as the registry sets it, and the
// lookups name the folder of the user's CAs as the download does.
func TestNewTrustsRoots(t *testing.T) {
d := paths.Dirs{Config: t.TempDir()}
l := New(d, assets.FS, &msg.Fake{}, platform.Host{}, "", nil)
if f, ok := l.Ubuntu.(*ubuntu.Finder); !ok || f.CAs != d.TrustedCAs() {
t.Errorf("the lookups name %+v's CAs, want %s", l.Ubuntu, d.TrustedCAs())
}
pool := x509.NewCertPool()
calls := 0
l.Roots = func() (*x509.CertPool, error) { calls++; return pool, nil }
for range 2 {
if err := l.trust(); err != nil {
t.Fatal(err)
}
}
if calls != 1 {
t.Errorf("Roots read %d times, want once a run", calls)
}
for name, c := range map[string]*fetch.Client{"the download's": l.ImageClient, "the lookups'": l.finderClient} {
if tc := c.Transport().TLSClientConfig; tc == nil || tc.RootCAs != pool {
t.Errorf("%s client doesn't trust Roots", name)
}
}
}
// A devvm that waited for another's download looks again under the lock,
// and takes the image the other kept rather than download it again.
func TestUbuntuImageAfterWait(t *testing.T) {
l, _, _ := testLima(t, "darwin")
body := []byte("ubuntu")
img, c, asked := imageServer(t, body)
l.ImageClient = c
for _, dir := range []string{l.Dirs.ImageLocks(), l.Dirs.UbuntuImages()} {
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
}
unlock, err := platform.LockFile(t.Context(), l.Dirs.UbuntuImageLock(), nil)
if err != nil {
t.Fatal(err)
}
path := l.Dirs.UbuntuImage(strings.TrimPrefix(img.Digest, "sha256:"))
// The other devvm finishes while this one waits.
l.Reporter = &msg.Fake{OnStatus: func(msg.M) {
if err := os.WriteFile(path, body, 0o600); err != nil {
t.Error(err)
}
unlock()
}}
got, err := l.localImage(t.Context(), img)
if err != nil || got != path {
t.Fatalf("localImage = %s, %v, want %s", got, err, path)
}
if n := asked.Load(); n != 0 {
t.Errorf("Ubuntu was asked %d times, want none", n)
}
}