package deploy import ( "context" "encoding/json" "fmt" "net" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "sync" "testing" "time" ) func mkdirs(t *testing.T, paths ...string) { t.Helper() for _, p := range paths { if err := os.MkdirAll(p, 0o755); err != nil { t.Fatal(err) } } } func TestSwapOverSymlinkAbsolute(t *testing.T) { dir := t.TempDir() a, b := filepath.Join(dir, "cache", "a"), filepath.Join(dir, "cache", "b") mkdirs(t, a, b, filepath.Join(dir, "envs")) link := filepath.Join(dir, "envs", "develop") for _, target := range []string{a, b, b} { if err := Swap(target, link); err != nil { t.Fatal(err) } if got, err := os.Readlink(link); err != nil || got != target { t.Fatalf("link -> %q (%v), want absolute %q", got, err, target) } } if _, err := os.Stat(a); err != nil { t.Fatal("swap must not touch the previous target") } if entries, _ := os.ReadDir(filepath.Dir(link)); len(entries) != 1 { t.Fatalf("leftover temp files: %v", entries) } } func TestSwapDirectoryCutover(t *testing.T) { dir := t.TempDir() target := filepath.Join(dir, "cache", "a") link := filepath.Join(dir, "envs", "develop") mkdirs(t, target, link) if err := os.WriteFile(filepath.Join(link, "site.pp"), []byte("old"), 0o644); err != nil { t.Fatal(err) } if err := Swap(target, link); err != nil { t.Fatal(err) } if got, _ := os.Readlink(link); got != target { t.Fatalf("link -> %q", got) } matches, _ := filepath.Glob(filepath.Join(dir, "envs", ".develop"+asideTag+"*", "site.pp")) if len(matches) != 1 { t.Fatalf("old g10k directory should be moved aside intact, got %v", matches) } } func TestGCGrace(t *testing.T) { root := t.TempDir() cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": {Name: "s", Basedir: filepath.Join(root, "envs")}}} clock := time.Unix(1_700_000_000, 0) gc := func() { d := New(cfg, 1, 10*time.Minute) d.now = func() time.Time { return clock } if err := d.GC(context.Background()); err != nil { t.Fatal(err) } } d := New(cfg, 1, 0) 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(d.doneFile(p), []byte(`{"modules":[]}`), 0o644); err != nil { t.Fatal(err) } } if err := Swap(cur, filepath.Join(cfg.Sources["s"].Basedir, "develop")); err != nil { t.Fatal(err) } gc() if !exists(old) || !exists(aside) { t.Fatal("first sight must only mark") } clock = clock.Add(9 * time.Minute) gc() if !exists(old) || !exists(aside) { t.Fatal("inside grace must keep") } if err := Swap(old, filepath.Join(cfg.Sources["s"].Basedir, "develop")); err != nil { t.Fatal(err) } gc() clock = clock.Add(2 * time.Minute) gc() if !exists(old) || exists(aside) { t.Fatal("re-referenced worktree must be unmarked; aside dir past grace removed") } if !exists(cur) { t.Fatal("newly unreferenced worktree must get a fresh mark, not inherit an old one") } clock = clock.Add(11 * time.Minute) gc() if exists(cur) || !exists(old) { t.Fatal("past grace must remove only the unreferenced worktree") } } func TestLockExcludes(t *testing.T) { d := New(&Config{Cachedir: t.TempDir()}, 1, 0) unlock, err := d.Lock() if err != nil { t.Fatal(err) } got := make(chan struct{}) go func() { u, err := d.Lock() if err == nil { u() } close(got) }() select { case <-got: t.Fatal("second lock acquired while first held") case <-time.After(100 * time.Millisecond): } unlock() select { case <-got: case <-time.After(5 * time.Second): t.Fatal("second lock never acquired") } } func gitT(t *testing.T, dir string, args ...string) string { t.Helper() cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"}, args...)...) cmd.Dir = dir out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git %v: %v\n%s", args, err, out) } return strings.TrimSpace(string(out)) } func commit(t *testing.T, dir string, files map[string]string) string { t.Helper() for p, c := range files { full := filepath.Join(dir, p) if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(full, []byte(c), 0o644); err != nil { t.Fatal(err) } } gitT(t, dir, "add", "-A") gitT(t, dir, "commit", "-q", "-m", "c") return gitT(t, dir, "rev-parse", "HEAD") } func newRepo(t *testing.T, dir string) { t.Helper() if err := os.MkdirAll(dir, 0o755); err != nil { t.Fatal(err) } gitT(t, dir, "init", "-q", "-b", "main") } func readMarker(t *testing.T, env string) deployResult { t.Helper() b, err := os.ReadFile(filepath.Join(env, markerFile)) if err != nil { t.Fatal(err) } var m deployResult if err := json.Unmarshal(b, &m); err != nil { t.Fatal(err) } return m } func exists(p string) bool { _, err := os.Lstat(p) return err == nil } func dirCount(t *testing.T, p string) int { t.Helper() e, err := os.ReadDir(p) if err != nil && !os.IsNotExist(err) { t.Fatal(err) } return len(e) } type fixture struct { t *testing.T root string control string mod string basedir string cfg *Config clock time.Time forgeURL string hit func(string) int } func newFixture(t *testing.T) *fixture { f := &fixture{t: t, root: t.TempDir(), clock: time.Unix(1_700_000_000, 0)} var mu sync.Mutex hits := map[string]int{} forge := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() hits[r.URL.Path]++ mu.Unlock() switch r.URL.Path { case "/v3/modules/acme-latest": _, _ = fmt.Fprint(w, `{"current_release":{"version":"2.0.0"}}`) case "/v3/files/acme-thing-1.0.0.tar.gz", "/v3/files/acme-latest-2.0.0.tar.gz": top := strings.TrimSuffix(filepath.Base(r.URL.Path), ".tar.gz") _, _ = w.Write(tarball(t, entry{name: top + "/metadata.json", body: `{"name":"` + top + `"}`, mode: 0o644})) default: http.NotFound(w, r) } })) t.Cleanup(forge.Close) 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") f.control = filepath.Join(f.root, "control") newRepo(t, f.control) f.basedir = filepath.Join(f.root, "code", "environments") cfg, err := ParseConfig([]byte(fmt.Sprintf("cachedir: %s\nsources:\n unkin:\n remote: %s\n basedir: %s\n", filepath.Join(f.root, "code", "cache"), f.control, f.basedir))) if err != nil { t.Fatal(err) } f.cfg = cfg return f } func (f *fixture) puppetfile() string { return fmt.Sprintf(`forge '%s' moduledir 'external_modules' mod 'acme-thing', '1.0.0' mod 'acme-latest', :latest mod 'bind', :git => '%s', :tag => '1.0' mod 'tracker', :git => '%s', :branch => 'main' `, f.forgeURL, f.mod, f.mod) } func (f *fixture) deployer() *Deployer { d := New(f.cfg, 4, 10*time.Minute) d.now = func() time.Time { return f.clock } return d } func (f *fixture) deploy(modules bool, only ...string) error { return f.deployer().Deploy(context.Background(), only, modules) } func (f *fixture) mustDeploy(modules bool) { f.t.Helper() if err := f.deploy(modules); err != nil { f.t.Fatal(err) } } func (f *fixture) settle() { f.t.Helper() for range 2 { f.clock = f.clock.Add(11 * time.Minute) f.mustDeploy(false) } } func (f *fixture) env(name string) string { return f.deployer().owned(f.cfg.Sources["unkin"], filepath.Join(f.basedir, name)) } 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"}) gitT(t, f.control, "branch", "benvin/foo-bar") f.mustDeploy(false) main1, foo1 := f.env("main"), f.env("benvin_foo_bar") if main1 == "" || main1 != foo1 || !strings.HasPrefix(filepath.Base(main1), sha1+"-") { t.Fatalf("envs not deployed as shared sha worktree: main=%q foo=%q", main1, foo1) } if l, _ := os.Readlink(filepath.Join(f.basedir, "main")); !filepath.IsAbs(l) { t.Fatalf("env link must be absolute: %s", l) } if l, _ := os.Readlink(filepath.Join(main1, "external_modules", "bind")); !filepath.IsAbs(l) { t.Fatalf("module link must be absolute: %s", l) } if m := readMarker(t, main1); m.Signature != sha1 || !m.DeploySuccess || len(m.Modules) != 4 || len(m.PuppetfileChecksum) != 64 || m.GitURL != f.control { t.Fatalf("deploy file %+v", m) } for _, p := range []string{"manifests/site.pp", "external_modules/thing/metadata.json", "external_modules/latest/metadata.json", "external_modules/bind/manifests/init.pp", "external_modules/tracker/manifests/init.pp"} { if _, err := os.Stat(filepath.Join(f.basedir, "main", p)); err != nil { t.Errorf("missing %s: %v", p, err) } } if f.hit("/v3/files/acme-thing-1.0.0.tar.gz") != 1 || f.hit("/v3/modules/acme-latest") != 1 { t.Fatal("forge modules should be fetched once") } if dirCount(t, f.cache("modules", urlKey(f.mod))) != 1 { t.Fatal("tag and branch at the same sha should share one module worktree") } f.mustDeploy(false) if f.env("main") != main1 || f.hit("/v3/files/acme-thing-1.0.0.tar.gz") != 1 || f.hit("/v3/modules/acme-latest") != 1 { t.Fatal("unchanged sha must be a no-op") } sha2 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default { }\n"}) f.mustDeploy(false) main2 := f.env("main") if !strings.HasPrefix(filepath.Base(main2), sha2+"-") || f.env("benvin_foo_bar") != main1 { t.Fatalf("moved branch: main=%s foo=%s", main2, f.env("benvin_foo_bar")) } gitT(t, f.control, "branch", "-D", "benvin/foo-bar") f.mustDeploy(false) if exists(filepath.Join(f.basedir, "benvin_foo_bar")) { t.Fatal("deleted branch must remove the env link") } if !exists(main1) { t.Fatal("worktree must never be deleted in the run that unreferenced it") } f.settle() if exists(main1) || dirCount(t, f.cache("worktrees", "unkin")) != 1 { t.Fatal("unreferenced worktree must be GC'd after grace") } if wl := gitT(t, f.cache("sources", "unkin.git"), "worktree", "list"); strings.Contains(wl, filepath.Base(main1)) { t.Fatalf("worktree not pruned:\n%s", wl) } commit(t, f.mod, 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") } f.mustDeploy(true) main3 := f.env("main") if main3 == main2 { t.Fatal("--modules should rebuild when a module ref moved") } f.settle() if exists(main2) || dirCount(t, f.cache("modules", urlKey(f.mod))) != 2 { t.Fatal("old env GC'd; bind (tag) and tracker (moved branch) are distinct module worktrees") } 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.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.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") } if err := f.deploy(false, "nope"); err == nil || !strings.Contains(err.Error(), "nope not found") { t.Fatalf("unknown env: %v", err) } if !exists(filepath.Join(f.basedir, "main")) { t.Fatal("filtered deploy must not purge other envs") } commit(t, f.control, map[string]string{"Puppetfile": "mod 'broken', :svn => 'x'\n"}) if err := f.deploy(false); err == nil { t.Fatal("bad Puppetfile must fail") } if f.env("main") == "" || !exists(f.env("main")) { t.Fatal("failed build must leave the live env untouched") } } func TestInFlightCompileSurvivesSwap(t *testing.T) { f := newFixture(t) commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"}) f.mustDeploy(false) resolved, err := os.Readlink(filepath.Join(f.basedir, "main")) if err != nil { t.Fatal(err) } var files []string var walk func(string) walk = func(dir string) { entries, err := os.ReadDir(dir) if err != nil { t.Fatal(err) } for _, e := range entries { p := filepath.Join(dir, e.Name()) if fi, err := os.Stat(p); err == nil && fi.IsDir() { walk(p) } else if e.Name() != ".git" { files = append(files, p) } } } walk(resolved) joined := strings.Join(files, "\n") for _, want := range []string{"manifests/site.pp", "external_modules/bind/manifests/init.pp", "external_modules/thing/metadata.json", markerFile} { if !strings.Contains(joined, filepath.Join(resolved, want)) { t.Fatalf("walk missed %s in:\n%s", want, joined) } } commit(t, f.control, map[string]string{"Puppetfile": "", "manifests/site.pp": "node default { }\n"}) f.clock = f.clock.Add(time.Minute) f.mustDeploy(false) if f.env("main") == resolved { t.Fatal("branch move must swap the env") } f.clock = f.clock.Add(8 * time.Minute) f.mustDeploy(false) for _, p := range files { if _, err := os.ReadFile(p); err != nil { t.Fatalf("in-flight compile lost %s: %v", p, err) } } f.clock = f.clock.Add(3 * time.Minute) f.mustDeploy(false) if exists(resolved) { 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) } } 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) } }