From 4b607bde2c7da8a39c472b671a2aec5af81a10c3 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 22 Apr 2025 19:58:05 -0700 Subject: [PATCH] Polish 'Protected against JsonValueWriter stack overflow' See gh-44627 --- .../springframework/boot/json/JsonValueWriter.java | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonValueWriter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonValueWriter.java index 27a5ee102a3..cfefe35e6cb 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonValueWriter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonValueWriter.java @@ -47,7 +47,7 @@ import org.springframework.util.function.ThrowingConsumer; */ class JsonValueWriter { - private static final int DEFAULT_MAX_NESTING_DEPTH = 1000; + private static final int DEFAULT_MAX_NESTING_DEPTH = 500; private final Appendable out; @@ -160,7 +160,10 @@ class JsonValueWriter { */ void start(Series series) { if (series != null) { - validateNestingDepth(); + int nestingDepth = this.activeSeries.size(); + Assert.state(nestingDepth <= this.maxNestingDepth, + () -> "JSON nesting depth (%s) exceeds maximum depth of %s (current path: %s)" + .formatted(nestingDepth, this.maxNestingDepth, this.path)); this.activeSeries.push(new ActiveSeries(series)); append(series.openChar); } @@ -288,13 +291,6 @@ class JsonValueWriter { } } - private void validateNestingDepth() { - if (this.activeSeries.size() > this.maxNestingDepth) { - throw new IllegalStateException("JSON nesting depth (%s) exceeds maximum depth of %s (current path: %s)" - .formatted(this.activeSeries.size(), this.maxNestingDepth, this.path)); - } - } - private void append(String value) { try { this.out.append(value);