This is an automated email from the ASF dual-hosted git repository.

Croway pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new fd595cebb623 CAMEL-27442: camel-xsd-json - a message nested too deep 
for the thread stack fails the same way in both directions
fd595cebb623 is described below

commit fd595cebb623d12be43b8926e15d48cbebcb2ed1
Author: croway <[email protected]>
AuthorDate: Mon Nov 23 14:03:39 2026 +0100

    CAMEL-27442: camel-xsd-json - a message nested too deep for the thread 
stack fails the same way in both directions
    
    On a thread stack lowered with -Xss, the stack can overflow before the limit
    of 512 levels:
    
    - XML to JSON now also turns the StackOverflowError into an
      IllegalArgumentException, as JSON to XML does since CAMEL-27428, so that
      onException(IllegalArgumentException) handles both directions.
    - The message says the level the conversion reached.
    - JSON to XML accepted 513 levels and XML to JSON 512, so unmarshal refused
      what marshal wrote: both accept 512 levels now.
    - The documentation says what limits the nesting: 512 levels, the XML parser
      (jdk.xml.maxElementDepth is 100 on JDK 25) and the thread stack.
---
 .../camel/catalog/docs/xsdJson-dataformat.adoc     | 13 ++++-
 .../src/main/docs/xsdJson-dataformat.adoc          | 13 ++++-
 .../apache/camel/dataformat/xsdjson/JsonToXml.java | 15 +++---
 .../apache/camel/dataformat/xsdjson/XmlToJson.java | 24 ++++++++++
 .../dataformat/xsdjson/XsdJsonDataFormat.java      |  7 ++-
 .../dataformat/xsdjson/XsdJsonSecurityTest.java    | 56 +++++++---------------
 .../dataformat/xsdjson/XsdJsonTestSupport.java     | 54 +++++++++++++++++++++
 .../dataformat/xsdjson/XsdJsonWoodstoxTest.java    | 45 +++++++++++++++--
 8 files changed, 171 insertions(+), 56 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/xsdJson-dataformat.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/xsdJson-dataformat.adoc
index c63d6600fa71..36d76d180692 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/xsdJson-dataformat.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/xsdJson-dataformat.adoc
@@ -151,8 +151,17 @@ with the same scheme as the `schema` option: a schema 
loaded from `https:` canno
 resource.
 
 The message XML is read with StAX with DTDs and external entities turned off, 
and a document with a DOCTYPE is
-refused. Nothing from the message is evaluated. The nesting of elements is 
limited (512 levels, or less when the XML
-parser of the JVM has a lower limit). The size of a message is otherwise 
limited by the route.
+refused. Nothing from the message is evaluated. The size of a message is 
otherwise limited by the route.
+
+The nesting of the elements that the data format maps is limited to 512 levels 
in both directions, and a message
+nested deeper fails with an `IllegalArgumentException` (unknown content 
skipped with `ignoreUnknown` is not counted).
+Two other limits can be lower:
+
+* The XML parser: the parser of the JDK stops at `jdk.xml.maxElementDepth`, 
which is 100 on JDK 25 (no limit on
+  JDK 21). Woodstox, which CXF brings, allows more than 512.
+* The stack of the thread: each level of nesting takes some of it. The default 
stack of the JVM (1 MB or more)
+  normally holds 512 levels, but a stack lowered with `-Xss` (such as 
`-Xss256k`) holds far fewer. A message nested
+  deeper than the stack holds fails with an `IllegalArgumentException` that 
says the level the conversion reached.
 
 == Usage
 
diff --git a/components/camel-xsd-json/src/main/docs/xsdJson-dataformat.adoc 
b/components/camel-xsd-json/src/main/docs/xsdJson-dataformat.adoc
index c63d6600fa71..36d76d180692 100644
--- a/components/camel-xsd-json/src/main/docs/xsdJson-dataformat.adoc
+++ b/components/camel-xsd-json/src/main/docs/xsdJson-dataformat.adoc
@@ -151,8 +151,17 @@ with the same scheme as the `schema` option: a schema 
loaded from `https:` canno
 resource.
 
 The message XML is read with StAX with DTDs and external entities turned off, 
and a document with a DOCTYPE is
-refused. Nothing from the message is evaluated. The nesting of elements is 
limited (512 levels, or less when the XML
-parser of the JVM has a lower limit). The size of a message is otherwise 
limited by the route.
+refused. Nothing from the message is evaluated. The size of a message is 
otherwise limited by the route.
+
+The nesting of the elements that the data format maps is limited to 512 levels 
in both directions, and a message
+nested deeper fails with an `IllegalArgumentException` (unknown content 
skipped with `ignoreUnknown` is not counted).
+Two other limits can be lower:
+
+* The XML parser: the parser of the JDK stops at `jdk.xml.maxElementDepth`, 
which is 100 on JDK 25 (no limit on
+  JDK 21). Woodstox, which CXF brings, allows more than 512.
+* The stack of the thread: each level of nesting takes some of it. The default 
stack of the JVM (1 MB or more)
+  normally holds 512 levels, but a stack lowered with `-Xss` (such as 
`-Xss256k`) holds far fewer. A message nested
+  deeper than the stack holds fails with an `IllegalArgumentException` that 
says the level the conversion reached.
 
 == Usage
 
diff --git 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/JsonToXml.java
 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/JsonToXml.java
index 5b3da8c08830..c32f578d65d1 100644
--- 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/JsonToXml.java
+++ 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/JsonToXml.java
@@ -53,6 +53,7 @@ final class JsonToXml {
     private final Set<String> inScope = new HashSet<>();
     private final Deque<List<String>> declared = new ArrayDeque<>();
     private int generated;
+    private int deepest;
 
     JsonToXml(XsdModel model, boolean ignoreUnknown, String textName, boolean 
pretty, XMLStreamWriter writer) {
         this.model = model;
@@ -73,16 +74,18 @@ final class JsonToXml {
             writeElement(root, value, "/" + root.jsonName(), 0);
         } catch (StackOverflowError e) {
             // the depth limit is checked per element, but a small thread 
stack can be exhausted before that limit
-            throw new IllegalArgumentException(
-                    "The JSON is nested too deep for the thread stack (the 
configured maximum is " + XmlToJson.MAX_DEPTH
-                                               + " levels)",
-                    e);
+            throw XmlToJson.tooDeepForTheStack("JSON", deepest, e);
         }
     }
 
     private void writeElement(Element element, Object value, String path, int 
depth) throws XMLStreamException {
-        if (depth > XmlToJson.MAX_DEPTH) {
-            throw new IllegalArgumentException("The JSON is nested deeper than 
" + XmlToJson.MAX_DEPTH + " at " + path);
+        // the depth of the root is 0 (no indentation), so the element is at 
level depth + 1
+        if (depth >= XmlToJson.MAX_DEPTH) {
+            throw new IllegalArgumentException(
+                    "The JSON is nested deeper than " + XmlToJson.MAX_DEPTH + 
" elements at " + path);
+        }
+        if (depth >= deepest) {
+            deepest = depth + 1;
         }
         if (element.unsupported != null) {
             throw new IllegalArgumentException("Cannot map " + path + ": " + 
element.unsupported);
diff --git 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XmlToJson.java
 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XmlToJson.java
index 01c2bb0ab87a..36d743fb9b09 100644
--- 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XmlToJson.java
+++ 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XmlToJson.java
@@ -46,6 +46,7 @@ final class XmlToJson {
     private final XsdModel model;
     private final boolean ignoreUnknown;
     private final String textName;
+    private int deepest;
 
     XmlToJson(XsdModel model, boolean ignoreUnknown, String textName) {
         this.model = model;
@@ -53,6 +54,26 @@ final class XmlToJson {
         this.textName = textName;
     }
 
+    /**
+     * The error when the stack of the thread overflows before the limit of 
{@link #MAX_DEPTH} levels is reached.
+     *
+     * @param format the format of the message, JSON or XML
+     * @param level  the deepest level reached, the root element being level 1
+     */
+    static IllegalArgumentException tooDeepForTheStack(String format, int 
level, StackOverflowError cause) {
+        return new IllegalArgumentException(
+                "The " + format + " is nested too deep for the thread stack, 
which overflowed after the conversion"
+                                            + " reached level " + level + " 
(the data format allows " + MAX_DEPTH + " levels)",
+                cause);
+    }
+
+    /**
+     * The deepest level of element read, the root element being level 1.
+     */
+    int deepest() {
+        return deepest;
+    }
+
     /**
      * A StAX factory for message XML: no DTD, no external entities.
      */
@@ -106,6 +127,9 @@ final class XmlToJson {
         if (depth > MAX_DEPTH) {
             throw new IllegalArgumentException("The XML is nested deeper than 
" + MAX_DEPTH + " elements at " + path);
         }
+        if (depth > deepest) {
+            deepest = depth;
+        }
         if (element.unsupported != null) {
             throw unsupported(element.unsupported, path);
         }
diff --git 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonDataFormat.java
 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonDataFormat.java
index 301e850460c9..663ec242ae61 100644
--- 
a/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonDataFormat.java
+++ 
b/components/camel-xsd-json/src/main/java/org/apache/camel/dataformat/xsdjson/XsdJsonDataFormat.java
@@ -187,12 +187,15 @@ public class XsdJsonDataFormat extends ServiceSupport 
implements DataFormat, Dat
             reader = charset != null
                     ? inputFactory.createXMLStreamReader(is, charset) : 
inputFactory.createXMLStreamReader(is);
         }
+        XmlToJson xmlToJson = new XmlToJson(model, ignoreUnknown, textName);
         try {
-            Map.Entry<Element, Object> root
-                    = new XmlToJson(model, ignoreUnknown, 
textName).read(reader, element(exchange));
+            Map.Entry<Element, Object> root = xmlToJson.read(reader, 
element(exchange));
             Object value = root.getValue() == XmlToJson.NULL ? null : 
root.getValue();
             Object json = includeRoot ? singletonMap(root.getKey().jsonName(), 
value) : value;
             return JsonText.write(json, prettyPrint);
+        } catch (StackOverflowError e) {
+            // the depth limit is checked per element, but a small thread 
stack can be exhausted before that limit
+            throw XmlToJson.tooDeepForTheStack("XML", xmlToJson.deepest(), e);
         } finally {
             reader.close();
         }
diff --git 
a/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonSecurityTest.java
 
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonSecurityTest.java
index 9b3ce7c7d0f6..5c0978b2a402 100644
--- 
a/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonSecurityTest.java
+++ 
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonSecurityTest.java
@@ -18,10 +18,6 @@ package org.apache.camel.dataformat.xsdjson;
 
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
 
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
@@ -81,52 +77,32 @@ class XsdJsonSecurityTest extends XsdJsonTestSupport {
     @Test
     void nestingDepthIsLimited() throws Exception {
         XsdJsonDataFormat df = dataFormat("classpath:xsdjson/shop.xsd", d -> 
d.setElement("tree"));
-        // the XML parser of the JDK may have a lower limit 
(jdk.xml.maxElementDepth) than the data format
-        String xml = "<tree xmlns=\"urn:shop\">" + "<node>".repeat(600) + 
"</node>".repeat(600) + "</tree>";
-        assertThatThrownBy(() -> toJson(df, xml))
+        // the XML parser of the JDK may have a lower limit 
(jdk.xml.maxElementDepth) than the data format,
+        // XsdJsonWoodstoxTest checks the limit of the data format in the XML 
to JSON direction
+        assertThat(thrownOnThread(BIG_STACK, () -> toJson(df, nestedXml(600))))
                 .satisfies(e -> 
assertThat(e.getMessage()).containsAnyOf("depth", "nested deeper than 512"));
 
-        Map<String, Object> tree = nestedTree(600);
-        // the stack of the thread may be exhausted before the limit of the 
data format
-        assertThatThrownBy(() -> toXml(df, tree))
+        // on a stack that holds 512 levels, the limit of the data format 
applies
+        assertThat(thrownOnThread(BIG_STACK, () -> toXml(df, 
nestedTree(512)))).isNull();
+        assertThat(thrownOnThread(BIG_STACK, () -> toXml(df, nestedTree(513))))
                 .isInstanceOf(IllegalArgumentException.class)
-                .satisfies(e -> assertThat(e.getMessage()).containsAnyOf("The 
JSON is nested deeper than 512",
-                        "The JSON is nested too deep for the thread stack"));
+                .hasMessageStartingWith("The JSON is nested deeper than 512 
elements at /tree/node[0]/node[0]");
     }
 
     @Test
     void nestingOnASmallStackIsRefused() throws Exception {
         XsdJsonDataFormat df = dataFormat("classpath:xsdjson/shop.xsd", d -> 
d.setElement("tree"));
-        Map<String, Object> tree = nestedTree(600);
         // load the classes first, so that the stack of the small thread is 
not exhausted by the class loading
-        toXml(df, nestedTree(2));
+        toXml(df, nestedTree(3));
 
-        AtomicReference<Throwable> thrown = new AtomicReference<>();
-        Thread thread = new Thread(null, () -> {
-            try {
-                toXml(df, tree);
-            } catch (Throwable e) {
-                thrown.set(e);
-            }
-        }, "small-stack", 128 * 1024);
-        thread.start();
-        thread.join();
-
-        // an IllegalArgumentException, never a StackOverflowError, whichever 
limit is reached first
-        assertThat(thrown.get()).isInstanceOf(IllegalArgumentException.class);
-        assertThat(thrown.get().getMessage()).containsAnyOf("The JSON is 
nested deeper than 512",
-                "The JSON is nested too deep for the thread stack");
-    }
-
-    private static Map<String, Object> nestedTree(int depth) {
-        Map<String, Object> tree = new LinkedHashMap<>();
-        Map<String, Object> current = tree;
-        for (int i = 0; i < depth; i++) {
-            Map<String, Object> node = new LinkedHashMap<>();
-            current.put("node", List.of(node));
-            current = node;
-        }
-        return tree;
+        // an IllegalArgumentException that says where the stack overflowed, 
never a StackOverflowError
+        assertThat(thrownOnThread(SMALL_STACK, () -> toXml(df, 
nestedTree(512))))
+                .isInstanceOf(IllegalArgumentException.class)
+                .hasCauseInstanceOf(StackOverflowError.class)
+                .hasMessageMatching(
+                        "The JSON is nested too deep for the thread stack, 
which overflowed after the conversion"
+                                    + " reached level \\d+"
+                                    + " \\(the data format allows 512 
levels\\)");
     }
 
     @Test
diff --git 
a/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonTestSupport.java
 
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonTestSupport.java
index 29a2e7733c86..8dc0e344e390 100644
--- 
a/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonTestSupport.java
+++ 
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonTestSupport.java
@@ -19,6 +19,10 @@ package org.apache.camel.dataformat.xsdjson;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.Consumer;
 
 import org.apache.camel.CamelContext;
@@ -27,9 +31,20 @@ import org.apache.camel.impl.DefaultCamelContext;
 import org.apache.camel.support.DefaultExchange;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.function.Executable;
 
 abstract class XsdJsonTestSupport {
 
+    /**
+     * A thread stack that cannot hold 512 levels of nesting.
+     */
+    protected static final long SMALL_STACK = 128 * 1024;
+
+    /**
+     * A thread stack that holds 512 levels of nesting in any JVM mode.
+     */
+    protected static final long BIG_STACK = 16 * 1024 * 1024;
+
     protected CamelContext context;
 
     @BeforeEach
@@ -73,4 +88,43 @@ abstract class XsdJsonTestSupport {
         df.marshal(exchange, json, out);
         return out.toString(StandardCharsets.UTF_8);
     }
+
+    /**
+     * The JSON of the element tree of shop.xsd with the given number of 
levels (the tree element and the node elements
+     * nested in it).
+     */
+    protected static Map<String, Object> nestedTree(int levels) {
+        Map<String, Object> tree = new LinkedHashMap<>();
+        Map<String, Object> current = tree;
+        for (int i = 1; i < levels; i++) {
+            Map<String, Object> node = new LinkedHashMap<>();
+            current.put("node", List.of(node));
+            current = node;
+        }
+        return tree;
+    }
+
+    /**
+     * The XML of the element tree of shop.xsd with the given number of levels.
+     */
+    protected static String nestedXml(int levels) {
+        return "<tree xmlns=\"urn:shop\">" + "<node>".repeat(levels - 1) + 
"</node>".repeat(levels - 1) + "</tree>";
+    }
+
+    /**
+     * Runs the task on a new thread with the given stack size, and returns 
what it threw, or null.
+     */
+    protected static Throwable thrownOnThread(long stackSize, Executable task) 
throws InterruptedException {
+        AtomicReference<Throwable> thrown = new AtomicReference<>();
+        Thread thread = new Thread(null, () -> {
+            try {
+                task.execute();
+            } catch (Throwable e) {
+                thrown.set(e);
+            }
+        }, "stack-" + stackSize, stackSize);
+        thread.start();
+        thread.join();
+        return thrown.get();
+    }
 }
diff --git 
a/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonWoodstoxTest.java
 
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonWoodstoxTest.java
index e23ec10db796..cc82b9ea2f80 100644
--- 
a/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonWoodstoxTest.java
+++ 
b/components/camel-xsd-json/src/test/java/org/apache/camel/dataformat/xsdjson/XsdJsonWoodstoxTest.java
@@ -16,6 +16,9 @@
  */
 package org.apache.camel.dataformat.xsdjson;
 
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.xml.stream.XMLInputFactory;
 import javax.xml.stream.XMLOutputFactory;
 
 import org.apache.camel.Exchange;
@@ -25,17 +28,51 @@ import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
 /**
- * Runs with Woodstox as the StAX writer, which CXF brings (such as in the 
soap Kamelets). Woodstox fails to close a
- * document that has no root, and that failure must not hide the error that 
stopped the document. The surefire execution
- * "woodstox" of the pom runs this class with woodstox-core on the classpath; 
the other tests use the writer of the JDK.
+ * Runs with Woodstox as the StAX writer and reader, which CXF brings (such as 
in the soap Kamelets). Woodstox fails to
+ * close a document that has no root, and that failure must not hide the error 
that stopped the document. Woodstox has
+ * no depth limit below the one of the data format, unlike the reader of the 
JDK on JDK 25. The surefire execution
+ * "woodstox" of the pom runs this class with woodstox-core on the classpath; 
the other tests use the StAX of the JDK.
  */
 class XsdJsonWoodstoxTest extends XsdJsonTestSupport {
 
     private static final String WSDL = "classpath:xsdjson/orders.wsdl";
 
     @Test
-    void theWriterIsWoodstox() {
+    void theReaderAndWriterAreWoodstox() {
         
assertThat(XMLOutputFactory.newFactory().getClass().getName()).startsWith("com.ctc.wstx.");
+        
assertThat(XMLInputFactory.newFactory().getClass().getName()).startsWith("com.ctc.wstx.");
+    }
+
+    @Test
+    void bothDirectionsAllow512Levels() throws Exception {
+        XsdJsonDataFormat df = dataFormat("classpath:xsdjson/shop.xsd", d -> 
d.setElement("tree"));
+        AtomicReference<String> xml = new AtomicReference<>();
+
+        assertThat(thrownOnThread(BIG_STACK, () -> xml.set(toXml(df, 
nestedTree(512))))).isNull();
+        assertThat(thrownOnThread(BIG_STACK, () -> toJson(df, 
xml.get()))).isNull();
+
+        assertThat(thrownOnThread(BIG_STACK, () -> toXml(df, nestedTree(513))))
+                .isInstanceOf(IllegalArgumentException.class)
+                .hasMessageStartingWith("The JSON is nested deeper than 512 
elements");
+        assertThat(thrownOnThread(BIG_STACK, () -> toJson(df, nestedXml(513))))
+                .isInstanceOf(IllegalArgumentException.class)
+                .hasMessageStartingWith("The XML is nested deeper than 512 
elements");
+    }
+
+    @Test
+    void nestingOnASmallStackIsRefused() throws Exception {
+        XsdJsonDataFormat df = dataFormat("classpath:xsdjson/shop.xsd", d -> 
d.setElement("tree"));
+        // load the classes first, so that the stack of the small thread is 
not exhausted by the class loading
+        toJson(df, nestedXml(3));
+
+        // an IllegalArgumentException that says where the stack overflowed, 
never a StackOverflowError
+        assertThat(thrownOnThread(SMALL_STACK, () -> toJson(df, 
nestedXml(512))))
+                .isInstanceOf(IllegalArgumentException.class)
+                .hasCauseInstanceOf(StackOverflowError.class)
+                .hasMessageMatching(
+                        "The XML is nested too deep for the thread stack, 
which overflowed after the conversion"
+                                    + " reached level \\d+"
+                                    + " \\(the data format allows 512 
levels\\)");
     }
 
     @Test

Reply via email to