From e73f3c8e1f256e378be19181c6b259c204c57e5c Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:54:57 +1100 Subject: [PATCH 1/2] Cap forge archive download and extracted size --- internal/deploy/forge.go | 30 ++++++++++++++++++++++++++---- internal/deploy/forge_test.go | 25 +++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/internal/deploy/forge.go b/internal/deploy/forge.go index 23696e8..e89172a 100644 --- a/internal/deploy/forge.go +++ b/internal/deploy/forge.go @@ -14,7 +14,11 @@ import ( "time" ) -const defaultForge = "https://forgeapi.puppet.com" +const ( + defaultForge = "https://forgeapi.puppet.com" + maxForgeDownload = 100 << 20 + maxForgeExtracted = 512 << 20 +) var httpClient = &http.Client{Timeout: 5 * time.Minute} @@ -79,24 +83,42 @@ func forgeInstall(ctx context.Context, base, release, dir string) error { if err != nil { return err } - if err := extract(body, tmp); err != nil { + if err := extract(&capReader{r: body, n: maxForgeDownload}, tmp, maxForgeExtracted); err != nil { _ = os.RemoveAll(tmp) return fmt.Errorf("%s: %w", release, err) } return os.Rename(tmp, dir) } -func extract(r io.Reader, dst string) error { +// capReader fails once more than n bytes are read, so an oversized stream errors instead of being truncated silently. +type capReader struct { + r io.Reader + n int64 +} + +func (c *capReader) Read(p []byte) (int, error) { + if int64(len(p)) > c.n+1 { + p = p[:c.n+1] + } + n, err := c.r.Read(p) + if c.n -= int64(n); c.n < 0 { + return 0, fmt.Errorf("archive exceeds size cap") + } + return n, err +} + +func extract(r io.Reader, dst string, limit int64) error { gz, err := gzip.NewReader(r) if err != nil { return err } + cr := &capReader{r: gz, n: limit} root, err := os.OpenRoot(dst) if err != nil { return err } defer func() { _ = root.Close() }() - tr := tar.NewReader(gz) + tr := tar.NewReader(cr) for { hdr, err := tr.Next() if err == io.EOF { diff --git a/internal/deploy/forge_test.go b/internal/deploy/forge_test.go index 292ebd7..6598222 100644 --- a/internal/deploy/forge_test.go +++ b/internal/deploy/forge_test.go @@ -4,8 +4,10 @@ import ( "archive/tar" "bytes" "compress/gzip" + "io" "os" "path/filepath" + "strings" "testing" ) @@ -58,7 +60,7 @@ func TestExtractStripsTopDir(t *testing.T) { entry{name: "./puppetlabs-stdlib-9.7.0/lib/x.rb", body: "x", mode: 0o644}, entry{name: "puppetlabs-stdlib-9.7.0/bin/run", body: "#!", mode: 0o700}, entry{name: "puppetlabs-stdlib-9.7.0/link", body: "/etc/passwd", typ: tar.TypeSymlink}, - )), dst) + )), dst, maxForgeExtracted) if err != nil { t.Fatal(err) } @@ -75,7 +77,7 @@ func TestExtractStripsTopDir(t *testing.T) { func TestExtractRejectsTraversal(t *testing.T) { dst := t.TempDir() - err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst) + err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst, maxForgeExtracted) if err == nil { t.Fatal("expected traversal error") } @@ -95,3 +97,22 @@ func TestForgeURL(t *testing.T) { } } } + +func TestExtractRejectsOversize(t *testing.T) { + big := entry{name: "m/a", body: strings.Repeat("x", 4096), mode: 0o644} + if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1024); err == nil { + t.Fatal("want extracted size cap error") + } + if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1<<20); err != nil { + t.Fatal(err) + } +} + +func TestCapReaderErrorsAtCap(t *testing.T) { + if _, err := io.ReadAll(&capReader{r: strings.NewReader("abcdef"), n: 4}); err == nil { + t.Fatal("want cap error") + } + if b, err := io.ReadAll(&capReader{r: strings.NewReader("abc"), n: 4}); err != nil || string(b) != "abc" { + t.Fatalf("under cap: %q %v", b, err) + } +} From 66580c9b37a0fc2d42b7a7829f8601776101cf01 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:54:57 +1100 Subject: [PATCH 2/2] Keep GC off targeted deploys, always drop live marks, let exact branches win env names --- internal/deploy/deploy.go | 111 ++++++++++++++++++------- internal/deploy/deploy_test.go | 146 +++++++++++++++++++++++++++++++++ 2 files changed, 226 insertions(+), 31 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 0c1868f..0fdbb21 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -9,10 +9,12 @@ import ( "errors" "fmt" "log" + "maps" "os" "path/filepath" "regexp" "runtime/debug" + "slices" "sort" "strings" "sync" @@ -216,9 +218,7 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro errs = append(errs, fmt.Errorf("environment %s not found", e)) } } - if err := d.GC(ctx); err != nil { - errs = append(errs, err) - } + errs = append(errs, d.gc(ctx, len(only) == 0)) return errors.Join(errs...) } @@ -234,7 +234,8 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR names = append(names, b) } sort.Strings(names) - envs := map[string]envRef{} + claims := map[string][]string{} + exact := map[string]string{} var errs []error for _, b := range names { if s.Ignored(b) { @@ -245,14 +246,31 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR errs = append(errs, err) continue } - if corrected && s.InvalidBranches == "correct_and_warn" { - log.Printf("warning: branch %s deployed as environment %s", b, name) + if !corrected { + exact[name] = b } - if _, dup := envs[name]; dup { - errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + claims[name] = append(claims[name], b) + } + envs := map[string]envRef{} + for _, name := range slices.Sorted(maps.Keys(claims)) { + bs := claims[name] + win, isExact := exact[name] + if !isExact && len(bs) == 1 { + win = bs[0] + } + if win == "" { + errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name)) continue } - envs[name] = envRef{b, all[b]} + for _, b := range bs { + if b != win { + errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + } + } + if !isExact && s.InvalidBranches == "correct_and_warn" { + log.Printf("warning: branch %s deployed as environment %s", win, name) + } + envs[name] = envRef{win, all[win]} } return envs, errs } @@ -697,26 +715,46 @@ func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(stri } } -func (d *Deployer) GC(ctx context.Context) error { - g := &gcRun{d: d, ctx: ctx, marks: map[string]time.Time{}, seen: map[string]bool{}} - statePath := d.path(gcStateFile) - if b, err := os.ReadFile(statePath); err == nil { - if err := json.Unmarshal(b, &g.marks); err != nil { - return fmt.Errorf("gc: %s: %w", statePath, err) +func (d *Deployer) GC(ctx context.Context) error { return d.gc(ctx, true) } + +// gc drops the mark of everything live this run; only a sweep may add marks or delete, and only where every live set it needs was computed. +func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) { + g := &gcRun{d: d, ctx: ctx, marks: d.loadMarks(), seen: map[string]bool{}} + defer func() { + for p := range g.marks { + if !g.seen[p] { + delete(g.marks, p) + } } - } else if !os.IsNotExist(err) { - return err - } + err = errors.Join(append(g.errs, d.saveMarks(g.marks))...) + }() liveEnv := map[string]bool{} + var ok []*Source for _, s := range d.Sources() { live, err := d.Live(s) if err != nil { - return fmt.Errorf("gc: %w", err) + g.errs = append(g.errs, fmt.Errorf("gc: %w", err)) + continue } + ok = append(ok, s) for _, t := range live { liveEnv[t] = true } + } + if !sweep { + liveMod, err := d.moduleRefs(liveEnv) + if err != nil || len(g.errs) > 0 { + g.errs = append(g.errs, err) + return nil + } + for p := range g.marks { + g.seen[p] = !liveEnv[p] && !liveMod[p] + } + return nil + } + + for _, s := range ok { mirror := d.srcMirror(s) g.sweep(mirror, d.srcWorktrees(s), liveEnv, func(p string) error { if err := os.Remove(d.doneFile(p)); err != nil && !os.IsNotExist(err) { @@ -731,7 +769,9 @@ func (d *Deployer) GC(ctx context.Context) error { } } } - + if len(ok) < len(d.cfg.Sources) { + return nil + } liveMod, err := d.moduleRefs(liveEnv) if err != nil { g.errs = append(g.errs, err) @@ -743,20 +783,29 @@ func (d *Deployer) GC(ctx context.Context) error { } g.sweep("", d.path("forge"), liveMod, func(p string) error { return d.discard(ctx, "", p) }) } + return nil +} - for p := range g.marks { - if !g.seen[p] { - delete(g.marks, p) - } - } - b, err := json.MarshalIndent(g.marks, "", " ") +// loadMarks treats an unreadable state file as empty, which only delays deletion. +func (d *Deployer) loadMarks() map[string]time.Time { + marks := map[string]time.Time{} + b, err := os.ReadFile(d.path(gcStateFile)) if err == nil { - tmp := statePath + ".tmp" - if err = os.WriteFile(tmp, b, 0o644); err == nil { - err = os.Rename(tmp, statePath) - } + err = json.Unmarshal(b, &marks) } - return errors.Join(append(g.errs, err)...) + if err != nil && !os.IsNotExist(err) { + log.Printf("gc: discarding unreadable %s: %v", gcStateFile, err) + marks = map[string]time.Time{} + } + return marks +} + +func (d *Deployer) saveMarks(marks map[string]time.Time) error { + b, err := json.MarshalIndent(marks, "", " ") + if err != nil { + return err + } + return writeAtomic(d.path(gcStateFile), b) } // moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir. diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 62474c7..c9acd44 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -910,3 +910,149 @@ func TestDeployMarkerNameIsBranch(t *testing.T) { t.Fatalf("marker name %q, want branch feat/x", m.Name) } } + +func TestTargetedDeploySkipsGC(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + old := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Hour) + if err := f.deploy(false, "main"); err != nil { + t.Fatal(err) + } + if !exists(old) { + t.Fatalf("targeted deploy ran GC and removed %s", old) + } +} + +func TestTargetedDeployDropsMarkOfReusedWorktree(t *testing.T) { + f := newFixture(t) + sha1 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + w1 := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Hour) + gitT(t, f.control, "reset", "-q", "--hard", sha1) + if err := f.deploy(false, "main"); err != nil || f.env("main") != w1 { + t.Fatalf("targeted deploy did not reuse %s: %v", w1, err) + } + commit(t, f.control, map[string]string{"manifests/site.pp": "node y {}\n"}) + if err := f.deploy(false, "main"); err != nil { + t.Fatal(err) + } + f.mustDeploy(false) + if !exists(w1) { + t.Fatal("worktree live during a targeted deploy kept its earlier mark and was deleted without grace") + } +} + +func TestGCLiveErrorDropsMarkOfLiveWorktree(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + u := &Source{Name: "u", Basedir: filepath.Join(root, "uenvs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s, "u": u}} + clock := time.Unix(1_700_000_000, 0) + gc := func() error { + d := New(cfg, 1, 10*time.Minute) + d.now = func() time.Time { return clock } + return d.GC(context.Background()) + } + d := New(cfg, 1, 0) + old, cur := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur") + mkdirs(t, old, cur, s.Basedir, filepath.Dir(d.doneFile(old))) + for _, p := range []string{old, cur} { + if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { + t.Fatal(err) + } + } + link := filepath.Join(s.Basedir, "develop") + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + if err := gc(); err != nil { + t.Fatal(err) + } + clock = clock.Add(time.Hour) + if err := Swap(old, link); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(u.Basedir, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := gc(); err == nil { + t.Fatal("want Live error") + } + if err := os.Remove(u.Basedir); err != nil { + t.Fatal(err) + } + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + _ = gc() + if !exists(old) { + t.Fatal("worktree unreferenced this run was deleted in the same run via a mark kept by GC's early return") + } +} + +func TestGCCorruptStateTreatedAsEmpty(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}} + d := New(cfg, 1, 10*time.Minute) + old := filepath.Join(d.srcWorktrees(s), "old") + mkdirs(t, old, s.Basedir) + state := d.path(gcStateFile) + if err := os.WriteFile(state, []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + if err := d.GC(context.Background()); err != nil { + t.Fatalf("corrupt state wedged GC: %v", err) + } + b, err := os.ReadFile(state) + if err != nil { + t.Fatal(err) + } + var marks map[string]time.Time + if err := json.Unmarshal(b, &marks); err != nil { + t.Fatalf("state not rewritten: %v", err) + } + if _, ok := marks[old]; !ok || !exists(old) { + t.Fatal("unreferenced worktree must be freshly marked, not deleted") + } +} + +func TestExactBranchWinsEnvName(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feature_x") + legit := commit(t, f.control, map[string]string{"manifests/site.pp": "node legit {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feature-x") + commit(t, f.control, map[string]string{"manifests/site.pp": "node evil {}\n"}) + err := f.deploy(false) + if got := f.env("feature_x"); !strings.HasPrefix(filepath.Base(got), legit+"-") { + t.Fatalf("env feature_x -> %s, want branch feature_x (%s); a pushed feature-x took it over", filepath.Base(got), legit) + } + if err == nil || !strings.Contains(err.Error(), "feature-x") { + t.Fatalf("want collision error naming feature-x, got %v", err) + } +} + +func TestCorrectedBranchCollisionSkipsAll(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "feature-x") + gitT(t, f.control, "branch", "feature.x") + err := f.deploy(false) + if exists(filepath.Join(f.basedir, "feature_x")) { + t.Fatal("colliding corrected branches must not deploy feature_x") + } + if err == nil || !strings.Contains(err.Error(), "feature-x") || !strings.Contains(err.Error(), "feature.x") { + t.Fatalf("want collision error naming both branches, got %v", err) + } + if f.env("main") == "" { + t.Fatal("collision must not block other envs") + } +}