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

177 lines
5.7 KiB
Go

package cosign
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
// A GitHub App's tokens (GitHub's "Generating a JSON Web Token (JWT) for
// a GitHub App" and "Create an installation access token for an app"):
// the app signs a JWT with its private key (RS256), issued 60 seconds in
// the past for clock drift and for at most 10 minutes, then trades it for
// an installation token, which lasts an hour.
const (
jwtBackdate = 60 * time.Second
jwtLife = 9 * time.Minute
// tokenSlack is how long before its expiry a token is replaced, so
// no call starts with one about to expire.
tokenSlack = 10 * time.Minute
)
// An AppToken is a GitHub App installation's token, made from the app's
// private key and kept until shortly before it expires. Each token is
// limited to Repos, to writing contents (releases and the tap) and to
// reading actions (CI's artifacts), whatever else the
// installation was granted.
type AppToken struct {
// API is GitHub's API root, and HTTP the client that calls it.
API string
HTTP *http.Client
// AppID is the app's ID or its client ID, the JWT's issuer, and
// Installation its installation's ID on devvm's account.
AppID string
Installation int64
Key *rsa.PrivateKey
// Repos are the repositories' names, without their owner, the token
// may write: devvm's and the tap's.
Repos []string
// Now is the clock; time.Now by default.
Now func() time.Time
mu sync.Mutex
token string
expires time.Time
}
// Token is a token for the installation: the one it has, until
// tokenSlack before it expires, then a new one.
func (a *AppToken) Token(ctx context.Context) (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
now := a.now()
if a.token != "" && now.Before(a.expires.Add(-tokenSlack)) {
return a.token, nil
}
jwt, err := a.jwt(now)
if err != nil {
return "", err
}
body, err := json.Marshal(map[string]any{"repositories": a.Repos, "permissions": map[string]string{"contents": "write", "actions": "read"}})
if err != nil {
return "", err
}
u := strings.TrimSuffix(a.API, "/") + "/app/installations/" + strconv.FormatInt(a.Installation, 10) + "/access_tokens"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, strings.NewReader(string(body)))
if err != nil {
return "", 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 "+jwt)
req.Header.Set("Content-Type", "application/json")
resp, err := a.HTTP.Do(req)
if err != nil {
return "", fmt.Errorf("asking GitHub for the app's installation token: %w", err)
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, maxJSON))
if err != nil {
return "", fmt.Errorf("reading the app's installation token: %w", err)
}
if resp.StatusCode != http.StatusCreated {
return "", &APIError{Method: http.MethodPost, Path: req.URL.Path, Status: resp.StatusCode, Body: snippet(data)}
}
var t struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
if err := json.Unmarshal(data, &t); err != nil {
return "", fmt.Errorf("reading the app's installation token: %w", err)
}
if t.Token == "" || !t.ExpiresAt.After(now.Add(tokenSlack)) {
return "", errors.New("GitHub gave the app no installation token, or one that's about to expire")
}
a.token, a.expires = t.Token, t.ExpiresAt
return a.token, nil
}
func (a *AppToken) now() time.Time {
if a.Now != nil {
return a.Now()
}
return time.Now()
}
// jwt is the app's JSON Web Token at now: RS256 over its header and
// claims, issued jwtBackdate before now, expiring jwtLife after.
func (a *AppToken) jwt(now time.Time) (string, error) {
if a.Key == nil || a.AppID == "" {
return "", errors.New("no GitHub App to make a token with")
}
enc := base64.RawURLEncoding
header, _ := json.Marshal(map[string]string{"alg": "RS256", "typ": "JWT"})
claims, err := json.Marshal(map[string]any{
"iat": now.Add(-jwtBackdate).Unix(),
"exp": now.Add(jwtLife).Unix(),
"iss": a.AppID,
})
if err != nil {
return "", err
}
signing := enc.EncodeToString(header) + "." + enc.EncodeToString(claims)
sum := sha256.Sum256([]byte(signing))
sig, err := rsa.SignPKCS1v15(rand.Reader, a.Key, crypto.SHA256, sum[:])
if err != nil {
return "", fmt.Errorf("signing the app's JWT: %w", err)
}
return signing + "." + enc.EncodeToString(sig), nil
}
// ParseAppKey reads a GitHub App's private key, the PEM file GitHub gives
// (PKCS #1), or the same key as PKCS #8; 2048 bits or more.
func ParseAppKey(data []byte) (*rsa.PrivateKey, error) {
block, rest := pem.Decode(data)
if block == nil || strings.TrimSpace(string(rest)) != "" {
return nil, errors.New("the GitHub App's private key isn't one PEM block")
}
var k *rsa.PrivateKey
switch block.Type {
case "RSA PRIVATE KEY":
var err error
if k, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
return nil, fmt.Errorf("the GitHub App's private key: %w", err)
}
case "PRIVATE KEY":
parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("the GitHub App's private key: %w", err)
}
var ok bool
if k, ok = parsed.(*rsa.PrivateKey); !ok {
return nil, errors.New("the GitHub App's private key isn't an RSA key")
}
default:
return nil, fmt.Errorf("the GitHub App's private key is a %q, not an RSA private key", block.Type)
}
if k.N.BitLen() < 2048 {
return nil, fmt.Errorf("the GitHub App's private key has %d bits, under 2048", k.N.BitLen())
}
return k, nil
}