rack 3.1.16 → 3.2.0

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