leak.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package scan
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/zricethezav/gitleaks/v7/options"
  8. "github.com/go-git/go-git/v5/plumbing/object"
  9. )
  10. // Leak is a struct that contains information about some line of code that contains
  11. // sensitive information as determined by the rules set in a gitleaks config
  12. type Leak struct {
  13. Line string `json:"line"`
  14. LineNumber int `json:"lineNumber"`
  15. Offender string `json:"offender"`
  16. Commit string `json:"commit"`
  17. Repo string `json:"repo"`
  18. RepoURL string `json:"repoURL"`
  19. LeakURL string `json:"leakURL"`
  20. Rule string `json:"rule"`
  21. Message string `json:"commitMessage"`
  22. Author string `json:"author"`
  23. Email string `json:"email"`
  24. File string `json:"file"`
  25. Date time.Time `json:"date"`
  26. Tags string `json:"tags"`
  27. }
  28. // RedactLeak will replace the offending string with "REDACTED" in both
  29. // the offender and line field of the leak which.
  30. func RedactLeak(leak Leak) Leak {
  31. leak.Line = strings.Replace(leak.Line, leak.Offender, "REDACTED", -1)
  32. leak.Offender = "REDACTED"
  33. return leak
  34. }
  35. // NewLeak creates a new leak from common data all leaks must have, line, offender, linenumber
  36. func NewLeak(line string, offender string, lineNumber int) Leak {
  37. return Leak{
  38. Line: line,
  39. Offender: offender,
  40. LineNumber: lineNumber,
  41. }
  42. }
  43. // WithCommit adds commit data to the leak
  44. func (leak Leak) WithCommit(commit *object.Commit) Leak {
  45. leak.Commit = commit.Hash.String()
  46. leak.Author = commit.Author.Name
  47. leak.Email = commit.Author.Email
  48. leak.Message = commit.Message
  49. leak.Date = commit.Author.When
  50. return leak
  51. }
  52. // Log logs a leak and redacts if necessary
  53. func (leak Leak) Log(opts options.Options) {
  54. if !opts.Quiet && !opts.Verbose {
  55. return
  56. }
  57. if opts.Redact {
  58. leak = RedactLeak(leak)
  59. }
  60. if opts.Quiet {
  61. var b []byte
  62. b, _ = json.Marshal(leak)
  63. fmt.Println(string(b))
  64. } else {
  65. var b []byte
  66. b, _ = json.MarshalIndent(leak, "", " ")
  67. fmt.Println(string(b))
  68. }
  69. }
  70. // URL generates a url to the leak if leak.RepoURL is set
  71. func (leak Leak) URL() string {
  72. if leak.RepoURL != "" {
  73. return fmt.Sprintf("%s/blob/%s/%s#L%d", leak.RepoURL, leak.Commit, leak.File, leak.LineNumber)
  74. }
  75. return ""
  76. }