Video in progress

Strong Middle 📁 IO and NIO

Why is reading an `InputStream` from outside with `readAllBytes()` dangerous, and what do you do instead?

readAllBytes gathers everything into memory until the stream ends, with no limit. A large file or a deliberately endless stream fills the heap. You set the limit yourself: read with readNBytes(limit + 1) and reject if it is exceeded.

📖 Answer

Convenient code written on one line:

byte[] body = request.getInputStream().readAllBytes();

If the client sends no Content-Length at all, or sends 3 GB chunked, this line fills the heap. A single array can't be much larger than 2 GB, so OutOfMemoryError comes before that, and it takes other requests down too.

The bounded version:

static byte[] readLimited(InputStream in, int limit) throws IOException {
    byte[] data = in.readNBytes(limit + 1);    // Java 11+
    if (data.length > limit) {
        throw new PayloadTooLargeException("ruxsat: " + limit + " bayt");
    }
    return data;
}

The limit + 1 trick is reading one byte more than the limit to find out whether the stream still has more data.

A few notes:

  • don't allocate an array based on the Content-Length header: it comes from the client too;
  • for compressed data, put the limit on the size after decompression. A 1 MB gzip can become 1 GB when unpacked (a "zip bomb");
  • if the data can really be large (a file upload), don't load it into memory: stream it with Files.copy(in, tmp) or into storage, and count the bytes along the way.

In Spring, spring.servlet.multipart.max-file-size and the body limit on the proxy are the first line of defense, but you still need the limit inside the code, because an InputStream comes from other sources too.