//go:build linux package runnersetup import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/release/renderertest" ) // The installer fetches renderer.tar.gz from the forge, at the address // built from the tag linked into the runner (never from the instance), // holds it to the linked size, digest and pin and to what the release // recorded, and unpacks it beside the runner as renderer//, the tree VerifyRenderer accepts. func TestInstallIncludesVerifiedRenderer(t *testing.T) { o, h, _ := installFixture(t) var urls []string archive, _ := renderertest.Archive(renderertest.Small()) h.fetchRenderer = forgeFetch(t, archive, &urls) r, err := installUser(context.Background(), o, h) if err != nil { t.Fatal(err) } want := release.RendererForge + h.renderer.Tag + "/renderer.tar.gz" if len(urls) != 1 || urls[0] != want { t.Fatalf("fetched %v, want [%s]", urls, want) } tree := release.RendererTree(filepath.Dir(r.BinaryPath), h.renderer.Pin) if err = release.VerifyRenderer(tree, h.renderer.Pin); err != nil { t.Fatalf("no verified renderer beside the runner: %v", err) } // A retry (the installer runs twice: before enrolment and after) // finds the tree verified and fetches nothing for it. urls = nil if _, err = installUser(context.Background(), o, h); err != nil || len(urls) != 0 { t.Fatalf("retry: fetched %v: %v", urls, err) } } // A new release beside an earlier one with the same renderer copies its // tree, fetching nothing: files copied, not linked, and verified. func TestInstallCopiesAnEarlierTree(t *testing.T) { o, h, _ := installFixture(t) if _, err := installUser(context.Background(), o, h); err != nil { t.Fatal(err) } var urls []string h.fetchRenderer = forgeFetch(t, nil, &urls) h.fetch = editManifest(h.fetch, func(m *release.InstallManifest) { m.Version = "fixture-17" }) o.Release = "fixture-17" r, err := installUser(context.Background(), o, h) if err != nil || len(urls) != 0 { t.Fatalf("second release: fetched %v: %v", urls, err) } tree := release.RendererTree(filepath.Dir(r.BinaryPath), h.renderer.Pin) if err = release.VerifyRenderer(tree, h.renderer.Pin); err != nil { t.Fatalf("copied tree: %v", err) } links := 0 filepath.Walk(tree, func(p string, info os.FileInfo, err error) error { if err == nil && info.Mode().IsRegular() && info.Sys().(*syscall.Stat_t).Nlink != 1 { links++ } return nil }) if links != 0 { t.Fatalf("%d files of the copy are linked to another", links) } } // Each check refuses before the runner or the renderer is written: the // download's size or digest, its MANIFEST, its files, what the release // recorded and what the runner has linked. func TestInstallRendererRefusesAnotherTree(t *testing.T) { small, pin := renderertest.Archive(renderertest.Small()) other, otherPin := renderertest.Archive(renderertest.Small()[:4]) // The pin's MANIFEST, over a file with other bytes than it lists. changed := renderertest.Small() changed[len(changed)-1].Body = "changed" tampered := renderertest.ArchiveOf(changed, renderertest.Manifest(renderertest.Small())) // The same tree and size, other bytes (the gzip header's time): only // the archive digest tells them apart. retimed := append([]byte{}, small...) retimed[4] ^= 0xff // link makes the runner's linked asset, and the release's record, // say archive with pin: every check before the one under test passes. link := func(h *installHost, archive []byte, pin string) { h.renderer = assetOf(archive, pin) h.fetchRenderer = forgeFetch(t, archive, nil) h.fetch = editManifest(h.fetch, func(m *release.InstallManifest) { linux := m.Targets[release.TargetLinux] linux.RendererSHA256, linux.RendererArchiveSHA256, linux.RendererArchiveSize = pin, h.renderer.SHA256, h.renderer.Size m.Targets[release.TargetLinux] = linux }) } record := func(edit func(*release.InstallTarget)) func(*installHost) { return func(h *installHost) { h.fetch = editManifest(h.fetch, func(m *release.InstallManifest) { linux := m.Targets[release.TargetLinux] edit(&linux) m.Targets[release.TargetLinux] = linux }) } } for name, c := range map[string]struct { change func(*installHost) key string }{ "other bytes": {func(h *installHost) { h.fetchRenderer = forgeFetch(t, other, nil) }, "runner.install.checksum"}, "same tree, other bytes": {func(h *installHost) { h.fetchRenderer = forgeFetch(t, retimed, nil) }, "runner.install.checksum"}, "short": {func(h *installHost) { h.fetchRenderer = forgeFetch(t, small[:len(small)-1], nil) }, "runner.install.checksum"}, "long": {func(h *installHost) { h.fetchRenderer = forgeFetch(t, append(append([]byte{}, small...), 0), nil) }, "runner.install.checksum"}, "another tree's MANIFEST": {func(h *installHost) { link(h, other, pin) }, "runner.install.checksum"}, "a changed file": {func(h *installHost) { link(h, tampered, pin) }, "runner.install.checksum"}, "not an archive": {func(h *installHost) { link(h, []byte("not gzip"), pin) }, "runner.install.checksum"}, "recorded another pin": {record(func(l *release.InstallTarget) { l.RendererSHA256 = otherPin }), "runner.install.checksum"}, "recorded another archive": {record(func(l *release.InstallTarget) { l.RendererArchiveSHA256 = strings.Repeat("a", 64) }), "runner.install.checksum"}, "recorded another size": {record(func(l *release.InstallTarget) { l.RendererArchiveSize++ }), "runner.install.checksum"}, "runner linked another pin": {func(h *installHost) { h.renderer.Pin = otherPin }, "runner.install.checksum"}, "runner linked another tag": {func(h *installHost) { h.renderer.Tag = "renderer-000000000000" }, "runner.install.checksum"}, "runner linked none": {func(h *installHost) { h.renderer = release.RendererAsset{} }, "runner.install.checksum"}, "forge unreachable": {func(h *installHost) { h.fetchRenderer = func(context.Context, string, int64, string) (*os.File, error) { return nil, errors.New("offline") } }, "runner.install.release"}, } { t.Run(name, func(t *testing.T) { o, h, calls := installFixture(t) pin := h.renderer.Pin c.change(&h) r, err := installUser(context.Background(), o, h) if err == nil || r.State != "unavailable" || strings.Join(r.Missing, ",") != c.key || *calls != 0 { t.Fatalf("installed with %s: %+v %v", name, r, err) } dir := filepath.Join(o.Root, "releases", o.Release) for _, p := range []string{release.RendererTree(dir, pin), release.RendererTree(dir, otherPin), filepath.Join(dir, "equipo-runner")} { if _, err := os.Lstat(p); !os.IsNotExist(err) { t.Fatalf("written at %s: %v", p, err) } } }) } } // fetchRendererArchive follows the forge's one redirect to https storage, // and refuses a second, a plain-http or credentialed target, another // status, a wrong length and a stalled body, leaving no file behind. func TestFetchRendererArchive(t *testing.T) { body := []byte("renderer archive bytes") storage := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/object": w.Write(body) case "/again": http.Redirect(w, r, "/object", http.StatusFound) case "/noheaders": // Withholds the response's headers. <-r.Context().Done() case "/stall": w.Header().Set("Content-Length", "22") w.Write(body[:4]) w.(http.Flusher).Flush() <-r.Context().Done() default: w.WriteHeader(http.StatusNotFound) } })) defer storage.Close() plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(body) })) defer plain.Close() forge := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { to := map[string]string{"/ok": storage.URL + "/object", "/twice": storage.URL + "/again", "/http": plain.URL + "/object", "/creds": strings.Replace(storage.URL, "https://", "https://user:pw@", 1) + "/object", "/stall": storage.URL + "/stall", "/noheaders": storage.URL + "/noheaders"}[r.URL.Path] if r.URL.Path == "/gone" { w.WriteHeader(http.StatusNotFound) return } http.Redirect(w, r, to, http.StatusFound) })) defer forge.Close() old, oldStall, oldMax := rendererTransport, rendererDownloadStall, rendererDownloadMax rendererTransport, rendererDownloadStall, rendererDownloadMax = forge.Client().Transport, 200*time.Millisecond, 8*time.Second defer func() { rendererTransport, rendererDownloadStall, rendererDownloadMax = old, oldStall, oldMax }() scratch := t.TempDir() f, err := fetchRendererArchive(context.Background(), forge.URL+"/ok", int64(len(body)), scratch) if err != nil { t.Fatal(err) } got, _ := os.ReadFile(f.Name()) f.Close() if string(got) != string(body) { t.Fatalf("got %q", got) } os.Remove(f.Name()) for _, c := range []struct { path string size int64 }{{"/twice", int64(len(body))}, {"/http", int64(len(body))}, {"/creds", int64(len(body))}, {"/gone", int64(len(body))}, {"/ok", int64(len(body)) - 1}, {"/ok", int64(len(body)) + 1}, {"/stall", int64(len(body))}, {"/noheaders", int64(len(body))}} { began := time.Now() if f, err := fetchRendererArchive(context.Background(), forge.URL+c.path, c.size, scratch); err == nil { f.Close() t.Errorf("%s (size %d) was accepted", c.path, c.size) } // A stall, body or headers, ends at the stall bound, not the // overall one. if took := time.Since(began); took > 5*time.Second { t.Errorf("%s took %v", c.path, took) } } if left, _ := os.ReadDir(scratch); len(left) != 0 { t.Fatalf("left in scratch: %v", left) } } func editManifest(fetch func(context.Context, string, int64) ([]byte, error), edit func(*release.InstallManifest)) func(context.Context, string, int64) ([]byte, error) { return func(ctx context.Context, url string, limit int64) ([]byte, error) { b, err := fetch(ctx, url, limit) if err == nil && strings.HasSuffix(url, "/install-manifest.json") { var m release.InstallManifest if err = json.Unmarshal(b, &m); err == nil { edit(&m) b, err = json.Marshal(m) } } return b, err } }