package main import ( "archive/tar" "bytes" "encoding/json" "mime/multipart" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "testing" ) type entry struct { name string body string typ byte link string } func makeBundle(t *testing.T, entries ...entry) []byte { t.Helper() var buf bytes.Buffer tw := tar.NewWriter(&buf) for _, e := range entries { typ := e.typ if typ == 0 { typ = tar.TypeReg } hdr := &tar.Header{Name: e.name, Typeflag: typ, Mode: 0o644, Size: int64(len(e.body)), Linkname: e.link} if typ != tar.TypeReg { hdr.Size = 0 } if err := tw.WriteHeader(hdr); err != nil { t.Fatal(err) } if typ == tar.TypeReg { tw.Write([]byte(e.body)) } } tw.Close() return buf.Bytes() } const hash32 = "00fs4zz9c0jjcvs62wg39b91dydz7zqb" func goodBundle(t *testing.T) []byte { return makeBundle(t, entry{name: "latest", body: `{"release":"/nix/store/x","version":"0.3.0","serial":2000,"schema":0}`}, entry{name: "cache/", typ: tar.TypeDir}, entry{name: "cache/log/", typ: tar.TypeDir}, entry{name: "cache/nix-cache-info", body: "StoreDir: /nix/store\n"}, entry{name: "cache/" + hash32 + ".narinfo", body: "StorePath: ..."}, entry{name: "cache/nar/" + strings.Repeat("a1", 26) + ".nar.zst", body: "nar"}, ) } func TestUnbundle(t *testing.T) { dir := filepath.Join(t.TempDir(), "staged") os.MkdirAll(dir, 0o700) os.WriteFile(filepath.Join(dir, "old"), []byte("x"), 0o600) if err := unbundle(bytes.NewReader(goodBundle(t)), dir); err != nil { t.Fatal(err) } for _, f := range []string{"latest", "cache/nix-cache-info", "cache/" + hash32 + ".narinfo"} { if _, err := os.Stat(filepath.Join(dir, f)); err != nil { t.Fatalf("%s: %v", f, err) } } if _, err := os.Stat(filepath.Join(dir, "old")); err == nil { t.Fatal("the previous staging was kept") } } func TestUnbundleRefusesHostileBundles(t *testing.T) { good := []entry{ {name: "latest", body: "{}"}, {name: "cache/nix-cache-info", body: "x"}, } for name, extra := range map[string]entry{ "traversal": {name: "../../etc/passwd", body: "x"}, "absolute": {name: "/etc/passwd", body: "x"}, "nested": {name: "cache/nar/../../../x", body: "x"}, "other file": {name: "cache/evil.sh", body: "x"}, "symlink": {name: "cache/" + hash32 + ".narinfo", typ: tar.TypeSymlink, link: "/etc/passwd"}, "hardlink": {name: "cache/" + hash32 + ".narinfo", typ: tar.TypeLink, link: "/etc/passwd"}, "directory": {name: "etc/", typ: tar.TypeDir}, "duplicate": {name: "latest", body: "{}"}, "huge latest": {name: "latest", body: strings.Repeat("x", maxLatest+1)}, } { dir := filepath.Join(t.TempDir(), "staged") entries := append([]entry{}, good...) if name == "huge latest" { entries = good[1:] // so the size, not a duplicate, is what is refused } err := unbundle(bytes.NewReader(makeBundle(t, append(entries, extra)...)), dir) if err == nil { t.Errorf("%s: accepted", name) } if _, statErr := os.Stat(dir); statErr == nil { t.Errorf("%s: left %s behind", name, dir) } if _, statErr := os.Stat(dir + ".tmp"); statErr == nil { t.Errorf("%s: left a temporary directory", name) } } // Incomplete or not a tar at all. if err := unbundle(bytes.NewReader(makeBundle(t, entry{name: "latest", body: "{}"})), filepath.Join(t.TempDir(), "s")); err == nil { t.Error("a bundle without a cache was accepted") } if err := unbundle(strings.NewReader("this is not a tar file"), filepath.Join(t.TempDir(), "s")); err == nil { t.Error("garbage was accepted") } } func upload(t *testing.T, h http.Handler, token string, cookie *http.Cookie, bundle []byte, force bool) *httptest.ResponseRecorder { t.Helper() var body bytes.Buffer mw := multipart.NewWriter(&body) if force { mw.WriteField("force", "on") } fw, _ := mw.CreateFormFile("bundle", "router-update.bundle") fw.Write(bundle) mw.Close() req := httptest.NewRequest("POST", "/update/upload?csrf="+url.QueryEscape(token), &body) req.Header.Set("Content-Type", mw.FormDataContentType()) if cookie != nil { req.AddCookie(cookie) } rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } func TestUpdateUploadAndInstall(t *testing.T) { a, sys := newTestApp(t) var started []string startUnit = func(unit string) error { started = append(started, unit); return nil } orig := startUnit defer func() { startUnit = orig }() h := a.routes() cookie := login(t, h) token := csrfFrom(t, do(h, "GET", "/update", nil, cookie).Body.String()) if rec := upload(t, h, "wrong", cookie, goodBundle(t), false); rec.Code != http.StatusForbidden { t.Fatalf("upload with a wrong token: %d", rec.Code) } if rec := upload(t, h, token, nil, goodBundle(t), false); rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/login") { t.Fatalf("upload without a session: %d %s", rec.Code, rec.Header().Get("Location")) } if len(started) != 0 { t.Fatal("the update unit was started by a rejected upload") } rec := upload(t, h, token, cookie, makeBundle(t, entry{name: "evil", body: "x"}), false) if loc := rec.Header().Get("Location"); !strings.Contains(loc, "Rejected") || len(started) != 0 { t.Fatalf("hostile bundle: %q, started %v", loc, started) } rec = upload(t, h, token, cookie, goodBundle(t), true) if loc := rec.Header().Get("Location"); !strings.Contains(loc, "Bundle+received") { t.Fatalf("upload: %d %q", rec.Code, loc) } if len(started) != 1 || started[0] != "router-update.service" { t.Fatalf("started %v", started) } var req struct { Mode string `json:"mode"` Force bool `json:"force"` } data, _ := os.ReadFile(filepath.Join(sys.updateDir(), "request.json")) if err := json.Unmarshal(data, &req); err != nil || req.Mode != "staged" || !req.Force { t.Fatalf("request: %s", data) } if _, err := os.Stat(filepath.Join(sys.updateDir(), "staged", "latest")); err != nil { t.Fatalf("not staged: %v", err) } // The page has no update server any more. for _, p := range []string{"/update/url", "/update/install", "/update/check"} { if rec := do(h, "POST", p, url.Values{"csrf": {token}}, cookie); rec.Code != 404 && rec.Code != 405 { t.Fatalf("%s still exists: %d", p, rec.Code) } } } func TestUpdateProgress(t *testing.T) { log := "" last := 0 for _, step := range []struct{ line, what string }{ {"", "Starting"}, {"router-update: verifying /nix/store/x-release\n", "Verifying the signature"}, {"router-update: importing it\n", "Importing the release"}, {"router-update: installed 0.1.0, update 0.2.0\n", "Checking the version"}, {"router-update: building and activating 0.2.0\nbuilding the system\n", "Building and activating the new version"}, } { log += step.line pct, what := updateProgress(log) if what != step.what || pct <= last { t.Fatalf("after %q: %d%% %q (before: %d%%)", step.line, pct, what, last) } last = pct } }