【问题标题】:Can Rails render forms w/o inline CSS for a stricter Content-Security-Policy?Rails 可以为更严格的 Content-Security-Policy 呈现没有内联 CSS 的表单吗?
【发布时间】:2015-01-01 17:55:10
【问题描述】:

我想实施尽可能严格的内容安全政策 (CSP)。根据this intro on CSP,内联样式不好(强调我的):

内联样式的处理方式相同:样式属性和样式标签都应合并到外部样式表中,以防止 CSS 支持的各种令人惊讶的巧妙数据泄露方法。

如果你真的,绝对必须有内联脚本和样式,你可以通过在 script-src 或 style-src 指令中添加“unsafe-inline”作为允许的源来启用它。 但请不要这样做。

默认的 form_tag 方法为 UTF-8 插入一个隐藏字段(我实际上是在寻找真实性令牌,但在我的标记中找不到它):

<div style="display:none"><input type="hidden" value="✓" name="utf8"></div>

由于 display:none 而在 Firefox 32 中被报告为违反以下 CSP:

$ curl -I http://localhost:3000 | grep Content-Security | fold
Content-Security-Policy-Report-Only: default-src https: 'self'; connect-src http
s: 'self'; font-src https: data:; frame-src https: 'self'; img-src https: 'self'
data:; media-src https: 'self'; object-src https: 'self'; script-src https: 'se
lf'; style-src https: 'self';

我想在我的 CSP 中禁止内联 CSS 样式,但默认情况下 Rails 会阻止这种情况。我能做什么?

【问题讨论】:

    标签: html css ruby-on-rails content-security-policy


    【解决方案1】:

    您可以覆盖 rails 附带的 extra_tags_for_html 方法,只需添加一个隐藏 div 的类,而不是内联添加它。尝试将此添加到帮助程序中,但请记住,这将对您网站上的每个表单产生影响,这听起来就像您正在寻找的那样:

    def extra_tags_for_form(html_options)
      authenticity_token = html_options.delete("authenticity_token")
      method = html_options.delete("method").to_s
    
      method_tag = case method
        when /^get$/ # must be case-insensitive, but can't use downcase as might be nil
          html_options["method"] = "get"
          ''
        when /^post$/, "", nil
          html_options["method"] = "post"
          token_tag(authenticity_token)
        else
          html_options["method"] = "post"
          method_tag(method) + token_tag(authenticity_token)
      end
    
      tags = utf8_enforcer_tag << method_tag
      #content_tag(:div, tags, :style => 'margin:0;padding:0;display:inline')
      content_tag(:div, tags, :class => 'hidden_form_field')
    end
    

    原始行已被注释掉,您需要替换它的行如下。您还必须将其添加到样式表以获得相同的视觉效果:

    .hidden_form_field {
      margin: 0;
      padding: 0;
      display: inline;
    }
    

    本质上,您只是覆盖了将 div 包裹在隐藏表单字段周围的 rails 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2016-11-01
      • 1970-01-01
      • 2019-01-18
      • 2020-09-09
      • 2021-06-02
      相关资源
      最近更新 更多