Validate regular expressions in dynamic templates. (#29013)

Today you would only get these errors at index time.

Relates #24749
This commit is contained in:
Adrien Grand 2018-03-15 16:43:56 +01:00 committed by GitHub
parent 312ccc05d5
commit 404e776a45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 1 deletions

View File

@ -216,7 +216,24 @@ public class DynamicTemplate implements ToXContentObject {
}
}
}
return new DynamicTemplate(name, pathMatch, pathUnmatch, match, unmatch, xcontentFieldType, MatchType.fromString(matchPattern), mapping);
final MatchType matchType = MatchType.fromString(matchPattern);
if (indexVersionCreated.onOrAfter(Version.V_6_3_0)) {
// Validate that the pattern
for (String regex : new String[] { pathMatch, match, pathUnmatch, unmatch }) {
if (regex == null) {
continue;
}
try {
matchType.matches(regex, "");
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Pattern [" + regex + "] of type [" + matchType + "] is invalid. Cannot create dynamic template [" + name + "].", e);
}
}
}
return new DynamicTemplate(name, pathMatch, pathUnmatch, match, unmatch, xcontentFieldType, matchType, mapping);
}
private final String name;

View File

@ -62,6 +62,19 @@ public class DynamicTemplateTests extends ESTestCase {
e.getMessage());
}
public void testParseInvalidRegex() {
for (String param : new String[] { "path_match", "match", "path_unmatch", "unmatch" }) {
Map<String, Object> templateDef = new HashMap<>();
templateDef.put("match", "foo");
templateDef.put(param, "*a");
templateDef.put("match_pattern", "regex");
templateDef.put("mapping", Collections.singletonMap("store", true));
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> DynamicTemplate.parse("my_template", templateDef, Version.V_6_3_0));
assertEquals("Pattern [*a] of type [regex] is invalid. Cannot create dynamic template [my_template].", e.getMessage());
}
}
public void testMatchAllTemplate() {
Map<String, Object> templateDef = new HashMap<>();
templateDef.put("match_mapping_type", "*");