diff --git a/.golangci.yml b/.golangci.yml index 1ea75c38..8eed4434 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -221,10 +221,14 @@ linters: linters: [forbidigo] text: os\.Exit|context\.(Background|TODO) # The co-signer is a program of its own, which imports the standard - # library alone (depguard's cosign): its one HTTP client is - # github.go's, which app.go's token calls with, and its lock is - # lock_unix.go's. Each exclusion names its file, so a second client - # or lock elsewhere in the package still fails. + # library alone (depguard's cosign): it exits with its status, makes + # its run's context and logs to the journal through its stderr; its + # one HTTP client is github.go's, which app.go's token calls with, + # and its lock is lock_unix.go's. Each exclusion names its file, so a + # second client or lock elsewhere in the package still fails. + - path: ^cmd/devvm-cosign/ + linters: [forbidigo] + text: os\.(Exit|Stderr)|context\.(Background|TODO) - path: ^internal/cosign/(github|app)\.go$ linters: [forbidigo] text: reach the web through internal/fetch diff --git a/cmd/devvm-cosign/main.go b/cmd/devvm-cosign/main.go new file mode 100644 index 00000000..da1f9256 --- /dev/null +++ b/cmd/devvm-cosign/main.go @@ -0,0 +1,26 @@ +// Command devvm-cosign is the co-signer of devvm's releases and bases: a +// program of its own, on a machine of the maintainer's, that rebuilds +// each build CI hands over, signs it only when its own build matches, and +// makes and publishes its release once two of the three keys signed it. +// It reads its keys from systemd's credentials. Its code is in +// internal/cosign; packaging/cosign has its systemd units and install +// script. +package main + +import ( + "context" + "os" + "os/signal" + "syscall" + + "github.com/devvmhq/devvm/internal/cosign" +) + +func main() { + // The run's own context, ended by systemd's stop (TERM) or Ctrl+C, + // which ends a build and its container through release.sh's traps. + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + code := cosign.Main(ctx, os.Args[1:], cosign.Env{Credentials: os.Getenv("CREDENTIALS_DIRECTORY")}, os.Stderr) + stop() + os.Exit(code) +} diff --git a/internal/cosign/base.go b/internal/cosign/base.go new file mode 100644 index 00000000..430b0ac3 --- /dev/null +++ b/internal/cosign/base.go @@ -0,0 +1,276 @@ +package cosign + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strconv" + + "github.com/devvmhq/devvm/internal/minisign" +) + +// base signs, then publishes, the newest base CI handed over, as release +// does a release, with these differences. Only the newest successful run +// of the base workflow counts, as each base replaces the last. An index +// whose every file a past rebuild of the co-signer's matched, and which is +// the last index it signed but for its serial and expiry, is signed +// without another rebuild, so an unchanged base is re-signed well inside +// its 30 days. Its release, base-, is made at the index's commit, +// and is never GitHub's latest release, which is devvm's newest release's. +func (c *Cosigner) base(ctx context.Context, s *State, rs []Release) error { + l := &s.Base.Ledger + // The first page holds the newest runs, and only the newest counts. + runs, err := c.GitHub.Runs(ctx, c.Repo, c.Base.Workflow, func(Run) bool { return true }) + if err != nil { + return fmt.Errorf("listing CI's runs of %s: %w", c.Base.Workflow, err) + } + var run Run + for _, r := range runs { + if fromWorkflow(r, c.Repo, c.Base.Workflow) && r.HeadBranch == "main" { + run = r + break + } + } + runKey := strconv.FormatInt(run.ID, 10) + if _, refused := l.refusedRun(run.ID); run.ID == 0 || refused || l.Published[l.Runs[runKey]] { + return nil // none yet, refused (held reports it), or done + } + var idx BaseIndex + h, err := c.stage(ctx, c.Base, run, indexName, func(data []byte) (Manifest, error) { + i, m, err := ParseIndex(data, c.now(), c.Base.MaxSnapshotAge) + idx = i + return m, err + }) + if err != nil { + return err + } + key := strconv.FormatUint(idx.Serial, 10) + tag := basePrefix + key + signed := l.Signed[key] + switch { + case l.Alerts[key].active(): + return nil + case signed == "" && idx.Serial <= s.Base.Last: + // An alert, until a maintainer acks it; acked, it's left alone. + if _, raised := l.Alerts[key]; !raised { + l.alert(key, fmt.Sprintf("refused: CI handed it over, but its serial isn't above %d, the highest the co-signer signed, so it's an older base replayed; find out why CI built it", s.Base.Last)) + return c.save(s) + } + return nil + case signed != "" && signed != h.m.sum(): + return fmt.Errorf("refused: %s's index (%s) isn't the one the co-signer signed for it (%s)", tag, h.m.sum(), signed) + case l.Refused[h.m.sum()].active(): + return nil + } + draft, err := c.ownDraft(ctx, l, key, tag, rs) + if err != nil { + return err + } + if signed == "" { + was := c.built + if ok, err := c.rebuildBase(ctx, s, tag, idx, h); err != nil || !ok { + return err + } + // A build took CI's files off the disk: staged again, and the same + // index, for the upload. + if !was && c.built { + again, err := c.stage(ctx, c.Base, run, indexName, func(data []byte) (Manifest, error) { + _, m, err := ParseIndex(data, c.now(), c.Base.MaxSnapshotAge) + return m, err + }) + if err != nil { + return err + } + if !bytes.Equal(again.m.Data, h.m.Data) { + return fmt.Errorf("refused: CI's artifact's %s changed while the co-signer built it", indexName) + } + h = again + } + } + return c.publishBase(ctx, s, tag, idx, draft, h) +} + +// rebuildBase records idx as signed: at once when it's the last index +// the co-signer signed but for its serial and expiry, and every file is +// one a past rebuild matched, and otherwise once the co-signer's own +// rebuild of it matches, recording each file it checked; a mismatch +// writes a report and records the index refused, and returns false. +func (c *Cosigner) rebuildBase(ctx context.Context, s *State, tag string, idx BaseIndex, h handover) (bool, error) { + key := strconv.FormatUint(idx.Serial, 10) + var unchecked []string + for _, name := range sortedKeys(h.m.Files) { + if _, ok := s.Base.Checked[h.m.Files[name]]; !ok { + unchecked = append(unchecked, name) + } + } + if len(unchecked) == 0 && idx.shape() == s.Base.Shape { + c.logf("%s: the last base it signed, with a new serial and expiry, so it's signed without a rebuild", tag) + } else { + if err := oneBuild(&c.built, h); err != nil { + return false, err + } + c.logf("%s: CI's signature and files check out, and %d files are new; rebuilding it", tag, len(unchecked)) + diffs, err := buildBase(ctx, c.BaseBuilder, c.Dir, tag, idx, h, unchecked) + if err != nil { + return false, c.buildFailed(ctx, s, &s.Base.Ledger, tag, key, h, err) + } + if len(diffs) > 0 { + path, err := report(c.Dir, c.now(), tag, h.m, diffs) + if err != nil { + return false, err + } + s.Base.refuse(h.m.sum(), key, h.run.ID) + c.logf("%s: %v: %d files differ, in %s", tag, errMismatch, len(diffs), path) + return false, c.save(s) + } + for _, sum := range h.m.Files { + if _, ok := s.Base.Checked[sum]; !ok { + s.Base.Checked[sum] = idx.Serial + } + } + } + s.Base.Signed[key] = h.m.sum() + s.Base.Runs[strconv.FormatInt(h.run.ID, 10)] = key + s.Base.Last = max(s.Base.Last, idx.Serial) + s.Base.Shape = idx.shape() + return true, c.save(s) +} + +// buildBase builds idx, base tag, with builder, its files in a folder of +// the state folder dir's, and compares it with h, CI's, returning each +// file that differs; unchecked are the files no rebuild has matched yet. +// An error is a build that failed, rather than differed. +func buildBase(ctx context.Context, builder BaseBuilder, dir, tag string, idx BaseIndex, h handover, unchecked []string) ([]diff, error) { + work, err := newOut(dir, tag) + if err != nil { + return nil, err + } + defer os.RemoveAll(work) + out := filepath.Join(work, "out") + if err := os.Mkdir(out, 0o700); err != nil { + return nil, err + } + if err := builder.Build(ctx, idx, out); err != nil { + return nil, fmt.Errorf("%v: %w", unchecked, err) + } + return compareBuild(h.m, out) +} + +// baseTitle and baseNotes are a base's release's title and notes, which +// the co-signer writes from its index. +func baseTitle(i BaseIndex) string { return "devvm's base " + strconv.FormatUint(i.Serial, 10) } + +func baseNotes(i BaseIndex) string { + return fmt.Sprintf("devvm's base, format %d, built from devvm %s and Ubuntu's snapshot %s, for devvm %s and later. It expires at the end of %s (UTC).\n", + i.Format, i.Commit, i.Snapshot, i.MinDevvm, i.Expires) +} + +// publishBase signs h's index, makes tag's draft release at the index's +// commit if the co-signer has none, uploads every file, and publishes it, +// never as GitHub's latest, once two of three keys signed it and the +// draft is exactly what it uploaded; then it checks it again. +func (c *Cosigner) publishBase(ctx context.Context, s *State, tag string, idx BaseIndex, draft Release, h handover) error { + l, key := &s.Base.Ledger, strconv.FormatUint(idx.Serial, 10) + sig, err := c.Base.Secret.Sign(h.m.Data, minisign.Base.Comment(h.m.Subject)) + if err != nil { + return err + } + if err := c.Base.Keys.Check(h.m.Data, map[minisign.Role][]byte{minisign.CI: h.ciSig, minisign.Cosign: sig}, h.m.Subject); err != nil { + return fmt.Errorf("not published: %w", err) + } + if draft.ID == 0 { + if draft, err = c.GitHub.CreateRelease(ctx, c.Repo, tag, idx.Commit, baseTitle(idx), baseNotes(idx), false); err != nil { + return fmt.Errorf("making its draft release: %w", err) + } + l.Drafts[key] = append(l.Drafts[key], draft.ID) + if err := c.save(s); err != nil { + return err + } + } + ids, err := c.upload(ctx, draft, h.assets(sig), "") + if err != nil { + return err + } + c.logf("%s: signed, and its draft release holds its files", tag) + now, err := c.GitHub.Release(ctx, c.Repo, draft.ID) + if err != nil { + return err + } + if err := exact(now, tag, baseTitle(idx), baseNotes(idx), ids, ""); err != nil { + return fmt.Errorf("not published: %w", err) + } + pub, err := c.GitHub.Publish(ctx, c.Repo, draft.ID, false, false) + if err != nil { + return fmt.Errorf("publishing: %w", err) + } + if err := exact(pub, tag, baseTitle(idx), baseNotes(idx), ids, ""); err != nil { + l.alert(key, "published, but "+err.Error()+": compare its files with its index by hand; devvm refuses a file that doesn't match it") + return c.save(s) + } + l.Published[key] = true + c.logf("%s: published", tag) + return c.save(s) +} + +// publishedBase looks at r, a published base, as publishedRelease does a +// release: its own draft that it didn't see published is checked. +func (c *Cosigner) publishedBase(ctx context.Context, s *State, r Release) error { + n, _ := baseSerial(r.TagName) + l, key := &s.Base.Ledger, strconv.FormatUint(n, 10) + switch { + case l.Published[key] || l.Alerts[key].active(): + return nil + case l.Signed[key] != "" && l.draft(key) == r.ID: + if err := c.checkPublishedBase(ctx, s, r, key); err != nil { + l.alert(key, "the co-signer's draft was published before its last check, and "+err.Error()+": compare its files with its index by hand, then ack it") + } else { + l.Published[key] = true + } + return c.save(s) + } + return nil // not its own: foreign alerts on it, if it's new +} + +// checkPublishedBase checks r, the co-signer's draft of base key, +// published: its index is the one it signed, CI's signature and its own +// check out, and every file has its SHA-256, downloaded. +func (c *Cosigner) checkPublishedBase(ctx context.Context, s *State, r Release, key string) error { + data, _, err := c.download(ctx, r, indexName, maxManifest) + if err != nil { + return err + } + if sha256Hex(data) != s.Base.Signed[key] { + return fmt.Errorf("its index isn't the one the co-signer signed") + } + _, m, err := parseIndex(data) + if err != nil { + return err + } + var names []string + for _, role := range []minisign.Role{minisign.CI, minisign.Cosign} { + name := minisign.SigName(indexName, role) + sig, _, err := c.download(ctx, r, name, maxSig) + if err != nil { + return err + } + if err := c.Base.Keys.CheckRole(role, m.Data, sig, m.Subject); err != nil { + return err + } + names = append(names, name) + } + return c.GitHub.checkFiles(ctx, c.Repo, r, m, names...) +} + +// shape is the SHA-256 of i with its serial and expiry left out: what +// two indexes of one unchanged base share. +func (i BaseIndex) shape() string { + i.Serial, i.Expires = 0, "" + data, _ := json.Marshal(i) + return sha256Hex(data) +} + +// sum is the manifest's SHA-256. +func (m Manifest) sum() string { return sha256Hex(m.Data) } diff --git a/internal/cosign/base_test.go b/internal/cosign/base_test.go new file mode 100644 index 00000000..f2a72587 --- /dev/null +++ b/internal/cosign/base_test.go @@ -0,0 +1,321 @@ +package cosign + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/devvmhq/devvm/internal/minisign" +) + +// fakeBaseBuilder stands in for phase 5's base build: it writes files +// into out, and counts its builds. +type fakeBaseBuilder struct { + files map[string][]byte + err error + builds int +} + +func (b *fakeBaseBuilder) Build(_ context.Context, _ BaseIndex, out string) error { + b.builds++ + if b.err != nil { + return b.err + } + for name, data := range b.files { + if err := os.WriteFile(filepath.Join(out, name), data, 0o600); err != nil { + return err + } + } + return nil +} + +// baseSetup is a setup with base keys, and a base draft's files. +type baseSetup struct { + *setup + base keys + builder *fakeBaseBuilder +} + +func newBaseSetup(t *testing.T, serial uint64) *baseSetup { + t.Helper() + b := &baseSetup{setup: newSetup(t, "0.2.0"), base: newKeys(t, minisign.Base, "base.yml"), builder: &fakeBaseBuilder{}} + b.c.Base, b.c.BaseBuilder = &b.base.kind, b.builder + st := b.state(t) + st.Base.Last = serial + if err := b.c.State.Save(st); err != nil { + t.Fatal(err) + } + return b +} + +// baseFiles is a base's two files, by what's in them. +func baseFiles(image, kernel string) map[string][]byte { + return map[string][]byte{"base-arm64.erofs": []byte(image), "vmlinux-arm64": []byte(kernel)} +} + +// baseIndex is serial's index of files, at the setup's time. +func (b *baseSetup) baseIndex(serial uint64, files map[string][]byte) BaseIndex { + i := index(b.c.now()) + i.Serial = serial + i.Files = nil + for _, name := range sortedKeys(files) { + role := "image" + if strings.HasPrefix(name, "vmlinux") { + role = "kernel" + } + i.Files = append(i.Files, BaseFile{Arch: "arm64", Role: role, Name: name, SHA256: sha256Hex(files[name]), Size: int64(len(files[name]))}) + } + return i +} + +// ci hands base i over with files, as CI's base workflow does: a run on +// main with them, the index and CI's signature as its artifact. +func (b *baseSetup) ci(t *testing.T, i BaseIndex, files map[string][]byte) []byte { + t.Helper() + data, _ := json.Marshal(i) + a := map[string][]byte{indexName: data, minisign.SigName(indexName, minisign.CI): b.base.ci.Sign(data, minisign.Base.Comment(i.Subject()))} + for n, d := range files { + a[n] = d + } + b.gh.addRun("base.yml", "main", testCommit, "schedule", "base", a) + b.builder.files = files + return data +} + +// draft hands serial's base over with files. +func (b *baseSetup) draft(t *testing.T, serial uint64, files map[string][]byte) []byte { + t.Helper() + return b.ci(t, b.baseIndex(serial, files), files) +} + +// published is whether base tag is published at the index's commit, +// never as GitHub's latest, with a co-signer signature that checks out. +func (b *baseSetup) published(t *testing.T, tag string) bool { + t.Helper() + r := b.gh.release(tag) + if r == nil || r.Draft { + return false + } + sig := r.file(minisign.SigName(indexName, minisign.Cosign)) + var i BaseIndex + if err := json.Unmarshal(r.file(indexName), &i); err != nil { + t.Fatal(err) + } + if err := b.base.kind.Keys.CheckRole(minisign.Cosign, r.file(indexName), sig, i.Subject()); err != nil { + t.Errorf("%s's co-signer signature: %v", tag, err) + } + if r.Latest != "false" || r.Prerelease || r.Target != testCommit || r.Name != "devvm's base "+strconv.FormatUint(i.Serial, 10) { + t.Errorf("%s: %+v", tag, r) + } + return true +} + +// A base with new files is rebuilt, signed and published, and its files +// recorded as checked; the next base with the same files, a new serial +// and expiry, is signed without a rebuild. +func TestBaseRebuiltThenResigned(t *testing.T) { + b := newBaseSetup(t, 40) + files := baseFiles("image 1", "kernel 1") + b.draft(t, 41, files) + if err := b.c.Run(t.Context()); err != nil { + t.Fatalf("Run: %v\n%s", err, b.log) + } + if !b.published(t, "base-41") || b.builder.builds != 1 { + t.Fatalf("base-41: %d builds\n%s", b.builder.builds, b.log) + } + st := b.state(t) + if st.Base.Last != 41 || st.Base.Checked[sha256Hex(files["vmlinux-arm64"])] != 41 || !st.Base.Published["41"] { + t.Errorf("state: %+v", st.Base) + } + if err := b.c.Run(t.Context()); err != nil || b.builder.builds != 1 || len(b.gh.releases) != 1 { + t.Errorf("a run with nothing new: %v, %d builds", err, b.builder.builds) + } + b.c.Now = func() time.Time { return time.Date(2026, 12, 8, 12, 0, 0, 0, time.UTC) } + b.draft(t, 42, files) + if err := b.c.Run(t.Context()); err != nil { + t.Fatalf("Run: %v\n%s", err, b.log) + } + if !b.published(t, "base-42") || b.builder.builds != 1 || !strings.Contains(b.log.String(), "without a rebuild") { + t.Errorf("base-42: %d builds\n%s", b.builder.builds, b.log) + } + // A new base, then base-41's older files again with a new serial: each + // is rebuilt, as only the last base signed is re-signed as it is, so + // files checked once can't come back on their own. + b.draft(t, 43, baseFiles("image 2", "kernel 2")) + if err := b.c.Run(t.Context()); err != nil || !b.published(t, "base-43") { + t.Fatalf("base-43: %v\n%s", err, b.log) + } + b.draft(t, 44, files) + if err := b.c.Run(t.Context()); err != nil { + t.Fatalf("Run: %v\n%s", err, b.log) + } + if !b.published(t, "base-44") || b.builder.builds != 3 { + t.Errorf("an older base's files again: %d builds, want 3", b.builder.builds) + } + b.c.BaseBuilder = NoBaseBuild{} + b.draft(t, 45, baseFiles("image 2", "kernel 2")) + if err := b.c.Run(t.Context()); !errors.Is(err, errNoBaseBuild) || b.published(t, "base-45") { + t.Errorf("base-43's files after base-44's, with no rebuild: %v", err) + } +} + +// A base with a file no rebuild has matched isn't signed until the +// co-signer can rebuild bases; one whose rebuild differs is refused with +// a report, and every run says so; an older serial is refused. +func TestBaseRefused(t *testing.T) { + b := newBaseSetup(t, 40) + b.c.BaseBuilder = NoBaseBuild{} + b.draft(t, 41, baseFiles("image 1", "kernel 1")) + if err := b.c.Run(t.Context()); !errors.Is(err, errNoBaseBuild) || b.published(t, "base-41") { + t.Errorf("no base build: %v", err) + } + + b = newBaseSetup(t, 40) + b.draft(t, 41, baseFiles("image 1", "kernel 1")) + b.builder.files = baseFiles("image 1", "kernel 2") + for range 2 { + if err := b.c.Run(t.Context()); !errors.Is(err, errMismatch) || !strings.Contains(err.Error(), "retry base-41") || b.published(t, "base-41") { + t.Errorf("a mismatch: %v", err) + } + } + if st := b.state(t); len(st.Base.Refused) != 1 || len(st.Base.Checked) != 0 || b.builder.builds != 1 { + t.Errorf("state: %+v, %d builds", st.Base, b.builder.builds) + } + + b = newBaseSetup(t, 41) + b.draft(t, 41, baseFiles("image 1", "kernel 1")) + if err := b.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "replayed") || b.builder.builds != 0 { + t.Errorf("an older serial: %v", err) + } + + // A base whose build keeps failing is refused at its third failure, as + // a release is, and devvm-cosign retry builds it again. + b = newBaseSetup(t, 40) + b.draft(t, 41, baseFiles("image 1", "kernel 1")) + b.builder.err = errors.New("qemu-aarch64: not found") + for n := 1; n < maxBuildFailures; n++ { + if err := b.c.Run(t.Context()); err == nil || errors.Is(err, errBuildFailed) { + t.Fatalf("failure %d: %v", n, err) + } + } + for range 2 { + if err := b.c.Run(t.Context()); !errors.Is(err, errBuildFailed) || !strings.Contains(err.Error(), "retry base-41") || b.builder.builds != maxBuildFailures { + t.Fatalf("refused: %v, %d builds", err, b.builder.builds) + } + } + if err := b.c.Clear("base-41", true); err != nil { + t.Fatal(err) + } + b.builder.err = nil + if err := b.c.Run(t.Context()); err != nil || !b.published(t, "base-41") { + t.Errorf("after retry: %v\n%s", err, b.log) + } +} + +// A base whose CI signature is for another serial, or whose snapshot is +// older than the bound, is refused before anything is built, whether or +// not its files were checked before: an unchanged base can't be kept on +// an old snapshot by re-signing it. +func TestBaseIndexChecked(t *testing.T) { + b := newBaseSetup(t, 40) + i := b.baseIndex(41, baseFiles("image 1", "kernel 1")) + data, _ := json.Marshal(i) + a := map[string][]byte{indexName: data, minisign.SigName(indexName, minisign.CI): b.base.ci.Sign(data, minisign.Base.Comment("1 42 2026-12-31"))} + for n, d := range baseFiles("image 1", "kernel 1") { + a[n] = d + } + b.gh.addRun("base.yml", "main", testCommit, "schedule", "base", a) + if err := b.c.Run(t.Context()); err == nil || b.builder.builds != 0 { + t.Errorf("another serial's signature: %v", err) + } + + b = newBaseSetup(t, 40) + files := baseFiles("image 1", "kernel 1") + b.draft(t, 41, files) + if err := b.c.Run(t.Context()); err != nil || !b.published(t, "base-41") { + t.Fatalf("base-41: %v", err) + } + b.c.Now = func() time.Time { return time.Date(2027, 1, 31, 12, 0, 0, 0, time.UTC) } + stale := b.baseIndex(42, files) + stale.Snapshot = "20261201T000000Z" + b.ci(t, stale, files) + if err := b.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "days old") || b.published(t, "base-42") { + t.Errorf("a re-signed base on a 61-day snapshot: %v", err) + } +} + +// A base someone else published, newer than the state, is an alert, and a +// base the co-signer signed, however long ago it expired, counts in +// checkBehind. +func TestBasePublishedElsewhere(t *testing.T) { + b := newBaseSetup(t, 40) + b.gh.addRelease("base-41", false, nil) + if err := b.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: base-41") { + t.Errorf("a base someone else published: %v", err) + } + + b = newBaseSetup(t, 40) + old := b.baseIndex(41, baseFiles("image 1", "kernel 1")) + old.Expires = "2025-01-01" + data, _ := json.Marshal(old) + sig, err := b.base.cosign.Sign(data, minisign.Base.Comment(old.Subject())) + if err != nil { + t.Fatal(err) + } + b.gh.addRelease("base-41", false, map[string][]byte{indexName: data, minisign.SigName(indexName, minisign.Cosign): sig}) + if err := b.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "behind") { + t.Errorf("an expired base the co-signer signed: %v", err) + } +} + +// A base published with its answer lost is checked as published by the +// next run, then recorded; one whose file was swapped as it was +// published is an alert. +func TestBasePublishChecked(t *testing.T) { + for _, swap := range []bool{false, true} { + b := newBaseSetup(t, 40) + b.draft(t, 41, baseFiles("image 1", "kernel 1")) + b.gh.publishAnswer = http.StatusBadGateway + if swap { + b.gh.onPublish = func(r *fakeRelease) { b.gh.put(r, "vmlinux-arm64", []byte("swapped")) } + } + if err := b.c.Run(t.Context()); err == nil { + t.Fatal("Run with the publish's answer lost") + } + b.gh.publishAnswer, b.gh.onPublish = 0, nil + err := b.c.Run(t.Context()) + switch st := b.state(t); { + case !swap && (err != nil || !st.Base.Published["41"]): + t.Errorf("the next run: %v, %+v", err, st.Base) + case swap && (err == nil || !strings.Contains(err.Error(), "ALERT: base-41") || st.Base.Published["41"]): + t.Errorf("a swapped file: %v", err) + } + } +} + +// Without base keys, bases are left alone. +func TestNoBaseKeys(t *testing.T) { + b := newBaseSetup(t, 40) + b.c.Base = nil + b.draft(t, 41, baseFiles("image 1", "kernel 1")) + if err := b.c.Run(t.Context()); err != nil || b.builder.builds != 0 || !strings.Contains(b.log.String(), "no base keys") { + t.Errorf("Run: %v\n%s", err, b.log) + } +} + +// baseSerial reads base- tags only. +func TestBaseSerial(t *testing.T) { + for tag, want := range map[string]uint64{"base-1": 1, "base-41": 41, "base-0": 0, "base-01": 0, "base-": 0, "base-1a": 0, "v1.0.0": 0, "base-99999999999999999999": 0} { + got, ok := baseSerial(tag) + if got != want || ok != (want != 0) { + t.Errorf("baseSerial(%q) = %d, %v", tag, got, ok) + } + } +} diff --git a/internal/cosign/cosigner.go b/internal/cosign/cosigner.go new file mode 100644 index 00000000..68e88ac2 --- /dev/null +++ b/internal/cosign/cosigner.go @@ -0,0 +1,492 @@ +package cosign + +import ( + "cmp" + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "time" + + "github.com/devvmhq/devvm/internal/minisign" +) + +// A Cosigner is one run of the co-signer: for each release and base CI +// hands over as a workflow artifact, it rebuilds it and signs it on a +// match, then makes its release, the only one that does, and publishes it +// once two of the three keys signed it. +type Cosigner struct { + GitHub Client + // Repo is devvm's repository and Tap the Homebrew tap's. + Repo, Tap string + // Release is the release keys, and Base the base's, or nil while the + // co-signer has none, when it leaves bases alone. + Release Kind + Base *Kind + // Builder rebuilds a release, and BaseBuilder a base. + Builder ReleaseBuilder + BaseBuilder BaseBuilder + State Store + // Dir is the state folder: kept/, reports/, src/ and stage/ are in + // it, none of which the builds' containers can reach. Work is the + // folder, in the build folder, each build's files go in, which they + // write. + Dir, Work string + // Log gets what each run does, for the journal. + Log io.Writer + // Now is the clock; time.Now by default. + Now func() time.Time + + // built is whether this run built already (oneBuild). + built bool +} + +// basePrefix starts a base release's tag, base-. +const basePrefix = "base-" + +// errWaiting is a release that isn't ready to publish yet, such as one +// waiting for the old key's signature: the next run looks again. +var errWaiting = errors.New("waiting") + +func (c *Cosigner) now() time.Time { + if c.Now != nil { + return c.Now() + } + return time.Now() +} + +func (c *Cosigner) logf(format string, args ...any) { + fmt.Fprintf(c.Log, format+"\n", args...) +} + +// Run looks once at every release CI handed over, and every release on +// GitHub the co-signer hasn't finished with: what's published is checked +// first (a release someone else published is an alert), then each of +// CI's releases is rebuilt, signed, made a draft and published, oldest +// first, then CI's newest base. One that fails is logged and the rest +// still run. Run returns every failure, and every alert and refusal that +// a maintainer hasn't cleared, on every run until they do. +func (c *Cosigner) Run(ctx context.Context) error { + c.built = false + s, err := c.State.Load() + if err != nil { + return err + } + rs, err := c.GitHub.Releases(ctx, c.Repo, settled(s)) + if err != nil { + return fmt.Errorf("listing %s's releases: %w", c.Repo, err) + } + if err := c.checkBehind(ctx, s, rs); err != nil { + return err + } + for _, dir := range []string{c.Work, filepath.Join(c.Dir, "stage"), filepath.Join(c.Dir, "src")} { + if err := emptyDir(dir); err != nil { + return err + } + } + var errs []error + note := func(tag string, err error) { + switch { + case err == nil: + case errors.Is(err, errWaiting): + c.logf("%s: %v", tag, err) + default: + c.logf("%s: %v", tag, err) + errs = append(errs, fmt.Errorf("%s: %w", tag, err)) + } + } + // GitHub's latest release too, which /releases/latest/download/ serves + // to curl | bash, wherever the list puts it. + latest, found, err := c.GitHub.Latest(ctx, c.Repo) + note("the latest release", err) + seen := rs + if found { + seen = append(slices.Clip(rs), latest) + } + raised := foreign(&s, seen) + if found && staleLatest(&s, latest) { + raised = true + } + if raised { + note("published releases", c.save(&s)) + } + for _, r := range sorted(rs, true) { + if !r.Draft { + note(r.TagName, c.publishedRelease(ctx, &s, r)) + } + } + cands, err := c.releaseRuns(ctx, s, rs) + note("CI's releases", err) + for _, cd := range cands { + note(cd.tag, c.release(ctx, &s, cd, rs)) + } + if c.Base == nil { + c.logf("no base keys in the config, so bases are left alone") + } else { + for _, r := range sorted(rs, false) { + if !r.Draft { + note(r.TagName, c.publishedBase(ctx, &s, r)) + } + } + note("CI's base", c.base(ctx, &s, rs)) + } + return errors.Join(append(errs, held(s)...)...) +} + +// foreign raises an alert for each published release past the +// watermark, or a draft from before init published since, that isn't a +// draft the co-signer made, whatever its tag: only the co-signer +// publishes, so whoever else did, by hand or with a stolen token, is +// someone to find out about. Each release has its own alert, by its tag +// and ID, which once acked stays, so that release isn't alerted on again, +// but another of the same tag is. It says whether it raised one. +func foreign(s *State, rs []Release) bool { + own := ownIDs(*s) + raised := false + for _, r := range rs { + if _, seen := s.Others[foreignKey(r)]; r.Draft || own[r.ID] || !past(*s, r) || seen { + continue + } + s.Others[foreignKey(r)] = Alert{Reason: "published, but not by the co-signer, which makes and publishes every release: find out who published it, delete it if it isn't one the co-signer made, and check who can write the repo", Raised: 1} + raised = true + } + return raised +} + +// staleLatest raises an alert for latest, GitHub's latest release, when +// it's an older release made the latest again, which the install script's +// default then downloads, such as one with a known flaw: one from before +// the state began that isn't the latest release init saw, or is but is +// older than one the co-signer published, or one of the co-signer's own +// older than another it published. One someone else +// published since is foreign's. The alert is by its tag and ID, as +// foreign's, behind latest:. It says whether it raised one. +func staleLatest(s *State, latest Release) bool { + key := "latest:" + foreignKey(latest) + if _, seen := s.Others[key]; seen { + return false + } + switch v, _, _ := tagKind(latest.TagName); { + case !past(*s, latest) && latest.ID == s.InitLatest && !olderThanPublished(*s, v): + return false + case past(*s, latest) && (!ownIDs(*s)[latest.ID] || !olderThanPublished(*s, v)): + return false + } + s.Others[key] = Alert{Reason: "GitHub's latest release, which the install script downloads by default, is an older release than the newest one, and only the co-signer publishes releases: find out who made it the latest, and make the newest release the latest again", Raised: 1} + return true +} + +// olderThanPublished is whether v is a release's version older than one +// the co-signer published that isn't a prerelease, which GitHub's latest +// release always is. +func olderThanPublished(s State, v version) bool { + if v.raw == "" { + return false + } + for p := range s.Release.Published { + if pv := mustVersion(p); !pv.prerelease() && pv.compare(v) > 0 { + return true + } + } + return false +} + +// foreignKey is the alert's key for r, a release someone else published. +func foreignKey(r Release) string { return r.TagName + "#" + strconv.FormatInt(r.ID, 10) } + +// past is whether r is new since the state began: above the watermark, +// or one of the drafts there were then. +func past(s State, r Release) bool { + return r.ID > s.Watermark || slices.Contains(s.InitDrafts, r.ID) +} + +// ownIDs is the IDs of every draft release the co-signer made. +func ownIDs(s State) map[int64]bool { + own := map[int64]bool{} + for _, l := range []Ledger{s.Release.Ledger, s.Base.Ledger} { + for _, ids := range l.Drafts { + for _, id := range ids { + own[id] = true + } + } + } + return own +} + +// held is every alert and refusal in s that a maintainer hasn't cleared, +// as an error each, so every run fails until they do. +func held(s State) []error { + var errs []error + for _, key := range sortedKeys(s.Others) { + if a := s.Others[key]; a.active() { + errs = append(errs, fmt.Errorf("ALERT: %s: %s; once you've dealt with it, devvm-cosign ack %s", key, a.Reason, key)) + } + } + for _, k := range []struct { + l Ledger + prefix string + }{{s.Release.Ledger, "v"}, {s.Base.Ledger, basePrefix}} { + for _, key := range sortedKeys(k.l.Alerts) { + if a := k.l.Alerts[key]; a.active() { + errs = append(errs, fmt.Errorf("ALERT: %s%s: %s; once you've dealt with it, devvm-cosign ack %s%s", k.prefix, key, a.Reason, k.prefix, key)) + } + } + for _, sum := range sortedKeys(k.l.Refused) { + r := k.l.Refused[sum] + switch { + case !r.active(): + case r.Why != "": + errs = append(errs, fmt.Errorf("%s%s: %w (%s): CI's manifest %s is refused (see reports/); once you've found and fixed why, devvm-cosign retry %s%s", k.prefix, r.Key, errBuildFailed, r.Why, sum, k.prefix, r.Key)) + default: + errs = append(errs, fmt.Errorf("%s%s: %w: CI's manifest %s is refused (see reports/); once you've found and fixed why, devvm-cosign retry %s%s", k.prefix, r.Key, errMismatch, sum, k.prefix, r.Key)) + } + } + } + return errs +} + +// settled is whether the co-signer is done with release r, given s: a +// published release no newer than the watermark, one of its own it +// finished, or one someone else published that it has alerted on. GitHub +// lists the newest first, so a page of settled releases ends the list +// (Client.pages). +func settled(s State) func(Release) bool { + own := ownIDs(s) + return func(r Release) bool { + v, n, kind := tagKind(r.TagName) + _, alerted := s.Others[foreignKey(r)] + switch { + case r.Draft: + return false + case !past(s, r): + return true + case !own[r.ID]: + return alerted + case kind == minisign.Release: + return s.Release.Done[v.raw] + case kind == minisign.Base: + return s.Base.Published[strconv.FormatUint(n, 10)] + } + return false + } +} + +// tagKind is what tag names: a release's version, v, or a base's +// serial, base-, and its kind; "" for neither. +func tagKind(tag string) (version, uint64, minisign.Kind) { + if s, ok := strings.CutPrefix(tag, "v"); ok { + if v, err := parseVersion(s); err == nil { + return v, 0, minisign.Release + } + } + if n, ok := baseSerial(tag); ok { + return version{}, n, minisign.Base + } + return version{}, 0, "" +} + +// sorted is rs's releases (releases true) or bases, oldest first, each +// with a tag of its kind's form. +func sorted(rs []Release, releases bool) []Release { + type keyed struct { + r Release + v version + n uint64 + } + var out []keyed + for _, r := range rs { + v, n, kind := tagKind(r.TagName) + if releases && kind == minisign.Release || !releases && kind == minisign.Base { + out = append(out, keyed{r: r, v: v, n: n}) + } + } + slices.SortStableFunc(out, func(a, b keyed) int { + if releases { + return a.v.compare(b.v) + } + return cmp.Compare(a.n, b.n) + }) + var rel []Release + for _, k := range out { + rel = append(rel, k.r) + } + return rel +} + +// baseSerial is the serial a base's tag, base-, names. +func baseSerial(tag string) (uint64, bool) { + s, ok := strings.CutPrefix(tag, basePrefix) + if !ok || s == "" || s[0] == '0' || len(s) > 18 || strings.Trim(s, "0123456789") != "" { + return 0, false + } + n, err := strconv.ParseUint(s, 10, 64) + return n, err == nil +} + +// checkBehind refuses a state older than what GitHub shows the +// co-signer signed: a release or base, a draft or published, with its +// signature and newer than the state's last, which a state it wrote never +// is, as it records a version before it uploads its signature. That's a +// state.json restored from an old backup, or replaced, which would let it +// sign an older release again. Only a signature that checks out with the +// co-signer's own key counts, so a file of that name that anyone uploaded +// stops nothing, and a base counts however long ago it expired. GitHub +// can only make this refuse, never let a run sign more. +func (c *Cosigner) checkBehind(ctx context.Context, s State, rs []Release) error { + last, err := parseVersion(s.Release.Last) + if err != nil { + return err + } + // ours is whether r has the co-signer's signature of its manifest + // name, checked with ks's cosign key and the trusted comment that + // subject gives the manifest's bytes. + ours := func(r Release, ks minisign.Keys, name string, subject func([]byte) string) bool { + if _, ok := r.asset(minisign.SigName(name, minisign.Cosign)); !ok { + return false + } + data, _, err := c.download(ctx, r, name, maxManifest) + if err != nil { + return false + } + sig, _, err := c.download(ctx, r, minisign.SigName(name, minisign.Cosign), maxSig) + return err == nil && ks.CheckRole(minisign.Cosign, data, sig, subject(data)) == nil + } + for _, r := range rs { + v, n, kind := tagKind(r.TagName) + if kind == minisign.Release && v.compare(last) > 0 && ours(r, c.Release.Keys, sumsName, func([]byte) string { return v.raw }) { + return fmt.Errorf("state.json is behind GitHub: %s has the co-signer's signature, but the state's last release is %s; restore state.json from its backup", r.TagName, s.Release.Last) + } + if kind == minisign.Base && n > s.Base.Last && c.Base != nil && ours(r, c.Base.Keys, indexName, indexSubject) { + return fmt.Errorf("state.json is behind GitHub: %s has the co-signer's signature, but the state's last base is %d; restore state.json from its backup", r.TagName, s.Base.Last) + } + } + return nil +} + +// Init writes the first state.json, from the newest release and base +// published on GitHub, so the co-signer signs only newer ones. It refuses +// to replace a state there is. +func (c *Cosigner) Init(ctx context.Context) error { + if _, err := c.State.Load(); !errors.Is(err, errNoState) { + if err == nil { + return fmt.Errorf("%s is already there: the co-signer has a state", c.State.Path) + } + return err + } + // The list is read until a page of published releases after the newest + // published release and base, or its end. + var release, base bool + rs, err := c.GitHub.Releases(ctx, c.Repo, func(r Release) bool { + _, _, kind := tagKind(r.TagName) + release = release || !r.Draft && kind == minisign.Release + base = base || !r.Draft && kind == minisign.Base + return !r.Draft && release && (base || c.Base == nil) + }) + if err != nil { + return fmt.Errorf("listing %s's releases: %w", c.Repo, err) + } + last, serial := "0.0.0", uint64(0) + for _, r := range sorted(rs, true) { + if !r.Draft { + last = strings.TrimPrefix(r.TagName, "v") + } + } + for _, r := range sorted(rs, false) { + if !r.Draft { + serial, _ = baseSerial(r.TagName) + } + } + s := newState(last, serial) + for _, r := range rs { + s.Watermark = max(s.Watermark, r.ID) + if r.Draft { + s.InitDrafts = append(s.InitDrafts, r.ID) + } + } + latest, found, err := c.GitHub.Latest(ctx, c.Repo) + if err != nil { + return fmt.Errorf("reading %s's latest release: %w", c.Repo, err) + } + if found { + s.InitLatest, s.Watermark = latest.ID, max(s.Watermark, latest.ID) + } + if err := c.State.Save(s); err != nil { + return err + } + c.logf("wrote %s: it signs releases newer than %s and bases after %d, and alerts on any release published after GitHub's release %d but its own", c.State.Path, last, serial, s.Watermark) + return nil +} + +// Clear clears what a maintainer dealt with for tag, a release's or a +// base's: its refusals (retry true), so the next run rebuilds it, or its +// alert (retry false), so the next run looks at it again. It never runs +// on its own: devvm-cosign retry and ack are the maintainer's. +func (c *Cosigner) Clear(tag string, retry bool) error { + s, err := c.State.Load() + if err != nil { + return err + } + if a, ok := s.Others[tag]; ok && !retry { + if !a.active() { + return fmt.Errorf("%s has no alert to clear", tag) + } + a.Acked = a.Raised + s.Others[tag] = a + if err := c.State.Save(s); err != nil { + return err + } + c.logf("%s: its alert is cleared, and it isn't alerted on again", tag) + return nil + } + v, n, kind := tagKind(tag) + l, key := &s.Release.Ledger, v.raw + switch kind { + case minisign.Release: + case minisign.Base: + l, key = &s.Base.Ledger, strconv.FormatUint(n, 10) + default: + return fmt.Errorf("%q isn't a release's tag, v, or a base's, base-", tag) + } + switch { + case retry && l.retry(key) == 0: + return fmt.Errorf("%s has no refusal to retry", tag) + case !retry && !l.ack(key): + return fmt.Errorf("%s has no alert to clear", tag) + } + if err := c.State.Save(s); err != nil { + return err + } + if retry { + c.logf("%s: its refusals are cleared, so the next run rebuilds CI's build of it again", tag) + } else { + c.logf("%s: its alert is cleared, so the next run looks at it again", tag) + } + return nil +} + +// emptyDir makes dir, or empties it in place: never a new folder of its +// name, as the podman service's unit binds work/ writable when it starts, +// and a folder made again would be another, which it can't write. +func emptyDir(dir string) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + entries, err := os.ReadDir(dir) + if err != nil { + return err + } + for _, e := range entries { + if err := os.RemoveAll(filepath.Join(dir, e.Name())); err != nil { + return err + } + } + return nil +} + +// save writes s, logging nothing: a failure is the caller's. +func (c *Cosigner) save(s *State) error { return c.State.Save(*s) } diff --git a/internal/cosign/cosigner_test.go b/internal/cosign/cosigner_test.go new file mode 100644 index 00000000..9442de7f --- /dev/null +++ b/internal/cosign/cosigner_test.go @@ -0,0 +1,1172 @@ +package cosign + +import ( + "bytes" + "context" + "errors" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/devvmhq/devvm/internal/minisign" + "github.com/devvmhq/devvm/internal/minisign/minisigntest" +) + +// keys is one kind's test keys: CI's and recovery's to sign with, and the +// co-signer's. +type keys struct { + ci, recovery minisigntest.Key + cosign minisign.SecretKey + kind Kind +} + +func newKeys(t testing.TB, kind minisign.Kind, workflow string) keys { + t.Helper() + k := keys{ci: minisigntest.NewKey(), recovery: minisigntest.NewKey()} + var pub string + k.cosign, _, pub = newSecret(t) + ks, err := minisign.NewKeys(kind, map[minisign.Role]string{minisign.CI: k.ci.Public(), minisign.Cosign: pub, minisign.Recovery: k.recovery.Public()}) + if err != nil { + t.Fatal(err) + } + k.kind = Kind{Keys: ks, Secret: k.cosign, Workflow: workflow, MaxSnapshotAge: maxSnapshotAge} + return k +} + +// fakeBuilder stands in for release.sh: it writes files into out, or +// fails, and counts its builds; the tag's commit, template and changelog +// are its own. +type fakeBuilder struct { + files map[string][]byte + commit string + changelog []byte + err error + builds int + // during, when set, runs as each build starts, with its out. + during func(out string) +} + +func (b *fakeBuilder) Build(_ context.Context, tag string, out string) (Built, error) { + b.builds++ + if b.during != nil { + b.during(out) + } + if b.err != nil { + return Built{}, b.err + } + if err := os.MkdirAll(out, 0o700); err != nil { + return Built{}, err + } + for name, data := range b.files { + if err := os.WriteFile(filepath.Join(out, name), data, 0o600); err != nil { + return Built{}, err + } + } + return Built{Tag: Tag{Name: tag, Commit: b.commit}, Object: fakeTagObject(tag), Formula: []byte(testTemplate), Changelog: b.changelog}, nil +} + +// releaseFiles is a release's files as release.sh builds them and their +// SHA256SUMS, for v. +func releaseFiles(v string) map[string][]byte { + files := map[string][]byte{ + "devvm-" + v + "-linux-amd64.tar.gz": []byte("linux amd64 " + v), + "devvm-" + v + "-darwin-arm64.tar.gz": []byte("darwin arm64 " + v), + "install.sh": []byte("#!/bin/bash\n# " + v + "\n"), + } + files[sumsName] = sums(files) + return files +} + +// sums is the SHA256SUMS of files, but any SHA256SUMS among them. +func sums(files map[string][]byte) []byte { + var b strings.Builder + for _, name := range sortedKeys(files) { + if name != sumsName { + b.WriteString(sha256Hex(files[name]) + " " + name + "\n") + } + } + return []byte(b.String()) +} + +// built is what release.sh's build writes for files, release v's: the +// files and their formulas. +func built(t *testing.T, v string, files map[string][]byte) map[string][]byte { + t.Helper() + out := map[string][]byte{} + for n, d := range files { + out[n] = d + } + ver, m := mustVersion(v), mustSums(t, v, files[sumsName]) + for _, f := range formulas(ver) { + data, err := renderFormula([]byte(testTemplate), strings.TrimSuffix(f, ".rb"), fakeRepo, ver, m) + if err != nil { + t.Fatal(err) + } + out[f] = data + } + return out +} + +func mustSums(t *testing.T, v string, data []byte) Manifest { + t.Helper() + m, err := ParseSums(v, data) + if err != nil { + t.Fatal(err) + } + return m +} + +// artifact is what CI's release workflow uploads for files: them, and its +// signature of SHA256SUMS. +func artifact(k keys, v string, files map[string][]byte) map[string][]byte { + a := map[string][]byte{} + for name, data := range files { + a[name] = data + } + a[minisign.SigName(sumsName, minisign.CI)] = k.ci.Sign(files[sumsName], minisign.Release.Comment(v)) + return a +} + +// setup is a co-signer against a fake GitHub, with a state whose last +// release is last. +type setup struct { + gh *fakeGitHub + keys keys + builder *fakeBuilder + c *Cosigner + log *bytes.Buffer +} + +func newSetup(t *testing.T, last string) *setup { + t.Helper() + dir := t.TempDir() + s := &setup{ + gh: newFakeGitHub(t), keys: newKeys(t, minisign.Release, "release.yml"), log: &bytes.Buffer{}, + builder: &fakeBuilder{commit: testCommit, changelog: changelog("0.3.0", "0.3.0-rc.1", "0.3.1", "0.2.9", "0.4.0")}, + } + s.c = &Cosigner{ + GitHub: s.gh.client(), Repo: fakeRepo, Tap: fakeTap, Release: s.keys.kind, + Builder: s.builder, BaseBuilder: NoBaseBuild{}, State: Store{Path: filepath.Join(dir, "state.json")}, + Dir: dir, Work: filepath.Join(t.TempDir(), "work"), Log: s.log, Now: func() time.Time { return time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) }, + } + if err := s.c.State.Save(newState(last, 0)); err != nil { + t.Fatal(err) + } + return s +} + +// ci hands v over as CI's release workflow does, a run with its files as +// an artifact, and has the builder build the same files; it returns the +// files and the run. +func (s *setup) ci(t *testing.T, v string) (map[string][]byte, *fakeRun) { + t.Helper() + files := releaseFiles(v) + run := s.gh.addRun("release.yml", "v"+v, testCommit, "push", "release", artifact(s.keys, v, files)) + s.builder.files = built(t, v, files) + return files, run +} + +// watermark marks every release the fake has now as published before the +// co-signer's state began, and its latest release as the one init saw, as +// init does. +func (s *setup) watermark(t *testing.T) { + t.Helper() + st := s.state(t) + for _, r := range s.gh.releases { + st.Watermark = max(st.Watermark, r.ID) + if !r.Draft && !r.Prerelease && r.Latest != "false" { + st.InitLatest = r.ID + } + } + if err := os.Remove(s.c.State.Path); err != nil { + t.Fatal(err) + } + if err := s.c.State.Save(st); err != nil { + t.Fatal(err) + } +} + +func (s *setup) state(t *testing.T) State { + t.Helper() + st, err := s.c.State.Load() + if err != nil { + t.Fatal(err) + } + return st +} + +// published is release tag, published, with the co-signer's signature, +// which checks out, and CI's. +func (s *setup) published(t *testing.T, tag string) *fakeRelease { + t.Helper() + r := s.gh.release(tag) + if r == nil || r.Draft { + return nil + } + sigs := map[minisign.Role][]byte{ + minisign.CI: r.file(minisign.SigName(sumsName, minisign.CI)), minisign.Cosign: r.file(minisign.SigName(sumsName, minisign.Cosign)), + } + if err := s.keys.kind.Keys.Check(r.file(sumsName), sigs, strings.TrimPrefix(tag, "v")); err != nil { + t.Errorf("%s's signatures: %v", tag, err) + } + return r +} + +// A release CI handed over whose rebuild matches is signed, made a release +// by the co-signer, with its title and its notes from the tag's +// changelog, published as GitHub's latest, and its formulas, rendered +// from SHA256SUMS, go to the tap; a second run does nothing, with no +// download and no rebuild. +func TestReleaseSignedAndPublished(t *testing.T) { + s := newSetup(t, "0.2.0") + files, run := s.ci(t, "0.3.0") + if err := s.c.Run(t.Context()); err != nil { + t.Fatalf("Run: %v\n%s", err, s.log) + } + r := s.published(t, "v0.3.0") + if r == nil || r.Prerelease || r.Latest != "true" || r.Name != "devvm 0.3.0" || r.Body != "- What's new in 0.3.0.\n" || r.Target != "" { + t.Fatalf("v0.3.0: %+v\n%s", r, s.log) + } + for name, data := range files { + if !bytes.Equal(r.file(name), data) { + t.Errorf("the release's %s isn't CI's", name) + } + } + if len(r.Assets) != len(files)+2 { + t.Errorf("%d assets, want %d", len(r.Assets), len(files)+2) + } + for _, f := range []string{"devvm.rb", "devvm-rc.rb"} { + got := s.gh.tap["Formula/"+f] + if !bytes.Equal(got, s.builder.files[f]) || !bytes.Contains(got, []byte(sha256Hex(files["devvm-0.3.0-linux-amd64.tar.gz"]))) { + t.Errorf("the tap's %s:\n%s", f, got) + } + } + st := s.state(t) + if st.Release.Last != "0.3.0" || st.Release.Signed["0.3.0"] != sha256Hex(files[sumsName]) || !st.Release.Published["0.3.0"] || !st.Release.Done["0.3.0"] { + t.Errorf("state: %+v", st.Release) + } + if s.gh.leaked != 0 || s.gh.tokens != 1 { + t.Errorf("the token reached the storage %d times; %d tokens for one run, want 1", s.gh.leaked, s.gh.tokens) + } + // Twice in the first run, before the build and after it, and never + // again. + if err := s.c.Run(t.Context()); err != nil || s.builder.builds != 1 || len(s.gh.tapLog) != 2 || s.gh.artifactDownloads[run.artifacts[0].ID] != 2 { + t.Errorf("the second run: %v, %d builds, tap %v, %d downloads", err, s.builder.builds, s.gh.tapLog, s.gh.artifactDownloads[run.artifacts[0].ID]) + } +} + +// A prerelease is published as one, never GitHub's latest, and changes +// only the tap's devvm-rc; a tap whose devvm-rc is newer keeps it. +func TestPrereleasePublished(t *testing.T) { + s := newSetup(t, "0.2.0") + s.ci(t, "0.3.0-rc.1") + if err := s.c.Run(t.Context()); err != nil { + t.Fatalf("Run: %v\n%s", err, s.log) + } + r := s.published(t, "v0.3.0-rc.1") + if r == nil || !r.Prerelease || r.Latest != "false" { + t.Fatalf("v0.3.0-rc.1: %+v", r) + } + if _, ok := s.gh.tap["Formula/devvm.rb"]; ok || !bytes.Equal(s.gh.tap["Formula/devvm-rc.rb"], s.builder.files["devvm-rc.rb"]) { + t.Errorf("the tap: %v", s.gh.tapLog) + } + + // A tap formula newer than any release the co-signer signed isn't one + // it wrote: an alert, and the formula stays until a maintainer acks it. + s = newSetup(t, "0.2.0") + newer := []byte("url \"https://github.com/devvmhq/devvm/releases/download/v0.4.0-rc.1/x\"\n") + s.gh.tap["Formula/devvm-rc.rb"] = newer + s.ci(t, "0.3.0") + for range 2 { + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: tap:devvm-rc.rb@0.4.0-rc.1: the tap's Formula/devvm-rc.rb installs 0.4.0-rc.1") { + t.Fatalf("Run: %v\n%s", err, s.log) + } + } + if !bytes.Equal(s.gh.tap["Formula/devvm-rc.rb"], newer) || s.gh.tap["Formula/devvm.rb"] == nil || s.state(t).Release.Done["0.3.0"] { + t.Errorf("the tap: %v", s.gh.tapLog) + } + if err := s.c.Clear("tap:devvm-rc.rb@0.4.0-rc.1", false); err != nil { + t.Fatal(err) + } + if err := s.c.Run(t.Context()); err != nil || !s.state(t).Release.Done["0.3.0"] || !bytes.Equal(s.gh.tap["Formula/devvm-rc.rb"], newer) { + t.Errorf("acked: %v, tap %v", err, s.gh.tapLog) + } +} + +// A rebuild that doesn't match signs nothing and makes no release: it +// writes a report naming the file that differs and both SHA-256s, and +// every run fails until devvm-cosign retry, without downloading or +// rebuilding it again, even for CI's run again with the same build; after +// retry, it's rebuilt once more. +func TestMismatchSignsNothing(t *testing.T) { + s := newSetup(t, "0.2.0") + files, run := s.ci(t, "0.3.0") + s.builder.files["devvm-0.3.0-linux-amd64.tar.gz"] = []byte("another build") + if err := s.c.Run(t.Context()); !errors.Is(err, errMismatch) { + t.Fatalf("Run: %v, want a mismatch\n%s", err, s.log) + } + if s.gh.release("v0.3.0") != nil { + t.Error("a mismatch made a release") + } + reports, _ := filepath.Glob(filepath.Join(s.c.Dir, "reports", "v0.3.0-*.txt")) + if len(reports) != 1 { + t.Fatalf("reports: %v", reports) + } + report, _ := os.ReadFile(reports[0]) + for _, want := range []string{"devvm-0.3.0-linux-amd64.tar.gz", sha256Hex(files["devvm-0.3.0-linux-amd64.tar.gz"]), sha256Hex([]byte("another build"))} { + if !strings.Contains(string(report), want) { + t.Errorf("the report has no %s:\n%s", want, report) + } + } + if strings.Contains(string(report), "install.sh") { + t.Errorf("the report names a file that matched:\n%s", report) + } + for range 2 { + if err := s.c.Run(t.Context()); !errors.Is(err, errMismatch) || !strings.Contains(err.Error(), "devvm-cosign retry v0.3.0") || + s.builder.builds != 1 || s.gh.artifactDownloads[run.artifacts[0].ID] != 1 { + t.Errorf("a later run: %v, %d builds, %d downloads", err, s.builder.builds, s.gh.artifactDownloads[run.artifacts[0].ID]) + } + } + // CI's run again, with the same build: downloaded, and still refused. + s.gh.addRun("release.yml", "v0.3.0", testCommit, "push", "release", artifact(s.keys, "0.3.0", files)) + if err := s.c.Run(t.Context()); !errors.Is(err, errMismatch) || s.builder.builds != 1 { + t.Errorf("CI's run again: %v, %d builds", err, s.builder.builds) + } + if err := s.c.Clear("v0.3.0", true); err != nil { + t.Fatal(err) + } + if err := s.c.Clear("v0.3.0", true); err == nil { + t.Error("a second retry with nothing to retry") + } + s.builder.files = built(t, "0.3.0", files) + if err := s.c.Run(t.Context()); err != nil || s.builder.builds != 2 || s.published(t, "v0.3.0") == nil { + t.Errorf("after retry: %v, %d builds\n%s", err, s.builder.builds, s.log) + } +} + +// A build that fails, rather than differs, is built again next run, as +// the cause is often the machine's, but the third failure in a row +// refuses it, as a mismatch is, with a report, so it stops taking every +// run's one build: the newer release behind it is built at the next run, +// and devvm-cosign retry builds it again. A build stopped with its run +// isn't counted. +func TestFailingBuildRefused(t *testing.T) { + s := newSetup(t, "0.2.0") + files, run := s.ci(t, "0.3.0") + s.builder.err = errors.New("no space left on device") + sum := sha256Hex(files[sumsName]) + for n := 1; n <= maxBuildFailures-1; n++ { + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "no space left") || errors.Is(err, errBuildFailed) { + t.Fatalf("failure %d: %v", n, err) + } + if st := s.state(t); s.builder.builds != n || st.Release.Refused[sum].active() || st.Release.Refused[sum].Failed != n { + t.Fatalf("failure %d: %d builds, %+v", n, s.builder.builds, st.Release.Refused) + } + } + _, second := s.ci(t, "0.3.1") + if err := s.c.Run(t.Context()); !errors.Is(err, errBuildFailed) || !strings.Contains(err.Error(), "devvm-cosign retry v0.3.0") || + s.gh.release("v0.3.1") != nil || s.gh.artifactDownloads[second.artifacts[0].ID] != 0 { + t.Fatalf("the last failure: %v\n%s", err, s.log) + } + reports, _ := filepath.Glob(filepath.Join(s.c.Dir, "reports", "v0.3.0-*.txt")) + if len(reports) != 1 { + t.Fatalf("reports: %v", reports) + } + if report, _ := os.ReadFile(reports[0]); !strings.Contains(string(report), "no space left on device") { + t.Errorf("the report:\n%s", report) + } + // The next run skips it, with no download, and builds the release + // behind it. + s.builder.err = nil + s.builder.files = built(t, "0.3.1", releaseFiles("0.3.1")) + if err := s.c.Run(t.Context()); !errors.Is(err, errBuildFailed) || s.published(t, "v0.3.1") == nil || + s.builder.builds != maxBuildFailures+1 || s.gh.artifactDownloads[run.artifacts[0].ID] != maxBuildFailures { + t.Fatalf("the run after: %v, %d builds, %d downloads\n%s", err, s.builder.builds, s.gh.artifactDownloads[run.artifacts[0].ID], s.log) + } + + // retry builds it again, once. + s = newSetup(t, "0.2.0") + files, _ = s.ci(t, "0.3.0") + s.builder.err = errors.New("no space left on device") + for range maxBuildFailures { + _ = s.c.Run(t.Context()) + } + if err := s.c.Run(t.Context()); !errors.Is(err, errBuildFailed) || s.builder.builds != maxBuildFailures { + t.Fatalf("refused: %v, %d builds", err, s.builder.builds) + } + if err := s.c.Clear("v0.3.0", true); err != nil { + t.Fatal(err) + } + s.builder.err = nil + s.builder.files = built(t, "0.3.0", files) + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.0") == nil { + t.Errorf("after retry: %v\n%s", err, s.log) + } + + // A build stopped with its run, at its time limit or by a stop, isn't + // a failure of the build's. + s = newSetup(t, "0.2.0") + files, _ = s.ci(t, "0.3.0") + ctx, cancel := context.WithCancel(t.Context()) + s.builder.during = func(string) { cancel() } + s.builder.err = context.Canceled + if err := s.c.Run(ctx); err == nil { + t.Fatal("a stopped run succeeded") + } + if r := s.state(t).Release.Refused[sha256Hex(files[sumsName])]; r.Failed != 0 { + t.Errorf("a stopped build counted: %+v", r) + } +} + +// The tap gets only formulas the co-signer rendered from the signed +// SHA256SUMS: a rebuild whose formula points elsewhere is a mismatch, and +// a kept formula changed on disk between runs stops the tap. +func TestFormulas(t *testing.T) { + s := newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + s.builder.files["devvm.rb"] = bytes.ReplaceAll(s.builder.files["devvm.rb"], []byte("github.com/devvmhq"), []byte("evil.example")) + if err := s.c.Run(t.Context()); !errors.Is(err, errMismatch) || s.gh.release("v0.3.0") != nil || len(s.gh.tapLog) != 0 { + t.Errorf("a rebuild's formula of its own: %v, tap %v", err, s.gh.tapLog) + } + + s = newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + s.gh.fail = func(r *http.Request) int { + if strings.Contains(r.URL.Path, fakeTap) { + return http.StatusInternalServerError + } + return 0 + } + if err := s.c.Run(t.Context()); err == nil || s.published(t, "v0.3.0") == nil { + t.Fatalf("Run with the tap failing: %v", err) + } + s.gh.fail = nil + kept := filepath.Join(s.c.Dir, "kept", "0.3.0", "devvm.rb") + if err := os.WriteFile(kept, []byte("url \"https://evil.example/x\"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "isn't the file the co-signer kept") || len(s.gh.tapLog) != 0 { + t.Errorf("a kept formula changed: %v, tap %v", err, s.gh.tapLog) + } +} + +// renderFormula writes what release.sh's formula function writes, for the +// real template: each platform's URL and SHA-256 from SHA256SUMS, comments +// as they are, and an archive SHA256SUMS doesn't list is an error. +func TestRenderFormula(t *testing.T) { + v := mustVersion("0.3.0") + files := map[string][]byte{} + for _, p := range []string{"darwin-arm64", "darwin-amd64", "linux-arm64", "linux-amd64"} { + files["devvm-0.3.0-"+p+".tar.gz"] = []byte(p) + } + m := mustSums(t, "0.3.0", sums(files)) + got, err := renderFormula([]byte(testTemplate), "devvm-rc", fakeRepo, v, m) + if err != nil { + t.Fatal(err) + } + want := `# The tests' formula: @CLASS@ stays in a comment. +class DevvmRc < Formula + url "https://github.com/devvmhq/devvm/releases/download/v0.3.0/devvm-0.3.0-darwin-arm64.tar.gz" + sha256 "` + sha256Hex([]byte("darwin-arm64")) + `" + url "https://github.com/devvmhq/devvm/releases/download/v0.3.0/devvm-0.3.0-linux-amd64.tar.gz" + sha256 "` + sha256Hex([]byte("linux-amd64")) + `" + conflicts_with "devvmhq/tap/devvm" +end +` + if string(got) != want { + t.Errorf("renderFormula:\n%s\nwant:\n%s", got, want) + } + delete(files, "devvm-0.3.0-linux-amd64.tar.gz") + if _, err := renderFormula([]byte(testTemplate), "devvm", fakeRepo, v, mustSums(t, "0.3.0", sums(files))); err == nil { + t.Error("a formula with an archive SHA256SUMS doesn't list") + } + if _, err := renderFormula([]byte(testTemplate+" @OTHER@\n"), "devvm", fakeRepo, v, m); err == nil { + t.Error("a placeholder left") + } + if _, err := renderFormula([]byte(testTemplate), "other", fakeRepo, v, m); err == nil { + t.Error("a formula of another name") + } +} + +// releaseNotes takes a version's changelog entry as publish.sh does. +func TestReleaseNotes(t *testing.T) { + log := []byte("# Changelog\n\n## 0.3.0\n\n\n- One.\n\n- Two.\n\n\n## 0.2.0\n\n- Old.\n") + if got, err := releaseNotes(log, "0.3.0"); err != nil || got != "- One.\n\n- Two.\n" { + t.Errorf("releaseNotes: %q, %v", got, err) + } + if _, err := releaseNotes(log, "0.4.0"); err == nil { + t.Error("notes for a version with no entry") + } + if _, err := releaseNotes([]byte("## 0.3.0\n\n## 0.2.0\n- Old.\n"), "0.3.0"); err == nil { + t.Error("notes from an empty entry") + } +} + +// A release whose CI signature doesn't check out is refused before any +// rebuild: another key's, another version's, or none. +func TestBadCISignature(t *testing.T) { + for name, sig := range map[string]func(k keys, sums []byte) []byte{ + "another key": func(_ keys, sums []byte) []byte { + return minisigntest.NewKey().Sign(sums, minisign.Release.Comment("0.3.0")) + }, + "another version": func(k keys, sums []byte) []byte { return k.ci.Sign(sums, minisign.Release.Comment("0.2.9")) }, + "recovery's key": func(k keys, sums []byte) []byte { return k.recovery.Sign(sums, minisign.Release.Comment("0.3.0")) }, + "another kind": func(k keys, sums []byte) []byte { return k.ci.Sign(sums, minisign.Base.Comment("0.3.0")) }, + "not a signature": func(keys, []byte) []byte { return []byte("nope\n") }, + } { + s := newSetup(t, "0.2.0") + files := releaseFiles("0.3.0") + a := artifact(s.keys, "0.3.0", files) + a[minisign.SigName(sumsName, minisign.CI)] = sig(s.keys, files[sumsName]) + s.gh.addRun("release.yml", "v0.3.0", testCommit, "push", "release", a) + if err := s.c.Run(t.Context()); err == nil || s.builder.builds != 0 || s.gh.release("v0.3.0") != nil { + t.Errorf("%s: %v, %d builds", name, err, s.builder.builds) + } + } +} + +// What CI hands over must be exactly a manifest, its signature and the +// files it lists, each with its SHA-256: a file it doesn't list, one +// missing, one with other bytes, or two artifacts, are each refused +// before any rebuild. +func TestArtifactChecked(t *testing.T) { + for name, change := range map[string]func(a map[string][]byte){ + "an unlisted file": func(a map[string][]byte) { a["extra.sh"] = []byte("x") }, + "a missing file": func(a map[string][]byte) { delete(a, "install.sh") }, + "another file": func(a map[string][]byte) { a["install.sh"] = []byte("#!/bin/bash\nevil\n") }, + "no signature": func(a map[string][]byte) { delete(a, minisign.SigName(sumsName, minisign.CI)) }, + } { + s := newSetup(t, "0.2.0") + a := artifact(s.keys, "0.3.0", releaseFiles("0.3.0")) + change(a) + s.gh.addRun("release.yml", "v0.3.0", testCommit, "push", "release", a) + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "refused") || s.builder.builds != 0 || s.gh.release("v0.3.0") != nil { + t.Errorf("%s: %v, %d builds", name, err, s.builder.builds) + } + } + s := newSetup(t, "0.2.0") + _, run := s.ci(t, "0.3.0") + run.artifacts = append(run.artifacts, run.artifacts[0]) + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "not one") { + t.Errorf("two artifacts: %v", err) + } + s = newSetup(t, "0.2.0") + _, run = s.ci(t, "0.3.0") + run.artifacts[0].Digest = "sha256:" + sumA + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "digest") { + t.Errorf("an artifact GitHub's digest doesn't match: %v", err) + } +} + +// Only the pinned workflow's own successful push runs count: another +// workflow's, a fork's, or a run for a branch hands nothing over, and a +// run whose commit isn't the tag's is refused after the build. +func TestRunsChecked(t *testing.T) { + s := newSetup(t, "0.2.0") + files := releaseFiles("0.3.0") + s.gh.addRun("other.yml", "v0.3.0", testCommit, "push", "release", artifact(s.keys, "0.3.0", files)) + fork := s.gh.addRun("release.yml", "v0.3.0", testCommit, "push", "release", artifact(s.keys, "0.3.0", files)) + fork.HeadRepository.FullName = "someone/devvm" + s.gh.addRun("release.yml", "main", testCommit, "push", "release", artifact(s.keys, "0.3.0", files)) + // A run that a tag's push didn't start, such as one by hand on a branch + // of the tag's name. + s.gh.addRun("release.yml", "v0.3.0", testCommit, "workflow_dispatch", "release", artifact(s.keys, "0.3.0", files)) + if err := s.c.Run(t.Context()); err != nil || s.builder.builds != 0 { + t.Errorf("no run of its own: %v, %d builds", err, s.builder.builds) + } + s.ci(t, "0.3.0") + s.builder.commit = strings.Repeat("e", 40) + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "built") || s.gh.release("v0.3.0") != nil { + t.Errorf("another commit: %v", err) + } +} + +// A release no newer than the newest the co-signer signed is refused +// before any rebuild, though CI signed it: an older release replayed. It's +// an alert every run until acked, then left alone. One published before +// the co-signer's state began is left alone. +func TestReplayedOlderVersion(t *testing.T) { + for _, v := range []string{"0.2.9", "0.3.0", "0.3.0-rc.1"} { + s := newSetup(t, "0.3.0") + s.ci(t, v) + for range 2 { + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: v"+v+": refused") || !strings.Contains(err.Error(), "replayed") || + s.builder.builds != 0 || s.gh.release("v"+v) != nil { + t.Errorf("%s: %v, %d builds", v, err, s.builder.builds) + } + } + if err := s.c.Clear("v"+v, false); err != nil { + t.Fatal(err) + } + if err := s.c.Run(t.Context()); err != nil || s.builder.builds != 0 { + t.Errorf("%s acked: %v", v, err) + } + } + s := newSetup(t, "0.3.0") + s.gh.addRelease("v0.2.9", false, nil) + s.watermark(t) + s.ci(t, "0.2.9") + if err := s.c.Run(t.Context()); err != nil || s.builder.builds != 0 { + t.Errorf("an old release published before: %v", err) + } +} + +// An asset changed after the upload, before the publish, stops the +// publish, and the next run puts it back and publishes; a draft renamed, +// or its notes changed, isn't published. +func TestDraftChangedBeforePublish(t *testing.T) { + s := newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + tarball := "devvm-0.3.0-linux-amd64.tar.gz" + s.gh.afterUpload = func(r *fakeRelease) { + if len(r.Assets) == 6 { + s.gh.put(r, tarball, []byte("swapped")) + } + } + err := s.c.Run(t.Context()) + if err == nil || !strings.Contains(err.Error(), "changed after it was checked") || !s.gh.release("v0.3.0").Draft { + t.Fatalf("a file replaced before publishing: %v", err) + } + s.gh.afterUpload = nil + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.0") == nil || + !bytes.Equal(s.gh.release("v0.3.0").file(tarball), []byte("linux amd64 0.3.0")) || s.builder.builds != 1 { + t.Errorf("the next run: %v, %d builds\n%s", err, s.builder.builds, s.log) + } + + for name, change := range map[string]func(r *fakeRelease){ + "retagged": func(r *fakeRelease) { r.Tag = "v9.0.0" }, + "another title": func(r *fakeRelease) { r.Body = "install with curl evil | bash" }, + } { + s = newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + s.gh.afterUpload = func(r *fakeRelease) { change(r) } + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "not published") { + t.Errorf("%s: %v", name, err) + } + for _, r := range s.gh.releases { + if !r.Draft { + t.Errorf("%s: published", name) + } + } + } +} + +// GitHub failing mid-upload leaves a half-uploaded asset; the next run +// deletes it, uploads it again without rebuilding, and publishes, with +// the signature the first run would have made, once. +func TestUploadRetried(t *testing.T) { + s := newSetup(t, "0.2.0") + files, _ := s.ci(t, "0.3.0") + s.gh.failUpload = true + if err := s.c.Run(t.Context()); err == nil || !s.gh.release("v0.3.0").Draft { + t.Fatalf("Run with the upload failing: %v", err) + } + if s.state(t).Release.Signed["0.3.0"] == "" { + t.Error("the state doesn't record the release as checked") + } + if err := s.c.Run(t.Context()); err != nil { + t.Fatalf("the retry: %v\n%s", err, s.log) + } + r := s.published(t, "v0.3.0") + want, err := s.keys.cosign.Sign(files[sumsName], minisign.Release.Comment("0.3.0")) + if err != nil { + t.Fatal(err) + } + if r == nil || !bytes.Equal(r.file(minisign.SigName(sumsName, minisign.Cosign)), want) || s.builder.builds != 1 || len(r.Assets) != len(files)+2 { + t.Errorf("after the retry: %+v, %d builds", r, s.builder.builds) + } + if n := len(s.gh.releases); n != 1 { + t.Errorf("%d releases, want the one draft", n) + } +} + +// A run that stopped after publishing finishes the tap on the next run, +// without rebuilding; a publish GitHub refuses leaves the draft for the +// next run; and a publish that took effect, whose answer was lost, is +// checked as published by the next run before the tap is touched. +func TestPublishFinishedLater(t *testing.T) { + s := newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + s.gh.fail = func(r *http.Request) int { + if r.Method == http.MethodPatch { + return http.StatusBadGateway + } + return 0 + } + if err := s.c.Run(t.Context()); err == nil || !s.gh.release("v0.3.0").Draft { + t.Fatalf("Run with the publish failing: %v", err) + } + s.gh.fail = nil + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.0") == nil || s.builder.builds != 1 { + t.Errorf("the next run: %v, %d builds", err, s.builder.builds) + } + + s = newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + s.gh.publishAnswer = http.StatusBadGateway + if err := s.c.Run(t.Context()); err == nil || s.gh.release("v0.3.0").Draft || len(s.gh.tapLog) != 0 { + t.Fatalf("Run with the publish's answer lost: %v, tap %v", err, s.gh.tapLog) + } + s.gh.publishAnswer = 0 + if err := s.c.Run(t.Context()); err != nil || len(s.gh.tapLog) != 2 || !s.state(t).Release.Published["0.3.0"] || s.builder.builds != 1 { + t.Errorf("the next run: %v, tap %v\n%s", err, s.gh.tapLog, s.log) + } +} + +// A publish whose answer was lost, with a file swapped as it took effect, +// is an alert on the next run's check, and the tap isn't touched; a draft +// of the co-signer's deleted by hand is made again. +func TestLostPublishChecked(t *testing.T) { + s := newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + s.gh.publishAnswer = http.StatusBadGateway + s.gh.onPublish = func(r *fakeRelease) { s.gh.put(r, "install.sh", []byte("swapped")) } + if err := s.c.Run(t.Context()); err == nil { + t.Fatal("Run with the publish's answer lost") + } + s.gh.publishAnswer, s.gh.onPublish = 0, nil + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: v0.3.0: the co-signer's draft was published before its last check") || len(s.gh.tapLog) != 0 { + t.Errorf("the next run: %v, tap %v", err, s.gh.tapLog) + } + + s = newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + s.gh.fail = func(r *http.Request) int { + if r.Method == http.MethodPatch { + return http.StatusBadGateway + } + return 0 + } + if err := s.c.Run(t.Context()); err == nil { + t.Fatal("Run with the publish failing") + } + s.gh.fail = nil + s.gh.releases = nil + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.0") == nil || len(s.state(t).Release.Drafts["0.3.0"]) != 2 { + t.Errorf("after the draft was deleted: %v, drafts %v\n%s", err, s.state(t).Release.Drafts, s.log) + } +} + +// A file swapped as the release is published raises an alert that every +// run reports, and the tap isn't updated; once a maintainer acks it, the +// next run checks the published release again, and alerts again while it +// still differs. +func TestAlertAfterPublish(t *testing.T) { + s := newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + tarball := "devvm-0.3.0-linux-amd64.tar.gz" + s.gh.onPublish = func(r *fakeRelease) { s.gh.put(r, tarball, []byte("swapped")) } + for range 2 { + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: v0.3.0") || len(s.gh.tapLog) != 0 { + t.Errorf("a file swapped as it was published: %v, tap %v", err, s.gh.tapLog) + } + } + if err := s.c.Clear("v0.3.0", false); err != nil { + t.Fatal(err) + } + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: v0.3.0") || len(s.gh.tapLog) != 0 { + t.Errorf("after ack, still swapped: %v, tap %v", err, s.gh.tapLog) + } + if a := s.state(t).Release.Alerts["0.3.0"]; a.Raised != 2 || a.Acked != 1 { + t.Errorf("the alert: %+v", a) + } +} + +// A release the co-signer didn't publish, newer than its state, is an +// alert, reported every run until acked and never put in the tap; a draft +// of a tag it's handed that it didn't make is refused. +func TestPublishedBySomeoneElse(t *testing.T) { + s := newSetup(t, "0.2.0") + r := s.gh.addRelease("v0.3.1", false, releaseFiles("0.3.1")) + key := foreignKey(r.json()) + for range 2 { + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: "+key+": published, but not by the co-signer") { + t.Errorf("a release someone else published: %v", err) + } + } + if err := s.c.Clear(key, false); err != nil { + t.Fatal(err) + } + if err := s.c.Run(t.Context()); err != nil || len(s.gh.tapLog) != 0 { + t.Errorf("after ack: %v, tap %v", err, s.gh.tapLog) + } + // Whatever its tag or version: an old one, or no version at all, and + // the same tag published again after its first alert was acked. + others := []*fakeRelease{s.gh.addRelease("v0.1.5", false, nil), s.gh.addRelease("install", false, nil), s.gh.addRelease("v0.3.1", false, nil)} + err := s.c.Run(t.Context()) + for _, o := range others { + if err == nil || !strings.Contains(err.Error(), "ALERT: "+foreignKey(o.json())+": published, but not by the co-signer") { + t.Errorf("%s: %v", o.Tag, err) + } + } + // One from before the state began is left alone, but a draft there + // was then, published since, isn't. + s = newSetup(t, "0.2.0") + s.gh.addRelease("v0.2.0", false, nil) + s.gh.addRelease("install", false, nil) + early := s.gh.addRelease("v0.2.1", true, nil) + if err := os.Remove(s.c.State.Path); err != nil { + t.Fatal(err) + } + if err := s.c.Init(t.Context()); err != nil { + t.Fatal(err) + } + if err := s.c.Run(t.Context()); err != nil { + t.Errorf("releases from before the state: %v", err) + } + early.Draft = false + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: "+foreignKey(early.json())) { + t.Errorf("a draft from before init, published: %v", err) + } + // GitHub's latest release, wherever the list puts it. + s = newSetup(t, "0.2.0") + late := s.gh.addRelease("v0.2.2", false, nil) + for range (maxPages + 1) * perPage { + s.gh.addRelease("v0.1.0", false, nil) + } + s.watermark(t) + // The oldest in the list, eleven pages back, past where a run stops + // reading, with an ID past the watermark, and GitHub's latest. + late.ID = 1 << 40 + for _, r := range s.gh.releases[1:] { + r.Latest = "false" + } + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: "+foreignKey(late.json())) { + t.Errorf("the latest release, someone else's: %v", err) + } + + s = newSetup(t, "0.2.0") + s.gh.addRelease("v0.3.0", true, nil) + s.ci(t, "0.3.0") + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "didn't make") || s.builder.builds != 0 { + t.Errorf("a draft someone else made: %v", err) + } +} + +// A state older than what GitHub shows the co-signer signed, published +// or a draft, as a restored backup would be, stops the run before +// anything is signed; a file of the signature's name that the co-signer's +// key didn't sign stops nothing. +func TestStateBehindGitHub(t *testing.T) { + signed := func(t *testing.T, s *setup, v string) map[string][]byte { + t.Helper() + files := releaseFiles(v) + sig, err := s.keys.cosign.Sign(files[sumsName], minisign.Release.Comment(v)) + if err != nil { + t.Fatal(err) + } + files[minisign.SigName(sumsName, minisign.Cosign)] = sig + return files + } + for _, draft := range []bool{false, true} { + s := newSetup(t, "0.2.0") + s.gh.addRelease("v0.3.0", draft, signed(t, s, "0.3.0")) + s.ci(t, "0.3.1") + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "behind") || s.builder.builds != 0 { + t.Errorf("draft %v: %v, %d builds", draft, err, s.builder.builds) + } + } + s := newSetup(t, "0.2.0") + forged := releaseFiles("0.1.9") + forged[minisign.SigName(sumsName, minisign.Cosign)] = []byte("sig") + s.gh.addRelease("v0.1.9", false, forged) + s.watermark(t) + s.ci(t, "0.3.0") + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.0") == nil { + t.Errorf("a forged signature: %v\n%s", err, s.log) + } +} + +// A run reads releases only until a page of ones it's done with, so more +// than ten pages of older releases never stop it. +func TestRunPagesReleases(t *testing.T) { + s := newSetup(t, "0.2.0") + for range (maxPages + 1) * perPage { + s.gh.addRelease("v0.1.0", false, nil) + } + s.watermark(t) + s.ci(t, "0.3.0") + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.0") == nil { + t.Errorf("Run with 1,100 old releases: %v", err) + } +} + +// While releases bridge from the old key, a release is signed and its +// draft made, but not published until the old key's signature is on it +// and checks out; waiting downloads nothing. +func TestLegacyBridge(t *testing.T) { + s := newSetup(t, "0.2.0") + old := minisigntest.NewKey() + oldKey, err := minisign.ParsePublicKey(old.Public()) + if err != nil { + t.Fatal(err) + } + s.c.Release.Legacy = &oldKey + files, run := s.ci(t, "0.3.0") + // Waiting fails each run, so the maintainer hears the draft waits for + // them, and downloads nothing again. + if err := s.c.Run(t.Context()); !errors.Is(err, errLegacy) || !s.gh.release("v0.3.0").Draft { + t.Fatalf("Run with no old signature: %v\n%s", err, s.log) + } + if err := s.c.Run(t.Context()); !errors.Is(err, errLegacy) || s.gh.artifactDownloads[run.artifacts[0].ID] != 2 { + t.Errorf("waiting: %v, %d downloads", err, s.gh.artifactDownloads[run.artifacts[0].ID]) + } + s.gh.put(s.gh.release("v0.3.0"), legacySig, old.Sign(files[sumsName], "devvm 0.2.9")) + if err := s.c.Run(t.Context()); err == nil || !s.gh.release("v0.3.0").Draft { + t.Errorf("Run with another version's old signature: %v", err) + } + s.gh.put(s.gh.release("v0.3.0"), legacySig, old.Sign(files[sumsName], "devvm 0.3.0")) + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.0") == nil || s.builder.builds != 1 { + t.Errorf("Run with the old signature: %v, %d builds\n%s", err, s.builder.builds, s.log) + } + if r := s.gh.release("v0.3.0"); !bytes.Equal(r.file(legacySig), old.Sign(files[sumsName], "devvm 0.3.0")) { + t.Error("the old signature isn't published") + } +} + +// A tag pushed again, or deleted, while its draft waited for the old +// key's signature isn't published: the release would be other code. +func TestTagMovedBeforePublish(t *testing.T) { + for _, now := range []string{strings.Repeat("e", 40), ""} { + s := newSetup(t, "0.2.0") + old := minisigntest.NewKey() + oldKey, err := minisign.ParsePublicKey(old.Public()) + if err != nil { + t.Fatal(err) + } + s.c.Release.Legacy = &oldKey + files, _ := s.ci(t, "0.3.0") + if err := s.c.Run(t.Context()); !errors.Is(err, errLegacy) { + t.Fatalf("Run: %v", err) + } + s.gh.movedTags = map[string]string{"v0.3.0": now} + s.gh.put(s.gh.release("v0.3.0"), legacySig, old.Sign(files[sumsName], "devvm 0.3.0")) + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "find out who moved it") || !s.gh.release("v0.3.0").Draft { + t.Errorf("the tag now %q: %v", now, err) + } + } +} + +// The co-signer refuses a second SHA256SUMS for a version it signed: +// CI's build of the same version again, but different. +func TestSecondManifestRefused(t *testing.T) { + s := newSetup(t, "0.2.0") + s.gh.failUpload = true + s.ci(t, "0.3.0") + if err := s.c.Run(t.Context()); err == nil { + t.Fatal("the failed upload") + } + other := releaseFiles("0.3.0") + other["install.sh"] = []byte("#!/bin/bash\n# other\n") + other[sumsName] = sums(other) + s.gh.addRun("release.yml", "v0.3.0", testCommit, "push", "release", artifact(s.keys, "0.3.0", other)) + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "isn't the one the co-signer signed") || !s.gh.release("v0.3.0").Draft { + t.Errorf("Run: %v", err) + } +} + +// Init writes the state from what GitHub has published, drafts aside, +// and never over a state there is. +func TestInit(t *testing.T) { + s := newSetup(t, "0.1.0") + if err := os.Remove(s.c.State.Path); err != nil { + t.Fatal(err) + } + s.gh.addRelease("v0.2.0", false, nil) + s.gh.addRelease("v0.2.1-rc.1", false, nil) + s.gh.addRelease("v0.3.0", true, nil) + s.gh.addRelease("base-7", false, nil) + if err := s.c.Run(t.Context()); !errors.Is(err, errNoState) { + t.Errorf("Run with no state: %v", err) + } + if err := s.c.Init(t.Context()); err != nil { + t.Fatal(err) + } + if st := s.state(t); st.Release.Last != "0.2.1-rc.1" || st.Base.Last != 7 { + t.Errorf("state: %+v", st) + } + if err := s.c.Init(t.Context()); err == nil { + t.Error("Init over a state") + } +} + +// GitHub's latest release, which the install script's default downloads, +// is the one init saw or one the co-signer published: an older release +// made the latest again, one with a known flaw say, is an alert, by its +// tag and ID, every run until it's acked. +func TestLatestChecked(t *testing.T) { + s := newSetup(t, "0.1.0") + if err := os.Remove(s.c.State.Path); err != nil { + t.Fatal(err) + } + old := s.gh.addRelease("v0.1.0", false, nil) + now := s.gh.addRelease("v0.2.0", false, nil) + if err := s.c.Init(t.Context()); err != nil { + t.Fatal(err) + } + if st := s.state(t); st.InitLatest != now.ID { + t.Fatalf("init recorded the latest release %d, want %d", st.InitLatest, now.ID) + } + if err := s.c.Run(t.Context()); err != nil { + t.Fatalf("Run: %v", err) + } + now.Latest = "false" + key := "latest:" + foreignKey(old.json()) + for range 2 { + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: "+key+": ") { + t.Fatalf("an older release made the latest: %v", err) + } + } + if err := s.c.Clear(key, false); err != nil { + t.Fatal(err) + } + if err := s.c.Run(t.Context()); err != nil { + t.Errorf("after ack: %v", err) + } + // Its own release, once published, is the latest; an older one of its + // own made the latest again isn't. + s.ci(t, "0.3.0") + for range 2 { + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.0") == nil { + t.Fatalf("its own release: %v\n%s", err, s.log) + } + } + s.ci(t, "0.3.1") + if err := s.c.Run(t.Context()); err != nil || s.published(t, "v0.3.1") == nil { + t.Fatalf("its next release: %v\n%s", err, s.log) + } + s.gh.release("v0.3.1").Latest = "false" + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: latest:"+foreignKey(s.gh.release("v0.3.0").json())+": ") { + t.Errorf("its own older release made the latest: %v", err) + } + // And the latest init saw, made the latest again once it's older than + // one the co-signer published. + s.gh.release("v0.3.0").Latest = "false" + now.Latest = "" + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "ALERT: latest:"+foreignKey(now.json())+": ") { + t.Errorf("init's latest made the latest again: %v", err) + } +} + +// A release published after a newer one, as when the old key signs a +// newer release's draft first, isn't made GitHub's latest, so the +// co-signer never moves the latest back itself. +func TestOlderReleaseNotLatest(t *testing.T) { + s := newSetup(t, "0.2.0") + old := minisigntest.NewKey() + oldKey, err := minisign.ParsePublicKey(old.Public()) + if err != nil { + t.Fatal(err) + } + s.c.Release.Legacy = &oldKey + first, _ := s.ci(t, "0.3.0") + if err := s.c.Run(t.Context()); !errors.Is(err, errLegacy) { + t.Fatalf("0.3.0: %v", err) + } + second, _ := s.ci(t, "0.3.1") + if err := s.c.Run(t.Context()); !errors.Is(err, errLegacy) || s.gh.release("v0.3.1") == nil { + t.Fatalf("0.3.1: %v\n%s", err, s.log) + } + s.gh.put(s.gh.release("v0.3.1"), legacySig, old.Sign(second[sumsName], "devvm 0.3.1")) + if err := s.c.Run(t.Context()); !errors.Is(err, errLegacy) || s.published(t, "v0.3.1") == nil { + t.Fatalf("0.3.1 published: %v\n%s", err, s.log) + } + s.gh.put(s.gh.release("v0.3.0"), legacySig, old.Sign(first[sumsName], "devvm 0.3.0")) + if err := s.c.Run(t.Context()); err != nil { + t.Fatalf("0.3.0 published after 0.3.1: %v\n%s", err, s.log) + } + if r := s.published(t, "v0.3.0"); r == nil || r.Latest != "false" { + t.Errorf("v0.3.0: %+v", r) + } +} + +// A run empties work/ and stage/ in place, never making them again: the +// podman service's unit binds work/ when it starts, so a new folder of +// that name would be one podman can't write. +func TestWorkEmptiedInPlace(t *testing.T) { + s := newSetup(t, "0.2.0") + work := s.c.Work + if err := os.MkdirAll(filepath.Join(work, "old", "x"), 0o700); err != nil { + t.Fatal(err) + } + before, err := os.Stat(work) + if err != nil { + t.Fatal(err) + } + if err := s.c.Run(t.Context()); err != nil { + t.Fatal(err) + } + after, err := os.Stat(work) + if err != nil || !os.SameFile(before, after) { + t.Errorf("work/ was made again: %v", err) + } + if left, _ := os.ReadDir(work); len(left) != 0 { + t.Errorf("work/ kept %v", left) + } +} + +// Init stops reading once it has seen the newest release and base, so +// years of bases never stop it, and records the watermark. +func TestInitPaged(t *testing.T) { + b := newBaseSetup(t, 0) + if err := os.Remove(b.c.State.Path); err != nil { + t.Fatal(err) + } + for n := range (maxPages + 1) * perPage { + b.gh.addRelease("base-"+strconv.Itoa(n+1), false, nil) + } + b.gh.addRelease("v0.2.0", false, nil) + newest := b.gh.addRelease("base-2000", false, nil) + if err := b.c.Init(t.Context()); err != nil { + t.Fatal(err) + } + if st := b.state(t); st.Release.Last != "0.2.0" || st.Base.Last != 2000 || st.Watermark != newest.ID { + t.Errorf("state: last %s, base %d, watermark %d", st.Release.Last, st.Base.Last, st.Watermark) + } +} + +// A build writes its files in the state folder, which no container can +// reach, and while it runs none of CI's files is on disk, so nothing that +// escaped a container can have the co-signer copy CI's bytes in place of +// its own build's. A run builds once: the next release CI handed over +// waits for the next run, with no download. +func TestOneBuildPerRun(t *testing.T) { + s := newSetup(t, "0.2.0") + files, _ := s.ci(t, "0.3.0") + _, second := s.ci(t, "0.3.1") + s.builder.files = built(t, "0.3.0", files) + s.builder.during = func(out string) { + if !strings.HasPrefix(out, s.c.Dir+string(filepath.Separator)) { + t.Errorf("the build's files go in %s, not in the state folder %s", out, s.c.Dir) + } + staged, _ := filepath.Glob(filepath.Join(s.c.Dir, "stage", "*", "*.tar.gz")) + if len(staged) != 0 { + t.Errorf("CI's files are on disk during the build: %v", staged) + } + } + if err := s.c.Run(t.Context()); err != nil || s.builder.builds != 1 || s.published(t, "v0.3.0") == nil || + s.gh.release("v0.3.1") != nil || s.gh.artifactDownloads[second.artifacts[0].ID] != 0 || !strings.Contains(s.log.String(), "next run") { + t.Fatalf("the first run: %v, %d builds\n%s", err, s.builder.builds, s.log) + } + s.builder.files = built(t, "0.3.1", releaseFiles("0.3.1")) + if err := s.c.Run(t.Context()); err != nil || s.builder.builds != 2 || s.published(t, "v0.3.1") == nil { + t.Errorf("the next run: %v, %d builds\n%s", err, s.builder.builds, s.log) + } +} + +// Clear refuses a tag of neither kind, and one with nothing to clear. +func TestClear(t *testing.T) { + s := newSetup(t, "0.2.0") + for _, tag := range []string{"x", "v1", "base-0"} { + if err := s.c.Clear(tag, true); err == nil { + t.Errorf("Clear(%q)", tag) + } + } + if err := s.c.Clear("base-4", false); err == nil { + t.Error("an ack with no alert") + } +} diff --git a/internal/cosign/doc.go b/internal/cosign/doc.go index b3efec74..4924be12 100644 --- a/internal/cosign/doc.go +++ b/internal/cosign/doc.go @@ -1,8 +1,15 @@ // Package cosign is devvm-cosign, the co-signer of devvm's releases and -// bases: a program of its own on a Linux machine of the maintainer's, -// which rebuilds each build CI hands over and signs it only when its own -// build matches. Everything it trusts is in its own config, never read -// from GitHub or from what it builds. +// bases: a program of its own (cmd/devvm-cosign) on a Linux machine of +// the maintainer's, which a systemd timer runs hourly. CI's token can only +// read the repo, so CI hands each build over as a workflow artifact. Each +// run, for each build it hasn't published, the co-signer checks CI's +// signature and every file, rebuilds it with its own pinned devvm, signs +// the manifest when the two builds match, then makes the release itself, +// uploads every file, and publishes it once two of the three keys signed +// it, the tap's formulas, which it renders from the signed SHA256SUMS, +// included. It's the only thing that makes or publishes a release, and a +// release published without it is an alert. Everything it trusts is in +// its own config, never read from GitHub or from what it builds. // // It imports the standard library, BurntSushi/toml for its config and // internal/minisign alone (depguard and the structure test hold it to @@ -11,17 +18,29 @@ // // The files: // -// - build.go: the rebuild (ReleaseBuild, with release.sh --tag; BaseBuilder, -// for phase 5); +// - main.go: the command line (Main), and New, the co-signer a config +// describes; notify.go, the maintainer's notify command; dumpable_*.go, +// the process made non-dumpable; // - config.go: config.toml (LoadConfig, ReadConfig), its keys, read from // systemd's credentials, and their files' modes; -// - manifest.go: the manifests it reads from CI, SHA256SUMS and -// base-index.json, and release versions; +// - cosigner.go: a run (Cosigner.Run), what's held for the maintainer +// (held, Clear), and the first state (Init); +// - release.go: a release CI handed over: its checks, rebuild, +// signature, release, publish and the tap (finish), and a published +// release's checks; +// - base.go: a base CI handed over, and its re-signing without a +// rebuild; +// - files.go: CI's artifact staged and checked, uploads that are safe +// to retry, a release's exact check, the rebuild's comparison and its +// report; artifact.go, the artifact's download and its unzip; +// - formula.go: the tap's formulas and a release's notes, from the tag; +// - manifest.go: SHA256SUMS, base-index.json and versions; +// - build.go: the rebuild (ReleaseBuild, with release.sh --tag; BaseBuilder, +// for phase 5); // - sshsig.go: git's SSH tag signatures, checked against the pinned // signers; // - state.go: state.json, written whole, never backwards; // - github.go and actions.go: every GitHub call (Client), and app.go its -// token, a GitHub App's installation token; artifact.go, CI's -// artifact's download and its unzip; +// token, a GitHub App's installation token; // - lock_unix.go: one run at a time. package cosign diff --git a/internal/cosign/dumpable_linux.go b/internal/cosign/dumpable_linux.go new file mode 100644 index 00000000..f744c936 --- /dev/null +++ b/internal/cosign/dumpable_linux.go @@ -0,0 +1,21 @@ +//go:build linux + +package cosign + +import ( + "fmt" + "syscall" +) + +// undumpable makes the process non-dumpable (prctl PR_SET_DUMPABLE 0): +// another process of the same user can't ptrace it or read its +// /proc//mem, environ or fds, which would give it the keys the +// co-signer holds in memory, and it leaves no core dump. A build's +// container runs as the same user, and Fedora lets a user's processes +// ptrace each other (kernel.yama.ptrace_scope 0). +func undumpable() error { + if _, _, errno := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_DUMPABLE, 0, 0); errno != 0 { + return fmt.Errorf("making the process non-dumpable: %w", errno) + } + return nil +} diff --git a/internal/cosign/dumpable_linux_test.go b/internal/cosign/dumpable_linux_test.go new file mode 100644 index 00000000..46fe95ed --- /dev/null +++ b/internal/cosign/dumpable_linux_test.go @@ -0,0 +1,21 @@ +//go:build linux + +package cosign + +import ( + "io" + "syscall" + "testing" +) + +// devvm-cosign makes itself non-dumpable before anything else, so a +// process of its user can't read its memory. +func TestUndumpable(t *testing.T) { + if Main(t.Context(), []string{"-h"}, Env{}, io.Discard) != 0 { + t.Fatal("devvm-cosign -h failed") + } + n, _, errno := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_GET_DUMPABLE, 0, 0) + if errno != 0 || n != 0 { + t.Errorf("PR_GET_DUMPABLE: %d, %v; want 0", n, errno) + } +} diff --git a/internal/cosign/dumpable_other.go b/internal/cosign/dumpable_other.go new file mode 100644 index 00000000..ab0050dd --- /dev/null +++ b/internal/cosign/dumpable_other.go @@ -0,0 +1,7 @@ +//go:build !linux + +package cosign + +// undumpable does nothing: the co-signer runs on Linux, and elsewhere only +// its tests run. +func undumpable() error { return nil } diff --git a/internal/cosign/files.go b/internal/cosign/files.go new file mode 100644 index 00000000..8cd2c731 --- /dev/null +++ b/internal/cosign/files.go @@ -0,0 +1,439 @@ +package cosign + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "time" + + "github.com/devvmhq/devvm/internal/minisign" +) + +// maxAsset bounds each file a release holds: a release's files come to +// 2 GiB at most, which release.sh checks, and a base's are smaller. +const maxAsset = 2 << 30 + +// artifactName is the artifact each kind's CI workflow uploads its build +// in, by its manifest's name: SHA256SUMS or base-index.json, CI's +// signature of it, and every file it lists, and nothing else. +func artifactName(manifest string) string { + if manifest == indexName { + return "base" + } + return "release" +} + +// A handover is a build CI handed over: its run, and once staged, its +// manifest, CI's signature of it and its files, unzipped. +type handover struct { + run Run + m Manifest + ciSig []byte + files map[string]staged +} + +// stage downloads run's artifact of kind into the stage folder, which the +// builds can't write, and checks it: the manifest (parse reads it), CI's +// signature of it with k's CI key and the trusted comment its subject +// gives, and the files, exactly the ones it lists, each with its SHA-256, +// and nothing else. +func (c *Cosigner) stage(ctx context.Context, k *Kind, run Run, name string, parse func([]byte) (Manifest, error)) (handover, error) { + h := handover{run: run} + arts, err := c.GitHub.Artifacts(ctx, c.Repo, run.ID, artifactName(name)) + if err != nil { + return h, fmt.Errorf("listing CI's run %d's artifacts: %w", run.ID, err) + } + if len(arts) != 1 { + return h, fmt.Errorf("CI's run %d has %d artifacts named %s, not one", run.ID, len(arts), artifactName(name)) + } + dir, err := os.MkdirTemp(filepath.Join(c.Dir, "stage"), strconv.FormatInt(run.ID, 10)+"-") + if err != nil { + return h, err + } + if h.files, err = c.GitHub.fetchArtifact(ctx, c.Repo, arts[0], dir); err != nil { + return h, err + } + sigName := minisign.SigName(name, minisign.CI) + manifest, ok := h.files[name] + sig, sigOK := h.files[sigName] + if !ok || !sigOK { + return h, fmt.Errorf("refused: CI's artifact has no %s or no %s", name, sigName) + } + data, err := manifest.read(maxManifest) + if err != nil { + return h, err + } + if h.ciSig, err = sig.read(maxSig); err != nil { + return h, err + } + if h.m, err = parse(data); err != nil { + return h, fmt.Errorf("refused: %w", err) + } + if err := k.Keys.CheckRole(minisign.CI, h.m.Data, h.ciSig, h.m.Subject); err != nil { + return h, fmt.Errorf("refused: %w", err) + } + for _, f := range sortedKeys(h.files) { + if _, listed := h.m.Files[f]; !listed && f != name && f != sigName { + return h, fmt.Errorf("refused: CI's artifact holds %s, which %s doesn't list, and everything published must be signed", f, name) + } + } + for _, f := range sortedKeys(h.m.Files) { + got, ok := h.files[f] + switch { + case !ok: + return h, fmt.Errorf("refused: CI's artifact has no %s, which %s lists", f, name) + case got.sum != h.m.Files[f]: + return h, fmt.Errorf("refused: CI's %s has the SHA-256 %s, not %s's %s", f, got.sum, name, h.m.Files[f]) + } + } + return h, nil +} + +// A source is the bytes an asset is uploaded from: a staged file of CI's, +// checked, or a signature in memory. +type source struct { + size int64 + sum string + path string + data []byte +} + +func bytesSource(data []byte) source { + return source{size: int64(len(data)), sum: sha256Hex(data), data: data} +} + +func (s source) open() (io.ReadCloser, error) { + if s.path == "" { + return io.NopCloser(bytes.NewReader(s.data)), nil + } + return os.Open(s.path) +} + +// assets are what h's release holds: the manifest, CI's signature and +// sig, the co-signer's, and every file the manifest lists. +func (h handover) assets(sig []byte) map[string]source { + want := map[string]source{ + h.m.Name: bytesSource(h.m.Data), + minisign.SigName(h.m.Name, minisign.CI): bytesSource(h.ciSig), + minisign.SigName(h.m.Name, minisign.Cosign): bytesSource(sig), + } + for name := range h.m.Files { + f := h.files[name] + want[name] = source{size: f.size, sum: f.sum, path: f.path} + } + return want +} + +// upload makes r, a draft the co-signer made, hold want's assets, safely +// again after a run that stopped: an asset with the bytes it should have, +// by size and GitHub's digest, is kept, and any other, such as a +// half-finished upload's or one nobody should have added, is deleted, +// but for keep's, which someone else uploads. Each upload's bytes are +// hashed as they're sent, and one that isn't what was checked is deleted +// again. It returns each asset as uploaded. +func (c *Cosigner) upload(ctx context.Context, r Release, want map[string]source, keep string) (map[string]Asset, error) { + got := map[string]Asset{} + for _, a := range r.Assets { + w, wanted := want[a.Name] + switch { + case a.Name == keep && keep != "": + case wanted && a.State == uploaded && a.Size == w.size && a.Digest == "sha256:"+w.sum: + got[a.Name] = a + default: + c.logf("%s: deleting its %s (%s, %d bytes), which isn't the file the co-signer checked", r.TagName, a.Name, a.State, a.Size) + if err := c.GitHub.DeleteAsset(ctx, c.Repo, a.ID); err != nil { + return nil, fmt.Errorf("deleting its %s: %w", a.Name, err) + } + } + } + for _, name := range sortedKeys(want) { + if _, ok := got[name]; ok { + continue + } + w := want[name] + f, err := w.open() + if err != nil { + return nil, err + } + a, sum, err := c.GitHub.Upload(ctx, c.Repo, r.ID, name, f, w.size) + _ = f.Close() + if err != nil { + return nil, fmt.Errorf("uploading %s: %w", name, err) + } + if sum != w.sum || a.Size != w.size { + _ = c.GitHub.DeleteAsset(ctx, c.Repo, a.ID) + return nil, fmt.Errorf("its %s changed on disk while it was uploaded: not published", name) + } + got[name] = a + } + return got, nil +} + +// exact checks that r, as GitHub has it now, is the release the +// co-signer made: its tag, name and notes, and as its assets exactly +// want's, by GitHub's ID, size and digest, plus keep when it isn't "". An +// asset deleted and uploaded again has another ID, even with the same +// name. +func exact(r Release, tag, name, body string, want map[string]Asset, keep string) error { + switch { + case r.TagName != tag: + return fmt.Errorf("its tag is now %q, not the %s it was made as", r.TagName, tag) + case !sameText(r.Name, name) || !sameText(r.Body, body): + return errors.New("its title or notes changed after the co-signer wrote them") + } + for _, a := range r.Assets { + w, ok := want[a.Name] + switch { + case a.Name == keep && keep != "": + case !ok: + return fmt.Errorf("its asset %s appeared after it was checked", a.Name) + case a.ID != w.ID || a.Size != w.Size || a.State != uploaded || w.Digest != "" && a.Digest != w.Digest: + return fmt.Errorf("its %s changed after it was checked", a.Name) + } + } + for n := range want { + if _, ok := r.asset(n); !ok { + return fmt.Errorf("its %s is gone", n) + } + } + return nil +} + +// sameText is whether a and b are the same text but for line endings and +// the space at either end, which GitHub may change in what it keeps. +func sameText(a, b string) bool { + norm := func(s string) string { return strings.TrimSpace(strings.ReplaceAll(s, "\r\n", "\n")) } + return norm(a) == norm(b) +} + +// download is r's asset name, at most maxBytes, and the asset; errWaiting +// when it isn't there or isn't uploaded yet. +func (c *Cosigner) download(ctx context.Context, r Release, name string, maxBytes int64) ([]byte, Asset, error) { + a, ok := r.asset(name) + if !ok || a.State != uploaded { + return nil, Asset{}, fmt.Errorf("%w for %s", errWaiting, name) + } + data, err := c.GitHub.DownloadBytes(ctx, c.Repo, a, maxBytes) + return data, a, err +} + +// checkFiles checks that r holds every file m lists, each one's bytes, +// downloaded once, with m's SHA-256 (and GitHub's digest, when it has +// one, saying the same), and no asset but those, m and names': what a +// release the co-signer made but didn't see published must hold. +func (c Client) checkFiles(ctx context.Context, repo string, r Release, m Manifest, names ...string) error { + for _, a := range r.Assets { + if _, listed := m.Files[a.Name]; !listed && a.Name != m.Name && !slices.Contains(names, a.Name) { + return fmt.Errorf("its asset %s isn't in %s", a.Name, m.Name) + } + } + for _, name := range sortedKeys(m.Files) { + want := m.Files[name] + a, ok := r.asset(name) + if !ok || a.State != uploaded { + return fmt.Errorf("it has no %s, which %s lists", name, m.Name) + } + got, err := c.Download(ctx, repo, a, maxAsset, io.Discard) + if err != nil { + return err + } + if got != want || a.Digest != "" && a.Digest != "sha256:"+want { + return fmt.Errorf("its %s has the SHA-256 %s, not %s's %s", name, got, m.Name, want) + } + } + return nil +} + +// A diff is one file whose two builds differ: CI's SHA-256 and the +// co-signer's, "" for a file one of them doesn't have. +type diff struct { + name, ci, ours string +} + +// compareBuild compares the co-signer's build in out with m: every file m +// lists, and for a release SHA256SUMS itself, with each file its own +// SHA256SUMS lists that CI's doesn't. What else the build leaves in out, +// such as GoReleaser's metadata, is never published, as only what m lists +// is uploaded. +func compareBuild(m Manifest, out string) ([]diff, error) { + if _, err := os.Stat(out); err != nil { + return nil, fmt.Errorf("reading the rebuild's files: %w", err) + } + var diffs []diff + for _, name := range sortedKeys(m.Files) { + ours, err := hashFile(filepath.Join(out, name)) + if err != nil { + return nil, err + } + if ours != m.Files[name] { + diffs = append(diffs, diff{name, m.Files[name], ours}) + } + } + if m.Kind == minisign.Release { + data, err := readBuilt(filepath.Join(out, m.Name)) + if err != nil { + return nil, err + } + if !bytes.Equal(data, m.Data) { + ours := "" + if data != nil { + ours = sha256Hex(data) + } + diffs = append(diffs, diff{m.Name, sha256Hex(m.Data), ours}) + } + if theirs, err := ParseSums(m.Subject, data); err == nil { + for _, name := range sortedKeys(theirs.Files) { + if _, listed := m.Files[name]; !listed { + diffs = append(diffs, diff{name, "", theirs.Files[name]}) + } + } + } + } + slices.SortFunc(diffs, func(a, b diff) int { return strings.Compare(a.name, b.name) }) + return diffs, nil +} + +// readBuilt reads the rebuild's file at path, at most maxManifest bytes; +// nil when the build has none. +func readBuilt(path string) ([]byte, error) { + fi, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } else if err != nil { + return nil, err + } + if !fi.Mode().IsRegular() || fi.Size() > maxManifest { + return nil, fmt.Errorf("the rebuild's %s isn't a regular file of %d bytes at most", filepath.Base(path), maxManifest) + } + return os.ReadFile(path) //nolint:gosec // a file of the co-signer's own build +} + +// hashFile is the SHA-256 of the regular file at path, never a link's +// target; "" when there's none. +func hashFile(path string) (string, error) { + fi, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } else if err != nil { + return "", err + } + if !fi.Mode().IsRegular() { + return "", fmt.Errorf("the rebuild's %s isn't a regular file", filepath.Base(path)) + } + f, err := os.Open(path) //nolint:gosec // a file of the co-signer's own build + if err != nil { + return "", err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, io.LimitReader(f, maxAsset+1)); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +// report writes the diff report for tag, whose rebuild didn't match at +// now, into the state folder state's reports/, and returns its path. +// Nothing is filed publicly. +func report(state string, now time.Time, tag string, m Manifest, diffs []diff) (string, error) { + var b strings.Builder + fmt.Fprintf(&b, "%s: the co-signer's rebuild doesn't match CI's %s (SHA-256 %s), so it signed nothing.\n", tag, m.Name, sha256Hex(m.Data)) + fmt.Fprintf(&b, "Checked %s. Each file that differs, with CI's SHA-256 and the co-signer's (none: that build has no such file):\n\n", now.UTC().Format(time.RFC3339)) + for _, d := range diffs { + fmt.Fprintf(&b, "%s\n CI: %s\n co-signer: %s\n", d.name, orNone(d.ci), orNone(d.ours)) + } + return writeReport(state, now, tag, b.String()) +} + +// writeReport writes text as tag's report in the state folder's reports/, +// named for the time, and returns its path. +func writeReport(state string, now time.Time, tag, text string) (string, error) { + dir := filepath.Join(state, "reports") + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", err + } + path := filepath.Join(dir, tag+"-"+now.UTC().Format("20060102T150405Z")+".txt") + return path, writeWhole(path, []byte(text), 0o600) +} + +// errBuildFailed is a manifest whose build failed maxBuildFailures times +// in a row, refused as a mismatch is. +var errBuildFailed = fmt.Errorf("the co-signer's build of it failed %d times in a row, so it signed nothing", maxBuildFailures) + +// buildFailed records that the co-signer's build of h's manifest, key's +// in l, for tag, failed with err, and returns what the run reports: err, +// so the next run builds it again, or, at the maxBuildFailures'th failure +// in a row, nothing, as it's then refused with a report, which held +// reports every run until devvm-cosign retry, and the next run builds the +// release or base behind it. A build stopped with its run, at its time +// limit say, isn't counted. +func (c *Cosigner) buildFailed(ctx context.Context, s *State, l *Ledger, tag, key string, h handover, err error) error { + if ctx.Err() != nil { + return err + } + if !l.failed(h.m.sum(), key, h.run.ID, err.Error()) { + return errors.Join(fmt.Errorf("its build failed, and the next run builds it again: %w", err), c.save(s)) + } + text := fmt.Sprintf("%s: the co-signer's build of CI's %s (SHA-256 %s) failed %d times in a row, so it signed nothing.\nChecked %s. The last failure:\n\n%v\n", + tag, h.m.Name, h.m.sum(), maxBuildFailures, c.now().UTC().Format(time.RFC3339), err) + path, rerr := writeReport(c.Dir, c.now(), tag, text) + if rerr != nil { + return errors.Join(err, rerr, c.save(s)) + } + c.logf("%s: %v: %v, in %s", tag, errBuildFailed, err, path) + return c.save(s) +} + +// errNextRun is a build that waits for the next run, as a run makes one. +var errNextRun = fmt.Errorf("%w for the next run, as each run builds one release or base", errWaiting) + +// oneBuild lets a run build once, and takes CI's files that h staged off +// the disk first, keeping only its manifest and CI's signature. Each run +// builds once, so the podman service, which runs only while the run does, +// lives for one build, and a process that escaped one build's container +// is gone before the next build's host git and release.sh run; and no +// CI file is on disk while the build runs, so nothing that escaped can +// have the co-signer's own build copy CI's bytes in place of its own, +// unless it has them from elsewhere: with CI compromised too, an escape +// counts as the co-signer's compromise, both builders', which the design +// accepts. The run stages CI's files again for the upload once the build +// matched. +func oneBuild(built *bool, h handover) error { + if *built { + return errNextRun + } + *built = true + for name := range h.m.Files { + if err := os.Remove(h.files[name].path); err != nil { + return err + } + } + return nil +} + +// newOut is a new folder, in the state folder state's src/, for one +// build's files: release.sh copies them there on the host, and the +// co-signer reads them there, where no build's container, nor anything +// that escaped one, can swap a file or the folder itself. +func newOut(state, tag string) (string, error) { + return os.MkdirTemp(filepath.Join(state, "src"), tag+"-") +} + +func orNone(s string) string { + if s == "" { + return "none" + } + return s +} + +// errMismatch is a rebuild that doesn't match CI's. +var errMismatch = errors.New("the co-signer's rebuild doesn't match CI's, so it signed nothing") diff --git a/internal/cosign/files_test.go b/internal/cosign/files_test.go new file mode 100644 index 00000000..2a2bd38d --- /dev/null +++ b/internal/cosign/files_test.go @@ -0,0 +1,88 @@ +package cosign + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" +) + +// A rebuild compared with CI's: a missing file, another one and another +// SHA256SUMS each differ, and a file only its SHA256SUMS lists is named; +// what else the build leaves, as GoReleaser's metadata, doesn't count, +// and a link in the build isn't read. +func TestCompareBuild(t *testing.T) { + files := releaseFiles("1.0.0") + m, err := ParseSums("1.0.0", files[sumsName]) + if err != nil { + t.Fatal(err) + } + write := func(t *testing.T, change func(out string)) string { + t.Helper() + out := t.TempDir() + for name, data := range files { + if err := os.WriteFile(filepath.Join(out, name), data, 0o600); err != nil { + t.Fatal(err) + } + } + change(out) + return out + } + for name, tc := range map[string]struct { + change func(out string) + diffs []string + }{ + "the same": {func(string) {}, nil}, + "metadata": {func(o string) { _ = os.Mkdir(filepath.Join(o, "devvm_linux_amd64_v1"), 0o700) }, nil}, + "an extra file": {func(o string) { _ = os.WriteFile(filepath.Join(o, "artifacts.json"), nil, 0o600) }, nil}, + "a missing file": {func(o string) { _ = os.Remove(filepath.Join(o, "install.sh")) }, []string{"install.sh"}}, + "no SHA256SUMS": {func(o string) { _ = os.Remove(filepath.Join(o, sumsName)) }, []string{sumsName}}, + "another SUMS": {func(o string) { _ = os.WriteFile(filepath.Join(o, sumsName), []byte("x"), 0o600) }, []string{sumsName}}, + "another tarball": {func(o string) { _ = os.WriteFile(filepath.Join(o, "install.sh"), []byte("x"), 0o600) }, []string{"install.sh"}}, + "a file CI lacks": {func(o string) { + _ = os.WriteFile(filepath.Join(o, sumsName), append(bytes.Clone(files[sumsName]), []byte(sumA+" extra.tar.gz\n")...), 0o600) + }, []string{sumsName, "extra.tar.gz"}}, + } { + diffs, err := compareBuild(m, write(t, tc.change)) + var got []string + for _, d := range diffs { + got = append(got, d.name) + } + if err != nil || strings.Join(got, " ") != strings.Join(tc.diffs, " ") { + t.Errorf("%s: %v %v, want %v", name, got, err, tc.diffs) + } + } + for _, name := range []string{"install.sh", sumsName} { + link := write(t, func(o string) { + _ = os.Remove(filepath.Join(o, name)) + _ = os.Symlink("/etc/passwd", filepath.Join(o, name)) + }) + if _, err := compareBuild(m, link); err == nil { + t.Errorf("a link for %s in the build was read", name) + } + } + if _, err := compareBuild(m, filepath.Join(t.TempDir(), "none")); err == nil { + t.Error("no build") + } +} + +// An upload whose bytes, as sent, aren't the ones checked is deleted +// again, and the release isn't published. +func TestUploadChangedOnDisk(t *testing.T) { + s := newSetup(t, "0.2.0") + s.ci(t, "0.3.0") + s.gh.afterUpload = func(*fakeRelease) { + // The next staged file changes on disk before it's uploaded. + matches, _ := filepath.Glob(filepath.Join(s.c.Dir, "stage", "*", "install.sh")) + for _, m := range matches { + _ = os.WriteFile(m, []byte("#!/bin/bash\n# 0.3.1\n"), 0o600) + } + } + if err := s.c.Run(t.Context()); err == nil || !strings.Contains(err.Error(), "changed on disk") { + t.Errorf("Run: %v", err) + } + if r := s.gh.release("v0.3.0"); r == nil || !r.Draft || r.file("install.sh") != nil { + t.Errorf("the draft: %+v", r) + } +} diff --git a/internal/cosign/formula.go b/internal/cosign/formula.go new file mode 100644 index 00000000..d19bb15f --- /dev/null +++ b/internal/cosign/formula.go @@ -0,0 +1,104 @@ +package cosign + +import ( + "fmt" + "regexp" + "strings" +) + +// The tap's formulas are Ruby that Homebrew runs, and Homebrew trusts the +// SHA-256s in them alone, so neither builder's container writes what the +// tap gets: the co-signer renders each formula itself from two signed +// inputs, the template in the tag's commit (Built.Formula), which the +// maintainer's tag signs, and SHA256SUMS, which two of three keys sign, +// as scripts/release.sh's formula function does. The rebuild's own +// formulas, which that function wrote in its container, must be the +// same bytes (compareBuild), so a difference between the two renderers +// is caught at the release that has one. + +// formulaClass is formula name's Ruby class and the formula it conflicts +// with, as release.sh's formula function names them. +func formulaClass(name string) ([2]string, bool) { + switch name { + case "devvm": + return [2]string{"Devvm", "devvmhq/tap/devvm-rc"}, true + case "devvm-rc": + return [2]string{"DevvmRc", "devvmhq/tap/devvm"}, true + } + return [2]string{}, false +} + +// placeholder is a template's @NAME@ that's still there. +var placeholder = regexp.MustCompile(`@[A-Z0-9_]+@`) + +// renderFormula is the formula name (devvm or devvm-rc) for release v of +// repo, from template and m, v's SHA256SUMS: each line that isn't a +// comment gets the class, the conflicting formula, and each platform's +// archive's URL and SHA-256, and a placeholder left, or an archive +// SHA256SUMS doesn't list, is an error. +func renderFormula(template []byte, name, repo string, v version, m Manifest) ([]byte, error) { + class, ok := formulaClass(name) + if !ok { + return nil, fmt.Errorf("no formula %s", name) + } + base := "https://github.com/" + repo + "/releases/download/v" + v.raw + var b strings.Builder + for _, line := range strings.Split(strings.TrimSuffix(string(template), "\n"), "\n") { + if !strings.HasPrefix(line, "#") { + line = strings.ReplaceAll(strings.ReplaceAll(line, "@CLASS@", class[0]), "@CONFLICTS@", class[1]) + for _, osName := range []string{"darwin", "linux"} { + for _, arch := range []string{"arm64", "amd64"} { + p := strings.ToUpper(osName + "_" + arch) + archive := "devvm-" + v.raw + "-" + osName + "-" + arch + ".tar.gz" + if strings.Contains(line, "@SHA256_"+p+"@") { + sum, listed := m.Files[archive] + if !listed { + return nil, fmt.Errorf("the formula %s needs %s, which %s doesn't list", name, archive, m.Name) + } + line = strings.ReplaceAll(line, "@SHA256_"+p+"@", sum) + } + line = strings.ReplaceAll(line, "@URL_"+p+"@", base+"/"+archive) + } + } + if placeholder.MatchString(line) { + return nil, fmt.Errorf("the formula %s has a placeholder left: %s", name, line) + } + } + b.WriteString(line + "\n") + } + return []byte(b.String()), nil +} + +// releaseNotes is the entry for v in changelog, CHANGELOG.md, as +// scripts/publish.sh takes it: the lines after "## " up to the next +// "## ", without the blank lines at either end; an error when there's +// none. +func releaseNotes(changelog []byte, v string) (string, error) { + var b strings.Builder + on, started, blank := false, false, 0 + for _, line := range strings.Split(string(changelog), "\n") { + if line == "## "+v { + on = true + continue + } + if !on { + continue + } + if strings.HasPrefix(line, "## ") { + break + } + if strings.TrimSpace(line) == "" { + blank++ + continue + } + if started { + b.WriteString(strings.Repeat("\n", blank)) + } + b.WriteString(line + "\n") + started, blank = true, 0 + } + if !started { + return "", fmt.Errorf("CHANGELOG.md has no entry ## %s", v) + } + return b.String(), nil +} diff --git a/internal/cosign/main.go b/internal/cosign/main.go new file mode 100644 index 00000000..3fe80d9e --- /dev/null +++ b/internal/cosign/main.go @@ -0,0 +1,185 @@ +package cosign + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" +) + +// usage is devvm-cosign's help. +const usage = `devvm-cosign: the co-signer of devvm's releases and bases. + + devvm-cosign [-config FILE] run sign and publish each build CI handed over whose rebuild matches + devvm-cosign [-config FILE] init write the first state.json, from what GitHub has published + devvm-cosign [-config FILE] check check the config, the keys and the devvm checkout, offline + devvm-cosign [-config FILE] retry TAG rebuild TAG again, though its last rebuild didn't match + devvm-cosign [-config FILE] ack TAG clear TAG's alert, once you've dealt with it + devvm-cosign [-config FILE] failed tell the config's notify command that a run failed + +FILE is /etc/devvm-cosign/config.toml by default. run, init and check read +the key files from systemd's credentials when CREDENTIALS_DIRECTORY is set. +` + +// An Env is what devvm-cosign reads from its environment: systemd's +// credentials folder, "" outside a unit that loads them. +type Env struct { + Credentials string +} + +// Main runs devvm-cosign with args, its log on log, and returns its exit +// status: 0 when everything it tried worked, 1 when something failed or a +// refusal or alert is waiting for a maintainer, and 2 for a usage error. +// It first makes the process non-dumpable, so no other process of its +// user, such as a build's that escaped its container, can read its +// memory, where its keys are. +func Main(ctx context.Context, args []string, env Env, log io.Writer) int { + if err := undumpable(); err != nil { + fmt.Fprintf(log, "devvm-cosign: %v\n", err) + return 1 + } + fs := flag.NewFlagSet("devvm-cosign", flag.ContinueOnError) + fs.SetOutput(log) + fs.Usage = func() { fmt.Fprint(log, usage) } + config := fs.String("config", DefaultConfig, "the config file") + if err := fs.Parse(args); err != nil { + if errors.Is(err, flag.ErrHelp) { + return 0 + } + return 2 + } + cmd, tag := "run", "" + switch a := fs.Args(); { + case len(a) == 0: + case len(a) == 1 && (a[0] == "run" || a[0] == "init" || a[0] == "check" || a[0] == "failed"): + cmd = a[0] + case len(a) == 2 && (a[0] == "retry" || a[0] == "ack"): + cmd, tag = a[0], a[1] + default: + fmt.Fprintf(log, "devvm-cosign: not a command: %s\n", strings.Join(a, " ")) + fs.Usage() + return 2 + } + if err := run(ctx, cmd, tag, *config, env, log); err != nil { + fmt.Fprintf(log, "devvm-cosign: %v\n", err) + return 1 + } + return 0 +} + +// run runs cmd with the config at path. +func run(ctx context.Context, cmd, tag, path string, env Env, log io.Writer) error { + if cmd == "failed" { + return failed(ctx, path, log) + } + if cmd == "retry" || cmd == "ack" { + c, err := ReadConfig(path) + if err != nil { + return err + } + unlock, err := Lock(c.StateDir) + if err != nil { + return err + } + defer unlock() + co := &Cosigner{State: Store{Path: filepath.Join(c.StateDir, "state.json")}, Log: log} + return co.Clear(tag, cmd == "retry") + } + s, err := LoadConfig(path, env.Credentials) + if err != nil { + return err + } + c := New(s, log) + if cmd == "check" { + b, ok := c.Builder.(ReleaseBuild) + if ok { + if err := b.checkCheckout(ctx); err != nil { + return err + } + } + fmt.Fprintf(log, "devvm-cosign: %s checks out: %d tag signers, its release key %s, devvm %s\n", + path, len(s.Signers), keyID(s.Release), s.Devvm.Commit[:12]) + return nil + } + unlock, err := Lock(s.StateDir) + if err != nil { + return err + } + defer unlock() + if cmd == "init" { + return c.Init(ctx) + } + // What failed, for devvm-cosign failed, which the units' OnFailure= + // runs: first that this run started, so one that's killed or times out + // isn't told as an earlier run's failure, then how it ended. + last := filepath.Join(s.StateDir, lastFailure) + started := time.Now().UTC().Format(time.RFC3339) + if err := writeWhole(last, []byte(started+": a run started and didn't finish: it was stopped, killed or timed out\n"), 0o600); err != nil { + return err + } + err = c.Run(ctx) + if err == nil { + return os.Remove(last) + } + if werr := writeWhole(last, []byte(started+": "+err.Error()+"\n"), 0o600); werr != nil { + fmt.Fprintf(log, "devvm-cosign: %v\n", werr) + } + return err +} + +// lastFailure is the state folder's record of the last run's failures. +const lastFailure = "last-failure.txt" + +// failed tells the maintainer that a devvm-cosign unit failed, through +// the config's notify command: devvm-cosign-failed.service runs it, as +// the units' OnFailure=. It reads no key, so it runs whatever failed. +func failed(ctx context.Context, path string, log io.Writer) error { + c, err := ReadConfig(path) + if err != nil { + return err + } + if len(c.Notify) == 0 { + return nil + } + text := "A devvm-cosign run failed or holds something for you: journalctl -u 'devvm-cosign@*' says why.\n" + if last, err := readFile(filepath.Join(c.StateDir, lastFailure), maxNotify, 0); err == nil { + text += "The last failure it recorded, at " + string(last) + } + return notify(ctx, c.Notify, text, log) +} + +// keyID is k's co-signer key's ID, as minisign prints it. +func keyID(k Kind) string { + id := k.Secret.Public().ID + return strings.ToUpper(fmt.Sprintf("%x", []byte{id[7], id[6], id[5], id[4], id[3], id[2], id[1], id[0]})) +} + +// New is the co-signer the setup describes, logging to log. +func New(s *Setup, log io.Writer) *Cosigner { + http := NewHTTP(false) + tok := &AppToken{ + API: s.API, HTTP: http, AppID: s.App.ID, Installation: s.App.Installation, Key: s.AppKey, + Repos: []string{name(s.Repo), name(s.Tap)}, + } + return &Cosigner{ + GitHub: Client{API: s.API, Uploads: s.Uploads, HTTP: http, Tokens: tok}, + Repo: s.Repo, Tap: s.Tap, Release: s.Release, Base: s.Base, + Builder: ReleaseBuild{ + Checkout: s.Devvm.Checkout, Commit: s.Devvm.Commit, GitURL: s.GitURL, Signers: s.Signers, + Runtime: s.Runtime, Src: filepath.Join(s.StateDir, "src"), Work: filepath.Join(s.BuildDir, "work"), + Cache: filepath.Join(s.StateDir, "cache"), Log: log, + }, + BaseBuilder: NoBaseBuild{}, + State: Store{Path: filepath.Join(s.StateDir, "state.json")}, + Dir: s.StateDir, + Work: filepath.Join(s.BuildDir, "work"), + Log: log, + } +} + +func name(repo string) string { _, n, _ := strings.Cut(repo, "/"); return n } diff --git a/internal/cosign/main_test.go b/internal/cosign/main_test.go new file mode 100644 index 00000000..3a5dc7a3 --- /dev/null +++ b/internal/cosign/main_test.go @@ -0,0 +1,121 @@ +package cosign + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +// withCheckout is configFiles with a real devvm checkout at its pinned +// commit, which devvm-cosign check reads, and more's change. +func withCheckout(t *testing.T, more func(string) string) (string, string) { + t.Helper() + checkout, _, pinned := buildRepos(t, newTagKey(t)) + return configFiles(t, func(s string) string { + s = regexp.MustCompile(`checkout = ".*"`).ReplaceAllString(s, `checkout = "`+checkout+`"`) + s = strings.Replace(s, strings.Repeat("a", 40), pinned, 1) + if more != nil { + s = more(s) + } + return s + }) +} + +// devvm-cosign's command line: a usage error exits 2, help 0, and a +// failure 1, saying why. +func TestCommandLine(t *testing.T) { + path, dir := withCheckout(t, nil) + for name, tc := range map[string]struct { + args []string + code int + want string + }{ + "help": {[]string{"-h"}, 0, "devvm-cosign [-config FILE] run"}, + "another flag": {[]string{"-x"}, 2, ""}, + "no such": {[]string{"-config", path, "sign"}, 2, "not a command: sign"}, + "two commands": {[]string{"-config", path, "run", "init"}, 2, "] init"}, + "retry, no tag": {[]string{"-config", path, "retry"}, 2, "not a command: retry"}, + "ack, two tags": {[]string{"-config", path, "ack", "v1.0.0", "v1.0.1"}, 2, "not a command"}, + "no config": {[]string{"-config", "/nowhere/config.toml", "check"}, 1, "nowhere"}, + "run, no state": {[]string{"-config", path}, 1, "devvm-cosign init"}, + "retry, none": {[]string{"-config", path, "retry", "v1.0.0"}, 1, "devvm-cosign init"}, + "check": {[]string{"-config", path, "check"}, 0, "checks out"}, + "a missing repo": {[]string{"-config", path + "x", "init"}, 1, ""}, + } { + var log bytes.Buffer + if code := Main(t.Context(), tc.args, Env{}, &log); code != tc.code || !strings.Contains(log.String(), tc.want) { + t.Errorf("%s: %d, want %d with %q\n%s", name, code, tc.code, tc.want, log.String()) + } + } + // Under its unit, check reads the keys from systemd's credentials. + creds := t.TempDir() + for _, name := range []string{"release.key", "base.key", "app.pem"} { + if err := os.Rename(filepath.Join(dir, name), filepath.Join(creds, name)); err != nil { + t.Fatal(err) + } + } + var log bytes.Buffer + if code := Main(t.Context(), []string{"-config", path, "check"}, Env{Credentials: creds}, &log); code != 0 { + t.Errorf("check from the credentials: %d\n%s", code, log.String()) + } + // retry and ack read no key file: the co-signer's user runs them, and + // can't read the keys, which are root's. + if err := (Store{Path: filepath.Join(dir, "state.json")}).Save(newState("0.2.0", 0)); err != nil { + t.Fatal(err) + } + log.Reset() + if code := Main(t.Context(), []string{"-config", path, "ack", "v0.3.0"}, Env{}, &log); code != 1 || !strings.Contains(log.String(), "no alert") { + t.Errorf("ack with no key files: %d\n%s", code, log.String()) + } +} + +// A run that fails records what failed; devvm-cosign failed, which the +// units' OnFailure= runs for any failure, killed or not, runs the +// config's notify command with it on its stdin and an environment of its +// own, none of the co-signer's, even once its own context is over. +func TestNotify(t *testing.T) { + out := t.TempDir() + script := filepath.Join(t.TempDir(), "notify") + if err := os.WriteFile(script, []byte("#!/bin/sh\ncat > '"+out+"/stdin'\nenv > '"+out+"/env'\necho notified\n"), 0o700); err != nil { //nolint:gosec // a test's script + t.Fatal(err) + } + path, dir := configFiles(t, func(s string) string { return "notify = [\"" + script + "\"]\n" + s }) + t.Setenv("DEVVM_COSIGN_SECRET", "x") + var log bytes.Buffer + if code := Main(t.Context(), []string{"-config", path, "run"}, Env{}, &log); code != 1 || strings.Contains(log.String(), "notified") { + t.Fatalf("run: %d\n%s", code, log.String()) + } + if last, err := os.ReadFile(filepath.Join(dir, lastFailure)); err != nil || !strings.Contains(string(last), "devvm-cosign init") { //nolint:gosec // the test's own file + t.Errorf("the last failure: %q %v", last, err) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + log.Reset() + if code := Main(ctx, []string{"-config", path, "failed"}, Env{}, &log); code != 0 || !strings.Contains(log.String(), "notified") { + t.Fatalf("failed: %d\n%s", code, log.String()) + } + stdin, _ := os.ReadFile(filepath.Join(out, "stdin")) //nolint:gosec // the test's own file + env, _ := os.ReadFile(filepath.Join(out, "env")) //nolint:gosec // the test's own file + if !strings.Contains(string(stdin), "journalctl") || !strings.Contains(string(stdin), "devvm-cosign init") || + strings.Contains(string(env), "DEVVM_COSIGN_SECRET") || !strings.Contains(string(env), "DEVVM_COSIGN_EVENT=failed") { + t.Errorf("notify's stdin %q, env %q", stdin, env) + } + // A notify that fails fails devvm-cosign failed, which the journal shows. + if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 3\n"), 0o700); err != nil { //nolint:gosec // a test's script + t.Fatal(err) + } + log.Reset() + if code := Main(t.Context(), []string{"-config", path, "failed"}, Env{}, &log); code != 1 || !strings.Contains(log.String(), "notify") { + t.Errorf("a failing notify: %d\n%s", code, log.String()) + } + // With no notify command, there's nothing to tell. + plain, _ := configFiles(t, nil) + if code := Main(t.Context(), []string{"-config", plain, "failed"}, Env{}, io.Discard); code != 0 { + t.Errorf("failed with no notify: %d", code) + } +} diff --git a/internal/cosign/notify.go b/internal/cosign/notify.go new file mode 100644 index 00000000..ccc2ed69 --- /dev/null +++ b/internal/cosign/notify.go @@ -0,0 +1,41 @@ +package cosign + +import ( + "context" + "fmt" + "io" + "os/exec" + "strings" + "time" +) + +// notifyTimeout bounds the notify command, and maxNotify what it's given. +const ( + notifyTimeout = time.Minute + maxNotify = 64 << 10 +) + +// notify runs command, the config's notify, to tell a maintainer that a +// run failed, or found a refusal or an alert waiting for them: what +// failed goes on its stdin, at most maxNotify bytes, and it runs with a +// fixed environment, none of the co-signer's, so it gets no credential +// and no runtime's socket, in the root folder, for a minute at most. What +// it writes goes to the log. +func notify(ctx context.Context, command []string, failures string, log io.Writer) error { + // Its own minute, whatever ended the caller's context. + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), notifyTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, command[0], command[1:]...) //nolint:gosec // the maintainer's own command, from the co-signer's config + cmd.Env = []string{"PATH=/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8", "DEVVM_COSIGN_EVENT=failed"} + cmd.Dir = "/" + if len(failures) > maxNotify { + failures = failures[:maxNotify] + } + cmd.Stdin = strings.NewReader(failures + "\n") + cmd.Stdout, cmd.Stderr = log, log + cmd.WaitDelay = 5 * time.Second + if err := cmd.Run(); err != nil { + return fmt.Errorf("%s: %w", command[0], err) + } + return nil +} diff --git a/internal/cosign/release.go b/internal/cosign/release.go new file mode 100644 index 00000000..343a2621 --- /dev/null +++ b/internal/cosign/release.go @@ -0,0 +1,550 @@ +package cosign + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + + "github.com/devvmhq/devvm/internal/minisign" +) + +// formulas are the Homebrew formulas a release gets in the tap: devvm for +// a release, devvm-rc for every one. +func formulas(v version) []string { + if v.prerelease() { + return []string{"devvm-rc.rb"} + } + return []string{"devvm.rb", "devvm-rc.rb"} +} + +// A candidate is a release CI handed over: its tag and version, and the +// newest successful run of the release workflow for that tag. +type candidate struct { + tag string + v version + run Run +} + +// releaseRuns are the releases CI handed over that the co-signer hasn't +// published, oldest version first: from the successful runs of the +// pinned release workflow, pushed for a tag of this repo, each tag's +// newest run. +func (c *Cosigner) releaseRuns(ctx context.Context, s State, rs []Release) ([]candidate, error) { + last, err := parseVersion(s.Release.Last) + if err != nil { + return nil, err + } + runs, err := c.GitHub.Runs(ctx, c.Repo, c.Release.Workflow, func(r Run) bool { + v, _, kind := tagKind(r.HeadBranch) + return kind != minisign.Release || v.compare(last) <= 0 && (s.Release.Signed[v.raw] == "" || s.Release.Published[v.raw]) + }) + if err != nil { + return nil, fmt.Errorf("listing CI's runs of %s: %w", c.Release.Workflow, err) + } + published := map[string]bool{} + for _, r := range rs { + published[r.TagName] = published[r.TagName] || !r.Draft + } + seen := map[string]bool{} + var out []candidate + for _, r := range runs { // newest first: a tag's first is its newest + v, _, kind := tagKind(r.HeadBranch) + // Only a tag's push starts a release's run: one started otherwise, on + // a branch of a tag's name, isn't one. + if kind != minisign.Release || seen[r.HeadBranch] || r.Event != PushEvent || !fromWorkflow(r, c.Repo, c.Release.Workflow) { + continue + } + seen[r.HeadBranch] = true + if !published[r.HeadBranch] && !s.Release.Published[v.raw] { + out = append(out, candidate{tag: r.HeadBranch, v: v, run: r}) + } + } + slices.SortStableFunc(out, func(a, b candidate) int { return a.v.compare(b.v) }) + return out, nil +} + +// PushEvent is the GitHub Actions event a tag's push starts a run with, +// the only one a release's run is: GitHub's name for the event, not git +// push, which devvm never runs. +const PushEvent = "push" + +// fromWorkflow is whether r is a successful run of the workflow file of +// repo's own, not a fork's. +func fromWorkflow(r Run, repo, workflow string) bool { + return r.Path == ".github/workflows/"+workflow && r.Conclusion == "success" && r.HeadRepository.FullName == repo +} + +// release signs, then publishes, the release CI handed over in cd: +// 1. its version is newer than any it signed, or one it signed already +// (a run that stopped), with the same SHA256SUMS; +// 2. CI's artifact holds SHA256SUMS, CI's signature of it, which checks +// out with CI's key, and the files it lists, with its SHA-256s, and +// nothing else (stage); +// 3. the co-signer's own build of its tag gives the same SHA256SUMS and +// files, and the formulas it renders from SHA256SUMS, or it signs +// nothing and writes a report (rebuild); +// 4. it signs SHA256SUMS, makes the release's draft, uploads every file, +// and publishes it (publishRelease). +func (c *Cosigner) release(ctx context.Context, s *State, cd candidate, rs []Release) error { + l, v := &s.Release.Ledger, cd.v.raw + if l.Alerts[v].active() { + return nil // held reports it + } + signed := l.Signed[v] + last, err := parseVersion(s.Release.Last) + if err != nil { + return err + } + if signed == "" && cd.v.compare(last) <= 0 { + if _, found, err := c.GitHub.ReleaseByTag(ctx, c.Repo, cd.tag); err != nil || found { + return err // published before the co-signer's state began + } + // An alert, so it's said every run until a maintainer, who knows + // why CI ran for it, acks it; acked, it's left alone. + if _, raised := l.Alerts[v]; !raised { + l.alert(v, "refused: CI handed it over, but it isn't newer than "+s.Release.Last+", the newest release the co-signer signed, so it's an older release replayed; find out why CI ran for it") + return c.save(s) + } + return nil + } + if _, refused := l.refusedRun(cd.run.ID); refused { + return nil // held reports it, with no download + } + draft, err := c.ownDraft(ctx, l, v, cd.tag, rs) + if err != nil { + return err + } + // Waiting for the old key's signature costs no download, and fails the + // run, so the maintainer hears that the draft waits for them. + if _, ok := draft.asset(legacySig); signed != "" && draft.ID != 0 && c.Release.Legacy != nil && !ok { + return errLegacy + } + if signed == "" && c.built { + return errNextRun // with no download + } + parse := func(data []byte) (Manifest, error) { return ParseSums(v, data) } + h, err := c.stage(ctx, &c.Release, cd.run, sumsName, parse) + if err != nil { + return err + } + sum := h.m.sum() + switch { + case signed != "" && signed != sum: + return fmt.Errorf("refused: its SHA256SUMS (%s) isn't the one the co-signer signed for %s (%s)", sum, v, signed) + case l.Refused[sum].active(): + r := l.Refused[sum] + r.Run = cd.run.ID + l.Refused[sum] = r + return c.save(s) // held reports it + } + if signed == "" { + if ok, err := c.rebuild(ctx, s, cd, h); err != nil || !ok { + return err + } + // The build took CI's files off the disk: staged again, and the + // same manifest, for the upload. + again, err := c.stage(ctx, &c.Release, cd.run, sumsName, parse) + if err != nil { + return err + } + if !bytes.Equal(again.m.Data, h.m.Data) { + return fmt.Errorf("refused: CI's artifact's SHA256SUMS changed while the co-signer built it") + } + h = again + } + return c.publishRelease(ctx, s, cd, draft, h) +} + +// ownDraft is the draft release of tag that the co-signer made for key, +// or an empty Release when it has none to use: none made, or one deleted +// since. A draft of tag that it didn't make is refused, as it makes the +// one it publishes. +func (c *Cosigner) ownDraft(ctx context.Context, l *Ledger, key, tag string, rs []Release) (Release, error) { + id := l.draft(key) + var mine Release + for _, r := range rs { + switch { + case !r.Draft || r.TagName != tag: + case r.ID == id: + mine = r + default: + return Release{}, fmt.Errorf("a draft release of %s (ID %d) that the co-signer didn't make: delete it by hand, as the co-signer makes the release it publishes", tag, r.ID) + } + } + if mine.ID != 0 || id == 0 { + return mine, nil + } + // Not in the list read: read it by its ID. + r, err := c.GitHub.Release(ctx, c.Repo, id) + switch { + case isStatus(err, 404): + return Release{}, nil + case err != nil: + return Release{}, err + case !r.Draft: + return Release{}, fmt.Errorf("%w: its release %d is published, which the next run finishes", errWaiting, id) + } + return r, nil +} + +// rebuild builds cd's tag with the co-signer's own devvm and compares it +// with CI's, and its formulas with those it renders from CI's SHA256SUMS. +// On a match it keeps the formulas and notes and records the manifest +// signed, and returns true; on a mismatch it writes a report and records +// the manifest refused, which held reports, and returns false. +func (c *Cosigner) rebuild(ctx context.Context, s *State, cd candidate, h handover) (bool, error) { + if err := oneBuild(&c.built, h); err != nil { + return false, err + } + c.logf("%s: CI's signature and files check out; rebuilding it", cd.tag) + b, err := buildRelease(ctx, c.Builder, c.Dir, c.Repo, cd, h) + if err != nil { + return false, c.buildFailed(ctx, s, &s.Release.Ledger, cd.tag, cd.v.raw, h, err) + } + sum := h.m.sum() + if len(b.diffs) > 0 { + path, err := report(c.Dir, c.now(), cd.tag, h.m, b.diffs) + if err != nil { + return false, err + } + s.Release.refuse(sum, cd.v.raw, cd.run.ID) + c.logf("%s: %v: %d files differ, in %s", cd.tag, errMismatch, len(b.diffs), path) + return false, c.save(s) + } + dir := filepath.Join(c.Dir, "kept", cd.v.raw) + if err := os.MkdirAll(dir, 0o700); err != nil { + return false, err + } + for _, name := range sortedKeys(b.keep) { + if err := writeWhole(filepath.Join(dir, name), b.keep[name], 0o600); err != nil { + return false, err + } + s.Release.Kept[cd.v.raw+"/"+name] = sha256Hex(b.keep[name]) + } + s.Release.Signed[cd.v.raw] = sum + s.Release.Tags[cd.v.raw] = b.object + s.Release.Runs[strconv.FormatInt(cd.run.ID, 10)] = cd.v.raw + if cd.v.compare(mustVersion(s.Release.Last)) > 0 { + s.Release.Last = cd.v.raw + } + return true, c.save(s) +} + +// A releaseBuild is the co-signer's own build of a release, compared with +// CI's: the tag object it checked, the files it keeps for publishing (the +// notes and the formulas it rendered), and each file that differs. +type releaseBuild struct { + object string + keep map[string][]byte + diffs []diff +} + +// buildRelease builds cd's tag with builder, its files in a folder of the +// state folder dir's, and compares it with h, CI's: every file, and the +// formulas it renders for repo from CI's SHA256SUMS with the build's. An +// error is a build that failed, rather than differed. +func buildRelease(ctx context.Context, builder ReleaseBuilder, dir, repo string, cd candidate, h handover) (releaseBuild, error) { + work, err := newOut(dir, cd.tag) + if err != nil { + return releaseBuild{}, err + } + defer os.RemoveAll(work) + out := filepath.Join(work, "out") + built, err := builder.Build(ctx, cd.tag, out) + if err != nil { + return releaseBuild{}, err + } + if built.Tag.Commit != cd.run.HeadSHA { + return releaseBuild{}, fmt.Errorf("CI's run %d built %s, but %s is %s", cd.run.ID, cd.run.HeadSHA, cd.tag, built.Tag.Commit) + } + notes, err := releaseNotes(built.Changelog, cd.v.raw) + if err != nil { + return releaseBuild{}, err + } + b := releaseBuild{object: built.Object, keep: map[string][]byte{notesFile: []byte(notes)}} + if b.diffs, err = compareBuild(h.m, out); err != nil { + return releaseBuild{}, err + } + for _, f := range formulas(cd.v) { + want, err := renderFormula(built.Formula, strings.TrimSuffix(f, ".rb"), repo, cd.v, h.m) + if err != nil { + return releaseBuild{}, err + } + got, err := readBuilt(filepath.Join(out, f)) + if err != nil { + return releaseBuild{}, err + } + if !bytes.Equal(got, want) { + ours := "" + if got != nil { + ours = sha256Hex(got) + } + // What's compared here is the co-signer's render, from the + // signed SHA256SUMS, with its own build's. + b.diffs = append(b.diffs, diff{f + " (rendered from SHA256SUMS, then the rebuild's)", sha256Hex(want), ours}) + } + b.keep[f] = want + } + return b, nil +} + +// errLegacy is a signed draft waiting for the old release key's +// signature, which the maintainer makes by hand while releases bridge +// from that key: a failure, so every run tells them until they do. +var errLegacy = errors.New("signed, and waiting for you: sign its SHA256SUMS with the old release key (trusted comment devvm ) and upload SHA256SUMS.minisig to its draft") + +// notesFile is the release's notes the co-signer keeps, from the tag's +// CHANGELOG.md. +const notesFile = "notes.md" + +// mustVersion is v parsed, which State.check made sure it is. +func mustVersion(v string) version { + out, _ := parseVersion(v) + return out +} + +// keptFile is the file name the co-signer kept for release v in its +// state folder dir, read again and checked against the SHA-256 the state +// recorded, as it sits on disk between runs. +func keptFile(dir string, s *State, v, name string) ([]byte, error) { + want, ok := s.Release.Kept[v+"/"+name] + if !ok { + return nil, fmt.Errorf("the co-signer kept no %s for %s: copy kept/%s from the machine that signed it", name, v, v) + } + f, err := os.Open(filepath.Join(dir, "kept", v, name)) //nolint:gosec // the co-signer's own state folder + if err != nil { + return nil, err + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, maxManifest+1)) + if err != nil { + return nil, err + } + if sha256Hex(data) != want { + return nil, fmt.Errorf("kept/%s/%s isn't the file the co-signer kept: check the machine", v, name) + } + return data, nil +} + +// releaseTitle is a release's title on GitHub, as scripts/publish.sh +// names it. +func releaseTitle(v string) string { return "devvm " + v } + +// publishRelease signs h's SHA256SUMS, makes cd's draft release if the +// co-signer has none, uploads every file to it, and publishes it once two +// of three keys signed it, and while the bridge lasts the old key too, and +// the draft is exactly what it uploaded; then it checks the release again +// and finishes the tap. +func (c *Cosigner) publishRelease(ctx context.Context, s *State, cd candidate, draft Release, h handover) error { + l, v := &s.Release.Ledger, cd.v.raw + notes, err := keptFile(c.Dir, s, v, notesFile) + if err != nil { + return err + } + sig, err := c.Release.Secret.Sign(h.m.Data, minisign.Release.Comment(v)) + if err != nil { + return err + } + if err := c.Release.Keys.Check(h.m.Data, map[minisign.Role][]byte{minisign.CI: h.ciSig, minisign.Cosign: sig}, v); err != nil { + return fmt.Errorf("not published: %w", err) + } + if draft.ID == 0 { + if draft, err = c.GitHub.CreateRelease(ctx, c.Repo, cd.tag, "", releaseTitle(v), string(notes), cd.v.prerelease()); err != nil { + return fmt.Errorf("making its draft release: %w", err) + } + l.Drafts[v] = append(l.Drafts[v], draft.ID) + if err := c.save(s); err != nil { + return err + } + } + keep := "" + if c.Release.Legacy != nil { + keep = legacySig + } + ids, err := c.upload(ctx, draft, h.assets(sig), keep) + if err != nil { + return err + } + c.logf("%s: signed, and its draft release holds its files", cd.tag) + now, err := c.GitHub.Release(ctx, c.Repo, draft.ID) + if err != nil { + return err + } + if c.Release.Legacy != nil { + old, a, err := c.download(ctx, now, legacySig, maxSig) + if errors.Is(err, errWaiting) { + return errLegacy + } else if err != nil { + return err + } + if err := c.Release.Legacy.Check(h.m.Data, old, minisign.LegacyComment(v)); err != nil { + return fmt.Errorf("not published: its %s: %w", legacySig, err) + } + ids[legacySig] = a + } + if err := exact(now, cd.tag, releaseTitle(v), string(notes), ids, ""); err != nil { + return fmt.Errorf("not published: %w", err) + } + // The tag must still be the one the rebuild checked: a tag deleted or + // pushed again while the draft waited would publish other code. + if obj, found, err := c.GitHub.TagRef(ctx, c.Repo, cd.tag); err != nil { + return err + } else if !found || obj != s.Release.Tags[v] { + return fmt.Errorf("not published: %s now names %q, not the tag object %s the co-signer checked; find out who moved it", cd.tag, obj, s.Release.Tags[v]) + } + // GitHub's latest only when it's newer than every release published, + // so a release published after a newer one, as when the old key signs + // the newer one's draft first, never moves the latest back. + pub, err := c.GitHub.Publish(ctx, c.Repo, draft.ID, cd.v.prerelease(), !cd.v.prerelease() && !olderThanPublished(*s, cd.v)) + if err != nil { + return fmt.Errorf("publishing: %w", err) + } + if err := exact(pub, cd.tag, releaseTitle(v), string(notes), ids, ""); err != nil { + l.alert(v, "published, but "+err.Error()+": compare its files with its SHA256SUMS by hand. devvm and the install script refuse a file that doesn't match it, and Homebrew one that doesn't match its formula, which the tap doesn't get; with immutable releases on, the fix is a newer release") + return c.save(s) + } + l.Published[v] = true + if err := c.save(s); err != nil { + return err + } + c.logf("%s: published", cd.tag) + return c.finish(ctx, s, cd.tag, cd.v) +} + +// publishedRelease looks at r, a published release: one the co-signer +// published gets its tap finished; its own draft that it didn't see +// published (its publish's answer lost, or a maintainer published it) is +// checked as published first. One it didn't make is foreign's. +func (c *Cosigner) publishedRelease(ctx context.Context, s *State, r Release) error { + v, _, _ := tagKind(r.TagName) + l := &s.Release.Ledger + switch { + case s.Release.Done[v.raw] || l.Alerts[v.raw].active(): + return nil + case l.Published[v.raw]: + return c.finish(ctx, s, r.TagName, v) + case l.Signed[v.raw] != "" && l.draft(v.raw) == r.ID: + if err := c.checkPublished(ctx, s, r, v); err != nil { + l.alert(v.raw, "the co-signer's draft was published before its last check, and "+err.Error()+": compare its files with its SHA256SUMS by hand, then ack it; the tap isn't updated") + return c.save(s) + } + l.Published[v.raw] = true + if err := c.save(s); err != nil { + return err + } + return c.finish(ctx, s, r.TagName, v) + } + return nil // not its own: foreign alerts on it, if it's new +} + +// checkPublished checks r, the co-signer's draft, published: its +// SHA256SUMS is the one it signed, CI's signature and its own check out, +// and the old key's while the bridge lasts, every file has its SHA-256, +// downloaded, and its title and notes are the co-signer's. +func (c *Cosigner) checkPublished(ctx context.Context, s *State, r Release, v version) error { + data, _, err := c.download(ctx, r, sumsName, maxManifest) + if err != nil { + return err + } + if sha256Hex(data) != s.Release.Signed[v.raw] { + return fmt.Errorf("its SHA256SUMS isn't the one the co-signer signed") + } + m, err := ParseSums(v.raw, data) + if err != nil { + return err + } + sigs := map[minisign.Role][]byte{} + for _, role := range []minisign.Role{minisign.CI, minisign.Cosign} { + if sigs[role], _, err = c.download(ctx, r, minisign.SigName(sumsName, role), maxSig); err != nil { + return err + } + if err := c.Release.Keys.CheckRole(role, m.Data, sigs[role], v.raw); err != nil { + return err + } + } + names := []string{minisign.SigName(sumsName, minisign.CI), minisign.SigName(sumsName, minisign.Cosign)} + if c.Release.Legacy != nil { + old, _, err := c.download(ctx, r, legacySig, maxSig) + if err != nil { + return err + } + if err := c.Release.Legacy.Check(m.Data, old, minisign.LegacyComment(v.raw)); err != nil { + return err + } + names = append(names, legacySig) + } + notes, err := keptFile(c.Dir, s, v.raw, notesFile) + if err != nil { + return err + } + if !sameText(r.Name, releaseTitle(v.raw)) || !sameText(r.Body, string(notes)) { + return fmt.Errorf("its title or notes aren't the co-signer's") + } + return c.GitHub.checkFiles(ctx, c.Repo, r, m, names...) +} + +// formulaVersion is the release the formula data installs, from its +// first download URL; "" for none. +func formulaVersion(data []byte) string { + m := regexp.MustCompile(`/releases/download/v([0-9a-z.-]+)/`).FindSubmatch(data) + if m == nil { + return "" + } + return string(m[1]) +} + +// finish updates the tap for release tag, v, which the co-signer +// published and checked after: the formulas it rendered from the signed +// SHA256SUMS and kept, each checked again, each only when the tap's is +// older, then records the release done. +func (c *Cosigner) finish(ctx context.Context, s *State, tag string, ver version) error { + v := ver.raw + message := "devvm " + v + if ver.prerelease() { + message = "devvm-rc " + v + } + for _, f := range formulas(ver) { + want, err := keptFile(c.Dir, s, v, f) + if err != nil { + return fmt.Errorf("the tap's %s: %w", f, err) + } + path := "Formula/" + f + have, sha, found, err := c.GitHub.Contents(ctx, c.Tap, path, "main") + if err != nil { + return err + } + if found && bytes.Equal(have, want) { + continue + } + if was, err := parseVersion(formulaVersion(have)); found && err == nil && was.compare(ver) > 0 { + // Newer than any release the co-signer signed: nothing it + // published, so someone else wrote the tap, which would hold + // every update back. Its alert is its own, by the formula and + // the version it installs, whatever else was raised on v. + key := "tap:" + f + "@" + was.raw + if a, raised := s.Others[key]; was.compare(mustVersion(s.Release.Last)) > 0 && (!raised || a.active()) { + if !raised { + s.Others[key] = Alert{Reason: "the tap's " + path + " installs " + was.raw + ", newer than any release the co-signer signed, so someone else wrote it, and it holds " + v + " back: find out who and put the tap right", Raised: 1} + return c.save(s) + } + return nil // held reports it + } + c.logf("%s: the tap's %s stays at %s, which is newer", tag, path, was.raw) + continue + } + if err := c.GitHub.PutContents(ctx, c.Tap, path, "main", message, want, sha); err != nil { + return fmt.Errorf("the tap's %s: %w", path, err) + } + c.logf("%s: the tap's %s is now devvm %s", tag, path, v) + } + s.Release.Done[v] = true + return c.save(s) +} diff --git a/internal/structure/structure_test.go b/internal/structure/structure_test.go index b7d2fb99..fa05fc72 100644 --- a/internal/structure/structure_test.go +++ b/internal/structure/structure_test.go @@ -339,6 +339,7 @@ func devvmExecSites() map[string]string { return map[string]string{ "internal/hostgit/hostgit.go": "the host git runner: git without the repo's fsmonitor, hooks or filters", "internal/cosign/build.go": "devvm-cosign's git and release.sh, its own program's, logged to the journal and the build's log", + "internal/cosign/notify.go": "devvm-cosign's notify command, the maintainer's own, with a fixed environment, logged to the journal", "internal/backend/lima/limactl.go": "limactl's command, which Lima's Runner runs into the run log", "internal/backend/lima/lima.go": "qemu-img's command, which Lima's Runner runs", "internal/backend/lima/oci.go": "docker save's command, which Lima's Runner runs", @@ -656,6 +657,7 @@ func devvmNames() map[string]literalOwner { func devvmNameFree() map[string]freeName { return map[string]freeName{ "internal/vm.CursorCommand": {"the Cursor editor's command, not its CLI agent's", []string{"internal/vm/ssh.go", "internal/cli/cursor.go"}}, + "internal/cosign.PushEvent": {"GitHub Actions' event for a tag's push, not git push", []string{"internal/cosign/release.go"}}, } } diff --git a/testdata/coverage/darwin.txt b/testdata/coverage/darwin.txt index 97b06f8f..e5485cd7 100644 --- a/testdata/coverage/darwin.txt +++ b/testdata/coverage/darwin.txt @@ -10,6 +10,7 @@ internal/backend/registry 100.0 internal/build 88.8 internal/cli 91.7 internal/cli/docgen 86.5 +internal/cosign 88.6 internal/daemon 98.3 internal/desktop 79.6 internal/devcontainer 96.8 diff --git a/testdata/coverage/linux.txt b/testdata/coverage/linux.txt index a5d533ef..ebc3aa36 100644 --- a/testdata/coverage/linux.txt +++ b/testdata/coverage/linux.txt @@ -10,6 +10,7 @@ internal/backend/registry 100.0 internal/build 88.5 internal/cli 91.1 internal/cli/docgen 86.5 +internal/cosign 88.6 internal/daemon 98.0 internal/desktop 77.2 internal/devcontainer 96.8