Files
w3cjandClaude Opus 5.5 00e5ea59f4 feat(cosign): the run, which makes and publishes each release CI hands over
devvm-cosign's run (Cosigner.Run), its command (cmd/devvm-cosign, Main)
and the maintainer's commands, devvm-cosign retry, ack and failed.

CI's token can only read the repo, so CI hands each build over as a
workflow artifact, and only the co-signer, and the maintainer by hand,
can make or publish a release. For each release CI handed over that it
hasn't published, oldest first, from the newest successful run of the
pinned release workflow for each tag, of this repo's own:

- its version is newer than the newest it signed, or one it signed, with
  the same SHA256SUMS; an older one is an alert, as a replay, until the
  maintainer acks it, unless it was published before the state began;
- CI's artifact is staged (stage/, which no build can reach) and
  checked: SHA256SUMS, CI's signature with CI's key and devvm-release
  <version>, and exactly the files it lists, each with its SHA-256; its
  files are deleted before the build and downloaded again after a match,
  so none of CI's bytes is on disk while a container could be live;
- a run builds once, so the podman service, which lives for the run,
  lives for one build, and anything that escaped a container is gone
  before the next build's host git and release.sh run; the next release
  or base waits for the next run;
- the build's finished files go in a folder of the state's src/, which
  release.sh copies to and the co-signer reads, where no container can
  swap a file or the folder;
- the tag's commit has to be the commit CI's run built, and the
  co-signer's own build has to match every file and SHA256SUMS; it
  renders the tap's formulas itself from the tag's template and the
  signed SHA256SUMS (formula.go, as release.sh's formula function does),
  and the build's own formulas have to be the same bytes, so neither
  builder's container decides what Homebrew installs. The formulas and
  the notes, the tag's CHANGELOG.md entry, are kept in kept/<v>/ with
  their SHA-256s in the state, and checked again before the tap;
- it signs, makes the draft itself, titled devvm <version> with the
  tag's notes, and uploads SHA256SUMS, both signatures and CI's files,
  each hashed as it's sent, keeping an asset only when its size and
  GitHub's digest are right and deleting any other;
- while the bridge lasts it waits for the old key's signature on the
  draft, failing each run so the maintainer hears of it, and downloading
  nothing again while it waits;
- it publishes only when the draft is exactly what it made, its tag,
  title and notes (but for line endings and the space at either end),
  and its assets by ID, size and digest, and the tag still names the tag
  object its rebuild checked; then checks the published release again,
  and finishes the tap.

Alerts and refusals:

- init records the highest release ID GitHub showed and the drafts there
  were then; IDs only go up, so any release published since that isn't a
  draft the co-signer made is an alert, whatever its tag or version, by
  <tag>#<ID>, so another release of an acked tag is alerted on again;
  each run also reads GitHub's latest release, wherever the list puts it.
- A published release that differs from what it checked, its own draft
  published without it seeing the answer that then doesn't check out,
  and a tap formula newer than any release it signed, by
  tap:<formula>@<version>, are alerts; the tap is updated only for a
  release it published and checked after.
- A rebuild that doesn't match is a refusal, which isn't downloaded or
  rebuilt again, even for CI's run again; devvm-cosign retry <tag> lets
  the next run rebuild it once more. Nothing retries on its own.
- Every run fails (exit 1) while an alert or refusal waits, until
  devvm-cosign ack or retry. A run records in last-failure.txt that it
  started, then what failed, or removes it when it succeeds; devvm-cosign failed, which the units' OnFailure=
  runs for any failure, a killed or timed-out run's or a config that
  won't load included, runs notify, the maintainer's command, with it on
  its stdin, a fixed environment and a minute of its own, whatever ended
  the run's context.

Bases go the same way, from the newest successful run of the base
workflow on main, made at the index's commit and never GitHub's latest.

Main makes the process non-dumpable (prctl PR_SET_DUMPABLE 0) before
anything else, so no process of its user can read its memory, where the
keys and token are, and reads the keys from systemd's credentials when
CREDENTIALS_DIRECTORY is set. A run empties the build folder's work/
and the state's stage/ and src/ in place, never making them again.

Tests, each fix reverted once to see it fail: TestPublishedBySomeoneElse
(a release published by someone else, whatever its tag or version, the
same tag again after an ack, a draft from before init published since,
and GitHub's latest past where the list stops; one from before the state
left alone), TestOneBuildPerRun (the build's files in the state, none of
CI's on disk during the build, and the next release left for the next
run), TestFormulas (a build's formula of
its own; a kept formula changed on disk), TestRenderFormula,
TestPrereleasePublished (a tap formula newer than any release signed),
TestDraftChangedBeforePublish (a swapped file, a retag, other notes),
TestTagMovedBeforePublish, TestAlertAfterPublish and
TestLostPublishChecked, TestMismatchSignsNothing (a failure every run,
and retry), TestReplayedOlderVersion (an alert, then acked),
TestNotify, TestLegacyBridge (a failure every run, with no download),
TestRunPagesReleases, TestInitPaged (init past ten pages of bases, which
fails with a page check that stops at its first unfinished entry),
TestRunsChecked, TestArtifactChecked, TestUploadChangedOnDisk,
TestBaseIndexChecked (a re-signed base on a 61-day snapshot),
TestBasePublishChecked, TestBasePublishedElsewhere (an expired base still
counts in checkBehind), TestWorkEmptiedInPlace, TestCommandLine (retry
and ack read no key file), and on Linux TestUndumpable.

A build that fails, rather than differs, is built again at the next
run, but the third failure in a row refuses it, with a report holding
the last failure (buildFailed), so a build that keeps failing no longer
takes every run's one build and holds up each newer release and base;
retry builds it again, and a build stopped with its run isn't counted.
Refusing rather than rotating past it keeps releases oldest first, as
versions only go up, and keeps the failure in front of the maintainer
through held and notify. buildRelease and buildBase are the build and
its comparison, apart from what's recorded. And GitHub's latest release
has to be the one init saw or one the co-signer published, not one of
its own older than another it published: anything else is an alert,
latest:<tag>#<ID> (staleLatest), as the install script's default
downloads it; so is the one init saw, once it's older than one the
co-signer published. The co-signer makes a release GitHub's latest only
when it's newer than every release it published, so publishing an older
release after a newer one, as when the old key signs the newer draft
first, never moves the latest back itself. And a release's run counts
only when a tag's push started it (PushEvent, which the structure
test's nameFree lets name "push"). Tests, each failing before its code:
TestFailingBuildRefused, TestBaseRefused's base that keeps failing,
TestLatestChecked, TestOlderReleaseNotLatest, TestRunsChecked's run by
hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 21:36:37 -07:00

322 lines
11 KiB
Go

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-<serial> 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)
}
}
}