metainspector 5.20.0 → 5.21.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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +16 -0
  3. data/Gemfile +1 -1
  4. data/README.md +147 -6
  5. data/examples/basic_scraping.rb +4 -3
  6. data/examples/faraday_redirect_options.rb +23 -31
  7. data/examples/html_size_limit.rb +17 -0
  8. data/examples/iframes.rb +15 -0
  9. data/examples/image_details.rb +17 -0
  10. data/examples/image_validation.rb +25 -0
  11. data/examples/link_checker.rb +2 -2
  12. data/examples/responsive_images.rb +15 -0
  13. data/examples/spider.rb +2 -2
  14. data/lib/meta_inspector/document.rb +14 -1
  15. data/lib/meta_inspector/http_session.rb +11 -1
  16. data/lib/meta_inspector/image_downloader.rb +48 -3
  17. data/lib/meta_inspector/parser.rb +20 -1
  18. data/lib/meta_inspector/parsers/head_links.rb +18 -3
  19. data/lib/meta_inspector/parsers/iframes.rb +21 -0
  20. data/lib/meta_inspector/parsers/images.rb +194 -26
  21. data/lib/meta_inspector/parsers/texts.rb +2 -2
  22. data/lib/meta_inspector/url_policy.rb +12 -2
  23. data/lib/meta_inspector/version.rb +1 -1
  24. data/lib/meta_inspector.rb +1 -0
  25. data/meta_inspector.gemspec +1 -2
  26. data/spec/document_spec.rb +139 -0
  27. data/spec/examples_spec.rb +206 -0
  28. data/spec/image_download_spec.rb +11 -0
  29. data/spec/image_metadata_spec.rb +110 -0
  30. data/spec/image_validity_spec.rb +195 -0
  31. data/spec/inline_images_spec.rb +75 -0
  32. data/spec/meta_inspector/head_links_spec.rb +69 -0
  33. data/spec/meta_inspector/iframes_spec.rb +50 -0
  34. data/spec/meta_inspector/images_spec.rb +130 -0
  35. data/spec/meta_inspector/texts_spec.rb +50 -0
  36. data/spec/parser_spec.rb +10 -0
  37. data/spec/unicode_image_urls_spec.rb +74 -0
  38. data/spec/url_filter_spec.rb +1 -1
  39. metadata +27 -36
  40. data/examples/redirect_web_server.rb +0 -5
@@ -0,0 +1,206 @@
1
+ require 'spec_helper'
2
+ require 'stringio'
3
+ require 'json'
4
+
5
+ RSpec.describe 'runnable examples' do
6
+ def run_example(name, *args)
7
+ stub_const('ARGV', args)
8
+ original_stdout = $stdout
9
+ $stdout = StringIO.new
10
+ load(File.expand_path("../examples/#{name}.rb", __dir__), true)
11
+ $stdout.string
12
+ ensure
13
+ $stdout = original_stdout
14
+ end
15
+
16
+ def stub_page(path, html, status: 200)
17
+ stub_request(:get, "http://site.example#{path}").to_return(
18
+ status: status, headers: { 'Content-Type' => 'text/html' }, body: html
19
+ )
20
+ end
21
+
22
+ def stub_image(path, fixture)
23
+ stub_request(:get, "http://site.example#{path}").to_return(fixture_file(fixture))
24
+ end
25
+
26
+ describe 'basic_scraping' do
27
+ it 'prints title and links' do
28
+ output = run_example('basic_scraping', 'http://example.com')
29
+ expect(output).to include('TITLE: An example page', 'internal links found')
30
+ end
31
+
32
+ it 'runs from the examples directory' do
33
+ Dir.chdir(File.expand_path('../examples', __dir__)) do
34
+ expect(run_example('basic_scraping', 'http://example.com')).to include('TITLE: An example page')
35
+ end
36
+ end
37
+
38
+ it 'prints the page hash as JSON' do
39
+ output = Dir.chdir(File.expand_path('../examples', __dir__)) do
40
+ run_example('basic_scraping', 'http://example.com')
41
+ end
42
+ expect(JSON.parse(output.split("to_hash...\n", 2).last)).to include('title' => 'An example page')
43
+ end
44
+ end
45
+
46
+ describe 'spider' do
47
+ it 'visits every internal page once' do
48
+ stub_page('/', '<a href="/a">A</a><a href="/b">B</a>')
49
+ stub_page('/a', '<a href="/">Home</a>')
50
+ stub_page('/b', '<title>B</title>')
51
+
52
+ output = run_example('spider', 'http://site.example/')
53
+ expect(output.lines.grep(/^VISITED: /).map(&:strip)).to contain_exactly(
54
+ 'VISITED: http://site.example/', 'VISITED: http://site.example/a', 'VISITED: http://site.example/b'
55
+ )
56
+ end
57
+ end
58
+
59
+ describe 'link_checker' do
60
+ it 'reports broken links with their origin' do
61
+ stub_page('/', '<a href="/ok">OK</a><a href="/missing">Missing</a>')
62
+ stub_page('/ok', '<title>OK</title>')
63
+ stub_page('/missing', '<title>Missing</title>', status: 404)
64
+
65
+ output = run_example('link_checker', 'http://site.example/')
66
+ expect(output).to include('1 broken links found.', "http://site.example/missing linked from\n - http://site.example/")
67
+ end
68
+ end
69
+
70
+ describe 'faraday_redirect_options' do
71
+ it 'rejects an untrusted initial URL before making a request' do
72
+ target = 'http://127.0.0.1/'
73
+ stub_request(:get, target).to_return(status: 200)
74
+
75
+ expect { run_example('faraday_redirect_options', target) }
76
+ .to output(/Request blocked by url_filter/).to_stderr
77
+ expect(a_request(:get, target)).not_to have_been_made
78
+ end
79
+
80
+ it 'rejects an untrusted redirect before making a request to its destination' do
81
+ target = 'http://127.0.0.1/'
82
+ stub_request(:get, 'https://example.com/').to_return(status: 302, headers: { 'Location' => target })
83
+ stub_request(:get, target).to_return(status: 200)
84
+ stdout = nil
85
+
86
+ expect { stdout = run_example('faraday_redirect_options', 'https://example.com/') }
87
+ .to output(/Request blocked by url_filter/).to_stderr
88
+ expect(stdout).to include('Redirect:')
89
+ expect(a_request(:get, target)).not_to have_been_made
90
+ end
91
+
92
+ it 'follows redirects to allowed HTTPS hosts' do
93
+ stub_request(:get, 'https://example.com/').to_return(status: 302, headers: { 'Location' => 'https://www.example.com/' })
94
+ stub_request(:get, 'https://www.example.com/').to_return(status: 200,
95
+ headers: { 'Content-Type' => 'text/html' }, body: '<title>Allowed page</title>')
96
+
97
+ stdout = run_example('faraday_redirect_options', 'https://example.com/')
98
+ expect(stdout).to match(/Redirect:.*Allowed page/m)
99
+ expect(a_request(:get, 'https://www.example.com/')).to have_been_made.once
100
+ end
101
+ end
102
+
103
+ describe 'responsive_images' do
104
+ it 'lists src and srcset candidates in document order' do
105
+ stub_page('/', <<~HTML)
106
+ <meta property="og:image" content="/og.png">
107
+ <img src="data:image/gif;base64,R0lGODlhAQABAAAAACw=" srcset="/medium.png 2x, /large.png 1000w">
108
+ <picture><source srcset="/wide.webp"><img src="/fallback.png"></picture>
109
+ HTML
110
+
111
+ stdout = run_example('responsive_images', 'http://site.example/')
112
+ expect(stdout.lines.grep(/^ ==> /).map(&:strip)).to eq([
113
+ '==> data:image/gif;base64',
114
+ '==> http://site.example/medium.png',
115
+ '==> http://site.example/large.png',
116
+ '==> http://site.example/wide.webp',
117
+ '==> http://site.example/fallback.png'
118
+ ])
119
+ expect(stdout).to include('5 image candidates found', 'BEST: http://site.example/og.png')
120
+ expect(stdout).not_to include('R0lGOD')
121
+ end
122
+ end
123
+
124
+ describe 'image_details' do
125
+ before do
126
+ stub_page('/', '<img src="/100x100.jpg"><img src="/10x10.jpg">')
127
+ stub_image('/100x100.jpg', '100x100.jpg.response')
128
+ stub_image('/10x10.jpg', '10x10.jpg.response')
129
+ end
130
+
131
+ it 'prints dimensions, type and file size, largest first' do
132
+ stub_page('/', '<img src="/10x10.jpg"><img src="/100x100.jpg">')
133
+ stdout = run_example('image_details', 'http://site.example/')
134
+ expect(stdout).to match(%r{100x100\.jpg 100x100 png, \d+ bytes.*10x10\.jpg 10x10 jpeg, \d+ bytes}m)
135
+ end
136
+
137
+ it 'respects the download limit' do
138
+ stdout = run_example('image_details', 'http://site.example/', '1')
139
+ expect(stdout).to include('http://site.example/100x100.jpg 100x100 png,',
140
+ 'http://site.example/10x10.jpg 0x0 unknown type, unknown size')
141
+ expect(a_request(:get, 'http://site.example/10x10.jpg')).not_to have_been_made
142
+ end
143
+ end
144
+
145
+ describe 'image_validation' do
146
+ before do
147
+ stub_page('/', <<~HTML)
148
+ <meta property="og:image" content="/missing.png">
149
+ <img src="/10x10.jpg"><img src="/broken.png">
150
+ HTML
151
+ stub_image('/10x10.jpg', '10x10.jpg.response')
152
+ stub_page('/broken.png', '<title>Not an image</title>')
153
+ stub_page('/missing.png', '<title>Missing</title>', status: 404)
154
+ end
155
+
156
+ it 'reports validity and skips invalid images' do
157
+ stdout = run_example('image_validation', 'http://site.example/')
158
+ expect(stdout).to include('http://site.example/10x10.jpg: valid',
159
+ 'http://site.example/broken.png: invalid',
160
+ 'BEST: http://site.example/10x10.jpg')
161
+ filtered = stdout.split("images remain after validation...\n", 2).last
162
+ expect(filtered).to include(' ==> http://site.example/10x10.jpg')
163
+ expect(filtered).not_to include('broken.png', 'missing.png')
164
+ expect(a_request(:get, 'http://site.example/missing.png')).to have_been_made.once
165
+ end
166
+
167
+ it 'reports images beyond the download limit as not checked' do
168
+ stdout = run_example('image_validation', 'http://site.example/', '1')
169
+ expect(stdout).to include('http://site.example/10x10.jpg: valid',
170
+ 'http://site.example/broken.png: not checked')
171
+ expect(a_request(:get, 'http://site.example/broken.png')).not_to have_been_made
172
+ expect(a_request(:get, 'http://site.example/missing.png')).not_to have_been_made
173
+ end
174
+
175
+ it 'can run twice without warnings' do
176
+ expect {
177
+ 2.times { run_example('image_validation', 'http://site.example/') }
178
+ }.not_to output.to_stderr
179
+ end
180
+ end
181
+
182
+ describe 'iframes' do
183
+ it 'prints iframe attributes without downloading embedded documents' do
184
+ stub_page('/', '<iframe src=" /embed " title="Video" allowfullscreen></iframe><iframe></iframe>')
185
+
186
+ stdout = run_example('iframes', 'http://site.example/')
187
+ expect(stdout).to include('2 iframes found', ' ==> http://site.example/embed',
188
+ 'title="Video"', 'allowfullscreen=""', ' ==> (no source)')
189
+ expect(a_request(:get, 'http://site.example/embed')).not_to have_been_made
190
+ end
191
+ end
192
+
193
+ describe 'html_size_limit' do
194
+ before do
195
+ stub_page('/', '<title>Small page</title>'.ljust(200))
196
+ end
197
+
198
+ it 'parses pages within the limit' do
199
+ expect(run_example('html_size_limit', 'http://site.example/')).to include('TITLE: Small page')
200
+ end
201
+
202
+ it 'skips pages over the limit' do
203
+ expect(run_example('html_size_limit', 'http://site.example/', '50')).to include('Skipped:')
204
+ end
205
+ end
206
+ end
@@ -60,6 +60,17 @@ RSpec.describe 'bounded image downloads' do
60
60
  end
61
61
  end
62
62
 
63
+ it 'counts a fully received chunked image without a content length' do
64
+ serve do |socket|
65
+ socket.write("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n")
66
+ socket.write("#{png.bytesize.to_s(16)}\r\n")
67
+ socket.write(png)
68
+ socket.write("\r\n0\r\n\r\n")
69
+ end
70
+ page = MetaInspector.new('http://page.example/', document: %(<img src="#{@url}">))
71
+ expect(page.images.with_details.first).to include(type: :png, file_size: png.bytesize)
72
+ end
73
+
63
74
  it 'bounds binary IO and stops a server that ignores Range before reading its full body' do
64
75
  sent = 0
65
76
  serve do |socket|
@@ -0,0 +1,110 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe 'image metadata' do
4
+ let(:url) { 'https://example.com/image.png' }
5
+ let(:png) { "\x89PNG\r\n\x1a\n".b + [13].pack('N') + 'IHDR' + [37, 29].pack('NN') + "\x08\x02\x00\x00\x00".b }
6
+ let(:html) { %(<img src="#{url}" width="10" height="20">) }
7
+
8
+ it 'returns metadata without changing the existing size tuples' do
9
+ stub_request(:get, url).to_return(body: png, headers: { 'Content-Length' => '1234' })
10
+ page = MetaInspector.new('https://example.com/', document: html)
11
+ expect(page.images.with_details).to eq([{ url: url, width: 10, height: 20, type: :png, file_size: 1234 }])
12
+ expect(page.images.with_size).to eq([[url, 10, 20]])
13
+ expect(a_request(:get, url)).to have_been_made.once
14
+ end
15
+
16
+ it 'uses the total from a partial response rather than its content length' do
17
+ stub_request(:get, url).to_return(status: 206, body: png,
18
+ headers: { 'Content-Length' => png.bytesize.to_s, 'Content-Range' => 'bytes 0-28/5000' })
19
+ page = MetaInspector.new('https://example.com/', document: %(<img src="#{url}">))
20
+ expect(page.images.with_details).to eq([{ url: url, width: 37, height: 29, type: :png, file_size: 5000 }])
21
+ end
22
+
23
+ it 'returns nil metadata for failed and disabled downloads' do
24
+ stub_request(:get, url).to_timeout
25
+ page = MetaInspector.new('https://example.com/', document: html)
26
+ expect(page.images.with_details.first).to eq(url: url, width: 10, height: 20, type: nil, file_size: nil)
27
+ disabled = MetaInspector.new('https://example.com/', document: html, download_images: false)
28
+ expect(disabled.images.with_details.first).to eq(url: url, width: 10, height: 20, type: nil, file_size: nil)
29
+ expect(a_request(:get, url)).to have_been_made.once
30
+ end
31
+
32
+ it 'preserves each HTML dimension when the other is missing' do
33
+ stub_request(:get, url).to_return(body: png)
34
+ page = MetaInspector.new('https://example.com/', document: %(<img src="#{url}" width="640">))
35
+ expect(page.images.with_details.first).to include(width: 640, height: 29)
36
+ disabled = MetaInspector.new('https://example.com/', download_images: false,
37
+ document: %(<img src="#{url}" height="480">))
38
+ expect(disabled.images.with_details.first).to include(width: 0, height: 480)
39
+ end
40
+
41
+ it 'counts the bytes of a complete response without a reported length' do
42
+ stub_request(:get, url).to_return(body: png)
43
+ page = MetaInspector.new('https://example.com/', document: html)
44
+ expect(page.images.with_details.first[:file_size]).to eq(png.bytesize)
45
+ end
46
+
47
+ it 'does not treat a stopped download as a complete file' do
48
+ stub_request(:get, url).to_return(body: png + ('x' * (256 * 1024)))
49
+ page = MetaInspector.new('https://example.com/', document: html)
50
+ expect(page.images.with_details.first[:file_size]).to be_nil
51
+ end
52
+
53
+ it 'does not mistake a partial or compressed response length for the file size' do
54
+ stub_request(:get, url).to_return(status: 206, body: png, headers: { 'Content-Length' => '29' })
55
+ page = MetaInspector.new('https://example.com/', document: html)
56
+ expect(page.images.with_details.first).to include(type: :png, file_size: nil)
57
+ end
58
+
59
+ it 'respects the download limit and sorts by area' do
60
+ other = 'https://example.com/other.png'
61
+ stub_request(:get, url).to_return(body: png)
62
+ page = MetaInspector.new('https://example.com/', max_image_downloads: 1,
63
+ document: %(<img src="#{url}"><img src="#{url}"><img src="#{other}" width="100" height="100">))
64
+ expect(page.images.with_details).to eq([
65
+ { url: other, width: 100, height: 100, type: nil, file_size: nil },
66
+ { url: url, width: 37, height: 29, type: :png, file_size: png.bytesize }
67
+ ])
68
+ expect(page.images.with_details.length).to eq(2)
69
+ expect(a_request(:get, url)).to have_been_made.once
70
+ expect(a_request(:get, other)).not_to have_been_made
71
+ end
72
+
73
+ it 'propagates URL policy failures' do
74
+ page = MetaInspector.new('https://example.com/', document: html, url_filter: ->(_) { false })
75
+ expect { page.images.with_details }.to raise_error(MetaInspector::RequestError)
76
+ end
77
+
78
+ it 'returns unknown metadata for an invalid inline image among responsive candidates' do
79
+ stub_request(:get, url).to_return(body: png)
80
+ invalid_png = 'data:image/png;base64,AAAA' # Decodes to three zero bytes, not a PNG.
81
+ html = %(<picture><source srcset="#{url} 2x, #{invalid_png} 1x"></picture>)
82
+ page = MetaInspector.new('https://example.com/', document: html)
83
+ expect(page.images.with_details).to include(include(url: url, type: :png, file_size: png.bytesize))
84
+ expect(page.images.with_details).to include(include(url: 'data:image/png;base64', type: nil, file_size: nil))
85
+ end
86
+
87
+ it 'sends only the page origin as referer to a cross-origin image server' do
88
+ image = 'https://assets.example/image.png'
89
+ stub_request(:get, image).with(headers: { 'Referer' => 'https://example.com/' })
90
+ .to_return(body: png, headers: { 'Content-Length' => '29' })
91
+ page = MetaInspector.new('https://example.com/private?token=secret', document: %(<img src="#{image}">),
92
+ headers: { 'Referer' => 'https://private.example/secret' })
93
+ expect(page.images.with_details.first).to include(type: :png, file_size: 29)
94
+ end
95
+
96
+ it 'does not send a secure page origin to an insecure image server' do
97
+ image = 'http://assets.example/image.png'
98
+ stub_request(:get, image).with { |request| !request.headers.key?('Referer') }.to_return(body: png)
99
+ page = MetaInspector.new('https://example.com/private', document: %(<img src="#{image}">))
100
+ expect(page.images.with_details.first).to include(type: :png)
101
+ end
102
+
103
+ it 'fetches Unicode image URLs while preserving their original representation' do
104
+ original = "https://example.com/image\u202fname.png?resize=800%2C425"
105
+ encoded = 'https://example.com/image%E2%80%AFname.png?resize=800%2C425'
106
+ stub_request(:get, encoded).to_return(body: png)
107
+ page = MetaInspector.new('https://example.com/', document: %(<img src="#{original}">))
108
+ expect(page.images.with_details.first).to include(url: original, type: :png, file_size: png.bytesize)
109
+ end
110
+ end
@@ -0,0 +1,195 @@
1
+ require 'spec_helper'
2
+
3
+ RSpec.describe 'image validity' do
4
+ let(:png) { "\x89PNG\r\n\x1a\n".b + [13].pack('N') + 'IHDR' + [37, 29].pack('NN') + "\x08\x02\x00\x00\x00".b }
5
+ let(:options) { { download_image_options: { reject_invalid_images: true } } }
6
+
7
+ before do
8
+ stub_request(:get, 'http://example.com/missing').to_return(status: 404)
9
+ stub_request(:get, 'http://example.com/not-image').to_return(body: 'not an image')
10
+ stub_request(:get, 'http://example.com/failure').to_timeout
11
+ stub_request(:get, 'http://example.com/good').to_return(body: png)
12
+ end
13
+
14
+ it 'skips invalid suggested images and falls back to a valid suggested image' do
15
+ html = '<meta property="og:image" content="/missing"><meta name="twitter:image" content="/good">'
16
+ page = MetaInspector.new('http://example.com/', **options, document: html)
17
+ expect(page.images.owner_suggested).to eq('http://example.com/good')
18
+ expect(page.images.best).to eq('http://example.com/good')
19
+ expect(a_request(:get, 'http://example.com/good')).to have_been_made.once
20
+ end
21
+
22
+ it 'filters invalid images even when HTML dimensions are present and falls back to a valid image' do
23
+ html = '<meta property="og:image" content="/missing"><img src="/not-image" width="100" height="100"><img src="/failure"><img src="/good" width="10" height="10">'
24
+ page = MetaInspector.new('http://example.com/', **options, document: html)
25
+ expect(page.images.to_a).to eq(['http://example.com/good'])
26
+ expect(page.images.with_size).to eq([['http://example.com/good', 10, 10]])
27
+ expect(page.images.best).to eq('http://example.com/good')
28
+ expect(a_request(:get, 'http://example.com/good')).to have_been_made.once
29
+ end
30
+
31
+ it 'exposes validity for attempted images and nil for images beyond the limit' do
32
+ html = '<img src="/missing"><img src="/good" width="10" height="10"><img src="/not-image">'
33
+ page = MetaInspector.new('http://example.com/', document: html, fetch_all_image_meta: true, max_image_downloads: 2)
34
+ expect(page.images.with_metadata).to eq([
35
+ { url: 'http://example.com/missing', valid: false },
36
+ { url: 'http://example.com/good', valid: true },
37
+ { url: 'http://example.com/not-image', valid: nil }
38
+ ])
39
+ end
40
+
41
+ it 'does not reject or download unverified images when downloads are disabled or exhausted' do
42
+ html = '<meta property="og:image" content="/missing"><img src="/not-image" width="10" height="10">'
43
+ [ { download_images: false }, { max_image_downloads: 0 } ].each do |limits|
44
+ page = MetaInspector.new('http://example.com/', **options, **limits, document: html)
45
+ expect(page.images.best).to eq('http://example.com/missing')
46
+ expect(page.images.to_a).to eq(['http://example.com/not-image'])
47
+ expect(page.images.with_details).to eq([
48
+ { url: 'http://example.com/not-image', width: 10, height: 10, type: nil, file_size: nil }
49
+ ])
50
+ end
51
+ expect(a_request(:get, 'http://example.com/missing')).not_to have_been_made
52
+ end
53
+
54
+ it 'preserves default suggested-image and collection behavior without downloading' do
55
+ html = '<meta property="og:image" content="/missing"><img src="/not-image" width="10" height="10">'
56
+ page = MetaInspector.new('http://example.com/', document: html)
57
+ expect(page.images.best).to eq('http://example.com/missing')
58
+ expect(page.images.to_a).to eq(['http://example.com/not-image'])
59
+ expect(a_request(:get, 'http://example.com/missing')).not_to have_been_made
60
+ expect(a_request(:get, 'http://example.com/not-image')).not_to have_been_made
61
+ end
62
+
63
+ it 'returns nil when all suggested and collection images are invalid' do
64
+ html = '<meta property="og:image" content="/missing"><img src="/not-image" width="10" height="10">'
65
+ page = MetaInspector.new('http://example.com/', **options, document: html)
66
+ expect(page.images.owner_suggested).to be_nil
67
+ expect(page.images.best).to be_nil
68
+ expect(page.images.to_a).to be_empty
69
+ end
70
+
71
+ it 'treats unsupported image URL schemes as invalid' do
72
+ html = '<meta property="og:image" content="data:image/png;base64,AAAA"><img src="ftp://example.com/image.png"><img src="/good">'
73
+ page = MetaInspector.new('http://example.com/', **options, document: html, fetch_all_image_meta: true)
74
+ expect(page.images.best).to eq('http://example.com/good')
75
+ expect(page.images.to_a).to eq(['http://example.com/good'])
76
+ expect(page.images.with_metadata.first).to eq(url: 'ftp://example.com/image.png', valid: false)
77
+ end
78
+
79
+ it 'raises for redirects to unsupported schemes during validation' do
80
+ stub_request(:get, 'http://example.com/redirect').to_return(status: 302, headers: { 'Location' => 'ftp://example.com/image.png' })
81
+ page = MetaInspector.new('http://example.com/', **options, document: '<img src="/redirect">')
82
+ expect { page.images.to_a }.to raise_error(MetaInspector::URLPolicy::InvalidURL)
83
+ end
84
+
85
+ it 'propagates errors from the URL filter during validation' do
86
+ error = MetaInspector::RequestError.new('filter failure')
87
+ page = MetaInspector.new('http://example.com/', **options, document: '<img src="/good">',
88
+ url_filter: ->(_) { raise error })
89
+ expect { page.images.to_a }.to raise_error { |raised| expect(raised).to equal(error) }
90
+ end
91
+
92
+ it 'propagates errors raised by the redirect callback during validation' do
93
+ stub_request(:get, 'http://example.com/redirect').to_return(status: 302, headers: { 'Location' => '/good' })
94
+ [MetaInspector::RequestError, MetaInspector::URLPolicy::InvalidURL, Faraday::ConnectionFailed].each do |error_class|
95
+ error = error_class.new('callback failure')
96
+ callback = ->(_, _) { raise error }
97
+ page = MetaInspector.new('http://example.com/', **options, document: '<img src="/redirect">',
98
+ faraday_options: { redirect: { callback: callback } })
99
+ expect { page.images.to_a }.to raise_error { |raised| expect(raised).to equal(error) }
100
+ end
101
+ end
102
+
103
+ it 'raises for unsupported redirects in metadata-only mode' do
104
+ stub_request(:get, 'http://example.com/redirect').to_return(status: 302, headers: { 'Location' => 'ftp://example.com/image.png' })
105
+ page = MetaInspector.new('http://example.com/', document: '<img src="/redirect">', fetch_all_image_meta: true)
106
+ expect { page.images.with_metadata }.to raise_error(MetaInspector::URLPolicy::InvalidURL)
107
+ end
108
+
109
+ it 'preserves default behavior for redirects to unsupported schemes' do
110
+ stub_request(:get, 'http://example.com/redirect').to_return(status: 302, headers: { 'Location' => 'ftp://example.com/image.png' })
111
+ page = MetaInspector.new('http://example.com/', document: '<img src="/redirect">')
112
+ expect { page.images.with_size }.to raise_error(MetaInspector::RequestError, /HTTP or HTTPS/)
113
+ end
114
+
115
+ describe 'image details' do
116
+ it 'omits images that failed validation instead of raising for unsupported URLs' do
117
+ html = '<img src="data:image/png;base64,AAAA"><img src="ftp://example.com/image.png"><img src="/missing">' \
118
+ '<img src="/good" width="10" height="10">'
119
+ page = MetaInspector.new('http://example.com/', **options, document: html)
120
+ expect(page.images.with_details).to eq([
121
+ { url: 'http://example.com/good', width: 10, height: 10, type: :png, file_size: png.bytesize }
122
+ ])
123
+ end
124
+
125
+ it 'reuses validation lookups instead of downloading images again' do
126
+ page = MetaInspector.new('http://example.com/', **options, document: '<img src="/good">')
127
+ expect(page.images.to_a).to eq(['http://example.com/good'])
128
+ expect(page.images.with_details).to eq([
129
+ { url: 'http://example.com/good', width: 37, height: 29, type: :png, file_size: png.bytesize }
130
+ ])
131
+ expect(a_request(:get, 'http://example.com/good')).to have_been_made.once
132
+ end
133
+
134
+ it 'shares the validation budget and keeps unchecked images without metadata' do
135
+ html = '<meta property="og:image" content="/missing"><img src="/good" width="10" height="10">'
136
+ page = MetaInspector.new('http://example.com/', **options, document: html, max_image_downloads: 1)
137
+ expect(page.images.owner_suggested).to be_nil
138
+ expect(page.images.with_details).to eq([
139
+ { url: 'http://example.com/good', width: 10, height: 10, type: nil, file_size: nil }
140
+ ])
141
+ expect(a_request(:get, 'http://example.com/good')).not_to have_been_made
142
+ end
143
+
144
+ it 'does not spend the budget on unsupported URLs, which need no request' do
145
+ html = '<picture><source srcset="data:image/png;base64,AAAA 1x"></picture><img src="/good">'
146
+ page = MetaInspector.new('http://example.com/', **options, document: html, max_image_downloads: 1)
147
+ expect(page.images.with_details).to eq([
148
+ { url: 'http://example.com/good', width: 37, height: 29, type: :png, file_size: png.bytesize }
149
+ ])
150
+ end
151
+
152
+ it 'propagates URL filter rejections' do
153
+ page = MetaInspector.new('http://example.com/', **options, document: '<img src="/good">',
154
+ url_filter: ->(_) { false })
155
+ expect { page.images.with_details }.to raise_error(MetaInspector::RequestError, /url_filter/)
156
+ end
157
+
158
+ it 'propagates invalid URL errors raised by the redirect callback' do
159
+ stub_request(:get, 'http://example.com/redirect').to_return(status: 302, headers: { 'Location' => '/good' })
160
+ error = MetaInspector::URLPolicy::InvalidURL.new('callback failure')
161
+ page = MetaInspector.new('http://example.com/', **options, document: '<img src="/redirect">',
162
+ faraday_options: { redirect: { callback: ->(_, _) { raise error } } })
163
+ expect { page.images.with_details }.to raise_error { |raised| expect(raised).to equal(error) }
164
+ end
165
+
166
+ it 'keeps unsupported URLs and failed lookups with unknown metadata in metadata-only mode' do
167
+ html = '<img src="data:image/png;base64,AAAA"><img src="/missing" width="5" height="5"><img src="/good">'
168
+ page = MetaInspector.new('http://example.com/', document: html, fetch_all_image_meta: true)
169
+ expect(page.images.with_details).to eq([
170
+ { url: 'http://example.com/good', width: 37, height: 29, type: :png, file_size: png.bytesize },
171
+ { url: 'http://example.com/missing', width: 5, height: 5, type: nil, file_size: nil },
172
+ { url: 'data:image/png;base64', width: 0, height: 0, type: nil, file_size: nil }
173
+ ])
174
+ end
175
+
176
+ it 'treats Unicode image URLs that cannot be normalized as invalid' do
177
+ html = %(<img src="http://%C3/ñ.png"><img src="/good" width="10" height="10">)
178
+ page = MetaInspector.new('http://example.com/', **options, document: html)
179
+ expect(page.images.to_a).to eq(['http://example.com/good'])
180
+ expect(page.images.with_details).to eq([
181
+ { url: 'http://example.com/good', width: 10, height: 10, type: :png, file_size: png.bytesize }
182
+ ])
183
+ end
184
+
185
+ it 'validates Unicode image URLs in their encoded form, preserving the original URL' do
186
+ original = "http://example.com/image\u202fname.png"
187
+ stub_request(:get, 'http://example.com/image%E2%80%AFname.png').to_return(body: png)
188
+ page = MetaInspector.new('http://example.com/', **options, document: %(<img src="#{original}">))
189
+ expect(page.images.to_a).to eq([original])
190
+ expect(page.images.with_details).to eq([
191
+ { url: original, width: 37, height: 29, type: :png, file_size: png.bytesize }
192
+ ])
193
+ end
194
+ end
195
+ end
@@ -0,0 +1,75 @@
1
+ require 'spec_helper'
2
+ require 'base64'
3
+
4
+ RSpec.describe 'inline images' do
5
+ let(:png) { "\x89PNG\r\n\x1a\n".b + [13].pack('N') + 'IHDR' + [37, 29].pack('NN') + "\x08\x02\x00\x00\x00".b }
6
+ let(:data_url) { "data:image/png;base64,#{Base64.strict_encode64(png)}" }
7
+ let(:encoded_url) { 'data:image/png,' + png.bytes.map { |byte| format('%%%02X', byte) }.join }
8
+
9
+ it 'returns PNG type and decoded byte size for base64 and percent-encoded images without spending the download budget' do
10
+ html = %(<img src="#{data_url}"><img src="#{encoded_url}"><img src="ftp://example.com/a"><img src="/good">)
11
+ stub_request(:get, 'http://example.com/good').to_return(body: png)
12
+ page = MetaInspector.new('http://example.com/', document: html, max_image_downloads: 1, fetch_all_image_meta: true, inline_image_data: true)
13
+ expect(page.images.with_metadata.map { |entry| entry[:valid] }).to eq([true, true, false, true])
14
+ expect(page.images.with_details).to include({ url: data_url, width: 37, height: 29, type: :png, file_size: png.bytesize },
15
+ { url: encoded_url, width: 37, height: 29, type: :png, file_size: png.bytesize })
16
+ expect(a_request(:get, 'http://example.com/good')).to have_been_made.once
17
+ end
18
+
19
+ it 'returns unknown details for invalid data and unsupported schemes, and rejects them when validating' do
20
+ html = '<img src="data:image/png;base64,!!!!"><img src="file:///bad">'
21
+ page = MetaInspector.new('http://example.com/', document: html)
22
+ expect(page.images.with_size.map { |_, w, h| [w, h] }).to eq([[0, 0], [0, 0]])
23
+ expect(page.images.with_details.map { |item| [item[:type], item[:file_size]] }).to eq([[nil, nil], [nil, nil]])
24
+ validating = MetaInspector.new('http://example.com/', document: html, download_image_options: { reject_invalid_images: true })
25
+ expect(validating.images.to_a).to be_empty
26
+ end
27
+
28
+ it 'hides payloads in every image result while retaining distinct candidates' do
29
+ second = 'data:image/png;base64,' + Base64.strict_encode64(png.sub([37, 29].pack('NN'), [2, 3].pack('NN')))
30
+ html = %(<meta property="og:image" content="#{data_url}"><link rel="icon" href="#{data_url}"><img src="#{data_url}"><img src="#{second}"><img src="/photo" width="800" height="600">)
31
+ page = MetaInspector.new('http://example.com/', document: html, fetch_all_image_meta: true)
32
+ stub_request(:get, 'http://example.com/photo').to_return(body: png)
33
+ expect(page.images.to_a).to eq(['data:image/png;base64', 'data:image/png;base64', 'http://example.com/photo'])
34
+ expect(page.images[0]).to eq('data:image/png;base64')
35
+ expect(page.images.with_size).to eq([['http://example.com/photo', 800, 600], ['data:image/png;base64', 37, 29], ['data:image/png;base64', 2, 3]])
36
+ expect(page.images.with_details.map { |item| item[:url] }).to eq(['http://example.com/photo', 'data:image/png;base64', 'data:image/png;base64'])
37
+ expect(page.images.with_metadata.map { |item| item[:url] }).to eq(page.images.to_a)
38
+ expect(page.images.owner_suggested).to eq('data:image/png;base64')
39
+ expect(page.images.favicon).to eq('data:image/png;base64')
40
+ expect(page.images.best).to eq('http://example.com/photo')
41
+ expect(page.images.largest).to eq('http://example.com/photo')
42
+ expect(page.meta['og:image']).to eq(data_url)
43
+ end
44
+
45
+ it 'returns and ranks full data URLs when opted in' do
46
+ html = %(<meta property="og:image" content="#{data_url}"><img src="#{data_url}">)
47
+ page = MetaInspector.new('http://example.com/', document: html, inline_image_data: true)
48
+ expect(page.images.to_a).to eq([data_url])
49
+ expect(page.images.with_size).to eq([[data_url, 37, 29]])
50
+ expect(page.images.largest).to eq(data_url)
51
+ expect(page.images.best).to eq(data_url)
52
+ end
53
+
54
+ it 'decodes local images after the HTTP download budget is exhausted' do
55
+ page = MetaInspector.new('http://example.com/', document: %(<img src="#{data_url}">),
56
+ max_image_downloads: 0, fetch_all_image_meta: true, inline_image_data: true)
57
+ expect(page.images.with_metadata).to eq([{ url: data_url, valid: true }])
58
+ expect(page.images.with_details.first).to include(width: 37, height: 29, type: :png, file_size: png.bytesize)
59
+ end
60
+
61
+ it 'skips inline suggested images for best and keeps raw metadata in to_hash' do
62
+ html = %(<meta property="og:image" content="#{data_url}"><meta name="twitter:image" content="/photo"><img src="#{data_url}">)
63
+ stub_request(:get, 'http://example.com/page').to_return(body: html, headers: { 'Content-Type' => 'text/html' })
64
+ page = MetaInspector.new('http://example.com/page')
65
+ expect(page.images.best).to eq('http://example.com/photo')
66
+ expect(page.to_hash['images']).to eq(['data:image/png;base64'])
67
+ expect(page.meta['og:image']).to eq(data_url)
68
+ end
69
+
70
+ it 'returns no largest or best image when all images are inline placeholders' do
71
+ page = MetaInspector.new('http://example.com/', document: %(<img src="#{data_url}">))
72
+ expect(page.images.largest).to be_nil
73
+ expect(page.images.best).to be_nil
74
+ end
75
+ end