Skip to content

Find, verify, and analyze leaked credentials

github: name the missing permission when a comment listing is refused (#5438)

Dave Hubbarde63326d6545d
diff --git a/pkg/sources/github/comments_test.go b/pkg/sources/github/comments_test.go
index 77f66d237..c3166b6cb 100644
--- a/pkg/sources/github/comments_test.go
+++ b/pkg/sources/github/comments_test.go
@@ -3,6 +3,7 @@ package github
import (
"bytes"
"encoding/json"
+ "errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -54,10 +55,12 @@ func newFakeGitHub(t *testing.T) *fakeGitHub {
var testRepo = repoInfo{owner: "o", name: "r", fullName: "o/r"}
-// collectingReporter records the link of every chunk the scan emits.
+// collectingReporter records the link of every chunk the scan emits, and every
+// chunk error it reports.
type collectingReporter struct {
mu sync.Mutex
links []string
+ errs []error
}
func (r *collectingReporter) ChunkOk(_ context.Context, chunk sources.Chunk) error {
@@ -67,7 +70,12 @@ func (r *collectingReporter) ChunkOk(_ context.Context, chunk sources.Chunk) err
return nil
}
-func (r *collectingReporter) ChunkErr(context.Context, error) error { return nil }
+func (r *collectingReporter) ChunkErr(_ context.Context, err error) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.errs = append(r.errs, err)
+ return nil
+}
func issueRecord(number int, updated time.Time) fakeRecord {
return fakeRecord{updated: updated, body: map[string]any{
@@ -311,6 +319,53 @@ func TestCommentScan_FailedPhaseDoesNotStopTheOthers(t *testing.T) {
}, reporter.links)
}
+// deniedWith returns a fail func that refuses every request the way GitHub
+// refuses a GitHub App that lacks a permission, naming accepted as what the
+// endpoint requires.
+func deniedWith(accepted string) func(int, http.ResponseWriter, *http.Request) bool {
+ return func(_ int, w http.ResponseWriter, _ *http.Request) bool {
+ w.Header().Set(acceptedPermissionsHeader, accepted)
+ writeJSON(w, http.StatusForbidden, map[string]string{"message": appDeniedMessage})
+ return true
+ }
+}
+
+func TestCommentScan_EachFailedPhaseIsReportedAsItsOwnChunkError(t *testing.T) {
+ gh := newFakeGitHub(t)
+ seedRepo(gh)
+ gh.issues.fail = deniedWith("issues=read")
+ gh.issueComments.fail = deniedWith("issues=read; pull_requests=read")
+ gh.prComments.fail = deniedWith("pull_requests=read")
+ s := &Source{includeIssueComments: true, includePRComments: true}
+
+ reporter, err := scanComments(t, s, gh, nil)
+ require.Error(t, err)
+ require.NoError(t, reportCommentErrors(context.Background(), reporter, err))
+
+ require.Len(t, reporter.errs, 3)
+ wantPrefixes := []string{
+ "error scanning comments: issues and pull requests: walk incomplete after 0 items: missing GitHub App permission: the request needs Issues (read);",
+ "error scanning comments: issue comments: walk incomplete after 0 items: missing GitHub App permission: the request needs Issues (read) or Pull requests (read);",
+ "error scanning comments: pull request comments: walk incomplete after 0 items: missing GitHub App permission: the request needs Pull requests (read);",
+ }
+ for i, reported := range reporter.errs {
+ assert.True(t, strings.HasPrefix(reported.Error(), wantPrefixes[i]), "got %q", reported.Error())
+ assert.NotContains(t, reported.Error(), "\n", "each chunk error covers one phase")
+ var permErr *permissionError
+ assert.ErrorAs(t, reported, &permErr)
+ }
+ assert.Empty(t, reporter.links)
+}
+
+func TestReportCommentErrors_UnjoinedErrorIsReportedOnce(t *testing.T) {
+ reporter := &collectingReporter{}
+
+ require.NoError(t, reportCommentErrors(context.Background(), reporter, errors.New("could not get API client")))
+
+ require.Len(t, reporter.errs, 1)
+ assert.EqualError(t, reporter.errs[0], "error scanning comments: could not get API client")
+}
+
func TestCommentScan_RetryLogNamesTheListing(t *testing.T) {
gh := newFakeGitHub(t)
seedRepo(gh)
diff --git a/pkg/sources/github/github.go b/pkg/sources/github/github.go
index dbe3a0fd0..5192e1abd 100644
--- a/pkg/sources/github/github.go
+++ b/pkg/sources/github/github.go
@@ -1396,8 +1396,7 @@ func (s *Source) scanRepo(ctx context.Context, repoURL string, reporter sources.
err := s.scanComments(ctx, repoURL, repoInfo, reporter)
commentsDuration = time.Since(commentsStart)
if err != nil {
- err := fmt.Errorf("error scanning comments: %w", err)
- if err := reporter.ChunkErr(ctx, err); err != nil {
+ if err := reportCommentErrors(ctx, reporter, err); err != nil {
return err
}
}
@@ -1782,6 +1781,25 @@ func (s *Source) setProgressCompleteWithRepo(index int, offset int, repoURL stri
s.SetProgressComplete(index+offset, len(s.repos)+offset, fmt.Sprintf("Repo: %s", repoURL), encodedResumeInfo)
}
+// reportCommentErrors reports a failed comment scan as chunk errors, one per
+// failed phase. processIssueandPRsWithCommentsREST joins one error per phase
+// that failed, and each phase is a separate listing that failed for its own
+// reason, often a different missing permission. Reporting them separately
+// gives each its own entry and its own "error scanning comments" context,
+// instead of one entry whose later lines have neither.
+func reportCommentErrors(ctx context.Context, reporter sources.ChunkReporter, err error) error {
+ phaseErrs := []error{err}
+ if joined, ok := err.(interface{ Unwrap() []error }); ok {
+ phaseErrs = joined.Unwrap()
+ }
+ for _, phaseErr := range phaseErrs {
+ if err := reporter.ChunkErr(ctx, fmt.Errorf("error scanning comments: %w", phaseErr)); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
func (s *Source) scanComments(ctx context.Context, repoPath string, repoInfo repoInfo, reporter sources.ChunkReporter) error {
urlString, urlParts, err := getRepoURLParts(repoPath)
if err != nil {
@@ -2015,8 +2033,9 @@ type commentPhase struct {
//
// The phases are independent: a failure in one is collected and the rest
// still run, so one capped or forbidden endpoint can't hide the others. All
-// failures come back joined into one error, which scanRepo reports as a
-// single ChunkErr for the repo. Chunks emitted before a failure are kept.
+// failures come back joined into one error, which scanRepo splits back apart
+// so each failed phase is its own ChunkErr (see reportCommentErrors). Chunks
+// emitted before a failure are kept.
//
// The "Scanning issues" and "Scanning pull requests" V(2) lines are the only
// log signal for scans on the unit path, whose comment errors go to the scan
diff --git a/pkg/sources/github/pagination.go b/pkg/sources/github/pagination.go
index d030e4b84..998296020 100644
--- a/pkg/sources/github/pagination.go
+++ b/pkg/sources/github/pagination.go
@@ -286,6 +286,10 @@ func transientBackoff(retry int) time.Duration {
// "giving up after N attempt(s)". Each attempt here is bounded by the
// client's 60 second timeout, so a page that keeps failing is reported after
// several minutes rather than retried indefinitely.
+//
+// Every page of every walk returns through here, so this is also where a 403
+// for a missing permission becomes a permissionError naming that permission.
+// It is never retried: the credential's permissions won't change mid-walk.
func fetchWithRetry[T any](ctx context.Context, p pager, fetch func() ([]T, *github.Response, error)) ([]T, *github.Response, error) {
transientRetries := 0
for {
@@ -294,7 +298,7 @@ func fetchWithRetry[T any](ctx context.Context, p pager, fetch func() ([]T, *git
continue
}
if err == nil || p.wait == nil || !isTransient(ctx, err) {
- return items, resp, err
+ return items, resp, asPermissionError(err)
}
if transientRetries == maxTransientRetries {
return items, resp, fmt.Errorf("giving up after %d attempts: %w", transientRetries+1, err)
diff --git a/pkg/sources/github/permission_error.go b/pkg/sources/github/permission_error.go
new file mode 100644
index 000000000..ed0e27206
--- /dev/null
+++ b/pkg/sources/github/permission_error.go
@@ -0,0 +1,176 @@
+package github
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/google/go-github/v67/github"
+)
+
+// acceptedPermissionsHeader is the response header in which GitHub names what
+// an endpoint requires. GitHub refuses a request the credential isn't
+// permitted to make with a 403 ("Resource not accessible by integration" for
+// GitHub App tokens, "...by personal access token" for fine-grained tokens)
+// that carries this header. The raw error doesn't say which permission is
+// missing, so comment walks rewrite these 403s into a permissionError that
+// does. The header's value is a comma-separated list of permissions that are
+// all required; a semicolon separates alternative lists, any one of which is
+// enough. See
+// https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api#resource-not-accessible
+const acceptedPermissionsHeader = "X-Accepted-GitHub-Permissions"
+
+// permission is one entry of the header, such as issues=read.
+type permission struct {
+ name string
+ access string
+}
+
+// String renders the permission the way GitHub's settings pages label it, for
+// example "Pull requests (read)".
+func (p permission) String() string {
+ label := strings.ReplaceAll(p.name, "_", " ")
+ return fmt.Sprintf("%s%s (%s)", strings.ToUpper(label[:1]), label[1:], p.access)
+}
+
+// credentialKind is the kind of credential GitHub says it refused, read from
+// the 403's message. The fix differs: an app's permissions are changed by its
+// owner and then accepted on each installation, while a fine-grained token's
+// are changed on the token.
+type credentialKind int
+
+const (
+ credentialUnknown credentialKind = iota
+ credentialApp
+ credentialFineGrainedToken
+)
+
+// permissionError reports a request GitHub refused because the credential
+// lacks a permission. accepted holds the permission sets that would satisfy
+// the endpoint: any one set is enough, and a set needs every permission in it.
+// method and path identify the request, and message is GitHub's own error
+// text, kept so the error still reads like the 403 it replaces.
+type permissionError struct {
+ accepted [][]permission
+ credential credentialKind
+ method string
+ path string
+ message string
+ err error
+}
+
+func (e *permissionError) Error() string {
+ var subject, fix string
+ switch e.credential {
+ case credentialApp:
+ subject = "missing GitHub App permission"
+ fix = "update the app's permissions and accept the change on the installation"
+ case credentialFineGrainedToken:
+ subject = "missing personal access token permission"
+ fix = "update the token's permissions"
+ default:
+ subject = "missing GitHub permission"
+ fix = "update the credential's permissions"
+ }
+
+ request := "request"
+ if e.path != "" {
+ request = e.method + " " + e.path
+ }
+ return fmt.Sprintf("%s: the request needs %s; %s (%s returned 403 %s)",
+ subject, describeAccepted(e.accepted), fix, request, e.message)
+}
+
+func (e *permissionError) Unwrap() error { return e.err }
+
+// asPermissionError returns err as a *permissionError when it is a 403 that
+// names the permissions it wanted, and returns err unchanged otherwise. 403s
+// without the header pass through as they are: rate limits arrive as their own
+// error types, and SAML enforcement, IP allow lists, and GitHub Enterprise
+// Server versions that don't send the header leave nothing to name.
+func asPermissionError(err error) error {
+ var errResp *github.ErrorResponse
+ if !errors.As(err, &errResp) || errResp.Response == nil || errResp.Response.StatusCode != http.StatusForbidden {
+ return err
+ }
+ accepted := parseAcceptedPermissions(errResp.Response.Header.Get(acceptedPermissionsHeader))
+ if len(accepted) == 0 {
+ return err
+ }
+
+ permErr := &permissionError{
+ accepted: accepted,
+ credential: credentialFromMessage(errResp.Message),
+ message: errResp.Message,
+ err: err,
+ }
+ if req := errResp.Response.Request; req != nil && req.URL != nil {
+ permErr.method = req.Method
+ permErr.path = req.URL.Path
+ }
+ return permErr
+}
+
+// parseAcceptedPermissions parses an acceptedPermissionsHeader value into its
+// alternative permission sets. A value that doesn't parse cleanly returns
+// nil, so a format change on GitHub's side leaves the original 403 intact
+// rather than producing a message that names the wrong permissions.
+func parseAcceptedPermissions(header string) [][]permission {
+ if strings.TrimSpace(header) == "" {
+ return nil
+ }
+ var sets [][]permission
+ for _, rawSet := range strings.Split(header, ";") {
+ var set []permission
+ for _, entry := range strings.Split(rawSet, ",") {
+ name, access, ok := strings.Cut(entry, "=")
+ name, access = strings.TrimSpace(name), strings.TrimSpace(access)
+ if !ok || name == "" || access == "" {
+ return nil
+ }
+ set = append(set, permission{name: name, access: access})
+ }
+ sets = append(sets, set)
+ }
+ return sets
+}
+
+// describeAccepted renders the accepted permission sets as a phrase:
+// "Issues (read)", "Pull requests (write) and Contents (read)", "Issues (read)
+// or Pull requests (read)", or, when an alternative needs more than one
+// permission, "either A (read) and B (read), or C (read) and B (read)".
+func describeAccepted(sets [][]permission) string {
+ described := make([]string, len(sets))
+ compound := false
+ for i, set := range sets {
+ names := make([]string, len(set))
+ for j, p := range set {
+ names[j] = p.String()
+ }
+ described[i] = strings.Join(names, " and ")
+ compound = compound || len(set) > 1
+ }
+ switch {
+ case len(described) == 1:
+ return described[0]
+ case compound:
+ return "either " + strings.Join(described, ", or ")
+ default:
+ return strings.Join(described, " or ")
+ }
+}
+
+// credentialFromMessage reads which kind of credential GitHub refused from the
+// 403's message.
+func credentialFromMessage(message string) credentialKind {
+ lower := strings.ToLower(message)
+ switch {
+ case strings.Contains(lower, "by integration"):
+ return credentialApp
+ case strings.Contains(lower, "by personal access token"):
+ return credentialFineGrainedToken
+ default:
+ return credentialUnknown
+ }
+}
diff --git a/pkg/sources/github/permission_error_test.go b/pkg/sources/github/permission_error_test.go
new file mode 100644
index 000000000..7aaec5641
--- /dev/null
+++ b/pkg/sources/github/permission_error_test.go
@@ -0,0 +1,212 @@
+package github
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "testing"
+
+ "github.com/google/go-github/v67/github"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/trufflesecurity/trufflehog/v3/pkg/context"
+)
+
+const (
+ appDeniedMessage = "Resource not accessible by integration"
+ tokenDeniedMessage = "Resource not accessible by personal access token"
+)
+
+// forbidden builds the error go-github returns for a 403 to GET path, with the
+// given message and acceptedPermissionsHeader value. An empty accepted omits
+// the header.
+func forbidden(path, message, accepted string) *github.ErrorResponse {
+ header := http.Header{}
+ if accepted != "" {
+ header.Set(acceptedPermissionsHeader, accepted)
+ }
+ return &github.ErrorResponse{
+ Response: &http.Response{
+ StatusCode: http.StatusForbidden,
+ Header: header,
+ Request: &http.Request{Method: http.MethodGet, URL: &url.URL{Scheme: "https", Host: "api.github.com", Path: path, RawQuery: "per_page=100"}},
+ },
+ Message: message,
+ }
+}
+
+func TestParseAcceptedPermissions(t *testing.T) {
+ tests := []struct {
+ name string
+ header string
+ want [][]permission
+ }{
+ {
+ name: "single permission",
+ header: "issues=read",
+ want: [][]permission{{{name: "issues", access: "read"}}},
+ },
+ {
+ name: "several permissions all required",
+ header: "pull_requests=write,contents=read",
+ want: [][]permission{{{name: "pull_requests", access: "write"}, {name: "contents", access: "read"}}},
+ },
+ {
+ name: "alternative sets",
+ header: "pull_requests=read,contents=read; issues=read,contents=read",
+ want: [][]permission{
+ {{name: "pull_requests", access: "read"}, {name: "contents", access: "read"}},
+ {{name: "issues", access: "read"}, {name: "contents", access: "read"}},
+ },
+ },
+ {
+ name: "whitespace around entries",
+ header: " issues = read ;pull_requests=read ",
+ want: [][]permission{{{name: "issues", access: "read"}}, {{name: "pull_requests", access: "read"}}},
+ },
+ {name: "empty", header: ""},
+ {name: "blank", header: " "},
+ {name: "entry without access level", header: "issues"},
+ {name: "empty entry", header: "issues=read,,contents=read"},
+ {name: "empty alternative", header: "issues=read;"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.want, parseAcceptedPermissions(tt.header))
+ })
+ }
+}
+
+func TestPermissionErrorMessage(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ wantText string
+ }{
+ {
+ name: "GitHub App missing one permission",
+ err: forbidden("/repos/o/r/issues", appDeniedMessage, "issues=read"),
+ wantText: "missing GitHub App permission: the request needs Issues (read); update the app's permissions and accept the change on the installation (GET /repos/o/r/issues returned 403 Resource not accessible by integration)",
+ },
+ {
+ name: "fine-grained token",
+ err: forbidden("/repos/o/r/pulls/comments", tokenDeniedMessage, "pull_requests=read"),
+ wantText: "missing personal access token permission: the request needs Pull requests (read); update the token's permissions (GET /repos/o/r/pulls/comments returned 403 Resource not accessible by personal access token)",
+ },
+ {
+ name: "unrecognized credential gets a generic fix",
+ err: forbidden("/repos/o/r/issues", "Forbidden", "issues=read"),
+ wantText: "missing GitHub permission: the request needs Issues (read); update the credential's permissions (GET /repos/o/r/issues returned 403 Forbidden)",
+ },
+ {
+ name: "single-permission alternatives",
+ err: forbidden("/repos/o/r/issues/comments", appDeniedMessage, "issues=read; pull_requests=read"),
+ wantText: "the request needs Issues (read) or Pull requests (read);",
+ },
+ {
+ name: "several permissions required together",
+ err: forbidden("/repos/o/r/pulls", appDeniedMessage, "pull_requests=write,contents=read"),
+ wantText: "the request needs Pull requests (write) and Contents (read);",
+ },
+ {
+ name: "alternatives needing several permissions each",
+ err: forbidden("/repos/o/r/issues/comments", appDeniedMessage, "pull_requests=read,contents=read; issues=read,contents=read"),
+ wantText: "the request needs either Pull requests (read) and Contents (read), or Issues (read) and Contents (read);",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := asPermissionError(tt.err)
+ var permErr *permissionError
+ require.ErrorAs(t, got, &permErr)
+ assert.Contains(t, got.Error(), tt.wantText)
+ assert.ErrorIs(t, got, tt.err, "the original 403 stays reachable through Unwrap")
+ })
+ }
+}
+
+func TestPermissionErrorWithoutRequestStillReads(t *testing.T) {
+ err := forbidden("/repos/o/r/issues", appDeniedMessage, "issues=read")
+ err.Response.Request = nil
+
+ got := asPermissionError(err)
+
+ assert.Contains(t, got.Error(), "(request returned 403 Resource not accessible by integration)")
+}
+
+func TestAsPermissionErrorPassesOtherErrorsThrough(t *testing.T) {
+ notFound := forbidden("/repos/o/r/issues", "Not Found", "issues=read")
+ notFound.Response.StatusCode = http.StatusNotFound
+
+ tests := []struct {
+ name string
+ err error
+ }{
+ {name: "nil"},
+ {name: "403 without the header", err: forbidden("/repos/o/r/issues", "Resource protected by organization SAML enforcement.", "")},
+ {name: "403 with a header that doesn't parse", err: forbidden("/repos/o/r/issues", appDeniedMessage, "issues")},
+ {name: "other status with the header", err: notFound},
+ {name: "primary rate limit", err: &github.RateLimitError{Response: &http.Response{StatusCode: http.StatusForbidden}}},
+ {name: "non-API error", err: errors.New("invalid pagination link")},
+ {name: "403 without a response", err: &github.ErrorResponse{Message: appDeniedMessage}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := asPermissionError(tt.err)
+ assert.Equal(t, tt.err, got)
+ var permErr *permissionError
+ assert.False(t, errors.As(got, &permErr))
+ })
+ }
+}
+
+func TestWalkPages_PermissionDeniedNamesMissingPermissionWithoutRetrying(t *testing.T) {
+ listing := &fakeListing{
+ records: sequentialRecords(7),
+ fail: func(n int, w http.ResponseWriter, _ *http.Request) bool {
+ if n != 2 {
+ return false
+ }
+ w.Header().Set(acceptedPermissionsHeader, "issues=read")
+ writeJSON(w, http.StatusForbidden, map[string]string{"message": appDeniedMessage})
+ return true
+ },
+ }
+ p := newTestPager(t, listing)
+ waits := recordWaits(&p)
+
+ var ids []int64
+ outcome, err := walkPages(context.Background(), p, firstItems(p), collect(&ids))
+
+ var permErr *permissionError
+ require.ErrorAs(t, err, &permErr)
+ assert.Equal(t, [][]permission{{{name: "issues", access: "read"}}}, permErr.accepted)
+ assert.Equal(t, credentialApp, permErr.credential)
+ assert.Contains(t, err.Error(), "GET /items returned 403 Resource not accessible by integration")
+ assert.Empty(t, *waits, "a permission 403 is not retried")
+ assert.Equal(t, 2, listing.requestCount())
+ assert.Equal(t, 3, outcome.items)
+ assert.Equal(t, idsUpTo(3), ids, "pages read before the 403 are kept")
+}
+
+func TestWalkUpdatedSince_PermissionErrorSurvivesWalkErrorWrapping(t *testing.T) {
+ listing := &fakeListing{
+ records: sequentialRecords(2),
+ fail: func(_ int, w http.ResponseWriter, _ *http.Request) bool {
+ w.Header().Set(acceptedPermissionsHeader, "pull_requests=read")
+ writeJSON(w, http.StatusForbidden, map[string]string{"message": appDeniedMessage})
+ return true
+ },
+ }
+ p := newTestPager(t, listing)
+
+ var ids []int64
+ _, err := walkUpdatedSince(context.Background(), p, sinceItems(p, &ids))
+ err = fmt.Errorf("pull request comments: %w", err)
+
+ var permErr *permissionError
+ require.ErrorAs(t, err, &permErr)
+ assert.Contains(t, err.Error(), "pull request comments: walk incomplete after 0 items: missing GitHub App permission: the request needs Pull requests (read)")
+}