Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Use SourceManager in engine (#1586)
Miccah1cd600f70f70
diff --git a/pkg/engine/circleci.go b/pkg/engine/circleci.goindex fb665eda7..e1113b8e7 100644--- a/pkg/engine/circleci.go+++ b/pkg/engine/circleci.go@@ -1,16 +1,14 @@package engineimport (- "fmt""runtime"- "github.com/go-errors/errors""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"+ "github.com/trufflesecurity/trufflehog/v3/pkg/sources""github.com/trufflesecurity/trufflehog/v3/pkg/sources/circleci")@@ -29,23 +27,17 @@ func (e *Engine) ScanCircleCI(ctx context.Context, token string) error {return err}- circleSource := circleci.Source{}- ctx = context.WithValues(ctx,- "source_type", circleSource.Type().String(),- "source_name", "Circle CI",- )- err = circleSource.Init(ctx, "trufflehog - Circle CI", 0, int64(sourcespb.SourceType_SOURCE_TYPE_CIRCLECI), true, &conn, runtime.NumCPU())+ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - Circle CI", new(circleci.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ circleSource := circleci.Source{}+ if err := circleSource.Init(ctx, "trufflehog - Circle CI", jobID, sourceID, true, &conn, runtime.NumCPU()); err != nil {+ return nil, err+ }+ return &circleSource, nil+ })if err != nil {- return errors.WrapPrefix(err, "failed to init Circle CI source", 0)+ return err}-- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- err := circleSource.Chunks(ctx, e.ChunksChan())- if err != nil {- return fmt.Errorf("error scanning CircleCI: %w", err)- }- return nil- })- return nil+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}diff --git a/pkg/engine/docker.go b/pkg/engine/docker.goindex 5cc18f6cd..97840f983 100644--- a/pkg/engine/docker.go+++ b/pkg/engine/docker.go@@ -1,38 +1,28 @@package engineimport (- "fmt""runtime"- "github.com/go-errors/errors""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context"- "github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"+ "github.com/trufflesecurity/trufflehog/v3/pkg/sources""github.com/trufflesecurity/trufflehog/v3/pkg/sources/docker")// ScanDocker scans a given docker connection.func (e *Engine) ScanDocker(ctx context.Context, conn *anypb.Any) error {- dockerSource := docker.Source{}-- ctx = context.WithValues(ctx,- "source_type", dockerSource.Type().String(),- "source_name", "docker",- )- err := dockerSource.Init(ctx, "trufflehog - docker", 0, int64(sourcespb.SourceType_SOURCE_TYPE_DOCKER), true, conn, runtime.NumCPU())+ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - docker", new(docker.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ dockerSource := docker.Source{}+ if err := dockerSource.Init(ctx, "trufflehog - docker", jobID, sourceID, true, conn, runtime.NumCPU()); err != nil {+ return nil, err+ }+ return &dockerSource, nil+ })if err != nil {- return errors.WrapPrefix(err, "could not init docker source", 0)+ return err}-- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- err := dockerSource.Chunks(ctx, e.ChunksChan())- if err != nil {- return fmt.Errorf("error scanning docker image: %w", err)- }- return nil- })- return nil+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}diff --git a/pkg/engine/engine.go b/pkg/engine/engine.goindex 8c5e61b91..b26c4b850 100644--- a/pkg/engine/engine.go+++ b/pkg/engine/engine.go@@ -12,7 +12,6 @@ import (ahocorasick "github.com/BobuSumisu/aho-corasick"lru "github.com/hashicorp/golang-lru"- "golang.org/x/sync/errgroup""google.golang.org/protobuf/proto""github.com/trufflesecurity/trufflehog/v3/pkg/common"@@ -69,10 +68,9 @@ type Engine struct {prefilter ahocorasick.Trie// Engine synchronization primitives.- chunks chan *sources.Chunk+ sourceManager *sources.SourceManagerresults chan detectors.ResultWithMetadatadetectableChunksChan chan detectableChunk- sourcesWg *errgroup.GroupworkersWg sync.WaitGroupwgDetectorWorkers sync.WaitGroupWgNotifier sync.WaitGroup@@ -273,10 +271,8 @@ func Start(ctx context.Context, options ...EngineOption) (*Engine, error) {}e := &Engine{- chunks: make(chan *sources.Chunk, defaultChannelBuffer),detectableChunksChan: make(chan detectableChunk, defaultChannelBuffer),results: make(chan detectors.ResultWithMetadata, defaultChannelBuffer),- sourcesWg: &errgroup.Group{},dedupeCache: cache,printer: new(output.PlainPrinter), // default printermetrics: runtimeMetrics{Metrics: Metrics{scanStartTime: time.Now()}},@@ -294,8 +290,11 @@ func Start(ctx context.Context, options ...EngineOption) (*Engine, error) {}ctx.Logger().V(3).Info("engine started", "workers", e.concurrency)- // Limit number of concurrent goroutines dedicated to chunking a source.- e.sourcesWg.SetLimit(int(e.concurrency))+ // Create SourceManager.+ e.sourceManager = sources.NewManager(+ sources.WithConcurrentSources(int(e.concurrency)),+ sources.WithConcurrentUnits(int(e.concurrency)),+ )if len(e.decoders) == 0 {e.decoders = decoders.DefaultDecoders()@@ -394,9 +393,7 @@ func Start(ctx context.Context, options ...EngineOption) (*Engine, error) {func (e *Engine) Finish(ctx context.Context) error {defer common.RecoverWithExit(ctx)// Wait for the sources to finish putting chunks onto the chunks channel.- err := e.sourcesWg.Wait()-- close(e.chunks) // Source workers are done.+ err := e.sourceManager.Wait()e.workersWg.Wait() // Wait for the workers to finish scanning chunks.close(e.detectableChunksChan)@@ -410,8 +407,8 @@ func (e *Engine) Finish(ctx context.Context) error {return err}-func (e *Engine) ChunksChan() chan *sources.Chunk {- return e.chunks+func (e *Engine) ChunksChan() <-chan *sources.Chunk {+ return e.sourceManager.Chunks()}func (e *Engine) ResultsChan() chan detectors.ResultWithMetadata {@@ -429,7 +426,7 @@ type detectableChunk struct {func (e *Engine) detectorWorker(ctx context.Context) {var wgDetect sync.WaitGroup- for originalChunk := range e.chunks {+ for originalChunk := range e.ChunksChan() {for chunk := range sources.Chunker(originalChunk) {matchedKeywords := make(map[string]struct{})atomic.AddUint64(&e.metrics.BytesScanned, uint64(len(chunk.Data)))diff --git a/pkg/engine/filesystem.go b/pkg/engine/filesystem.goindex 98293e017..9e26c75b1 100644--- a/pkg/engine/filesystem.go+++ b/pkg/engine/filesystem.go@@ -1,14 +1,11 @@package engineimport (- "fmt""runtime"- "github.com/go-errors/errors""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""github.com/trufflesecurity/trufflehog/v3/pkg/sources"@@ -27,39 +24,18 @@ func (e *Engine) ScanFileSystem(ctx context.Context, c sources.FilesystemConfig)return err}- fileSystemSource := filesystem.Source{}- fileSystemSource.WithFilter(c.Filter)-- // TODO: This is how it would be used; everything after these comments would be removed.- // handle, err := e.sourceManager.Enroll(ctx, "trufflehog - filesystem", fileSystemSource.Type(),- // func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {- // fileSystemSource := filesystem.Source{}- // fileSystemSource.WithFilter(c.Filter)- // if err := fileSystemSource.Init(ctx, "trufflehog - filesystem", jobID, sourceID, true, &conn, runtime.NumCPU()); err != nil {- // return nil, err- // }- // return &fileSystemSource, nil- // })- // if err != nil {- // return err- // }- // return e.sourceManager.ScheduleRun(ctx, handle)-- ctx = context.WithValues(ctx,- "source_type", fileSystemSource.Type().String(),- "source_name", "filesystem",- )- err = fileSystemSource.Init(ctx, "trufflehog - filesystem", 0, int64(sourcespb.SourceType_SOURCE_TYPE_FILESYSTEM), true, &conn, runtime.NumCPU())+ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - filesystem", new(filesystem.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ fileSystemSource := filesystem.Source{}+ fileSystemSource.WithFilter(c.Filter)+ if err := fileSystemSource.Init(ctx, "trufflehog - filesystem", jobID, sourceID, true, &conn, runtime.NumCPU()); err != nil {+ return nil, err+ }+ return &fileSystemSource, nil+ })if err != nil {- return errors.WrapPrefix(err, "could not init filesystem source", 0)+ return err}- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- err := fileSystemSource.Chunks(ctx, e.ChunksChan())- if err != nil {- return fmt.Errorf("error scanning filesystem: %w", err)- }- return nil- })- return nil+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}diff --git a/pkg/engine/gcs.go b/pkg/engine/gcs.goindex 1ae24f901..32d977f74 100644--- a/pkg/engine/gcs.go+++ b/pkg/engine/gcs.go@@ -6,7 +6,6 @@ import ("google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""github.com/trufflesecurity/trufflehog/v3/pkg/sources"@@ -45,23 +44,19 @@ func (e *Engine) ScanGCS(ctx context.Context, c sources.GCSConfig) error {return fmt.Errorf("failed to marshal GCS connection: %w", err)}- source := gcs.Source{}- ctx = context.WithValues(ctx,- "source_type", source.Type().String(),- "source_name", "gcs",- )- if err = source.Init(ctx, "trufflehog - GCS", 0, 0, true, &conn, int(c.Concurrency)); err != nil {- return fmt.Errorf("failed to initialize GCS source: %w", err)+ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - gcs", new(gcs.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ gcsSource := gcs.Source{}+ if err := gcsSource.Init(ctx, "trufflehog - gcs", jobID, sourceID, true, &conn, int(c.Concurrency)); err != nil {+ return nil, err+ }+ return &gcsSource, nil+ })+ if err != nil {+ return err}-- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- if err := source.Chunks(ctx, e.ChunksChan()); err != nil {- return fmt.Errorf("could not scan GCS: %w", err)- }- return nil- })- return nil+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}func isAuthValid(ctx context.Context, c sources.GCSConfig, connection *sourcespb.GCS) bool {diff --git a/pkg/engine/gcs_test.go b/pkg/engine/gcs_test.goindex b62783408..4a7d2cae4 100644--- a/pkg/engine/gcs_test.go+++ b/pkg/engine/gcs_test.go@@ -80,7 +80,10 @@ func TestScanGCS(t *testing.T) {t.Errorf("ScanGCS() got: %v, want: %v", err, nil)return}- assert.Nil(t, e.Finish(ctx))+ if err := e.Finish(ctx); err != nil && !test.wantErr && !strings.Contains(err.Error(), "googleapi: Error 400: Bad Request") {+ t.Errorf("Finish() got: %v, want: %v", err, nil)+ return+ }if err == nil && test.wantErr {t.Errorf("ScanGCS() got: %v, want: %v", err, "error")diff --git a/pkg/engine/git.go b/pkg/engine/git.goindex 6e0983298..d7785494e 100644--- a/pkg/engine/git.go+++ b/pkg/engine/git.go@@ -1,15 +1,12 @@package engineimport (- "fmt""runtime"- "github.com/go-errors/errors"gogit "github.com/go-git/go-git/v5""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""github.com/trufflesecurity/trufflehog/v3/pkg/sources"@@ -54,26 +51,21 @@ func (e *Engine) ScanGit(ctx context.Context, c sources.GitConfig) error {return err}- gitSource := git.Source{}- if err := gitSource.Init(ctx, "trufflehog - git", 0, 0, true, &conn, runtime.NumCPU()); err != nil {- return errors.WrapPrefix(err, "could not init git source", 0)+ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - git", new(git.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ gitSource := git.Source{}+ if err := gitSource.Init(ctx, "trufflehog - git", jobID, sourceID, true, &conn, runtime.NumCPU()); err != nil {+ return nil, err+ }+ gitSource.WithScanOptions(scanOptions)+ // Don't try to clean up the provided directory. That's handled by the+ // caller of ScanGit.+ gitSource.WithPreserveTempDirs(true)+ return &gitSource, nil+ })+ if err != nil {+ return err}- gitSource.WithScanOptions(scanOptions)- // Don't try to clean up the provided directory. That's handled by the- // caller of ScanGit.- gitSource.WithPreserveTempDirs(true)-- ctx = context.WithValues(ctx,- "source_type", sourcespb.SourceType_SOURCE_TYPE_GIT.String(),- "source_name", "git",- )- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- err := gitSource.Chunks(ctx, e.ChunksChan())- if err != nil {- return fmt.Errorf("could not scan repo: %w", err)- }- return nil- })- return nil+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}diff --git a/pkg/engine/github.go b/pkg/engine/github.goindex 79d34d768..0442c4756 100644--- a/pkg/engine/github.go+++ b/pkg/engine/github.go@@ -1,13 +1,10 @@package engineimport (- "fmt"-gogit "github.com/go-git/go-git/v5""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""github.com/trufflesecurity/trufflehog/v3/pkg/sources"@@ -17,8 +14,6 @@ import (// ScanGitHub scans Github with the provided options.func (e *Engine) ScanGitHub(ctx context.Context, c sources.GithubConfig) error {- source := github.Source{}-connection := sourcespb.GitHub{Endpoint: c.Endpoint,Organizations: c.Orgs,@@ -42,31 +37,25 @@ func (e *Engine) ScanGitHub(ctx context.Context, c sources.GithubConfig) error {return err}- ctx = context.WithValues(ctx,- "source_type", source.Type().String(),- "source_name", "github",- )- err = source.Init(ctx, "trufflehog - github", 0, 0, false, &conn, c.Concurrency)- if err != nil {- ctx.Logger().Error(err, "failed to initialize github source")- return err- }-logOptions := &gogit.LogOptions{}opts := []git.ScanOption{git.ScanOptionFilter(c.Filter),git.ScanOptionLogOptions(logOptions),}scanOptions := git.NewScanOptions(opts...)- source.WithScanOptions(scanOptions)- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- err := source.Chunks(ctx, e.ChunksChan())- if err != nil {- return fmt.Errorf("could not scan github: %w", err)- }- return nil- })- return nil+ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - github", new(github.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ githubSource := github.Source{}+ if err := githubSource.Init(ctx, "trufflehog - github", jobID, sourceID, true, &conn, c.Concurrency); err != nil {+ return nil, err+ }+ githubSource.WithScanOptions(scanOptions)+ return &githubSource, nil+ })+ if err != nil {+ return err+ }+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}diff --git a/pkg/engine/gitlab.go b/pkg/engine/gitlab.goindex ab0f58d20..7179b238c 100644--- a/pkg/engine/gitlab.go+++ b/pkg/engine/gitlab.go@@ -4,12 +4,10 @@ import ("fmt""runtime"- "github.com/go-errors/errors"gogit "github.com/go-git/go-git/v5""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""github.com/trufflesecurity/trufflehog/v3/pkg/sources"@@ -52,24 +50,18 @@ func (e *Engine) ScanGitLab(ctx context.Context, c sources.GitlabConfig) error {return err}- gitlabSource := gitlab.Source{}- ctx = context.WithValues(ctx,- "source_type", gitlabSource.Type().String(),- "source_name", "gitlab",- )- err = gitlabSource.Init(ctx, "trufflehog - gitlab", 0, int64(sourcespb.SourceType_SOURCE_TYPE_GITLAB), true, &conn, runtime.NumCPU())+ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - gitlab", new(gitlab.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ gitlabSource := gitlab.Source{}+ if err := gitlabSource.Init(ctx, "trufflehog - gitlab", jobID, sourceID, true, &conn, runtime.NumCPU()); err != nil {+ return nil, err+ }+ gitlabSource.WithScanOptions(scanOptions)+ return &gitlabSource, nil+ })if err != nil {- return errors.WrapPrefix(err, "could not init GitLab source", 0)+ return err}- gitlabSource.WithScanOptions(scanOptions)-- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- err := gitlabSource.Chunks(ctx, e.ChunksChan())- if err != nil {- return fmt.Errorf("error scanning GitLab: %w", err)- }- return nil- })- return nil+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}diff --git a/pkg/engine/s3.go b/pkg/engine/s3.goindex a2056010a..57ae6bb6c 100644--- a/pkg/engine/s3.go+++ b/pkg/engine/s3.go@@ -4,11 +4,9 @@ import ("fmt""runtime"- "github.com/go-errors/errors""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/credentialspb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"@@ -55,23 +53,17 @@ func (e *Engine) ScanS3(ctx context.Context, c sources.S3Config) error {return err}- s3Source := s3.Source{}- ctx = context.WithValues(ctx,- "source_type", s3Source.Type().String(),- "source_name", "s3",- )- err = s3Source.Init(ctx, "trufflehog - s3", 0, int64(sourcespb.SourceType_SOURCE_TYPE_S3), true, &conn, runtime.NumCPU())+ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - s3", new(s3.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ s3Source := s3.Source{}+ if err := s3Source.Init(ctx, "trufflehog - s3", jobID, sourceID, true, &conn, runtime.NumCPU()); err != nil {+ return nil, err+ }+ return &s3Source, nil+ })if err != nil {- return errors.WrapPrefix(err, "failed to init S3 source", 0)+ return err}-- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- err := s3Source.Chunks(ctx, e.ChunksChan())- if err != nil {- return fmt.Errorf("error scanning S3: %w", err)- }- return nil- })- return nil+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}diff --git a/pkg/engine/syslog.go b/pkg/engine/syslog.goindex d93cfa973..7bf413ff4 100644--- a/pkg/engine/syslog.go+++ b/pkg/engine/syslog.go@@ -1,14 +1,12 @@package engineimport (- "fmt""os""github.com/go-errors/errors""google.golang.org/protobuf/proto""google.golang.org/protobuf/types/known/anypb"- "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""github.com/trufflesecurity/trufflehog/v3/pkg/sources"@@ -42,25 +40,19 @@ func (e *Engine) ScanSyslog(ctx context.Context, c sources.SyslogConfig) error {if err != nil {return errors.WrapPrefix(err, "error unmarshalling connection", 0)}- source := syslog.Source{}- ctx = context.WithValues(ctx,- "source_type", source.Type().String(),- "source_name", "syslog",- )- err = source.Init(ctx, "trufflehog - syslog", 0, 0, false, &conn, c.Concurrency)- source.InjectConnection(connection)++ handle, err := e.sourceManager.Enroll(ctx, "trufflehog - syslog", new(syslog.Source).Type(),+ func(ctx context.Context, jobID, sourceID int64) (sources.Source, error) {+ syslogSource := syslog.Source{}+ if err := syslogSource.Init(ctx, "trufflehog - syslog", jobID, sourceID, true, &conn, c.Concurrency); err != nil {+ return nil, err+ }+ syslogSource.InjectConnection(connection)+ return &syslogSource, nil+ })if err != nil {- ctx.Logger().Error(err, "failed to initialize syslog source")return err}-- e.sourcesWg.Go(func() error {- defer common.RecoverWithExit(ctx)- err := source.Chunks(ctx, e.ChunksChan())- if err != nil {- return fmt.Errorf("could not scan syslog: %w", err)- }- return nil- })- return nil+ _, err = e.sourceManager.ScheduleRun(ctx, handle)+ return err}diff --git a/pkg/sources/job_progress.go b/pkg/sources/job_progress.goindex 50605485d..0ae4b8472 100644--- a/pkg/sources/job_progress.go+++ b/pkg/sources/job_progress.go@@ -7,7 +7,6 @@ import ("errors""fmt""sync"- "sync/atomic""time")@@ -103,10 +102,14 @@ type JobProgress struct {// JobProgressMetrics tracks the metrics of a job.type JobProgressMetrics struct {- StartTime time.Time- EndTime time.Time- TotalUnits uint64- FinishedUnits uint64+ StartTime time.Time+ EndTime time.Time+ // Total number of units found by the Source.+ TotalUnits uint64+ // Total number of units that have finished chunking.+ FinishedUnits uint64+ // Total number of chunks produced. This metric updates before the+ // chunk is sent on the output channel.TotalChunks uint64Errors []errorDoneEnumerating bool@@ -163,11 +166,15 @@ func (jp *JobProgress) Finish() {}func (jp *JobProgress) Done() <-chan struct{} { return jp.ctx.Done() }func (jp *JobProgress) ReportUnit(unit SourceUnit) {- atomic.AddUint64(&jp.metrics.TotalUnits, 1)+ jp.metricsLock.Lock()+ jp.metrics.TotalUnits+++ jp.metricsLock.Unlock()jp.executeHooks(func(hook JobProgressHook) { hook.ReportUnit(jp.Ref(), unit) })}func (jp *JobProgress) ReportChunk(unit SourceUnit, chunk *Chunk) {- atomic.AddUint64(&jp.metrics.TotalChunks, 1)+ jp.metricsLock.Lock()+ jp.metrics.TotalChunks+++ jp.metricsLock.Unlock()jp.executeHooks(func(hook JobProgressHook) { hook.ReportChunk(jp.Ref(), unit, chunk) })}func (jp *JobProgress) StartUnitChunking(unit SourceUnit, start time.Time) {@@ -176,7 +183,9 @@ func (jp *JobProgress) StartUnitChunking(unit SourceUnit, start time.Time) {}func (jp *JobProgress) EndUnitChunking(unit SourceUnit, end time.Time) {// TODO: Record time.- atomic.AddUint64(&jp.metrics.FinishedUnits, 1)+ jp.metricsLock.Lock()+ jp.metrics.FinishedUnits+++ jp.metricsLock.Unlock()jp.executeHooks(func(hook JobProgressHook) { hook.EndUnitChunking(jp.Ref(), unit, end) })}func (jp *JobProgress) StartEnumerating(start time.Time) {@@ -196,7 +205,12 @@ func (jp *JobProgress) EndEnumerating(end time.Time) {func (jp *JobProgress) Snapshot() JobProgressMetrics {jp.metricsLock.Lock()defer jp.metricsLock.Unlock()- return jp.metrics++ metrics := jp.metrics+ metrics.Errors = make([]error, len(metrics.Errors))+ copy(metrics.Errors, jp.metrics.Errors)++ return metrics}// ReportError adds a non-nil error to the aggregate of errorsdiff --git a/pkg/sources/source_manager.go b/pkg/sources/source_manager.goindex 890099478..0528e9b04 100644--- a/pkg/sources/source_manager.go+++ b/pkg/sources/source_manager.go@@ -21,11 +21,18 @@ type handle int64// initialized Source.type SourceInitFunc func(ctx context.Context, sourceID int64, jobID int64) (Source, error)+// sourceInfo is an aggregate struct to store source information provided on+// initialization.+type sourceInfo struct {+ initFunc SourceInitFunc+ name string+}+type SourceManager struct {api apiClienthooks []JobProgressHook// Map of handle to source initializer.- handles map[handle]SourceInitFunc+ handles map[handle]sourceInfohandlesLock sync.Mutex// Pool limiting the amount of concurrent sources running.pool errgroup.Group@@ -58,8 +65,8 @@ func WithReportHook(hook JobProgressHook) func(*SourceManager) {}}-// WithConcurrency limits the concurrent number of sources a manager can run.-func WithConcurrency(concurrency int) func(*SourceManager) {+// WithConcurrentSources limits the concurrent number of sources a manager can run.+func WithConcurrentSources(concurrency int) func(*SourceManager) {return func(mgr *SourceManager) { mgr.pool.SetLimit(concurrency) }}@@ -85,7 +92,7 @@ func NewManager(opts ...func(*SourceManager)) *SourceManager {mgr := SourceManager{// Default to the headless API. Can be overwritten by the WithAPI option.api: &headlessAPI{},- handles: make(map[handle]SourceInitFunc),+ handles: make(map[handle]sourceInfo),outputChunks: make(chan *Chunk),}for _, opt := range opts {@@ -110,19 +117,22 @@ func (s *SourceManager) Enroll(ctx context.Context, name string, kind sourcespb.// TODO: smartly handle this?return 0, fmt.Errorf("handle ID '%d' already in use", handleID)}- s.handles[handleID] = f+ s.handles[handleID] = sourceInfo{+ initFunc: f,+ name: name,+ }return handleID, nil}// Run blocks until a resource is available to run the source, then// synchronously runs it. The first fatal error, if any, will be returned.func (s *SourceManager) Run(ctx context.Context, handle handle) (JobProgressRef, error) {- report, err := s.asyncRun(ctx, handle)+ progress, err := s.asyncRun(ctx, handle)if err != nil {- return report, err+ return progress, err}- <-report.Done()- return report, report.Snapshot().FatalError()+ <-progress.Done()+ return progress, progress.Snapshot().FatalError()}// ScheduleRun blocks until a resource is available to run the source, then@@ -133,26 +143,30 @@ func (s *SourceManager) ScheduleRun(ctx context.Context, handle handle) (JobProg}// asyncRun is a helper method to asynchronously run the Source. It calls out-// to the API to get a job ID for this run, creates a report, then waits for an-// available goroutine to asynchronously run it.+// to the API to get a job ID for this run, creates a JobProgress object, then+// waits for an available goroutine to asynchronously run it.func (s *SourceManager) asyncRun(ctx context.Context, handle handle) (JobProgressRef, error) {// Do preflight checks before waiting on the pool.if err := s.preflightChecks(ctx, handle); err != nil {return JobProgressRef{}, err}// Get a Job ID.+ ctx = context.WithValue(ctx, "source_id", int64(handle))jobID, err := s.api.GetJobID(ctx, int64(handle))if err != nil {return JobProgressRef{SourceID: int64(handle)}, err}- // Start a report for this job.- report := NewJobProgress(int64(handle), jobID, WithHooks(s.hooks...))+ // Create a JobProgress object for tracking progress.+ progress := NewJobProgress(int64(handle), jobID, WithHooks(s.hooks...))s.pool.Go(func() error {+ ctx := context.WithValues(ctx,+ "job_id", jobID,+ "source_manager_worker_id", common.RandomID(5),+ )defer common.Recover(ctx)- _ = s.run(ctx, handle, jobID, report)- return nil+ return s.run(ctx, handle, jobID, progress)})- return report.Ref(), nil+ return progress.Ref(), nil}// Chunks returns the read only channel of all the chunks produced by all of@@ -165,17 +179,16 @@ func (s *SourceManager) Chunks() <-chan *Chunk {// returned by Chunks(). The manager should not be reused after calling this// method. This current implementation is not thread safe and should only be// called by one thread.-func (s *SourceManager) Wait() {+func (s *SourceManager) Wait() error {// Check if the manager has been Waited.if s.done {- return+ return s.pool.Wait()}defer close(s.outputChunks)defer func() { s.done = true }()- // We are only using the errgroup for limiting concurrency.- // TODO: Maybe switch to using a semaphore.Weighted.- _ = s.pool.Wait()+ // Return the first error returned by run.+ return s.pool.Wait()}// preflightChecks is a helper method to check the Manager or the context isn't@@ -186,7 +199,7 @@ func (s *SourceManager) preflightChecks(ctx context.Context, handle handle) erroreturn fmt.Errorf("manager is done")}// Check the handle is valid.- if _, ok := s.getInitFunc(handle); !ok {+ if _, ok := s.getSourceInfo(handle); !ok {return fmt.Errorf("unrecognized handle")}return ctx.Err()@@ -201,18 +214,22 @@ func (s *SourceManager) run(ctx context.Context, handle handle, jobID int64, repdefer func() { report.End(time.Now()) }()// Initialize the source.- initFunc, ok := s.getInitFunc(handle)+ sourceInfo, ok := s.getSourceInfo(handle)if !ok {// Shouldn't happen due to preflight checks.err := fmt.Errorf("unrecognized handle")report.ReportError(Fatal{err})return Fatal{err}}- source, err := initFunc(ctx, int64(handle), jobID)+ source, err := sourceInfo.initFunc(ctx, int64(handle), jobID)if err != nil {report.ReportError(Fatal{err})return Fatal{err}}+ ctx = context.WithValues(ctx,+ "source_type", source.Type().String(),+ "source_name", sourceInfo.name,+ )// Check for the preferred method of tracking source units.if enumChunker, ok := source.(SourceUnitEnumChunker); ok && s.useSourceUnits {return s.runWithUnits(ctx, handle, enumChunker, report)@@ -224,7 +241,7 @@ func (s *SourceManager) run(ctx context.Context, handle handle, jobID int64, rep// job reporting.func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, source Source, report *JobProgress) error {// Introspect on the chunks we get from the Chunks method.- ch := make(chan *Chunk)+ ch := make(chan *Chunk, 1)var wg sync.WaitGroup// Consume chunks and export chunks.wg.Add(1)@@ -232,7 +249,7 @@ func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, sourdefer wg.Done()for chunk := range ch {report.ReportChunk(nil, chunk)- _ = common.CancellableWrite(ctx, s.outputChunks, chunk)+ s.outputChunks <- chunk}}()// Don't return from this function until the goroutine has finished@@ -253,7 +270,7 @@ func (s *SourceManager) runWithoutUnits(ctx context.Context, handle handle, sour// scanned and any errors encountered.func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, source SourceUnitEnumChunker, report *JobProgress) error {unitReporter := &mgrUnitReporter{- unitCh: make(chan SourceUnit),+ unitCh: make(chan SourceUnit, 1),report: report,}// Create a function that will save the first error encountered (if@@ -271,6 +288,7 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, sourcereport.StartEnumerating(time.Now())defer func() { report.EndEnumerating(time.Now()) }()defer close(unitReporter.unitCh)+ ctx.Logger().V(2).Info("enumerating source")if err := source.Enumerate(ctx, unitReporter); err != nil {report.ReportError(Fatal{err})catchFirstFatal(Fatal{err})@@ -287,7 +305,7 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, sourceunit := unitchunkReporter := &mgrChunkReporter{unit: unit,- chunkCh: make(chan *Chunk),+ chunkCh: make(chan *Chunk, 1),report: report,}// Consume units and produce chunks.@@ -295,6 +313,8 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, sourcereport.StartUnitChunking(unit, time.Now())// TODO: Catch panics and add to report.defer close(chunkReporter.chunkCh)+ ctx := context.WithValue(ctx, "unit", unit.SourceUnitID())+ ctx.Logger().V(3).Info("chunking unit")if err := source.ChunkUnit(ctx, unit, chunkReporter); err != nil {report.ReportError(Fatal{err})catchFirstFatal(Fatal{err})@@ -307,8 +327,7 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, sourcedefer wg.Done()defer func() { report.EndUnitChunking(unit, time.Now()) }()for chunk := range chunkReporter.chunkCh {- report.ReportChunk(chunkReporter.unit, chunk)- _ = common.CancellableWrite(ctx, s.outputChunks, chunk)+ s.outputChunks <- chunk}}()}@@ -321,9 +340,9 @@ func (s *SourceManager) runWithUnits(ctx context.Context, handle handle, source}}-// getInitFunc is a helper method for safe concurrent access to the+// getSourceInfo is a helper method for safe concurrent access to the// map[handle]SourceInitFunc map.-func (s *SourceManager) getInitFunc(handle handle) (SourceInitFunc, bool) {+func (s *SourceManager) getSourceInfo(handle handle) (sourceInfo, bool) {s.handlesLock.Lock()defer s.handlesLock.Unlock()f, ok := s.handles[handle]@@ -352,6 +371,7 @@ type mgrUnitReporter struct {}func (s *mgrUnitReporter) UnitOk(ctx context.Context, unit SourceUnit) error {+ s.report.ReportUnit(unit)return common.CancellableWrite(ctx, s.unitCh, unit)}@@ -368,6 +388,7 @@ type mgrChunkReporter struct {}func (s *mgrChunkReporter) ChunkOk(ctx context.Context, chunk Chunk) error {+ s.report.ReportChunk(s.unit, &chunk)return common.CancellableWrite(ctx, s.chunkCh, &chunk)}diff --git a/pkg/sources/source_manager_test.go b/pkg/sources/source_manager_test.goindex 4f7db5f1e..266263343 100644--- a/pkg/sources/source_manager_test.go+++ b/pkg/sources/source_manager_test.go@@ -4,6 +4,8 @@ import ("fmt""testing"+ "github.com/stretchr/testify/assert"+ "github.com/trufflesecurity/trufflehog/v3/pkg/common""github.com/trufflesecurity/trufflehog/v3/pkg/context""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb""google.golang.org/protobuf/types/known/anypb"@@ -39,10 +41,14 @@ type counterChunker struct {count int}-func (c *counterChunker) Chunks(_ context.Context, ch chan *Chunk) error {+func (c *counterChunker) Chunks(ctx context.Context, ch chan *Chunk) error {for i := 0; i < c.count; i++ {- ch <- &Chunk{Data: []byte{c.chunkCounter}}- c.chunkCounter+++ select {+ case ch <- &Chunk{Data: []byte{c.chunkCounter}}:+ c.chunkCounter+++ case <-ctx.Done():+ return ctx.Err()+ }}return nil}@@ -98,71 +104,50 @@ func tryRead(ch <-chan *Chunk) (*Chunk, error) {func TestSourceManagerRun(t *testing.T) {mgr := NewManager(WithBufferedOutput(8))handle, err := enrollDummy(mgr, &counterChunker{count: 1})- if err != nil {- t.Fatalf("unexpected error enrolling source: %v", err)- }+ assert.NoError(t, err)for i := 0; i < 3; i++ {- if _, err := mgr.Run(context.Background(), handle); err != nil {- t.Fatalf("unexpected error running source: %v", err)- }+ _, err = mgr.Run(context.Background(), handle)+ assert.NoError(t, err)chunk, err := tryRead(mgr.Chunks())- if err != nil {- t.Fatalf("reading chunk failed: %v", err)- }- if chunk.Data[0] != byte(i) {- t.Fatalf("unexpected chunk value, wanted %v, got: %v", chunk.Data[0], i)- }-+ assert.NoError(t, err)+ assert.Equal(t, []byte{byte(i)}, chunk.Data)// The Chunks channel should be empty now.- if chunk, err := tryRead(mgr.Chunks()); err == nil {- t.Fatalf("unexpected chunk found: %+v", chunk)- }+ _, err = tryRead(mgr.Chunks())+ assert.Error(t, err)}}func TestSourceManagerWait(t *testing.T) {mgr := NewManager()handle, err := enrollDummy(mgr, &counterChunker{count: 1})- if err != nil {- t.Fatalf("unexpected error enrolling source: %v", err)- }+ assert.NoError(t, err)// Asynchronously run the source.- if _, err := mgr.ScheduleRun(context.Background(), handle); err != nil {- t.Fatalf("unexpected error scheduling run: %v", err)- }+ _, err = mgr.ScheduleRun(context.Background(), handle)+ assert.NoError(t, err)// Read the 1 chunk we're expecting so Waiting completes.<-mgr.Chunks()// Wait for all resources to complete.- mgr.Wait()+ assert.NoError(t, mgr.Wait())// Enroll and run should return an error now.- if _, err := enrollDummy(mgr, &counterChunker{count: 1}); err == nil {- t.Fatalf("expected enroll to fail")- }- if _, err := mgr.ScheduleRun(context.Background(), handle); err == nil {- t.Fatalf("expected scheduling run to fail")- }+ _, err = enrollDummy(mgr, &counterChunker{count: 1})+ assert.Error(t, err)+ _, err = mgr.ScheduleRun(context.Background(), handle)+ assert.Error(t, err)}func TestSourceManagerError(t *testing.T) {mgr := NewManager()handle, err := enrollDummy(mgr, errorChunker{fmt.Errorf("oops")})- if err != nil {- t.Fatalf("unexpected error enrolling source: %v", err)- }+ assert.NoError(t, err)// A synchronous run should fail.- if _, err := mgr.Run(context.Background(), handle); err == nil {- t.Fatalf("expected run to fail")- }+ _, err = mgr.Run(context.Background(), handle)+ assert.Error(t, err)// Scheduling a run should not fail, but the error should surface in// Wait().ref, err := mgr.ScheduleRun(context.Background(), handle)- if err != nil {- t.Fatalf("unexpected error scheduling run: %v", err)- }- <-ref.Done()- if err := ref.Snapshot().FatalError(); err == nil {- t.Fatalf("expected wait to fail")- }+ assert.NoError(t, err)+ assert.Error(t, mgr.Wait())+ assert.Error(t, ref.Snapshot().FatalError())}func TestSourceManagerReport(t *testing.T) {@@ -173,19 +158,90 @@ func TestSourceManagerReport(t *testing.T) {} {mgr := NewManager(opts...)handle, err := enrollDummy(mgr, &counterChunker{count: 4})- if err != nil {- t.Fatalf("unexpected error enrolling source: %v", err)- }+ assert.NoError(t, err)// Synchronously run the source.ref, err := mgr.Run(context.Background(), handle)- if err != nil {- t.Fatalf("unexpected error running source: %v", err)+ assert.NoError(t, err)+ assert.Equal(t, 0, len(ref.Snapshot().Errors))+ assert.Equal(t, uint64(4), ref.Snapshot().TotalChunks)+ }+}++type unitChunk struct {+ unit string+ output string+ err string+}++type unitChunker struct{ steps []unitChunk }++func (c *unitChunker) Chunks(ctx context.Context, ch chan *Chunk) error {+ for _, step := range c.steps {+ if step.err != "" {+ continue}- if errs := ref.Snapshot().Errors; len(errs) > 0 {- t.Fatalf("unexpected errors in report: %v", errs)+ if err := common.CancellableWrite(ctx, ch, &Chunk{Data: []byte(step.output)}); err != nil {+ return err}- if count := ref.Snapshot().TotalChunks; count != 4 {- t.Fatalf("expected report to have 4 chunks, got: %d", count)+ }+ return nil+}+func (c *unitChunker) Enumerate(ctx context.Context, rep UnitReporter) error {+ for _, step := range c.steps {+ if err := rep.UnitOk(ctx, CommonSourceUnit{step.unit}); err != nil {+ return err}}+ return nil+}+func (c *unitChunker) ChunkUnit(ctx context.Context, unit SourceUnit, rep ChunkReporter) error {+ for _, step := range c.steps {+ if unit.SourceUnitID() != step.unit {+ continue+ }+ if step.err != "" {+ if err := rep.ChunkErr(ctx, fmt.Errorf(step.err)); err != nil {+ return err+ }+ continue+ }+ if err := rep.ChunkOk(ctx, Chunk{Data: []byte(step.output)}); err != nil {+ return err+ }+ }+ return nil+}++func TestSourceManagerNonFatalError(t *testing.T) {+ input := []unitChunk{+ {unit: "one", output: "bar"},+ {unit: "two", err: "oh no"},+ {unit: "three", err: "not again"},+ }+ mgr := NewManager(WithBufferedOutput(8), WithSourceUnits())+ handle, err := enrollDummy(mgr, &unitChunker{input})+ assert.NoError(t, err)+ ref, err := mgr.Run(context.Background(), handle)+ assert.NoError(t, err)+ report := ref.Snapshot()+ assert.Equal(t, len(input), int(report.TotalUnits))+ assert.Equal(t, len(input), int(report.FinishedUnits))+ assert.Equal(t, 1, int(report.TotalChunks))+ assert.Equal(t, 2, len(report.Errors))+ assert.True(t, report.DoneEnumerating)+}++func TestSourceManagerContextCancelled(t *testing.T) {+ mgr := NewManager(WithBufferedOutput(8))+ handle, err := enrollDummy(mgr, &counterChunker{count: 100})+ assert.NoError(t, err)++ ctx, cancel := context.WithCancel(context.Background())+ ref, err := mgr.ScheduleRun(ctx, handle)+ assert.NoError(t, err)++ cancel()+ <-ref.Done()+ report := ref.Snapshot()+ assert.Error(t, report.FatalError())}