actionpack 4.2.10 → 6.1.3.2

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of actionpack might be problematic. Click here for more details.

Files changed (187) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +291 -479
  3. data/MIT-LICENSE +1 -1
  4. data/README.rdoc +9 -9
  5. data/lib/abstract_controller/asset_paths.rb +2 -0
  6. data/lib/abstract_controller/base.rb +81 -51
  7. data/lib/{action_controller → abstract_controller}/caching/fragments.rb +64 -17
  8. data/lib/abstract_controller/caching.rb +66 -0
  9. data/lib/abstract_controller/callbacks.rb +61 -33
  10. data/lib/abstract_controller/collector.rb +9 -13
  11. data/lib/abstract_controller/error.rb +6 -0
  12. data/lib/abstract_controller/helpers.rb +115 -99
  13. data/lib/abstract_controller/logger.rb +2 -0
  14. data/lib/abstract_controller/railties/routes_helpers.rb +21 -3
  15. data/lib/abstract_controller/rendering.rb +48 -47
  16. data/lib/abstract_controller/translation.rb +17 -8
  17. data/lib/abstract_controller/url_for.rb +2 -0
  18. data/lib/abstract_controller.rb +13 -5
  19. data/lib/action_controller/api/api_rendering.rb +16 -0
  20. data/lib/action_controller/api.rb +150 -0
  21. data/lib/action_controller/base.rb +29 -24
  22. data/lib/action_controller/caching.rb +12 -57
  23. data/lib/action_controller/form_builder.rb +50 -0
  24. data/lib/action_controller/log_subscriber.rb +17 -19
  25. data/lib/action_controller/metal/basic_implicit_render.rb +13 -0
  26. data/lib/action_controller/metal/conditional_get.rb +134 -46
  27. data/lib/action_controller/metal/content_security_policy.rb +51 -0
  28. data/lib/action_controller/metal/cookies.rb +6 -4
  29. data/lib/action_controller/metal/data_streaming.rb +30 -50
  30. data/lib/action_controller/metal/default_headers.rb +17 -0
  31. data/lib/action_controller/metal/etag_with_flash.rb +18 -0
  32. data/lib/action_controller/metal/etag_with_template_digest.rb +21 -16
  33. data/lib/action_controller/metal/exceptions.rb +63 -15
  34. data/lib/action_controller/metal/flash.rb +9 -8
  35. data/lib/action_controller/metal/head.rb +26 -21
  36. data/lib/action_controller/metal/helpers.rb +37 -18
  37. data/lib/action_controller/metal/http_authentication.rb +81 -73
  38. data/lib/action_controller/metal/implicit_render.rb +53 -9
  39. data/lib/action_controller/metal/instrumentation.rb +32 -35
  40. data/lib/action_controller/metal/live.rb +102 -120
  41. data/lib/action_controller/metal/logging.rb +20 -0
  42. data/lib/action_controller/metal/mime_responds.rb +49 -47
  43. data/lib/action_controller/metal/parameter_encoding.rb +82 -0
  44. data/lib/action_controller/metal/params_wrapper.rb +83 -66
  45. data/lib/action_controller/metal/permissions_policy.rb +46 -0
  46. data/lib/action_controller/metal/redirecting.rb +53 -32
  47. data/lib/action_controller/metal/renderers.rb +87 -44
  48. data/lib/action_controller/metal/rendering.rb +77 -50
  49. data/lib/action_controller/metal/request_forgery_protection.rb +267 -103
  50. data/lib/action_controller/metal/rescue.rb +10 -17
  51. data/lib/action_controller/metal/streaming.rb +12 -11
  52. data/lib/action_controller/metal/strong_parameters.rb +714 -186
  53. data/lib/action_controller/metal/testing.rb +2 -17
  54. data/lib/action_controller/metal/url_for.rb +19 -10
  55. data/lib/action_controller/metal.rb +104 -87
  56. data/lib/action_controller/railtie.rb +28 -10
  57. data/lib/action_controller/railties/helpers.rb +3 -1
  58. data/lib/action_controller/renderer.rb +141 -0
  59. data/lib/action_controller/template_assertions.rb +11 -0
  60. data/lib/action_controller/test_case.rb +296 -422
  61. data/lib/action_controller.rb +34 -23
  62. data/lib/action_dispatch/http/cache.rb +107 -56
  63. data/lib/action_dispatch/http/content_disposition.rb +45 -0
  64. data/lib/action_dispatch/http/content_security_policy.rb +286 -0
  65. data/lib/action_dispatch/http/filter_parameters.rb +32 -25
  66. data/lib/action_dispatch/http/filter_redirect.rb +10 -12
  67. data/lib/action_dispatch/http/headers.rb +55 -22
  68. data/lib/action_dispatch/http/mime_negotiation.rb +82 -50
  69. data/lib/action_dispatch/http/mime_type.rb +153 -121
  70. data/lib/action_dispatch/http/mime_types.rb +20 -6
  71. data/lib/action_dispatch/http/parameters.rb +90 -40
  72. data/lib/action_dispatch/http/permissions_policy.rb +173 -0
  73. data/lib/action_dispatch/http/rack_cache.rb +2 -0
  74. data/lib/action_dispatch/http/request.rb +226 -121
  75. data/lib/action_dispatch/http/response.rb +248 -113
  76. data/lib/action_dispatch/http/upload.rb +21 -7
  77. data/lib/action_dispatch/http/url.rb +182 -100
  78. data/lib/action_dispatch/journey/formatter.rb +90 -43
  79. data/lib/action_dispatch/journey/gtg/builder.rb +28 -41
  80. data/lib/action_dispatch/journey/gtg/simulator.rb +11 -16
  81. data/lib/action_dispatch/journey/gtg/transition_table.rb +23 -21
  82. data/lib/action_dispatch/journey/nfa/dot.rb +3 -14
  83. data/lib/action_dispatch/journey/nodes/node.rb +29 -15
  84. data/lib/action_dispatch/journey/parser.rb +17 -16
  85. data/lib/action_dispatch/journey/parser.y +4 -3
  86. data/lib/action_dispatch/journey/parser_extras.rb +12 -4
  87. data/lib/action_dispatch/journey/path/pattern.rb +58 -54
  88. data/lib/action_dispatch/journey/route.rb +100 -32
  89. data/lib/action_dispatch/journey/router/utils.rb +29 -18
  90. data/lib/action_dispatch/journey/router.rb +55 -51
  91. data/lib/action_dispatch/journey/routes.rb +17 -17
  92. data/lib/action_dispatch/journey/scanner.rb +26 -17
  93. data/lib/action_dispatch/journey/visitors.rb +98 -54
  94. data/lib/action_dispatch/journey.rb +5 -5
  95. data/lib/action_dispatch/middleware/actionable_exceptions.rb +46 -0
  96. data/lib/action_dispatch/middleware/callbacks.rb +3 -6
  97. data/lib/action_dispatch/middleware/cookies.rb +347 -217
  98. data/lib/action_dispatch/middleware/debug_exceptions.rb +135 -63
  99. data/lib/action_dispatch/middleware/debug_locks.rb +124 -0
  100. data/lib/action_dispatch/middleware/debug_view.rb +66 -0
  101. data/lib/action_dispatch/middleware/exception_wrapper.rb +115 -71
  102. data/lib/action_dispatch/middleware/executor.rb +21 -0
  103. data/lib/action_dispatch/middleware/flash.rb +78 -54
  104. data/lib/action_dispatch/middleware/host_authorization.rb +130 -0
  105. data/lib/action_dispatch/middleware/public_exceptions.rb +32 -27
  106. data/lib/action_dispatch/middleware/reloader.rb +5 -91
  107. data/lib/action_dispatch/middleware/remote_ip.rb +53 -45
  108. data/lib/action_dispatch/middleware/request_id.rb +17 -10
  109. data/lib/action_dispatch/middleware/session/abstract_store.rb +41 -26
  110. data/lib/action_dispatch/middleware/session/cache_store.rb +24 -14
  111. data/lib/action_dispatch/middleware/session/cookie_store.rb +74 -75
  112. data/lib/action_dispatch/middleware/session/mem_cache_store.rb +8 -2
  113. data/lib/action_dispatch/middleware/show_exceptions.rb +28 -23
  114. data/lib/action_dispatch/middleware/ssl.rb +118 -35
  115. data/lib/action_dispatch/middleware/stack.rb +82 -41
  116. data/lib/action_dispatch/middleware/static.rb +156 -89
  117. data/lib/action_dispatch/middleware/templates/rescues/_actions.html.erb +13 -0
  118. data/lib/action_dispatch/middleware/templates/rescues/_actions.text.erb +0 -0
  119. data/lib/action_dispatch/middleware/templates/rescues/_message_and_suggestions.html.erb +22 -0
  120. data/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb +4 -14
  121. data/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb +1 -1
  122. data/lib/action_dispatch/middleware/templates/rescues/{_source.erb → _source.html.erb} +4 -2
  123. data/lib/action_dispatch/middleware/templates/rescues/_source.text.erb +8 -0
  124. data/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb +45 -35
  125. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.html.erb +7 -0
  126. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.text.erb +5 -0
  127. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb +23 -4
  128. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb +1 -1
  129. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.html.erb +24 -0
  130. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.text.erb +15 -0
  131. data/lib/action_dispatch/middleware/templates/rescues/layout.erb +105 -8
  132. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.html.erb +19 -0
  133. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.text.erb +3 -0
  134. data/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb +2 -2
  135. data/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb +1 -1
  136. data/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb +3 -3
  137. data/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb +1 -1
  138. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb +1 -1
  139. data/lib/action_dispatch/middleware/templates/routes/_route.html.erb +4 -4
  140. data/lib/action_dispatch/middleware/templates/routes/_table.html.erb +87 -64
  141. data/lib/action_dispatch/railtie.rb +27 -13
  142. data/lib/action_dispatch/request/session.rb +109 -61
  143. data/lib/action_dispatch/request/utils.rb +90 -23
  144. data/lib/action_dispatch/routing/endpoint.rb +9 -2
  145. data/lib/action_dispatch/routing/inspector.rb +141 -102
  146. data/lib/action_dispatch/routing/mapper.rb +811 -473
  147. data/lib/action_dispatch/routing/polymorphic_routes.rb +167 -143
  148. data/lib/action_dispatch/routing/redirection.rb +37 -27
  149. data/lib/action_dispatch/routing/route_set.rb +363 -331
  150. data/lib/action_dispatch/routing/routes_proxy.rb +32 -5
  151. data/lib/action_dispatch/routing/url_for.rb +66 -26
  152. data/lib/action_dispatch/routing.rb +36 -36
  153. data/lib/action_dispatch/system_test_case.rb +190 -0
  154. data/lib/action_dispatch/system_testing/browser.rb +86 -0
  155. data/lib/action_dispatch/system_testing/driver.rb +67 -0
  156. data/lib/action_dispatch/system_testing/server.rb +31 -0
  157. data/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb +138 -0
  158. data/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb +29 -0
  159. data/lib/action_dispatch/testing/assertion_response.rb +46 -0
  160. data/lib/action_dispatch/testing/assertions/response.rb +44 -22
  161. data/lib/action_dispatch/testing/assertions/routing.rb +47 -31
  162. data/lib/action_dispatch/testing/assertions.rb +6 -4
  163. data/lib/action_dispatch/testing/integration.rb +391 -220
  164. data/lib/action_dispatch/testing/request_encoder.rb +55 -0
  165. data/lib/action_dispatch/testing/test_process.rb +53 -22
  166. data/lib/action_dispatch/testing/test_request.rb +27 -34
  167. data/lib/action_dispatch/testing/test_response.rb +11 -11
  168. data/lib/action_dispatch.rb +35 -21
  169. data/lib/action_pack/gem_version.rb +6 -4
  170. data/lib/action_pack/version.rb +3 -1
  171. data/lib/action_pack.rb +4 -2
  172. metadata +78 -49
  173. data/lib/action_controller/metal/force_ssl.rb +0 -97
  174. data/lib/action_controller/metal/hide_actions.rb +0 -40
  175. data/lib/action_controller/metal/rack_delegation.rb +0 -32
  176. data/lib/action_controller/middleware.rb +0 -39
  177. data/lib/action_controller/model_naming.rb +0 -12
  178. data/lib/action_dispatch/http/parameter_filter.rb +0 -72
  179. data/lib/action_dispatch/journey/backwards.rb +0 -5
  180. data/lib/action_dispatch/journey/nfa/builder.rb +0 -76
  181. data/lib/action_dispatch/journey/nfa/simulator.rb +0 -47
  182. data/lib/action_dispatch/journey/nfa/transition_table.rb +0 -163
  183. data/lib/action_dispatch/journey/router/strexp.rb +0 -27
  184. data/lib/action_dispatch/middleware/params_parser.rb +0 -60
  185. data/lib/action_dispatch/testing/assertions/dom.rb +0 -3
  186. data/lib/action_dispatch/testing/assertions/selector.rb +0 -3
  187. data/lib/action_dispatch/testing/assertions/tag.rb +0 -3
@@ -1,6 +1,8 @@
1
- require 'rack/session/abstract/id'
2
- require 'action_controller/metal/exceptions'
3
- require 'active_support/security_utils'
1
+ # frozen_string_literal: true
2
+
3
+ require "rack/session/abstract/id"
4
+ require "action_controller/metal/exceptions"
5
+ require "active_support/security_utils"
4
6
 
5
7
  module ActionController #:nodoc:
6
8
  class InvalidAuthenticityToken < ActionControllerError #:nodoc:
@@ -13,9 +15,14 @@ module ActionController #:nodoc:
13
15
  # by including a token in the rendered HTML for your application. This token is
14
16
  # stored as a random string in the session, to which an attacker does not have
15
17
  # access. When a request reaches your application, \Rails verifies the received
16
- # token with the token in the session. Only HTML and JavaScript requests are checked,
17
- # so this will not protect your XML API (presumably you'll have a different
18
- # authentication scheme there anyway).
18
+ # token with the token in the session. All requests are checked except GET requests
19
+ # as these should be idempotent. Keep in mind that all session-oriented requests
20
+ # are CSRF protected by default, including JavaScript and HTML requests.
21
+ #
22
+ # Since HTML and JavaScript requests are typically made from the browser, we
23
+ # need to ensure to verify request authenticity for the web browser. We can
24
+ # use session-oriented authentication for these types of requests, by using
25
+ # the <tt>protect_from_forgery</tt> method in our controllers.
19
26
  #
20
27
  # GET requests are not protected since they don't have side effects like writing
21
28
  # to the database and don't leak sensitive information. JavaScript requests are
@@ -23,32 +30,30 @@ module ActionController #:nodoc:
23
30
  # URL on your site. When your JavaScript response loads on their site, it executes.
24
31
  # With carefully crafted JavaScript on their end, sensitive data in your JavaScript
25
32
  # response may be extracted. To prevent this, only XmlHttpRequest (known as XHR or
26
- # Ajax) requests are allowed to make GET requests for JavaScript responses.
33
+ # Ajax) requests are allowed to make requests for JavaScript responses.
27
34
  #
28
- # It's important to remember that XML or JSON requests are also affected and if
29
- # you're building an API you'll need something like:
35
+ # Subclasses of <tt>ActionController::Base</tt> are protected by default with the
36
+ # <tt>:exception</tt> strategy, which raises an
37
+ # <tt>ActionController::InvalidAuthenticityToken</tt> error on unverified requests.
30
38
  #
31
- # class ApplicationController < ActionController::Base
32
- # protect_from_forgery
33
- # skip_before_action :verify_authenticity_token, if: :json_request?
39
+ # APIs may want to disable this behavior since they are typically designed to be
40
+ # state-less: that is, the request API client handles the session instead of Rails.
41
+ # One way to achieve this is to use the <tt>:null_session</tt> strategy instead,
42
+ # which allows unverified requests to be handled, but with an empty session:
34
43
  #
35
- # protected
36
- #
37
- # def json_request?
38
- # request.format.json?
39
- # end
44
+ # class ApplicationController < ActionController::Base
45
+ # protect_from_forgery with: :null_session
40
46
  # end
41
47
  #
42
- # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
43
- # which checks the token and resets the session if it doesn't match what was expected.
44
- # A call to this method is generated for new \Rails applications by default.
48
+ # Note that API only applications don't include this module or a session middleware
49
+ # by default, and so don't require CSRF protection to be configured.
45
50
  #
46
51
  # The token parameter is named <tt>authenticity_token</tt> by default. The name and
47
52
  # value of this token must be added to every layout that renders forms by including
48
53
  # <tt>csrf_meta_tags</tt> in the HTML +head+.
49
54
  #
50
55
  # Learn more about CSRF attacks and securing your application in the
51
- # {Ruby on Rails Security Guide}[http://guides.rubyonrails.org/security.html].
56
+ # {Ruby on Rails Security Guide}[https://guides.rubyonrails.org/security.html].
52
57
  module RequestForgeryProtection
53
58
  extend ActiveSupport::Concern
54
59
 
@@ -73,6 +78,22 @@ module ActionController #:nodoc:
73
78
  config_accessor :log_warning_on_csrf_failure
74
79
  self.log_warning_on_csrf_failure = true
75
80
 
81
+ # Controls whether the Origin header is checked in addition to the CSRF token.
82
+ config_accessor :forgery_protection_origin_check
83
+ self.forgery_protection_origin_check = false
84
+
85
+ # Controls whether form-action/method specific CSRF tokens are used.
86
+ config_accessor :per_form_csrf_tokens
87
+ self.per_form_csrf_tokens = false
88
+
89
+ # Controls whether forgery protection is enabled by default.
90
+ config_accessor :default_protect_from_forgery
91
+ self.default_protect_from_forgery = false
92
+
93
+ # Controls whether URL-safe CSRF tokens are generated.
94
+ config_accessor :urlsafe_csrf_tokens, instance_writer: false
95
+ self.urlsafe_csrf_tokens = false
96
+
76
97
  helper_method :form_authenticity_token
77
98
  helper_method :protect_against_forgery?
78
99
  end
@@ -86,13 +107,21 @@ module ActionController #:nodoc:
86
107
  #
87
108
  # class FooController < ApplicationController
88
109
  # protect_from_forgery except: :index
110
+ # end
111
+ #
112
+ # You can disable forgery protection on controller by skipping the verification before_action:
89
113
  #
90
- # You can disable CSRF protection on controller by skipping the verification before_action:
91
114
  # skip_before_action :verify_authenticity_token
92
115
  #
93
116
  # Valid Options:
94
117
  #
95
- # * <tt>:only/:except</tt> - Passed to the <tt>before_action</tt> call. Set which actions are verified.
118
+ # * <tt>:only/:except</tt> - Only apply forgery protection to a subset of actions. For example <tt>only: [ :create, :create_all ]</tt>.
119
+ # * <tt>:if/:unless</tt> - Turn off the forgery protection entirely depending on the passed Proc or method reference.
120
+ # * <tt>:prepend</tt> - By default, the verification of the authentication token will be added at the position of the
121
+ # protect_from_forgery call in your application. This means any callbacks added before are run first. This is useful
122
+ # when you want your forgery protection to depend on other callbacks, like authentication methods (Oauth vs Cookie auth).
123
+ #
124
+ # If you need to add verification to the beginning of the callback chain, use <tt>prepend: true</tt>.
96
125
  # * <tt>:with</tt> - Set the method to handle unverified request.
97
126
  #
98
127
  # Valid unverified request handling methods are:
@@ -100,19 +129,29 @@ module ActionController #:nodoc:
100
129
  # * <tt>:reset_session</tt> - Resets the session.
101
130
  # * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
102
131
  def protect_from_forgery(options = {})
132
+ options = options.reverse_merge(prepend: false)
133
+
103
134
  self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
104
135
  self.request_forgery_protection_token ||= :authenticity_token
105
- prepend_before_action :verify_authenticity_token, options
136
+ before_action :verify_authenticity_token, options
106
137
  append_after_action :verify_same_origin_request
107
138
  end
108
139
 
109
- private
110
-
111
- def protection_method_class(name)
112
- ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
113
- rescue NameError
114
- raise ArgumentError, 'Invalid request forgery protection method, use :null_session, :exception, or :reset_session'
140
+ # Turn off request forgery protection. This is a wrapper for:
141
+ #
142
+ # skip_before_action :verify_authenticity_token
143
+ #
144
+ # See +skip_before_action+ for allowed options.
145
+ def skip_forgery_protection(options = {})
146
+ skip_before_action :verify_authenticity_token, options
115
147
  end
148
+
149
+ private
150
+ def protection_method_class(name)
151
+ ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
152
+ rescue NameError
153
+ raise ArgumentError, "Invalid request forgery protection method, use :null_session, :exception, or :reset_session"
154
+ end
116
155
  end
117
156
 
118
157
  module ProtectionMethods
@@ -124,42 +163,33 @@ module ActionController #:nodoc:
124
163
  # This is the method that defines the application behavior when a request is found to be unverified.
125
164
  def handle_unverified_request
126
165
  request = @controller.request
127
- request.session = NullSessionHash.new(request.env)
128
- request.env['action_dispatch.request.flash_hash'] = nil
129
- request.env['rack.session.options'] = { skip: true }
130
- request.env['action_dispatch.cookies'] = NullCookieJar.build(request)
166
+ request.session = NullSessionHash.new(request)
167
+ request.flash = nil
168
+ request.session_options = { skip: true }
169
+ request.cookie_jar = NullCookieJar.build(request, {})
131
170
  end
132
171
 
133
- protected
134
-
135
- class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc:
136
- def initialize(env)
137
- super(nil, env)
138
- @data = {}
139
- @loaded = true
140
- end
141
-
142
- # no-op
143
- def destroy; end
144
-
145
- def exists?
146
- true
147
- end
148
- end
172
+ private
173
+ class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc:
174
+ def initialize(req)
175
+ super(nil, req)
176
+ @data = {}
177
+ @loaded = true
178
+ end
149
179
 
150
- class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
151
- def self.build(request)
152
- key_generator = request.env[ActionDispatch::Cookies::GENERATOR_KEY]
153
- host = request.host
154
- secure = request.ssl?
180
+ # no-op
181
+ def destroy; end
155
182
 
156
- new(key_generator, host, secure, options_for_env({}))
183
+ def exists?
184
+ true
185
+ end
157
186
  end
158
187
 
159
- def write(*)
160
- # nothing
188
+ class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
189
+ def write(*)
190
+ # nothing
191
+ end
161
192
  end
162
- end
163
193
  end
164
194
 
165
195
  class ResetSession
@@ -183,29 +213,33 @@ module ActionController #:nodoc:
183
213
  end
184
214
  end
185
215
 
186
- protected
216
+ private
187
217
  # The actual before_action that is used to verify the CSRF token.
188
218
  # Don't override this directly. Provide your own forgery protection
189
219
  # strategy instead. If you override, you'll disable same-origin
190
- # `<script>` verification.
220
+ # <tt><script></tt> verification.
191
221
  #
192
222
  # Lean on the protect_from_forgery declaration to mark which actions are
193
223
  # due for same-origin request verification. If protect_from_forgery is
194
224
  # enabled on an action, this before_action flags its after_action to
195
225
  # verify that JavaScript responses are for XHR requests, ensuring they
196
226
  # follow the browser's same-origin policy.
197
- def verify_authenticity_token
227
+ def verify_authenticity_token # :doc:
198
228
  mark_for_same_origin_verification!
199
229
 
200
230
  if !verified_request?
201
231
  if logger && log_warning_on_csrf_failure
202
- logger.warn "Can't verify CSRF token authenticity"
232
+ if valid_request_origin?
233
+ logger.warn "Can't verify CSRF token authenticity."
234
+ else
235
+ logger.warn "HTTP Origin header (#{request.origin}) didn't match request.base_url (#{request.base_url})"
236
+ end
203
237
  end
204
238
  handle_unverified_request
205
239
  end
206
240
  end
207
241
 
208
- def handle_unverified_request
242
+ def handle_unverified_request # :doc:
209
243
  forgery_protection_strategy.new(self).handle_unverified_request
210
244
  end
211
245
 
@@ -215,71 +249,91 @@ module ActionController #:nodoc:
215
249
  "If you know what you're doing, go ahead and disable forgery " \
216
250
  "protection on this action to permit cross-origin JavaScript embedding."
217
251
  private_constant :CROSS_ORIGIN_JAVASCRIPT_WARNING
252
+ # :startdoc:
218
253
 
219
- # If `verify_authenticity_token` was run (indicating that we have
254
+ # If +verify_authenticity_token+ was run (indicating that we have
220
255
  # forgery protection enabled for this request) then also verify that
221
256
  # we aren't serving an unauthorized cross-origin response.
222
- def verify_same_origin_request
257
+ def verify_same_origin_request # :doc:
223
258
  if marked_for_same_origin_verification? && non_xhr_javascript_response?
224
- logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING if logger
259
+ if logger && log_warning_on_csrf_failure
260
+ logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING
261
+ end
225
262
  raise ActionController::InvalidCrossOriginRequest, CROSS_ORIGIN_JAVASCRIPT_WARNING
226
263
  end
227
264
  end
228
265
 
229
266
  # GET requests are checked for cross-origin JavaScript after rendering.
230
- def mark_for_same_origin_verification!
267
+ def mark_for_same_origin_verification! # :doc:
231
268
  @marked_for_same_origin_verification = request.get?
232
269
  end
233
270
 
234
- # If the `verify_authenticity_token` before_action ran, verify that
271
+ # If the +verify_authenticity_token+ before_action ran, verify that
235
272
  # JavaScript responses are only served to same-origin GET requests.
236
- def marked_for_same_origin_verification?
273
+ def marked_for_same_origin_verification? # :doc:
237
274
  @marked_for_same_origin_verification ||= false
238
275
  end
239
276
 
240
277
  # Check for cross-origin JavaScript responses.
241
- def non_xhr_javascript_response?
242
- content_type =~ %r(\Atext/javascript) && !request.xhr?
278
+ def non_xhr_javascript_response? # :doc:
279
+ %r(\A(?:text|application)/javascript).match?(media_type) && !request.xhr?
243
280
  end
244
281
 
245
282
  AUTHENTICITY_TOKEN_LENGTH = 32
246
283
 
247
284
  # Returns true or false if a request is verified. Checks:
248
285
  #
249
- # * is it a GET or HEAD request? Gets should be safe and idempotent
286
+ # * Is it a GET or HEAD request? GETs should be safe and idempotent
250
287
  # * Does the form_authenticity_token match the given token value from the params?
251
- # * Does the X-CSRF-Token header match the form_authenticity_token
252
- def verified_request?
288
+ # * Does the X-CSRF-Token header match the form_authenticity_token?
289
+ def verified_request? # :doc:
253
290
  !protect_against_forgery? || request.get? || request.head? ||
254
- valid_authenticity_token?(session, form_authenticity_param) ||
255
- valid_authenticity_token?(session, request.headers['X-CSRF-Token'])
291
+ (valid_request_origin? && any_authenticity_token_valid?)
292
+ end
293
+
294
+ # Checks if any of the authenticity tokens from the request are valid.
295
+ def any_authenticity_token_valid? # :doc:
296
+ request_authenticity_tokens.any? do |token|
297
+ valid_authenticity_token?(session, token)
298
+ end
299
+ end
300
+
301
+ # Possible authenticity tokens sent in the request.
302
+ def request_authenticity_tokens # :doc:
303
+ [form_authenticity_param, request.x_csrf_token]
256
304
  end
257
305
 
258
306
  # Sets the token value for the current session.
259
- def form_authenticity_token
260
- masked_authenticity_token(session)
307
+ def form_authenticity_token(form_options: {})
308
+ masked_authenticity_token(session, form_options: form_options)
261
309
  end
262
310
 
263
311
  # Creates a masked version of the authenticity token that varies
264
312
  # on each request. The masking is used to mitigate SSL attacks
265
313
  # like BREACH.
266
- def masked_authenticity_token(session)
267
- one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
268
- encrypted_csrf_token = xor_byte_strings(one_time_pad, real_csrf_token(session))
269
- masked_token = one_time_pad + encrypted_csrf_token
270
- Base64.strict_encode64(masked_token)
314
+ def masked_authenticity_token(session, form_options: {}) # :doc:
315
+ action, method = form_options.values_at(:action, :method)
316
+
317
+ raw_token = if per_form_csrf_tokens && action && method
318
+ action_path = normalize_action_path(action)
319
+ per_form_csrf_token(session, action_path, method)
320
+ else
321
+ global_csrf_token(session)
322
+ end
323
+
324
+ mask_token(raw_token)
271
325
  end
272
326
 
273
327
  # Checks the client's masked token to see if it matches the
274
328
  # session token. Essentially the inverse of
275
329
  # +masked_authenticity_token+.
276
- def valid_authenticity_token?(session, encoded_masked_token)
330
+ def valid_authenticity_token?(session, encoded_masked_token) # :doc:
277
331
  if encoded_masked_token.nil? || encoded_masked_token.empty? || !encoded_masked_token.is_a?(String)
278
332
  return false
279
333
  end
280
334
 
281
335
  begin
282
- masked_token = Base64.strict_decode64(encoded_masked_token)
336
+ masked_token = decode_csrf_token(encoded_masked_token)
283
337
  rescue ArgumentError # encoded_masked_token is invalid Base64
284
338
  return false
285
339
  end
@@ -291,44 +345,154 @@ module ActionController #:nodoc:
291
345
  if masked_token.length == AUTHENTICITY_TOKEN_LENGTH
292
346
  # This is actually an unmasked token. This is expected if
293
347
  # you have just upgraded to masked tokens, but should stop
294
- # happening shortly after installing this gem
348
+ # happening shortly after installing this gem.
295
349
  compare_with_real_token masked_token, session
296
350
 
297
351
  elsif masked_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
298
- # Split the token into the one-time pad and the encrypted
299
- # value and decrypt it
300
- one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
301
- encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
302
- csrf_token = xor_byte_strings(one_time_pad, encrypted_csrf_token)
352
+ csrf_token = unmask_token(masked_token)
353
+
354
+ compare_with_global_token(csrf_token, session) ||
355
+ compare_with_real_token(csrf_token, session) ||
356
+ valid_per_form_csrf_token?(csrf_token, session)
357
+ else
358
+ false # Token is malformed.
359
+ end
360
+ end
361
+
362
+ def unmask_token(masked_token) # :doc:
363
+ # Split the token into the one-time pad and the encrypted
364
+ # value and decrypt it.
365
+ one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
366
+ encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
367
+ xor_byte_strings(one_time_pad, encrypted_csrf_token)
368
+ end
369
+
370
+ def mask_token(raw_token) # :doc:
371
+ one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
372
+ encrypted_csrf_token = xor_byte_strings(one_time_pad, raw_token)
373
+ masked_token = one_time_pad + encrypted_csrf_token
374
+ encode_csrf_token(masked_token)
375
+ end
376
+
377
+ def compare_with_real_token(token, session) # :doc:
378
+ ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, real_csrf_token(session))
379
+ end
380
+
381
+ def compare_with_global_token(token, session) # :doc:
382
+ ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, global_csrf_token(session))
383
+ end
303
384
 
304
- compare_with_real_token csrf_token, session
385
+ def valid_per_form_csrf_token?(token, session) # :doc:
386
+ if per_form_csrf_tokens
387
+ correct_token = per_form_csrf_token(
388
+ session,
389
+ request.path.chomp("/"),
390
+ request.request_method
391
+ )
305
392
 
393
+ ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, correct_token)
306
394
  else
307
- false # Token is malformed
395
+ false
308
396
  end
309
397
  end
310
398
 
311
- def compare_with_real_token(token, session)
312
- ActiveSupport::SecurityUtils.secure_compare(token, real_csrf_token(session))
399
+ def real_csrf_token(session) # :doc:
400
+ session[:_csrf_token] ||= generate_csrf_token
401
+ decode_csrf_token(session[:_csrf_token])
402
+ end
403
+
404
+ def per_form_csrf_token(session, action_path, method) # :doc:
405
+ csrf_token_hmac(session, [action_path, method.downcase].join("#"))
406
+ end
407
+
408
+ GLOBAL_CSRF_TOKEN_IDENTIFIER = "!real_csrf_token"
409
+ private_constant :GLOBAL_CSRF_TOKEN_IDENTIFIER
410
+
411
+ def global_csrf_token(session) # :doc:
412
+ csrf_token_hmac(session, GLOBAL_CSRF_TOKEN_IDENTIFIER)
313
413
  end
314
414
 
315
- def real_csrf_token(session)
316
- session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
317
- Base64.strict_decode64(session[:_csrf_token])
415
+ def csrf_token_hmac(session, identifier) # :doc:
416
+ OpenSSL::HMAC.digest(
417
+ OpenSSL::Digest::SHA256.new,
418
+ real_csrf_token(session),
419
+ identifier
420
+ )
318
421
  end
319
422
 
320
- def xor_byte_strings(s1, s2)
321
- s1.bytes.zip(s2.bytes).map { |(c1,c2)| c1 ^ c2 }.pack('c*')
423
+ def xor_byte_strings(s1, s2) # :doc:
424
+ s2 = s2.dup
425
+ size = s1.bytesize
426
+ i = 0
427
+ while i < size
428
+ s2.setbyte(i, s1.getbyte(i) ^ s2.getbyte(i))
429
+ i += 1
430
+ end
431
+ s2
322
432
  end
323
433
 
324
434
  # The form's authenticity parameter. Override to provide your own.
325
- def form_authenticity_param
435
+ def form_authenticity_param # :doc:
326
436
  params[request_forgery_protection_token]
327
437
  end
328
438
 
329
439
  # Checks if the controller allows forgery protection.
330
- def protect_against_forgery?
440
+ def protect_against_forgery? # :doc:
331
441
  allow_forgery_protection
332
442
  end
443
+
444
+ NULL_ORIGIN_MESSAGE = <<~MSG
445
+ The browser returned a 'null' origin for a request with origin-based forgery protection turned on. This usually
446
+ means you have the 'no-referrer' Referrer-Policy header enabled, or that the request came from a site that
447
+ refused to give its origin. This makes it impossible for Rails to verify the source of the requests. Likely the
448
+ best solution is to change your referrer policy to something less strict like same-origin or strict-origin.
449
+ If you cannot change the referrer policy, you can disable origin checking with the
450
+ Rails.application.config.action_controller.forgery_protection_origin_check setting.
451
+ MSG
452
+
453
+ # Checks if the request originated from the same origin by looking at the
454
+ # Origin header.
455
+ def valid_request_origin? # :doc:
456
+ if forgery_protection_origin_check
457
+ # We accept blank origin headers because some user agents don't send it.
458
+ raise InvalidAuthenticityToken, NULL_ORIGIN_MESSAGE if request.origin == "null"
459
+ request.origin.nil? || request.origin == request.base_url
460
+ else
461
+ true
462
+ end
463
+ end
464
+
465
+ def normalize_action_path(action_path) # :doc:
466
+ uri = URI.parse(action_path)
467
+ uri.path.chomp("/")
468
+ end
469
+
470
+ def generate_csrf_token # :nodoc:
471
+ if urlsafe_csrf_tokens
472
+ SecureRandom.urlsafe_base64(AUTHENTICITY_TOKEN_LENGTH, padding: false)
473
+ else
474
+ SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
475
+ end
476
+ end
477
+
478
+ def encode_csrf_token(csrf_token) # :nodoc:
479
+ if urlsafe_csrf_tokens
480
+ Base64.urlsafe_encode64(csrf_token, padding: false)
481
+ else
482
+ Base64.strict_encode64(csrf_token)
483
+ end
484
+ end
485
+
486
+ def decode_csrf_token(encoded_csrf_token) # :nodoc:
487
+ if urlsafe_csrf_tokens
488
+ Base64.urlsafe_decode64(encoded_csrf_token)
489
+ else
490
+ begin
491
+ Base64.strict_decode64(encoded_csrf_token)
492
+ rescue ArgumentError
493
+ Base64.urlsafe_decode64(encoded_csrf_token)
494
+ end
495
+ end
496
+ end
333
497
  end
334
498
  end
@@ -1,35 +1,28 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module ActionController #:nodoc:
2
- # This module is responsible to provide `rescue_from` helpers
3
- # to controllers and configure when detailed exceptions must be
4
+ # This module is responsible for providing +rescue_from+ helpers
5
+ # to controllers and configuring when detailed exceptions must be
4
6
  # shown.
5
7
  module Rescue
6
8
  extend ActiveSupport::Concern
7
9
  include ActiveSupport::Rescuable
8
10
 
9
- def rescue_with_handler(exception)
10
- if (exception.respond_to?(:original_exception) &&
11
- (orig_exception = exception.original_exception) &&
12
- handler_for_rescue(orig_exception))
13
- exception = orig_exception
14
- end
15
- super(exception)
16
- end
17
-
18
11
  # Override this method if you want to customize when detailed
19
12
  # exceptions must be shown. This method is only called when
20
- # consider_all_requests_local is false. By default, it returns
21
- # false, but someone may set it to `request.local?` so local
22
- # requests in production still shows the detailed exception pages.
13
+ # +consider_all_requests_local+ is +false+. By default, it returns
14
+ # +false+, but someone may set it to <tt>request.local?</tt> so local
15
+ # requests in production still show the detailed exception pages.
23
16
  def show_detailed_exceptions?
24
17
  false
25
18
  end
26
19
 
27
20
  private
28
- def process_action(*args)
21
+ def process_action(*)
29
22
  super
30
23
  rescue Exception => exception
31
- request.env['action_dispatch.show_detailed_exceptions'] ||= show_detailed_exceptions?
32
- rescue_with_handler(exception) || raise(exception)
24
+ request.env["action_dispatch.show_detailed_exceptions"] ||= show_detailed_exceptions?
25
+ rescue_with_handler(exception) || raise
33
26
  end
34
27
  end
35
28
  end
@@ -1,9 +1,11 @@
1
- require 'rack/chunked'
1
+ # frozen_string_literal: true
2
+
3
+ require "rack/chunked"
2
4
 
3
5
  module ActionController #:nodoc:
4
6
  # Allows views to be streamed back to the client as they are rendered.
5
7
  #
6
- # The default way Rails renders views is by first rendering the template
8
+ # By default, Rails renders views by first rendering the template
7
9
  # and then the layout. The response is sent to the client after the whole
8
10
  # template is rendered, all queries are made, and the layout is processed.
9
11
  #
@@ -110,9 +112,9 @@ module ActionController #:nodoc:
110
112
  # This means that, if you have <code>yield :title</code> in your layout
111
113
  # and you want to use streaming, you would have to render the whole template
112
114
  # (and eventually trigger all queries) before streaming the title and all
113
- # assets, which kills the purpose of streaming. For this reason Rails 3.1
114
- # introduces a new helper called +provide+ that does the same as +content_for+
115
- # but tells the layout to stop searching for other entries and continue rendering.
115
+ # assets, which kills the purpose of streaming. For this purpose, you can use
116
+ # a helper called +provide+ that does the same as +content_for+ but tells the
117
+ # layout to stop searching for other entries and continue rendering.
116
118
  #
117
119
  # For instance, the template above using +provide+ would be:
118
120
  #
@@ -181,7 +183,7 @@ module ActionController #:nodoc:
181
183
  # unicorn_rails --config-file unicorn.config.rb
182
184
  #
183
185
  # You may also want to configure other parameters like <tt>:tcp_nodelay</tt>.
184
- # Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen
186
+ # Please check its documentation for more information: https://bogomips.org/unicorn/Unicorn/Configurator.html#method-i-listen
185
187
  #
186
188
  # If you are using Unicorn with NGINX, you may need to tweak NGINX.
187
189
  # Streaming should work out of the box on Rainbows.
@@ -193,13 +195,12 @@ module ActionController #:nodoc:
193
195
  module Streaming
194
196
  extend ActiveSupport::Concern
195
197
 
196
- protected
197
-
198
+ private
198
199
  # Set proper cache control and transfer encoding when streaming
199
- def _process_options(options) #:nodoc:
200
+ def _process_options(options)
200
201
  super
201
202
  if options[:stream]
202
- if env["HTTP_VERSION"] == "HTTP/1.0"
203
+ if request.version == "HTTP/1.0"
203
204
  options.delete(:stream)
204
205
  else
205
206
  headers["Cache-Control"] ||= "no-cache"
@@ -210,7 +211,7 @@ module ActionController #:nodoc:
210
211
  end
211
212
 
212
213
  # Call render_body if we are streaming instead of usual +render+.
213
- def _render_template(options) #:nodoc:
214
+ def _render_template(options)
214
215
  if options.delete(:stream)
215
216
  Rack::Chunked::Body.new view_renderer.render_body(view_context, options)
216
217
  else