Skip to content

Find, verify, and analyze leaked credentials

Scan Github Private Repositories With Token (#4426)

Kashif Khan000d74865180
diff --git a/pkg/sources/github/github.go b/pkg/sources/github/github.go
index 9912bbcb4..20eb992f0 100644
--- a/pkg/sources/github/github.go
+++ b/pkg/sources/github/github.go
@@ -503,7 +503,7 @@ func (s *Source) ensureRepoInfoCache(ctx context.Context, repo string, reporter
func (s *Source) enumerateBasicAuth(ctx context.Context, reporter sources.UnitReporter) error {
for _, org := range s.orgsCache.Keys() {
orgCtx := context.WithValue(ctx, "account", org)
- userType, err := s.getReposByOrgOrUser(ctx, org, reporter)
+ userType, err := s.getReposByOrgOrUser(ctx, org, true, reporter)
if err != nil {
orgCtx.Logger().Error(err, "error fetching repos for org or user")
continue
@@ -528,7 +528,7 @@ func (s *Source) enumerateUnauthenticated(ctx context.Context, reporter sources.
for _, org := range s.orgsCache.Keys() {
orgCtx := context.WithValue(ctx, "account", org)
- userType, err := s.getReposByOrgOrUser(ctx, org, reporter)
+ userType, err := s.getReposByOrgOrUser(ctx, org, false, reporter)
if err != nil {
orgCtx.Logger().Error(err, "error fetching repos for org or user")
continue
@@ -559,7 +559,7 @@ func (s *Source) enumerateWithToken(ctx context.Context, isGithubEnterprise bool
specificScope := len(s.repos) > 0 || s.orgsCache.Count() > 0
if !specificScope {
// Enumerate the user's orgs and repos if none were specified.
- if err := s.getReposByUser(ctx, ghUser.GetLogin(), reporter); err != nil {
+ if err := s.getReposByUser(ctx, ghUser.GetLogin(), true, reporter); err != nil {
ctx.Logger().Error(err, "Unable to fetch repos for the current user", "user", ghUser.GetLogin())
}
if err := s.addUserGistsToCache(ctx, ghUser.GetLogin(), reporter); err != nil {
@@ -578,7 +578,7 @@ func (s *Source) enumerateWithToken(ctx context.Context, isGithubEnterprise bool
if len(s.orgsCache.Keys()) > 0 {
for _, org := range s.orgsCache.Keys() {
orgCtx := context.WithValue(ctx, "account", org)
- userType, err := s.getReposByOrgOrUser(ctx, org, reporter)
+ userType, err := s.getReposByOrgOrUser(ctx, org, true, reporter)
if err != nil {
orgCtx.Logger().Error(err, "Unable to fetch repos for org or user")
continue
@@ -620,7 +620,9 @@ func (s *Source) enumerateWithApp(ctx context.Context, installationClient *githu
if err := s.addUserGistsToCache(ctx, member, reporter); err != nil {
logger.Error(err, "error fetching gists by user")
}
- if err := s.getReposByUser(ctx, member, reporter); err != nil {
+ // TODO: Add authenticated user list repo for app token. It does support as per docs but need to test it before we enable it here.
+ // docs: https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#list-repositories-for-the-authenticated-user
+ if err := s.getReposByUser(ctx, member, false, reporter); err != nil {
logger.Error(err, "error fetching repos by user")
}
}
@@ -861,7 +863,7 @@ func (s *Source) addReposForMembers(ctx context.Context, reporter sources.UnitRe
if err := s.addUserGistsToCache(ctx, member, reporter); err != nil {
ctx.Logger().Info("Unable to fetch gists by user", "user", member, "error", err)
}
- if err := s.getReposByUser(ctx, member, reporter); err != nil {
+ if err := s.getReposByUser(ctx, member, false, reporter); err != nil {
ctx.Logger().Info("Unable to fetch repos by user", "user", member, "error", err)
}
}
diff --git a/pkg/sources/github/github_test.go b/pkg/sources/github/github_test.go
index 48a615643..cc5ed953a 100644
--- a/pkg/sources/github/github_test.go
+++ b/pkg/sources/github/github_test.go
@@ -158,7 +158,7 @@ func TestAddReposByUser(t *testing.T) {
},
IgnoreRepos: []string{"super-secret-user/super-secret-repo2"},
})
- err := s.getReposByUser(context.Background(), "super-secret-user", noopReporter())
+ err := s.getReposByUser(context.Background(), "super-secret-user", false, noopReporter())
assert.Nil(t, err)
assert.Equal(t, 1, s.filteredRepoCache.Count())
ok := s.filteredRepoCache.Exists("super-secret-user/super-secret-repo")
diff --git a/pkg/sources/github/repo.go b/pkg/sources/github/repo.go
index 660dfd955..aced5feb2 100644
--- a/pkg/sources/github/repo.go
+++ b/pkg/sources/github/repo.go
@@ -17,23 +17,28 @@ import (
"github.com/trufflesecurity/trufflehog/v3/pkg/sources"
)
+// repoInfoCache is a thread-safe cache to store information about repositories.
type repoInfoCache struct {
mu sync.RWMutex
- cache map[string]repoInfo
+ cache map[string]repoInfo // the actual cache storing the repository information by URL.
}
+// newRepoInfoCache creates a new instance of repoInfoCache with an empty cache.
func newRepoInfoCache() repoInfoCache {
return repoInfoCache{
cache: make(map[string]repoInfo),
}
}
+// put adds repository information to the cache, locking for thread safety.
func (r *repoInfoCache) put(repoURL string, info repoInfo) {
r.mu.Lock()
defer r.mu.Unlock()
r.cache[repoURL] = info
}
+// get retrieves repository information from the cache, locking for thread safety.
+// it returns the info and a boolean indicating whether it was found.
func (r *repoInfoCache) get(repoURL string) (repoInfo, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
@@ -42,33 +47,42 @@ func (r *repoInfoCache) get(repoURL string) (repoInfo, bool) {
return info, ok
}
+// repoInfo holds basic metadata about a repository.
type repoInfo struct {
- owner string
- name string
- fullName string
- hasWiki bool // the repo is _likely_ to have a wiki (see the comment on wikiIsReachable func).
- size int
- visibility source_metadatapb.Visibility
+ owner string // repository owner (user|organization).
+ name string // repository name.
+ fullName string // full repository name (owner/repo).
+ hasWiki bool // whether the repository is likely to have a wiki.
+ size int // size of the repository in kilobytes.
+ visibility source_metadatapb.Visibility // visibility of the repository (public/private).
}
+// cloneRepo clones a repository given its URL, returns the path and the repository object.
func (s *Source) cloneRepo(ctx context.Context, repoURL string) (string, *gogit.Repository, error) {
return s.connector.Clone(ctx, repoURL)
}
+// repoListOptions is an interface for types that provide options for listing repositories.
type repoListOptions interface {
getListOptions() *github.ListOptions
}
+// repoLister is a function signature for listing repositories based on certain options.
type repoLister func(ctx context.Context, target string, opts repoListOptions) ([]*github.Repository, *github.Response, error)
+// === GitHub App Repositories ===
+
+// appListOptions represents options for listing repositories by GitHub Apps.
type appListOptions struct {
github.ListOptions
}
+// getListOptions returns the ListOptions for appListOptions.
func (a *appListOptions) getListOptions() *github.ListOptions {
return &a.ListOptions
}
+// appListReposWrapper lists repositories for a GitHub App, using the provided options.
func (s *Source) appListReposWrapper(ctx context.Context, _ string, opts repoListOptions) ([]*github.Repository, *github.Response, error) {
someRepos, res, err := s.connector.APIClient().Apps.ListRepos(ctx, opts.getListOptions())
if someRepos != nil {
@@ -77,27 +91,59 @@ func (s *Source) appListReposWrapper(ctx context.Context, _ string, opts repoLis
return nil, res, err
}
+// getReposByApp retrieves repositories by a GitHub App.
func (s *Source) getReposByApp(ctx context.Context, reporter sources.UnitReporter) error {
return s.processRepos(ctx, "", reporter, s.appListReposWrapper, &appListOptions{
ListOptions: github.ListOptions{
- PerPage: defaultPagination,
+ PerPage: defaultPagination, // Default pagination setting for API requests.
},
})
}
+// === GitHub User Repositories ===
+
+// userListOptions represents options for listing repositories by user.
type userListOptions struct {
- github.RepositoryListByUserOptions
+ github.RepositoryListByUserOptions // embedded options for listing repositories by user.
}
+// getListOptions returns the ListOptions for userListOptions.
func (u *userListOptions) getListOptions() *github.ListOptions {
return &u.ListOptions
}
+// authenticatedUserListOption represents options for listing repositories by authenticated user.
+type authenticatedUserListOption struct {
+ github.RepositoryListByAuthenticatedUserOptions // embedded options for listing repositories by authenticated user.
+}
+
+// getListOptions returns the ListOptions for authenticatedUserListOption.
+func (a *authenticatedUserListOption) getListOptions() *github.ListOptions {
+ return &a.ListOptions
+}
+
+// userListReposWrapper lists repositories for a user, using the provided options.
func (s *Source) userListReposWrapper(ctx context.Context, user string, opts repoListOptions) ([]*github.Repository, *github.Response, error) {
return s.connector.APIClient().Repositories.ListByUser(ctx, user, &opts.(*userListOptions).RepositoryListByUserOptions)
}
-func (s *Source) getReposByUser(ctx context.Context, user string, reporter sources.UnitReporter) error {
+// authenticatedUserListReposWrapper lists repositories for an authenticated user, using the provided options.
+func (s *Source) authenticatedUserListReposWrapper(ctx context.Context, user string, opts repoListOptions) ([]*github.Repository, *github.Response, error) {
+ return s.connector.APIClient().Repositories.ListByAuthenticatedUser(ctx, &opts.(*authenticatedUserListOption).RepositoryListByAuthenticatedUserOptions)
+}
+
+// getReposByUser retrieves repositories for a given user.
+func (s *Source) getReposByUser(ctx context.Context, user string, authenticated bool, reporter sources.UnitReporter) error {
+ if authenticated {
+ return s.processRepos(ctx, user, reporter, s.authenticatedUserListReposWrapper, &authenticatedUserListOption{
+ RepositoryListByAuthenticatedUserOptions: github.RepositoryListByAuthenticatedUserOptions{
+ ListOptions: github.ListOptions{
+ PerPage: defaultPagination,
+ },
+ },
+ })
+ }
+
return s.processRepos(ctx, user, reporter, s.userListReposWrapper, &userListOptions{
RepositoryListByUserOptions: github.RepositoryListByUserOptions{
ListOptions: github.ListOptions{
@@ -107,19 +153,25 @@ func (s *Source) getReposByUser(ctx context.Context, user string, reporter sourc
})
}
+// === GitHub Organization Repositories ===
+
+// orgListOptions represents options for listing repositories by organization.
type orgListOptions struct {
- github.RepositoryListByOrgOptions
+ github.RepositoryListByOrgOptions // Embedded options for listing repositories by organization.
}
+// getListOptions returns the ListOptions for orgListOptions.
func (o *orgListOptions) getListOptions() *github.ListOptions {
return &o.ListOptions
}
+// orgListReposWrapper lists repositories for an organization, using the provided options.
func (s *Source) orgListReposWrapper(ctx context.Context, org string, opts repoListOptions) ([]*github.Repository, *github.Response, error) {
- // TODO: It's possible to exclude forks when making the API request rather than doing post-request filtering
+ // TODO: It's possible to exclude forks when making the API request rather than doing post-request filtering.
return s.connector.APIClient().Repositories.ListByOrg(ctx, org, &opts.(*orgListOptions).RepositoryListByOrgOptions)
}
+// getReposByOrg retrieves repositories for a given organization.
func (s *Source) getReposByOrg(ctx context.Context, org string, reporter sources.UnitReporter) error {
return s.processRepos(ctx, org, reporter, s.orgListReposWrapper, &orgListOptions{
RepositoryListByOrgOptions: github.RepositoryListByOrgOptions{
@@ -137,44 +189,45 @@ func (s *Source) getReposByOrg(ctx context.Context, org string, reporter sources
// - https://docs.github.com/en/rest/users/users?apiVersion=2022-11-28#get-a-user
type userType int
+// Constants for userType.
const (
- // Default invalid state.
- unknown userType = iota
- // The account is a person (https://docs.github.com/en/rest/users/users).
- user
- // The account is an organization (https://docs.github.com/en/rest/orgs/orgs).
- organization
+ unknown userType = iota // default invalid state.
+ user // the account is a person (https://docs.github.com/en/rest/users/users).
+ organization // the account is an organization (https://docs.github.com/en/rest/orgs/orgs).
)
-func (s *Source) getReposByOrgOrUser(ctx context.Context, name string, reporter sources.UnitReporter) (userType, error) {
+// getReposByOrgOrUser retrieves repositories for an organization or user.
+func (s *Source) getReposByOrgOrUser(ctx context.Context, name string, authenticated bool, reporter sources.UnitReporter) (userType, error) {
var err error
- // List repositories for the organization |name|.
+ // try to get repositories for the organization first.
err = s.getReposByOrg(ctx, name, reporter)
if err == nil {
return organization, nil
- } else if !isGitHub404Error(err) {
+ } else if !isGitHub404Error(err) { // if the error is not a "not found" error, report it.
if err := reporter.UnitErr(ctx, fmt.Errorf("error getting repos by org: %w", err)); err != nil {
return unknown, err
}
+
return unknown, err
}
- // List repositories for the user |name|.
- err = s.getReposByUser(ctx, name, reporter)
+ // if organization repos aren't found, try user repos.
+ err = s.getReposByUser(ctx, name, authenticated, reporter)
if err == nil {
if err := s.addUserGistsToCache(ctx, name, reporter); err != nil {
ctx.Logger().Error(err, "Unable to add user to cache")
}
return user, nil
- } else if !isGitHub404Error(err) {
+ } else if !isGitHub404Error(err) { // if the error is not a "not found" error, report it.
return unknown, err
}
+ // if neither organization nor user repos are found, return an error.
return unknown, fmt.Errorf("account '%s' not found", name)
}
-// isGitHub404Error returns true if |err| is a `github.ErrorResponse` and has the status code `404`.
+// isGitHub404Error checks if the error is a GitHub API error with a 404 status.
func isGitHub404Error(err error) bool {
var ghErr *github.ErrorResponse
if !errors.As(err, &ghErr) {
@@ -184,7 +237,7 @@ func isGitHub404Error(err error) bool {
return ghErr.Response.StatusCode == http.StatusNotFound
}
-// processRepos is the main function for getting repositories from a source.
+// 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)
opts := listOpts.getListOptions()
@@ -194,6 +247,7 @@ func (s *Source) processRepos(ctx context.Context, target string, reporter sourc
uniqueOrgs = map[string]struct{}{}
)
+ // loop to handle pagination.
for {
someRepos, res, err := listRepos(ctx, target, listOpts)
if s.handleRateLimitWithUnitReporter(ctx, reporter, err) {
@@ -213,6 +267,7 @@ func (s *Source) processRepos(ctx context.Context, target string, reporter sourc
}
numRepos++
+ // track unique organizations.
if r.GetOwner().GetType() == "Organization" {
uniqueOrgs[r.GetOwner().GetLogin()] = struct{}{}
}
@@ -224,6 +279,7 @@ func (s *Source) processRepos(ctx context.Context, target string, reporter sourc
if err := reporter.UnitOk(ctx, RepoUnit{Name: repoName, URL: repoURL}); err != nil {
return err
}
+
logger.V(3).Info("repo attributes", "name", repoName, "kb_size", r.GetSize(), "repo_url", repoURL)
}
@@ -233,12 +289,14 @@ func (s *Source) processRepos(ctx context.Context, target string, reporter sourc
opts.Page = res.NextPage
}
+ // final logging of repository stats.
logger.V(2).Info("found repos", "total", numRepos, "num_forks", numForks, "num_orgs", len(uniqueOrgs))
githubOrgsEnumerated.WithLabelValues(s.name).Add(float64(len(uniqueOrgs)))
return nil
}
+// cacheRepoInfo caches basic information about a repository for later use.
func (s *Source) cacheRepoInfo(r *github.Repository) {
info := repoInfo{
owner: r.GetOwner().GetLogin(),
@@ -255,6 +313,7 @@ func (s *Source) cacheRepoInfo(r *github.Repository) {
s.repoInfoCache.put(r.GetCloneURL(), info)
}
+// cacheGistInfo caches information about a Gist.
func (s *Source) cacheGistInfo(g *github.Gist) {
info := repoInfo{
owner: g.GetOwner().GetLogin(),
@@ -267,7 +326,7 @@ func (s *Source) cacheGistInfo(g *github.Gist) {
s.repoInfoCache.put(g.GetGitPullURL(), info)
}
-// wikiIsReachable returns true if https://github.com/$org/$repo/wiki is not redirected.
+// wikiIsReachable checks if the wiki for a repository is reachable by sending a HEAD request.
// Unfortunately, this isn't 100% accurate. Some repositories have `has_wiki: true` and don't redirect their wiki page,
// but still don't have a cloneable wiki.
func (s *Source) wikiIsReachable(ctx context.Context, repoURL string) bool {
@@ -284,12 +343,13 @@ func (s *Source) wikiIsReachable(ctx context.Context, repoURL string) bool {
_, _ = io.Copy(io.Discard, res.Body)
_ = res.Body.Close()
- // If the wiki is disabled, or is enabled but has no content, the request should be redirected.
+ // if the wiki is disabled or unreachable, the request will be redirected.
return wikiURL == res.Request.URL.String()
}
+// normalizeRepo normalizes a GitHub repository URL or name to its canonical form.
func (s *Source) normalizeRepo(repo string) (string, error) {
- // If there's a '/', assume it's a URL and try to normalize it.
+ // if the string contains a '/', assume it's a GitHub repository.
if strings.ContainsRune(repo, '/') {
return giturl.NormalizeGithubRepo(repo)
}