package release import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "os" "os/exec" "path/filepath" "runtime" "strings" "testing" "amadan.net/oficina/equipo/internal/release/renderertest" "amadan.net/oficina/equipo/internal/testci" ) // publishRig is a release kit, the repository it was built from (with a // bare origin), and stub curl, amadan and go: the forge is a directory of // published assets by tag, amadan release create copies into it and logs, // and go version -m reports the tag linked into the kit's runner. type publishRig struct { t *testing.T repo, kit, forge, log, commit string archive, sources, tag, pinJSON string origin string env []string linked rigAsset } // rigAsset is what the rig's kit runner says is linked into it; none // makes it say nothing and exit 1. type rigAsset struct { tag, pin, sum, size string none bool } // writeRunner writes the kit's stub runner for r.linked. func (r *publishRig) writeRunner() { exit := "" if r.linked.none { exit = "exit 1\n" } body := fmt.Sprintf("#!/bin/sh\n[ \"$1 $2\" = \"renderer-asset --json\" ] || exit 2\n%sprintf '{\"tag\":\"%s\",\"pin\":\"%s\",\"sha256\":\"%s\",\"size\":%s}\\n'\n", exit, r.linked.tag, r.linked.pin, r.linked.sum, r.linked.size) os.WriteFile(filepath.Join(r.kit, "equipo-runner"), []byte(body), 0o755) } // linking rewrites the kit's runner with edit applied to what it says. func linking(edit func(*rigAsset)) func(*publishRig) []string { return func(r *publishRig) []string { edit(&r.linked) r.writeRunner() return nil } } func newPublishRig(t *testing.T) *publishRig { t.Helper() testci.Files(t, "../../scripts/publish-renderer.sh", "../../scripts/renderer-sources.py") testci.Tools(t, "git", "python3", "sh", "bwrap") r := &publishRig{t: t, repo: t.TempDir(), kit: t.TempDir(), forge: t.TempDir(), log: filepath.Join(t.TempDir(), "log")} run := func(dir string, args ...string) string { t.Helper() cmd := exec.Command(args[0], args[1:]...) cmd.Dir = dir cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com", "GIT_CONFIG_GLOBAL=/dev/null") out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("%v: %v\n%s", args, err, out) } return strings.TrimSpace(string(out)) } origin := t.TempDir() run(origin, "git", "init", "-q", "--bare") run(r.repo, "git", "init", "-q", "-b", "main") r.pinJSON = `{"version":"1.0-1","amd64":[{"package":"chromium-headless-shell","version":"1.0-1","architecture":"amd64","url":"https://snapshot.debian.org/archive/debian/20990101T000000Z/pool/main/c/chromium/chromium-headless-shell_1.0-1_amd64.deb","sha256":"` + strings.Repeat("a", 64) + `","size":1}]}` os.MkdirAll(filepath.Join(r.repo, "internal", "release"), 0o755) os.WriteFile(filepath.Join(r.repo, "internal", "release", "renderer.json"), []byte(r.pinJSON), 0o644) run(r.repo, "git", "add", "-A") run(r.repo, "git", "commit", "-q", "-m", "pin") run(r.repo, "git", "remote", "add", "origin", origin) r.commit = run(r.repo, "git", "rev-parse", "HEAD") // A later commit: the kit is not the current checkout. run(r.repo, "git", "commit", "-q", "--allow-empty", "-m", "later") archive, pin := renderertest.Archive(renderertest.Small()) r.archive = string(archive) r.sources = "The page renderer: Chromium headless shell 1.0-1, from Debian.\nChromium source: https://snapshot.debian.org/package/chromium/1.0-1/\n\n" + "chromium-headless-shell 1.0-1 amd64 https://snapshot.debian.org/archive/debian/20990101T000000Z/pool/main/c/chromium/chromium-headless-shell_1.0-1_amd64.deb https://snapshot.debian.org/package/chromium/1.0-1/\n" sum := sha256.Sum256([]byte(r.archive)) r.tag = "renderer-" + hex.EncodeToString(sum[:])[:12] archiveSum := hex.EncodeToString(sum[:]) manifest := fmt.Sprintf(`{"targets":{"linux/amd64":{"renderer_sha256":%q,"renderer_archive_sha256":%q,"renderer_archive_size":%d}}}`, pin, archiveSum, len(archive)) for name, body := range map[string]string{"renderer.tar.gz": r.archive, "SOURCES": r.sources, "install-manifest.json": manifest, "COMMIT": r.commit + "\n"} { os.WriteFile(filepath.Join(r.kit, name), []byte(body), 0o644) } bin := t.TempDir() stub := func(name, body string) { os.WriteFile(filepath.Join(bin, name), []byte("#!/bin/sh\n"+body), 0o755) } // curl: the last argument is the URL; --output names where to write; // prints the status as --write-out asks. stub("curl", `out=; for a; do [ "$prev" = --output ] && out=$a; prev=$a; url=$a; done echo "curl $*" >> `+r.log+` path=`+r.forge+`/${url#https://amadan.net/oficina/equipo/-/releases/} if [ -f "$path" ]; then cp "$path" "$out"; printf 200; else : > "$out"; printf 404; fi `) // amadan release create -repo R -notes-file N TAG FILE... stub("amadan", `echo "amadan $*" >> `+r.log+` tag=$7; shift 7; mkdir -p `+r.forge+`/$tag; for f; do cp "$f" `+r.forge+`/$tag/; done `) // The kit's runner answers renderer-asset --json with what is linked // into it (the script runs it sandboxed with an empty environment, so // each case writes its own). r.linked = rigAsset{tag: r.tag, pin: pin, sum: archiveSum, size: fmt.Sprint(len(archive))} r.writeRunner() r.env = append(os.Environ(), "PATH="+bin+string(os.PathListSeparator)+os.Getenv("PATH"), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com") r.origin = origin return r } func (r *publishRig) run(args ...string) (string, error) { script, _ := filepath.Abs("../../scripts/publish-renderer.sh") cmd := exec.Command("bash", append([]string{script}, args...)...) cmd.Dir = r.repo cmd.Env = r.env out, err := cmd.CombinedOutput() return string(out), err } func (r *publishRig) logged() string { b, _ := os.ReadFile(r.log); return string(b) } // publish puts the kit's archive and SOURCES on the forge under the tag // linked into its runner, tagging the kit's commit (not the checkout), // then downloads both in full and compares them. A second publish only // checks; check mode downloads into a directory. func TestPublishRenderer(t *testing.T) { r := newPublishRig(t) if out, err := r.run("publish", r.kit); err != nil { t.Fatalf("publish: %v\n%s", err, out) } if !strings.Contains(r.logged(), "amadan release create -repo oficina/equipo -notes-file ") || !strings.Contains(r.logged(), r.tag+" "+filepath.Join(r.kit, "renderer.tar.gz")+" "+filepath.Join(r.kit, "SOURCES")) { t.Fatalf("no release created:\n%s", r.logged()) } out, err := exec.Command("git", "--git-dir", r.origin, "rev-parse", r.tag+"^{commit}").Output() if err != nil || strings.TrimSpace(string(out)) != r.commit { t.Fatalf("the forge's tag names %q, not the kit's commit %s: %v", out, r.commit, err) } for _, name := range []string{"renderer.tar.gz", "SOURCES"} { if b, _ := os.ReadFile(filepath.Join(r.forge, r.tag, name)); string(b) == "" { t.Fatalf("%s not published", name) } } os.Remove(r.log) if out, err := r.run("publish", r.kit); err != nil || strings.Contains(r.logged(), "amadan release") { t.Fatalf("second publish: %v\n%s\n%s", err, out, r.logged()) } dir := filepath.Join(t.TempDir(), "downloaded") if out, err := r.run("check", r.kit, dir); err != nil { t.Fatalf("check: %v\n%s", err, out) } if b, _ := os.ReadFile(filepath.Join(dir, "renderer.tar.gz")); string(b) != r.archive { t.Fatalf("check downloaded %q", b) } if !strings.Contains(r.logged(), "curl --silent") { t.Fatalf("curl's arguments not logged:\n%s", r.logged()) } if strings.Contains(r.logged(), " -I ") || strings.Contains(r.logged(), "--head") || strings.Contains(r.logged(), "--range") || strings.Contains(r.logged(), " -r ") { t.Fatalf("a HEAD or ranged request:\n%s", r.logged()) } } // A published asset that differs from the kit, a tag that is not the // archive's, SOURCES that are not the pinned packages', and check with // nothing published: refused, and nothing is created. func TestPublishRendererRefuses(t *testing.T) { for name, c := range map[string]struct { set func(r *publishRig) []string args func(r *publishRig) []string }{ "a different published archive": {func(r *publishRig) []string { os.MkdirAll(filepath.Join(r.forge, r.tag), 0o755) os.WriteFile(filepath.Join(r.forge, r.tag, "renderer.tar.gz"), []byte("other bytes"), 0o644) os.WriteFile(filepath.Join(r.forge, r.tag, "SOURCES"), []byte(r.sources), 0o644) return nil }, nil}, "a tag naming another archive": {linking(func(a *rigAsset) { a.tag = "renderer-000000000000" }), nil}, "no linked tag": {linking(func(a *rigAsset) { a.tag = "" }), nil}, "no asset linked": {linking(func(a *rigAsset) { a.none = true }), nil}, "another linked size": {linking(func(a *rigAsset) { a.size = "1" }), nil}, "another linked digest": {linking(func(a *rigAsset) { a.sum = strings.Repeat("0", 64) }), nil}, "another linked pin": {linking(func(a *rigAsset) { a.pin = strings.Repeat("0", 64) }), nil}, // The runner runs with no home, no network and no environment: one // that tries to read the publisher's files or a credential in its // environment finds nothing. // Nor can it find the publisher's environment through the // sandbox's first process (/proc/1/environ). "a runner reading the publisher's environment": {func(r *publishRig) []string { r.writeRunner() good, _ := os.ReadFile(filepath.Join(r.kit, "equipo-runner")) body := strings.Replace(string(good), "printf", "tr '\\0' '\\n' < /proc/1/environ | grep -q '^PUBLISHER_CANARY=leaked$' || exit 1\nprintf", 1) os.WriteFile(filepath.Join(r.kit, "equipo-runner"), []byte(body), 0o755) return []string{"PUBLISHER_CANARY=leaked"} }, nil}, "a runner reading the home directory": {func(r *publishRig) []string { r.writeRunner() good, _ := os.ReadFile(filepath.Join(r.kit, "equipo-runner")) // It answers properly only where it can read the kit. body := strings.Replace(string(good), "printf", "cat \""+filepath.Join(r.kit, "COMMIT")+"\" >/dev/null || exit 1\nprintf", 1) os.WriteFile(filepath.Join(r.kit, "equipo-runner"), []byte(body), 0o755) return nil }, nil}, "a manifest recording another size": {func(r *publishRig) []string { raw, _ := os.ReadFile(filepath.Join(r.kit, "install-manifest.json")) os.WriteFile(filepath.Join(r.kit, "install-manifest.json"), []byte(strings.Replace(string(raw), `"renderer_archive_size":`, `"renderer_archive_size":1`, 1)), 0o644) return nil }, nil}, "SOURCES not the pin's": {func(r *publishRig) []string { os.WriteFile(filepath.Join(r.kit, "SOURCES"), []byte(strings.Replace(r.sources, "1.0-1 amd64", "9.9-9 amd64", 1)), 0o644) return nil }, nil}, "check with nothing published": {func(r *publishRig) []string { return nil }, func(r *publishRig) []string { return []string{"check", r.kit, t.TempDir()} }}, } { t.Run(name, func(t *testing.T) { r := newPublishRig(t) r.env = append(r.env, c.set(r)...) args := []string{"publish", r.kit} if c.args != nil { args = c.args(r) } if out, err := r.run(args...); err == nil { t.Fatalf("passed:\n%s", out) } if strings.Contains(r.logged(), "amadan release create") { t.Fatalf("created a release:\n%s", r.logged()) } }) } } // releaseRunnerCommand is the shell command make release-runner runs to // build the Linux runner into kit, as make -n prints it: -trimpath and // the real -ldflags. Only its target is this machine's (the CI box is // arm64), so the test can run what it builds. func releaseRunnerCommand(t *testing.T, kit string) string { t.Helper() cmd := exec.Command("make", "-n", "--no-print-directory", "release-runner", "RUNNER_RELEASE_DIR="+kit) cmd.Dir = "../.." out, err := cmd.Output() if err != nil { t.Fatalf("make -n release-runner: %v", err) } text := string(out) start := strings.Index(text, "CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath \\\n") end := strings.Index(text[max(start, 0):], "-o "+kit+"/equipo-runner ./cmd/equipo-runner\n") if start < 0 || end < 0 { t.Fatalf("no Linux runner build in make -n release-runner:\n%s", text) } build := text[start : start+end+len("-o "+kit+"/equipo-runner ./cmd/equipo-runner")] if !strings.Contains(build, "-trimpath") || !strings.Contains(build, "internal/release.rendererTag=") { t.Fatalf("the release build has changed shape: %s", build) } return strings.Replace(build, "GOOS=linux GOARCH=amd64", "GOOS="+runtime.GOOS+" GOARCH="+runtime.GOARCH, 1) } // The release tooling reads what is linked into a runner built exactly as // make release-runner builds it (-trimpath keeps no -ldflags in the build // information, go.dev/issue/52372): the runner's renderer-asset --json // names the kit's archive, and publish-renderer.sh check passes against // it. A check that read build information would refuse here. func TestPublishRendererReadsAReleaseBuiltRunner(t *testing.T) { testci.Files(t, "../../Makefile") testci.Tools(t, "git", "tar", "bwrap") // The runner it builds, and everything it is built from. testci.GoPackages(t, "../..", nil, "", "./cmd/equipo-runner") r := newPublishRig(t) for _, name := range []string{"gitleaks", "equipo-tool-proxy"} { os.WriteFile(filepath.Join(r.kit, name), []byte("fixture "+name), 0o755) } os.Remove(filepath.Join(r.kit, "equipo-runner")) build := exec.Command("sh", "-c", releaseRunnerCommand(t, r.kit)) build.Dir = "../.." if out, err := build.CombinedOutput(); err != nil { t.Fatalf("build: %v\n%s", err, out) } if info, err := exec.Command("go", "version", "-m", filepath.Join(r.kit, "equipo-runner")).Output(); err != nil || strings.Contains(string(info), "rendererTag") { t.Fatalf("the build information holds the ldflags after all (%v): the test proves nothing", err) } out, err := exec.Command(filepath.Join(r.kit, "equipo-runner"), "renderer-asset", "--json").Output() if err != nil { t.Fatalf("renderer-asset: %v", err) } var got struct { Tag, Pin, SHA256 string Size int64 } if err = json.Unmarshal(out, &got); err != nil || got.Tag != r.tag || got.SHA256 != fmt.Sprintf("%x", sha256.Sum256([]byte(r.archive))) || got.Size != int64(len(r.archive)) || got.Pin == "" { t.Fatalf("renderer-asset %s: %v", out, err) } os.MkdirAll(filepath.Join(r.forge, r.tag), 0o755) for _, name := range []string{"renderer.tar.gz", "SOURCES"} { b, _ := os.ReadFile(filepath.Join(r.kit, name)) os.WriteFile(filepath.Join(r.forge, r.tag, name), b, 0o644) } if out, err := r.run("check", r.kit, t.TempDir()); err != nil { t.Fatalf("check against a release-built runner: %v\n%s", err, out) } }