Skip to content

Commit eb6c3f6

Browse files
committed
Validate regular expressions in dynamic templates.
Today you would only get these errors at index time. Relates elastic#24749
1 parent 3cf599b commit eb6c3f6

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

server/src/main/java/org/elasticsearch/index/mapper/DynamicTemplate.java

+18-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,24 @@ public static DynamicTemplate parse(String name, Map<String, Object> conf,
216216
}
217217
}
218218
}
219-
return new DynamicTemplate(name, pathMatch, pathUnmatch, match, unmatch, xcontentFieldType, MatchType.fromString(matchPattern), mapping);
219+
220+
final MatchType matchType = MatchType.fromString(matchPattern);
221+
222+
if (indexVersionCreated.onOrAfter(Version.V_6_3_0)) {
223+
// Validate that the pattern
224+
for (String regex : new String[] { pathMatch, match, pathUnmatch, unmatch }) {
225+
if (regex == null) {
226+
continue;
227+
}
228+
try {
229+
matchType.matches(regex, "");
230+
} catch (IllegalArgumentException e) {
231+
throw new IllegalArgumentException("Pattern [" + regex + "] of type [" + matchType + "] is invalid. Cannot create dynamic template [" + name + "].", e);
232+
}
233+
}
234+
}
235+
236+
return new DynamicTemplate(name, pathMatch, pathUnmatch, match, unmatch, xcontentFieldType, matchType, mapping);
220237
}
221238

222239
private final String name;

server/src/test/java/org/elasticsearch/index/mapper/DynamicTemplateTests.java

+13
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,19 @@ public void testParseUnknownMatchType() {
6161
e.getMessage());
6262
}
6363

64+
public void testParseInvalidRegex() {
65+
for (String param : new String[] { "path_match", "match", "path_unmatch", "unmatch" }) {System.out.println(param);
66+
Map<String, Object> templateDef = new HashMap<>();
67+
templateDef.put("match", "foo");
68+
templateDef.put(param, "*a");
69+
templateDef.put("match_pattern", "regex");
70+
templateDef.put("mapping", Collections.singletonMap("store", true));
71+
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
72+
() -> DynamicTemplate.parse("my_template", templateDef, Version.V_6_3_0));
73+
assertEquals("Pattern [*a] of type [regex] is invalid. Cannot create dynamic template [my_template].", e.getMessage());
74+
}
75+
}
76+
6477
public void testMatchAllTemplate() {
6578
Map<String, Object> templateDef = new HashMap<>();
6679
templateDef.put("match_mapping_type", "*");

0 commit comments

Comments
 (0)