actionpack 7.2.3.1 → 8.1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +606 -120
  3. data/lib/abstract_controller/asset_paths.rb +4 -2
  4. data/lib/abstract_controller/base.rb +11 -5
  5. data/lib/abstract_controller/caching.rb +6 -3
  6. data/lib/abstract_controller/callbacks.rb +6 -0
  7. data/lib/abstract_controller/logger.rb +2 -1
  8. data/lib/abstract_controller/rendering.rb +0 -1
  9. data/lib/action_controller/api.rb +1 -0
  10. data/lib/action_controller/base.rb +3 -2
  11. data/lib/action_controller/caching.rb +1 -2
  12. data/lib/action_controller/form_builder.rb +4 -4
  13. data/lib/action_controller/log_subscriber.rb +22 -3
  14. data/lib/action_controller/metal/allow_browser.rb +12 -2
  15. data/lib/action_controller/metal/conditional_get.rb +30 -1
  16. data/lib/action_controller/metal/data_streaming.rb +5 -5
  17. data/lib/action_controller/metal/exceptions.rb +5 -0
  18. data/lib/action_controller/metal/flash.rb +1 -4
  19. data/lib/action_controller/metal/head.rb +3 -1
  20. data/lib/action_controller/metal/http_authentication.rb +1 -1
  21. data/lib/action_controller/metal/instrumentation.rb +1 -2
  22. data/lib/action_controller/metal/live.rb +83 -31
  23. data/lib/action_controller/metal/permissions_policy.rb +9 -0
  24. data/lib/action_controller/metal/rate_limiting.rb +39 -9
  25. data/lib/action_controller/metal/redirecting.rb +107 -14
  26. data/lib/action_controller/metal/renderers.rb +29 -9
  27. data/lib/action_controller/metal/rendering.rb +16 -3
  28. data/lib/action_controller/metal/request_forgery_protection.rb +18 -10
  29. data/lib/action_controller/metal/rescue.rb +9 -0
  30. data/lib/action_controller/metal/streaming.rb +5 -84
  31. data/lib/action_controller/metal/strong_parameters.rb +294 -98
  32. data/lib/action_controller/railtie.rb +35 -15
  33. data/lib/action_controller/structured_event_subscriber.rb +116 -0
  34. data/lib/action_controller/test_case.rb +12 -2
  35. data/lib/action_dispatch/http/cache.rb +143 -12
  36. data/lib/action_dispatch/http/content_security_policy.rb +14 -1
  37. data/lib/action_dispatch/http/filter_parameters.rb +5 -3
  38. data/lib/action_dispatch/http/mime_negotiation.rb +66 -2
  39. data/lib/action_dispatch/http/mime_types.rb +1 -0
  40. data/lib/action_dispatch/http/param_builder.rb +187 -0
  41. data/lib/action_dispatch/http/param_error.rb +26 -0
  42. data/lib/action_dispatch/http/parameters.rb +3 -3
  43. data/lib/action_dispatch/http/permissions_policy.rb +8 -1
  44. data/lib/action_dispatch/http/query_parser.rb +55 -0
  45. data/lib/action_dispatch/http/request.rb +70 -21
  46. data/lib/action_dispatch/http/response.rb +52 -17
  47. data/lib/action_dispatch/http/url.rb +112 -16
  48. data/lib/action_dispatch/journey/formatter.rb +5 -0
  49. data/lib/action_dispatch/journey/gtg/simulator.rb +33 -12
  50. data/lib/action_dispatch/journey/gtg/transition_table.rb +33 -41
  51. data/lib/action_dispatch/journey/nodes/node.rb +2 -1
  52. data/lib/action_dispatch/journey/parser.rb +99 -196
  53. data/lib/action_dispatch/journey/route.rb +45 -31
  54. data/lib/action_dispatch/journey/router/utils.rb +9 -15
  55. data/lib/action_dispatch/journey/router.rb +59 -81
  56. data/lib/action_dispatch/journey/routes.rb +7 -0
  57. data/lib/action_dispatch/journey/scanner.rb +44 -42
  58. data/lib/action_dispatch/journey/visitors.rb +55 -23
  59. data/lib/action_dispatch/journey/visualizer/fsm.js +4 -6
  60. data/lib/action_dispatch/log_subscriber.rb +7 -3
  61. data/lib/action_dispatch/middleware/cookies.rb +24 -5
  62. data/lib/action_dispatch/middleware/debug_exceptions.rb +24 -5
  63. data/lib/action_dispatch/middleware/debug_view.rb +11 -5
  64. data/lib/action_dispatch/middleware/exception_wrapper.rb +12 -12
  65. data/lib/action_dispatch/middleware/executor.rb +12 -2
  66. data/lib/action_dispatch/middleware/host_authorization.rb +3 -2
  67. data/lib/action_dispatch/middleware/public_exceptions.rb +1 -5
  68. data/lib/action_dispatch/middleware/remote_ip.rb +61 -24
  69. data/lib/action_dispatch/middleware/request_id.rb +2 -1
  70. data/lib/action_dispatch/middleware/session/abstract_store.rb +5 -0
  71. data/lib/action_dispatch/middleware/session/cache_store.rb +44 -4
  72. data/lib/action_dispatch/middleware/session/cookie_store.rb +0 -3
  73. data/lib/action_dispatch/middleware/ssl.rb +13 -3
  74. data/lib/action_dispatch/middleware/templates/rescues/_copy_button.html.erb +1 -0
  75. data/lib/action_dispatch/middleware/templates/rescues/_source.html.erb +3 -5
  76. data/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb +9 -5
  77. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.html.erb +1 -0
  78. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb +1 -0
  79. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.html.erb +4 -0
  80. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.text.erb +3 -0
  81. data/lib/action_dispatch/middleware/templates/rescues/layout.erb +50 -0
  82. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.html.erb +1 -0
  83. data/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb +1 -0
  84. data/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb +7 -8
  85. data/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb +1 -1
  86. data/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb +1 -0
  87. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb +1 -0
  88. data/lib/action_dispatch/railtie.rb +21 -0
  89. data/lib/action_dispatch/request/session.rb +1 -0
  90. data/lib/action_dispatch/request/utils.rb +9 -3
  91. data/lib/action_dispatch/routing/inspector.rb +80 -57
  92. data/lib/action_dispatch/routing/mapper.rb +404 -223
  93. data/lib/action_dispatch/routing/polymorphic_routes.rb +2 -2
  94. data/lib/action_dispatch/routing/redirection.rb +10 -7
  95. data/lib/action_dispatch/routing/route_set.rb +21 -12
  96. data/lib/action_dispatch/routing/routes_proxy.rb +1 -0
  97. data/lib/action_dispatch/structured_event_subscriber.rb +20 -0
  98. data/lib/action_dispatch/system_test_case.rb +3 -3
  99. data/lib/action_dispatch/system_testing/browser.rb +15 -22
  100. data/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb +2 -2
  101. data/lib/action_dispatch/testing/assertions/response.rb +26 -2
  102. data/lib/action_dispatch/testing/assertions/routing.rb +27 -15
  103. data/lib/action_dispatch/testing/integration.rb +18 -7
  104. data/lib/action_dispatch/testing/test_helpers/page_dump_helper.rb +1 -1
  105. data/lib/action_dispatch.rb +14 -4
  106. data/lib/action_pack/gem_version.rb +3 -3
  107. metadata +18 -48
  108. data/lib/action_dispatch/journey/parser.y +0 -50
  109. data/lib/action_dispatch/journey/parser_extras.rb +0 -33
@@ -27,7 +27,7 @@ module ActionController
27
27
  # end
28
28
  #
29
29
  # There are a few caveats with this module. You **cannot** write headers after
30
- # the response has been committed (Response#committed? will return truthy).
30
+ # the response has been committed (`Response#committed?` will return truthy).
31
31
  # Calling `write` or `close` on the response stream will cause the response
32
32
  # object to be committed. Make sure all headers are set before calling write or
33
33
  # close on your stream.
@@ -50,12 +50,55 @@ module ActionController
50
50
  #
51
51
  # def stream
52
52
  # response.headers["Content-Type"] = "text/event-stream"
53
- # response.headers["Last-Modified"] = Time.now.httpdate # Add this line if your Rack version is 2.2.x
53
+ # # Add this line if your Rack version is 2.2.x
54
+ # response.headers["Last-Modified"] = Time.now.httpdate
54
55
  # ...
55
56
  # end
57
+ #
58
+ # ## Streaming and Execution State
59
+ #
60
+ # When streaming, the action is executed in a separate thread. By default, this thread
61
+ # shares execution state from the parent thread.
62
+ #
63
+ # You can configure which execution state keys should be excluded from being shared
64
+ # using the `config.action_controller.live_streaming_excluded_keys` configuration:
65
+ #
66
+ # # config/application.rb
67
+ # config.action_controller.live_streaming_excluded_keys =
68
+ # [:active_record_connected_to_stack]
69
+ #
70
+ # This is useful when using ActionController::Live inside a `connected_to` block. For example,
71
+ # if the parent request is reading from a replica using `connected_to(role: :reading)`, you may
72
+ # want the streaming thread to use its own connection context instead of inheriting the read-only
73
+ # context:
74
+ #
75
+ # # Without configuration, streaming thread inherits read-only connection
76
+ # ActiveRecord::Base.connected_to(role: :reading) do
77
+ # @posts = Post.all
78
+ # render stream: true # Streaming thread cannot write to database
79
+ # end
80
+ #
81
+ # # With configuration, streaming thread gets fresh connection context
82
+ # # config.action_controller.live_streaming_excluded_keys = [:active_record_connected_to_stack]
83
+ # ActiveRecord::Base.connected_to(role: :reading) do
84
+ # @posts = Post.all
85
+ # render stream: true # Streaming thread can write to database if needed
86
+ # end
87
+ #
88
+ # Common keys you might want to exclude:
89
+ # - `:active_record_connected_to_stack` - Database connection routing and roles
90
+ # - `:active_record_prohibit_shard_swapping` - Shard swapping restrictions
91
+ #
92
+ # By default, no keys are excluded to maintain backward compatibility.
56
93
  module Live
57
94
  extend ActiveSupport::Concern
58
95
 
96
+ mattr_accessor :live_streaming_excluded_keys, default: []
97
+
98
+ included do
99
+ class_attribute :live_streaming_excluded_keys, instance_accessor: false, default: Live.live_streaming_excluded_keys
100
+ end
101
+
59
102
  module ClassMethods
60
103
  def make_response!(request)
61
104
  if (request.get_header("SERVER_PROTOCOL") || request.get_header("HTTP_VERSION")) == "HTTP/1.0"
@@ -133,15 +176,16 @@ module ActionController
133
176
  private
134
177
  def perform_write(json, options)
135
178
  current_options = @options.merge(options).stringify_keys
136
-
179
+ event = +""
137
180
  PERMITTED_OPTIONS.each do |option_name|
138
181
  if (option_value = current_options[option_name])
139
- @stream.write "#{option_name}: #{option_value}\n"
182
+ event << "#{option_name}: #{option_value}\n"
140
183
  end
141
184
  end
142
185
 
143
186
  message = json.gsub("\n", "\ndata: ")
144
- @stream.write "data: #{message}\n\n"
187
+ event << "data: #{message}\n\n"
188
+ @stream.write event
145
189
  end
146
190
  end
147
191
 
@@ -171,19 +215,17 @@ module ActionController
171
215
  @ignore_disconnect = false
172
216
  end
173
217
 
174
- # ActionDispatch::Response delegates #to_ary to the internal
175
- # ActionDispatch::Response::Buffer, defining #to_ary is an indicator that the
176
- # response body can be buffered and/or cached by Rack middlewares, this is not
177
- # the case for Live responses so we undefine it for this Buffer subclass.
178
- undef_method :to_ary
179
-
180
218
  def write(string)
181
219
  unless @response.committed?
182
220
  @response.headers["Cache-Control"] ||= "no-cache"
183
221
  @response.delete_header "Content-Length"
184
222
  end
185
223
 
186
- super
224
+ begin
225
+ super
226
+ rescue ClosedQueueError
227
+ raise IOError, "closed stream" if connected?
228
+ end
187
229
 
188
230
  unless connected?
189
231
  @buf.clear
@@ -194,6 +236,8 @@ module ActionController
194
236
  raise ClientDisconnected, "client disconnected"
195
237
  end
196
238
  end
239
+
240
+ string.bytesize
197
241
  end
198
242
 
199
243
  # Same as `write` but automatically include a newline at the end of the string.
@@ -201,14 +245,14 @@ module ActionController
201
245
  write string.end_with?("\n") ? string : "#{string}\n"
202
246
  end
203
247
 
204
- # Write a 'close' event to the buffer; the producer/writing thread uses this to
205
- # notify us that it's finished supplying content.
248
+ # Close the buffer; the producer/writing thread uses this to notify us that
249
+ # it's finished supplying content.
206
250
  #
207
251
  # See also #abort.
208
252
  def close
209
253
  synchronize do
210
254
  super
211
- @buf.push nil
255
+ @buf.close
212
256
  @cv.broadcast
213
257
  end
214
258
  end
@@ -220,7 +264,9 @@ module ActionController
220
264
  def abort
221
265
  synchronize do
222
266
  @aborted = true
267
+ @buf.close
223
268
  @buf.clear
269
+ @cv.broadcast
224
270
  end
225
271
  end
226
272
 
@@ -242,12 +288,7 @@ module ActionController
242
288
 
243
289
  private
244
290
  def each_chunk(&block)
245
- loop do
246
- str = nil
247
- ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
248
- str = @buf.pop
249
- end
250
- break unless str
291
+ while str = @buf.pop
251
292
  yield str
252
293
  end
253
294
  end
@@ -281,16 +322,15 @@ module ActionController
281
322
  # This processes the action in a child thread. It lets us return the response
282
323
  # code and headers back up the Rack stack, and still process the body in
283
324
  # parallel with sending data to the client.
284
- new_controller_thread {
325
+ new_controller_thread do
285
326
  ActiveSupport::Dependencies.interlock.running do
286
327
  t2 = Thread.current
287
328
 
288
329
  # Since we're processing the view in a different thread, copy the thread locals
289
330
  # from the main thread to the child thread. :'(
290
331
  locals.each { |k, v| t2[k] = v }
291
- ActiveSupport::IsolatedExecutionState.share_with(t1)
292
332
 
293
- begin
333
+ ActiveSupport::IsolatedExecutionState.share_with(t1, except: self.class.live_streaming_excluded_keys) do
294
334
  super(name)
295
335
  rescue => e
296
336
  if @_response.committed?
@@ -307,15 +347,15 @@ module ActionController
307
347
  error = e
308
348
  end
309
349
  ensure
350
+ clean_up_thread_locals(locals, t2)
351
+
310
352
  @_response.commit!
311
353
  end
312
354
  end
313
- }
314
-
315
- ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
316
- @_response.await_commit
317
355
  end
318
356
 
357
+ @_response.await_commit
358
+
319
359
  raise error if error
320
360
  end
321
361
 
@@ -328,7 +368,8 @@ module ActionController
328
368
  # or other running data where you don't want the entire file buffered in memory
329
369
  # first. Similar to send_data, but where the data is generated live.
330
370
  #
331
- # Options:
371
+ # #### Options:
372
+ #
332
373
  # * `:filename` - suggests a filename for the browser to use.
333
374
  # * `:type` - specifies an HTTP content type. You can specify either a string
334
375
  # or a symbol for a registered type with `Mime::Type.register`, for example
@@ -371,11 +412,20 @@ module ActionController
371
412
  # data from the response bodies. Nobody should call this method except in Rails
372
413
  # internals. Seriously!
373
414
  def new_controller_thread # :nodoc:
374
- Thread.new {
415
+ ActionController::Live.live_thread_pool_executor.post do
375
416
  t2 = Thread.current
376
417
  t2.abort_on_exception = true
377
418
  yield
378
- }
419
+ end
420
+ end
421
+
422
+ # Ensure we clean up any thread locals we copied so that the thread can reused.
423
+ def clean_up_thread_locals(locals, thread) # :nodoc:
424
+ locals.each { |k, _| thread[k] = nil }
425
+ end
426
+
427
+ def self.live_thread_pool_executor
428
+ @live_thread_pool_executor ||= Concurrent::CachedThreadPool.new(name: "action_controller.live")
379
429
  end
380
430
 
381
431
  def log_error(exception)
@@ -389,5 +439,7 @@ module ActionController
389
439
  "#{message}\n\n"
390
440
  end
391
441
  end
442
+
443
+ ActiveSupport.run_load_hooks(:action_controller_live, self)
392
444
  end
393
445
  end
@@ -24,8 +24,17 @@ module ActionController # :nodoc:
24
24
  # end
25
25
  # end
26
26
  #
27
+ # Requires a global policy defined in an initializer, which can be
28
+ # empty:
29
+ #
30
+ # Rails.application.config.permissions_policy do |policy|
31
+ # # policy.gyroscope :none
32
+ # end
27
33
  def permissions_policy(**options, &block)
28
34
  before_action(options) do
35
+ unless request.respond_to?(:permissions_policy)
36
+ raise "Cannot override permissions_policy if no global permissions_policy configured."
37
+ end
29
38
  if block_given?
30
39
  policy = request.permissions_policy.clone
31
40
  instance_exec(policy, &block)
@@ -18,8 +18,13 @@ module ActionController # :nodoc:
18
18
  # parameter. It's evaluated within the context of the controller processing the
19
19
  # request.
20
20
  #
21
- # Requests that exceed the rate limit are refused with a `429 Too Many Requests`
22
- # response. You can specialize this by passing a callable in the `with:`
21
+ # By default, rate limits are scoped to the controller's path. If you want to
22
+ # share rate limits across multiple controllers, you can provide your own scope,
23
+ # by passing value in the `scope:` parameter.
24
+ #
25
+ # Requests that exceed the rate limit will raise an `ActionController::TooManyRequests`
26
+ # error. By default, Action Dispatch will rescue from the error and refuse the request
27
+ # with a `429 Too Many Requests` response. You can specialize this by passing a callable in the `with:`
23
28
  # parameter. It's evaluated within the context of the controller processing the
24
29
  # request.
25
30
  #
@@ -29,6 +34,9 @@ module ActionController # :nodoc:
29
34
  # datastore as your general caches, you can pass a custom store in the `store`
30
35
  # parameter.
31
36
  #
37
+ # If you want to use multiple rate limits per controller, you need to give each of
38
+ # them an explicit name via the `name:` option.
39
+ #
32
40
  # Examples:
33
41
  #
34
42
  # class SessionsController < ApplicationController
@@ -37,24 +45,46 @@ module ActionController # :nodoc:
37
45
  #
38
46
  # class SignupsController < ApplicationController
39
47
  # rate_limit to: 1000, within: 10.seconds,
40
- # by: -> { request.domain }, with: -> { redirect_to busy_controller_url, alert: "Too many signups on domain!" }, only: :new
48
+ # by: -> { request.domain }, with: :redirect_to_busy, only: :new
49
+ #
50
+ # private
51
+ # def redirect_to_busy
52
+ # redirect_to busy_controller_url, alert: "Too many signups on domain!"
53
+ # end
41
54
  # end
42
55
  #
43
56
  # class APIController < ApplicationController
44
57
  # RATE_LIMIT_STORE = ActiveSupport::Cache::RedisCacheStore.new(url: ENV["REDIS_URL"])
45
58
  # rate_limit to: 10, within: 3.minutes, store: RATE_LIMIT_STORE
59
+ # rate_limit to: 100, within: 5.minutes, scope: :api_global
46
60
  # end
47
- def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { head :too_many_requests }, store: cache_store, **options)
48
- before_action -> { rate_limiting(to: to, within: within, by: by, with: with, store: store) }, **options
61
+ #
62
+ # class SessionsController < ApplicationController
63
+ # rate_limit to: 3, within: 2.seconds, name: "short-term"
64
+ # rate_limit to: 10, within: 5.minutes, name: "long-term"
65
+ # end
66
+ def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { raise TooManyRequests }, store: cache_store, name: nil, scope: nil, **options)
67
+ before_action -> { rate_limiting(to: to, within: within, by: by, with: with, store: store, name: name, scope: scope || controller_path) }, **options
49
68
  end
50
69
  end
51
70
 
52
71
  private
53
- def rate_limiting(to:, within:, by:, with:, store:)
54
- count = store.increment("rate-limit:#{controller_path}:#{instance_exec(&by)}", 1, expires_in: within)
72
+ def rate_limiting(to:, within:, by:, with:, store:, name:, scope:)
73
+ by = by.is_a?(Symbol) ? send(by) : instance_exec(&by)
74
+
75
+ cache_key = ["rate-limit", scope, name, by].compact.join(":")
76
+ count = store.increment(cache_key, 1, expires_in: within)
55
77
  if count && count > to
56
- ActiveSupport::Notifications.instrument("rate_limit.action_controller", request: request) do
57
- instance_exec(&with)
78
+ ActiveSupport::Notifications.instrument("rate_limit.action_controller",
79
+ request: request,
80
+ count: count,
81
+ to: to,
82
+ within: within,
83
+ by: by,
84
+ name: name,
85
+ scope: scope,
86
+ cache_key: cache_key) do
87
+ with.is_a?(Symbol) ? send(with) : instance_exec(&with)
58
88
  end
59
89
  end
60
90
  end
@@ -11,10 +11,36 @@ module ActionController
11
11
 
12
12
  class UnsafeRedirectError < StandardError; end
13
13
 
14
+ class OpenRedirectError < UnsafeRedirectError
15
+ def initialize(location)
16
+ super("Unsafe redirect to #{location.to_s.truncate(100).inspect}, pass allow_other_host: true to redirect anyway.")
17
+ end
18
+ end
19
+
20
+ class PathRelativeRedirectError < UnsafeRedirectError
21
+ def initialize(url)
22
+ super("Path relative URL redirect detected: #{url.inspect}")
23
+ end
24
+ end
25
+
14
26
  ILLEGAL_HEADER_VALUE_REGEX = /[\x00-\x08\x0A-\x1F]/
15
27
 
16
28
  included do
17
29
  mattr_accessor :raise_on_open_redirects, default: false
30
+ mattr_accessor :action_on_open_redirect, default: :log
31
+ mattr_accessor :action_on_path_relative_redirect, default: :log
32
+ class_attribute :_allowed_redirect_hosts, :allowed_redirect_hosts_permissions, instance_accessor: false, instance_predicate: false
33
+ singleton_class.alias_method :allowed_redirect_hosts, :_allowed_redirect_hosts
34
+ end
35
+
36
+ module ClassMethods # :nodoc:
37
+ def allowed_redirect_hosts=(hosts)
38
+ hosts = hosts.dup.freeze
39
+ self._allowed_redirect_hosts = hosts
40
+ self.allowed_redirect_hosts_permissions = if hosts.present?
41
+ ActionDispatch::HostAuthorization::Permissions.new(hosts)
42
+ end
43
+ end
18
44
  end
19
45
 
20
46
  # Redirects the browser to the target specified in `options`. This parameter can
@@ -82,16 +108,17 @@ module ActionController
82
108
  # ### Open Redirect protection
83
109
  #
84
110
  # By default, Rails protects against redirecting to external hosts for your
85
- # app's safety, so called open redirects. Note: this was a new default in Rails
86
- # 7.0, after upgrading opt-in by uncommenting the line with
87
- # `raise_on_open_redirects` in
88
- # `config/initializers/new_framework_defaults_7_0.rb`
111
+ # app's safety, so called open redirects.
89
112
  #
90
113
  # Here #redirect_to automatically validates the potentially-unsafe URL:
91
114
  #
92
115
  # redirect_to params[:redirect_url]
93
116
  #
94
- # Raises UnsafeRedirectError in the case of an unsafe redirect.
117
+ # The `action_on_open_redirect` configuration option controls the behavior when an unsafe
118
+ # redirect is detected:
119
+ # * `:log` - Logs a warning but allows the redirect
120
+ # * `:notify` - Sends an Active Support notification for monitoring
121
+ # * `:raise` - Raises an UnsafeRedirectError
95
122
  #
96
123
  # To allow any external redirects pass `allow_other_host: true`, though using a
97
124
  # user-provided param in that case is unsafe.
@@ -100,11 +127,31 @@ module ActionController
100
127
  #
101
128
  # See #url_from for more information on what an internal and safe URL is, or how
102
129
  # to fall back to an alternate redirect URL in the unsafe case.
130
+ #
131
+ # ### Path Relative URL Redirect Protection
132
+ #
133
+ # Rails also protects against potentially unsafe path relative URL redirects that don't
134
+ # start with a leading slash. These can create security vulnerabilities:
135
+ #
136
+ # redirect_to "example.com" # Creates http://yourdomain.comexample.com
137
+ # redirect_to "@attacker.com" # Creates http://yourdomain.com@attacker.com
138
+ # # which browsers interpret as user@host
139
+ #
140
+ # You can configure how Rails handles these cases using:
141
+ #
142
+ # config.action_controller.action_on_path_relative_redirect = :log # default
143
+ # config.action_controller.action_on_path_relative_redirect = :notify
144
+ # config.action_controller.action_on_path_relative_redirect = :raise
145
+ #
146
+ # * `:log` - Logs a warning but allows the redirect
147
+ # * `:notify` - Sends an Active Support notification but allows the redirect
148
+ # (includes stack trace to help identify the source)
149
+ # * `:raise` - Raises an UnsafeRedirectError
103
150
  def redirect_to(options = {}, response_options = {})
104
151
  raise ActionControllerError.new("Cannot redirect to nil!") unless options
105
152
  raise AbstractController::DoubleRenderError if response_body
106
153
 
107
- allow_other_host = response_options.delete(:allow_other_host) { _allow_other_host }
154
+ allow_other_host = response_options.delete(:allow_other_host)
108
155
 
109
156
  proposed_status = _extract_redirect_to_status(options, response_options)
110
157
 
@@ -166,6 +213,10 @@ module ActionController
166
213
  when /\A([a-z][a-z\d\-+.]*:|\/\/).*/i
167
214
  options.to_str
168
215
  when String
216
+ if !options.start_with?("/", "?") && !options.empty?
217
+ _handle_path_relative_redirect(options)
218
+ end
219
+
169
220
  request.protocol + request.host_with_port + options
170
221
  when Proc
171
222
  _compute_redirect_to_location request, instance_eval(&options)
@@ -190,7 +241,8 @@ module ActionController
190
241
  # url_from("http://example.com/profile") # => "http://example.com/profile"
191
242
  # url_from("http://evil.com/profile") # => nil
192
243
  #
193
- # Subdomains are considered part of the host:
244
+ # Subdomains are included when comparing hosts. The hostname must match exactly
245
+ # for a redirect to be considered internal.
194
246
  #
195
247
  # # If request.host is on https://example.com or https://app.example.com, you'd get:
196
248
  # url_from("https://dev.example.com/profile") # => nil
@@ -207,7 +259,9 @@ module ActionController
207
259
 
208
260
  private
209
261
  def _allow_other_host
210
- !raise_on_open_redirects
262
+ return false if raise_on_open_redirects
263
+
264
+ action_on_open_redirect != :raise
211
265
  end
212
266
 
213
267
  def _extract_redirect_to_status(options, response_options)
@@ -221,20 +275,42 @@ module ActionController
221
275
  end
222
276
 
223
277
  def _enforce_open_redirect_protection(location, allow_other_host:)
278
+ # Explictly allowed other host or host is in allow list allow redirect
224
279
  if allow_other_host || _url_host_allowed?(location)
225
280
  location
281
+ # Explicitly disallowed other host
282
+ elsif allow_other_host == false
283
+ raise OpenRedirectError.new(location)
284
+ # Configuration disallows other hosts
285
+ elsif !_allow_other_host
286
+ raise OpenRedirectError.new(location)
287
+ # Log but allow redirect
288
+ elsif action_on_open_redirect == :log
289
+ logger.warn "Open redirect to #{location.inspect} detected" if logger
290
+ location
291
+ # Notify but allow redirect
292
+ elsif action_on_open_redirect == :notify
293
+ ActiveSupport::Notifications.instrument("open_redirect.action_controller",
294
+ location: location,
295
+ request: request,
296
+ stack_trace: caller,
297
+ )
298
+ location
299
+ # Fall through, should not happen but raise for safety
226
300
  else
227
- raise UnsafeRedirectError, "Unsafe redirect to #{location.truncate(100).inspect}, pass allow_other_host: true to redirect anyway."
301
+ raise OpenRedirectError.new(location)
228
302
  end
229
303
  end
230
304
 
231
305
  def _url_host_allowed?(url)
232
- host = URI(url.to_s).host
306
+ url_to_s = url.to_s
307
+ host = URI(url_to_s).host
233
308
 
234
- return true if host == request.host
235
- return false unless host.nil?
236
- return false unless url.to_s.start_with?("/")
237
- !url.to_s.start_with?("//")
309
+ if host.nil?
310
+ url_to_s.start_with?("/") && !url_to_s.start_with?("//")
311
+ else
312
+ host == request.host || self.class.allowed_redirect_hosts_permissions&.allows?(host)
313
+ end
238
314
  rescue ArgumentError, URI::Error
239
315
  false
240
316
  end
@@ -248,5 +324,22 @@ module ActionController
248
324
  raise UnsafeRedirectError, msg
249
325
  end
250
326
  end
327
+
328
+ def _handle_path_relative_redirect(url)
329
+ message = "Path relative URL redirect detected: #{url.inspect}"
330
+
331
+ case action_on_path_relative_redirect
332
+ when :log
333
+ logger&.warn message
334
+ when :notify
335
+ ActiveSupport::Notifications.instrument("unsafe_redirect.action_controller",
336
+ url: url,
337
+ message: message,
338
+ stack_trace: caller
339
+ )
340
+ when :raise
341
+ raise PathRelativeRedirectError.new(url)
342
+ end
343
+ end
251
344
  end
252
345
  end
@@ -2,8 +2,6 @@
2
2
 
3
3
  # :markup: markdown
4
4
 
5
- require "set"
6
-
7
5
  module ActionController
8
6
  # See Renderers.add
9
7
  def self.add_renderer(key, &block)
@@ -29,8 +27,23 @@ module ActionController
29
27
  # Default values are `:json`, `:js`, `:xml`.
30
28
  RENDERERS = Set.new
31
29
 
30
+ module DeprecatedEscapeJsonResponses # :nodoc:
31
+ def escape_json_responses=(value)
32
+ if value
33
+ ActionController.deprecator.warn(<<~MSG.squish)
34
+ Setting action_controller.escape_json_responses = true is deprecated and will have no effect in Rails 8.2.
35
+ Set it to `false`, or remove the config.
36
+ MSG
37
+ end
38
+ super
39
+ end
40
+ end
41
+
32
42
  included do
33
43
  class_attribute :_renderers, default: Set.new.freeze
44
+ class_attribute :escape_json_responses, instance_writer: false, instance_accessor: false, default: true
45
+
46
+ singleton_class.prepend DeprecatedEscapeJsonResponses
34
47
  end
35
48
 
36
49
  # Used in ActionController::Base and ActionController::API to include all
@@ -88,7 +101,7 @@ module ActionController
88
101
  remove_possible_method(method_name)
89
102
  end
90
103
 
91
- def self._render_with_renderer_method_name(key)
104
+ def self._render_with_renderer_method_name(key) # :nodoc:
92
105
  "_render_with_renderer_#{key}"
93
106
  end
94
107
 
@@ -142,7 +155,7 @@ module ActionController
142
155
  _render_to_body_with_renderer(options) || super
143
156
  end
144
157
 
145
- def _render_to_body_with_renderer(options)
158
+ def _render_to_body_with_renderer(options) # :nodoc:
146
159
  _renderers.each do |name|
147
160
  if options.key?(name)
148
161
  _process_options(options)
@@ -154,28 +167,35 @@ module ActionController
154
167
  end
155
168
 
156
169
  add :json do |json, options|
157
- json = json.to_json(options) unless json.kind_of?(String)
170
+ json_options = options.except(:callback, :content_type, :status)
171
+ json_options[:escape] ||= false if !self.class.escape_json_responses? && options[:callback].blank?
172
+ json = json.to_json(json_options) unless json.kind_of?(String)
158
173
 
159
174
  if options[:callback].present?
160
175
  if media_type.nil? || media_type == Mime[:json]
161
- self.content_type = Mime[:js]
176
+ self.content_type = :js
162
177
  end
163
178
 
164
179
  "/**/#{options[:callback]}(#{json})"
165
180
  else
166
- self.content_type = Mime[:json] if media_type.nil?
181
+ self.content_type = :json if media_type.nil?
167
182
  json
168
183
  end
169
184
  end
170
185
 
171
186
  add :js do |js, options|
172
- self.content_type = Mime[:js] if media_type.nil?
187
+ self.content_type = :js if media_type.nil?
173
188
  js.respond_to?(:to_js) ? js.to_js(options) : js
174
189
  end
175
190
 
176
191
  add :xml do |xml, options|
177
- self.content_type = Mime[:xml] if media_type.nil?
192
+ self.content_type = :xml if media_type.nil?
178
193
  xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml
179
194
  end
195
+
196
+ add :markdown do |md, options|
197
+ self.content_type = :md if media_type.nil?
198
+ md.respond_to?(:to_markdown) ? md.to_markdown : md
199
+ end
180
200
  end
181
201
  end
@@ -160,6 +160,12 @@ module ActionController
160
160
  # render "posts/new", status: :unprocessable_entity
161
161
  # # => renders app/views/posts/new.html.erb with HTTP status code 422
162
162
  #
163
+ # `:variants`
164
+ # : This tells Rails to look for the first template matching any of the variations.
165
+ #
166
+ # render "posts/index", variants: [:mobile]
167
+ # # => renders app/views/posts/index.html+mobile.erb
168
+ #
163
169
  #--
164
170
  # Check for double render errors and set the content_type after rendering.
165
171
  def render(*args)
@@ -208,7 +214,7 @@ module ActionController
208
214
  end
209
215
 
210
216
  def _set_html_content_type
211
- self.content_type = Mime[:html].to_s
217
+ self.content_type = :html
212
218
  end
213
219
 
214
220
  def _set_rendered_content_type(format)
@@ -218,8 +224,15 @@ module ActionController
218
224
  end
219
225
 
220
226
  def _set_vary_header
221
- if response.headers["Vary"].blank? && request.should_apply_vary_header?
222
- response.headers["Vary"] = "Accept"
227
+ if request.should_apply_vary_header?
228
+ vary_headers = response.headers["Vary"].to_s.split(",").map(&:strip).reject(&:blank?)
229
+
230
+ unless vary_headers.include?("*")
231
+ request.vary_headers.each do |header|
232
+ vary_headers << header unless vary_headers.any? { |existing| existing.casecmp?(header) }
233
+ end
234
+ response.headers["Vary"] = vary_headers.join(", ")
235
+ end
223
236
  end
224
237
  end
225
238