package assets import ( "bytes" "crypto/sha256" "encoding/hex" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "slices" "strconv" "sync" "testing" "time" ) // devvmFetch is devvm-fetch as base.sh installs it, written into a // folder of the test's own, with a sleep there that waits for nothing, so // its tries don't wait on the real clock. func devvmFetch(t *testing.T) (script, bin string) { t.Helper() for _, tool := range []string{"curl", "sha256sum"} { if _, err := exec.LookPath(tool); err != nil { t.Skipf("no %s: devvm-fetch runs it", tool) } } body := heredoc(t, "sudo tee /usr/local/bin/devvm-fetch >/dev/null <<'SH'", "SH") dir := t.TempDir() script = filepath.Join(dir, "devvm-fetch") must(t, os.WriteFile(script, []byte(body+"\n"), 0o600)) bin = filepath.Join(dir, "bin") must(t, os.Mkdir(bin, 0o700)) must(t, os.WriteFile(filepath.Join(bin, "sleep"), []byte("#!/bin/sh\nexit 0\n"), 0o700)) //nolint:gosec // a program: the script runs it return script, bin } // fetchServer serves body as a file server does (Range), going wrong on // its first requests as fail says, and records each request's Range: // "cut" sends a quarter of the body then drops the connection, "500" // answers that, "whole" sends the whole body (200) whatever range it was // asked for, and "other" serves another file of the same length. type fetchServer struct { body, other []byte fail []string mu sync.Mutex ranges []string } func (f *fetchServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.mu.Lock() n := len(f.ranges) f.ranges = append(f.ranges, r.Header.Get("Range")) f.mu.Unlock() how := "" if n < len(f.fail) { how = f.fail[n] } switch how { case "500": http.Error(w, "no", http.StatusInternalServerError) case "redirect": http.Redirect(w, r, "http://"+r.Host+r.URL.Path, http.StatusFound) //nolint:gosec // G710: the test's own server, sending curl back to itself over http case "whole": _, _ = w.Write(f.body) case "other": http.ServeContent(w, r, "f", time.Time{}, bytes.NewReader(f.other)) case "cut": cw := &quarterWriter{ResponseWriter: w, left: len(f.body) / 4} http.ServeContent(cw, r, "f", time.Time{}, bytes.NewReader(f.body)) panic(http.ErrAbortHandler) // drops the connection default: http.ServeContent(w, r, "f", time.Time{}, bytes.NewReader(f.body)) } } // quarterWriter writes no more than left bytes of a body, flushed. type quarterWriter struct { http.ResponseWriter left int } func (q *quarterWriter) Write(b []byte) (int, error) { n := min(len(b), q.left) q.left -= n n, err := q.ResponseWriter.Write(b[:n]) if fl, ok := q.ResponseWriter.(http.Flusher); ok { fl.Flush() } if err == nil && n < len(b) { panic(http.ErrAbortHandler) } return n, err } // devvm-fetch keeps only a file whose checksum is the one asked for: it // resumes a download that was cut from where it stopped, starts again from // nothing when the server won't resume (curl's 33) or a resume joined two // files (the server changed it), and fails after five tries that failed. func TestDevvmFetchTries(t *testing.T) { script, bin := devvmFetch(t) body := bytes.Repeat([]byte("0123456789abcdef"), 4096) other := bytes.Repeat([]byte("fedcba9876543210"), 4096) sum := sha256.Sum256(body) quarter := "bytes=" + strconv.Itoa(len(body)/4) + "-" for _, tc := range []struct { name string fail []string want bool wantRanges []string }{ {name: "whole", want: true, wantRanges: []string{""}}, {name: "cut", fail: []string{"cut"}, want: true, wantRanges: []string{"", quarter}}, {name: "a range answered whole", fail: []string{"cut", "whole"}, want: true, wantRanges: []string{"", quarter, ""}}, {name: "the file changed", fail: []string{"cut", "other"}, want: true, wantRanges: []string{"", quarter, ""}}, {name: "five failures", fail: []string{"500", "500", "500", "500", "500"}, wantRanges: []string{"", "", "", "", ""}}, // A redirect goes only to https, as devvm's own downloads do. {name: "a redirect to http", fail: []string{"redirect", "redirect", "redirect", "redirect", "redirect"}, wantRanges: []string{"", "", "", "", ""}}, } { t.Run(tc.name, func(t *testing.T) { f := &fetchServer{body: body, other: other, fail: tc.fail} srv := httptest.NewServer(f) defer srv.Close() out := filepath.Join(t.TempDir(), "f") cmd := exec.CommandContext(t.Context(), "sh", script, srv.URL+"/f", hex.EncodeToString(sum[:]), out) //nolint:gosec // G204: devvm's own embedded script, with the test's arguments cmd.Env = []string{"PATH=" + bin + string(os.PathListSeparator) + os.Getenv("PATH"), "HOME=" + t.TempDir()} msgs, err := cmd.CombinedOutput() if (err == nil) != tc.want { t.Fatalf("devvm-fetch: %v, want success %v:\n%s", err, tc.want, msgs) } f.mu.Lock() got := f.ranges f.mu.Unlock() if !slices.Equal(got, tc.wantRanges) { t.Errorf("ranges asked: %q, want %q\n%s", got, tc.wantRanges, msgs) } data, rerr := os.ReadFile(out) //nolint:gosec // the test's own temp folder switch { case tc.want && !bytes.Equal(data, body): t.Errorf("the file: %d bytes, %v", len(data), rerr) case !tc.want && rerr == nil: t.Error("a failed download left its file") } }) } }