From 7e85fc454eb53235fe31e9a510f0fb4338b89459 Mon Sep 17 00:00:00 2001 From: feifeiiiiiiiiii Date: Tue, 4 Feb 2020 23:58:53 +0800 Subject: [PATCH] Throw better exception on wrong `dynamic_templates` syntax (#51783) Currently, a mappings update request, where dynamic_mappings is an object instead of an array, results in a http response with a 500 code. This PR checks for this condition and throws a MapperParsingException like we do for other malformed mapping cases. Closes #51486 --- .../index/mapper/RootObjectMapper.java | 3 +++ .../index/mapper/RootObjectMapperTests.java | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/server/src/main/java/org/elasticsearch/index/mapper/RootObjectMapper.java b/server/src/main/java/org/elasticsearch/index/mapper/RootObjectMapper.java index cd3242e98a2d7..27afb49e36998 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/RootObjectMapper.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/RootObjectMapper.java @@ -168,6 +168,9 @@ protected boolean processField(RootObjectMapper.Builder builder, String fieldNam } ] */ + if ((fieldNode instanceof List) == false) { + throw new MapperParsingException("Dynamic template syntax error. An array of named objects is expected."); + } List tmplNodes = (List) fieldNode; List templates = new ArrayList<>(); for (Object tmplNode : tmplNodes) { diff --git a/server/src/test/java/org/elasticsearch/index/mapper/RootObjectMapperTests.java b/server/src/test/java/org/elasticsearch/index/mapper/RootObjectMapperTests.java index 0b805eb726646..a8bd8f5a0e2d3 100644 --- a/server/src/test/java/org/elasticsearch/index/mapper/RootObjectMapperTests.java +++ b/server/src/test/java/org/elasticsearch/index/mapper/RootObjectMapperTests.java @@ -185,4 +185,19 @@ public void testIllegalFormatField() throws Exception { assertEquals("Invalid format: [[test_format]]: expected string value", e.getMessage()); } } + + public void testIllegalDynamicTemplates() throws Exception { + String mapping = Strings.toString(XContentFactory.jsonBuilder() + .startObject() + .startObject("type") + .startObject("dynamic_templates") + .endObject() + .endObject() + .endObject()); + + DocumentMapperParser parser = createIndex("test").mapperService().documentMapperParser(); + MapperParsingException e = expectThrows(MapperParsingException.class, + () -> parser.parse("type", new CompressedXContent(mapping))); + assertEquals("Dynamic template syntax error. An array of named objects is expected.", e.getMessage()); + } }