metainspector 5.21.2 → 6.0.0

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.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +37 -0
  3. data/README.md +215 -48
  4. data/lib/meta_inspector/attempt_timeout.rb +40 -0
  5. data/lib/meta_inspector/document.rb +101 -68
  6. data/lib/meta_inspector/errors.rb +5 -1
  7. data/lib/meta_inspector/html_encoding.rb +183 -0
  8. data/lib/meta_inspector/http_session.rb +74 -45
  9. data/lib/meta_inspector/image_downloader.rb +37 -24
  10. data/lib/meta_inspector/parser.rb +144 -34
  11. data/lib/meta_inspector/parsers/base.rb +7 -2
  12. data/lib/meta_inspector/parsers/head_links.rb +20 -28
  13. data/lib/meta_inspector/parsers/iframes.rb +2 -3
  14. data/lib/meta_inspector/parsers/images.rb +119 -70
  15. data/lib/meta_inspector/parsers/links.rb +19 -9
  16. data/lib/meta_inspector/parsers/meta_tags.rb +22 -31
  17. data/lib/meta_inspector/parsers/texts.rb +43 -33
  18. data/lib/meta_inspector/request.rb +67 -55
  19. data/lib/meta_inspector/url.rb +43 -19
  20. data/lib/meta_inspector/url_policy.rb +18 -11
  21. data/lib/meta_inspector/version.rb +1 -1
  22. data/lib/meta_inspector.rb +14 -13
  23. data/lib/metainspector.rb +1 -1
  24. data/meta_inspector.gemspec +1 -1
  25. data/spec/document_spec.rb +154 -56
  26. data/spec/meta_inspector/content_type_spec.rb +47 -0
  27. data/spec/meta_inspector/head_links_spec.rb +3 -3
  28. data/spec/meta_inspector/images_spec.rb +82 -1
  29. data/spec/meta_inspector/links_spec.rb +98 -2
  30. data/spec/meta_inspector/meta_inspector_spec.rb +3 -25
  31. data/spec/meta_inspector/meta_tags_spec.rb +53 -0
  32. data/spec/meta_inspector/texts_spec.rb +140 -3
  33. data/spec/meta_inspector/timeouts_spec.rb +107 -0
  34. data/spec/noscript_spec.rb +179 -0
  35. data/spec/parser_spec.rb +380 -10
  36. data/spec/query_string_spec.rb +125 -0
  37. data/spec/request_errors_spec.rb +91 -0
  38. data/spec/request_spec.rb +28 -10
  39. data/spec/response_encoding_spec.rb +487 -0
  40. data/spec/url_filter_spec.rb +2 -1
  41. data/spec/url_spec.rb +37 -0
  42. metadata +10 -2
data/spec/parser_spec.rb CHANGED
@@ -1,24 +1,394 @@
1
1
  require 'spec_helper'
2
+ require 'json'
2
3
 
3
4
  describe MetaInspector::Parser do
4
5
  let(:doc) { MetaInspector::Document.new('http://pagerankalert.com') }
5
6
  let(:parser) { MetaInspector::Parser.new(doc) }
6
7
 
7
- it 'returns the first feed URL through the deprecated feed method' do
8
- expect { expect(parser.feed).to eq('http://feeds.feedburner.com/PageRankAlert') }
9
- .to output(/DEPRECATION.*page\.feed.*6\.0.*page\.feeds/).to_stderr
8
+ it "should have a Nokogiri::HTML5::Document as parsed" do
9
+ expect(parser.parsed.class).to eq(Nokogiri::HTML5::Document)
10
10
  end
11
11
 
12
- it 'returns the favicon URL through the deprecated favicon method' do
13
- expect { expect(parser.favicon).to eq('http://pagerankalert.com/src/favicon.ico') }
14
- .to output(/DEPRECATION.*page\.favicon.*6\.0.*page\.images\.favicon/).to_stderr
12
+ it "should return the document as a string" do
13
+ expect(parser.to_s.class).to eq(String)
14
+ end
15
+
16
+ describe 'parser resource limits' do
17
+ def nested_html(depth)
18
+ "<html><body>#{'<div>' * depth}<a href=\"/deep\">deep</a>#{'</div>' * depth}" \
19
+ '<a href="/after">after</a><h1>After</h1></body></html>'
20
+ end
21
+
22
+ # Past libxml2's nesting limit (256), within the HTML5 one (400)
23
+ let(:deep_html) { nested_html(300) }
24
+ # Past both limits
25
+ let(:too_deep_html) { nested_html(500) }
26
+
27
+ it 'parses a passed document nested past the libxml2 limit but within the HTML5 one' do
28
+ page = MetaInspector.new('http://example.com', document: deep_html)
29
+
30
+ expect(page.links.raw).to eq(['/deep', '/after'])
31
+ expect(page.h1).to eq(['After'])
32
+ end
33
+
34
+ it 'parses a downloaded document nested past the libxml2 limit but within the HTML5 one' do
35
+ stub_request(:get, 'http://example.com/').to_return(
36
+ body: deep_html, headers: { 'Content-Type' => 'text/html' }
37
+ )
38
+
39
+ expect(MetaInspector.new('http://example.com').links.raw).to eq(['/deep', '/after'])
40
+ end
41
+
42
+ it 'parses markup that only nests in the libxml2 tree' do
43
+ # HTML5 closes the open <div>s at </section>; libxml2's HTML4 parser
44
+ # leaves them open, so each section nests inside the previous one.
45
+ sections = (1..100).map { |i| %(<section><div><div><a href="/r#{i}">Read more</a></section>) }.join
46
+ page = MetaInspector.new('http://example.com', document: "<title>Release notes</title>#{sections}")
47
+
48
+ expect(page.title).to eq('Release notes')
49
+ expect(page.links.raw.size).to eq(100)
50
+ expect(page.parsed.css('section section')).to be_empty
51
+ end
52
+
53
+ it 'rejects a passed document nested past the HTML5 limit' do
54
+ expect do
55
+ MetaInspector.new('http://example.com', document: too_deep_html)
56
+ end.to raise_error(MetaInspector::ParserError, /tree depth limit/)
57
+ end
58
+
59
+ it 'rejects a downloaded document nested past the HTML5 limit' do
60
+ stub_request(:get, 'http://example.com/').to_return(
61
+ body: too_deep_html, headers: { 'Content-Type' => 'text/html' }
62
+ )
63
+
64
+ expect do
65
+ MetaInspector.new('http://example.com')
66
+ end.to raise_error(MetaInspector::ParserError, /tree depth limit/)
67
+ end
68
+
69
+ # libxml2 stops reading at its depth limit, so it can't check the size of
70
+ # what comes after. The same size limits apply to the HTML5 tree instead.
71
+ {
72
+ 'text' => '<p>%s</p>',
73
+ 'attribute value' => '<p title="%s">t</p>',
74
+ 'comment' => '<!--%s-->',
75
+ 'script' => '<script>%s</script>'
76
+ }.each do |kind, template|
77
+ it "rejects an oversized #{kind} after nesting past the libxml2 limit" do
78
+ html = "<html><body>#{'<div>' * 300}#{format(template, 'x' * 10_000_001)}</body></html>"
79
+
80
+ expect do
81
+ MetaInspector.new('http://example.com', document: html)
82
+ end.to raise_error(MetaInspector::ParserError, /Resource limit exceeded/)
83
+ end
84
+ end
85
+
86
+ it 'accepts nodes at the size limit after nesting past the libxml2 limit' do
87
+ html = "<html><body>#{'<div>' * 300}<p title=\"#{'x' * 10_000_000}\">#{'y' * 10_000_000}</p></body></html>"
88
+
89
+ expect(MetaInspector.new('http://example.com', document: html).parsed.at_css('p')['title'].size)
90
+ .to eq(10_000_000)
91
+ end
92
+
93
+ it 'rejects a document truncated by the libxml2 limit when HTML5 cannot parse its encoding' do
94
+ html = "<meta charset=\"UTF-7\">#{deep_html}".b
95
+
96
+ expect do
97
+ MetaInspector.new('http://example.com', document: html)
98
+ end.to raise_error(MetaInspector::ParserError, /Excessive depth in document/)
99
+ end
100
+
101
+ it 'wraps the HTML5 tree depth limit when HTML4 would close nested paragraphs' do
102
+ html = '<div><h1><p>' * 220 + 'deep'
103
+
104
+ expect do
105
+ MetaInspector.new('http://example.com', document: html)
106
+ end.to raise_error(MetaInspector::ParserError, /tree depth limit/)
107
+ end
108
+
109
+ describe 'with allow_non_html_content' do
110
+ def non_html_page(body, content_type)
111
+ stub_request(:get, 'http://example.com/file').to_return(
112
+ body: body, headers: { 'Content-Type' => content_type }
113
+ )
114
+ MetaInspector.new('http://example.com/file', allow_non_html_content: true)
115
+ end
116
+
117
+ it 'returns binary content nested past both depth limits' do
118
+ body = "%PDF-1.7\n".b + ('<x>' * 500) + 'end'
119
+ page = non_html_page(body, 'application/pdf')
120
+
121
+ expect(page.content_type).to eq('application/pdf')
122
+ expect(page.to_s).to eq(body)
123
+ expect(page.parsed.errors.map(&:message)).to include(/Excessive depth in document/)
124
+ expect { page.to_hash }.not_to raise_error
125
+ end
126
+
127
+ it 'returns feeds nested past the HTML5 depth limit' do
128
+ categories = '<category term="tag"/>' * 500
129
+ page = non_html_page(
130
+ "<?xml version=\"1.0\"?><feed><title>Feed</title>#{categories}<link href=\"/entry\"/></feed>",
131
+ 'application/atom+xml'
132
+ )
133
+
134
+ expect(page.content_type).to eq('application/atom+xml')
135
+ expect(page.parsed.at_css('feed > title').text).to eq('Feed')
136
+ expect(page.parsed.css('category').size).to eq(500)
137
+ expect { page.to_hash }.not_to raise_error
138
+ end
139
+
140
+ it 'still rejects HTML responses nested past the HTML5 limit' do
141
+ stub_request(:get, 'http://example.com/').to_return(
142
+ body: too_deep_html, headers: { 'Content-Type' => 'text/html' }
143
+ )
144
+
145
+ expect do
146
+ MetaInspector.new('http://example.com', allow_non_html_content: true)
147
+ end.to raise_error(MetaInspector::ParserError, /tree depth limit/)
148
+ end
149
+
150
+ it 'still enforces max_html_bytes' do
151
+ stub_request(:get, 'http://example.com/file').to_return(
152
+ body: 'x' * 100, headers: { 'Content-Type' => 'application/pdf' }
153
+ )
154
+
155
+ expect do
156
+ MetaInspector.new('http://example.com/file', allow_non_html_content: true, max_html_bytes: 10)
157
+ end.to raise_error(MetaInspector::ParserError)
158
+ end
159
+ end
160
+
161
+ it 'does not introduce an attribute count limit' do
162
+ attributes = (1..500).map { |i| "data-#{i}=\"#{i}\"" }.join(' ')
163
+ page = MetaInspector.new('http://example.com', document: "<h1 #{attributes}><p>Hello</p></h1>")
164
+
165
+ expect(page.h1).to eq(['Hello'])
166
+ end
167
+
168
+ {
169
+ 'text node' => ['<p>', '</p>'],
170
+ 'attribute value' => ['<p title="', '">text</p>'],
171
+ 'comment' => ['<!--', '-->']
172
+ }.each do |kind, (opening, closing)|
173
+ it "does not silently lose content after an oversized #{kind}" do
174
+ html = "#{opening}#{'x' * 12_000_000}#{closing}<a href=\"/after\">after</a>"
175
+
176
+ # Some system libxml2 versions allow oversized attributes and comments.
177
+ if Nokogiri::HTML(html).at_css('a')
178
+ page = MetaInspector.new('http://example.com', document: html)
179
+ expect(page.links.raw).to eq(['/after'])
180
+ else
181
+ expect do
182
+ MetaInspector.new('http://example.com', document: html)
183
+ end.to raise_error(MetaInspector::ParserError, /Resource limit exceeded|huge text node/)
184
+ end
185
+ end
186
+ end
187
+
188
+ it 'preserves all links and headings below the nesting limit' do
189
+ html = "<html><body>#{'<div>' * 250}<a href=\"/deep\">deep</a>#{'</div>' * 250}" \
190
+ '<a href="/after">after</a><h1>After</h1></body></html>'
191
+ page = MetaInspector.new('http://example.com', document: html)
192
+
193
+ expect(page.links.raw).to eq(['/deep', '/after'])
194
+ expect(page.h1).to eq(['After'])
195
+ end
196
+
197
+ it 'continues recovering from ordinary HTML errors' do
198
+ html = '<html><body><unexpected>text</unexpected><a href="/after">after</a></body></html>'
199
+ page = MetaInspector.new('http://example.com', document: html)
200
+
201
+ expect(page.parsed.errors).not_to be_empty
202
+ expect(page.links.raw).to eq(['/after'])
203
+ end
204
+
205
+ it 'continues recovering from fatal encoding errors that do not truncate the document' do
206
+ html = "<meta charset=\"UTF-8\"><title>caf\xE9</title><a href=\"/after\">after</a>".b
207
+ page = MetaInspector.new('http://example.com', document: html)
208
+
209
+ expect(page.parsed.errors.any?(&:fatal?)).to be(true)
210
+ expect(page.links.raw).to eq(['/after'])
211
+ end
212
+
213
+ it 'rejects the nonfatal huge-text diagnostic from older system libxml2 versions' do
214
+ parsed = Nokogiri::HTML('<p>truncated</p>')
215
+ error = Nokogiri::XML::SyntaxError.new('xmlSAX2Characters: huge text node')
216
+ allow(error).to receive(:level).and_return(2)
217
+ parsed.errors << error
218
+ allow(Nokogiri).to receive(:HTML).and_return(parsed)
219
+
220
+ expect do
221
+ MetaInspector.new('http://example.com', document: '<p>text</p><a href="/after">after</a>')
222
+ end.to raise_error(MetaInspector::ParserError, /huge text node/)
223
+ end
15
224
  end
16
225
 
17
- it "should have a Nokogiri::HTML::Document as parsed" do
18
- expect(parser.parsed.class).to eq(Nokogiri::HTML::Document)
226
+ describe 'invalid bytes in a passed document' do
227
+ let(:html) do
228
+ "<html><head><title>caf\xE9</title></head><body><h1>caf\xE9</h1></body></html>"
229
+ end
230
+ let(:page) { MetaInspector.new('http://example.com', document: html) }
231
+
232
+ it 'replaces invalid bytes in the title' do
233
+ expect(page.title).to eq("caf\uFFFD")
234
+ end
235
+
236
+ it 'returns a best title without an encoding error' do
237
+ expect(page.best_title).to eq("caf\uFFFD")
238
+ end
239
+
240
+ it 'returns headings without an encoding error' do
241
+ expect(page.h1).to eq(["caf\uFFFD"])
242
+ end
243
+
244
+ it 'returns serializable metadata without an encoding error' do
245
+ expect(JSON.parse(JSON.generate(page.to_hash))).to include(
246
+ 'title' => "caf\uFFFD", 'best_title' => "caf\uFFFD", 'h1' => ["caf\uFFFD"]
247
+ )
248
+ end
249
+
250
+ it 'preserves the original document, including when frozen' do
251
+ original = html.dup
252
+ html.freeze
253
+
254
+ expect(page.title).to eq("caf\uFFFD")
255
+ expect(page.to_s).to equal(html)
256
+ expect(html).to eq(original)
257
+ end
19
258
  end
20
259
 
21
- it "should return the document as a string" do
22
- expect(parser.to_s.class).to eq(String)
260
+ describe 'valid bytes in a passed document' do
261
+ it 'uses the first charset declaration in a binary string' do
262
+ html = '<html><head><meta charset="utf-8"><title>中国</title></head>' \
263
+ '<body><p>新闻</p><meta charset="gbk"><a href="/a">a</a></body></html>'
264
+ page = MetaInspector.new('http://example.com', document: html.b)
265
+
266
+ expect(page.title).to eq('中国')
267
+ expect(page.links.raw).to eq(['/a'])
268
+ expect(page.parsed.encoding).to eq('UTF-8')
269
+ end
270
+
271
+ [
272
+ '<meta http-equiv="content-type" content="text/html; CHARSET = UTF-8">',
273
+ %q{<META CONTENT="text/html; charset='UTF-8'" HTTP-EQUIV="Content-Type">},
274
+ '<meta charset=UTF-8>',
275
+ '<meta data-note="a > b" charset="UTF-8">'
276
+ ].each do |declaration|
277
+ it "honors the first declaration written as #{declaration}" do
278
+ html = "<html><head>#{declaration}<meta charset=gbk><title>中国</title></head>" \
279
+ '<body><a href="/a">a</a></body></html>'
280
+ page = MetaInspector.new('http://example.com', document: html.b)
281
+
282
+ expect(page.title).to eq('中国')
283
+ expect(page.links.raw).to eq(['/a'])
284
+ end
285
+ end
286
+
287
+ it 'uses a legacy declaration before a conflicting modern declaration' do
288
+ html = '<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">' \
289
+ '<meta charset=UTF-8><title>Café</title><a href="/a">a</a>'
290
+ page = MetaInspector.new('http://example.com', document: html.encode('ISO-8859-1').b)
291
+
292
+ expect(page.title).to eq('Café')
293
+ expect(page.links.raw).to eq(['/a'])
294
+ end
295
+
296
+ it 'ignores meta-like text in comments, scripts and other attributes' do
297
+ html = '<!-- <meta charset=gbk> --><script>var tag = "<meta charset=gbk>";</script>' +
298
+ %q{<meta name="example" content='<meta charset=gbk>'>} +
299
+ '<meta charset=UTF-8><meta charset=gbk><title>中国</title><a href="/a">a</a>'
300
+ page = MetaInspector.new('http://example.com', document: html.b)
301
+
302
+ expect(page.title).to eq('中国')
303
+ expect(page.links.raw).to eq(['/a'])
304
+ end
305
+
306
+ %w[textarea xmp title iframe noembed].each do |element|
307
+ it "ignores meta-like text inside #{element}" do
308
+ html = "<#{element}><meta charset=gbk></#{element}><meta charset=UTF-8>" \
309
+ '<h1>中国</h1><a href="/a">a</a>'
310
+ page = MetaInspector.new('http://example.com', document: html.b)
311
+
312
+ expect(page.h1).to eq(['中国'])
313
+ expect(page.links.raw).to eq(['/a'])
314
+ end
315
+ end
316
+
317
+ %w[UTF-8 UTF-16LE UTF-16BE UTF-32LE UTF-32BE].each do |encoding|
318
+ it "honors a #{encoding} BOM before conflicting meta declarations" do
319
+ html = "\uFEFF<html><head><meta charset=gbk><title>中国</title></head>" \
320
+ '<body><a href="/a">a</a></body></html>'
321
+ body = html.encode(encoding).b.freeze
322
+ page = MetaInspector.new('http://example.com', document: body)
323
+
324
+ expect(page.title).to eq('中国')
325
+ expect(page.links.raw).to eq(['/a'])
326
+ expect(page.to_s).to equal(body)
327
+ end
328
+ end
329
+
330
+ it 'preserves an explicitly tagged string over conflicting meta declarations' do
331
+ html = '<meta charset=gbk><title>中国</title><meta charset=UTF-8><a href="/a">a</a>'
332
+ page = MetaInspector.new('http://example.com', document: html)
333
+
334
+ expect(page.title).to eq('中国')
335
+ expect(page.links.raw).to eq(['/a'])
336
+ end
337
+
338
+ it 'preserves the valid Shift_JIS encoding name when parsing headings' do
339
+ html = '<meta charset="Shift_JIS"><h1><p>日本</p></h1>'.encode('Shift_JIS').b
340
+ page = MetaInspector.new('http://example.com', document: html)
341
+
342
+ expect(page.h1).to eq(['日本'])
343
+ end
344
+
345
+ %w[latin1 L1 ISO_8859-1 ISO_8859-1:1987].each do |charset|
346
+ it "accepts the libxml2 charset alias #{charset} for HTML5 headings" do
347
+ html = "<meta charset=\"#{charset}\"><h1><p>Café</p></h1>".encode('ISO-8859-1').b
348
+ page = MetaInspector.new('http://example.com', document: html)
349
+
350
+ expect(page.h1).to eq(['Café'])
351
+ end
352
+ end
353
+
354
+ it 'retains HTML4 support for encodings without a Ruby converter' do
355
+ html = '<meta charset="UTF-7"><title>Caf+AOk-</title>'.b
356
+ page = MetaInspector.new('http://example.com', document: html)
357
+
358
+ expect(page.title).to eq('Café')
359
+ end
360
+
361
+ it 'preserves valid UTF-8 characters around invalid bytes' do
362
+ html = "<title>Café \xFF 日本語</title>"
363
+ page = MetaInspector.new('http://example.com', document: html)
364
+
365
+ expect(page.title).to eq("Café \uFFFD 日本語")
366
+ end
367
+
368
+ it 'preserves characters in a valid non-UTF-8 string' do
369
+ html = '<title>Café</title>'.encode('ISO-8859-1')
370
+ page = MetaInspector.new('http://example.com', document: html)
371
+
372
+ expect(page.title).to eq('Café')
373
+ end
374
+
375
+ it 'allows Nokogiri to detect the charset of a binary string' do
376
+ html = '<meta charset="ISO-8859-1"><title>Café</title>'.encode('ISO-8859-1').b
377
+ page = MetaInspector.new('http://example.com', document: html)
378
+
379
+ expect(page.title).to eq('Café')
380
+ end
381
+
382
+ it 'decodes GBK characters in a binary document declaring gb2312 before HTML5 parsing' do
383
+ html = '<meta charset="gb2312"><h1><p>朱镕基</p></h1><a href="/after">after</a>'.encode('GBK').b
384
+ original = html.dup
385
+ page = MetaInspector.new('http://example.com', document: html.freeze)
386
+
387
+ expect(page.h1).to eq(['朱镕基'])
388
+ expect(page.best_title).to eq('朱镕基')
389
+ expect(page.links.raw).to eq(['/after'])
390
+ expect(page.to_s).to equal(html)
391
+ expect(html).to eq(original)
392
+ end
23
393
  end
24
394
  end
@@ -0,0 +1,125 @@
1
+ require 'spec_helper'
2
+ require 'socket'
3
+
4
+ # WebMock normalizes request URIs before matching, so these examples read the
5
+ # request line from a real socket to see the query exactly as it was sent.
6
+ RSpec.describe 'query strings' do
7
+ around do |example|
8
+ @server = TCPServer.new('127.0.0.1', 0)
9
+ @base = "http://127.0.0.1:#{@server.addr[1]}"
10
+ @targets = []
11
+ WebMock.disable!
12
+ example.run
13
+ ensure
14
+ @server&.close
15
+ @worker&.kill
16
+ @worker&.join
17
+ WebMock.enable!
18
+ WebMock.disable_net_connect!
19
+ end
20
+
21
+ def serve(responses = {})
22
+ @worker = Thread.new do
23
+ loop do
24
+ socket = @server.accept
25
+ method, target = socket.gets.split
26
+ while (line = socket.gets) && line != "\r\n"; end
27
+ @targets << target
28
+ status, headers, body = responses.fetch(target.split('?').first, [200, { 'Content-Type' => 'text/html' }, ''])
29
+ header_lines = headers.merge('Content-Length' => body.bytesize, 'Connection' => 'close')
30
+ .map { |name, value| "#{name}: #{value}\r\n" }.join
31
+ socket.write("HTTP/1.1 #{status} OK\r\n#{header_lines}\r\n")
32
+ socket.write(body) unless method == 'HEAD'
33
+ socket.close
34
+ end
35
+ rescue IOError
36
+ # The server is closed after each example.
37
+ end
38
+ end
39
+
40
+ [
41
+ '/?b=2&a=1',
42
+ '/?tag=x&tag=y',
43
+ '/?q=a%20b',
44
+ '/?q=1;r=2',
45
+ '/?a=b=c',
46
+ '/?ids=1,2,3',
47
+ '/?a[]=1&a[]=2',
48
+ '/?=x',
49
+ '/?%61=1',
50
+ '/?q=caf%E9'
51
+ ].each do |target|
52
+ it "requests #{target} as given and reports it in url" do
53
+ serve
54
+ page = MetaInspector.new("#{@base}#{target}", normalize_url: false)
55
+ expect(@targets).to eq([target])
56
+ expect(page.url).to eq("#{@base}#{target}")
57
+ end
58
+ end
59
+
60
+ it 'requests a non-UTF-8 escape with URL normalization enabled' do
61
+ serve
62
+ MetaInspector.new("#{@base}/?q=caf%E9")
63
+ expect(@targets).to eq(['/?q=caf%E9'])
64
+ end
65
+
66
+ # With normalize_url, the default, only what can't be sent is escaped (#613).
67
+ {
68
+ '/?q=1;r=2' => '/?q=1;r=2',
69
+ '/?a[]=1&a[]=2' => '/?a[]=1&a[]=2',
70
+ '/?q=a%2fb' => '/?q=a%2fb',
71
+ '/?%61=1' => '/?%61=1',
72
+ '/?q=%7e' => '/?q=%7e',
73
+ '/?q=caf%c3%a9' => '/?q=caf%c3%a9',
74
+ '/?q=(1)*!$+,:@/?' => '/?q=(1)*!$+,:@/?',
75
+ '/?q=café' => '/?q=caf%C3%A9',
76
+ '/?q=a|b' => '/?q=a%7Cb',
77
+ '/?q={x}' => '/?q=%7Bx%7D',
78
+ '/?q=50%' => '/?q=50%25',
79
+ '/?q=%zz' => '/?q=%25zz',
80
+ '/?q=a b' => '/?q=a%20b',
81
+ '/?q="<x>"' => '/?q=%22%3Cx%3E%22',
82
+ '/?q=a^b\\c`d' => '/?q=a%5Eb%5Cc%60d'
83
+ }.each do |given, sent|
84
+ it "requests #{given} as #{sent} with URL normalization" do
85
+ serve
86
+ page = MetaInspector.new("#{@base}#{given}")
87
+ expect(@targets).to eq([sent])
88
+ expect(page.url).to eq("#{@base}#{sent}")
89
+ end
90
+ end
91
+
92
+ it 'keeps the fragment out of the request and in url' do
93
+ serve
94
+ page = MetaInspector.new("#{@base}/page?b=2&a=1#section", normalize_url: false)
95
+ expect(@targets).to eq(['/page?b=2&a=1'])
96
+ expect(page.url).to eq("#{@base}/page?b=2&a=1#section")
97
+ end
98
+
99
+ it 'sends the same query in the HEAD request' do
100
+ serve
101
+ MetaInspector.new("#{@base}/?tag=x&tag=y", head_first: true)
102
+ expect(@targets).to eq(['/?tag=x&tag=y', '/?tag=x&tag=y'])
103
+ end
104
+
105
+ it 'follows redirects from and to URLs with queries' do
106
+ serve('/old' => [301, { 'Location' => '/new?tag=x&tag=y' }, ''])
107
+ page = MetaInspector.new("#{@base}/old?b=2&a=1", normalize_url: false)
108
+ expect(@targets).to eq(['/old?b=2&a=1', '/new?tag=x&tag=y'])
109
+ expect(page.url).to eq("#{@base}/new?tag=x&tag=y")
110
+ end
111
+
112
+ it 'requests image URLs with their query as given' do
113
+ png = "\x89PNG\r\n\x1a\n".b + [13].pack('N') + 'IHDR' + [37, 29].pack('NN') + "\x08\x02\x00\x00\x00".b
114
+ serve('/image' => [200, { 'Content-Type' => 'image/png' }, png])
115
+ page = MetaInspector.new('http://page.example/', document: %(<img src="#{@base}/image?w=2&h=1&w=3">))
116
+ expect(page.images.with_size).to eq([["#{@base}/image?w=2&h=1&w=3", 37, 29]])
117
+ expect(@targets).to eq(['/image?w=2&h=1&w=3'])
118
+ end
119
+
120
+ it 'uses a params encoder given in faraday_options' do
121
+ serve
122
+ MetaInspector.new("#{@base}/?b=2&a=1", faraday_options: { request: { params_encoder: Faraday::FlatParamsEncoder } })
123
+ expect(@targets).to eq(['/?a=1&b=2'])
124
+ end
125
+ end
@@ -0,0 +1,91 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe 'request error handling' do
4
+ let(:url) { 'https://errors.example/page' }
5
+
6
+ %w[gzip deflate].each do |compression|
7
+ it "wraps malformed #{compression} responses in RequestError" do
8
+ stub_request(:get, url).to_return(body: 'not compressed', headers: {
9
+ 'Content-Type' => 'text/html', 'Content-Encoding' => compression
10
+ })
11
+
12
+ expect { MetaInspector.new(url) }.to raise_error(MetaInspector::RequestError) { |error|
13
+ expect(error.cause).to be_a(Zlib::Error)
14
+ expect(error.message).to eq(error.cause.message)
15
+ }
16
+ end
17
+ end
18
+
19
+ describe 'content encodings that are not decoded' do
20
+ let(:compressed) { "\x1B\x4F\x00\xF8\x8D\x94\x6E\xDE\x44\x55\x86\xD6".b * 50 }
21
+
22
+ [['br', 'text/html'], ['zstd', 'text/html; charset=utf-8'], ['gzip, br', 'text/html']].each do |encoding, type|
23
+ it "raises RequestError for Content-Encoding: #{encoding} with #{type}" do
24
+ stub_request(:get, url).to_return(body: compressed, headers: {
25
+ 'Content-Type' => type, 'Content-Encoding' => encoding
26
+ })
27
+
28
+ expect { MetaInspector.new(url) }
29
+ .to raise_error(MetaInspector::RequestError, "Unsupported Content-Encoding: #{encoding}")
30
+ end
31
+ end
32
+
33
+ it 'raises RequestError for non-HTML content too' do
34
+ stub_request(:get, url).to_return(body: compressed, headers: {
35
+ 'Content-Type' => 'application/pdf', 'Content-Encoding' => 'br'
36
+ })
37
+
38
+ expect { MetaInspector.new(url, allow_non_html_content: true) }
39
+ .to raise_error(MetaInspector::RequestError, 'Unsupported Content-Encoding: br')
40
+ end
41
+
42
+ it 'parses an identity-encoded body' do
43
+ stub_request(:get, url).to_return(body: '<title>Hi</title>', headers: {
44
+ 'Content-Type' => 'text/html', 'Content-Encoding' => 'Identity'
45
+ })
46
+
47
+ expect(MetaInspector.new(url).title).to eq('Hi')
48
+ end
49
+
50
+ it 'returns an empty page for an empty body with a Content-Encoding' do
51
+ stub_request(:get, url).to_return(body: '', headers: {
52
+ 'Content-Type' => 'text/html', 'Content-Encoding' => 'gzip'
53
+ })
54
+
55
+ expect(MetaInspector.new(url).title).to be_nil
56
+ end
57
+ end
58
+
59
+ it 'wraps malformed mailto page URLs in RequestError' do
60
+ expect { MetaInspector.new('mailto:') }.to raise_error(MetaInspector::RequestError) { |error|
61
+ expect(error.cause).to be_a(URI::InvalidComponentError)
62
+ }
63
+ end
64
+
65
+ [:head, :get].each do |method|
66
+ it "wraps malformed mailto destinations in #{method} redirects in RequestError" do
67
+ stub_request(method, url).to_return(status: 302, headers: { 'Location' => 'mailto:' })
68
+
69
+ expect { MetaInspector.new(url, head_first: method == :head) }
70
+ .to raise_error(MetaInspector::RequestError) { |error|
71
+ expect(error.cause).to be_a(URI::InvalidComponentError)
72
+ }
73
+ end
74
+ end
75
+
76
+ it 'reports malformed mailto images with unknown dimensions and no best image' do
77
+ page = MetaInspector.new(url, document: '<img src="mailto:">')
78
+
79
+ expect(page.images.with_size).to eq([['mailto:', 0, 0]])
80
+ expect(page.images.best).to be_nil
81
+ end
82
+
83
+ it 'rejects malformed mailto destinations in image redirects with RequestError' do
84
+ stub_request(:get, 'https://errors.example/image').to_return(status: 302, headers: { 'Location' => 'mailto:' })
85
+ page = MetaInspector.new(url, document: '<img src="/image">')
86
+
87
+ expect { page.images.with_size }.to raise_error(MetaInspector::RequestError) { |error|
88
+ expect(error.cause).to be_a(URI::InvalidComponentError)
89
+ }
90
+ end
91
+ end
data/spec/request_spec.rb CHANGED
@@ -14,20 +14,14 @@ describe MetaInspector::Request do
14
14
  expect(page_request.read[0..14]).to eq("<!DOCTYPE html>")
15
15
  end
16
16
 
17
- it "can have a forced encoding" do
17
+ it "replaces invalid bytes in the declared encoding" do
18
18
  page_request =
19
19
  MetaInspector::Request.new(url('http://example.com/invalid_utf8_byte_seq'))
20
20
 
21
- expect do
22
- page_request.read
23
- end.to raise_error(MetaInspector::RequestError, "invalid byte sequence in UTF-8")
24
-
25
- page_request_with_forced_encoding =
26
- MetaInspector::Request.new(url('http://example.com/invalid_utf8_byte_seq'), encoding: "UTF-8")
21
+ body = page_request.read
27
22
 
28
- expect do
29
- page_request_with_forced_encoding.read
30
- end.not_to raise_error
23
+ expect(body.encoding).to eq(Encoding::UTF_8)
24
+ expect(body).to be_valid_encoding
31
25
  end
32
26
  end
33
27
 
@@ -69,6 +63,30 @@ describe MetaInspector::Request do
69
63
  end
70
64
 
71
65
  describe "options it is given" do
66
+ [false, true].each do |head_first|
67
+ it "uses independent connection and read timeouts with head_first: #{head_first}" do
68
+ requests = []
69
+ stubs = Faraday::Adapter::Test::Stubs.new do |stub|
70
+ [:head, :get].each do |method|
71
+ stub.public_send(method, '/') do |env|
72
+ requests << [env.method, env.request.open_timeout, env.request.timeout]
73
+ [200, { 'Content-Type' => 'text/html' }, '<html></html>']
74
+ end
75
+ end
76
+ end
77
+ connection = Faraday.new { |faraday| faraday.adapter :test, stubs }
78
+ http_session = instance_double(MetaInspector::HttpSession, build: connection)
79
+
80
+ MetaInspector::Request.new(url('http://example.com'), http_session: http_session,
81
+ head_first: head_first,
82
+ connection_timeout: 1,
83
+ read_timeout: 10)
84
+
85
+ methods = head_first ? [:head, :get] : [:get]
86
+ expect(requests).to eq(methods.map { |method| [method, 1, 10] })
87
+ end
88
+ end
89
+
72
90
  it "accepts a frozen faraday_options hash" do
73
91
  expect do
74
92
  MetaInspector::Request.new(url('http://example.com'), faraday_options: { ssl: { verify: true } }.freeze)