actionpack 6.0.0

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 (181) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +311 -0
  3. data/MIT-LICENSE +21 -0
  4. data/README.rdoc +58 -0
  5. data/lib/abstract_controller.rb +27 -0
  6. data/lib/abstract_controller/asset_paths.rb +12 -0
  7. data/lib/abstract_controller/base.rb +267 -0
  8. data/lib/abstract_controller/caching.rb +66 -0
  9. data/lib/abstract_controller/caching/fragments.rb +150 -0
  10. data/lib/abstract_controller/callbacks.rb +224 -0
  11. data/lib/abstract_controller/collector.rb +43 -0
  12. data/lib/abstract_controller/error.rb +6 -0
  13. data/lib/abstract_controller/helpers.rb +194 -0
  14. data/lib/abstract_controller/logger.rb +14 -0
  15. data/lib/abstract_controller/railties/routes_helpers.rb +20 -0
  16. data/lib/abstract_controller/rendering.rb +127 -0
  17. data/lib/abstract_controller/translation.rb +32 -0
  18. data/lib/abstract_controller/url_for.rb +35 -0
  19. data/lib/action_controller.rb +67 -0
  20. data/lib/action_controller/api.rb +150 -0
  21. data/lib/action_controller/api/api_rendering.rb +16 -0
  22. data/lib/action_controller/base.rb +271 -0
  23. data/lib/action_controller/caching.rb +46 -0
  24. data/lib/action_controller/form_builder.rb +50 -0
  25. data/lib/action_controller/log_subscriber.rb +81 -0
  26. data/lib/action_controller/metal.rb +256 -0
  27. data/lib/action_controller/metal/basic_implicit_render.rb +13 -0
  28. data/lib/action_controller/metal/conditional_get.rb +280 -0
  29. data/lib/action_controller/metal/content_security_policy.rb +52 -0
  30. data/lib/action_controller/metal/cookies.rb +16 -0
  31. data/lib/action_controller/metal/data_streaming.rb +151 -0
  32. data/lib/action_controller/metal/default_headers.rb +17 -0
  33. data/lib/action_controller/metal/etag_with_flash.rb +18 -0
  34. data/lib/action_controller/metal/etag_with_template_digest.rb +57 -0
  35. data/lib/action_controller/metal/exceptions.rb +74 -0
  36. data/lib/action_controller/metal/flash.rb +61 -0
  37. data/lib/action_controller/metal/force_ssl.rb +58 -0
  38. data/lib/action_controller/metal/head.rb +60 -0
  39. data/lib/action_controller/metal/helpers.rb +122 -0
  40. data/lib/action_controller/metal/http_authentication.rb +518 -0
  41. data/lib/action_controller/metal/implicit_render.rb +63 -0
  42. data/lib/action_controller/metal/instrumentation.rb +105 -0
  43. data/lib/action_controller/metal/live.rb +314 -0
  44. data/lib/action_controller/metal/mime_responds.rb +324 -0
  45. data/lib/action_controller/metal/parameter_encoding.rb +51 -0
  46. data/lib/action_controller/metal/params_wrapper.rb +297 -0
  47. data/lib/action_controller/metal/redirecting.rb +133 -0
  48. data/lib/action_controller/metal/renderers.rb +181 -0
  49. data/lib/action_controller/metal/rendering.rb +122 -0
  50. data/lib/action_controller/metal/request_forgery_protection.rb +456 -0
  51. data/lib/action_controller/metal/rescue.rb +28 -0
  52. data/lib/action_controller/metal/streaming.rb +223 -0
  53. data/lib/action_controller/metal/strong_parameters.rb +1105 -0
  54. data/lib/action_controller/metal/testing.rb +16 -0
  55. data/lib/action_controller/metal/url_for.rb +58 -0
  56. data/lib/action_controller/railtie.rb +89 -0
  57. data/lib/action_controller/railties/helpers.rb +24 -0
  58. data/lib/action_controller/renderer.rb +130 -0
  59. data/lib/action_controller/template_assertions.rb +11 -0
  60. data/lib/action_controller/test_case.rb +626 -0
  61. data/lib/action_dispatch.rb +114 -0
  62. data/lib/action_dispatch/http/cache.rb +226 -0
  63. data/lib/action_dispatch/http/content_disposition.rb +45 -0
  64. data/lib/action_dispatch/http/content_security_policy.rb +284 -0
  65. data/lib/action_dispatch/http/filter_parameters.rb +86 -0
  66. data/lib/action_dispatch/http/filter_redirect.rb +37 -0
  67. data/lib/action_dispatch/http/headers.rb +132 -0
  68. data/lib/action_dispatch/http/mime_negotiation.rb +177 -0
  69. data/lib/action_dispatch/http/mime_type.rb +350 -0
  70. data/lib/action_dispatch/http/mime_types.rb +50 -0
  71. data/lib/action_dispatch/http/parameter_filter.rb +12 -0
  72. data/lib/action_dispatch/http/parameters.rb +136 -0
  73. data/lib/action_dispatch/http/rack_cache.rb +63 -0
  74. data/lib/action_dispatch/http/request.rb +427 -0
  75. data/lib/action_dispatch/http/response.rb +534 -0
  76. data/lib/action_dispatch/http/upload.rb +92 -0
  77. data/lib/action_dispatch/http/url.rb +350 -0
  78. data/lib/action_dispatch/journey.rb +7 -0
  79. data/lib/action_dispatch/journey/formatter.rb +189 -0
  80. data/lib/action_dispatch/journey/gtg/builder.rb +164 -0
  81. data/lib/action_dispatch/journey/gtg/simulator.rb +41 -0
  82. data/lib/action_dispatch/journey/gtg/transition_table.rb +158 -0
  83. data/lib/action_dispatch/journey/nfa/builder.rb +78 -0
  84. data/lib/action_dispatch/journey/nfa/dot.rb +36 -0
  85. data/lib/action_dispatch/journey/nfa/simulator.rb +47 -0
  86. data/lib/action_dispatch/journey/nfa/transition_table.rb +120 -0
  87. data/lib/action_dispatch/journey/nodes/node.rb +141 -0
  88. data/lib/action_dispatch/journey/parser.rb +199 -0
  89. data/lib/action_dispatch/journey/parser.y +50 -0
  90. data/lib/action_dispatch/journey/parser_extras.rb +31 -0
  91. data/lib/action_dispatch/journey/path/pattern.rb +203 -0
  92. data/lib/action_dispatch/journey/route.rb +204 -0
  93. data/lib/action_dispatch/journey/router.rb +153 -0
  94. data/lib/action_dispatch/journey/router/utils.rb +102 -0
  95. data/lib/action_dispatch/journey/routes.rb +81 -0
  96. data/lib/action_dispatch/journey/scanner.rb +71 -0
  97. data/lib/action_dispatch/journey/visitors.rb +268 -0
  98. data/lib/action_dispatch/journey/visualizer/fsm.css +30 -0
  99. data/lib/action_dispatch/journey/visualizer/fsm.js +134 -0
  100. data/lib/action_dispatch/journey/visualizer/index.html.erb +52 -0
  101. data/lib/action_dispatch/middleware/actionable_exceptions.rb +39 -0
  102. data/lib/action_dispatch/middleware/callbacks.rb +34 -0
  103. data/lib/action_dispatch/middleware/cookies.rb +663 -0
  104. data/lib/action_dispatch/middleware/debug_exceptions.rb +185 -0
  105. data/lib/action_dispatch/middleware/debug_locks.rb +124 -0
  106. data/lib/action_dispatch/middleware/debug_view.rb +68 -0
  107. data/lib/action_dispatch/middleware/exception_wrapper.rb +181 -0
  108. data/lib/action_dispatch/middleware/executor.rb +21 -0
  109. data/lib/action_dispatch/middleware/flash.rb +300 -0
  110. data/lib/action_dispatch/middleware/host_authorization.rb +103 -0
  111. data/lib/action_dispatch/middleware/public_exceptions.rb +61 -0
  112. data/lib/action_dispatch/middleware/reloader.rb +12 -0
  113. data/lib/action_dispatch/middleware/remote_ip.rb +181 -0
  114. data/lib/action_dispatch/middleware/request_id.rb +43 -0
  115. data/lib/action_dispatch/middleware/session/abstract_store.rb +92 -0
  116. data/lib/action_dispatch/middleware/session/cache_store.rb +54 -0
  117. data/lib/action_dispatch/middleware/session/cookie_store.rb +113 -0
  118. data/lib/action_dispatch/middleware/session/mem_cache_store.rb +28 -0
  119. data/lib/action_dispatch/middleware/show_exceptions.rb +62 -0
  120. data/lib/action_dispatch/middleware/ssl.rb +150 -0
  121. data/lib/action_dispatch/middleware/stack.rb +148 -0
  122. data/lib/action_dispatch/middleware/static.rb +129 -0
  123. data/lib/action_dispatch/middleware/templates/rescues/_actions.html.erb +13 -0
  124. data/lib/action_dispatch/middleware/templates/rescues/_actions.text.erb +0 -0
  125. data/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb +24 -0
  126. data/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb +23 -0
  127. data/lib/action_dispatch/middleware/templates/rescues/_source.html.erb +29 -0
  128. data/lib/action_dispatch/middleware/templates/rescues/_source.text.erb +8 -0
  129. data/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb +62 -0
  130. data/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb +9 -0
  131. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.html.erb +7 -0
  132. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.text.erb +5 -0
  133. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb +38 -0
  134. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb +9 -0
  135. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.html.erb +24 -0
  136. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.text.erb +15 -0
  137. data/lib/action_dispatch/middleware/templates/rescues/layout.erb +165 -0
  138. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.html.erb +19 -0
  139. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.text.erb +3 -0
  140. data/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb +11 -0
  141. data/lib/action_dispatch/middleware/templates/rescues/missing_template.text.erb +3 -0
  142. data/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb +32 -0
  143. data/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb +11 -0
  144. data/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb +20 -0
  145. data/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb +7 -0
  146. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb +6 -0
  147. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.text.erb +3 -0
  148. data/lib/action_dispatch/middleware/templates/routes/_route.html.erb +16 -0
  149. data/lib/action_dispatch/middleware/templates/routes/_table.html.erb +203 -0
  150. data/lib/action_dispatch/railtie.rb +58 -0
  151. data/lib/action_dispatch/request/session.rb +242 -0
  152. data/lib/action_dispatch/request/utils.rb +78 -0
  153. data/lib/action_dispatch/routing.rb +261 -0
  154. data/lib/action_dispatch/routing/endpoint.rb +17 -0
  155. data/lib/action_dispatch/routing/inspector.rb +274 -0
  156. data/lib/action_dispatch/routing/mapper.rb +2289 -0
  157. data/lib/action_dispatch/routing/polymorphic_routes.rb +351 -0
  158. data/lib/action_dispatch/routing/redirection.rb +201 -0
  159. data/lib/action_dispatch/routing/route_set.rb +887 -0
  160. data/lib/action_dispatch/routing/routes_proxy.rb +69 -0
  161. data/lib/action_dispatch/routing/url_for.rb +237 -0
  162. data/lib/action_dispatch/system_test_case.rb +168 -0
  163. data/lib/action_dispatch/system_testing/browser.rb +80 -0
  164. data/lib/action_dispatch/system_testing/driver.rb +68 -0
  165. data/lib/action_dispatch/system_testing/server.rb +31 -0
  166. data/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb +97 -0
  167. data/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb +33 -0
  168. data/lib/action_dispatch/system_testing/test_helpers/undef_methods.rb +26 -0
  169. data/lib/action_dispatch/testing/assertion_response.rb +47 -0
  170. data/lib/action_dispatch/testing/assertions.rb +24 -0
  171. data/lib/action_dispatch/testing/assertions/response.rb +106 -0
  172. data/lib/action_dispatch/testing/assertions/routing.rb +234 -0
  173. data/lib/action_dispatch/testing/integration.rb +659 -0
  174. data/lib/action_dispatch/testing/request_encoder.rb +55 -0
  175. data/lib/action_dispatch/testing/test_process.rb +50 -0
  176. data/lib/action_dispatch/testing/test_request.rb +71 -0
  177. data/lib/action_dispatch/testing/test_response.rb +25 -0
  178. data/lib/action_pack.rb +26 -0
  179. data/lib/action_pack/gem_version.rb +17 -0
  180. data/lib/action_pack/version.rb +10 -0
  181. metadata +329 -0
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActionController #:nodoc:
4
+ # This module is responsible for providing +rescue_from+ helpers
5
+ # to controllers and configuring when detailed exceptions must be
6
+ # shown.
7
+ module Rescue
8
+ extend ActiveSupport::Concern
9
+ include ActiveSupport::Rescuable
10
+
11
+ # Override this method if you want to customize when detailed
12
+ # exceptions must be shown. This method is only called when
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.
16
+ def show_detailed_exceptions?
17
+ false
18
+ end
19
+
20
+ private
21
+ def process_action(*args)
22
+ super
23
+ rescue Exception => exception
24
+ request.env["action_dispatch.show_detailed_exceptions"] ||= show_detailed_exceptions?
25
+ rescue_with_handler(exception) || raise
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,223 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack/chunked"
4
+
5
+ module ActionController #:nodoc:
6
+ # Allows views to be streamed back to the client as they are rendered.
7
+ #
8
+ # By default, Rails renders views by first rendering the template
9
+ # and then the layout. The response is sent to the client after the whole
10
+ # template is rendered, all queries are made, and the layout is processed.
11
+ #
12
+ # Streaming inverts the rendering flow by rendering the layout first and
13
+ # streaming each part of the layout as they are processed. This allows the
14
+ # header of the HTML (which is usually in the layout) to be streamed back
15
+ # to client very quickly, allowing JavaScripts and stylesheets to be loaded
16
+ # earlier than usual.
17
+ #
18
+ # This approach was introduced in Rails 3.1 and is still improving. Several
19
+ # Rack middlewares may not work and you need to be careful when streaming.
20
+ # Those points are going to be addressed soon.
21
+ #
22
+ # In order to use streaming, you will need to use a Ruby version that
23
+ # supports fibers (fibers are supported since version 1.9.2 of the main
24
+ # Ruby implementation).
25
+ #
26
+ # Streaming can be added to a given template easily, all you need to do is
27
+ # to pass the :stream option.
28
+ #
29
+ # class PostsController
30
+ # def index
31
+ # @posts = Post.all
32
+ # render stream: true
33
+ # end
34
+ # end
35
+ #
36
+ # == When to use streaming
37
+ #
38
+ # Streaming may be considered to be overkill for lightweight actions like
39
+ # +new+ or +edit+. The real benefit of streaming is on expensive actions
40
+ # that, for example, do a lot of queries on the database.
41
+ #
42
+ # In such actions, you want to delay queries execution as much as you can.
43
+ # For example, imagine the following +dashboard+ action:
44
+ #
45
+ # def dashboard
46
+ # @posts = Post.all
47
+ # @pages = Page.all
48
+ # @articles = Article.all
49
+ # end
50
+ #
51
+ # Most of the queries here are happening in the controller. In order to benefit
52
+ # from streaming you would want to rewrite it as:
53
+ #
54
+ # def dashboard
55
+ # # Allow lazy execution of the queries
56
+ # @posts = Post.all
57
+ # @pages = Page.all
58
+ # @articles = Article.all
59
+ # render stream: true
60
+ # end
61
+ #
62
+ # Notice that :stream only works with templates. Rendering :json
63
+ # or :xml with :stream won't work.
64
+ #
65
+ # == Communication between layout and template
66
+ #
67
+ # When streaming, rendering happens top-down instead of inside-out.
68
+ # Rails starts with the layout, and the template is rendered later,
69
+ # when its +yield+ is reached.
70
+ #
71
+ # This means that, if your application currently relies on instance
72
+ # variables set in the template to be used in the layout, they won't
73
+ # work once you move to streaming. The proper way to communicate
74
+ # between layout and template, regardless of whether you use streaming
75
+ # or not, is by using +content_for+, +provide+ and +yield+.
76
+ #
77
+ # Take a simple example where the layout expects the template to tell
78
+ # which title to use:
79
+ #
80
+ # <html>
81
+ # <head><title><%= yield :title %></title></head>
82
+ # <body><%= yield %></body>
83
+ # </html>
84
+ #
85
+ # You would use +content_for+ in your template to specify the title:
86
+ #
87
+ # <%= content_for :title, "Main" %>
88
+ # Hello
89
+ #
90
+ # And the final result would be:
91
+ #
92
+ # <html>
93
+ # <head><title>Main</title></head>
94
+ # <body>Hello</body>
95
+ # </html>
96
+ #
97
+ # However, if +content_for+ is called several times, the final result
98
+ # would have all calls concatenated. For instance, if we have the following
99
+ # template:
100
+ #
101
+ # <%= content_for :title, "Main" %>
102
+ # Hello
103
+ # <%= content_for :title, " page" %>
104
+ #
105
+ # The final result would be:
106
+ #
107
+ # <html>
108
+ # <head><title>Main page</title></head>
109
+ # <body>Hello</body>
110
+ # </html>
111
+ #
112
+ # This means that, if you have <code>yield :title</code> in your layout
113
+ # and you want to use streaming, you would have to render the whole template
114
+ # (and eventually trigger all queries) before streaming the title and all
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.
118
+ #
119
+ # For instance, the template above using +provide+ would be:
120
+ #
121
+ # <%= provide :title, "Main" %>
122
+ # Hello
123
+ # <%= content_for :title, " page" %>
124
+ #
125
+ # Giving:
126
+ #
127
+ # <html>
128
+ # <head><title>Main</title></head>
129
+ # <body>Hello</body>
130
+ # </html>
131
+ #
132
+ # That said, when streaming, you need to properly check your templates
133
+ # and choose when to use +provide+ and +content_for+.
134
+ #
135
+ # == Headers, cookies, session and flash
136
+ #
137
+ # When streaming, the HTTP headers are sent to the client right before
138
+ # it renders the first line. This means that, modifying headers, cookies,
139
+ # session or flash after the template starts rendering will not propagate
140
+ # to the client.
141
+ #
142
+ # == Middlewares
143
+ #
144
+ # Middlewares that need to manipulate the body won't work with streaming.
145
+ # You should disable those middlewares whenever streaming in development
146
+ # or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it
147
+ # needs to inject contents in the HTML body.
148
+ #
149
+ # Also <tt>Rack::Cache</tt> won't work with streaming as it does not support
150
+ # streaming bodies yet. Whenever streaming Cache-Control is automatically
151
+ # set to "no-cache".
152
+ #
153
+ # == Errors
154
+ #
155
+ # When it comes to streaming, exceptions get a bit more complicated. This
156
+ # happens because part of the template was already rendered and streamed to
157
+ # the client, making it impossible to render a whole exception page.
158
+ #
159
+ # Currently, when an exception happens in development or production, Rails
160
+ # will automatically stream to the client:
161
+ #
162
+ # "><script>window.location = "/500.html"</script></html>
163
+ #
164
+ # The first two characters (">) are required in case the exception happens
165
+ # while rendering attributes for a given tag. You can check the real cause
166
+ # for the exception in your logger.
167
+ #
168
+ # == Web server support
169
+ #
170
+ # Not all web servers support streaming out-of-the-box. You need to check
171
+ # the instructions for each of them.
172
+ #
173
+ # ==== Unicorn
174
+ #
175
+ # Unicorn supports streaming but it needs to be configured. For this, you
176
+ # need to create a config file as follow:
177
+ #
178
+ # # unicorn.config.rb
179
+ # listen 3000, tcp_nopush: false
180
+ #
181
+ # And use it on initialization:
182
+ #
183
+ # unicorn_rails --config-file unicorn.config.rb
184
+ #
185
+ # You may also want to configure other parameters like <tt>:tcp_nodelay</tt>.
186
+ # Please check its documentation for more information: https://bogomips.org/unicorn/Unicorn/Configurator.html#method-i-listen
187
+ #
188
+ # If you are using Unicorn with NGINX, you may need to tweak NGINX.
189
+ # Streaming should work out of the box on Rainbows.
190
+ #
191
+ # ==== Passenger
192
+ #
193
+ # To be described.
194
+ #
195
+ module Streaming
196
+ extend ActiveSupport::Concern
197
+
198
+ private
199
+
200
+ # Set proper cache control and transfer encoding when streaming
201
+ def _process_options(options)
202
+ super
203
+ if options[:stream]
204
+ if request.version == "HTTP/1.0"
205
+ options.delete(:stream)
206
+ else
207
+ headers["Cache-Control"] ||= "no-cache"
208
+ headers["Transfer-Encoding"] = "chunked"
209
+ headers.delete("Content-Length")
210
+ end
211
+ end
212
+ end
213
+
214
+ # Call render_body if we are streaming instead of usual +render+.
215
+ def _render_template(options)
216
+ if options.delete(:stream)
217
+ Rack::Chunked::Body.new view_renderer.render_body(view_context, options)
218
+ else
219
+ super
220
+ end
221
+ end
222
+ end
223
+ end
@@ -0,0 +1,1105 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/hash/indifferent_access"
4
+ require "active_support/core_ext/array/wrap"
5
+ require "active_support/core_ext/string/filters"
6
+ require "active_support/core_ext/object/to_query"
7
+ require "action_dispatch/http/upload"
8
+ require "rack/test"
9
+ require "stringio"
10
+ require "set"
11
+ require "yaml"
12
+
13
+ module ActionController
14
+ # Raised when a required parameter is missing.
15
+ #
16
+ # params = ActionController::Parameters.new(a: {})
17
+ # params.fetch(:b)
18
+ # # => ActionController::ParameterMissing: param is missing or the value is empty: b
19
+ # params.require(:a)
20
+ # # => ActionController::ParameterMissing: param is missing or the value is empty: a
21
+ class ParameterMissing < KeyError
22
+ attr_reader :param # :nodoc:
23
+
24
+ def initialize(param) # :nodoc:
25
+ @param = param
26
+ super("param is missing or the value is empty: #{param}")
27
+ end
28
+ end
29
+
30
+ # Raised when a supplied parameter is not expected and
31
+ # ActionController::Parameters.action_on_unpermitted_parameters
32
+ # is set to <tt>:raise</tt>.
33
+ #
34
+ # params = ActionController::Parameters.new(a: "123", b: "456")
35
+ # params.permit(:c)
36
+ # # => ActionController::UnpermittedParameters: found unpermitted parameters: :a, :b
37
+ class UnpermittedParameters < IndexError
38
+ attr_reader :params # :nodoc:
39
+
40
+ def initialize(params) # :nodoc:
41
+ @params = params
42
+ super("found unpermitted parameter#{'s' if params.size > 1 }: #{params.map { |e| ":#{e}" }.join(", ")}")
43
+ end
44
+ end
45
+
46
+ # Raised when a Parameters instance is not marked as permitted and
47
+ # an operation to transform it to hash is called.
48
+ #
49
+ # params = ActionController::Parameters.new(a: "123", b: "456")
50
+ # params.to_h
51
+ # # => ActionController::UnfilteredParameters: unable to convert unpermitted parameters to hash
52
+ class UnfilteredParameters < ArgumentError
53
+ def initialize # :nodoc:
54
+ super("unable to convert unpermitted parameters to hash")
55
+ end
56
+ end
57
+
58
+ # == Action Controller \Parameters
59
+ #
60
+ # Allows you to choose which attributes should be permitted for mass updating
61
+ # and thus prevent accidentally exposing that which shouldn't be exposed.
62
+ # Provides two methods for this purpose: #require and #permit. The former is
63
+ # used to mark parameters as required. The latter is used to set the parameter
64
+ # as permitted and limit which attributes should be allowed for mass updating.
65
+ #
66
+ # params = ActionController::Parameters.new({
67
+ # person: {
68
+ # name: "Francesco",
69
+ # age: 22,
70
+ # role: "admin"
71
+ # }
72
+ # })
73
+ #
74
+ # permitted = params.require(:person).permit(:name, :age)
75
+ # permitted # => <ActionController::Parameters {"name"=>"Francesco", "age"=>22} permitted: true>
76
+ # permitted.permitted? # => true
77
+ #
78
+ # Person.first.update!(permitted)
79
+ # # => #<Person id: 1, name: "Francesco", age: 22, role: "user">
80
+ #
81
+ # It provides two options that controls the top-level behavior of new instances:
82
+ #
83
+ # * +permit_all_parameters+ - If it's +true+, all the parameters will be
84
+ # permitted by default. The default is +false+.
85
+ # * +action_on_unpermitted_parameters+ - Allow to control the behavior when parameters
86
+ # that are not explicitly permitted are found. The values can be +false+ to just filter them
87
+ # out, <tt>:log</tt> to additionally write a message on the logger, or <tt>:raise</tt> to raise
88
+ # ActionController::UnpermittedParameters exception. The default value is <tt>:log</tt>
89
+ # in test and development environments, +false+ otherwise.
90
+ #
91
+ # Examples:
92
+ #
93
+ # params = ActionController::Parameters.new
94
+ # params.permitted? # => false
95
+ #
96
+ # ActionController::Parameters.permit_all_parameters = true
97
+ #
98
+ # params = ActionController::Parameters.new
99
+ # params.permitted? # => true
100
+ #
101
+ # params = ActionController::Parameters.new(a: "123", b: "456")
102
+ # params.permit(:c)
103
+ # # => <ActionController::Parameters {} permitted: true>
104
+ #
105
+ # ActionController::Parameters.action_on_unpermitted_parameters = :raise
106
+ #
107
+ # params = ActionController::Parameters.new(a: "123", b: "456")
108
+ # params.permit(:c)
109
+ # # => ActionController::UnpermittedParameters: found unpermitted keys: a, b
110
+ #
111
+ # Please note that these options *are not thread-safe*. In a multi-threaded
112
+ # environment they should only be set once at boot-time and never mutated at
113
+ # runtime.
114
+ #
115
+ # You can fetch values of <tt>ActionController::Parameters</tt> using either
116
+ # <tt>:key</tt> or <tt>"key"</tt>.
117
+ #
118
+ # params = ActionController::Parameters.new(key: "value")
119
+ # params[:key] # => "value"
120
+ # params["key"] # => "value"
121
+ class Parameters
122
+ cattr_accessor :permit_all_parameters, instance_accessor: false, default: false
123
+
124
+ cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false
125
+
126
+ ##
127
+ # :method: as_json
128
+ #
129
+ # :call-seq:
130
+ # as_json(options=nil)
131
+ #
132
+ # Returns a hash that can be used as the JSON representation for the parameters.
133
+
134
+ ##
135
+ # :method: each_key
136
+ #
137
+ # :call-seq:
138
+ # each_key()
139
+ #
140
+ # Calls block once for each key in the parameters, passing the key.
141
+ # If no block is given, an enumerator is returned instead.
142
+
143
+ ##
144
+ # :method: empty?
145
+ #
146
+ # :call-seq:
147
+ # empty?()
148
+ #
149
+ # Returns true if the parameters have no key/value pairs.
150
+
151
+ ##
152
+ # :method: has_key?
153
+ #
154
+ # :call-seq:
155
+ # has_key?(key)
156
+ #
157
+ # Returns true if the given key is present in the parameters.
158
+
159
+ ##
160
+ # :method: has_value?
161
+ #
162
+ # :call-seq:
163
+ # has_value?(value)
164
+ #
165
+ # Returns true if the given value is present for some key in the parameters.
166
+
167
+ ##
168
+ # :method: include?
169
+ #
170
+ # :call-seq:
171
+ # include?(key)
172
+ #
173
+ # Returns true if the given key is present in the parameters.
174
+
175
+ ##
176
+ # :method: key?
177
+ #
178
+ # :call-seq:
179
+ # key?(key)
180
+ #
181
+ # Returns true if the given key is present in the parameters.
182
+
183
+ ##
184
+ # :method: keys
185
+ #
186
+ # :call-seq:
187
+ # keys()
188
+ #
189
+ # Returns a new array of the keys of the parameters.
190
+
191
+ ##
192
+ # :method: to_s
193
+ #
194
+ # :call-seq:
195
+ # to_s()
196
+ #
197
+ # Returns the content of the parameters as a string.
198
+
199
+ ##
200
+ # :method: value?
201
+ #
202
+ # :call-seq:
203
+ # value?(value)
204
+ #
205
+ # Returns true if the given value is present for some key in the parameters.
206
+
207
+ ##
208
+ # :method: values
209
+ #
210
+ # :call-seq:
211
+ # values()
212
+ #
213
+ # Returns a new array of the values of the parameters.
214
+ delegate :keys, :key?, :has_key?, :values, :has_value?, :value?, :empty?, :include?,
215
+ :as_json, :to_s, :each_key, to: :@parameters
216
+
217
+ # By default, never raise an UnpermittedParameters exception if these
218
+ # params are present. The default includes both 'controller' and 'action'
219
+ # because they are added by Rails and should be of no concern. One way
220
+ # to change these is to specify `always_permitted_parameters` in your
221
+ # config. For instance:
222
+ #
223
+ # config.always_permitted_parameters = %w( controller action format )
224
+ cattr_accessor :always_permitted_parameters, default: %w( controller action )
225
+
226
+ # Returns a new instance of <tt>ActionController::Parameters</tt>.
227
+ # Also, sets the +permitted+ attribute to the default value of
228
+ # <tt>ActionController::Parameters.permit_all_parameters</tt>.
229
+ #
230
+ # class Person < ActiveRecord::Base
231
+ # end
232
+ #
233
+ # params = ActionController::Parameters.new(name: "Francesco")
234
+ # params.permitted? # => false
235
+ # Person.new(params) # => ActiveModel::ForbiddenAttributesError
236
+ #
237
+ # ActionController::Parameters.permit_all_parameters = true
238
+ #
239
+ # params = ActionController::Parameters.new(name: "Francesco")
240
+ # params.permitted? # => true
241
+ # Person.new(params) # => #<Person id: nil, name: "Francesco">
242
+ def initialize(parameters = {})
243
+ @parameters = parameters.with_indifferent_access
244
+ @permitted = self.class.permit_all_parameters
245
+ end
246
+
247
+ # Returns true if another +Parameters+ object contains the same content and
248
+ # permitted flag.
249
+ def ==(other)
250
+ if other.respond_to?(:permitted?)
251
+ permitted? == other.permitted? && parameters == other.parameters
252
+ else
253
+ @parameters == other
254
+ end
255
+ end
256
+
257
+ # Returns a safe <tt>ActiveSupport::HashWithIndifferentAccess</tt>
258
+ # representation of the parameters with all unpermitted keys removed.
259
+ #
260
+ # params = ActionController::Parameters.new({
261
+ # name: "Senjougahara Hitagi",
262
+ # oddity: "Heavy stone crab"
263
+ # })
264
+ # params.to_h
265
+ # # => ActionController::UnfilteredParameters: unable to convert unpermitted parameters to hash
266
+ #
267
+ # safe_params = params.permit(:name)
268
+ # safe_params.to_h # => {"name"=>"Senjougahara Hitagi"}
269
+ def to_h
270
+ if permitted?
271
+ convert_parameters_to_hashes(@parameters, :to_h)
272
+ else
273
+ raise UnfilteredParameters
274
+ end
275
+ end
276
+
277
+ # Returns a safe <tt>Hash</tt> representation of the parameters
278
+ # with all unpermitted keys removed.
279
+ #
280
+ # params = ActionController::Parameters.new({
281
+ # name: "Senjougahara Hitagi",
282
+ # oddity: "Heavy stone crab"
283
+ # })
284
+ # params.to_hash
285
+ # # => ActionController::UnfilteredParameters: unable to convert unpermitted parameters to hash
286
+ #
287
+ # safe_params = params.permit(:name)
288
+ # safe_params.to_hash # => {"name"=>"Senjougahara Hitagi"}
289
+ def to_hash
290
+ to_h.to_hash
291
+ end
292
+
293
+ # Returns a string representation of the receiver suitable for use as a URL
294
+ # query string:
295
+ #
296
+ # params = ActionController::Parameters.new({
297
+ # name: "David",
298
+ # nationality: "Danish"
299
+ # })
300
+ # params.to_query
301
+ # # => ActionController::UnfilteredParameters: unable to convert unpermitted parameters to hash
302
+ #
303
+ # safe_params = params.permit(:name, :nationality)
304
+ # safe_params.to_query
305
+ # # => "name=David&nationality=Danish"
306
+ #
307
+ # An optional namespace can be passed to enclose key names:
308
+ #
309
+ # params = ActionController::Parameters.new({
310
+ # name: "David",
311
+ # nationality: "Danish"
312
+ # })
313
+ # safe_params = params.permit(:name, :nationality)
314
+ # safe_params.to_query("user")
315
+ # # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
316
+ #
317
+ # The string pairs "key=value" that conform the query string
318
+ # are sorted lexicographically in ascending order.
319
+ #
320
+ # This method is also aliased as +to_param+.
321
+ def to_query(*args)
322
+ to_h.to_query(*args)
323
+ end
324
+ alias_method :to_param, :to_query
325
+
326
+ # Returns an unsafe, unfiltered
327
+ # <tt>ActiveSupport::HashWithIndifferentAccess</tt> representation of the
328
+ # parameters.
329
+ #
330
+ # params = ActionController::Parameters.new({
331
+ # name: "Senjougahara Hitagi",
332
+ # oddity: "Heavy stone crab"
333
+ # })
334
+ # params.to_unsafe_h
335
+ # # => {"name"=>"Senjougahara Hitagi", "oddity" => "Heavy stone crab"}
336
+ def to_unsafe_h
337
+ convert_parameters_to_hashes(@parameters, :to_unsafe_h)
338
+ end
339
+ alias_method :to_unsafe_hash, :to_unsafe_h
340
+
341
+ # Convert all hashes in values into parameters, then yield each pair in
342
+ # the same way as <tt>Hash#each_pair</tt>.
343
+ def each_pair(&block)
344
+ @parameters.each_pair do |key, value|
345
+ yield [key, convert_hashes_to_parameters(key, value)]
346
+ end
347
+ end
348
+ alias_method :each, :each_pair
349
+
350
+ # Convert all hashes in values into parameters, then yield each value in
351
+ # the same way as <tt>Hash#each_value</tt>.
352
+ def each_value(&block)
353
+ @parameters.each_pair do |key, value|
354
+ yield convert_hashes_to_parameters(key, value)
355
+ end
356
+ end
357
+
358
+ # Attribute that keeps track of converted arrays, if any, to avoid double
359
+ # looping in the common use case permit + mass-assignment. Defined in a
360
+ # method to instantiate it only if needed.
361
+ #
362
+ # Testing membership still loops, but it's going to be faster than our own
363
+ # loop that converts values. Also, we are not going to build a new array
364
+ # object per fetch.
365
+ def converted_arrays
366
+ @converted_arrays ||= Set.new
367
+ end
368
+
369
+ # Returns +true+ if the parameter is permitted, +false+ otherwise.
370
+ #
371
+ # params = ActionController::Parameters.new
372
+ # params.permitted? # => false
373
+ # params.permit!
374
+ # params.permitted? # => true
375
+ def permitted?
376
+ @permitted
377
+ end
378
+
379
+ # Sets the +permitted+ attribute to +true+. This can be used to pass
380
+ # mass assignment. Returns +self+.
381
+ #
382
+ # class Person < ActiveRecord::Base
383
+ # end
384
+ #
385
+ # params = ActionController::Parameters.new(name: "Francesco")
386
+ # params.permitted? # => false
387
+ # Person.new(params) # => ActiveModel::ForbiddenAttributesError
388
+ # params.permit!
389
+ # params.permitted? # => true
390
+ # Person.new(params) # => #<Person id: nil, name: "Francesco">
391
+ def permit!
392
+ each_pair do |key, value|
393
+ Array.wrap(value).flatten.each do |v|
394
+ v.permit! if v.respond_to? :permit!
395
+ end
396
+ end
397
+
398
+ @permitted = true
399
+ self
400
+ end
401
+
402
+ # This method accepts both a single key and an array of keys.
403
+ #
404
+ # When passed a single key, if it exists and its associated value is
405
+ # either present or the singleton +false+, returns said value:
406
+ #
407
+ # ActionController::Parameters.new(person: { name: "Francesco" }).require(:person)
408
+ # # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
409
+ #
410
+ # Otherwise raises <tt>ActionController::ParameterMissing</tt>:
411
+ #
412
+ # ActionController::Parameters.new.require(:person)
413
+ # # ActionController::ParameterMissing: param is missing or the value is empty: person
414
+ #
415
+ # ActionController::Parameters.new(person: nil).require(:person)
416
+ # # ActionController::ParameterMissing: param is missing or the value is empty: person
417
+ #
418
+ # ActionController::Parameters.new(person: "\t").require(:person)
419
+ # # ActionController::ParameterMissing: param is missing or the value is empty: person
420
+ #
421
+ # ActionController::Parameters.new(person: {}).require(:person)
422
+ # # ActionController::ParameterMissing: param is missing or the value is empty: person
423
+ #
424
+ # When given an array of keys, the method tries to require each one of them
425
+ # in order. If it succeeds, an array with the respective return values is
426
+ # returned:
427
+ #
428
+ # params = ActionController::Parameters.new(user: { ... }, profile: { ... })
429
+ # user_params, profile_params = params.require([:user, :profile])
430
+ #
431
+ # Otherwise, the method re-raises the first exception found:
432
+ #
433
+ # params = ActionController::Parameters.new(user: {}, profile: {})
434
+ # user_params, profile_params = params.require([:user, :profile])
435
+ # # ActionController::ParameterMissing: param is missing or the value is empty: user
436
+ #
437
+ # Technically this method can be used to fetch terminal values:
438
+ #
439
+ # # CAREFUL
440
+ # params = ActionController::Parameters.new(person: { name: "Finn" })
441
+ # name = params.require(:person).require(:name) # CAREFUL
442
+ #
443
+ # but take into account that at some point those ones have to be permitted:
444
+ #
445
+ # def person_params
446
+ # params.require(:person).permit(:name).tap do |person_params|
447
+ # person_params.require(:name) # SAFER
448
+ # end
449
+ # end
450
+ #
451
+ # for example.
452
+ def require(key)
453
+ return key.map { |k| require(k) } if key.is_a?(Array)
454
+ value = self[key]
455
+ if value.present? || value == false
456
+ value
457
+ else
458
+ raise ParameterMissing.new(key)
459
+ end
460
+ end
461
+
462
+ # Alias of #require.
463
+ alias :required :require
464
+
465
+ # Returns a new <tt>ActionController::Parameters</tt> instance that
466
+ # includes only the given +filters+ and sets the +permitted+ attribute
467
+ # for the object to +true+. This is useful for limiting which attributes
468
+ # should be allowed for mass updating.
469
+ #
470
+ # params = ActionController::Parameters.new(user: { name: "Francesco", age: 22, role: "admin" })
471
+ # permitted = params.require(:user).permit(:name, :age)
472
+ # permitted.permitted? # => true
473
+ # permitted.has_key?(:name) # => true
474
+ # permitted.has_key?(:age) # => true
475
+ # permitted.has_key?(:role) # => false
476
+ #
477
+ # Only permitted scalars pass the filter. For example, given
478
+ #
479
+ # params.permit(:name)
480
+ #
481
+ # +:name+ passes if it is a key of +params+ whose associated value is of type
482
+ # +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
483
+ # +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
484
+ # +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
485
+ # Otherwise, the key +:name+ is filtered out.
486
+ #
487
+ # You may declare that the parameter should be an array of permitted scalars
488
+ # by mapping it to an empty array:
489
+ #
490
+ # params = ActionController::Parameters.new(tags: ["rails", "parameters"])
491
+ # params.permit(tags: [])
492
+ #
493
+ # Sometimes it is not possible or convenient to declare the valid keys of
494
+ # a hash parameter or its internal structure. Just map to an empty hash:
495
+ #
496
+ # params.permit(preferences: {})
497
+ #
498
+ # Be careful because this opens the door to arbitrary input. In this
499
+ # case, +permit+ ensures values in the returned structure are permitted
500
+ # scalars and filters out anything else.
501
+ #
502
+ # You can also use +permit+ on nested parameters, like:
503
+ #
504
+ # params = ActionController::Parameters.new({
505
+ # person: {
506
+ # name: "Francesco",
507
+ # age: 22,
508
+ # pets: [{
509
+ # name: "Purplish",
510
+ # category: "dogs"
511
+ # }]
512
+ # }
513
+ # })
514
+ #
515
+ # permitted = params.permit(person: [ :name, { pets: :name } ])
516
+ # permitted.permitted? # => true
517
+ # permitted[:person][:name] # => "Francesco"
518
+ # permitted[:person][:age] # => nil
519
+ # permitted[:person][:pets][0][:name] # => "Purplish"
520
+ # permitted[:person][:pets][0][:category] # => nil
521
+ #
522
+ # Note that if you use +permit+ in a key that points to a hash,
523
+ # it won't allow all the hash. You also need to specify which
524
+ # attributes inside the hash should be permitted.
525
+ #
526
+ # params = ActionController::Parameters.new({
527
+ # person: {
528
+ # contact: {
529
+ # email: "none@test.com",
530
+ # phone: "555-1234"
531
+ # }
532
+ # }
533
+ # })
534
+ #
535
+ # params.require(:person).permit(:contact)
536
+ # # => <ActionController::Parameters {} permitted: true>
537
+ #
538
+ # params.require(:person).permit(contact: :phone)
539
+ # # => <ActionController::Parameters {"contact"=><ActionController::Parameters {"phone"=>"555-1234"} permitted: true>} permitted: true>
540
+ #
541
+ # params.require(:person).permit(contact: [ :email, :phone ])
542
+ # # => <ActionController::Parameters {"contact"=><ActionController::Parameters {"email"=>"none@test.com", "phone"=>"555-1234"} permitted: true>} permitted: true>
543
+ def permit(*filters)
544
+ params = self.class.new
545
+
546
+ filters.flatten.each do |filter|
547
+ case filter
548
+ when Symbol, String
549
+ permitted_scalar_filter(params, filter)
550
+ when Hash
551
+ hash_filter(params, filter)
552
+ end
553
+ end
554
+
555
+ unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters
556
+
557
+ params.permit!
558
+ end
559
+
560
+ # Returns a parameter for the given +key+. If not found,
561
+ # returns +nil+.
562
+ #
563
+ # params = ActionController::Parameters.new(person: { name: "Francesco" })
564
+ # params[:person] # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
565
+ # params[:none] # => nil
566
+ def [](key)
567
+ convert_hashes_to_parameters(key, @parameters[key])
568
+ end
569
+
570
+ # Assigns a value to a given +key+. The given key may still get filtered out
571
+ # when +permit+ is called.
572
+ def []=(key, value)
573
+ @parameters[key] = value
574
+ end
575
+
576
+ # Returns a parameter for the given +key+. If the +key+
577
+ # can't be found, there are several options: With no other arguments,
578
+ # it will raise an <tt>ActionController::ParameterMissing</tt> error;
579
+ # if a second argument is given, then that is returned (converted to an
580
+ # instance of ActionController::Parameters if possible); if a block
581
+ # is given, then that will be run and its result returned.
582
+ #
583
+ # params = ActionController::Parameters.new(person: { name: "Francesco" })
584
+ # params.fetch(:person) # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
585
+ # params.fetch(:none) # => ActionController::ParameterMissing: param is missing or the value is empty: none
586
+ # params.fetch(:none, {}) # => <ActionController::Parameters {} permitted: false>
587
+ # params.fetch(:none, "Francesco") # => "Francesco"
588
+ # params.fetch(:none) { "Francesco" } # => "Francesco"
589
+ def fetch(key, *args)
590
+ convert_value_to_parameters(
591
+ @parameters.fetch(key) {
592
+ if block_given?
593
+ yield
594
+ else
595
+ args.fetch(0) { raise ActionController::ParameterMissing.new(key) }
596
+ end
597
+ }
598
+ )
599
+ end
600
+
601
+ # Extracts the nested parameter from the given +keys+ by calling +dig+
602
+ # at each step. Returns +nil+ if any intermediate step is +nil+.
603
+ #
604
+ # params = ActionController::Parameters.new(foo: { bar: { baz: 1 } })
605
+ # params.dig(:foo, :bar, :baz) # => 1
606
+ # params.dig(:foo, :zot, :xyz) # => nil
607
+ #
608
+ # params2 = ActionController::Parameters.new(foo: [10, 11, 12])
609
+ # params2.dig(:foo, 1) # => 11
610
+ def dig(*keys)
611
+ convert_hashes_to_parameters(keys.first, @parameters[keys.first])
612
+ @parameters.dig(*keys)
613
+ end
614
+
615
+ # Returns a new <tt>ActionController::Parameters</tt> instance that
616
+ # includes only the given +keys+. If the given +keys+
617
+ # don't exist, returns an empty hash.
618
+ #
619
+ # params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
620
+ # params.slice(:a, :b) # => <ActionController::Parameters {"a"=>1, "b"=>2} permitted: false>
621
+ # params.slice(:d) # => <ActionController::Parameters {} permitted: false>
622
+ def slice(*keys)
623
+ new_instance_with_inherited_permitted_status(@parameters.slice(*keys))
624
+ end
625
+
626
+ # Returns current <tt>ActionController::Parameters</tt> instance which
627
+ # contains only the given +keys+.
628
+ def slice!(*keys)
629
+ @parameters.slice!(*keys)
630
+ self
631
+ end
632
+
633
+ # Returns a new <tt>ActionController::Parameters</tt> instance that
634
+ # filters out the given +keys+.
635
+ #
636
+ # params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
637
+ # params.except(:a, :b) # => <ActionController::Parameters {"c"=>3} permitted: false>
638
+ # params.except(:d) # => <ActionController::Parameters {"a"=>1, "b"=>2, "c"=>3} permitted: false>
639
+ def except(*keys)
640
+ new_instance_with_inherited_permitted_status(@parameters.except(*keys))
641
+ end
642
+
643
+ # Removes and returns the key/value pairs matching the given keys.
644
+ #
645
+ # params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
646
+ # params.extract!(:a, :b) # => <ActionController::Parameters {"a"=>1, "b"=>2} permitted: false>
647
+ # params # => <ActionController::Parameters {"c"=>3} permitted: false>
648
+ def extract!(*keys)
649
+ new_instance_with_inherited_permitted_status(@parameters.extract!(*keys))
650
+ end
651
+
652
+ # Returns a new <tt>ActionController::Parameters</tt> with the results of
653
+ # running +block+ once for every value. The keys are unchanged.
654
+ #
655
+ # params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
656
+ # params.transform_values { |x| x * 2 }
657
+ # # => <ActionController::Parameters {"a"=>2, "b"=>4, "c"=>6} permitted: false>
658
+ def transform_values
659
+ return to_enum(:transform_values) unless block_given?
660
+ new_instance_with_inherited_permitted_status(
661
+ @parameters.transform_values { |v| yield convert_value_to_parameters(v) }
662
+ )
663
+ end
664
+
665
+ # Performs values transformation and returns the altered
666
+ # <tt>ActionController::Parameters</tt> instance.
667
+ def transform_values!
668
+ return to_enum(:transform_values!) unless block_given?
669
+ @parameters.transform_values! { |v| yield convert_value_to_parameters(v) }
670
+ self
671
+ end
672
+
673
+ # Returns a new <tt>ActionController::Parameters</tt> instance with the
674
+ # results of running +block+ once for every key. The values are unchanged.
675
+ def transform_keys(&block)
676
+ return to_enum(:transform_keys) unless block_given?
677
+ new_instance_with_inherited_permitted_status(
678
+ @parameters.transform_keys(&block)
679
+ )
680
+ end
681
+
682
+ # Performs keys transformation and returns the altered
683
+ # <tt>ActionController::Parameters</tt> instance.
684
+ def transform_keys!(&block)
685
+ return to_enum(:transform_keys!) unless block_given?
686
+ @parameters.transform_keys!(&block)
687
+ self
688
+ end
689
+
690
+ # Deletes a key-value pair from +Parameters+ and returns the value. If
691
+ # +key+ is not found, returns +nil+ (or, with optional code block, yields
692
+ # +key+ and returns the result). Cf. +#extract!+, which returns the
693
+ # corresponding +ActionController::Parameters+ object.
694
+ def delete(key, &block)
695
+ convert_value_to_parameters(@parameters.delete(key, &block))
696
+ end
697
+
698
+ # Returns a new instance of <tt>ActionController::Parameters</tt> with only
699
+ # items that the block evaluates to true.
700
+ def select(&block)
701
+ new_instance_with_inherited_permitted_status(@parameters.select(&block))
702
+ end
703
+
704
+ # Equivalent to Hash#keep_if, but returns +nil+ if no changes were made.
705
+ def select!(&block)
706
+ @parameters.select!(&block)
707
+ self
708
+ end
709
+ alias_method :keep_if, :select!
710
+
711
+ # Returns a new instance of <tt>ActionController::Parameters</tt> with items
712
+ # that the block evaluates to true removed.
713
+ def reject(&block)
714
+ new_instance_with_inherited_permitted_status(@parameters.reject(&block))
715
+ end
716
+
717
+ # Removes items that the block evaluates to true and returns self.
718
+ def reject!(&block)
719
+ @parameters.reject!(&block)
720
+ self
721
+ end
722
+ alias_method :delete_if, :reject!
723
+
724
+ # Returns values that were assigned to the given +keys+. Note that all the
725
+ # +Hash+ objects will be converted to <tt>ActionController::Parameters</tt>.
726
+ def values_at(*keys)
727
+ convert_value_to_parameters(@parameters.values_at(*keys))
728
+ end
729
+
730
+ # Returns a new <tt>ActionController::Parameters</tt> with all keys from
731
+ # +other_hash+ merged into current hash.
732
+ def merge(other_hash)
733
+ new_instance_with_inherited_permitted_status(
734
+ @parameters.merge(other_hash.to_h)
735
+ )
736
+ end
737
+
738
+ # Returns current <tt>ActionController::Parameters</tt> instance with
739
+ # +other_hash+ merged into current hash.
740
+ def merge!(other_hash)
741
+ @parameters.merge!(other_hash.to_h)
742
+ self
743
+ end
744
+
745
+ # Returns a new <tt>ActionController::Parameters</tt> with all keys from
746
+ # current hash merged into +other_hash+.
747
+ def reverse_merge(other_hash)
748
+ new_instance_with_inherited_permitted_status(
749
+ other_hash.to_h.merge(@parameters)
750
+ )
751
+ end
752
+ alias_method :with_defaults, :reverse_merge
753
+
754
+ # Returns current <tt>ActionController::Parameters</tt> instance with
755
+ # current hash merged into +other_hash+.
756
+ def reverse_merge!(other_hash)
757
+ @parameters.merge!(other_hash.to_h) { |key, left, right| left }
758
+ self
759
+ end
760
+ alias_method :with_defaults!, :reverse_merge!
761
+
762
+ # This is required by ActiveModel attribute assignment, so that user can
763
+ # pass +Parameters+ to a mass assignment methods in a model. It should not
764
+ # matter as we are using +HashWithIndifferentAccess+ internally.
765
+ def stringify_keys # :nodoc:
766
+ dup
767
+ end
768
+
769
+ def inspect
770
+ "<#{self.class} #{@parameters} permitted: #{@permitted}>"
771
+ end
772
+
773
+ def self.hook_into_yaml_loading # :nodoc:
774
+ # Wire up YAML format compatibility with Rails 4.2 and Psych 2.0.8 and 2.0.9+.
775
+ # Makes the YAML parser call `init_with` when it encounters the keys below
776
+ # instead of trying its own parsing routines.
777
+ YAML.load_tags["!ruby/hash-with-ivars:ActionController::Parameters"] = name
778
+ YAML.load_tags["!ruby/hash:ActionController::Parameters"] = name
779
+ end
780
+ hook_into_yaml_loading
781
+
782
+ def init_with(coder) # :nodoc:
783
+ case coder.tag
784
+ when "!ruby/hash:ActionController::Parameters"
785
+ # YAML 2.0.8's format where hash instance variables weren't stored.
786
+ @parameters = coder.map.with_indifferent_access
787
+ @permitted = false
788
+ when "!ruby/hash-with-ivars:ActionController::Parameters"
789
+ # YAML 2.0.9's Hash subclass format where keys and values
790
+ # were stored under an elements hash and `permitted` within an ivars hash.
791
+ @parameters = coder.map["elements"].with_indifferent_access
792
+ @permitted = coder.map["ivars"][:@permitted]
793
+ when "!ruby/object:ActionController::Parameters"
794
+ # YAML's Object format. Only needed because of the format
795
+ # backwards compatibility above, otherwise equivalent to YAML's initialization.
796
+ @parameters, @permitted = coder.map["parameters"], coder.map["permitted"]
797
+ end
798
+ end
799
+
800
+ # Returns duplicate of object including all parameters.
801
+ def deep_dup
802
+ self.class.new(@parameters.deep_dup).tap do |duplicate|
803
+ duplicate.permitted = @permitted
804
+ end
805
+ end
806
+
807
+ protected
808
+ attr_reader :parameters
809
+
810
+ attr_writer :permitted
811
+
812
+ def fields_for_style?
813
+ @parameters.all? { |k, v| k =~ /\A-?\d+\z/ && (v.is_a?(Hash) || v.is_a?(Parameters)) }
814
+ end
815
+
816
+ private
817
+ def new_instance_with_inherited_permitted_status(hash)
818
+ self.class.new(hash).tap do |new_instance|
819
+ new_instance.permitted = @permitted
820
+ end
821
+ end
822
+
823
+ def convert_parameters_to_hashes(value, using)
824
+ case value
825
+ when Array
826
+ value.map { |v| convert_parameters_to_hashes(v, using) }
827
+ when Hash
828
+ value.transform_values do |v|
829
+ convert_parameters_to_hashes(v, using)
830
+ end.with_indifferent_access
831
+ when Parameters
832
+ value.send(using)
833
+ else
834
+ value
835
+ end
836
+ end
837
+
838
+ def convert_hashes_to_parameters(key, value)
839
+ converted = convert_value_to_parameters(value)
840
+ @parameters[key] = converted unless converted.equal?(value)
841
+ converted
842
+ end
843
+
844
+ def convert_value_to_parameters(value)
845
+ case value
846
+ when Array
847
+ return value if converted_arrays.member?(value)
848
+ converted = value.map { |_| convert_value_to_parameters(_) }
849
+ converted_arrays << converted
850
+ converted
851
+ when Hash
852
+ self.class.new(value)
853
+ else
854
+ value
855
+ end
856
+ end
857
+
858
+ def each_element(object)
859
+ case object
860
+ when Array
861
+ object.grep(Parameters).map { |el| yield el }.compact
862
+ when Parameters
863
+ if object.fields_for_style?
864
+ hash = object.class.new
865
+ object.each { |k, v| hash[k] = yield v }
866
+ hash
867
+ else
868
+ yield object
869
+ end
870
+ end
871
+ end
872
+
873
+ def unpermitted_parameters!(params)
874
+ unpermitted_keys = unpermitted_keys(params)
875
+ if unpermitted_keys.any?
876
+ case self.class.action_on_unpermitted_parameters
877
+ when :log
878
+ name = "unpermitted_parameters.action_controller"
879
+ ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys)
880
+ when :raise
881
+ raise ActionController::UnpermittedParameters.new(unpermitted_keys)
882
+ end
883
+ end
884
+ end
885
+
886
+ def unpermitted_keys(params)
887
+ keys - params.keys - always_permitted_parameters
888
+ end
889
+
890
+ #
891
+ # --- Filtering ----------------------------------------------------------
892
+ #
893
+
894
+ # This is a white list of permitted scalar types that includes the ones
895
+ # supported in XML and JSON requests.
896
+ #
897
+ # This list is in particular used to filter ordinary requests, String goes
898
+ # as first element to quickly short-circuit the common case.
899
+ #
900
+ # If you modify this collection please update the API of +permit+ above.
901
+ PERMITTED_SCALAR_TYPES = [
902
+ String,
903
+ Symbol,
904
+ NilClass,
905
+ Numeric,
906
+ TrueClass,
907
+ FalseClass,
908
+ Date,
909
+ Time,
910
+ # DateTimes are Dates, we document the type but avoid the redundant check.
911
+ StringIO,
912
+ IO,
913
+ ActionDispatch::Http::UploadedFile,
914
+ Rack::Test::UploadedFile,
915
+ ]
916
+
917
+ def permitted_scalar?(value)
918
+ PERMITTED_SCALAR_TYPES.any? { |type| value.is_a?(type) }
919
+ end
920
+
921
+ # Adds existing keys to the params if their values are scalar.
922
+ #
923
+ # For example:
924
+ #
925
+ # puts self.keys #=> ["zipcode(90210i)"]
926
+ # params = {}
927
+ #
928
+ # permitted_scalar_filter(params, "zipcode")
929
+ #
930
+ # puts params.keys # => ["zipcode"]
931
+ def permitted_scalar_filter(params, permitted_key)
932
+ permitted_key = permitted_key.to_s
933
+
934
+ if has_key?(permitted_key) && permitted_scalar?(self[permitted_key])
935
+ params[permitted_key] = self[permitted_key]
936
+ end
937
+
938
+ each_key do |key|
939
+ next unless key =~ /\(\d+[if]?\)\z/
940
+ next unless $~.pre_match == permitted_key
941
+
942
+ params[key] = self[key] if permitted_scalar?(self[key])
943
+ end
944
+ end
945
+
946
+ def array_of_permitted_scalars?(value)
947
+ if value.is_a?(Array) && value.all? { |element| permitted_scalar?(element) }
948
+ yield value
949
+ end
950
+ end
951
+
952
+ def non_scalar?(value)
953
+ value.is_a?(Array) || value.is_a?(Parameters)
954
+ end
955
+
956
+ EMPTY_ARRAY = []
957
+ EMPTY_HASH = {}
958
+ def hash_filter(params, filter)
959
+ filter = filter.with_indifferent_access
960
+
961
+ # Slicing filters out non-declared keys.
962
+ slice(*filter.keys).each do |key, value|
963
+ next unless value
964
+ next unless has_key? key
965
+
966
+ if filter[key] == EMPTY_ARRAY
967
+ # Declaration { comment_ids: [] }.
968
+ array_of_permitted_scalars?(self[key]) do |val|
969
+ params[key] = val
970
+ end
971
+ elsif filter[key] == EMPTY_HASH
972
+ # Declaration { preferences: {} }.
973
+ if value.is_a?(Parameters)
974
+ params[key] = permit_any_in_parameters(value)
975
+ end
976
+ elsif non_scalar?(value)
977
+ # Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
978
+ params[key] = each_element(value) do |element|
979
+ element.permit(*Array.wrap(filter[key]))
980
+ end
981
+ end
982
+ end
983
+ end
984
+
985
+ def permit_any_in_parameters(params)
986
+ self.class.new.tap do |sanitized|
987
+ params.each do |key, value|
988
+ case value
989
+ when ->(v) { permitted_scalar?(v) }
990
+ sanitized[key] = value
991
+ when Array
992
+ sanitized[key] = permit_any_in_array(value)
993
+ when Parameters
994
+ sanitized[key] = permit_any_in_parameters(value)
995
+ else
996
+ # Filter this one out.
997
+ end
998
+ end
999
+ end
1000
+ end
1001
+
1002
+ def permit_any_in_array(array)
1003
+ [].tap do |sanitized|
1004
+ array.each do |element|
1005
+ case element
1006
+ when ->(e) { permitted_scalar?(e) }
1007
+ sanitized << element
1008
+ when Parameters
1009
+ sanitized << permit_any_in_parameters(element)
1010
+ else
1011
+ # Filter this one out.
1012
+ end
1013
+ end
1014
+ end
1015
+ end
1016
+
1017
+ def initialize_copy(source)
1018
+ super
1019
+ @parameters = @parameters.dup
1020
+ end
1021
+ end
1022
+
1023
+ # == Strong \Parameters
1024
+ #
1025
+ # It provides an interface for protecting attributes from end-user
1026
+ # assignment. This makes Action Controller parameters forbidden
1027
+ # to be used in Active Model mass assignment until they have been explicitly
1028
+ # enumerated.
1029
+ #
1030
+ # In addition, parameters can be marked as required and flow through a
1031
+ # predefined raise/rescue flow to end up as a <tt>400 Bad Request</tt> with no
1032
+ # effort.
1033
+ #
1034
+ # class PeopleController < ActionController::Base
1035
+ # # Using "Person.create(params[:person])" would raise an
1036
+ # # ActiveModel::ForbiddenAttributesError exception because it'd
1037
+ # # be using mass assignment without an explicit permit step.
1038
+ # # This is the recommended form:
1039
+ # def create
1040
+ # Person.create(person_params)
1041
+ # end
1042
+ #
1043
+ # # This will pass with flying colors as long as there's a person key in the
1044
+ # # parameters, otherwise it'll raise an ActionController::ParameterMissing
1045
+ # # exception, which will get caught by ActionController::Base and turned
1046
+ # # into a 400 Bad Request reply.
1047
+ # def update
1048
+ # redirect_to current_account.people.find(params[:id]).tap { |person|
1049
+ # person.update!(person_params)
1050
+ # }
1051
+ # end
1052
+ #
1053
+ # private
1054
+ # # Using a private method to encapsulate the permissible parameters is
1055
+ # # a good pattern since you'll be able to reuse the same permit
1056
+ # # list between create and update. Also, you can specialize this method
1057
+ # # with per-user checking of permissible attributes.
1058
+ # def person_params
1059
+ # params.require(:person).permit(:name, :age)
1060
+ # end
1061
+ # end
1062
+ #
1063
+ # In order to use <tt>accepts_nested_attributes_for</tt> with Strong \Parameters, you
1064
+ # will need to specify which nested attributes should be permitted. You might want
1065
+ # to allow +:id+ and +:_destroy+, see ActiveRecord::NestedAttributes for more information.
1066
+ #
1067
+ # class Person
1068
+ # has_many :pets
1069
+ # accepts_nested_attributes_for :pets
1070
+ # end
1071
+ #
1072
+ # class PeopleController < ActionController::Base
1073
+ # def create
1074
+ # Person.create(person_params)
1075
+ # end
1076
+ #
1077
+ # ...
1078
+ #
1079
+ # private
1080
+ #
1081
+ # def person_params
1082
+ # # It's mandatory to specify the nested attributes that should be permitted.
1083
+ # # If you use `permit` with just the key that points to the nested attributes hash,
1084
+ # # it will return an empty hash.
1085
+ # params.require(:person).permit(:name, :age, pets_attributes: [ :id, :name, :category ])
1086
+ # end
1087
+ # end
1088
+ #
1089
+ # See ActionController::Parameters.require and ActionController::Parameters.permit
1090
+ # for more information.
1091
+ module StrongParameters
1092
+ # Returns a new ActionController::Parameters object that
1093
+ # has been instantiated with the <tt>request.parameters</tt>.
1094
+ def params
1095
+ @_params ||= Parameters.new(request.parameters)
1096
+ end
1097
+
1098
+ # Assigns the given +value+ to the +params+ hash. If +value+
1099
+ # is a Hash, this will create an ActionController::Parameters
1100
+ # object that has been instantiated with the given +value+ hash.
1101
+ def params=(value)
1102
+ @_params = value.is_a?(Hash) ? Parameters.new(value) : value
1103
+ end
1104
+ end
1105
+ end