Skip to content

Commit ec055da

Browse files
onjikbclozel
authored andcommitted
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
1 parent c03f798 commit ec055da

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

spring-web/src/main/java/org/springframework/http/HttpHeaders.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -969,8 +969,13 @@ public Locale getContentLanguage() {
969969
/**
970970
* Set the length of the body in bytes, as specified by the
971971
* {@code Content-Length} header.
972+
* @param contentLength content length (greater than or equal to zero)
973+
* @throws IllegalArgumentException if the content length is negative
972974
*/
973975
public void setContentLength(long contentLength) {
976+
if (contentLength < 0) {
977+
throw new IllegalArgumentException("Content-Length must be a non-negative number");
978+
}
974979
set(CONTENT_LENGTH, Long.toString(contentLength));
975980
}
976981

spring-web/src/test/java/org/springframework/http/HttpHeadersTests.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,17 @@ void contentLength() {
154154
assertThat(headers.getFirst("Content-Length")).as("Invalid Content-Length header").isEqualTo("42");
155155
}
156156

157+
@Test
158+
void setContentLengthWithNegativeValue() {
159+
assertThatIllegalArgumentException().isThrownBy(() ->
160+
headers.setContentLength(-1));
161+
}
162+
163+
@Test
164+
void getContentLengthReturnsMinusOneForAbsentHeader() {
165+
assertThat(headers.getContentLength()).isEqualTo(-1);
166+
}
167+
157168
@Test
158169
void contentType() {
159170
MediaType contentType = new MediaType("text", "html", StandardCharsets.UTF_8);

0 commit comments

Comments
 (0)