189 lines
6.0 KiB
Go
189 lines
6.0 KiB
Go
package fetch
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/downloader"
|
|
)
|
|
|
|
func sum(b []byte) string {
|
|
h := sha256.Sum256(b)
|
|
return hex.EncodeToString(h[:])
|
|
}
|
|
|
|
// rangeServer serves body at /file (honouring Range) and a SHA256SUMS.txt.
|
|
func rangeServer(t *testing.T, name string, body []byte, sums string) *httptest.Server {
|
|
t.Helper()
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/" + SumsAsset:
|
|
fmt.Fprint(w, sums)
|
|
case "/file":
|
|
http.ServeContent(w, r, name, timeZero, strings.NewReader(string(body)))
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
}))
|
|
t.Cleanup(srv.Close)
|
|
return srv
|
|
}
|
|
|
|
func TestExpectedSum(t *testing.T) {
|
|
body := []byte("new exe")
|
|
srv := rangeServer(t, "app.exe", body, sum(body)+" *app.exe\n"+strings.Repeat("0", 64)+" other.zip\n")
|
|
got, err := ExpectedSum(context.Background(), srv.Client(), srv.URL+"/"+SumsAsset, "app.exe")
|
|
if err != nil || got != sum(body) {
|
|
t.Fatalf("got %q, %v", got, err)
|
|
}
|
|
if _, err := ExpectedSum(context.Background(), srv.Client(), srv.URL+"/"+SumsAsset, "missing.exe"); err == nil {
|
|
t.Fatal("a name without an entry must fail")
|
|
}
|
|
if _, err := ExpectedSum(context.Background(), srv.Client(), "", "app.exe"); err == nil {
|
|
t.Fatal("no sums URL must fail closed")
|
|
}
|
|
}
|
|
|
|
func TestResumeContinuesPartialAndVerifies(t *testing.T) {
|
|
body := []byte(strings.Repeat("reims-go update payload ", 4096))
|
|
srv := rangeServer(t, "app.exe", body, "")
|
|
dir := t.TempDir()
|
|
final := filepath.Join(dir, "app.exe")
|
|
if err := os.WriteFile(final+".part", body[:1000], 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var last int64
|
|
path, err := Resume(context.Background(), srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), func(done, _ int64) { last = done })
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, _ := os.ReadFile(path)
|
|
if string(got) != string(body) || last != int64(len(body)) {
|
|
t.Fatalf("resumed file wrong: %d bytes, last progress %d", len(got), last)
|
|
}
|
|
if _, err := os.Stat(final + ".part"); !os.IsNotExist(err) {
|
|
t.Fatal(".part must be gone after a verified download")
|
|
}
|
|
|
|
// A verified final file is returned without hitting the network.
|
|
srv.Close()
|
|
if _, err := Resume(context.Background(), http.DefaultClient, srv.URL+"/file", final, int64(len(body)), sum(body), nil); err != nil {
|
|
t.Fatalf("already-verified file: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestResumeDiscardsMismatch(t *testing.T) {
|
|
body := []byte("tampered")
|
|
srv := rangeServer(t, "app.exe", body, "")
|
|
final := filepath.Join(t.TempDir(), "app.exe")
|
|
_, err := Resume(context.Background(), srv.Client(), srv.URL+"/file", final, 0, sum([]byte("expected")), nil)
|
|
if err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") {
|
|
t.Fatalf("want a mismatch error, got %v", err)
|
|
}
|
|
for _, p := range []string{final, final + ".part"} {
|
|
if _, err := os.Stat(p); !os.IsNotExist(err) {
|
|
t.Errorf("%s must not be kept after a mismatch", filepath.Base(p))
|
|
}
|
|
}
|
|
}
|
|
|
|
var timeZero = time.Time{}
|
|
|
|
type spyDownloader struct {
|
|
called atomic.Int32
|
|
}
|
|
|
|
func (s *spyDownloader) ID() string { return "test.spy" }
|
|
|
|
func (s *spyDownloader) Download(_ context.Context, _ downloader.Request, _ func(downloader.Progress)) error {
|
|
s.called.Add(1)
|
|
return nil
|
|
}
|
|
|
|
func TestResumeDirectBypassesDownloaderAndEnforcesMaxBytesAndStall(t *testing.T) {
|
|
spy := &spyDownloader{}
|
|
SetDefaultDownloader(func() downloader.Provider { return spy })
|
|
t.Cleanup(func() { SetDefaultDownloader(nil) })
|
|
|
|
// 1. Streaming response with unknown declared size (size=0) exceeding MaxBytes must abort early and delete .part.
|
|
bigBody := []byte(strings.Repeat("x", 4096))
|
|
stallRelease := make(chan struct{})
|
|
t.Cleanup(func() { close(stallRelease) })
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/chunked-big":
|
|
fl, _ := w.(http.Flusher)
|
|
w.WriteHeader(http.StatusOK)
|
|
for i := 0; i < len(bigBody); i += 64 {
|
|
_, _ = w.Write(bigBody[i : i+64])
|
|
if fl != nil {
|
|
fl.Flush()
|
|
}
|
|
}
|
|
case "/content-length-big":
|
|
w.Header().Set("Content-Length", "4096")
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write(bigBody)
|
|
case "/stall":
|
|
fl, _ := w.(http.Flusher)
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte("partial"))
|
|
if fl != nil {
|
|
fl.Flush()
|
|
}
|
|
select {
|
|
case <-stallRelease:
|
|
case <-r.Context().Done():
|
|
}
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
}))
|
|
t.Cleanup(srv.Close)
|
|
|
|
dir := t.TempDir()
|
|
chunkedFinal := filepath.Join(dir, "chunked.zip")
|
|
if _, err := ResumeDirect(context.Background(), srv.Client(), srv.URL+"/chunked-big", chunkedFinal, 0, sum(bigBody), nil, ResumeOptions{
|
|
MaxBytes: 256,
|
|
}); err == nil || !strings.Contains(err.Error(), "exceeds 256 byte limit") {
|
|
t.Fatalf("expected MaxBytes error on chunked body, got: %v", err)
|
|
}
|
|
if _, err := os.Stat(chunkedFinal + ".part"); !os.IsNotExist(err) {
|
|
t.Fatal("oversized .part must be deleted")
|
|
}
|
|
|
|
clFinal := filepath.Join(dir, "cl.zip")
|
|
if _, err := ResumeDirect(context.Background(), srv.Client(), srv.URL+"/content-length-big", clFinal, 0, sum(bigBody), nil, ResumeOptions{
|
|
MaxBytes: 256,
|
|
}); err == nil || !strings.Contains(err.Error(), "exceeds 256 byte limit") {
|
|
t.Fatalf("expected Content-Length MaxBytes error, got: %v", err)
|
|
}
|
|
|
|
// 2. Stalled stream aborts within StallTimeout instead of hanging indefinitely.
|
|
stallFinal := filepath.Join(dir, "stall.zip")
|
|
started := time.Now()
|
|
if _, err := ResumeDirect(context.Background(), srv.Client(), srv.URL+"/stall", stallFinal, 0, sum([]byte("x")), nil, ResumeOptions{
|
|
MaxBytes: 4096,
|
|
StallTimeout: 150 * time.Millisecond,
|
|
}); err == nil || !strings.Contains(err.Error(), "stalled") {
|
|
t.Fatalf("expected stall timeout error, got: %v", err)
|
|
}
|
|
if elapsed := time.Since(started); elapsed > 2*time.Second {
|
|
t.Fatalf("stall timeout took too long: %s", elapsed)
|
|
}
|
|
|
|
if spy.called.Load() != 0 {
|
|
t.Fatalf("ResumeDirect must bypass activeDownloader, got %d calls", spy.called.Load())
|
|
}
|
|
}
|