git.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package detect
  2. import (
  3. "strings"
  4. "sync"
  5. "github.com/gitleaks/go-gitdiff/gitdiff"
  6. "github.com/rs/zerolog/log"
  7. "github.com/zricethezav/gitleaks/v8/config"
  8. "github.com/zricethezav/gitleaks/v8/report"
  9. godocutil "golang.org/x/tools/godoc/util"
  10. )
  11. // FromGit accepts a gitdiff.File channel (structure output from `git log -p`) and a configuration
  12. // struct. Files from the gitdiff.File channel are then checked against each rule in the configuration to
  13. // check for secrets. If any secrets are found, they are added to the list of findings.
  14. func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Options) []*report.Finding {
  15. var findings []*report.Finding
  16. mu := sync.Mutex{}
  17. wg := sync.WaitGroup{}
  18. commitMap := make(map[string]bool)
  19. for f := range files {
  20. // keep track of commits for logging
  21. if f.PatchHeader != nil {
  22. commitMap[f.PatchHeader.SHA] = true
  23. }
  24. wg.Add(1)
  25. go func(f *gitdiff.File) {
  26. defer wg.Done()
  27. if f.IsBinary {
  28. return
  29. }
  30. if f.IsDelete {
  31. return
  32. }
  33. commitSHA := ""
  34. // Check if commit is allowed
  35. if f.PatchHeader != nil {
  36. commitSHA = f.PatchHeader.SHA
  37. if cfg.Allowlist.CommitAllowed(f.PatchHeader.SHA) {
  38. return
  39. }
  40. }
  41. for _, tf := range f.TextFragments {
  42. if f.TextFragments == nil {
  43. // TODO fix this in gitleaks gitdiff fork
  44. // https://github.com/gitleaks/gitleaks/issues/11
  45. continue
  46. }
  47. if !godocutil.IsText([]byte(tf.Raw(gitdiff.OpAdd))) {
  48. continue
  49. }
  50. for _, fi := range DetectFindings(cfg, []byte(tf.Raw(gitdiff.OpAdd)), f.NewName, commitSHA) {
  51. // don't add to start/end lines if finding is from a file only rule
  52. if !strings.HasPrefix(fi.Context, "file detected") {
  53. fi.StartLine += int(tf.NewPosition)
  54. fi.EndLine += int(tf.NewPosition)
  55. }
  56. if f.PatchHeader != nil {
  57. fi.Commit = f.PatchHeader.SHA
  58. fi.Message = f.PatchHeader.Message()
  59. if f.PatchHeader.Author != nil {
  60. fi.Author = f.PatchHeader.Author.Name
  61. fi.Email = f.PatchHeader.Author.Email
  62. }
  63. fi.Date = f.PatchHeader.AuthorDate.String()
  64. }
  65. if outputOptions.Redact {
  66. fi.Redact()
  67. }
  68. if outputOptions.Verbose {
  69. printFinding(fi)
  70. }
  71. mu.Lock()
  72. findings = append(findings, &fi)
  73. mu.Unlock()
  74. }
  75. }
  76. }(f)
  77. }
  78. wg.Wait()
  79. log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(commitMap))
  80. return findings
  81. }