Resource writer doesn't consider subclasses of InputStreamResource
for content length bypass
#33089
Labels
in: web
Issues in web modules (web, webmvc, webflux, websocket)
type: documentation
A documentation task
Milestone
Issue
Currently, when returning a subclass of
InputStreamResource
from a controller,ResourceHttpMessageWriter
from the Spring Web module doesn't consider subclasses ofInputStreamResource
when deciding whether or not to call thecontentLength
method on the givenResource
, it only considers the ownInputStreamResource
class.The result is: subclasses of
InputStreamResource
must provide an override for the given method or risk having the whole input stream read by the default implementation ofResource#contentLength
, which could be very undesirable and lead to errors such as:This issue doesn't happen if you return a
ResponseEntity<Resource>
from your controller and make sure to set theContent-Length
header because there's no need to check for the length of the resource. But that's not always the case, there are cases where the final size of the input stream is undetermined, and for these cases, Spring already does handle these cases and properly sets and useschunked
as thetransfer-encoding
header, but only when returning an actualInputStreamResource
. This is the point I'm going to propose a change.Affects: All versions up to Spring Framework 6.1.10 / Spring Boot 3.3.1 (and possibility newer versions too).
Proposed Solution
To fix this, I propose a simple, yet significant change in the Spring Web module, changing the check being made in this line:
spring-framework/spring-web/src/main/java/org/springframework/http/codec/ResourceHttpMessageWriter.java
Line 191 in 9b58e1f
to this
Here's a simple test code I ran to double-check that the current check doesn't support subclasses of
InputStreamResource
.The text was updated successfully, but these errors were encountered: