2014-11-05 35 views
1

我想实施尽可能严格的内容安全策略(CSP)。据this intro on CSP,内嵌样式是不好的(重点煤矿):Can Rails可以呈现无内联CSS的表单来实现更严格的内容安全策略吗?

内嵌样式是相同的方式处理:无论是样式属性和样式的标签应合并成为外部样式表,以防止各种出奇的聪明数据CSS支持的渗透方法。

如果您确实必须拥有内联脚本和样式,则可以通过在脚本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的默认阻止那。我能做什么?

回答

0

您可以重写随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。