mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
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]>
277 lines
9.9 KiB
Go
277 lines
9.9 KiB
Go
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-<serial>, 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) }
|