mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
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]>
This commit is contained in:
20 files changed
+3905
-14
No files matched your search
+8
-4
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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-<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) }
|
||||
@@ -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-<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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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-<serial>.
|
||||
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<version>, or a base's
|
||||
// serial, base-<serial>, 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-<serial>, 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<version>, or a base's, base-<serial>", 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) }
|
||||
File diff suppressed because it is too large.
Load diff
+29
-10
@@ -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
|
||||
@@ -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/<pid>/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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 "## <v>" 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
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 <version>) 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)
|
||||
}
|
||||
@@ -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"}},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+1
@@ -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
|
||||
|
||||
Vendored
+1
@@ -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
|
||||
|
||||
Reference in new issue
Block a user