Document ETag compatible CSP nonce generator

The content_security_policy initializer template was updated in 40b25fd
to suggest a method compatible with conditional GET requests by default,
so this updates the security documentation to describe the difference
between the original value and the "etag compatible" value and when
they should be used.
This commit is contained in:
Hartley McGuire 2022-04-02 16:08:04 -04:00
parent 926b803297
commit f5cf908122
No known key found for this signature in database
GPG Key ID: E823FC1403858A82

@ -1173,8 +1173,23 @@ end
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
``` ```
Then you can add an automatic nonce value by passing `nonce: true` There are a few tradeoffs to consider when configuring the nonce generator.
as part of `html_options`. Example: Using `SecureRandom.base64(16)` is a good default value, because it will
generate a new random nonce for each request. However, this method is
incompatible with [Conditional GET caching](caching_with_rails.html#conditional-get-caching)
because new nonces will result in new ETag values for every request. An
alternative to per-request random nonces would be to use the session id:
```ruby
Rails.application.config.content_security_policy_nonce_generator = -> request { request.session.id.to_s }
```
This generation method is compatible with ETags, however its security depends on
the session id being sufficiently random and not being exposed in insecure
cookies.
Once nonce generation is configured in an initializer, automatic nonce values
can be added to script tags by passing `nonce: true` as part of `html_options`:
```html+erb ```html+erb
<%= javascript_tag nonce: true do -%> <%= javascript_tag nonce: true do -%>