actionpack 7.1.5.1 → 8.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +308 -523
  3. data/README.rdoc +1 -1
  4. data/lib/abstract_controller/asset_paths.rb +6 -2
  5. data/lib/abstract_controller/base.rb +104 -105
  6. data/lib/abstract_controller/caching/fragments.rb +50 -53
  7. data/lib/abstract_controller/caching.rb +8 -3
  8. data/lib/abstract_controller/callbacks.rb +70 -62
  9. data/lib/abstract_controller/collector.rb +7 -7
  10. data/lib/abstract_controller/deprecator.rb +2 -0
  11. data/lib/abstract_controller/error.rb +2 -0
  12. data/lib/abstract_controller/helpers.rb +71 -84
  13. data/lib/abstract_controller/logger.rb +4 -1
  14. data/lib/abstract_controller/railties/routes_helpers.rb +2 -0
  15. data/lib/abstract_controller/rendering.rb +13 -13
  16. data/lib/abstract_controller/translation.rb +12 -13
  17. data/lib/abstract_controller/url_for.rb +8 -6
  18. data/lib/abstract_controller.rb +2 -0
  19. data/lib/action_controller/api/api_rendering.rb +2 -0
  20. data/lib/action_controller/api.rb +76 -72
  21. data/lib/action_controller/base.rb +199 -126
  22. data/lib/action_controller/caching.rb +16 -14
  23. data/lib/action_controller/deprecator.rb +2 -0
  24. data/lib/action_controller/form_builder.rb +21 -18
  25. data/lib/action_controller/log_subscriber.rb +23 -2
  26. data/lib/action_controller/metal/allow_browser.rb +133 -0
  27. data/lib/action_controller/metal/basic_implicit_render.rb +2 -0
  28. data/lib/action_controller/metal/conditional_get.rb +217 -175
  29. data/lib/action_controller/metal/content_security_policy.rb +25 -24
  30. data/lib/action_controller/metal/cookies.rb +4 -2
  31. data/lib/action_controller/metal/data_streaming.rb +72 -63
  32. data/lib/action_controller/metal/default_headers.rb +5 -3
  33. data/lib/action_controller/metal/etag_with_flash.rb +3 -1
  34. data/lib/action_controller/metal/etag_with_template_digest.rb +17 -15
  35. data/lib/action_controller/metal/exceptions.rb +16 -9
  36. data/lib/action_controller/metal/flash.rb +13 -14
  37. data/lib/action_controller/metal/head.rb +15 -11
  38. data/lib/action_controller/metal/helpers.rb +63 -55
  39. data/lib/action_controller/metal/http_authentication.rb +209 -201
  40. data/lib/action_controller/metal/implicit_render.rb +17 -15
  41. data/lib/action_controller/metal/instrumentation.rb +16 -14
  42. data/lib/action_controller/metal/live.rb +177 -128
  43. data/lib/action_controller/metal/logging.rb +6 -4
  44. data/lib/action_controller/metal/mime_responds.rb +151 -142
  45. data/lib/action_controller/metal/parameter_encoding.rb +34 -32
  46. data/lib/action_controller/metal/params_wrapper.rb +57 -59
  47. data/lib/action_controller/metal/permissions_policy.rb +22 -12
  48. data/lib/action_controller/metal/rate_limiting.rb +92 -0
  49. data/lib/action_controller/metal/redirecting.rb +213 -94
  50. data/lib/action_controller/metal/renderers.rb +78 -57
  51. data/lib/action_controller/metal/rendering.rb +111 -77
  52. data/lib/action_controller/metal/request_forgery_protection.rb +182 -143
  53. data/lib/action_controller/metal/rescue.rb +20 -9
  54. data/lib/action_controller/metal/streaming.rb +118 -195
  55. data/lib/action_controller/metal/strong_parameters.rb +720 -530
  56. data/lib/action_controller/metal/testing.rb +2 -0
  57. data/lib/action_controller/metal/url_for.rb +17 -15
  58. data/lib/action_controller/metal.rb +86 -60
  59. data/lib/action_controller/railtie.rb +36 -15
  60. data/lib/action_controller/railties/helpers.rb +2 -0
  61. data/lib/action_controller/renderer.rb +41 -36
  62. data/lib/action_controller/structured_event_subscriber.rb +116 -0
  63. data/lib/action_controller/template_assertions.rb +4 -2
  64. data/lib/action_controller/test_case.rb +160 -131
  65. data/lib/action_controller.rb +5 -1
  66. data/lib/action_dispatch/constants.rb +8 -0
  67. data/lib/action_dispatch/deprecator.rb +2 -0
  68. data/lib/action_dispatch/http/cache.rb +163 -35
  69. data/lib/action_dispatch/http/content_disposition.rb +2 -0
  70. data/lib/action_dispatch/http/content_security_policy.rb +54 -39
  71. data/lib/action_dispatch/http/filter_parameters.rb +14 -8
  72. data/lib/action_dispatch/http/filter_redirect.rb +22 -1
  73. data/lib/action_dispatch/http/headers.rb +22 -22
  74. data/lib/action_dispatch/http/mime_negotiation.rb +89 -41
  75. data/lib/action_dispatch/http/mime_type.rb +25 -21
  76. data/lib/action_dispatch/http/mime_types.rb +3 -0
  77. data/lib/action_dispatch/http/param_builder.rb +187 -0
  78. data/lib/action_dispatch/http/param_error.rb +26 -0
  79. data/lib/action_dispatch/http/parameters.rb +14 -12
  80. data/lib/action_dispatch/http/permissions_policy.rb +25 -36
  81. data/lib/action_dispatch/http/query_parser.rb +55 -0
  82. data/lib/action_dispatch/http/rack_cache.rb +2 -0
  83. data/lib/action_dispatch/http/request.rb +141 -92
  84. data/lib/action_dispatch/http/response.rb +137 -77
  85. data/lib/action_dispatch/http/upload.rb +18 -16
  86. data/lib/action_dispatch/http/url.rb +187 -89
  87. data/lib/action_dispatch/journey/formatter.rb +21 -9
  88. data/lib/action_dispatch/journey/gtg/builder.rb +4 -3
  89. data/lib/action_dispatch/journey/gtg/simulator.rb +34 -11
  90. data/lib/action_dispatch/journey/gtg/transition_table.rb +47 -53
  91. data/lib/action_dispatch/journey/nfa/dot.rb +2 -0
  92. data/lib/action_dispatch/journey/nodes/node.rb +8 -6
  93. data/lib/action_dispatch/journey/parser.rb +99 -195
  94. data/lib/action_dispatch/journey/path/pattern.rb +4 -1
  95. data/lib/action_dispatch/journey/route.rb +54 -38
  96. data/lib/action_dispatch/journey/router/utils.rb +22 -27
  97. data/lib/action_dispatch/journey/router.rb +63 -83
  98. data/lib/action_dispatch/journey/routes.rb +11 -2
  99. data/lib/action_dispatch/journey/scanner.rb +46 -42
  100. data/lib/action_dispatch/journey/visitors.rb +57 -23
  101. data/lib/action_dispatch/journey/visualizer/fsm.js +4 -6
  102. data/lib/action_dispatch/journey.rb +2 -0
  103. data/lib/action_dispatch/log_subscriber.rb +7 -1
  104. data/lib/action_dispatch/middleware/actionable_exceptions.rb +2 -0
  105. data/lib/action_dispatch/middleware/assume_ssl.rb +8 -5
  106. data/lib/action_dispatch/middleware/callbacks.rb +3 -1
  107. data/lib/action_dispatch/middleware/cookies.rb +125 -106
  108. data/lib/action_dispatch/middleware/debug_exceptions.rb +37 -8
  109. data/lib/action_dispatch/middleware/debug_locks.rb +15 -13
  110. data/lib/action_dispatch/middleware/debug_view.rb +13 -5
  111. data/lib/action_dispatch/middleware/exception_wrapper.rb +18 -23
  112. data/lib/action_dispatch/middleware/executor.rb +19 -4
  113. data/lib/action_dispatch/middleware/flash.rb +63 -51
  114. data/lib/action_dispatch/middleware/host_authorization.rb +17 -15
  115. data/lib/action_dispatch/middleware/public_exceptions.rb +14 -12
  116. data/lib/action_dispatch/middleware/reloader.rb +5 -3
  117. data/lib/action_dispatch/middleware/remote_ip.rb +87 -77
  118. data/lib/action_dispatch/middleware/request_id.rb +16 -10
  119. data/lib/action_dispatch/middleware/server_timing.rb +4 -2
  120. data/lib/action_dispatch/middleware/session/abstract_store.rb +2 -0
  121. data/lib/action_dispatch/middleware/session/cache_store.rb +30 -8
  122. data/lib/action_dispatch/middleware/session/cookie_store.rb +27 -26
  123. data/lib/action_dispatch/middleware/session/mem_cache_store.rb +7 -3
  124. data/lib/action_dispatch/middleware/show_exceptions.rb +16 -16
  125. data/lib/action_dispatch/middleware/ssl.rb +53 -40
  126. data/lib/action_dispatch/middleware/stack.rb +11 -10
  127. data/lib/action_dispatch/middleware/static.rb +33 -31
  128. data/lib/action_dispatch/middleware/templates/rescues/_copy_button.html.erb +1 -0
  129. data/lib/action_dispatch/middleware/templates/rescues/_source.html.erb +3 -5
  130. data/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb +9 -5
  131. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.html.erb +1 -0
  132. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb +1 -0
  133. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.html.erb +4 -0
  134. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.text.erb +3 -0
  135. data/lib/action_dispatch/middleware/templates/rescues/layout.erb +50 -0
  136. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.html.erb +1 -0
  137. data/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb +1 -0
  138. data/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb +1 -0
  139. data/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb +1 -0
  140. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb +1 -0
  141. data/lib/action_dispatch/middleware/templates/routes/_table.html.erb +1 -1
  142. data/lib/action_dispatch/railtie.rb +23 -3
  143. data/lib/action_dispatch/request/session.rb +24 -21
  144. data/lib/action_dispatch/request/utils.rb +11 -3
  145. data/lib/action_dispatch/routing/endpoint.rb +2 -0
  146. data/lib/action_dispatch/routing/inspector.rb +85 -60
  147. data/lib/action_dispatch/routing/mapper.rb +1031 -851
  148. data/lib/action_dispatch/routing/polymorphic_routes.rb +69 -62
  149. data/lib/action_dispatch/routing/redirection.rb +47 -39
  150. data/lib/action_dispatch/routing/route_set.rb +79 -56
  151. data/lib/action_dispatch/routing/routes_proxy.rb +7 -4
  152. data/lib/action_dispatch/routing/url_for.rb +130 -125
  153. data/lib/action_dispatch/routing.rb +150 -148
  154. data/lib/action_dispatch/structured_event_subscriber.rb +20 -0
  155. data/lib/action_dispatch/system_test_case.rb +91 -81
  156. data/lib/action_dispatch/system_testing/browser.rb +16 -23
  157. data/lib/action_dispatch/system_testing/driver.rb +2 -0
  158. data/lib/action_dispatch/system_testing/server.rb +2 -0
  159. data/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb +34 -23
  160. data/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb +2 -0
  161. data/lib/action_dispatch/testing/assertion_response.rb +9 -7
  162. data/lib/action_dispatch/testing/assertions/response.rb +52 -25
  163. data/lib/action_dispatch/testing/assertions/routing.rb +168 -87
  164. data/lib/action_dispatch/testing/assertions.rb +2 -0
  165. data/lib/action_dispatch/testing/integration.rb +233 -223
  166. data/lib/action_dispatch/testing/request_encoder.rb +11 -9
  167. data/lib/action_dispatch/testing/test_helpers/page_dump_helper.rb +35 -0
  168. data/lib/action_dispatch/testing/test_process.rb +11 -8
  169. data/lib/action_dispatch/testing/test_request.rb +3 -1
  170. data/lib/action_dispatch/testing/test_response.rb +27 -26
  171. data/lib/action_dispatch.rb +36 -32
  172. data/lib/action_pack/gem_version.rb +6 -4
  173. data/lib/action_pack/version.rb +3 -1
  174. data/lib/action_pack.rb +17 -16
  175. metadata +36 -32
  176. data/lib/action_dispatch/journey/parser.y +0 -50
  177. data/lib/action_dispatch/journey/parser_extras.rb +0 -31
@@ -1,37 +1,41 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # :markup: markdown
4
+
3
5
  require "ipaddr"
4
6
 
5
7
  module ActionDispatch
6
- # = Action Dispatch \RemoteIp
8
+ # # Action Dispatch RemoteIp
7
9
  #
8
- # This middleware calculates the IP address of the remote client that is
9
- # making the request. It does this by checking various headers that could
10
- # contain the address, and then picking the last-set address that is not
11
- # on the list of trusted IPs. This follows the precedent set by e.g.
12
- # {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453].
13
- # A more detailed explanation of the algorithm is given at GetIp#calculate_ip.
10
+ # This middleware calculates the IP address of the remote client that is making
11
+ # the request. It does this by checking various headers that could contain the
12
+ # address, and then picking the last-set address that is not on the list of
13
+ # trusted IPs. This follows the precedent set by e.g. [the Tomcat
14
+ # server](https://issues.apache.org/bugzilla/show_bug.cgi?id=50453). A more
15
+ # detailed explanation of the algorithm is given at GetIp#calculate_ip.
14
16
  #
15
- # Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2]
16
- # requires. Some Rack servers simply drop preceding headers, and only report
17
- # the value that was {given in the last header}[https://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers].
18
- # If you are behind multiple proxy servers (like NGINX to HAProxy to Unicorn)
19
- # then you should test your Rack server to make sure your data is good.
17
+ # Some Rack servers concatenate repeated headers, like [HTTP RFC
18
+ # 2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2) requires.
19
+ # Some Rack servers simply drop preceding headers, and only report the value
20
+ # that was [given in the last
21
+ # header](https://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers).
22
+ # If you are behind multiple proxy servers (like NGINX to HAProxy to
23
+ # Unicorn) then you should test your Rack server to make sure your data is good.
20
24
  #
21
- # IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING.
22
- # This middleware assumes that there is at least one proxy sitting around
23
- # and setting headers with the client's remote IP address. If you don't use
24
- # a proxy, because you are hosted on e.g. Heroku without SSL, any client can
25
- # claim to have any IP address by setting the +X-Forwarded-For+ header. If you
26
- # care about that, then you need to explicitly drop or ignore those headers
27
- # sometime before this middleware runs. Alternatively, remove this middleware
28
- # to avoid inadvertently relying on it.
25
+ # IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING. This
26
+ # middleware assumes that there is at least one proxy sitting around and setting
27
+ # headers with the client's remote IP address. If you don't use a proxy, because
28
+ # you are hosted on e.g. Heroku without SSL, any client can claim to have any IP
29
+ # address by setting the `X-Forwarded-For` header. If you care about that, then
30
+ # you need to explicitly drop or ignore those headers sometime before this
31
+ # middleware runs. Alternatively, remove this middleware to avoid inadvertently
32
+ # relying on it.
29
33
  class RemoteIp
30
34
  class IpSpoofAttackError < StandardError; end
31
35
 
32
- # The default trusted IPs list simply includes IP addresses that are
33
- # guaranteed by the IP specification to be private addresses. Those will
34
- # not be the ultimate client IP in production, and so are discarded. See
36
+ # The default trusted IPs list simply includes IP addresses that are guaranteed
37
+ # by the IP specification to be private addresses. Those will not be the
38
+ # ultimate client IP in production, and so are discarded. See
35
39
  # https://en.wikipedia.org/wiki/Private_network for details.
36
40
  TRUSTED_PROXIES = [
37
41
  "127.0.0.0/8", # localhost IPv4 range, per RFC-3330
@@ -40,24 +44,26 @@ module ActionDispatch
40
44
  "10.0.0.0/8", # private IPv4 range 10.x.x.x
41
45
  "172.16.0.0/12", # private IPv4 range 172.16.0.0 .. 172.31.255.255
42
46
  "192.168.0.0/16", # private IPv4 range 192.168.x.x
47
+ "169.254.0.0/16", # link-local IPv4 range 169.254.x.x
48
+ "fe80::/10", # link-local IPv6 range fe80::/10
43
49
  ].map { |proxy| IPAddr.new(proxy) }
44
50
 
45
51
  attr_reader :check_ip, :proxies
46
52
 
47
- # Create a new +RemoteIp+ middleware instance.
53
+ # Create a new `RemoteIp` middleware instance.
48
54
  #
49
- # The +ip_spoofing_check+ option is on by default. When on, an exception
50
- # is raised if it looks like the client is trying to lie about its own IP
51
- # address. It makes sense to turn off this check on sites aimed at non-IP
52
- # clients (like WAP devices), or behind proxies that set headers in an
53
- # incorrect or confusing way (like AWS ELB).
55
+ # The `ip_spoofing_check` option is on by default. When on, an exception is
56
+ # raised if it looks like the client is trying to lie about its own IP address.
57
+ # It makes sense to turn off this check on sites aimed at non-IP clients (like
58
+ # WAP devices), or behind proxies that set headers in an incorrect or confusing
59
+ # way (like AWS ELB).
54
60
  #
55
- # The +custom_proxies+ argument can take an enumerable which will be used
56
- # instead of +TRUSTED_PROXIES+. Any proxy setup will put the value you
57
- # want in the middle (or at the beginning) of the +X-Forwarded-For+ list,
58
- # with your proxy servers after it. If your proxies aren't removed, pass
59
- # them in via the +custom_proxies+ parameter. That way, the middleware will
60
- # ignore those IP addresses, and return the one that you want.
61
+ # The `custom_proxies` argument can take an enumerable which will be used
62
+ # instead of `TRUSTED_PROXIES`. Any proxy setup will put the value you want in
63
+ # the middle (or at the beginning) of the `X-Forwarded-For` list, with your
64
+ # proxy servers after it. If your proxies aren't removed, pass them in via the
65
+ # `custom_proxies` parameter. That way, the middleware will ignore those IP
66
+ # addresses, and return the one that you want.
61
67
  def initialize(app, ip_spoofing_check = true, custom_proxies = nil)
62
68
  @app = app
63
69
  @check_ip = ip_spoofing_check
@@ -82,19 +88,19 @@ module ActionDispatch
82
88
  end
83
89
  end
84
90
 
85
- # Since the IP address may not be needed, we store the object here
86
- # without calculating the IP to keep from slowing down the majority of
87
- # requests. For those requests that do need to know the IP, the
88
- # GetIp#calculate_ip method will calculate the memoized client IP address.
91
+ # Since the IP address may not be needed, we store the object here without
92
+ # calculating the IP to keep from slowing down the majority of requests. For
93
+ # those requests that do need to know the IP, the GetIp#calculate_ip method will
94
+ # calculate the memoized client IP address.
89
95
  def call(env)
90
96
  req = ActionDispatch::Request.new env
91
97
  req.remote_ip = GetIp.new(req, check_ip, proxies)
92
98
  @app.call(req.env)
93
99
  end
94
100
 
95
- # The GetIp class exists as a way to defer processing of the request data
96
- # into an actual IP address. If the ActionDispatch::Request#remote_ip method
97
- # is called, this class will calculate the value and then memoize it.
101
+ # The GetIp class exists as a way to defer processing of the request data into
102
+ # an actual IP address. If the ActionDispatch::Request#remote_ip method is
103
+ # called, this class will calculate the value and then memoize it.
98
104
  class GetIp
99
105
  def initialize(req, check_ip, proxies)
100
106
  @req = req
@@ -102,63 +108,64 @@ module ActionDispatch
102
108
  @proxies = proxies
103
109
  end
104
110
 
105
- # Sort through the various IP address headers, looking for the IP most
106
- # likely to be the address of the actual remote client making this
107
- # request.
111
+ # Sort through the various IP address headers, looking for the IP most likely to
112
+ # be the address of the actual remote client making this request.
108
113
  #
109
- # REMOTE_ADDR will be correct if the request is made directly against the
110
- # Ruby process, on e.g. Heroku. When the request is proxied by another
111
- # server like HAProxy or NGINX, the IP address that made the original
112
- # request will be put in an +X-Forwarded-For+ header. If there are multiple
113
- # proxies, that header may contain a list of IPs. Other proxy services
114
- # set the +Client-Ip+ header instead, so we check that too.
114
+ # REMOTE_ADDR will be correct if the request is made directly against the Ruby
115
+ # process, on e.g. Heroku. When the request is proxied by another server like
116
+ # HAProxy or NGINX, the IP address that made the original request will be put in
117
+ # an `X-Forwarded-For` header. If there are multiple proxies, that header may
118
+ # contain a list of IPs. Other proxy services set the `Client-Ip` header
119
+ # instead, so we check that too.
115
120
  #
116
- # As discussed in {this post about Rails IP Spoofing}[https://web.archive.org/web/20170626095448/https://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
117
- # while the first IP in the list is likely to be the "originating" IP,
118
- # it could also have been set by the client maliciously.
121
+ # As discussed in [this post about Rails IP
122
+ # Spoofing](https://web.archive.org/web/20170626095448/https://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/),
123
+ # while the first IP in the list is likely to be the "originating" IP, it
124
+ # could also have been set by the client maliciously.
119
125
  #
120
- # In order to find the first address that is (probably) accurate, we
121
- # take the list of IPs, remove known and trusted proxies, and then take
122
- # the last address left, which was presumably set by one of those proxies.
126
+ # In order to find the first address that is (probably) accurate, we take the
127
+ # list of IPs, remove known and trusted proxies, and then take the last address
128
+ # left, which was presumably set by one of those proxies.
123
129
  def calculate_ip
124
130
  # Set by the Rack web server, this is a single value.
125
- remote_addr = ips_from(@req.remote_addr).last
131
+ remote_addr = sanitize_ips(ips_from(@req.remote_addr)).last
126
132
 
127
133
  # Could be a CSV list and/or repeated headers that were concatenated.
128
- client_ips = ips_from(@req.client_ip).reverse!
129
- forwarded_ips = ips_from(@req.x_forwarded_for).reverse!
134
+ client_ips = sanitize_ips(ips_from(@req.client_ip)).reverse!
135
+ forwarded_ips = sanitize_ips(@req.forwarded_for || []).reverse!
130
136
 
131
- # +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
132
- # If they are both set, it means that either:
137
+ # `Client-Ip` and `X-Forwarded-For` should not, generally, both be set. If they
138
+ # are both set, it means that either:
133
139
  #
134
140
  # 1) This request passed through two proxies with incompatible IP header
135
- # conventions.
136
- # 2) The client passed one of +Client-Ip+ or +X-Forwarded-For+
137
- # (whichever the proxy servers weren't using) themselves.
141
+ # conventions.
142
+ #
143
+ # 2) The client passed one of `Client-Ip` or `X-Forwarded-For`
144
+ # (whichever the proxy servers weren't using) themselves.
138
145
  #
139
- # Either way, there is no way for us to determine which header is the
140
- # right one after the fact. Since we have no idea, if we are concerned
141
- # about IP spoofing we need to give up and explode. (If you're not
142
- # concerned about IP spoofing you can turn the +ip_spoofing_check+
143
- # option off.)
146
+ # Either way, there is no way for us to determine which header is the right one
147
+ # after the fact. Since we have no idea, if we are concerned about IP spoofing
148
+ # we need to give up and explode. (If you're not concerned about IP spoofing you
149
+ # can turn the `ip_spoofing_check` option off.)
144
150
  should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
145
151
  if should_check_ip && !forwarded_ips.include?(client_ips.last)
146
152
  # We don't know which came from the proxy, and which from the user
147
153
  raise IpSpoofAttackError, "IP spoofing attack?! " \
148
154
  "HTTP_CLIENT_IP=#{@req.client_ip.inspect} " \
149
- "HTTP_X_FORWARDED_FOR=#{@req.x_forwarded_for.inspect}"
155
+ "HTTP_X_FORWARDED_FOR=#{@req.x_forwarded_for.inspect}" \
156
+ " HTTP_FORWARDED=" + @req.forwarded_for.map { "for=#{_1}" }.join(", ").inspect if @req.forwarded_for.any?
150
157
  end
151
158
 
152
159
  # We assume these things about the IP headers:
153
160
  #
154
- # - X-Forwarded-For will be a list of IPs, one per proxy, or blank
155
- # - Client-Ip is propagated from the outermost proxy, or is blank
156
- # - REMOTE_ADDR will be the IP that made the request to Rack
161
+ # - X-Forwarded-For will be a list of IPs, one per proxy, or blank
162
+ # - Client-Ip is propagated from the outermost proxy, or is blank
163
+ # - REMOTE_ADDR will be the IP that made the request to Rack
157
164
  ips = forwarded_ips + client_ips
158
165
  ips.compact!
159
166
 
160
- # If every single IP option is in the trusted list, return the IP
161
- # that's furthest away
167
+ # If every single IP option is in the trusted list, return the IP that's
168
+ # furthest away
162
169
  filter_proxies(ips + [remote_addr]).first || ips.last || remote_addr
163
170
  end
164
171
 
@@ -172,7 +179,10 @@ module ActionDispatch
172
179
  def ips_from(header) # :doc:
173
180
  return [] unless header
174
181
  # Split the comma-separated list into an array of strings.
175
- ips = header.strip.split(/[,\s]+/)
182
+ header.strip.split(/[,\s]+/)
183
+ end
184
+
185
+ def sanitize_ips(ips) # :doc:
176
186
  ips.select! do |ip|
177
187
  # Only return IPs that are valid according to the IPAddr#new method.
178
188
  range = IPAddr.new(ip).to_range
@@ -1,30 +1,36 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # :markup: markdown
4
+
3
5
  require "securerandom"
4
6
  require "active_support/core_ext/string/access"
5
7
 
6
8
  module ActionDispatch
7
- # = Action Dispatch \RequestId
9
+ # # Action Dispatch RequestId
8
10
  #
9
- # Makes a unique request id available to the +action_dispatch.request_id+ env variable (which is then accessible
10
- # through ActionDispatch::Request#request_id or the alias ActionDispatch::Request#uuid) and sends
11
- # the same id to the client via the +X-Request-Id+ header.
11
+ # Makes a unique request id available to the `action_dispatch.request_id` env
12
+ # variable (which is then accessible through ActionDispatch::Request#request_id
13
+ # or the alias ActionDispatch::Request#uuid) and sends the same id to the client
14
+ # via the `X-Request-Id` header.
12
15
  #
13
- # The unique request id is either based on the +X-Request-Id+ header in the request, which would typically be generated
14
- # by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the
15
- # header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only.
16
+ # The unique request id is either based on the `X-Request-Id` header in the
17
+ # request, which would typically be generated by a firewall, load balancer, or
18
+ # the web server, or, if this header is not available, a random uuid. If the
19
+ # header is accepted from the outside world, we sanitize it to a max of 255
20
+ # chars and alphanumeric and dashes only.
16
21
  #
17
- # The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
18
- # from multiple pieces of the stack.
22
+ # The unique request id can be used to trace a request end-to-end and would
23
+ # typically end up being part of log files from multiple pieces of the stack.
19
24
  class RequestId
20
25
  def initialize(app, header:)
21
26
  @app = app
22
27
  @header = header
28
+ @env_header = "HTTP_#{header.upcase.tr("-", "_")}"
23
29
  end
24
30
 
25
31
  def call(env)
26
32
  req = ActionDispatch::Request.new env
27
- req.request_id = make_request_id(req.headers[@header])
33
+ req.request_id = make_request_id(req.get_header(@env_header))
28
34
  @app.call(env).tap { |_status, headers, _body| headers[@header] = req.request_id }
29
35
  end
30
36
 
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # :markup: markdown
4
+
3
5
  require "active_support/notifications"
4
6
 
5
7
  module ActionDispatch
@@ -29,8 +31,8 @@ module ActionDispatch
29
31
 
30
32
  def ensure_subscribed
31
33
  @mutex.synchronize do
32
- # Subscribe to all events, except those beginning with "!"
33
- # Ideally we would be more selective of what is being measured
34
+ # Subscribe to all events, except those beginning with "!" Ideally we would be
35
+ # more selective of what is being measured
34
36
  @subscriber ||= ActiveSupport::Notifications.subscribe(/\A[^!]/, self)
35
37
  end
36
38
  end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # :markup: markdown
4
+
3
5
  require "rack/utils"
4
6
  require "rack/request"
5
7
  require "rack/session/abstract/id"
@@ -1,23 +1,33 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # :markup: markdown
4
+
3
5
  require "action_dispatch/middleware/session/abstract_store"
4
6
 
5
7
  module ActionDispatch
6
8
  module Session
7
- # = Action Dispatch Session \CacheStore
9
+ # # Action Dispatch Session CacheStore
10
+ #
11
+ # A session store that uses an ActiveSupport::Cache::Store to store the
12
+ # sessions. This store is most useful if you don't store critical data in your
13
+ # sessions and you don't need them to live for extended periods of time.
8
14
  #
9
- # A session store that uses an ActiveSupport::Cache::Store to store the sessions. This store is most useful
10
- # if you don't store critical data in your sessions and you don't need them to live for extended periods
11
- # of time.
15
+ # #### Options
16
+ # * `cache` - The cache to use. If it is not specified, `Rails.cache`
17
+ # will be used.
18
+ # * `expire_after` - The length of time a session will be stored before
19
+ # automatically expiring. By default, the `:expires_in` option of the cache
20
+ # is used.
21
+ # * `check_collisions` - Check if newly generated session ids aren't already in use.
22
+ # If for some reason 128 bits of randomness aren't considered secure enough to avoid
23
+ # collisions, this option can be enabled to ensure newly generated ids aren't in use.
24
+ # By default, it is set to `false` to avoid additional cache write operations.
12
25
  #
13
- # ==== Options
14
- # * <tt>cache</tt> - The cache to use. If it is not specified, <tt>Rails.cache</tt> will be used.
15
- # * <tt>expire_after</tt> - The length of time a session will be stored before automatically expiring.
16
- # By default, the <tt>:expires_in</tt> option of the cache is used.
17
26
  class CacheStore < AbstractSecureStore
18
27
  def initialize(app, options = {})
19
28
  @cache = options[:cache] || Rails.cache
20
29
  options[:expire_after] ||= @cache.options[:expires_in]
30
+ @check_collisions = options[:check_collisions] || false
21
31
  super
22
32
  end
23
33
 
@@ -56,6 +66,18 @@ module ActionDispatch
56
66
  def get_session_with_fallback(sid)
57
67
  @cache.read(cache_key(sid.private_id)) || @cache.read(cache_key(sid.public_id))
58
68
  end
69
+
70
+ def generate_sid
71
+ if @check_collisions
72
+ loop do
73
+ sid = super
74
+ key = cache_key(sid.private_id)
75
+ break sid if @cache.write(key, {}, unless_exist: true, expires_in: default_options[:expire_after])
76
+ end
77
+ else
78
+ super
79
+ end
80
+ end
59
81
  end
60
82
  end
61
83
  end
@@ -1,53 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # :markup: markdown
4
+
3
5
  require "active_support/core_ext/hash/keys"
4
6
  require "action_dispatch/middleware/session/abstract_store"
5
7
  require "rack/session/cookie"
6
8
 
7
9
  module ActionDispatch
8
10
  module Session
9
- # = Action Dispatch Session \CookieStore
11
+ # # Action Dispatch Session CookieStore
10
12
  #
11
- # This cookie-based session store is the \Rails default. It is
12
- # dramatically faster than the alternatives.
13
+ # This cookie-based session store is the Rails default. It is dramatically
14
+ # faster than the alternatives.
13
15
  #
14
16
  # Sessions typically contain at most a user ID and flash message; both fit
15
- # within the 4096 bytes cookie size limit. A +CookieOverflow+ exception is raised if
16
- # you attempt to store more than 4096 bytes of data.
17
+ # within the 4096 bytes cookie size limit. A `CookieOverflow` exception is
18
+ # raised if you attempt to store more than 4096 bytes of data.
17
19
  #
18
- # The cookie jar used for storage is automatically configured to be the
19
- # best possible option given your application's configuration.
20
+ # The cookie jar used for storage is automatically configured to be the best
21
+ # possible option given your application's configuration.
20
22
  #
21
- # Your cookies will be encrypted using your application's +secret_key_base+. This
22
- # goes a step further than signed cookies in that encrypted cookies cannot
23
- # be altered or read by users. This is the default starting in \Rails 4.
23
+ # Your cookies will be encrypted using your application's `secret_key_base`.
24
+ # This goes a step further than signed cookies in that encrypted cookies cannot
25
+ # be altered or read by users. This is the default starting in Rails 4.
24
26
  #
25
27
  # Configure your session store in an initializer:
26
28
  #
27
- # Rails.application.config.session_store :cookie_store, key: '_your_app_session'
29
+ # Rails.application.config.session_store :cookie_store, key: '_your_app_session'
28
30
  #
29
- # In the development and test environments your application's +secret_key_base+ is
30
- # generated by \Rails and stored in a temporary file in <tt>tmp/local_secret.txt</tt>.
31
- # In all other environments, it is stored encrypted in the
32
- # <tt>config/credentials.yml.enc</tt> file.
31
+ # In the development and test environments your application's `secret_key_base`
32
+ # is generated by Rails and stored in a temporary file in
33
+ # `tmp/local_secret.txt`. In all other environments, it is stored encrypted in
34
+ # the `config/credentials.yml.enc` file.
33
35
  #
34
- # If your application was not updated to \Rails 5.2 defaults, the +secret_key_base+
35
- # will be found in the old <tt>config/secrets.yml</tt> file.
36
+ # If your application was not updated to Rails 5.2 defaults, the
37
+ # `secret_key_base` will be found in the old `config/secrets.yml` file.
36
38
  #
37
- # Note that changing your +secret_key_base+ will invalidate all existing session.
38
- # Additionally, you should take care to make sure you are not relying on the
39
- # ability to decode signed cookies generated by your app in external
39
+ # Note that changing your `secret_key_base` will invalidate all existing
40
+ # session. Additionally, you should take care to make sure you are not relying
41
+ # on the ability to decode signed cookies generated by your app in external
40
42
  # applications or JavaScript before changing it.
41
43
  #
42
- # Because CookieStore extends +Rack::Session::Abstract::Persisted+, many of the
43
- # options described there can be used to customize the session cookie that
44
- # is generated. For example:
44
+ # Because CookieStore extends `Rack::Session::Abstract::Persisted`, many of the
45
+ # options described there can be used to customize the session cookie that is
46
+ # generated. For example:
45
47
  #
46
- # Rails.application.config.session_store :cookie_store, expire_after: 14.days
48
+ # Rails.application.config.session_store :cookie_store, expire_after: 14.days
47
49
  #
48
50
  # would set the session cookie to expire automatically 14 days after creation.
49
- # Other useful options include <tt>:key</tt>, <tt>:secure</tt>,
50
- # <tt>:httponly</tt>, and <tt>:same_site</tt>.
51
+ # Other useful options include `:key`, `:secure`, `:httponly`, and `:same_site`.
51
52
  class CookieStore < AbstractSecureStore
52
53
  class SessionId < DelegateClass(Rack::Session::SessionId)
53
54
  attr_reader :cookie_value
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # :markup: markdown
4
+
3
5
  require "action_dispatch/middleware/session/abstract_store"
4
6
  begin
5
7
  require "rack/session/dalli"
@@ -10,12 +12,14 @@ end
10
12
 
11
13
  module ActionDispatch
12
14
  module Session
13
- # = Action Dispatch Session \MemCacheStore
15
+ # # Action Dispatch Session MemCacheStore
14
16
  #
15
17
  # A session store that uses MemCache to implement storage.
16
18
  #
17
- # ==== Options
18
- # * <tt>expire_after</tt> - The length of time a session will be stored before automatically expiring.
19
+ # #### Options
20
+ # * `expire_after` - The length of time a session will be stored before
21
+ # automatically expiring.
22
+ #
19
23
  class MemCacheStore < Rack::Session::Dalli
20
24
  include Compatibility
21
25
  include StaleSessionCheck
@@ -1,26 +1,27 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # :markup: markdown
4
+
3
5
  require "action_dispatch/middleware/exception_wrapper"
4
6
 
5
7
  module ActionDispatch
6
- # = Action Dispatch \ShowExceptions
8
+ # # Action Dispatch ShowExceptions
7
9
  #
8
- # This middleware rescues any exception returned by the application
9
- # and calls an exceptions app that will wrap it in a format for the end user.
10
+ # This middleware rescues any exception returned by the application and calls an
11
+ # exceptions app that will wrap it in a format for the end user.
10
12
  #
11
13
  # The exceptions app should be passed as a parameter on initialization of
12
- # +ShowExceptions+. Every time there is an exception, +ShowExceptions+ will
13
- # store the exception in <tt>env["action_dispatch.exception"]</tt>, rewrite
14
- # the +PATH_INFO+ to the exception status code, and call the Rack app.
14
+ # `ShowExceptions`. Every time there is an exception, `ShowExceptions` will
15
+ # store the exception in `env["action_dispatch.exception"]`, rewrite the
16
+ # `PATH_INFO` to the exception status code, and call the Rack app.
15
17
  #
16
- # In \Rails applications, the exceptions app can be configured with
17
- # +config.exceptions_app+, which defaults to ActionDispatch::PublicExceptions.
18
+ # In Rails applications, the exceptions app can be configured with
19
+ # `config.exceptions_app`, which defaults to ActionDispatch::PublicExceptions.
18
20
  #
19
- # If the application returns a response with the <tt>X-Cascade</tt> header
20
- # set to <tt>"pass"</tt>, this middleware will send an empty response as a
21
- # result with the correct status code. If any exception happens inside the
22
- # exceptions app, this middleware catches the exceptions and returns a
23
- # failsafe response.
21
+ # If the application returns a response with the `X-Cascade` header set to
22
+ # `"pass"`, this middleware will send an empty response as a result with the
23
+ # correct status code. If any exception happens inside the exceptions app, this
24
+ # middleware catches the exceptions and returns a failsafe response.
24
25
  class ShowExceptions
25
26
  def initialize(app, exceptions_app)
26
27
  @app = app
@@ -64,9 +65,8 @@ module ActionDispatch
64
65
  end
65
66
 
66
67
  def fallback_to_html_format_if_invalid_mime_type(request)
67
- # If the MIME type for the request is invalid then the
68
- # @exceptions_app may not be able to handle it. To make it
69
- # easier to handle, we switch to HTML.
68
+ # If the MIME type for the request is invalid then the @exceptions_app may not
69
+ # be able to handle it. To make it easier to handle, we switch to HTML.
70
70
  begin
71
71
  request.content_mime_type
72
72
  rescue ActionDispatch::Http::MimeNegotiation::InvalidType