Skip to content

A platform for community discussion. Free, open, simple.

SECURITY: Escape topic title for mailers

Nat72e224b7627b
diff --git a/lib/email/message_builder.rb b/lib/email/message_builder.rb
index c1141720ebf..c8a94daa606 100644
--- a/lib/email/message_builder.rb
+++ b/lib/email/message_builder.rb
@@ -211,6 +211,14 @@ module Email
body = nil
if @opts[:template]
+ template_args_to_escape = %i[topic_title inviter_name]
+
+ template_args_to_escape.each do |key|
+ next if !@template_args.key?(key)
+
+ @template_args[key] = escaped_template_arg(key)
+ end
+
body = I18n.t("#{@opts[:template]}.text_body_template", template_args).dup
else
body = @opts[:body].dup
@@ -360,5 +368,14 @@ module Email
from_alias = Email.site_title
%Q|"#{Email.cleanup_alias(from_alias)}" <#{source}>|
end
+
+ private
+
+ def escaped_template_arg(key)
+ value = template_args[key].dup
+ # explicitly escaped twice, as Mailers will mark the body as html_safe
+ once_escaped = String.new(ERB::Util.html_escape(value))
+ ERB::Util.html_escape(once_escaped)
+ end
end
end
diff --git a/spec/lib/email/message_builder_spec.rb b/spec/lib/email/message_builder_spec.rb
index 7cfaf0e0669..c86a2c7a85d 100644
--- a/spec/lib/email/message_builder_spec.rb
+++ b/spec/lib/email/message_builder_spec.rb
@@ -524,7 +524,7 @@ RSpec.describe Email::MessageBuilder do
end
end
- describe "subject_template" do
+ describe "template" do
let(:templated_builder) { Email::MessageBuilder.new(to_address, template: "mystery") }
let(:rendered_template) { "rendered template" }
@@ -577,6 +577,43 @@ RSpec.describe Email::MessageBuilder do
expect(templated_builder.subject).to match("customized subject")
end
end
+
+ context "when template arguments include html" do
+ it "escapes arguments for html body" do
+ bad_title = "<a href=\"https://zelda.com\">a bad link</a>"
+ bad_user_name = "<a href=\"https://link.com\">link</a>"
+
+ builder =
+ Email::MessageBuilder.new(
+ to_address,
+ {
+ template: "invite_mailer",
+ topic_title: bad_title,
+ inviter_name: bad_user_name,
+ topic_excerpt: "an excerpt",
+ site_title: "hyrule",
+ site_description: "kingdom",
+ invite_link: "link.com/invite",
+ },
+ )
+
+ expect(builder.body).to eq(<<~EMAIL)
+ &amp;lt;a href=&amp;quot;https://link.com&amp;quot;&amp;gt;link&amp;lt;/a&amp;gt; invited you to a discussion
+
+ > **&amp;lt;a href=&amp;quot;https://zelda.com&amp;quot;&amp;gt;a bad link&amp;lt;/a&amp;gt;**
+ >
+ > an excerpt
+
+ at
+
+ > hyrule -- kingdom
+
+ If you're interested, click the link below:
+
+ link.com/invite
+ EMAIL
+ end
+ end
end
describe "from field" do