Rails: unable to escape after using content_for with raw - ruby-on-rails

In a helper method I have this:
content_for(:title, raw(page_title))
And in my view I have this after calling the helper method:
<%= h(content_for(:title)) %>
However when I do this, the h() does not HTML escape the content? I've also tried content_for(:title).html_safe and html_escape(content_for(:title)) with no success.
I save the content as raw as I want to access the raw (unescaped) content in a separate view.
I'm on Rails 3.0.17.

After some investigation, here's my conclusions: It's all about html_safe.
Let me explain with some code:
page_title.html_safe? #false
raw(page_title).html_safe? #true - that's all that raw does
content_for(:title, raw(page_title)) #associates :title with page_title, where page_title.html_safe? returns true
Now when the view calls the helper method here's what happens:
content_for(:title) #no escaping. Since page_title was stored and html_safe is true, conetnt_for will not escape
h(content_for(:title)) #no escaping. Since the last line returned a string where html_safe? returns true, this will also not escape.
<%= h(content_for(:title)) %> #no escaping. Same reason as above
In short, raw simply sets the html_safe attribute on the string/SafeBuffer. Escaping is performed only on strings where string.html_safe? returns false. Since the string returns true at each opportunity for escaping, the string is never escaped.
Resolution:
Create a new string through interpolation or concatenation - this will set html_safe to false again and the string will be escaped.
For more, check out this guide on SafeBuffers and read the docs.

Related

Does Rails' #link_to only accept one parameter in its block when used outside of ERB?

When I did this in ERB, it works as expected, giving me an a tag that wraps around an image and some text
<%= link_to(...) do %>
<img src="..." />
text
<% end %>
But when I tried to put this in a method, the a tag only wraps the last argument, which in this case, is the text.
def build_link
link_to(...) do
image_tag(...)
text
end
end
Looking at the docs, they only gave an example of using link_to in ERB, so is it smart to assume that using it in a method doesn't work as well and can't accept two parameters?
Following up to my comment:
The reason is behavior happens is because of how Ruby handles blocks, and how Rails handles the output for ActionController.
The trick here is to use handy-dandy concat.
def build_link
link_to("#") do
concat image_tag("http://placehold.it/300x300")
concat "hello world"
end
end
Pretend the block you pass to link_to is just another method, and it gets returned some object/value. In this case, your text object gets returned.
But because you want to output both image_tag and text, you need to pass that together to the output.

Rails escapes string inside label tag

I have a label tag, whose content is loaded from a en.yml file.
html.erb
<%=label_tag(:name, t(:name, scope:[:helpers, :form], name: person_name(person))).html_safe%>
person_name is a helper and outputs a string
persons_helper.rb
def person_name(person)
content_tag(:span,
formatted_name(person.name) || t("helpers.persons.default_name"),
class: 'name').html_safe
end
output string from the helper is passed on t method and concatenated as following
en.yml
name: "Person Name: (%{name})"
I want the output to be like
<label for="person">
Person Name:
<span class='name> John Doe </span>
</label>
but Instead I get
<label for="person">
Person Name:(<span class="name">John Doe</span>)
</label>
I understand that it got to do with html_safe, raw and escaping strings but I just could not get it to work!
Thanks!
Call .html_safe on the method call inside the label_tag. E.g:
<%=label_tag(:name, t(:name, scope:[:helpers, :form], name: person_name(person).html_safe))%>
It appears that the I18n.t method does not return a SafeBuffer (i.e. an html_safe string). So you should call .html_safe on the output from this method.
<%= label_tag(:name, t(:name, scope:[:helpers, :form], name: person_name(person)).html_safe) %>
Note the .html_safe call has been moved in one parenthesis from where you had it. This can also be made marginally easier to see by using the block form of the label_tag helper.
<%= label_tag(:name) { t("helpers.form.name", name: person_name(person)).html_safe } %>
Note: I also switched to the "helpers.form.name" method of selecting the I18n translation in this example to further increase readability (but this may be just a personal preference -- so use your original style if you prefer!).
Finally, for security purposes -- so that a user's name doesn't come through unescaped -- you should remove the .html_safe from your person_name helper and add a strict html_escape (or sanitize) so that it looks like this:
def person_name(person)
content_tag(:span,
h(formatted_name(person.name)) || t("helpers.persons.default_name"),
class: 'name')
end
In this form, the content_tag will make sure everything is html_safe except for the content. Meaning that the person.name will come through as is and be escaped as needed. However, this is not needed if the formatted_name method returns an already escaped or html_safe name. Basically the point is that you don't want to blindly mark strings as html_safe when they come from user inputted values because you don't know if they contain script tags or what. Hopefully this didn't confuse. :) In general, only mark strings as html_safe when you are 100% sure that they are actually always going to be safe (i.e. they come from within your system and not from user input of any sort).
Rails translations can be automatically marked as html_safe but using a naming convention. If a translation is suffixed with _html then the string is marked as html_safe, likewise keys named html are also marked as html_safe.
# config/locales/en.yml
en:
welcome: <b>welcome!</b>
hello_html: <b>hello!</b>
title:
html: <b>title!</b>
In the above t('hello_html') and t('title.html') will be html_safe strings and will not require a call to raw or .html_safe where as t('welcome') will not be html_safe and will require calling raw or .html_safe to avoid the html in the string being escaped.
See http://guides.rubyonrails.org/i18n.html#using-safe-html-translations

Rails 3 and HTML escape from within helpers

From one ERB view, I have this helper call:
<p><%=progress #object.progress %></p>
This is the helper method (I've simplified it):
def progress(value)
s = content_tag(:span, "pre:")
s += " <strong>#{value} %</strong>"
return s.html_safe
end
It seems that if you merge those two types of HTML strings, the latest part is not rendered properly. You'll see this:
pre: <strong>40 %</strong>
If you combine the strings like so:
def progress(value)
s = content_tag(:span, "pre:")
s += content_tag(:strong, " #{value} %")
return s.html_safe
end
everything work!
String returned from content_tag is marked as html_safe, when you add other unsafe string it's escaped before concat.
Here's a nice explanation on how the SafeBuffers (the class that does the html_safe magic) work: http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/
I think, it's happened, because string returned from content_tag marked as html_safe. So, if you try to add something to this string, it's automaticly escaped.
If you are using first example then add to_s for a type transformation.

rails_xss, prefer raw or .html_escape?

Which is preferable?
<%= raw #item.description %>
or
<%= #item.description.html_safe %>
If you are outside of view then the raw helper is not accessible (you can include it anywhere but by default it is not available in model / controller). So in those cases the html_safe is the only sane option.
And inside view? Well, there is source code of the raw helper:
# actionpack-3.0.0/lib/action_view/helpers/raw_output_helper.rb
def raw(stringish)
stringish.to_s.html_safe
end
so there is almost no difference as the raw simply calls #html_safe
As Radek notes, raw uses html_safe, but because it first casts to a string, it avoids null exceptions. Therefore, raw is slightly better!

Don't escape html in ruby on rails

rails 3 seems to escape everything, including html. I have tried using raw() but it still escapes html. Is there a workaround? This is my helper that I am using (/helpers/application_helper.rb):
module ApplicationHelper
def good_time(status = true)
res = ""
if status == true
res << "Status is true, with a long message attached..."
else
res << "Status is false, with another long message"
end
end
end
I am calling the helper in my view using this code:
<%= raw(good_time(true)) %>
You can use .html_safe like this:
def good_time(status = true)
if status
"Status is true, with a long message attached...".html_safe
else
"Status is false, with another long message".html_safe
end
end
<%= good_time(true) %>
I ran into this same thing and discovered a safer solution than using html_safe, especially once you introduce strings which are dynamic.
First, the updated code:
def good_time(long_message1, long_message2, status = true)
html = "".html_safe
html << "Status is #{status}, "
if status
html << long_message1
else
html << long_message2
end
html
end
<%= good_time(true) %>
This escapes long_message content if it is unsafe, but leaves it unescaped if it is safe.
This allows "long message for success & such." to display properly, but also escapes "malicious message <script>alert('foo')</script>".
The explanation boils down to this -- 'foo'.html_safe returns an ActiveSupport::SafeBuffer which acts like a String in every way except one: When you append a String to a SafeBuffer (by calling + or <<), that other String is HTML-escaped before it is appended to the SafeBuffer. When you append another SafeBuffer to a SafeBuffer, no escaping will occur. Rails is rendering all of your views under the hood using SafeBuffers, so the updated method above ends up providing Rails with a SafeBuffer that we've controlled to perform escaping on the long_message "as-needed" rather than "always".
Now, the credit for this answer goes entirely to Henning Koch, and is explained in far more detail at Everything you know about html_safe is wrong -- my recap above attempts only to provide the essence of the explanation in the event that this link ever dies.

Resources