From e7f04a86746de2421ef6513e3f313dff64334b9f Mon Sep 17 00:00:00 2001 From: Bianca Nenciu Date: Mon, 18 Jul 2022 14:17:54 +0300 Subject: [PATCH] FIX: Use URI#merge to merge base and relative URLs (#17454) The old implementation did not handle all cases, such as the case when `src` is a relative URL that starts with `..`. --- lib/onebox/helpers.rb | 15 ++++----------- spec/lib/onebox/helpers_spec.rb | 9 +++++++++ 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/lib/onebox/helpers.rb b/lib/onebox/helpers.rb index 4d54ac8d2ef..fab4b63f508 100644 --- a/lib/onebox/helpers.rb +++ b/lib/onebox/helpers.rb @@ -199,18 +199,11 @@ module Onebox end def self.get_absolute_image_url(src, url) - if src && !!(src =~ /^\/\//) - uri = URI(url) - src = "#{uri.scheme}:#{src}" - elsif src && src.match(/^https?:\/\//i).nil? - uri = URI(url) - src = if !src.start_with?("/") && uri.path.present? - "#{uri.scheme}://#{uri.host.sub(/\/$/, '')}#{uri.path.sub(/\/$/, '')}/#{src.sub(/^\//, '')}" - else - "#{uri.scheme}://#{uri.host.sub(/\/$/, '')}/#{src.sub(/^\//, '')}" - end + begin + URI.parse(url).merge(src).to_s + rescue ArgumentError, URI::BadURIError, URI::InvalidURIError + src end - src end # Percent-encodes a URI string per RFC3986 - https://tools.ietf.org/html/rfc3986 diff --git a/spec/lib/onebox/helpers_spec.rb b/spec/lib/onebox/helpers_spec.rb index bf5ac880b4b..c8f8c1547dd 100644 --- a/spec/lib/onebox/helpers_spec.rb +++ b/spec/lib/onebox/helpers_spec.rb @@ -174,6 +174,15 @@ RSpec.describe Onebox::Helpers do it { expect(described_class.normalize_url_for_output('linear-gradient(310.77deg, #29AA9F 0%, #098EA6 100%)')).to eq("") } end + describe '.get_absolute_image_url' do + it { expect(described_class.get_absolute_image_url('//meta.discourse.org/favicon.ico', 'https://meta.discourse.org')).to eq('https://meta.discourse.org/favicon.ico') } + it { expect(described_class.get_absolute_image_url('http://meta.discourse.org/favicon.ico', 'https://meta.discourse.org')).to eq('http://meta.discourse.org/favicon.ico') } + it { expect(described_class.get_absolute_image_url('https://meta.discourse.org/favicon.ico', 'https://meta.discourse.org')).to eq('https://meta.discourse.org/favicon.ico') } + it { expect(described_class.get_absolute_image_url('/favicon.ico', 'https://meta.discourse.org')).to eq('https://meta.discourse.org/favicon.ico') } + it { expect(described_class.get_absolute_image_url('/favicon.ico', 'https://meta.discourse.org/forum/subdir')).to eq('https://meta.discourse.org/favicon.ico') } + it { expect(described_class.get_absolute_image_url('../favicon.ico', 'https://meta.discourse.org/forum/subdir/')).to eq('https://meta.discourse.org/forum/favicon.ico') } + end + describe '.uri_encode' do it { expect(described_class.uri_encode('http://example.com/f"o&o?[b"ar]')).to eq("http://example.com/f%22o&o?%5Bb%22ar%5D") } it { expect(described_class.uri_encode("http://example.com/f.o~o;?")).to eq("http://example.com/f.o~o;?%3Cba%27r%3E") }