leak.go 2.0 KB

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