2014-11-05 43 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。