1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #32607 from yaroslav/feature/nonce-for-javascript_include_tag

Add the `nonce: true` option for `javascript_include_tag` helper.
This commit is contained in:
Andrew White 2018-04-18 18:49:27 +01:00 committed by GitHub
commit 185fce1597
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 28 additions and 0 deletions

View file

@ -1,3 +1,9 @@
* Add the `nonce: true` option for `javascript_include_tag` helper to
support automatic nonce generation for Content Security Policy.
Works the same way as `javascript_tag nonce: true` does.
*Yaroslav Markin*
* Remove `ActionView::Helpers::RecordTagHelper`.
*Yoshiyuki Hirano*

View file

@ -55,6 +55,8 @@ module ActionView
# that path.
# * <tt>:skip_pipeline</tt> - This option is used to bypass the asset pipeline
# when it is set to true.
# * <tt>:nonce<tt> - When set to true, adds an automatic nonce value if
# you have Content Security Policy enabled.
#
# ==== Examples
#
@ -79,6 +81,9 @@ module ActionView
#
# javascript_include_tag "http://www.example.com/xmlhr.js"
# # => <script src="http://www.example.com/xmlhr.js"></script>
#
# javascript_include_tag "http://www.example.com/xmlhr.js", nonce: true
# # => <script src="http://www.example.com/xmlhr.js" nonce="..."></script>
def javascript_include_tag(*sources)
options = sources.extract_options!.stringify_keys
path_options = options.extract!("protocol", "extname", "host", "skip_pipeline").symbolize_keys
@ -90,6 +95,9 @@ module ActionView
tag_options = {
"src" => href
}.merge!(options)
if tag_options["nonce"] == true
tag_options["nonce"] = content_security_policy_nonce
end
content_tag("script".freeze, "", tag_options)
}.join("\n").html_safe

View file

@ -29,6 +29,10 @@ class AssetTagHelperTest < ActionView::TestCase
"http://www.example.com"
end
def content_security_policy_nonce
"iyhD0Yc0W+c="
end
AssetPathToTag = {
%(asset_path("")) => %(),
%(asset_path(" ")) => %(),
@ -421,6 +425,10 @@ class AssetTagHelperTest < ActionView::TestCase
assert_dom_equal %(<script src="//assets.example.com/javascripts/prototype.js"></script>), javascript_include_tag("prototype")
end
def test_javascript_include_tag_nonce
assert_dom_equal %(<script src="/javascripts/bank.js" nonce="iyhD0Yc0W+c="></script>), javascript_include_tag("bank", nonce: true)
end
def test_stylesheet_path
StylePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
end

View file

@ -1182,6 +1182,12 @@ as part of `html_options`. Example:
<% end -%>
```
The same works with `javascript_include_tag`:
```html+erb
<%= javascript_include_tag "script", nonce: true %>
```
Use [`csp_meta_tag`](http://api.rubyonrails.org/classes/ActionView/Helpers/CspHelper.html#method-i-csp_meta_tag)
helper to create a meta tag "csp-nonce" with the per-session nonce value
for allowing inline `<script>` tags.