4
0

baseline.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package detect
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "github.com/zricethezav/gitleaks/v8/report"
  8. )
  9. func IsNew(finding report.Finding, baseline []report.Finding) bool {
  10. // Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that
  11. // the code requires maintenance if/when the Finding struct changes
  12. for _, b := range baseline {
  13. if finding.Author == b.Author &&
  14. finding.Commit == b.Commit &&
  15. finding.Date == b.Date &&
  16. finding.Description == b.Description &&
  17. finding.Email == b.Email &&
  18. finding.EndColumn == b.EndColumn &&
  19. finding.EndLine == b.EndLine &&
  20. finding.Entropy == b.Entropy &&
  21. finding.File == b.File &&
  22. // Omit checking finding.Fingerprint - if the format of the fingerprint changes, the users will see unexpected behaviour
  23. finding.Match == b.Match &&
  24. finding.Message == b.Message &&
  25. finding.RuleID == b.RuleID &&
  26. finding.Secret == b.Secret &&
  27. finding.StartColumn == b.StartColumn &&
  28. finding.StartLine == b.StartLine {
  29. return false
  30. }
  31. }
  32. return true
  33. }
  34. func LoadBaseline(baselinePath string) ([]report.Finding, error) {
  35. bytes, err := os.ReadFile(baselinePath)
  36. if err != nil {
  37. return nil, fmt.Errorf("could not open %s", baselinePath)
  38. }
  39. var previousFindings []report.Finding
  40. err = json.Unmarshal(bytes, &previousFindings)
  41. if err != nil {
  42. return nil, fmt.Errorf("the format of the file %s is not supported", baselinePath)
  43. }
  44. return previousFindings, nil
  45. }
  46. func (d *Detector) AddBaseline(baselinePath string, source string) error {
  47. if baselinePath != "" {
  48. absoluteSource, err := filepath.Abs(source)
  49. if err != nil {
  50. return err
  51. }
  52. absoluteBaseline, err := filepath.Abs(baselinePath)
  53. if err != nil {
  54. return err
  55. }
  56. relativeBaseline, err := filepath.Rel(absoluteSource, absoluteBaseline)
  57. if err != nil {
  58. return err
  59. }
  60. baseline, err := LoadBaseline(baselinePath)
  61. if err != nil {
  62. return err
  63. }
  64. d.baseline = baseline
  65. baselinePath = relativeBaseline
  66. }
  67. d.baselinePath = baselinePath
  68. return nil
  69. }