feat(rule): validate & sort rule when generating (#1817)

This commit is contained in:
Richard Gomez authored and GitHub committed 2025-04-12 10:09:19 -05:00
1 parent 107a41827b
commit cfdeb0d7e0
18 files changed
+125 -95

No files matched your search

+1 -1
View File
@@ -11,7 +11,7 @@ import (
func CreateGlobalConfig() config.Config { func CreateGlobalConfig() config.Config {
return config.Config{ return config.Config{
Title: "gitleaks config", Title: "gitleaks config",
Allowlist: config.Allowlist{ Allowlist: &config.Allowlist{
Description: "global allow lists", Description: "global allow lists",
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// ----------- General placeholders ----------- // ----------- General placeholders -----------
+20 -2
View File
@@ -1,6 +1,7 @@
package main package main
import ( import (
"golang.org/x/exp/slices"
"os" "os"
"text/template" "text/template"
@@ -18,7 +19,7 @@ const (
func main() { func main() {
if len(os.Args) < 2 { if len(os.Args) < 2 {
os.Stderr.WriteString("Specify path to the gitleaks.toml config\n") _, _ = os.Stderr.WriteString("Specify path to the gitleaks.toml config\n")
os.Exit(2) os.Exit(2)
} }
gitleaksConfigPath := os.Args[1] gitleaksConfigPath := os.Args[1]
@@ -239,9 +240,18 @@ func main() {
// ensure rules have unique ids // ensure rules have unique ids
ruleLookUp := make(map[string]config.Rule, len(configRules)) ruleLookUp := make(map[string]config.Rule, len(configRules))
for _, rule := range configRules { for _, rule := range configRules {
if err := rule.Validate(); err != nil {
logging.Fatal().Err(err).
Str("rule-id", rule.RuleID).
Msg("Failed to validate rule")
}
sortRule(rule)
// check if rule is in ruleLookUp // check if rule is in ruleLookUp
if _, ok := ruleLookUp[rule.RuleID]; ok { if _, ok := ruleLookUp[rule.RuleID]; ok {
logging.Fatal().Msgf("rule id %s is not unique", rule.RuleID) logging.Fatal().
Str("rule-id", rule.RuleID).
Msg("rule id is not unique")
} }
// TODO: eventually change all the signatures to get ride of this // TODO: eventually change all the signatures to get ride of this
// nasty dereferencing. // nasty dereferencing.
@@ -257,6 +267,7 @@ func main() {
if err != nil { if err != nil {
logging.Fatal().Err(err).Msg("Failed to create rules.toml") logging.Fatal().Err(err).Msg("Failed to create rules.toml")
} }
defer f.Close()
cfg := base.CreateGlobalConfig() cfg := base.CreateGlobalConfig()
cfg.Rules = ruleLookUp cfg.Rules = ruleLookUp
@@ -264,3 +275,10 @@ func main() {
logging.Fatal().Err(err).Msg("could not execute template") logging.Fatal().Err(err).Msg("could not execute template")
} }
} }
// sortRule makes the generated config deterministic.
func sortRule(r *config.Rule) {
for _, a := range r.Allowlists {
slices.Sort(a.StopWords)
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ func AWS() *config.Rule {
"ABIA", // AWS STS service bearer token "ABIA", // AWS STS service bearer token
"ACCA", // Context-specific credential "ACCA", // Context-specific credential
}, },
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
regexp.MustCompile(`.+EXAMPLE$`), regexp.MustCompile(`.+EXAMPLE$`),
+2 -2
View File
@@ -16,7 +16,7 @@ func CurlBasicAuth() *config.Rule {
Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})("(:[^"]{3,}|[^:"]{3,}:|[^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`), Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})("(:[^"]{3,}|[^:"]{3,}:|[^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`),
Keywords: []string{"curl"}, Keywords: []string{"curl"},
Entropy: 2, Entropy: 2,
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
regexp.MustCompile(`[^:]+:(?:change(?:it|me)|pass(?:word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords regexp.MustCompile(`[^:]+:(?:change(?:it|me)|pass(?:word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords
@@ -109,7 +109,7 @@ func CurlHeaderAuth() *config.Rule {
fmt.Sprintf(`\bcurl\b(?:.*?|.*?(?:[\r\n]{1,2}.*?){1,5})[ \t\n\r](?:-H|--header)(?:=|[ \t]{0,5})(?:"%s"|'%s')(?:\B|\s|\z)`, authPat, authPat)), fmt.Sprintf(`\bcurl\b(?:.*?|.*?(?:[\r\n]{1,2}.*?){1,5})[ \t\n\r](?:-H|--header)(?:=|[ \t]{0,5})(?:"%s"|'%s')(?:\B|\s|\z)`, authPat, authPat)),
Entropy: 2.75, Entropy: 2.75,
Keywords: []string{"curl"}, Keywords: []string{"curl"},
//Allowlists: []config.Allowlist{ //Allowlists: []*config.Allowlist{
// { // {
// Regexes: []*regexp.Regexp{}, // Regexes: []*regexp.Regexp{},
// }, // },
+1 -1
View File
@@ -34,7 +34,7 @@ func GCPAPIKey() *config.Rule {
Keywords: []string{ Keywords: []string{
"AIza", "AIza",
}, },
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// example keys from https://github.com/firebase/firebase-android-sdk // example keys from https://github.com/firebase/firebase-android-sdk
+2 -2
View File
@@ -36,7 +36,7 @@ func GenericCredential() *config.Rule {
"token", "token",
}, },
Entropy: 3.5, Entropy: 3.5,
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
// NOTE: this is a goofy hack to get around the fact there golang's regex engine does not support positive lookaheads. // NOTE: this is a goofy hack to get around the fact there golang's regex engine does not support positive lookaheads.
// Ideally we would want to ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters. // Ideally we would want to ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters.
@@ -281,7 +281,7 @@ jdbc.snowflake.url=`,
} }
func newPlausibleSecret(regex string) string { func newPlausibleSecret(regex string) string {
allowList := config.Allowlist{StopWords: DefaultStopWords} allowList := &config.Allowlist{StopWords: DefaultStopWords}
// attempt to generate a random secret, // attempt to generate a random secret,
// retrying until it contains at least one digit and no stop words // retrying until it contains at least one digit and no stop words
// TODO: currently the DefaultStopWords list contains many short words, // TODO: currently the DefaultStopWords list contains many short words,
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/zricethezav/gitleaks/v8/regexp" "github.com/zricethezav/gitleaks/v8/regexp"
) )
var githubAllowlist = []config.Allowlist{ var githubAllowlist = []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{ Paths: []*regexp.Regexp{
// https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options // https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options
+1 -1
View File
@@ -15,7 +15,7 @@ func VaultServiceToken() *config.Rule {
Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false), Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false),
Entropy: 3.5, Entropy: 3.5,
Keywords: []string{"hvs.", "s."}, Keywords: []string{"hvs.", "s."},
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357 // https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357
+1 -1
View File
@@ -31,7 +31,7 @@ func KubernetesSecret() *config.Rule {
}, },
// Kubernetes secrets are usually yaml files. // Kubernetes secrets are usually yaml files.
Path: regexp.MustCompile(`(?i)\.ya?ml$`), Path: regexp.MustCompile(`(?i)\.ya?ml$`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// Ignore empty or placeholder values. // Ignore empty or placeholder values.
+1 -1
View File
@@ -14,7 +14,7 @@ func NugetConfigPassword() *config.Rule {
Path: regexp.MustCompile(`(?i)nuget\.config$`), Path: regexp.MustCompile(`(?i)nuget\.config$`),
Keywords: []string{"<add key="}, Keywords: []string{"<add key="},
Entropy: 1, Entropy: 1,
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file // samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file
+22 -4
View File
@@ -38,9 +38,6 @@ type Allowlist struct {
// Paths is a slice of path regular expressions that are allowed to be ignored. // Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp Paths []*regexp.Regexp
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
// Can be `match` or `line`. // Can be `match` or `line`.
// //
// If `match` the _Regexes_ will be tested against the match of the _Rule.Regex_. // If `match` the _Regexes_ will be tested against the match of the _Rule.Regex_.
@@ -50,15 +47,21 @@ type Allowlist struct {
// If RegexTarget is empty, it will be tested against the found secret. // If RegexTarget is empty, it will be tested against the found secret.
RegexTarget string RegexTarget string
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
// StopWords is a slice of stop words that are allowed to be ignored. // StopWords is a slice of stop words that are allowed to be ignored.
// This targets the _secret_, not the content of the regex match like the // This targets the _secret_, not the content of the regex match like the
// Regexes slice. // Regexes slice.
StopWords []string StopWords []string
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
} }
// CommitAllowed returns true if the commit is allowed to be ignored. // CommitAllowed returns true if the commit is allowed to be ignored.
func (a *Allowlist) CommitAllowed(c string) (bool, string) { func (a *Allowlist) CommitAllowed(c string) (bool, string) {
if c == "" { if a == nil || c == "" {
return false, "" return false, ""
} }
@@ -72,15 +75,25 @@ func (a *Allowlist) CommitAllowed(c string) (bool, string) {
// PathAllowed returns true if the path is allowed to be ignored. // PathAllowed returns true if the path is allowed to be ignored.
func (a *Allowlist) PathAllowed(path string) bool { func (a *Allowlist) PathAllowed(path string) bool {
if a == nil || path == "" {
return false
}
return anyRegexMatch(path, a.Paths) return anyRegexMatch(path, a.Paths)
} }
// RegexAllowed returns true if the regex is allowed to be ignored. // RegexAllowed returns true if the regex is allowed to be ignored.
func (a *Allowlist) RegexAllowed(secret string) bool { func (a *Allowlist) RegexAllowed(secret string) bool {
if a == nil || secret == "" {
return false
}
return anyRegexMatch(secret, a.Regexes) return anyRegexMatch(secret, a.Regexes)
} }
func (a *Allowlist) ContainsStopWord(s string) (bool, string) { func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
if a == nil || s == "" {
return false, ""
}
s = strings.ToLower(s) s = strings.ToLower(s)
for _, stopWord := range a.StopWords { for _, stopWord := range a.StopWords {
if strings.Contains(s, strings.ToLower(stopWord)) { if strings.Contains(s, strings.ToLower(stopWord)) {
@@ -91,6 +104,10 @@ func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
} }
func (a *Allowlist) Validate() error { func (a *Allowlist) Validate() error {
if a.validated {
return nil
}
// Disallow empty allowlists. // Disallow empty allowlists.
if len(a.Commits) == 0 && if len(a.Commits) == 0 &&
len(a.Paths) == 0 && len(a.Paths) == 0 &&
@@ -116,5 +133,6 @@ func (a *Allowlist) Validate() error {
a.StopWords = maps.Keys(uniqueStopwords) a.StopWords = maps.Keys(uniqueStopwords)
} }
a.validated = true
return nil return nil
} }
+1
View File
@@ -148,6 +148,7 @@ func TestValidate(t *testing.T) {
opts = cmp.Options{ opts = cmp.Options{
cmp.Comparer(regexComparer), cmp.Comparer(regexComparer),
cmpopts.SortSlices(arrayComparer), cmpopts.SortSlices(arrayComparer),
cmpopts.IgnoreUnexported(Allowlist{}),
} }
) )
if diff := cmp.Diff(tt.input, tt.expected, opts); diff != "" { if diff := cmp.Diff(tt.input, tt.expected, opts); diff != "" {
+6 -8
View File
@@ -67,7 +67,7 @@ type Config struct {
Path string Path string
Description string Description string
Rules map[string]Rule Rules map[string]Rule
Allowlist Allowlist Allowlist *Allowlist
Keywords map[string]struct{} Keywords map[string]struct{}
// used to keep sarif results consistent // used to keep sarif results consistent
@@ -164,17 +164,15 @@ func (vc *ViperConfig) Translate() (Config, error) {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a)) allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
} }
allowlist := Allowlist{ allowlist := &Allowlist{
Description: a.Description,
MatchCondition: condition, MatchCondition: condition,
Commits: a.Commits,
Paths: allowlistPaths,
RegexTarget: a.RegexTarget, RegexTarget: a.RegexTarget,
Regexes: allowlistRegexes, Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: a.Commits,
StopWords: a.StopWords, StopWords: a.StopWords,
} }
if err := allowlist.Validate(); err != nil {
return Config{}, fmt.Errorf("%s: %w", cr.RuleID, err)
}
cr.Allowlists = append(cr.Allowlists, allowlist) cr.Allowlists = append(cr.Allowlists, allowlist)
} }
orderedRules = append(orderedRules, cr.RuleID) orderedRules = append(orderedRules, cr.RuleID)
@@ -192,7 +190,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
Description: vc.Description, Description: vc.Description,
Extend: vc.Extend, Extend: vc.Extend,
Rules: rulesMap, Rules: rulesMap,
Allowlist: Allowlist{ Allowlist: &Allowlist{
RegexTarget: vc.Allowlist.RegexTarget, RegexTarget: vc.Allowlist.RegexTarget,
Regexes: allowlistRegexes, Regexes: allowlistRegexes,
Paths: allowlistPaths, Paths: allowlistPaths,
+13 -8
View File
@@ -2,6 +2,7 @@ package config
import ( import (
"fmt" "fmt"
"github.com/google/go-cmp/cmp/cmpopts"
"testing" "testing"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
@@ -33,7 +34,7 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile(`example\d+`), Regex: regexp.MustCompile(`example\d+`),
Tags: []string{}, Tags: []string{},
Keywords: []string{}, Keywords: []string{},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{ {
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("123")}, Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
@@ -66,7 +67,7 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"), Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{ {
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")}, Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
@@ -84,7 +85,7 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"), Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{ {
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
Commits: []string{"allowthiscommit"}, Commits: []string{"allowthiscommit"},
@@ -102,7 +103,7 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"), Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{ {
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(".go")}, Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
@@ -178,7 +179,7 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`), Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{ {
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
StopWords: []string{"fake"}, StopWords: []string{"fake"},
@@ -206,7 +207,7 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`), Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{ {
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
StopWords: []string{"fake"}, StopWords: []string{"fake"},
@@ -234,8 +235,9 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`), Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{ {
Description: "False positive. Keys used for colors match the rule, and should be excluded.",
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)},
}, },
@@ -401,7 +403,10 @@ func TestTranslate(t *testing.T) {
} }
return x.String() == y.String() return x.String() == y.String()
} }
opts := cmp.Options{cmp.Comparer(regexComparer)} opts := cmp.Options{
cmp.Comparer(regexComparer),
cmpopts.IgnoreUnexported(Rule{}, Allowlist{}),
}
if diff := cmp.Diff(tt.cfg.Rules, cfg.Rules, opts); diff != "" { if diff := cmp.Diff(tt.cfg.Rules, cfg.Rules, opts); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", tt.cfgName, diff) t.Errorf("%s diff: (-want +got)\n%s", tt.cfgName, diff)
} }
+5 -36
View File
@@ -595,6 +595,8 @@ regexes = [
] ]
stopwords = [ stopwords = [
"000000", "000000",
"6fe4476ee5a1832882e326b506d14126",
"_ec2_",
"aaaaaa", "aaaaaa",
"about", "about",
"abstract", "abstract",
@@ -610,9 +612,9 @@ stopwords = [
"activity", "activity",
"adapter", "adapter",
"add-", "add-",
"add-on",
"add.", "add.",
"add_", "add_",
"add-on",
"addon", "addon",
"addres", "addres",
"admin", "admin",
@@ -655,10 +657,7 @@ stopwords = [
"any_", "any_",
"apache", "apache",
"app-", "app-",
"app-",
"app.", "app.",
"app.",
"app_",
"app_", "app_",
"apple", "apple",
"arch", "arch",
@@ -682,7 +681,6 @@ stopwords = [
"aura", "aura",
"auth", "auth",
"author", "author",
"author",
"authorize", "authorize",
"auto", "auto",
"automated", "automated",
@@ -803,7 +801,6 @@ stopwords = [
"cli.", "cli.",
"cli_", "cli_",
"client", "client",
"client",
"clojure", "clojure",
"clone", "clone",
"closure", "closure",
@@ -838,7 +835,6 @@ stopwords = [
"concept", "concept",
"conf", "conf",
"config", "config",
"config",
"connect", "connect",
"connector", "connector",
"console", "console",
@@ -897,7 +893,6 @@ stopwords = [
"dead", "dead",
"debian", "debian",
"debug", "debug",
"debug",
"debugger", "debugger",
"deck", "deck",
"define", "define",
@@ -929,10 +924,7 @@ stopwords = [
"dns-", "dns-",
"dns_", "dns_",
"doc-", "doc-",
"doc-",
"doc.", "doc.",
"doc.",
"doc_",
"doc_", "doc_",
"docker", "docker",
"docpad", "docpad",
@@ -946,8 +938,8 @@ stopwords = [
"dom.", "dom.",
"dom_", "dom_",
"domain", "domain",
"done",
"don't", "don't",
"done",
"dot-", "dot-",
"dot.", "dot.",
"dot_", "dot_",
@@ -967,7 +959,6 @@ stopwords = [
"dsl_", "dsl_",
"dynamic", "dynamic",
"easy", "easy",
"_ec2_",
"ecdsa", "ecdsa",
"eclipse", "eclipse",
"edit", "edit",
@@ -997,7 +988,6 @@ stopwords = [
"event", "event",
"evented", "evented",
"example", "example",
"example",
"exchange", "exchange",
"exercise", "exercise",
"experiment", "experiment",
@@ -1245,10 +1235,7 @@ stopwords = [
"koan", "koan",
"kohana", "kohana",
"lab-", "lab-",
"lab-",
"lab.", "lab.",
"lab.",
"lab_",
"lab_", "lab_",
"lambda", "lambda",
"lamp", "lamp",
@@ -1333,10 +1320,7 @@ stopwords = [
"manifest", "manifest",
"manual", "manual",
"map-", "map-",
"map-",
"map.", "map.",
"map.",
"map_",
"map_", "map_",
"mapper", "mapper",
"mapping", "mapping",
@@ -1422,10 +1406,7 @@ stopwords = [
"nette", "nette",
"network", "network",
"new-", "new-",
"new-",
"new.", "new.",
"new.",
"new_",
"new_", "new_",
"next", "next",
"nginx", "nginx",
@@ -1494,7 +1475,6 @@ stopwords = [
"package", "package",
"packet", "packet",
"page", "page",
"page",
"panel", "panel",
"paper", "paper",
"paperclip", "paperclip",
@@ -1611,8 +1591,8 @@ stopwords = [
"readme", "readme",
"ready", "ready",
"real", "real",
"reality",
"real-time", "real-time",
"reality",
"realtime", "realtime",
"recipe", "recipe",
"recorder", "recorder",
@@ -1678,7 +1658,6 @@ stopwords = [
"rvm_", "rvm_",
"salt", "salt",
"sample", "sample",
"sample",
"sandbox", "sandbox",
"sas-", "sas-",
"sas.", "sas.",
@@ -1729,7 +1708,6 @@ stopwords = [
"set.", "set.",
"set_", "set_",
"setting", "setting",
"setting",
"setup", "setup",
"sha1", "sha1",
"sha2", "sha2",
@@ -1852,19 +1830,12 @@ stopwords = [
"synopsi", "synopsi",
"syntax", "syntax",
"system", "system",
"system",
"tab-",
"tab-", "tab-",
"tab.", "tab.",
"tab.",
"tab_",
"tab_", "tab_",
"table", "table",
"tag-", "tag-",
"tag-",
"tag.", "tag.",
"tag.",
"tag_",
"tag_", "tag_",
"talk", "talk",
"target", "target",
@@ -2003,7 +1974,6 @@ stopwords = [
"website", "website",
"websocket", "websocket",
"welcome", "welcome",
"welcome",
"what", "what",
"what'", "what'",
"when", "when",
@@ -2070,7 +2040,6 @@ stopwords = [
"zsh-", "zsh-",
"zsh.", "zsh.",
"zsh_", "zsh_",
"6fe4476ee5a1832882e326b506d14126",
] ]
[[rules.allowlists]] [[rules.allowlists]]
regexTarget = "line" regexTarget = "line"
+20 -2
View File
@@ -41,11 +41,18 @@ type Rule struct {
Keywords []string Keywords []string
// Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords. // Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords.
Allowlists []Allowlist Allowlists []*Allowlist
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
} }
// Validate guards against common misconfigurations. // Validate guards against common misconfigurations.
func (r Rule) Validate() error { func (r *Rule) Validate() error {
if r.validated {
return nil
}
// Ensure |id| is present. // Ensure |id| is present.
if strings.TrimSpace(r.RuleID) == "" { if strings.TrimSpace(r.RuleID) == "" {
// Try to provide helpful context, since |id| is empty. // Try to provide helpful context, since |id| is empty.
@@ -70,5 +77,16 @@ func (r Rule) Validate() error {
return fmt.Errorf("%s: invalid regex secret group %d, max regex secret group %d", r.RuleID, r.SecretGroup, r.Regex.NumSubexp()) return fmt.Errorf("%s: invalid regex secret group %d, max regex secret group %d", r.RuleID, r.SecretGroup, r.Regex.NumSubexp())
} }
for _, allowlist := range r.Allowlists {
// This will probably never happen.
if allowlist == nil {
continue
}
if err := allowlist.Validate(); err != nil {
return fmt.Errorf("%s: %w", r.RuleID, err)
}
}
r.validated = true
return nil return nil
} }
+3
View File
@@ -473,6 +473,8 @@ MatchLoop:
continue continue
} }
} }
if d.Config.Allowlist != nil {
// check if the regexTarget is defined in the allowlist "regexes" entry // check if the regexTarget is defined in the allowlist "regexes" entry
// or if the secret is in the list of stopwords // or if the secret is in the list of stopwords
globalAllowlistTarget := finding.Secret globalAllowlistTarget := finding.Secret
@@ -494,6 +496,7 @@ MatchLoop:
Msg("skipping finding: global allowlist stopword") Msg("skipping finding: global allowlist stopword")
continue continue
} }
}
// check if the result matches any of the rule allowlists. // check if the result matches any of the rule allowlists.
for _, a := range r.Allowlists { for _, a := range r.Allowlists {
+24 -24
View File
@@ -915,7 +915,7 @@ func TestDetectWithSymlinks(t *testing.T) {
func TestDetectRuleAllowlist(t *testing.T) { func TestDetectRuleAllowlist(t *testing.T) {
cases := map[string]struct { cases := map[string]struct {
fragment Fragment fragment Fragment
allowlist config.Allowlist allowlist *config.Allowlist
expected []report.Finding expected []report.Finding
}{ }{
// Commit / path // Commit / path
@@ -923,7 +923,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
fragment: Fragment{ fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
}, },
}, },
@@ -931,7 +931,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
fragment: Fragment{ fragment: Fragment{
FilePath: "package-lock.json", FilePath: "package-lock.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
}, },
}, },
@@ -940,7 +940,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json", FilePath: "package-lock.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -951,7 +951,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package.json", FilePath: "package.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -974,7 +974,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json", FilePath: "package-lock.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -998,7 +998,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json", FilePath: "package-lock.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchOr, MatchCondition: config.AllowlistMatchOr,
Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"}, Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -1008,19 +1008,19 @@ func TestDetectRuleAllowlist(t *testing.T) {
// Regex / stopwords // Regex / stopwords
"regex allowed": { "regex allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)}, Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
}, },
}, },
"stopwords allowed": { "stopwords allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
StopWords: []string{"summer"}, StopWords: []string{"summer"},
}, },
}, },
"regex AND stopword allowed": { "regex AND stopword allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)}, Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"2024"}, StopWords: []string{"2024"},
@@ -1031,7 +1031,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "config.js", FilePath: "config.js",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
@@ -1043,7 +1043,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
fragment: Fragment{ fragment: Fragment{
FilePath: "config.js", FilePath: "config.js",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
@@ -1065,7 +1065,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
}, },
"regex AND stopword NOT allowed": { "regex AND stopword NOT allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
regexp.MustCompile(`(?i)winter.+`), regexp.MustCompile(`(?i)winter.+`),
@@ -1089,7 +1089,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b", CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b",
FilePath: "config.js", FilePath: "config.js",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -1111,7 +1111,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
}, },
"regex OR stopword allowed": { "regex OR stopword allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchOr, MatchCondition: config.AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)}, Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"winter"}, StopWords: []string{"winter"},
@@ -1126,7 +1126,7 @@ let password = 'Summer2024!';`
rule := config.Rule{ rule := config.Rule{
RuleID: "test-rule", RuleID: "test-rule",
Regex: regexp.MustCompile(`Summer2024!`), Regex: regexp.MustCompile(`Summer2024!`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
tc.allowlist, tc.allowlist,
}, },
} }
@@ -1320,7 +1320,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "unix-rule", RuleID: "unix-rule",
Regex: regexp.MustCompile(`s3cr3t`), Regex: regexp.MustCompile(`s3cr3t`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
}, },
@@ -1336,7 +1336,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "windows-rule", RuleID: "windows-rule",
Regex: regexp.MustCompile(`s3cr3t`), Regex: regexp.MustCompile(`s3cr3t`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
}, },
@@ -1364,7 +1364,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "unix-rule", RuleID: "unix-rule",
Regex: regexp.MustCompile(`value: "[^"]+"`), Regex: regexp.MustCompile(`value: "[^"]+"`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
@@ -1382,7 +1382,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "windows-rule", RuleID: "windows-rule",
Regex: regexp.MustCompile(`value: "[^"]+"`), Regex: regexp.MustCompile(`value: "[^"]+"`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
@@ -1414,7 +1414,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "unix-rule", RuleID: "unix-rule",
Regex: regexp.MustCompile(`s3cr3t`), Regex: regexp.MustCompile(`s3cr3t`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
}, },
@@ -1431,7 +1431,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "windows-rule", RuleID: "windows-rule",
Regex: regexp.MustCompile(`s3cr3t`), Regex: regexp.MustCompile(`s3cr3t`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
}, },
@@ -1448,7 +1448,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "unix-rule", RuleID: "unix-rule",
Regex: regexp.MustCompile(`value: "[^"]+"`), Regex: regexp.MustCompile(`value: "[^"]+"`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
@@ -1467,7 +1467,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "windows-rule", RuleID: "windows-rule",
Regex: regexp.MustCompile(`value: "[^"]+"`), Regex: regexp.MustCompile(`value: "[^"]+"`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},