Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Skip GitHub comment errors when issues or PRs are off (#5467)
Kashif Khan291e3f03c3c6
diff --git a/pkg/sources/github/comments_test.go b/pkg/sources/github/comments_test.goindex 539213dff..c7f1ff7af 100644--- a/pkg/sources/github/comments_test.go+++ b/pkg/sources/github/comments_test.go@@ -516,6 +516,101 @@ func TestCommentScan_SkippedListingNeedingBothPermissionsSaysSo(t *testing.T) {assert.Contains(t, err.Error(), "issues and pull requests: missing GitHub App permission: Issues (read) and Pull requests (read) are needed;")}+// respondWith returns a fail func that answers every request with status,+// the way GitHub answers listings for a feature the repo has turned off.+func respondWith(status int) func(int, http.ResponseWriter, *http.Request) bool {+ return func(_ int, w http.ResponseWriter, _ *http.Request) bool {+ writeJSON(w, status, map[string]string{"message": http.StatusText(status)})+ return true+ }+}++func TestCommentScan_IssueCommentsDisabledWhenRepoHasNoIssues(t *testing.T) {+ for _, status := range []int{http.StatusNotFound, http.StatusGone} {+ t.Run(http.StatusText(status), func(t *testing.T) {+ // Issues and pull requests are both off: /issues is empty and+ // /issues/comments refuses, but old review comments remain.+ gh := newFakeGitHub(t)+ gh.issueComments.fail = respondWith(status)+ gh.prComments.records = []fakeRecord{+ commentRecord(200, testEpoch, "https://github.com/o/r/pull/2#discussion_r200"),+ }+ s := &Source{includeIssueComments: true, includePRComments: true}+ repo := testRepo+ repo.hasNoIssues = true+ reporter := &collectingReporter{}++ err := s.processIssueandPRsWithCommentsREST(context.Background(), gh.client, repo, nil, reporter, nil)++ require.NoError(t, err)+ assert.Equal(t, []string{"https://github.com/o/r/pull/2#discussion_r200"}, reporter.links)+ })+ }+}++func TestCommentScan_IssueCommentsNotFoundIsReportedWhenIssuesAreOn(t *testing.T) {+ gh := newFakeGitHub(t)+ gh.issueComments.fail = respondWith(http.StatusNotFound)+ s := &Source{includeIssueComments: true}++ _, err := scanComments(t, s, gh, nil)++ require.Error(t, err)+ assert.Contains(t, err.Error(), "issue comments:")+ assert.Contains(t, err.Error(), "404")+}++func TestCommentScan_PullsDisabledStillListsReviewComments(t *testing.T) {+ gh := newFakeGitHub(t)+ gh.pulls.fail = respondWith(http.StatusNotFound)+ gh.prComments.records = []fakeRecord{+ commentRecord(200, testEpoch, "https://github.com/o/r/pull/2#discussion_r200"),+ }+ s := &Source{includePRComments: true}++ reporter, err := scanComments(t, s, gh, nil)++ require.NoError(t, err)+ assert.Equal(t, []string{"https://github.com/o/r/pull/2#discussion_r200"}, reporter.links)+ assert.Equal(t, 1, gh.prComments.requestCount())+}++func TestCommentScan_NoPullRequestsSkipsReviewComments(t *testing.T) {+ gh := newFakeGitHub(t)+ s := &Source{includePRComments: true}++ reporter, err := scanComments(t, s, gh, nil)++ require.NoError(t, err)+ assert.Empty(t, reporter.links)+ assert.Equal(t, 1, gh.pulls.requestCount())+ assert.Zero(t, gh.prComments.requestCount())+}++func TestCacheRepoInfo_HasNoIssues(t *testing.T) {+ off, on := false, true+ tests := []struct {+ name string+ hasIssues *bool+ want bool+ }{+ {name: "issues off", hasIssues: &off, want: true},+ {name: "issues on", hasIssues: &on, want: false},+ {name: "field missing", hasIssues: nil, want: false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ s := &Source{repoInfoCache: newRepoInfoCache()}+ cloneURL := "https://github.com/o/r.git"+ s.cacheRepoInfo(&github.Repository{CloneURL: &cloneURL, HasIssues: tt.hasIssues})++ info, ok := s.repoInfoCache.get(cloneURL)+ require.True(t, ok)+ assert.Equal(t, tt.want, info.hasNoIssues)+ })+ }+}+func TestReportCommentErrors_UnjoinedErrorIsReportedOnce(t *testing.T) {reporter := &collectingReporter{}diff --git a/pkg/sources/github/github.go b/pkg/sources/github/github.goindex bdfa96a6b..c8af360a5 100644--- a/pkg/sources/github/github.go+++ b/pkg/sources/github/github.go@@ -2096,9 +2096,20 @@ func (s *Source) processIssueandPRsWithCommentsREST(narrowed := func(missing, listing string, needs permission) error {return fmt.Errorf("%s: %w", missing, newNarrowedListingError(installationID, listing, []permission{needs}))}+ // noPRs is set when /pulls ran and found nothing. Its state=all listing+ // then shows the repo has no pull requests, so it has no review comments+ // either. A 404 or 410 means pull requests are off, which is different:+ // /pulls/comments still serves review comments from before that.+ var noPRs boolpullsPhase := func(startLog string) commentPhase {return commentPhase{name: "pull requests", startLog: startLog, run: func() (int, error) {- return s.processPRs(ctx, p, repoInfo, reporter)+ emitted, err := s.processPRs(ctx, p, repoInfo, reporter)+ if isGitHubListingDisabled(err) {+ ctx.Logger().V(2).Info("pull requests listing disabled for repo, skipping")+ return emitted, nil+ }+ noPRs = err == nil && emitted == 0+ return emitted, err}}}@@ -2163,6 +2174,10 @@ func (s *Source) processIssueandPRsWithCommentsREST(prStartLog = ""}phases = append(phases, commentPhase{name: "pull request comments", startLog: prStartLog, skipped: prsSkipped, run: func() (int, error) {+ if noPRs {+ ctx.Logger().V(2).Info("no pull requests in repo, skipping pull request comments")+ return 0, nil+ }return s.processPRComments(ctx, p, repoInfo, reporter, since)}})}@@ -2312,8 +2327,12 @@ func (s *Source) chunkIssues(ctx context.Context, repoInfo repoInfo, issues []*g// after since. /issues/comments also returns comments on pull requests, since// GitHub treats every pull request as an issue. The endpoint stops at 300// pages, so the walk continues past that cap in since windows.+//+// When both issues and pull requests are off, GitHub answers 404 here. That+// is only treated as empty when the repo also reports issues off, so an+// unexpected 404 is still reported.func (s *Source) processIssueComments(ctx context.Context, p pager, repoInfo repoInfo, reporter sources.ChunkReporter, since time.Time) (int, error) {- return walkUpdatedSince(ctx, p, sinceWalk[*github.IssueComment]{+ emitted, err := walkUpdatedSince(ctx, p, sinceWalk[*github.IssueComment]{name: "issue comments",since: since,list: func(ctx context.Context, since time.Time) ([]*github.IssueComment, *github.Response, error) {@@ -2335,6 +2354,11 @@ func (s *Source) processIssueComments(ctx context.Context, p pager, repoInfo repreturn s.chunkIssueComments(ctx, repoInfo, comments, reporter)},})+ if err != nil && repoInfo.hasNoIssues && isGitHubListingDisabled(err) {+ ctx.Logger().V(2).Info("issue comments listing disabled for repo, skipping")+ return emitted, nil+ }+ return emitted, err}// chunkIssueComments emits a chunk for each comment. The comments timeframediff --git a/pkg/sources/github/repo.go b/pkg/sources/github/repo.goindex a74698a09..5c62f2ede 100644--- a/pkg/sources/github/repo.go+++ b/pkg/sources/github/repo.go@@ -58,6 +58,10 @@ type repoInfo struct {size int // size of the repository in kilobytes.visibility source_metadatapb.Visibility // visibility of the repository (public/private).hasWiki bool // whether the repository is likely to have a wiki.+ // hasNoIssues is true only when GitHub said issues are off. The zero+ // value means scan as usual, so a missing has_issues never turns+ // anything off.+ hasNoIssues bool}// cloneRepo clones a repository given its URL, returns the path and the repository object.@@ -240,6 +244,17 @@ func isGitHub404Error(err error) bool {return ghErr.Response.StatusCode == http.StatusNotFound}+// isGitHubListingDisabled reports whether a listing failed because the repo+// has the feature turned off. GitHub answers with 404 or 410 for that.+func isGitHubListingDisabled(err error) bool {+ var ghErr *github.ErrorResponse+ if !errors.As(err, &ghErr) || ghErr.Response == nil {+ return false+ }+ code := ghErr.Response.StatusCode+ return code == http.StatusNotFound || code == http.StatusGone+}+// processRepos processes repositories from a source, handling pagination and rate limits.func (s *Source) processRepos(ctx context.Context, target string, reporter sources.UnitReporter, listRepos repoLister, listOpts repoListOptions) error {logger := ctx.Logger().WithValues("target", target)@@ -338,11 +353,12 @@ func (s *Source) processRepos(ctx context.Context, target string, reporter sourc// cacheRepoInfo caches basic information about a repository for later use.func (s *Source) cacheRepoInfo(r *github.Repository) {info := repoInfo{- owner: r.GetOwner().GetLogin(),- name: r.GetName(),- fullName: r.GetFullName(),- hasWiki: r.GetHasWiki(),- size: r.GetSize(),+ owner: r.GetOwner().GetLogin(),+ name: r.GetName(),+ fullName: r.GetFullName(),+ hasWiki: r.GetHasWiki(),+ hasNoIssues: r.HasIssues != nil && !*r.HasIssues,+ size: r.GetSize(),}if r.GetPrivate() {info.visibility = source_metadatapb.Visibility_private