rack 3.0.15 → 3.2.6

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