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) }