0

I was wondering when it is safe to use html_safe and when not. I read that you don't want to do this if the code may contain user content. What does this mean in practice?

flash[:danger]="Dear #{@user.username} <br> please take a look #{view_context.link_to('here', some_path)}" <br> Your organization #{@user.organizationname} bla bla"

For example, for a flash message such as this one, will need html_safe to display correctly, but it also contains in this case username and organizationname which is content entered by the user. Is it then still safe to use html_safe...?

Marty
  • 2,132
  • 4
  • 21
  • 47

2 Answers2

3

If you inject user content into strings you render with html_safe you have to make sure all the injected content is sanitized

flash[:danger]="Dear #{ActionController::Base.helpers.sanitize @user.username} <br> please take a look #{view_context.link_to('here', some_path)}" <br> Your organization #{ActionController::Base.helpers.sanitize @user.organizationname} bla bla"

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

Axel Tetzlaff
  • 1,355
  • 8
  • 11
  • How is this with regard to shared error messages? I have: `<% object.errors.full_messages.each do |msg| %>` `
  • <%= msg.html_safe %>
  • ` `<% end %>`. Is it better to change this to: `<%= sanitize msg.html_safe %>` or `<%= msg %>`? To the best of my knowledge, I only have plain text custom error messages, but you never know given the gems used... What would you say is best-practice for shared error messages? – Marty Jul 25 '15 at 13:53
  • I think it is common and good practice to have plain text only in active record error messages. I've never seen anyone doing `html_safe` on them. So I would definitely omit the html_safe for the extra security until you really need it. I don't think any reasonable gem provider does or should place HTML in active record error messages. – Axel Tetzlaff Jul 25 '15 at 18:51