config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. package config
  2. import (
  3. _ "embed"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "github.com/spf13/viper"
  9. "github.com/zricethezav/gitleaks/v8/logging"
  10. "github.com/zricethezav/gitleaks/v8/regexp"
  11. )
  12. var (
  13. //go:embed gitleaks.toml
  14. DefaultConfig string
  15. // use to keep track of how many configs we can extend
  16. // yea I know, globals bad
  17. extendDepth int
  18. )
  19. const maxExtendDepth = 2
  20. // ViperConfig is the config struct used by the Viper config package
  21. // to parse the config file. This struct does not include regular expressions.
  22. // It is used as an intermediary to convert the Viper config to the Config struct.
  23. type ViperConfig struct {
  24. Title string
  25. Description string
  26. Extend Extend
  27. Rules []struct {
  28. ID string
  29. Description string
  30. Path string
  31. Regex string
  32. SecretGroup int
  33. Entropy float64
  34. Keywords []string
  35. Tags []string
  36. // Deprecated: this is a shim for backwards-compatibility.
  37. // TODO: Remove this in 9.x.
  38. AllowList *viperRuleAllowlist
  39. Allowlists []*viperRuleAllowlist
  40. }
  41. // Deprecated: this is a shim for backwards-compatibility.
  42. // TODO: Remove this in 9.x.
  43. AllowList *viperGlobalAllowlist
  44. Allowlists []*viperGlobalAllowlist
  45. }
  46. type viperRuleAllowlist struct {
  47. Description string
  48. Condition string
  49. Commits []string
  50. Paths []string
  51. RegexTarget string
  52. Regexes []string
  53. StopWords []string
  54. }
  55. type viperGlobalAllowlist struct {
  56. TargetRules []string
  57. viperRuleAllowlist `mapstructure:",squash"`
  58. }
  59. // Config is a configuration struct that contains rules and an allowlist if present.
  60. type Config struct {
  61. Title string
  62. Extend Extend
  63. Path string
  64. Description string
  65. Rules map[string]Rule
  66. Keywords map[string]struct{}
  67. // used to keep sarif results consistent
  68. OrderedRules []string
  69. Allowlists []*Allowlist
  70. }
  71. // Extend is a struct that allows users to define how they want their
  72. // configuration extended by other configuration files.
  73. type Extend struct {
  74. Path string
  75. URL string
  76. UseDefault bool
  77. DisabledRules []string
  78. }
  79. func (vc *ViperConfig) Translate() (Config, error) {
  80. var (
  81. keywords = make(map[string]struct{})
  82. orderedRules []string
  83. rulesMap = make(map[string]Rule)
  84. ruleAllowlists = make(map[string][]*Allowlist)
  85. )
  86. // Validate individual rules.
  87. for _, vr := range vc.Rules {
  88. var (
  89. pathPat *regexp.Regexp
  90. regexPat *regexp.Regexp
  91. )
  92. if vr.Path != "" {
  93. pathPat = regexp.MustCompile(vr.Path)
  94. }
  95. if vr.Regex != "" {
  96. regexPat = regexp.MustCompile(vr.Regex)
  97. }
  98. if vr.Keywords == nil {
  99. vr.Keywords = []string{}
  100. } else {
  101. for i, k := range vr.Keywords {
  102. keyword := strings.ToLower(k)
  103. keywords[keyword] = struct{}{}
  104. vr.Keywords[i] = keyword
  105. }
  106. }
  107. if vr.Tags == nil {
  108. vr.Tags = []string{}
  109. }
  110. cr := Rule{
  111. RuleID: vr.ID,
  112. Description: vr.Description,
  113. Regex: regexPat,
  114. SecretGroup: vr.SecretGroup,
  115. Entropy: vr.Entropy,
  116. Path: pathPat,
  117. Keywords: vr.Keywords,
  118. Tags: vr.Tags,
  119. }
  120. // Parse the rule allowlists, including the older format for backwards compatibility.
  121. if vr.AllowList != nil {
  122. // TODO: Remove this in v9.
  123. if len(vr.Allowlists) > 0 {
  124. return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", cr.RuleID)
  125. }
  126. vr.Allowlists = append(vr.Allowlists, vr.AllowList)
  127. }
  128. for _, a := range vr.Allowlists {
  129. allowlist, err := parseAllowlist(a)
  130. if err != nil {
  131. return Config{}, fmt.Errorf("%s: [[rules.allowlists]] %w", cr.RuleID, err)
  132. }
  133. cr.Allowlists = append(cr.Allowlists, allowlist)
  134. }
  135. orderedRules = append(orderedRules, cr.RuleID)
  136. rulesMap[cr.RuleID] = cr
  137. }
  138. // Assemble the config.
  139. c := Config{
  140. Title: vc.Title,
  141. Description: vc.Description,
  142. Extend: vc.Extend,
  143. Rules: rulesMap,
  144. Keywords: keywords,
  145. OrderedRules: orderedRules,
  146. }
  147. // Parse the config allowlists, including the older format for backwards compatibility.
  148. if vc.AllowList != nil {
  149. // TODO: Remove this in v9.
  150. if len(vc.Allowlists) > 0 {
  151. return Config{}, errors.New("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]")
  152. }
  153. vc.Allowlists = append(vc.Allowlists, vc.AllowList)
  154. }
  155. for _, a := range vc.Allowlists {
  156. allowlist, err := parseAllowlist(&a.viperRuleAllowlist)
  157. if err != nil {
  158. return Config{}, fmt.Errorf("[[allowlists]] %w", err)
  159. }
  160. // Allowlists with |targetRules| aren't added to the global list.
  161. if len(a.TargetRules) > 0 {
  162. for _, ruleID := range a.TargetRules {
  163. // It's not possible to validate |ruleID| until after extend.
  164. ruleAllowlists[ruleID] = append(ruleAllowlists[ruleID], allowlist)
  165. }
  166. } else {
  167. c.Allowlists = append(c.Allowlists, allowlist)
  168. }
  169. }
  170. if maxExtendDepth != extendDepth {
  171. // disallow both usedefault and path from being set
  172. if c.Extend.Path != "" && c.Extend.UseDefault {
  173. return Config{}, errors.New("unable to load config due to extend.path and extend.useDefault being set")
  174. }
  175. if c.Extend.UseDefault {
  176. if err := c.extendDefault(); err != nil {
  177. return Config{}, err
  178. }
  179. } else if c.Extend.Path != "" {
  180. if err := c.extendPath(); err != nil {
  181. return Config{}, err
  182. }
  183. }
  184. }
  185. // Validate the rules after everything has been assembled (including extended configs).
  186. if extendDepth == 0 {
  187. for _, rule := range c.Rules {
  188. if err := rule.Validate(); err != nil {
  189. return Config{}, err
  190. }
  191. }
  192. // Populate targeted configs.
  193. for ruleID, allowlists := range ruleAllowlists {
  194. rule, ok := c.Rules[ruleID]
  195. if !ok {
  196. return Config{}, fmt.Errorf("[[allowlists]] target rule ID '%s' does not exist", ruleID)
  197. }
  198. rule.Allowlists = append(rule.Allowlists, allowlists...)
  199. c.Rules[ruleID] = rule
  200. }
  201. }
  202. return c, nil
  203. }
  204. func parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
  205. var matchCondition AllowlistMatchCondition
  206. switch strings.ToUpper(a.Condition) {
  207. case "AND", "&&":
  208. matchCondition = AllowlistMatchAnd
  209. case "", "OR", "||":
  210. matchCondition = AllowlistMatchOr
  211. default:
  212. return nil, fmt.Errorf("unknown allowlist |condition| '%s' (expected 'and', 'or')", a.Condition)
  213. }
  214. // Validate the target.
  215. regexTarget := a.RegexTarget
  216. if regexTarget != "" {
  217. switch regexTarget {
  218. case "secret":
  219. regexTarget = ""
  220. case "match", "line":
  221. // do nothing
  222. default:
  223. return nil, fmt.Errorf("unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", regexTarget)
  224. }
  225. }
  226. var allowlistRegexes []*regexp.Regexp
  227. for _, a := range a.Regexes {
  228. allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
  229. }
  230. var allowlistPaths []*regexp.Regexp
  231. for _, a := range a.Paths {
  232. allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
  233. }
  234. allowlist := &Allowlist{
  235. Description: a.Description,
  236. MatchCondition: matchCondition,
  237. Commits: a.Commits,
  238. Paths: allowlistPaths,
  239. RegexTarget: regexTarget,
  240. Regexes: allowlistRegexes,
  241. StopWords: a.StopWords,
  242. }
  243. if err := allowlist.Validate(); err != nil {
  244. return nil, err
  245. }
  246. return allowlist, nil
  247. }
  248. func (c *Config) GetOrderedRules() []Rule {
  249. var orderedRules []Rule
  250. for _, id := range c.OrderedRules {
  251. if _, ok := c.Rules[id]; ok {
  252. orderedRules = append(orderedRules, c.Rules[id])
  253. }
  254. }
  255. return orderedRules
  256. }
  257. func (c *Config) extendDefault() error {
  258. extendDepth++
  259. viper.SetConfigType("toml")
  260. if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
  261. return fmt.Errorf("failed to load extended default config, err: %w", err)
  262. }
  263. defaultViperConfig := ViperConfig{}
  264. if err := viper.Unmarshal(&defaultViperConfig); err != nil {
  265. return fmt.Errorf("failed to load extended default config, err: %w", err)
  266. }
  267. cfg, err := defaultViperConfig.Translate()
  268. if err != nil {
  269. return fmt.Errorf("failed to load extended default config, err: %w", err)
  270. }
  271. logging.Debug().Msg("extending config with default config")
  272. c.extend(cfg)
  273. return nil
  274. }
  275. func (c *Config) extendPath() error {
  276. extendDepth++
  277. viper.SetConfigFile(c.Extend.Path)
  278. if err := viper.ReadInConfig(); err != nil {
  279. return fmt.Errorf("failed to load extended config, err: %w", err)
  280. }
  281. extensionViperConfig := ViperConfig{}
  282. if err := viper.Unmarshal(&extensionViperConfig); err != nil {
  283. return fmt.Errorf("failed to load extended config, err: %w", err)
  284. }
  285. cfg, err := extensionViperConfig.Translate()
  286. if err != nil {
  287. return fmt.Errorf("failed to load extended config, err: %w", err)
  288. }
  289. logging.Debug().Msgf("extending config with %s", c.Extend.Path)
  290. c.extend(cfg)
  291. return nil
  292. }
  293. func (c *Config) extendURL() {
  294. // TODO
  295. }
  296. func (c *Config) extend(extensionConfig Config) {
  297. // Get config name for helpful log messages.
  298. var configName string
  299. if c.Extend.Path != "" {
  300. configName = c.Extend.Path
  301. } else {
  302. configName = "default"
  303. }
  304. // Convert |Config.DisabledRules| into a map for ease of access.
  305. disabledRuleIDs := map[string]struct{}{}
  306. for _, id := range c.Extend.DisabledRules {
  307. if _, ok := extensionConfig.Rules[id]; !ok {
  308. logging.Warn().
  309. Str("rule-id", id).
  310. Str("config", configName).
  311. Msg("Disabled rule doesn't exist in extended config.")
  312. }
  313. disabledRuleIDs[id] = struct{}{}
  314. }
  315. for ruleID, baseRule := range extensionConfig.Rules {
  316. // Skip the rule.
  317. if _, ok := disabledRuleIDs[ruleID]; ok {
  318. logging.Debug().
  319. Str("rule-id", ruleID).
  320. Str("config", configName).
  321. Msg("Ignoring rule from extended config.")
  322. continue
  323. }
  324. currentRule, ok := c.Rules[ruleID]
  325. if !ok {
  326. // Rule doesn't exist, add it to the config.
  327. c.Rules[ruleID] = baseRule
  328. for _, k := range baseRule.Keywords {
  329. c.Keywords[k] = struct{}{}
  330. }
  331. c.OrderedRules = append(c.OrderedRules, ruleID)
  332. } else {
  333. // Rule exists, merge our changes into the base.
  334. if currentRule.Description != "" {
  335. baseRule.Description = currentRule.Description
  336. }
  337. if currentRule.Entropy != 0 {
  338. baseRule.Entropy = currentRule.Entropy
  339. }
  340. if currentRule.SecretGroup != 0 {
  341. baseRule.SecretGroup = currentRule.SecretGroup
  342. }
  343. if currentRule.Regex != nil {
  344. baseRule.Regex = currentRule.Regex
  345. }
  346. if currentRule.Path != nil {
  347. baseRule.Path = currentRule.Path
  348. }
  349. baseRule.Tags = append(baseRule.Tags, currentRule.Tags...)
  350. baseRule.Keywords = append(baseRule.Keywords, currentRule.Keywords...)
  351. baseRule.Allowlists = append(baseRule.Allowlists, currentRule.Allowlists...)
  352. // The keywords from the base rule and the extended rule must be merged into the global keywords list
  353. for _, k := range baseRule.Keywords {
  354. c.Keywords[k] = struct{}{}
  355. }
  356. c.Rules[ruleID] = baseRule
  357. }
  358. }
  359. // append allowlists, not attempting to merge
  360. c.Allowlists = append(c.Allowlists, extensionConfig.Allowlists...)
  361. // sort to keep extended rules in order
  362. sort.Strings(c.OrderedRules)
  363. }