I need to allow inline "style=position: absolute;"
output by sanitize(post.content)
. I found documentation for Rails 4 that said
config.action_view.sanitized_allowed_css_properties = ['position']
in application.rb would add properties to the whitelist, but I can't find documentation whether this is still the case for Rails 5 and it doesn't appear to be working after restarting the server multiple times. Is there a way to easily add whitelisted css properties? This answer for Rails 4 suggests a monkey patch, but I'm not sure where or how to do so.
Update: installing gem rails-deprecated_sanitized allowed the above config line to work, so it looks like sanitized_allowed_css_properties is deprecated. Surely there's a way to do this in Rails 5? I can't step back to 4, and I need to whitelist inline style position in order to get a third party plugin to work (CKEditor + Iframely)
Working off this answer and the list of default allowed properties here, I ended up adding
default_tags = Loofah::HTML5::WhiteList::ALLOWED_CSS_PROPERTIES.add('position')
to application.rb, which allowed position to pass through sanitize by default. Not sure how safe this is.
I have absolutely no idea of what @Jim Hogan tried to do with his answer. I tried it and it did not work. So I spent a bit of time to analyze everything and I found my own answer:
We got a helper named sanitize_css
from ActionController::Base.helpers
.
So why not using it by extracting the raw style ? Nokogiri is included in Rails > 4.
def patched_sanitize(html_tag_string)
sanitize html_tag_string, tags: %w(a b strong), attributes: manual_attributes
end
def manual_attributes
attributes = %w(href target align)
attributes << 'style' unless style_unsafe?
attributes
end
def style_unsafe?
ActionController::Base.helpers.sanitize_css(style_attributes_of(string)).empty?
end
def style_attributes_of(string)
Nokogiri::HTML(self.body).xpath('//body').children.map{|e| e.attr('style')}.join(' ')
end
EDIT: Ok I think I finally understand what OP wanted to say. And for a reason, it DOES work only if one does what I do in this answer. So my answer is complementary I guess :)
You can add multiple CSS properties to whitelist in Loofah for Rails 5 sanitizer.
Loofah::HTML5::WhiteList::ALLOWED_CSS_PROPERTIES.merge %w(position background-image left list-style min-width top z-index)
Add above line in application.rb
(Again not sure how safe this is)