From af20148ea41e1d636211cee62556d096796fc2b1 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 18:07:09 +1100 Subject: [PATCH] Confine worktree writes, time out git calls, keep removed sources' modules - write the deploy marker and module links through os.Root - extract forge tarballs through os.Root - bound each git call with w10k.git_timeout (default 10m) and http low-speed abort - count module refs from every worktree and basedir link, not only configured sources --- internal/deploy/config.go | 6 +- internal/deploy/config_test.go | 23 +++-- internal/deploy/deploy.go | 173 ++++++++++++++++++++------------- internal/deploy/deploy_test.go | 78 +++++++++++++++ internal/deploy/forge.go | 17 ++-- internal/deploy/forge_test.go | 5 +- internal/deploy/git.go | 11 ++- 7 files changed, 226 insertions(+), 87 deletions(-) diff --git a/internal/deploy/config.go b/internal/deploy/config.go index 20e9636..0943c71 100644 --- a/internal/deploy/config.go +++ b/internal/deploy/config.go @@ -15,7 +15,8 @@ type Config struct { Cachedir string `yaml:"cachedir"` Sources map[string]*Source `yaml:"sources"` W10k struct { - GCGrace *time.Duration `yaml:"gc_grace"` + GCGrace *time.Duration `yaml:"gc_grace"` + GitTimeout *time.Duration `yaml:"git_timeout"` } `yaml:"w10k"` } @@ -53,6 +54,9 @@ func ParseConfig(b []byte) (*Config, error) { if c.W10k.GCGrace != nil && *c.W10k.GCGrace < 0 { return nil, fmt.Errorf("w10k.gc_grace must not be negative") } + if c.W10k.GitTimeout != nil && *c.W10k.GitTimeout <= 0 { + return nil, fmt.Errorf("w10k.git_timeout must be positive") + } if len(c.Sources) == 0 { return nil, fmt.Errorf("no sources defined") } diff --git a/internal/deploy/config_test.go b/internal/deploy/config_test.go index 20ebe34..dc52d9c 100644 --- a/internal/deploy/config_test.go +++ b/internal/deploy/config_test.go @@ -1,6 +1,9 @@ package deploy -import "testing" +import ( + "testing" + "time" +) func TestParseConfigSymbolKeys(t *testing.T) { c, err := ParseConfig([]byte(` @@ -25,6 +28,8 @@ func TestParseConfigSymbolKeys(t *testing.T) { func TestParseConfigOptions(t *testing.T) { c, err := ParseConfig([]byte(` cachedir: /c +w10k: + git_timeout: 90s sources: a: remote: r @@ -42,6 +47,9 @@ sources: t.Fatal(err) } a, b := c.Sources["a"], c.Sources["b"] + if c.W10k.GitTimeout == nil || *c.W10k.GitTimeout != 90*time.Second { + t.Fatalf("git_timeout: %v", c.W10k.GitTimeout) + } if a.Prefix != "a" || a.InvalidBranches != "error" || len(a.IgnoreBranchPrefixes) != 2 { t.Fatalf("a: %+v", a) } @@ -52,12 +60,13 @@ sources: func TestParseConfigErrors(t *testing.T) { for name, in := range map[string]string{ - "no cachedir": "sources: {a: {remote: r, basedir: /b}}", - "no sources": "cachedir: /c", - "no remote": "cachedir: /c\nsources: {a: {basedir: /b}}", - "bad prefix": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, prefix: [x]}}", - "bad invalid": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, invalid_branches: nope}}", - "bad source name": "cachedir: /c\nsources: {a-b: {remote: r, basedir: /b}}", + "no cachedir": "sources: {a: {remote: r, basedir: /b}}", + "no sources": "cachedir: /c", + "zero git_timeout": "cachedir: /c\nw10k: {git_timeout: 0s}\nsources: {a: {remote: r, basedir: /b}}", + "no remote": "cachedir: /c\nsources: {a: {basedir: /b}}", + "bad prefix": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, prefix: [x]}}", + "bad invalid": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, invalid_branches: nope}}", + "bad source name": "cachedir: /c\nsources: {a-b: {remote: r, basedir: /b}}", } { if _, err := ParseConfig([]byte(in)); err == nil { t.Errorf("%s: expected error", name) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 18abe54..95f9dae 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -31,13 +31,14 @@ var ( ) type Deployer struct { - runGit func(ctx context.Context, dir string, args ...string) (string, error) - cfg *Config - grace time.Duration - now func() time.Time - sem chan struct{} - mu sync.Mutex - flights map[string]*flight + runGit func(ctx context.Context, dir string, args ...string) (string, error) + cfg *Config + grace time.Duration + gitTimeout time.Duration + now func() time.Time + sem chan struct{} + mu sync.Mutex + flights map[string]*flight } type flight struct { @@ -68,7 +69,11 @@ func New(cfg *Config, jobs int, grace time.Duration) *Deployer { if jobs < 1 { jobs = 1 } - return &Deployer{runGit: runGit, cfg: cfg, grace: grace, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}} + gt := defaultGitTimeout + if cfg.W10k.GitTimeout != nil { + gt = *cfg.W10k.GitTimeout + } + return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}} } func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { @@ -237,7 +242,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string] return errors.Join(errs...) } -func (d *Deployer) owned(s *Source, link string) string { +func linkTarget(link string) string { t, err := os.Readlink(link) if err != nil { return "" @@ -245,11 +250,14 @@ func (d *Deployer) owned(s *Source, link string) string { if !filepath.IsAbs(t) { t = filepath.Join(filepath.Dir(link), t) } - t = filepath.Clean(t) - if filepath.Dir(t) != d.srcWorktrees(s) { - return "" + return filepath.Clean(t) +} + +func (d *Deployer) owned(s *Source, link string) string { + if t := linkTarget(link); filepath.Dir(t) == d.srcWorktrees(s) { + return t } - return t + return "" } func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) error { @@ -416,55 +424,31 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha); err != nil { return err } + root, err := os.OpenRoot(target) + if err != nil { + return err + } + defer func() { _ = root.Close() }() for _, mod := range mods { - if err := linkModule(target, mod.path, mod.dir); err != nil { + if err := linkModule(root, mod.path, mod.dir); err != nil { return err } } return nil } -// linkModule creates root/rel -> dir without following any symlink under root, so committed links cannot redirect it. -func linkModule(root, rel, dir string) error { +// linkModule creates rel -> dir inside root; os.Root refuses any committed symlink that leads outside. +func linkModule(root *os.Root, rel, dir string) error { if !filepath.IsLocal(rel) { return fmt.Errorf("module path %q escapes the environment", rel) } - parts := strings.Split(filepath.Clean(rel), string(filepath.Separator)) - p := root - for i, part := range parts { - p = filepath.Join(p, part) - fi, err := os.Lstat(p) - last := i == len(parts)-1 - switch { - case os.IsNotExist(err): - if !last { - if err := os.Mkdir(p, 0o755); err != nil { - return err - } - } - case err != nil: - return err - case fi.Mode()&os.ModeSymlink != 0: - return fmt.Errorf("module path %s: %s is a symlink", rel, filepath.Join(parts[:i+1]...)) - case !last && !fi.IsDir(): - return fmt.Errorf("module path %s: %s is not a directory", rel, filepath.Join(parts[:i+1]...)) - } + if err := root.MkdirAll(filepath.Dir(rel), 0o755); err != nil { + return fmt.Errorf("module path %s: %w", rel, err) } - realRoot, err := filepath.EvalSymlinks(root) - if err != nil { - return err + if err := root.RemoveAll(rel); err != nil { + return fmt.Errorf("module path %s: %w", rel, err) } - realParent, err := filepath.EvalSymlinks(filepath.Dir(p)) - if err != nil { - return err - } - if realParent != realRoot && !strings.HasPrefix(realParent, realRoot+string(filepath.Separator)) { - return fmt.Errorf("module path %s resolves outside the environment", rel) - } - if err := os.RemoveAll(p); err != nil { - return err - } - return os.Symlink(dir, p) + return root.Symlink(dir, rel) } // prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete. @@ -488,7 +472,7 @@ func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods [ return err } b = append(b, '\n') - if err := writeAtomic(filepath.Join(target, markerFile), b); err != nil { + if err := writeMarker(target, b); err != nil { return err } done := d.doneFile(target) @@ -498,6 +482,34 @@ func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods [ return writeAtomic(done, b) } +// writeMarker replaces whatever the branch committed at the marker paths without following it. +func writeMarker(dir string, b []byte) error { + root, err := os.OpenRoot(dir) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + tmp := markerFile + ".tmp" + if err := root.RemoveAll(tmp); err != nil { + return err + } + f, err := root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o644) + if err != nil { + return err + } + if _, err := f.Write(b); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + if err := root.RemoveAll(markerFile); err != nil { + return err + } + return root.Rename(tmp, markerFile) +} + func writeAtomic(p string, b []byte) error { tmp := p + ".tmp" if err := os.WriteFile(tmp, b, 0o644); err != nil { @@ -679,34 +691,55 @@ func (d *Deployer) GC(ctx context.Context) error { return errors.Join(append(g.errs, err)...) } -// moduleRefs returns every module dir referenced by an env worktree still on disk, live or awaiting GC. +// moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir. func (d *Deployer) moduleRefs(liveEnv map[string]bool) (map[string]bool, error) { - refs := map[string]bool{} + wts := map[string]bool{} + for p := range liveEnv { + wts[p] = true + } for _, s := range d.Sources() { - entries, err := os.ReadDir(d.srcWorktrees(s)) - if os.IsNotExist(err) { - continue + entries, err := os.ReadDir(s.Basedir) + if err != nil && !os.IsNotExist(err) { + return nil, err } + for _, e := range entries { + if t := linkTarget(filepath.Join(s.Basedir, e.Name())); filepath.Dir(filepath.Dir(t)) == d.path("worktrees") { + wts[t] = true + } + } + } + srcs, err := os.ReadDir(d.path("worktrees")) + if err != nil && !os.IsNotExist(err) { + return nil, err + } + for _, src := range srcs { + dir := d.path("worktrees", src.Name()) + entries, err := os.ReadDir(dir) if err != nil { return nil, err } for _, e := range entries { - p := filepath.Join(d.srcWorktrees(s), e.Name()) - b, err := os.ReadFile(d.doneFile(p)) - if os.IsNotExist(err) && !liveEnv[p] { - continue - } - var r deployResult - if err == nil { - err = json.Unmarshal(b, &r) - } - if err != nil { - return nil, fmt.Errorf("gc: module refs of %s: %w", p, err) - } - for _, m := range r.Modules { - refs[m] = true + if p := filepath.Join(dir, e.Name()); !wts[p] { + wts[p] = false } } } + refs := map[string]bool{} + for p, live := range wts { + b, err := os.ReadFile(d.doneFile(p)) + if os.IsNotExist(err) && !live { + continue + } + var r deployResult + if err == nil { + err = json.Unmarshal(b, &r) + } + if err != nil { + return nil, fmt.Errorf("gc: module refs of %s: %w", p, err) + } + for _, m := range r.Modules { + refs[m] = true + } + } return refs, nil } diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 3b15c13..37b488a 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net" "net/http" "net/http/httptest" "os" @@ -594,3 +595,80 @@ func TestJobsBoundGitProcesses(t *testing.T) { t.Fatalf("%d concurrent git processes with -j %d", peak, jobs) } } + +func TestCommittedMarkerTmpSymlinkWritesOutside(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + victim := filepath.Join(f.basedir, "main", "manifests", "site.pp") + + gitT(t, f.control, "checkout", "-q", "-b", "attacker") + if err := os.Symlink(victim, filepath.Join(f.control, markerFile+".tmp")); err != nil { + t.Fatal(err) + } + gitT(t, f.control, "add", "-f", "-A") + gitT(t, f.control, "commit", "-q", "-m", "link") + _ = f.deploy(false) + + if b, _ := os.ReadFile(victim); string(b) != "node default {}\n" { + t.Fatalf("branch overwrote a live env file via committed symlink:\n%s", b) + } +} + +func TestStalledGitRemoteFailsOnlyItsEnv(t *testing.T) { + f := newFixture(t) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + t.Cleanup(func() { _ = c.Close() }) + } + }() + timeout := 2 * time.Second + f.cfg.W10k.GitTimeout = &timeout + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "slow") + commit(t, f.control, map[string]string{"Puppetfile": "mod 'slow', :git => 'http://" + ln.Addr().String() + "/x.git'\n"}) + done := make(chan error, 1) + go func() { done <- f.deploy(false) }() + select { + case err := <-done: + if err == nil || !strings.Contains(err.Error(), "environment slow") { + t.Fatalf("stalled remote must fail its env, got %v", err) + } + case <-time.After(20 * time.Second): + t.Fatal("deploy still blocked on a stalled :git remote after 20s") + } + if f.env("main") == "" || f.env("slow") != "" { + t.Fatalf("main=%q slow=%q", f.env("main"), f.env("slow")) + } +} + +func TestGCKeepsModulesOfRemovedSource(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod)}) + f.mustDeploy(false) + site := filepath.Join(f.basedir, "main", "modules", "bind", "manifests", "init.pp") + if !exists(site) { + t.Fatal("module not deployed") + } + other := filepath.Join(f.root, "other") + newRepo(t, other) + commit(t, other, map[string]string{"manifests/site.pp": "node default {}\n"}) + cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n other:\n remote: %s\n basedir: %s\n", f.cfg.Cachedir, other, filepath.Join(f.root, "other-envs"))) + if err != nil { + t.Fatal(err) + } + f.cfg = cfg + f.settle() + if _, err := os.Stat(site); err != nil { + t.Fatalf("GC deleted a module still linked from a removed source's live env: %v", err) + } +} diff --git a/internal/deploy/forge.go b/internal/deploy/forge.go index 9e1d259..23696e8 100644 --- a/internal/deploy/forge.go +++ b/internal/deploy/forge.go @@ -91,6 +91,11 @@ func extract(r io.Reader, dst string) error { if err != nil { return err } + root, err := os.OpenRoot(dst) + if err != nil { + return err + } + defer func() { _ = root.Close() }() tr := tar.NewReader(gz) for { hdr, err := tr.Next() @@ -104,32 +109,32 @@ func extract(r io.Reader, dst string) error { if rel == "" { continue } + rel = filepath.Clean(rel) if !filepath.IsLocal(rel) { return fmt.Errorf("unsafe path %q in archive", hdr.Name) } - p := filepath.Join(dst, rel) switch hdr.Typeflag { case tar.TypeDir: - if err := os.MkdirAll(p, 0o755); err != nil { + if err := root.MkdirAll(rel, 0o755); err != nil { return err } case tar.TypeReg: - if err := writeFile(p, tr, hdr.Mode&0o111 != 0); err != nil { + if err := writeFile(root, rel, tr, hdr.Mode&0o111 != 0); err != nil { return err } } } } -func writeFile(p string, r io.Reader, exec bool) error { - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { +func writeFile(root *os.Root, p string, r io.Reader, exec bool) error { + if err := root.MkdirAll(filepath.Dir(p), 0o755); err != nil { return err } mode := os.FileMode(0o644) if exec { mode = 0o755 } - f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) + f, err := root.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) if err != nil { return err } diff --git a/internal/deploy/forge_test.go b/internal/deploy/forge_test.go index cc58208..292ebd7 100644 --- a/internal/deploy/forge_test.go +++ b/internal/deploy/forge_test.go @@ -53,6 +53,7 @@ func TestExtractStripsTopDir(t *testing.T) { dst := t.TempDir() err := extract(bytes.NewReader(tarball(t, entry{name: "puppetlabs-stdlib-9.7.0/", typ: tar.TypeDir, mode: 0o755}, + entry{name: "puppetlabs-stdlib-9.7.0/spec/", typ: tar.TypeDir, mode: 0o755}, entry{name: "puppetlabs-stdlib-9.7.0/metadata.json", body: "{}", mode: 0o600}, 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}, @@ -61,9 +62,9 @@ func TestExtractStripsTopDir(t *testing.T) { if err != nil { t.Fatal(err) } - for p, perm := range map[string]os.FileMode{"metadata.json": 0o644, "lib/x.rb": 0o644, "bin/run": 0o755} { + for p, perm := range map[string]os.FileMode{"spec": 0o755 | os.ModeDir, "metadata.json": 0o644, "lib/x.rb": 0o644, "bin/run": 0o755} { fi, err := os.Stat(filepath.Join(dst, p)) - if err != nil || fi.Mode().Perm() != perm { + if err != nil || fi.Mode()&(os.ModePerm|os.ModeDir) != perm { t.Errorf("%s: %v %v", p, fi, err) } } diff --git a/internal/deploy/git.go b/internal/deploy/git.go index 992ec78..9d166b3 100644 --- a/internal/deploy/git.go +++ b/internal/deploy/git.go @@ -7,12 +7,19 @@ import ( "os" "os/exec" "strings" + "syscall" + "time" ) +const defaultGitTimeout = 10 * time.Minute + func runGit(ctx context.Context, dir string, args ...string) (string, error) { - cmd := exec.CommandContext(ctx, "git", args...) + cmd := exec.CommandContext(ctx, "git", append([]string{"-c", "http.lowSpeedLimit=1", "-c", "http.lowSpeedTime=60"}, args...)...) cmd.Dir = dir cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } + cmd.WaitDelay = 5 * time.Second var out, errb bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &errb if err := cmd.Run(); err != nil { @@ -24,6 +31,8 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) { // git holds a -j slot only for the subprocess itself, so callers never nest slots. func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) { err = d.limit(func() error { + ctx, cancel := context.WithTimeout(ctx, d.gitTimeout) + defer cancel() out, err = d.runGit(ctx, dir, args...) return err })