homura-runtime 0.3.3 → 0.3.4

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 (79) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +7 -0
  3. data/lib/homura/runtime/version.rb +1 -1
  4. data/vendor/rack/auth/abstract/handler.rb +41 -0
  5. data/vendor/rack/auth/abstract/request.rb +51 -0
  6. data/vendor/rack/auth/basic.rb +58 -0
  7. data/vendor/rack/bad_request.rb +8 -0
  8. data/vendor/rack/body_proxy.rb +63 -0
  9. data/vendor/rack/builder.rb +315 -0
  10. data/vendor/rack/cascade.rb +67 -0
  11. data/vendor/rack/common_logger.rb +94 -0
  12. data/vendor/rack/conditional_get.rb +87 -0
  13. data/vendor/rack/config.rb +22 -0
  14. data/vendor/rack/constants.rb +68 -0
  15. data/vendor/rack/content_length.rb +34 -0
  16. data/vendor/rack/content_type.rb +33 -0
  17. data/vendor/rack/deflater.rb +159 -0
  18. data/vendor/rack/directory.rb +210 -0
  19. data/vendor/rack/etag.rb +71 -0
  20. data/vendor/rack/events.rb +172 -0
  21. data/vendor/rack/files.rb +224 -0
  22. data/vendor/rack/head.rb +25 -0
  23. data/vendor/rack/headers.rb +238 -0
  24. data/vendor/rack/lint.rb +1000 -0
  25. data/vendor/rack/lock.rb +29 -0
  26. data/vendor/rack/media_type.rb +42 -0
  27. data/vendor/rack/method_override.rb +56 -0
  28. data/vendor/rack/mime.rb +694 -0
  29. data/vendor/rack/mock.rb +3 -0
  30. data/vendor/rack/mock_request.rb +161 -0
  31. data/vendor/rack/mock_response.rb +147 -0
  32. data/vendor/rack/multipart/generator.rb +99 -0
  33. data/vendor/rack/multipart/parser.rb +586 -0
  34. data/vendor/rack/multipart/uploaded_file.rb +82 -0
  35. data/vendor/rack/multipart.rb +77 -0
  36. data/vendor/rack/null_logger.rb +48 -0
  37. data/vendor/rack/protection/authenticity_token.rb +256 -0
  38. data/vendor/rack/protection/base.rb +140 -0
  39. data/vendor/rack/protection/content_security_policy.rb +80 -0
  40. data/vendor/rack/protection/cookie_tossing.rb +77 -0
  41. data/vendor/rack/protection/escaped_params.rb +93 -0
  42. data/vendor/rack/protection/form_token.rb +25 -0
  43. data/vendor/rack/protection/frame_options.rb +39 -0
  44. data/vendor/rack/protection/http_origin.rb +43 -0
  45. data/vendor/rack/protection/ip_spoofing.rb +27 -0
  46. data/vendor/rack/protection/json_csrf.rb +60 -0
  47. data/vendor/rack/protection/path_traversal.rb +45 -0
  48. data/vendor/rack/protection/referrer_policy.rb +27 -0
  49. data/vendor/rack/protection/remote_referrer.rb +22 -0
  50. data/vendor/rack/protection/remote_token.rb +24 -0
  51. data/vendor/rack/protection/session_hijacking.rb +37 -0
  52. data/vendor/rack/protection/strict_transport.rb +41 -0
  53. data/vendor/rack/protection/version.rb +7 -0
  54. data/vendor/rack/protection/xss_header.rb +27 -0
  55. data/vendor/rack/protection.rb +58 -0
  56. data/vendor/rack/query_parser.rb +261 -0
  57. data/vendor/rack/recursive.rb +66 -0
  58. data/vendor/rack/reloader.rb +112 -0
  59. data/vendor/rack/request.rb +818 -0
  60. data/vendor/rack/response.rb +403 -0
  61. data/vendor/rack/rewindable_input.rb +116 -0
  62. data/vendor/rack/runtime.rb +35 -0
  63. data/vendor/rack/sendfile.rb +197 -0
  64. data/vendor/rack/session/abstract/id.rb +533 -0
  65. data/vendor/rack/session/constants.rb +13 -0
  66. data/vendor/rack/session/cookie.rb +292 -0
  67. data/vendor/rack/session/encryptor.rb +415 -0
  68. data/vendor/rack/session/pool.rb +76 -0
  69. data/vendor/rack/session/version.rb +10 -0
  70. data/vendor/rack/session.rb +12 -0
  71. data/vendor/rack/show_exceptions.rb +433 -0
  72. data/vendor/rack/show_status.rb +121 -0
  73. data/vendor/rack/static.rb +188 -0
  74. data/vendor/rack/tempfile_reaper.rb +44 -0
  75. data/vendor/rack/urlmap.rb +99 -0
  76. data/vendor/rack/utils.rb +631 -0
  77. data/vendor/rack/version.rb +17 -0
  78. data/vendor/rack.rb +66 -0
  79. metadata +76 -1
@@ -0,0 +1,1000 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'forwardable'
4
+
5
+ require_relative 'constants'
6
+ require_relative 'utils'
7
+
8
+ module Rack
9
+ # Validates your application and the requests and responses according to the Rack spec. See SPEC.rdoc for details.
10
+ class Lint
11
+ # Represents a failure to meet the Rack specification.
12
+ class LintError < RuntimeError; end
13
+
14
+ # Invoke the application, validating the request and response according to the Rack spec.
15
+ def call(env = nil)
16
+ Wrapper.new(@app, env).response
17
+ end
18
+
19
+ # :stopdoc:
20
+
21
+ ALLOWED_SCHEMES = %w(https http wss ws).freeze
22
+
23
+ REQUEST_PATH_ORIGIN_FORM = /\A\/[^#]*\z/
24
+ REQUEST_PATH_ABSOLUTE_FORM = /\A#{Utils::URI_PARSER.make_regexp}\z/
25
+ REQUEST_PATH_AUTHORITY_FORM = /\A[^\/:]+:\d+\z/
26
+ REQUEST_PATH_ASTERISK_FORM = '*'
27
+
28
+ # Match a host name, according to RFC3986. Copied from `URI::RFC3986_Parser::HOST` because older Ruby versions (< 3.3) don't expose it.
29
+ HOST_PATTERN = /
30
+ (?<IP-literal>\[(?:
31
+ (?<IPv6address>
32
+ (?:\h{1,4}:){6}
33
+ (?<ls32>\h{1,4}:\h{1,4}
34
+ | (?<IPv4address>(?<dec-octet>[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]|\d)
35
+ \.\g<dec-octet>\.\g<dec-octet>\.\g<dec-octet>)
36
+ )
37
+ | ::(?:\h{1,4}:){5}\g<ls32>
38
+ | \h{1,4}?::(?:\h{1,4}:){4}\g<ls32>
39
+ | (?:(?:\h{1,4}:)?\h{1,4})?::(?:\h{1,4}:){3}\g<ls32>
40
+ | (?:(?:\h{1,4}:){,2}\h{1,4})?::(?:\h{1,4}:){2}\g<ls32>
41
+ | (?:(?:\h{1,4}:){,3}\h{1,4})?::\h{1,4}:\g<ls32>
42
+ | (?:(?:\h{1,4}:){,4}\h{1,4})?::\g<ls32>
43
+ | (?:(?:\h{1,4}:){,5}\h{1,4})?::\h{1,4}
44
+ | (?:(?:\h{1,4}:){,6}\h{1,4})?::
45
+ )
46
+ | (?<IPvFuture>v\h++\.[!$&-.0-9:;=A-Z_a-z~]++)
47
+ )\])
48
+ | \g<IPv4address>
49
+ | (?<reg-name>(?:%\h\h|[!$&-.0-9;=A-Z_a-z~])*+)
50
+ /x.freeze
51
+ SERVER_NAME_PATTERN = /\A#{HOST_PATTERN}\z/.freeze
52
+ HTTP_HOST_PATTERN = /\A#{HOST_PATTERN}(:\d*+)?\z/.freeze
53
+
54
+ private_constant :HOST_PATTERN, :SERVER_NAME_PATTERN, :HTTP_HOST_PATTERN
55
+
56
+ # N.B. The empty `##` comments creates paragraphs in the output. A trailing "\" is used to escape the newline character, which combines the comments into a single paragraph.
57
+ #
58
+ ## = Rack Specification
59
+ ##
60
+ ## This specification aims to formalize the Rack protocol. You can (and should) use +Rack::Lint+ to enforce it. When you develop middleware, be sure to test with +Rack::Lint+ to catch possible violations of this specification.
61
+ ##
62
+ ## == The Application
63
+ ##
64
+ ## A Rack application is a Ruby object that responds to +call+. \
65
+ def initialize(app)
66
+ raise LintError, "app must respond to call" unless app.respond_to?(:call)
67
+
68
+ @app = app
69
+ end
70
+
71
+ class Wrapper
72
+ def initialize(app, env)
73
+ @app = app
74
+ @env = env
75
+ @response = nil
76
+ @head_request = false
77
+
78
+ @status = nil
79
+ @headers = nil
80
+ @body = nil
81
+ @consumed = nil
82
+ @content_length = nil
83
+ @closed = false
84
+ @size = 0
85
+ end
86
+
87
+ def response
88
+ ## It takes exactly one argument, the +environment+ (representing an HTTP request) \
89
+ raise LintError, "No env given" unless @env
90
+ check_environment(@env)
91
+
92
+ ## and returns a non-frozen +Array+ of exactly three elements: \
93
+ @response = @app.call(@env)
94
+
95
+ raise LintError, "response is not an Array, but #{@response.class}" unless @response.kind_of? Array
96
+ raise LintError, "response is frozen" if @response.frozen?
97
+ raise LintError, "response array has #{@response.size} elements instead of 3" unless @response.size == 3
98
+
99
+ @status, @headers, @body = @response
100
+ ## the +status+, \
101
+ check_status(@status)
102
+
103
+ ## the +headers+, \
104
+ check_headers(@headers)
105
+
106
+ hijack_proc = check_hijack_response(@headers, @env)
107
+ if hijack_proc
108
+ @headers[RACK_HIJACK] = hijack_proc
109
+ end
110
+
111
+ ## and the +body+ (representing an HTTP response).
112
+ check_content_type_header(@status, @headers)
113
+ check_content_length_header(@status, @headers)
114
+ check_rack_protocol_header(@status, @headers)
115
+ @head_request = @env[REQUEST_METHOD] == HEAD
116
+
117
+ @lint = (@env['rack.lint'] ||= []) << self
118
+
119
+ if (@env['rack.lint.body_iteration'] ||= 0) > 0
120
+ raise LintError, "Middleware must not call #each directly"
121
+ end
122
+
123
+ return [@status, @headers, self]
124
+ end
125
+
126
+ private def assert_required(key)
127
+ raise LintError, "env missing required key #{key}" unless @env.include?(key)
128
+
129
+ return @env[key]
130
+ end
131
+
132
+ ##
133
+ ## == The Request Environment
134
+ ##
135
+ ## Incoming HTTP requests are represented using an environment. \
136
+ def check_environment(env)
137
+ ## The environment must be an unfrozen +Hash+. The Rack application is free to modify the environment, but the modified environment should also comply with this specification. \
138
+ raise LintError, "env #{env.inspect} is not a Hash, but #{env.class}" unless env.kind_of? Hash
139
+ raise LintError, "env should not be frozen, but is" if env.frozen?
140
+
141
+ ## All environment keys must be strings.
142
+ keys = env.keys
143
+ keys.reject!{|key| String === key}
144
+ unless keys.empty?
145
+ raise LintError, "env contains non-string keys: #{keys.inspect}"
146
+ end
147
+
148
+ ##
149
+ ## === CGI Variables
150
+ ##
151
+ ## The environment is required to include these variables, adopted from {The Common Gateway Interface}[https://datatracker.ietf.org/doc/html/rfc3875] (CGI), except when they'd be empty, but see below.
152
+
153
+ ##
154
+ ## The CGI keys (named without a period) must have +String+ values and are reserved for the Rack specification. If the values for CGI keys contain non-ASCII characters, they should use <tt>ASCII-8BIT</tt> encoding.
155
+ env.each do |key, value|
156
+ next if key.include?(".") # Skip extensions
157
+
158
+ unless value.kind_of? String
159
+ raise LintError, "env variable #{key} has non-string value #{value.inspect}"
160
+ end
161
+
162
+ next if value.encoding == Encoding::ASCII_8BIT
163
+
164
+ unless value.b !~ /[\x80-\xff]/n
165
+ raise LintError, "env variable #{key} has value containing non-ASCII characters and has non-ASCII-8BIT encoding #{value.inspect} encoding: #{value.encoding}"
166
+ end
167
+ end
168
+
169
+ ##
170
+ ## The server and application can store their own data in the environment, too. The keys must contain at least one dot, and should be prefixed uniquely. The prefix <tt>rack.</tt> is reserved for use with the Rack specification and the classes that ship with Rack.
171
+
172
+ ##
173
+ ## ==== <tt>REQUEST_METHOD</tt>
174
+ ##
175
+ ## The HTTP request method, such as "GET" or "POST". This cannot ever be an empty string, and so is always required.
176
+ request_method = assert_required(REQUEST_METHOD)
177
+ unless request_method =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
178
+ raise LintError, "REQUEST_METHOD unknown: #{request_method.inspect}"
179
+ end
180
+
181
+ ##
182
+ ## ==== <tt>SCRIPT_NAME</tt>
183
+ ##
184
+ ## The initial portion of the request URL's path that corresponds to the application object, so that the application knows its virtual location. This may be an empty string, if the application corresponds to the root of the server. If non-empty, the string must start with <tt>/</tt>, but should not end with <tt>/</tt>.
185
+ if script_name = env[SCRIPT_NAME]
186
+ if script_name != "" && script_name !~ /\A\//
187
+ raise LintError, "SCRIPT_NAME must start with /"
188
+ end
189
+
190
+ ##
191
+ ## In addition, <tt>SCRIPT_NAME</tt> MUST not be <tt>/</tt>, but instead be empty, \
192
+ if script_name == "/"
193
+ raise LintError, "SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'"
194
+ end
195
+ end
196
+
197
+ ## and one of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be set, e.g. <tt>PATH_INFO</tt> can be <tt>/</tt> if <tt>SCRIPT_NAME</tt> is empty.
198
+ path_info = env[PATH_INFO]
199
+ if (script_name.nil? || script_name.empty?) && (path_info.nil? || path_info.empty?)
200
+ raise LintError, "One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)"
201
+ end
202
+
203
+ ##
204
+ ## ==== <tt>PATH_INFO</tt>
205
+ ##
206
+ ## The remainder of the request URL's "path", designating the virtual "location" of the request's target within the application. This may be an empty string, if the request URL targets the application root and does not have a trailing slash. This value may be percent-encoded when originating from a URL.
207
+ ##
208
+ ## The <tt>PATH_INFO</tt>, if provided, must be a valid request target or an empty string, as defined by {RFC9110}[https://datatracker.ietf.org/doc/html/rfc9110#target.resource].
209
+ case path_info
210
+ when REQUEST_PATH_ASTERISK_FORM
211
+ ## * Only <tt>OPTIONS</tt> requests may have <tt>PATH_INFO</tt> set to <tt>*</tt> (asterisk-form).
212
+ unless request_method == OPTIONS
213
+ raise LintError, "Only OPTIONS requests may have PATH_INFO set to '*' (asterisk-form)"
214
+ end
215
+ when REQUEST_PATH_AUTHORITY_FORM
216
+ ## * Only <tt>CONNECT</tt> requests may have <tt>PATH_INFO</tt> set to an authority (authority-form). Note that in HTTP/2+, the authority-form is not a valid request target.
217
+ unless request_method == CONNECT
218
+ raise LintError, "Only CONNECT requests may have PATH_INFO set to an authority (authority-form)"
219
+ end
220
+ when REQUEST_PATH_ABSOLUTE_FORM
221
+ ## * <tt>CONNECT</tt> and <tt>OPTIONS</tt> requests must not have <tt>PATH_INFO</tt> set to a URI (absolute-form).
222
+ if request_method == CONNECT || request_method == OPTIONS
223
+ raise LintError, "CONNECT and OPTIONS requests must not have PATH_INFO set to a URI (absolute-form)"
224
+ end
225
+ when REQUEST_PATH_ORIGIN_FORM
226
+ ## * Otherwise, <tt>PATH_INFO</tt> must start with a <tt>/</tt> and must not include a fragment part starting with <tt>#</tt> (origin-form).
227
+ when "", nil
228
+ # Empty string or nil is okay.
229
+ else
230
+ raise LintError, "PATH_INFO must start with a '/' and must not include a fragment part starting with '#' (origin-form)"
231
+ end
232
+
233
+ ##
234
+ ## ==== <tt>QUERY_STRING</tt>
235
+ ##
236
+ ## The portion of the request URL that follows the <tt>?</tt>, if any. May be empty, but is always required!
237
+ assert_required(QUERY_STRING)
238
+
239
+ ##
240
+ ## ==== <tt>SERVER_NAME</tt>
241
+ ##
242
+ ## Must be a valid host, as defined by {RFC3986}[https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2].
243
+ ##
244
+ ## When combined with <tt>SCRIPT_NAME</tt>, <tt>PATH_INFO</tt>, and <tt>QUERY_STRING</tt>, these variables can be used to reconstruct the original the request URL. Note, however, that <tt>HTTP_HOST</tt>, if present, should be used in preference to <tt>SERVER_NAME</tt> for reconstructing the request URL.
245
+ server_name = assert_required(SERVER_NAME)
246
+ unless server_name.match?(SERVER_NAME_PATTERN)
247
+ raise LintError, "env[SERVER_NAME] must be a valid host"
248
+ end
249
+
250
+ ##
251
+ ## ==== <tt>SERVER_PROTOCOL</tt>
252
+ ##
253
+ ## The HTTP version used for the request. It must match the regular expression <tt>HTTP\/\d(\.\d)?</tt>.
254
+ server_protocol = assert_required(SERVER_PROTOCOL)
255
+ unless %r{HTTP/\d(\.\d)?}.match?(server_protocol)
256
+ raise LintError, "env[SERVER_PROTOCOL] does not match HTTP/\\d(\\.\\d)?"
257
+ end
258
+
259
+ ##
260
+ ## ==== <tt>SERVER_PORT</tt>
261
+ ##
262
+ ## The port the server is running on, if the server is running on a non-standard port. It must consist of digits only.
263
+ ##
264
+ ## The standard ports are:
265
+ ## * 80 for HTTP
266
+ ## * 443 for HTTPS
267
+ if server_port = env[SERVER_PORT]
268
+ unless server_port =~ /\A\d+\z/
269
+ raise LintError, "env[SERVER_PORT] is not an Integer"
270
+ end
271
+ end
272
+
273
+ ##
274
+ ## ==== <tt>CONTENT_TYPE</tt>
275
+ ##
276
+ ## The optional MIME type of the request body, if any.
277
+ # N.B. We do not validate this field as it is considered user-provided data.
278
+
279
+ ##
280
+ ## ==== <tt>CONTENT_LENGTH</tt>
281
+ ##
282
+ ## The length of the request body, if any. It must consist of digits only.
283
+ if content_length = env["CONTENT_LENGTH"]
284
+ if content_length !~ /\A\d+\z/
285
+ raise LintError, "Invalid CONTENT_LENGTH: #{content_length.inspect}"
286
+ end
287
+ end
288
+
289
+ ##
290
+ ## ==== <tt>HTTP_HOST</tt>
291
+ ##
292
+ ## An optional HTTP authority, as defined by {RFC9110}[https://datatracker.ietf.org/doc/html/rfc9110#name-host-and-authority].
293
+ if http_host = env[HTTP_HOST]
294
+ unless http_host.match?(HTTP_HOST_PATTERN)
295
+ raise LintError, "env[HTTP_HOST] must be a valid authority"
296
+ end
297
+ end
298
+
299
+ ##
300
+ ## ==== <tt>HTTP_</tt> Headers
301
+ ##
302
+ ## Unless specified above, the environment can contain any number of additional headers, each starting with <tt>HTTP_</tt>. The presence or absence of these variables should correspond with the presence or absence of the appropriate HTTP header in the request, and those headers have no specific interpretation or validation by the Rack specification. However, there are many standard HTTP headers that have a specific meaning in the context of a request; see {RFC3875 section 4.1.18}[https://tools.ietf.org/html/rfc3875#section-4.1.18] for more details.
303
+ ##
304
+ ## For compatibility with the CGI specifiction, the environment must not contain the keys <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>. Instead, the keys <tt>CONTENT_TYPE</tt> and <tt>CONTENT_LENGTH</tt> must be used.
305
+ %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each do |header|
306
+ if env.include?(header)
307
+ raise LintError, "env contains #{header}, must use #{header[5..-1]}"
308
+ end
309
+ end
310
+
311
+ ##
312
+ ## === Rack-Specific Variables
313
+ ##
314
+ ## In addition to CGI variables, the Rack environment includes Rack-specific variables. These variables are prefixed with <tt>rack.</tt> and are reserved for use by the Rack specification, or by the classes that ship with Rack.
315
+ ##
316
+ ## ==== <tt>rack.url_scheme</tt>
317
+ ##
318
+ ## The URL scheme, which must be one of <tt>http</tt>, <tt>https</tt>, <tt>ws</tt> or <tt>wss</tt>. This can never be an empty string, and so is always required. The scheme should be set according to the last hop. For example, if a client makes a request to a reverse proxy over HTTPS, but the connection between the reverse proxy and the server is over plain HTTP, the reverse proxy should set <tt>rack.url_scheme</tt> to <tt>http</tt>.
319
+ rack_url_scheme = assert_required(RACK_URL_SCHEME)
320
+ unless ALLOWED_SCHEMES.include?(rack_url_scheme)
321
+ raise LintError, "rack.url_scheme unknown: #{rack_url_scheme.inspect}"
322
+ end
323
+
324
+ ##
325
+ ## ==== <tt>rack.protocol</tt>
326
+ ##
327
+ ## An optional +Array+ of +String+ values, containing the protocols advertised by the client in the <tt>upgrade</tt> header (HTTP/1) or the <tt>:protocol</tt> pseudo-header (HTTP/2+).
328
+ if protocols = env[RACK_PROTOCOL]
329
+ unless protocols.is_a?(Array) && protocols.all?{|protocol| protocol.is_a?(String)}
330
+ raise LintError, "rack.protocol must be an Array of Strings"
331
+ end
332
+ end
333
+
334
+ ##
335
+ ## ==== <tt>rack.session</tt>
336
+ ##
337
+ ## An optional +Hash+-like interface for storing request session data. The store must implement:
338
+ if session = env[RACK_SESSION]
339
+ ## * <tt>store(key, value)</tt> (aliased as <tt>[]=</tt>) to set a value for a key,
340
+ unless session.respond_to?(:store) && session.respond_to?(:[]=)
341
+ raise LintError, "session #{session.inspect} must respond to store and []="
342
+ end
343
+
344
+ ## * <tt>fetch(key, default = nil)</tt> (aliased as <tt>[]</tt>) to retrieve a value for a key,
345
+ unless session.respond_to?(:fetch) && session.respond_to?(:[])
346
+ raise LintError, "session #{session.inspect} must respond to fetch and []"
347
+ end
348
+
349
+ ## * <tt>delete(key)</tt> to delete a key,
350
+ unless session.respond_to?(:delete)
351
+ raise LintError, "session #{session.inspect} must respond to delete"
352
+ end
353
+
354
+ ## * <tt>clear</tt> to clear the session,
355
+ unless session.respond_to?(:clear)
356
+ raise LintError, "session #{session.inspect} must respond to clear"
357
+ end
358
+
359
+ ## * <tt>to_hash</tt> (optional) to retrieve the session as a Hash.
360
+ unless session.respond_to?(:to_hash) && session.to_hash.kind_of?(Hash) && !session.to_hash.frozen?
361
+ raise LintError, "session #{session.inspect} must respond to to_hash and return unfrozen Hash instance"
362
+ end
363
+ end
364
+
365
+ ##
366
+ ## ==== <tt>rack.logger</tt>
367
+ ##
368
+ ## An optional +Logger+-like interface for logging messages. The logger must implement:
369
+ if logger = env[RACK_LOGGER]
370
+ ## * <tt>info(message, &block)</tt>,
371
+ unless logger.respond_to?(:info)
372
+ raise LintError, "logger #{logger.inspect} must respond to info"
373
+ end
374
+
375
+ ## * <tt>debug(message, &block)</tt>,
376
+ unless logger.respond_to?(:debug)
377
+ raise LintError, "logger #{logger.inspect} must respond to debug"
378
+ end
379
+
380
+ ## * <tt>warn(message, &block)</tt>,
381
+ unless logger.respond_to?(:warn)
382
+ raise LintError, "logger #{logger.inspect} must respond to warn"
383
+ end
384
+
385
+ ## * <tt>error(message, &block)</tt>,
386
+ unless logger.respond_to?(:error)
387
+ raise LintError, "logger #{logger.inspect} must respond to error"
388
+ end
389
+
390
+ ## * <tt>fatal(message, &block)</tt>.
391
+ unless logger.respond_to?(:fatal)
392
+ raise LintError, "logger #{logger.inspect} must respond to fatal"
393
+ end
394
+ end
395
+
396
+ ##
397
+ ## ==== <tt>rack.multipart.buffer_size</tt>
398
+ ##
399
+ ## An optional +Integer+ hint to the multipart parser as to what chunk size to use for reads and writes.
400
+ if rack_multipart_buffer_size = env[RACK_MULTIPART_BUFFER_SIZE]
401
+ unless rack_multipart_buffer_size.is_a?(Integer) && rack_multipart_buffer_size > 0
402
+ raise LintError, "rack.multipart.buffer_size must be an Integer > 0 if specified"
403
+ end
404
+ end
405
+
406
+ ##
407
+ ## ==== <tt>rack.multipart.tempfile_factory</tt>
408
+ ##
409
+ ## An optional object for constructing temporary files for multipart form data. The factory must implement:
410
+ if rack_multipart_tempfile_factory = env[RACK_MULTIPART_TEMPFILE_FACTORY]
411
+ ## * <tt>call(filename, content_type)</tt> to create a temporary file for a multipart form field.
412
+ unless rack_multipart_tempfile_factory.respond_to?(:call)
413
+ raise LintError, "rack.multipart.tempfile_factory must respond to #call"
414
+ end
415
+
416
+ ## The factory must return an +IO+-like object that responds to <tt><<</tt> and optionally <tt>rewind</tt>.
417
+ env[RACK_MULTIPART_TEMPFILE_FACTORY] = lambda do |filename, content_type|
418
+ io = rack_multipart_tempfile_factory.call(filename, content_type)
419
+ unless io.respond_to?(:<<)
420
+ raise LintError, "rack.multipart.tempfile_factory return value must respond to #<<"
421
+ end
422
+ io
423
+ end
424
+ end
425
+
426
+ ##
427
+ ## ==== <tt>rack.hijack?</tt>
428
+ ##
429
+ ## If present and truthy, indicates that the server supports partial hijacking. See the section below on hijacking for more information.
430
+ #
431
+ # N.B. There is no specific validation here. If the user provides a partial hijack response, we will confirm this value is truthy in `check_hijack_response`.
432
+
433
+ ##
434
+ ## ==== <tt>rack.hijack</tt>
435
+ ##
436
+ ## If present, an object responding to +call+ that is used to perform a full hijack. See the section below on hijacking for more information.
437
+ check_hijack(env)
438
+
439
+ ##
440
+ ## ==== <tt>rack.early_hints</tt>
441
+ ##
442
+ ## If present, an object responding to +call+ that is used to send early hints. See the section below on early hints for more information.
443
+ check_early_hints env
444
+
445
+ ##
446
+ ## ==== <tt>rack.input</tt>
447
+ ##
448
+ ## If present, the input stream. See the section below on the input stream for more information.
449
+ if rack_input = env[RACK_INPUT]
450
+ check_input_stream(rack_input)
451
+ @env[RACK_INPUT] = InputWrapper.new(rack_input)
452
+ end
453
+
454
+ ##
455
+ ## ==== <tt>rack.errors</tt>
456
+ ##
457
+ ## The error stream. See the section below on the error stream for more information.
458
+ rack_errors = assert_required(RACK_ERRORS)
459
+ check_error_stream(rack_errors)
460
+ @env[RACK_ERRORS] = ErrorWrapper.new(rack_errors)
461
+
462
+ ##
463
+ ## ==== <tt>rack.response_finished</tt>
464
+ ##
465
+ ## If present, an array of callables that will be run by the server after the response has been processed. Typically this will be after sending the response to the client, but it could also be if an error occurs while generating the response or sending the response.
466
+ ##
467
+ ## The callables must be called in reverse order with four arguments which must be:
468
+ if rack_response_finished = env[RACK_RESPONSE_FINISHED]
469
+ raise LintError, "rack.response_finished must be an array of callable objects" unless rack_response_finished.is_a?(Array)
470
+
471
+ rack_response_finished.map! do |callable|
472
+ raise LintError, "rack.response_finished values must respond to call(env, status, headers, error)" unless callable.respond_to?(:call)
473
+
474
+ if ResponseFinishedWrapper === callable
475
+ callable
476
+ else
477
+ ResponseFinishedWrapper.new(self, callable)
478
+ end
479
+ end
480
+ end
481
+ end
482
+
483
+ class ResponseFinishedWrapper
484
+ def initialize(wrapper, callback)
485
+ @wrapper = wrapper
486
+ @callback = callback
487
+ end
488
+
489
+ def call(env, status, headers, error)
490
+ ## * <tt>env</tt> a valid Rack environment
491
+ @wrapper.check_environment(env)
492
+
493
+ ## * <tt>status</tt> a valid Rack status (or +nil+)
494
+ status.nil? || @wrapper.check_status(status)
495
+
496
+ ## * <tt>headers</tt> valid Rack response headers (or +nil+)
497
+ headers.nil? || @wrapper.check_headers(headers)
498
+
499
+ ## * <tt>error</tt> an Exception (or +nil+)
500
+ unless error.nil? || Exception === error
501
+ raise LintError, "rack.response_finished callable's fourth argument must be an Exception or nil, got #{error}"
502
+ end
503
+
504
+ @callback.call(env, status, headers, error)
505
+ end
506
+
507
+ ## and should not raise any exceptions.
508
+ end
509
+
510
+ ##
511
+ ## === The Input Stream
512
+ ##
513
+ ## The input stream is an +IO+-like object which contains the raw HTTP request data. \
514
+ def check_input_stream(input)
515
+ ## When applicable, its external encoding must be <tt>ASCII-8BIT</tt> and it must be opened in binary mode. \
516
+ if input.respond_to?(:external_encoding) && input.external_encoding != Encoding::ASCII_8BIT
517
+ raise LintError, "rack.input #{input} does not have ASCII-8BIT as its external encoding"
518
+ end
519
+ if input.respond_to?(:binmode?) && !input.binmode?
520
+ raise LintError, "rack.input #{input} is not opened in binary mode"
521
+ end
522
+
523
+ ## The input stream must respond to +gets+, +each+, and +read+:
524
+ [:gets, :each, :read].each do |method|
525
+ unless input.respond_to? method
526
+ raise LintError, "rack.input #{input} does not respond to ##{method}"
527
+ end
528
+ end
529
+ end
530
+
531
+ class InputWrapper
532
+ def initialize(input)
533
+ @input = input
534
+ end
535
+
536
+ ## * +gets+ must be called without arguments and return a +String+, or +nil+ on EOF (end-of-file).
537
+ def gets(*args)
538
+ raise LintError, "rack.input#gets called with arguments" unless args.size == 0
539
+
540
+ chunk = @input.gets
541
+
542
+ unless chunk.nil? or chunk.kind_of? String
543
+ raise LintError, "rack.input#gets didn't return a String"
544
+ end
545
+
546
+ chunk
547
+ end
548
+
549
+ ## * +read+ behaves like <tt>IO#read</tt>. Its signature is <tt>read([length, [buffer]])</tt>.
550
+ ## * If given, +length+ must be a non-negative Integer (>= 0) or +nil+, and +buffer+ must be a +String+ and may not be +nil+.
551
+ ## * If +length+ is given and not +nil+, then this method reads at most +length+ bytes from the input stream.
552
+ ## * If +length+ is not given or +nil+, then this method reads all data until EOF.
553
+ ## * When EOF is reached, this method returns +nil+ if +length+ is given and not +nil+, or +""+ if +length+ is not given or is +nil+.
554
+ ## * If +buffer+ is given, then the read data will be placed into +buffer+ instead of a newly created +String+.
555
+ def read(*args)
556
+ unless args.size <= 2
557
+ raise LintError, "rack.input#read called with too many arguments"
558
+ end
559
+ if args.size >= 1
560
+ unless args.first.kind_of?(Integer) || args.first.nil?
561
+ raise LintError, "rack.input#read called with non-integer and non-nil length"
562
+ end
563
+ unless args.first.nil? || args.first >= 0
564
+ raise LintError, "rack.input#read called with a negative length"
565
+ end
566
+ end
567
+ if args.size >= 2
568
+ unless args[1].kind_of?(String)
569
+ raise LintError, "rack.input#read called with non-String buffer"
570
+ end
571
+ end
572
+
573
+ chunk = @input.read(*args)
574
+
575
+ unless chunk.nil? or chunk.kind_of? String
576
+ raise LintError, "rack.input#read didn't return nil or a String"
577
+ end
578
+ if args[0].nil?
579
+ unless !chunk.nil?
580
+ raise LintError, "rack.input#read(nil) returned nil on EOF"
581
+ end
582
+ end
583
+
584
+ chunk
585
+ end
586
+
587
+ ## * +each+ must be called without arguments and only yield +String+ values.
588
+ def each(*args)
589
+ raise LintError, "rack.input#each called with arguments" unless args.size == 0
590
+ @input.each do |line|
591
+ unless line.kind_of? String
592
+ raise LintError, "rack.input#each didn't yield a String"
593
+ end
594
+ yield line
595
+ end
596
+ end
597
+
598
+ ## * +close+ can be called on the input stream to indicate that any remaining input is not needed.
599
+ def close(*args)
600
+ @input.close(*args)
601
+ end
602
+ end
603
+
604
+ ##
605
+ ## === The Error Stream
606
+ ##
607
+ def check_error_stream(error)
608
+ ## The error stream must respond to +puts+, +write+ and +flush+:
609
+ [:puts, :write, :flush].each do |method|
610
+ unless error.respond_to? method
611
+ raise LintError, "rack.error #{error} does not respond to ##{method}"
612
+ end
613
+ end
614
+ end
615
+
616
+ class ErrorWrapper
617
+ def initialize(error)
618
+ @error = error
619
+ end
620
+
621
+ ## * +puts+ must be called with a single argument that responds to +to_s+.
622
+ def puts(str)
623
+ @error.puts str
624
+ end
625
+
626
+ ## * +write+ must be called with a single argument that is a +String+.
627
+ def write(str)
628
+ raise LintError, "rack.errors#write not called with a String" unless str.kind_of? String
629
+ @error.write str
630
+ end
631
+
632
+ ## * +flush+ must be called without arguments and must be called in order to make the error appear for sure.
633
+ def flush
634
+ @error.flush
635
+ end
636
+
637
+ ## * +close+ must never be called on the error stream.
638
+ def close(*args)
639
+ raise LintError, "rack.errors#close must not be called"
640
+ end
641
+ end
642
+
643
+ ##
644
+ ## === Hijacking
645
+ ##
646
+ ## The hijacking interfaces provides a means for an application to take control of the HTTP connection. There are two distinct hijack interfaces: full hijacking where the application takes over the raw connection, and partial hijacking where the application takes over just the response body stream. In both cases, the application is responsible for closing the hijacked stream.
647
+ ##
648
+ ## Full hijacking only works with HTTP/1. Partial hijacking is functionally equivalent to streaming bodies, and is still optionally supported for backwards compatibility with older Rack versions.
649
+ ##
650
+ ## ==== Full Hijack
651
+ ##
652
+ ## Full hijack is used to completely take over an HTTP/1 connection. It occurs before any headers are written and causes the server to ignore any response generated by the application. It is intended to be used when applications need access to the raw HTTP/1 connection.
653
+ ##
654
+ def check_hijack(env)
655
+ ## If <tt>rack.hijack</tt> is present in +env+, it must respond to +call+ \
656
+ if original_hijack = env[RACK_HIJACK]
657
+ raise LintError, "rack.hijack must respond to call" unless original_hijack.respond_to?(:call)
658
+
659
+ env[RACK_HIJACK] = proc do
660
+ io = original_hijack.call
661
+
662
+ ## and return an +IO+ object which can be used to read and write to the underlying connection using HTTP/1 semantics and formatting.
663
+ raise LintError, "rack.hijack must return an IO instance" unless io.is_a?(IO)
664
+
665
+ io
666
+ end
667
+ end
668
+ end
669
+
670
+ ##
671
+ ## ==== Partial Hijack
672
+ ##
673
+ ## Partial hijack is used for bi-directional streaming of the request and response body. It occurs after the status and headers are written by the server and causes the server to ignore the Body of the response. It is intended to be used when applications need bi-directional streaming.
674
+ ##
675
+ def check_hijack_response(headers, env)
676
+ ## If <tt>rack.hijack?</tt> is present in +env+ and truthy, \
677
+ if env[RACK_IS_HIJACK]
678
+ ## an application may set the special response header <tt>rack.hijack</tt> \
679
+ if original_hijack = headers[RACK_HIJACK]
680
+ ## to an object that responds to +call+, \
681
+ unless original_hijack.respond_to?(:call)
682
+ raise LintError, 'rack.hijack header must respond to #call'
683
+ end
684
+ ## accepting a +stream+ argument.
685
+ return proc do |io|
686
+ original_hijack.call StreamWrapper.new(io)
687
+ end
688
+ end
689
+ ##
690
+ ## After the response status and headers have been sent, this hijack callback will be called with a +stream+ argument which follows the same interface as outlined in "Streaming Body". Servers must ignore the +body+ part of the response tuple when the <tt>rack.hijack</tt> response header is present. Using an empty +Array+ is recommended.
691
+ else
692
+ ##
693
+ ## If <tt>rack.hijack?</tt> is not present and truthy, the special response header <tt>rack.hijack</tt> must not be present in the response headers.
694
+ if headers.key?(RACK_HIJACK)
695
+ raise LintError, 'rack.hijack header must not be present if server does not support hijacking'
696
+ end
697
+ end
698
+
699
+ nil
700
+ end
701
+
702
+ ##
703
+ ## === Early Hints
704
+ ##
705
+ ## The application or any middleware may call the <tt>rack.early_hints</tt> with an object which would be valid as the headers of a Rack response.
706
+ def check_early_hints(env)
707
+ if env[RACK_EARLY_HINTS]
708
+ ##
709
+ ## If <tt>rack.early_hints</tt> is present, it must respond to +call+.
710
+ unless env[RACK_EARLY_HINTS].respond_to?(:call)
711
+ raise LintError, "rack.early_hints must respond to call"
712
+ end
713
+
714
+ original_callback = env[RACK_EARLY_HINTS]
715
+ env[RACK_EARLY_HINTS] = lambda do |headers|
716
+ ## If <tt>rack.early_hints</tt> is called, it must be called with valid Rack response headers.
717
+ check_headers(headers)
718
+ original_callback.call(headers)
719
+ end
720
+ end
721
+ end
722
+
723
+ ##
724
+ ## == The Response
725
+ ##
726
+ ## Outgoing HTTP responses are generated from the response tuple generated by the application. The response tuple is an +Array+ of three elements, which are: the HTTP status, the headers, and the response body. The Rack application is responsible for ensuring that the response tuple is well-formed and should follow the rules set out in this specification.
727
+ ##
728
+ ## === The Status
729
+ ##
730
+ def check_status(status)
731
+ ## This is an HTTP status. It must be an Integer greater than or equal to 100.
732
+ unless status.is_a?(Integer) && status >= 100
733
+ raise LintError, "Status must be an Integer >=100"
734
+ end
735
+ end
736
+
737
+ ##
738
+ ## === The Headers
739
+ ##
740
+ def check_headers(headers)
741
+ ## The headers must be an unfrozen +Hash+. \
742
+ unless headers.kind_of?(Hash)
743
+ raise LintError, "headers object should be a hash, but isn't (got #{headers.class} as headers)"
744
+ end
745
+
746
+ if headers.frozen?
747
+ raise LintError, "headers object should not be frozen, but is"
748
+ end
749
+
750
+ headers.each do |key, value|
751
+ ## The header keys must be +String+ values. \
752
+ unless key.kind_of? String
753
+ raise LintError, "header key must be a string, was #{key.class}"
754
+ end
755
+
756
+ ## Special headers starting <tt>rack.</tt> are for communicating with the server, and must not be sent back to the client.
757
+ next if key.start_with?("rack.")
758
+
759
+ ##
760
+ ## * The headers must not contain a <tt>"status"</tt> key.
761
+ raise LintError, "headers must not contain status" if key == "status"
762
+ ## * Header keys must conform to {RFC7230}[https://tools.ietf.org/html/rfc7230] token specification, i.e. cannot contain non-printable ASCII, <tt>DQUOTE</tt> or <tt>(),/:;<=>?@[\]{}</tt>.
763
+ raise LintError, "invalid header name: #{key}" if key =~ /[\(\),\/:;<=>\?@\[\\\]{}[:cntrl:]]/
764
+ ## * Header keys must not contain uppercase ASCII characters (A-Z).
765
+ raise LintError, "uppercase character in header name: #{key}" if key =~ /[A-Z]/
766
+
767
+ ## * Header values must be either a +String+, \
768
+ if value.kind_of?(String)
769
+ check_header_value(key, value)
770
+ elsif value.kind_of?(Array)
771
+ ## or an +Array+ of +String+ values, \
772
+ value.each{|value| check_header_value(key, value)}
773
+ else
774
+ raise LintError, "a header value must be a String or Array of Strings, but the value of '#{key}' is a #{value.class}"
775
+ end
776
+ end
777
+ end
778
+
779
+ def check_header_value(key, value)
780
+ ## such that each +String+ must not contain <tt>NUL</tt> (<tt>\0</tt>), <tt>CR</tt> (<tt>\r</tt>), or <tt>LF</tt> (<tt>\n</tt>).
781
+ if value.match?(/[\x00\x0A\x0D]/)
782
+ raise LintError, "invalid header value #{key}: #{value.inspect}"
783
+ end
784
+ end
785
+
786
+ ##
787
+ ## ==== The <tt>content-type</tt> Header
788
+ ##
789
+ def check_content_type_header(status, headers)
790
+ headers.each do |key, value|
791
+ ## There must not be a <tt>content-type</tt> header key when the status is <tt>1xx</tt>, <tt>204</tt>, or <tt>304</tt>.
792
+ if key == "content-type"
793
+ if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i
794
+ raise LintError, "content-type header found in #{status} response, not allowed"
795
+ end
796
+ return
797
+ end
798
+ end
799
+ end
800
+
801
+ ##
802
+ ## ==== The <tt>content-length</tt> Header
803
+ ##
804
+ def check_content_length_header(status, headers)
805
+ headers.each do |key, value|
806
+ if key == 'content-length'
807
+ ## There must not be a <tt>content-length</tt> header key when the status is <tt>1xx</tt>, <tt>204</tt>, or <tt>304</tt>.
808
+ if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key? status.to_i
809
+ raise LintError, "content-length header found in #{status} response, not allowed"
810
+ end
811
+ @content_length = value
812
+ end
813
+ end
814
+ end
815
+
816
+ def verify_content_length(size)
817
+ if @head_request
818
+ unless size == 0
819
+ raise LintError, "Response body was given for HEAD request, but should be empty"
820
+ end
821
+ elsif @content_length
822
+ unless @content_length == size.to_s
823
+ raise LintError, "content-length header was #{@content_length}, but should be #{size}"
824
+ end
825
+ end
826
+ end
827
+
828
+ ##
829
+ ## ==== The <tt>rack.protocol</tt> Header
830
+ ##
831
+ def check_rack_protocol_header(status, headers)
832
+ ## If the <tt>rack.protocol</tt> header is present, it must be a +String+, and must be one of the values from the <tt>rack.protocol</tt> array from the environment.
833
+ protocol = headers['rack.protocol']
834
+
835
+ if protocol
836
+ request_protocols = @env['rack.protocol']
837
+
838
+ if request_protocols.nil?
839
+ raise LintError, "rack.protocol header is #{protocol.inspect}, but rack.protocol was not set in request!"
840
+ elsif !request_protocols.include?(protocol)
841
+ raise LintError, "rack.protocol header is #{protocol.inspect}, but should be one of #{request_protocols.inspect} from the request!"
842
+ end
843
+ end
844
+ end
845
+ ##
846
+ ## Setting this value informs the server that it should perform a connection upgrade. In HTTP/1, this is done using the +upgrade+ header. In HTTP/2+, this is done by accepting the request.
847
+ ##
848
+ ## === The Body
849
+ ##
850
+ ## The Body is typically an +Array+ of +String+ values, an enumerable that yields +String+ values, a +Proc+, or an +IO+-like object.
851
+ ##
852
+ ## The Body must respond to +each+ or +call+. It may optionally respond to +to_path+ or +to_ary+. A Body that responds to +each+ is considered to be an Enumerable Body. A Body that responds to +call+ is considered to be a Streaming Body.
853
+ ##
854
+ ## A Body that responds to both +each+ and +call+ must be treated as an Enumerable Body, not a Streaming Body. If it responds to +each+, you must call +each+ and not +call+. If the Body doesn't respond to +each+, then you can assume it responds to +call+.
855
+ ##
856
+ ## The Body must either be consumed or returned. The Body is consumed by optionally calling either +each+ or +call+. Then, if the Body responds to +close+, it must be called to release any resources associated with the generation of the body. In other words, +close+ must always be called at least once; typically after the web server has sent the response to the client, but also in cases where the Rack application makes internal/virtual requests and discards the response.
857
+ def close
858
+ ##
859
+ ## After calling +close+, the Body is considered closed and should not be consumed again. \
860
+ @closed = true
861
+
862
+ ## If the original Body is replaced by a new Body, the new Body must also consume the original Body by calling +close+ if possible.
863
+ @body.close if @body.respond_to?(:close)
864
+
865
+ index = @lint.index(self)
866
+ unless @env['rack.lint'][0..index].all? {|lint| lint.instance_variable_get(:@closed)}
867
+ raise LintError, "Body has not been closed"
868
+ end
869
+ end
870
+
871
+ def verify_to_path
872
+ ##
873
+ ## If the Body responds to +to_path+, it must return either +nil+ or a +String+. If a +String+ is returned, it must be a path for the local file system whose contents are identical to that produced by calling +each+; this may be used by the server as an alternative, possibly more efficient way to transport the response. The +to_path+ method does not consume the body.
874
+ if @body.respond_to?(:to_path)
875
+ optional_path = @body.to_path
876
+
877
+ if optional_path != nil
878
+ unless optional_path.is_a?(String) && ::File.exist?(optional_path)
879
+ raise LintError, "body.to_path must be nil or a path to an existing file"
880
+ end
881
+ end
882
+ end
883
+ end
884
+
885
+ ##
886
+ ## ==== Enumerable Body
887
+ ##
888
+ def each
889
+ ## The Enumerable Body must respond to +each+, \
890
+ raise LintError, "Enumerable Body must respond to each" unless @body.respond_to?(:each)
891
+
892
+ ## which must only be called once, \
893
+ raise LintError, "Response body must only be called once (#{@consumed})" unless @consumed.nil?
894
+
895
+ ## must not be called after being closed, \
896
+ raise LintError, "Response body is already closed" if @closed
897
+
898
+ @consumed = :each
899
+
900
+ @body.each do |chunk|
901
+ ## and must only yield +String+ values.
902
+ unless chunk.kind_of? String
903
+ raise LintError, "Body yielded non-string value #{chunk.inspect}"
904
+ end
905
+
906
+ ##
907
+ ## Middleware must not call +each+ directly on the Body. Instead, middleware can return a new Body that calls +each+ on the original Body, yielding at least once per iteration.
908
+ if @lint[0] == self
909
+ @env['rack.lint.body_iteration'] += 1
910
+ else
911
+ if (@env['rack.lint.body_iteration'] -= 1) > 0
912
+ raise LintError, "New body must yield at least once per iteration of old body"
913
+ end
914
+ end
915
+
916
+ @size += chunk.bytesize
917
+ yield chunk
918
+ end
919
+
920
+ verify_content_length(@size)
921
+
922
+ verify_to_path
923
+ end
924
+
925
+ BODY_METHODS = {to_ary: true, each: true, call: true, to_path: true}
926
+
927
+ def to_path
928
+ @body.to_path
929
+ end
930
+
931
+ def respond_to?(name, *)
932
+ if BODY_METHODS.key?(name)
933
+ @body.respond_to?(name)
934
+ else
935
+ super
936
+ end
937
+ end
938
+
939
+ ##
940
+ ## If the Body responds to +to_ary+, it must return an +Array+ whose contents are identical to that produced by calling +each+. Middleware may call +to_ary+ directly on the Body and return a new Body in its place. In other words, middleware can only process the Body directly if it responds to +to_ary+. If the Body responds to both +to_ary+ and +close+, its implementation of +to_ary+ must call +close+.
941
+ def to_ary
942
+ @body.to_ary.tap do |content|
943
+ unless content == @body.enum_for.to_a
944
+ raise LintError, "#to_ary not identical to contents produced by calling #each"
945
+ end
946
+ end
947
+ ensure
948
+ close
949
+ end
950
+
951
+ ##
952
+ ## ==== Streaming Body
953
+ ##
954
+ def call(stream)
955
+ ## The Streaming Body must respond to +call+, \
956
+ raise LintError, "Streaming Body must respond to call" unless @body.respond_to?(:call)
957
+
958
+ ## which must only be called once, \
959
+ raise LintError, "Response body must only be called once (#{@consumed})" unless @consumed.nil?
960
+
961
+ ## must not be called after being closed, \
962
+ raise LintError, "Response body is already closed" if @closed
963
+
964
+ @consumed = :call
965
+
966
+ ## and accept a +stream+ argument.
967
+ ##
968
+ ## The +stream+ argument must respond to: +read+, +write+, <tt><<</tt>, +flush+, +close+, +close_read+, +close_write+, and +closed?+. \
969
+ @body.call(StreamWrapper.new(stream))
970
+ end
971
+
972
+ class StreamWrapper
973
+ extend Forwardable
974
+
975
+ ## The semantics of these +IO+ methods must be a best effort match to those of a normal Ruby +IO+ or +Socket+ object, using standard arguments and raising standard exceptions. Servers may simply pass on real +IO+ objects to the Streaming Body. In some cases (e.g. when using <tt>transfer-encoding</tt> or HTTP/2+), the server may need to provide a wrapper that implements the required methods, in order to provide the correct semantics.
976
+ REQUIRED_METHODS = [
977
+ :read, :write, :<<, :flush, :close,
978
+ :close_read, :close_write, :closed?
979
+ ]
980
+
981
+ def_delegators :@stream, *REQUIRED_METHODS
982
+
983
+ def initialize(stream)
984
+ @stream = stream
985
+
986
+ REQUIRED_METHODS.each do |method_name|
987
+ raise LintError, "Stream must respond to #{method_name}" unless stream.respond_to?(method_name)
988
+ end
989
+ end
990
+ end
991
+ end
992
+ end
993
+ end
994
+
995
+ ##
996
+ ## == Thanks
997
+ ##
998
+ ## We'd like to thank everyone who has contributed to the Rack project over the years. Your work has made this specification possible. That includes everyone who has contributed code, documentation, bug reports, and feedback. We'd also like to thank the authors of the various web servers, frameworks, and libraries that have implemented the Rack specification. Your work has helped to make the web a better place.
999
+ ##
1000
+ ## Some parts of this specification are adapted from {PEP 333 – Python Web Server Gateway Interface v1.0}[https://peps.python.org/pep-0333/]. We'd like to thank everyone involved in that effort.