metainspector 5.21.1 → 5.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e84dae185b72b0ea7bec6e573db063bf2a0fe3632d978222f2c00cb2a0111075
4
- data.tar.gz: 48799a4f6609282828b6161a4333231e0a0d0d762916fedf5e1ab854dc19e074
3
+ metadata.gz: 1a32c7da227fe7a2fbf3f106e6eb03af652694e293e4ea47928ee3adb71f21e5
4
+ data.tar.gz: 6777d770a847f417cfa20a8cf70667e22db82393e2f6d5a839ac7d22406094ff
5
5
  SHA512:
6
- metadata.gz: 7af14afd571dc86d85a04e88a85a81b1386919a2b156a40ce5c57d59b4ec7084f9af4a40def4158797530ddeb99aca0406a628bf1f17c1d65dfb3761c3a5108f
7
- data.tar.gz: e11c0c31565f180b1df73e4c291d4f1840dc1c7be48bbfe7b9507cda3383a593b0412a158edda73099288a7f4d0b3acd28b4b7764fdb21292f00bc9345aae134
6
+ metadata.gz: 239049c807eaf8c178fe386be88b79fac5888934191f372ab3995fefe443026389e0b99d2f92f03e616eb93104acc24e6da15fa616da7172c2f067dc9da41aef
7
+ data.tar.gz: 4676aaa3467c872f19db8b584eacf8cd66bfe9351adbe4f2fb882233043ba9aece759d93cb859f2aefaa41dca109becbaab25ca657bf66c6a37be6d7518b8606
data/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # MetaInspector Changelog
2
2
 
3
+ ## [Changes in 5.21.2](https://github.com/jaimeiniesta/metainspector/compare/v5.21.1...v5.21.2)
4
+
5
+ * Security: apply `max_html_bytes` while downloading page and redirect responses and during gzip/deflate decompression, before charset conversion and parsing. Oversized responses raise `MetaInspector::ParserError`; cached responses are checked as well. The 5.x default remains `nil` (unlimited); set a finite limit for untrusted URLs. Other content encodings are rejected with a finite limit ([GHSA-36j3-rh89-4gm2](https://github.com/jaimeiniesta/metainspector/security/advisories/GHSA-36j3-rh89-4gm2)).
6
+
3
7
  ## [Changes in 5.21.1](https://github.com/jaimeiniesta/metainspector/compare/v5.21.0...v5.21.1)
4
8
 
5
9
  * Security: forward only `User-Agent`, `Accept`, `Accept-Language` and `Accept-Encoding` when page redirects change the origin (scheme, host or port), preventing custom credentials from reaching another origin. Apply the policy to GET and HEAD, including headers supplied through `faraday_options`, and keep the initial credentials out of image requests on the redirected origin. Custom headers remain available within the initial origin ([GHSA-mcmp-j8cq-h65f](https://github.com/jaimeiniesta/metainspector/security/advisories/GHSA-mcmp-j8cq-h65f)).
data/README.md CHANGED
@@ -339,11 +339,20 @@ documents, set `max_html_bytes` to a non-negative integer:
339
339
  page = MetaInspector.new(url, max_html_bytes: 2 * 1024 * 1024)
340
340
  ```
341
341
 
342
- The default is `nil` (no limit). HTML larger than the limit raises
343
- `MetaInspector::ParserError` before parsing, including HTML passed with the
344
- `document` option. The limit is measured in bytes after fetching and processing
345
- the response, so it does not limit download size or memory used for the response.
346
- It also does not guarantee a parsing deadline: even a small document can be
342
+ The default in 5.x is `nil` (no limit). Set a finite limit when fetching URLs you
343
+ do not control. Exceeding it raises `MetaInspector::ParserError` during
344
+ initialization. The limit applies separately to the bytes received for each
345
+ response (including redirect bodies), each stage of gzip/deflate decompression,
346
+ and the HTML after charset conversion and processing, before parsing. Downloads
347
+ stop as soon as a received chunk exceeds the limit; decompression stops as soon
348
+ as an output chunk exceeds it, without expanding the entire body. Cached
349
+ responses are checked too. With a finite limit, only gzip and deflate compression
350
+ are supported; other content encodings raise `MetaInspector::RequestError`.
351
+ HTML passed with `document:` is checked before parsing as well.
352
+
353
+ This bounds response buffers, not total process memory: charset conversion and
354
+ DOM construction still need additional memory. It also does not guarantee a
355
+ parsing deadline: even a small document can be
347
356
  slow to parse. Ruby's `Timeout.timeout` cannot reliably interrupt Nokogiri's
348
357
  native parser; use a separately supervised process if a hard deadline is needed.
349
358
 
@@ -18,7 +18,7 @@ module MetaInspector
18
18
  # * download_image_options: supports reject_invalid_images (default false)
19
19
  # * inline_image_data: return full data URLs in image results (default false)
20
20
  # * fetch_all_image_meta: enable image validity metadata (default false)
21
- # * max_html_bytes: maximum HTML size before parsing, or nil for unlimited
21
+ # * max_html_bytes: maximum received, decompressed and parsed HTML bytes, or nil for unlimited
22
22
  # * url_filter: callable receiving a URI before each request; false/nil rejects it
23
23
  # * faraday_options: an optional hash of options to pass to Faraday on the request.
24
24
  # Its faraday_http_cache key configures response caching with Faraday::HttpCache
@@ -7,6 +7,7 @@ require 'faraday/follow_redirects'
7
7
  require 'faraday/gzip'
8
8
  require 'faraday/retry'
9
9
  require_relative 'url_policy'
10
+ require_relative 'limited_response'
10
11
 
11
12
  module MetaInspector
12
13
  # Builds page and binary image transports from the same caller configuration.
@@ -15,6 +16,7 @@ module MetaInspector
15
16
  @allow_redirections = options[:allow_redirections]
16
17
  @retries = options[:retries]
17
18
  @headers = options[:headers]
19
+ @max_html_bytes = options[:max_html_bytes]
18
20
  @url_filter = options[:url_filter]
19
21
  if !@url_filter.nil? && !@url_filter.respond_to?(:call)
20
22
  raise ArgumentError, 'url_filter must respond to call'
@@ -42,7 +44,9 @@ module MetaInspector
42
44
  Faraday.new(faraday_options) do |faraday|
43
45
  unless image
44
46
  faraday.request :retry, max: @retries
45
- faraday.request :gzip
47
+ # Responses run in reverse order: decompress before applying the charset.
48
+ faraday.response :encoding if @max_html_bytes
49
+ faraday.request :gzip if @max_html_bytes.nil?
46
50
  end
47
51
  if @allow_redirections
48
52
  redirects[:limit] ||= 10
@@ -51,13 +55,15 @@ module MetaInspector
51
55
  end
52
56
  faraday.use URLPolicy, @url_filter, image ? origin : nil,
53
57
  request_origin: @page_origin || origin
58
+ faraday.use LimitedResponse, @max_html_bytes if !image && @max_html_bytes
54
59
  if !image && @cache.is_a?(Hash)
55
60
  cache_options = @cache.dup
56
61
  cache_options[:serializer] ||= Marshal
57
62
  faraday.use Faraday::HttpCache, **cache_options
58
63
  end
64
+ faraday.use LimitedResponse::Streaming, @max_html_bytes if !image && @max_html_bytes
59
65
  faraday.headers.merge!(@headers || {})
60
- faraday.response :encoding unless image
66
+ faraday.response :encoding unless image || @max_html_bytes
61
67
  faraday.adapter :net_http
62
68
  end
63
69
  end
@@ -0,0 +1,125 @@
1
+ require 'zlib'
2
+ require 'stringio'
3
+
4
+ module MetaInspector
5
+ # Enforces max_html_bytes before charset conversion or parsing. Keep this
6
+ # outside the HTTP cache, and Streaming inside it, so cached bodies are checked
7
+ # too and the cache stores the received bytes rather than an empty stream.
8
+ class LimitedResponse < Faraday::Middleware
9
+ CHUNK_SIZE = 16 * 1024
10
+
11
+ def self.check_size!(size, limit)
12
+ return if size <= limit
13
+
14
+ raise MetaInspector::ParserError, "HTML response exceeds the limit of #{limit} bytes"
15
+ end
16
+
17
+ def initialize(app, limit)
18
+ super(app)
19
+ @limit = limit
20
+ end
21
+
22
+ def call(env)
23
+ env.request_headers['Accept-Encoding'] ||= 'gzip,deflate'
24
+ @app.call(env).on_complete do |response|
25
+ body = response.body
26
+ self.class.check_size!(body.bytesize, @limit)
27
+ next if body.empty? || response.status == 206
28
+
29
+ encodings = response.response_headers['Content-Encoding'].to_s.split(',').map { |value| value.strip.downcase }
30
+ next if encodings.empty? || encodings.include?('identity')
31
+
32
+ encodings.reverse_each do |encoding|
33
+ body = case encoding
34
+ when 'gzip' then gunzip(body)
35
+ when 'deflate' then inflate(body)
36
+ else
37
+ raise MetaInspector::RequestError, "Unsupported Content-Encoding with max_html_bytes: #{encoding}"
38
+ end
39
+ end
40
+ response.body = body
41
+ response.response_headers['Content-Length'] = body.bytesize
42
+ response.response_headers.delete('Content-Encoding')
43
+ end
44
+ rescue Zlib::Error => error
45
+ raise MetaInspector::RequestError.new(error)
46
+ end
47
+
48
+ private
49
+
50
+ def append(body, chunk)
51
+ self.class.check_size!(body.bytesize + chunk.bytesize, @limit)
52
+ body << chunk
53
+ end
54
+
55
+ def gunzip(bytes)
56
+ body = ''.b
57
+ io = StringIO.new(bytes)
58
+ # gzip can contain multiple members; apply one budget to all of them.
59
+ until io.eof?
60
+ reader = Zlib::GzipReader.new(io, encoding: Encoding::BINARY)
61
+ begin
62
+ while (chunk = reader.read(CHUNK_SIZE)) && !chunk.empty?
63
+ append(body, chunk)
64
+ end
65
+ unused = reader.unused
66
+ ensure
67
+ reader.finish
68
+ end
69
+ io.pos -= unused.bytesize if unused
70
+ end
71
+ body
72
+ end
73
+
74
+ def inflate(bytes, window_bits = Zlib::MAX_WBITS)
75
+ body = ''.b
76
+ inflater = Zlib::Inflate.new(window_bits)
77
+ begin
78
+ # Block form yields bounded chunks instead of allocating the full output.
79
+ inflater.inflate(bytes) { |chunk| append(body, chunk) }
80
+ inflater.finish { |chunk| append(body, chunk) }
81
+ ensure
82
+ inflater.close
83
+ end
84
+ body
85
+ rescue Zlib::DataError
86
+ raise if window_bits < 0
87
+
88
+ # Some servers send raw DEFLATE rather than a zlib-wrapped stream.
89
+ inflate(bytes, -Zlib::MAX_WBITS)
90
+ end
91
+
92
+ class Streaming < Faraday::Middleware
93
+ def initialize(app, limit)
94
+ super(app)
95
+ @limit = limit
96
+ end
97
+
98
+ def call(env)
99
+ body = ''.b
100
+ # Redirects copy the environment but share request options. Each hop
101
+ # needs its own buffer and callback, as do retries and HEAD/GET pairs.
102
+ env.request = env.request.dup
103
+ env.request.on_data = proc do |chunk, _total, _response|
104
+ LimitedResponse.check_size!(body.bytesize + chunk.bytesize, @limit)
105
+ body << chunk.b
106
+ end
107
+ @app.call(env).on_complete do |response|
108
+ # Net::HTTP tags its buffered body with the HTTP charset, including
109
+ # quoted labels. Streaming replaces that body, so retain the tag.
110
+ charset = response.response_headers['Content-Type'].to_s[/(?:\A|;)\s*charset=([^;]+)/i, 1]
111
+ if charset
112
+ charset = charset.strip
113
+ charset = charset[1...-1] if charset.start_with?('"') && charset.end_with?('"')
114
+ begin
115
+ body.force_encoding(charset)
116
+ rescue ArgumentError
117
+ # Unknown charsets are ignored, as in the Net::HTTP adapter.
118
+ end
119
+ end
120
+ response.body = body
121
+ end
122
+ end
123
+ end
124
+ end
125
+ end
@@ -1,3 +1,3 @@
1
1
  module MetaInspector
2
- VERSION = '5.21.1'
2
+ VERSION = '5.21.2'
3
3
  end
@@ -0,0 +1,176 @@
1
+ require 'spec_helper'
2
+ require 'socket'
3
+
4
+ RSpec.describe 'bounded page responses' do
5
+ let(:url) { 'https://size.example/page' }
6
+
7
+ [nil, 'gzip', 'deflate', 'raw deflate', 'gzip, deflate'].each do |compression|
8
+ [false, true].each do |head_first|
9
+ it "preserves #{compression || 'plain'} HTML and its charset with head_first: #{head_first}" do
10
+ html = '<title>Café</title>'.encode('Windows-1252')
11
+ body = case compression
12
+ when 'gzip' then Zlib.gzip(html)
13
+ when 'deflate' then Zlib::Deflate.deflate(html)
14
+ when 'raw deflate'
15
+ deflater = Zlib::Deflate.new(nil, -Zlib::MAX_WBITS)
16
+ begin
17
+ deflater.deflate(html, Zlib::FINISH)
18
+ ensure
19
+ deflater.close
20
+ end
21
+ when 'gzip, deflate' then Zlib::Deflate.deflate(Zlib.gzip(html))
22
+ else html
23
+ end
24
+ headers = { 'Content-Type' => 'text/html; charset=Windows-1252', 'Content-Length' => '999999' }
25
+ headers['Content-Encoding'] = compression == 'raw deflate' ? 'deflate' : compression if compression
26
+ stub_request(:head, url).to_return(headers: headers)
27
+ stub_request(:get, url).to_return(body: body, headers: headers)
28
+
29
+ page = MetaInspector.new(url, max_html_bytes: 128, head_first: head_first)
30
+ expect(page.title).to eq('Café')
31
+ expect(page.response.body).to eq(html)
32
+ expect(page.to_s.encoding).to eq(Encoding::Windows_1252)
33
+ end
34
+ end
35
+ end
36
+
37
+ it 'accepts exactly the limit in bytes' do
38
+ html = '<title>é</title>'
39
+ stub_request(:get, url).to_return(body: html, headers: { 'Content-Type' => 'text/html; charset=UTF-8' })
40
+ expect(MetaInspector.new(url, max_html_bytes: html.bytesize).title).to eq('é')
41
+ end
42
+
43
+ it 'preserves a quoted HTTP charset on streamed uncompressed HTML' do
44
+ html = '<title>Café</title>'.encode('Windows-1252')
45
+ stub_request(:get, url).to_return(body: html, headers: { 'Content-Type' => 'text/html; charset="Windows-1252"' })
46
+ page = MetaInspector.new(url, max_html_bytes: 128)
47
+ expect(page.title).to eq('Café')
48
+ expect(page.to_s.encoding).to eq(Encoding::Windows_1252)
49
+ end
50
+
51
+ it 'caches complete streamed responses for subsequent requests' do
52
+ cache = Class.new(Hash) do
53
+ def read(key); self[key]; end
54
+ def write(key, value); self[key] = value; end
55
+ end.new
56
+ stub_request(:get, url).to_return(body: Zlib.gzip('<title>cached</title>'), headers: {
57
+ 'Content-Encoding' => 'gzip', 'Cache-Control' => 'public, max-age=3600'
58
+ })
59
+ 2.times do
60
+ page = MetaInspector.new(url, max_html_bytes: 128, faraday_options: { faraday_http_cache: { store: cache } })
61
+ expect(page.title).to eq('cached')
62
+ end
63
+ expect(a_request(:get, url)).to have_been_made.once
64
+ end
65
+
66
+ it 'accepts an empty response with a zero limit' do
67
+ stub_request(:get, url).to_return(body: '')
68
+ expect(MetaInspector.new(url, max_html_bytes: 0).to_s).to eq('')
69
+ end
70
+
71
+ it 'limits compressed bytes even if the decoded HTML fits' do
72
+ body = Zlib.gzip('<title>x</title>')
73
+ stub_request(:get, url).to_return(body: body, headers: { 'Content-Encoding' => 'gzip' })
74
+ expect { MetaInspector.new(url, max_html_bytes: 16) }.to raise_error(MetaInspector::ParserError)
75
+ end
76
+
77
+ it 'reads concatenated gzip members' do
78
+ body = Zlib.gzip('<title>') + Zlib.gzip('joined</title>')
79
+ stub_request(:get, url).to_return(body: body, headers: { 'Content-Encoding' => 'gzip' })
80
+ expect(MetaInspector.new(url, max_html_bytes: 128).title).to eq('joined')
81
+ end
82
+
83
+ it 'limits the combined output of concatenated gzip members' do
84
+ body = Zlib.gzip('x' * 100) * 2
85
+ stub_request(:get, url).to_return(body: body, headers: { 'Content-Encoding' => 'gzip' })
86
+ expect { MetaInspector.new(url, max_html_bytes: 128) }.to raise_error(MetaInspector::ParserError)
87
+ end
88
+
89
+ %w[gzip deflate].each do |compression|
90
+ it "keeps malformed #{compression} errors as RequestError" do
91
+ stub_request(:get, url).to_return(body: 'not compressed', headers: { 'Content-Encoding' => compression })
92
+ expect { MetaInspector.new(url, max_html_bytes: 128) }.to raise_error(MetaInspector::RequestError) { |error|
93
+ expect(error.cause).to be_a(Zlib::Error)
94
+ }
95
+ end
96
+ end
97
+
98
+ it 'keeps a fresh body for each redirect' do
99
+ stub_request(:get, url).to_return(status: 302, body: 'redirect', headers: { 'Location' => '/next' })
100
+ stub_request(:get, 'https://size.example/next').to_return(body: '<title>next</title>')
101
+ expect(MetaInspector.new(url, max_html_bytes: 32).to_s).to eq('<title>next</title>')
102
+ end
103
+
104
+ it 'rejects oversized redirect bodies before following their location' do
105
+ stub_request(:get, url).to_return(status: 302, body: 'x' * 100, headers: { 'Location' => '/next' })
106
+ expect { MetaInspector.new(url, max_html_bytes: 32) }.to raise_error(MetaInspector::ParserError)
107
+ expect(a_request(:get, 'https://size.example/next')).not_to have_been_made
108
+ end
109
+
110
+ it 'checks cached bodies against the limit of the current request' do
111
+ cache = Class.new(Hash) do
112
+ def read(key); self[key]; end
113
+ def write(key, value); self[key] = value; end
114
+ end.new
115
+ stub_request(:get, url).to_return(body: Zlib.gzip('<title>cached</title>' + ' ' * 1024), headers: {
116
+ 'Content-Encoding' => 'gzip', 'Cache-Control' => 'public, max-age=3600'
117
+ })
118
+ options = { faraday_options: { faraday_http_cache: { store: cache } } }
119
+ expect(MetaInspector.new(url, **options).title).to eq('cached')
120
+ expect { MetaInspector.new(url, **options, max_html_bytes: 128) }.to raise_error(MetaInspector::ParserError)
121
+ expect(a_request(:get, url)).to have_been_made.once
122
+ end
123
+
124
+ %w[gzip deflate].each do |compression|
125
+ it "stops expanding #{compression} before reaching a corrupt trailer" do
126
+ body = '<p>' + 'x' * (4 * 1024 * 1024) + '</p>'
127
+ compressed = compression == 'gzip' ? Zlib.gzip(body) : Zlib::Deflate.deflate(body)
128
+ compressed.setbyte(-1, compressed.getbyte(-1) ^ 255)
129
+ stub_request(:get, url).to_return(body: compressed, headers: {
130
+ 'Content-Type' => 'text/html', 'Content-Encoding' => compression
131
+ })
132
+
133
+ expect { MetaInspector.new(url, max_html_bytes: 64 * 1024) }
134
+ .to raise_error(MetaInspector::ParserError, /limit.*65536 bytes/)
135
+ end
136
+ end
137
+
138
+ context 'with a real HTTP server' do
139
+ around do |example|
140
+ @server = TCPServer.new('127.0.0.1', 0)
141
+ @url = "http://127.0.0.1:#{@server.addr[1]}/page"
142
+ # WebMock buffers real responses, hiding incremental reads.
143
+ WebMock.disable!
144
+ example.run
145
+ ensure
146
+ @server&.close
147
+ @worker&.kill
148
+ @worker&.join
149
+ WebMock.enable!
150
+ WebMock.disable_net_connect!
151
+ end
152
+
153
+ it 'stops an oversized chunked response before the server finishes sending' do
154
+ sent = 0
155
+ @worker = Thread.new do
156
+ socket = @server.accept
157
+ while (line = socket.gets) && line != "\r\n"; end
158
+ socket.write("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n")
159
+ 1024.times do
160
+ socket.write("1000\r\n#{'x' * 4096}\r\n")
161
+ sent += 4096
162
+ sleep 0.001
163
+ end
164
+ socket.write("0\r\n\r\n")
165
+ rescue Errno::EPIPE, Errno::ECONNRESET, IOError
166
+ # The size limit closes the connection.
167
+ ensure
168
+ socket&.close
169
+ end
170
+
171
+ expect { MetaInspector.new(@url, max_html_bytes: 64 * 1024) }
172
+ .to raise_error(MetaInspector::ParserError)
173
+ expect(sent).to be < 4 * 1024 * 1024
174
+ end
175
+ end
176
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: metainspector
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.21.1
4
+ version: 5.21.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jaime Iniesta
@@ -312,6 +312,7 @@ files:
312
312
  - lib/meta_inspector/errors.rb
313
313
  - lib/meta_inspector/http_session.rb
314
314
  - lib/meta_inspector/image_downloader.rb
315
+ - lib/meta_inspector/limited_response.rb
315
316
  - lib/meta_inspector/parser.rb
316
317
  - lib/meta_inspector/parsers/base.rb
317
318
  - lib/meta_inspector/parsers/head_links.rb
@@ -411,6 +412,7 @@ files:
411
412
  - spec/parser_spec.rb
412
413
  - spec/redirect_headers_spec.rb
413
414
  - spec/request_spec.rb
415
+ - spec/response_size_spec.rb
414
416
  - spec/spec_helper.rb
415
417
  - spec/unicode_image_urls_spec.rb
416
418
  - spec/url_filter_spec.rb