From 71fc29491d8954e8986507a2bb459f5b805cf02c Mon Sep 17 00:00:00 2001 From: Erik Berlin Date: Wed, 25 Nov 2026 09:35:33 -0800 Subject: [PATCH 1/2] Bound the size of each chunk the Inflater returns Inflater#readpartial inflated a whole read from the connection at once. Deflate can expand data by roughly 1032:1, so one 16 KiB read of highly compressed data could come back as a chunk of about 16 MiB, which defeats streaming a body with readpartial or Body#each as a way to keep memory bounded. Compressed input is now handed to zlib 1 KiB at a time, so each chunk is at most about 1 MiB. Input left over from a read is consumed before the connection is read again, and readpartial keeps going until a slice produces output, so it never returns an empty string. Each read is copied, since a caller that reuses its outbuf could otherwise overwrite input that has not been inflated yet. --- CHANGELOG.md | 7 ++ lib/http/response/inflater.rb | 59 +++++++++++++++-- sig/http.rbs | 7 ++ test/http/response/inflater_test.rb | 99 +++++++++++++++++++++++++++++ 4 files changed, 165 insertions(+), 7 deletions(-) create mode 100644 test/http/response/inflater_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 416ad1e2..960a6f38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 JVM could garbage-collect llhttp's native callback trampolines while a parser was still in use, after which `llhttp_execute` succeeded without invoking any callbacks. Callback procs are now retained for the lifetime of the parser. +- With `auto_inflate`, each `readpartial` (and each chunk yielded by + `Body#each`) now returns at most about 1 MiB of decompressed data. + Previously a whole network read was inflated at once, so a highly + compressed 16 KiB read could expand to roughly 16 MiB in a single chunk, + defeating streaming as a way to bound memory use. Compressed input is now + inflated in 1 KiB slices. ([#865]) ## [6.0.4] - 2026-07-14 @@ -343,6 +349,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [#785]: https://github.com/httprb/http/issues/785 [#826]: https://github.com/httprb/http/issues/826 [#841]: https://github.com/httprb/http/pull/841 +[#865]: https://github.com/httprb/http/pull/865 [#863]: https://github.com/httprb/http/issues/863 [GHSA-r98x-p6m8-xcrv]: https://github.com/httprb/http/security/advisories/GHSA-r98x-p6m8-xcrv diff --git a/lib/http/response/inflater.rb b/lib/http/response/inflater.rb index 18854457..b9a72550 100644 --- a/lib/http/response/inflater.rb +++ b/lib/http/response/inflater.rb @@ -6,6 +6,14 @@ module HTTP class Response # Decompresses gzip/deflate response body streams class Inflater + # Largest slice of compressed input handed to zlib at once + # + # Deflate can expand input by roughly 1032:1 at most, so a 1 KiB + # slice caps each decompressed chunk at about 1 MiB, however much + # compressed data a single read from the connection returns. + INPUT_SLICE_SIZE = 1_024 + private_constant :INPUT_SLICE_SIZE + # The underlying connection # # @example @@ -25,10 +33,17 @@ class Inflater # @api public def initialize(connection) @connection = connection + @input = "" + @offset = 0 end # Read and inflate a chunk of the response body # + # Compressed input is inflated one slice at a time, so each call + # returns a bounded amount of decompressed data even when the + # compression ratio is extreme. Input left over from an earlier + # read is consumed before the connection is read again. + # # @example # inflater.readpartial # => "decompressed data" # @@ -36,19 +51,49 @@ def initialize(connection) # @raise [EOFError] when no more data left # @api public def readpartial(*) - chunk = @connection.readpartial(*) - zstream.inflate(chunk) - rescue EOFError - unless zstream.closed? - zstream.finished? ? zstream.finish : zstream.reset - zstream.close + loop do + fill_input(*) if @offset >= @input.bytesize + output = zstream.inflate(next_slice) + return output unless output.empty? end - + rescue EOFError + close_zstream raise end private + # Flush and close the zlib stream once the connection is exhausted + # @return [void] + # @api private + def close_zstream + return if zstream.closed? + + zstream.finished? ? zstream.finish : zstream.reset + zstream.close + end + + # Replace the consumed input with a fresh read from the connection + # + # The read is copied because a caller-supplied outbuf may be reused + # while part of its input is still pending. + # + # @return [void] + # @api private + def fill_input(*) + @input = @connection.readpartial(*).b + @offset = 0 + end + + # Take the next slice of pending compressed input + # @return [String] + # @api private + def next_slice + slice = String(@input.byteslice(@offset, INPUT_SLICE_SIZE)) + @offset += INPUT_SLICE_SIZE + slice + end + # Return the zlib inflate stream # @return [Zlib::Inflate] # @api private diff --git a/sig/http.rbs b/sig/http.rbs index ddf820a3..d76fe942 100644 --- a/sig/http.rbs +++ b/sig/http.rbs @@ -1049,7 +1049,11 @@ module HTTP end class Inflater + INPUT_SLICE_SIZE: Integer + @zstream: Zlib::Inflate? + @input: String + @offset: Integer attr_reader connection: untyped @@ -1058,6 +1062,9 @@ module HTTP private + def close_zstream: () -> void + def fill_input: (?Integer size, ?String? outbuf) -> void + def next_slice: () -> String def zstream: () -> Zlib::Inflate end diff --git a/test/http/response/inflater_test.rb b/test/http/response/inflater_test.rb new file mode 100644 index 00000000..1d5a0bf5 --- /dev/null +++ b/test/http/response/inflater_test.rb @@ -0,0 +1,99 @@ +# frozen_string_literal: true + +require "test_helper" +require "zlib" +require "stringio" + +class HTTPResponseInflaterTest < Minitest::Test + cover "HTTP::Response::Inflater*" + + # Upper bound on decompressed bytes from one 1 KiB slice of deflate input + MAX_CHUNK_SIZE = 1_024 * 1_032 + + def gzip(data) + io = StringIO.new("".b) + gz = Zlib::GzipWriter.new(io) + gz.write(data) + gz.close + io.string + end + + def connection_for(chunks, reads: []) + fake(readpartial: proc { |*args| + reads << args + chunks.shift || raise(EOFError) + }) + end + + def read_all(inflater) + parts = [] + loop { parts << inflater.readpartial } + rescue EOFError + parts + end + + def test_bounds_each_chunk_inflated_from_a_highly_compressed_read + data = "\0" * (16 * 1_024 * 1_024) + inflater = HTTP::Response::Inflater.new(connection_for([gzip(data)])) + parts = read_all(inflater) + + assert_operator parts.map(&:bytesize).max, :<=, MAX_CHUNK_SIZE + assert_equal data.bytesize, parts.sum(&:bytesize) + end + + def test_inflates_data_split_across_slices_and_reads + data = Random.new(42).bytes(5_000) * 3 + compressed = gzip(data) + chunks = [compressed[0, 3_000], compressed[3_000..]] + inflater = HTTP::Response::Inflater.new(connection_for(chunks)) + + assert_equal data, read_all(inflater).join + end + + def test_consumes_pending_input_before_reading_the_connection_again + data = Random.new(42).bytes(10_000) + reads = [] + inflater = HTTP::Response::Inflater.new(connection_for([gzip(data)], reads: reads)) + + inflater.readpartial + inflater.readpartial + + assert_equal 1, reads.size + end + + def test_keeps_reading_when_a_slice_yields_no_output + compressed = gzip("hello") + chunks = [compressed[0, 10], compressed[10..]] + inflater = HTTP::Response::Inflater.new(connection_for(chunks)) + + assert_equal "hello", inflater.readpartial + end + + def test_forwards_read_arguments_to_the_connection + reads = [] + inflater = HTTP::Response::Inflater.new(connection_for([gzip("hello")], reads: reads)) + + inflater.readpartial(512) + + assert_equal [[512]], reads + end + + def test_copies_reads_so_a_reused_outbuf_cannot_corrupt_pending_input + data = Random.new(42).bytes(10_000) + compressed = gzip(data) + outbuf = +"" + conn = fake(readpartial: proc { |_size, buf| + raise EOFError if compressed.empty? + + buf.replace(compressed) + compressed = "" + buf + }) + inflater = HTTP::Response::Inflater.new(conn) + parts = [inflater.readpartial(16_384, outbuf)] + outbuf.replace("garbage") + parts.concat(read_all(inflater)) + + assert_equal data, parts.join + end +end From 41de179a413eb7c4fd7f20b0711d335af81ed481 Mon Sep 17 00:00:00 2001 From: Erik Berlin Date: Wed, 25 Nov 2026 09:59:33 -0800 Subject: [PATCH 2/2] Inflate in 4 KiB slices, and copy and slice reads only when needed Each slice is a call to zlib, which has a fixed cost, so 1 KiB slices made inflating a large gzipped body about 1.7x slower. 4 KiB slices cap each chunk at about 4 MiB instead of 1 MiB, still a quarter of the old worst case, and cost about 1.25x on a large body. A read is now copied only when the caller passed an outbuf, which is the only case where it can be overwritten while input is pending. And a read that fits in one slice goes to zlib whole, without a byteslice. --- CHANGELOG.md | 4 ++-- lib/http/response/inflater.rb | 30 ++++++++++++++++++++--------- test/http/response/inflater_test.rb | 4 ++-- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 960a6f38..218fc9a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,11 +39,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 was still in use, after which `llhttp_execute` succeeded without invoking any callbacks. Callback procs are now retained for the lifetime of the parser. - With `auto_inflate`, each `readpartial` (and each chunk yielded by - `Body#each`) now returns at most about 1 MiB of decompressed data. + `Body#each`) now returns at most about 4 MiB of decompressed data. Previously a whole network read was inflated at once, so a highly compressed 16 KiB read could expand to roughly 16 MiB in a single chunk, defeating streaming as a way to bound memory use. Compressed input is now - inflated in 1 KiB slices. ([#865]) + inflated in 4 KiB slices. ([#865]) ## [6.0.4] - 2026-07-14 diff --git a/lib/http/response/inflater.rb b/lib/http/response/inflater.rb index b9a72550..b063a279 100644 --- a/lib/http/response/inflater.rb +++ b/lib/http/response/inflater.rb @@ -8,10 +8,12 @@ class Response class Inflater # Largest slice of compressed input handed to zlib at once # - # Deflate can expand input by roughly 1032:1 at most, so a 1 KiB - # slice caps each decompressed chunk at about 1 MiB, however much - # compressed data a single read from the connection returns. - INPUT_SLICE_SIZE = 1_024 + # Deflate can expand input by roughly 1032:1 at most, so a 4 KiB + # slice caps each decompressed chunk at about 4 MiB, however much + # compressed data a single read from the connection returns. Each + # slice is a call to zlib, which has a fixed cost, so smaller slices + # inflate a large body noticeably slower. + INPUT_SLICE_SIZE = 4_096 private_constant :INPUT_SLICE_SIZE # The underlying connection @@ -75,21 +77,31 @@ def close_zstream # Replace the consumed input with a fresh read from the connection # - # The read is copied because a caller-supplied outbuf may be reused - # while part of its input is still pending. + # A read into a caller-supplied outbuf is copied, because the caller + # may reuse the outbuf while part of its input is still pending. + # Without one, the connection returns a new string, which is kept + # as it is. # # @return [void] # @api private - def fill_input(*) - @input = @connection.readpartial(*).b + def fill_input(*args) + chunk = @connection.readpartial(*args) + @input = args[1] ? chunk.b : chunk @offset = 0 end # Take the next slice of pending compressed input + # + # A read that fits in one slice is used whole, without slicing it. + # # @return [String] # @api private def next_slice - slice = String(@input.byteslice(@offset, INPUT_SLICE_SIZE)) + slice = if @offset.zero? && @input.bytesize <= INPUT_SLICE_SIZE + @input + else + String(@input.byteslice(@offset, INPUT_SLICE_SIZE)) + end @offset += INPUT_SLICE_SIZE slice end diff --git a/test/http/response/inflater_test.rb b/test/http/response/inflater_test.rb index 1d5a0bf5..ef5f342e 100644 --- a/test/http/response/inflater_test.rb +++ b/test/http/response/inflater_test.rb @@ -7,8 +7,8 @@ class HTTPResponseInflaterTest < Minitest::Test cover "HTTP::Response::Inflater*" - # Upper bound on decompressed bytes from one 1 KiB slice of deflate input - MAX_CHUNK_SIZE = 1_024 * 1_032 + # Upper bound on decompressed bytes from one 4 KiB slice of deflate input + MAX_CHUNK_SIZE = 4_096 * 1_032 def gzip(data) io = StringIO.new("".b)