rack 2.0.9.3 → 3.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 rack might be problematic. Click here for more details.

Files changed (201) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +808 -0
  3. data/CONTRIBUTING.md +142 -0
  4. data/{COPYING → MIT-LICENSE} +4 -2
  5. data/README.md +293 -0
  6. data/SPEC.rdoc +340 -0
  7. data/lib/rack/auth/abstract/handler.rb +6 -2
  8. data/lib/rack/auth/abstract/request.rb +4 -2
  9. data/lib/rack/auth/basic.rb +7 -4
  10. data/lib/rack/auth/digest/md5.rb +1 -129
  11. data/lib/rack/auth/digest/nonce.rb +1 -51
  12. data/lib/rack/auth/digest/params.rb +1 -52
  13. data/lib/rack/auth/digest/request.rb +1 -41
  14. data/lib/rack/auth/digest.rb +256 -0
  15. data/lib/rack/body_proxy.rb +18 -15
  16. data/lib/rack/builder.rb +151 -40
  17. data/lib/rack/cascade.rb +30 -12
  18. data/lib/rack/chunked.rb +74 -23
  19. data/lib/rack/common_logger.rb +49 -36
  20. data/lib/rack/conditional_get.rb +33 -26
  21. data/lib/rack/config.rb +2 -0
  22. data/lib/rack/constants.rb +63 -0
  23. data/lib/rack/content_length.rb +13 -16
  24. data/lib/rack/content_type.rb +12 -8
  25. data/lib/rack/deflater.rb +84 -45
  26. data/lib/rack/directory.rb +90 -64
  27. data/lib/rack/etag.rb +17 -23
  28. data/lib/rack/events.rb +23 -20
  29. data/lib/rack/file.rb +5 -172
  30. data/lib/rack/files.rb +216 -0
  31. data/lib/rack/head.rb +10 -9
  32. data/lib/rack/headers.rb +154 -0
  33. data/lib/rack/lint.rb +786 -645
  34. data/lib/rack/lock.rb +4 -6
  35. data/lib/rack/logger.rb +4 -0
  36. data/lib/rack/media_type.rb +10 -5
  37. data/lib/rack/method_override.rb +8 -2
  38. data/lib/rack/mime.rb +17 -1
  39. data/lib/rack/mock.rb +2 -195
  40. data/lib/rack/mock_request.rb +166 -0
  41. data/lib/rack/mock_response.rb +126 -0
  42. data/lib/rack/multipart/generator.rb +21 -15
  43. data/lib/rack/multipart/parser.rb +161 -118
  44. data/lib/rack/multipart/uploaded_file.rb +19 -7
  45. data/lib/rack/multipart.rb +23 -41
  46. data/lib/rack/null_logger.rb +11 -0
  47. data/lib/rack/query_parser.rb +126 -65
  48. data/lib/rack/recursive.rb +9 -5
  49. data/lib/rack/reloader.rb +6 -4
  50. data/lib/rack/request.rb +331 -74
  51. data/lib/rack/response.rb +223 -70
  52. data/lib/rack/rewindable_input.rb +28 -8
  53. data/lib/rack/runtime.rb +11 -8
  54. data/lib/rack/sendfile.rb +42 -33
  55. data/lib/rack/show_exceptions.rb +35 -18
  56. data/lib/rack/show_status.rb +25 -15
  57. data/lib/rack/static.rb +30 -18
  58. data/lib/rack/tempfile_reaper.rb +16 -5
  59. data/lib/rack/urlmap.rb +14 -6
  60. data/lib/rack/utils.rb +268 -260
  61. data/lib/rack/version.rb +34 -0
  62. data/lib/rack.rb +15 -92
  63. metadata +44 -207
  64. data/HISTORY.md +0 -520
  65. data/README.rdoc +0 -316
  66. data/Rakefile +0 -116
  67. data/SPEC +0 -263
  68. data/bin/rackup +0 -4
  69. data/contrib/rack.png +0 -0
  70. data/contrib/rack.svg +0 -150
  71. data/contrib/rack_logo.svg +0 -164
  72. data/contrib/rdoc.css +0 -412
  73. data/example/lobster.ru +0 -4
  74. data/example/protectedlobster.rb +0 -14
  75. data/example/protectedlobster.ru +0 -8
  76. data/lib/rack/handler/cgi.rb +0 -60
  77. data/lib/rack/handler/fastcgi.rb +0 -100
  78. data/lib/rack/handler/lsws.rb +0 -61
  79. data/lib/rack/handler/scgi.rb +0 -70
  80. data/lib/rack/handler/thin.rb +0 -36
  81. data/lib/rack/handler/webrick.rb +0 -120
  82. data/lib/rack/handler.rb +0 -99
  83. data/lib/rack/lobster.rb +0 -70
  84. data/lib/rack/server.rb +0 -395
  85. data/lib/rack/session/abstract/id.rb +0 -510
  86. data/lib/rack/session/cookie.rb +0 -204
  87. data/lib/rack/session/memcache.rb +0 -99
  88. data/lib/rack/session/pool.rb +0 -83
  89. data/rack.gemspec +0 -34
  90. data/test/builder/an_underscore_app.rb +0 -5
  91. data/test/builder/anything.rb +0 -5
  92. data/test/builder/comment.ru +0 -4
  93. data/test/builder/end.ru +0 -5
  94. data/test/builder/line.ru +0 -1
  95. data/test/builder/options.ru +0 -2
  96. data/test/cgi/assets/folder/test.js +0 -1
  97. data/test/cgi/assets/fonts/font.eot +0 -1
  98. data/test/cgi/assets/images/image.png +0 -1
  99. data/test/cgi/assets/index.html +0 -1
  100. data/test/cgi/assets/javascripts/app.js +0 -1
  101. data/test/cgi/assets/stylesheets/app.css +0 -1
  102. data/test/cgi/lighttpd.conf +0 -26
  103. data/test/cgi/rackup_stub.rb +0 -6
  104. data/test/cgi/sample_rackup.ru +0 -5
  105. data/test/cgi/test +0 -9
  106. data/test/cgi/test+directory/test+file +0 -1
  107. data/test/cgi/test.fcgi +0 -9
  108. data/test/cgi/test.gz +0 -0
  109. data/test/cgi/test.ru +0 -5
  110. data/test/gemloader.rb +0 -10
  111. data/test/helper.rb +0 -34
  112. data/test/multipart/bad_robots +0 -259
  113. data/test/multipart/binary +0 -0
  114. data/test/multipart/content_type_and_no_filename +0 -6
  115. data/test/multipart/empty +0 -10
  116. data/test/multipart/fail_16384_nofile +0 -814
  117. data/test/multipart/file1.txt +0 -1
  118. data/test/multipart/filename_and_modification_param +0 -7
  119. data/test/multipart/filename_and_no_name +0 -6
  120. data/test/multipart/filename_with_encoded_words +0 -7
  121. data/test/multipart/filename_with_escaped_quotes +0 -6
  122. data/test/multipart/filename_with_escaped_quotes_and_modification_param +0 -7
  123. data/test/multipart/filename_with_null_byte +0 -7
  124. data/test/multipart/filename_with_percent_escaped_quotes +0 -6
  125. data/test/multipart/filename_with_single_quote +0 -7
  126. data/test/multipart/filename_with_unescaped_percentages +0 -6
  127. data/test/multipart/filename_with_unescaped_percentages2 +0 -6
  128. data/test/multipart/filename_with_unescaped_percentages3 +0 -6
  129. data/test/multipart/filename_with_unescaped_quotes +0 -6
  130. data/test/multipart/ie +0 -6
  131. data/test/multipart/invalid_character +0 -6
  132. data/test/multipart/mixed_files +0 -21
  133. data/test/multipart/nested +0 -10
  134. data/test/multipart/none +0 -9
  135. data/test/multipart/quoted +0 -15
  136. data/test/multipart/rack-logo.png +0 -0
  137. data/test/multipart/semicolon +0 -6
  138. data/test/multipart/text +0 -15
  139. data/test/multipart/three_files_three_fields +0 -31
  140. data/test/multipart/unity3d_wwwform +0 -11
  141. data/test/multipart/webkit +0 -32
  142. data/test/rackup/config.ru +0 -31
  143. data/test/registering_handler/rack/handler/registering_myself.rb +0 -8
  144. data/test/spec_auth_basic.rb +0 -89
  145. data/test/spec_auth_digest.rb +0 -260
  146. data/test/spec_body_proxy.rb +0 -85
  147. data/test/spec_builder.rb +0 -233
  148. data/test/spec_cascade.rb +0 -63
  149. data/test/spec_cgi.rb +0 -84
  150. data/test/spec_chunked.rb +0 -103
  151. data/test/spec_common_logger.rb +0 -107
  152. data/test/spec_conditional_get.rb +0 -103
  153. data/test/spec_config.rb +0 -23
  154. data/test/spec_content_length.rb +0 -86
  155. data/test/spec_content_type.rb +0 -46
  156. data/test/spec_deflater.rb +0 -375
  157. data/test/spec_directory.rb +0 -148
  158. data/test/spec_etag.rb +0 -108
  159. data/test/spec_events.rb +0 -133
  160. data/test/spec_fastcgi.rb +0 -85
  161. data/test/spec_file.rb +0 -264
  162. data/test/spec_handler.rb +0 -57
  163. data/test/spec_head.rb +0 -46
  164. data/test/spec_lint.rb +0 -520
  165. data/test/spec_lobster.rb +0 -59
  166. data/test/spec_lock.rb +0 -204
  167. data/test/spec_logger.rb +0 -24
  168. data/test/spec_media_type.rb +0 -42
  169. data/test/spec_method_override.rb +0 -110
  170. data/test/spec_mime.rb +0 -51
  171. data/test/spec_mock.rb +0 -359
  172. data/test/spec_multipart.rb +0 -721
  173. data/test/spec_null_logger.rb +0 -21
  174. data/test/spec_recursive.rb +0 -75
  175. data/test/spec_request.rb +0 -1423
  176. data/test/spec_response.rb +0 -528
  177. data/test/spec_rewindable_input.rb +0 -128
  178. data/test/spec_runtime.rb +0 -50
  179. data/test/spec_sendfile.rb +0 -125
  180. data/test/spec_server.rb +0 -193
  181. data/test/spec_session_abstract_id.rb +0 -31
  182. data/test/spec_session_abstract_session_hash.rb +0 -45
  183. data/test/spec_session_cookie.rb +0 -442
  184. data/test/spec_session_memcache.rb +0 -357
  185. data/test/spec_session_persisted_secure_secure_session_hash.rb +0 -73
  186. data/test/spec_session_pool.rb +0 -247
  187. data/test/spec_show_exceptions.rb +0 -93
  188. data/test/spec_show_status.rb +0 -104
  189. data/test/spec_static.rb +0 -184
  190. data/test/spec_tempfile_reaper.rb +0 -64
  191. data/test/spec_thin.rb +0 -96
  192. data/test/spec_urlmap.rb +0 -237
  193. data/test/spec_utils.rb +0 -742
  194. data/test/spec_version.rb +0 -11
  195. data/test/spec_webrick.rb +0 -206
  196. data/test/static/another/index.html +0 -1
  197. data/test/static/foo.html +0 -1
  198. data/test/static/index.html +0 -1
  199. data/test/testrequest.rb +0 -78
  200. data/test/unregistered_handler/rack/handler/unregistered.rb +0 -7
  201. data/test/unregistered_handler/rack/handler/unregistered_long_one.rb +0 -7
@@ -0,0 +1,256 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'abstract/handler'
4
+ require_relative 'abstract/request'
5
+ require 'digest/md5'
6
+ require 'base64'
7
+
8
+ module Rack
9
+ warn "Rack::Auth::Digest is deprecated and will be removed in Rack 3.1", uplevel: 1
10
+
11
+ module Auth
12
+ module Digest
13
+ # Rack::Auth::Digest::Nonce is the default nonce generator for the
14
+ # Rack::Auth::Digest::MD5 authentication handler.
15
+ #
16
+ # +private_key+ needs to set to a constant string.
17
+ #
18
+ # +time_limit+ can be optionally set to an integer (number of seconds),
19
+ # to limit the validity of the generated nonces.
20
+
21
+ class Nonce
22
+
23
+ class << self
24
+ attr_accessor :private_key, :time_limit
25
+ end
26
+
27
+ def self.parse(string)
28
+ new(*Base64.decode64(string).split(' ', 2))
29
+ end
30
+
31
+ def initialize(timestamp = Time.now, given_digest = nil)
32
+ @timestamp, @given_digest = timestamp.to_i, given_digest
33
+ end
34
+
35
+ def to_s
36
+ Base64.encode64("#{@timestamp} #{digest}").strip
37
+ end
38
+
39
+ def digest
40
+ ::Digest::MD5.hexdigest("#{@timestamp}:#{self.class.private_key}")
41
+ end
42
+
43
+ def valid?
44
+ digest == @given_digest
45
+ end
46
+
47
+ def stale?
48
+ !self.class.time_limit.nil? && (Time.now.to_i - @timestamp) > self.class.time_limit
49
+ end
50
+
51
+ def fresh?
52
+ !stale?
53
+ end
54
+
55
+ end
56
+
57
+ class Params < Hash
58
+
59
+ def self.parse(str)
60
+ Params[*split_header_value(str).map do |param|
61
+ k, v = param.split('=', 2)
62
+ [k, dequote(v)]
63
+ end.flatten]
64
+ end
65
+
66
+ def self.dequote(str) # From WEBrick::HTTPUtils
67
+ ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup
68
+ ret.gsub!(/\\(.)/, "\\1")
69
+ ret
70
+ end
71
+
72
+ def self.split_header_value(str)
73
+ str.scan(/\w+\=(?:"[^\"]+"|[^,]+)/n)
74
+ end
75
+
76
+ def initialize
77
+ super()
78
+
79
+ yield self if block_given?
80
+ end
81
+
82
+ def [](k)
83
+ super k.to_s
84
+ end
85
+
86
+ def []=(k, v)
87
+ super k.to_s, v.to_s
88
+ end
89
+
90
+ UNQUOTED = ['nc', 'stale']
91
+
92
+ def to_s
93
+ map do |k, v|
94
+ "#{k}=#{(UNQUOTED.include?(k) ? v.to_s : quote(v))}"
95
+ end.join(', ')
96
+ end
97
+
98
+ def quote(str) # From WEBrick::HTTPUtils
99
+ '"' + str.gsub(/[\\\"]/o, "\\\1") + '"'
100
+ end
101
+
102
+ end
103
+
104
+ class Request < Auth::AbstractRequest
105
+ def method
106
+ @env[RACK_METHODOVERRIDE_ORIGINAL_METHOD] || @env[REQUEST_METHOD]
107
+ end
108
+
109
+ def digest?
110
+ "digest" == scheme
111
+ end
112
+
113
+ def correct_uri?
114
+ request.fullpath == uri
115
+ end
116
+
117
+ def nonce
118
+ @nonce ||= Nonce.parse(params['nonce'])
119
+ end
120
+
121
+ def params
122
+ @params ||= Params.parse(parts.last)
123
+ end
124
+
125
+ def respond_to?(sym, *)
126
+ super or params.has_key? sym.to_s
127
+ end
128
+
129
+ def method_missing(sym, *args)
130
+ return super unless params.has_key?(key = sym.to_s)
131
+ return params[key] if args.size == 0
132
+ raise ArgumentError, "wrong number of arguments (#{args.size} for 0)"
133
+ end
134
+ end
135
+
136
+ # Rack::Auth::Digest::MD5 implements the MD5 algorithm version of
137
+ # HTTP Digest Authentication, as per RFC 2617.
138
+ #
139
+ # Initialize with the [Rack] application that you want protecting,
140
+ # and a block that looks up a plaintext password for a given username.
141
+ #
142
+ # +opaque+ needs to be set to a constant base64/hexadecimal string.
143
+ #
144
+ class MD5 < AbstractHandler
145
+
146
+ attr_accessor :opaque
147
+
148
+ attr_writer :passwords_hashed
149
+
150
+ def initialize(app, realm = nil, opaque = nil, &authenticator)
151
+ @passwords_hashed = nil
152
+ if opaque.nil? and realm.respond_to? :values_at
153
+ realm, opaque, @passwords_hashed = realm.values_at :realm, :opaque, :passwords_hashed
154
+ end
155
+ super(app, realm, &authenticator)
156
+ @opaque = opaque
157
+ end
158
+
159
+ def passwords_hashed?
160
+ !!@passwords_hashed
161
+ end
162
+
163
+ def call(env)
164
+ auth = Request.new(env)
165
+
166
+ unless auth.provided?
167
+ return unauthorized
168
+ end
169
+
170
+ if !auth.digest? || !auth.correct_uri? || !valid_qop?(auth)
171
+ return bad_request
172
+ end
173
+
174
+ if valid?(auth)
175
+ if auth.nonce.stale?
176
+ return unauthorized(challenge(stale: true))
177
+ else
178
+ env['REMOTE_USER'] = auth.username
179
+
180
+ return @app.call(env)
181
+ end
182
+ end
183
+
184
+ unauthorized
185
+ end
186
+
187
+
188
+ private
189
+
190
+ QOP = 'auth'
191
+
192
+ def params(hash = {})
193
+ Params.new do |params|
194
+ params['realm'] = realm
195
+ params['nonce'] = Nonce.new.to_s
196
+ params['opaque'] = H(opaque)
197
+ params['qop'] = QOP
198
+
199
+ hash.each { |k, v| params[k] = v }
200
+ end
201
+ end
202
+
203
+ def challenge(hash = {})
204
+ "Digest #{params(hash)}"
205
+ end
206
+
207
+ def valid?(auth)
208
+ valid_opaque?(auth) && valid_nonce?(auth) && valid_digest?(auth)
209
+ end
210
+
211
+ def valid_qop?(auth)
212
+ QOP == auth.qop
213
+ end
214
+
215
+ def valid_opaque?(auth)
216
+ H(opaque) == auth.opaque
217
+ end
218
+
219
+ def valid_nonce?(auth)
220
+ auth.nonce.valid?
221
+ end
222
+
223
+ def valid_digest?(auth)
224
+ pw = @authenticator.call(auth.username)
225
+ pw && Rack::Utils.secure_compare(digest(auth, pw), auth.response)
226
+ end
227
+
228
+ def md5(data)
229
+ ::Digest::MD5.hexdigest(data)
230
+ end
231
+
232
+ alias :H :md5
233
+
234
+ def KD(secret, data)
235
+ H "#{secret}:#{data}"
236
+ end
237
+
238
+ def A1(auth, password)
239
+ "#{auth.username}:#{auth.realm}:#{password}"
240
+ end
241
+
242
+ def A2(auth)
243
+ "#{auth.method}:#{auth.uri}"
244
+ end
245
+
246
+ def digest(auth, password)
247
+ password_hash = passwords_hashed? ? password : H(A1(auth, password))
248
+
249
+ KD password_hash, "#{auth.nonce}:#{auth.nc}:#{auth.cnonce}:#{QOP}:#{H A2(auth)}"
250
+ end
251
+
252
+ end
253
+ end
254
+ end
255
+ end
256
+
@@ -1,44 +1,47 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Rack
4
+ # Proxy for response bodies allowing calling a block when
5
+ # the response body is closed (after the response has been fully
6
+ # sent to the client).
2
7
  class BodyProxy
8
+ # Set the response body to wrap, and the block to call when the
9
+ # response has been fully sent.
3
10
  def initialize(body, &block)
4
11
  @body = body
5
12
  @block = block
6
13
  @closed = false
7
14
  end
8
15
 
9
- def respond_to?(method_name, include_all=false)
10
- case method_name
11
- when :to_ary, 'to_ary'
12
- return false
13
- end
16
+ # Return whether the wrapped body responds to the method.
17
+ def respond_to_missing?(method_name, include_all = false)
14
18
  super or @body.respond_to?(method_name, include_all)
15
19
  end
16
20
 
21
+ # If not already closed, close the wrapped body and
22
+ # then call the block the proxy was initialized with.
17
23
  def close
18
24
  return if @closed
19
25
  @closed = true
20
26
  begin
21
- @body.close if @body.respond_to? :close
27
+ @body.close if @body.respond_to?(:close)
22
28
  ensure
23
29
  @block.call
24
30
  end
25
31
  end
26
32
 
33
+ # Whether the proxy is closed. The proxy starts as not closed,
34
+ # and becomes closed on the first call to close.
27
35
  def closed?
28
36
  @closed
29
37
  end
30
38
 
31
- # N.B. This method is a special case to address the bug described by #434.
32
- # We are applying this special case for #each only. Future bugs of this
33
- # class will be handled by requesting users to patch their ruby
34
- # implementation, to save adding too many methods in this class.
35
- def each
36
- @body.each { |body| yield body }
37
- end
38
-
39
+ # Delegate missing methods to the wrapped body.
39
40
  def method_missing(method_name, *args, &block)
40
- super if :to_ary == method_name
41
41
  @body.__send__(method_name, *args, &block)
42
42
  end
43
+ # :nocov:
44
+ ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
45
+ # :nocov:
43
46
  end
44
47
  end
data/lib/rack/builder.rb CHANGED
@@ -1,6 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'urlmap'
4
+
1
5
  module Rack
2
- # Rack::Builder implements a small DSL to iteratively construct Rack
3
- # applications.
6
+ # Rack::Builder provides a domain-specific language (DSL) to construct Rack
7
+ # applications. It is primarily used to parse +config.ru+ files which
8
+ # instantiate several middleware and a final application which are hosted
9
+ # by a Rack-compatible web server.
4
10
  #
5
11
  # Example:
6
12
  #
@@ -27,34 +33,96 @@ module Rack
27
33
  #
28
34
  # +use+ adds middleware to the stack, +run+ dispatches to an application.
29
35
  # You can use +map+ to construct a Rack::URLMap in a convenient way.
30
-
31
36
  class Builder
32
- def self.parse_file(config, opts = Server::Options.new)
33
- options = {}
34
- if config =~ /\.ru$/
35
- cfgfile = ::File.read(config)
36
- if cfgfile[/^#\\(.*)/] && opts
37
- options = opts.parse! $1.split(/\s+/)
38
- end
39
- cfgfile.sub!(/^__END__\n.*\Z/m, '')
40
- app = new_from_string cfgfile, config
37
+
38
+ # https://stackoverflow.com/questions/2223882/whats-the-difference-between-utf-8-and-utf-8-without-bom
39
+ UTF_8_BOM = '\xef\xbb\xbf'
40
+
41
+ # Parse the given config file to get a Rack application.
42
+ #
43
+ # If the config file ends in +.ru+, it is treated as a
44
+ # rackup file and the contents will be treated as if
45
+ # specified inside a Rack::Builder block.
46
+ #
47
+ # If the config file does not end in +.ru+, it is
48
+ # required and Rack will use the basename of the file
49
+ # to guess which constant will be the Rack application to run.
50
+ #
51
+ # Examples:
52
+ #
53
+ # Rack::Builder.parse_file('config.ru')
54
+ # # Rack application built using Rack::Builder.new
55
+ #
56
+ # Rack::Builder.parse_file('app.rb')
57
+ # # requires app.rb, which can be anywhere in Ruby's
58
+ # # load path. After requiring, assumes App constant
59
+ # # contains Rack application
60
+ #
61
+ # Rack::Builder.parse_file('./my_app.rb')
62
+ # # requires ./my_app.rb, which should be in the
63
+ # # process's current directory. After requiring,
64
+ # # assumes MyApp constant contains Rack application
65
+ def self.parse_file(path)
66
+ if path.end_with?('.ru')
67
+ return self.load_file(path)
41
68
  else
42
- require config
43
- app = Object.const_get(::File.basename(config, '.rb').split('_').map(&:capitalize).join(''))
69
+ require path
70
+ return Object.const_get(::File.basename(path, '.rb').split('_').map(&:capitalize).join(''))
44
71
  end
45
- return app, options
46
72
  end
47
73
 
48
- def self.new_from_string(builder_script, file="(rackup)")
49
- eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app",
50
- TOPLEVEL_BINDING, file, 0
74
+ # Load the given file as a rackup file, treating the
75
+ # contents as if specified inside a Rack::Builder block.
76
+ #
77
+ # Ignores content in the file after +__END__+, so that
78
+ # use of +__END__+ will not result in a syntax error.
79
+ #
80
+ # Example config.ru file:
81
+ #
82
+ # $ cat config.ru
83
+ #
84
+ # use Rack::ContentLength
85
+ # require './app.rb'
86
+ # run App
87
+ def self.load_file(path)
88
+ config = ::File.read(path)
89
+ config.slice!(/\A#{UTF_8_BOM}/) if config.encoding == Encoding::UTF_8
90
+
91
+ if config[/^#\\(.*)/]
92
+ fail "Parsing options from the first comment line is no longer supported: #{path}"
93
+ end
94
+
95
+ config.sub!(/^__END__\n.*\Z/m, '')
96
+
97
+ return new_from_string(config, path)
51
98
  end
52
99
 
100
+ # Evaluate the given +builder_script+ string in the context of
101
+ # a Rack::Builder block, returning a Rack application.
102
+ def self.new_from_string(builder_script, file = "(rackup)")
103
+ # We want to build a variant of TOPLEVEL_BINDING with self as a Rack::Builder instance.
104
+ # We cannot use instance_eval(String) as that would resolve constants differently.
105
+ binding, builder = TOPLEVEL_BINDING.eval('Rack::Builder.new.instance_eval { [binding, self] }')
106
+ eval builder_script, binding, file
107
+
108
+ return builder.to_app
109
+ end
110
+
111
+ # Initialize a new Rack::Builder instance. +default_app+ specifies the
112
+ # default application if +run+ is not called later. If a block
113
+ # is given, it is evaluated in the context of the instance.
53
114
  def initialize(default_app = nil, &block)
54
- @use, @map, @run, @warmup = [], nil, default_app, nil
115
+ @use = []
116
+ @map = nil
117
+ @run = default_app
118
+ @warmup = nil
119
+ @freeze_app = false
120
+
55
121
  instance_eval(&block) if block_given?
56
122
  end
57
123
 
124
+ # Create a new Rack::Builder instance and return the Rack application
125
+ # generated from it.
58
126
  def self.app(default_app = nil, &block)
59
127
  self.new(default_app, &block).to_app
60
128
  end
@@ -73,7 +141,7 @@ module Rack
73
141
  # end
74
142
  #
75
143
  # use Middleware
76
- # run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
144
+ # run lambda { |env| [200, { "content-type" => "text/plain" }, ["OK"]] }
77
145
  #
78
146
  # All requests through to this application will first be processed by the middleware class.
79
147
  # The +call+ method in this example sets an additional environment key which then can be
@@ -81,30 +149,54 @@ module Rack
81
149
  def use(middleware, *args, &block)
82
150
  if @map
83
151
  mapping, @map = @map, nil
84
- @use << proc { |app| generate_map app, mapping }
152
+ @use << proc { |app| generate_map(app, mapping) }
85
153
  end
86
154
  @use << proc { |app| middleware.new(app, *args, &block) }
87
155
  end
156
+ # :nocov:
157
+ ruby2_keywords(:use) if respond_to?(:ruby2_keywords, true)
158
+ # :nocov:
88
159
 
89
- # Takes an argument that is an object that responds to #call and returns a Rack response.
90
- # The simplest form of this is a lambda object:
160
+ # Takes a block or argument that is an object that responds to #call and
161
+ # returns a Rack response.
91
162
  #
92
- # run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] }
163
+ # You can use a block:
93
164
  #
94
- # However this could also be a class:
165
+ # run do |env|
166
+ # [200, { "content-type" => "text/plain" }, ["Hello World!"]]
167
+ # end
168
+ #
169
+ # You can also provide a lambda:
170
+ #
171
+ # run lambda { |env| [200, { "content-type" => "text/plain" }, ["OK"]] }
172
+ #
173
+ # You can also provide a class instance:
95
174
  #
96
175
  # class Heartbeat
97
- # def self.call(env)
98
- # [200, { "Content-Type" => "text/plain" }, ["OK"]]
176
+ # def call(env)
177
+ # [200, { "content-type" => "text/plain" }, ["OK"]]
99
178
  # end
100
179
  # end
101
180
  #
102
- # run Heartbeat
103
- def run(app)
104
- @run = app
181
+ # run Heartbeat.new
182
+ #
183
+ # It could also be a module:
184
+ #
185
+ # module HelloWorld
186
+ # def call(env)
187
+ # [200, { "content-type" => "text/plain" }, ["Hello World"]]
188
+ # end
189
+ # end
190
+ #
191
+ # run HelloWorld
192
+ def run(app = nil, &block)
193
+ raise ArgumentError, "Both app and block given!" if app && block_given?
194
+
195
+ @run = app || block
105
196
  end
106
197
 
107
- # Takes a lambda or block that is used to warm-up the application.
198
+ # Takes a lambda or block that is used to warm-up the application. This block is called
199
+ # before the Rack application is returned by to_app.
108
200
  #
109
201
  # warmup do |app|
110
202
  # client = Rack::MockRequest.new(app)
@@ -113,51 +205,70 @@ module Rack
113
205
  #
114
206
  # use SomeMiddleware
115
207
  # run MyApp
116
- def warmup(prc=nil, &block)
208
+ def warmup(prc = nil, &block)
117
209
  @warmup = prc || block
118
210
  end
119
211
 
120
- # Creates a route within the application.
212
+ # Creates a route within the application. Routes under the mapped path will be sent to
213
+ # the Rack application specified by run inside the block. Other requests will be sent to the
214
+ # default application specified by run outside the block.
121
215
  #
122
216
  # Rack::Builder.app do
123
- # map '/' do
217
+ # map '/heartbeat' do
124
218
  # run Heartbeat
125
219
  # end
220
+ # run App
126
221
  # end
127
222
  #
128
- # The +use+ method can also be used here to specify middleware to run under a specific path:
223
+ # The +use+ method can also be used inside the block to specify middleware to run under a specific path:
129
224
  #
130
225
  # Rack::Builder.app do
131
- # map '/' do
226
+ # map '/heartbeat' do
132
227
  # use Middleware
133
228
  # run Heartbeat
134
229
  # end
230
+ # run App
135
231
  # end
136
232
  #
137
- # This example includes a piece of middleware which will run before requests hit +Heartbeat+.
233
+ # This example includes a piece of middleware which will run before +/heartbeat+ requests hit +Heartbeat+.
138
234
  #
235
+ # Note that providing a +path+ of +/+ will ignore any default application given in a +run+ statement
236
+ # outside the block.
139
237
  def map(path, &block)
140
238
  @map ||= {}
141
239
  @map[path] = block
142
240
  end
143
241
 
242
+ # Freeze the app (set using run) and all middleware instances when building the application
243
+ # in to_app.
244
+ def freeze_app
245
+ @freeze_app = true
246
+ end
247
+
248
+ # Return the Rack application generated by this instance.
144
249
  def to_app
145
250
  app = @map ? generate_map(@run, @map) : @run
146
251
  fail "missing run or map statement" unless app
147
- app = @use.reverse.inject(app) { |a,e| e[a] }
252
+ app.freeze if @freeze_app
253
+ app = @use.reverse.inject(app) { |a, e| e[a].tap { |x| x.freeze if @freeze_app } }
148
254
  @warmup.call(app) if @warmup
149
255
  app
150
256
  end
151
257
 
258
+ # Call the Rack application generated by this builder instance. Note that
259
+ # this rebuilds the Rack application and runs the warmup code (if any)
260
+ # every time it is called, so it should not be used if performance is important.
152
261
  def call(env)
153
262
  to_app.call(env)
154
263
  end
155
264
 
156
265
  private
157
266
 
267
+ # Generate a URLMap instance by generating new Rack applications for each
268
+ # map block in this instance.
158
269
  def generate_map(default_app, mapping)
159
- mapped = default_app ? {'/' => default_app} : {}
160
- mapping.each { |r,b| mapped[r] = self.class.new(default_app, &b).to_app }
270
+ mapped = default_app ? { '/' => default_app } : {}
271
+ mapping.each { |r, b| mapped[r] = self.class.new(default_app, &b).to_app }
161
272
  URLMap.new(mapped)
162
273
  end
163
274
  end
data/lib/rack/cascade.rb CHANGED
@@ -1,24 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'constants'
4
+
1
5
  module Rack
2
6
  # Rack::Cascade tries a request on several apps, and returns the
3
- # first response that is not 404 or 405 (or in a list of configurable
4
- # status codes).
7
+ # first response that is not 404 or 405 (or in a list of configured
8
+ # status codes). If all applications tried return one of the configured
9
+ # status codes, return the last response.
5
10
 
6
11
  class Cascade
7
- NotFound = [404, {CONTENT_TYPE => "text/plain"}, []]
12
+ # deprecated, no longer used
13
+ NotFound = [404, { CONTENT_TYPE => "text/plain" }, []]
8
14
 
15
+ # An array of applications to try in order.
9
16
  attr_reader :apps
10
17
 
11
- def initialize(apps, catch=[404, 405])
12
- @apps = []; @has_app = {}
18
+ # Set the apps to send requests to, and what statuses result in
19
+ # cascading. Arguments:
20
+ #
21
+ # apps: An enumerable of rack applications.
22
+ # cascade_for: The statuses to use cascading for. If a response is received
23
+ # from an app, the next app is tried.
24
+ def initialize(apps, cascade_for = [404, 405])
25
+ @apps = []
13
26
  apps.each { |app| add app }
14
27
 
15
- @catch = {}
16
- [*catch].each { |status| @catch[status] = true }
28
+ @cascade_for = {}
29
+ [*cascade_for].each { |status| @cascade_for[status] = true }
17
30
  end
18
31
 
32
+ # Call each app in order. If the responses uses a status that requires
33
+ # cascading, try the next app. If all responses require cascading,
34
+ # return the response from the last app.
19
35
  def call(env)
20
- result = NotFound
21
-
36
+ return [404, { CONTENT_TYPE => "text/plain" }, []] if @apps.empty?
37
+ result = nil
22
38
  last_body = nil
23
39
 
24
40
  @apps.each do |app|
@@ -31,20 +47,22 @@ module Rack
31
47
  last_body.close if last_body.respond_to? :close
32
48
 
33
49
  result = app.call(env)
50
+ return result unless @cascade_for.include?(result[0].to_i)
34
51
  last_body = result[2]
35
- break unless @catch.include?(result[0].to_i)
36
52
  end
37
53
 
38
54
  result
39
55
  end
40
56
 
57
+ # Append an app to the list of apps to cascade. This app will
58
+ # be tried last.
41
59
  def add(app)
42
- @has_app[app] = true
43
60
  @apps << app
44
61
  end
45
62
 
63
+ # Whether the given app is one of the apps to cascade to.
46
64
  def include?(app)
47
- @has_app.include? app
65
+ @apps.include?(app)
48
66
  end
49
67
 
50
68
  alias_method :<<, :add