mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 16:27:33 -10:00
What devvm-cosign reads and writes, below its run: - github.go, actions.go: every GitHub call goes through Client: releases listed, read one, by its tag, a draft made, an upload streamed from a file with the SHA-256 of the bytes it sent, a delete, a publish, the tap's contents; and the Actions API's runs of a workflow file, a run's artifacts by name and an artifact's zip, which redirects to storage that never gets the token. CI's token can only read the repo, so CI hands its build over this way, and only the co-signer makes and publishes releases. - Lists are read a page at a time until a page holds only entries the caller is done with, newest first as GitHub lists them, so years of releases and bases never stop a run; ten pages it isn't done with are an error, never a list cut short. Every entry of a page is asked about (every), never stopping at the first that isn't done, so a caller that counts what it's asked, as init does, sees the whole page. - TagRef: what a tag names now, so a release is published only while its tag names the tag object the rebuild checked; Latest: GitHub's latest release, which /releases/latest/download/ serves. - artifact.go: an artifact downloaded into the co-signer's stage folder, capped, checked against GitHub's digest, and unzipped with nothing but a flat list of regular files, each named as a manifest names a file, stored or deflated, written new (O_EXCL), each no larger than its header says, within the artifact's bounds, and hashed as written. - app.go: the GitHub App's installation token (RS256 JWT), now asking for actions: read beside contents: write, on the two repos alone. - config.go: release_workflow and [base]'s workflow and max_snapshot_days; notify, the maintainer's command for a failed run; build_dir, the folder the builds' containers write, apart from state_dir, which they can't reach, neither in the other; ReadConfig, without the keys, for retry and ack; and the key files read from systemd's credentials folder ($CREDENTIALS_DIRECTORY) by their own names, where systemd's system manager makes them root's, mode 0440, with an ACL for the service's user, so there only others' bits are refused. A kind with no keys at all, as before the release keys are made, is refused by name, pointing at github-setup.md's step 1, so the co-signer doesn't start without them. - state.go: a ledger for each kind: what it signed, the drafts it made, what it published, each refusal with how often it was retried, each alert with how often it was acked, and the CI runs it signed; releases also record the SHA-256 of each file kept for the tap and each tag object checked. The state's watermark, the highest release ID GitHub showed at init, and the drafts there were then, and the alerts on what isn't one of its own: a release someone else published since, by <tag>#<ID>, and a tap formula it didn't write. A save is refused when it drops or changes an entry or counts one back, and writeWhole now syncs the folder after the rename, so a crash can't lose the record of a version made before its signature is uploaded. - lock_unix.go: one run at a time, unchanged. - forbidigo's exclusions now name their files: the web for github.go and app.go, Flock for lock_unix.go, so a second client or lock elsewhere in the package still fails the lint. Tests: the fake GitHub serves workflow runs and artifacts and makes drafts; TestUnzip (a folder, a path, a parent, a dot file, a link, a file twice, too many, a size that lies, not a zip, a file already there), TestFetchArtifact, TestClientReleasesAndRuns, TestReleasesPaged (1,100 settled releases read in two pages), TestLedger, TestStateNeverBackwards (drafts, publishes, kept files, alerts and refusals counted back), TestConfigCredentials, TestConfigRefused (the build folder in the state folder or the reverse). Reverted once each to see the test fail: the paging's stop (TestReleasesPaged), the credentials folder (TestConfigCredentials), the lint's scope (an http.Client in another file fails forbidigo). The folder's fsync was checked with strace on Fedora: openat of the folder and fsync right after the rename. The state also counts each manifest's failed builds in a row (Refusal.Failed, Ledger.failed): the third, maxBuildFailures, refuses it as a mismatch does, with its cause (Why), and the count alone may go back, as a lower one only builds more. And it records GitHub's latest release at init (InitLatest), which a save may never change. TestStateNeverBackwards covers both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
459 lines
15 KiB
Go
459 lines
15 KiB
Go
package cosign
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
)
|
|
|
|
// stateFormat is state.json's format; a file of another is refused.
|
|
const stateFormat = 1
|
|
|
|
// errNoState is a state folder with no state.json yet: devvm-cosign init
|
|
// writes the first.
|
|
var errNoState = errors.New("no state.json: run devvm-cosign init first")
|
|
|
|
// State is what the co-signer has signed, so it never signs an older
|
|
// release or base than one it signed, nor two different manifests for
|
|
// one version or serial, and what it made, published, refused and
|
|
// alerted on. It's written whole, and never with less than the file on
|
|
// disk holds (Store.Save).
|
|
type State struct {
|
|
Format int `json:"format"`
|
|
Release ReleaseState `json:"release"`
|
|
Base BaseState `json:"base"`
|
|
// Watermark is the highest release ID GitHub showed when the state was
|
|
// made (init): GitHub's IDs only go up, so every release published
|
|
// since, whatever its tag, has a higher one, and one that isn't a draft
|
|
// the co-signer made is an alert.
|
|
Watermark int64 `json:"watermark"`
|
|
// InitDrafts are the drafts GitHub showed then, which init didn't
|
|
// make: one published later is an alert too, though its ID isn't
|
|
// above the watermark.
|
|
InitDrafts []int64 `json:"init_drafts"`
|
|
// InitLatest is GitHub's latest release when the state was made, 0 for
|
|
// none: the latest is that one or one the co-signer published, and an
|
|
// older release made the latest since is an alert, as it's what the
|
|
// install script's default downloads.
|
|
InitLatest int64 `json:"init_latest"`
|
|
// Others are the alerts on what isn't one release or base of the
|
|
// co-signer's: a release someone else published, by <tag>#<ID>, and a
|
|
// tap formula it didn't write, by tap:<file>@<version>; each key is
|
|
// what devvm-cosign ack takes.
|
|
Others map[string]Alert `json:"others"`
|
|
}
|
|
|
|
// A Ledger is what the co-signer did with one kind's manifests, each
|
|
// version's or serial's by its key: the version for a release, the serial
|
|
// for a base.
|
|
type Ledger struct {
|
|
// Signed is the SHA-256 of the manifest it signed, by key.
|
|
Signed map[string]string `json:"signed"`
|
|
// Refused is each manifest whose rebuild didn't match, by its SHA-256.
|
|
Refused map[string]Refusal `json:"refused"`
|
|
// Drafts are the draft releases it made for each key, by GitHub's ID,
|
|
// the last the one it uses: one deleted by hand is made again.
|
|
Drafts map[string][]int64 `json:"drafts"`
|
|
// Published is each key it published, its files checked after.
|
|
Published map[string]bool `json:"published"`
|
|
// Alerts are what it found wrong with a key that a maintainer must
|
|
// look at, such as a release published by someone else.
|
|
Alerts map[string]Alert `json:"alerts"`
|
|
// Runs is the key of each CI run whose manifest it signed, by the
|
|
// run's ID, so a run it's done with isn't downloaded again.
|
|
Runs map[string]string `json:"runs"`
|
|
}
|
|
|
|
// A Refusal is a manifest whose rebuild didn't match, or failed
|
|
// maxBuildFailures times in a row: never rebuilt again on its own, but
|
|
// once for each devvm-cosign retry.
|
|
type Refusal struct {
|
|
// Key is its version or serial, and Run the CI run it came from last.
|
|
Key string `json:"key"`
|
|
Run int64 `json:"run"`
|
|
// Times is how many times it was refused, and Retried how many of
|
|
// those a maintainer cleared with devvm-cosign retry.
|
|
Times int `json:"times"`
|
|
Retried int `json:"retried"`
|
|
// Failed is how many of its builds in a row failed, rather than
|
|
// differed, since it was last refused: the count that refuses it, which
|
|
// alone may go back, as a lower count only builds it more. Why is the
|
|
// last refusal's cause when a failed build refused it, "" when a
|
|
// mismatch did.
|
|
Failed int `json:"failed,omitempty"`
|
|
Why string `json:"why,omitempty"`
|
|
}
|
|
|
|
// active is whether r still refuses its manifest.
|
|
func (r Refusal) active() bool { return r.Times > r.Retried }
|
|
|
|
// maxBuildFailures is how many builds of one manifest in a row may fail
|
|
// before it's refused: a failure is often the machine's, a download cut
|
|
// short or a full disk, so it's built again at the next run, but one that
|
|
// keeps failing would take every run's one build, and hold up each newer
|
|
// release and base.
|
|
const maxBuildFailures = 3
|
|
|
|
// An Alert is a key the co-signer stops at until a maintainer has looked:
|
|
// devvm-cosign ack clears the alerts raised so far, and a new one raises
|
|
// it again.
|
|
type Alert struct {
|
|
Reason string `json:"reason"`
|
|
Raised int `json:"raised"`
|
|
Acked int `json:"acked"`
|
|
}
|
|
|
|
// active is whether a is still waiting for a maintainer.
|
|
func (a Alert) active() bool { return a.Raised > a.Acked }
|
|
|
|
// ReleaseState is the releases the co-signer signed.
|
|
type ReleaseState struct {
|
|
// Last is the newest version it signed, or the newest published one
|
|
// when the state was made (init); it signs only newer ones.
|
|
Last string `json:"last"`
|
|
Ledger
|
|
// Done is the versions whose tap it updated, after publishing them.
|
|
Done map[string]bool `json:"done"`
|
|
// Kept is the SHA-256 of each file it kept for a release it signed,
|
|
// its formulas and notes, by <version>/<name>, so one changed on disk
|
|
// between runs is refused.
|
|
Kept map[string]string `json:"kept"`
|
|
// Tags is the tag object each signed version's rebuild checked, which
|
|
// the tag must still name when its release is published.
|
|
Tags map[string]string `json:"tags"`
|
|
}
|
|
|
|
// BaseState is the bases the co-signer signed.
|
|
type BaseState struct {
|
|
// Last is the highest serial it signed, or the one init found.
|
|
Last uint64 `json:"last"`
|
|
Ledger
|
|
// Checked is the SHA-256 of every base file a rebuild of the
|
|
// co-signer's own matched, with the serial it was first in, so an
|
|
// unchanged base is re-signed with a new serial and expiry without
|
|
// another rebuild.
|
|
Checked map[string]uint64 `json:"checked"`
|
|
// Shape is the SHA-256 of the last index it signed with its serial and
|
|
// expiry left out (BaseIndex.shape): only an index of that shape, the
|
|
// same files, commit, snapshot and format, is re-signed without a
|
|
// rebuild, so an older base's files can't come back with a new serial.
|
|
Shape string `json:"shape"`
|
|
}
|
|
|
|
// newState is an empty state, from last, the newest release published,
|
|
// and serial, the highest base's.
|
|
func newState(last string, serial uint64) State {
|
|
s := State{Format: stateFormat, Release: ReleaseState{Last: last}, Base: BaseState{Last: serial}}
|
|
s.fill()
|
|
return s
|
|
}
|
|
|
|
// fill gives s's maps a value, so a state read from a file with none can
|
|
// be added to.
|
|
func (s *State) fill() {
|
|
s.Release.fill()
|
|
s.Base.fill()
|
|
if s.Release.Kept == nil {
|
|
s.Release.Kept = map[string]string{}
|
|
}
|
|
if s.Release.Tags == nil {
|
|
s.Release.Tags = map[string]string{}
|
|
}
|
|
if s.Release.Done == nil {
|
|
s.Release.Done = map[string]bool{}
|
|
}
|
|
if s.Base.Checked == nil {
|
|
s.Base.Checked = map[string]uint64{}
|
|
}
|
|
if s.Others == nil {
|
|
s.Others = map[string]Alert{}
|
|
}
|
|
}
|
|
|
|
func (l *Ledger) fill() {
|
|
if l.Signed == nil {
|
|
l.Signed = map[string]string{}
|
|
}
|
|
if l.Refused == nil {
|
|
l.Refused = map[string]Refusal{}
|
|
}
|
|
if l.Drafts == nil {
|
|
l.Drafts = map[string][]int64{}
|
|
}
|
|
if l.Published == nil {
|
|
l.Published = map[string]bool{}
|
|
}
|
|
if l.Alerts == nil {
|
|
l.Alerts = map[string]Alert{}
|
|
}
|
|
if l.Runs == nil {
|
|
l.Runs = map[string]string{}
|
|
}
|
|
}
|
|
|
|
// draft is the draft release the co-signer made for key, 0 for none.
|
|
func (l *Ledger) draft(key string) int64 {
|
|
if ids := l.Drafts[key]; len(ids) > 0 {
|
|
return ids[len(ids)-1]
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// refuse records manifest sum, key's from CI's run, as refused once more,
|
|
// as its rebuild didn't match.
|
|
func (l *Ledger) refuse(sum, key string, run int64) {
|
|
r := l.Refused[sum]
|
|
r.Key, r.Run, r.Times, r.Failed, r.Why = key, run, r.Times+1, 0, ""
|
|
l.Refused[sum] = r
|
|
}
|
|
|
|
// failed records that a build of manifest sum, key's from CI's run,
|
|
// failed with why, and refuses it at the maxBuildFailures'th in a row; it
|
|
// says whether it refused it.
|
|
func (l *Ledger) failed(sum, key string, run int64, why string) bool {
|
|
r := l.Refused[sum]
|
|
r.Key, r.Run, r.Failed = key, run, r.Failed+1
|
|
refused := r.Failed >= maxBuildFailures
|
|
if refused {
|
|
r.Times, r.Failed, r.Why = r.Times+1, 0, why
|
|
}
|
|
l.Refused[sum] = r
|
|
return refused
|
|
}
|
|
|
|
// refusedRun is whether a refusal still holds for CI's run, so its
|
|
// artifact needn't be downloaded again to be refused.
|
|
func (l *Ledger) refusedRun(run int64) (string, bool) {
|
|
for sum, r := range l.Refused {
|
|
if r.Run == run && r.active() {
|
|
return sum, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// retry clears key's refusals, and says how many it cleared.
|
|
func (l *Ledger) retry(key string) int {
|
|
n := 0
|
|
for sum, r := range l.Refused {
|
|
if r.Key == key && r.active() {
|
|
r.Retried = r.Times
|
|
l.Refused[sum] = r
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// alert raises key's alert, for reason.
|
|
func (l *Ledger) alert(key, reason string) {
|
|
a := l.Alerts[key]
|
|
a.Reason, a.Raised = reason, a.Raised+1
|
|
l.Alerts[key] = a
|
|
}
|
|
|
|
// ack clears key's alert, and says whether there was one to clear.
|
|
func (l *Ledger) ack(key string) bool {
|
|
a, ok := l.Alerts[key]
|
|
if !ok || !a.active() {
|
|
return false
|
|
}
|
|
a.Acked = a.Raised
|
|
l.Alerts[key] = a
|
|
return true
|
|
}
|
|
|
|
// check is whether s is a state the co-signer could have written: its
|
|
// format, a version for Last, and nothing signed past Last.
|
|
func (s State) check() error {
|
|
if s.Format != stateFormat {
|
|
return fmt.Errorf("state.json's format is %d, not %d", s.Format, stateFormat)
|
|
}
|
|
last, err := parseVersion(s.Release.Last)
|
|
if err != nil {
|
|
return fmt.Errorf("state.json's last release: %w", err)
|
|
}
|
|
for v := range s.Release.Signed {
|
|
sv, err := parseVersion(v)
|
|
if err != nil || sv.compare(last) > 0 {
|
|
return fmt.Errorf("state.json signed %q, past its last release %s", v, s.Release.Last)
|
|
}
|
|
}
|
|
for serial := range s.Base.Signed {
|
|
n, err := strconv.ParseUint(serial, 10, 64)
|
|
if err != nil || n > s.Base.Last {
|
|
return fmt.Errorf("state.json signed base %q, past its last serial %d", serial, s.Base.Last)
|
|
}
|
|
}
|
|
for _, l := range []Ledger{s.Release.Ledger, s.Base.Ledger} {
|
|
for key := range l.Published {
|
|
if l.Signed[key] == "" {
|
|
return fmt.Errorf("state.json published %q, which it didn't sign", key)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// behind is why s holds less than was, the state on disk, which a save
|
|
// must never do: an older last release or serial, or a signature, a
|
|
// draft, a publish, a tap, a kept file or a checked file it dropped or
|
|
// changed, or a refusal or alert counted back.
|
|
func (s State) behind(was State) error {
|
|
last, err := parseVersion(s.Release.Last)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
wasLast, err := parseVersion(was.Release.Last)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
switch {
|
|
case last.compare(wasLast) < 0:
|
|
return fmt.Errorf("its last release %s is older than %s", s.Release.Last, was.Release.Last)
|
|
case s.Base.Last < was.Base.Last:
|
|
return fmt.Errorf("its last base %d is older than %d", s.Base.Last, was.Base.Last)
|
|
case s.Watermark != was.Watermark || !slices.Equal(s.InitDrafts, was.InitDrafts) || s.InitLatest != was.InitLatest:
|
|
return fmt.Errorf("its watermark %d, drafts or latest release at init aren't the %d and the ones init recorded", s.Watermark, was.Watermark)
|
|
case !kept(was.Others, s.Others, func(w, n Alert) bool { return n.Raised >= w.Raised && n.Acked >= w.Acked }):
|
|
return errors.New("it drops or counts back an alert on a release or a tap formula it didn't make")
|
|
case !s.Release.keeps(was.Release.Ledger) || !s.Base.keeps(was.Base.Ledger) ||
|
|
!kept(was.Release.Done, s.Release.Done, same) || !kept(was.Release.Kept, s.Release.Kept, same) || !kept(was.Release.Tags, s.Release.Tags, same) ||
|
|
!kept(was.Base.Checked, s.Base.Checked, same):
|
|
return errors.New("it drops or changes what the file on disk records")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// keeps is whether l holds everything was does: each draft list as a
|
|
// prefix, and each refusal and alert counted no lower.
|
|
func (l Ledger) keeps(was Ledger) bool {
|
|
return kept(was.Signed, l.Signed, same) && kept(was.Published, l.Published, same) && kept(was.Runs, l.Runs, same) &&
|
|
kept(was.Drafts, l.Drafts, func(w, n []int64) bool { return len(n) >= len(w) && slices.Equal(n[:len(w)], w) }) &&
|
|
kept(was.Refused, l.Refused, func(w, n Refusal) bool { return n.Key == w.Key && n.Times >= w.Times && n.Retried >= w.Retried }) &&
|
|
kept(was.Alerts, l.Alerts, func(w, n Alert) bool { return n.Raised >= w.Raised && n.Acked >= w.Acked })
|
|
}
|
|
|
|
func same[V comparable](was, now V) bool { return was == now }
|
|
|
|
// kept is whether now holds every entry of was, each one ok with its
|
|
// value there.
|
|
func kept[V any](was, now map[string]V, ok func(was, now V) bool) bool {
|
|
for k, v := range was {
|
|
if w, found := now[k]; !found || !ok(v, w) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// A Store is state.json, in the co-signer's state folder.
|
|
type Store struct {
|
|
Path string
|
|
}
|
|
|
|
// maxState bounds state.json: years of releases and bases are far under.
|
|
const maxState = 16 << 20
|
|
|
|
// Load reads the state, checked; errNoState when there's none.
|
|
func (st Store) Load() (State, error) {
|
|
f, err := os.Open(st.Path)
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return State{}, errNoState
|
|
} else if err != nil {
|
|
return State{}, err
|
|
}
|
|
defer f.Close()
|
|
data, err := io.ReadAll(io.LimitReader(f, maxState+1))
|
|
if err != nil {
|
|
return State{}, fmt.Errorf("reading %s: %w", st.Path, err)
|
|
}
|
|
if len(data) > maxState {
|
|
return State{}, fmt.Errorf("%s is over %d bytes", st.Path, maxState)
|
|
}
|
|
dec := json.NewDecoder(bytes.NewReader(data))
|
|
dec.DisallowUnknownFields()
|
|
var s State
|
|
if err := dec.Decode(&s); err != nil {
|
|
return State{}, fmt.Errorf("reading %s: %w", st.Path, err)
|
|
}
|
|
s.fill()
|
|
if err := s.check(); err != nil {
|
|
return State{}, fmt.Errorf("%s: %w", st.Path, err)
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
// Save writes s whole, replacing the file at once (a temp file, synced,
|
|
// then renamed, and the folder synced), so a crash leaves the old state
|
|
// or the new one. It refuses a state that's behind the file on disk, as a
|
|
// replayed or restored older state would be, and one that doesn't check
|
|
// out.
|
|
func (st Store) Save(s State) error {
|
|
if err := s.check(); err != nil {
|
|
return err
|
|
}
|
|
was, err := st.Load()
|
|
switch {
|
|
case errors.Is(err, errNoState):
|
|
case err != nil:
|
|
return err
|
|
default:
|
|
if err := s.behind(was); err != nil {
|
|
return fmt.Errorf("refusing to write %s, as it would go backwards: %w", st.Path, err)
|
|
}
|
|
}
|
|
data, _ := json.MarshalIndent(s, "", " ")
|
|
return writeWhole(st.Path, append(data, '\n'), 0o600)
|
|
}
|
|
|
|
// writeWhole writes data to path through a temp file beside it, synced,
|
|
// then renamed over path, with mode, and syncs the folder, so a reader
|
|
// sees the old file or the new one, never part of either, and a crash
|
|
// after it returns can't lose the rename: state.json records a version
|
|
// before its signature is uploaded.
|
|
func writeWhole(path string, data []byte, mode os.FileMode) error {
|
|
f, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// The first error is the one returned: the temp file is closed and
|
|
// removed after any.
|
|
if err = f.Chmod(mode); err == nil {
|
|
if _, err = f.Write(data); err == nil {
|
|
err = f.Sync()
|
|
}
|
|
}
|
|
if cerr := f.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
if err != nil {
|
|
_ = os.Remove(f.Name())
|
|
return err
|
|
}
|
|
if err := os.Rename(f.Name(), path); err != nil {
|
|
return err
|
|
}
|
|
return syncDir(filepath.Dir(path))
|
|
}
|
|
|
|
// syncDir syncs the folder dir, so a rename in it is on disk.
|
|
func syncDir(dir string) error {
|
|
d, err := os.Open(dir) //nolint:gosec // the folder of a file the co-signer just wrote
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer d.Close()
|
|
if err := d.Sync(); err != nil {
|
|
return fmt.Errorf("syncing %s: %w", dir, err)
|
|
}
|
|
return nil
|
|
}
|