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