A platform for community discussion. Free, open, simple.
FIX: Handle malformed URLs in `TopicEmbed.absolutize_urls`.
Alan Guo Xiang Tane4e37257cc5d
diff --git a/app/models/topic_embed.rb b/app/models/topic_embed.rbindex 010676cb162..d3d1572c5d2 100644--- a/app/models/topic_embed.rb+++ b/app/models/topic_embed.rb@@ -208,14 +208,24 @@ class TopicEmbed < ActiveRecord::Basefragment = Nokogiri::HTML5.fragment("<div>#{contents}</div>")fragment.css('a').each do |a|if a['href'].present?- a['href'] = URI.join(prefix, a['href']).to_s+ begin+ a['href'] = URI.join(prefix, a['href']).to_s+ rescue URI::InvalidURIError+ # NOOP, URL is malformed+ endendend+fragment.css('img').each do |a|if a['src'].present?- a['src'] = URI.join(prefix, a['src']).to_s+ begin+ a['src'] = URI.join(prefix, a['src']).to_s+ rescue URI::InvalidURIError+ # NOOP, URL is malformed+ endendend+fragment.at('div').inner_htmlenddiff --git a/spec/models/topic_embed_spec.rb b/spec/models/topic_embed_spec.rbindex 8913e9b3d8e..abd7cd57f66 100644--- a/spec/models/topic_embed_spec.rb+++ b/spec/models/topic_embed_spec.rb@@ -379,13 +379,25 @@ describe TopicEmbed doenddescribe '.absolutize_urls' do- let(:invalid_url) { 'http://source.com/#double#anchor' }- let(:contents) { "hello world new post <a href='/hello'>hello</a>" }-it "handles badly formed URIs" do+ invalid_url = 'http://source.com/#double#anchor'+ contents = "hello world new post <a href='/hello'>hello</a>"+raw = TopicEmbed.absolutize_urls(invalid_url, contents)expect(raw).to eq("hello world new post <a href=\"http://source.com/hello\">hello</a>")end++ it "handles malformed links" do+ url = "https://somesource.com"++ contents = <<~CONTENT+ hello world new post <a href="mailto:[email protected]>">hello</a>+ some image <img src="https:/><invalidimagesrc/">+ CONTENT++ raw = TopicEmbed.absolutize_urls(url, contents)+ expect(raw).to eq(contents)+ endendend