Merge remote-tracking branch 'origin/benvin/generate-types' into benvin/timings

# Conflicts:
#	internal/deploy/deploy.go
#	internal/deploy/deploy_test.go
#	internal/deploy/git.go
This commit is contained in:
2026-11-08 20:33:44 +11:00
6 changed files with 377 additions and 74 deletions
+1 -1
View File
@@ -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:
+98 -38
View File
@@ -2,6 +2,7 @@ package deploy
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
@@ -13,6 +14,7 @@ import (
"os"
"path/filepath"
"regexp"
"runtime/debug"
"slices"
"sort"
"strconv"
@@ -28,12 +30,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 {
@@ -48,6 +53,7 @@ type Deployer struct {
skips map[string]int
counts map[string]int
Timings *slog.Logger
wtLocks sync.Map
}
type flight struct {
@@ -96,8 +102,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
@@ -131,14 +140,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.
@@ -244,7 +290,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 {
fctx, end := d.phase(ctx, "source.fetch", "source", s.Name)
err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, envRefspecs...)
err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, nil, envRefspecs)
end()
if err != nil {
return err
@@ -269,7 +315,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()
@@ -407,14 +457,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)
}()
}
@@ -430,7 +483,7 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) {
fetched := false
_, err := d.once("fetch:"+mirror, func() (string, error) {
fetched = true
return "", d.syncMirror(pctx, mirror, m.Git, modRefspecs...)
return "", d.syncMirror(pctx, mirror, m.Git, modFetchOpts, modRefspecs)
})
end("cache", cache(!fetched))
if err != nil {
@@ -452,36 +505,35 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) {
pctx, end = d.phase(ctx, "module.resolve", "module", m.Name)
sha, err := d.revParse(pctx, mirror, cands...)
dir := d.path("modules", key, sha)
end("cache", cache(d.Timings != nil && err == nil && present(dir)))
end("cache", cache(d.Timings != nil && err == nil && d.complete(dir)))
if err != nil {
return resolved{}, err
}
pctx, end = d.phase(ctx, "module.worktree", "module", m.Name)
added := false
_, err = d.once("mod:"+dir, func() (string, error) {
if present(dir) {
if d.complete(dir) {
return "", nil
}
added = true
tmp := dir + ".tmp"
if err := d.removeWorktree(pctx, mirror, tmp); err != nil {
return "", err
for _, p := range []string{tmp, dir} {
if err := d.removeWorktree(pctx, mirror, p); err != nil {
return "", err
}
}
if _, err := d.git(pctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil {
return "", err
}
_, err := d.git(pctx, mirror, "worktree", "move", "--", tmp, dir)
return "", err
if _, err := d.git(pctx, mirror, "worktree", "move", "--", tmp, dir); err != nil {
return "", err
}
return "", d.markDone(dir, nil)
})
end("cache", cache(!added))
return resolved{name: m.Name, dir: dir, key: "git " + m.Git + " " + sha, hit: !added}, err
}
func present(p string) bool {
_, err := os.Stat(p)
return err == nil
}
func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (resolved, error) {
slug := m.Owner + "-" + m.Name
version := m.Version
@@ -506,12 +558,15 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso
var dl, ex, wait time.Duration
installed := false
_, err := d.once("forge:"+dir, func() (string, error) {
if present(dir) {
if d.complete(dir) {
return "", nil
}
installed = true
if err := os.RemoveAll(dir); err != nil {
return "", err
}
q := time.Now()
return "", d.limit(ctx, func() error {
if err := d.limit(ctx, func() error {
wait = time.Since(q)
t := time.Now()
var err error
@@ -519,7 +574,10 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso
ex = time.Since(t) - dl
dl += wait
return err
})
}); err != nil {
return "", err
}
return "", d.markDone(dir, nil)
})
if !installed {
dl = time.Since(start)
@@ -615,11 +673,7 @@ func (d *Deployer) prepare(ctx context.Context, s *Source, name, sha, checksum,
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.
@@ -761,6 +815,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
}
@@ -821,9 +881,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 {
+167 -10
View File
@@ -9,6 +9,7 @@ import (
"log/slog"
"net"
"net/http"
"net/http/cgi"
"net/http/httptest"
"os"
"os/exec"
@@ -216,6 +217,8 @@ type fixture struct {
root string
control string
mod string
modDir string
gitURL string
basedir string
cfg *Config
clock time.Time
@@ -245,10 +248,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)
@@ -261,6 +273,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'
@@ -369,7 +390,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")
@@ -532,7 +553,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)
@@ -541,9 +562,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"))
@@ -572,7 +593,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 {
@@ -609,7 +630,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",
})
@@ -860,3 +881,139 @@ func TestTimingsOffEmitsNothing(t *testing.T) {
t.Fatalf("timings off must emit nothing:\n%s", buf.String())
}
}
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")
}
}
func TestConcurrentWorktreeAddsOneMirror(t *testing.T) {
f := newFixture(t)
for i := range 40 {
gitT(t, f.control, "checkout", "-q", "-B", fmt.Sprintf("b%d", i))
commit(t, f.control, map[string]string{"n": fmt.Sprint(i)})
}
d := New(f.cfg, 16, 10*time.Minute)
d.now = func() time.Time { return f.clock }
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
}
+10 -3
View File
@@ -6,7 +6,9 @@ import (
"fmt"
"os"
"os/exec"
"slices"
"strings"
"sync"
"syscall"
"time"
)
@@ -28,8 +30,13 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) {
return strings.TrimSpace(out.String()), nil
}
// git holds a -j slot only for the subprocess itself, so callers never nest slots.
// git holds a -j slot only for the subprocess itself; worktree commands are serialized per repo since concurrent adds read each other's half-written admin dirs.
func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) {
if len(args) > 0 && args[0] == "worktree" {
mu, _ := d.wtLocks.LoadOrStore(dir, &sync.Mutex{})
mu.(*sync.Mutex).Lock()
defer mu.(*sync.Mutex).Unlock()
}
err = d.limit(ctx, func() error {
ctx, cancel := context.WithTimeout(ctx, d.gitTimeout)
defer cancel()
@@ -39,13 +46,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
}
+32 -8
View File
@@ -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":
+69 -14
View File
@@ -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)
}
}
})
}