Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Handle errors in a thread safe manner (#1052)
ahrav8be89a593bd4
diff --git a/pkg/sources/circleci/circleci.go b/pkg/sources/circleci/circleci.goindex a84e16c5a..ad0fb63db 100644--- a/pkg/sources/circleci/circleci.go+++ b/pkg/sources/circleci/circleci.go@@ -6,7 +6,6 @@ import ("fmt""io""net/http"- "sync""sync/atomic""github.com/go-errors/errors"@@ -75,25 +74,6 @@ func (s *Source) Init(_ context.Context, name string, jobId, sourceId int64, verreturn nil}-// scanErrors is used to collect errors encountered while scanning.-// It ensures that errors are collected in a thread-safe manner.-type scanErrors struct {- count uint64- mu sync.Mutex- errors []error-}--func newScanErrors(projects int) *scanErrors {- return &scanErrors{errors: make([]error, 0, projects)}-}--func (s *scanErrors) add(err error) {- atomic.AddUint64(&s.count, 1)- s.mu.Lock()- s.errors = append(s.errors, err)- s.mu.Unlock()-}-// Chunks emits chunks of bytes over a channel.func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) error {projects, err := s.projects(ctx)@@ -102,28 +82,28 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err}var scanned uint64- scanErrs := newScanErrors(len(projects))+ scanErrs := sources.NewScanErrors(len(projects))for _, proj := range projects {proj := projs.jobPool.Go(func() error {builds, err := s.buildsForProject(ctx, proj)if err != nil {- scanErrs.add(fmt.Errorf("error getting builds for project %s: %w", proj.RepoName, err))+ scanErrs.Add(fmt.Errorf("error getting builds for project %s: %w", proj.RepoName, err))return nil}for _, bld := range builds {buildSteps, err := s.stepsForBuild(ctx, proj, bld)if err != nil {- scanErrs.add(fmt.Errorf("error getting steps for build %d: %w", bld.BuildNum, err))+ scanErrs.Add(fmt.Errorf("error getting steps for build %d: %w", bld.BuildNum, err))return nil}for _, step := range buildSteps {for _, action := range step.Actions {if err = s.chunkAction(ctx, proj, bld, action, step.Name, chunksChan); err != nil {- scanErrs.add(fmt.Errorf("error chunking action %v: %w", action, err))+ scanErrs.Add(fmt.Errorf("error chunking action %v: %w", action, err))return nil}}@@ -137,8 +117,8 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err}_ = s.jobPool.Wait()- if scanErrs.count > 0 {- log.Debugf("encountered %d errors while scanning; errors: %v", scanErrs.count, scanErrs)+ if scanErrs.Count() > 0 {+ log.Debugf("encountered %d errors while scanning; errors: %v", scanErrs.Count(), scanErrs)}return nildiff --git a/pkg/sources/errors.go b/pkg/sources/errors.gonew file mode 100644index 000000000..2d9cc274d--- /dev/null+++ b/pkg/sources/errors.go@@ -0,0 +1,31 @@+package sources++import (+ "sync"+)++// ScanErrors is used to collect errors encountered while scanning.+// It ensures that errors are collected in a thread-safe manner.+type ScanErrors struct {+ mu sync.RWMutex+ errors []error+}++// NewScanErrors creates a new thread safe error collector.+func NewScanErrors(projects int) *ScanErrors {+ return &ScanErrors{errors: make([]error, 0, projects)}+}++// Add an error to the collection in a thread-safe manner.+func (s *ScanErrors) Add(err error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.errors = append(s.errors, err)+}++// Count returns the number of errors collected.+func (s *ScanErrors) Count() uint64 {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return uint64(len(s.errors))+}diff --git a/pkg/sources/gitlab/gitlab.go b/pkg/sources/gitlab/gitlab.goindex c139c0bbf..5cd313a03 100644--- a/pkg/sources/gitlab/gitlab.go+++ b/pkg/sources/gitlab/gitlab.go@@ -9,6 +9,8 @@ import ("strings""sync"+ "golang.org/x/sync/errgroup"+"github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/giturl"@@ -24,7 +26,6 @@ import (log "github.com/sirupsen/logrus""github.com/xanzy/go-gitlab""golang.org/x/exp/slices"- "golang.org/x/sync/semaphore""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb")@@ -45,8 +46,8 @@ type Source struct {scanOptions *git.ScanOptionsresumeInfoSlice []stringresumeInfoMutex sync.Mutex- jobSem *semaphore.Weightedsources.Progress+ jobPool *errgroup.Group}// Ensure the Source satisfies the interface at compile time.@@ -73,7 +74,8 @@ func (s *Source) Init(_ context.Context, name string, jobId, sourceId int64, vers.sourceId = sourceIds.jobId = jobIds.verify = verify- s.jobSem = semaphore.NewWeighted(int64(concurrency))+ s.jobPool = &errgroup.Group{}+ s.jobPool.SetLimit(concurrency)var conn sourcespb.GitLaberr := anypb.UnmarshalTo(connection, &conn, proto.UnmarshalOptions{})@@ -131,6 +133,55 @@ func (s *Source) Init(_ context.Context, name string, jobId, sourceId int64, verreturn nil}+// Chunks emits chunks of bytes over a channel.+func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) error {+ // Start client.+ apiClient, err := s.newClient()+ if err != nil {+ return errors.New(err)+ }+ // Get repo within target.+ repos, errs := s.getRepos()+ for _, repoErr := range errs {+ log.WithError(repoErr).Warn("error getting repo")+ }++ // End early if we had errors getting specified repos but none were validated.+ if len(errs) > 0 && len(repos) == 0 {+ return errors.New("All specified repos had validation issues, ending scan")+ }++ // Get all repos if not specified.+ if len(repos) == 0 {+ projects, err := s.getAllProjects(apiClient)+ if err != nil {+ return fmt.Errorf("error getting all projects: %v", err)+ }+ // Turn projects into URLs for Git cloner.+ for _, prj := range projects {+ if s.ignoreRepo(prj.PathWithNamespace) {+ continue+ }++ // Ensure the urls are valid before adding them to the repo list.+ _, err := url.Parse(prj.HTTPURLToRepo)+ if err != nil {+ fmt.Printf("could not parse url given by project: %s", prj.HTTPURLToRepo)+ }+ repos = append(repos, prj.HTTPURLToRepo)+ }+ if len(repos) == 0 {+ return errors.Errorf("unable to discover any repos")+ }+ }++ s.repos = repos+ // We must sort the repos so we can resume later if necessary.+ slices.Sort(s.repos)++ return s.scanRepos(ctx, chunksChan)+}+func (s *Source) newClient() (*gitlab.Client, error) {// Initialize a new api instance.switch s.authMethod {@@ -166,6 +217,20 @@ func (s *Source) newClient() (*gitlab.Client, error) {}}+func (s *Source) basicAuthSuccessful(apiClient *gitlab.Client) bool {+ user, resp, err := apiClient.Users.CurrentUser()+ if err != nil {+ return false+ }+ if resp.StatusCode != 200 {+ return false+ }+ if user != nil {+ return true+ }+ return false+}+func (s *Source) getAllProjects(apiClient *gitlab.Client) ([]*gitlab.Project, error) {// Projects without repo will get user projects, groups projects, and subgroup projects.user, _, err := apiClient.Users.CurrentUser()@@ -268,31 +333,26 @@ func (s *Source) getRepos() ([]string, []error) {return validRepos, errs}-func (s *Source) scanRepos(ctx context.Context, chunksChan chan *sources.Chunk) []error {- wg := sync.WaitGroup{}- var errs []error- var errsMut sync.Mutex+func (s *Source) scanRepos(ctx context.Context, chunksChan chan *sources.Chunk) error {// If there is resume information available, limit this scan to only the repos that still need scanning.reposToScan, progressIndexOffset := sources.FilterReposToResume(s.repos, s.GetProgress().EncodedResumeInfo)s.repos = reposToScan+ scanErrs := sources.NewScanErrors(len(s.repos))for i, repo := range s.repos {- if common.IsDone(ctx) {- // We are returning nil instead of the scanErrors slice here because- // we don't want to mark this scan as errored if we cancelled it.- return nil- }- if err := s.jobSem.Acquire(ctx, 1); err != nil {- log.WithError(err).Debug("could not acquire semaphore")- continue- }- wg.Add(1)- go func(ctx context.Context, repoURL string, i int) {- defer s.jobSem.Release(1)- defer wg.Done()+ i, repoURL := i, repo+ s.jobPool.Go(func() error {+ if common.IsDone(ctx) {+ // We are returning nil instead of the scanErrors slice here because+ // we don't want to mark this scan as errored if we cancelled it.+ log.Debugf("Skipping repo %s because context was cancelled", repoURL)+ return nil+ }+if len(repoURL) == 0 {- return+ log.Debugf("Skipping empty repo %s", repoURL)+ return nil}s.setProgressCompleteWithRepo(i, progressIndexOffset, repoURL)@@ -319,28 +379,28 @@ func (s *Source) scanRepos(ctx context.Context, chunksChan chan *sources.Chunk)}defer os.RemoveAll(path)if err != nil {- errsMut.Lock()- errs = append(errs, err)- errsMut.Unlock()- return+ scanErrs.Add(err)+ return nil}- log.Debugf("Starting to scan repo %d/%d: %s", i+1, len(s.repos), repoURL)- err = s.git.ScanRepo(ctx, repo, path, s.scanOptions, chunksChan)- if err != nil {- errsMut.Lock()- errs = append(errs, err)- errsMut.Unlock()- return++ log.Debugf("Starting to scan repo %d/%d: %s", i+1, len(s.repos), repo)+ if err = s.git.ScanRepo(ctx, repo, path, s.scanOptions, chunksChan); err != nil {+ scanErrs.Add(err)+ return nil}- log.Debugf("Completed scanning repo %d/%d: %s", i+1, len(s.repos), repoURL)- }(ctx, repo, i)++ log.Debugf("Completed scanning repo %d/%d: %s", i+1, len(s.repos), repo)+ return nil+ })}- wg.Wait()- if len(errs) == 0 {- s.SetProgressComplete(len(s.repos), len(s.repos), fmt.Sprintf("Completed scanning source %s", s.name), "")++ _ = s.jobPool.Wait()+ if scanErrs.Count() > 0 {+ log.Debugf("encountered %d errors while scanning; errors: %v", scanErrs.Count(), scanErrs)}+ s.SetProgressComplete(len(s.repos), len(s.repos), "Completed Gitlab scan", "")- return errs+ return nil}func (s *Source) ignoreRepo(r string) bool {@@ -358,80 +418,6 @@ func (s *Source) ignoreRepo(r string) bool {return false}-// Chunks emits chunks of bytes over a channel.-func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) error {- // Start client.- apiClient, err := s.newClient()- if err != nil {- return errors.New(err)- }- // Get repo within target.- repos, errs := s.getRepos()- for _, repoErr := range errs {- log.WithError(repoErr).Warn("error getting repo")- }-- // End early if we had errors getting specified repos but none were validated.- if len(errs) > 0 && len(repos) == 0 {- return errors.New("All specified repos had validation issues, ending scan")- }-- // Get all repos if not specified.- if repos == nil {- projects, err := s.getAllProjects(apiClient)- if err != nil {- return errors.New(err)- }- // Turn projects into URLs for Git cloner.- for _, prj := range projects {- if s.ignoreRepo(prj.PathWithNamespace) {- continue- }-- // Ensure the urls are valid before adding them to the repo list.- _, err := url.Parse(prj.HTTPURLToRepo)- if err != nil {- fmt.Printf("could not parse url given by project: %s", prj.HTTPURLToRepo)- }- repos = append(repos, prj.HTTPURLToRepo)- }- if repos == nil {- return errors.Errorf("unable to discover any repos")- }- }-- s.repos = repos- // We must sort the repos so we can resume later if necessary.- slices.Sort(s.repos)-- errs = s.scanRepos(ctx, chunksChan)- for _, err := range errs {- log.WithError(err).WithFields(- log.Fields{- "source_name": s.name,- "source_type": s.Type(),- "repos": repos,- },- ).Error("error scanning repo")- }-- return nil-}--func (s *Source) basicAuthSuccessful(apiClient *gitlab.Client) bool {- user, resp, err := apiClient.Users.CurrentUser()- if err != nil {- return false- }- if resp.StatusCode != 200 {- return false- }- if user != nil {- return true- }- return false-}-// setProgressCompleteWithRepo calls the s.SetProgressComplete after safely setting up the encoded resume info string.func (s *Source) setProgressCompleteWithRepo(index int, offset int, repoURL string) {s.resumeInfoMutex.Lock()diff --git a/pkg/sources/gitlab/gitlab_test.go b/pkg/sources/gitlab/gitlab_test.goindex 500fc4ac5..3b194a65a 100644--- a/pkg/sources/gitlab/gitlab_test.go+++ b/pkg/sources/gitlab/gitlab_test.go@@ -9,7 +9,7 @@ import ("github.com/kylelemons/godebug/pretty"log "github.com/sirupsen/logrus""github.com/stretchr/testify/assert"- "golang.org/x/sync/semaphore"+ "golang.org/x/sync/errgroup""google.golang.org/protobuf/types/known/anypb""github.com/trufflesecurity/trufflehog/v3/pkg/common"@@ -17,6 +17,7 @@ import ("github.com/trufflesecurity/trufflehog/v3/pkg/pb/credentialspb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""github.com/trufflesecurity/trufflehog/v3/pkg/sources"+ "github.com/trufflesecurity/trufflehog/v3/pkg/sources/git")func TestSource_Scan(t *testing.T) {@@ -280,9 +281,9 @@ func Test_scanRepos_SetProgressComplete(t *testing.T) {wantComplete: true,},{- name: "one valid repo",- repos: []string{"a"},- wantErr: true,+ name: "one valid repo",+ repos: []string{"repo"},+ wantComplete: true,},}@@ -291,7 +292,8 @@ func Test_scanRepos_SetProgressComplete(t *testing.T) {src := &Source{repos: tc.repos,}- src.jobSem = semaphore.NewWeighted(1)+ src.jobPool = &errgroup.Group{}+ src.scanOptions = &git.ScanOptions{}_ = src.scanRepos(context.Background(), nil)if !tc.wantErr {diff --git a/pkg/sources/s3/s3.go b/pkg/sources/s3/s3.goindex 7dc2489c6..42e5c85f0 100644--- a/pkg/sources/s3/s3.go+++ b/pkg/sources/s3/s3.go@@ -16,7 +16,7 @@ import (diskbufferreader "github.com/bill-rich/disk-buffer-reader""github.com/go-errors/errors""github.com/go-logr/logr"- "golang.org/x/sync/semaphore"+ "golang.org/x/sync/errgroup""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"@@ -39,6 +39,7 @@ type Source struct {sources.ProgresserrorCount *sync.Mapconn *sourcespb.S3+ jobPool *errgroup.Group}// Ensure the Source satisfies the interface at compile time@@ -68,6 +69,8 @@ func (s *Source) Init(aCtx context.Context, name string, jobId, sourceId int64,s.concurrency = concurrencys.errorCount = &sync.Map{}s.log = aCtx.Logger()+ s.jobPool = &errgroup.Group{}+ s.jobPool.SetLimit(concurrency)var conn sourcespb.S3err := anypb.UnmarshalTo(connection, &conn, proto.UnmarshalOptions{})@@ -181,9 +184,8 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err// pageChunker emits chunks onto the given channel from a pagefunc (s *Source) pageChunker(ctx context.Context, client *s3.S3, chunksChan chan *sources.Chunk, bucket string, page *s3.ListObjectsV2Output, errorCount *sync.Map, pageNumber int, objectCount *uint64) {- sem := semaphore.NewWeighted(int64(s.concurrency))- var wg sync.WaitGroupfor _, obj := range page.Contents {+ obj := objif common.IsDone(ctx) {return}@@ -216,19 +218,12 @@ func (s *Source) pageChunker(ctx context.Context, client *s3.S3, chunksChan chanreturn}- err := sem.Acquire(ctx, 1)- if err != nil {- s.log.Error(err, "could not acquire semaphore")- continue- }- wg.Add(1)- go func(ctx context.Context, wg *sync.WaitGroup, sem *semaphore.Weighted, obj *s3.Object) {+ s.jobPool.Go(func() error {defer common.RecoverWithExit(ctx)- defer sem.Release(1)- defer wg.Done()- if (*obj.Key)[len(*obj.Key)-1:] == "/" {- return+ if strings.HasSuffix(*obj.Key, "/") {+ s.log.V(5).Info("Skipping directory", "object", *obj.Key)+ return nil}path := strings.Split(*obj.Key, "/")@@ -240,7 +235,7 @@ func (s *Source) pageChunker(ctx context.Context, client *s3.S3, chunksChan chan}if nErr.(int) > 3 {s.log.V(2).Info("Skipped due to excessive errors", "object", *obj.Key)- return+ return nil}// files break with spaces, must replace with +@@ -262,7 +257,7 @@ func (s *Source) pageChunker(ctx context.Context, client *s3.S3, chunksChan chan}if nErr.(int) > 3 {s.log.V(3).Info("Skipped due to excessive errors", "object", *obj.Key)- return+ return nil}nErr = nErr.(int) + 1errorCount.Store(prefix, nErr)@@ -270,14 +265,14 @@ func (s *Source) pageChunker(ctx context.Context, client *s3.S3, chunksChan chanif nErr.(int) > 3 {s.log.V(2).Info("Too many consecutive errors, excluding prefix", "prefix", prefix)}- return+ return nil}defer res.Body.Close()reader, err := diskbufferreader.New(res.Body)if err != nil {s.log.Error(err, "Could not create reader.")- return+ return nil}defer reader.Close()@@ -306,7 +301,7 @@ func (s *Source) pageChunker(ctx context.Context, client *s3.S3, chunksChan chanif handlers.HandleFile(ctx, reader, chunkSkel, chunksChan) {atomic.AddUint64(objectCount, 1)s.log.V(5).Info("S3 object scanned.", "object_count", objectCount, "page_number", pageNumber)- return+ return nil}if err := reader.Reset(); err != nil {@@ -318,7 +313,7 @@ func (s *Source) pageChunker(ctx context.Context, client *s3.S3, chunksChan chanchunkData, err := io.ReadAll(reader)if err != nil {s.log.Error(err, "Could not read file data.")- return+ return nil}atomic.AddUint64(objectCount, 1)s.log.V(5).Info("S3 object scanned.", "object_count", objectCount, "page_number", pageNumber)@@ -332,9 +327,12 @@ func (s *Source) pageChunker(ctx context.Context, client *s3.S3, chunksChan chanif nErr.(int) > 0 {errorCount.Store(prefix, 0)}- }(ctx, &wg, sem, obj)++ return nil+ })}- wg.Wait()++ _ = s.jobPool.Wait()}// S3 links currently have the general format of:diff --git a/pkg/sources/s3/s3_test.go b/pkg/sources/s3/s3_test.goindex f437df735..e1f962543 100644--- a/pkg/sources/s3/s3_test.go+++ b/pkg/sources/s3/s3_test.go@@ -80,7 +80,7 @@ func TestSource_Chunks(t *testing.T) {t.Errorf("Source.Init() error = %v, wantErr %v", err, tt.wantErr)return}- chunksCh := make(chan *sources.Chunk, 100)+ chunksCh := make(chan *sources.Chunk)go func() {err = s.Chunks(ctx, chunksCh)if (err != nil) != tt.wantErr {