Files
w3cjandClaude Opus 5.5 da68e5d67e feat(cosign): GitHub, CI's artifacts, the app's token, the config, the state and the lock
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]>
2026-11-30 21:36:37 -07:00

206 lines
7.5 KiB
Go

package cosign
import (
"errors"
"maps"
"os"
"path/filepath"
"strings"
"testing"
)
// clone is a copy of s that shares no map with it.
func (s State) clone() State {
c := s
c.Release.Ledger, c.Base.Ledger = s.Release.clone(), s.Base.clone()
c.Release.Done, c.Release.Kept = maps.Clone(s.Release.Done), maps.Clone(s.Release.Kept)
c.Base.Checked = maps.Clone(s.Base.Checked)
c.fill()
return c
}
func (l Ledger) clone() Ledger {
return Ledger{
Signed: maps.Clone(l.Signed), Refused: maps.Clone(l.Refused), Drafts: maps.Clone(l.Drafts),
Published: maps.Clone(l.Published), Alerts: maps.Clone(l.Alerts), Runs: maps.Clone(l.Runs),
}
}
// A state saves and loads back whole, with mode 0600; a folder with none
// says so.
func TestStateSaveLoad(t *testing.T) {
st := Store{Path: filepath.Join(t.TempDir(), "state.json")}
if _, err := st.Load(); !errors.Is(err, errNoState) {
t.Fatalf("Load of none: %v", err)
}
s := newState("0.2.0", 3)
s.Release.Signed["0.2.0"] = sumA
s.Base.Checked[sumB] = 3
if err := st.Save(s); err != nil {
t.Fatal(err)
}
got, err := st.Load()
if err != nil {
t.Fatal(err)
}
if got.Release.Signed["0.2.0"] != sumA || got.Base.Checked[sumB] != 3 || got.Base.Last != 3 {
t.Errorf("Load: %+v", got)
}
fi, err := os.Stat(st.Path)
if err != nil || fi.Mode().Perm() != 0o600 {
t.Errorf("state.json's mode: %v %v", fi, err)
}
if left, _ := filepath.Glob(filepath.Join(filepath.Dir(st.Path), ".state.json.*")); len(left) != 0 {
t.Errorf("temp files left: %v", left)
}
}
// A save never goes backwards from the file on disk: an older last
// release or serial, or a dropped or changed signature, refusal, publish
// or checked file, is refused, and the file stays as it was.
func TestStateNeverBackwards(t *testing.T) {
st := Store{Path: filepath.Join(t.TempDir(), "state.json")}
was := newState("0.3.0", 5)
was.Release.Signed["0.3.0"] = sumA
was.Release.refuse(sumB, "0.2.9", 7)
was.Release.Drafts["0.3.0"] = []int64{11}
was.Release.Published["0.3.0"] = true
was.Release.Done["0.3.0"] = true
was.Release.Kept["0.3.0/devvm.rb"] = sumA
was.Release.alert("0.3.1", "x")
was.Base.Signed["5"] = sumA
was.Base.Runs["9"] = "5"
was.Base.Checked[sumA] = 5
if err := st.Save(was); err != nil {
t.Fatal(err)
}
for name, change := range map[string]func(*State){
"an older release": func(s *State) { s.Release.Last = "0.2.0"; delete(s.Release.Signed, "0.3.0") },
"an older serial": func(s *State) { s.Base.Last = 4; delete(s.Base.Signed, "5") },
"a dropped signed": func(s *State) { delete(s.Release.Signed, "0.3.0") },
"a changed signed": func(s *State) { s.Release.Signed["0.3.0"] = sumB },
"a dropped refusal": func(s *State) { delete(s.Release.Refused, sumB) },
"a refusal counted back": func(s *State) {
r := s.Release.Refused[sumB]
r.Times = 0
s.Release.Refused[sumB] = r
},
"a dropped draft": func(s *State) { s.Release.Drafts["0.3.0"] = nil },
"a changed draft": func(s *State) { s.Release.Drafts["0.3.0"] = []int64{12} },
"a dropped publish": func(s *State) { delete(s.Release.Published, "0.3.0") },
"a dropped done": func(s *State) { delete(s.Release.Done, "0.3.0") },
"a changed kept file": func(s *State) { s.Release.Kept["0.3.0/devvm.rb"] = sumB },
"a dropped alert": func(s *State) { delete(s.Release.Alerts, "0.3.1") },
"an alert counted back": func(s *State) { s.Release.Alerts["0.3.1"] = Alert{Reason: "x"} },
"a dropped run": func(s *State) { delete(s.Base.Runs, "9") },
"a dropped checked": func(s *State) { delete(s.Base.Checked, sumA) },
"a dropped base sig": func(s *State) { delete(s.Base.Signed, "5") },
"another latest": func(s *State) { s.InitLatest = 3 },
} {
s := was.clone()
change(&s)
if err := st.Save(s); err == nil {
t.Errorf("%s: saved", name)
}
}
got, err := st.Load()
if err != nil || got.Release.Last != "0.3.0" || got.Base.Last != 5 || got.Release.Signed["0.3.0"] != sumA {
t.Errorf("after the refusals: %+v %v", got, err)
}
next := was.clone()
next.Release.Last, next.Release.Signed["0.3.1"] = "0.3.1", sumB
next.Release.Drafts["0.3.0"] = append(next.Release.Drafts["0.3.0"], 12)
if !next.Release.ack("0.3.1") || next.Release.retry("0.2.9") != 1 {
t.Fatal("ack or retry cleared nothing")
}
// A count of failed builds may go back, as a refusal clears it.
next.Release.failed(sumB, "0.2.9", 7, "x")
if err := st.Save(next); err != nil {
t.Fatal(err)
}
next.Release.refuse(sumB, "0.2.9", 7)
if next.Release.Refused[sumB].Failed != 0 {
t.Error("a refusal kept its count of failed builds")
}
if err := st.Save(next); err != nil {
t.Errorf("a newer state, its alert acked and its refusal retried: %v", err)
}
}
// A state file that the co-signer couldn't have written is refused when
// it's read, and not written.
func TestStateRefused(t *testing.T) {
dir := t.TempDir()
for name, data := range map[string]string{
"another format": `{"format":2,"release":{"last":"0.2.0"},"base":{}}`,
"no last release": `{"format":1,"release":{},"base":{}}`,
"signed past its last": `{"format":1,"release":{"last":"0.2.0","signed":{"0.3.0":"x"}},"base":{}}`,
"a base past its last": `{"format":1,"release":{"last":"0.2.0"},"base":{"last":1,"signed":{"2":"x"}}}`,
"a bad serial": `{"format":1,"release":{"last":"0.2.0"},"base":{"signed":{"x":"x"}}}`,
"an unknown field": `{"format":1,"release":{"last":"0.2.0"},"base":{},"x":1}`,
"not JSON": `{`,
"over the size": strings.Repeat(" ", maxState+1),
} {
p := filepath.Join(dir, strings.ReplaceAll(name, " ", "-"))
if err := os.WriteFile(p, []byte(data), 0o600); err != nil {
t.Fatal(err)
}
if _, err := (Store{Path: p}).Load(); err == nil {
t.Errorf("%s: loaded", name)
}
if err := (Store{Path: p}).Save(newState("9.0.0", 0)); err == nil {
t.Errorf("%s: saved over it", name)
}
}
if err := (Store{Path: filepath.Join(dir, "x")}).Save(State{Format: 1}); err == nil {
t.Error("saved a state with no last release")
}
if err := (Store{Path: filepath.Join(dir, "none", "state.json")}).Save(newState("0.1.0", 0)); err == nil {
t.Error("saved into a folder that isn't there")
}
}
// A ledger's refusal holds until it's retried, for the run it came from
// and for the next one of the same manifest, and counts each mismatch; an
// alert holds until it's acked, and is raised again after; the draft is
// the last one made.
func TestLedger(t *testing.T) {
s := newState("0.2.0", 0)
l := &s.Release.Ledger
if l.draft("0.3.0") != 0 {
t.Error("a draft before any was made")
}
l.Drafts["0.3.0"] = []int64{4, 9}
if l.draft("0.3.0") != 9 {
t.Errorf("draft: %d, want the last made", l.draft("0.3.0"))
}
l.refuse(sumA, "0.3.0", 7)
if sum, ok := l.refusedRun(7); !ok || sum != sumA {
t.Errorf("refusedRun(7): %s %v", sum, ok)
}
if _, ok := l.refusedRun(8); ok {
t.Error("another run refused")
}
if l.retry("0.3.1") != 0 || l.retry("0.3.0") != 1 || l.Refused[sumA].active() {
t.Errorf("retry: %+v", l.Refused[sumA])
}
if _, ok := l.refusedRun(7); ok {
t.Error("refused after retry")
}
l.refuse(sumA, "0.3.0", 8)
if r := l.Refused[sumA]; r.Times != 2 || r.Retried != 1 || !r.active() || r.Run != 8 {
t.Errorf("refused again: %+v", r)
}
if l.ack("0.3.0") {
t.Error("an ack with no alert")
}
l.alert("0.3.0", "x")
if !l.Alerts["0.3.0"].active() || !l.ack("0.3.0") || l.Alerts["0.3.0"].active() || l.ack("0.3.0") {
t.Errorf("ack: %+v", l.Alerts["0.3.0"])
}
l.alert("0.3.0", "y")
if a := l.Alerts["0.3.0"]; !a.active() || a.Reason != "y" || a.Raised != 2 {
t.Errorf("raised again: %+v", a)
}
}