diff --git a/grok.go b/grok.go index 9036161..2edb9bb 100644 --- a/grok.go +++ b/grok.go @@ -14,9 +14,9 @@ import ( ) var ( - canonical = regexp.MustCompile(`%{(\w+(?::\w+(?::\w+)?)?)}`) - normal = regexp.MustCompile(`%{([\w-.]+(?::[\w-.]+(?::[\w-.]+)?)?)}`) - symbolic = regexp.MustCompile(`\W`) + valid = regexp.MustCompile(`^\w+([-.]\w+)*(:([-.\w]+)(:(string|float|int))?)?$`) + normal = regexp.MustCompile(`%{([\w-.]+(?::[\w-.]+(?::[\w-.]+)?)?)}`) + symbolic = regexp.MustCompile(`\W`) ) // A Config structure is used to configure a Grok parser. @@ -131,7 +131,10 @@ func (g *Grok) addPatternsFromMap(m map[string]string) error { patternDeps := graph{} for k, v := range m { keys := []string{} - for _, key := range canonical.FindAllStringSubmatch(v, -1) { + for _, key := range normal.FindAllStringSubmatch(v, -1) { + if !valid.MatchString(key[1]) { + return fmt.Errorf("invalid pattern %%{%s}", key[1]) + } names := strings.Split(key[1], ":") syntax := names[0] if g.patterns[syntax] == nil { @@ -331,6 +334,9 @@ func (g *Grok) compile(pattern string) (*gRegexp, error) { func (g *Grok) denormalizePattern(pattern string, storedPatterns map[string]*gPattern) (string, semanticTypes, error) { ti := semanticTypes{} for _, values := range normal.FindAllStringSubmatch(pattern, -1) { + if !valid.MatchString(values[1]) { + return "", ti, fmt.Errorf("invalid pattern %%{%s}", values[1]) + } names := strings.Split(values[1], ":") syntax, semantic, alias := names[0], names[0], names[0] diff --git a/grok_test.go b/grok_test.go index d9822cf..ddbb05e 100644 --- a/grok_test.go +++ b/grok_test.go @@ -225,6 +225,19 @@ func TestErrorCaptureUnknowPattern(t *testing.T) { } } +func TestErrorCaptureInvalidPattern(t *testing.T) { + g, _ := New() + pattern := "%{-InvalidPattern-}" + expectederr := "invalid pattern %{-InvalidPattern-}" + _, err := g.Parse(pattern, "") + if err == nil { + t.Fatal("Expected error not set") + } + if err.Error() != expectederr { + t.Fatalf("Expected error %q but got %q", expectederr, err.Error()) + } +} + func TestParse(t *testing.T) { g, _ := New() g.AddPatternsFromPath("./patterns")