| 1 | //go:build linux |
| 2 | |
| 3 | package runnersetup |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "syscall" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/release" |
| 19 | "amadan.net/oficina/equipo/internal/release/renderertest" |
| 20 | ) |
| 21 | |
| 22 | // The installer fetches renderer.tar.gz from the forge, at the address |
| 23 | // built from the tag linked into the runner (never from the instance), |
| 24 | // holds it to the linked size, digest and pin and to what the release |
| 25 | // recorded, and unpacks it beside the runner as renderer/<first 12 of |
| 26 | // pin>/, the tree VerifyRenderer accepts. |
| 27 | func TestInstallIncludesVerifiedRenderer(t *testing.T) { |
| 28 | o, h, _ := installFixture(t) |
| 29 | var urls []string |
| 30 | archive, _ := renderertest.Archive(renderertest.Small()) |
| 31 | h.fetchRenderer = forgeFetch(t, archive, &urls) |
| 32 | r, err := installUser(context.Background(), o, h) |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | want := release.RendererForge + h.renderer.Tag + "/renderer.tar.gz" |
| 37 | if len(urls) != 1 || urls[0] != want { |
| 38 | t.Fatalf("fetched %v, want [%s]", urls, want) |
| 39 | } |
| 40 | tree := release.RendererTree(filepath.Dir(r.BinaryPath), h.renderer.Pin) |
| 41 | if err = release.VerifyRenderer(tree, h.renderer.Pin); err != nil { |
| 42 | t.Fatalf("no verified renderer beside the runner: %v", err) |
| 43 | } |
| 44 | // A retry (the installer runs twice: before enrolment and after) |
| 45 | // finds the tree verified and fetches nothing for it. |
| 46 | urls = nil |
| 47 | if _, err = installUser(context.Background(), o, h); err != nil || len(urls) != 0 { |
| 48 | t.Fatalf("retry: fetched %v: %v", urls, err) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // A new release beside an earlier one with the same renderer copies its |
| 53 | // tree, fetching nothing: files copied, not linked, and verified. |
| 54 | func TestInstallCopiesAnEarlierTree(t *testing.T) { |
| 55 | o, h, _ := installFixture(t) |
| 56 | if _, err := installUser(context.Background(), o, h); err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | var urls []string |
| 60 | h.fetchRenderer = forgeFetch(t, nil, &urls) |
| 61 | h.fetch = editManifest(h.fetch, func(m *release.InstallManifest) { m.Version = "fixture-17" }) |
| 62 | o.Release = "fixture-17" |
| 63 | r, err := installUser(context.Background(), o, h) |
| 64 | if err != nil || len(urls) != 0 { |
| 65 | t.Fatalf("second release: fetched %v: %v", urls, err) |
| 66 | } |
| 67 | tree := release.RendererTree(filepath.Dir(r.BinaryPath), h.renderer.Pin) |
| 68 | if err = release.VerifyRenderer(tree, h.renderer.Pin); err != nil { |
| 69 | t.Fatalf("copied tree: %v", err) |
| 70 | } |
| 71 | links := 0 |
| 72 | filepath.Walk(tree, func(p string, info os.FileInfo, err error) error { |
| 73 | if err == nil && info.Mode().IsRegular() && info.Sys().(*syscall.Stat_t).Nlink != 1 { |
| 74 | links++ |
| 75 | } |
| 76 | return nil |
| 77 | }) |
| 78 | if links != 0 { |
| 79 | t.Fatalf("%d files of the copy are linked to another", links) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // Each check refuses before the runner or the renderer is written: the |
| 84 | // download's size or digest, its MANIFEST, its files, what the release |
| 85 | // recorded and what the runner has linked. |
| 86 | func TestInstallRendererRefusesAnotherTree(t *testing.T) { |
| 87 | small, pin := renderertest.Archive(renderertest.Small()) |
| 88 | other, otherPin := renderertest.Archive(renderertest.Small()[:4]) |
| 89 | // The pin's MANIFEST, over a file with other bytes than it lists. |
| 90 | changed := renderertest.Small() |
| 91 | changed[len(changed)-1].Body = "changed" |
| 92 | tampered := renderertest.ArchiveOf(changed, renderertest.Manifest(renderertest.Small())) |
| 93 | // The same tree and size, other bytes (the gzip header's time): only |
| 94 | // the archive digest tells them apart. |
| 95 | retimed := append([]byte{}, small...) |
| 96 | retimed[4] ^= 0xff |
| 97 | // link makes the runner's linked asset, and the release's record, |
| 98 | // say archive with pin: every check before the one under test passes. |
| 99 | link := func(h *installHost, archive []byte, pin string) { |
| 100 | h.renderer = assetOf(archive, pin) |
| 101 | h.fetchRenderer = forgeFetch(t, archive, nil) |
| 102 | h.fetch = editManifest(h.fetch, func(m *release.InstallManifest) { |
| 103 | linux := m.Targets[release.TargetLinux] |
| 104 | linux.RendererSHA256, linux.RendererArchiveSHA256, linux.RendererArchiveSize = pin, h.renderer.SHA256, h.renderer.Size |
| 105 | m.Targets[release.TargetLinux] = linux |
| 106 | }) |
| 107 | } |
| 108 | record := func(edit func(*release.InstallTarget)) func(*installHost) { |
| 109 | return func(h *installHost) { |
| 110 | h.fetch = editManifest(h.fetch, func(m *release.InstallManifest) { |
| 111 | linux := m.Targets[release.TargetLinux] |
| 112 | edit(&linux) |
| 113 | m.Targets[release.TargetLinux] = linux |
| 114 | }) |
| 115 | } |
| 116 | } |
| 117 | for name, c := range map[string]struct { |
| 118 | change func(*installHost) |
| 119 | key string |
| 120 | }{ |
| 121 | "other bytes": {func(h *installHost) { h.fetchRenderer = forgeFetch(t, other, nil) }, "runner.install.checksum"}, |
| 122 | "same tree, other bytes": {func(h *installHost) { h.fetchRenderer = forgeFetch(t, retimed, nil) }, "runner.install.checksum"}, |
| 123 | "short": {func(h *installHost) { h.fetchRenderer = forgeFetch(t, small[:len(small)-1], nil) }, "runner.install.checksum"}, |
| 124 | "long": {func(h *installHost) { h.fetchRenderer = forgeFetch(t, append(append([]byte{}, small...), 0), nil) }, "runner.install.checksum"}, |
| 125 | "another tree's MANIFEST": {func(h *installHost) { link(h, other, pin) }, "runner.install.checksum"}, |
| 126 | "a changed file": {func(h *installHost) { link(h, tampered, pin) }, "runner.install.checksum"}, |
| 127 | "not an archive": {func(h *installHost) { link(h, []byte("not gzip"), pin) }, "runner.install.checksum"}, |
| 128 | "recorded another pin": {record(func(l *release.InstallTarget) { l.RendererSHA256 = otherPin }), "runner.install.checksum"}, |
| 129 | "recorded another archive": {record(func(l *release.InstallTarget) { l.RendererArchiveSHA256 = strings.Repeat("a", 64) }), "runner.install.checksum"}, |
| 130 | "recorded another size": {record(func(l *release.InstallTarget) { l.RendererArchiveSize++ }), "runner.install.checksum"}, |
| 131 | "runner linked another pin": {func(h *installHost) { h.renderer.Pin = otherPin }, "runner.install.checksum"}, |
| 132 | "runner linked another tag": {func(h *installHost) { h.renderer.Tag = "renderer-000000000000" }, "runner.install.checksum"}, |
| 133 | "runner linked none": {func(h *installHost) { h.renderer = release.RendererAsset{} }, "runner.install.checksum"}, |
| 134 | "forge unreachable": {func(h *installHost) { |
| 135 | h.fetchRenderer = func(context.Context, string, int64, string) (*os.File, error) { return nil, errors.New("offline") } |
| 136 | }, "runner.install.release"}, |
| 137 | } { |
| 138 | t.Run(name, func(t *testing.T) { |
| 139 | o, h, calls := installFixture(t) |
| 140 | pin := h.renderer.Pin |
| 141 | c.change(&h) |
| 142 | r, err := installUser(context.Background(), o, h) |
| 143 | if err == nil || r.State != "unavailable" || strings.Join(r.Missing, ",") != c.key || *calls != 0 { |
| 144 | t.Fatalf("installed with %s: %+v %v", name, r, err) |
| 145 | } |
| 146 | dir := filepath.Join(o.Root, "releases", o.Release) |
| 147 | for _, p := range []string{release.RendererTree(dir, pin), release.RendererTree(dir, otherPin), filepath.Join(dir, "equipo-runner")} { |
| 148 | if _, err := os.Lstat(p); !os.IsNotExist(err) { |
| 149 | t.Fatalf("written at %s: %v", p, err) |
| 150 | } |
| 151 | } |
| 152 | }) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // fetchRendererArchive follows the forge's one redirect to https storage, |
| 157 | // and refuses a second, a plain-http or credentialed target, another |
| 158 | // status, a wrong length and a stalled body, leaving no file behind. |
| 159 | func TestFetchRendererArchive(t *testing.T) { |
| 160 | body := []byte("renderer archive bytes") |
| 161 | storage := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 162 | switch r.URL.Path { |
| 163 | case "/object": |
| 164 | w.Write(body) |
| 165 | case "/again": |
| 166 | http.Redirect(w, r, "/object", http.StatusFound) |
| 167 | case "/noheaders": |
| 168 | // Withholds the response's headers. |
| 169 | <-r.Context().Done() |
| 170 | case "/stall": |
| 171 | w.Header().Set("Content-Length", "22") |
| 172 | w.Write(body[:4]) |
| 173 | w.(http.Flusher).Flush() |
| 174 | <-r.Context().Done() |
| 175 | default: |
| 176 | w.WriteHeader(http.StatusNotFound) |
| 177 | } |
| 178 | })) |
| 179 | defer storage.Close() |
| 180 | plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(body) })) |
| 181 | defer plain.Close() |
| 182 | forge := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 183 | to := map[string]string{"/ok": storage.URL + "/object", "/twice": storage.URL + "/again", "/http": plain.URL + "/object", |
| 184 | "/creds": strings.Replace(storage.URL, "https://", "https://user:pw@", 1) + "/object", "/stall": storage.URL + "/stall", "/noheaders": storage.URL + "/noheaders"}[r.URL.Path] |
| 185 | if r.URL.Path == "/gone" { |
| 186 | w.WriteHeader(http.StatusNotFound) |
| 187 | return |
| 188 | } |
| 189 | http.Redirect(w, r, to, http.StatusFound) |
| 190 | })) |
| 191 | defer forge.Close() |
| 192 | old, oldStall, oldMax := rendererTransport, rendererDownloadStall, rendererDownloadMax |
| 193 | rendererTransport, rendererDownloadStall, rendererDownloadMax = forge.Client().Transport, 200*time.Millisecond, 8*time.Second |
| 194 | defer func() { rendererTransport, rendererDownloadStall, rendererDownloadMax = old, oldStall, oldMax }() |
| 195 | |
| 196 | scratch := t.TempDir() |
| 197 | f, err := fetchRendererArchive(context.Background(), forge.URL+"/ok", int64(len(body)), scratch) |
| 198 | if err != nil { |
| 199 | t.Fatal(err) |
| 200 | } |
| 201 | got, _ := os.ReadFile(f.Name()) |
| 202 | f.Close() |
| 203 | if string(got) != string(body) { |
| 204 | t.Fatalf("got %q", got) |
| 205 | } |
| 206 | os.Remove(f.Name()) |
| 207 | for _, c := range []struct { |
| 208 | path string |
| 209 | size int64 |
| 210 | }{{"/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))}} { |
| 211 | began := time.Now() |
| 212 | if f, err := fetchRendererArchive(context.Background(), forge.URL+c.path, c.size, scratch); err == nil { |
| 213 | f.Close() |
| 214 | t.Errorf("%s (size %d) was accepted", c.path, c.size) |
| 215 | } |
| 216 | // A stall, body or headers, ends at the stall bound, not the |
| 217 | // overall one. |
| 218 | if took := time.Since(began); took > 5*time.Second { |
| 219 | t.Errorf("%s took %v", c.path, took) |
| 220 | } |
| 221 | } |
| 222 | if left, _ := os.ReadDir(scratch); len(left) != 0 { |
| 223 | t.Fatalf("left in scratch: %v", left) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | func editManifest(fetch func(context.Context, string, int64) ([]byte, error), edit func(*release.InstallManifest)) func(context.Context, string, int64) ([]byte, error) { |
| 228 | return func(ctx context.Context, url string, limit int64) ([]byte, error) { |
| 229 | b, err := fetch(ctx, url, limit) |
| 230 | if err == nil && strings.HasSuffix(url, "/install-manifest.json") { |
| 231 | var m release.InstallManifest |
| 232 | if err = json.Unmarshal(b, &m); err == nil { |
| 233 | edit(&m) |
| 234 | b, err = json.Marshal(m) |
| 235 | } |
| 236 | } |
| 237 | return b, err |
| 238 | } |
| 239 | } |
| 240 | |