From 09d4422cdb47b68e04b3dcdbecd46d6797f02402 Mon Sep 17 00:00:00 2001 From: ahrav Date: Mon, 9 Jan 2023 09:45:30 -0800 Subject: [PATCH] Handle invalid regex for custom detector. (#1005) * Handle invalid regex for custom detector. * Add comment highlighting invalid regex. --- pkg/custom_detectors/custom_detectors.go | 8 ++++---- pkg/custom_detectors/custom_detectors_test.go | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/pkg/custom_detectors/custom_detectors.go b/pkg/custom_detectors/custom_detectors.go index 6a06e008..7b17aecb 100644 --- a/pkg/custom_detectors/custom_detectors.go +++ b/pkg/custom_detectors/custom_detectors.go @@ -64,9 +64,8 @@ func (c *customRegexWebhook) FromData(ctx context.Context, verify bool, data []b for name, regex := range c.GetRegex() { regex, err := regexp.Compile(regex) if err != nil { - // TODO: Log error. - // This should never happen due to validation. - continue + // This will only happen if the regex is invalid. + return nil, err } regexMatches[name] = regex.FindAllStringSubmatch(dataStr, -1) } @@ -183,7 +182,8 @@ func productIndices(lengths ...int) [][]int { // permutateMatches converts the list of all regex matches into all possible // permutations selecting one from each named entry in the map. For example: // {"foo": [matchA, matchB], "bar": [matchC]} becomes -// [{"foo": matchA, "bar": matchC}, {"foo": matchB, "bar": matchC}] +// +// [{"foo": matchA, "bar": matchC}, {"foo": matchB, "bar": matchC}] func permutateMatches(regexMatches map[string][][]string) []map[string][]string { // Get a consistent order for names and their matching lengths. // The lengths are used in calculating the permutation so order matters. diff --git a/pkg/custom_detectors/custom_detectors_test.go b/pkg/custom_detectors/custom_detectors_test.go index 7b4fa85f..b60e65d2 100644 --- a/pkg/custom_detectors/custom_detectors_test.go +++ b/pkg/custom_detectors/custom_detectors_test.go @@ -1,9 +1,11 @@ package custom_detectors import ( + "context" "testing" "github.com/stretchr/testify/assert" + "github.com/trufflesecurity/trufflehog/v3/pkg/pb/custom_detectorspb" "github.com/trufflesecurity/trufflehog/v3/pkg/protoyaml" ) @@ -102,6 +104,21 @@ func TestCustomDetectorsParsing(t *testing.T) { assert.Equal(t, []string{"Authorization: Bearer token"}, got.Verify[0].Headers) } +func TestFromData_InvalidRegEx(t *testing.T) { + c := &customRegexWebhook{ + &custom_detectorspb.CustomRegex{ + Name: "Internal bi tool", + Keywords: []string{"secret_v1_", "pat_v2_"}, + Regex: map[string]string{ + "test": "!!?(?:?)[a-zA-Z0-9]{32}", // invalid regex + }, + }, + } + + _, err := c.FromData(context.Background(), false, []byte("test")) + assert.Error(t, err) +} + func TestProductIndices(t *testing.T) { tests := []struct { name string