Files
Reims-Go/internal/app/download_host_test.go
T

287 lines
9.7 KiB
Go

package app
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
)
type downloadTestEnv struct {
app *App
h *fakedriver.Harness
plugin string
other string
roots []string
mu sync.Mutex
events []downloadEvent
}
func newDownloadTestEnv(t *testing.T, origins ...string) *downloadTestEnv {
t.Helper()
h := fakedriver.NewHarness(t)
e := &downloadTestEnv{h: h, plugin: "test.fake.dl", other: "test.fake.other"}
perms := make([]string, 0, len(origins))
for _, o := range origins {
perms = append(perms, "net:"+o)
}
h.AddWithPermissions("hosted", e.plugin, "test.driver.dl", perms...)
h.Add("hosted", e.other, "test.driver.dlother")
e.app = &App{cfg: &config.Config{DataRoot: h.DataRoot}}
e.roots = []string{filepath.Join(h.DataRoot, "plugins", "data", e.plugin)}
return e
}
func (e *downloadTestEnv) notify(method string, params any) {
if method != "download/progress" {
return
}
ev, ok := params.(downloadEvent)
if !ok {
return
}
e.mu.Lock()
e.events = append(e.events, ev)
e.mu.Unlock()
}
func (e *downloadTestEnv) start(t *testing.T, pluginID string, req map[string]any) (string, error) {
t.Helper()
raw, _ := json.Marshal(req)
res, err := e.app.startPluginDownload(e.h.Broker, e.notify, pluginID, e.roots, raw)
if err != nil {
return "", err
}
return res.(map[string]any)["id"].(string), nil
}
// final waits for the last notification of a download and returns it.
func (e *downloadTestEnv) final(t *testing.T, id string) downloadEvent {
t.Helper()
var last downloadEvent
waitFor(t, "download "+id+" to finish", func() bool {
e.mu.Lock()
defer e.mu.Unlock()
for _, ev := range e.events {
if ev.ID == id && ev.Status != "running" {
last = ev
return true
}
}
return false
})
return last
}
func sum(b []byte) string {
s := sha256.Sum256(b)
return hex.EncodeToString(s[:])
}
func TestHostDownloadVerifiesAndReportsProgress(t *testing.T) {
body := []byte(strings.Repeat("reims", 1000))
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/file.bin":
_, _ = w.Write(body)
case "/SHA256SUMS.txt":
fmt.Fprintf(w, "%s other.bin\n%s file.bin\n", sum([]byte("x")), sum(body))
case "/one.sha256":
fmt.Fprintln(w, sum(body))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
e := newDownloadTestEnv(t, srv.URL)
cases := map[string]map[string]any{
"explicit hash": {"url": srv.URL + "/file.bin", "sha256": sum(body), "dest": "a/file.bin"},
"sums file": {"url": srv.URL + "/file.bin", "sha256_url": srv.URL + "/SHA256SUMS.txt", "sha256_name": "file.bin", "dest": "b/file.bin"},
"single hash": {"url": srv.URL + "/file.bin", "sha256_url": srv.URL + "/one.sha256", "dest": "c/file.bin"},
}
for name, req := range cases {
id, err := e.start(t, e.plugin, req)
if err != nil {
t.Fatalf("%s: %v", name, err)
}
ev := e.final(t, id)
if ev.Status != "done" || ev.Path == "" {
t.Fatalf("%s: final event = %+v", name, ev)
}
got, err := os.ReadFile(ev.Path)
if err != nil || string(got) != string(body) {
t.Fatalf("%s: file = %d bytes, %v", name, len(got), err)
}
if !pathInside(e.roots[0], ev.Path) {
t.Fatalf("%s: %s is outside the plugin's data folder", name, ev.Path)
}
}
}
func TestHostDownloadRejectsAWrongHashAndKeepsNoFile(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("payload")) }))
defer srv.Close()
e := newDownloadTestEnv(t, srv.URL)
id, err := e.start(t, e.plugin, map[string]any{"url": srv.URL + "/x", "sha256": sum([]byte("something else")), "dest": "bad.bin"})
if err != nil {
t.Fatal(err)
}
if ev := e.final(t, id); ev.Status != "failed" || !strings.Contains(ev.Error, "SHA256") {
t.Fatalf("event = %+v", ev)
}
if _, err := os.Stat(filepath.Join(e.roots[0], "bad.bin")); !os.IsNotExist(err) {
t.Fatal("a download with the wrong hash was kept")
}
}
func TestHostDownloadChecksOriginsAndDestinations(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }))
defer srv.Close()
denied := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("no")) }))
defer denied.Close()
e := newDownloadTestEnv(t, srv.URL) // a full http://127.0.0.1:port origin
outside := filepath.Join(t.TempDir(), "out.bin")
bad := map[string]map[string]any{
"undeclared origin": {"url": denied.URL + "/x", "sha256": sum([]byte("ok")), "dest": "a.bin"},
"undeclared checksum": {"url": srv.URL + "/x", "sha256_url": denied.URL + "/sums", "dest": "a.bin"},
"plain http to a remote": {"url": "http://example.com/x", "sha256": sum([]byte("ok")), "dest": "a.bin"},
"url with user info": {"url": strings.Replace(srv.URL, "http://", "http://user:pw@", 1) + "/x", "sha256": sum([]byte("ok")), "dest": "a.bin"},
"file scheme": {"url": "file:///C:/Windows/win.ini", "sha256": sum([]byte("ok")), "dest": "a.bin"},
"dest above the folder": {"url": srv.URL + "/x", "sha256": sum([]byte("ok")), "dest": "../escaped.bin"},
"dest elsewhere": {"url": srv.URL + "/x", "sha256": sum([]byte("ok")), "dest": outside},
"empty dest": {"url": srv.URL + "/x", "sha256": sum([]byte("ok")), "dest": ""},
"no checksum": {"url": srv.URL + "/x", "dest": "a.bin"},
"bad hash": {"url": srv.URL + "/x", "sha256": "zz", "dest": "a.bin"},
}
for name, req := range bad {
if id, err := e.start(t, e.plugin, req); err == nil {
t.Errorf("%s was accepted (download %s)", name, id)
}
}
if _, err := os.Stat(outside); !os.IsNotExist(err) {
t.Fatal("a file was written outside the allowed folders")
}
// Another plugin without the permission cannot use this origin.
if id, err := e.start(t, e.other, map[string]any{"url": srv.URL + "/x", "sha256": sum([]byte("ok")), "dest": "a.bin"}); err == nil {
t.Fatalf("a plugin without the net permission started download %s", id)
}
}
func TestHostDownloadCancelIsPerPlugin(t *testing.T) {
started := make(chan struct{}, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "1000000")
_, _ = w.Write([]byte("start"))
w.(http.Flusher).Flush()
select {
case started <- struct{}{}:
default:
}
<-r.Context().Done()
}))
defer srv.Close()
e := newDownloadTestEnv(t, srv.URL, "127.0.0.1")
id, err := e.start(t, e.plugin, map[string]any{"url": srv.URL + "/slow", "sha256": sum([]byte("x")), "dest": "slow.bin"})
if err != nil {
t.Fatal(err)
}
select {
case <-started:
case <-time.After(10 * time.Second):
t.Fatal("the download never reached the server")
}
cancelBy := func(plugin string) error {
raw, _ := json.Marshal(map[string]any{"id": id})
_, err := cancelPluginDownload(plugin, raw)
return err
}
if err := cancelBy(e.other); err == nil {
t.Fatal("a plugin cancelled another plugin's download")
}
if err := cancelBy(e.plugin); err != nil {
t.Fatal(err)
}
if ev := e.final(t, id); ev.Status != "canceled" {
t.Fatalf("event = %+v, want canceled", ev)
}
if _, err := os.Stat(filepath.Join(e.roots[0], "slow.bin")); !os.IsNotExist(err) {
t.Fatal("a cancelled download left its file")
}
}
func TestDownloadRedirectsNeverDowngradeOrReachInternalHosts(t *testing.T) {
client := safeDownloadClient("https://downloads.example.com/file")
req := func(raw string) *http.Request {
u, _ := url.Parse(raw)
return &http.Request{URL: u}
}
via := []*http.Request{req("https://downloads.example.com/file")}
cases := map[string]string{
"downgrade to http": "http://8.8.8.8/x",
"loopback": "https://127.0.0.1/x",
"loopback name": "https://localhost/x",
"private range": "https://10.1.2.3/x",
"link local": "https://169.254.169.254/latest",
"scheme change": "ftp://8.8.8.8/x",
"user info": "https://u:p@8.8.8.8/x",
}
for name, target := range cases {
if err := client.CheckRedirect(req(target), via); err == nil {
t.Errorf("%s: redirect to %s was allowed", name, target)
}
}
if err := client.CheckRedirect(req("https://8.8.8.8/x"), via); err != nil {
t.Errorf("a plain HTTPS redirect to a public address was refused: %v", err)
}
long := make([]*http.Request, downloadMaxRedirects)
for i := range long {
long[i] = req("https://downloads.example.com/f")
}
if err := client.CheckRedirect(req("https://8.8.8.8/x"), long); err == nil {
t.Error("an eleventh redirect was allowed")
}
// A loopback origin the plugin declared may redirect within loopback.
local := safeDownloadClient("http://127.0.0.1:1/f")
if err := local.CheckRedirect(req("http://127.0.0.1:1/g"), []*http.Request{req("http://127.0.0.1:1/f")}); err != nil {
t.Errorf("a loopback redirect from a loopback origin was refused: %v", err)
}
}
func TestHasRunningDownloadFollowsPluginDownloads(t *testing.T) {
m := &taskManager{tasks: map[string]*taskEntry{}}
if m.hasRunningDownload() {
t.Fatal("an empty task list reports a download")
}
id := m.start(taskKindPluginDownload, "x", "", func() {})
if !m.hasRunningDownload() {
t.Fatal("a running plugin download is not reported")
}
m.finish(id, "", nil)
if m.hasRunningDownload() {
t.Fatal("a finished download is still reported")
}
other := m.start("vm-create", "vm", "vm", func() {})
if m.hasRunningDownload() {
t.Fatal("a VM creation counts as a download")
}
m.setInstaller(other, "offline", "26.7.3", TaskPhaseDownloading)
if !m.hasRunningDownload() {
t.Fatal("a VM creation downloading its installer is not reported")
}
m.finish(other, "", nil)
}