From 01fa51110bdca896107a304cd33332918c923372 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 17:52:07 +1100 Subject: [PATCH] Harden module installs against untrusted Puppetfiles - reject option-like :git URLs and refs; pass -- before git positionals - link modules without following symlinks; reject nested module paths - judge worktree completeness by an out-of-tree done file - key git mirrors by URL hash and forge releases by forge base - bound every git and forge call with the -j semaphore --- internal/deploy/deploy.go | 190 ++++++++++++++++++++--------- internal/deploy/deploy_test.go | 145 +++++++++++++++++++++- internal/deploy/git.go | 31 +++-- internal/deploy/puppetfile.go | 27 +++- internal/deploy/puppetfile_test.go | 14 +++ 5 files changed, 327 insertions(+), 80 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index ad4d372..18abe54 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -31,6 +31,7 @@ var ( ) type Deployer struct { + runGit func(ctx context.Context, dir string, args ...string) (string, error) cfg *Config grace time.Duration now func() time.Time @@ -67,7 +68,7 @@ func New(cfg *Config, jobs int, grace time.Duration) *Deployer { if jobs < 1 { jobs = 1 } - return &Deployer{cfg: cfg, grace: grace, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}} + return &Deployer{runGit: runGit, cfg: cfg, grace: grace, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}} } func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { @@ -98,7 +99,29 @@ func (d *Deployer) path(parts ...string) string { func (d *Deployer) srcMirror(s *Source) string { return d.path("sources", s.Name+".git") } func (d *Deployer) srcWorktrees(s *Source) string { return d.path("worktrees", s.Name) } -func urlKey(url string) string { return unsafeChars.ReplaceAllString(url, "_") } + +func shortHash(s string) string { + sum := sha256.Sum256([]byte(s)) + return hex.EncodeToString(sum[:8]) +} + +func urlKey(url string) string { + k := unsafeChars.ReplaceAllString(url, "_") + if len(k) > 64 { + k = k[len(k)-64:] + } + return k + "-" + shortHash(url) +} + +// doneFile is the out-of-tree completion marker; a branch can commit anything inside its own worktree. +func (d *Deployer) doneFile(worktree string) string { + return d.path("state", filepath.Base(filepath.Dir(worktree)), filepath.Base(worktree)+".done") +} + +func (d *Deployer) complete(worktree string) bool { + _, err := os.Stat(d.doneFile(worktree)) + return err == nil +} // Lock takes an exclusive flock on the cachedir, released by the returned func. func (d *Deployer) Lock() (func(), error) { @@ -146,7 +169,7 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro } func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]string, []error) { - all, err := branches(ctx, d.srcMirror(s)) + all, err := d.branches(ctx, d.srcMirror(s)) if err != nil { return nil, []error{err} } @@ -179,7 +202,7 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]stri } func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string]bool, modules bool) error { - if err := syncMirror(ctx, d.srcMirror(s), s.Remote, envRefspecs...); err != nil { + if err := d.syncMirror(ctx, d.srcMirror(s), s.Remote, envRefspecs...); err != nil { return err } envs, errs := d.Environments(ctx, s) @@ -229,15 +252,10 @@ func (d *Deployer) owned(s *Source, link string) string { return t } -func complete(dir string) bool { - _, err := os.Stat(filepath.Join(dir, markerFile)) - return err == nil -} - func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) error { link := filepath.Join(s.Basedir, name) cur := d.owned(s, link) - if cur != "" && !modules && strings.HasPrefix(filepath.Base(cur), sha+"-") && complete(cur) { + if cur != "" && !modules && strings.HasPrefix(filepath.Base(cur), sha+"-") && d.complete(cur) { return nil } pf, checksum, err := d.puppetfile(ctx, d.srcMirror(s), sha) @@ -253,11 +271,11 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m _, _ = fmt.Fprintf(h, "%s %s\n", m.path, m.key) } target := filepath.Join(d.srcWorktrees(s), sha+"-"+hex.EncodeToString(h.Sum(nil))[:12]) - if cur == target && complete(cur) { + if cur == target && d.complete(cur) { return nil } if _, err := d.once("env:"+target, func() (string, error) { - if complete(target) { + if d.complete(target) { return "", nil } started := d.now().UTC() @@ -276,10 +294,10 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m } func (d *Deployer) puppetfile(ctx context.Context, mirror, sha string) (*Puppetfile, string, error) { - if _, err := git(ctx, mirror, "cat-file", "-e", sha+":Puppetfile"); err != nil { + if _, err := d.git(ctx, mirror, "cat-file", "-e", sha+":Puppetfile"); err != nil { return &Puppetfile{Moduledir: "modules"}, "", nil } - src, err := git(ctx, mirror, "cat-file", "blob", sha+":Puppetfile") + src, err := d.git(ctx, mirror, "cat-file", "blob", sha+":Puppetfile") if err != nil { return nil, "", err } @@ -320,7 +338,7 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { key := urlKey(m.Git) mirror := d.path("git", key+".git") if _, err := d.once("fetch:"+mirror, func() (string, error) { - return "", d.limit(func() error { return syncMirror(ctx, mirror, m.Git, modRefspecs...) }) + return "", d.syncMirror(ctx, mirror, m.Git, modRefspecs...) }); err != nil { return resolved{}, err } @@ -337,7 +355,7 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { default: cands = []string{"refs/w10k/HEAD"} } - sha, err := revParse(ctx, mirror, cands...) + sha, err := d.revParse(ctx, mirror, cands...) if err != nil { return resolved{}, err } @@ -346,17 +364,15 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { if _, err := os.Stat(dir); err == nil { return "", nil } - return "", d.limit(func() error { - tmp := dir + ".tmp" - if err := removeWorktree(ctx, mirror, tmp); err != nil { - return err - } - if _, err := git(ctx, mirror, "worktree", "add", "--detach", "-q", tmp, sha); err != nil { - return err - } - _, err := git(ctx, mirror, "worktree", "move", tmp, dir) - return err - }) + tmp := dir + ".tmp" + if err := d.removeWorktree(ctx, mirror, tmp); err != nil { + return "", err + } + if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil { + return "", err + } + _, err := d.git(ctx, mirror, "worktree", "move", "--", tmp, dir) + return "", err }) return resolved{dir: dir, key: "git " + m.Git + " " + sha}, err } @@ -365,53 +381,93 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso slug := m.Owner + "-" + m.Name version := m.Version if version == "" { - v, err := d.once("latest:"+slug, func() (string, error) { return forgeLatest(ctx, base, slug) }) + v, err := d.once("latest:"+base+" "+slug, func() (string, error) { + var v string + err := d.limit(func() (err error) { v, err = forgeLatest(ctx, base, slug); return err }) + return v, err + }) if err != nil { return resolved{}, err } version = v } release := slug + "-" + version - dir := d.path("forge", release) - _, err := d.once("forge:"+release, func() (string, error) { + dir := d.path("forge", release+"-"+shortHash(base)) + _, err := d.once("forge:"+dir, func() (string, error) { if _, err := os.Stat(dir); err == nil { return "", nil } return "", d.limit(func() error { return forgeInstall(ctx, base, release, dir) }) }) - return resolved{dir: dir, key: "forge " + release}, err + return resolved{dir: dir, key: "forge " + base + " " + release}, err } func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, mods []resolved) error { mirror := d.srcMirror(s) - if err := removeWorktree(ctx, mirror, target); err != nil { + if err := os.Remove(d.doneFile(target)); err != nil && !os.IsNotExist(err) { + return err + } + if err := d.removeWorktree(ctx, mirror, target); err != nil { return err } if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { return err } - if err := d.limit(func() error { - _, err := git(ctx, mirror, "worktree", "add", "--detach", "-q", target, sha) - return err - }); err != nil { + if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha); err != nil { return err } for _, mod := range mods { - p := filepath.Join(target, mod.path) - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { - return err - } - if err := os.RemoveAll(p); err != nil { - return err - } - if err := os.Symlink(mod.dir, p); err != nil { + if err := linkModule(target, mod.path, mod.dir); err != nil { return err } } return nil } -// prepare runs last before a worktree can be swapped in; the deploy file it writes marks the worktree complete. +// linkModule creates root/rel -> dir without following any symlink under root, so committed links cannot redirect it. +func linkModule(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]...)) + } + } + realRoot, err := filepath.EvalSymlinks(root) + if err != nil { + return 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) +} + +// prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete. func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods []resolved, started time.Time) error { r := deployResult{ Name: name, @@ -431,11 +487,23 @@ func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods [ if err != nil { return err } - tmp := filepath.Join(target, markerFile+".tmp") - if err := os.WriteFile(tmp, append(b, '\n'), 0o644); err != nil { + b = append(b, '\n') + if err := writeAtomic(filepath.Join(target, markerFile), b); err != nil { return err } - return os.Rename(tmp, filepath.Join(target, markerFile)) + done := d.doneFile(target) + if err := os.MkdirAll(filepath.Dir(done), 0o755); err != nil { + return err + } + return writeAtomic(done, b) +} + +func writeAtomic(p string, b []byte) error { + tmp := p + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + return os.Rename(tmp, p) } // Swap points link at target via a temporary symlink renamed over it; a real directory is moved aside for GC. @@ -522,7 +590,7 @@ func (g *gcRun) collect(p string, remove func() error) { log.Printf("gc: removed %s", p) } -func (g *gcRun) sweep(mirror, dir string, live map[string]bool) { +func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(string) error) { entries, err := os.ReadDir(dir) if err != nil { if !os.IsNotExist(err) { @@ -535,16 +603,11 @@ func (g *gcRun) sweep(mirror, dir string, live map[string]bool) { if live[p] { continue } - g.collect(p, func() error { - if mirror == "" { - return os.RemoveAll(p) - } - return removeWorktree(g.ctx, mirror, p) - }) + g.collect(p, func() error { return remove(p) }) } if mirror != "" { if _, err := os.Stat(mirror); err == nil { - if _, err := git(g.ctx, mirror, "worktree", "prune"); err != nil { + if _, err := g.d.git(g.ctx, mirror, "worktree", "prune"); err != nil { g.errs = append(g.errs, err) } } @@ -571,7 +634,13 @@ func (d *Deployer) GC(ctx context.Context) error { for _, t := range live { liveEnv[t] = true } - g.sweep(d.srcMirror(s), d.srcWorktrees(s), liveEnv) + 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) { + return err + } + return d.removeWorktree(ctx, mirror, p) + }) entries, _ := os.ReadDir(s.Basedir) for _, e := range entries { if p := filepath.Join(s.Basedir, e.Name()); strings.HasPrefix(e.Name(), ".") && strings.Contains(e.Name(), asideTag) { @@ -589,9 +658,10 @@ func (d *Deployer) GC(ctx context.Context) error { } else { keys, _ := os.ReadDir(d.path("modules")) for _, k := range keys { - g.sweep(d.path("git", k.Name()+".git"), d.path("modules", k.Name()), liveMod) + mirror := d.path("git", k.Name()+".git") + g.sweep(mirror, d.path("modules", k.Name()), liveMod, func(p string) error { return d.removeWorktree(ctx, mirror, p) }) } - g.sweep("", d.path("forge"), liveMod) + g.sweep("", d.path("forge"), liveMod, os.RemoveAll) } for p := range g.marks { @@ -622,7 +692,7 @@ func (d *Deployer) moduleRefs(liveEnv map[string]bool) (map[string]bool, error) } for _, e := range entries { p := filepath.Join(d.srcWorktrees(s), e.Name()) - b, err := os.ReadFile(filepath.Join(p, markerFile)) + b, err := os.ReadFile(d.doneFile(p)) if os.IsNotExist(err) && !liveEnv[p] { continue } diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 58e30d6..3b15c13 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -80,8 +80,9 @@ func TestGCGrace(t *testing.T) { old, cur := filepath.Join(d.srcWorktrees(cfg.Sources["s"]), "old"), filepath.Join(d.srcWorktrees(cfg.Sources["s"]), "cur") aside := filepath.Join(cfg.Sources["s"].Basedir, ".develop"+asideTag+"1") mkdirs(t, old, cur, aside) + mkdirs(t, filepath.Dir(d.doneFile(old))) for _, p := range []string{old, cur} { - if err := os.WriteFile(filepath.Join(p, markerFile), []byte(`{"modules":[]}`), 0o644); err != nil { + if err := os.WriteFile(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { t.Fatal(err) } } @@ -301,6 +302,10 @@ func (f *fixture) cache(parts ...string) string { return filepath.Join(append([]string{f.cfg.Cachedir}, parts...)...) } +func (f *fixture) forgeDir(release string) string { + return f.cache("forge", release+"-"+shortHash(f.forgeURL)) +} + func TestDeployIntegration(t *testing.T) { f := newFixture(t) sha1 := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) @@ -377,12 +382,12 @@ func TestDeployIntegration(t *testing.T) { commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmoduledir 'external_modules'\nmod 'acme-latest', :latest\n", f.forgeURL)}) f.mustDeploy(false) - if dirCount(t, f.cache("modules", urlKey(f.mod))) != 2 || !exists(f.cache("forge", "acme-thing-1.0.0")) { + if dirCount(t, f.cache("modules", urlKey(f.mod))) != 2 || !exists(f.forgeDir("acme-thing-1.0.0")) { t.Fatal("modules still referenced by a worktree awaiting GC must be kept") } f.settle() f.settle() - if dirCount(t, f.cache("modules", urlKey(f.mod))) != 0 || exists(f.cache("forge", "acme-thing-1.0.0")) || !exists(f.cache("forge", "acme-latest-2.0.0")) { + if dirCount(t, f.cache("modules", urlKey(f.mod))) != 0 || exists(f.forgeDir("acme-thing-1.0.0")) || !exists(f.forgeDir("acme-latest-2.0.0")) { t.Fatal("dropped modules must be GC'd, kept ones retained") } @@ -455,3 +460,137 @@ func TestInFlightCompileSurvivesSwap(t *testing.T) { t.Fatal("old worktree must be removed once grace has passed") } } + +func TestGitURLOptionInjection(t *testing.T) { + f := newFixture(t) + pwned := filepath.Join(f.root, "pwned") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'evil', :git => '--upload-pack=touch %s;'\n", pwned)}) + if err := f.deploy(false); err == nil { + t.Fatal("option-like :git must be rejected") + } + if exists(pwned) { + t.Fatal("injected --upload-pack ran") + } +} + +func TestInstallPathThroughCommittedSymlink(t *testing.T) { + f := newFixture(t) + victim := filepath.Join(f.root, "victim") + mkdirs(t, filepath.Join(victim, "bind", "keep")) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0', :install_path => 'escape'\n", f.mod)}) + if err := os.Symlink(victim, filepath.Join(f.control, "escape")); err != nil { + t.Fatal(err) + } + gitT(t, f.control, "add", "-A") + gitT(t, f.control, "commit", "-q", "-m", "link") + if err := f.deploy(false); err == nil { + t.Fatal("install_path through a committed symlink must fail") + } + if !exists(filepath.Join(victim, "bind", "keep")) { + t.Fatal("deploy wrote outside the worktree") + } + if f.env("main") != "" { + t.Fatal("failed build must not go live") + } +} + +func TestNestedInstallPathSharedModule(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\n", f.forgeURL)}) + f.mustDeploy(false) + gitT(t, f.control, "checkout", "-q", "-b", "attacker") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\nmod 'metadata', :git => '%s', :tag => '1.0', :install_path => 'modules/thing'\n", f.forgeURL, f.mod)}) + if err := f.deploy(false); err == nil { + t.Fatal("nested install_path must fail") + } + if exists(filepath.Join(f.forgeDir("acme-thing-1.0.0"), "metadata")) { + t.Fatal("shared forge cache dir mutated by another branch") + } +} + +func TestCommittedMarkerDoesNotCompleteWorktree(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), + markerFile: `{"modules":[]}`, + "modules": "a file, so the module link fails", + }) + for range 2 { + if err := f.deploy(false); err == nil { + t.Fatal("broken build must fail") + } + if f.env("main") != "" { + t.Fatal("incomplete worktree went live") + } + } +} + +func TestMirrorKeyDistinctURLs(t *testing.T) { + f := newFixture(t) + other, victim := filepath.Join(f.root, "m_od"), filepath.Join(f.root, "m", "od") + if urlKey(other) == urlKey(victim) { + t.Fatal("distinct URLs share a mirror key") + } + newRepo(t, other) + commit(t, other, map[string]string{"manifests/init.pp": "class evil {}\n"}) + gitT(t, other, "tag", "1.0") + newRepo(t, victim) + commit(t, victim, map[string]string{"manifests/init.pp": "class good {}\n"}) + gitT(t, victim, "tag", "1.0") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'x', :git => '%s', :tag => '1.0'\n", victim)}) + gitT(t, f.control, "checkout", "-q", "-b", "attacker") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'x', :git => '%s', :tag => '1.0'\n", other)}) + for range 5 { + f.mustDeploy(true) + b, _ := os.ReadFile(filepath.Join(f.env("main"), "modules", "x", "manifests", "init.pp")) + if !strings.Contains(string(b), "good") { + t.Fatalf("main got another branch's module: %q", b) + } + } +} + +func TestForgeCacheKeyedByBase(t *testing.T) { + f := newFixture(t) + gitT(t, f.control, "checkout", "-q", "-b", "a") + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\n", f.forgeURL)}) + f.mustDeploy(false) + gitT(t, f.control, "checkout", "-q", "-b", "b") + commit(t, f.control, map[string]string{"Puppetfile": "forge 'http://127.0.0.1:1'\nmod 'acme-thing', '1.0.0'\n"}) + if err := f.deploy(false); err == nil { + t.Fatal("release cached from one forge was served for another") + } +} + +func TestJobsBoundGitProcesses(t *testing.T) { + f := newFixture(t) + var pf strings.Builder + for i := range 6 { + repo := filepath.Join(f.root, fmt.Sprintf("r%d", i)) + newRepo(t, repo) + commit(t, repo, map[string]string{"manifests/init.pp": "class m {}\n"}) + fmt.Fprintf(&pf, "mod 'm%d', :git => '%s'\n", i, repo) + } + commit(t, f.control, map[string]string{"Puppetfile": pf.String()}) + for i := range 4 { + gitT(t, f.control, "branch", fmt.Sprintf("b%d", i)) + } + const jobs = 2 + var mu sync.Mutex + cur, peak := 0, 0 + d := New(f.cfg, jobs, 10*time.Minute) + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + mu.Lock() + cur++ + peak = max(peak, cur) + mu.Unlock() + defer func() { mu.Lock(); cur--; mu.Unlock() }() + time.Sleep(time.Millisecond) + return runGit(ctx, dir, args...) + } + if err := d.Deploy(context.Background(), nil, true); err != nil { + t.Fatal(err) + } + if peak > jobs { + t.Fatalf("%d concurrent git processes with -j %d", peak, jobs) + } +} diff --git a/internal/deploy/git.go b/internal/deploy/git.go index 679242d..992ec78 100644 --- a/internal/deploy/git.go +++ b/internal/deploy/git.go @@ -9,7 +9,7 @@ import ( "strings" ) -func git(ctx context.Context, dir string, args ...string) (string, error) { +func runGit(ctx context.Context, dir string, args ...string) (string, error) { cmd := exec.CommandContext(ctx, "git", args...) cmd.Dir = dir cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") @@ -21,19 +21,28 @@ func git(ctx context.Context, dir string, args ...string) (string, error) { return strings.TrimSpace(out.String()), nil } -func syncMirror(ctx context.Context, mirror, url string, refspecs ...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 { + out, err = d.runGit(ctx, dir, args...) + return err + }) + return out, err +} + +func (d *Deployer) syncMirror(ctx context.Context, mirror, url string, refspecs ...string) error { if _, err := os.Stat(mirror); os.IsNotExist(err) { - if _, err := git(ctx, "", "init", "-q", "--bare", mirror); err != nil { + if _, err := d.git(ctx, "", "init", "-q", "--bare", "--", mirror); err != nil { return err } } - args := append([]string{"fetch", "-q", "--prune", "--force", url}, refspecs...) - _, err := git(ctx, mirror, args...) + args := append([]string{"fetch", "-q", "--prune", "--force", "--", url}, refspecs...) + _, err := d.git(ctx, mirror, args...) return err } -func branches(ctx context.Context, mirror string) (map[string]string, error) { - out, err := git(ctx, mirror, "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads/") +func (d *Deployer) branches(ctx context.Context, mirror string) (map[string]string, error) { + out, err := d.git(ctx, mirror, "for-each-ref", "--format=%(objectname) %(refname)", "refs/heads/") if err != nil { return nil, err } @@ -47,16 +56,16 @@ func branches(ctx context.Context, mirror string) (map[string]string, error) { return m, nil } -func revParse(ctx context.Context, mirror string, candidates ...string) (string, error) { +func (d *Deployer) revParse(ctx context.Context, mirror string, candidates ...string) (string, error) { for _, c := range candidates { - if sha, err := git(ctx, mirror, "rev-parse", "--verify", "--quiet", c+"^{commit}"); err == nil { + if sha, err := d.git(ctx, mirror, "rev-parse", "--verify", "--quiet", "--end-of-options", c+"^{commit}"); err == nil { return sha, nil } } return "", fmt.Errorf("cannot resolve %s", strings.Join(candidates, " or ")) } -func removeWorktree(ctx context.Context, mirror, path string) error { - _, _ = git(ctx, mirror, "worktree", "remove", "--force", path) +func (d *Deployer) removeWorktree(ctx context.Context, mirror, path string) error { + _, _ = d.git(ctx, mirror, "worktree", "remove", "--force", "--", path) return os.RemoveAll(path) } diff --git a/internal/deploy/puppetfile.go b/internal/deploy/puppetfile.go index f65b539..7786698 100644 --- a/internal/deploy/puppetfile.go +++ b/internal/deploy/puppetfile.go @@ -208,7 +208,6 @@ func ParsePuppetfile(src string) (*Puppetfile, error) { return nil, err } pf := &Puppetfile{Moduledir: "modules"} - seen := map[string]bool{} for _, c := range calls { switch c.name { case "forge", "moduledir": @@ -225,16 +224,26 @@ func ParsePuppetfile(src string) (*Puppetfile, error) { if err != nil { return nil, fmt.Errorf("line %d: %w", c.line, err) } - p := m.Path(pf) - if seen[p] { - return nil, fmt.Errorf("line %d: duplicate module %s", c.line, p) - } - seen[p] = true pf.Modules = append(pf.Modules, m) default: return nil, fmt.Errorf("line %d: unsupported statement %q", c.line, c.name) } } + seen := map[string]bool{} + for _, m := range pf.Modules { + p := m.Path(pf) + if seen[p] { + return nil, fmt.Errorf("duplicate module %s", p) + } + seen[p] = true + } + for p := range seen { + for d := filepath.Dir(p); d != "."; d = filepath.Dir(d) { + if seen[d] { + return nil, fmt.Errorf("module %s is nested inside module %s", p, d) + } + } + } return pf, nil } @@ -265,8 +274,14 @@ func parseMod(c call) (Module, error) { } switch k { case "git": + if v.val == "" || strings.HasPrefix(v.val, "-") { + return m, fmt.Errorf("mod %s: invalid :git %q", full, v.val) + } m.Git = v.val case "tag", "branch", "ref", "commit": + if v.val == "" || strings.HasPrefix(v.val, "-") { + return m, fmt.Errorf("mod %s: invalid :%s %q", full, k, v.val) + } if m.RefKind != "" { return m, fmt.Errorf("mod %s: only one of :tag, :branch, :ref, :commit allowed", full) } diff --git a/internal/deploy/puppetfile_test.go b/internal/deploy/puppetfile_test.go index 103bf58..ed70f47 100644 --- a/internal/deploy/puppetfile_test.go +++ b/internal/deploy/puppetfile_test.go @@ -88,6 +88,10 @@ func TestParsePuppetfileErrors(t *testing.T) { "escape moduledir": "moduledir '../x'", "escape install": "mod 'x', :git => 'g', :install_path => '../../x'", "duplicate": "mod 'a-b', '1'\nmod 'c-b', '2'", + "final moduledir": "mod 'a-x', '1'\nmoduledir 'site'\nmod 'x', :git => 'g', :install_path => 'site'", + "nested": "mod 'a-thing', '1'\nmod 'metadata', :git => 'g', :install_path => 'modules/thing'", + "option git": "mod 'x', :git => '--upload-pack=touch /tmp/x'", + "option ref": "mod 'x', :git => 'g', :branch => '--output=/tmp/x'", "trailing junk": "mod 'a-b', '1' 'c'", "bad char": "mod 'a-b', '1'; x", } { @@ -96,3 +100,13 @@ func TestParsePuppetfileErrors(t *testing.T) { } } } + +func TestParsePuppetfileFinalModuledir(t *testing.T) { + pf, err := ParsePuppetfile("mod 'a-x', '1'\nmoduledir 'site'\nmod 'x', :git => 'g', :install_path => 'modules'\n") + if err != nil { + t.Fatal(err) + } + if p := pf.Modules[0].Path(pf); p != "site/x" { + t.Fatalf("forge module path %s, want final moduledir", p) + } +}