From ec055da7c3d939a867436821a1405835475a6393 Mon Sep 17 00:00:00 2001 From: Onji Kim Date: Wed, 17 Apr 2024 22:58:04 +0900 Subject: [PATCH] Reject negative Content-Length values in HttpHeaders Prior to this commit, `HttpHeaders#setContentLength` would accept negative values. Those are not allowed by the RFC and the headers implementation only uses "-1" as a way to convey that no value was set. This commit ensures that negative values are rejected. Fixes gh-32660 --- .../java/org/springframework/http/HttpHeaders.java | 5 +++++ .../org/springframework/http/HttpHeadersTests.java | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/spring-web/src/main/java/org/springframework/http/HttpHeaders.java b/spring-web/src/main/java/org/springframework/http/HttpHeaders.java index e39b884581..16ee323dce 100644 --- a/spring-web/src/main/java/org/springframework/http/HttpHeaders.java +++ b/spring-web/src/main/java/org/springframework/http/HttpHeaders.java @@ -969,8 +969,13 @@ public class HttpHeaders implements MultiValueMap, Serializable /** * Set the length of the body in bytes, as specified by the * {@code Content-Length} header. + * @param contentLength content length (greater than or equal to zero) + * @throws IllegalArgumentException if the content length is negative */ public void setContentLength(long contentLength) { + if (contentLength < 0) { + throw new IllegalArgumentException("Content-Length must be a non-negative number"); + } set(CONTENT_LENGTH, Long.toString(contentLength)); } diff --git a/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java b/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java index de8ab6ac0c..d08892bbb4 100644 --- a/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java +++ b/spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java @@ -154,6 +154,17 @@ class HttpHeadersTests { assertThat(headers.getFirst("Content-Length")).as("Invalid Content-Length header").isEqualTo("42"); } + @Test + void setContentLengthWithNegativeValue() { + assertThatIllegalArgumentException().isThrownBy(() -> + headers.setContentLength(-1)); + } + + @Test + void getContentLengthReturnsMinusOneForAbsentHeader() { + assertThat(headers.getContentLength()).isEqualTo(-1); + } + @Test void contentType() { MediaType contentType = new MediaType("text", "html", StandardCharsets.UTF_8);