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

194 lines
7.8 KiB
Go

package cosign
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
)
// A download is capped, its hash is of the bytes written, and GitHub's
// error statuses come back as APIErrors, with the start of the body.
func TestClientDownload(t *testing.T) {
gh := newFakeGitHub(t)
r := gh.addRelease("v1.0.0", true, map[string][]byte{"big": bytes.Repeat([]byte("x"), 100)})
c := gh.client()
a := r.json().Assets[0]
var w bytes.Buffer
sum, err := c.Download(t.Context(), fakeRepo, a, 100, &w)
if err != nil || sum != sha256Hex(w.Bytes()) || w.Len() != 100 {
t.Errorf("Download: %s %v, %d bytes", sum, err, w.Len())
}
if _, err := c.Download(t.Context(), fakeRepo, a, 99, io.Discard); err == nil || !strings.Contains(err.Error(), "larger") {
t.Errorf("a download past its cap: %v", err)
}
if _, err := c.DownloadBytes(t.Context(), fakeRepo, Asset{ID: 1, Name: "gone"}, 10); !isStatus(err, http.StatusNotFound) {
t.Errorf("a missing asset: %v", err)
}
if _, err := c.Release(t.Context(), fakeRepo, 1); !isStatus(err, http.StatusNotFound) || !strings.Contains(err.Error(), "404") {
t.Errorf("a missing release: %v", err)
}
if err := c.DeleteAsset(t.Context(), fakeRepo, 1); err == nil {
t.Error("deleted a missing asset")
}
gh.fail = func(*http.Request) int { return http.StatusServiceUnavailable }
if _, err := c.Releases(t.Context(), fakeRepo, func(Release) bool { return true }); !isStatus(err, http.StatusServiceUnavailable) {
t.Errorf("Releases with GitHub down: %v", err)
}
}
// A draft is made, an upload's hash is of the bytes it sent, a published
// release is found by its tag and a draft isn't, and a workflow's runs
// and a run's artifact are listed and downloaded, the zip from the
// storage, without the token.
func TestClientReleasesAndRuns(t *testing.T) {
gh := newFakeGitHub(t)
c := gh.client()
r, err := c.CreateRelease(t.Context(), fakeRepo, "v1.0.0", testCommit, "devvm 1.0.0", "notes", true)
if err != nil || !r.Draft || r.Name != "devvm 1.0.0" || r.Body != "notes" || gh.release("v1.0.0").Target != testCommit {
t.Fatalf("CreateRelease: %+v %v", r, err)
}
a, sum, err := c.Upload(t.Context(), fakeRepo, r.ID, "x", strings.NewReader("hello"), 5)
if err != nil || sum != sha256Hex([]byte("hello")) || a.Size != 5 {
t.Errorf("Upload: %+v %s %v", a, sum, err)
}
if _, found, err := c.ReleaseByTag(t.Context(), fakeRepo, "v1.0.0"); found || err != nil {
t.Errorf("a draft found by its tag: %v", err)
}
if _, err := c.Publish(t.Context(), fakeRepo, r.ID, false, true); err != nil {
t.Fatal(err)
}
if got, found, err := c.ReleaseByTag(t.Context(), fakeRepo, "v1.0.0"); !found || err != nil || got.ID != r.ID {
t.Errorf("ReleaseByTag: %+v %v %v", got, found, err)
}
run := gh.addRun("release.yml", "v1.0.0", testCommit, "push", "release", map[string][]byte{"a": []byte("a")})
runs, err := c.Runs(t.Context(), fakeRepo, "release.yml", func(Run) bool { return true })
if err != nil || len(runs) != 1 || runs[0].ID != run.ID || runs[0].HeadSHA != testCommit || runs[0].HeadBranch != "v1.0.0" {
t.Errorf("Runs: %+v %v", runs, err)
}
arts, err := c.Artifacts(t.Context(), fakeRepo, run.ID, "release")
if err != nil || len(arts) != 1 {
t.Fatalf("Artifacts: %+v %v", arts, err)
}
var zip bytes.Buffer
sum, err = c.DownloadArtifact(t.Context(), fakeRepo, arts[0], 1<<20, &zip)
if err != nil || "sha256:"+sum != arts[0].Digest || gh.leaked != 0 {
t.Errorf("DownloadArtifact: %s %v, %d leaked", sum, err, gh.leaked)
}
if none, err := c.Artifacts(t.Context(), fakeRepo, run.ID, "base"); err != nil || len(none) != 0 {
t.Errorf("another artifact's name: %+v %v", none, err)
}
// An asset uploaded again is another asset, by its ID.
was := a
gh.put(gh.release("v1.0.0"), "x", []byte("other"))
now, err := c.Release(t.Context(), fakeRepo, r.ID)
if a, ok := now.asset("x"); err != nil || !ok || a.ID == was.ID || a.Size != 5 {
t.Errorf("the asset uploaded again: %+v %v", a, err)
}
if _, ok := now.asset("y"); ok {
t.Error("an asset that isn't there")
}
}
// An artifact is downloaded into the stage, checked against GitHub's
// digest and unzipped there; an expired one, one over the cap and one
// whose digest doesn't match are refused.
func TestFetchArtifact(t *testing.T) {
gh := newFakeGitHub(t)
c := gh.client()
run := gh.addRun("release.yml", "v1.0.0", testCommit, "push", "release", map[string][]byte{"SHA256SUMS": []byte("sums\n")})
a := run.artifacts[0].Artifact
files, err := c.fetchArtifact(t.Context(), fakeRepo, a, t.TempDir())
if err != nil || files["SHA256SUMS"].sum != sha256Hex([]byte("sums\n")) {
t.Errorf("fetchArtifact: %+v %v", files, err)
}
for name, change := range map[string]func(*Artifact){
"expired": func(a *Artifact) { a.Expired = true },
"over the cap": func(a *Artifact) { a.Size = maxArtifact + 1 },
"another digest": func(a *Artifact) { a.Digest = "sha256:" + sumA },
} {
bad := a
change(&bad)
if _, err := c.fetchArtifact(t.Context(), fakeRepo, bad, t.TempDir()); err == nil {
t.Errorf("%s: fetched", name)
}
}
}
// The co-signer's client follows redirects over HTTPS alone, and sends
// its token to no other host than the one it called.
func TestClientRedirects(t *testing.T) {
plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://example.invalid/x", http.StatusFound)
}))
defer plain.Close()
c := Client{API: plain.URL, HTTP: NewHTTP(false), Tokens: staticToken("tok")}
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, plain.URL, nil)
if err != nil {
t.Fatal(err)
}
if _, err := c.HTTP.Do(req); err == nil || !strings.Contains(err.Error(), "not https") { //nolint:bodyclose // it fails
t.Errorf("a redirect to http: %v", err)
}
loop := httptest.NewServer(nil)
loop.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, loop.URL, http.StatusFound) })
defer loop.Close()
if err := (Client{API: loop.URL, HTTP: NewHTTP(true), Tokens: staticToken("t")}).do(t.Context(), http.MethodGet, loop.URL, nil, "", 200, nil); err == nil {
t.Error("a redirect loop")
}
big := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(bytes.Repeat([]byte(" "), maxJSON+1))
}))
defer big.Close()
if err := (Client{HTTP: NewHTTP(true), Tokens: staticToken("t")}).do(t.Context(), http.MethodGet, big.URL, nil, "", 200, nil); err == nil {
t.Error("an answer past its cap")
}
}
type staticToken string
func (s staticToken) Token(context.Context) (string, error) { return string(s), nil }
// The state folder's lock lets one run in at a time.
func TestLock(t *testing.T) {
dir := t.TempDir()
unlock, err := Lock(dir)
if err != nil {
t.Fatal(err)
}
if _, err := Lock(dir); err == nil || !strings.Contains(err.Error(), "another devvm-cosign run") {
t.Errorf("a second lock: %v", err)
}
unlock()
again, err := Lock(dir)
if err != nil {
t.Fatalf("the lock once let go: %v", err)
}
again()
if _, err := Lock(filepath.Join(dir, "none")); err == nil {
t.Error("a lock in no folder")
}
}
// The release list is read only until a page of releases the co-signer
// is done with, so years of releases never stop it, but ten pages it
// isn't done with are an error, never a list cut short.
func TestReleasesPaged(t *testing.T) {
gh := newFakeGitHub(t)
for range (maxPages + 1) * perPage {
gh.addRelease("v0.1.0", false, nil)
}
gh.addRelease("v0.3.0", true, nil)
rs, err := gh.client().Releases(t.Context(), fakeRepo, func(r Release) bool { return !r.Draft })
if err != nil || len(rs) != 2*perPage || rs[0].TagName != "v0.3.0" {
t.Errorf("Releases: %d, %v", len(rs), err)
}
if _, err := gh.client().Releases(t.Context(), fakeRepo, func(Release) bool { return false }); err == nil {
t.Error("a list cut short")
}
}