diff --git a/.woodpecker/lint.yaml b/.woodpecker/lint.yaml index e842a70..dffd4d5 100644 --- a/.woodpecker/lint.yaml +++ b/.woodpecker/lint.yaml @@ -3,7 +3,7 @@ when: steps: - name: lint - image: golangci/golangci-lint:latest + image: golangci/golangci-lint:v2.13.1 commands: - golangci-lint run ./... backend_options: diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 8cc92fa..d4ca526 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -2,6 +2,7 @@ package deploy import ( "context" + "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" @@ -12,6 +13,7 @@ import ( "os" "path/filepath" "regexp" + "runtime/debug" "slices" "sort" "strconv" @@ -27,12 +29,15 @@ const ( markerFile = ".g10k-deploy.json" gcStateFile = "gc-state.json" asideTag = ".w10k-old-" + gcTag = ".gc-" ) var ( - envRefspecs = []string{"+refs/heads/*:refs/heads/*"} - modRefspecs = []string{"+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", "+HEAD:refs/w10k/HEAD"} - unsafeChars = regexp.MustCompile(`[^A-Za-z0-9._-]`) + envRefspecs = []string{"+refs/heads/*:refs/heads/*"} + modFetchOpts = []string{"-c", "protocol.file.allow=never"} + modRefspecs = []string{"+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", "+HEAD:refs/w10k/HEAD"} + unsafeChars = regexp.MustCompile(`[^A-Za-z0-9._-]`) + gcLeftover = regexp.MustCompile(`\.gc-[A-Z2-7]{26}$`) ) type Deployer struct { @@ -91,8 +96,11 @@ func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { } d.mu.Unlock() if !ok { - f.val, f.err = fn() - close(f.done) + func() { + defer close(f.done) + defer recoverErr(&f.err, key) + f.val, f.err = fn() + }() } <-f.done return f.val, f.err @@ -124,14 +132,51 @@ func urlKey(url string) string { 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") +// doneFile is the out-of-tree completion marker for a cache dir; a branch can commit anything inside its own worktree. +func (d *Deployer) doneFile(dir string) string { + rel, _ := filepath.Rel(d.cfg.Cachedir, dir) + return d.path("state", rel+".done") } -func (d *Deployer) complete(worktree string) bool { - _, err := os.Stat(d.doneFile(worktree)) - return err == nil +func (d *Deployer) complete(dir string) bool { + _, err := os.Stat(d.doneFile(dir)) + _, derr := os.Stat(dir) + return err == nil && derr == nil +} + +func (d *Deployer) markDone(dir string, b []byte) error { + done := d.doneFile(dir) + if err := os.MkdirAll(filepath.Dir(done), 0o755); err != nil { + return err + } + return writeAtomic(done, b) +} + +// discard unmarks dir, renames it aside atomically and only then deletes it, so an interrupted GC never leaves a reusable half-deleted dir. +func (d *Deployer) discard(ctx context.Context, mirror, dir string) error { + if err := os.Remove(d.doneFile(dir)); err != nil && !os.IsNotExist(err) { + return err + } + gc := dir + gcTag + rand.Text() + if mirror == "" { + if err := os.Rename(dir, gc); err != nil { + return err + } + return os.RemoveAll(gc) + } + if _, err := d.git(ctx, mirror, "worktree", "move", "--", dir, gc); err != nil { + if err := os.Rename(dir, gc); err != nil { + return err + } + } + return d.removeWorktree(ctx, mirror, gc) +} + +func recoverErr(err *error, what string) { + if r := recover(); r != nil { + log.Printf("%s: panic: %v\n%s", what, r, debug.Stack()) + *err = fmt.Errorf("panic: %v", r) + } } // Lock takes an exclusive flock on the cachedir, released by the returned func. @@ -221,7 +266,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 := d.syncMirror(ctx, d.srcMirror(s), s.Remote, envRefspecs...); err != nil { + if err := d.syncMirror(ctx, d.srcMirror(s), s.Remote, nil, envRefspecs); err != nil { return err } envs, errs := d.Environments(ctx, s) @@ -242,7 +287,11 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string] wg.Add(1) go func() { defer wg.Done() - if err := d.deployEnv(ctx, s, name, sha, modules); err != nil { + err := func() (err error) { + defer recoverErr(&err, "environment "+name) + return d.deployEnv(ctx, s, name, sha, modules) + }() + if err != nil { mu.Lock() errs = append(errs, fmt.Errorf("environment %s: %w", name, err)) mu.Unlock() @@ -355,14 +404,17 @@ func (d *Deployer) installModules(ctx context.Context, pf *Puppetfile) ([]resolv go func() { defer wg.Done() var err error + defer func() { + if err != nil { + errs[i] = fmt.Errorf("module %s: %w", m.Name, err) + } + }() + defer recoverErr(&err, "module "+m.Name) if m.Git != "" { out[i], err = d.gitModule(ctx, m) } else { out[i], err = d.forgeModule(ctx, forgeURL(pf.Forge), m) } - if err != nil { - errs[i] = fmt.Errorf("module %s: %w", m.Name, err) - } out[i].path = m.Path(pf) }() } @@ -375,7 +427,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.syncMirror(ctx, mirror, m.Git, modRefspecs...) + return "", d.syncMirror(ctx, mirror, m.Git, modFetchOpts, modRefspecs) }); err != nil { return resolved{}, err } @@ -398,18 +450,22 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) { } dir := d.path("modules", key, sha) _, err = d.once("mod:"+dir, func() (string, error) { - if _, err := os.Stat(dir); err == nil { + if d.complete(dir) { return "", nil } tmp := dir + ".tmp" - if err := d.removeWorktree(ctx, mirror, tmp); err != nil { - return "", err + for _, p := range []string{tmp, dir} { + if err := d.removeWorktree(ctx, mirror, p); 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 + if _, err := d.git(ctx, mirror, "worktree", "move", "--", tmp, dir); err != nil { + return "", err + } + return "", d.markDone(dir, nil) }) return resolved{dir: dir, key: "git " + m.Git + " " + sha}, err } @@ -431,10 +487,16 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso release := slug + "-" + version dir := d.path("forge", release+"-"+shortHash(base)) _, err := d.once("forge:"+dir, func() (string, error) { - if _, err := os.Stat(dir); err == nil { + if d.complete(dir) { return "", nil } - return "", d.limit(func() error { return forgeInstall(ctx, base, release, dir) }) + if err := os.RemoveAll(dir); err != nil { + return "", err + } + if err := d.limit(func() error { return forgeInstall(ctx, base, release, dir) }); err != nil { + return "", err + } + return "", d.markDone(dir, nil) }) return resolved{dir: dir, key: "forge " + base + " " + release}, err } @@ -514,11 +576,7 @@ func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods [ if err := writeMarker(target, b); err != nil { return "", err } - done := d.doneFile(target) - if err := os.MkdirAll(filepath.Dir(done), 0o755); err != nil { - return "", err - } - return strconv.Itoa(len(skipped)), writeAtomic(done, b) + return strconv.Itoa(len(skipped)), d.markDone(target, b) } // writeMarker replaces whatever the branch committed at the marker paths without following it. @@ -651,6 +709,12 @@ func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(stri } for _, e := range entries { p := filepath.Join(dir, e.Name()) + if gcLeftover.MatchString(e.Name()) { + if err := os.RemoveAll(p); err != nil { + g.errs = append(g.errs, err) + } + continue + } if live[p] { continue } @@ -710,9 +774,9 @@ func (d *Deployer) GC(ctx context.Context) error { keys, _ := os.ReadDir(d.path("modules")) for _, k := range keys { 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(mirror, d.path("modules", k.Name()), liveMod, func(p string) error { return d.discard(ctx, mirror, p) }) } - g.sweep("", d.path("forge"), liveMod, os.RemoveAll) + g.sweep("", d.path("forge"), liveMod, func(p string) error { return d.discard(ctx, "", p) }) } for p := range g.marks { diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 248f841..13671c8 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -8,6 +8,7 @@ import ( "log" "net" "net/http" + "net/http/cgi" "net/http/httptest" "os" "os/exec" @@ -215,6 +216,8 @@ type fixture struct { root string control string mod string + modDir string + gitURL string basedir string cfg *Config clock time.Time @@ -244,10 +247,19 @@ func newFixture(t *testing.T) *fixture { f.forgeURL = forge.URL f.hit = func(p string) int { mu.Lock(); defer mu.Unlock(); return hits[p] } - f.mod = filepath.Join(f.root, "mod") - newRepo(t, f.mod) - commit(t, f.mod, map[string]string{"manifests/init.pp": "class bind {}\n"}) - gitT(t, f.mod, "tag", "1.0") + gitBin, err := exec.LookPath("git") + if err != nil { + t.Fatal(err) + } + gitSrv := httptest.NewServer(&cgi.Handler{Path: gitBin, Args: []string{"http-backend"}, Env: []string{"GIT_PROJECT_ROOT=" + f.root, "GIT_HTTP_EXPORT_ALL=1"}}) + t.Cleanup(gitSrv.Close) + f.gitURL = gitSrv.URL + + f.modDir = filepath.Join(f.root, "mod") + f.mod = f.url(f.modDir) + newRepo(t, f.modDir) + commit(t, f.modDir, map[string]string{"manifests/init.pp": "class bind {}\n"}) + gitT(t, f.modDir, "tag", "1.0") f.control = filepath.Join(f.root, "control") newRepo(t, f.control) @@ -260,6 +272,15 @@ func newFixture(t *testing.T) *fixture { return f } +// url serves a repo under f.root over git smart HTTP; module sources must be remote. +func (f *fixture) url(dir string) string { + rel, err := filepath.Rel(f.root, dir) + if err != nil { + f.t.Fatal(err) + } + return f.gitURL + "/" + filepath.ToSlash(rel) +} + func (f *fixture) puppetfile() string { return fmt.Sprintf(`forge '%s' moduledir 'external_modules' @@ -368,7 +389,7 @@ func TestDeployIntegration(t *testing.T) { t.Fatalf("worktree not pruned:\n%s", wl) } - commit(t, f.mod, map[string]string{"manifests/init.pp": "class tracker {}\n"}) + commit(t, f.modDir, map[string]string{"manifests/init.pp": "class tracker {}\n"}) f.mustDeploy(false) if f.env("main") != main2 { t.Fatal("module branch move must not redeploy without --modules") @@ -531,7 +552,7 @@ func TestCommittedMarkerDoesNotCompleteWorktree(t *testing.T) { 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) { + if urlKey(f.url(other)) == urlKey(f.url(victim)) { t.Fatal("distinct URLs share a mirror key") } newRepo(t, other) @@ -540,9 +561,9 @@ func TestMirrorKeyDistinctURLs(t *testing.T) { 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)}) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'x', :git => '%s', :tag => '1.0'\n", f.url(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)}) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'x', :git => '%s', :tag => '1.0'\n", f.url(other))}) for range 5 { f.mustDeploy(true) b, _ := os.ReadFile(filepath.Join(f.env("main"), "modules", "x", "manifests", "init.pp")) @@ -571,7 +592,7 @@ func TestJobsBoundGitProcesses(t *testing.T) { 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) + fmt.Fprintf(&pf, "mod 'm%d', :git => '%s'\n", i, f.url(repo)) } commit(t, f.control, map[string]string{"Puppetfile": pf.String()}) for i := range 4 { @@ -608,7 +629,7 @@ func TestGenerateTypesBeforeSwap(t *testing.T) { "lib/puppet/provider/typed/posix.rb": "", }) commit(t, f.control, map[string]string{ - "Puppetfile": fmt.Sprintf("moduledir 'external_modules'\nmod 'typed', :git => '%s'\n", typed), + "Puppetfile": fmt.Sprintf("moduledir 'external_modules'\nmod 'typed', :git => '%s'\n", f.url(typed)), "environment.conf": "modulepath = site:external_modules:$basemodulepath\n", "site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n ensurable\n newparam(:name)\nend\n", }) @@ -770,3 +791,126 @@ func TestGCKeepsModulesOfRemovedSource(t *testing.T) { t.Fatalf("GC deleted a module still linked from a removed source's live env: %v", err) } } + +func TestPuppetfileLocalRepoRejected(t *testing.T) { + f := newFixture(t) + secret := filepath.Join(f.root, "secret") + newRepo(t, secret) + commit(t, secret, map[string]string{"manifests/init.pp": "# private\n"}) + for _, g := range []string{"file://" + secret, secret} { + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'loot', :git => '%s'\n", g)}) + if err := f.deploy(false); err == nil { + t.Fatalf(":git %s accepted", g) + } + if p := filepath.Join(f.basedir, "main", "modules", "loot", "manifests", "init.pp"); exists(p) { + t.Fatalf("untrusted Puppetfile cloned a local repo into the env: %s", p) + } + } +} + +func TestModuleFetchRefusesFileProtocol(t *testing.T) { + f := newFixture(t) + d := f.deployer() + if err := d.syncMirror(context.Background(), filepath.Join(f.root, "m.git"), "file://"+f.modDir, modFetchOpts, modRefspecs); err == nil || !strings.Contains(err.Error(), "transport 'file' not allowed") { + t.Fatalf("module fetch over file:// not refused: %v", err) + } +} + +func TestInterruptedModuleGCNotReused(t *testing.T) { + f := newFixture(t) + pf := fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod) + commit(t, f.control, map[string]string{"Puppetfile": pf}) + f.mustDeploy(false) + commit(t, f.control, map[string]string{"Puppetfile": "\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(11 * time.Minute) + f.mustDeploy(false) + f.clock = f.clock.Add(11 * time.Minute) + d := f.deployer() + crashed := false + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + if len(args) > 1 && args[0] == "worktree" && args[1] == "remove" && strings.Contains(args[len(args)-1], "/modules/") { + _ = os.Remove(filepath.Join(args[len(args)-1], "manifests", "init.pp")) + crashed = true + panic("crash mid-removal") + } + return runGit(ctx, dir, args...) + } + func() { + defer func() { _ = recover() }() + _ = d.GC(context.Background()) + }() + if !crashed { + t.Fatal("GC never reached module removal") + } + commit(t, f.control, map[string]string{"Puppetfile": pf + "# again\n"}) + f.mustDeploy(false) + if p := filepath.Join(f.basedir, "main", "modules", "bind", "manifests", "init.pp"); !exists(p) { + t.Fatalf("env went live with a half-deleted module dir reused from cache: %s missing", p) + } + if n := dirCount(t, f.cache("modules", urlKey(f.mod))); n != 1 { + t.Fatalf("interrupted GC leftover not removed: %d entries", n) + } +} + +func TestUnmarkedCacheDirsRebuilt(t *testing.T) { + f := newFixture(t) + pf := fmt.Sprintf("forge '%s'\nmod 'acme-thing', '1.0.0'\nmod 'bind', :git => '%s', :tag => '1.0'\n", f.forgeURL, f.mod) + commit(t, f.control, map[string]string{"Puppetfile": pf}) + f.mustDeploy(false) + d := f.deployer() + forge := f.forgeDir("acme-thing-1.0.0") + mods, _ := os.ReadDir(f.cache("modules", urlKey(f.mod))) + mod := f.cache("modules", urlKey(f.mod), mods[0].Name()) + for _, dir := range []string{forge, mod} { + if err := os.Remove(d.doneFile(dir)); err != nil { + t.Fatal(err) + } + } + mustRemove(t, filepath.Join(forge, "metadata.json"), filepath.Join(mod, "manifests", "init.pp")) + leftover := f.cache("forge", "x"+gcTag+strings.Repeat("A", 26)) + mkdirs(t, leftover) + commit(t, f.control, map[string]string{"Puppetfile": pf + "# again\n"}) + f.mustDeploy(false) + for _, p := range []string{"modules/thing/metadata.json", "modules/bind/manifests/init.pp"} { + if !exists(filepath.Join(f.env("main"), p)) { + t.Fatalf("unmarked cache dir reused: %s missing", p) + } + } + if exists(leftover) { + t.Fatal("gc leftover not removed") + } +} + +func mustRemove(t *testing.T, paths ...string) { + t.Helper() + for _, p := range paths { + if err := os.Remove(p); err != nil { + t.Fatal(err) + } + } +} + +func TestPanicFailsOnlyItsEnv(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "bad") + bad := commit(t, f.control, map[string]string{"manifests/site.pp": "# bad\n"}) + d := f.deployer() + d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) { + if len(args) > 2 && args[0] == "cat-file" && strings.HasPrefix(args[2], bad) { + panic("boom") + } + return runGit(ctx, dir, args...) + } + err := d.Deploy(context.Background(), nil, false) + if err == nil || !strings.Contains(err.Error(), "environment bad: panic: boom") { + t.Fatalf("panic not reported as env error: %v", err) + } + if f.env("main") == "" || f.env("bad") != "" { + t.Fatalf("main=%q bad=%q", f.env("main"), f.env("bad")) + } + if !exists(f.cache(gcStateFile)) { + t.Fatal("GC skipped after a panicking env") + } +} diff --git a/internal/deploy/git.go b/internal/deploy/git.go index 9d166b3..2bc3271 100644 --- a/internal/deploy/git.go +++ b/internal/deploy/git.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "os/exec" + "slices" "strings" "syscall" "time" @@ -39,13 +40,13 @@ func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out str return out, err } -func (d *Deployer) syncMirror(ctx context.Context, mirror, url string, refspecs ...string) error { +func (d *Deployer) syncMirror(ctx context.Context, mirror, url string, opts, refspecs []string) error { if _, err := os.Stat(mirror); os.IsNotExist(err) { if _, err := d.git(ctx, "", "init", "-q", "--bare", "--", mirror); err != nil { return err } } - args := append([]string{"fetch", "-q", "--prune", "--force", "--", url}, refspecs...) + args := slices.Concat(opts, []string{"fetch", "-q", "--prune", "--force", "--", url}, refspecs) _, err := d.git(ctx, mirror, args...) return err } diff --git a/internal/deploy/puppetfile.go b/internal/deploy/puppetfile.go index 7786698..512b4a2 100644 --- a/internal/deploy/puppetfile.go +++ b/internal/deploy/puppetfile.go @@ -2,6 +2,7 @@ package deploy import ( "fmt" + "net/url" "path/filepath" "regexp" "strings" @@ -138,7 +139,13 @@ type call struct { func parseCalls(toks []token) ([]call, error) { var calls []call i := 0 - next := func() token { t := toks[i]; i++; return t } + next := func() token { + t := toks[i] + if t.kind != tEOF { + i++ + } + return t + } peek := func() token { return toks[i] } skipNL := func() { for peek().kind == tNewline { @@ -163,11 +170,15 @@ func parseCalls(toks []token) ([]call, error) { for k := peek().kind; k != tNewline && k != tEOF && k != tRParen; k = peek().kind { a := next() switch { - case a.kind == tLabel: - c.opts[a.val] = next() - case a.kind == tSymbol && peek().kind == tArrow: - i++ - c.opts[a.val] = next() + case a.kind == tLabel || a.kind == tSymbol && peek().kind == tArrow: + if a.kind == tSymbol { + i++ + } + v := next() + if v.kind != tString && v.kind != tSymbol { + return nil, fmt.Errorf("line %d: %s needs a value", a.line, a.val) + } + c.opts[a.val] = v case a.kind == tString || a.kind == tSymbol: c.args = append(c.args, a) default: @@ -247,6 +258,19 @@ func ParsePuppetfile(src string) (*Puppetfile, error) { return pf, nil } +var scpURL = regexp.MustCompile(`^[A-Za-z0-9._][A-Za-z0-9._-]*@[A-Za-z0-9.][A-Za-z0-9.-]*:[^:]+$`) + +func remoteURL(s string) bool { + if scpURL.MatchString(s) { + return true + } + u, err := url.Parse(s) + if err != nil || u.Hostname() == "" || strings.HasPrefix(u.Host, "-") || strings.HasPrefix(u.User.Username(), "-") { + return false + } + return u.Scheme == "https" || u.Scheme == "http" || u.Scheme == "ssh" +} + func localPath(p string) (string, error) { if !filepath.IsLocal(p) { return "", fmt.Errorf("%q must be a relative path inside the environment", p) @@ -274,8 +298,8 @@ 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) + if !remoteURL(v.val) { + return m, fmt.Errorf("mod %s: :git %q must be an https, http, ssh or user@host:path URL", full, v.val) } m.Git = v.val case "tag", "branch", "ref", "commit": diff --git a/internal/deploy/puppetfile_test.go b/internal/deploy/puppetfile_test.go index ed70f47..d5b67c9 100644 --- a/internal/deploy/puppetfile_test.go +++ b/internal/deploy/puppetfile_test.go @@ -1,6 +1,7 @@ package deploy import ( + "path/filepath" "reflect" "testing" ) @@ -45,9 +46,9 @@ mod 'a-b', 'latest' mod('x', git: 'https://example/x.git', branch: 'main') -mod 'y', :git => "file:///y#not-a-comment", :ref => 'v1' -mod 'z', :git => 'g', :commit => 'abc123', :install_path => 'site' -mod 'h', :git => 'g2' +mod 'y', :git => "https://h/y#not-a-comment", :ref => 'v1' +mod 'z', :git => 'git@h:g', :commit => 'abc123', :install_path => 'site' +mod 'h', :git => 'ssh://h/g2' `) if err != nil { t.Fatal(err) @@ -58,9 +59,9 @@ mod 'h', :git => 'g2' {Owner: "saz", Name: "ssh"}, {Owner: "a", Name: "b"}, {Name: "x", Git: "https://example/x.git", RefKind: "branch", Ref: "main"}, - {Name: "y", Git: "file:///y#not-a-comment", RefKind: "ref", Ref: "v1"}, - {Name: "z", Git: "g", RefKind: "commit", Ref: "abc123", InstallPath: "site"}, - {Name: "h", Git: "g2"}, + {Name: "y", Git: "https://h/y#not-a-comment", RefKind: "ref", Ref: "v1"}, + {Name: "z", Git: "git@h:g", RefKind: "commit", Ref: "abc123", InstallPath: "site"}, + {Name: "h", Git: "ssh://h/g2"}, } if !reflect.DeepEqual(pf.Modules, want) { t.Fatalf("modules:\n got %+v\nwant %+v", pf.Modules, want) @@ -77,21 +78,21 @@ func TestParsePuppetfileErrors(t *testing.T) { for name, in := range map[string]string{ "unterminated": "mod 'a-b", "unknown stmt": "require 'x'", - "unknown option": "mod 'x', :git => 'g', :default_branch => 'main'", - "two refs": "mod 'x', :git => 'g', :tag => 'a', :branch => 'b'", + "unknown option": "mod 'x', :git => 'git@h:g', :default_branch => 'main'", + "two refs": "mod 'x', :git => 'git@h:g', :tag => 'a', :branch => 'b'", "ref without git": "mod 'a-b', :tag => '1'", - "git version": "mod 'x', '1.0', :git => 'g'", + "git version": "mod 'x', '1.0', :git => 'git@h:g'", "no owner": "mod 'stdlib', '1.0'", "bad name": "mod 'a-B@d', '1.0'", "bad version": "mod 'a-b', '../../etc'", "abs moduledir": "moduledir '/etc'", "escape moduledir": "moduledir '../x'", - "escape install": "mod 'x', :git => 'g', :install_path => '../../x'", + "escape install": "mod 'x', :git => 'git@h: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'", + "final moduledir": "mod 'a-x', '1'\nmoduledir 'site'\nmod 'x', :git => 'git@h:g', :install_path => 'site'", + "nested": "mod 'a-thing', '1'\nmod 'metadata', :git => 'git@h: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'", + "option ref": "mod 'x', :git => 'git@h:g', :branch => '--output=/tmp/x'", "trailing junk": "mod 'a-b', '1' 'c'", "bad char": "mod 'a-b', '1'; x", } { @@ -102,7 +103,7 @@ 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") + pf, err := ParsePuppetfile("mod 'a-x', '1'\nmoduledir 'site'\nmod 'x', :git => 'git@h:g', :install_path => 'modules'\n") if err != nil { t.Fatal(err) } @@ -110,3 +111,57 @@ func TestParsePuppetfileFinalModuledir(t *testing.T) { t.Fatalf("forge module path %s, want final moduledir", p) } } + +func TestParsePuppetfileTrailingOptionNoPanic(t *testing.T) { + for _, src := range []string{"mod 'x', git:", "mod 'x', :git =>", "mod('x', git:", "mod 'x', git:\n", "mod 'x', :git => ,"} { + func() { + defer func() { + if r := recover(); r != nil { + t.Errorf("ParsePuppetfile(%q) panicked: %v", src, r) + } + }() + if _, err := ParsePuppetfile(src); err == nil { + t.Errorf("ParsePuppetfile(%q) accepted", src) + } + }() + } +} + +func TestParsePuppetfileGitRemoteOnly(t *testing.T) { + for _, g := range []string{"file:///srv/repo", "/srv/repo", "../repo", "repo", "ext::sh -c id", "host:repo", "git@host::x", "https:///x", "ftp://h/x", "git://h/x", "ssh://-oProxyCommand=id/x", "ssh://-oProxyCommand=id@h/x", "-oProxyCommand=id@h:x", "git@-oProxyCommand=id:x"} { + if _, err := ParsePuppetfile("mod 'x', :git => '" + g + "'"); err == nil { + t.Errorf(":git %q accepted", g) + } + } + for _, g := range []string{"https://h/x.git", "http://h:8080/x", "ssh://git@h/x", "git@git.unkin.net:unkin/x.git"} { + if _, err := ParsePuppetfile("mod 'x', :git => '" + g + "'"); err != nil { + t.Errorf(":git %q rejected: %v", g, err) + } + } +} + +func FuzzParsePuppetfile(f *testing.F) { + for _, s := range []string{ + "forge 'forge.puppetlabs.com'\nmoduledir 'external_modules'\n\n# puppetlabs\nmod 'puppetlabs-stdlib', '9.7.0'\nmod 'puppetlabs-yumrepo_core', '2.1.0' # trailing comment\n\nmod 'bind',\n :git => 'https://git.unkin.net/unkinben/puppet-bind.git',\n :tag => '1.0'\n", + "mod \"puppet/systemd\", \"8.1.0\"\nmod 'saz-sudo', :latest\nmod('x',\n git: 'https://example/x.git',\n branch: 'main')\nmod 'z', :git => 'git@h:g', :commit => 'abc123', :install_path => 'site'\n", + "mod 'a-x', '1'\nmoduledir 'site'\nmod 'x', :git => 'git@h:g', :install_path => 'modules'\n", + "mod 'x', git:", + "mod 'x', :git =>", + } { + f.Add(s) + } + f.Fuzz(func(t *testing.T, src string) { + pf, err := ParsePuppetfile(src) + if err != nil { + return + } + for _, m := range pf.Modules { + if p := m.Path(pf); !filepath.IsLocal(p) { + t.Fatalf("module path %q escapes", p) + } + if m.Git != "" && !remoteURL(m.Git) { + t.Fatalf("non-remote :git %q", m.Git) + } + } + }) +}