actionpack 8.0.5.2 → 8.1.0.beta1

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 (80) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +231 -277
  3. data/lib/abstract_controller/asset_paths.rb +4 -2
  4. data/lib/abstract_controller/base.rb +10 -2
  5. data/lib/abstract_controller/caching.rb +6 -3
  6. data/lib/abstract_controller/helpers.rb +1 -1
  7. data/lib/abstract_controller/logger.rb +2 -1
  8. data/lib/action_controller/base.rb +1 -1
  9. data/lib/action_controller/caching.rb +1 -2
  10. data/lib/action_controller/form_builder.rb +1 -1
  11. data/lib/action_controller/log_subscriber.rb +7 -0
  12. data/lib/action_controller/metal/allow_browser.rb +1 -1
  13. data/lib/action_controller/metal/conditional_get.rb +25 -0
  14. data/lib/action_controller/metal/data_streaming.rb +1 -3
  15. data/lib/action_controller/metal/exceptions.rb +5 -0
  16. data/lib/action_controller/metal/flash.rb +1 -4
  17. data/lib/action_controller/metal/head.rb +3 -1
  18. data/lib/action_controller/metal/live.rb +5 -52
  19. data/lib/action_controller/metal/permissions_policy.rb +9 -0
  20. data/lib/action_controller/metal/rate_limiting.rb +22 -7
  21. data/lib/action_controller/metal/redirecting.rb +61 -5
  22. data/lib/action_controller/metal/renderers.rb +27 -6
  23. data/lib/action_controller/metal/rendering.rb +9 -10
  24. data/lib/action_controller/metal/request_forgery_protection.rb +18 -10
  25. data/lib/action_controller/metal/rescue.rb +9 -0
  26. data/lib/action_controller/metal/strong_parameters.rb +8 -16
  27. data/lib/action_controller/railtie.rb +2 -11
  28. data/lib/action_dispatch/http/cache.rb +111 -1
  29. data/lib/action_dispatch/http/filter_parameters.rb +5 -3
  30. data/lib/action_dispatch/http/mime_negotiation.rb +1 -11
  31. data/lib/action_dispatch/http/mime_types.rb +1 -0
  32. data/lib/action_dispatch/http/param_builder.rb +28 -27
  33. data/lib/action_dispatch/http/parameters.rb +3 -3
  34. data/lib/action_dispatch/http/permissions_policy.rb +4 -0
  35. data/lib/action_dispatch/http/query_parser.rb +12 -10
  36. data/lib/action_dispatch/http/request.rb +10 -5
  37. data/lib/action_dispatch/http/response.rb +16 -3
  38. data/lib/action_dispatch/http/url.rb +99 -3
  39. data/lib/action_dispatch/journey/gtg/simulator.rb +33 -12
  40. data/lib/action_dispatch/journey/gtg/transition_table.rb +33 -43
  41. data/lib/action_dispatch/journey/nodes/node.rb +2 -1
  42. data/lib/action_dispatch/journey/route.rb +45 -31
  43. data/lib/action_dispatch/journey/router/utils.rb +8 -14
  44. data/lib/action_dispatch/journey/router.rb +59 -81
  45. data/lib/action_dispatch/journey/routes.rb +7 -0
  46. data/lib/action_dispatch/journey/visitors.rb +55 -23
  47. data/lib/action_dispatch/journey/visualizer/fsm.js +4 -6
  48. data/lib/action_dispatch/middleware/cookies.rb +5 -18
  49. data/lib/action_dispatch/middleware/debug_exceptions.rb +8 -2
  50. data/lib/action_dispatch/middleware/debug_view.rb +11 -0
  51. data/lib/action_dispatch/middleware/exception_wrapper.rb +11 -5
  52. data/lib/action_dispatch/middleware/executor.rb +12 -2
  53. data/lib/action_dispatch/middleware/public_exceptions.rb +1 -5
  54. data/lib/action_dispatch/middleware/session/abstract_store.rb +0 -5
  55. data/lib/action_dispatch/middleware/session/cache_store.rb +16 -22
  56. data/lib/action_dispatch/middleware/session/cookie_store.rb +3 -0
  57. data/lib/action_dispatch/middleware/templates/rescues/_copy_button.html.erb +1 -0
  58. data/lib/action_dispatch/middleware/templates/rescues/_source.html.erb +3 -2
  59. data/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb +9 -5
  60. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.html.erb +1 -0
  61. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb +1 -0
  62. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.html.erb +1 -0
  63. data/lib/action_dispatch/middleware/templates/rescues/layout.erb +50 -0
  64. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.html.erb +1 -0
  65. data/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb +1 -0
  66. data/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb +1 -0
  67. data/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb +1 -0
  68. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb +1 -0
  69. data/lib/action_dispatch/railtie.rb +10 -2
  70. data/lib/action_dispatch/routing/inspector.rb +4 -1
  71. data/lib/action_dispatch/routing/mapper.rb +323 -173
  72. data/lib/action_dispatch/routing/route_set.rb +2 -4
  73. data/lib/action_dispatch/routing/routes_proxy.rb +0 -1
  74. data/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb +2 -2
  75. data/lib/action_dispatch/testing/assertions/response.rb +14 -0
  76. data/lib/action_dispatch/testing/assertions/routing.rb +11 -3
  77. data/lib/action_dispatch/testing/integration.rb +7 -7
  78. data/lib/action_dispatch/testing/request_encoder.rb +9 -9
  79. data/lib/action_pack/gem_version.rb +3 -3
  80. metadata +12 -11
@@ -7,8 +7,10 @@ module AbstractController
7
7
  extend ActiveSupport::Concern
8
8
 
9
9
  included do
10
- config_accessor :asset_host, :assets_dir, :javascripts_dir,
11
- :stylesheets_dir, :default_asset_host_protocol, :relative_url_root
10
+ singleton_class.delegate :asset_host, :asset_host=, :assets_dir, :assets_dir=, :javascripts_dir, :javascripts_dir=,
11
+ :stylesheets_dir, :stylesheets_dir=, :default_asset_host_protocol, :default_asset_host_protocol=, :relative_url_root, :relative_url_root=, to: :config
12
+ delegate :asset_host, :asset_host=, :assets_dir, :assets_dir=, :javascripts_dir, :javascripts_dir=,
13
+ :stylesheets_dir, :stylesheets_dir=, :default_asset_host_protocol, :default_asset_host_protocol=, :relative_url_root, :relative_url_root=, to: :config
12
14
  end
13
15
  end
14
16
  end
@@ -3,7 +3,6 @@
3
3
  # :markup: markdown
4
4
 
5
5
  require "abstract_controller/error"
6
- require "active_support/configurable"
7
6
  require "active_support/descendants_tracker"
8
7
  require "active_support/core_ext/module/anonymous"
9
8
  require "active_support/core_ext/module/attr_internal"
@@ -47,7 +46,7 @@ module AbstractController
47
46
  # Returns the formats that can be processed by the controller.
48
47
  attr_internal :formats
49
48
 
50
- include ActiveSupport::Configurable
49
+ class_attribute :config, instance_predicate: false, default: ActiveSupport::OrderedOptions.new
51
50
  extend ActiveSupport::DescendantsTracker
52
51
 
53
52
  class << self
@@ -65,6 +64,7 @@ module AbstractController
65
64
  unless klass.instance_variable_defined?(:@abstract)
66
65
  klass.instance_variable_set(:@abstract, false)
67
66
  end
67
+ klass.config = ActiveSupport::InheritableOptions.new(config)
68
68
  super
69
69
  end
70
70
 
@@ -121,6 +121,10 @@ module AbstractController
121
121
  @controller_path ||= name.delete_suffix("Controller").underscore unless anonymous?
122
122
  end
123
123
 
124
+ def configure # :nodoc:
125
+ yield config
126
+ end
127
+
124
128
  # Refresh the cached action_methods when a new action_method is added.
125
129
  def method_added(name)
126
130
  super
@@ -190,6 +194,10 @@ module AbstractController
190
194
  true
191
195
  end
192
196
 
197
+ def config # :nodoc:
198
+ @_config ||= self.class.config.inheritable_copy
199
+ end
200
+
193
201
  def inspect # :nodoc:
194
202
  "#<#{self.class.name}:#{'%#016x' % (object_id << 1)}>"
195
203
  end
@@ -32,13 +32,16 @@ module AbstractController
32
32
  included do
33
33
  extend ConfigMethods
34
34
 
35
- config_accessor :default_static_extension
35
+ singleton_class.delegate :default_static_extension, :default_static_extension=, to: :config
36
+ delegate :default_static_extension, :default_static_extension=, to: :config
36
37
  self.default_static_extension ||= ".html"
37
38
 
38
- config_accessor :perform_caching
39
+ singleton_class.delegate :perform_caching, :perform_caching=, to: :config
40
+ delegate :perform_caching, :perform_caching=, to: :config
39
41
  self.perform_caching = true if perform_caching.nil?
40
42
 
41
- config_accessor :enable_fragment_cache_logging
43
+ singleton_class.delegate :enable_fragment_cache_logging, :enable_fragment_cache_logging=, to: :config
44
+ delegate :enable_fragment_cache_logging, :enable_fragment_cache_logging=, to: :config
42
45
  self.enable_fragment_cache_logging = false
43
46
 
44
47
  class_attribute :_view_cache_dependencies, default: []
@@ -90,7 +90,7 @@ module AbstractController
90
90
  #--
91
91
  # Implemented by Resolution#modules_for_helpers.
92
92
 
93
- # :method: all_helpers_from_path
93
+ # :method: # all_helpers_from_path
94
94
  # :call-seq: all_helpers_from_path(path)
95
95
  #
96
96
  # Returns a list of helper names in a given path.
@@ -9,7 +9,8 @@ module AbstractController
9
9
  extend ActiveSupport::Concern
10
10
 
11
11
  included do
12
- config_accessor :logger
12
+ singleton_class.delegate :logger, :logger=, to: :config
13
+ delegate :logger, :logger=, to: :config
13
14
  include ActiveSupport::Benchmarkable
14
15
  end
15
16
  end
@@ -128,7 +128,7 @@ module ActionController
128
128
  #
129
129
  # Action Controller sends content to the user by using one of five rendering
130
130
  # methods. The most versatile and common is the rendering of a template.
131
- # Included in the Action Pack is the Action View, which enables rendering of ERB
131
+ # Also included with \Rails is Action View, which enables rendering of ERB
132
132
  # templates. It's automatically configured. The controller passes objects to the
133
133
  # view by assigning instance variables:
134
134
  #
@@ -9,9 +9,8 @@ module ActionController
9
9
  # of calculations, renderings, and database calls around for subsequent
10
10
  # requests.
11
11
  #
12
- # You can read more about each approach by clicking the modules below.
13
- #
14
12
  # Note: To turn off all caching provided by Action Controller, set
13
+ #
15
14
  # config.action_controller.perform_caching = false
16
15
  #
17
16
  # ## Caching stores
@@ -40,7 +40,7 @@ module ActionController
40
40
  # rendered by this controller and its subclasses.
41
41
  #
42
42
  # #### Parameters
43
- # * `builder` - Default form builder, an instance of
43
+ # * `builder` - Default form builder. Accepts a subclass of
44
44
  # ActionView::Helpers::FormBuilder
45
45
  def default_form_builder(builder)
46
46
  self._default_form_builder = builder
@@ -49,6 +49,13 @@ module ActionController
49
49
  end
50
50
  subscribe_log_level :halted_callback, :info
51
51
 
52
+ # Manually subscribed below
53
+ def rescue_from_callback(event)
54
+ exception = event.payload[:exception]
55
+ info { "rescue_from handled #{exception.class} (#{exception.message}) - #{exception.backtrace.first.delete_prefix("#{Rails.root}/")}" }
56
+ end
57
+ subscribe_log_level :rescue_from_callback, :info
58
+
52
59
  def send_file(event)
53
60
  info { "Sent file #{event.payload[:path]} (#{event.duration.round(1)}ms)" }
54
61
  end
@@ -14,7 +14,7 @@ module ActionController # :nodoc:
14
14
  # aren't reporting a user-agent header, will be allowed access.
15
15
  #
16
16
  # A browser that's blocked will by default be served the file in
17
- # public/406-unsupported-browser.html with a HTTP status code of "406 Not
17
+ # public/406-unsupported-browser.html with an HTTP status code of "406 Not
18
18
  # Acceptable".
19
19
  #
20
20
  # In addition to specifically named browser versions, you can also pass
@@ -332,6 +332,31 @@ module ActionController
332
332
  response.cache_control.replace(no_store: true)
333
333
  end
334
334
 
335
+ # Adds the `must-understand` directive to the `Cache-Control` header, which indicates
336
+ # that a cache MUST understand the semantics of the response status code that has been
337
+ # received, or discard the response.
338
+ #
339
+ # This is particularly useful when returning responses with new or uncommon
340
+ # status codes that might not be properly interpreted by older caches.
341
+ #
342
+ # #### Example
343
+ #
344
+ # def show
345
+ # @article = Article.find(params[:id])
346
+ #
347
+ # if @article.early_access?
348
+ # must_understand
349
+ # render status: 203 # Non-Authoritative Information
350
+ # else
351
+ # fresh_when @article
352
+ # end
353
+ # end
354
+ #
355
+ def must_understand
356
+ response.cache_control[:must_understand] = true
357
+ response.cache_control[:no_store] = true
358
+ end
359
+
335
360
  private
336
361
  def combine_etags(validator, options)
337
362
  [validator, *etaggers.map { |etagger| instance_exec(options, &etagger) }].compact
@@ -134,9 +134,7 @@ module ActionController # :nodoc:
134
134
  raise ArgumentError, ":type option required" if content_type.nil?
135
135
 
136
136
  if content_type.is_a?(Symbol)
137
- extension = Mime[content_type]
138
- raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension
139
- self.content_type = extension
137
+ self.content_type = content_type
140
138
  else
141
139
  if !type_provided && options[:filename]
142
140
  # If type wasn't provided, try guessing from file extension.
@@ -103,4 +103,9 @@ module ActionController
103
103
  super(message)
104
104
  end
105
105
  end
106
+
107
+ # Raised when a Rate Limit is exceeded by too many requests within a period of
108
+ # time.
109
+ class TooManyRequests < ActionControllerError
110
+ end
106
111
  end
@@ -38,15 +38,12 @@ module ActionController # :nodoc:
38
38
  define_method(type) do
39
39
  request.flash[type]
40
40
  end
41
+ private type
41
42
  helper_method(type) if respond_to?(:helper_method)
42
43
 
43
44
  self._flash_types += [type]
44
45
  end
45
46
  end
46
-
47
- def action_methods # :nodoc:
48
- @action_methods ||= super - _flash_types.map(&:to_s).to_set
49
- end
50
47
  end
51
48
 
52
49
  private
@@ -25,6 +25,8 @@ module ActionController
25
25
  raise ArgumentError, "#{status.inspect} is not a valid value for `status`."
26
26
  end
27
27
 
28
+ raise ::AbstractController::DoubleRenderError if response_body
29
+
28
30
  status ||= :ok
29
31
 
30
32
  if options
@@ -41,7 +43,7 @@ module ActionController
41
43
 
42
44
  if include_content?(response_code)
43
45
  unless self.media_type
44
- self.content_type = content_type || ((f = formats) && Mime[f.first]) || Mime[:html]
46
+ self.content_type = content_type || ((f = formats) && Mime[f.first]) || :html
45
47
  end
46
48
 
47
49
  response.charset = false
@@ -53,50 +53,9 @@ module ActionController
53
53
  # response.headers["Last-Modified"] = Time.now.httpdate # Add this line if your Rack version is 2.2.x
54
54
  # ...
55
55
  # end
56
- #
57
- # ## Streaming and Execution State
58
- #
59
- # When streaming, the action is executed in a separate thread. By default, this thread
60
- # shares execution state from the parent thread.
61
- #
62
- # You can configure which execution state keys should be excluded from being shared
63
- # using the `config.action_controller.live_streaming_excluded_keys` configuration:
64
- #
65
- # # config/application.rb
66
- # config.action_controller.live_streaming_excluded_keys = [:active_record_connected_to_stack]
67
- #
68
- # This is useful when using ActionController::Live inside a `connected_to` block. For example,
69
- # if the parent request is reading from a replica using `connected_to(role: :reading)`, you may
70
- # want the streaming thread to use its own connection context instead of inheriting the read-only
71
- # context:
72
- #
73
- # # Without configuration, streaming thread inherits read-only connection
74
- # ActiveRecord::Base.connected_to(role: :reading) do
75
- # @posts = Post.all
76
- # render stream: true # Streaming thread cannot write to database
77
- # end
78
- #
79
- # # With configuration, streaming thread gets fresh connection context
80
- # # config.action_controller.live_streaming_excluded_keys = [:active_record_connected_to_stack]
81
- # ActiveRecord::Base.connected_to(role: :reading) do
82
- # @posts = Post.all
83
- # render stream: true # Streaming thread can write to database if needed
84
- # end
85
- #
86
- # Common keys you might want to exclude:
87
- # - `:active_record_connected_to_stack` - Database connection routing and roles
88
- # - `:active_record_prohibit_shard_swapping` - Shard swapping restrictions
89
- #
90
- # By default, no keys are excluded to maintain backward compatibility.
91
56
  module Live
92
57
  extend ActiveSupport::Concern
93
58
 
94
- mattr_accessor :live_streaming_excluded_keys, default: []
95
-
96
- included do
97
- class_attribute :live_streaming_excluded_keys, instance_accessor: false, default: Live.live_streaming_excluded_keys
98
- end
99
-
100
59
  module ClassMethods
101
60
  def make_response!(request)
102
61
  if (request.get_header("SERVER_PROTOCOL") || request.get_header("HTTP_VERSION")) == "HTTP/1.0"
@@ -218,11 +177,7 @@ module ActionController
218
177
  @response.delete_header "Content-Length"
219
178
  end
220
179
 
221
- begin
222
- super
223
- rescue ClosedQueueError
224
- raise IOError, "closed stream" if connected?
225
- end
180
+ super
226
181
 
227
182
  unless connected?
228
183
  @buf.clear
@@ -240,14 +195,14 @@ module ActionController
240
195
  write string.end_with?("\n") ? string : "#{string}\n"
241
196
  end
242
197
 
243
- # Close the buffer; the producer/writing thread uses this to notify us that
244
- # it's finished supplying content.
198
+ # Write a 'close' event to the buffer; the producer/writing thread uses this to
199
+ # notify us that it's finished supplying content.
245
200
  #
246
201
  # See also #abort.
247
202
  def close
248
203
  synchronize do
249
204
  super
250
- @buf.close
205
+ @buf.push nil
251
206
  @cv.broadcast
252
207
  end
253
208
  end
@@ -259,9 +214,7 @@ module ActionController
259
214
  def abort
260
215
  synchronize do
261
216
  @aborted = true
262
- @buf.close
263
217
  @buf.clear
264
- @cv.broadcast
265
218
  end
266
219
  end
267
220
 
@@ -329,7 +282,7 @@ module ActionController
329
282
  # Since we're processing the view in a different thread, copy the thread locals
330
283
  # from the main thread to the child thread. :'(
331
284
  locals.each { |k, v| t2[k] = v }
332
- ActiveSupport::IsolatedExecutionState.share_with(t1, except: self.class.live_streaming_excluded_keys)
285
+ ActiveSupport::IsolatedExecutionState.share_with(t1)
333
286
 
334
287
  begin
335
288
  super(name)
@@ -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
  #
@@ -46,23 +51,33 @@ module ActionController # :nodoc:
46
51
  # class APIController < ApplicationController
47
52
  # RATE_LIMIT_STORE = ActiveSupport::Cache::RedisCacheStore.new(url: ENV["REDIS_URL"])
48
53
  # rate_limit to: 10, within: 3.minutes, store: RATE_LIMIT_STORE
54
+ # rate_limit to: 100, within: 5.minutes, scope: :api_global
49
55
  # end
50
56
  #
51
57
  # class SessionsController < ApplicationController
52
58
  # rate_limit to: 3, within: 2.seconds, name: "short-term"
53
59
  # rate_limit to: 10, within: 5.minutes, name: "long-term"
54
60
  # end
55
- def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { head :too_many_requests }, store: cache_store, name: nil, **options)
56
- before_action -> { rate_limiting(to: to, within: within, by: by, with: with, store: store, name: name) }, **options
61
+ def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { raise TooManyRequests }, store: cache_store, name: nil, scope: nil, **options)
62
+ before_action -> { rate_limiting(to: to, within: within, by: by, with: with, store: store, name: name, scope: scope || controller_path) }, **options
57
63
  end
58
64
  end
59
65
 
60
66
  private
61
- def rate_limiting(to:, within:, by:, with:, store:, name:)
62
- cache_key = ["rate-limit", controller_path, name, instance_exec(&by)].compact.join(":")
67
+ def rate_limiting(to:, within:, by:, with:, store:, name:, scope:)
68
+ by = instance_exec(&by)
69
+ cache_key = ["rate-limit", scope, name, by].compact.join(":")
63
70
  count = store.increment(cache_key, 1, expires_in: within)
64
71
  if count && count > to
65
- ActiveSupport::Notifications.instrument("rate_limit.action_controller", request: request) do
72
+ ActiveSupport::Notifications.instrument("rate_limit.action_controller",
73
+ request: request,
74
+ count: count,
75
+ to: to,
76
+ within: within,
77
+ by: by,
78
+ name: name,
79
+ scope: scope,
80
+ cache_key: cache_key) do
66
81
  instance_exec(&with)
67
82
  end
68
83
  end
@@ -15,6 +15,19 @@ module ActionController
15
15
 
16
16
  included do
17
17
  mattr_accessor :raise_on_open_redirects, default: false
18
+ mattr_accessor :action_on_path_relative_redirect, default: :log
19
+ class_attribute :_allowed_redirect_hosts, :allowed_redirect_hosts_permissions, instance_accessor: false, instance_predicate: false
20
+ singleton_class.alias_method :allowed_redirect_hosts, :_allowed_redirect_hosts
21
+ end
22
+
23
+ module ClassMethods # :nodoc:
24
+ def allowed_redirect_hosts=(hosts)
25
+ hosts = hosts.dup.freeze
26
+ self._allowed_redirect_hosts = hosts
27
+ self.allowed_redirect_hosts_permissions = if hosts.present?
28
+ ActionDispatch::HostAuthorization::Permissions.new(hosts)
29
+ end
30
+ end
18
31
  end
19
32
 
20
33
  # Redirects the browser to the target specified in `options`. This parameter can
@@ -100,6 +113,26 @@ module ActionController
100
113
  #
101
114
  # See #url_from for more information on what an internal and safe URL is, or how
102
115
  # to fall back to an alternate redirect URL in the unsafe case.
116
+ #
117
+ # ### Path Relative URL Redirect Protection
118
+ #
119
+ # Rails also protects against potentially unsafe path relative URL redirects that don't
120
+ # start with a leading slash. These can create security vulnerabilities:
121
+ #
122
+ # redirect_to "example.com" # Creates http://yourdomain.comexample.com
123
+ # redirect_to "@attacker.com" # Creates http://yourdomain.com@attacker.com
124
+ # # which browsers interpret as user@host
125
+ #
126
+ # You can configure how Rails handles these cases using:
127
+ #
128
+ # config.action_controller.action_on_path_relative_redirect = :log # default
129
+ # config.action_controller.action_on_path_relative_redirect = :notify
130
+ # config.action_controller.action_on_path_relative_redirect = :raise
131
+ #
132
+ # * `:log` - Logs a warning but allows the redirect
133
+ # * `:notify` - Sends an ActiveSupport notification but allows the redirect
134
+ # (includes stack trace to help identify the source)
135
+ # * `:raise` - Raises an UnsafeRedirectError
103
136
  def redirect_to(options = {}, response_options = {})
104
137
  raise ActionControllerError.new("Cannot redirect to nil!") unless options
105
138
  raise AbstractController::DoubleRenderError if response_body
@@ -166,6 +199,10 @@ module ActionController
166
199
  when /\A([a-z][a-z\d\-+.]*:|\/\/).*/i
167
200
  options.to_str
168
201
  when String
202
+ if !options.start_with?("/", "?") && !options.empty?
203
+ _handle_path_relative_redirect(options)
204
+ end
205
+
169
206
  request.protocol + request.host_with_port + options
170
207
  when Proc
171
208
  _compute_redirect_to_location request, instance_eval(&options)
@@ -229,12 +266,14 @@ module ActionController
229
266
  end
230
267
 
231
268
  def _url_host_allowed?(url)
232
- host = URI(url.to_s).host
269
+ url_to_s = url.to_s
270
+ host = URI(url_to_s).host
233
271
 
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?("//")
272
+ if host.nil?
273
+ url_to_s.start_with?("/") && !url_to_s.start_with?("//")
274
+ else
275
+ host == request.host || self.class.allowed_redirect_hosts_permissions&.allows?(host)
276
+ end
238
277
  rescue ArgumentError, URI::Error
239
278
  false
240
279
  end
@@ -248,5 +287,22 @@ module ActionController
248
287
  raise UnsafeRedirectError, msg
249
288
  end
250
289
  end
290
+
291
+ def _handle_path_relative_redirect(url)
292
+ message = "Path relative URL redirect detected: #{url.inspect}"
293
+
294
+ case action_on_path_relative_redirect
295
+ when :log
296
+ logger&.warn message
297
+ when :notify
298
+ ActiveSupport::Notifications.instrument("unsafe_redirect.action_controller",
299
+ url: url,
300
+ message: message,
301
+ stack_trace: caller
302
+ )
303
+ when :raise
304
+ raise UnsafeRedirectError, message
305
+ end
306
+ end
251
307
  end
252
308
  end
@@ -27,8 +27,23 @@ module ActionController
27
27
  # Default values are `:json`, `:js`, `:xml`.
28
28
  RENDERERS = Set.new
29
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
+
30
42
  included do
31
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
32
47
  end
33
48
 
34
49
  # Used in ActionController::Base and ActionController::API to include all
@@ -86,7 +101,7 @@ module ActionController
86
101
  remove_possible_method(method_name)
87
102
  end
88
103
 
89
- def self._render_with_renderer_method_name(key)
104
+ def self._render_with_renderer_method_name(key) # :nodoc:
90
105
  "_render_with_renderer_#{key}"
91
106
  end
92
107
 
@@ -140,7 +155,7 @@ module ActionController
140
155
  _render_to_body_with_renderer(options) || super
141
156
  end
142
157
 
143
- def _render_to_body_with_renderer(options)
158
+ def _render_to_body_with_renderer(options) # :nodoc:
144
159
  _renderers.each do |name|
145
160
  if options.key?(name)
146
161
  _process_options(options)
@@ -153,28 +168,34 @@ module ActionController
153
168
 
154
169
  add :json do |json, options|
155
170
  json_options = options.except(:callback, :content_type, :status)
171
+ json_options[:escape] ||= false if !self.class.escape_json_responses? && options[:callback].blank?
156
172
  json = json.to_json(json_options) unless json.kind_of?(String)
157
173
 
158
174
  if options[:callback].present?
159
175
  if media_type.nil? || media_type == Mime[:json]
160
- self.content_type = Mime[:js]
176
+ self.content_type = :js
161
177
  end
162
178
 
163
179
  "/**/#{options[:callback]}(#{json})"
164
180
  else
165
- self.content_type = Mime[:json] if media_type.nil?
181
+ self.content_type = :json if media_type.nil?
166
182
  json
167
183
  end
168
184
  end
169
185
 
170
186
  add :js do |js, options|
171
- self.content_type = Mime[:js] if media_type.nil?
187
+ self.content_type = :js if media_type.nil?
172
188
  js.respond_to?(:to_js) ? js.to_js(options) : js
173
189
  end
174
190
 
175
191
  add :xml do |xml, options|
176
- self.content_type = Mime[:xml] if media_type.nil?
192
+ self.content_type = :xml if media_type.nil?
177
193
  xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml
178
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
179
200
  end
180
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,15 +224,8 @@ module ActionController
218
224
  end
219
225
 
220
226
  def _set_vary_header
221
- if request.should_apply_vary_header?
222
- vary_headers = response.headers["Vary"].to_s.split(",").map(&:strip).reject(&:blank?)
223
-
224
- unless vary_headers.include?("*")
225
- request.vary_headers.each do |header|
226
- vary_headers << header unless vary_headers.any? { |existing| existing.casecmp?(header) }
227
- end
228
- response.headers["Vary"] = vary_headers.join(", ")
229
- end
227
+ if response.headers["Vary"].blank? && request.should_apply_vary_header?
228
+ response.headers["Vary"] = "Accept"
230
229
  end
231
230
  end
232
231