diff --git a/.golangci.yml b/.golangci.yml index c6f87fa2..1ea75c38 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -220,6 +220,17 @@ linters: - path: ^cmd/devvm/ linters: [forbidigo] text: os\.Exit|context\.(Background|TODO) + # The co-signer is a program of its own, which imports the standard + # library alone (depguard's cosign): its one HTTP client is + # github.go's, which app.go's token calls with, and its lock is + # lock_unix.go's. Each exclusion names its file, so a second client + # or lock elsewhere in the package still fails. + - path: ^internal/cosign/(github|app)\.go$ + linters: [forbidigo] + text: reach the web through internal/fetch + - path: ^internal/cosign/lock_unix\.go$ + linters: [forbidigo] + text: (syscall|unix)\.Flock # The end-to-end runner is a test, not devvm: it prints its results, # TestMain exits with m.Run's code, and it stops its own checks' # process groups and reads whether a lock's process is alive. diff --git a/internal/cosign/actions.go b/internal/cosign/actions.go new file mode 100644 index 00000000..eb6b87d8 --- /dev/null +++ b/internal/cosign/actions.go @@ -0,0 +1,79 @@ +package cosign + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" +) + +// CI hands its build over as a workflow artifact, never a release: it +// has contents: read, so only the co-signer makes and publishes releases. +// These are GitHub's Actions API calls the co-signer reads them with. + +// A Run is one run of a workflow, as the co-signer reads one. +type Run struct { + ID int64 `json:"id"` + // Path is the workflow file's path, .github/workflows/. + Path string `json:"path"` + // HeadBranch is the tag or branch it ran for, and HeadSHA the commit. + HeadBranch string `json:"head_branch"` + HeadSHA string `json:"head_sha"` + Event string `json:"event"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + // HeadRepository is the repository its commit came from. + HeadRepository struct { + FullName string `json:"full_name"` + } `json:"head_repository"` +} + +// An Artifact is a run's artifact: a zip of the files it uploaded. +type Artifact struct { + ID int64 `json:"id"` + Name string `json:"name"` + Size int64 `json:"size_in_bytes"` + Expired bool `json:"expired"` + // Digest is GitHub's sha256: of the zip, when it has one. + Digest string `json:"digest"` +} + +// Runs lists the successful runs of repo's workflow file (its name in +// .github/workflows), newest first, until the list ends or a page whose +// every run settled says is done with: see pages. +func (c Client) Runs(ctx context.Context, repo, workflow string, settled func(Run) bool) ([]Run, error) { + var all []Run + last := 0 + err := c.pages(ctx, c.repoURL(repo, "actions", "workflows", workflow, "runs")+"?status=success", func(data []byte) (int, error) { + var page struct { + Runs []Run `json:"workflow_runs"` + } + if err := json.Unmarshal(data, &page); err != nil { + return 0, fmt.Errorf("reading %s's runs of %s: %w", repo, workflow, err) + } + last = len(all) + all = append(all, page.Runs...) + return len(page.Runs), nil + }, func() bool { return every(all[last:], settled) }) + return all, err +} + +// Artifacts are repo's run id's artifacts named name. +func (c Client) Artifacts(ctx context.Context, repo string, id int64, name string) ([]Artifact, error) { + var page struct { + Artifacts []Artifact `json:"artifacts"` + } + u := c.repoURL(repo, "actions", "runs", strconv.FormatInt(id, 10), "artifacts") + "?per_page=100&name=" + url.QueryEscape(name) + err := c.do(ctx, http.MethodGet, u, nil, "", http.StatusOK, &page) + return page.Artifacts, err +} + +// DownloadArtifact writes repo's artifact a, a zip, to w, at most +// maxBytes, and returns its SHA-256. The download redirects to GitHub's +// storage, which never gets the token. +func (c Client) DownloadArtifact(ctx context.Context, repo string, a Artifact, maxBytes int64, w io.Writer) (string, error) { + return c.download(ctx, c.repoURL(repo, "actions", "artifacts", strconv.FormatInt(a.ID, 10), "zip"), "application/vnd.github+json", a.Name, maxBytes, w) +} diff --git a/internal/cosign/app.go b/internal/cosign/app.go new file mode 100644 index 00000000..3ceeb217 --- /dev/null +++ b/internal/cosign/app.go @@ -0,0 +1,176 @@ +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 +} diff --git a/internal/cosign/app_test.go b/internal/cosign/app_test.go new file mode 100644 index 00000000..8f677c35 --- /dev/null +++ b/internal/cosign/app_test.go @@ -0,0 +1,154 @@ +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) + } + } +} diff --git a/internal/cosign/artifact.go b/internal/cosign/artifact.go new file mode 100644 index 00000000..1b5a1c46 --- /dev/null +++ b/internal/cosign/artifact.go @@ -0,0 +1,144 @@ +package cosign + +import ( + "archive/zip" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" +) + +// The bounds on a CI artifact: its zip, everything it unzips to together, +// and how many files it holds (a manifest's files, the manifest and its +// signature). +const ( + maxArtifact = 4 << 30 + maxArtifactFiles = maxFiles + 2 +) + +// A staged file is one of CI's files, unzipped from its artifact into the +// co-signer's stage folder, which no build can write: its path, and the +// size and SHA-256 of what was written there. +type staged struct { + path string + size int64 + sum string +} + +// read is the staged file's bytes, at most maxBytes. +func (s staged) read(maxBytes int64) ([]byte, error) { + if s.size > maxBytes { + return nil, fmt.Errorf("%s is over %d bytes", filepath.Base(s.path), maxBytes) + } + data, err := os.ReadFile(s.path) + if err != nil { + return nil, err + } + if sha256Hex(data) != s.sum { + return nil, fmt.Errorf("%s changed after it was unzipped", filepath.Base(s.path)) + } + return data, nil +} + +// fetchArtifact downloads repo's artifact a into dir, a new, empty folder +// of the stage, checked against GitHub's digest when it has one, and +// unzips it there (unzip). +func (c Client) fetchArtifact(ctx context.Context, repo string, a Artifact, dir string) (map[string]staged, error) { + if a.Expired { + return nil, fmt.Errorf("CI's artifact %s has expired: run the release workflow again", a.Name) + } + if a.Size > maxArtifact { + return nil, fmt.Errorf("CI's artifact %s is %d bytes, over %d", a.Name, a.Size, int64(maxArtifact)) + } + zipPath := filepath.Join(dir, ".artifact.zip") + f, err := os.OpenFile(zipPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) //nolint:gosec // a new file in the co-signer's own stage folder + if err != nil { + return nil, err + } + sum, err := c.DownloadArtifact(ctx, repo, a, maxArtifact, f) + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + return nil, fmt.Errorf("downloading CI's artifact %s: %w", a.Name, err) + } + if a.Digest != "" && a.Digest != "sha256:"+sum { + return nil, fmt.Errorf("CI's artifact %s has the SHA-256 %s, not GitHub's digest %s", a.Name, sum, a.Digest) + } + files, err := unzip(zipPath, dir) + if rerr := os.Remove(zipPath); err == nil { + err = rerr + } + return files, err +} + +// unzip unzips the zip at path into dir, refusing anything but a flat +// list of regular files: at most maxArtifactFiles, each once, each named +// as a manifest names a file (no folder, no leading dot, no link), stored +// or deflated, together no more than maxArtifact bytes, each no more than +// the size its header gives, which the zip's own CRC-32 checks too. Each +// file is made new (never one that's there), and hashed as it's written. +func unzip(path, dir string) (map[string]staged, error) { + zr, err := zip.OpenReader(path) + if err != nil { + return nil, fmt.Errorf("CI's artifact isn't a zip: %w", err) + } + defer zr.Close() + if len(zr.File) > maxArtifactFiles { + return nil, fmt.Errorf("CI's artifact holds %d files, over %d", len(zr.File), maxArtifactFiles) + } + files := map[string]staged{} + var total uint64 + for _, f := range zr.File { + switch { + case !fileName.MatchString(f.Name): + return nil, fmt.Errorf("CI's artifact holds %q, which isn't a file's name a manifest can list", f.Name) + case !f.Mode().IsRegular(): + return nil, fmt.Errorf("CI's artifact's %s isn't a regular file (%s)", f.Name, f.Mode()) + case f.Method != zip.Store && f.Method != zip.Deflate: + return nil, fmt.Errorf("CI's artifact's %s is compressed with method %d, not stored or deflated", f.Name, f.Method) + case files[f.Name] != (staged{}): + return nil, fmt.Errorf("CI's artifact holds %s twice", f.Name) + } + total += f.UncompressedSize64 + if total > maxArtifact { + return nil, fmt.Errorf("CI's artifact unzips to more than %d bytes", int64(maxArtifact)) + } + s, err := unzipFile(f, filepath.Join(dir, f.Name)) //nolint:gosec // G305: fileName, checked above, has no folder and no leading dot + if err != nil { + return nil, fmt.Errorf("unzipping CI's %s: %w", f.Name, err) + } + files[f.Name] = s + } + return files, nil +} + +// unzipFile writes f to path, a new file, at most the size f's header +// gives. +func unzipFile(f *zip.File, path string) (staged, error) { + r, err := f.Open() + if err != nil { + return staged{}, err + } + defer r.Close() + out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) //nolint:gosec // a new file in the co-signer's own stage folder, named as a manifest names a file + if err != nil { + return staged{}, err + } + h := sha256.New() + n, err := io.Copy(io.MultiWriter(out, h), io.LimitReader(r, int64(f.UncompressedSize64)+1)) //nolint:gosec // bounded by maxArtifact above + if cerr := out.Close(); err == nil { + err = cerr + } + switch { + case err != nil: + return staged{}, err + case uint64(n) != f.UncompressedSize64: //nolint:gosec // n is never negative + return staged{}, errors.New("its size isn't the one its header gives") + } + return staged{path: path, size: n, sum: hex.EncodeToString(h.Sum(nil))}, nil +} diff --git a/internal/cosign/artifact_test.go b/internal/cosign/artifact_test.go new file mode 100644 index 00000000..ebff92d3 --- /dev/null +++ b/internal/cosign/artifact_test.go @@ -0,0 +1,114 @@ +package cosign + +import ( + "archive/zip" + "bytes" + "hash/crc32" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +// zipOf is a zip of entries, each made by its function on the writer. +func zipOf(t *testing.T, entries ...func(*zip.Writer) error) string { + t.Helper() + var b bytes.Buffer + zw := zip.NewWriter(&b) + for _, e := range entries { + if err := e(zw); err != nil { + t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "a.zip") + if err := os.WriteFile(path, b.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +// entry is a file name with data, with mode. +func entry(name string, data []byte, mode fs.FileMode) func(*zip.Writer) error { + return func(zw *zip.Writer) error { + h := &zip.FileHeader{Name: name, Method: zip.Deflate} + h.SetMode(mode) + w, err := zw.CreateHeader(h) + if err != nil { + return err + } + _, err = w.Write(data) + return err + } +} + +// A good artifact unzips to its files, each hashed as written; anything +// but a flat list of regular files with plain names, each once and the +// size its header gives, is refused. +func TestUnzip(t *testing.T) { + good := zipOf(t, entry("SHA256SUMS", []byte("sums\n"), 0o644), entry("install.sh", []byte("#!/bin/bash\n"), 0o755)) + dir := t.TempDir() + files, err := unzip(good, dir) + if err != nil { + t.Fatal(err) + } + if f := files["install.sh"]; f.sum != sha256Hex([]byte("#!/bin/bash\n")) || f.size != 12 || f.path != filepath.Join(dir, "install.sh") { + t.Errorf("unzip: %+v", files) + } + if data, err := files["SHA256SUMS"].read(maxManifest); err != nil || string(data) != "sums\n" { + t.Errorf("read: %q %v", data, err) + } + if err := os.WriteFile(files["SHA256SUMS"].path, []byte("other\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := files["SHA256SUMS"].read(maxManifest); err == nil { + t.Error("a staged file changed since it was unzipped was read") + } + + many := make([]func(*zip.Writer) error, maxArtifactFiles+1) + for i := range many { + many[i] = entry("f"+strconv.Itoa(i), []byte("x"), 0o644) + } + lying := func(zw *zip.Writer) error { + data := []byte("ten bytes!") + w, err := zw.CreateRaw(&zip.FileHeader{Name: "lie", Method: zip.Store, CRC32: crc32.ChecksumIEEE(data), CompressedSize64: 10, UncompressedSize64: 3}) + if err != nil { + return err + } + _, err = w.Write(data) + return err + } + for name, path := range map[string]string{ + "a folder": zipOf(t, entry("dir/", nil, fs.ModeDir|0o755)), + "a path": zipOf(t, entry("a/b", []byte("x"), 0o644)), + "a parent": zipOf(t, entry("../x", []byte("x"), 0o644)), + "a dot file": zipOf(t, entry(".git", []byte("x"), 0o644)), + "a link": zipOf(t, entry("link", []byte("/etc/passwd"), fs.ModeSymlink|0o777)), + "a file twice": zipOf(t, entry("x", []byte("1"), 0o644), entry("x", []byte("2"), 0o644)), + "too many files": zipOf(t, many...), + "a size that lies": zipOf(t, lying), + } { + if _, err := unzip(path, t.TempDir()); err == nil { + t.Errorf("%s: unzipped", name) + } + } + notZip := filepath.Join(t.TempDir(), "x.zip") + if err := os.WriteFile(notZip, []byte("not a zip"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := unzip(notZip, t.TempDir()); err == nil || !strings.Contains(err.Error(), "isn't a zip") { + t.Errorf("not a zip: %v", err) + } + // A file already there is never written over. + dir = t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "install.sh"), []byte("mine"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := unzip(good, dir); err == nil { + t.Error("unzipped over a file that was there") + } +} diff --git a/internal/cosign/config.go b/internal/cosign/config.go new file mode 100644 index 00000000..772958da --- /dev/null +++ b/internal/cosign/config.go @@ -0,0 +1,378 @@ +package cosign + +import ( + "crypto/rsa" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "time" + + "github.com/BurntSushi/toml" + + "github.com/devvmhq/devvm/internal/minisign" +) + +// The co-signer's files, by default. +const ( + DefaultConfig = "/etc/devvm-cosign/config.toml" + defaultState = "/var/lib/devvm-cosign" + defaultBuild = "/var/lib/devvm-cosign-build" + maxConfig = 1 << 20 + maxKeyFile = 64 << 10 +) + +// Config is /etc/devvm-cosign/config.toml: what the co-signer trusts and +// signs with, all of it pinned here, on its own machine, and none of it +// read from GitHub or from what it builds. +type Config struct { + // Repo is devvm's repository, owner/name, and Tap the Homebrew tap's, + // under the same owner, as the app's one installation covers both. + Repo string `toml:"repo"` + Tap string `toml:"tap"` + // GitURL is where tags are fetched from, https://github.com/.git + // by default. + GitURL string `toml:"git_url"` + // API and Uploads are GitHub's API and uploads roots, by default + // https://api.github.com and https://uploads.github.com. + API string `toml:"api_url"` + Uploads string `toml:"uploads_url"` + // StateDir holds state.json, the reports, the kept formulas, CI's + // staged files and the builds' clones, none of which a build's + // container can reach, /var/lib/devvm-cosign by default. BuildDir + // holds what the containers write, the builds' work and caches and + // podman's storage, /var/lib/devvm-cosign-build by default; the two + // are apart, so the podman service's unit can hide the first whole. + StateDir string `toml:"state_dir"` + BuildDir string `toml:"build_dir"` + // Devvm is the co-signer's own devvm: a checkout of a release tag + // that the maintainer checked by hand, at the commit pinned here, + // whose release.sh rebuilds each release. + Devvm DevvmConfig `toml:"devvm"` + // TagSigners are the SSH public keys whose signed tags it builds, as + // .pub files have them. + TagSigners []string `toml:"tag_signers"` + // Runtime is the container runtime release.sh builds with, podman or + // docker (DEVVM_RELEASE_RUNTIME); its choice when "". + Runtime string `toml:"runtime"` + // ReleaseWorkflow is the file name, in .github/workflows, of the + // workflow whose artifact hands over each release CI built, + // release.yml by default. + ReleaseWorkflow string `toml:"release_workflow"` + // Notify is a command, its program's absolute path then its + // arguments, that each run that failed or alerted runs, with the + // failures on its stdin, so a maintainer hears of it; none when empty. + Notify []string `toml:"notify"` + // Release and Base are each kind's keys. Base is optional until + // bases are published. + Release KindConfig `toml:"release"` + Base *KindConfig `toml:"base"` + // App is the GitHub App whose installation token it calls GitHub + // with. + App AppConfig `toml:"app"` +} + +// DevvmConfig is the co-signer's own devvm checkout. +type DevvmConfig struct { + Checkout string `toml:"checkout"` + Commit string `toml:"commit"` +} + +// KindConfig is one kind's keys: the co-signer's secret key's file, and +// the three roles' public keys that devvm embeds for the kind. +type KindConfig struct { + SecretKey string `toml:"secret_key"` + Keys map[string]string `toml:"keys"` + // LegacyKey, for releases while they bridge from the old release key, + // is that key: a release is published only once its SHA256SUMS.minisig + // checks out with it too, so 0.1 and 0.2 can upgrade to it. + LegacyKey string `toml:"legacy_key"` + // Workflow, for bases, is the file name of the workflow whose artifact + // hands over each base CI built, base.yml by default, and + // MaxSnapshotDays how old a base's Ubuntu snapshot may be, 60 by + // default (ParseIndex says why). + Workflow string `toml:"workflow"` + MaxSnapshotDays int `toml:"max_snapshot_days"` +} + +// AppConfig is the GitHub App's ID (or client ID), its installation's ID +// and its private key's file. +type AppConfig struct { + ID string `toml:"id"` + Installation int64 `toml:"installation"` + PrivateKey string `toml:"private_key"` +} + +// A Kind is one kind's keys, read: the three public keys, the +// co-signer's secret key, and for releases the old key while the bridge +// lasts. +type Kind struct { + Keys minisign.Keys + Secret minisign.SecretKey + Legacy *minisign.PublicKey + // Workflow is the workflow file whose artifacts hand this kind over. + Workflow string + // MaxSnapshotAge bounds a base's snapshot's age. + MaxSnapshotAge time.Duration +} + +// Setup is the config, checked, with its keys read. +type Setup struct { + Config + Signers []Signer + Release Kind + Base *Kind + AppKey *rsa.PrivateKey +} + +// repoName is an owner/name on GitHub. +var repoName = regexp.MustCompile(`^[A-Za-z0-9-]{1,39}/[A-Za-z0-9._-]{1,100}$`) + +// ReadConfig reads the config at path, refusing a key it doesn't know, +// and checks it, without reading its key files: what devvm-cosign retry +// and ack need, which change the state alone. +func ReadConfig(path string) (Config, error) { + data, err := readFile(path, maxConfig, 0) + if err != nil { + return Config{}, err + } + var c Config + md, err := toml.Decode(string(data), &c) + if err != nil { + return Config{}, fmt.Errorf("reading %s: %w", path, err) + } + if un := md.Undecoded(); len(un) > 0 { + return Config{}, fmt.Errorf("%s has %s, which the co-signer doesn't read", path, un[0]) + } + c.defaults() + if err := c.check(); err != nil { + return Config{}, fmt.Errorf("%s: %w", path, err) + } + return c, nil +} + +// LoadConfig reads the config at path (ReadConfig) and its keys, +// checking each. creds is systemd's credentials folder +// ($CREDENTIALS_DIRECTORY), "" for none: the service's unit loads each +// key file, root's, into it (LoadCredential=) under the file's own name, +// and the co-signer reads it from there, never the file itself, which its +// user can't read. +func LoadConfig(path, creds string) (*Setup, error) { + c, err := ReadConfig(path) + if err != nil { + return nil, err + } + s := &Setup{Config: c} + for _, line := range c.TagSigners { + sg, err := ParseSigner(line) + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + s.Signers = append(s.Signers, sg) + } + if s.Release, err = readKind(minisign.Release, c.Release, creds); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + s.Release.Workflow = c.ReleaseWorkflow + if c.Base != nil { + if c.Base.LegacyKey != "" { + return nil, fmt.Errorf("%s: a base has no old key: take [base]'s legacy_key out", path) + } + b, err := readKind(minisign.Base, *c.Base, creds) + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + b.Workflow, b.MaxSnapshotAge = c.Base.Workflow, time.Duration(c.Base.MaxSnapshotDays)*24*time.Hour + s.Base = &b + } + key, err := readFile(credential(c.App.PrivateKey, creds), maxKeyFile, forbidden(creds)) + if err != nil { + return nil, err + } + if s.AppKey, err = ParseAppKey(key); err != nil { + return nil, fmt.Errorf("%s: %w", c.App.PrivateKey, err) + } + return s, nil +} + +// defaults fills in what c leaves out. +func (c *Config) defaults() { + if c.GitURL == "" { + c.GitURL = "https://github.com/" + c.Repo + ".git" + } + if c.API == "" { + c.API = "https://api.github.com" + } + if c.Uploads == "" { + c.Uploads = "https://uploads.github.com" + } + if c.StateDir == "" { + c.StateDir = defaultState + } + if c.BuildDir == "" { + c.BuildDir = defaultBuild + } + if c.ReleaseWorkflow == "" { + c.ReleaseWorkflow = "release.yml" + } + if c.Base != nil && c.Base.Workflow == "" { + c.Base.Workflow = "base.yml" + } + if c.Base != nil && c.Base.MaxSnapshotDays == 0 { + c.Base.MaxSnapshotDays = defaultSnapshotDays + } +} + +// defaultSnapshotDays is how old a base's snapshot may be by default: +// two months, against Ubuntu's archive, which changes daily. +const defaultSnapshotDays = 60 + +// workflowFile is a workflow's file name in .github/workflows. +var workflowFile = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}\.ya?ml$`) + +// within is whether path is dir or in it. +func within(path, dir string) bool { + rel, err := filepath.Rel(filepath.Clean(dir), filepath.Clean(path)) + return err == nil && rel != ".." && !strings.HasPrefix(rel, "../") +} + +// credential is where the key file path is read from: systemd's copy in +// creds, by the file's name, or the file itself when creds is "". +func credential(path, creds string) string { + if creds == "" { + return path + } + return filepath.Join(creds, filepath.Base(path)) +} + +// check is whether c holds everything the co-signer needs, each in its +// form. +func (c Config) check() error { + switch { + case !repoName.MatchString(c.Repo) || !repoName.MatchString(c.Tap): + return fmt.Errorf("repo and tap must each be owner/name: %q, %q", c.Repo, c.Tap) + case owner(c.Repo) != owner(c.Tap): + return fmt.Errorf("the tap %s isn't under %s, the owner the app's installation is on", c.Tap, owner(c.Repo)) + case !filepath.IsAbs(c.StateDir) || !filepath.IsAbs(c.BuildDir) || !filepath.IsAbs(c.Devvm.Checkout): + return errors.New("state_dir, build_dir and devvm's checkout must be absolute paths") + case within(c.BuildDir, c.StateDir) || within(c.StateDir, c.BuildDir): + return fmt.Errorf("build_dir %s and state_dir %s must be apart, neither in the other, so a build can't reach the state", c.BuildDir, c.StateDir) + case !regexp.MustCompile(`^[0-9a-f]{40}$`).MatchString(c.Devvm.Commit): + return fmt.Errorf("devvm's commit must be a full SHA-1: %q", c.Devvm.Commit) + case len(c.TagSigners) == 0: + return errors.New("no tag_signers: the release tags' SSH public keys") + case c.Runtime != "" && c.Runtime != "podman" && c.Runtime != "docker": + return fmt.Errorf("runtime is podman or docker, not %q", c.Runtime) + case c.App.ID == "" || c.App.Installation <= 0 || !filepath.IsAbs(c.App.PrivateKey): + return errors.New("app needs its id, its installation and its private_key's absolute path") + case !workflowFile.MatchString(c.ReleaseWorkflow) || c.Base != nil && !workflowFile.MatchString(c.Base.Workflow): + return errors.New("release_workflow and [base]'s workflow are each a workflow file's name, such as release.yml") + case c.Base != nil && (c.Base.MaxSnapshotDays < 1 || c.Base.MaxSnapshotDays > 365): + return fmt.Errorf("[base]'s max_snapshot_days is from 1 to 365, not %d", c.Base.MaxSnapshotDays) + case len(c.Notify) > 0 && !filepath.IsAbs(c.Notify[0]): + return fmt.Errorf("notify's program must be an absolute path: %q", c.Notify[0]) + } + for _, u := range []string{c.GitURL, c.API, c.Uploads} { + if !strings.HasPrefix(u, "https://") { + return fmt.Errorf("%q isn't https", u) + } + } + return nil +} + +func owner(repo string) string { o, _, _ := strings.Cut(repo, "/"); return o } + +// readKind reads kind's keys from c: the three roles' public keys, the +// co-signer's secret key, whose public half must be the cosign role's, +// and the old key, if any. +func readKind(kind minisign.Kind, c KindConfig, creds string) (Kind, error) { + if len(c.Keys) == 0 { + return Kind{}, fmt.Errorf("no %s keys: the co-signer checks with all three, CI's, its own and the recovery key's, so make them first (docs/content/docs/contributing/github-setup.md, step 1)", kind) + } + pub := map[minisign.Role]string{} + for r, k := range c.Keys { + pub[minisign.Role(r)] = k + } + keys, err := minisign.NewKeys(kind, pub) + if err != nil { + return Kind{}, err + } + if !filepath.IsAbs(c.SecretKey) { + return Kind{}, fmt.Errorf("the %s secret_key must be an absolute path: %q", kind, c.SecretKey) + } + data, err := readFile(credential(c.SecretKey, creds), maxKeyFile, forbidden(creds)) + if err != nil { + return Kind{}, err + } + secret, err := minisign.ParseSecretKey(data) + if err != nil { + return Kind{}, fmt.Errorf("%s: %w", c.SecretKey, err) + } + own, err := minisign.ParsePublicKey(c.Keys[string(minisign.Cosign)]) + if err != nil { + return Kind{}, err + } + if p := secret.Public(); p.ID != own.ID || !slices.Equal(p.Key, own.Key) { + return Kind{}, fmt.Errorf("%s isn't the %s cosign key's secret half", c.SecretKey, kind) + } + k := Kind{Keys: keys, Secret: secret} + if c.LegacyKey != "" { + old, err := minisign.ParsePublicKey(c.LegacyKey) + if err != nil { + return Kind{}, fmt.Errorf("the old release key: %w", err) + } + k.Legacy = &old + } + return k, nil +} + +// The modes a key file may not have, as anyone else who can read it could +// sign or call GitHub as the co-signer: its owner's alone, 0600 or 0400, +// or as systemd's system manager loads a credential, root's, 0440, with +// an ACL for the service's user, in a folder that only the service sees, +// not readable by others. +const ( + keyModes os.FileMode = 0o077 + credentialModes os.FileMode = 0o007 +) + +// forbidden is the modes the key files in creds (systemd's credentials +// folder, "" for none) may not have. +func forbidden(creds string) os.FileMode { + if creds == "" { + return keyModes + } + return credentialModes +} + +// readFile reads path, a regular file, up to maxBytes, refusing one with +// any of the modes forbid. +func readFile(path string, maxBytes int64, forbid os.FileMode) ([]byte, error) { + f, err := os.Open(path) //nolint:gosec // the co-signer's own config names it + if err != nil { + return nil, err + } + defer f.Close() + fi, err := f.Stat() + if err != nil { + return nil, err + } + if !fi.Mode().IsRegular() { + return nil, fmt.Errorf("%s isn't a regular file", path) + } + if fi.Mode().Perm()&forbid != 0 { + return nil, fmt.Errorf("%s has mode %04o: a key file must be readable by its owner alone (chmod 600 %s)", path, fi.Mode().Perm(), path) + } + data, err := io.ReadAll(io.LimitReader(f, maxBytes+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > maxBytes { + return nil, fmt.Errorf("%s is over %d bytes", path, maxBytes) + } + return data, nil +} diff --git a/internal/cosign/config_test.go b/internal/cosign/config_test.go new file mode 100644 index 00000000..2da3d97f --- /dev/null +++ b/internal/cosign/config_test.go @@ -0,0 +1,231 @@ +package cosign + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "testing" + "time" + + "github.com/devvmhq/devvm/internal/minisign" + "github.com/devvmhq/devvm/internal/minisign/minisigntest" +) + +// newSecret is a minisign secret key of the test's own, as minisign -G -W +// writes it, and its public key's line. +func newSecret(t testing.TB) (minisign.SecretKey, []byte, string) { + t.Helper() + pub, priv, err := ed25519.GenerateKey(nil) + if err != nil { + t.Fatal(err) + } + id := pub[:8] + raw := append([]byte("Ed\x00\x00B2"), make([]byte, 48)...) + raw = append(append(append(raw, id...), priv...), make([]byte, 32)...) + file := []byte("untrusted comment: a test key\n" + base64.StdEncoding.EncodeToString(raw) + "\n") + k, err := minisign.ParseSecretKey(file) + if err != nil { + t.Fatal(err) + } + return k, file, base64.StdEncoding.EncodeToString(append(append([]byte("Ed"), id...), pub...)) +} + +// configFiles writes a good config and its key files into a folder of +// its own, and returns the config's path; change edits the config's text +// first. Its devvm checkout and commit are placeholders, which only +// devvm-cosign check reads (withCheckout). +func configFiles(t *testing.T, change func(string) string) (string, string) { + t.Helper() + dir := t.TempDir() + _, secret, pub := newSecret(t) + _, baseSecret, basePub := newSecret(t) + app, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + for name, data := range map[string][]byte{ + "release.key": secret, "base.key": baseSecret, + "app.pem": pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(app)}), + } { + if err := os.WriteFile(filepath.Join(dir, name), data, 0o600); err != nil { + t.Fatal(err) + } + } + checkout, pinned := filepath.Join(dir, "devvm"), strings.Repeat("a", 40) + text := `repo = "devvmhq/devvm" +tap = "devvmhq/homebrew-tap" +state_dir = "` + dir + `" +tag_signers = ["` + realTagPub + `"] +runtime = "podman" + +[devvm] +checkout = "` + checkout + `" +commit = "` + pinned + `" + +[release] +secret_key = "` + filepath.Join(dir, "release.key") + `" +legacy_key = "` + minisigntest.NewKey().Public() + `" +keys = { ci = "` + minisigntest.NewKey().Public() + `", cosign = "` + pub + `", recovery = "` + minisigntest.NewKey().Public() + `" } + +[base] +secret_key = "` + filepath.Join(dir, "base.key") + `" +keys = { ci = "` + minisigntest.NewKey().Public() + `", cosign = "` + basePub + `", recovery = "` + minisigntest.NewKey().Public() + `" } + +[app] +id = "` + appID + `" +installation = ` + strconv.Itoa(install) + ` +private_key = "` + filepath.Join(dir, "app.pem") + `" +` + if change != nil { + text = change(text) + } + path := filepath.Join(dir, "config.toml") + if err := os.WriteFile(path, []byte(text), 0o600); err != nil { + t.Fatal(err) + } + return path, dir +} + +// A good config loads with its keys and defaults; devvm-cosign check +// passes on it. +func TestLoadConfig(t *testing.T) { + path, dir := configFiles(t, nil) + s, err := LoadConfig(path, "") + if err != nil { + t.Fatal(err) + } + if s.GitURL != "https://github.com/devvmhq/devvm.git" || s.API != "https://api.github.com" || s.Base == nil || + s.Release.Legacy == nil || len(s.Signers) != 1 || s.AppKey == nil || s.StateDir != dir || + s.Release.Workflow != "release.yml" || s.Base.Workflow != "base.yml" || s.Base.MaxSnapshotAge != 60*24*time.Hour { + t.Errorf("LoadConfig: %+v", s) + } +} + +// Under its unit, the key files, root's, are read from systemd's +// credentials folder by their own names, never from where the config +// says they are, which the co-signer's user can't read. +func TestConfigCredentials(t *testing.T) { + path, dir := configFiles(t, nil) + creds := t.TempDir() + // systemd's system manager makes each credential root's, readable by + // the service's group, mode 0440, in a folder only the service sees. + for _, name := range []string{"release.key", "base.key", "app.pem"} { + if err := os.Rename(filepath.Join(dir, name), filepath.Join(creds, name)); err != nil { + t.Fatal(err) + } + if err := os.Chmod(filepath.Join(creds, name), 0o440); err != nil { //nolint:gosec // G302: the mode systemd gives a credential, which the test is about + t.Fatal(err) + } + } + if _, err := LoadConfig(path, ""); err == nil { + t.Error("loaded with no key files where the config says") + } + if _, err := LoadConfig(path, creds); err != nil { + t.Errorf("LoadConfig from the credentials: %v", err) + } + // Anyone else reading it is refused there too. + if err := os.Chmod(filepath.Join(creds, "base.key"), 0o444); err != nil { //nolint:gosec // G302: a mode the config must refuse + t.Fatal(err) + } + if _, err := LoadConfig(path, creds); err == nil { + t.Error("loaded a credential anyone can read") + } + if err := os.Remove(filepath.Join(creds, "base.key")); err != nil { + t.Fatal(err) + } + if _, err := LoadConfig(path, creds); err == nil { + t.Error("loaded with a credential missing") + } +} + +// A config is refused for anything out of place: a key it doesn't know, +// a key file others can read, a secret key that isn't the cosign key's, +// a tap under another owner, a URL that isn't HTTPS, no signers, an +// unpinned commit, or a base with an old key. +func TestConfigRefused(t *testing.T) { + for name, change := range map[string]func(string) string{ + "an unknown key": func(s string) string { return "extra = 1\n" + s }, + "a tap elsewhere": func(s string) string { + return strings.Replace(s, `"devvmhq/homebrew-tap"`, `"someone/homebrew-tap"`, 1) + }, + "http": func(s string) string { return "api_url = \"http://api.github.com\"\n" + s }, + "no signers": func(s string) string { + return strings.Replace(s, "tag_signers = [\""+realTagPub+"\"]", "tag_signers = []", 1) + }, + "an RSA signer": func(s string) string { return strings.Replace(s, realTagPub, "ssh-rsa AAAAB3NzaC1yc2E x", 1) }, + "a short commit": func(s string) string { return strings.Replace(s, "commit = \"", "commit = \"abc", 1) }, + "a runtime": func(s string) string { return strings.Replace(s, `"podman"`, `"lxc"`, 1) }, + "a relative state": func(s string) string { return "state_dir = \"x\"\n" + strings.Replace(s, "state_dir", "#", 1) }, + "no app": func(s string) string { return strings.Replace(s, "installation = ", "installation = -", 1) }, + "swapped keys": func(s string) string { + return strings.Replace(strings.Replace(s, "release.key", "RELEASE", 1), "base.key", "release.key", 1) + }, + "a base legacy key": func(s string) string { return strings.Replace(s, "[base]\n", "[base]\nlegacy_key = \"x\"\n", 1) }, + "a bad legacy key": func(s string) string { return strings.Replace(s, "legacy_key = \"", "legacy_key = \"x", 1) }, + "a missing role": func(s string) string { return strings.Replace(s, "recovery = ", "other = ", 1) }, + "not TOML": func(s string) string { return s + "[[" }, + "a relative key file": func(s string) string { return strings.Replace(s, "secret_key = \"/", "secret_key = \"", 1) }, + "a workflow path": func(s string) string { return "release_workflow = \"../x.yml\"\n" + s }, + "a base workflow": func(s string) string { return strings.Replace(s, "[base]\n", "[base]\nworkflow = \"base\"\n", 1) }, + "a snapshot bound": func(s string) string { return strings.Replace(s, "[base]\n", "[base]\nmax_snapshot_days = 400\n", 1) }, + "no snapshot bound": func(s string) string { return strings.Replace(s, "[base]\n", "[base]\nmax_snapshot_days = -1\n", 1) }, + "a relative notify": func(s string) string { return "notify = [\"notify-cj\"]\n" + s }, + "builds in the state": func(s string) string { + return regexp.MustCompile(`state_dir = "(.*)"`).ReplaceAllString(s, "state_dir = \"$1\"\nbuild_dir = \"$1/build\"") + }, + "the state in builds": func(s string) string { return "build_dir = \"/\"\n" + s }, + "a relative build": func(s string) string { return "build_dir = \"build\"\n" + s }, + } { + path, _ := configFiles(t, change) + if _, err := LoadConfig(path, ""); err == nil { + t.Errorf("%s: loaded", name) + } + } + // No release keys, as before they're made: it doesn't start, and says + // where making them is described. + path, _ := configFiles(t, func(s string) string { + return regexp.MustCompile(`(?m)^keys = \{.*\}\n`).ReplaceAllLiteralString(s, "") + }) + if _, err := LoadConfig(path, ""); err == nil || !strings.Contains(err.Error(), "no release keys") || !strings.Contains(err.Error(), "github-setup.md") { + t.Errorf("no release keys: %v", err) + } + for _, mode := range []os.FileMode{0o640, 0o604, 0o644} { + path, dir := configFiles(t, nil) + if err := os.Chmod(filepath.Join(dir, "release.key"), mode); err != nil { + t.Fatal(err) + } + if _, err := LoadConfig(path, ""); err == nil || !strings.Contains(err.Error(), "chmod 600") { + t.Errorf("a key file with mode %04o: %v", mode, err) + } + if err := os.Chmod(filepath.Join(dir, "release.key"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(filepath.Join(dir, "app.pem"), mode); err != nil { + t.Fatal(err) + } + if _, err := LoadConfig(path, ""); err == nil { + t.Errorf("an app key with mode %04o: loaded", mode) + } + } + path, dir := configFiles(t, nil) + if err := os.Remove(filepath.Join(dir, "app.pem")); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(dir, "app.pem"), 0o700); err != nil { + t.Fatal(err) + } + if _, err := LoadConfig(path, ""); err == nil { + t.Error("a folder for the app's key: loaded") + } + if _, err := LoadConfig(filepath.Join(dir, "none.toml"), ""); err == nil { + t.Error("no config: loaded") + } +} diff --git a/internal/cosign/doc.go b/internal/cosign/doc.go index 93be28a5..b12addbf 100644 --- a/internal/cosign/doc.go +++ b/internal/cosign/doc.go @@ -4,14 +4,22 @@ // build matches. Everything it trusts is in its own config, never read // from GitHub or from what it builds. // -// It imports the standard library and internal/minisign alone (depguard -// and the structure test hold it to them), so it can't reach the rest of -// devvm's code, and nothing of devvm's imports it. +// It imports the standard library, BurntSushi/toml for its config and +// internal/minisign alone (depguard and the structure test hold it to +// them), so it can't reach the rest of devvm's code, and nothing of +// devvm's imports it. // // The files: // +// - config.go: config.toml (LoadConfig, ReadConfig), its keys, read from +// systemd's credentials, and their files' modes; // - manifest.go: the manifests it reads from CI, SHA256SUMS and // base-index.json, and release versions; // - sshsig.go: git's SSH tag signatures, checked against the pinned -// signers. +// signers; +// - state.go: state.json, written whole, never backwards; +// - github.go and actions.go: every GitHub call (Client), and app.go its +// token, a GitHub App's installation token; artifact.go, CI's +// artifact's download and its unzip; +// - lock_unix.go: one run at a time. package cosign diff --git a/internal/cosign/fakegithub_test.go b/internal/cosign/fakegithub_test.go new file mode 100644 index 00000000..c24a113b --- /dev/null +++ b/internal/cosign/fakegithub_test.go @@ -0,0 +1,610 @@ +package cosign + +import ( + "archive/zip" + "bytes" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +// fakeOwner, fakeRepo and fakeTap are the fake GitHub's repositories. +const ( + fakeOwner = "devvmhq" + fakeRepo = fakeOwner + "/devvm" + fakeTap = fakeOwner + "/homebrew-tap" + appID = "12345" + install = 678 +) + +// A fakeAsset is a release's file on the fake GitHub. +type fakeAsset struct { + Asset + data []byte +} + +// A fakeRelease is a release on the fake GitHub. +type fakeRelease struct { + ID int64 + Tag string + Target string + Name, Body string + Draft bool + Prerelease bool + Latest string + Assets []*fakeAsset +} + +// A fakeRun is a workflow's run on the fake GitHub, with its artifacts, +// each a zip. +type fakeRun struct { + Run + workflow string + artifacts []*fakeArtifact +} + +type fakeArtifact struct { + Artifact + data []byte +} + +// fakeGitHub is GitHub's REST API as the co-signer calls it, in memory: +// the app's installation token, releases and their assets (downloads +// redirect to a storage server of its own, as GitHub's do), uploads, and +// the tap's contents. It checks each call's token, and records what the +// tests ask about. +type fakeGitHub struct { + t *testing.T + mu sync.Mutex + api *httptest.Server + storage *httptest.Server + appKey *rsa.PrivateKey + nextID int64 + + releases []*fakeRelease + runs []*fakeRun + // movedTags are tags pushed again since the tests' builds checked them, + // by what they name now, "" for a tag deleted; every other tag names + // fakeTagObject's. + movedTags map[string]string + tap map[string][]byte + tapLog []string + // tokens is how many installation tokens it gave, and leaked how + // many requests reached its storage with a token. + tokens, leaked int + // downloads counts each asset's downloads, by ID, and + // artifactDownloads each artifact's. + downloads, artifactDownloads map[int64]int + // publishAnswer, when set, is the status a publish that took effect + // answers with, as when its answer is lost. + publishAnswer int + // failUpload, when set, fails the next upload with 502, leaving a + // starter asset with part of the bytes, as GitHub can. + failUpload bool + // onPublish runs before a publish takes effect; afterUpload after an + // upload. + onPublish, afterUpload func(r *fakeRelease) + // serve, when set, gives an asset's bytes in place of its own, by ID + // and how many times it was downloaded before. + serve func(id int64, n int) []byte + // fail, when set, answers a call with its status instead, when it + // returns one. + fail func(r *http.Request) int +} + +func newFakeGitHub(t *testing.T) *fakeGitHub { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + f := &fakeGitHub{t: t, appKey: key, nextID: 100, tap: map[string][]byte{}, downloads: map[int64]int{}, artifactDownloads: map[int64]int{}} + f.storage = httptest.NewServer(http.HandlerFunc(f.serveStorage)) + f.api = httptest.NewServer(http.HandlerFunc(f.serveAPI)) + t.Cleanup(func() { f.api.Close(); f.storage.Close() }) + return f +} + +// client is a Client for the fake, with an app token of its own. +func (f *fakeGitHub) client() Client { + h := NewHTTP(true) + return Client{ + API: f.api.URL, Uploads: f.api.URL + "/uploads", HTTP: h, + Tokens: &AppToken{API: f.api.URL, HTTP: h, AppID: appID, Installation: install, Key: f.appKey, Repos: []string{"devvm", "homebrew-tap"}}, + } +} + +func (f *fakeGitHub) id() int64 { f.nextID++; return f.nextID } + +// addRelease adds a release with files, as a draft or published. +func (f *fakeGitHub) addRelease(tag string, draft bool, files map[string][]byte) *fakeRelease { + f.mu.Lock() + defer f.mu.Unlock() + r := &fakeRelease{ID: f.id(), Tag: tag, Draft: draft} + for _, name := range sortedKeys(files) { + r.Assets = append(r.Assets, f.asset(name, files[name])) + } + f.releases = append(f.releases, r) + return r +} + +// addRun adds a successful run of workflow, pushed for branch (a tag) at +// commit, whose artifact name zips files, as CI's upload-artifact makes +// one; it returns the run. +func (f *fakeGitHub) addRun(workflow, branch, commit, event, name string, files map[string][]byte) *fakeRun { + f.t.Helper() + var b bytes.Buffer + zw := zip.NewWriter(&b) + for _, n := range sortedKeys(files) { + w, err := zw.Create(n) + if err != nil { + f.t.Fatal(err) + } + if _, err := w.Write(files[n]); err != nil { + f.t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + f.t.Fatal(err) + } + return f.addRunZip(workflow, branch, commit, event, name, b.Bytes()) +} + +// addRunZip adds a run as addRun does, with its artifact's zip as it is. +func (f *fakeGitHub) addRunZip(workflow, branch, commit, event, name string, zipped []byte) *fakeRun { + f.mu.Lock() + defer f.mu.Unlock() + r := &fakeRun{workflow: workflow} + r.ID, r.Path, r.HeadBranch, r.HeadSHA, r.Event = f.id(), ".github/workflows/"+workflow, branch, commit, event + r.Status, r.Conclusion, r.HeadRepository.FullName = "completed", "success", fakeRepo + sum := sha256.Sum256(zipped) + r.artifacts = []*fakeArtifact{{Artifact: Artifact{ID: f.id(), Name: name, Size: int64(len(zipped)), Digest: "sha256:" + hexOf(sum[:])}, data: zipped}} + f.runs = append(f.runs, r) + return r +} + +func (f *fakeGitHub) asset(name string, data []byte) *fakeAsset { + sum := sha256.Sum256(data) + return &fakeAsset{Asset: Asset{ID: f.id(), Name: name, State: uploaded, Size: int64(len(data)), Digest: "sha256:" + hexOf(sum[:])}, data: data} +} + +// put replaces or adds r's asset name, with a new ID, as deleting and +// uploading it again would. +func (f *fakeGitHub) put(r *fakeRelease, name string, data []byte) { + r.Assets = slices.DeleteFunc(r.Assets, func(a *fakeAsset) bool { return a.Name == name }) + r.Assets = append(r.Assets, f.asset(name, data)) +} + +// release is the release tagged tag, and whether there is one. +func (f *fakeGitHub) release(tag string) *fakeRelease { + f.mu.Lock() + defer f.mu.Unlock() + for _, r := range f.releases { + if r.Tag == tag { + return r + } + } + return nil +} + +// file is r's asset name's bytes, nil for none. +func (r *fakeRelease) file(name string) []byte { + for _, a := range r.Assets { + if a.Name == name { + return a.data + } + } + return nil +} + +func (r *fakeRelease) json() Release { + out := Release{ID: r.ID, TagName: r.Tag, Name: r.Name, Body: r.Body, Draft: r.Draft, Prerelease: r.Prerelease, Assets: []Asset{}} + for _, a := range r.Assets { + out.Assets = append(out.Assets, a.Asset) + } + return out +} + +func (f *fakeGitHub) write(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if err := json.NewEncoder(w).Encode(v); err != nil { + f.t.Errorf("encoding the fake's answer: %v", err) + } +} + +func (f *fakeGitHub) serveStorage(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + defer f.mu.Unlock() + if r.Header.Get("Authorization") != "" { + f.leaked++ + } + if s, ok := strings.CutPrefix(r.URL.Path, "/artifact/"); ok { + for _, run := range f.runs { + for _, a := range run.artifacts { + if strconv.FormatInt(a.ID, 10) == s { + f.artifactDownloads[a.ID]++ + _, _ = w.Write(a.data) + return + } + } + } + http.NotFound(w, r) + return + } + id, err := strconv.ParseInt(strings.TrimPrefix(r.URL.Path, "/"), 10, 64) + if err != nil { + http.NotFound(w, r) + return + } + for _, rel := range f.releases { + for _, a := range rel.Assets { + if a.ID == id { + data := a.data + if f.serve != nil { + if alt := f.serve(id, f.downloads[id]); alt != nil { + data = alt + } + } + f.downloads[id]++ + _, _ = w.Write(data) + return + } + } + } + http.NotFound(w, r) +} + +func (f *fakeGitHub) serveAPI(w http.ResponseWriter, r *http.Request) { + if f.fail != nil { + if status := f.fail(r); status != 0 { + http.Error(w, "the fake's failure", status) + return + } + } + if r.Method == http.MethodPost && r.URL.Path == "/app/installations/"+strconv.Itoa(install)+"/access_tokens" { + f.token(w, r) + return + } + if !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer tok-") || r.Header.Get("X-Github-Api-Version") != apiVersion { + f.write(w, http.StatusUnauthorized, map[string]string{"message": "Bad credentials"}) + return + } + f.mu.Lock() + defer f.mu.Unlock() + p := r.URL.Path + switch { + case strings.HasPrefix(p, "/repos/"+fakeTap+"/contents/"): + f.contents(w, r, strings.TrimPrefix(p, "/repos/"+fakeTap+"/contents/")) + case strings.HasPrefix(p, "/uploads/repos/"+fakeRepo+"/releases/"): + f.upload(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/uploads/repos/"+fakeRepo+"/releases/"), "/assets")) + case p == "/repos/"+fakeRepo+"/releases" && r.Method == http.MethodPost: + f.create(w, r) + case p == "/repos/"+fakeRepo+"/releases": + f.list(w, r) + case p == "/repos/"+fakeRepo+"/releases/latest": + f.latest(w) + case strings.HasPrefix(p, "/repos/"+fakeRepo+"/releases/tags/"): + f.byTag(w, strings.TrimPrefix(p, "/repos/"+fakeRepo+"/releases/tags/")) + case strings.HasPrefix(p, "/repos/"+fakeRepo+"/git/ref/tags/"): + tag := strings.TrimPrefix(p, "/repos/"+fakeRepo+"/git/ref/tags/") + obj, moved := f.movedTags[tag] + switch { + case !moved: + obj = fakeTagObject(tag) + case obj == "": + f.write(w, http.StatusNotFound, map[string]string{"message": "Not Found"}) + return + } + f.write(w, http.StatusOK, map[string]any{"ref": "refs/tags/" + tag, "object": map[string]string{"sha": obj, "type": "tag"}}) + case strings.HasPrefix(p, "/repos/"+fakeRepo+"/actions/"): + f.actions(w, r, strings.TrimPrefix(p, "/repos/"+fakeRepo+"/actions/")) + case strings.HasPrefix(p, "/repos/"+fakeRepo+"/releases/assets/"): + f.assetCall(w, r, strings.TrimPrefix(p, "/repos/"+fakeRepo+"/releases/assets/")) + case strings.HasPrefix(p, "/repos/"+fakeRepo+"/releases/"): + f.releaseCall(w, r, strings.TrimPrefix(p, "/repos/"+fakeRepo+"/releases/")) + default: + f.write(w, http.StatusNotFound, map[string]string{"message": "Not Found"}) + } +} + +// token checks the app's JWT, as GitHub does, and gives a token. +func (f *fakeGitHub) token(w http.ResponseWriter, r *http.Request) { + jwt, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + parts := strings.Split(jwt, ".") + if !ok || len(parts) != 3 { + f.write(w, http.StatusUnauthorized, nil) + return + } + sig, err := base64.RawURLEncoding.DecodeString(parts[2]) + sum := sha256.Sum256([]byte(parts[0] + "." + parts[1])) + if err != nil || rsa.VerifyPKCS1v15(&f.appKey.PublicKey, crypto.SHA256, sum[:], sig) != nil { + f.write(w, http.StatusUnauthorized, map[string]string{"message": "the JWT's signature"}) + return + } + var header map[string]string + var claims struct { + Iat, Exp int64 + Iss string + } + h, _ := base64.RawURLEncoding.DecodeString(parts[0]) + c, _ := base64.RawURLEncoding.DecodeString(parts[1]) + if json.Unmarshal(h, &header) != nil || json.Unmarshal(c, &claims) != nil || header["alg"] != "RS256" || + claims.Iss != appID || claims.Exp-claims.Iat > 600 || claims.Exp <= claims.Iat { + f.write(w, http.StatusUnauthorized, map[string]string{"message": "the JWT's claims"}) + return + } + var body struct { + Repositories []string + Permissions map[string]string + } + data, _ := io.ReadAll(r.Body) + if json.Unmarshal(data, &body) != nil || !slices.Equal(body.Repositories, []string{"devvm", "homebrew-tap"}) || + body.Permissions["contents"] != "write" || body.Permissions["actions"] != "read" || len(body.Permissions) != 2 { + f.write(w, http.StatusUnprocessableEntity, map[string]string{"message": "the token's scope: " + string(data)}) + return + } + f.mu.Lock() + f.tokens++ + n := f.tokens + f.mu.Unlock() + f.write(w, http.StatusCreated, map[string]any{"token": "tok-" + strconv.Itoa(n), "expires_at": time.Unix(claims.Iat+60, 0).Add(time.Hour).UTC()}) +} + +func (f *fakeGitHub) list(w http.ResponseWriter, r *http.Request) { + page, _ := strconv.Atoi(r.URL.Query().Get("page")) + per, _ := strconv.Atoi(r.URL.Query().Get("per_page")) + if page < 1 || per != perPage { + f.write(w, http.StatusBadRequest, nil) + return + } + out := []Release{} + for i := len(f.releases) - 1; i >= 0; i-- { // newest first, as GitHub lists them + out = append(out, f.releases[i].json()) + } + lo, hi := min((page-1)*per, len(out)), min(page*per, len(out)) + f.write(w, http.StatusOK, out[lo:hi]) +} + +// create makes a draft release, as GitHub's POST /releases does. +func (f *fakeGitHub) create(w http.ResponseWriter, r *http.Request) { + var body struct { + Tag string `json:"tag_name"` + Target string `json:"target_commitish"` + Name, Body string + Draft bool + Prerelease bool + } + data, _ := io.ReadAll(r.Body) + if json.Unmarshal(data, &body) != nil || body.Tag == "" || !body.Draft { + f.write(w, http.StatusUnprocessableEntity, map[string]string{"message": "the fake makes drafts only: " + string(data)}) + return + } + rel := &fakeRelease{ID: f.id(), Tag: body.Tag, Target: body.Target, Name: body.Name, Body: body.Body, Draft: true, Prerelease: body.Prerelease} + f.releases = append(f.releases, rel) + f.write(w, http.StatusCreated, rel.json()) +} + +// latest is GitHub's latest release: the newest published one that +// wasn't published with make_latest false. +func (f *fakeGitHub) latest(w http.ResponseWriter) { + for i := len(f.releases) - 1; i >= 0; i-- { + if r := f.releases[i]; !r.Draft && !r.Prerelease && r.Latest != "false" { + f.write(w, http.StatusOK, r.json()) + return + } + } + f.write(w, http.StatusNotFound, map[string]string{"message": "Not Found"}) +} + +// byTag is a published release by its tag, as GitHub's +// /releases/tags/, which never shows a draft. +func (f *fakeGitHub) byTag(w http.ResponseWriter, tag string) { + for _, r := range f.releases { + if r.Tag == tag && !r.Draft { + f.write(w, http.StatusOK, r.json()) + return + } + } + f.write(w, http.StatusNotFound, map[string]string{"message": "Not Found"}) +} + +// actions serves the Actions API's runs of a workflow, a run's artifacts +// and an artifact's zip, which redirects to the storage. +func (f *fakeGitHub) actions(w http.ResponseWriter, r *http.Request, p string) { + parts := strings.Split(p, "/") + q := r.URL.Query() + switch { + case len(parts) == 3 && parts[0] == "workflows" && parts[2] == "runs": + page, _ := strconv.Atoi(q.Get("page")) + if page < 1 || q.Get("per_page") != strconv.Itoa(perPage) || q.Get("status") != "success" { + f.write(w, http.StatusBadRequest, nil) + return + } + out := []Run{} + for i := len(f.runs) - 1; i >= 0; i-- { // newest first + if run := f.runs[i]; run.workflow == parts[1] && (q.Get("event") == "" || q.Get("event") == run.Event) { + out = append(out, run.Run) + } + } + lo, hi := min((page-1)*perPage, len(out)), min(page*perPage, len(out)) + f.write(w, http.StatusOK, map[string]any{"total_count": len(out), "workflow_runs": out[lo:hi]}) + case len(parts) == 3 && parts[0] == "runs" && parts[2] == "artifacts": + out := []Artifact{} + for _, run := range f.runs { + if strconv.FormatInt(run.ID, 10) != parts[1] { + continue + } + for _, a := range run.artifacts { + if q.Get("name") == "" || q.Get("name") == a.Name { + out = append(out, a.Artifact) + } + } + } + f.write(w, http.StatusOK, map[string]any{"total_count": len(out), "artifacts": out}) + case len(parts) == 3 && parts[0] == "artifacts" && parts[2] == "zip": + http.Redirect(w, r, f.storage.URL+"/artifact/"+parts[1], http.StatusFound) //nolint:gosec // to the fake's own storage + default: + f.write(w, http.StatusNotFound, map[string]string{"message": "Not Found"}) + } +} + +func (f *fakeGitHub) byID(id string) *fakeRelease { + for _, r := range f.releases { + if strconv.FormatInt(r.ID, 10) == id { + return r + } + } + return nil +} + +func (f *fakeGitHub) releaseCall(w http.ResponseWriter, r *http.Request, id string) { + rel := f.byID(id) + if rel == nil { + f.write(w, http.StatusNotFound, nil) + return + } + switch r.Method { + case http.MethodGet: + f.write(w, http.StatusOK, rel.json()) + case http.MethodPatch: + var body struct { + Draft *bool `json:"draft"` + Prerelease *bool `json:"prerelease"` + MakeLatest string `json:"make_latest"` + } + data, _ := io.ReadAll(r.Body) + if json.Unmarshal(data, &body) != nil || body.Draft == nil || *body.Draft || body.Prerelease == nil { + f.write(w, http.StatusUnprocessableEntity, nil) + return + } + if f.onPublish != nil { + f.onPublish(rel) + } + rel.Draft, rel.Prerelease, rel.Latest = false, *body.Prerelease, body.MakeLatest + if f.publishAnswer != 0 { + f.write(w, f.publishAnswer, map[string]string{"message": "the answer was lost"}) + return + } + f.write(w, http.StatusOK, rel.json()) + default: + f.write(w, http.StatusMethodNotAllowed, nil) + } +} + +func (f *fakeGitHub) assetCall(w http.ResponseWriter, r *http.Request, id string) { + for _, rel := range f.releases { + for i, a := range rel.Assets { + if strconv.FormatInt(a.ID, 10) != id { + continue + } + switch { + case r.Method == http.MethodDelete: + rel.Assets = slices.Delete(rel.Assets, i, i+1) + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodGet && r.Header.Get("Accept") == "application/octet-stream": + http.Redirect(w, r, f.storage.URL+"/"+id, http.StatusFound) //nolint:gosec // to the fake's own storage, by an asset's ID it holds + default: + f.write(w, http.StatusOK, a.Asset) + } + return + } + } + f.write(w, http.StatusNotFound, nil) +} + +func (f *fakeGitHub) upload(w http.ResponseWriter, r *http.Request, id string) { + rel := f.byID(id) + name := r.URL.Query().Get("name") + if rel == nil || r.Method != http.MethodPost || r.Header.Get("Content-Type") != "application/octet-stream" || name == "" { + f.write(w, http.StatusBadRequest, nil) + return + } + if rel.file(name) != nil || slices.ContainsFunc(rel.Assets, func(a *fakeAsset) bool { return a.Name == name }) { + f.write(w, http.StatusUnprocessableEntity, map[string]string{"message": "already_exists"}) + return + } + data, _ := io.ReadAll(r.Body) + a := f.asset(name, data) + if f.failUpload { + f.failUpload = false + a.State, a.data, a.Size, a.Digest = "starter", data[:len(data)/2], int64(len(data)/2), "" + rel.Assets = append(rel.Assets, a) + f.write(w, http.StatusBadGateway, map[string]string{"message": "upstream failure"}) + return + } + rel.Assets = append(rel.Assets, a) + if f.afterUpload != nil { + f.afterUpload(rel) + } + f.write(w, http.StatusCreated, a.Asset) +} + +func (f *fakeGitHub) contents(w http.ResponseWriter, r *http.Request, path string) { + path, _ = url.PathUnescape(path) + blob := func(data []byte) string { s := sha256.Sum256(data); return hexOf(s[:20]) } + switch r.Method { + case http.MethodGet: + data, ok := f.tap[path] + if !ok || r.URL.Query().Get("ref") != "main" { + f.write(w, http.StatusNotFound, map[string]string{"message": "Not Found"}) + return + } + f.write(w, http.StatusOK, map[string]string{"type": "file", "encoding": "base64", "sha": blob(data), "content": base64.StdEncoding.EncodeToString(data)}) + case http.MethodPut: + var body struct{ Message, Content, SHA, Branch string } + data, _ := io.ReadAll(r.Body) + if json.Unmarshal(data, &body) != nil || body.Branch != "main" || body.Message == "" { + f.write(w, http.StatusUnprocessableEntity, nil) + return + } + old, ok := f.tap[path] + if ok && body.SHA != blob(old) || !ok && body.SHA != "" { + f.write(w, http.StatusConflict, map[string]string{"message": "sha mismatch"}) + return + } + content, err := base64.StdEncoding.DecodeString(body.Content) + if err != nil { + f.write(w, http.StatusUnprocessableEntity, nil) + return + } + f.tap[path] = content + f.tapLog = append(f.tapLog, body.Message+": "+path) + status := http.StatusOK + if !ok { + status = http.StatusCreated + } + f.write(w, status, map[string]any{"content": map[string]string{"sha": blob(content)}}) + default: + f.write(w, http.StatusMethodNotAllowed, nil) + } +} + +// fakeTagObject is the tag object the fake's tag names, and the tests' +// builds check, unless the test moved it. +func fakeTagObject(tag string) string { + sum := sha256.Sum256([]byte("tag " + tag)) + return hexOf(sum[:20]) +} + +func hexOf(b []byte) string { + const digits = "0123456789abcdef" + out := make([]byte, 0, 2*len(b)) + for _, c := range b { + out = append(out, digits[c>>4], digits[c&15]) + } + return string(out) +} diff --git a/internal/cosign/github.go b/internal/cosign/github.go new file mode 100644 index 00000000..6161f41d --- /dev/null +++ b/internal/cosign/github.go @@ -0,0 +1,460 @@ +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: 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, "/") +} diff --git a/internal/cosign/github_test.go b/internal/cosign/github_test.go new file mode 100644 index 00000000..615a45fc --- /dev/null +++ b/internal/cosign/github_test.go @@ -0,0 +1,193 @@ +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") + } +} diff --git a/internal/cosign/lock_other.go b/internal/cosign/lock_other.go new file mode 100644 index 00000000..f64bbecf --- /dev/null +++ b/internal/cosign/lock_other.go @@ -0,0 +1,8 @@ +//go:build !unix + +package cosign + +import "errors" + +// Lock fails: the co-signer runs on Linux. +func Lock(string) (func(), error) { return nil, errors.New("devvm-cosign runs on Linux") } diff --git a/internal/cosign/lock_unix.go b/internal/cosign/lock_unix.go new file mode 100644 index 00000000..251d7265 --- /dev/null +++ b/internal/cosign/lock_unix.go @@ -0,0 +1,25 @@ +//go:build unix + +package cosign + +import ( + "fmt" + "os" + "path/filepath" + "syscall" +) + +// Lock takes the state folder's lock for one run, or fails at once when +// another run holds it, such as the timer's while a maintainer runs it by +// hand. The returned func lets it go; so does the process ending. +func Lock(dir string) (func(), error) { + f, err := os.OpenFile(filepath.Join(dir, "lock"), os.O_RDWR|os.O_CREATE, 0o600) //nolint:gosec // the state folder's own lock file + if err != nil { + return nil, err + } + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + _ = f.Close() + return nil, fmt.Errorf("another devvm-cosign run holds %s: %w", f.Name(), err) + } + return func() { _ = f.Close() }, nil +} diff --git a/internal/cosign/manifest.go b/internal/cosign/manifest.go index 6250cd61..16ed0e77 100644 --- a/internal/cosign/manifest.go +++ b/internal/cosign/manifest.go @@ -3,6 +3,8 @@ package cosign import ( "bytes" "cmp" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -213,6 +215,22 @@ func parseIndex(data []byte) (BaseIndex, Manifest, error) { return i, m, nil } +// sha256Hex is data's SHA-256, in hex, as a manifest writes it. +func sha256Hex(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +// sortedKeys is m's keys, sorted: a manifest's files, in order. +func sortedKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + slices.Sort(keys) + return keys +} + // errVersion is a release's version that isn't one release.sh builds. var errVersion = errors.New("not a release's version, x.y.z or x.y.z-.N") diff --git a/internal/cosign/state.go b/internal/cosign/state.go new file mode 100644 index 00000000..a0173924 --- /dev/null +++ b/internal/cosign/state.go @@ -0,0 +1,458 @@ +package cosign + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strconv" +) + +// stateFormat is state.json's format; a file of another is refused. +const stateFormat = 1 + +// errNoState is a state folder with no state.json yet: devvm-cosign init +// writes the first. +var errNoState = errors.New("no state.json: run devvm-cosign init first") + +// State is what the co-signer has signed, so it never signs an older +// release or base than one it signed, nor two different manifests for +// one version or serial, and what it made, published, refused and +// alerted on. It's written whole, and never with less than the file on +// disk holds (Store.Save). +type State struct { + Format int `json:"format"` + Release ReleaseState `json:"release"` + Base BaseState `json:"base"` + // Watermark is the highest release ID GitHub showed when the state was + // made (init): GitHub's IDs only go up, so every release published + // since, whatever its tag, has a higher one, and one that isn't a draft + // the co-signer made is an alert. + Watermark int64 `json:"watermark"` + // InitDrafts are the drafts GitHub showed then, which init didn't + // make: one published later is an alert too, though its ID isn't + // above the watermark. + InitDrafts []int64 `json:"init_drafts"` + // InitLatest is GitHub's latest release when the state was made, 0 for + // none: the latest is that one or one the co-signer published, and an + // older release made the latest since is an alert, as it's what the + // install script's default downloads. + InitLatest int64 `json:"init_latest"` + // Others are the alerts on what isn't one release or base of the + // co-signer's: a release someone else published, by #, and a + // tap formula it didn't write, by tap:@; each key is + // what devvm-cosign ack takes. + Others map[string]Alert `json:"others"` +} + +// A Ledger is what the co-signer did with one kind's manifests, each +// version's or serial's by its key: the version for a release, the serial +// for a base. +type Ledger struct { + // Signed is the SHA-256 of the manifest it signed, by key. + Signed map[string]string `json:"signed"` + // Refused is each manifest whose rebuild didn't match, by its SHA-256. + Refused map[string]Refusal `json:"refused"` + // Drafts are the draft releases it made for each key, by GitHub's ID, + // the last the one it uses: one deleted by hand is made again. + Drafts map[string][]int64 `json:"drafts"` + // Published is each key it published, its files checked after. + Published map[string]bool `json:"published"` + // Alerts are what it found wrong with a key that a maintainer must + // look at, such as a release published by someone else. + Alerts map[string]Alert `json:"alerts"` + // Runs is the key of each CI run whose manifest it signed, by the + // run's ID, so a run it's done with isn't downloaded again. + Runs map[string]string `json:"runs"` +} + +// A Refusal is a manifest whose rebuild didn't match, or failed +// maxBuildFailures times in a row: never rebuilt again on its own, but +// once for each devvm-cosign retry. +type Refusal struct { + // Key is its version or serial, and Run the CI run it came from last. + Key string `json:"key"` + Run int64 `json:"run"` + // Times is how many times it was refused, and Retried how many of + // those a maintainer cleared with devvm-cosign retry. + Times int `json:"times"` + Retried int `json:"retried"` + // Failed is how many of its builds in a row failed, rather than + // differed, since it was last refused: the count that refuses it, which + // alone may go back, as a lower count only builds it more. Why is the + // last refusal's cause when a failed build refused it, "" when a + // mismatch did. + Failed int `json:"failed,omitempty"` + Why string `json:"why,omitempty"` +} + +// active is whether r still refuses its manifest. +func (r Refusal) active() bool { return r.Times > r.Retried } + +// maxBuildFailures is how many builds of one manifest in a row may fail +// before it's refused: a failure is often the machine's, a download cut +// short or a full disk, so it's built again at the next run, but one that +// keeps failing would take every run's one build, and hold up each newer +// release and base. +const maxBuildFailures = 3 + +// An Alert is a key the co-signer stops at until a maintainer has looked: +// devvm-cosign ack clears the alerts raised so far, and a new one raises +// it again. +type Alert struct { + Reason string `json:"reason"` + Raised int `json:"raised"` + Acked int `json:"acked"` +} + +// active is whether a is still waiting for a maintainer. +func (a Alert) active() bool { return a.Raised > a.Acked } + +// ReleaseState is the releases the co-signer signed. +type ReleaseState struct { + // Last is the newest version it signed, or the newest published one + // when the state was made (init); it signs only newer ones. + Last string `json:"last"` + Ledger + // Done is the versions whose tap it updated, after publishing them. + Done map[string]bool `json:"done"` + // Kept is the SHA-256 of each file it kept for a release it signed, + // its formulas and notes, by /, so one changed on disk + // between runs is refused. + Kept map[string]string `json:"kept"` + // Tags is the tag object each signed version's rebuild checked, which + // the tag must still name when its release is published. + Tags map[string]string `json:"tags"` +} + +// BaseState is the bases the co-signer signed. +type BaseState struct { + // Last is the highest serial it signed, or the one init found. + Last uint64 `json:"last"` + Ledger + // Checked is the SHA-256 of every base file a rebuild of the + // co-signer's own matched, with the serial it was first in, so an + // unchanged base is re-signed with a new serial and expiry without + // another rebuild. + Checked map[string]uint64 `json:"checked"` + // Shape is the SHA-256 of the last index it signed with its serial and + // expiry left out (BaseIndex.shape): only an index of that shape, the + // same files, commit, snapshot and format, is re-signed without a + // rebuild, so an older base's files can't come back with a new serial. + Shape string `json:"shape"` +} + +// newState is an empty state, from last, the newest release published, +// and serial, the highest base's. +func newState(last string, serial uint64) State { + s := State{Format: stateFormat, Release: ReleaseState{Last: last}, Base: BaseState{Last: serial}} + s.fill() + return s +} + +// fill gives s's maps a value, so a state read from a file with none can +// be added to. +func (s *State) fill() { + s.Release.fill() + s.Base.fill() + if s.Release.Kept == nil { + s.Release.Kept = map[string]string{} + } + if s.Release.Tags == nil { + s.Release.Tags = map[string]string{} + } + if s.Release.Done == nil { + s.Release.Done = map[string]bool{} + } + if s.Base.Checked == nil { + s.Base.Checked = map[string]uint64{} + } + if s.Others == nil { + s.Others = map[string]Alert{} + } +} + +func (l *Ledger) fill() { + if l.Signed == nil { + l.Signed = map[string]string{} + } + if l.Refused == nil { + l.Refused = map[string]Refusal{} + } + if l.Drafts == nil { + l.Drafts = map[string][]int64{} + } + if l.Published == nil { + l.Published = map[string]bool{} + } + if l.Alerts == nil { + l.Alerts = map[string]Alert{} + } + if l.Runs == nil { + l.Runs = map[string]string{} + } +} + +// draft is the draft release the co-signer made for key, 0 for none. +func (l *Ledger) draft(key string) int64 { + if ids := l.Drafts[key]; len(ids) > 0 { + return ids[len(ids)-1] + } + return 0 +} + +// refuse records manifest sum, key's from CI's run, as refused once more, +// as its rebuild didn't match. +func (l *Ledger) refuse(sum, key string, run int64) { + r := l.Refused[sum] + r.Key, r.Run, r.Times, r.Failed, r.Why = key, run, r.Times+1, 0, "" + l.Refused[sum] = r +} + +// failed records that a build of manifest sum, key's from CI's run, +// failed with why, and refuses it at the maxBuildFailures'th in a row; it +// says whether it refused it. +func (l *Ledger) failed(sum, key string, run int64, why string) bool { + r := l.Refused[sum] + r.Key, r.Run, r.Failed = key, run, r.Failed+1 + refused := r.Failed >= maxBuildFailures + if refused { + r.Times, r.Failed, r.Why = r.Times+1, 0, why + } + l.Refused[sum] = r + return refused +} + +// refusedRun is whether a refusal still holds for CI's run, so its +// artifact needn't be downloaded again to be refused. +func (l *Ledger) refusedRun(run int64) (string, bool) { + for sum, r := range l.Refused { + if r.Run == run && r.active() { + return sum, true + } + } + return "", false +} + +// retry clears key's refusals, and says how many it cleared. +func (l *Ledger) retry(key string) int { + n := 0 + for sum, r := range l.Refused { + if r.Key == key && r.active() { + r.Retried = r.Times + l.Refused[sum] = r + n++ + } + } + return n +} + +// alert raises key's alert, for reason. +func (l *Ledger) alert(key, reason string) { + a := l.Alerts[key] + a.Reason, a.Raised = reason, a.Raised+1 + l.Alerts[key] = a +} + +// ack clears key's alert, and says whether there was one to clear. +func (l *Ledger) ack(key string) bool { + a, ok := l.Alerts[key] + if !ok || !a.active() { + return false + } + a.Acked = a.Raised + l.Alerts[key] = a + return true +} + +// check is whether s is a state the co-signer could have written: its +// format, a version for Last, and nothing signed past Last. +func (s State) check() error { + if s.Format != stateFormat { + return fmt.Errorf("state.json's format is %d, not %d", s.Format, stateFormat) + } + last, err := parseVersion(s.Release.Last) + if err != nil { + return fmt.Errorf("state.json's last release: %w", err) + } + for v := range s.Release.Signed { + sv, err := parseVersion(v) + if err != nil || sv.compare(last) > 0 { + return fmt.Errorf("state.json signed %q, past its last release %s", v, s.Release.Last) + } + } + for serial := range s.Base.Signed { + n, err := strconv.ParseUint(serial, 10, 64) + if err != nil || n > s.Base.Last { + return fmt.Errorf("state.json signed base %q, past its last serial %d", serial, s.Base.Last) + } + } + for _, l := range []Ledger{s.Release.Ledger, s.Base.Ledger} { + for key := range l.Published { + if l.Signed[key] == "" { + return fmt.Errorf("state.json published %q, which it didn't sign", key) + } + } + } + return nil +} + +// behind is why s holds less than was, the state on disk, which a save +// must never do: an older last release or serial, or a signature, a +// draft, a publish, a tap, a kept file or a checked file it dropped or +// changed, or a refusal or alert counted back. +func (s State) behind(was State) error { + last, err := parseVersion(s.Release.Last) + if err != nil { + return err + } + wasLast, err := parseVersion(was.Release.Last) + if err != nil { + return err + } + switch { + case last.compare(wasLast) < 0: + return fmt.Errorf("its last release %s is older than %s", s.Release.Last, was.Release.Last) + case s.Base.Last < was.Base.Last: + return fmt.Errorf("its last base %d is older than %d", s.Base.Last, was.Base.Last) + case s.Watermark != was.Watermark || !slices.Equal(s.InitDrafts, was.InitDrafts) || s.InitLatest != was.InitLatest: + return fmt.Errorf("its watermark %d, drafts or latest release at init aren't the %d and the ones init recorded", s.Watermark, was.Watermark) + case !kept(was.Others, s.Others, func(w, n Alert) bool { return n.Raised >= w.Raised && n.Acked >= w.Acked }): + return errors.New("it drops or counts back an alert on a release or a tap formula it didn't make") + case !s.Release.keeps(was.Release.Ledger) || !s.Base.keeps(was.Base.Ledger) || + !kept(was.Release.Done, s.Release.Done, same) || !kept(was.Release.Kept, s.Release.Kept, same) || !kept(was.Release.Tags, s.Release.Tags, same) || + !kept(was.Base.Checked, s.Base.Checked, same): + return errors.New("it drops or changes what the file on disk records") + } + return nil +} + +// keeps is whether l holds everything was does: each draft list as a +// prefix, and each refusal and alert counted no lower. +func (l Ledger) keeps(was Ledger) bool { + return kept(was.Signed, l.Signed, same) && kept(was.Published, l.Published, same) && kept(was.Runs, l.Runs, same) && + kept(was.Drafts, l.Drafts, func(w, n []int64) bool { return len(n) >= len(w) && slices.Equal(n[:len(w)], w) }) && + kept(was.Refused, l.Refused, func(w, n Refusal) bool { return n.Key == w.Key && n.Times >= w.Times && n.Retried >= w.Retried }) && + kept(was.Alerts, l.Alerts, func(w, n Alert) bool { return n.Raised >= w.Raised && n.Acked >= w.Acked }) +} + +func same[V comparable](was, now V) bool { return was == now } + +// kept is whether now holds every entry of was, each one ok with its +// value there. +func kept[V any](was, now map[string]V, ok func(was, now V) bool) bool { + for k, v := range was { + if w, found := now[k]; !found || !ok(v, w) { + return false + } + } + return true +} + +// A Store is state.json, in the co-signer's state folder. +type Store struct { + Path string +} + +// maxState bounds state.json: years of releases and bases are far under. +const maxState = 16 << 20 + +// Load reads the state, checked; errNoState when there's none. +func (st Store) Load() (State, error) { + f, err := os.Open(st.Path) + if errors.Is(err, fs.ErrNotExist) { + return State{}, errNoState + } else if err != nil { + return State{}, err + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, maxState+1)) + if err != nil { + return State{}, fmt.Errorf("reading %s: %w", st.Path, err) + } + if len(data) > maxState { + return State{}, fmt.Errorf("%s is over %d bytes", st.Path, maxState) + } + dec := json.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + var s State + if err := dec.Decode(&s); err != nil { + return State{}, fmt.Errorf("reading %s: %w", st.Path, err) + } + s.fill() + if err := s.check(); err != nil { + return State{}, fmt.Errorf("%s: %w", st.Path, err) + } + return s, nil +} + +// Save writes s whole, replacing the file at once (a temp file, synced, +// then renamed, and the folder synced), so a crash leaves the old state +// or the new one. It refuses a state that's behind the file on disk, as a +// replayed or restored older state would be, and one that doesn't check +// out. +func (st Store) Save(s State) error { + if err := s.check(); err != nil { + return err + } + was, err := st.Load() + switch { + case errors.Is(err, errNoState): + case err != nil: + return err + default: + if err := s.behind(was); err != nil { + return fmt.Errorf("refusing to write %s, as it would go backwards: %w", st.Path, err) + } + } + data, _ := json.MarshalIndent(s, "", " ") + return writeWhole(st.Path, append(data, '\n'), 0o600) +} + +// writeWhole writes data to path through a temp file beside it, synced, +// then renamed over path, with mode, and syncs the folder, so a reader +// sees the old file or the new one, never part of either, and a crash +// after it returns can't lose the rename: state.json records a version +// before its signature is uploaded. +func writeWhole(path string, data []byte, mode os.FileMode) error { + f, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*") + if err != nil { + return err + } + // The first error is the one returned: the temp file is closed and + // removed after any. + if err = f.Chmod(mode); err == nil { + if _, err = f.Write(data); err == nil { + err = f.Sync() + } + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + _ = os.Remove(f.Name()) + return err + } + if err := os.Rename(f.Name(), path); err != nil { + return err + } + return syncDir(filepath.Dir(path)) +} + +// syncDir syncs the folder dir, so a rename in it is on disk. +func syncDir(dir string) error { + d, err := os.Open(dir) //nolint:gosec // the folder of a file the co-signer just wrote + if err != nil { + return err + } + defer d.Close() + if err := d.Sync(); err != nil { + return fmt.Errorf("syncing %s: %w", dir, err) + } + return nil +} diff --git a/internal/cosign/state_test.go b/internal/cosign/state_test.go new file mode 100644 index 00000000..606f1940 --- /dev/null +++ b/internal/cosign/state_test.go @@ -0,0 +1,205 @@ +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) + } +}