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

461 lines
16 KiB
Go

package cosign
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// GitHub's REST API, as the co-signer uses it: every call it makes goes
// through Client.
const (
apiVersion = "2022-11-28"
userAgent = "devvm-cosign"
maxJSON = 8 << 20
maxPages = 10
perPage = 100
callTimeout = 10 * time.Minute
)
// A TokenSource gives the token each call is made with: a GitHub App's
// installation token (AppToken).
type TokenSource interface {
Token(ctx context.Context) (string, error)
}
// A Client calls GitHub's REST API with a token, and nothing else.
type Client struct {
// API is the API's root, https://api.github.com, and Uploads the
// uploads' root, https://uploads.github.com; the tests' fake
// serves both.
API, Uploads string
// HTTP makes the requests; NewHTTP's, by default.
HTTP *http.Client
// Tokens gives each call its token.
Tokens TokenSource
}
// NewHTTP is the co-signer's HTTP client: each request bounded in time,
// redirects followed only over HTTPS (and HTTP to a test's server, when
// insecure), and the token never sent to a redirect's other host, such
// as the storage an asset's download goes to.
func NewHTTP(insecure bool) *http.Client {
return &http.Client{
Timeout: callTimeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 5 {
return errors.New("more than 5 redirects")
}
if req.URL.Scheme != "https" && (!insecure || req.URL.Scheme != "http") {
return fmt.Errorf("a redirect to %s, not https", req.URL.Scheme)
}
if req.URL.Host != via[0].URL.Host {
req.Header.Del("Authorization")
}
return nil
},
}
}
// An APIError is a call GitHub answered with a status it wasn't asked
// for.
type APIError struct {
Method, Path string
Status int
Body string
}
func (e *APIError) Error() string {
return fmt.Sprintf("GitHub's %s %s: %d %s", e.Method, e.Path, e.Status, e.Body)
}
// isStatus is whether err is GitHub answering with status.
func isStatus(err error, status int) bool {
var e *APIError
return errors.As(err, &e) && e.Status == status
}
// A Release is a GitHub release, as the co-signer reads one.
type Release struct {
ID int64 `json:"id"`
TagName string `json:"tag_name"`
// Name and Body are its title and notes, which the co-signer writes.
Name string `json:"name"`
Body string `json:"body"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
Assets []Asset `json:"assets"`
}
// uploaded is an asset's state once its upload finished.
const uploaded = "uploaded"
// An Asset is one of a release's files.
type Asset struct {
ID int64 `json:"id"`
Name string `json:"name"`
// State is uploaded once its upload finished; an upload that failed
// can leave one in another state, such as starter, which is deleted.
State string `json:"state"`
Size int64 `json:"size"`
// Digest is GitHub's sha256:<hex> of it, when it has one.
Digest string `json:"digest"`
}
// asset is r's asset named name.
func (r Release) asset(name string) (Asset, bool) {
for _, a := range r.Assets {
if a.Name == name {
return a, true
}
}
return Asset{}, false
}
// do makes one call: method on url, with body (JSON when it isn't nil
// bytes) and contentType, and reads its answer into out (JSON) when out
// isn't nil, at most maxJSON bytes. A status other than want is an
// APIError.
func (c Client) do(ctx context.Context, method, u string, body []byte, contentType string, want int, out any) error {
if body == nil {
return c.send(ctx, method, u, nil, 0, contentType, want, out)
}
return c.send(ctx, method, u, bytes.NewReader(body), int64(len(body)), contentType, want, out)
}
// send is do with a body of size bytes read from body, nil for none.
func (c Client) send(ctx context.Context, method, u string, body io.Reader, size int64, contentType string, want int, out any) error {
req, err := c.request(ctx, method, u, nil, contentType)
if err != nil {
return err
}
switch {
case body != nil && size == 0:
req.Body = http.NoBody
case body != nil:
req.Body, req.ContentLength = io.NopCloser(body), size
}
resp, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, maxJSON+1))
if err != nil {
return fmt.Errorf("reading GitHub's answer to %s %s: %w", method, req.URL.Path, err)
}
if resp.StatusCode != want {
return &APIError{Method: method, Path: req.URL.Path, Status: resp.StatusCode, Body: snippet(data)}
}
if len(data) > maxJSON {
return fmt.Errorf("GitHub's answer to %s %s is over %d bytes", method, req.URL.Path, maxJSON)
}
if out == nil {
return nil
}
if err := json.Unmarshal(data, out); err != nil {
return fmt.Errorf("reading GitHub's answer to %s %s: %w", method, req.URL.Path, err)
}
return nil
}
// request is a call's request, with GitHub's headers and the token.
func (c Client) request(ctx context.Context, method, u string, body io.Reader, contentType string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, method, u, body)
if err != nil {
return nil, err
}
tok, err := c.Tokens.Token(ctx)
if err != nil {
return nil, fmt.Errorf("getting a token for GitHub: %w", err)
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-Github-Api-Version", apiVersion)
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Authorization", "Bearer "+tok)
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
return req, nil
}
// snippet is the start of an error's body, on one line, for its message.
func snippet(data []byte) string {
s := strings.Join(strings.Fields(string(data)), " ")
if len(s) > 200 {
s = s[:200] + "…"
}
return s
}
// repoURL is the API's URL for repo's path, each of path's segments
// escaped.
func (c Client) repoURL(repo string, path ...string) string {
u := strings.TrimSuffix(c.API, "/") + "/repos/" + repo
for _, p := range path {
u += "/" + url.PathEscape(p)
}
return u
}
// pages reads the list at u (a URL with no query of its own, or one that
// ends with &), a page of perPage at a time, newest first as GitHub lists
// them, each page through page, which returns how many entries it read.
// It stops when the list ends, or once done says a page settles the rest:
// GitHub lists the newest first, so what follows a page whose entries are
// all ones the co-signer has finished with is older still. maxPages pages
// that don't settle it are an error, never a list cut short, so a list
// as long as GitHub's grows never stops it, and only one gone wrong does.
func (c Client) pages(ctx context.Context, u string, page func(data []byte) (int, error), done func() bool) error {
sep := "?"
if strings.Contains(u, "?") {
sep = "&"
}
for n := 1; ; n++ {
var raw json.RawMessage
if err := c.do(ctx, http.MethodGet, u+sep+"per_page="+strconv.Itoa(perPage)+"&page="+strconv.Itoa(n), nil, "", http.StatusOK, &raw); err != nil {
return err
}
got, err := page(raw)
if err != nil {
return err
}
if got < perPage || done() {
return nil
}
if n >= maxPages {
return fmt.Errorf("%s: %d pages of entries the co-signer hasn't finished with, more than it reads", u, maxPages)
}
}
}
// Releases lists repo's releases, drafts included (the token's
// installation can push), newest first, until the list ends or a page
// whose every release settled says is done with: see pages.
func (c Client) Releases(ctx context.Context, repo string, settled func(Release) bool) ([]Release, error) {
var all []Release
last := 0
err := c.pages(ctx, c.repoURL(repo, "releases"), func(data []byte) (int, error) {
var rs []Release
if err := json.Unmarshal(data, &rs); err != nil {
return 0, fmt.Errorf("reading %s's releases: %w", repo, err)
}
last = len(all)
all = append(all, rs...)
return len(rs), nil
}, func() bool { return every(all[last:], settled) })
return all, err
}
// every is whether ok holds for each of xs, asking it of every one, never
// stopping at the first that doesn't, so a caller that counts what it's
// asked about sees the whole page.
func every[T any](xs []T, ok func(T) bool) bool {
all := true
for _, x := range xs {
all = ok(x) && all
}
return all
}
// CreateRelease makes a draft release of repo for tag, at target when the
// tag isn't there yet ("" for one that is), named name, with body.
func (c Client) CreateRelease(ctx context.Context, repo, tag, target, name, body string, prerelease bool) (Release, error) {
req := map[string]any{"tag_name": tag, "name": name, "body": body, "draft": true, "prerelease": prerelease}
if target != "" {
req["target_commitish"] = target
}
data, err := json.Marshal(req)
if err != nil {
return Release{}, err
}
var r Release
err = c.do(ctx, http.MethodPost, c.repoURL(repo, "releases"), data, "application/json", http.StatusCreated, &r)
return r, err
}
// Release reads repo's release id again, as it is now.
func (c Client) Release(ctx context.Context, repo string, id int64) (Release, error) {
var r Release
err := c.do(ctx, http.MethodGet, c.repoURL(repo, "releases", strconv.FormatInt(id, 10)), nil, "", http.StatusOK, &r)
return r, err
}
// ReleaseByTag reads repo's published release of tag, found false when
// it has none.
func (c Client) ReleaseByTag(ctx context.Context, repo, tag string) (Release, bool, error) {
var r Release
err := c.do(ctx, http.MethodGet, c.repoURL(repo, "releases", "tags", tag), nil, "", http.StatusOK, &r)
if isStatus(err, http.StatusNotFound) {
return Release{}, false, nil
}
return r, err == nil, err
}
// Latest reads repo's latest release, the one /releases/latest/download/
// serves, found false when it has none.
func (c Client) Latest(ctx context.Context, repo string) (Release, bool, error) {
var r Release
err := c.do(ctx, http.MethodGet, c.repoURL(repo, "releases", "latest"), nil, "", http.StatusOK, &r)
if isStatus(err, http.StatusNotFound) {
return Release{}, false, nil
}
return r, err == nil, err
}
// TagRef is the object repo's tag names now, a tag object's ID for an
// annotated tag; found false when there's no such tag.
func (c Client) TagRef(ctx context.Context, repo, tag string) (string, bool, error) {
var ref struct {
Object struct {
SHA string `json:"sha"`
} `json:"object"`
}
err := c.do(ctx, http.MethodGet, c.repoURL(repo, "git", "ref", "tags", tag), nil, "", http.StatusOK, &ref)
if isStatus(err, http.StatusNotFound) {
return "", false, nil
}
return ref.Object.SHA, err == nil, err
}
// errTooLarge is a download past the size it was allowed.
var errTooLarge = errors.New("larger than allowed")
// Download writes asset a of repo to w, at most max bytes, and returns
// its SHA-256, of the bytes written: what's checked is what was written,
// never a second download.
func (c Client) Download(ctx context.Context, repo string, a Asset, maxBytes int64, w io.Writer) (string, error) {
return c.download(ctx, c.repoURL(repo, "releases", "assets", strconv.FormatInt(a.ID, 10)), "application/octet-stream", a.Name, maxBytes, w)
}
// download writes what u answers to w, at most maxBytes, and returns its
// SHA-256; name is what it's called in an error.
func (c Client) download(ctx context.Context, u, accept, name string, maxBytes int64, w io.Writer) (string, error) {
req, err := c.request(ctx, http.MethodGet, u, nil, "")
if err != nil {
return "", err
}
req.Header.Set("Accept", accept)
resp, err := c.HTTP.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) // only for the error's text
return "", &APIError{Method: http.MethodGet, Path: req.URL.Path, Status: resp.StatusCode, Body: snippet(data)}
}
h := sha256.New()
n, err := io.Copy(io.MultiWriter(w, h), io.LimitReader(resp.Body, maxBytes+1))
if err != nil {
return "", fmt.Errorf("downloading %s: %w", name, err)
}
if n > maxBytes {
return "", fmt.Errorf("%s: %w (%d bytes)", name, errTooLarge, maxBytes)
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// DownloadBytes is Download into memory.
func (c Client) DownloadBytes(ctx context.Context, repo string, a Asset, maxBytes int64) ([]byte, error) {
var b bytes.Buffer
if _, err := c.Download(ctx, repo, a, maxBytes, &b); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Upload adds size bytes from body to repo's release id as the asset
// name, and returns the asset and the SHA-256 of the bytes it sent, so
// what was uploaded is what was checked, whatever the file on disk did.
func (c Client) Upload(ctx context.Context, repo string, id int64, name string, body io.Reader, size int64) (Asset, string, error) {
u := strings.TrimSuffix(c.Uploads, "/") + "/repos/" + repo + "/releases/" + strconv.FormatInt(id, 10) +
"/assets?name=" + url.QueryEscape(name)
h := sha256.New()
var a Asset
err := c.send(ctx, http.MethodPost, u, io.TeeReader(io.LimitReader(body, size), h), size, "application/octet-stream", http.StatusCreated, &a)
return a, hex.EncodeToString(h.Sum(nil)), err
}
// DeleteAsset deletes repo's asset id.
func (c Client) DeleteAsset(ctx context.Context, repo string, id int64) error {
return c.do(ctx, http.MethodDelete, c.repoURL(repo, "releases", "assets", strconv.FormatInt(id, 10)), nil, "", http.StatusNoContent, nil)
}
// Publish takes repo's draft release id out of draft: a prerelease
// marked as one, and made GitHub's latest release only when latest.
func (c Client) Publish(ctx context.Context, repo string, id int64, prerelease, latest bool) (Release, error) {
body, err := json.Marshal(map[string]any{"draft": false, "prerelease": prerelease, "make_latest": strconv.FormatBool(latest)})
if err != nil {
return Release{}, err
}
var r Release
err = c.do(ctx, http.MethodPatch, c.repoURL(repo, "releases", strconv.FormatInt(id, 10)), body, "application/json", http.StatusOK, &r)
return r, err
}
// A file is a file in a repository, as the contents API has it.
type file struct {
Type string `json:"type"`
SHA string `json:"sha"`
Encoding string `json:"encoding"`
Content string `json:"content"`
}
// Contents reads path in repo at branch: its bytes and its blob's SHA,
// which an update names, or found false when it isn't there.
func (c Client) Contents(ctx context.Context, repo, path, branch string) (data []byte, sha string, found bool, err error) {
var f file
u := c.repoURL(repo, "contents") + "/" + escapePath(path) + "?ref=" + url.QueryEscape(branch)
err = c.do(ctx, http.MethodGet, u, nil, "", http.StatusOK, &f)
if isStatus(err, http.StatusNotFound) {
return nil, "", false, nil
} else if err != nil {
return nil, "", false, err
}
if f.Type != "file" || f.Encoding != "base64" {
return nil, "", false, fmt.Errorf("%s in %s is a %s in %q, not a file in base64", path, repo, f.Type, f.Encoding)
}
data, err = base64.StdEncoding.DecodeString(strings.ReplaceAll(f.Content, "\n", ""))
if err != nil {
return nil, "", false, fmt.Errorf("%s in %s: %w", path, repo, err)
}
return data, f.SHA, true, nil
}
// PutContents commits data as path in repo's branch, with message: over
// the blob sha, which GitHub refuses when the file has changed since, or
// as a new file when sha is "".
func (c Client) PutContents(ctx context.Context, repo, path, branch, message string, data []byte, sha string) error {
body := map[string]string{"message": message, "content": base64.StdEncoding.EncodeToString(data), "branch": branch}
if sha != "" {
body["sha"] = sha
}
b, _ := json.Marshal(body)
want := http.StatusOK
if sha == "" {
want = http.StatusCreated
}
return c.do(ctx, http.MethodPut, c.repoURL(repo, "contents")+"/"+escapePath(path), b, "application/json", want, nil)
}
// escapePath escapes each of path's segments.
func escapePath(path string) string {
parts := strings.Split(path, "/")
for i, p := range parts {
parts[i] = url.PathEscape(p)
}
return strings.Join(parts, "/")
}