Rails 4: Disable automatic CSS sanitizing when using built-in HTML sanitize

微笑、不失礼 提交于 2019-12-11 06:58:00

问题


I'm building an application that has a HTML GUI interface to create, move and edit boxes (div) inside a container div. These boxes get assigned inline styles when editing, these inline styles are saved to the database and are output in the views:

<%= sanitize raw(@slide.content) %>

I want to sanitize the HTML itself, to avoid someone hacking in, for instance, a script tag, through sending that by editing what's sent to the server when the boxes are saved.

Rails 4 has a helper method sanitize available through the class ActionView::Helpers::SanitizeHelper. When I use this with a test content value that contains a malicious <script> tag, the script gets removed just fine. But sanitizing the content also strips CSS properties inside the style tag that are necessary for the boxes, like top, left, position, etc.

In the linked documentation, it's stated that sanitize will automatically use the function sanitize_css when it comes across a style attribute:

sanitize_css(style)

Sanitizes a block of CSS code. Used by sanitize when it comes across a style attribute.

I do not want this behaviour of sanitize. How can I disable sanitize using sanitize_css, to sanitize the HTML, but not the CSS?


回答1:


You can allow any attributes and tags you need, so rails will skip them.

sanitize raw(@slide.content), tags: %w(table tr td ul li), attributes: %w(style href title)

Speaking about CSS rules themselves, it's a bit harder to allow additional rules, but still possible. You can monkey patch the HTML::WhiteListSanitizer class (https://github.com/rails/rails/blob/c71c8a962353642ee44b5cc6ed68dc18322eea72/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb). There are several attributes that can help.



来源:https://stackoverflow.com/questions/21623281/rails-4-disable-automatic-css-sanitizing-when-using-built-in-html-sanitize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!