From fc5d90b6841323c33309e90d0595c9093ee028f9 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 17:37:47 +1100 Subject: [PATCH 01/11] Add w10k: deploy Puppet environments as sha-pinned git worktrees --- .gitignore | 4 + .pre-commit-config.yaml | 30 ++ .woodpecker/build.yaml | 18 + .woodpecker/lint.yaml | 18 + .woodpecker/pre-commit.yaml | 18 + .woodpecker/release.yaml | 125 ++++++ .woodpecker/test.yaml | 18 + Makefile | 57 +++ README.md | 2 +- go.mod | 13 + go.sum | 13 + internal/deploy/config.go | 135 ++++++ internal/deploy/config_test.go | 100 +++++ internal/deploy/deploy.go | 642 +++++++++++++++++++++++++++++ internal/deploy/deploy_test.go | 457 ++++++++++++++++++++ internal/deploy/forge.go | 141 +++++++ internal/deploy/forge_test.go | 96 +++++ internal/deploy/git.go | 62 +++ internal/deploy/puppetfile.go | 310 ++++++++++++++ internal/deploy/puppetfile_test.go | 98 +++++ main.go | 119 ++++++ packaging/nfpm.yaml | 31 ++ scripts/build-rpm.sh | 31 ++ 23 files changed, 2537 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 .woodpecker/build.yaml create mode 100644 .woodpecker/lint.yaml create mode 100644 .woodpecker/pre-commit.yaml create mode 100644 .woodpecker/release.yaml create mode 100644 .woodpecker/test.yaml create mode 100644 Makefile create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/deploy/config.go create mode 100644 internal/deploy/config_test.go create mode 100644 internal/deploy/deploy.go create mode 100644 internal/deploy/deploy_test.go create mode 100644 internal/deploy/forge.go create mode 100644 internal/deploy/forge_test.go create mode 100644 internal/deploy/git.go create mode 100644 internal/deploy/puppetfile.go create mode 100644 internal/deploy/puppetfile_test.go create mode 100644 main.go create mode 100644 packaging/nfpm.yaml create mode 100755 scripts/build-rpm.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6fde1e4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/w10k +/w10k-* +dist/ +sha256sums.txt diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..24236dd --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,30 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-merge-conflict + - id: mixed-line-ending + args: [--fix=lf] + + - repo: https://github.com/dnephin/pre-commit-golang + rev: v0.5.1 + hooks: + - id: go-fmt + + - repo: local + hooks: + - id: go-vet-mod + name: go vet (module) + entry: go vet ./... + language: system + types: [go] + pass_filenames: false + - id: go-test-mod + name: go test (module) + entry: go test ./... + language: system + types: [go] + pass_filenames: false diff --git a/.woodpecker/build.yaml b/.woodpecker/build.yaml new file mode 100644 index 0000000..74123b5 --- /dev/null +++ b/.woodpecker/build.yaml @@ -0,0 +1,18 @@ +when: + - event: pull_request + +steps: + - name: build + image: golang:1.25 + commands: + - make build + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 diff --git a/.woodpecker/lint.yaml b/.woodpecker/lint.yaml new file mode 100644 index 0000000..e842a70 --- /dev/null +++ b/.woodpecker/lint.yaml @@ -0,0 +1,18 @@ +when: + - event: pull_request + +steps: + - name: lint + image: golangci/golangci-lint:latest + commands: + - golangci-lint run ./... + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 diff --git a/.woodpecker/pre-commit.yaml b/.woodpecker/pre-commit.yaml new file mode 100644 index 0000000..d57b508 --- /dev/null +++ b/.woodpecker/pre-commit.yaml @@ -0,0 +1,18 @@ +when: + - event: pull_request + +steps: + - name: pre-commit + image: git.unkin.net/unkin/almalinux9-gobuilder:20260606 + commands: + - uvx pre-commit run --all-files + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 diff --git a/.woodpecker/release.yaml b/.woodpecker/release.yaml new file mode 100644 index 0000000..00a41fd --- /dev/null +++ b/.woodpecker/release.yaml @@ -0,0 +1,125 @@ +when: + - event: tag + ref: refs/tags/v* + +steps: + - name: test + image: golang:1.25 + commands: + - go test -race ./... + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 + + - name: build + image: git.unkin.net/unkin/almalinux9-gobuilder:20260606 + commands: + - make build VERSION=${CI_COMMIT_TAG} + - | + for osarch in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64; do + os="$${osarch%/*}"; arch="$${osarch#*/}" + CGO_ENABLED=0 GOOS="$$os" GOARCH="$$arch" \ + go build -ldflags="-s -w -X main.version=${CI_COMMIT_TAG}" \ + -o "w10k-$${os}-$${arch}" . + done + depends_on: [test] + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 + + - name: package + image: git.unkin.net/unkin/almalinux9-rpmbuilder:latest + commands: + - ./scripts/build-rpm.sh ${CI_COMMIT_TAG} + depends_on: [build] + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 + + - name: upload-rpm + image: git.unkin.net/unkin/almalinux9-base:20260606 + commands: + - | + HOST="https://artifactapi.k8s.syd1.au.unkin.net" + REPO="rpm-internal" + for rpm in dist/*.rpm; do + FILE=$$(basename "$$rpm") + code=$$(curl -s -o /dev/null -w '%{http_code}' "$$HOST/api/v2/remotes/$$REPO/files/Packages/$$FILE" || true) + if [ "$$code" = "200" ]; then + echo "$$FILE already in $$REPO; skipping" + continue + fi + curl -f -X PUT "$$HOST/api/v2/remotes/$$REPO/files/$$FILE" \ + -H "Content-Type: application/x-rpm" --data-binary @"$$rpm" + done + depends_on: [package] + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 128Mi + cpu: 100m + limits: + memory: 512Mi + cpu: 500m + + - name: release + image: git.unkin.net/unkin/almalinux9-base:20260606 + environment: + RELEASER_TOKEN: + from_secret: RELEASER_TOKEN + commands: + - | + curl --output /usr/local/bin/tea https://artifactapi.k8s.syd1.au.unkin.net/api/v1/remote/gitea-dl/tea/0.12.0/tea-0.12.0-linux-amd64 && chmod +x /usr/local/bin/tea + tea logins add --name gitea --url https://git.unkin.net --token "$${RELEASER_TOKEN}" --no-version-check + CUR_SHA=$$(git rev-list -n1 "${CI_COMMIT_TAG}") + PREV_TAG="" + for t in $$(git tag --sort=-v:refname); do + [ "$$t" = "${CI_COMMIT_TAG}" ] && continue + [ "$$(git rev-list -n1 "$$t")" = "$$CUR_SHA" ] && continue + if git merge-base --is-ancestor "$$t" "${CI_COMMIT_TAG}" 2>/dev/null; then + PREV_TAG="$$t"; break + fi + done + if [ -n "$$PREV_TAG" ]; then + NOTES=$$(git log "$${PREV_TAG}..${CI_COMMIT_TAG}" --pretty=format:"- %s") + else + NOTES=$$(git log --pretty=format:"- %s") + fi + tea releases create --tag "${CI_COMMIT_TAG}" --title "${CI_COMMIT_TAG}" --note "$${NOTES}" --login gitea --repo "${CI_REPO}" + ASSETS="w10k-linux-amd64 w10k-linux-arm64 w10k-darwin-amd64 w10k-darwin-arm64 $$(ls dist/*.rpm)" + sha256sum $$ASSETS > sha256sums.txt + tea releases assets create "${CI_COMMIT_TAG}" $$ASSETS sha256sums.txt --login gitea --repo "${CI_REPO}" + depends_on: [upload-rpm] + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 128Mi + cpu: 100m + limits: + memory: 512Mi + cpu: 500m diff --git a/.woodpecker/test.yaml b/.woodpecker/test.yaml new file mode 100644 index 0000000..32c0e9a --- /dev/null +++ b/.woodpecker/test.yaml @@ -0,0 +1,18 @@ +when: + - event: pull_request + +steps: + - name: test + image: golang:1.25 + commands: + - go test -v -race ./... + backend_options: + kubernetes: + serviceAccountName: default + resources: + requests: + memory: 512Mi + cpu: 1 + limits: + memory: 2Gi + cpu: 2 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..601b4f2 --- /dev/null +++ b/Makefile @@ -0,0 +1,57 @@ +BINARY := w10k +DIST := dist +VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) +GOFLAGS := -ldflags="-s -w -X main.version=$(VERSION)" +OS ?= $(shell go env GOOS) +ARCH ?= $(shell go env GOARCH) + +.PHONY: all build test lint fmt pre-commit clean install rpm rpm-package patch minor major _tag + +all: build + +build: + CGO_ENABLED=0 GOOS=$(OS) GOARCH=$(ARCH) go build $(GOFLAGS) -o $(DIST)/$(BINARY) . + +test: + go test -v -race ./... + +lint: + golangci-lint run ./... + +fmt: + gofmt -w . + +pre-commit: + uvx pre-commit run --all-files + +clean: + rm -rf $(DIST) $(BINARY) + +install: + go install $(GOFLAGS) . + +rpm: build rpm-package + +rpm-package: + ./scripts/build-rpm.sh $(VERSION) + +_LATEST := $(shell git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1) +_BASE := $(if $(_LATEST),$(_LATEST),v0.0.0) +_MAJ := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f1) +_MIN := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f2) +_PAT := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f3) + +patch: + @NEW=v$(_MAJ).$(_MIN).$(shell expr $(_PAT) + 1); \ + git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW + +minor: + @NEW=v$(_MAJ).$(shell expr $(_MIN) + 1).0; \ + git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW + +major: + @NEW=v$(shell expr $(_MAJ) + 1).0.0; \ + git tag $$NEW && echo "Tagged $$NEW" && $(MAKE) _tag TAG=$$NEW + +_tag: + git push origin $(TAG) diff --git a/README.md b/README.md index 863d1df..141e2af 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ # w10k -worktree-r10k: r10k/g10k replacement deploying Puppet environments and Puppetfile modules as sha-pinned git worktrees \ No newline at end of file +worktree-r10k: r10k/g10k replacement deploying Puppet environments and Puppetfile modules as sha-pinned git worktrees diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..22f5faf --- /dev/null +++ b/go.mod @@ -0,0 +1,13 @@ +module git.unkin.net/unkin/w10k + +go 1.25.7 + +require ( + github.com/spf13/cobra v1.10.2 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/spf13/pflag v1.0.9 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..47edb24 --- /dev/null +++ b/go.sum @@ -0,0 +1,13 @@ +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/deploy/config.go b/internal/deploy/config.go new file mode 100644 index 0000000..20e9636 --- /dev/null +++ b/internal/deploy/config.go @@ -0,0 +1,135 @@ +package deploy + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "gopkg.in/yaml.v3" +) + +type Config struct { + Cachedir string `yaml:"cachedir"` + Sources map[string]*Source `yaml:"sources"` + W10k struct { + GCGrace *time.Duration `yaml:"gc_grace"` + } `yaml:"w10k"` +} + +type Source struct { + Name string `yaml:"-"` + Remote string `yaml:"remote"` + Basedir string `yaml:"basedir"` + PrefixRaw any `yaml:"prefix"` + IgnoreBranchPrefixes []string `yaml:"ignore_branch_prefixes"` + InvalidBranches string `yaml:"invalid_branches"` + Prefix string `yaml:"-"` +} + +func LoadConfig(path string) (*Config, error) { + b, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return ParseConfig(b) +} + +func ParseConfig(b []byte) (*Config, error) { + var n yaml.Node + if err := yaml.Unmarshal(b, &n); err != nil { + return nil, err + } + stripSymbols(&n) + var c Config + if err := n.Decode(&c); err != nil { + return nil, err + } + if c.Cachedir == "" { + return nil, fmt.Errorf("cachedir is required") + } + if c.W10k.GCGrace != nil && *c.W10k.GCGrace < 0 { + return nil, fmt.Errorf("w10k.gc_grace must not be negative") + } + if len(c.Sources) == 0 { + return nil, fmt.Errorf("no sources defined") + } + var err error + if c.Cachedir, err = filepath.Abs(c.Cachedir); err != nil { + return nil, err + } + for name, s := range c.Sources { + if !wordOnly.MatchString(name) { + return nil, fmt.Errorf("source %q: name must match \\w+", name) + } + s.Name = name + if s.Remote == "" || s.Basedir == "" { + return nil, fmt.Errorf("source %q: remote and basedir are required", name) + } + if s.Basedir, err = filepath.Abs(s.Basedir); err != nil { + return nil, err + } + switch p := s.PrefixRaw.(type) { + case nil: + case bool: + if p { + s.Prefix = name + } + case string: + s.Prefix = p + default: + return nil, fmt.Errorf("source %q: prefix must be a bool or string", name) + } + s.InvalidBranches = strings.TrimPrefix(s.InvalidBranches, ":") + switch s.InvalidBranches { + case "": + s.InvalidBranches = "correct_and_warn" + case "correct_and_warn", "correct", "error": + default: + return nil, fmt.Errorf("source %q: invalid_branches must be correct_and_warn, correct or error", name) + } + } + return &c, nil +} + +func stripSymbols(n *yaml.Node) { + if n.Kind == yaml.MappingNode { + for i := 0; i < len(n.Content); i += 2 { + n.Content[i].Value = strings.TrimPrefix(n.Content[i].Value, ":") + } + } + for _, c := range n.Content { + stripSymbols(c) + } +} + +var ( + wordOnly = regexp.MustCompile(`^\w+$`) + nonWord = regexp.MustCompile(`\W`) +) + +func (s *Source) Ignored(branch string) bool { + for _, p := range s.IgnoreBranchPrefixes { + if strings.HasPrefix(branch, p) { + return true + } + } + return false +} + +// EnvName applies prefix and invalid_branches handling; corrected reports a \W substitution. +func (s *Source) EnvName(branch string) (name string, corrected bool, err error) { + name = branch + if s.Prefix != "" { + name = s.Prefix + "_" + branch + } + if wordOnly.MatchString(name) { + return name, false, nil + } + if s.InvalidBranches == "error" { + return "", false, fmt.Errorf("branch %q is not a valid environment name", branch) + } + return nonWord.ReplaceAllString(name, "_"), true, nil +} diff --git a/internal/deploy/config_test.go b/internal/deploy/config_test.go new file mode 100644 index 0000000..20ebe34 --- /dev/null +++ b/internal/deploy/config_test.go @@ -0,0 +1,100 @@ +package deploy + +import "testing" + +func TestParseConfigSymbolKeys(t *testing.T) { + c, err := ParseConfig([]byte(` +:cachedir: '/var/cache/w10k' +:sources: + :unkin: + remote: 'https://git.unkin.net/unkin/puppet-prod.git' + basedir: '/etc/puppetlabs/code/environments' +`)) + if err != nil { + t.Fatal(err) + } + s := c.Sources["unkin"] + if c.Cachedir != "/var/cache/w10k" || s == nil || s.Name != "unkin" || s.Remote != "https://git.unkin.net/unkin/puppet-prod.git" || s.Basedir != "/etc/puppetlabs/code/environments" { + t.Fatalf("unexpected config %+v %+v", c, s) + } + if s.Prefix != "" || s.InvalidBranches != "correct_and_warn" { + t.Fatalf("defaults wrong: %+v", s) + } +} + +func TestParseConfigOptions(t *testing.T) { + c, err := ParseConfig([]byte(` +cachedir: /c +sources: + a: + remote: r + basedir: /a + prefix: true + ignore_branch_prefixes: [wip/, tmp] + invalid_branches: ':error' + b: + remote: r + basedir: /b + prefix: custom + invalid_branches: correct +`)) + if err != nil { + t.Fatal(err) + } + a, b := c.Sources["a"], c.Sources["b"] + if a.Prefix != "a" || a.InvalidBranches != "error" || len(a.IgnoreBranchPrefixes) != 2 { + t.Fatalf("a: %+v", a) + } + if b.Prefix != "custom" || b.InvalidBranches != "correct" { + t.Fatalf("b: %+v", b) + } +} + +func TestParseConfigErrors(t *testing.T) { + for name, in := range map[string]string{ + "no cachedir": "sources: {a: {remote: r, basedir: /b}}", + "no sources": "cachedir: /c", + "no remote": "cachedir: /c\nsources: {a: {basedir: /b}}", + "bad prefix": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, prefix: [x]}}", + "bad invalid": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, invalid_branches: nope}}", + "bad source name": "cachedir: /c\nsources: {a-b: {remote: r, basedir: /b}}", + } { + if _, err := ParseConfig([]byte(in)); err == nil { + t.Errorf("%s: expected error", name) + } + } +} + +func TestEnvName(t *testing.T) { + cases := []struct { + src Source + branch string + want string + corrected bool + err bool + }{ + {Source{InvalidBranches: "correct_and_warn"}, "develop", "develop", false, false}, + {Source{InvalidBranches: "correct_and_warn"}, "benvin/foo-bar", "benvin_foo_bar", true, false}, + {Source{InvalidBranches: "correct_and_warn"}, "release/1.2.3", "release_1_2_3", true, false}, + {Source{InvalidBranches: "correct"}, "a.b", "a_b", true, false}, + {Source{InvalidBranches: "error"}, "benvin/foo", "", false, true}, + {Source{InvalidBranches: "error"}, "ok_name", "ok_name", false, false}, + {Source{Prefix: "unkin", InvalidBranches: "correct_and_warn"}, "develop", "unkin_develop", false, false}, + {Source{Prefix: "unkin", InvalidBranches: "correct_and_warn"}, "a/b", "unkin_a_b", true, false}, + } + for _, c := range cases { + got, corrected, err := c.src.EnvName(c.branch) + if (err != nil) != c.err || got != c.want || corrected != c.corrected { + t.Errorf("EnvName(%q, %+v) = %q, %v, %v; want %q, %v, err=%v", c.branch, c.src, got, corrected, err, c.want, c.corrected, c.err) + } + } +} + +func TestIgnored(t *testing.T) { + s := Source{IgnoreBranchPrefixes: []string{"wip/", "tmp"}} + for b, want := range map[string]bool{"wip/x": true, "tmpfoo": true, "develop": false, "x/wip/": false} { + if s.Ignored(b) != want { + t.Errorf("Ignored(%q) != %v", b, want) + } + } +} diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go new file mode 100644 index 0000000..ad4d372 --- /dev/null +++ b/internal/deploy/deploy.go @@ -0,0 +1,642 @@ +package deploy + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "sync" + "syscall" + "time" +) + +const ( + markerFile = ".g10k-deploy.json" + gcStateFile = "gc-state.json" + asideTag = ".w10k-old-" +) + +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._-]`) +) + +type Deployer struct { + cfg *Config + grace time.Duration + now func() time.Time + sem chan struct{} + mu sync.Mutex + flights map[string]*flight +} + +type flight struct { + done chan struct{} + val string + err error +} + +type deployResult struct { + Name string `json:"name"` + Signature string `json:"signature"` + StartedAt time.Time `json:"started_at"` + FinishedAt time.Time `json:"finished_at"` + DeploySuccess bool `json:"deploy_success"` + PuppetfileChecksum string `json:"puppetfile_checksum"` + GitDir string `json:"git_dir"` + GitURL string `json:"git_url"` + Modules []string `json:"modules"` +} + +type resolved struct { + path string + dir string + key string +} + +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{}} +} + +func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { + d.mu.Lock() + f, ok := d.flights[key] + if !ok { + f = &flight{done: make(chan struct{})} + d.flights[key] = f + } + d.mu.Unlock() + if !ok { + f.val, f.err = fn() + close(f.done) + } + <-f.done + return f.val, f.err +} + +func (d *Deployer) limit(fn func() error) error { + d.sem <- struct{}{} + defer func() { <-d.sem }() + return fn() +} + +func (d *Deployer) path(parts ...string) string { + return filepath.Join(append([]string{d.cfg.Cachedir}, parts...)...) +} + +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, "_") } + +// Lock takes an exclusive flock on the cachedir, released by the returned func. +func (d *Deployer) Lock() (func(), error) { + if err := os.MkdirAll(d.cfg.Cachedir, 0o755); err != nil { + return nil, err + } + f, err := os.OpenFile(d.path(".lock"), os.O_CREATE|os.O_RDWR, 0o644) + if err != nil { + return nil, err + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { + _ = f.Close() + return nil, err + } + return func() { _ = f.Close() }, nil +} + +func (d *Deployer) Sources() []*Source { + var out []*Source + for _, s := range d.cfg.Sources { + out = append(out, s) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} + +func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error { + want := map[string]bool{} + for _, e := range only { + want[e] = true + } + var errs []error + for _, s := range d.Sources() { + if err := d.deploySource(ctx, s, want, modules); err != nil { + errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err)) + } + } + for e := range want { + errs = append(errs, fmt.Errorf("environment %s not found", e)) + } + if err := d.GC(ctx); err != nil { + errs = append(errs, err) + } + return errors.Join(errs...) +} + +func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]string, []error) { + all, err := branches(ctx, d.srcMirror(s)) + if err != nil { + return nil, []error{err} + } + names := make([]string, 0, len(all)) + for b := range all { + names = append(names, b) + } + sort.Strings(names) + envs := map[string]string{} + var errs []error + for _, b := range names { + if s.Ignored(b) { + continue + } + name, corrected, err := s.EnvName(b) + if err != nil { + errs = append(errs, err) + continue + } + if corrected && s.InvalidBranches == "correct_and_warn" { + log.Printf("warning: branch %s deployed as environment %s", b, name) + } + if _, dup := envs[name]; dup { + errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + continue + } + envs[name] = all[b] + } + return envs, errs +} + +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 { + return err + } + envs, errs := d.Environments(ctx, s) + if envs == nil { + return errors.Join(errs...) + } + full := len(want) == 0 + if err := os.MkdirAll(s.Basedir, 0o755); err != nil { + return err + } + var mu sync.Mutex + var wg sync.WaitGroup + for name, sha := range envs { + if !full && !want[name] { + continue + } + delete(want, name) + wg.Add(1) + go func() { + defer wg.Done() + if err := d.deployEnv(ctx, s, name, sha, modules); err != nil { + mu.Lock() + errs = append(errs, fmt.Errorf("environment %s: %w", name, err)) + mu.Unlock() + } + }() + } + wg.Wait() + if full { + errs = append(errs, d.purge(s, envs)) + } + return errors.Join(errs...) +} + +func (d *Deployer) owned(s *Source, link string) string { + t, err := os.Readlink(link) + if err != nil { + return "" + } + if !filepath.IsAbs(t) { + t = filepath.Join(filepath.Dir(link), t) + } + t = filepath.Clean(t) + if filepath.Dir(t) != d.srcWorktrees(s) { + return "" + } + 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) { + return nil + } + pf, checksum, err := d.puppetfile(ctx, d.srcMirror(s), sha) + if err != nil { + return err + } + mods, err := d.installModules(ctx, pf) + if err != nil { + return err + } + h := sha256.New() + for _, m := range mods { + _, _ = 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) { + return nil + } + if _, err := d.once("env:"+target, func() (string, error) { + if complete(target) { + return "", nil + } + started := d.now().UTC() + if err := d.checkout(ctx, s, sha, target, mods); err != nil { + return "", err + } + return "", d.prepare(s, name, sha, checksum, target, mods, started) + }); err != nil { + return err + } + if err := Swap(target, link); err != nil { + return err + } + log.Printf("environment %s -> %s", name, filepath.Base(target)) + return nil +} + +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 { + return &Puppetfile{Moduledir: "modules"}, "", nil + } + src, err := git(ctx, mirror, "cat-file", "blob", sha+":Puppetfile") + if err != nil { + return nil, "", err + } + pf, err := ParsePuppetfile(src) + if err != nil { + return nil, "", fmt.Errorf("puppetfile: %w", err) + } + sum := sha256.Sum256([]byte(src)) + return pf, hex.EncodeToString(sum[:]), nil +} + +func (d *Deployer) installModules(ctx context.Context, pf *Puppetfile) ([]resolved, error) { + out := make([]resolved, len(pf.Modules)) + errs := make([]error, len(pf.Modules)) + var wg sync.WaitGroup + for i, m := range pf.Modules { + wg.Add(1) + go func() { + defer wg.Done() + var err error + 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) + }() + } + wg.Wait() + sort.Slice(out, func(i, j int) bool { return out[i].path < out[j].path }) + return out, errors.Join(errs...) +} + +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...) }) + }); err != nil { + return resolved{}, err + } + var cands []string + switch m.RefKind { + case "tag": + cands = []string{"refs/tags/" + m.Ref} + case "branch": + cands = []string{"refs/heads/" + m.Ref} + case "commit": + cands = []string{m.Ref} + case "ref": + cands = []string{"refs/heads/" + m.Ref, "refs/tags/" + m.Ref, m.Ref} + default: + cands = []string{"refs/w10k/HEAD"} + } + sha, err := revParse(ctx, mirror, cands...) + if err != nil { + return resolved{}, err + } + dir := d.path("modules", key, sha) + _, err = d.once("mod:"+dir, func() (string, 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 + }) + }) + return resolved{dir: dir, key: "git " + m.Git + " " + sha}, err +} + +func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (resolved, error) { + slug := m.Owner + "-" + m.Name + version := m.Version + if version == "" { + v, err := d.once("latest:"+slug, func() (string, error) { return forgeLatest(ctx, base, slug) }) + if err != nil { + return resolved{}, err + } + version = v + } + release := slug + "-" + version + dir := d.path("forge", release) + _, err := d.once("forge:"+release, 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 +} + +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 { + 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 { + 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 { + return err + } + } + return nil +} + +// prepare runs last before a worktree can be swapped in; the deploy file it writes 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, + Signature: sha, + StartedAt: started, + FinishedAt: d.now().UTC(), + DeploySuccess: true, + PuppetfileChecksum: checksum, + GitDir: d.srcMirror(s), + GitURL: s.Remote, + Modules: []string{}, + } + for _, m := range mods { + r.Modules = append(r.Modules, m.dir) + } + b, err := json.MarshalIndent(r, "", " ") + if err != nil { + return err + } + tmp := filepath.Join(target, markerFile+".tmp") + if err := os.WriteFile(tmp, append(b, '\n'), 0o644); err != nil { + return err + } + return os.Rename(tmp, filepath.Join(target, markerFile)) +} + +// Swap points link at target via a temporary symlink renamed over it; a real directory is moved aside for GC. +func Swap(target, link string) error { + dir, base := filepath.Dir(link), filepath.Base(link) + tmp := filepath.Join(dir, "."+base+".w10k") + _ = os.Remove(tmp) + if err := os.Symlink(target, tmp); err != nil { + return err + } + if fi, err := os.Lstat(link); err == nil && fi.IsDir() { + aside := filepath.Join(dir, fmt.Sprintf(".%s%s%d", base, asideTag, time.Now().UnixNano())) + if err := os.Rename(link, aside); err != nil { + return err + } + } + return os.Rename(tmp, link) +} + +func (d *Deployer) purge(s *Source, envs map[string]string) error { + entries, err := os.ReadDir(s.Basedir) + if err != nil { + return err + } + for _, e := range entries { + if _, ok := envs[e.Name()]; ok { + continue + } + link := filepath.Join(s.Basedir, e.Name()) + if d.owned(s, link) == "" { + continue + } + if err := os.Remove(link); err != nil { + return err + } + log.Printf("environment %s removed", e.Name()) + } + return nil +} + +// Live returns env name -> worktree for every environment symlink owned by s. +func (d *Deployer) Live(s *Source) (map[string]string, error) { + entries, err := os.ReadDir(s.Basedir) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + live := map[string]string{} + for _, e := range entries { + if t := d.owned(s, filepath.Join(s.Basedir, e.Name())); t != "" { + live[e.Name()] = t + } + } + return live, nil +} + +type gcRun struct { + d *Deployer + ctx context.Context + marks map[string]time.Time + seen map[string]bool + errs []error +} + +// collect marks p on first sight and removes it only once a previous run's mark is older than the grace period. +func (g *gcRun) collect(p string, remove func() error) { + g.seen[p] = true + t, ok := g.marks[p] + if !ok { + g.marks[p] = g.d.now() + log.Printf("gc: marked %s", p) + return + } + if g.d.now().Sub(t) < g.d.grace { + return + } + if err := remove(); err != nil { + g.errs = append(g.errs, err) + return + } + delete(g.marks, p) + log.Printf("gc: removed %s", p) +} + +func (g *gcRun) sweep(mirror, dir string, live map[string]bool) { + entries, err := os.ReadDir(dir) + if err != nil { + if !os.IsNotExist(err) { + g.errs = append(g.errs, err) + } + return + } + for _, e := range entries { + p := filepath.Join(dir, e.Name()) + if live[p] { + continue + } + g.collect(p, func() error { + if mirror == "" { + return os.RemoveAll(p) + } + return removeWorktree(g.ctx, mirror, p) + }) + } + if mirror != "" { + if _, err := os.Stat(mirror); err == nil { + if _, err := git(g.ctx, mirror, "worktree", "prune"); err != nil { + g.errs = append(g.errs, err) + } + } + } +} + +func (d *Deployer) GC(ctx context.Context) error { + g := &gcRun{d: d, ctx: ctx, marks: map[string]time.Time{}, seen: map[string]bool{}} + statePath := d.path(gcStateFile) + if b, err := os.ReadFile(statePath); err == nil { + if err := json.Unmarshal(b, &g.marks); err != nil { + return fmt.Errorf("gc: %s: %w", statePath, err) + } + } else if !os.IsNotExist(err) { + return err + } + + liveEnv := map[string]bool{} + for _, s := range d.Sources() { + live, err := d.Live(s) + if err != nil { + return fmt.Errorf("gc: %w", err) + } + for _, t := range live { + liveEnv[t] = true + } + g.sweep(d.srcMirror(s), d.srcWorktrees(s), liveEnv) + 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) { + g.collect(p, func() error { return os.RemoveAll(p) }) + } + } + } + + liveMod, err := d.moduleRefs(liveEnv) + if err != nil { + g.errs = append(g.errs, err) + for p := range g.marks { + g.seen[p] = true + } + } 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) + } + g.sweep("", d.path("forge"), liveMod) + } + + for p := range g.marks { + if !g.seen[p] { + delete(g.marks, p) + } + } + b, err := json.MarshalIndent(g.marks, "", " ") + if err == nil { + tmp := statePath + ".tmp" + if err = os.WriteFile(tmp, b, 0o644); err == nil { + err = os.Rename(tmp, statePath) + } + } + return errors.Join(append(g.errs, err)...) +} + +// moduleRefs returns every module dir referenced by an env worktree still on disk, live or awaiting GC. +func (d *Deployer) moduleRefs(liveEnv map[string]bool) (map[string]bool, error) { + refs := map[string]bool{} + for _, s := range d.Sources() { + entries, err := os.ReadDir(d.srcWorktrees(s)) + if os.IsNotExist(err) { + continue + } + if err != nil { + return nil, err + } + for _, e := range entries { + p := filepath.Join(d.srcWorktrees(s), e.Name()) + b, err := os.ReadFile(filepath.Join(p, markerFile)) + if os.IsNotExist(err) && !liveEnv[p] { + continue + } + var r deployResult + if err == nil { + err = json.Unmarshal(b, &r) + } + if err != nil { + return nil, fmt.Errorf("gc: module refs of %s: %w", p, err) + } + for _, m := range r.Modules { + refs[m] = true + } + } + } + return refs, nil +} diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go new file mode 100644 index 0000000..58e30d6 --- /dev/null +++ b/internal/deploy/deploy_test.go @@ -0,0 +1,457 @@ +package deploy + +import ( + "context" + "encoding/json" + "fmt" + "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) + for _, p := range []string{old, cur} { + if err := os.WriteFile(filepath.Join(p, markerFile), []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 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.cache("forge", "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")) { + 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") + } +} diff --git a/internal/deploy/forge.go b/internal/deploy/forge.go new file mode 100644 index 0000000..9e1d259 --- /dev/null +++ b/internal/deploy/forge.go @@ -0,0 +1,141 @@ +package deploy + +import ( + "archive/tar" + "compress/gzip" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +const defaultForge = "https://forgeapi.puppet.com" + +var httpClient = &http.Client{Timeout: 5 * time.Minute} + +func forgeURL(s string) string { + switch strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://"), "/") { + case "", "forge.puppetlabs.com", "forge.puppet.com", "forgeapi.puppetlabs.com", "forgeapi.puppet.com": + return defaultForge + } + if !strings.Contains(s, "://") { + s = "https://" + s + } + return strings.TrimSuffix(s, "/") +} + +func forgeGet(ctx context.Context, url string) (io.ReadCloser, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "w10k") + resp, err := httpClient.Do(req) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + _ = resp.Body.Close() + return nil, fmt.Errorf("GET %s: %s", url, resp.Status) + } + return resp.Body, nil +} + +func forgeLatest(ctx context.Context, base, slug string) (string, error) { + body, err := forgeGet(ctx, base+"/v3/modules/"+slug) + if err != nil { + return "", err + } + defer func() { _ = body.Close() }() + var r struct { + CurrentRelease struct { + Version string `json:"version"` + } `json:"current_release"` + } + if err := json.NewDecoder(body).Decode(&r); err != nil { + return "", fmt.Errorf("%s: %w", slug, err) + } + if !versionStr.MatchString(r.CurrentRelease.Version) { + return "", fmt.Errorf("%s: forge returned no usable current_release", slug) + } + return r.CurrentRelease.Version, nil +} + +func forgeInstall(ctx context.Context, base, release, dir string) error { + body, err := forgeGet(ctx, base+"/v3/files/"+release+".tar.gz") + if err != nil { + return err + } + defer func() { _ = body.Close() }() + if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { + return err + } + tmp, err := os.MkdirTemp(filepath.Dir(dir), ".tmp-") + if err != nil { + return err + } + if err := extract(body, tmp); err != nil { + _ = os.RemoveAll(tmp) + return fmt.Errorf("%s: %w", release, err) + } + return os.Rename(tmp, dir) +} + +func extract(r io.Reader, dst string) error { + gz, err := gzip.NewReader(r) + if err != nil { + return err + } + tr := tar.NewReader(gz) + for { + hdr, err := tr.Next() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + _, rel, _ := strings.Cut(strings.TrimPrefix(hdr.Name, "./"), "/") + if rel == "" { + continue + } + if !filepath.IsLocal(rel) { + return fmt.Errorf("unsafe path %q in archive", hdr.Name) + } + p := filepath.Join(dst, rel) + switch hdr.Typeflag { + case tar.TypeDir: + if err := os.MkdirAll(p, 0o755); err != nil { + return err + } + case tar.TypeReg: + if err := writeFile(p, tr, hdr.Mode&0o111 != 0); err != nil { + return err + } + } + } +} + +func writeFile(p string, r io.Reader, exec bool) error { + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + mode := os.FileMode(0o644) + if exec { + mode = 0o755 + } + f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) + if err != nil { + return err + } + if _, err := io.Copy(f, r); err != nil { + _ = f.Close() + return err + } + return f.Close() +} diff --git a/internal/deploy/forge_test.go b/internal/deploy/forge_test.go new file mode 100644 index 0000000..cc58208 --- /dev/null +++ b/internal/deploy/forge_test.go @@ -0,0 +1,96 @@ +package deploy + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "os" + "path/filepath" + "testing" +) + +type entry struct { + name string + body string + mode int64 + typ byte +} + +func tarball(t *testing.T, entries ...entry) []byte { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for _, e := range entries { + typ := e.typ + if typ == 0 { + typ = tar.TypeReg + } + hdr := &tar.Header{Name: e.name, Mode: e.mode, Size: int64(len(e.body)), Typeflag: typ} + if typ != tar.TypeReg { + hdr.Size = 0 + hdr.Linkname = e.body + } + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if typ == tar.TypeReg { + if _, err := tw.Write([]byte(e.body)); err != nil { + t.Fatal(err) + } + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func TestExtractStripsTopDir(t *testing.T) { + dst := t.TempDir() + err := extract(bytes.NewReader(tarball(t, + entry{name: "puppetlabs-stdlib-9.7.0/", typ: tar.TypeDir, mode: 0o755}, + entry{name: "puppetlabs-stdlib-9.7.0/metadata.json", body: "{}", mode: 0o600}, + entry{name: "./puppetlabs-stdlib-9.7.0/lib/x.rb", body: "x", mode: 0o644}, + entry{name: "puppetlabs-stdlib-9.7.0/bin/run", body: "#!", mode: 0o700}, + entry{name: "puppetlabs-stdlib-9.7.0/link", body: "/etc/passwd", typ: tar.TypeSymlink}, + )), dst) + if err != nil { + t.Fatal(err) + } + for p, perm := range map[string]os.FileMode{"metadata.json": 0o644, "lib/x.rb": 0o644, "bin/run": 0o755} { + fi, err := os.Stat(filepath.Join(dst, p)) + if err != nil || fi.Mode().Perm() != perm { + t.Errorf("%s: %v %v", p, fi, err) + } + } + if _, err := os.Lstat(filepath.Join(dst, "link")); !os.IsNotExist(err) { + t.Error("symlink should be skipped") + } +} + +func TestExtractRejectsTraversal(t *testing.T) { + dst := t.TempDir() + err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst) + if err == nil { + t.Fatal("expected traversal error") + } +} + +func TestForgeURL(t *testing.T) { + for in, want := range map[string]string{ + "": defaultForge, + "forge.puppetlabs.com": defaultForge, + "https://forge.puppet.com/": defaultForge, + "forge.example.com": "https://forge.example.com", + "http://127.0.0.1:8080/": "http://127.0.0.1:8080", + "https://artifacts/api/forge/": "https://artifacts/api/forge", + } { + if got := forgeURL(in); got != want { + t.Errorf("forgeURL(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/deploy/git.go b/internal/deploy/git.go new file mode 100644 index 0000000..679242d --- /dev/null +++ b/internal/deploy/git.go @@ -0,0 +1,62 @@ +package deploy + +import ( + "bytes" + "context" + "fmt" + "os" + "os/exec" + "strings" +) + +func git(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") + var out, errb bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &errb + if err := cmd.Run(); err != nil { + return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) + } + return strings.TrimSpace(out.String()), nil +} + +func 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 { + return err + } + } + args := append([]string{"fetch", "-q", "--prune", "--force", url}, refspecs...) + _, err := 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/") + if err != nil { + return nil, err + } + m := map[string]string{} + for _, l := range strings.Split(out, "\n") { + sha, ref, ok := strings.Cut(l, " ") + if ok { + m[strings.TrimPrefix(ref, "refs/heads/")] = sha + } + } + return m, nil +} + +func 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 { + 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) + return os.RemoveAll(path) +} diff --git a/internal/deploy/puppetfile.go b/internal/deploy/puppetfile.go new file mode 100644 index 0000000..f65b539 --- /dev/null +++ b/internal/deploy/puppetfile.go @@ -0,0 +1,310 @@ +package deploy + +import ( + "fmt" + "path/filepath" + "regexp" + "strings" +) + +type Puppetfile struct { + Forge string + Moduledir string + Modules []Module +} + +type Module struct { + Owner string + Name string + Version string + Git string + RefKind string + Ref string + InstallPath string +} + +// Path is the module's install location relative to the environment root. +func (m Module) Path(pf *Puppetfile) string { + dir := pf.Moduledir + if m.InstallPath != "" { + dir = m.InstallPath + } + return filepath.Join(dir, m.Name) +} + +type tokKind int + +const ( + tIdent tokKind = iota + tString + tSymbol + tLabel + tArrow + tComma + tLParen + tRParen + tNewline + tEOF +) + +type token struct { + kind tokKind + val string + line int +} + +func isIdent(c byte) bool { + return c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' +} + +func lex(src string) ([]token, error) { + var toks []token + line := 1 + for i := 0; i < len(src); { + c := src[i] + switch { + case c == ' ' || c == '\t' || c == '\r': + i++ + case c == '#': + for i < len(src) && src[i] != '\n' { + i++ + } + case c == '\n': + toks = append(toks, token{tNewline, "", line}) + line++ + i++ + case c == '\'' || c == '"': + var sb strings.Builder + j := i + 1 + for ; j < len(src) && src[j] != c; j++ { + if src[j] == '\n' { + break + } + if src[j] == '\\' && j+1 < len(src) { + j++ + } + sb.WriteByte(src[j]) + } + if j >= len(src) || src[j] != c { + return nil, fmt.Errorf("line %d: unterminated string", line) + } + toks = append(toks, token{tString, sb.String(), line}) + i = j + 1 + case c == ':' && i+1 < len(src) && isIdent(src[i+1]): + j := i + 1 + for j < len(src) && isIdent(src[j]) { + j++ + } + toks = append(toks, token{tSymbol, src[i+1 : j], line}) + i = j + case isIdent(c): + j := i + for j < len(src) && isIdent(src[j]) { + j++ + } + if j < len(src) && src[j] == ':' && (j+1 >= len(src) || src[j+1] != ':') { + toks = append(toks, token{tLabel, src[i:j], line}) + i = j + 1 + } else { + toks = append(toks, token{tIdent, src[i:j], line}) + i = j + } + case strings.HasPrefix(src[i:], "=>"): + toks = append(toks, token{tArrow, "", line}) + i += 2 + case c == ',': + toks = append(toks, token{tComma, "", line}) + i++ + case c == '(': + toks = append(toks, token{tLParen, "", line}) + i++ + case c == ')': + toks = append(toks, token{tRParen, "", line}) + i++ + default: + return nil, fmt.Errorf("line %d: unexpected %q", line, c) + } + } + return append(toks, token{tEOF, "", line}), nil +} + +type call struct { + name string + line int + args []token + opts map[string]token +} + +func parseCalls(toks []token) ([]call, error) { + var calls []call + i := 0 + next := func() token { t := toks[i]; i++; return t } + peek := func() token { return toks[i] } + skipNL := func() { + for peek().kind == tNewline { + i++ + } + } + for { + skipNL() + t := next() + if t.kind == tEOF { + return calls, nil + } + if t.kind != tIdent { + return nil, fmt.Errorf("line %d: expected a statement", t.line) + } + c := call{name: t.val, line: t.line, opts: map[string]token{}} + paren := peek().kind == tLParen + if paren { + i++ + skipNL() + } + 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 == tString || a.kind == tSymbol: + c.args = append(c.args, a) + default: + return nil, fmt.Errorf("line %d: unexpected token in %s", a.line, c.name) + } + if peek().kind != tComma { + break + } + i++ + skipNL() + } + if paren { + skipNL() + if next().kind != tRParen { + return nil, fmt.Errorf("line %d: expected )", c.line) + } + } + if k := peek().kind; k != tNewline && k != tEOF { + return nil, fmt.Errorf("line %d: unexpected trailing tokens", c.line) + } + calls = append(calls, c) + } +} + +var ( + moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) + ownerName = regexp.MustCompile(`^[A-Za-z0-9]+$`) + versionStr = regexp.MustCompile(`^[0-9A-Za-z.+-]+$`) +) + +func ParsePuppetfile(src string) (*Puppetfile, error) { + toks, err := lex(src) + if err != nil { + return nil, err + } + calls, err := parseCalls(toks) + if err != nil { + return nil, err + } + pf := &Puppetfile{Moduledir: "modules"} + seen := map[string]bool{} + for _, c := range calls { + switch c.name { + case "forge", "moduledir": + if len(c.args) != 1 || c.args[0].kind != tString || len(c.opts) > 0 { + return nil, fmt.Errorf("line %d: %s takes one string", c.line, c.name) + } + if c.name == "forge" { + pf.Forge = c.args[0].val + } else if pf.Moduledir, err = localPath(c.args[0].val); err != nil { + return nil, fmt.Errorf("line %d: moduledir: %w", c.line, err) + } + case "mod": + m, err := parseMod(c) + 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) + } + } + return pf, nil +} + +func localPath(p string) (string, error) { + if !filepath.IsLocal(p) { + return "", fmt.Errorf("%q must be a relative path inside the environment", p) + } + return filepath.Clean(p), nil +} + +func parseMod(c call) (Module, error) { + var m Module + if len(c.args) == 0 || c.args[0].kind != tString { + return m, fmt.Errorf("mod needs a name") + } + full := c.args[0].val + if i := strings.IndexAny(full, "-/"); i >= 0 { + m.Owner, m.Name = full[:i], full[i+1:] + } else { + m.Name = full + } + if !moduleName.MatchString(m.Name) { + return m, fmt.Errorf("invalid module name %q", full) + } + for k, v := range c.opts { + if v.kind != tString { + return m, fmt.Errorf("mod %s: :%s must be a string", full, k) + } + switch k { + case "git": + m.Git = v.val + case "tag", "branch", "ref", "commit": + if m.RefKind != "" { + return m, fmt.Errorf("mod %s: only one of :tag, :branch, :ref, :commit allowed", full) + } + m.RefKind, m.Ref = k, v.val + case "install_path": + p, err := localPath(v.val) + if err != nil { + return m, fmt.Errorf("mod %s: install_path: %w", full, err) + } + m.InstallPath = p + default: + return m, fmt.Errorf("mod %s: unsupported option :%s", full, k) + } + } + if m.Git != "" { + if len(c.args) > 1 { + return m, fmt.Errorf("mod %s: git modules take no version", full) + } + return m, nil + } + if m.RefKind != "" { + return m, fmt.Errorf("mod %s: :%s requires :git", full, m.RefKind) + } + if !ownerName.MatchString(m.Owner) { + return m, fmt.Errorf("forge module %q must be owner-name", full) + } + if len(c.args) > 2 { + return m, fmt.Errorf("mod %s: too many arguments", full) + } + if len(c.args) == 2 { + v := c.args[1] + switch { + case v.val == "latest": + case v.kind == tString && versionStr.MatchString(v.val): + m.Version = v.val + default: + return m, fmt.Errorf("mod %s: unsupported version %q", full, v.val) + } + } + return m, nil +} diff --git a/internal/deploy/puppetfile_test.go b/internal/deploy/puppetfile_test.go new file mode 100644 index 0000000..103bf58 --- /dev/null +++ b/internal/deploy/puppetfile_test.go @@ -0,0 +1,98 @@ +package deploy + +import ( + "reflect" + "testing" +) + +func TestParsePuppetfileEstate(t *testing.T) { + pf, err := ParsePuppetfile(`forge 'forge.puppetlabs.com' +moduledir 'external_modules' + +# puppetlabs +mod 'puppetlabs-stdlib', '9.7.0' +mod 'puppetlabs-yumrepo_core', '2.1.0' # trailing comment + +mod 'bind', + :git => 'https://git.unkin.net/unkinben/puppet-bind.git', + :tag => '1.0' +`) + if err != nil { + t.Fatal(err) + } + if pf.Forge != "forge.puppetlabs.com" || pf.Moduledir != "external_modules" { + t.Fatalf("header: %+v", pf) + } + want := []Module{ + {Owner: "puppetlabs", Name: "stdlib", Version: "9.7.0"}, + {Owner: "puppetlabs", Name: "yumrepo_core", Version: "2.1.0"}, + {Name: "bind", Git: "https://git.unkin.net/unkinben/puppet-bind.git", RefKind: "tag", Ref: "1.0"}, + } + if !reflect.DeepEqual(pf.Modules, want) { + t.Fatalf("modules:\n got %+v\nwant %+v", pf.Modules, want) + } + if p := pf.Modules[2].Path(pf); p != "external_modules/bind" { + t.Fatalf("path %s", p) + } +} + +func TestParsePuppetfileForms(t *testing.T) { + pf, err := ParsePuppetfile(` +mod "puppet/systemd", "8.1.0" +mod 'saz-sudo', :latest +mod 'saz-ssh' +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' +`) + if err != nil { + t.Fatal(err) + } + want := []Module{ + {Owner: "puppet", Name: "systemd", Version: "8.1.0"}, + {Owner: "saz", Name: "sudo"}, + {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"}, + } + if !reflect.DeepEqual(pf.Modules, want) { + t.Fatalf("modules:\n got %+v\nwant %+v", pf.Modules, want) + } + if pf.Moduledir != "modules" { + t.Fatalf("default moduledir %q", pf.Moduledir) + } + if p := pf.Modules[6].Path(pf); p != "site/z" { + t.Fatalf("install_path %s", p) + } +} + +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'", + "ref without git": "mod 'a-b', :tag => '1'", + "git version": "mod 'x', '1.0', :git => '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'", + "duplicate": "mod 'a-b', '1'\nmod 'c-b', '2'", + "trailing junk": "mod 'a-b', '1' 'c'", + "bad char": "mod 'a-b', '1'; x", + } { + if _, err := ParsePuppetfile(in); err == nil { + t.Errorf("%s: expected error", name) + } + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..d5f5157 --- /dev/null +++ b/main.go @@ -0,0 +1,119 @@ +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "path/filepath" + "sort" + "strings" + "syscall" + "time" + + "git.unkin.net/unkin/w10k/internal/deploy" + "github.com/spf13/cobra" +) + +var version = "dev" + +func main() { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := rootCmd().ExecuteContext(ctx); err != nil { + os.Exit(1) + } +} + +func rootCmd() *cobra.Command { + var cfgPath string + var jobs int + var grace time.Duration + var root *cobra.Command + load := func() (*deploy.Deployer, error) { + cfg, err := deploy.LoadConfig(cfgPath) + if err != nil { + return nil, err + } + g := grace + if !root.PersistentFlags().Changed("gc-grace") && cfg.W10k.GCGrace != nil { + g = *cfg.W10k.GCGrace + } + if g < 0 { + return nil, fmt.Errorf("--gc-grace must not be negative") + } + return deploy.New(cfg, jobs, g), nil + } + locked := func(fn func(*deploy.Deployer) error) error { + d, err := load() + if err != nil { + return err + } + unlock, err := d.Lock() + if err != nil { + return err + } + defer unlock() + return fn(d) + } + + root = &cobra.Command{ + Use: "w10k", + Short: "Deploy Puppet environments and Puppetfile modules as sha-pinned git worktrees", + Version: version, + SilenceUsage: true, + } + root.PersistentFlags().StringVarP(&cfgPath, "config", "c", "/etc/puppetlabs/r10k/r10k.yaml", "r10k.yaml path") + root.PersistentFlags().IntVarP(&jobs, "jobs", "j", 8, "maximum concurrent git/forge operations") + root.PersistentFlags().DurationVar(&grace, "gc-grace", 10*time.Minute, "keep unreferenced worktrees and modules this long after a run marks them (overrides w10k.gc_grace)") + + var modules bool + deployCmd := &cobra.Command{ + Use: "deploy [env...]", + Short: "Deploy all environments, or only the named ones", + RunE: func(cmd *cobra.Command, args []string) error { + return locked(func(d *deploy.Deployer) error { return d.Deploy(cmd.Context(), args, modules) }) + }, + } + deployCmd.Flags().BoolVarP(&modules, "modules", "m", false, "re-resolve Puppetfile modules for unchanged environments") + + listCmd := &cobra.Command{ + Use: "list", + Short: "List deployed environments", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + d, err := load() + if err != nil { + return err + } + for _, s := range d.Sources() { + live, err := d.Live(s) + if err != nil { + return err + } + envs := make([]string, 0, len(live)) + for e := range live { + envs = append(envs, e) + } + sort.Strings(envs) + for _, e := range envs { + sha, _, _ := strings.Cut(filepath.Base(live[e]), "-") + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", s.Name, e, sha) + } + } + return nil + }, + } + + gcCmd := &cobra.Command{ + Use: "gc", + Short: "Remove worktrees and modules no longer referenced by any environment", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return locked(func(d *deploy.Deployer) error { return d.GC(cmd.Context()) }) + }, + } + + root.AddCommand(deployCmd, listCmd, gcCmd) + return root +} diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml new file mode 100644 index 0000000..c2bcb5c --- /dev/null +++ b/packaging/nfpm.yaml @@ -0,0 +1,31 @@ +name: ${PACKAGE_NAME} +version: ${PACKAGE_VERSION} +release: ${PACKAGE_RELEASE} +arch: ${PACKAGE_ARCH} +platform: ${PACKAGE_PLATFORM} +section: default +priority: extra +description: "${PACKAGE_DESCRIPTION}" + +maintainer: ${PACKAGE_MAINTAINER} +homepage: ${PACKAGE_HOMEPAGE} +license: ${PACKAGE_LICENSE} + +depends: + - git + +contents: + - src: dist/w10k + dst: /usr/bin/w10k + file_info: + mode: 0755 + owner: root + group: root + - src: dist/completions/w10k.bash + dst: /usr/share/bash-completion/completions/w10k + file_info: + mode: 0644 + - src: dist/completions/_w10k + dst: /usr/share/zsh/site-functions/_w10k + file_info: + mode: 0644 diff --git a/scripts/build-rpm.sh b/scripts/build-rpm.sh new file mode 100755 index 0000000..3c28aa5 --- /dev/null +++ b/scripts/build-rpm.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +VERSION="${1:-${CI_COMMIT_TAG:-0.0.0-dev}}" +VERSION="${VERSION#v}" +DIST="dist" + +if [ ! -f "${DIST}/w10k" ]; then + echo "ERROR: ${DIST}/w10k not found; run 'make build' first" >&2 + exit 1 +fi + +mkdir -p "${DIST}/completions" +"./${DIST}/w10k" completion bash >"${DIST}/completions/w10k.bash" +"./${DIST}/w10k" completion zsh >"${DIST}/completions/_w10k" + +export PACKAGE_NAME="w10k" +export PACKAGE_VERSION="${VERSION}" +export PACKAGE_RELEASE="1" +export PACKAGE_ARCH="amd64" +export PACKAGE_PLATFORM="linux" +export PACKAGE_DESCRIPTION="Deploy Puppet environments and Puppetfile modules as sha-pinned git worktrees" +export PACKAGE_MAINTAINER="Ben Vincent " +export PACKAGE_HOMEPAGE="https://git.unkin.net/unkin/w10k" +export PACKAGE_LICENSE="MIT" + +envsubst "${DIST}/nfpm.yaml" +nfpm pkg --config "${DIST}/nfpm.yaml" --target "${DIST}" --packager rpm +ls -1 "${DIST}"/*.rpm -- 2.47.3 From 01fa51110bdca896107a304cd33332918c923372 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 17:52:07 +1100 Subject: [PATCH 02/11] 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) + } +} -- 2.47.3 From fd1ddea356fda175c69e1fbf9ba5471fac46d3f0 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 17:52:07 +1100 Subject: [PATCH 03/11] Use gobuilder/rpmbuilder images and authenticate RPM upload - run Go steps on docker-internal gobuilder with the shared GOCACHE - package with docker-internal rpmbuilder - upload the RPM with a Vault-minted artifactapi-writer token - ship fish completion in the RPM --- .woodpecker/build.yaml | 14 ++++++++++++- .woodpecker/pre-commit.yaml | 14 ++++++++++++- .woodpecker/release.yaml | 39 +++++++++++++++++++++++++++++++++---- .woodpecker/test.yaml | 14 ++++++++++++- packaging/nfpm.yaml | 4 ++++ scripts/build-rpm.sh | 1 + 6 files changed, 79 insertions(+), 7 deletions(-) diff --git a/.woodpecker/build.yaml b/.woodpecker/build.yaml index 74123b5..c8e553d 100644 --- a/.woodpecker/build.yaml +++ b/.woodpecker/build.yaml @@ -3,7 +3,19 @@ when: steps: - name: build - image: golang:1.25 + image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.2-alma9 + environment: + GOCACHE_S3_BUCKET: gocache + GOCACHE_S3_REGION: us-east-1 + GOCACHE_S3_ENDPOINT_URL: https://s3.ceph.unkin.net + GOCACHE_S3_PATH_STYLE: "true" + GOCACHE_KEY_PREFIX: ci-w10k + GOCACHE_METRICS: "true" + GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache + AWS_ACCESS_KEY_ID: + from_secret: GOCACHE_AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY: + from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY commands: - make build backend_options: diff --git a/.woodpecker/pre-commit.yaml b/.woodpecker/pre-commit.yaml index d57b508..a7c86a9 100644 --- a/.woodpecker/pre-commit.yaml +++ b/.woodpecker/pre-commit.yaml @@ -3,7 +3,19 @@ when: steps: - name: pre-commit - image: git.unkin.net/unkin/almalinux9-gobuilder:20260606 + image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.2-alma9 + environment: + GOCACHE_S3_BUCKET: gocache + GOCACHE_S3_REGION: us-east-1 + GOCACHE_S3_ENDPOINT_URL: https://s3.ceph.unkin.net + GOCACHE_S3_PATH_STYLE: "true" + GOCACHE_KEY_PREFIX: ci-w10k + GOCACHE_METRICS: "true" + GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache + AWS_ACCESS_KEY_ID: + from_secret: GOCACHE_AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY: + from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY commands: - uvx pre-commit run --all-files backend_options: diff --git a/.woodpecker/release.yaml b/.woodpecker/release.yaml index 00a41fd..fd84368 100644 --- a/.woodpecker/release.yaml +++ b/.woodpecker/release.yaml @@ -4,7 +4,19 @@ when: steps: - name: test - image: golang:1.25 + image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.2-alma9 + environment: + GOCACHE_S3_BUCKET: gocache + GOCACHE_S3_REGION: us-east-1 + GOCACHE_S3_ENDPOINT_URL: https://s3.ceph.unkin.net + GOCACHE_S3_PATH_STYLE: "true" + GOCACHE_KEY_PREFIX: ci-w10k + GOCACHE_METRICS: "true" + GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache + AWS_ACCESS_KEY_ID: + from_secret: GOCACHE_AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY: + from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY commands: - go test -race ./... backend_options: @@ -19,7 +31,19 @@ steps: cpu: 2 - name: build - image: git.unkin.net/unkin/almalinux9-gobuilder:20260606 + image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.2-alma9 + environment: + GOCACHE_S3_BUCKET: gocache + GOCACHE_S3_REGION: us-east-1 + GOCACHE_S3_ENDPOINT_URL: https://s3.ceph.unkin.net + GOCACHE_S3_PATH_STYLE: "true" + GOCACHE_KEY_PREFIX: ci-w10k + GOCACHE_METRICS: "true" + GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache + AWS_ACCESS_KEY_ID: + from_secret: GOCACHE_AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY: + from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY commands: - make build VERSION=${CI_COMMIT_TAG} - | @@ -42,7 +66,7 @@ steps: cpu: 2 - name: package - image: git.unkin.net/unkin/almalinux9-rpmbuilder:latest + image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/rpmbuilder:0.1.0-alma9 commands: - ./scripts/build-rpm.sh ${CI_COMMIT_TAG} depends_on: [build] @@ -63,6 +87,13 @@ steps: - | HOST="https://artifactapi.k8s.syd1.au.unkin.net" REPO="rpm-internal" + set -o pipefail + VAULT="https://vault.service.consul:8200" + AUTH=$$(mktemp) + VT=$$(jq -n --rawfile jwt /var/run/secrets/kubernetes.io/serviceaccount/token '{role:"woodpecker_artifactapi_writer",jwt:$$jwt}' \ + | curl -sf -d @- "$$VAULT/v1/auth/k8s/au/syd1/login" | jq -er .auth.client_token) || exit 1 + printf 'X-Vault-Token: %s\n' "$$VT" | curl -sf -H @- "$$VAULT/v1/identity/oidc/token/artifactapi-writer" \ + | jq -er '"Authorization: Bearer " + .data.token' > "$$AUTH" || exit 1 for rpm in dist/*.rpm; do FILE=$$(basename "$$rpm") code=$$(curl -s -o /dev/null -w '%{http_code}' "$$HOST/api/v2/remotes/$$REPO/files/Packages/$$FILE" || true) @@ -71,7 +102,7 @@ steps: continue fi curl -f -X PUT "$$HOST/api/v2/remotes/$$REPO/files/$$FILE" \ - -H "Content-Type: application/x-rpm" --data-binary @"$$rpm" + -H "Content-Type: application/x-rpm" -H @"$$AUTH" --data-binary @"$$rpm" done depends_on: [package] backend_options: diff --git a/.woodpecker/test.yaml b/.woodpecker/test.yaml index 32c0e9a..d894aba 100644 --- a/.woodpecker/test.yaml +++ b/.woodpecker/test.yaml @@ -3,7 +3,19 @@ when: steps: - name: test - image: golang:1.25 + image: artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.2-alma9 + environment: + GOCACHE_S3_BUCKET: gocache + GOCACHE_S3_REGION: us-east-1 + GOCACHE_S3_ENDPOINT_URL: https://s3.ceph.unkin.net + GOCACHE_S3_PATH_STYLE: "true" + GOCACHE_KEY_PREFIX: ci-w10k + GOCACHE_METRICS: "true" + GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache + AWS_ACCESS_KEY_ID: + from_secret: GOCACHE_AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY: + from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY commands: - go test -v -race ./... backend_options: diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml index c2bcb5c..c65533b 100644 --- a/packaging/nfpm.yaml +++ b/packaging/nfpm.yaml @@ -29,3 +29,7 @@ contents: dst: /usr/share/zsh/site-functions/_w10k file_info: mode: 0644 + - src: dist/completions/w10k.fish + dst: /usr/share/fish/vendor_completions.d/w10k.fish + file_info: + mode: 0644 diff --git a/scripts/build-rpm.sh b/scripts/build-rpm.sh index 3c28aa5..15440c9 100755 --- a/scripts/build-rpm.sh +++ b/scripts/build-rpm.sh @@ -15,6 +15,7 @@ fi mkdir -p "${DIST}/completions" "./${DIST}/w10k" completion bash >"${DIST}/completions/w10k.bash" "./${DIST}/w10k" completion zsh >"${DIST}/completions/_w10k" +"./${DIST}/w10k" completion fish >"${DIST}/completions/w10k.fish" export PACKAGE_NAME="w10k" export PACKAGE_VERSION="${VERSION}" -- 2.47.3 From af20148ea41e1d636211cee62556d096796fc2b1 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 18:07:09 +1100 Subject: [PATCH 04/11] Confine worktree writes, time out git calls, keep removed sources' modules - write the deploy marker and module links through os.Root - extract forge tarballs through os.Root - bound each git call with w10k.git_timeout (default 10m) and http low-speed abort - count module refs from every worktree and basedir link, not only configured sources --- internal/deploy/config.go | 6 +- internal/deploy/config_test.go | 23 +++-- internal/deploy/deploy.go | 173 ++++++++++++++++++++------------- internal/deploy/deploy_test.go | 78 +++++++++++++++ internal/deploy/forge.go | 17 ++-- internal/deploy/forge_test.go | 5 +- internal/deploy/git.go | 11 ++- 7 files changed, 226 insertions(+), 87 deletions(-) diff --git a/internal/deploy/config.go b/internal/deploy/config.go index 20e9636..0943c71 100644 --- a/internal/deploy/config.go +++ b/internal/deploy/config.go @@ -15,7 +15,8 @@ type Config struct { Cachedir string `yaml:"cachedir"` Sources map[string]*Source `yaml:"sources"` W10k struct { - GCGrace *time.Duration `yaml:"gc_grace"` + GCGrace *time.Duration `yaml:"gc_grace"` + GitTimeout *time.Duration `yaml:"git_timeout"` } `yaml:"w10k"` } @@ -53,6 +54,9 @@ func ParseConfig(b []byte) (*Config, error) { if c.W10k.GCGrace != nil && *c.W10k.GCGrace < 0 { return nil, fmt.Errorf("w10k.gc_grace must not be negative") } + if c.W10k.GitTimeout != nil && *c.W10k.GitTimeout <= 0 { + return nil, fmt.Errorf("w10k.git_timeout must be positive") + } if len(c.Sources) == 0 { return nil, fmt.Errorf("no sources defined") } diff --git a/internal/deploy/config_test.go b/internal/deploy/config_test.go index 20ebe34..dc52d9c 100644 --- a/internal/deploy/config_test.go +++ b/internal/deploy/config_test.go @@ -1,6 +1,9 @@ package deploy -import "testing" +import ( + "testing" + "time" +) func TestParseConfigSymbolKeys(t *testing.T) { c, err := ParseConfig([]byte(` @@ -25,6 +28,8 @@ func TestParseConfigSymbolKeys(t *testing.T) { func TestParseConfigOptions(t *testing.T) { c, err := ParseConfig([]byte(` cachedir: /c +w10k: + git_timeout: 90s sources: a: remote: r @@ -42,6 +47,9 @@ sources: t.Fatal(err) } a, b := c.Sources["a"], c.Sources["b"] + if c.W10k.GitTimeout == nil || *c.W10k.GitTimeout != 90*time.Second { + t.Fatalf("git_timeout: %v", c.W10k.GitTimeout) + } if a.Prefix != "a" || a.InvalidBranches != "error" || len(a.IgnoreBranchPrefixes) != 2 { t.Fatalf("a: %+v", a) } @@ -52,12 +60,13 @@ sources: func TestParseConfigErrors(t *testing.T) { for name, in := range map[string]string{ - "no cachedir": "sources: {a: {remote: r, basedir: /b}}", - "no sources": "cachedir: /c", - "no remote": "cachedir: /c\nsources: {a: {basedir: /b}}", - "bad prefix": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, prefix: [x]}}", - "bad invalid": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, invalid_branches: nope}}", - "bad source name": "cachedir: /c\nsources: {a-b: {remote: r, basedir: /b}}", + "no cachedir": "sources: {a: {remote: r, basedir: /b}}", + "no sources": "cachedir: /c", + "zero git_timeout": "cachedir: /c\nw10k: {git_timeout: 0s}\nsources: {a: {remote: r, basedir: /b}}", + "no remote": "cachedir: /c\nsources: {a: {basedir: /b}}", + "bad prefix": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, prefix: [x]}}", + "bad invalid": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, invalid_branches: nope}}", + "bad source name": "cachedir: /c\nsources: {a-b: {remote: r, basedir: /b}}", } { if _, err := ParseConfig([]byte(in)); err == nil { t.Errorf("%s: expected error", name) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 18abe54..95f9dae 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -31,13 +31,14 @@ var ( ) type Deployer struct { - runGit func(ctx context.Context, dir string, args ...string) (string, error) - cfg *Config - grace time.Duration - now func() time.Time - sem chan struct{} - mu sync.Mutex - flights map[string]*flight + runGit func(ctx context.Context, dir string, args ...string) (string, error) + cfg *Config + grace time.Duration + gitTimeout time.Duration + now func() time.Time + sem chan struct{} + mu sync.Mutex + flights map[string]*flight } type flight struct { @@ -68,7 +69,11 @@ func New(cfg *Config, jobs int, grace time.Duration) *Deployer { if jobs < 1 { jobs = 1 } - return &Deployer{runGit: runGit, cfg: cfg, grace: grace, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}} + gt := defaultGitTimeout + if cfg.W10k.GitTimeout != nil { + gt = *cfg.W10k.GitTimeout + } + return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}} } func (d *Deployer) once(key string, fn func() (string, error)) (string, error) { @@ -237,7 +242,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string] return errors.Join(errs...) } -func (d *Deployer) owned(s *Source, link string) string { +func linkTarget(link string) string { t, err := os.Readlink(link) if err != nil { return "" @@ -245,11 +250,14 @@ func (d *Deployer) owned(s *Source, link string) string { if !filepath.IsAbs(t) { t = filepath.Join(filepath.Dir(link), t) } - t = filepath.Clean(t) - if filepath.Dir(t) != d.srcWorktrees(s) { - return "" + return filepath.Clean(t) +} + +func (d *Deployer) owned(s *Source, link string) string { + if t := linkTarget(link); filepath.Dir(t) == d.srcWorktrees(s) { + return t } - return t + return "" } func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) error { @@ -416,55 +424,31 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha); err != nil { return err } + root, err := os.OpenRoot(target) + if err != nil { + return err + } + defer func() { _ = root.Close() }() for _, mod := range mods { - if err := linkModule(target, mod.path, mod.dir); err != nil { + if err := linkModule(root, mod.path, mod.dir); err != nil { return err } } return nil } -// linkModule creates root/rel -> dir without following any symlink under root, so committed links cannot redirect it. -func linkModule(root, rel, dir string) error { +// linkModule creates rel -> dir inside root; os.Root refuses any committed symlink that leads outside. +func linkModule(root *os.Root, rel, dir string) error { if !filepath.IsLocal(rel) { return fmt.Errorf("module path %q escapes the environment", rel) } - parts := strings.Split(filepath.Clean(rel), string(filepath.Separator)) - p := root - for i, part := range parts { - p = filepath.Join(p, part) - fi, err := os.Lstat(p) - last := i == len(parts)-1 - switch { - case os.IsNotExist(err): - if !last { - if err := os.Mkdir(p, 0o755); err != nil { - return err - } - } - case err != nil: - return err - case fi.Mode()&os.ModeSymlink != 0: - return fmt.Errorf("module path %s: %s is a symlink", rel, filepath.Join(parts[:i+1]...)) - case !last && !fi.IsDir(): - return fmt.Errorf("module path %s: %s is not a directory", rel, filepath.Join(parts[:i+1]...)) - } + if err := root.MkdirAll(filepath.Dir(rel), 0o755); err != nil { + return fmt.Errorf("module path %s: %w", rel, err) } - realRoot, err := filepath.EvalSymlinks(root) - if err != nil { - return err + if err := root.RemoveAll(rel); err != nil { + return fmt.Errorf("module path %s: %w", rel, err) } - realParent, err := filepath.EvalSymlinks(filepath.Dir(p)) - if err != nil { - return err - } - if realParent != realRoot && !strings.HasPrefix(realParent, realRoot+string(filepath.Separator)) { - return fmt.Errorf("module path %s resolves outside the environment", rel) - } - if err := os.RemoveAll(p); err != nil { - return err - } - return os.Symlink(dir, p) + return root.Symlink(dir, rel) } // prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete. @@ -488,7 +472,7 @@ func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods [ return err } b = append(b, '\n') - if err := writeAtomic(filepath.Join(target, markerFile), b); err != nil { + if err := writeMarker(target, b); err != nil { return err } done := d.doneFile(target) @@ -498,6 +482,34 @@ func (d *Deployer) prepare(s *Source, name, sha, checksum, target string, mods [ return writeAtomic(done, b) } +// writeMarker replaces whatever the branch committed at the marker paths without following it. +func writeMarker(dir string, b []byte) error { + root, err := os.OpenRoot(dir) + if err != nil { + return err + } + defer func() { _ = root.Close() }() + tmp := markerFile + ".tmp" + if err := root.RemoveAll(tmp); err != nil { + return err + } + f, err := root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o644) + if err != nil { + return err + } + if _, err := f.Write(b); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + if err := root.RemoveAll(markerFile); err != nil { + return err + } + return root.Rename(tmp, markerFile) +} + func writeAtomic(p string, b []byte) error { tmp := p + ".tmp" if err := os.WriteFile(tmp, b, 0o644); err != nil { @@ -679,34 +691,55 @@ func (d *Deployer) GC(ctx context.Context) error { return errors.Join(append(g.errs, err)...) } -// moduleRefs returns every module dir referenced by an env worktree still on disk, live or awaiting GC. +// moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir. func (d *Deployer) moduleRefs(liveEnv map[string]bool) (map[string]bool, error) { - refs := map[string]bool{} + wts := map[string]bool{} + for p := range liveEnv { + wts[p] = true + } for _, s := range d.Sources() { - entries, err := os.ReadDir(d.srcWorktrees(s)) - if os.IsNotExist(err) { - continue + entries, err := os.ReadDir(s.Basedir) + if err != nil && !os.IsNotExist(err) { + return nil, err } + for _, e := range entries { + if t := linkTarget(filepath.Join(s.Basedir, e.Name())); filepath.Dir(filepath.Dir(t)) == d.path("worktrees") { + wts[t] = true + } + } + } + srcs, err := os.ReadDir(d.path("worktrees")) + if err != nil && !os.IsNotExist(err) { + return nil, err + } + for _, src := range srcs { + dir := d.path("worktrees", src.Name()) + entries, err := os.ReadDir(dir) if err != nil { return nil, err } for _, e := range entries { - p := filepath.Join(d.srcWorktrees(s), e.Name()) - b, err := os.ReadFile(d.doneFile(p)) - if os.IsNotExist(err) && !liveEnv[p] { - continue - } - var r deployResult - if err == nil { - err = json.Unmarshal(b, &r) - } - if err != nil { - return nil, fmt.Errorf("gc: module refs of %s: %w", p, err) - } - for _, m := range r.Modules { - refs[m] = true + if p := filepath.Join(dir, e.Name()); !wts[p] { + wts[p] = false } } } + refs := map[string]bool{} + for p, live := range wts { + b, err := os.ReadFile(d.doneFile(p)) + if os.IsNotExist(err) && !live { + continue + } + var r deployResult + if err == nil { + err = json.Unmarshal(b, &r) + } + if err != nil { + return nil, fmt.Errorf("gc: module refs of %s: %w", p, err) + } + for _, m := range r.Modules { + refs[m] = true + } + } return refs, nil } diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 3b15c13..37b488a 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net" "net/http" "net/http/httptest" "os" @@ -594,3 +595,80 @@ func TestJobsBoundGitProcesses(t *testing.T) { t.Fatalf("%d concurrent git processes with -j %d", peak, jobs) } } + +func TestCommittedMarkerTmpSymlinkWritesOutside(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + victim := filepath.Join(f.basedir, "main", "manifests", "site.pp") + + gitT(t, f.control, "checkout", "-q", "-b", "attacker") + if err := os.Symlink(victim, filepath.Join(f.control, markerFile+".tmp")); err != nil { + t.Fatal(err) + } + gitT(t, f.control, "add", "-f", "-A") + gitT(t, f.control, "commit", "-q", "-m", "link") + _ = f.deploy(false) + + if b, _ := os.ReadFile(victim); string(b) != "node default {}\n" { + t.Fatalf("branch overwrote a live env file via committed symlink:\n%s", b) + } +} + +func TestStalledGitRemoteFailsOnlyItsEnv(t *testing.T) { + f := newFixture(t) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + t.Cleanup(func() { _ = c.Close() }) + } + }() + timeout := 2 * time.Second + f.cfg.W10k.GitTimeout = &timeout + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "slow") + commit(t, f.control, map[string]string{"Puppetfile": "mod 'slow', :git => 'http://" + ln.Addr().String() + "/x.git'\n"}) + done := make(chan error, 1) + go func() { done <- f.deploy(false) }() + select { + case err := <-done: + if err == nil || !strings.Contains(err.Error(), "environment slow") { + t.Fatalf("stalled remote must fail its env, got %v", err) + } + case <-time.After(20 * time.Second): + t.Fatal("deploy still blocked on a stalled :git remote after 20s") + } + if f.env("main") == "" || f.env("slow") != "" { + t.Fatalf("main=%q slow=%q", f.env("main"), f.env("slow")) + } +} + +func TestGCKeepsModulesOfRemovedSource(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"Puppetfile": fmt.Sprintf("mod 'bind', :git => '%s', :tag => '1.0'\n", f.mod)}) + f.mustDeploy(false) + site := filepath.Join(f.basedir, "main", "modules", "bind", "manifests", "init.pp") + if !exists(site) { + t.Fatal("module not deployed") + } + other := filepath.Join(f.root, "other") + newRepo(t, other) + commit(t, other, map[string]string{"manifests/site.pp": "node default {}\n"}) + cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n other:\n remote: %s\n basedir: %s\n", f.cfg.Cachedir, other, filepath.Join(f.root, "other-envs"))) + if err != nil { + t.Fatal(err) + } + f.cfg = cfg + f.settle() + if _, err := os.Stat(site); err != nil { + t.Fatalf("GC deleted a module still linked from a removed source's live env: %v", err) + } +} diff --git a/internal/deploy/forge.go b/internal/deploy/forge.go index 9e1d259..23696e8 100644 --- a/internal/deploy/forge.go +++ b/internal/deploy/forge.go @@ -91,6 +91,11 @@ func extract(r io.Reader, dst string) error { if err != nil { return err } + root, err := os.OpenRoot(dst) + if err != nil { + return err + } + defer func() { _ = root.Close() }() tr := tar.NewReader(gz) for { hdr, err := tr.Next() @@ -104,32 +109,32 @@ func extract(r io.Reader, dst string) error { if rel == "" { continue } + rel = filepath.Clean(rel) if !filepath.IsLocal(rel) { return fmt.Errorf("unsafe path %q in archive", hdr.Name) } - p := filepath.Join(dst, rel) switch hdr.Typeflag { case tar.TypeDir: - if err := os.MkdirAll(p, 0o755); err != nil { + if err := root.MkdirAll(rel, 0o755); err != nil { return err } case tar.TypeReg: - if err := writeFile(p, tr, hdr.Mode&0o111 != 0); err != nil { + if err := writeFile(root, rel, tr, hdr.Mode&0o111 != 0); err != nil { return err } } } } -func writeFile(p string, r io.Reader, exec bool) error { - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { +func writeFile(root *os.Root, p string, r io.Reader, exec bool) error { + if err := root.MkdirAll(filepath.Dir(p), 0o755); err != nil { return err } mode := os.FileMode(0o644) if exec { mode = 0o755 } - f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) + f, err := root.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) if err != nil { return err } diff --git a/internal/deploy/forge_test.go b/internal/deploy/forge_test.go index cc58208..292ebd7 100644 --- a/internal/deploy/forge_test.go +++ b/internal/deploy/forge_test.go @@ -53,6 +53,7 @@ func TestExtractStripsTopDir(t *testing.T) { dst := t.TempDir() err := extract(bytes.NewReader(tarball(t, entry{name: "puppetlabs-stdlib-9.7.0/", typ: tar.TypeDir, mode: 0o755}, + entry{name: "puppetlabs-stdlib-9.7.0/spec/", typ: tar.TypeDir, mode: 0o755}, entry{name: "puppetlabs-stdlib-9.7.0/metadata.json", body: "{}", mode: 0o600}, entry{name: "./puppetlabs-stdlib-9.7.0/lib/x.rb", body: "x", mode: 0o644}, entry{name: "puppetlabs-stdlib-9.7.0/bin/run", body: "#!", mode: 0o700}, @@ -61,9 +62,9 @@ func TestExtractStripsTopDir(t *testing.T) { if err != nil { t.Fatal(err) } - for p, perm := range map[string]os.FileMode{"metadata.json": 0o644, "lib/x.rb": 0o644, "bin/run": 0o755} { + for p, perm := range map[string]os.FileMode{"spec": 0o755 | os.ModeDir, "metadata.json": 0o644, "lib/x.rb": 0o644, "bin/run": 0o755} { fi, err := os.Stat(filepath.Join(dst, p)) - if err != nil || fi.Mode().Perm() != perm { + if err != nil || fi.Mode()&(os.ModePerm|os.ModeDir) != perm { t.Errorf("%s: %v %v", p, fi, err) } } diff --git a/internal/deploy/git.go b/internal/deploy/git.go index 992ec78..9d166b3 100644 --- a/internal/deploy/git.go +++ b/internal/deploy/git.go @@ -7,12 +7,19 @@ import ( "os" "os/exec" "strings" + "syscall" + "time" ) +const defaultGitTimeout = 10 * time.Minute + func runGit(ctx context.Context, dir string, args ...string) (string, error) { - cmd := exec.CommandContext(ctx, "git", args...) + cmd := exec.CommandContext(ctx, "git", append([]string{"-c", "http.lowSpeedLimit=1", "-c", "http.lowSpeedTime=60"}, args...)...) cmd.Dir = dir cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } + cmd.WaitDelay = 5 * time.Second var out, errb bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &errb if err := cmd.Run(); err != nil { @@ -24,6 +31,8 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) { // git holds a -j slot only for the subprocess itself, so callers never nest slots. func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) { err = d.limit(func() error { + ctx, cancel := context.WithTimeout(ctx, d.gitTimeout) + defer cancel() out, err = d.runGit(ctx, dir, args...) return err }) -- 2.47.3 From 24857770b2d31e8381dc62456783a4eb543a1f5d Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:25:59 +1100 Subject: [PATCH 05/11] Pin golangci-lint to v2.13.1 --- .woodpecker/lint.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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: -- 2.47.3 From 8a336b62a5b2d97c5a1981e6031cb073bb95681e Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:25:59 +1100 Subject: [PATCH 06/11] Harden Puppetfile parsing, module sources and cache GC - return an error for an option with no value instead of reading past EOF - recover panics per environment, module and single-flight as errors - accept only https, http, ssh and user@host:path module remotes - fetch modules with protocol.file.allow=never - reuse module and forge dirs only with an out-of-tree done marker - rename GC'd dirs aside before deleting and sweep leftovers - add a Puppetfile fuzz target; serve test modules over git smart HTTP --- internal/deploy/deploy.go | 126 ++++++++++++++++------ internal/deploy/deploy_test.go | 162 +++++++++++++++++++++++++++-- internal/deploy/git.go | 5 +- internal/deploy/puppetfile.go | 40 +++++-- internal/deploy/puppetfile_test.go | 83 ++++++++++++--- 5 files changed, 352 insertions(+), 64 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 95f9dae..9b8d1d8 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" @@ -11,6 +12,7 @@ import ( "os" "path/filepath" "regexp" + "runtime/debug" "sort" "strings" "sync" @@ -22,12 +24,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 { @@ -85,8 +90,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 @@ -118,14 +126,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. @@ -207,7 +252,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) @@ -228,7 +273,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() @@ -326,14 +375,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) }() } @@ -346,7 +398,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 } @@ -369,18 +421,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 } @@ -402,10 +458,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 } @@ -475,11 +537,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 writeAtomic(done, b) + return d.markDone(target, b) } // writeMarker replaces whatever the branch committed at the marker paths without following it. @@ -612,6 +670,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 } @@ -671,9 +735,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 37b488a..c5d6cca 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net" "net/http" + "net/http/cgi" "net/http/httptest" "os" "os/exec" @@ -213,6 +214,8 @@ type fixture struct { root string control string mod string + modDir string + gitURL string basedir string cfg *Config clock time.Time @@ -242,10 +245,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) @@ -258,6 +270,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' @@ -366,7 +387,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") @@ -529,7 +550,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) @@ -538,9 +559,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")) @@ -569,7 +590,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 { @@ -672,3 +693,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) + } + } + }) +} -- 2.47.3 From 53e78a5f75e9c58b413665e3d55fb736d41ce31b Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:29:23 +1100 Subject: [PATCH 07/11] Serialize worktree commands per repo --- internal/deploy/deploy.go | 1 + internal/deploy/deploy_test.go | 13 +++++++++++++ internal/deploy/git.go | 8 +++++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 9b8d1d8..c79851b 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -44,6 +44,7 @@ type Deployer struct { sem chan struct{} mu sync.Mutex flights map[string]*flight + wtLocks sync.Map } type flight struct { diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index c5d6cca..6466652 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -816,3 +816,16 @@ func TestPanicFailsOnlyItsEnv(t *testing.T) { 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) + } +} diff --git a/internal/deploy/git.go b/internal/deploy/git.go index 2bc3271..2c6cb20 100644 --- a/internal/deploy/git.go +++ b/internal/deploy/git.go @@ -8,6 +8,7 @@ import ( "os/exec" "slices" "strings" + "sync" "syscall" "time" ) @@ -29,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(func() error { ctx, cancel := context.WithTimeout(ctx, d.gitTimeout) defer cancel() -- 2.47.3 From 1c192c94096b61178aacb8355f7c91ccb71d2ab6 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:39:22 +1100 Subject: [PATCH 08/11] Keep targeted deploys targeted across sources and drop unverifiable GC marks --- internal/deploy/deploy.go | 14 +++---- internal/deploy/deploy_test.go | 68 ++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 7 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index c79851b..133b647 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -204,14 +204,17 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro for _, e := range only { want[e] = true } + found := map[string]bool{} var errs []error for _, s := range d.Sources() { - if err := d.deploySource(ctx, s, want, modules); err != nil { + if err := d.deploySource(ctx, s, want, found, modules); err != nil { errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err)) } } for e := range want { - errs = append(errs, fmt.Errorf("environment %s not found", e)) + if !found[e] { + errs = append(errs, fmt.Errorf("environment %s not found", e)) + } } if err := d.GC(ctx); err != nil { errs = append(errs, err) @@ -252,7 +255,7 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]stri return envs, errs } -func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string]bool, modules bool) error { +func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[string]bool, modules bool) error { if err := d.syncMirror(ctx, d.srcMirror(s), s.Remote, nil, envRefspecs); err != nil { return err } @@ -270,7 +273,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want map[string] if !full && !want[name] { continue } - delete(want, name) + found[name] = true wg.Add(1) go func() { defer wg.Done() @@ -729,9 +732,6 @@ func (d *Deployer) GC(ctx context.Context) error { liveMod, err := d.moduleRefs(liveEnv) if err != nil { g.errs = append(g.errs, err) - for p := range g.marks { - g.seen[p] = true - } } else { keys, _ := os.ReadDir(d.path("modules")) for _, k := range keys { diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 6466652..18f12fd 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -829,3 +829,71 @@ func TestConcurrentWorktreeAddsOneMirror(t *testing.T) { t.Fatal(err) } } + +func TestGCRefsErrorDropsMarkOfLiveWorktree(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}} + clock := time.Unix(1_700_000_000, 0) + gc := func() error { + d := New(cfg, 1, 10*time.Minute) + d.now = func() time.Time { return clock } + return d.GC(context.Background()) + } + d := New(cfg, 1, 0) + old, cur, broken := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur"), filepath.Join(d.srcWorktrees(s), "broken") + mkdirs(t, old, cur, broken, s.Basedir, 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) + } + } + link := filepath.Join(s.Basedir, "develop") + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + if err := gc(); err != nil { + t.Fatal(err) + } + clock = clock.Add(time.Hour) + if err := Swap(old, link); err != nil { + t.Fatal(err) + } + if err := Swap(broken, filepath.Join(s.Basedir, "other")); err != nil { + t.Fatal(err) + } + if err := gc(); err == nil { + t.Fatal("want moduleRefs error from live worktree without done file") + } + if err := os.WriteFile(d.doneFile(broken), []byte(`{"modules":[]}`), 0o644); err != nil { + t.Fatal(err) + } + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + _ = gc() + if !exists(old) { + t.Fatal("worktree unreferenced this run was deleted in the same run via a stale mark kept while it was live") + } +} + +func TestDeployOnlyLeavesLaterSourceAlone(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "production") + other := filepath.Join(f.root, "other") + newRepo(t, other) + commit(t, other, map[string]string{"manifests/site.pp": "node default {}\n"}) + otherBase := filepath.Join(f.root, "other-envs") + cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n aaa:\n remote: %s\n basedir: %s\n zzz:\n remote: %s\n basedir: %s\n", f.cfg.Cachedir, f.control, f.basedir, other, otherBase)) + if err != nil { + t.Fatal(err) + } + f.cfg = cfg + if err := f.deploy(false, "production"); err != nil { + t.Fatal(err) + } + if exists(filepath.Join(otherBase, "main")) { + t.Fatal("deploy production also deployed every env of the next source") + } +} -- 2.47.3 From d7ab79f8744c9e10eb3a558511fb06d3b70d32f3 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:40:10 +1100 Subject: [PATCH 09/11] Write the branch as the deploy marker name, as g10k does --- internal/deploy/deploy.go | 25 ++++++++++++++----------- internal/deploy/deploy_test.go | 13 +++++++++++++ 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 133b647..0c1868f 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -222,7 +222,9 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro return errors.Join(errs...) } -func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]string, []error) { +type envRef struct{ branch, sha string } + +func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envRef, []error) { all, err := d.branches(ctx, d.srcMirror(s)) if err != nil { return nil, []error{err} @@ -232,7 +234,7 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]stri names = append(names, b) } sort.Strings(names) - envs := map[string]string{} + envs := map[string]envRef{} var errs []error for _, b := range names { if s.Ignored(b) { @@ -250,7 +252,7 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]stri errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) continue } - envs[name] = all[b] + envs[name] = envRef{b, all[b]} } return envs, errs } @@ -269,7 +271,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[ } var mu sync.Mutex var wg sync.WaitGroup - for name, sha := range envs { + for name, ref := range envs { if !full && !want[name] { continue } @@ -279,7 +281,7 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[ defer wg.Done() err := func() (err error) { defer recoverErr(&err, "environment "+name) - return d.deployEnv(ctx, s, name, sha, modules) + return d.deployEnv(ctx, s, name, ref, modules) }() if err != nil { mu.Lock() @@ -313,7 +315,8 @@ func (d *Deployer) owned(s *Source, link string) string { return "" } -func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, modules bool) error { +func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref envRef, modules bool) error { + sha := ref.sha link := filepath.Join(s.Basedir, name) cur := d.owned(s, link) if cur != "" && !modules && strings.HasPrefix(filepath.Base(cur), sha+"-") && d.complete(cur) { @@ -343,7 +346,7 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name, sha string, m if err := d.checkout(ctx, s, sha, target, mods); err != nil { return "", err } - return "", d.prepare(s, name, sha, checksum, target, mods, started) + return "", d.prepare(s, ref, checksum, target, mods, started) }); err != nil { return err } @@ -518,10 +521,10 @@ func linkModule(root *os.Root, rel, dir string) error { } // 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 { +func (d *Deployer) prepare(s *Source, ref envRef, checksum, target string, mods []resolved, started time.Time) error { r := deployResult{ - Name: name, - Signature: sha, + Name: ref.branch, + Signature: ref.sha, StartedAt: started, FinishedAt: d.now().UTC(), DeploySuccess: true, @@ -597,7 +600,7 @@ func Swap(target, link string) error { return os.Rename(tmp, link) } -func (d *Deployer) purge(s *Source, envs map[string]string) error { +func (d *Deployer) purge(s *Source, envs map[string]envRef) error { entries, err := os.ReadDir(s.Basedir) if err != nil { return err diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 18f12fd..62474c7 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -897,3 +897,16 @@ func TestDeployOnlyLeavesLaterSourceAlone(t *testing.T) { t.Fatal("deploy production also deployed every env of the next source") } } + +func TestDeployMarkerNameIsBranch(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feat/x") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + if err := f.deploy(false, "feat_x"); err != nil { + t.Fatal(err) + } + if m := readMarker(t, f.env("feat_x")); m.Name != "feat/x" { + t.Fatalf("marker name %q, want branch feat/x", m.Name) + } +} -- 2.47.3 From e73f3c8e1f256e378be19181c6b259c204c57e5c Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:54:57 +1100 Subject: [PATCH 10/11] Cap forge archive download and extracted size --- internal/deploy/forge.go | 30 ++++++++++++++++++++++++++---- internal/deploy/forge_test.go | 25 +++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/internal/deploy/forge.go b/internal/deploy/forge.go index 23696e8..e89172a 100644 --- a/internal/deploy/forge.go +++ b/internal/deploy/forge.go @@ -14,7 +14,11 @@ import ( "time" ) -const defaultForge = "https://forgeapi.puppet.com" +const ( + defaultForge = "https://forgeapi.puppet.com" + maxForgeDownload = 100 << 20 + maxForgeExtracted = 512 << 20 +) var httpClient = &http.Client{Timeout: 5 * time.Minute} @@ -79,24 +83,42 @@ func forgeInstall(ctx context.Context, base, release, dir string) error { if err != nil { return err } - if err := extract(body, tmp); err != nil { + if err := extract(&capReader{r: body, n: maxForgeDownload}, tmp, maxForgeExtracted); err != nil { _ = os.RemoveAll(tmp) return fmt.Errorf("%s: %w", release, err) } return os.Rename(tmp, dir) } -func extract(r io.Reader, dst string) error { +// capReader fails once more than n bytes are read, so an oversized stream errors instead of being truncated silently. +type capReader struct { + r io.Reader + n int64 +} + +func (c *capReader) Read(p []byte) (int, error) { + if int64(len(p)) > c.n+1 { + p = p[:c.n+1] + } + n, err := c.r.Read(p) + if c.n -= int64(n); c.n < 0 { + return 0, fmt.Errorf("archive exceeds size cap") + } + return n, err +} + +func extract(r io.Reader, dst string, limit int64) error { gz, err := gzip.NewReader(r) if err != nil { return err } + cr := &capReader{r: gz, n: limit} root, err := os.OpenRoot(dst) if err != nil { return err } defer func() { _ = root.Close() }() - tr := tar.NewReader(gz) + tr := tar.NewReader(cr) for { hdr, err := tr.Next() if err == io.EOF { diff --git a/internal/deploy/forge_test.go b/internal/deploy/forge_test.go index 292ebd7..6598222 100644 --- a/internal/deploy/forge_test.go +++ b/internal/deploy/forge_test.go @@ -4,8 +4,10 @@ import ( "archive/tar" "bytes" "compress/gzip" + "io" "os" "path/filepath" + "strings" "testing" ) @@ -58,7 +60,7 @@ func TestExtractStripsTopDir(t *testing.T) { entry{name: "./puppetlabs-stdlib-9.7.0/lib/x.rb", body: "x", mode: 0o644}, entry{name: "puppetlabs-stdlib-9.7.0/bin/run", body: "#!", mode: 0o700}, entry{name: "puppetlabs-stdlib-9.7.0/link", body: "/etc/passwd", typ: tar.TypeSymlink}, - )), dst) + )), dst, maxForgeExtracted) if err != nil { t.Fatal(err) } @@ -75,7 +77,7 @@ func TestExtractStripsTopDir(t *testing.T) { func TestExtractRejectsTraversal(t *testing.T) { dst := t.TempDir() - err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst) + err := extract(bytes.NewReader(tarball(t, entry{name: "m-1/../../evil", body: "x", mode: 0o644})), dst, maxForgeExtracted) if err == nil { t.Fatal("expected traversal error") } @@ -95,3 +97,22 @@ func TestForgeURL(t *testing.T) { } } } + +func TestExtractRejectsOversize(t *testing.T) { + big := entry{name: "m/a", body: strings.Repeat("x", 4096), mode: 0o644} + if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1024); err == nil { + t.Fatal("want extracted size cap error") + } + if err := extract(bytes.NewReader(tarball(t, big)), t.TempDir(), 1<<20); err != nil { + t.Fatal(err) + } +} + +func TestCapReaderErrorsAtCap(t *testing.T) { + if _, err := io.ReadAll(&capReader{r: strings.NewReader("abcdef"), n: 4}); err == nil { + t.Fatal("want cap error") + } + if b, err := io.ReadAll(&capReader{r: strings.NewReader("abc"), n: 4}); err != nil || string(b) != "abc" { + t.Fatalf("under cap: %q %v", b, err) + } +} -- 2.47.3 From 66580c9b37a0fc2d42b7a7829f8601776101cf01 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 20:54:57 +1100 Subject: [PATCH 11/11] Keep GC off targeted deploys, always drop live marks, let exact branches win env names --- internal/deploy/deploy.go | 111 ++++++++++++++++++------- internal/deploy/deploy_test.go | 146 +++++++++++++++++++++++++++++++++ 2 files changed, 226 insertions(+), 31 deletions(-) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 0c1868f..0fdbb21 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -9,10 +9,12 @@ import ( "errors" "fmt" "log" + "maps" "os" "path/filepath" "regexp" "runtime/debug" + "slices" "sort" "strings" "sync" @@ -216,9 +218,7 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro errs = append(errs, fmt.Errorf("environment %s not found", e)) } } - if err := d.GC(ctx); err != nil { - errs = append(errs, err) - } + errs = append(errs, d.gc(ctx, len(only) == 0)) return errors.Join(errs...) } @@ -234,7 +234,8 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR names = append(names, b) } sort.Strings(names) - envs := map[string]envRef{} + claims := map[string][]string{} + exact := map[string]string{} var errs []error for _, b := range names { if s.Ignored(b) { @@ -245,14 +246,31 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envR errs = append(errs, err) continue } - if corrected && s.InvalidBranches == "correct_and_warn" { - log.Printf("warning: branch %s deployed as environment %s", b, name) + if !corrected { + exact[name] = b } - if _, dup := envs[name]; dup { - errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + claims[name] = append(claims[name], b) + } + envs := map[string]envRef{} + for _, name := range slices.Sorted(maps.Keys(claims)) { + bs := claims[name] + win, isExact := exact[name] + if !isExact && len(bs) == 1 { + win = bs[0] + } + if win == "" { + errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name)) continue } - envs[name] = envRef{b, all[b]} + for _, b := range bs { + if b != win { + errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name)) + } + } + if !isExact && s.InvalidBranches == "correct_and_warn" { + log.Printf("warning: branch %s deployed as environment %s", win, name) + } + envs[name] = envRef{win, all[win]} } return envs, errs } @@ -697,26 +715,46 @@ func (g *gcRun) sweep(mirror, dir string, live map[string]bool, remove func(stri } } -func (d *Deployer) GC(ctx context.Context) error { - g := &gcRun{d: d, ctx: ctx, marks: map[string]time.Time{}, seen: map[string]bool{}} - statePath := d.path(gcStateFile) - if b, err := os.ReadFile(statePath); err == nil { - if err := json.Unmarshal(b, &g.marks); err != nil { - return fmt.Errorf("gc: %s: %w", statePath, err) +func (d *Deployer) GC(ctx context.Context) error { return d.gc(ctx, true) } + +// gc drops the mark of everything live this run; only a sweep may add marks or delete, and only where every live set it needs was computed. +func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) { + g := &gcRun{d: d, ctx: ctx, marks: d.loadMarks(), seen: map[string]bool{}} + defer func() { + for p := range g.marks { + if !g.seen[p] { + delete(g.marks, p) + } } - } else if !os.IsNotExist(err) { - return err - } + err = errors.Join(append(g.errs, d.saveMarks(g.marks))...) + }() liveEnv := map[string]bool{} + var ok []*Source for _, s := range d.Sources() { live, err := d.Live(s) if err != nil { - return fmt.Errorf("gc: %w", err) + g.errs = append(g.errs, fmt.Errorf("gc: %w", err)) + continue } + ok = append(ok, s) for _, t := range live { liveEnv[t] = true } + } + if !sweep { + liveMod, err := d.moduleRefs(liveEnv) + if err != nil || len(g.errs) > 0 { + g.errs = append(g.errs, err) + return nil + } + for p := range g.marks { + g.seen[p] = !liveEnv[p] && !liveMod[p] + } + return nil + } + + for _, s := range ok { 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) { @@ -731,7 +769,9 @@ func (d *Deployer) GC(ctx context.Context) error { } } } - + if len(ok) < len(d.cfg.Sources) { + return nil + } liveMod, err := d.moduleRefs(liveEnv) if err != nil { g.errs = append(g.errs, err) @@ -743,20 +783,29 @@ func (d *Deployer) GC(ctx context.Context) error { } g.sweep("", d.path("forge"), liveMod, func(p string) error { return d.discard(ctx, "", p) }) } + return nil +} - for p := range g.marks { - if !g.seen[p] { - delete(g.marks, p) - } - } - b, err := json.MarshalIndent(g.marks, "", " ") +// loadMarks treats an unreadable state file as empty, which only delays deletion. +func (d *Deployer) loadMarks() map[string]time.Time { + marks := map[string]time.Time{} + b, err := os.ReadFile(d.path(gcStateFile)) if err == nil { - tmp := statePath + ".tmp" - if err = os.WriteFile(tmp, b, 0o644); err == nil { - err = os.Rename(tmp, statePath) - } + err = json.Unmarshal(b, &marks) } - return errors.Join(append(g.errs, err)...) + if err != nil && !os.IsNotExist(err) { + log.Printf("gc: discarding unreadable %s: %v", gcStateFile, err) + marks = map[string]time.Time{} + } + return marks +} + +func (d *Deployer) saveMarks(marks map[string]time.Time) error { + b, err := json.MarshalIndent(marks, "", " ") + if err != nil { + return err + } + return writeAtomic(d.path(gcStateFile), b) } // moduleRefs returns every module dir referenced by any source's env worktree on disk or by any link in a configured basedir. diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 62474c7..c9acd44 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -910,3 +910,149 @@ func TestDeployMarkerNameIsBranch(t *testing.T) { t.Fatalf("marker name %q, want branch feat/x", m.Name) } } + +func TestTargetedDeploySkipsGC(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + old := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Hour) + if err := f.deploy(false, "main"); err != nil { + t.Fatal(err) + } + if !exists(old) { + t.Fatalf("targeted deploy ran GC and removed %s", old) + } +} + +func TestTargetedDeployDropsMarkOfReusedWorktree(t *testing.T) { + f := newFixture(t) + sha1 := commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + f.mustDeploy(false) + w1 := f.env("main") + commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Hour) + gitT(t, f.control, "reset", "-q", "--hard", sha1) + if err := f.deploy(false, "main"); err != nil || f.env("main") != w1 { + t.Fatalf("targeted deploy did not reuse %s: %v", w1, err) + } + commit(t, f.control, map[string]string{"manifests/site.pp": "node y {}\n"}) + if err := f.deploy(false, "main"); err != nil { + t.Fatal(err) + } + f.mustDeploy(false) + if !exists(w1) { + t.Fatal("worktree live during a targeted deploy kept its earlier mark and was deleted without grace") + } +} + +func TestGCLiveErrorDropsMarkOfLiveWorktree(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + u := &Source{Name: "u", Basedir: filepath.Join(root, "uenvs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s, "u": u}} + clock := time.Unix(1_700_000_000, 0) + gc := func() error { + d := New(cfg, 1, 10*time.Minute) + d.now = func() time.Time { return clock } + return d.GC(context.Background()) + } + d := New(cfg, 1, 0) + old, cur := filepath.Join(d.srcWorktrees(s), "old"), filepath.Join(d.srcWorktrees(s), "cur") + mkdirs(t, old, cur, s.Basedir, 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) + } + } + link := filepath.Join(s.Basedir, "develop") + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + if err := gc(); err != nil { + t.Fatal(err) + } + clock = clock.Add(time.Hour) + if err := Swap(old, link); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(u.Basedir, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := gc(); err == nil { + t.Fatal("want Live error") + } + if err := os.Remove(u.Basedir); err != nil { + t.Fatal(err) + } + if err := Swap(cur, link); err != nil { + t.Fatal(err) + } + _ = gc() + if !exists(old) { + t.Fatal("worktree unreferenced this run was deleted in the same run via a mark kept by GC's early return") + } +} + +func TestGCCorruptStateTreatedAsEmpty(t *testing.T) { + root := t.TempDir() + s := &Source{Name: "s", Basedir: filepath.Join(root, "envs")} + cfg := &Config{Cachedir: filepath.Join(root, "cache"), Sources: map[string]*Source{"s": s}} + d := New(cfg, 1, 10*time.Minute) + old := filepath.Join(d.srcWorktrees(s), "old") + mkdirs(t, old, s.Basedir) + state := d.path(gcStateFile) + if err := os.WriteFile(state, []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + if err := d.GC(context.Background()); err != nil { + t.Fatalf("corrupt state wedged GC: %v", err) + } + b, err := os.ReadFile(state) + if err != nil { + t.Fatal(err) + } + var marks map[string]time.Time + if err := json.Unmarshal(b, &marks); err != nil { + t.Fatalf("state not rewritten: %v", err) + } + if _, ok := marks[old]; !ok || !exists(old) { + t.Fatal("unreferenced worktree must be freshly marked, not deleted") + } +} + +func TestExactBranchWinsEnvName(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feature_x") + legit := commit(t, f.control, map[string]string{"manifests/site.pp": "node legit {}\n"}) + gitT(t, f.control, "checkout", "-q", "-b", "feature-x") + commit(t, f.control, map[string]string{"manifests/site.pp": "node evil {}\n"}) + err := f.deploy(false) + if got := f.env("feature_x"); !strings.HasPrefix(filepath.Base(got), legit+"-") { + t.Fatalf("env feature_x -> %s, want branch feature_x (%s); a pushed feature-x took it over", filepath.Base(got), legit) + } + if err == nil || !strings.Contains(err.Error(), "feature-x") { + t.Fatalf("want collision error naming feature-x, got %v", err) + } +} + +func TestCorrectedBranchCollisionSkipsAll(t *testing.T) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "feature-x") + gitT(t, f.control, "branch", "feature.x") + err := f.deploy(false) + if exists(filepath.Join(f.basedir, "feature_x")) { + t.Fatal("colliding corrected branches must not deploy feature_x") + } + if err == nil || !strings.Contains(err.Error(), "feature-x") || !strings.Contains(err.Error(), "feature.x") { + t.Fatalf("want collision error naming both branches, got %v", err) + } + if f.env("main") == "" { + t.Fatal("collision must not block other envs") + } +} -- 2.47.3