Skip to content

Commit 72317fb

Browse files
committed
Validate regular expressions in dynamic templates. (#29013)
Today you would only get these errors at index time. Relates #24749
1 parent 0730ee9 commit 72317fb

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
@@ -62,6 +62,19 @@ public void testParseUnknownMatchType() {
6262
e.getMessage());
6363
}
6464

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

0 commit comments

Comments
 (0)