4 # Rack::Lint validates your application and the requests and
5 # responses according to the Rack spec.
14 class LintError
< RuntimeError
; end
16 def assert(message
, &block
)
18 raise LintError
, message
24 ## This specification aims to formalize the Rack protocol. You
25 ## can (and should) use Rack::Lint to enforce it.
27 ## When you develop middleware, be sure to add a Lint before and
28 ## after to catch all mistakes.
30 ## = Rack applications
32 ## A Rack application is an Ruby object (not a class) that
33 ## responds to +call+.
39 ## It takes exactly one argument, the *environment*
40 assert("No env given") { env }
43 env['rack.input'] = InputWrapper
.new(env['rack.input'])
44 env['rack.errors'] = ErrorWrapper
.new(env['rack.errors'])
46 ## and returns an Array of exactly three values:
47 status
, headers
, @body = @app.call(env)
53 check_content_type status
, headers
54 check_content_length status
, headers
, env
55 [status
, headers
, self]
60 ## The environment must be an true instance of Hash (no
61 ## subclassing allowed) that includes CGI-like headers.
62 ## The application is free to modify the environment.
63 assert("env #{env.inspect} is not a Hash, but #{env.class}") {
68 ## The environment is required to include these variables
69 ## (adopted from PEP333), except when they'd be empty, but see
72 ## <tt>REQUEST_METHOD</tt>:: The HTTP request method, such as
73 ## "GET" or "POST". This cannot ever
74 ## be an empty string, and so is
77 ## <tt>SCRIPT_NAME</tt>:: The initial portion of the request
78 ## URL's "path" that corresponds to the
79 ## application object, so that the
80 ## application knows its virtual
81 ## "location". This may be an empty
82 ## string, if the application corresponds
83 ## to the "root" of the server.
85 ## <tt>PATH_INFO</tt>:: The remainder of the request URL's
86 ## "path", designating the virtual
87 ## "location" of the request's target
88 ## within the application. This may be an
89 ## empty string, if the request URL targets
90 ## the application root and does not have a
91 ## trailing slash. This information should be
92 ## decoded by the server if it comes from a
95 ## <tt>QUERY_STRING</tt>:: The portion of the request URL that
96 ## follows the <tt>?</tt>, if any. May be
97 ## empty, but is always required!
99 ## <tt>SERVER_NAME</tt>, <tt>SERVER_PORT</tt>:: When combined with <tt>SCRIPT_NAME</tt> and <tt>PATH_INFO</tt>, these variables can be used to complete the 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. <tt>SERVER_NAME</tt> and <tt>SERVER_PORT</tt> can never be empty strings, and so are always required.
101 ## <tt>HTTP_</tt> Variables:: Variables corresponding to the
102 ## client-supplied HTTP request
103 ## headers (i.e., variables whose
104 ## names begin with <tt>HTTP_</tt>). The
105 ## presence or absence of these
106 ## variables should correspond with
107 ## the presence or absence of the
108 ## appropriate HTTP header in the
111 ## In addition to this, the Rack environment must include these
112 ## Rack-specific variables:
114 ## <tt>rack.version</tt>:: The Array [0,1], representing this version of Rack.
115 ## <tt>rack.url_scheme</tt>:: +http+ or +https+, depending on the request URL.
116 ## <tt>rack.input</tt>:: See below, the input stream.
117 ## <tt>rack.errors</tt>:: See below, the error stream.
118 ## <tt>rack.multithread</tt>:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise.
119 ## <tt>rack.multiprocess</tt>:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise.
120 ## <tt>rack.run_once</tt>:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar).
122 ## The server or the application can store their own data in the
123 ## environment, too. The keys must contain at least one dot,
124 ## and should be prefixed uniquely. The prefix <tt>rack.</tt>
125 ## is reserved for use with the Rack core distribution and must
126 ## not be used otherwise.
129 %w
[REQUEST_METHOD SERVER_NAME SERVER_PORT
131 rack
.version rack
.input rack
.errors
132 rack
.multithread rack
.multiprocess rack
.run_once
].each
{ |header
|
133 assert("env missing required key #{header}") { env.include? header
}
136 ## The environment must not contain the keys
137 ## <tt>HTTP_CONTENT_TYPE</tt> or <tt>HTTP_CONTENT_LENGTH</tt>
138 ## (use the versions without <tt>HTTP_</tt>).
139 %w
[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH
].each
{ |header
|
140 assert("env contains #{header}, must use #{header[5,-1]}") {
141 not env.include? header
145 ## The CGI keys (named without a period) must have String values.
146 env.each
{ |key
, value
|
147 next if key
.include? "." # Skip extensions
148 assert("env variable #{key} has non-string value #{value.inspect}") {
149 value
.instance_of
? String
154 ## There are the following restrictions:
156 ## * <tt>rack.version</tt> must be an array of Integers.
157 assert("rack.version must be an Array, was #{env["rack
.version"].class}") {
158 env["rack.version"].instance_of
? Array
160 ## * <tt>rack.url_scheme</tt> must either be +http+ or +https+.
161 assert("rack.url_scheme unknown: #{env["rack
.url_scheme
"].inspect}") {
162 %w
[http https
].include? env["rack.url_scheme"]
165 ## * There must be a valid input stream in <tt>rack.input</tt>.
166 check_input
env["rack.input"]
167 ## * There must be a valid error stream in <tt>rack.errors</tt>.
168 check_error
env["rack.errors"]
170 ## * The <tt>REQUEST_METHOD</tt> must be a valid token.
171 assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD
"]}") {
172 env["REQUEST_METHOD"] =~
/\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/
175 ## * The <tt>SCRIPT_NAME</tt>, if non-empty, must start with <tt>/</tt>
176 assert("SCRIPT_NAME must start with /") {
177 !env.include?("SCRIPT_NAME") ||
178 env["SCRIPT_NAME"] == "" ||
179 env["SCRIPT_NAME"] =~
/\A\//
181 ## * The <tt>PATH_INFO</tt>, if non-empty, must start with <tt>/</tt>
182 assert("PATH_INFO must start with /") {
183 !env.include?("PATH_INFO") ||
184 env["PATH_INFO"] == "" ||
185 env["PATH_INFO"] =~
/\A\//
187 ## * The <tt>CONTENT_LENGTH</tt>, if given, must consist of digits only.
188 assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH
"]}") {
189 !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~
/\A\d+\z/
192 ## * One of <tt>SCRIPT_NAME</tt> or <tt>PATH_INFO</tt> must be
193 ## set. <tt>PATH_INFO</tt> should be <tt>/</tt> if
194 ## <tt>SCRIPT_NAME</tt> is empty.
195 assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") {
196 env["SCRIPT_NAME"] || env["PATH_INFO"]
198 ## <tt>SCRIPT_NAME</tt> never should be <tt>/</tt>, but instead be empty.
199 assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") {
200 env["SCRIPT_NAME"] != "/"
204 ## === The Input Stream
205 def check_input(input
)
206 ## The input stream must respond to +gets+, +each+ and +read+.
207 [:gets, :each, :read].each
{ |method
|
208 assert("rack.input #{input} does not respond to ##{method}") {
209 input
.respond_to
? method
217 def initialize(input
)
229 ## * +gets+ must be called without arguments and return a string,
232 assert("rack.input#gets called with arguments") { args
.size
== 0 }
234 assert("rack.input#gets didn't return a String") {
235 v
.nil? or v
.instance_of
? String
240 ## * +read+ must be called without or with one integer argument
241 ## and return a string, or +nil+ on EOF.
243 assert("rack.input#read called with too many arguments") {
247 assert("rack.input#read called with non-integer argument") {
248 args
.first
.kind_of
? Integer
251 v
= @input.read(*args
)
252 assert("rack.input#read didn't return a String") {
253 v
.nil? or v
.instance_of
? String
258 ## * +each+ must be called without arguments and only yield Strings.
260 assert("rack.input#each called with arguments") { args
.size
== 0 }
262 assert("rack.input#each didn't yield a String") {
263 line
.instance_of
? String
269 ## * +close+ must never be called on the input stream.
271 assert("rack.input#close must not be called") { false }
275 ## === The Error Stream
276 def check_error(error
)
277 ## The error stream must respond to +puts+, +write+ and +flush+.
278 [:puts, :write, :flush].each
{ |method
|
279 assert("rack.error #{error} does not respond to ##{method}") {
280 error
.respond_to
? method
288 def initialize(error
)
292 ## * +puts+ must be called with a single argument that responds to +to_s+.
297 ## * +write+ must be called with a single argument that is a String.
299 assert("rack.errors#write not called with a String") { str
.instance_of
? String
}
303 ## * +flush+ must be called without arguments and must be called
304 ## in order to make the error appear for sure.
309 ## * +close+ must never be called on the error stream.
311 assert("rack.errors#close must not be called") { false }
318 def check_status(status
)
319 ## The status, if parsed as integer (+to_i+), must be greater than or equal to 100.
320 assert("Status must be >=100 seen as integer") { status
.to_i
>= 100 }
324 def check_headers(header
)
325 ## The header must respond to each, and yield values of key and value.
326 assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") {
327 header
.respond_to
? :each
329 header
.each
{ |key
, value
|
330 ## The header keys must be Strings.
331 assert("header key must be a string, was #{key.class}") {
332 key
.instance_of
? String
334 ## The header must not contain a +Status+ key,
335 assert("header must not contain Status") { key
.downcase
!= "status" }
336 ## contain keys with <tt>:</tt> or newlines in their name,
337 assert("header names must not contain : or \\n") { key
!~
/[:\n]/ }
338 ## contain keys names that end in <tt>-</tt> or <tt>_</tt>,
339 assert("header names must not end in - or _") { key
!~
/[-_]\z/ }
340 ## but only contain keys that consist of
341 ## letters, digits, <tt>_</tt> or <tt>-</tt> and start with a letter.
342 assert("invalid header name: #{key}") { key
=~
/\A[a-zA-Z][a-zA-Z0-9_-]*\z/ }
344 ## The values of the header must be Strings,
345 assert("a header value must be a String, but the value of " +
346 "'#{key}' is a #{value.class}") { value
.kind_of
? String
}
347 ## consisting of lines (for multiple header values) seperated by "\n".
348 value
.split("\n").each
{ |item
|
349 ## The lines must not contain characters below 037.
350 assert("invalid header value #{key}: #{item.inspect}") {
351 item
!~
/[\000-\037]/
357 ## === The Content-Type
358 def check_content_type(status
, headers
)
359 headers
.each
{ |key
, value
|
360 ## There must be a <tt>Content-Type</tt>, except when the
361 ## +Status+ is 1xx, 204 or 304, in which case there must be none
363 if key
.downcase
== "content-type"
364 assert("Content-Type header found in #{status} response, not allowed") {
365 not Rack
::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status
.to_i
370 assert("No Content-Type header found") {
371 Rack
::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status
.to_i
375 ## === The Content-Length
376 def check_content_length(status
, headers
, env)
377 headers
.each
{ |key
, value
|
378 if key
.downcase
== 'content-length'
379 ## There must not be a <tt>Content-Length</tt> header when the
380 ## +Status+ is 1xx, 204 or 304.
381 assert("Content-Length header found in #{status} response, not allowed") {
382 not Rack
::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status
.to_i
388 if @body.respond_to
?(:to_ary)
390 unless part
.kind_of
?(String
)
395 bytes
+= Rack
::Utils.bytesize(part
)
398 if env["REQUEST_METHOD"] == "HEAD"
399 assert("Response body was given for HEAD request, but should be empty") {
404 assert("Content-Length header was #{value}, but should be #{bytes}") {
419 ## The Body must respond to #each
421 ## and must only yield String values.
422 assert("Body yielded non-string value #{part.inspect}") {
423 part
.instance_of
? String
428 ## If the Body responds to #close, it will be called after iteration.
429 # XXX howto: assert("Body has not been closed") { @closed }
433 ## If the Body responds to #to_path, it must return a String
434 ## identifying the location of a file whose contents are identical
435 ## to that produced by calling #each.
437 if @body.respond_to
?(:to_path)
438 assert("The file identified by body.to_path does not exist") {
439 ::File.exist
? @body.to_path
444 ## The Body commonly is an Array of Strings, the application
445 ## instance itself, or a File-like object.
450 @body.close
if @body.respond_to
?(:close)
459 ## Some parts of this specification are adopted from PEP333: Python
460 ## Web Server Gateway Interface
461 ## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank
462 ## everyone involved in that effort.