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, "/") }