oficina / equipo Public

runner: Task 16 review 1, limits before hashing, every go.sum

The zip's structure (x/mod/zip.CheckZip), plain-file entries and its
declared sizes and file count are checked against the limits before
its bodies are hashed, and hashing stops with its context. Pins and
conflicts come from every go.sum in each tree, so a vendor marker
cannot hide a changed pin. Module discovery returns walk errors,
ErrTooLarge past 64 modules and ErrMalformed for a go.mod or go.sum
that does not parse. A module the base pins only by its go.mod has its
.mod staged and is reported missing. The checks.GoModuleDirsFS
refactor is reverted (depsbundle has its own error-aware walk).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev dc52f8d8f218d20a56b6fafa036e668e1a9f930c parent f7aa5dc
5 files changed, +478 −67
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +40 −0
  • internal/runner/checks/network.go +2 −9
  • internal/runner/depsbundle/depsbundle_test.go +232 −0
  • internal/runner/depsbundle/gosum.go +122 −31
  • internal/runner/depsbundle/stage.go +82 −27
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index da92d1d7..fbf63719 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1193,3 +1193,43 @@ Mutation checks (exact unique string replaced by a script, `go test ./internal/r
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.
+
+### Task 16 review round 1 (t16-r1.md: findings 1-4 fixed; 5, the relay send, ruled to Task 23; reason registration is Task 17's)
+
+1. **Limits before hashing.** `stage` now runs `preflight` on a zip before `zipHash`: `x/mod/zip.CheckZip` (structure from the directory only: every entry a clean path under `path@version/`, no collisions, the go command's caps), plain files only, and the declared sizes and file count charged against what is left of `Expanded` and `Files`. Actual decompressed bytes are bounded by those declared sizes: archive/zip fails a body that outgrows its declared size while hashing (`TestLyingZipRefused`), and `Unzip` does the same while extracting. A read error while hashing is now `ErrUnsafePath`, not `ErrHashMismatch`. `zipHash` is `dirhash.HashZip` with every body read through a reader that checks the context, so an ended context stops it.
+2. **Pins and conflicts from every go.sum.** `sumFiles` walks the whole tree (no vendoring filter, no skipped directories, symlinks not followed, at most 256 files, then `ErrTooLarge`), for the base and the candidate separately. Base lines that disagree are `ErrMalformed`. On this repository: 428 pins, no conflicts with itself.
+3. **Error-aware discovery.** `ModulesFor` uses its own walk, `moduleDirs`, with the same directory rules as `checks.GoModuleDirs` (a test checks both agree on a tree with a vendored module, testdata, dot and underscore directories). Walk errors are returned. A 65th module directory is `ErrTooLarge`, and a go.mod that does not parse, or a requirement that is not a valid module version, is the new `ErrMalformed`. A go.sum line that is not "path version hash" is `ErrMalformed` (lines of other hash kinds are still skipped, as the go command skips them). Because depsbundle has its own walk now, the `checks.GoModuleDirsFS` refactor is reverted: `internal/runner/checks` is byte-identical to 250f4f35. On this repository `ModulesFor` still finds 133 modules.
+4. **A go.mod-only pin is missing.** When the base pins only a module's `/go.mod`, or the bundle has no zip for a tree pin, its verified `.mod` (and `.info`) is staged and the module is in `Missing`. Its zip, extracted directory and `.ziphash` are not staged.
+
+New tests: `TestOversizedZipRefusedBeforeHash`, `TestLyingZipRefused`, `TestZipHashCancellable`, `TestVendorMarkerDoesNotHideConflict`, `TestModuleDiscoveryErrors` (the 65th module, a malformed go.mod, a malformed go.sum, agreement with the checks' module directories), `TestGoModOnlyPinReported` (with and without a zip in the bundle), and `TestZipDirectoryEntries`, added after mutation 183 below.
+
+Red (the tests against f7aa5dc5's code, with `ErrMalformed` declared and `zipHash` stubbed as `dirhash.HashZip`): `go test ./internal/runner/depsbundle -count=1` FAIL:
+- `depsbundle_test.go:572: Stage under {Bundle:0 Expanded:524288 Files:0} = {Dir: Missing:[]}, example.com/dep@v1.0.0: zip: depsbundle: module does not match its base pin; want ErrTooLarge before the hash`, the same for `{Files:3}`.
+- `:588: Stage of a zip with an entry outside its module = ... module does not match its base pin; want ErrUnsafePath before the hash`.
+- `:631: Stage of a zip whose entry outgrows its declared size = ... module does not match its base pin; want ErrUnsafePath`.
+- `:645: zipHash with an ended context = "h1:Pva7...", <nil>; want context.Canceled`.
+- `:662: Conflicts with a vendor marker added = [], <nil>; want [example.com/dep@v1.0.0]`.
+- `:682: 65 modules: [example.com/dep@v1.0.0], <nil>; want ErrTooLarge, not a partial list`.
+- `:689: ModulesFor with a malformed go.mod = [example.com/dep@v1.0.0], <nil>; want ErrMalformed`.
+- `:696: Pins of a malformed go.sum = map[], <nil>; want ErrMalformed`.
+- `:747: missing [], want [example.com/dep@v1.0.0]: its source is not staged`, in both `TestGoModOnlyPinReported` subtests.
+
+The agreement subtest passed at red, as expected: it guards the walk's rules, which were the checks' own.
+
+Green: `go test ./internal/runner/depsbundle -count=3`: ok. `make budget build vet`: exit 0. staticcheck v0.7.0 on depsbundle: clean. gofmt and `git diff --check`: clean. A throwaway test on this repository (deleted) gave `ModulesFor` 133 modules, `Pins` 428, `Conflicts` none.
+
+Mutation checks (same method: exact unique strings replaced by a script, `-count=1 -timeout 120s`, restored from a copy and checked with `filecmp`):
+
+181. Hash before the preflight (`zipHash` and the pin comparison moved ahead of `st.preflight`). `-run TestOversizedZipRefusedBeforeHash`: FAIL `depsbundle_test.go:572` (both limits) and `:588`, each `... module does not match its base pin; want ErrTooLarge before the hash` (or `ErrUnsafePath`). Restored.
+182. No structure check (`CheckZip`'s error ignored: `err != nil && false`). `-run 'TestOversizedZipRefusedBeforeHash|TestUnsafeZipRefused'`: FAIL `depsbundle_test.go:588: Stage of a zip with an entry outside its module = ... module does not match its base pin; want ErrUnsafePath before the hash`. Restored. (`TestUnsafeZipRefused` still passed: `Unzip` refused the `../` path after a matching hash.)
+183. Write zip entries directly instead of through `Unzip` (the brief's mutation, rerun). On its own, against `TestUnsafeZipRefused|TestOversizedZipRefusedBeforeHash|TestLyingZipRefused|TestBundleRoundTrip|TestOfflineBuild`: ok, it **survived**. `CheckZip` in the preflight now refuses the `../` path before extraction, so the hand-written loop only ever saw valid zips. Added `TestZipDirectoryEntries`: a zip with a directory entry, which x/mod/zip accepts and `Unzip` skips. It passes on the real code. With the mutation: FAIL `depsbundle_test.go:778: Stage of a zip with a directory entry: example.com/dep@v1.0.0: depsbundle: unsafe path in the dependencies: mkdir .../example.com/dep@v1.0.0/sub: not a directory`. Restored.
+184. Both together: hand-written extraction and no `CheckZip`. `-run TestUnsafeZipRefused`: FAIL `a_../_path`: `depsbundle_test.go:415: Stage = {Dir:.../a/b/deps-2989840189 Missing:[]}, <nil>; want ErrUnsafePath`, `:419: Stage wrote .../a/b/escape.txt`, `:424: a refused Stage left [deps-2989840189 escape.txt]`. Restored.
+185. Hashing not cancellable (the context check in `ctxReader.Read` removed). `-run TestZipHashCancellable`: FAIL `depsbundle_test.go:645: zipHash with an ended context = "h1:Pva7JEkl0a3W2/OuPIzQ10VfYFeyh0/bkh/n5Rdh3/0=", <nil>; want context.Canceled`. Restored.
+186. go.sum files found through the module walk (`sumFiles` replaced by `moduleDirs` + `go.sum`). `-run TestVendorMarkerDoesNotHideConflict`: FAIL `depsbundle_test.go:662: Conflicts with a vendor marker added = [], <nil>; want [example.com/dep@v1.0.0]`. Restored.
+187. Silent module cap (the `ErrTooLarge` return → `fs.SkipAll`). `-run TestModuleDiscoveryErrors`: FAIL `the_65th_module`: `depsbundle_test.go:682: 65 modules: [example.com/dep@v1.0.0], <nil>; want ErrTooLarge, not a partial list`. Restored.
+188. Malformed go.mod skipped (`return nil, fmt.Errorf("%w: %v", ErrMalformed, err)` → `continue`). Same test: FAIL `a_malformed_go.mod`: `depsbundle_test.go:689: ModulesFor with a malformed go.mod = [example.com/dep@v1.0.0], <nil>; want ErrMalformed`. Restored.
+189. Malformed go.sum line skipped (the `ErrMalformed` return → `continue`). Same test: FAIL `a_malformed_go.sum`: `depsbundle_test.go:696: Pins of a malformed go.sum = map[], <nil>; want ErrMalformed`. Restored.
+190. A go.mod-only module reported complete (`if !source { return false, nil }` → `return true, nil`). `-run TestGoModOnlyPinReported`: FAIL both subtests, `depsbundle_test.go:747: missing [], want [example.com/dep@v1.0.0]: its source is not staged`. Restored.
+173 and 174, rerun with the checks moved into the preflight: 173 (no symlink refusal) FAIL `a_symlink`: `depsbundle_test.go:415: ... want ErrUnsafePath`, `:419: Stage wrote .../example.com/dep@v1.0.0/escape.txt`. 174 (no expanded limit) FAIL `TestExpandedLimit/expanded` `:451` and `TestOversizedZipRefusedBeforeHash` `:572`. Both restored.
+
+Not covered by a test: a walk error (an `fs.FS` whose directory read fails) is returned, but no test fakes one.
diff --git a/internal/runner/checks/network.go b/internal/runner/checks/network.go
index 4d78b969..efadfc0c 100644
--- a/internal/runner/checks/network.go
+++ b/internal/runner/checks/network.go
@@ -192,15 +192,8 @@ 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(fsys, ".", func(name string, d fs.DirEntry, err error) error {
+ _ = fs.WalkDir(dir.FS(), ".", func(name string, d fs.DirEntry, err error) error {
if err != nil || len(out) >= 64 {
return fs.SkipDir
}
@@ -213,7 +206,7 @@ func GoModuleDirsFS(fsys fs.FS) []string {
if d.Name() != "go.mod" || !d.Type().IsRegular() {
return nil
}
- if info, err := fs.Lstat(fsys, path.Join(path.Dir(name), "vendor/modules.txt")); err != nil || !info.Mode().IsRegular() {
+ if info, err := dir.Lstat(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/depsbundle_test.go b/internal/runner/depsbundle/depsbundle_test.go
index 12311b4f..01889200 100644
--- a/internal/runner/depsbundle/depsbundle_test.go
+++ b/internal/runner/depsbundle/depsbundle_test.go
@@ -3,10 +3,13 @@ package depsbundle
import (
"archive/zip"
"bytes"
+ "compress/flate"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
+ "fmt"
+ "hash/crc32"
"io"
"io/fs"
"os"
@@ -17,6 +20,7 @@ import (
"testing"
"testing/fstest"
+ "amadan.net/oficina/equipo/internal/runner/checks"
"golang.org/x/mod/module"
"golang.org/x/mod/sumdb/dirhash"
modzip "golang.org/x/mod/zip"
@@ -549,3 +553,231 @@ func TestOfflineBuildFromEmptyCache(t *testing.T) {
t.Fatalf("the built program said %q, %v", got, err)
}
}
+
+// Round 1 (t16-r1.md).
+
+// TestOversizedZipRefusedBeforeHash: the zip's structure and the limits
+// are checked from its directory before any body is read. The pin here
+// does not match, so a Stage that hashed first would answer
+// ErrHashMismatch.
+func TestOversizedZipRefusedBeforeHash(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", "big1.txt": strings.Repeat("0", 384<<10), "big2.txt": strings.Repeat("1", 384<<10)})
+ pin.Zip = "h1:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
+ 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)
+ for _, limits := range []Limits{{Expanded: 512 << 10}, {Files: 3}} {
+ dir := stageDir(t)
+ if s, err := stage(t, b, base, dir, limits); !errors.Is(err, ErrTooLarge) {
+ t.Errorf("Stage under %+v = %+v, %v; want ErrTooLarge before the hash", limits, s, err)
+ }
+ if left := leftBehind(t, dir); len(left) != 0 {
+ t.Errorf("a refused Stage left %v", left)
+ }
+ }
+
+ // A zip whose entry is outside its module: refused as unsafe, from
+ // its directory, before the hash.
+ cache = t.TempDir()
+ gomod := []byte("module example.com/dep\n")
+ z := craftedZip(t, []zipEntry{{"example.com/dep@v1.0.0/go.mod", string(gomod), 0o644}, {"example.com/other@v1.0.0/x.go", "package x\n", 0o644}})
+ pin = writeCacheFiles(t, cacheDir(t, cache, dep), dep, gomod, z)
+ pin.Zip = "h1:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
+ base = fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, pin)))}}
+ if s, err := stage(t, bundleFor(t, cache, base, base), base, stageDir(t), Limits{}); !errors.Is(err, ErrUnsafePath) {
+ t.Errorf("Stage of a zip with an entry outside its module = %+v, %v; want ErrUnsafePath before the hash", s, err)
+ }
+}
+
+// TestLyingZipRefused: an entry that inflates past its declared size is
+// refused (archive/zip stops at the declared size), never staged.
+func TestLyingZipRefused(t *testing.T) {
+ cache := t.TempDir()
+ gomod := []byte("module example.com/dep\n")
+ var buf bytes.Buffer
+ w := zip.NewWriter(&buf)
+ f, err := w.Create("example.com/dep@v1.0.0/go.mod")
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.Write(gomod)
+ body := []byte(strings.Repeat("x", 1<<20))
+ var deflated bytes.Buffer
+ fw, err := flateWriter(&deflated)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fw.Write(body)
+ fw.Close()
+ raw, err := w.CreateRaw(&zip.FileHeader{Name: "example.com/dep@v1.0.0/big.txt", Method: zip.Deflate, CompressedSize64: uint64(deflated.Len()), UncompressedSize64: 10, CRC32: crc(body[:10])})
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw.Write(deflated.Bytes())
+ if err := w.Close(); err != nil {
+ t.Fatal(err)
+ }
+ at := cacheDir(t, cache, dep)
+ if err := os.WriteFile(filepath.Join(at, "v1.0.0.zip"), buf.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(at, "v1.0.0.mod"), gomod, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ pin := Pin{Mod: hashGoMod(t, gomod), Zip: "h1:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="}
+ base := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(sumFor(dep, pin)))}}
+ dir := stageDir(t)
+ if s, err := stage(t, bundleFor(t, cache, base, base), base, dir, Limits{}); !errors.Is(err, ErrUnsafePath) {
+ t.Errorf("Stage of a zip whose entry outgrows its declared size = %+v, %v; want ErrUnsafePath", s, err)
+ }
+ if left := leftBehind(t, dir); len(left) != 0 {
+ t.Errorf("a refused Stage left %v", left)
+ }
+}
+
+// TestZipHashCancellable: hashing a zip stops when its context ends.
+func TestZipHashCancellable(t *testing.T) {
+ cache := t.TempDir()
+ fixtureModule(t, cache, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n"})
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if h, err := zipHash(ctx, filepath.Join(cacheDir(t, cache, dep), "v1.0.0.zip")); !errors.Is(err, context.Canceled) {
+ t.Fatalf("zipHash with an ended context = %q, %v; want context.Canceled", h, err)
+ }
+}
+
+func TestVendorMarkerDoesNotHideConflict(t *testing.T) {
+ real := t.TempDir()
+ realPin := fixtureModule(t, real, dep, map[string]string{"go.mod": "module example.com/dep\n", "dep.go": "package dep\n"})
+ evilPin := realPin
+ evilPin.Zip = "h1:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="
+ 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)))},
+ "vendor/modules.txt": {Data: []byte("# example.com/dep v1.0.0\n")},
+ }
+ conflicts, err := Conflicts(base, cand)
+ if err != nil || !slices.Equal(conflicts, []Module{dep}) {
+ t.Fatalf("Conflicts with a vendor marker added = %v, %v; want [%v]", conflicts, err, dep)
+ }
+ // A vendored base still pins.
+ base["vendor/modules.txt"] = &fstest.MapFile{Data: []byte("# example.com/dep v1.0.0\n")}
+ if pins, err := Pins(base); err != nil || pins[dep] != realPin {
+ t.Fatalf("Pins of a vendored base = %v, %v; want %v", pins, err, realPin)
+ }
+}
+
+func TestModuleDiscoveryErrors(t *testing.T) {
+ t.Run("the 65th module", func(t *testing.T) {
+ tree := fstest.MapFS{}
+ for i := range 64 {
+ tree[fmt.Sprintf("m%02d/go.mod", i)] = &fstest.MapFile{Data: []byte(goModFor(fmt.Sprintf("example.com/m%02d", i), dep))}
+ }
+ if want, err := ModulesFor(tree, tree); err != nil || !slices.Equal(want, []Module{dep}) {
+ t.Fatalf("64 modules: %v, %v", want, err)
+ }
+ tree["m64/go.mod"] = &fstest.MapFile{Data: []byte(goModFor("example.com/m64", gone))}
+ if want, err := ModulesFor(tree, fstest.MapFS{}); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("65 modules: %v, %v; want ErrTooLarge, not a partial list", want, err)
+ }
+ })
+ t.Run("a malformed go.mod", func(t *testing.T) {
+ good := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}}
+ bad := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "sub/go.mod": {Data: []byte("module example.com/app/sub\n\nrequire (\n")}}
+ if want, err := ModulesFor(good, bad); !errors.Is(err, ErrMalformed) {
+ t.Fatalf("ModulesFor with a malformed go.mod = %v, %v; want ErrMalformed", want, err)
+ }
+ })
+ t.Run("a malformed go.sum", func(t *testing.T) {
+ good := fstest.MapFS{"go.sum": {Data: []byte("example.com/dep v1.0.0 h1:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=\n")}}
+ bad := fstest.MapFS{"go.sum": {Data: []byte("example.com/dep v1.0.0\n")}}
+ if pins, err := Pins(bad); !errors.Is(err, ErrMalformed) {
+ t.Fatalf("Pins of a malformed go.sum = %v, %v; want ErrMalformed", pins, err)
+ }
+ if c, err := Conflicts(good, bad); !errors.Is(err, ErrMalformed) {
+ t.Fatalf("Conflicts with a malformed candidate go.sum = %v, %v; want ErrMalformed", c, err)
+ }
+ })
+ t.Run("the checks' module directories", func(t *testing.T) {
+ root := t.TempDir()
+ mods := map[string]Module{".": dep, "sub": upper, "vend": {"example.com/v", "v1.0.0"}, "testdata/x": {"example.com/t", "v1.0.0"}, ".hidden": {"example.com/h", "v1.0.0"}, "_skip": {"example.com/s", "v1.0.0"}}
+ for dir, req := range mods {
+ if err := os.MkdirAll(filepath.Join(root, dir), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(root, dir, "go.mod"), []byte(goModFor("example.com/"+strings.ReplaceAll(dir, "/", "-"), req)), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.MkdirAll(filepath.Join(root, "vend/vendor"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(root, "vend/vendor/modules.txt"), nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if got := checks.GoModuleDirs(root); !slices.Equal(got, []string{".", "sub"}) {
+ t.Fatalf("checks.GoModuleDirs = %v", got)
+ }
+ if want, err := ModulesFor(os.DirFS(root), fstest.MapFS{}); err != nil || !slices.Equal(want, []Module{upper, dep}) {
+ t.Fatalf("ModulesFor = %v, %v; want the requirements of the checks' module directories [%v %v]", want, err, upper, dep)
+ }
+ })
+}
+
+// TestGoModOnlyPinReported: a module the base pins only by its go.mod has
+// its .mod staged and no source, so it is reported missing, whether the
+// bundle carries a zip for it or not.
+func TestGoModOnlyPinReported(t *testing.T) {
+ for _, withZip := range []bool{true, false} {
+ t.Run(fmt.Sprintf("zip in the bundle %v", withZip), 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 !withZip {
+ if err := os.Remove(filepath.Join(cacheDir(t, cache, dep), "v1.0.0.zip")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ base := fstest.MapFS{"go.mod": {Data: []byte(goModFor("example.com/app", dep))}, "go.sum": {Data: []byte(sumText(dep.Path + " " + dep.Version + "/go.mod " + pin.Mod))}}
+ s, err := stage(t, bundleFor(t, cache, base, base), base, stageDir(t), Limits{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(s.Missing, []Module{dep}) {
+ t.Errorf("missing %v, want [%v]: its source is not staged", s.Missing, dep)
+ }
+ if _, err := os.Stat(filepath.Join(s.Dir, "cache/download/example.com/dep/@v/v1.0.0.mod")); err != nil {
+ t.Errorf("its .mod was not staged: %v", err)
+ }
+ for _, name := range []string{"example.com/dep@v1.0.0", "cache/download/example.com/dep/@v/v1.0.0.zip", "cache/download/example.com/dep/@v/v1.0.0.ziphash"} {
+ if _, err := os.Lstat(filepath.Join(s.Dir, name)); !errors.Is(err, fs.ErrNotExist) {
+ t.Errorf("%s staged (%v), want absent", name, err)
+ }
+ }
+ })
+ }
+}
+
+func flateWriter(w io.Writer) (io.WriteCloser, error) {
+ return flate.NewWriter(w, flate.BestCompression)
+}
+
+func crc(b []byte) uint32 { return crc32.ChecksumIEEE(b) }
+
+// TestZipDirectoryEntries: a module zip may name directories (x/mod/zip
+// accepts them); staging extracts it as the go command does.
+func TestZipDirectoryEntries(t *testing.T) {
+ cache := t.TempDir()
+ prefix := "example.com/dep@v1.0.0/"
+ gomod := []byte("module example.com/dep\n")
+ z := craftedZip(t, []zipEntry{{prefix + "go.mod", string(gomod), 0o644}, {prefix + "sub/", "", fs.ModeDir | 0o755}, {prefix + "sub/s.go", "package sub\n", 0o644}})
+ 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)))}}
+ s, err := stage(t, bundleFor(t, cache, base, base), base, stageDir(t), Limits{})
+ if err != nil {
+ t.Fatalf("Stage of a zip with a directory entry: %v", err)
+ }
+ if got, err := os.ReadFile(filepath.Join(s.Dir, "example.com/dep@v1.0.0/sub/s.go")); err != nil || string(got) != "package sub\n" {
+ t.Fatalf("sub/s.go = %q, %v", got, err)
+ }
+}
diff --git a/internal/runner/depsbundle/gosum.go b/internal/runner/depsbundle/gosum.go
index 76294d8a..186d354e 100644
--- a/internal/runner/depsbundle/gosum.go
+++ b/internal/runner/depsbundle/gosum.go
@@ -10,6 +10,7 @@ package depsbundle
import (
"bufio"
"bytes"
+ "errors"
"fmt"
"io"
"io/fs"
@@ -17,7 +18,6 @@ import (
"slices"
"strings"
- "amadan.net/oficina/equipo/internal/runner/checks"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
)
@@ -39,15 +39,29 @@ const (
maxModFile = 16 << 20
)
+// maxModules bounds the module directories ModulesFor reads (the
+// checks' own walk stops at the same number); maxSumFiles bounds the
+// go.sum files Pins and Conflicts read. Past either is ErrTooLarge,
+// never a partial answer.
+const (
+ maxModules = 64
+ maxSumFiles = 256
+)
+
// 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.
+// versioned replacement) of every go.mod in either tree, in the module
+// directories checks.GoModuleDirs gives (vendored modules skipped). A
+// go.mod that does not parse is ErrMalformed and a walk error is
+// returned: a partial list would leave modules out of MODULES, where
+// staging could not report them missing.
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) {
+ dirs, err := moduleDirs(tree)
+ if err != nil {
+ return nil, err
+ }
+ for _, dir := range dirs {
name := path.Join(dir, "go.mod")
data, err := readBounded(tree, name, maxModFile)
if err != nil {
@@ -55,20 +69,31 @@ func ModulesFor(base, candidate fs.FS) (want []Module, err error) {
}
f, err := modfile.Parse(name, data, nil)
if err != nil {
- continue
+ return nil, fmt.Errorf("%w: %v", ErrMalformed, err)
}
- add := func(p, v string) {
+ add := func(p, v string) error {
m := Module{p, v}
- if v != "" && module.Check(p, v) == nil && !seen[m] {
+ if module.Check(p, v) != nil {
+ return fmt.Errorf("%w: %s: %s", ErrMalformed, name, m)
+ }
+ if !seen[m] {
seen[m] = true
want = append(want, m)
}
+ return nil
}
for _, r := range f.Require {
- add(r.Mod.Path, r.Mod.Version)
+ if err := add(r.Mod.Path, r.Mod.Version); err != nil {
+ return nil, err
+ }
}
for _, r := range f.Replace {
- add(r.New.Path, r.New.Version)
+ if r.New.Version == "" {
+ continue // a directory, not a module
+ }
+ if err := add(r.New.Path, r.New.Version); err != nil {
+ return nil, err
+ }
}
}
}
@@ -76,9 +101,71 @@ func ModulesFor(base, candidate fs.FS) (want []Module, err error) {
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.
+// moduleDirs is checks.GoModuleDirs over an fs.FS with its errors kept:
+// the directories ("." first) holding a go.mod whose dependencies come
+// from the module cache, not vendored, and not under vendor or testdata
+// or a directory Go ignores (a leading dot or underscore). Symlinks are
+// not followed. More than maxModules is ErrTooLarge.
+func moduleDirs(tree fs.FS) ([]string, error) {
+ var out []string
+ err := fs.WalkDir(tree, ".", func(name string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ if base := d.Name(); name != "." && (base == "vendor" || base == "testdata" || strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_")) {
+ return fs.SkipDir
+ }
+ return nil
+ }
+ if d.Name() != "go.mod" || !d.Type().IsRegular() {
+ return nil
+ }
+ info, err := fs.Lstat(tree, path.Join(path.Dir(name), "vendor/modules.txt"))
+ switch {
+ case err == nil && info.Mode().IsRegular():
+ return nil // vendored
+ case err != nil && !errors.Is(err, fs.ErrNotExist):
+ return err
+ }
+ if len(out) == maxModules {
+ return fmt.Errorf("depsbundle: more than %d Go modules: %w", maxModules, ErrTooLarge)
+ }
+ out = append(out, path.Dir(name))
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ slices.Sort(out)
+ return out, nil
+}
+
+// sumFiles is every regular go.sum in tree, at any depth: vendoring and
+// Go's ignored directories do not hide one (a candidate adding a vendor
+// marker must not hide a changed pin). Symlinks are not followed. More
+// than maxSumFiles is ErrTooLarge.
+func sumFiles(tree fs.FS) ([]string, error) {
+ var out []string
+ err := fs.WalkDir(tree, ".", func(name string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() || d.Name() != "go.sum" || !d.Type().IsRegular() {
+ return nil
+ }
+ if len(out) == maxSumFiles {
+ return fmt.Errorf("depsbundle: more than %d go.sum files: %w", maxSumFiles, ErrTooLarge)
+ }
+ out = append(out, name)
+ return nil
+ })
+ return out, err
+}
+
+// Pins reads the h1: lines of every go.sum in the BASE tree (sumFiles).
+// Only the base is ever a source of pins. Two base lines that disagree
+// are ErrMalformed.
func Pins(base fs.FS) (map[Module]Pin, error) {
lines, err := sumLines(base)
if err != nil {
@@ -92,7 +179,7 @@ func Pins(base fs.FS) (map[Module]Pin, error) {
have = &p.Mod
}
if *have != "" && *have != l.hash {
- return nil, fmt.Errorf("depsbundle: the base's go.sum files disagree on %s", l.m)
+ return nil, fmt.Errorf("%w: the base's go.sum files disagree on %s", ErrMalformed, l.m)
}
*have = l.hash
pins[l.m] = p
@@ -138,36 +225,40 @@ type sumLine struct {
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).
+// sumLines are the h1: lines of every go.sum in tree (sumFiles). Lines
+// of other hash kinds are skipped, as the go command skips them; a line
+// that is not "path version hash" is ErrMalformed.
func sumLines(tree fs.FS) ([]sumLine, error) {
+ names, err := sumFiles(tree)
+ if err != nil {
+ return nil, err
+ }
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
- }
+ for _, name := range names {
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() {
+ for n := 1; sc.Scan(); n++ {
f := strings.Fields(sc.Text())
- if len(f) != 3 || !strings.HasPrefix(f[2], "h1:") {
+ if len(f) == 0 {
continue
}
- v, mod := strings.CutSuffix(f[1], "/go.mod")
- if module.Check(f[0], v) != nil {
- continue
+ v, mod := "", false
+ if len(f) == 3 {
+ v, mod = strings.CutSuffix(f[1], "/go.mod")
+ }
+ if len(f) != 3 || module.Check(f[0], v) != nil {
+ return nil, fmt.Errorf("%w: %s:%d", ErrMalformed, name, n)
+ }
+ if strings.HasPrefix(f[2], "h1:") {
+ out = append(out, sumLine{Module{f[0], v}, mod, f[2]})
}
- 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 nil, fmt.Errorf("%w: %s: %v", ErrMalformed, name, err)
}
}
return out, nil
diff --git a/internal/runner/depsbundle/stage.go b/internal/runner/depsbundle/stage.go
index 3dd70d5c..7ad579f6 100644
--- a/internal/runner/depsbundle/stage.go
+++ b/internal/runner/depsbundle/stage.go
@@ -33,6 +33,8 @@ var (
// 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")
+ // ErrMalformed: a go.mod or go.sum in a tree that does not parse.
+ ErrMalformed = errors.New("depsbundle: malformed go.mod or go.sum")
)
// Limits bound a staging: Bundle bytes read, Expanded bytes written and
@@ -74,8 +76,9 @@ func (s Staged) Remove() error { return removeTree(s.Dir) }
// 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
+// dir. A module the base does not pin is never staged. A module without
+// staged source (its base pin has no tree line, or the bundle has no
+// zip for it) has only its .mod staged and is reported missing. 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{}}
@@ -100,11 +103,11 @@ func Stage(ctx context.Context, bundle io.Reader, pins map[Module]Pin, dir strin
if err := ctx.Err(); err != nil {
return Staged{}, err
}
- staged, err := st.stage(m, pins)
+ complete, err := st.stage(ctx, m, pins)
if err != nil {
return Staged{}, fmt.Errorf("%s: %w", m, err)
}
- if !staged {
+ if !complete {
missing = append(missing, m)
}
}
@@ -281,20 +284,33 @@ func parseName(name string) (Module, string, bool) {
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) {
+// stage verifies and writes one wanted module and reports whether it is
+// complete. Nothing is written when the base does not pin it or the
+// bundle lacks its .mod. Its verified .mod is written but it is not
+// complete when it has no source to stage: the base pins only its
+// go.mod, or the bundle lacks its zip.
+func (st *stager) stage(ctx context.Context, 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 == "") {
+ if !pinned || pin.Mod == "" || p == nil || p.mod == nil {
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 {
+ source := pin.Zip != "" && p.zip != ""
+ if source {
+ if err := st.preflight(m, p.zip); err != nil {
+ return false, err
+ }
+ h, err := zipHash(ctx, p.zip)
+ if cerr := ctx.Err(); cerr != nil {
+ return false, cerr
+ }
+ if err != nil {
+ return false, fmt.Errorf("zip: %w: %v", ErrUnsafePath, err)
+ }
+ if h != pin.Zip {
return false, fmt.Errorf("zip: %w", ErrHashMismatch)
}
}
@@ -314,11 +330,11 @@ func (st *stager) stage(m Module, pins map[Module]Pin) (bool, error) {
return false, err
}
}
- if pin.Zip == "" {
- return true, nil
+ if !source {
+ return false, nil
}
- if err := st.extract(m, p.zip, filepath.Join(st.fresh, filepath.FromSlash(esc)+"@"+ver)); err != nil {
- return false, err
+ if err := modzip.Unzip(filepath.Join(st.fresh, filepath.FromSlash(esc)+"@"+ver), module.Version{Path: m.Path, Version: m.Version}, p.zip); err != nil {
+ return false, fmt.Errorf("%w: %v", ErrUnsafePath, err)
}
if err := os.Rename(p.zip, base+".zip"); err != nil {
return false, err
@@ -326,40 +342,79 @@ func (st *stager) stage(m Module, pins map[Module]Pin) (bool, error) {
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 {
+// preflight reads only the zip's directory, before any body is read: its
+// structure as x/mod/zip.CheckZip judges it (every entry a clean path
+// inside the module, no collisions, the go command's size caps), plain
+// files only (CheckZip and Unzip ignore a symlink's mode), and its
+// declared sizes and file count within what is left of the limits. The
+// actual bytes are bounded by those declared sizes: archive/zip fails a
+// body that outgrows its declared size (hashing), as Unzip does
+// (extraction).
+func (st *stager) preflight(m Module, zipPath string) error {
+ if _, err := modzip.CheckZip(module.Version{Path: m.Path, Version: m.Version}, zipPath); err != nil {
+ return fmt.Errorf("%w: %v", ErrUnsafePath, err)
+ }
z, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("zip: %w", ErrUnsafePath)
}
+ defer z.Close()
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
+ return st.write(size, files)
+}
+
+// zipHash is dirhash.HashZip (the go.sum tree hash) with every body read
+// through ctx, so an ended context stops it.
+func zipHash(ctx context.Context, name string) (string, error) {
+ z, err := zip.OpenReader(name)
+ if 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)
+ defer z.Close()
+ var files []string
+ byName := map[string]*zip.File{}
+ for _, f := range z.File {
+ files = append(files, f.Name)
+ byName[f.Name] = f
}
- return nil
+ return dirhash.Hash1(files, func(name string) (io.ReadCloser, error) {
+ f := byName[name]
+ if f == nil {
+ return nil, fmt.Errorf("file %q not found in zip", name)
+ }
+ r, err := f.Open()
+ if err != nil {
+ return nil, err
+ }
+ return ctxReader{ctx, r}, nil
+ })
+}
+
+type ctxReader struct {
+ ctx context.Context
+ io.ReadCloser
+}
+
+func (r ctxReader) Read(p []byte) (int, error) {
+ if err := r.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return r.ReadCloser.Read(p)
}
func (st *stager) writeFile(name string, data []byte) error {