package release import ( "archive/tar" "bytes" "compress/gzip" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/wire" ) // debMember is one entry of a fixture deb's data.tar: a file (body), a // link (link) or a directory (dir). type debMember struct { name, body, link string mode int64 dir bool } // fixtureDeb is a small Debian package as dpkg-deb builds one: an ar // archive of debian-binary, control.tar.gz and data.tar.gz. Its members // carry a build machine's owner and times, which the tree must not keep. func fixtureDeb(t *testing.T, members []debMember, control string) []byte { t.Helper() targz := func(members []debMember) []byte { var b bytes.Buffer gz := gzip.NewWriter(&b) tw := tar.NewWriter(gz) for _, m := range members { h := &tar.Header{Name: m.name, Mode: m.mode, Uid: 1000, Gid: 1000, Uname: "builder", Gname: "builder", ModTime: time.Unix(1764000000, 0)} switch { case m.dir: h.Typeflag = tar.TypeDir case m.link != "": h.Typeflag, h.Linkname = tar.TypeSymlink, m.link default: h.Typeflag, h.Size = tar.TypeReg, int64(len(m.body)) } if err := tw.WriteHeader(h); err != nil { t.Fatal(err) } if _, err := io.WriteString(tw, m.body); err != nil { t.Fatal(err) } } if err := tw.Close(); err != nil { t.Fatal(err) } if err := gz.Close(); err != nil { t.Fatal(err) } return b.Bytes() } var ar bytes.Buffer ar.WriteString("!\n") member := func(name string, body []byte) { fmt.Fprintf(&ar, "%-16s%-12d%-6d%-6d%-8o%-10d`\n", name, 1764000000, 0, 0, 0o100644, len(body)) ar.Write(body) if len(body)%2 == 1 { ar.WriteByte('\n') } } member("debian-binary", []byte("2.0\n")) member("control.tar.gz", targz([]debMember{{name: "./control", body: control, mode: 0o644}})) member("data.tar.gz", targz(members)) return ar.Bytes() } // rendererFixture is a pin of three small packages (in the pin's sorted // order) and their debs by URL: the browser, a fonts config whose links // are absolute as Debian writes them (one top-level directory to // another), and a loader. The fonts link's target comes from a later // package; two packages ship the same directory and one identical file. type rendererFixture struct { packages map[string][]debMember order []string edit func(p *rendererPackage) control func(name, control string) string } func newRendererFixture() *rendererFixture { return &rendererFixture{ order: []string{"chromium-headless-shell", "fontconfig-config", "fonts-fixture", "libc6"}, packages: map[string][]debMember{ "chromium-headless-shell": { {name: "./", dir: true, mode: 0o755}, {name: "./usr/", dir: true, mode: 0o755}, {name: "./usr/lib/", dir: true, mode: 0o755}, {name: "./usr/lib/chromium/", dir: true, mode: 0o755}, {name: "./usr/lib/chromium/chromium-headless-shell", body: "browser", mode: 0o755}, // No ./usr/bin/ member: its directory is implied. {name: "./usr/bin/chromium-headless-shell", link: "../lib/chromium/chromium-headless-shell", mode: 0o777}, {name: "./usr/share/doc/shared/copyright", body: "same words", mode: 0o644}, }, "fontconfig-config": { {name: "./etc/", dir: true, mode: 0o755}, {name: "./etc/fonts/", dir: true, mode: 0o755}, {name: "./etc/fonts/conf.d/", dir: true, mode: 0o755}, {name: "./etc/fonts/conf.d/10-fixture.conf", link: "/usr/share/fontconfig/conf.avail/10-fixture.conf", mode: 0o777}, }, "fonts-fixture": { {name: "./usr/share/fontconfig/conf.avail/10-fixture.conf", body: "", mode: 0o664}, {name: "./usr/share/doc/shared/copyright", body: "same words", mode: 0o644}, }, "libc6": { {name: "./usr/", dir: true, mode: 0o755}, {name: "./usr/lib64/", dir: true, mode: 0o755}, {name: "./usr/lib64/ld-linux-x86-64.so.2", body: "loader", mode: 0o4775}, }, }, } } // write puts the pin and its debs in dir and returns the pin's path and // the URL-to-file map the script's fetch reads. func (f *rendererFixture) write(t *testing.T, dir string) (string, map[string]string) { t.Helper() pin := rendererPin{Version: "1.0-1", Snapshots: map[string]string{"debian": "20990101T000000Z"}, Program: "usr/lib/chromium/chromium-headless-shell"} urls := map[string]string{} for _, name := range f.order { // Its control file, as Debian's: the browser is built from the // chromium source package, the others from their own. control := "Package: " + name + "\nVersion: 1.0-1\nArchitecture: amd64\n" if name == "chromium-headless-shell" { control += "Source: chromium\n" } if f.control != nil { control = f.control(name, control) } deb := fixtureDeb(t, f.packages[name], control) sum := sha256.Sum256(deb) p := rendererPackage{Package: name, Version: "1.0-1", Architecture: "amd64", URL: fmt.Sprintf("https://snapshot.debian.org/archive/debian/20990101T000000Z/pool/main/%c/%s/%s_1.0-1_amd64.deb", name[0], name, name), SHA256: hex.EncodeToString(sum[:]), Size: int64(len(deb)), Base: name == "libc6"} path := filepath.Join(dir, name+".deb") if err := os.WriteFile(path, deb, 0o600); err != nil { t.Fatal(err) } if f.edit != nil { f.edit(&p) } urls[p.URL] = path pin.AMD64 = append(pin.AMD64, p) } raw, err := json.Marshal(pin) if err != nil { t.Fatal(err) } path := filepath.Join(dir, "renderer.json") if err = os.WriteFile(path, raw, 0o600); err != nil { t.Fatal(err) } return path, urls } // buildRendererTree runs scripts/build-renderer-tree.py on the fixture, // its fetch reading the fixture debs instead of the network. clock, when // set, is what the script's time.time returns: the output must not // depend on it. func buildRendererTree(t *testing.T, pin string, urls map[string]string, out string, clock float64, extra ...string) (string, string, error) { t.Helper() fixture, err := json.Marshal(urls) if err != nil { t.Fatal(err) } const prelude = ` import json, os, sys, time, types if float(sys.argv[2]): time.time = lambda: float(sys.argv[2]) os.umask(0o077) # The script's source bytes, compiled here: never a cached .pyc, which # could be stale (same size, same mtime second) after an edit. path = "../../scripts/build-renderer-tree.py" with open(path, "rb") as f: code = compile(f.read(), path, "exec", dont_inherit=True) m = types.ModuleType("tree") m.__file__ = path sys.modules["tree"] = m exec(code, m.__dict__) urls = json.loads(sys.argv[1]) m.fetch = lambda url: open(urls[url], "rb").read() sys.exit(m.main(sys.argv[3:])) ` // Under a group-writable umask, so nothing the script keeps may take // its mode from the umask (the verifier refuses a group-writable tree). cmd := exec.Command("sh", append([]string{"-c", `umask 002 && exec python3 "$@"`, "sh", "-I", "-B", "-c", prelude, string(fixture), fmt.Sprint(clock), pin, out}, extra...)...) cmd.Env = append(os.Environ(), "PYTHONDONTWRITEBYTECODE=1") var stdout, stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &stdout, &stderr err = cmd.Run() return stdout.String(), stderr.String(), err } // The release's renderer: every pinned deb unpacked into one tree, listed // by MANIFEST (one line per entry, sorted by path), both in a gzip tar // whose bytes depend only on the pin. A Debian absolute link becomes the // same path relative to the link, so no entry points out of the tree. func TestRendererTreeIsDeterministic(t *testing.T) { testci.Files(t, "../../scripts/build-renderer-tree.py") testci.Tools(t, "python3") dir := t.TempDir() pin, urls := newRendererFixture().write(t, dir) first, second := filepath.Join(dir, "a", "renderer.tar.gz"), filepath.Join(dir, "b", "renderer.tar.gz") for _, d := range []string{filepath.Dir(first), filepath.Dir(second)} { if err := os.Mkdir(d, 0o700); err != nil { t.Fatal(err) } } pinA, stderr, err := buildRendererTree(t, pin, urls, first, 0) if err != nil { t.Fatalf("build: %v\n%s", err, stderr) } // Another clock and umask: the same bytes. pinB, stderr, err := buildRendererTree(t, pin, urls, second, 4102444800) if err != nil { t.Fatalf("build again: %v\n%s", err, stderr) } a, _ := os.ReadFile(first) b, _ := os.ReadFile(second) if len(a) == 0 || !bytes.Equal(a, b) || pinA != pinB { t.Fatalf("two builds of one pin differ: %d and %d bytes, pins %q %q", len(a), len(b), pinA, pinB) } // gzip: no file name, no time (RFC 1952: FLG, then MTIME). if a[0] != 0x1f || a[1] != 0x8b || a[3] != 0 || !bytes.Equal(a[4:8], []byte{0, 0, 0, 0}) { t.Fatalf("gzip header % x", a[:10]) } sum := func(s string) string { h := sha256.Sum256([]byte(s)); return hex.EncodeToString(h[:]) } want := strings.Join([]string{ "dir etc", "dir etc/fonts", "dir etc/fonts/conf.d", "link etc/fonts/conf.d/10-fixture.conf ../../../usr/share/fontconfig/conf.avail/10-fixture.conf", "dir usr", "dir usr/bin", "link usr/bin/chromium-headless-shell ../lib/chromium/chromium-headless-shell", "dir usr/lib", "dir usr/lib/chromium", "file usr/lib/chromium/chromium-headless-shell " + sum("browser") + " 0755", "dir usr/lib64", "file usr/lib64/ld-linux-x86-64.so.2 " + sum("loader") + " 0755", "dir usr/share", "dir usr/share/doc", "dir usr/share/doc/shared", "file usr/share/doc/shared/copyright " + sum("same words") + " 0644", "dir usr/share/fontconfig", "dir usr/share/fontconfig/conf.avail", "file usr/share/fontconfig/conf.avail/10-fixture.conf " + sum("") + " 0644", }, "\n") + "\n" gz, err := gzip.NewReader(bytes.NewReader(a)) if err != nil { t.Fatal(err) } if gz.Name != "" || !gz.ModTime.IsZero() { t.Fatalf("gzip header names %q at %v", gz.Name, gz.ModTime) } tr := tar.NewReader(gz) var names []string var manifest string for { h, err := tr.Next() if err == io.EOF { break } if err != nil { t.Fatal(err) } // A directory's tar name ends in a slash; its path does not. name := strings.TrimSuffix(h.Name, "/") names = append(names, name) if h.Uid != 0 || h.Gid != 0 || h.Uname != "" || h.Gname != "" || h.ModTime.Unix() != 0 { t.Errorf("%s: owner %d:%d %q:%q, time %v", h.Name, h.Uid, h.Gid, h.Uname, h.Gname, h.ModTime) } body, _ := io.ReadAll(tr) var line string switch h.Typeflag { case tar.TypeDir: line = "dir " + name if h.Mode != 0o755 { t.Errorf("%s: mode %o", h.Name, h.Mode) } case tar.TypeSymlink: line = "link " + h.Name + " " + h.Linkname case tar.TypeReg: if h.Name == "MANIFEST" { manifest = string(body) if h.Mode != 0o644 { t.Errorf("MANIFEST mode %o", h.Mode) } continue } line = fmt.Sprintf("file %s %s %04o", h.Name, sum(string(body)), h.Mode) default: t.Errorf("%s: type %c", h.Name, h.Typeflag) } // Every entry is the MANIFEST line that names it. if !strings.Contains(want, line+"\n") { t.Errorf("tar entry %q is not in the MANIFEST", line) } } if manifest != want { t.Fatalf("MANIFEST:\n%s\nwant:\n%s", manifest, want) } if !slices.IsSorted(names) || len(names) != strings.Count(want, "\n")+1 || names[0] != "MANIFEST" { t.Fatalf("tar entries %v", names) } // The script prints the MANIFEST's SHA-256: the pin the runner is linked with. if pinA != sum(manifest)+"\n" { t.Fatalf("printed %q, MANIFEST is %s", pinA, sum(manifest)) } // --tree keeps the unpacked tree, its MANIFEST at the root. tree := filepath.Join(dir, "tree") if _, stderr, err = buildRendererTree(t, pin, urls, filepath.Join(dir, "c.tar.gz"), 0, "--tree", tree); err != nil { t.Fatalf("build with --tree: %v\n%s", err, stderr) } kept, _ := os.ReadFile(filepath.Join(tree, "MANIFEST")) link, _ := os.Readlink(filepath.Join(tree, "etc/fonts/conf.d/10-fixture.conf")) if string(kept) != want || link != "../../../usr/share/fontconfig/conf.avail/10-fixture.conf" { t.Fatalf("kept tree: MANIFEST %q, link %q", kept, link) } if font, err := os.ReadFile(filepath.Join(tree, "etc/fonts/conf.d/10-fixture.conf")); err != nil || string(font) != "" { t.Fatalf("the kept tree's link does not reach its target: %q %v", font, err) } } // A deb that is not the pinned one, or a tree that would point outside // itself, builds nothing: no tar, no scratch tree left beside it. func TestRendererTreeRefuses(t *testing.T) { testci.Files(t, "../../scripts/build-renderer-tree.py") testci.Tools(t, "python3") add := func(pkg string, m debMember) func(f *rendererFixture) { return func(f *rendererFixture) { f.packages[pkg] = append(f.packages[pkg], m) } } for _, c := range []struct { name, want string change func(f *rendererFixture) }{ {"bad deb hash", "SHA-256", func(f *rendererFixture) { f.edit = func(p *rendererPackage) { if p.Package == "libc6" { p.SHA256 = strings.Repeat("0", 64) } } }}, {"wrong deb size", "bytes", func(f *rendererFixture) { f.edit = func(p *rendererPackage) { if p.Package == "fonts-fixture" { p.Size++ } } }}, {"not a snapshot URL", "want a snapshot.debian.org .deb URL", func(f *rendererFixture) { f.edit = func(p *rendererPackage) { p.URL = strings.Replace(p.URL, "https://snapshot.debian.org/", "http://snapshot.debian.org/", 1) } }}, {"escaping link", "climbs out of the tree", add("libc6", debMember{name: "./usr/lib64/passwd", link: "../../../etc/passwd", mode: 0o777})}, {"escaping through a link", "climbs out of the tree", func(f *rendererFixture) { add("libc6", debMember{name: "./usr/up", link: "..", mode: 0o777})(f) add("libc6", debMember{name: "./usr/out", link: "up/..", mode: 0o777})(f) }}, {"a link to a file with a slash", "is not a directory", add("libc6", debMember{name: "./usr/lib64/ld", link: "ld-linux-x86-64.so.2/", mode: 0o777})}, {"a link to a file with /.", "is not a directory", add("libc6", debMember{name: "./usr/lib64/ld", link: "ld-linux-x86-64.so.2/.", mode: 0o777})}, {"a slash through another link", "is not a directory", func(f *rendererFixture) { add("libc6", debMember{name: "./usr/lib64/ld", link: "ld-linux-x86-64.so.2", mode: 0o777})(f) add("libc6", debMember{name: "./usr/lib64/via", link: "ld/", mode: 0o777})(f) }}, {"the browser's link with a slash", "is not a directory", func(f *rendererFixture) { f.packages["chromium-headless-shell"][5].link = "../lib/chromium/chromium-headless-shell/." }}, {"absolute link outside the tree", "names nothing in the tree", add("libc6", debMember{name: "./usr/lib64/sh", link: "/bin/sh", mode: 0o777})}, {"absolute link climbing out", "climbs out of the tree", add("libc6", debMember{name: "./usr/lib64/root", link: "/../../etc", mode: 0o777})}, {"path climbing out", "not a path inside the tree", add("libc6", debMember{name: "./usr/../../evil", body: "x", mode: 0o644})}, {"absolute path", "not a path inside the tree", add("libc6", debMember{name: "/etc/evil", body: "x", mode: 0o644})}, {"a path through a link", "through a link", func(f *rendererFixture) { add("libc6", debMember{name: "./usr/lib64/host", link: "../lib", mode: 0o777})(f) add("libc6", debMember{name: "./usr/lib64/host/evil", body: "x", mode: 0o644})(f) }}, {"two packages disagree", "disagree", add("libc6", debMember{name: "./usr/share/doc/shared/copyright", body: "other words", mode: 0o644})}, {"a name the MANIFEST cannot hold", "not a path inside the tree", add("libc6", debMember{name: "./usr/two words", body: "x", mode: 0o644})}, {"the tree's own MANIFEST", "MANIFEST", add("libc6", debMember{name: "./MANIFEST", body: "file x", mode: 0o644})}, {"no program", "usr/lib/chromium/chromium-headless-shell", func(f *rendererFixture) { f.packages["chromium-headless-shell"][4].mode = 0o644 }}, } { t.Run(c.name, func(t *testing.T) { t.Parallel() dir := t.TempDir() f := newRendererFixture() c.change(f) pin, urls := f.write(t, dir) out := filepath.Join(dir, "out") if err := os.Mkdir(out, 0o700); err != nil { t.Fatal(err) } stdout, stderr, err := buildRendererTree(t, pin, urls, filepath.Join(out, "renderer.tar.gz"), 0) if err == nil || !strings.Contains(stderr, c.want) || stdout != "" { t.Fatalf("got %v, stdout %q, stderr %q; want a refusal naming %q", err, stdout, stderr, c.want) } if left, _ := os.ReadDir(out); len(left) != 0 { t.Fatalf("a refused build left %v", left) } }) } } // A runner built without a renderer pin linked reports its renderer // unpinned, whatever is on disk; so does a malformed pin. func TestRendererPinUnpinned(t *testing.T) { saved := rendererSHA256 t.Cleanup(func() { rendererSHA256 = saved }) pin := strings.Repeat("ab", 32) for linked, want := range map[string][2]string{ "": {"", wire.ToolUnpinned}, "not a digest": {"", wire.ToolUnpinned}, strings.ToUpper(pin): {"", wire.ToolUnpinned}, pin: {pin, ""}, } { rendererSHA256 = linked if got, health := RendererPin(); got != want[0] || health != want[1] { t.Errorf("linked %q: got %q %q, want %q %q", linked, got, health, want[0], want[1]) } } } // writeRendererTar writes a renderer.tar.gz holding only a MANIFEST with // the given text, as packaging fixtures need one, and returns its SHA-256. func writeRendererTar(t *testing.T, path, manifest string) string { t.Helper() var b bytes.Buffer gz := gzip.NewWriter(&b) tw := tar.NewWriter(gz) if err := tw.WriteHeader(&tar.Header{Name: "MANIFEST", Mode: 0o644, Size: int64(len(manifest))}); err != nil { t.Fatal(err) } if _, err := io.WriteString(tw, manifest); err != nil { t.Fatal(err) } if err := tw.Close(); err != nil { t.Fatal(err) } if err := gz.Close(); err != nil { t.Fatal(err) } if err := os.WriteFile(path, b.Bytes(), 0o600); err != nil { t.Fatal(err) } sum := sha256.Sum256([]byte(manifest)) return hex.EncodeToString(sum[:]) } // The build writes SOURCES beside the archive, from the same checked // debs: the Chromium version and its source, and per package its version, // architecture, deb and source package on snapshot.debian.org. // renderer-sources.py check accepts it, and refuses it changed. func TestRendererTreeWritesSources(t *testing.T) { testci.Files(t, "../../scripts/build-renderer-tree.py", "../../scripts/renderer-sources.py") testci.Tools(t, "python3") dir := t.TempDir() pin, urls := newRendererFixture().write(t, dir) out := filepath.Join(dir, "out", "renderer.tar.gz") os.Mkdir(filepath.Dir(out), 0o755) if _, stderr, err := buildRendererTree(t, pin, urls, out, 0); err != nil { t.Fatalf("build: %v\n%s", err, stderr) } sources := filepath.Join(dir, "out", "SOURCES") raw, err := os.ReadFile(sources) if err != nil { t.Fatal(err) } snap := "https://snapshot.debian.org/archive/debian/20990101T000000Z/pool/main/" want := "The page renderer: Chromium headless shell 1.0-1, from Debian.\n" + "Chromium source: https://snapshot.debian.org/package/chromium/1.0-1/\n\n" + "chromium-headless-shell 1.0-1 amd64 " + snap + "c/chromium-headless-shell/chromium-headless-shell_1.0-1_amd64.deb https://snapshot.debian.org/package/chromium/1.0-1/\n" + "fontconfig-config 1.0-1 amd64 " + snap + "f/fontconfig-config/fontconfig-config_1.0-1_amd64.deb https://snapshot.debian.org/package/fontconfig-config/1.0-1/\n" + "fonts-fixture 1.0-1 amd64 " + snap + "f/fonts-fixture/fonts-fixture_1.0-1_amd64.deb https://snapshot.debian.org/package/fonts-fixture/1.0-1/\n" + "libc6 1.0-1 amd64 " + snap + "l/libc6/libc6_1.0-1_amd64.deb https://snapshot.debian.org/package/libc6/1.0-1/\n" if string(raw) != want { t.Fatalf("SOURCES:\n%s\nwant:\n%s", raw, want) } check := func(path string) error { return exec.Command("python3", "-I", "../../scripts/renderer-sources.py", "check", pin, path).Run() } if err := check(sources); err != nil { t.Fatalf("check refused the build's SOURCES: %v", err) } for name, edit := range map[string]func(string) string{ "a package dropped": func(s string) string { return strings.Replace(s, "libc6 1.0-1", "", 1) }, "another version": func(s string) string { return strings.Replace(s, "libc6 1.0-1 amd64", "libc6 1.0-2 amd64", 1) }, "another header": func(s string) string { return strings.Replace(s, "shell 1.0-1,", "shell 2.0-1,", 1) }, } { bad := filepath.Join(dir, name) os.WriteFile(bad, []byte(edit(want)), 0o600) if check(bad) == nil { t.Errorf("check accepted SOURCES with %s", name) } } } // A deb whose control file is not the pinned package and version, or // names no chromium source for the browser, is refused: SOURCES is never // written from a guess, and neither is the archive. func TestRendererTreeRefusesAnotherControl(t *testing.T) { testci.Files(t, "../../scripts/build-renderer-tree.py", "../../scripts/renderer-sources.py") testci.Tools(t, "python3") for name, edit := range map[string]func(pkg, control string) string{ "another version": func(pkg, c string) string { if pkg == "libc6" { return strings.Replace(c, "1.0-1", "1.0-9", 1) } return c }, "the browser from another source": func(pkg, c string) string { return strings.Replace(c, "Source: chromium", "Source: other", 1) }, } { t.Run(name, func(t *testing.T) { dir := t.TempDir() f := newRendererFixture() f.control = edit pin, urls := f.write(t, dir) out := filepath.Join(dir, "renderer.tar.gz") if _, _, err := buildRendererTree(t, pin, urls, out, 0); err == nil { t.Fatal("built") } for _, p := range []string{out, filepath.Join(dir, "SOURCES")} { if _, err := os.Stat(p); !os.IsNotExist(err) { t.Fatalf("%s written: %v", p, err) } } }) } }