4
0

baseline.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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, redact uint, 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.RuleID == b.RuleID &&
  14. finding.Description == b.Description &&
  15. finding.StartLine == b.StartLine &&
  16. finding.EndLine == b.EndLine &&
  17. finding.StartColumn == b.StartColumn &&
  18. finding.EndColumn == b.EndColumn &&
  19. (redact > 0 || (finding.Match == b.Match && finding.Secret == b.Secret)) &&
  20. finding.File == b.File &&
  21. finding.Commit == b.Commit &&
  22. finding.Author == b.Author &&
  23. finding.Email == b.Email &&
  24. finding.Date == b.Date &&
  25. finding.Message == b.Message &&
  26. // Omit checking finding.Fingerprint - if the format of the fingerprint changes, the users will see unexpected behaviour
  27. finding.Entropy == b.Entropy {
  28. return false
  29. }
  30. }
  31. return true
  32. }
  33. func LoadBaseline(baselinePath string) ([]report.Finding, error) {
  34. bytes, err := os.ReadFile(baselinePath)
  35. if err != nil {
  36. return nil, fmt.Errorf("could not open %s", baselinePath)
  37. }
  38. var previousFindings []report.Finding
  39. err = json.Unmarshal(bytes, &previousFindings)
  40. if err != nil {
  41. return nil, fmt.Errorf("the format of the file %s is not supported", baselinePath)
  42. }
  43. return previousFindings, nil
  44. }
  45. func (d *Detector) AddBaseline(baselinePath string, source string) error {
  46. if baselinePath != "" {
  47. absoluteSource, err := filepath.Abs(source)
  48. if err != nil {
  49. return err
  50. }
  51. absoluteBaseline, err := filepath.Abs(baselinePath)
  52. if err != nil {
  53. return err
  54. }
  55. relativeBaseline, err := filepath.Rel(absoluteSource, absoluteBaseline)
  56. if err != nil {
  57. return err
  58. }
  59. baseline, err := LoadBaseline(baselinePath)
  60. if err != nil {
  61. return err
  62. }
  63. d.baseline = baseline
  64. baselinePath = relativeBaseline
  65. }
  66. d.baselinePath = baselinePath
  67. return nil
  68. }