validate.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // == WARNING ==
  2. // These functions are used to generate GitLeak's default config.
  3. // You are free to use these in your own project, HOWEVER, no API stability is guaranteed.
  4. package utils
  5. import (
  6. "github.com/rs/zerolog/log"
  7. "github.com/zricethezav/gitleaks/v8/config"
  8. "github.com/zricethezav/gitleaks/v8/detect"
  9. "strings"
  10. )
  11. func Validate(r config.Rule, truePositives []string, falsePositives []string) *config.Rule {
  12. // normalize keywords like in the config package
  13. var keywords []string
  14. for _, k := range r.Keywords {
  15. keywords = append(keywords, strings.ToLower(k))
  16. }
  17. r.Keywords = keywords
  18. rules := make(map[string]config.Rule)
  19. rules[r.RuleID] = r
  20. d := detect.NewDetector(config.Config{
  21. Rules: rules,
  22. Keywords: keywords,
  23. })
  24. for _, tp := range truePositives {
  25. if len(d.DetectString(tp)) != 1 {
  26. log.Fatal().
  27. Str("rule", r.RuleID).
  28. Str("value", tp).
  29. Str("regex", r.Regex.String()).
  30. Msg("Failed to Validate. True positive was not detected by regex.")
  31. }
  32. }
  33. for _, fp := range falsePositives {
  34. if len(d.DetectString(fp)) != 0 {
  35. log.Fatal().
  36. Str("rule", r.RuleID).
  37. Str("value", fp).
  38. Str("regex", r.Regex.String()).
  39. Msg("Failed to Validate. False positive was detected by regex.")
  40. }
  41. }
  42. return &r
  43. }
  44. func ValidateWithPaths(r config.Rule, truePositives map[string]string, falsePositives map[string]string) *config.Rule {
  45. var keywords []string
  46. for _, k := range r.Keywords {
  47. keywords = append(keywords, strings.ToLower(k))
  48. }
  49. r.Keywords = keywords
  50. rules := make(map[string]config.Rule)
  51. rules[r.RuleID] = r
  52. d := detect.NewDetector(config.Config{
  53. Rules: rules,
  54. Keywords: keywords,
  55. })
  56. for path, tp := range truePositives {
  57. f := detect.Fragment{Raw: tp, FilePath: path}
  58. if len(d.Detect(f)) != 1 {
  59. log.Fatal().
  60. Str("rule", r.RuleID).
  61. Str("value", tp).
  62. Str("regex", r.Regex.String()).
  63. Str("path", r.Path.String()).
  64. Msg("Failed to Validate. True positive was not detected by regex and/or path.")
  65. }
  66. }
  67. for path, fp := range falsePositives {
  68. f := detect.Fragment{Raw: fp, FilePath: path}
  69. if len(d.Detect(f)) != 0 {
  70. log.Fatal().
  71. Str("rule", r.RuleID).
  72. Str("value", fp).
  73. Str("regex", r.Regex.String()).
  74. Str("path", r.Path.String()).
  75. Msg("Failed to Validate. False positive was detected by regex and/or path.")
  76. }
  77. }
  78. return &r
  79. }