actionpack 6.0.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of actionpack might be problematic. Click here for more details.

Files changed (181) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +311 -0
  3. data/MIT-LICENSE +21 -0
  4. data/README.rdoc +58 -0
  5. data/lib/abstract_controller.rb +27 -0
  6. data/lib/abstract_controller/asset_paths.rb +12 -0
  7. data/lib/abstract_controller/base.rb +267 -0
  8. data/lib/abstract_controller/caching.rb +66 -0
  9. data/lib/abstract_controller/caching/fragments.rb +150 -0
  10. data/lib/abstract_controller/callbacks.rb +224 -0
  11. data/lib/abstract_controller/collector.rb +43 -0
  12. data/lib/abstract_controller/error.rb +6 -0
  13. data/lib/abstract_controller/helpers.rb +194 -0
  14. data/lib/abstract_controller/logger.rb +14 -0
  15. data/lib/abstract_controller/railties/routes_helpers.rb +20 -0
  16. data/lib/abstract_controller/rendering.rb +127 -0
  17. data/lib/abstract_controller/translation.rb +32 -0
  18. data/lib/abstract_controller/url_for.rb +35 -0
  19. data/lib/action_controller.rb +67 -0
  20. data/lib/action_controller/api.rb +150 -0
  21. data/lib/action_controller/api/api_rendering.rb +16 -0
  22. data/lib/action_controller/base.rb +271 -0
  23. data/lib/action_controller/caching.rb +46 -0
  24. data/lib/action_controller/form_builder.rb +50 -0
  25. data/lib/action_controller/log_subscriber.rb +81 -0
  26. data/lib/action_controller/metal.rb +256 -0
  27. data/lib/action_controller/metal/basic_implicit_render.rb +13 -0
  28. data/lib/action_controller/metal/conditional_get.rb +280 -0
  29. data/lib/action_controller/metal/content_security_policy.rb +52 -0
  30. data/lib/action_controller/metal/cookies.rb +16 -0
  31. data/lib/action_controller/metal/data_streaming.rb +151 -0
  32. data/lib/action_controller/metal/default_headers.rb +17 -0
  33. data/lib/action_controller/metal/etag_with_flash.rb +18 -0
  34. data/lib/action_controller/metal/etag_with_template_digest.rb +57 -0
  35. data/lib/action_controller/metal/exceptions.rb +74 -0
  36. data/lib/action_controller/metal/flash.rb +61 -0
  37. data/lib/action_controller/metal/force_ssl.rb +58 -0
  38. data/lib/action_controller/metal/head.rb +60 -0
  39. data/lib/action_controller/metal/helpers.rb +122 -0
  40. data/lib/action_controller/metal/http_authentication.rb +518 -0
  41. data/lib/action_controller/metal/implicit_render.rb +63 -0
  42. data/lib/action_controller/metal/instrumentation.rb +105 -0
  43. data/lib/action_controller/metal/live.rb +314 -0
  44. data/lib/action_controller/metal/mime_responds.rb +324 -0
  45. data/lib/action_controller/metal/parameter_encoding.rb +51 -0
  46. data/lib/action_controller/metal/params_wrapper.rb +297 -0
  47. data/lib/action_controller/metal/redirecting.rb +133 -0
  48. data/lib/action_controller/metal/renderers.rb +181 -0
  49. data/lib/action_controller/metal/rendering.rb +122 -0
  50. data/lib/action_controller/metal/request_forgery_protection.rb +456 -0
  51. data/lib/action_controller/metal/rescue.rb +28 -0
  52. data/lib/action_controller/metal/streaming.rb +223 -0
  53. data/lib/action_controller/metal/strong_parameters.rb +1105 -0
  54. data/lib/action_controller/metal/testing.rb +16 -0
  55. data/lib/action_controller/metal/url_for.rb +58 -0
  56. data/lib/action_controller/railtie.rb +89 -0
  57. data/lib/action_controller/railties/helpers.rb +24 -0
  58. data/lib/action_controller/renderer.rb +130 -0
  59. data/lib/action_controller/template_assertions.rb +11 -0
  60. data/lib/action_controller/test_case.rb +626 -0
  61. data/lib/action_dispatch.rb +114 -0
  62. data/lib/action_dispatch/http/cache.rb +226 -0
  63. data/lib/action_dispatch/http/content_disposition.rb +45 -0
  64. data/lib/action_dispatch/http/content_security_policy.rb +284 -0
  65. data/lib/action_dispatch/http/filter_parameters.rb +86 -0
  66. data/lib/action_dispatch/http/filter_redirect.rb +37 -0
  67. data/lib/action_dispatch/http/headers.rb +132 -0
  68. data/lib/action_dispatch/http/mime_negotiation.rb +177 -0
  69. data/lib/action_dispatch/http/mime_type.rb +350 -0
  70. data/lib/action_dispatch/http/mime_types.rb +50 -0
  71. data/lib/action_dispatch/http/parameter_filter.rb +12 -0
  72. data/lib/action_dispatch/http/parameters.rb +136 -0
  73. data/lib/action_dispatch/http/rack_cache.rb +63 -0
  74. data/lib/action_dispatch/http/request.rb +427 -0
  75. data/lib/action_dispatch/http/response.rb +534 -0
  76. data/lib/action_dispatch/http/upload.rb +92 -0
  77. data/lib/action_dispatch/http/url.rb +350 -0
  78. data/lib/action_dispatch/journey.rb +7 -0
  79. data/lib/action_dispatch/journey/formatter.rb +189 -0
  80. data/lib/action_dispatch/journey/gtg/builder.rb +164 -0
  81. data/lib/action_dispatch/journey/gtg/simulator.rb +41 -0
  82. data/lib/action_dispatch/journey/gtg/transition_table.rb +158 -0
  83. data/lib/action_dispatch/journey/nfa/builder.rb +78 -0
  84. data/lib/action_dispatch/journey/nfa/dot.rb +36 -0
  85. data/lib/action_dispatch/journey/nfa/simulator.rb +47 -0
  86. data/lib/action_dispatch/journey/nfa/transition_table.rb +120 -0
  87. data/lib/action_dispatch/journey/nodes/node.rb +141 -0
  88. data/lib/action_dispatch/journey/parser.rb +199 -0
  89. data/lib/action_dispatch/journey/parser.y +50 -0
  90. data/lib/action_dispatch/journey/parser_extras.rb +31 -0
  91. data/lib/action_dispatch/journey/path/pattern.rb +203 -0
  92. data/lib/action_dispatch/journey/route.rb +204 -0
  93. data/lib/action_dispatch/journey/router.rb +153 -0
  94. data/lib/action_dispatch/journey/router/utils.rb +102 -0
  95. data/lib/action_dispatch/journey/routes.rb +81 -0
  96. data/lib/action_dispatch/journey/scanner.rb +71 -0
  97. data/lib/action_dispatch/journey/visitors.rb +268 -0
  98. data/lib/action_dispatch/journey/visualizer/fsm.css +30 -0
  99. data/lib/action_dispatch/journey/visualizer/fsm.js +134 -0
  100. data/lib/action_dispatch/journey/visualizer/index.html.erb +52 -0
  101. data/lib/action_dispatch/middleware/actionable_exceptions.rb +39 -0
  102. data/lib/action_dispatch/middleware/callbacks.rb +34 -0
  103. data/lib/action_dispatch/middleware/cookies.rb +663 -0
  104. data/lib/action_dispatch/middleware/debug_exceptions.rb +185 -0
  105. data/lib/action_dispatch/middleware/debug_locks.rb +124 -0
  106. data/lib/action_dispatch/middleware/debug_view.rb +68 -0
  107. data/lib/action_dispatch/middleware/exception_wrapper.rb +181 -0
  108. data/lib/action_dispatch/middleware/executor.rb +21 -0
  109. data/lib/action_dispatch/middleware/flash.rb +300 -0
  110. data/lib/action_dispatch/middleware/host_authorization.rb +103 -0
  111. data/lib/action_dispatch/middleware/public_exceptions.rb +61 -0
  112. data/lib/action_dispatch/middleware/reloader.rb +12 -0
  113. data/lib/action_dispatch/middleware/remote_ip.rb +181 -0
  114. data/lib/action_dispatch/middleware/request_id.rb +43 -0
  115. data/lib/action_dispatch/middleware/session/abstract_store.rb +92 -0
  116. data/lib/action_dispatch/middleware/session/cache_store.rb +54 -0
  117. data/lib/action_dispatch/middleware/session/cookie_store.rb +113 -0
  118. data/lib/action_dispatch/middleware/session/mem_cache_store.rb +28 -0
  119. data/lib/action_dispatch/middleware/show_exceptions.rb +62 -0
  120. data/lib/action_dispatch/middleware/ssl.rb +150 -0
  121. data/lib/action_dispatch/middleware/stack.rb +148 -0
  122. data/lib/action_dispatch/middleware/static.rb +129 -0
  123. data/lib/action_dispatch/middleware/templates/rescues/_actions.html.erb +13 -0
  124. data/lib/action_dispatch/middleware/templates/rescues/_actions.text.erb +0 -0
  125. data/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb +24 -0
  126. data/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb +23 -0
  127. data/lib/action_dispatch/middleware/templates/rescues/_source.html.erb +29 -0
  128. data/lib/action_dispatch/middleware/templates/rescues/_source.text.erb +8 -0
  129. data/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb +62 -0
  130. data/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb +9 -0
  131. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.html.erb +7 -0
  132. data/lib/action_dispatch/middleware/templates/rescues/blocked_host.text.erb +5 -0
  133. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb +38 -0
  134. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb +9 -0
  135. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.html.erb +24 -0
  136. data/lib/action_dispatch/middleware/templates/rescues/invalid_statement.text.erb +15 -0
  137. data/lib/action_dispatch/middleware/templates/rescues/layout.erb +165 -0
  138. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.html.erb +19 -0
  139. data/lib/action_dispatch/middleware/templates/rescues/missing_exact_template.text.erb +3 -0
  140. data/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb +11 -0
  141. data/lib/action_dispatch/middleware/templates/rescues/missing_template.text.erb +3 -0
  142. data/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb +32 -0
  143. data/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb +11 -0
  144. data/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb +20 -0
  145. data/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb +7 -0
  146. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb +6 -0
  147. data/lib/action_dispatch/middleware/templates/rescues/unknown_action.text.erb +3 -0
  148. data/lib/action_dispatch/middleware/templates/routes/_route.html.erb +16 -0
  149. data/lib/action_dispatch/middleware/templates/routes/_table.html.erb +203 -0
  150. data/lib/action_dispatch/railtie.rb +58 -0
  151. data/lib/action_dispatch/request/session.rb +242 -0
  152. data/lib/action_dispatch/request/utils.rb +78 -0
  153. data/lib/action_dispatch/routing.rb +261 -0
  154. data/lib/action_dispatch/routing/endpoint.rb +17 -0
  155. data/lib/action_dispatch/routing/inspector.rb +274 -0
  156. data/lib/action_dispatch/routing/mapper.rb +2289 -0
  157. data/lib/action_dispatch/routing/polymorphic_routes.rb +351 -0
  158. data/lib/action_dispatch/routing/redirection.rb +201 -0
  159. data/lib/action_dispatch/routing/route_set.rb +887 -0
  160. data/lib/action_dispatch/routing/routes_proxy.rb +69 -0
  161. data/lib/action_dispatch/routing/url_for.rb +237 -0
  162. data/lib/action_dispatch/system_test_case.rb +168 -0
  163. data/lib/action_dispatch/system_testing/browser.rb +80 -0
  164. data/lib/action_dispatch/system_testing/driver.rb +68 -0
  165. data/lib/action_dispatch/system_testing/server.rb +31 -0
  166. data/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb +97 -0
  167. data/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb +33 -0
  168. data/lib/action_dispatch/system_testing/test_helpers/undef_methods.rb +26 -0
  169. data/lib/action_dispatch/testing/assertion_response.rb +47 -0
  170. data/lib/action_dispatch/testing/assertions.rb +24 -0
  171. data/lib/action_dispatch/testing/assertions/response.rb +106 -0
  172. data/lib/action_dispatch/testing/assertions/routing.rb +234 -0
  173. data/lib/action_dispatch/testing/integration.rb +659 -0
  174. data/lib/action_dispatch/testing/request_encoder.rb +55 -0
  175. data/lib/action_dispatch/testing/test_process.rb +50 -0
  176. data/lib/action_dispatch/testing/test_request.rb +71 -0
  177. data/lib/action_dispatch/testing/test_response.rb +25 -0
  178. data/lib/action_pack.rb +26 -0
  179. data/lib/action_pack/gem_version.rb +17 -0
  180. data/lib/action_pack/version.rb +10 -0
  181. metadata +329 -0
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActionDispatch
4
+ # ActionDispatch::Reloader wraps the request with callbacks provided by ActiveSupport::Reloader
5
+ # callbacks, intended to assist with code reloading during development.
6
+ #
7
+ # By default, ActionDispatch::Reloader is included in the middleware stack
8
+ # only in the development environment; specifically, when +config.cache_classes+
9
+ # is false.
10
+ class Reloader < Executor
11
+ end
12
+ end
@@ -0,0 +1,181 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+
5
+ module ActionDispatch
6
+ # This middleware calculates the IP address of the remote client that is
7
+ # making the request. It does this by checking various headers that could
8
+ # contain the address, and then picking the last-set address that is not
9
+ # on the list of trusted IPs. This follows the precedent set by e.g.
10
+ # {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453],
11
+ # with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection]
12
+ # by @gingerlime. A more detailed explanation of the algorithm is given
13
+ # at GetIp#calculate_ip.
14
+ #
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}[http://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.
20
+ #
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.
28
+ class RemoteIp
29
+ class IpSpoofAttackError < StandardError; end
30
+
31
+ # The default trusted IPs list simply includes IP addresses that are
32
+ # guaranteed by the IP specification to be private addresses. Those will
33
+ # not be the ultimate client IP in production, and so are discarded. See
34
+ # https://en.wikipedia.org/wiki/Private_network for details.
35
+ TRUSTED_PROXIES = [
36
+ "127.0.0.1", # localhost IPv4
37
+ "::1", # localhost IPv6
38
+ "fc00::/7", # private IPv6 range fc00::/7
39
+ "10.0.0.0/8", # private IPv4 range 10.x.x.x
40
+ "172.16.0.0/12", # private IPv4 range 172.16.0.0 .. 172.31.255.255
41
+ "192.168.0.0/16", # private IPv4 range 192.168.x.x
42
+ ].map { |proxy| IPAddr.new(proxy) }
43
+
44
+ attr_reader :check_ip, :proxies
45
+
46
+ # Create a new +RemoteIp+ middleware instance.
47
+ #
48
+ # The +ip_spoofing_check+ option is on by default. When on, an exception
49
+ # is raised if it looks like the client is trying to lie about its own IP
50
+ # address. It makes sense to turn off this check on sites aimed at non-IP
51
+ # clients (like WAP devices), or behind proxies that set headers in an
52
+ # incorrect or confusing way (like AWS ELB).
53
+ #
54
+ # The +custom_proxies+ argument can take an Array of string, IPAddr, or
55
+ # Regexp objects which will be used instead of +TRUSTED_PROXIES+. If a
56
+ # single string, IPAddr, or Regexp object is provided, it will be used in
57
+ # addition to +TRUSTED_PROXIES+. Any proxy setup will put the value you
58
+ # want in the middle (or at the beginning) of the X-Forwarded-For list,
59
+ # with your proxy servers after it. If your proxies aren't removed, pass
60
+ # them in via the +custom_proxies+ parameter. That way, the middleware will
61
+ # ignore those IP addresses, and return the one that you want.
62
+ def initialize(app, ip_spoofing_check = true, custom_proxies = nil)
63
+ @app = app
64
+ @check_ip = ip_spoofing_check
65
+ @proxies = if custom_proxies.blank?
66
+ TRUSTED_PROXIES
67
+ elsif custom_proxies.respond_to?(:any?)
68
+ custom_proxies
69
+ else
70
+ Array(custom_proxies) + TRUSTED_PROXIES
71
+ end
72
+ end
73
+
74
+ # Since the IP address may not be needed, we store the object here
75
+ # without calculating the IP to keep from slowing down the majority of
76
+ # requests. For those requests that do need to know the IP, the
77
+ # GetIp#calculate_ip method will calculate the memoized client IP address.
78
+ def call(env)
79
+ req = ActionDispatch::Request.new env
80
+ req.remote_ip = GetIp.new(req, check_ip, proxies)
81
+ @app.call(req.env)
82
+ end
83
+
84
+ # The GetIp class exists as a way to defer processing of the request data
85
+ # into an actual IP address. If the ActionDispatch::Request#remote_ip method
86
+ # is called, this class will calculate the value and then memoize it.
87
+ class GetIp
88
+ def initialize(req, check_ip, proxies)
89
+ @req = req
90
+ @check_ip = check_ip
91
+ @proxies = proxies
92
+ end
93
+
94
+ # Sort through the various IP address headers, looking for the IP most
95
+ # likely to be the address of the actual remote client making this
96
+ # request.
97
+ #
98
+ # REMOTE_ADDR will be correct if the request is made directly against the
99
+ # Ruby process, on e.g. Heroku. When the request is proxied by another
100
+ # server like HAProxy or NGINX, the IP address that made the original
101
+ # request will be put in an X-Forwarded-For header. If there are multiple
102
+ # proxies, that header may contain a list of IPs. Other proxy services
103
+ # set the Client-Ip header instead, so we check that too.
104
+ #
105
+ # As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
106
+ # while the first IP in the list is likely to be the "originating" IP,
107
+ # it could also have been set by the client maliciously.
108
+ #
109
+ # In order to find the first address that is (probably) accurate, we
110
+ # take the list of IPs, remove known and trusted proxies, and then take
111
+ # the last address left, which was presumably set by one of those proxies.
112
+ def calculate_ip
113
+ # Set by the Rack web server, this is a single value.
114
+ remote_addr = ips_from(@req.remote_addr).last
115
+
116
+ # Could be a CSV list and/or repeated headers that were concatenated.
117
+ client_ips = ips_from(@req.client_ip).reverse
118
+ forwarded_ips = ips_from(@req.x_forwarded_for).reverse
119
+
120
+ # +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
121
+ # If they are both set, it means that either:
122
+ #
123
+ # 1) This request passed through two proxies with incompatible IP header
124
+ # conventions.
125
+ # 2) The client passed one of +Client-Ip+ or +X-Forwarded-For+
126
+ # (whichever the proxy servers weren't using) themselves.
127
+ #
128
+ # Either way, there is no way for us to determine which header is the
129
+ # right one after the fact. Since we have no idea, if we are concerned
130
+ # about IP spoofing we need to give up and explode. (If you're not
131
+ # concerned about IP spoofing you can turn the +ip_spoofing_check+
132
+ # option off.)
133
+ should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
134
+ if should_check_ip && !forwarded_ips.include?(client_ips.last)
135
+ # We don't know which came from the proxy, and which from the user
136
+ raise IpSpoofAttackError, "IP spoofing attack?! " \
137
+ "HTTP_CLIENT_IP=#{@req.client_ip.inspect} " \
138
+ "HTTP_X_FORWARDED_FOR=#{@req.x_forwarded_for.inspect}"
139
+ end
140
+
141
+ # We assume these things about the IP headers:
142
+ #
143
+ # - X-Forwarded-For will be a list of IPs, one per proxy, or blank
144
+ # - Client-Ip is propagated from the outermost proxy, or is blank
145
+ # - REMOTE_ADDR will be the IP that made the request to Rack
146
+ ips = [forwarded_ips, client_ips, remote_addr].flatten.compact
147
+
148
+ # If every single IP option is in the trusted list, just return REMOTE_ADDR
149
+ filter_proxies(ips).first || remote_addr
150
+ end
151
+
152
+ # Memoizes the value returned by #calculate_ip and returns it for
153
+ # ActionDispatch::Request to use.
154
+ def to_s
155
+ @ip ||= calculate_ip
156
+ end
157
+
158
+ private
159
+
160
+ def ips_from(header) # :doc:
161
+ return [] unless header
162
+ # Split the comma-separated list into an array of strings.
163
+ ips = header.strip.split(/[,\s]+/)
164
+ ips.select do |ip|
165
+ # Only return IPs that are valid according to the IPAddr#new method.
166
+ range = IPAddr.new(ip).to_range
167
+ # We want to make sure nobody is sneaking a netmask in.
168
+ range.begin == range.end
169
+ rescue ArgumentError
170
+ nil
171
+ end
172
+ end
173
+
174
+ def filter_proxies(ips) # :doc:
175
+ ips.reject do |ip|
176
+ @proxies.any? { |proxy| proxy === ip }
177
+ end
178
+ end
179
+ end
180
+ end
181
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "active_support/core_ext/string/access"
5
+
6
+ module ActionDispatch
7
+ # Makes a unique request id available to the +action_dispatch.request_id+ env variable (which is then accessible
8
+ # through <tt>ActionDispatch::Request#request_id</tt> or the alias <tt>ActionDispatch::Request#uuid</tt>) and sends
9
+ # the same id to the client via the X-Request-Id header.
10
+ #
11
+ # The unique request id is either based on the X-Request-Id header in the request, which would typically be generated
12
+ # by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the
13
+ # header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only.
14
+ #
15
+ # The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
16
+ # from multiple pieces of the stack.
17
+ class RequestId
18
+ X_REQUEST_ID = "X-Request-Id" #:nodoc:
19
+
20
+ def initialize(app)
21
+ @app = app
22
+ end
23
+
24
+ def call(env)
25
+ req = ActionDispatch::Request.new env
26
+ req.request_id = make_request_id(req.x_request_id)
27
+ @app.call(env).tap { |_status, headers, _body| headers[X_REQUEST_ID] = req.request_id }
28
+ end
29
+
30
+ private
31
+ def make_request_id(request_id)
32
+ if request_id.presence
33
+ request_id.gsub(/[^\w\-@]/, "").first(255)
34
+ else
35
+ internal_request_id
36
+ end
37
+ end
38
+
39
+ def internal_request_id
40
+ SecureRandom.uuid
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack/utils"
4
+ require "rack/request"
5
+ require "rack/session/abstract/id"
6
+ require "action_dispatch/middleware/cookies"
7
+ require "action_dispatch/request/session"
8
+
9
+ module ActionDispatch
10
+ module Session
11
+ class SessionRestoreError < StandardError #:nodoc:
12
+ def initialize
13
+ super("Session contains objects whose class definition isn't available.\n" \
14
+ "Remember to require the classes for all objects kept in the session.\n" \
15
+ "(Original exception: #{$!.message} [#{$!.class}])\n")
16
+ set_backtrace $!.backtrace
17
+ end
18
+ end
19
+
20
+ module Compatibility
21
+ def initialize(app, options = {})
22
+ options[:key] ||= "_session_id"
23
+ super
24
+ end
25
+
26
+ def generate_sid
27
+ sid = SecureRandom.hex(16)
28
+ sid.encode!(Encoding::UTF_8)
29
+ sid
30
+ end
31
+
32
+ private
33
+
34
+ def initialize_sid # :doc:
35
+ @default_options.delete(:sidbits)
36
+ @default_options.delete(:secure_random)
37
+ end
38
+
39
+ def make_request(env)
40
+ ActionDispatch::Request.new env
41
+ end
42
+ end
43
+
44
+ module StaleSessionCheck
45
+ def load_session(env)
46
+ stale_session_check! { super }
47
+ end
48
+
49
+ def extract_session_id(env)
50
+ stale_session_check! { super }
51
+ end
52
+
53
+ def stale_session_check!
54
+ yield
55
+ rescue ArgumentError => argument_error
56
+ if argument_error.message =~ %r{undefined class/module ([\w:]*\w)}
57
+ begin
58
+ # Note that the regexp does not allow $1 to end with a ':'.
59
+ $1.constantize
60
+ rescue LoadError, NameError
61
+ raise ActionDispatch::Session::SessionRestoreError
62
+ end
63
+ retry
64
+ else
65
+ raise
66
+ end
67
+ end
68
+ end
69
+
70
+ module SessionObject # :nodoc:
71
+ def prepare_session(req)
72
+ Request::Session.create(self, req, @default_options)
73
+ end
74
+
75
+ def loaded_session?(session)
76
+ !session.is_a?(Request::Session) || session.loaded?
77
+ end
78
+ end
79
+
80
+ class AbstractStore < Rack::Session::Abstract::Persisted
81
+ include Compatibility
82
+ include StaleSessionCheck
83
+ include SessionObject
84
+
85
+ private
86
+
87
+ def set_cookie(request, session_id, cookie)
88
+ request.cookie_jar[key] = cookie
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "action_dispatch/middleware/session/abstract_store"
4
+
5
+ module ActionDispatch
6
+ module Session
7
+ # A session store that uses an ActiveSupport::Cache::Store to store the sessions. This store is most useful
8
+ # if you don't store critical data in your sessions and you don't need them to live for extended periods
9
+ # of time.
10
+ #
11
+ # ==== Options
12
+ # * <tt>cache</tt> - The cache to use. If it is not specified, <tt>Rails.cache</tt> will be used.
13
+ # * <tt>expire_after</tt> - The length of time a session will be stored before automatically expiring.
14
+ # By default, the <tt>:expires_in</tt> option of the cache is used.
15
+ class CacheStore < AbstractStore
16
+ def initialize(app, options = {})
17
+ @cache = options[:cache] || Rails.cache
18
+ options[:expire_after] ||= @cache.options[:expires_in]
19
+ super
20
+ end
21
+
22
+ # Get a session from the cache.
23
+ def find_session(env, sid)
24
+ unless sid && (session = @cache.read(cache_key(sid)))
25
+ sid, session = generate_sid, {}
26
+ end
27
+ [sid, session]
28
+ end
29
+
30
+ # Set a session in the cache.
31
+ def write_session(env, sid, session, options)
32
+ key = cache_key(sid)
33
+ if session
34
+ @cache.write(key, session, expires_in: options[:expire_after])
35
+ else
36
+ @cache.delete(key)
37
+ end
38
+ sid
39
+ end
40
+
41
+ # Remove a session from the cache.
42
+ def delete_session(env, sid, options)
43
+ @cache.delete(cache_key(sid))
44
+ generate_sid
45
+ end
46
+
47
+ private
48
+ # Turn the session id into a cache key.
49
+ def cache_key(sid)
50
+ "_session_id:#{sid}"
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/hash/keys"
4
+ require "action_dispatch/middleware/session/abstract_store"
5
+ require "rack/session/cookie"
6
+
7
+ module ActionDispatch
8
+ module Session
9
+ # This cookie-based session store is the Rails default. It is
10
+ # dramatically faster than the alternatives.
11
+ #
12
+ # Sessions typically contain at most a user_id and flash message; both fit
13
+ # within the 4K cookie size limit. A CookieOverflow exception is raised if
14
+ # you attempt to store more than 4K of data.
15
+ #
16
+ # The cookie jar used for storage is automatically configured to be the
17
+ # best possible option given your application's configuration.
18
+ #
19
+ # Your cookies will be encrypted using your apps secret_key_base. This
20
+ # goes a step further than signed cookies in that encrypted cookies cannot
21
+ # be altered or read by users. This is the default starting in Rails 4.
22
+ #
23
+ # Configure your session store in an initializer:
24
+ #
25
+ # Rails.application.config.session_store :cookie_store, key: '_your_app_session'
26
+ #
27
+ # In the development and test environments your application's secret key base is
28
+ # generated by Rails and stored in a temporary file in <tt>tmp/development_secret.txt</tt>.
29
+ # In all other environments, it is stored encrypted in the
30
+ # <tt>config/credentials.yml.enc</tt> file.
31
+ #
32
+ # If your application was not updated to Rails 5.2 defaults, the secret_key_base
33
+ # will be found in the old <tt>config/secrets.yml</tt> file.
34
+ #
35
+ # Note that changing your secret_key_base will invalidate all existing session.
36
+ # Additionally, you should take care to make sure you are not relying on the
37
+ # ability to decode signed cookies generated by your app in external
38
+ # applications or JavaScript before changing it.
39
+ #
40
+ # Because CookieStore extends Rack::Session::Abstract::Persisted, many of the
41
+ # options described there can be used to customize the session cookie that
42
+ # is generated. For example:
43
+ #
44
+ # Rails.application.config.session_store :cookie_store, expire_after: 14.days
45
+ #
46
+ # would set the session cookie to expire automatically 14 days after creation.
47
+ # Other useful options include <tt>:key</tt>, <tt>:secure</tt> and
48
+ # <tt>:httponly</tt>.
49
+ class CookieStore < AbstractStore
50
+ def initialize(app, options = {})
51
+ super(app, options.merge!(cookie_only: true))
52
+ end
53
+
54
+ def delete_session(req, session_id, options)
55
+ new_sid = generate_sid unless options[:drop]
56
+ # Reset hash and Assign the new session id
57
+ req.set_header("action_dispatch.request.unsigned_session_cookie", new_sid ? { "session_id" => new_sid } : {})
58
+ new_sid
59
+ end
60
+
61
+ def load_session(req)
62
+ stale_session_check! do
63
+ data = unpacked_cookie_data(req)
64
+ data = persistent_session_id!(data)
65
+ [data["session_id"], data]
66
+ end
67
+ end
68
+
69
+ private
70
+
71
+ def extract_session_id(req)
72
+ stale_session_check! do
73
+ unpacked_cookie_data(req)["session_id"]
74
+ end
75
+ end
76
+
77
+ def unpacked_cookie_data(req)
78
+ req.fetch_header("action_dispatch.request.unsigned_session_cookie") do |k|
79
+ v = stale_session_check! do
80
+ if data = get_cookie(req)
81
+ data.stringify_keys!
82
+ end
83
+ data || {}
84
+ end
85
+ req.set_header k, v
86
+ end
87
+ end
88
+
89
+ def persistent_session_id!(data, sid = nil)
90
+ data ||= {}
91
+ data["session_id"] ||= sid || generate_sid
92
+ data
93
+ end
94
+
95
+ def write_session(req, sid, session_data, options)
96
+ session_data["session_id"] = sid
97
+ session_data
98
+ end
99
+
100
+ def set_cookie(request, session_id, cookie)
101
+ cookie_jar(request)[@key] = cookie
102
+ end
103
+
104
+ def get_cookie(req)
105
+ cookie_jar(req)[@key]
106
+ end
107
+
108
+ def cookie_jar(request)
109
+ request.cookie_jar.signed_or_encrypted
110
+ end
111
+ end
112
+ end
113
+ end