git.go 2.1 KB

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