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

155 lines
5.2 KiB
Go

package cosign
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"io"
"net/http"
"strings"
"testing"
"testing/synctest"
"time"
)
// roundTrip is an http.RoundTripper in memory.
type roundTrip func(*http.Request) (*http.Response, error)
func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func answer(status int, body string) *http.Response {
return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}
}
// An installation token is kept until ten minutes before it expires, then
// replaced, on the bubble's clock; each JWT is issued a minute in the
// past and lasts nine minutes.
func TestAppTokenRefreshed(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
synctest.Test(t, func(t *testing.T) {
var asked []time.Time
var claims []map[string]any
a := &AppToken{
API: "https://api.example", AppID: appID, Installation: install, Key: key, Repos: []string{"devvm"},
HTTP: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
asked = append(asked, time.Now())
jwt := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
var c map[string]any
if err := json.Unmarshal(decodeSegment(t, strings.Split(jwt, ".")[1]), &c); err != nil {
t.Fatal(err)
}
claims = append(claims, c)
exp := time.Now().Add(time.Hour).UTC().Format(time.RFC3339)
return answer(http.StatusCreated, `{"token":"tok-`+time.Now().Format("150405")+`","expires_at":"`+exp+`"}`), nil
})},
}
first, err := a.Token(t.Context())
if err != nil {
t.Fatal(err)
}
time.Sleep(49 * time.Minute)
if again, err := a.Token(t.Context()); err != nil || again != first || len(asked) != 1 {
t.Errorf("at 49 minutes: %q %v, %d asked, want the first", again, err, len(asked))
}
time.Sleep(2 * time.Minute)
if next, err := a.Token(t.Context()); err != nil || next == first || len(asked) != 2 {
t.Errorf("at 51 minutes: %q %v, %d asked, want a new one", next, err, len(asked))
}
iat, exp := claims[0]["iat"].(float64), claims[0]["exp"].(float64)
if now := float64(asked[0].Unix()); iat != now-60 || exp != now+540 || claims[0]["iss"] != appID {
t.Errorf("the JWT's claims: %v at %v", claims[0], asked[0].Unix())
}
})
}
// A token GitHub refuses, doesn't give, or gives about to expire, is an
// error; so is no key.
func TestAppTokenRefused(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
soon := time.Now().Add(5 * time.Minute).UTC().Format(time.RFC3339)
for name, tc := range map[string]struct {
status int
body string
}{
"401": {http.StatusUnauthorized, `{"message":"A JSON web token could not be decoded"}`},
"no token": {http.StatusCreated, `{"expires_at":"2099-01-01T00:00:00Z"}`},
"expiring": {http.StatusCreated, `{"token":"t","expires_at":"` + soon + `"}`},
"not JSON": {http.StatusCreated, `{`},
"a bad expiry": {http.StatusCreated, `{"token":"t","expires_at":"soon"}`},
} {
a := &AppToken{
API: "https://api.example", AppID: appID, Installation: install, Key: key,
HTTP: &http.Client{Transport: roundTrip(func(*http.Request) (*http.Response, error) { return answer(tc.status, tc.body), nil })},
}
if _, err := a.Token(t.Context()); err == nil {
t.Errorf("%s: a token", name)
}
}
if _, err := (&AppToken{AppID: appID}).Token(t.Context()); err == nil {
t.Error("a token with no key")
}
}
func decodeSegment(t *testing.T, s string) []byte {
t.Helper()
b, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
t.Fatal(err)
}
return b
}
// ParseAppKey takes GitHub's PKCS #1 file and PKCS #8, and refuses other
// keys, small ones and what isn't one PEM block.
func TestParseAppKey(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
small, err := rsa.GenerateKey(rand.Reader, 1024) //nolint:gosec // a test of the refusal
if err != nil {
t.Fatal(err)
}
ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
pkcs8 := func(k any) []byte {
der, err := x509.MarshalPKCS8PrivateKey(k)
if err != nil {
t.Fatal(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})
}
pkcs1 := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
for name, tc := range map[string]struct {
data []byte
ok bool
}{
"PKCS #1": {pkcs1, true},
"PKCS #8": {pkcs8(key), true},
"1024 bits": {pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(small)}), false},
"an EC key": {pkcs8(ec), false},
"two blocks": {append(pkcs1, pkcs1...), false},
"a public key": {pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: []byte("x")}), false},
"bad PKCS #1": {pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: []byte("x")}), false},
"bad PKCS #8": {pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte("x")}), false},
"not PEM": {[]byte("key"), false},
} {
if _, err := ParseAppKey(tc.data); (err == nil) != tc.ok {
t.Errorf("%s: %v, want ok %v", name, err, tc.ok)
}
}
}