actionpack 5.2.3

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