Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Clean up Git source logging for per-source debug (#5451)
Kashif Khan400d35c2c71a
diff --git a/pkg/sources/git/git.go b/pkg/sources/git/git.goindex 326188dcc..9e29dd256 100644--- a/pkg/sources/git/git.go+++ b/pkg/sources/git/git.go@@ -261,6 +261,23 @@ func (s *Source) Init(aCtx context.Context, name string, jobId sources.JobID, soUseCustomContentWriter: s.useCustomContentWriter,}s.git = NewGit(cfg)++ // log the config choices so support can see how the source was set up+ // only counts and flags, never URLs or credentials+ aCtx.Logger().V(1).Info("git source initialized",+ "repo_count", len(conn.GetRepositories()),+ "dir_count", len(conn.GetDirectories()),+ "auth_type", fmt.Sprintf("%T", conn.GetCredential()),+ "base", conn.GetBase(),+ "head", conn.GetHead(),+ "max_depth", conn.GetMaxDepth(),+ "bare", conn.GetBare(),+ "skip_binaries", conn.GetSkipBinaries(),+ "skip_archives", conn.GetSkipArchives(),+ "has_include_filter", conn.GetIncludePathsFile() != "",+ "has_exclude_filter", conn.GetExcludePathsFile() != "",+ "has_exclude_globs", conn.GetExcludeGlobs() != "",+ )return nil}@@ -299,7 +316,7 @@ func (s *Source) scanRepos(ctx context.Context, reporter sources.ChunkReporter)}if err := s.scanRepo(ctx, repoURI, reporter); err != nil {- ctx.Logger().Info("error scanning repository", "repo", repoURI, "error", err)+ ctx.Logger().Error(err, "error scanning repository", "repo", repoURI)continue}}@@ -361,7 +378,7 @@ func (s *Source) scanDirs(ctx context.Context, reporter sources.ChunkReporter) e}if err := s.scanDir(ctx, gitDir, reporter); err != nil {- ctx.Logger().Info("error scanning repository", "repo", gitDir, "error", err)+ ctx.Logger().Error(err, "error scanning repository", "repo", gitDir)continue}}@@ -372,6 +389,7 @@ func (s *Source) scanDirs(ctx context.Context, reporter sources.ChunkReporter) efunc (s *Source) scanDir(ctx context.Context, gitDir string, reporter sources.ChunkReporter) error {if !s.scanOptions.Bare && strings.HasSuffix(gitDir, "git") {// TODO: Figure out why we skip directories ending in "git".+ ctx.Logger().V(4).Info("skipping directory", "path", gitDir, "reason", "non-bare directory name ends in git")return nil}@@ -666,39 +684,43 @@ func executeClone(ctx context.Context, params cloneParams) (*git.Repository, errgitArgs = append(gitArgs, cloneURL.String(), params.clonePath)cloneCmd := exec.CommandContext(ctx, "git", gitArgs...)- safeURL, secretForRedaction, err := stripPassword(params.gitURL)+ // the parse error from stripPassword contains the raw URL, which can hold+ // a password, so only log that stripping failed, not the error itself+ safeURL, urlPassword, err := stripPassword(params.gitURL)if err != nil {- ctx.Logger().V(1).Info("error stripping password from git url", "error", err)+ ctx.Logger().V(4).Info("could not strip password from git url; repo field left empty")}- logger := ctx.Logger().WithValues(+ ctx = context.WithValues(ctx,"subcommand", "git clone","repo", safeURL,"path", params.clonePath,"args", params.args,)- logger.V(3).Info("executing git clone command")+ ctx.Logger().V(2).Info("executing git clone command")outputBytes, err := cloneCmd.CombinedOutput()- var output string- if secretForRedaction != "" {- output = strings.ReplaceAll(string(outputBytes), secretForRedaction, "<secret>")- } else {- output = string(outputBytes)- }++ // hide passwords from the git output before it is logged or returned+ // the password can be inside the url, or passed in separately and added+ // to the url above when authInUrl is set+ userInfoPassword, _ := params.userInfo.Password()+ output := redactPasswords(string(outputBytes), urlPassword, userInfoPassword)if err != nil {err = fmt.Errorf("error executing git clone: %w, %s", err, output)}- logger.V(3).Info("git subcommand finished", "output", output)+ ctx.Logger().V(5).Info("git subcommand finished", "output", output, "duration", time.Since(start).String())if common.IsDone(ctx) {return nil, fmt.Errorf("git clone timed out (after %s)", time.Since(start))} else if cloneCmd.ProcessState == nil {return nil, fmt.Errorf("clone command exited with no output")} else if cloneCmd.ProcessState.ExitCode() != 0 {- logger.V(0).Info("git clone failed", "error", err)failureReason := ClassifyCloneError(output)exitCode := cloneCmd.ProcessState.ExitCode()+ // the error is returned and logged by the caller; this line only adds+ // how the failure was classified, which decides if it is retried+ ctx.Logger().V(4).Info("git clone attempt failed", "failure_reason", failureReason, "exit_code", exitCode)metricsInstance.RecordCloneOperation(statusFailure, failureReason, exitCode)return nil, fmt.Errorf("could not clone repo: %s, %w", safeURL, err)}@@ -707,13 +729,29 @@ func executeClone(ctx context.Context, params cloneParams) (*git.Repository, errif err != nil {return nil, fmt.Errorf("could not open cloned repo: %w", err)}- logger.V(1).Info("successfully cloned repo", "time_seconds", time.Since(start).Seconds())+ ctx.Logger().V(2).Info("successfully cloned repo", "time_seconds", time.Since(start).Seconds())metricsInstance.RecordCloneOperation(statusSuccess, cloneSuccess, 0)return repo, nil}+// redactPasswords replaces each password in output with "<secret>".+// Git gets the password inside the clone URL, where Go percent-encodes it+// (a "/" becomes "%2F"), so if git prints the URL we have to hide that form too.+// The encoded form is built the same way Go builds the clone URL.+func redactPasswords(output string, passwords ...string) string {+ for _, password := range passwords {+ if password == "" {+ continue+ }+ encoded := strings.TrimPrefix(url.UserPassword("", password).String(), ":")+ output = strings.ReplaceAll(output, password, "<secret>")+ output = strings.ReplaceAll(output, encoded, "<secret>")+ }+ return output+}+// PingRepoUsingToken executes git ls-remote on a repo and returns any error that occurs. It can be used to validate// that a repo actually exists and is reachable.//@@ -884,7 +922,7 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path stringreturn nil}- logger.Info("scanning repo", logValues...)+ logger.V(2).Info("scanning repo", logValues...)var (gitDir = getGitDir(path)@@ -894,7 +932,7 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path stringfor diff := range diffChan {if scanOptions.MaxDepth > 0 && depth >= scanOptions.MaxDepth {- logger.V(1).Info("reached max depth", "depth", depth)+ logger.V(4).Info("reached max depth, stopping scan", "depth", depth)break}@@ -909,7 +947,7 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path strings.metrics.RecordCommitScanned()// Increment repo-specific commit counteratomic.AddUint64(&s.repoCommitsScanned, 1)- logger.V(5).Info("scanning commit", "commit", fullHash)+ logger.V(3).Info("scanning commit", "commit", fullHash)// Scan the commit metadata.// See https://github.com/trufflesecurity/trufflehog/issues/2683@@ -948,6 +986,7 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path string}if !scanOptions.Filter.Pass(fileName) {+ logger.V(4).Info("skipping file", "commit", fullHash, "path", fileName, "reason", "excluded by path filter")continue}@@ -956,9 +995,10 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path stringcommitHash := plumbing.NewHash(fullHash)if s.skipBinaries || feature.ForceSkipBinaries.Load() {- logger.V(5).Info("skipping binary file",+ logger.V(4).Info("skipping file","commit", commitHash.String()[:7],- "path", fileName)+ "path", fileName,+ "reason", "binary files are skipped")continue}@@ -979,7 +1019,7 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path stringSourceVerify: s.verify,}- if err := HandleBinary(ctx, gitDir, reporter, chunkSkel, commitHash, fileName, s.skipArchives); err != nil {+ if err := HandleBinary(repoCtx, gitDir, reporter, chunkSkel, commitHash, fileName, s.skipArchives); err != nil {logger.Error(err,"error handling binary file",@@ -991,7 +1031,7 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path string}if diff.Len() > sources.DefaultChunkSize+sources.DefaultPeekSize {- s.gitChunk(ctx, diff, fileName, email, fullHash, when, remoteURL, reporter)+ s.gitChunk(repoCtx, diff, fileName, email, fullHash, when, remoteURL, reporter)continue}@@ -1008,7 +1048,7 @@ func (s *Git) ScanCommits(ctx context.Context, repo *git.Repository, path stringreader, err := d.ReadCloser()if err != nil {- ctx.Logger().Error(+ logger.Error(err, "error creating reader for commits","commit", fullHash,"path", fileName,@@ -1140,7 +1180,7 @@ func (s *Git) gitChunk(ctx context.Context, diff *gitparse.Diff, fileName, email// stream while still recording that content was truncated. Genuine reader// errors are still surfaced at ERROR.if errors.Is(err, bufio.ErrTooLong) {- ctx.Logger().V(2).Info("skipping oversize diff line; remainder of file not scanned",+ ctx.Logger().V(4).Info("skipping oversize diff line; remainder of file not scanned","filename", fileName, "commit", hash, "file", diff.PathB, "max_line_bytes", maxScanTokenSize)} else {ctx.Logger().Error(err, "error scanning chunk", "filename", fileName, "commit", hash, "file", diff.PathB)@@ -1198,7 +1238,7 @@ func (s *Git) ScanStaged(ctx context.Context, repo *git.Repository, path string,logValues = append(logValues, "max_depth", scanOptions.MaxDepth)}- logger.V(1).Info("scanning staged changes", logValues...)+ logger.V(2).Info("scanning staged changes", logValues...)var (reachedBase = false@@ -1208,11 +1248,11 @@ func (s *Git) ScanStaged(ctx context.Context, repo *git.Repository, path string,)for diff := range diffChan {fullHash := diff.Commit.Hash- logger := ctx.Logger().WithValues("commit", fullHash, "path", diff.PathB)- logger.V(2).Info("scanning staged changes from git")+ logger := context.WithValues(ctx, "commit", fullHash, "path", diff.PathB).Logger()+ logger.V(3).Info("scanning staged changes from git")if scanOptions.MaxDepth > 0 && depth >= scanOptions.MaxDepth {- logger.V(1).Info("reached max depth")+ logger.V(4).Info("reached max depth, stopping scan", "depth", depth)break}@@ -1229,11 +1269,12 @@ func (s *Git) ScanStaged(ctx context.Context, repo *git.Repository, path string,}if scanOptions.BaseHash != "" && fullHash == scanOptions.BaseHash {- logger.V(1).Info("reached base hash, finishing scanning files")+ logger.V(4).Info("reached base hash, finishing scanning files")reachedBase = true}if !scanOptions.Filter.Pass(diff.PathB) {+ logger.V(4).Info("skipping file", "reason", "excluded by path filter")continue}@@ -1250,9 +1291,7 @@ func (s *Git) ScanStaged(ctx context.Context, repo *git.Repository, path string,commitHash := plumbing.NewHash(fullHash)if s.skipBinaries || feature.ForceSkipBinaries.Load() {- logger.V(5).Info("skipping binary file",- "commit", commitHash.String()[:7],- "path", fileName)+ logger.V(4).Info("skipping file", "reason", "binary files are skipped")continue}@@ -1328,6 +1367,17 @@ func (s *Git) ScanRepo(ctx context.Context, repo *git.Repository, repoPath strin}start := time.Now().Unix()+ // The repoPath is usually a temp folder, so add the remote to the log fields once here+ // and every line below (commits, staged changes, the summary) says which repo it is about.+ // Other sources may have added it already, in which case we don't add it again.+ if ctx.Value("repo") == nil {+ repoName := GetSafeRemoteURL(repo, "origin")+ if repoName == "" {+ repoName = repoPath+ }+ ctx = context.WithValue(ctx, "repo", repoName)+ }+// Reset the repo-specific commit counteratomic.StoreUint64(&s.repoCommitsScanned, 0)@@ -1339,28 +1389,15 @@ func (s *Git) ScanRepo(ctx context.Context, repo *git.Repository, repoPath strin// Skip staged scanning for mirror/bare clonesif !isRepoBare(repoPath) {if err := s.ScanStaged(ctx, repo, repoPath, scanOptions, reporter); err != nil {- ctx.Logger().V(1).Info("error scanning unstaged changes", "error", err)+ ctx.Logger().Error(err, "error scanning staged changes")}}// Get the number of commits scanned in this repocommitsScannedInRepo := atomic.LoadUint64(&s.repoCommitsScanned)- logger := ctx.Logger()- // We're logging time, but the repoPath is usually a dynamically generated folder in /tmp.- // To make this duration logging useful, we need to log the remote as well.- // Other sources may have included this info to the context, in which case we don't need to add it again.- if ctx.Value("repo") == nil {- remotes, _ := repo.Remotes()- repoURL := "Could not get remote for repo"- if len(remotes) != 0 {- repoURL = GetSafeRemoteURL(repo, remotes[0].Config().Name)- }- logger = logger.WithValues("repo", repoURL)- }-scanTime := time.Now().Unix() - start- logger.V(1).Info(+ ctx.Logger().V(2).Info("scanning git repo complete","path", repoPath,"time_seconds", scanTime,@@ -1523,14 +1560,18 @@ func prepareRepoSinceCommit(ctx context.Context, uriString, clonePath, commitHasclient = github.NewClient(tc)}- commit, _, err := client.Git.GetCommit(context.Background(), owner, repoName, commitHash)+ commit, _, err := client.Git.GetCommit(ctx, owner, repoName, commitHash)if err != nil {+ // the GitHub error can say why: not found, no access, or rate limited+ ctx.Logger().V(4).Info("could not look up base commit on GitHub; cloning full history",+ "commit", commitHash, "reason", err.Error())return PrepareRepo(ctx, uriString, clonePath, trustLocalGitConfig, isBare)}var timestamp string{author := commit.GetAuthor()if author == nil {+ ctx.Logger().V(4).Info("base commit has no author date; cloning full history", "commit", commitHash)return PrepareRepo(ctx, uriString, clonePath, trustLocalGitConfig, isBare)}timestamp = author.GetDate().Format(time.RFC3339)@@ -1703,10 +1744,10 @@ func HandleBinary(skipArchives bool,) (err error) {fileCtx := context.WithValues(ctx, "commit", commitHash.String()[:7], "path", path)- fileCtx.Logger().V(5).Info("handling binary file")+ fileCtx.Logger().V(3).Info("handling binary file")if common.SkipFile(path) {- fileCtx.Logger().V(5).Info("file contains ignored extension")+ fileCtx.Logger().V(4).Info("skipping file", "reason", "ignored file extension")return nil}@@ -1754,14 +1795,14 @@ func HandleBinary(defer func() {n, copyErr := io.Copy(io.Discard, stdout)if copyErr != nil {- ctx.Logger().Error(+ fileCtx.Logger().Error(copyErr,"Failed to discard remaining stdout data after HandleFile completion",)}if n > 0 {- ctx.Logger().V(3).Info(+ fileCtx.Logger().V(5).Info("HandleFile did not consume all stdout data; excess discarded","bytes_discarded", n)}diff --git a/pkg/sources/git/git_test.go b/pkg/sources/git/git_test.goindex 07db93a2a..35db28700 100644--- a/pkg/sources/git/git_test.go+++ b/pkg/sources/git/git_test.go@@ -13,13 +13,18 @@ import ("testing""time"+ "github.com/go-logr/zapr""github.com/kylelemons/godebug/pretty""github.com/stretchr/testify/assert""github.com/trufflesecurity/trufflehog/v3/pkg/feature"+ "go.uber.org/zap"+ "go.uber.org/zap/zapcore"+ "go.uber.org/zap/zaptest/observer""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/log/logtest""github.com/trufflesecurity/trufflehog/v3/pkg/pb/credentialspb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/source_metadatapb""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb"@@ -2324,3 +2329,132 @@ func gitHasObject(t *testing.T, repoPath, rev string) bool {t.Helper()return exec.Command("git", "-C", repoPath, "cat-file", "-e", rev+"^{commit}").Run() == nil}++func TestSource_DebugLogging(t *testing.T) {+ const testSecret = "TESTSECRET-do-not-log-1234567890"++ repoPath := setupTestRepo(t, "debug-log-repo")+ addTestFileAndCommit(t, repoPath, "config.txt", "password = "+testSecret)++ conn, err := anypb.New(&sourcespb.Git{+ Credential: &sourcespb.Git_Unauthenticated{+ Unauthenticated: &credentialspb.Unauthenticated{},+ },+ Repositories: []string{"file://" + repoPath},+ })+ assert.NoError(t, err)++ // run the source and drain its chunks, the way the engine does+ runSource := func(ctx context.Context) {+ s := Source{}+ assert.NoError(t, s.Init(ctx, "test debug logging", 1, 1, false, conn, 1))++ chunksCh := make(chan *sources.Chunk, 64)+ go func() {+ for range chunksCh {+ }+ }()+ assert.NoError(t, s.Chunks(ctx, chunksCh))+ close(chunksCh)+ }++ t.Run("debug on", func(t *testing.T) {+ ctx, logs := logtest.DebugContext()+ ctx = context.WithValues(ctx, "source_name", "test debug logging", "job_id", 1)+ runSource(ctx)++ // lines from each level we care about show up+ for _, msg := range []string{+ "git source initialized", // V(1)+ "successfully cloned repo", // V(2)+ "scanning commit", // V(3)+ "git subcommand finished", // V(5)+ "scanning git repo complete", // V(2)+ } {+ assert.NotZero(t, logs.FilterMessage(msg).Len(), "missing log line %q", msg)+ }++ // every line came from the context logger, so it carries the source fields,+ // and none of them contain the secret+ for _, entry := range logs.All() {+ fields := entry.ContextMap()+ assert.Contains(t, fields, "source_name", "line %q", entry.Message)+ assert.Contains(t, fields, "job_id", "line %q", entry.Message)+ assert.NotContains(t, entry.Message, testSecret)+ assert.NotContains(t, fmt.Sprint(fields), testSecret)+ }+ })++ t.Run("debug off", func(t *testing.T) {+ core, logs := observer.New(zapcore.InfoLevel)+ ctx := context.WithLogger(context.Background(), zapr.NewLogger(zap.New(core)))+ runSource(ctx)++ assert.Zero(t, logs.FilterMessage("git subcommand finished").Len())+ assert.Zero(t, logs.FilterMessage("scanning commit").Len())+ })+}++func TestCloneRepo_DoesNotLogToken(t *testing.T) {+ const token = "TESTTOKEN-do-not-log-1234567890"++ ctx, logs := logtest.DebugContext()++ // nothing listens on port 1, so the clone fails fast and is not retried;+ // the token is passed separately and only added to the URL inside CloneRepo+ _, _, err := CloneRepoUsingToken(ctx, token, "http://127.0.0.1:1/org/repo.git", "", "x-access-token", true)+ assert.Error(t, err)+ assert.NotContains(t, err.Error(), token)++ assert.NotZero(t, logs.FilterMessage("git clone attempt failed").Len())+ for _, entry := range logs.All() {+ assert.NotContains(t, entry.Message, token)+ assert.NotContains(t, fmt.Sprint(entry.ContextMap()), token)+ }+}++func TestRedactPasswords(t *testing.T) {+ tests := []struct {+ name string+ output string+ password string+ want string+ }{+ {+ name: "plain token",+ output: "fatal: unable to access 'https://user:glpat-abc123@host/r.git/'",+ password: "glpat-abc123",+ want: "fatal: unable to access 'https://user:<secret>@host/r.git/'",+ },+ {+ name: "base64 token is percent-encoded in the url",+ output: "fatal: unable to access 'https://user:abc+%2F=def@host/r.git/'",+ password: "abc+/=def",+ want: "fatal: unable to access 'https://user:<secret>@host/r.git/'",+ },+ {+ name: "token with @ : and ?",+ output: "fatal: unable to access 'https://user:a%40b%3Ac%3Fd@host/r.git/'",+ password: "a@b:c?d",+ want: "fatal: unable to access 'https://user:<secret>@host/r.git/'",+ },+ {+ name: "plain form printed somewhere else",+ output: "token a@b:c?d was rejected",+ password: "a@b:c?d",+ want: "token <secret> was rejected",+ },+ {+ name: "empty password leaves output alone",+ output: "fatal: repository not found",+ password: "",+ want: "fatal: repository not found",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ assert.Equal(t, tt.want, redactPasswords(tt.output, tt.password))+ })+ }+}diff --git a/pkg/sources/source_manager.go b/pkg/sources/source_manager.goindex c9aadf7e4..edfff48a9 100644--- a/pkg/sources/source_manager.go+++ b/pkg/sources/source_manager.go@@ -360,18 +360,7 @@ func (s *SourceManager) run(ctx context.Context, source Source, report *JobProgr}()report.TrackProgress(source.GetProgress())- if ctx.Value("job_id") == "" {- ctx = context.WithValue(ctx, "job_id", report.JobID)- }- if ctx.Value("source_id") == "" {- ctx = context.WithValue(ctx, "source_id", report.SourceID)- }- if ctx.Value("source_name") == "" {- ctx = context.WithValue(ctx, "source_name", report.SourceName)- }- if ctx.Value("source_type") == "" {- ctx = context.WithValue(ctx, "source_type", source.Type().String())- }+ ctx = withSourceFields(ctx, source, report)// Check if source units are supported and configured.canUseSourceUnits := len(targets) == 0 && s.useSourceUnitsFunc != nil@@ -387,6 +376,26 @@ func (s *SourceManager) run(ctx context.Context, source Source, report *JobProgrreturn s.runWithoutUnits(ctx, source, report, targets...)}+// withSourceFields adds the job and source fields to the context, so every log+// line the source writes says which source and job it came from.+// A caller (like thog) may have added some of them already. We skip those so a+// field doesn't show up twice. A missing value is nil, not "", so check for nil.+func withSourceFields(ctx context.Context, source Source, report *JobProgress) context.Context {+ if ctx.Value("job_id") == nil {+ ctx = context.WithValue(ctx, "job_id", report.JobID)+ }+ if ctx.Value("source_id") == nil {+ ctx = context.WithValue(ctx, "source_id", report.SourceID)+ }+ if ctx.Value("source_name") == nil {+ ctx = context.WithValue(ctx, "source_name", report.SourceName)+ }+ if ctx.Value("source_type") == nil {+ ctx = context.WithValue(ctx, "source_type", source.Type().String())+ }+ return ctx+}+// enumerate is a helper method to enumerate a Source.func (s *SourceManager) enumerate(ctx context.Context, source Source, report *JobProgress, reporter UnitReporter) error {report.Start(time.Now())@@ -399,18 +408,7 @@ func (s *SourceManager) enumerate(ctx context.Context, source Source, report *Jo}()report.TrackProgress(source.GetProgress())- if ctx.Value("job_id") == "" {- ctx = context.WithValue(ctx, "job_id", report.JobID)- }- if ctx.Value("source_id") == "" {- ctx = context.WithValue(ctx, "source_id", report.SourceID)- }- if ctx.Value("source_name") == "" {- ctx = context.WithValue(ctx, "source_name", report.SourceName)- }- if ctx.Value("source_type") == "" {- ctx = context.WithValue(ctx, "source_type", source.Type().String())- }+ ctx = withSourceFields(ctx, source, report)// Check if source units are supported and configured.canUseSourceUnits := s.useSourceUnitsFunc != nil@@ -435,18 +433,7 @@ func (s *SourceManager) scan(ctx context.Context, source Source, report *JobProgreport.ReportUnit(unit)report.TrackProgress(source.GetProgress())- if ctx.Value("job_id") == "" {- ctx = context.WithValue(ctx, "job_id", report.JobID)- }- if ctx.Value("source_id") == "" {- ctx = context.WithValue(ctx, "source_id", report.SourceID)- }- if ctx.Value("source_name") == "" {- ctx = context.WithValue(ctx, "source_name", report.SourceName)- }- if ctx.Value("source_type") == "" {- ctx = context.WithValue(ctx, "source_type", source.Type().String())- }+ ctx = withSourceFields(ctx, source, report)// Check if source units are supported and configured.canUseSourceUnits := s.useSourceUnitsFunc != nildiff --git a/pkg/sources/source_manager_test.go b/pkg/sources/source_manager_test.goindex d0c3575c6..7503ee197 100644--- a/pkg/sources/source_manager_test.go+++ b/pkg/sources/source_manager_test.go@@ -9,10 +9,12 @@ import ("time""github.com/stretchr/testify/assert"+ "go.uber.org/zap/zaptest/observer""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/log/logtest""github.com/trufflesecurity/trufflehog/v3/pkg/pb/sourcespb")@@ -598,3 +600,57 @@ func TestSourceManagerSemaphoreAcquireError(t *testing.T) {})})}++// loggingChunker writes one log line through the context it was given, then+// chunks like counterChunker.+type loggingChunker struct{ counterChunker }++func (c *loggingChunker) Chunks(ctx context.Context, ch chan *Chunk, targets ...ChunkingTarget) error {+ ctx.Logger().Info("chunking from source")+ return c.counterChunker.Chunks(ctx, ch, targets...)+}++func TestSourceManagerAddsSourceFieldsToLogs(t *testing.T) {+ // runSource scans one dummy source and returns the line it logged.+ runSource := func(t *testing.T, ctx context.Context, logs *observer.ObservedLogs) observer.LoggedEntry {+ mgr := NewManager(WithBufferedOutput(8))+ source, err := buildDummy(&loggingChunker{counterChunker{count: 1}})+ assert.NoError(t, err)++ ref, err := mgr.EnumerateAndScan(ctx, "dummy", source)+ assert.NoError(t, err)+ <-ref.Done()++ entries := logs.FilterMessage("chunking from source").All()+ if !assert.Len(t, entries, 1) {+ t.FailNow()+ }+ return entries[0]+ }++ t.Run("fields are added", func(t *testing.T) {+ ctx, logs := logtest.DebugContext()+ fields := runSource(t, ctx, logs).ContextMap()++ assert.Equal(t, "dummy", fields["source_name"])+ assert.Contains(t, fields, "job_id")+ assert.Contains(t, fields, "source_id")+ assert.Contains(t, fields, "source_type")+ })++ t.Run("fields set by the caller are kept and not repeated", func(t *testing.T) {+ ctx, logs := logtest.DebugContext()+ ctx = context.WithValue(ctx, "source_name", "set by caller")+ entry := runSource(t, ctx, logs)++ // count the raw fields, since ContextMap would hide a duplicate key+ count := 0+ for _, field := range entry.Context {+ if field.Key == "source_name" {+ count+++ }+ }+ assert.Equal(t, 1, count)+ assert.Equal(t, "set by caller", entry.ContextMap()["source_name"])+ })+}