oficina / equipo Public

runner: dependency bundle verified against base pins

New package internal/runner/depsbundle (slice 2 ruling S2-1): the
primary bundles its module cache's .mod, .zip and .info files for every
go.mod requirement of the base and the candidate; the hosted runner,
outside the sandbox, stages only modules the base's go.sum pins,
verified against those pins (go.mod and tree hashes), extracted with
x/mod/zip.Unzip into a fresh read-only module cache, within 256 MiB of
bundle, 2 GiB expanded and 200000 files. Conflicts reports candidate
go.sum lines that change a base pin. checks.GoModuleDirsFS is
GoModuleDirs over an fs.FS. The relay's send is Task 23.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f7aa5dc5f6b4467d99e8cad22192d5c1694bb514 parent 250f4f3
6 files changed, +1,424 −2
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +32 −0
  • internal/runner/checks/network.go +9 −2
  • internal/runner/depsbundle/build.go +184 −0
  • internal/runner/depsbundle/depsbundle_test.go +551 −0
  • internal/runner/depsbundle/gosum.go +200 −0
  • internal/runner/depsbundle/stage.go +448 −0
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 2654bef4..da92d1d7 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1161,3 +1161,35 @@ Red: `go test ./internal/equipo/chat -run TestHostedPackIncompleteReportKept -co
Green: that test ok. The brief's command: ok. `./internal/wire` whole package, `./internal/equipo -run 'TestStepReasons|Copy'` (`TestStepReasonsHaveWords` included), chat `-run 'TestHostedPack|TestTransfer|TestPlacement'`, thintest `-run 'TestContractTransfer|TestReview'`: ok. `make budget build vet`: exit 0 (records: internal/equipo 24736, wire 9862, chat 45105/18911, with reasons). gofmt and `git diff --check`: clean. `python3 scripts/copy-status.py verify` (stdin `{"candidate": <worktree>}`): `{"valid": false}` with the pending entry, by design (pending blocks release until Copy or Paul reviews it); `{"valid": true}` on the tree without this change.
167. The registration removed (`ReasonPackIncomplete: true,` deleted from `StepReasons`). `-run TestHostedPackIncompleteReportKept`: FAIL `hosted_pack_test.go:127: hosted pack_incomplete report kept as state "done" checks "cannot_run" reason "unknown"`. Restored (checked with `cmp`).
+
+## Task 16
+
+The dependency bundle (S2-1), new package `internal/runner/depsbundle` (build.go, stage.go, gosum.go, depsbundle_test.go). `checks.GoModuleDirs` gained an `fs.FS` twin, `GoModuleDirsFS` (same walk: not vendored, not under vendor, testdata, dot or underscore directories; `fs.Lstat` for `vendor/modules.txt`), which `GoModuleDirs` now calls; `ModulesFor`, `Pins` and `Conflicts` use it, so the bundle sees exactly the module directories the offline checks see.
+
+- `ModulesFor(base, candidate)`: every `require` (and every versioned `replace` target) of every such go.mod in either tree; a go.mod that does not parse is skipped (the checks report it).
+- `Pins(base)`: the `h1:` lines of the base tree's go.sum files only (`Pin{Mod, Zip}`); two base files that disagree are an error. `Conflicts(base, candidate)`: candidate lines with another hash for a pinned module version (same go.mod or tree line).
+- `Build(ctx, cache, want, limit)`: a tar stream, `MODULES` ("path version" lines) first, then `cache/download/<escaped path>/@v/<escaped version>.{mod,zip,info}` read through an `os.Root` on the cache's `cache/download`. A module with no `.mod` goes in `Bundle.Missing`. Past `limit` is `ErrTooLarge`. `Digest` is `sha256:<hex>`; `Bundle.Bytes()` is the payload for Task 23's deps transfer.
+- `Stage(ctx, r, pins, dir, limits)`: a fresh `deps-*` directory under `dir` (zips land in a sibling `deps-incoming-*` first, removed after). Entries must be regular files with canonical names of modules the list names, each once. For each listed module: unpinned, no `.mod`, or a tree pin with no `.zip` goes in `Staged.Missing` and nothing is written for it; otherwise the `.mod` must hash (`dirhash.Hash1` over `go.mod`) to the pin and, when the pin has a tree line, the zip must hash (`dirhash.HashZip`) to it, else `ErrHashMismatch`. A zip whose module has no tree pin is not staged (only its `.mod` is). Zip entries that are not plain files (a symlink) are `ErrUnsafePath` before extraction; extraction is `x/mod/zip.Unzip` (its refusal, a `../` path for one, is `ErrUnsafePath`). Then `.mod`, a re-encoded `.info` (`{"Version","Time"}`, only when it names the version), the `.zip` and the `.ziphash` (the go command treats a module directory without one as partly extracted and downloads again) are written, and the tree is made read-only (files 0444, directories 0555). Limits (`DefaultLimits`: 256 MiB bundle, 2 GiB expanded, 200000 files; a zero field takes its default) count bundle bytes read, bytes written (zips, cache files, declared uncompressed sizes) and files written; past one is `ErrTooLarge`. Any error removes the fresh directory. `Staged.Remove` makes it writable and removes it.
+- The step outcomes (`deps_conflict`, `needs_network` with `deps_new_module`/`deps_missing`, `deps_too_large`) and the relay's send are the worker's and Task 23's: `relay.go` is not touched here (Build needs nothing from it), so no budget record changes.
+
+A check on this repository (a throwaway test, deleted): `ModulesFor` over the repo found 133 modules; `Build` from the real module cache gave 399 files, 246 MiB, none missing; staged, `go list -deps -test ./...` with `GOPROXY=off GOFLAGS=-mod=mod GOMODCACHE=<staged>` succeeded. The go.mod requirements are enough for module loading; but this repo's own bundle is within 10 MiB of the 256 MiB limit.
+
+Red (API stubs returning "not implemented"): `go test ./internal/runner/depsbundle -count=1` FAIL, every test: `depsbundle_test.go:196: not implemented` (round trip), `Build: not implemented` in `TestBasePinWins`, `TestNewModuleNotStaged`, both `TestBundleRefusesHashMismatch` and both `TestUnsafeZipRefused` subtests, `TestExpandedLimit`, `TestStagedReadOnly`, `TestOfflineBuildFromEmptyCache`. (`Conflicts` was already written; `TestBasePinWins` got past its conflict assertion and failed at `Build`.)
+
+Green: the brief's command `go test ./internal/runner/depsbundle -count=1`: ok (0.12 s); `-count=3 -v`: every test and subtest passes each time, `TestOfflineBuildFromEmptyCache` included (the fixture dependency `example.com/greet` is made with `x/mod/zip.CreateFromDir`, nothing downloaded; the built program prints its greeting). `go test ./internal/runner/checks -run TestDependencyStage -count=1` (which covers `GoModuleDirs`): ok. `make budget build vet`: exit 0 (139 directories within budget). `staticcheck@v0.7.0` on depsbundle and checks: clean. gofmt and `git diff --check`: clean.
+
+Mutation checks (exact unique string replaced by a script, `go test ./internal/runner/depsbundle -run <regex> -count=1 -timeout 120s`, restored from a copy and checked with `filecmp`); each compiled and failed on an assertion.
+
+168. Accept the candidate's pin (`Conflicts`: `if pinned != "" && pinned != l.hash && !seen[l.m]` → `if false && ...`). `-run TestBasePinWins`: FAIL `depsbundle_test.go:271: Conflicts = [], want [example.com/dep@v1.0.0]: the candidate changes a base pin`. Restored.
+169. Accept a zip that does not match its pin (`err != nil || h != pin.Zip` → `err != nil || (h != pin.Zip && false)`). `-run 'TestBasePinWins|TestBundleRefusesHashMismatch'`: FAIL `depsbundle_test.go:288: Stage of bytes matching the candidate's line = {Dir:.../deps-1999463952 Missing:[]}, <nil>; want ErrHashMismatch` and `depsbundle_test.go:348: Stage with the tree changed = {...}, <nil>; want ErrHashMismatch`. Restored.
+170. Accept a go.mod that does not match its pin (the same for `h != pin.Mod`). `-run TestBundleRefusesHashMismatch`: FAIL `depsbundle_test.go:348: Stage with the go.mod changed = {...}, <nil>; want ErrHashMismatch`. Restored.
+171. Stage an unpinned module, pinning it from its own bytes (before the stage check: `if !pinned && p != nil && p.mod != nil && p.zip != "" { pin.Mod, _ = goModHash(p.mod); pin.Zip, _ = dirhash.HashZip(p.zip, dirhash.Hash1); pinned = true }`). `-run TestNewModuleNotStaged`: FAIL `depsbundle_test.go:312: missing [], want [example.com/added@v1.0.0]: the base does not pin it`. Restored.
+172. Write zip entries directly instead of through `Unzip` (the `modzip.Unzip(...)` call replaced by a loop writing each entry to `filepath.Join(target, strings.TrimPrefix(f.Name, prefix))`). `-run TestUnsafeZipRefused`: FAIL `a_../_path`: `depsbundle_test.go:411: Stage = {Dir:.../a/b/deps-806269386 Missing:[]}, <nil>; want ErrUnsafePath`, `depsbundle_test.go:415: Stage wrote .../a/b/escape.txt`, `depsbundle_test.go:420: a refused Stage left [deps-806269386 escape.txt]`. Restored.
+173. No refusal of non-regular zip entries (`!mode.IsRegular() && !mode.IsDir()` → `false && !mode.IsDir()`). `-run TestUnsafeZipRefused`: FAIL `a_symlink`: `depsbundle_test.go:411: Stage = {...}, <nil>; want ErrUnsafePath`, `depsbundle_test.go:415: Stage wrote .../deps-2291313124/example.com/dep@v1.0.0/escape.txt`. Restored.
+174. No expanded limit (`n > st.limits.Expanded-st.expanded ||` removed). First run with a single 1 MiB file: ok, it **survived**: the per-entry size check (there to keep the sum from overflowing) caught it. The fixture now has two 384 KiB files, each within 512 KiB, together past it. Rerun: FAIL `TestExpandedLimit/expanded`: `depsbundle_test.go:447: Stage under {Bundle:0 Expanded:524288 Files:0} = {Dir:.../deps-697017279 Missing:[]}, <nil>; want ErrTooLarge`. Restored.
+175. No file limit (`|| files > st.limits.Files-st.files` removed). `-run TestExpandedLimit`: FAIL `files`: `depsbundle_test.go:446: Stage under {Bundle:0 Expanded:0 Files:3} = {...}, <nil>; want ErrTooLarge`. Restored.
+176. No bundle limit (`if cr.n > st.limits.Bundle {` → `if false {`). `-run TestExpandedLimit`: FAIL `bundle`: `depsbundle_test.go:446: Stage under {Bundle:6655 Expanded:0 Files:0} = {...}, <nil>; want ErrTooLarge`. Restored.
+177. Not made read-only (`readOnly(st.fresh)` → `error(nil)`). `-run TestStagedReadOnly`: FAIL `depsbundle_test.go:484: .../deps-1247203959 is writable (drwx------)` (and every directory and the zip), `depsbundle_test.go:494: wrote a file into the staged tree`. Restored.
+178. No clean-up on failure (`_ = removeTree(st.fresh)` → `_ = removeTree`). `-run 'TestBasePinWins|TestBundleRefusesHashMismatch|TestUnsafeZipRefused|TestExpandedLimit'`: FAIL `depsbundle_test.go:291: a refused Stage left [deps-4011462399]`, `:351` (both hash subtests), `:420` (both unsafe subtests), and the limit subtests. Restored.
+179. Missing not reported (`missing = append(missing, m)` → `_ = m`). `-run 'TestBundleRoundTrip|TestNewModuleNotStaged'`: FAIL `depsbundle_test.go:226: staged missing [], want [example.com/gone@v0.1.0] (pinned, absent from the bundle)`, `depsbundle_test.go:312: missing [], want [example.com/added@v1.0.0]: the base does not pin it`. Restored.
+180. No `.ziphash` (`return true, st.writeFile(base+".ziphash", ...)` → `return true, nil`). `-run TestOfflineBuildFromEmptyCache`: FAIL `depsbundle_test.go:544: offline build: exit status 1 / go: downloading example.com/greet v1.0.0 / main.go:6:2: open .../cache/download/example.com/greet/@v/v1.0.0.lock: permission denied`. Restored.
diff --git a/internal/runner/checks/network.go b/internal/runner/checks/network.go
index efadfc0c..4d78b969 100644
--- a/internal/runner/checks/network.go
+++ b/internal/runner/checks/network.go
@@ -192,8 +192,15 @@ func GoModuleDirs(root string) []string {
return nil
}
defer dir.Close()
+ return GoModuleDirsFS(dir.FS())
+}
+
+// GoModuleDirsFS is GoModuleDirs over a tree given as an fs.FS (a
+// commit's tree, say). Symlinks are not followed where fsys reports
+// them (fs.ReadLinkFS).
+func GoModuleDirsFS(fsys fs.FS) []string {
var out []string
- _ = fs.WalkDir(dir.FS(), ".", func(name string, d fs.DirEntry, err error) error {
+ _ = fs.WalkDir(fsys, ".", func(name string, d fs.DirEntry, err error) error {
if err != nil || len(out) >= 64 {
return fs.SkipDir
}
@@ -206,7 +213,7 @@ func GoModuleDirs(root string) []string {
if d.Name() != "go.mod" || !d.Type().IsRegular() {
return nil
}
- if info, err := dir.Lstat(path.Join(path.Dir(name), "vendor/modules.txt")); err != nil || !info.Mode().IsRegular() {
+ if info, err := fs.Lstat(fsys, path.Join(path.Dir(name), "vendor/modules.txt")); err != nil || !info.Mode().IsRegular() {
out = append(out, path.Dir(name))
}
return nil
diff --git a/internal/runner/depsbundle/build.go b/internal/runner/depsbundle/build.go
new file mode 100644
index 00000000..96a5c99a
--- /dev/null
+++ b/internal/runner/depsbundle/build.go
@@ -0,0 +1,184 @@
+package depsbundle
+
+import (
+ "archive/tar"
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path"
+ "path/filepath"
+ "slices"
+
+ "golang.org/x/mod/module"
+)
+
+// Bundle is the primary's dependency bundle: a tar stream whose first
+// entry, MODULES, lists the wanted modules ("path version" lines), and
+// whose other entries are cache/download/<escaped path>/@v/<escaped
+// version>.{mod,zip,info} files copied from the module cache. Digest is
+// "sha256:<hex>" of the stream, Size its length. Missing are wanted
+// modules the cache has no .mod for.
+type Bundle struct {
+ Digest string
+ Size int64
+ Files []File
+ Missing []Module
+
+ data []byte
+}
+
+// File is one cache file in a bundle: its name in the stream (relative
+// to the module cache root) and its size.
+type File struct {
+ Name string
+ Size int64
+}
+
+// Bytes is the bundle's stream, the deps transfer's payload.
+func (b Bundle) Bytes() []byte { return b.data }
+
+const (
+ manifestName = "MODULES"
+ downloadDir = "cache/download"
+ maxManifest = 4 << 20
+ maxInfoFile = 64 << 10
+ maxModuleWant = 20000
+)
+
+// cacheExts are the files a bundle carries per module, in stream order.
+var cacheExts = []string{".mod", ".zip", ".info"}
+
+// Build reads want's .mod, .zip and .info files from cache/download
+// under cache (a GOMODCACHE) and writes the bundle. Files are opened
+// through an os.Root there, so a symlink cannot reach outside it. A
+// stream past limit bytes is ErrTooLarge.
+func Build(ctx context.Context, cache string, want []Module, limit int64) (Bundle, error) {
+ want = slices.Clone(want)
+ sortModules(want)
+ want = slices.Compact(want)
+ if len(want) > maxModuleWant {
+ return Bundle{}, fmt.Errorf("depsbundle: %d modules: %w", len(want), ErrTooLarge)
+ }
+ root, err := os.OpenRoot(filepath.Join(cache, filepath.FromSlash(downloadDir)))
+ if err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return Bundle{}, err
+ }
+ if root != nil {
+ defer root.Close()
+ }
+
+ var buf bytes.Buffer
+ out := &boundedWriter{w: &buf, n: limit}
+ tw := tar.NewWriter(out)
+ var manifest bytes.Buffer
+ for _, m := range want {
+ if err := module.Check(m.Path, m.Version); err != nil {
+ return Bundle{}, fmt.Errorf("depsbundle: %w", err)
+ }
+ fmt.Fprintf(&manifest, "%s %s\n", m.Path, m.Version)
+ }
+ if err := writeEntry(tw, manifestName, int64(manifest.Len()), &manifest); err != nil {
+ return Bundle{}, out.err(err)
+ }
+
+ var b Bundle
+ for _, m := range want {
+ if err := ctx.Err(); err != nil {
+ return Bundle{}, err
+ }
+ names := cacheNames(m)
+ if root == nil || !regular(root, names[0]) {
+ b.Missing = append(b.Missing, m)
+ continue
+ }
+ for _, name := range names {
+ if !regular(root, name) {
+ continue
+ }
+ size, err := copyEntry(tw, root, name)
+ if err != nil {
+ return Bundle{}, out.err(err)
+ }
+ b.Files = append(b.Files, File{Name: path.Join(downloadDir, name), Size: size})
+ }
+ }
+ if err := tw.Close(); err != nil {
+ return Bundle{}, out.err(err)
+ }
+ sum := sha256.Sum256(buf.Bytes())
+ b.Digest, b.Size, b.data = "sha256:"+hex.EncodeToString(sum[:]), int64(buf.Len()), buf.Bytes()
+ return b, nil
+}
+
+// cacheNames are m's .mod, .zip and .info names under cache/download.
+func cacheNames(m Module) []string {
+ esc, _ := module.EscapePath(m.Path)
+ ver, _ := module.EscapeVersion(m.Version)
+ var out []string
+ for _, ext := range cacheExts {
+ out = append(out, esc+"/@v/"+ver+ext)
+ }
+ return out
+}
+
+func regular(root *os.Root, name string) bool {
+ info, err := root.Lstat(filepath.FromSlash(name))
+ return err == nil && info.Mode().IsRegular()
+}
+
+func copyEntry(tw *tar.Writer, root *os.Root, name string) (int64, error) {
+ f, err := root.Open(filepath.FromSlash(name))
+ if err != nil {
+ return 0, err
+ }
+ defer f.Close()
+ info, err := f.Stat()
+ if err != nil {
+ return 0, err
+ }
+ if !info.Mode().IsRegular() {
+ return 0, fmt.Errorf("depsbundle: %s: %w", name, ErrUnsafePath)
+ }
+ return info.Size(), writeEntry(tw, path.Join(downloadDir, name), info.Size(), f)
+}
+
+func writeEntry(tw *tar.Writer, name string, size int64, r io.Reader) error {
+ if err := tw.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: name, Size: size, Mode: 0o444, Format: tar.FormatPAX}); err != nil {
+ return err
+ }
+ n, err := io.Copy(tw, io.LimitReader(r, size))
+ if err == nil && n != size {
+ err = fmt.Errorf("depsbundle: %s changed while it was read", name)
+ }
+ return err
+}
+
+// boundedWriter refuses a write past n bytes in all.
+type boundedWriter struct {
+ w io.Writer
+ n int64
+ over bool
+}
+
+func (b *boundedWriter) Write(p []byte) (int, error) {
+ if int64(len(p)) > b.n {
+ b.over = true
+ return 0, ErrTooLarge
+ }
+ b.n -= int64(len(p))
+ return b.w.Write(p)
+}
+
+// err is ErrTooLarge when the bound was what stopped the stream.
+func (b *boundedWriter) err(err error) error {
+ if b.over {
+ return fmt.Errorf("depsbundle: the bundle: %w", ErrTooLarge)
+ }
+ return err
+}
diff --git a/internal/runner/depsbundle/depsbundle_test.go b/internal/runner/depsbundle/depsbundle_test.go
new file mode 100644
index 00000000..12311b4f
--- /dev/null
+++ b/internal/runner/depsbundle/depsbundle_test.go
@@ -0,0 +1,551 @@
+package depsbundle
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "io"
+ "io/fs"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "testing/fstest"
+
+ "golang.org/x/mod/module"
+ "golang.org/x/mod/sumdb/dirhash"
+ modzip "golang.org/x/mod/zip"
+)
+
+// fixtureModule writes m's source files into a scratch directory, zips
+// it with x/mod/zip.CreateFromDir into cache/download under cache, writes
+// the .mod and .info beside it, and returns the module's pin as the go
+// command would compute it.
+func fixtureModule(t *testing.T, cache string, m Module, files map[string]string) Pin {
+ t.Helper()
+ src := t.TempDir()
+ for name, body := range files {
+ p := filepath.Join(src, filepath.FromSlash(name))
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ at := cacheDir(t, cache, m)
+ var z bytes.Buffer
+ if err := modzip.CreateFromDir(&z, module.Version{Path: m.Path, Version: m.Version}, src); err != nil {
+ t.Fatal(err)
+ }
+ return writeCacheFiles(t, at, m, []byte(files["go.mod"]), z.Bytes())
+}
+
+// writeCacheFiles writes a module's .zip, .mod and .info into its
+// cache/download directory and returns their hashes.
+func writeCacheFiles(t *testing.T, at string, m Module, gomod, z []byte) Pin {
+ t.Helper()
+ ver, _ := module.EscapeVersion(m.Version)
+ base := filepath.Join(at, ver)
+ if err := os.WriteFile(base+".zip", z, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(base+".mod", gomod, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(base+".info", []byte(`{"Version":"`+m.Version+`","Time":"2026-01-02T03:04:05Z"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return Pin{Mod: hashGoMod(t, gomod), Zip: hashZip(t, base+".zip")}
+}
+
+func cacheDir(t *testing.T, cache string, m Module) string {
+ t.Helper()
+ esc, err := module.EscapePath(m.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ at := filepath.Join(cache, "cache", "download", filepath.FromSlash(esc), "@v")
+ if err := os.MkdirAll(at, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ return at
+}
+
+func hashGoMod(t *testing.T, gomod []byte) string {
+ t.Helper()
+ h, err := dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) {
+ return io.NopCloser(bytes.NewReader(gomod)), nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return h
+}
+
+func hashZip(t *testing.T, name string) string {
+ t.Helper()
+ h, err := dirhash.HashZip(name, dirhash.Hash1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return h
+}
+
+func sumText(lines ...string) string { return strings.Join(lines, "\n") + "\n" }
+
+func sumFor(m Module, p Pin) string {
+ return m.Path + " " + m.Version + " " + p.Zip + "\n" + m.Path + " " + m.Version + "/go.mod " + p.Mod
+}
+
+func goModFor(name string, reqs ...Module) string {
+ s := "module " + name + "\n\ngo 1.22\n"
+ for _, r := range reqs {
+ s += "\nrequire " + r.Path + " " + r.Version + "\n"
+ }
+ return s
+}
+
+// stageDir is a scratch parent for Stage whose read-only tree is made
+// writable again before the test's own clean-up removes it.
+func stageDir(t *testing.T) string {
+ t.Helper()
+ dir := t.TempDir()
+ t.Cleanup(func() { makeWritable(dir) })
+ return dir
+}
+
+func makeWritable(dir string) {
+ _ = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
+ if err == nil && d.IsDir() {
+ _ = os.Chmod(p, 0o755)
+ }
+ return nil
+ })
+}
+
+func bundleFor(t *testing.T, cache string, base, candidate fs.FS) Bundle {
+ t.Helper()
+ want, err := ModulesFor(base, candidate)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := Build(context.Background(), cache, want, DefaultLimits.Bundle)
+ if err != nil {
+ t.Fatalf("Build: %v", err)
+ }
+ return b
+}
+
+func stage(t *testing.T, b Bundle, base fs.FS, dir string, limits Limits) (Staged, error) {
+ t.Helper()
+ pins, err := Pins(base)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return Stage(context.Background(), bytes.NewReader(b.Bytes()), pins, dir, limits)
+}
+
+// leftBehind lists what a failed Stage left under dir.
+func leftBehind(t *testing.T, dir string) []string {
+ t.Helper()
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, e := range entries {
+ out = append(out, e.Name())
+ }
+ return out
+}
+
+var (
+ dep = Module{"example.com/dep", "v1.0.0"}
+ upper = Module{"example.com/Upper", "v1.2.0"}
+ gone = Module{"example.com/gone", "v0.1.0"}
+)
+
+func TestBundleRoundTrip(t *testing.T) {
+ cache := t.TempDir()
+ depPin := fixtureModule(t, cache, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n\nconst Name = \"dep\"\n"})
+ upperPin := fixtureModule(t, cache, upper, map[string]string{"go.mod": "module example.com/Upper\n", "u.go": "package upper\n"})
+ gonePin := Pin{Mod: "h1:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", Zip: "h1:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="}
+ vend := Module{"example.com/vendored", "v1.0.0"}
+ base := fstest.MapFS{
+ "go.mod": {Data: []byte(goModFor("example.com/app", dep, upper, gone))},
+ "go.sum": {Data: []byte(sumText(sumFor(dep, depPin), sumFor(upper, upperPin), sumFor(gone, gonePin)))},
+ "tools/go.mod": {Data: []byte(goModFor("example.com/app/tools", vend))},
+ "tools/vendor/modules.txt": {Data: []byte("# example.com/vendored v1.0.0\n")},
+ }
+
+ want, err := ModulesFor(base, base)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(want, []Module{upper, dep, gone}) {
+ t.Fatalf("ModulesFor = %v, want %v (the vendored module skipped)", want, []Module{upper, dep, gone})
+ }
+ b, err := Build(context.Background(), cache, want, DefaultLimits.Bundle)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(b.Bytes())
+ if b.Digest != "sha256:"+hex.EncodeToString(sum[:]) || b.Size != int64(len(b.Bytes())) {
+ t.Fatalf("bundle digest %s size %d, want the stream's (%d bytes)", b.Digest, b.Size, len(b.Bytes()))
+ }
+ if !slices.Equal(b.Missing, []Module{gone}) {
+ t.Fatalf("bundle missing %v, want [%v]", b.Missing, gone)
+ }
+ var names []string
+ for _, f := range b.Files {
+ names = append(names, f.Name)
+ }
+ wantNames := []string{
+ "cache/download/example.com/!upper/@v/v1.2.0.mod", "cache/download/example.com/!upper/@v/v1.2.0.zip", "cache/download/example.com/!upper/@v/v1.2.0.info",
+ "cache/download/example.com/dep/@v/v1.0.0.mod", "cache/download/example.com/dep/@v/v1.0.0.zip", "cache/download/example.com/dep/@v/v1.0.0.info",
+ }
+ if !slices.Equal(names, wantNames) {
+ t.Fatalf("bundle files %v, want %v", names, wantNames)
+ }
+
+ dir := stageDir(t)
+ s, err := stage(t, b, base, dir, Limits{})
+ if err != nil {
+ t.Fatalf("Stage: %v", err)
+ }
+ if filepath.Dir(s.Dir) != dir {
+ t.Fatalf("staged in %s, want a fresh directory under %s", s.Dir, dir)
+ }
+ if !slices.Equal(s.Missing, []Module{gone}) {
+ t.Fatalf("staged missing %v, want [%v] (pinned, absent from the bundle)", s.Missing, gone)
+ }
+ for name, body := range map[string]string{
+ "example.com/dep@v1.0.0/dep.go": "package dep\n\nconst Name = \"dep\"\n",
+ "example.com/!upper@v1.2.0/u.go": "package upper\n",
+ "cache/download/example.com/dep/@v/v1.0.0.mod": "module example.com/dep\n",
+ "cache/download/example.com/dep/@v/v1.0.0.ziphash": depPin.Zip,
+ "cache/download/example.com/!upper/@v/v1.2.0.ziphash": upperPin.Zip,
+ "cache/download/example.com/!upper/@v/v1.2.0.mod": "module example.com/Upper\n",
+ "cache/download/example.com/dep/@v/v1.0.0.info": `{"Version":"v1.0.0","Time":"2026-01-02T03:04:05Z"}`,
+ } {
+ got, err := os.ReadFile(filepath.Join(s.Dir, filepath.FromSlash(name)))
+ if err != nil || strings.TrimSpace(string(got)) != strings.TrimSpace(body) {
+ t.Errorf("staged %s = %q, %v; want %q", name, got, err, body)
+ }
+ }
+ if got := hashZip(t, filepath.Join(s.Dir, "cache/download/example.com/dep/@v/v1.0.0.zip")); got != depPin.Zip {
+ t.Errorf("staged zip hashes %s, want %s", got, depPin.Zip)
+ }
+ if err := s.Remove(); err != nil {
+ t.Fatalf("Remove: %v", err)
+ }
+ if _, err := os.Stat(s.Dir); !errors.Is(err, fs.ErrNotExist) {
+ t.Fatalf("after Remove %s: %v", s.Dir, err)
+ }
+}
+
+func TestBasePinWins(t *testing.T) {
+ // The base pins the real dep; the candidate's go.sum pins other bytes
+ // for the same version, and the primary's cache holds those bytes.
+ real := t.TempDir()
+ realPin := fixtureModule(t, real, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n"})
+ cache := t.TempDir()
+ evilPin := fixtureModule(t, cache, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n\nfunc init() { panic(\"evil\") }\n"})
+ if realPin.Zip == evilPin.Zip {
+ t.Fatal("fixture: the two trees hash alike")
+ }
+ base := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, realPin)))}}
+ cand := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, evilPin)))}}
+
+ conflicts, err := Conflicts(base, cand)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(conflicts, []Module{dep}) {
+ t.Fatalf("Conflicts = %v, want [%v]: the candidate changes a base pin", conflicts, dep)
+ }
+ if same, _ := Conflicts(base, base); len(same) != 0 {
+ t.Fatalf("Conflicts(base, base) = %v, want none", same)
+ }
+ pins, err := Pins(base)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if pins[dep] != realPin {
+ t.Fatalf("pin %v, want the base's %v", pins[dep], realPin)
+ }
+
+ b := bundleFor(t, cache, base, cand)
+ dir := stageDir(t)
+ s, err := stage(t, b, base, dir, Limits{})
+ if !errors.Is(err, ErrHashMismatch) {
+ t.Fatalf("Stage of bytes matching the candidate's line = %+v, %v; want ErrHashMismatch", s, err)
+ }
+ if left := leftBehind(t, dir); len(left) != 0 {
+ t.Fatalf("a refused Stage left %v", left)
+ }
+}
+
+func TestNewModuleNotStaged(t *testing.T) {
+ cache := t.TempDir()
+ depPin := fixtureModule(t, cache, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n"})
+ added := Module{"example.com/added", "v1.0.0"}
+ addedPin := fixtureModule(t, cache, added, map[string]string{"go.mod": "module example.com/added\n", "a.go": "package added\n"})
+ base := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, depPin)))}}
+ cand := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep, added))}, "go.sum": {Data: []byte(sumText(sumFor(dep, depPin), sumFor(added, addedPin)))}}
+
+ b := bundleFor(t, cache, base, cand)
+ if len(b.Files) != 6 {
+ t.Fatalf("the primary bundles %d files, want both modules' 6", len(b.Files))
+ }
+ s, err := stage(t, b, base, stageDir(t), Limits{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(s.Missing, []Module{added}) {
+ t.Fatalf("missing %v, want [%v]: the base does not pin it", s.Missing, added)
+ }
+ for _, name := range []string{"example.com/added@v1.0.0", "cache/download/example.com/added"} {
+ if _, err := os.Lstat(filepath.Join(s.Dir, name)); !errors.Is(err, fs.ErrNotExist) {
+ t.Errorf("%s staged (%v), want absent", name, err)
+ }
+ }
+ if _, err := os.Stat(filepath.Join(s.Dir, "example.com/dep@v1.0.0/dep.go")); err != nil {
+ t.Errorf("the pinned module was not staged: %v", err)
+ }
+}
+
+func TestBundleRefusesHashMismatch(t *testing.T) {
+ for _, tc := range []struct{ name, ext string }{{"the go.mod", ".mod"}, {"the tree", ".zip"}} {
+ t.Run(tc.name, func(t *testing.T) {
+ cache := t.TempDir()
+ pin := fixtureModule(t, cache, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n"})
+ if tc.ext == ".mod" {
+ if err := os.WriteFile(filepath.Join(cacheDir(t, cache, dep), "v1.0.0.mod"), []byte("module example.com/dep\n\nrequire example.com/x v1.0.0\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ other := t.TempDir()
+ fixtureModule(t, other, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep // changed\n"})
+ z, err := os.ReadFile(filepath.Join(cacheDir(t, other, dep), "v1.0.0.zip"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(cacheDir(t, cache, dep), "v1.0.0.zip"), z, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ base := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, pin)))}}
+ dir := stageDir(t)
+ s, err := stage(t, bundleFor(t, cache, base, base), base, dir, Limits{})
+ if !errors.Is(err, ErrHashMismatch) {
+ t.Fatalf("Stage with %s changed = %+v, %v; want ErrHashMismatch", tc.name, s, err)
+ }
+ if left := leftBehind(t, dir); len(left) != 0 {
+ t.Fatalf("a refused Stage left %v", left)
+ }
+ })
+ }
+}
+
+// craftedZip is a module zip written entry by entry, bypassing
+// x/mod/zip's own checks, the way a hostile cache could hold one.
+func craftedZip(t *testing.T, entries []zipEntry) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ w := zip.NewWriter(&buf)
+ for _, e := range entries {
+ h := &zip.FileHeader{Name: e.name, Method: zip.Deflate}
+ h.SetMode(e.mode)
+ f, err := w.CreateHeader(h)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.Write([]byte(e.body)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := w.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+type zipEntry struct {
+ name, body string
+ mode fs.FileMode
+}
+
+func TestUnsafeZipRefused(t *testing.T) {
+ prefix := "example.com/dep@v1.0.0/"
+ for _, tc := range []struct {
+ name string
+ entry zipEntry
+ }{
+ {"a ../ path", zipEntry{prefix + "../../../escape.txt", "escaped\n", 0o644}},
+ {"a symlink", zipEntry{prefix + "escape.txt", "/etc/passwd", fs.ModeSymlink | 0o777}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cache := t.TempDir()
+ gomod := []byte("module example.com/dep\n")
+ z := craftedZip(t, []zipEntry{{prefix + "go.mod", string(gomod), 0o644}, {prefix + "dep.go", "package dep\n", 0o644}, tc.entry})
+ // The base pins exactly these bytes, so only the extraction
+ // stands between them and the disk.
+ pin := writeCacheFiles(t, cacheDir(t, cache, dep), dep, gomod, z)
+ base := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, pin)))}}
+ root := t.TempDir()
+ dir := filepath.Join(root, "a", "b")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { makeWritable(root) })
+
+ s, err := stage(t, bundleFor(t, cache, base, base), base, dir, Limits{})
+ if !errors.Is(err, ErrUnsafePath) {
+ t.Errorf("Stage = %+v, %v; want ErrUnsafePath", s, err)
+ }
+ _ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err == nil && (d.Name() == "escape.txt" || d.Type()&fs.ModeSymlink != 0) {
+ t.Errorf("Stage wrote %s", p)
+ }
+ return nil
+ })
+ if left := leftBehind(t, dir); len(left) != 0 {
+ t.Errorf("a refused Stage left %v", left)
+ }
+ })
+ }
+}
+
+func TestExpandedLimit(t *testing.T) {
+ cache := t.TempDir()
+ // Two files each within the expanded limit, together past it.
+ pin := fixtureModule(t, cache, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n", "big1.txt": strings.Repeat("0", 384<<10), "big2.txt": strings.Repeat("1", 384<<10)})
+ base := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, pin)))}}
+ b := bundleFor(t, cache, base, base)
+ if b.Size > 64<<10 {
+ t.Fatalf("fixture: the bundle is %d bytes, want a small zip of a large tree", b.Size)
+ }
+ for _, tc := range []struct {
+ name string
+ limits Limits
+ }{
+ {"expanded", Limits{Expanded: 512 << 10}},
+ {"files", Limits{Files: 3}},
+ {"bundle", Limits{Bundle: b.Size - 1}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := stageDir(t)
+ s, err := stage(t, b, base, dir, tc.limits)
+ if !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("Stage under %+v = %+v, %v; want ErrTooLarge", tc.limits, s, err)
+ }
+ if left := leftBehind(t, dir); len(left) != 0 {
+ t.Fatalf("a refused Stage left %v", left)
+ }
+ })
+ }
+ t.Run("within", func(t *testing.T) {
+ if _, err := stage(t, b, base, stageDir(t), Limits{Expanded: 4 << 20, Files: 10, Bundle: b.Size}); err != nil {
+ t.Fatalf("Stage within the limits: %v", err)
+ }
+ })
+ t.Run("build", func(t *testing.T) {
+ want, _ := ModulesFor(base, base)
+ if _, err := Build(context.Background(), cache, want, b.Size-1); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("Build past its limit: %v, want ErrTooLarge", err)
+ }
+ })
+}
+
+func TestStagedReadOnly(t *testing.T) {
+ cache := t.TempDir()
+ pin := fixtureModule(t, cache, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n", "sub/s.go": "package sub\n"})
+ base := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, pin)))}}
+ s, err := stage(t, bundleFor(t, cache, base, base), base, stageDir(t), Limits{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ n := 0
+ _ = filepath.WalkDir(s.Dir, func(p string, d fs.DirEntry, err error) error {
+ if err != nil {
+ t.Fatal(err)
+ }
+ info, err := d.Info()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm()&0o222 != 0 {
+ t.Errorf("%s is writable (%v)", p, info.Mode())
+ }
+ n++
+ return nil
+ })
+ if n < 10 {
+ t.Fatalf("walked %d entries, want the whole staged tree", n)
+ }
+ if os.Getuid() != 0 {
+ if err := os.WriteFile(filepath.Join(s.Dir, "example.com/dep@v1.0.0/new.go"), []byte("package dep\n"), 0o644); err == nil {
+ t.Error("wrote a file into the staged tree")
+ }
+ }
+}
+
+// TestOfflineBuildFromEmptyCache builds a real module whose one
+// dependency comes only from the staged cache: no proxy, no network,
+// a fresh GOMODCACHE.
+func TestOfflineBuildFromEmptyCache(t *testing.T) {
+ gobin, err := exec.LookPath("go")
+ if err != nil {
+ t.Fatalf("the go command: %v", err)
+ }
+ primary := t.TempDir()
+ greet := Module{"example.com/greet", "v1.0.0"}
+ pin := fixtureModule(t, primary, greet, map[string]string{
+ "go.mod": "module example.com/greet\n\ngo 1.22\n",
+ "greet.go": "package greet\n\nfunc Hello() string { return \"hello from greet\" }\n",
+ })
+ app := t.TempDir()
+ for name, body := range map[string]string{
+ "go.mod": goModFor("example.com/app", greet),
+ "go.sum": sumText(sumFor(greet, pin)),
+ "main.go": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"example.com/greet\"\n)\n\nfunc main() { fmt.Println(greet.Hello()) }\n",
+ } {
+ if err := os.WriteFile(filepath.Join(app, name), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ tree := os.DirFS(app)
+ s, err := stage(t, bundleFor(t, primary, tree, tree), tree, stageDir(t), Limits{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(s.Missing) != 0 {
+ t.Fatalf("missing %v", s.Missing)
+ }
+
+ out := filepath.Join(t.TempDir(), "app")
+ cmd := exec.Command(gobin, "build", "-o", out, ".")
+ cmd.Dir = app
+ for _, kv := range os.Environ() {
+ switch k, _, _ := strings.Cut(kv, "="); k {
+ case "GOPROXY", "GOFLAGS", "GOMODCACHE", "GOPRIVATE", "GONOPROXY", "GONOSUMDB", "GOINSECURE", "GOWORK":
+ default:
+ cmd.Env = append(cmd.Env, kv)
+ }
+ }
+ cmd.Env = append(cmd.Env, "GOPROXY=off", "GOFLAGS=-mod=mod", "GOMODCACHE="+s.Dir)
+ if b, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("offline build: %v\n%s", err, b)
+ }
+ got, err := exec.Command(out).Output()
+ if err != nil || string(got) != "hello from greet\n" {
+ t.Fatalf("the built program said %q, %v", got, err)
+ }
+}
diff --git a/internal/runner/depsbundle/gosum.go b/internal/runner/depsbundle/gosum.go
new file mode 100644
index 00000000..76294d8a
--- /dev/null
+++ b/internal/runner/depsbundle/gosum.go
@@ -0,0 +1,200 @@
+// Package depsbundle carries Go module dependencies from a person's
+// primary runner to a hosted VM (slice 2 ruling S2-1). The primary
+// builds a bundle from the module cache its own checks use; the hosted
+// runner, outside the sandbox, stages only modules the BASE commit's
+// go.sum pins, verified against those pins, extracted with
+// golang.org/x/mod/zip into a fresh read-only module cache. Nothing is
+// ever fetched from the network.
+package depsbundle
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "io"
+ "io/fs"
+ "path"
+ "slices"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "golang.org/x/mod/modfile"
+ "golang.org/x/mod/module"
+)
+
+// Module is one module version.
+type Module struct{ Path, Version string }
+
+func (m Module) String() string { return m.Path + "@" + m.Version }
+
+// Pin is what a base go.sum says a module version hashes to: Mod for its
+// go.mod (the "/go.mod" line), Zip for its whole tree. Either may be
+// empty when the base has no such line.
+type Pin struct{ Mod, Zip string }
+
+// maxSumFile and maxModFile bound one go.sum and one go.mod read from a
+// tree.
+const (
+ maxSumFile = 16 << 20
+ maxModFile = 16 << 20
+)
+
+// ModulesFor is what the primary bundles: every requirement (and every
+// module replacement) of every go.mod in either tree, in the module
+// directories checks.GoModuleDirs would give (vendored modules skipped).
+// A go.mod that does not parse is skipped: the checks themselves report
+// it.
+func ModulesFor(base, candidate fs.FS) (want []Module, err error) {
+ seen := map[Module]bool{}
+ for _, tree := range []fs.FS{base, candidate} {
+ for _, dir := range checks.GoModuleDirsFS(tree) {
+ name := path.Join(dir, "go.mod")
+ data, err := readBounded(tree, name, maxModFile)
+ if err != nil {
+ return nil, err
+ }
+ f, err := modfile.Parse(name, data, nil)
+ if err != nil {
+ continue
+ }
+ add := func(p, v string) {
+ m := Module{p, v}
+ if v != "" && module.Check(p, v) == nil && !seen[m] {
+ seen[m] = true
+ want = append(want, m)
+ }
+ }
+ for _, r := range f.Require {
+ add(r.Mod.Path, r.Mod.Version)
+ }
+ for _, r := range f.Replace {
+ add(r.New.Path, r.New.Version)
+ }
+ }
+ }
+ sortModules(want)
+ return want, nil
+}
+
+// Pins reads the h1: lines of the BASE tree's go.sum files (one beside
+// each go.mod of checks.GoModuleDirs). Only the base is ever a source
+// of pins. Two base files that disagree on a line are an error.
+func Pins(base fs.FS) (map[Module]Pin, error) {
+ lines, err := sumLines(base)
+ if err != nil {
+ return nil, err
+ }
+ pins := map[Module]Pin{}
+ for _, l := range lines {
+ p := pins[l.m]
+ have := &p.Zip
+ if l.mod {
+ have = &p.Mod
+ }
+ if *have != "" && *have != l.hash {
+ return nil, fmt.Errorf("depsbundle: the base's go.sum files disagree on %s", l.m)
+ }
+ *have = l.hash
+ pins[l.m] = p
+ }
+ return pins, nil
+}
+
+// Conflicts are the modules for which a candidate go.sum line changes a
+// base pin: the same module version (and the same go.mod or tree line)
+// with another hash. Sorted, each once.
+func Conflicts(base, candidate fs.FS) ([]Module, error) {
+ pins, err := Pins(base)
+ if err != nil {
+ return nil, err
+ }
+ lines, err := sumLines(candidate)
+ if err != nil {
+ return nil, err
+ }
+ seen := map[Module]bool{}
+ var out []Module
+ for _, l := range lines {
+ p, ok := pins[l.m]
+ if !ok {
+ continue
+ }
+ pinned := p.Zip
+ if l.mod {
+ pinned = p.Mod
+ }
+ if pinned != "" && pinned != l.hash && !seen[l.m] {
+ seen[l.m] = true
+ out = append(out, l.m)
+ }
+ }
+ sortModules(out)
+ return out, nil
+}
+
+type sumLine struct {
+ m Module
+ mod bool // the "/go.mod" line
+ hash string
+}
+
+// sumLines are the h1: lines of every go.sum in tree's module
+// directories. Other hash kinds and malformed lines are skipped (the go
+// command ignores unknown kinds too).
+func sumLines(tree fs.FS) ([]sumLine, error) {
+ var out []sumLine
+ for _, dir := range checks.GoModuleDirsFS(tree) {
+ name := path.Join(dir, "go.sum")
+ info, err := fs.Lstat(tree, name)
+ if err != nil || !info.Mode().IsRegular() {
+ continue
+ }
+ data, err := readBounded(tree, name, maxSumFile)
+ if err != nil {
+ return nil, err
+ }
+ sc := bufio.NewScanner(bytes.NewReader(data))
+ sc.Buffer(make([]byte, 64<<10), 64<<10)
+ for sc.Scan() {
+ f := strings.Fields(sc.Text())
+ if len(f) != 3 || !strings.HasPrefix(f[2], "h1:") {
+ continue
+ }
+ v, mod := strings.CutSuffix(f[1], "/go.mod")
+ if module.Check(f[0], v) != nil {
+ continue
+ }
+ out = append(out, sumLine{Module{f[0], v}, mod, f[2]})
+ }
+ if err := sc.Err(); err != nil {
+ return nil, fmt.Errorf("depsbundle: %s: %w", name, err)
+ }
+ }
+ return out, nil
+}
+
+func readBounded(tree fs.FS, name string, max int64) ([]byte, error) {
+ f, err := tree.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ var buf bytes.Buffer
+ n, err := buf.ReadFrom(io.LimitReader(f, max+1))
+ if err != nil {
+ return nil, err
+ }
+ if n > max {
+ return nil, fmt.Errorf("depsbundle: %s: %w", name, ErrTooLarge)
+ }
+ return buf.Bytes(), nil
+}
+
+func sortModules(ms []Module) {
+ slices.SortFunc(ms, func(a, b Module) int {
+ if c := strings.Compare(a.Path, b.Path); c != 0 {
+ return c
+ }
+ return strings.Compare(a.Version, b.Version)
+ })
+}
diff --git a/internal/runner/depsbundle/stage.go b/internal/runner/depsbundle/stage.go
new file mode 100644
index 00000000..3dd70d5c
--- /dev/null
+++ b/internal/runner/depsbundle/stage.go
@@ -0,0 +1,448 @@
+package depsbundle
+
+import (
+ "archive/tar"
+ "archive/zip"
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "time"
+
+ "golang.org/x/mod/module"
+ "golang.org/x/mod/sumdb/dirhash"
+ modzip "golang.org/x/mod/zip"
+)
+
+// Errors Stage returns. Each ends the staging; nothing is left behind.
+var (
+ // ErrHashMismatch: a module's go.mod or tree does not match its base
+ // pin.
+ ErrHashMismatch = errors.New("depsbundle: module does not match its base pin")
+ // ErrTooLarge: the bundle, the expanded tree or its file count is
+ // past its limit.
+ ErrTooLarge = errors.New("depsbundle: dependencies past their limit")
+ // ErrUnsafePath: a bundle entry or a module zip entry that is not a
+ // plain file at a clean path inside its module.
+ ErrUnsafePath = errors.New("depsbundle: unsafe path in the dependencies")
+)
+
+// Limits bound a staging: Bundle bytes read, Expanded bytes written and
+// Files files written. A zero field takes its default.
+type Limits struct {
+ Bundle, Expanded int64
+ Files int
+}
+
+// DefaultLimits are 256 MiB of bundle, 2 GiB expanded and 200000 files.
+var DefaultLimits = Limits{Bundle: 256 << 20, Expanded: 2 << 30, Files: 200000}
+
+func (l Limits) withDefaults() Limits {
+ if l.Bundle <= 0 {
+ l.Bundle = DefaultLimits.Bundle
+ }
+ if l.Expanded <= 0 {
+ l.Expanded = DefaultLimits.Expanded
+ }
+ if l.Files <= 0 {
+ l.Files = DefaultLimits.Files
+ }
+ return l
+}
+
+// Staged is a read-only module cache: Dir is a GOMODCACHE. Missing are
+// the bundle's wanted modules not staged: the base does not pin them, or
+// the bundle lacks a file their pin needs.
+type Staged struct {
+ Dir string
+ Missing []Module
+}
+
+// Remove makes the staged tree writable again and removes it.
+func (s Staged) Remove() error { return removeTree(s.Dir) }
+
+// Stage runs outside the sandbox. It reads bundle, verifies each wanted
+// module the base pins against that pin (its .mod, and its .zip when the
+// pin has a tree hash), extracts the zip with golang.org/x/mod/zip.Unzip,
+// writes the cache/download files (and the .ziphash the go command looks
+// for), and makes the tree read-only, all in a fresh directory under
+// dir. A module the base does not pin is never staged. A zip whose base
+// pin has no tree line is not staged either (only its .mod is). On an
+// error nothing is left under dir.
+func Stage(ctx context.Context, bundle io.Reader, pins map[Module]Pin, dir string, limits Limits) (_ Staged, err error) {
+ st := &stager{limits: limits.withDefaults(), parts: map[Module]*received{}}
+ if st.fresh, err = os.MkdirTemp(dir, "deps-"); err != nil {
+ return Staged{}, err
+ }
+ defer func() {
+ if err != nil {
+ _ = removeTree(st.fresh)
+ }
+ }()
+ if st.incoming, err = os.MkdirTemp(dir, "deps-incoming-"); err != nil {
+ return Staged{}, err
+ }
+ defer func() { _ = removeTree(st.incoming) }()
+
+ if err := st.receive(ctx, bundle); err != nil {
+ return Staged{}, err
+ }
+ var missing []Module
+ for _, m := range st.want {
+ if err := ctx.Err(); err != nil {
+ return Staged{}, err
+ }
+ staged, err := st.stage(m, pins)
+ if err != nil {
+ return Staged{}, fmt.Errorf("%s: %w", m, err)
+ }
+ if !staged {
+ missing = append(missing, m)
+ }
+ }
+ if err := readOnly(st.fresh); err != nil {
+ return Staged{}, err
+ }
+ return Staged{Dir: st.fresh, Missing: missing}, nil
+}
+
+type stager struct {
+ limits Limits
+ fresh, incoming string
+ expanded int64 // bytes written
+ files int // files written
+ want []Module
+ parts map[Module]*received
+}
+
+// received is what the bundle carried for one module: its .mod and
+// .info bytes and its .zip, written to the incoming directory.
+type received struct {
+ mod, info []byte
+ zip string
+ seen map[string]bool
+}
+
+func (st *stager) write(n int64, files int) error {
+ if n < 0 || n > st.limits.Expanded-st.expanded || files > st.limits.Files-st.files {
+ return fmt.Errorf("depsbundle: the staged tree: %w", ErrTooLarge)
+ }
+ st.expanded += n
+ st.files += files
+ return nil
+}
+
+// receive reads the stream: MODULES first, then cache files of the
+// modules it names. Past the bundle limit is ErrTooLarge whatever else
+// went wrong.
+func (st *stager) receive(ctx context.Context, bundle io.Reader) error {
+ cr := &countingReader{r: io.LimitReader(bundle, st.limits.Bundle+1)}
+ over := func(err error) error {
+ _, _ = io.Copy(io.Discard, cr)
+ if cr.n > st.limits.Bundle {
+ return fmt.Errorf("depsbundle: the bundle: %w", ErrTooLarge)
+ }
+ return err
+ }
+ tr := tar.NewReader(cr)
+ hdr, err := tr.Next()
+ if err != nil {
+ return over(fmt.Errorf("depsbundle: the bundle: %w", err))
+ }
+ if hdr.Name != manifestName || hdr.Typeflag != tar.TypeReg || hdr.Size > maxManifest {
+ return over(fmt.Errorf("depsbundle: the bundle does not start with its module list"))
+ }
+ if err := st.manifest(tr); err != nil {
+ return over(err)
+ }
+ for {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ hdr, err := tr.Next()
+ if err == io.EOF {
+ return over(nil)
+ }
+ if err != nil {
+ return over(fmt.Errorf("depsbundle: the bundle: %w", err))
+ }
+ if err := st.entry(tr, hdr); err != nil {
+ return over(err)
+ }
+ }
+}
+
+func (st *stager) manifest(r io.Reader) error {
+ sc := bufio.NewScanner(r)
+ seen := map[Module]bool{}
+ for sc.Scan() {
+ f := strings.Fields(sc.Text())
+ if len(f) != 2 || !validVersion(f[0], f[1]) || seen[Module{f[0], f[1]}] || len(st.want) >= maxModuleWant {
+ return fmt.Errorf("depsbundle: the bundle's module list has a bad line %q", sc.Text())
+ }
+ m := Module{f[0], f[1]}
+ seen[m] = true
+ st.want = append(st.want, m)
+ }
+ return sc.Err()
+}
+
+func validVersion(p, v string) bool {
+ return module.Check(p, v) == nil && module.CanonicalVersion(v) == v
+}
+
+// entry takes one cache file: a regular file named exactly
+// cache/download/<escaped path>/@v/<escaped version><ext> for a module
+// the list names, each once.
+func (st *stager) entry(tr *tar.Reader, hdr *tar.Header) error {
+ m, ext, ok := parseName(hdr.Name)
+ if !ok || hdr.Typeflag != tar.TypeReg {
+ return fmt.Errorf("depsbundle: bundle entry %q: %w", hdr.Name, ErrUnsafePath)
+ }
+ if !slices.Contains(st.want, m) {
+ return fmt.Errorf("depsbundle: bundle entry %q is not in its module list", hdr.Name)
+ }
+ p := st.parts[m]
+ if p == nil {
+ p = &received{seen: map[string]bool{}}
+ st.parts[m] = p
+ }
+ if p.seen[ext] {
+ return fmt.Errorf("depsbundle: bundle entry %q twice", hdr.Name)
+ }
+ p.seen[ext] = true
+ switch ext {
+ case ".mod", ".info":
+ max := int64(maxModFile)
+ if ext == ".info" {
+ max = maxInfoFile
+ }
+ if hdr.Size > max {
+ return fmt.Errorf("depsbundle: %s: %w", hdr.Name, ErrTooLarge)
+ }
+ data, err := io.ReadAll(tr)
+ if err != nil {
+ return err
+ }
+ if ext == ".mod" {
+ p.mod = data
+ } else {
+ p.info = data
+ }
+ case ".zip":
+ if err := st.write(hdr.Size, 1); err != nil {
+ return err
+ }
+ f, err := os.CreateTemp(st.incoming, "*.zip")
+ if err != nil {
+ return err
+ }
+ _, err = io.Copy(f, tr)
+ if err := errors.Join(err, f.Close()); err != nil {
+ return err
+ }
+ p.zip = f.Name()
+ }
+ return nil
+}
+
+// parseName reads cache/download/<escaped path>/@v/<escaped version><ext>
+// and accepts it only in its canonical spelling.
+func parseName(name string) (Module, string, bool) {
+ rest, ok := strings.CutPrefix(name, downloadDir+"/")
+ i := strings.LastIndex(rest, "/@v/")
+ if !ok || i < 0 {
+ return Module{}, "", false
+ }
+ for _, ext := range cacheExts {
+ ver, ok := strings.CutSuffix(rest[i+len("/@v/"):], ext)
+ if !ok {
+ continue
+ }
+ p, err1 := module.UnescapePath(rest[:i])
+ v, err2 := module.UnescapeVersion(ver)
+ if err1 != nil || err2 != nil || !validVersion(p, v) {
+ return Module{}, "", false
+ }
+ m := Module{p, v}
+ if canon := downloadDir + "/" + cacheNames(m)[slices.Index(cacheExts, ext)]; canon != name {
+ return Module{}, "", false
+ }
+ return m, ext, true
+ }
+ return Module{}, "", false
+}
+
+// stage verifies and writes one wanted module. It reports false, writing
+// nothing, when the base does not pin it or the bundle lacks a file its
+// pin needs.
+func (st *stager) stage(m Module, pins map[Module]Pin) (bool, error) {
+ pin, pinned := pins[m]
+ p := st.parts[m]
+ if !pinned || pin.Mod == "" || p == nil || p.mod == nil || (pin.Zip != "" && p.zip == "") {
+ return false, nil
+ }
+ if h, err := goModHash(p.mod); err != nil || h != pin.Mod {
+ return false, fmt.Errorf("go.mod: %w", ErrHashMismatch)
+ }
+ if pin.Zip != "" {
+ if h, err := dirhash.HashZip(p.zip, dirhash.Hash1); err != nil || h != pin.Zip {
+ return false, fmt.Errorf("zip: %w", ErrHashMismatch)
+ }
+ }
+
+ esc, _ := module.EscapePath(m.Path)
+ ver, _ := module.EscapeVersion(m.Version)
+ at := filepath.Join(st.fresh, filepath.FromSlash(downloadDir), filepath.FromSlash(esc), "@v")
+ if err := os.MkdirAll(at, 0o755); err != nil {
+ return false, err
+ }
+ base := filepath.Join(at, ver)
+ if err := st.writeFile(base+".mod", p.mod); err != nil {
+ return false, err
+ }
+ if info, ok := canonicalInfo(m, p.info); ok {
+ if err := st.writeFile(base+".info", info); err != nil {
+ return false, err
+ }
+ }
+ if pin.Zip == "" {
+ return true, nil
+ }
+ if err := st.extract(m, p.zip, filepath.Join(st.fresh, filepath.FromSlash(esc)+"@"+ver)); err != nil {
+ return false, err
+ }
+ if err := os.Rename(p.zip, base+".zip"); err != nil {
+ return false, err
+ }
+ return true, st.writeFile(base+".ziphash", []byte(pin.Zip+"\n"))
+}
+
+// extract checks the zip's entries (plain files only, sizes within the
+// limits) and extracts it with x/mod/zip.Unzip, which refuses paths
+// outside the module and every other name the go command would refuse.
+func (st *stager) extract(m Module, zipPath, target string) error {
+ z, err := zip.OpenReader(zipPath)
+ if err != nil {
+ return fmt.Errorf("zip: %w", ErrUnsafePath)
+ }
+ var size int64
+ files := 0
+ for _, f := range z.File {
+ mode := f.Mode()
+ if !mode.IsRegular() && !mode.IsDir() {
+ z.Close()
+ return fmt.Errorf("zip entry %q (%v): %w", f.Name, mode, ErrUnsafePath)
+ }
+ if mode.IsDir() {
+ continue
+ }
+ if f.UncompressedSize64 > uint64(st.limits.Expanded) {
+ z.Close()
+ return fmt.Errorf("zip entry %q: %w", f.Name, ErrTooLarge)
+ }
+ size += int64(f.UncompressedSize64)
+ files++
+ }
+ z.Close()
+ if err := st.write(size, files); err != nil {
+ return err
+ }
+ if err := modzip.Unzip(target, module.Version{Path: m.Path, Version: m.Version}, zipPath); err != nil {
+ return fmt.Errorf("%w: %v", ErrUnsafePath, err)
+ }
+ return nil
+}
+
+func (st *stager) writeFile(name string, data []byte) error {
+ if err := st.write(int64(len(data)), 1); err != nil {
+ return err
+ }
+ f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o444)
+ if err != nil {
+ return err
+ }
+ _, err = f.Write(data)
+ return errors.Join(err, f.Close())
+}
+
+// goModHash is a go.mod's go.sum hash (the "/go.mod" line).
+func goModHash(data []byte) (string, error) {
+ return dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) {
+ return io.NopCloser(bytes.NewReader(data)), nil
+ })
+}
+
+// canonicalInfo re-encodes a .info that names m's version; the staged
+// tree never holds the bundle's own bytes for it.
+func canonicalInfo(m Module, data []byte) ([]byte, bool) {
+ var info struct {
+ Version string
+ Time time.Time
+ }
+ if data == nil || json.Unmarshal(data, &info) != nil || info.Version != m.Version {
+ return nil, false
+ }
+ out, err := json.Marshal(info)
+ return out, err == nil
+}
+
+// readOnly removes every write bit in the tree, directories last.
+func readOnly(root string) error {
+ var dirs []string
+ err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ switch {
+ case err != nil:
+ return err
+ case d.IsDir():
+ dirs = append(dirs, p)
+ return nil
+ case d.Type().IsRegular():
+ return os.Chmod(p, 0o444)
+ default:
+ return fmt.Errorf("depsbundle: %s: %w", p, ErrUnsafePath)
+ }
+ })
+ if err != nil {
+ return err
+ }
+ for _, d := range slices.Backward(dirs) {
+ if err := os.Chmod(d, 0o555); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// removeTree makes a staged tree's directories writable and removes it.
+func removeTree(root string) error {
+ if root == "" {
+ return nil
+ }
+ _ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err == nil && d.IsDir() {
+ _ = os.Chmod(p, 0o755)
+ }
+ return nil
+ })
+ return os.RemoveAll(root)
+}
+
+type countingReader struct {
+ r io.Reader
+ n int64
+}
+
+func (c *countingReader) Read(p []byte) (int, error) {
+ n, err := c.r.Read(p)
+ c.n += int64(n)
+ return n, err
+}