rule.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package config
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. )
  7. // Rules contain information that define details on how to detect secrets
  8. type Rule struct {
  9. // RuleID is a unique identifier for this rule
  10. RuleID string
  11. // Description is the description of the rule.
  12. Description string
  13. // Entropy is a float representing the minimum shannon
  14. // entropy a regex group must have to be considered a secret.
  15. Entropy float64
  16. // SecretGroup is an int used to extract secret from regex
  17. // match and used as the group that will have its entropy
  18. // checked if `entropy` is set.
  19. SecretGroup int
  20. // Regex is a golang regular expression used to detect secrets.
  21. Regex *regexp.Regexp
  22. // Path is a golang regular expression used to
  23. // filter secrets by path
  24. Path *regexp.Regexp
  25. // Tags is an array of strings used for metadata
  26. // and reporting purposes.
  27. Tags []string
  28. // Keywords are used for pre-regex check filtering. Rules that contain
  29. // keywords will perform a quick string compare check to make sure the
  30. // keyword(s) are in the content being scanned.
  31. Keywords []string
  32. // Allowlist allows a rule to be ignored for specific
  33. // regexes, paths, and/or commits
  34. Allowlist Allowlist
  35. }
  36. // Validate guards against common misconfigurations.
  37. func (r Rule) Validate() error {
  38. // Ensure |id| is present.
  39. if strings.TrimSpace(r.RuleID) == "" {
  40. // Try to provide helpful context, since |id| is empty.
  41. var context string
  42. if r.Regex != nil {
  43. context = ", regex: " + r.Regex.String()
  44. } else if r.Path != nil {
  45. context = ", path: " + r.Path.String()
  46. } else if r.Description != "" {
  47. context = ", description: " + r.Description
  48. }
  49. return fmt.Errorf("rule |id| is missing or empty" + context)
  50. }
  51. // TODO: uncomment this once it works with |extend|.
  52. // See: https://github.com/gitleaks/gitleaks/issues/1507#issuecomment-2352559213
  53. // Ensure the rule actually matches something.
  54. //if r.Regex == nil && r.Path == nil {
  55. // return fmt.Errorf("%s: both |regex| and |path| are empty, this rule will have no effect", r.RuleID)
  56. //}
  57. // Ensure |secretGroup| works.
  58. if r.Regex != nil && r.SecretGroup > r.Regex.NumSubexp() {
  59. return fmt.Errorf("%s: invalid regex secret group %d, max regex secret group %d", r.RuleID, r.SecretGroup, r.Regex.NumSubexp())
  60. }
  61. return nil
  62. }