From 337153b29fd57527d82dae203913b9888c942da9 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 ff967b9dd36..fad840c2f76 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/RootObjectMapper.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/RootObjectMapper.java @@ -163,6 +163,9 @@ public class RootObjectMapper extends ObjectMapper { // } // } // ] + 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 0b805eb7266..fbd9de02fef 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 class RootObjectMapperTests extends ESSingleNodeTestCase { 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()); + } }