blob: fbd35361e6d851e0c977b1c0f85080c097fc9b53 [file] [log] [blame]
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
2# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
3# Also licenced under the Apache License, 2.0: http://opensource.org/licenses/apache2.0.php
4# Licensed to PSF under a Contributor Agreement
5"""
6Middleware to check for obedience to the WSGI specification.
7
8Some of the things this checks:
9
10* Signature of the application and start_response (including that
11 keyword arguments are not used).
12
13* Environment checks:
14
15 - Environment is a dictionary (and not a subclass).
16
17 - That all the required keys are in the environment: REQUEST_METHOD,
18 SERVER_NAME, SERVER_PORT, wsgi.version, wsgi.input, wsgi.errors,
19 wsgi.multithread, wsgi.multiprocess, wsgi.run_once
20
21 - That HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH are not in the
22 environment (these headers should appear as CONTENT_LENGTH and
23 CONTENT_TYPE).
24
25 - Warns if QUERY_STRING is missing, as the cgi module acts
26 unpredictably in that case.
27
28 - That CGI-style variables (that don't contain a .) have
29 (non-unicode) string values
30
31 - That wsgi.version is a tuple
32
33 - That wsgi.url_scheme is 'http' or 'https' (@@: is this too
34 restrictive?)
35
36 - Warns if the REQUEST_METHOD is not known (@@: probably too
37 restrictive).
38
39 - That SCRIPT_NAME and PATH_INFO are empty or start with /
40
41 - That at least one of SCRIPT_NAME or PATH_INFO are set.
42
43 - That CONTENT_LENGTH is a positive integer.
44
45 - That SCRIPT_NAME is not '/' (it should be '', and PATH_INFO should
46 be '/').
47
48 - That wsgi.input has the methods read, readline, readlines, and
49 __iter__
50
51 - That wsgi.errors has the methods flush, write, writelines
52
53* The status is a string, contains a space, starts with an integer,
54 and that integer is in range (> 100).
55
56* That the headers is a list (not a subclass, not another kind of
57 sequence).
58
59* That the items of the headers are tuples of strings.
60
61* That there is no 'status' header (that is used in CGI, but not in
62 WSGI).
63
64* That the headers don't contain newlines or colons, end in _ or -, or
65 contain characters codes below 037.
66
67* That Content-Type is given if there is content (CGI often has a
68 default content type, but WSGI does not).
69
70* That no Content-Type is given when there is no content (@@: is this
71 too restrictive?)
72
73* That the exc_info argument to start_response is a tuple or None.
74
75* That all calls to the writer are with strings, and no other methods
76 on the writer are accessed.
77
78* That wsgi.input is used properly:
79
80 - .read() is called with zero or one argument
81
82 - That it returns a string
83
84 - That readline, readlines, and __iter__ return strings
85
86 - That .close() is not called
87
88 - No other methods are provided
89
90* That wsgi.errors is used properly:
91
92 - .write() and .writelines() is called with a string
93
94 - That .close() is not called, and no other methods are provided.
95
96* The response iterator:
97
98 - That it is not a string (it should be a list of a single string; a
99 string will work, but perform horribly).
100
Georg Brandla18af4e2007-04-21 15:47:16 +0000101 - That .__next__() returns a string
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000102
103 - That the iterator is not iterated over until start_response has
104 been called (that can signal either a server or application
105 error).
106
107 - That .close() is called (doesn't raise exception, only prints to
108 sys.stderr, because we only know it isn't called when the object
109 is garbage collected).
110"""
111__all__ = ['validator']
112
113
114import re
115import sys
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000116import warnings
117
118header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
119bad_header_value_re = re.compile(r'[\000-\037]')
120
121class WSGIWarning(Warning):
122 """
123 Raised in response to WSGI-spec-related warnings
124 """
125
126def assert_(cond, *args):
127 if not cond:
128 raise AssertionError(*args)
129
130def validator(application):
131
132 """
133 When applied between a WSGI server and a WSGI application, this
134 middleware will check for WSGI compliancy on a number of levels.
135 This middleware does not modify the request or response in any
136 way, but will throw an AssertionError if anything seems off
137 (except for a failure to close the application iterator, which
138 will be printed to stderr -- there's no way to throw an exception
139 at that point).
140 """
141
142 def lint_app(*args, **kw):
143 assert_(len(args) == 2, "Two arguments required")
144 assert_(not kw, "No keyword arguments allowed")
145 environ, start_response = args
146
147 check_environ(environ)
148
149 # We use this to check if the application returns without
150 # calling start_response:
151 start_response_started = []
152
153 def start_response_wrapper(*args, **kw):
154 assert_(len(args) == 2 or len(args) == 3, (
155 "Invalid number of arguments: %s" % (args,)))
156 assert_(not kw, "No keyword arguments allowed")
157 status = args[0]
158 headers = args[1]
159 if len(args) == 3:
160 exc_info = args[2]
161 else:
162 exc_info = None
163
164 check_status(status)
165 check_headers(headers)
166 check_content_type(status, headers)
167 check_exc_info(exc_info)
168
169 start_response_started.append(None)
170 return WriteWrapper(start_response(*args))
171
172 environ['wsgi.input'] = InputWrapper(environ['wsgi.input'])
173 environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors'])
174
175 iterator = application(environ, start_response_wrapper)
176 assert_(iterator is not None and iterator != False,
177 "The application must return an iterator, if only an empty list")
178
179 check_iterator(iterator)
180
181 return IteratorWrapper(iterator, start_response_started)
182
183 return lint_app
184
185class InputWrapper:
186
187 def __init__(self, wsgi_input):
188 self.input = wsgi_input
189
190 def read(self, *args):
191 assert_(len(args) <= 1)
192 v = self.input.read(*args)
Guido van Rossum13257902007-06-07 23:15:56 +0000193 assert_(isinstance(v, str))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000194 return v
195
196 def readline(self):
197 v = self.input.readline()
Guido van Rossum13257902007-06-07 23:15:56 +0000198 assert_(isinstance(v, str))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000199 return v
200
201 def readlines(self, *args):
202 assert_(len(args) <= 1)
203 lines = self.input.readlines(*args)
Guido van Rossum13257902007-06-07 23:15:56 +0000204 assert_(isinstance(lines, list))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000205 for line in lines:
Guido van Rossum13257902007-06-07 23:15:56 +0000206 assert_(isinstance(line, str))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000207 return lines
208
209 def __iter__(self):
210 while 1:
211 line = self.readline()
212 if not line:
213 return
214 yield line
215
216 def close(self):
217 assert_(0, "input.close() must not be called")
218
219class ErrorWrapper:
220
221 def __init__(self, wsgi_errors):
222 self.errors = wsgi_errors
223
224 def write(self, s):
Guido van Rossum13257902007-06-07 23:15:56 +0000225 assert_(isinstance(s, str))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000226 self.errors.write(s)
227
228 def flush(self):
229 self.errors.flush()
230
231 def writelines(self, seq):
232 for line in seq:
233 self.write(line)
234
235 def close(self):
236 assert_(0, "errors.close() must not be called")
237
238class WriteWrapper:
239
240 def __init__(self, wsgi_writer):
241 self.writer = wsgi_writer
242
243 def __call__(self, s):
Guido van Rossum13257902007-06-07 23:15:56 +0000244 assert_(isinstance(s, str))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000245 self.writer(s)
246
247class PartialIteratorWrapper:
248
249 def __init__(self, wsgi_iterator):
250 self.iterator = wsgi_iterator
251
252 def __iter__(self):
253 # We want to make sure __iter__ is called
254 return IteratorWrapper(self.iterator, None)
255
256class IteratorWrapper:
257
258 def __init__(self, wsgi_iterator, check_start_response):
259 self.original_iterator = wsgi_iterator
260 self.iterator = iter(wsgi_iterator)
261 self.closed = False
262 self.check_start_response = check_start_response
263
264 def __iter__(self):
265 return self
266
Georg Brandla18af4e2007-04-21 15:47:16 +0000267 def __next__(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000268 assert_(not self.closed,
269 "Iterator read after closed")
Georg Brandla18af4e2007-04-21 15:47:16 +0000270 v = next(self.iterator)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000271 if self.check_start_response is not None:
272 assert_(self.check_start_response,
273 "The application returns and we started iterating over its body, but start_response has not yet been called")
274 self.check_start_response = None
275 return v
276
277 def close(self):
278 self.closed = True
279 if hasattr(self.original_iterator, 'close'):
280 self.original_iterator.close()
281
282 def __del__(self):
283 if not self.closed:
284 sys.stderr.write(
285 "Iterator garbage collected without being closed")
286 assert_(self.closed,
287 "Iterator garbage collected without being closed")
288
289def check_environ(environ):
Guido van Rossum13257902007-06-07 23:15:56 +0000290 assert_(isinstance(environ, dict),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000291 "Environment is not of the right type: %r (environment: %r)"
292 % (type(environ), environ))
293
294 for key in ['REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT',
295 'wsgi.version', 'wsgi.input', 'wsgi.errors',
296 'wsgi.multithread', 'wsgi.multiprocess',
297 'wsgi.run_once']:
298 assert_(key in environ,
299 "Environment missing required key: %r" % (key,))
300
301 for key in ['HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH']:
302 assert_(key not in environ,
303 "Environment should not have the key: %s "
304 "(use %s instead)" % (key, key[5:]))
305
306 if 'QUERY_STRING' not in environ:
307 warnings.warn(
308 'QUERY_STRING is not in the WSGI environment; the cgi '
309 'module will use sys.argv when this variable is missing, '
310 'so application errors are more likely',
311 WSGIWarning)
312
313 for key in environ.keys():
314 if '.' in key:
315 # Extension, we don't care about its type
316 continue
Guido van Rossum13257902007-06-07 23:15:56 +0000317 assert_(isinstance(environ[key], str),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000318 "Environmental variable %s is not a string: %r (value: %r)"
319 % (key, type(environ[key]), environ[key]))
320
Guido van Rossum13257902007-06-07 23:15:56 +0000321 assert_(isinstance(environ['wsgi.version'], tuple),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000322 "wsgi.version should be a tuple (%r)" % (environ['wsgi.version'],))
323 assert_(environ['wsgi.url_scheme'] in ('http', 'https'),
324 "wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
325
326 check_input(environ['wsgi.input'])
327 check_errors(environ['wsgi.errors'])
328
329 # @@: these need filling out:
330 if environ['REQUEST_METHOD'] not in (
331 'GET', 'HEAD', 'POST', 'OPTIONS','PUT','DELETE','TRACE'):
332 warnings.warn(
333 "Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
334 WSGIWarning)
335
336 assert_(not environ.get('SCRIPT_NAME')
337 or environ['SCRIPT_NAME'].startswith('/'),
338 "SCRIPT_NAME doesn't start with /: %r" % environ['SCRIPT_NAME'])
339 assert_(not environ.get('PATH_INFO')
340 or environ['PATH_INFO'].startswith('/'),
341 "PATH_INFO doesn't start with /: %r" % environ['PATH_INFO'])
342 if environ.get('CONTENT_LENGTH'):
343 assert_(int(environ['CONTENT_LENGTH']) >= 0,
344 "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
345
346 if not environ.get('SCRIPT_NAME'):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000347 assert_('PATH_INFO' in environ,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000348 "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
349 "should at least be '/' if SCRIPT_NAME is empty)")
350 assert_(environ.get('SCRIPT_NAME') != '/',
351 "SCRIPT_NAME cannot be '/'; it should instead be '', and "
352 "PATH_INFO should be '/'")
353
354def check_input(wsgi_input):
355 for attr in ['read', 'readline', 'readlines', '__iter__']:
356 assert_(hasattr(wsgi_input, attr),
357 "wsgi.input (%r) doesn't have the attribute %s"
358 % (wsgi_input, attr))
359
360def check_errors(wsgi_errors):
361 for attr in ['flush', 'write', 'writelines']:
362 assert_(hasattr(wsgi_errors, attr),
363 "wsgi.errors (%r) doesn't have the attribute %s"
364 % (wsgi_errors, attr))
365
366def check_status(status):
Guido van Rossum13257902007-06-07 23:15:56 +0000367 assert_(isinstance(status, str),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000368 "Status must be a string (not %r)" % status)
369 # Implicitly check that we can turn it into an integer:
370 status_code = status.split(None, 1)[0]
371 assert_(len(status_code) == 3,
372 "Status codes must be three characters: %r" % status_code)
373 status_int = int(status_code)
374 assert_(status_int >= 100, "Status code is invalid: %r" % status_int)
375 if len(status) < 4 or status[3] != ' ':
376 warnings.warn(
377 "The status string (%r) should be a three-digit integer "
378 "followed by a single space and a status explanation"
379 % status, WSGIWarning)
380
381def check_headers(headers):
Guido van Rossum13257902007-06-07 23:15:56 +0000382 assert_(isinstance(headers, list),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000383 "Headers (%r) must be of type list: %r"
384 % (headers, type(headers)))
385 header_names = {}
386 for item in headers:
Guido van Rossum13257902007-06-07 23:15:56 +0000387 assert_(isinstance(item, tuple),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000388 "Individual headers (%r) must be of type tuple: %r"
389 % (item, type(item)))
390 assert_(len(item) == 2)
391 name, value = item
392 assert_(name.lower() != 'status',
393 "The Status header cannot be used; it conflicts with CGI "
394 "script, and HTTP status is not given through headers "
395 "(value: %r)." % value)
396 header_names[name.lower()] = None
397 assert_('\n' not in name and ':' not in name,
398 "Header names may not contain ':' or '\\n': %r" % name)
399 assert_(header_re.search(name), "Bad header name: %r" % name)
400 assert_(not name.endswith('-') and not name.endswith('_'),
401 "Names may not end in '-' or '_': %r" % name)
402 if bad_header_value_re.search(value):
403 assert_(0, "Bad header value: %r (bad char: %r)"
404 % (value, bad_header_value_re.search(value).group(0)))
405
406def check_content_type(status, headers):
407 code = int(status.split(None, 1)[0])
408 # @@: need one more person to verify this interpretation of RFC 2616
409 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
410 NO_MESSAGE_BODY = (204, 304)
411 for name, value in headers:
412 if name.lower() == 'content-type':
413 if code not in NO_MESSAGE_BODY:
414 return
415 assert_(0, ("Content-Type header found in a %s response, "
416 "which must not return content.") % code)
417 if code not in NO_MESSAGE_BODY:
418 assert_(0, "No Content-Type header found in headers (%s)" % headers)
419
420def check_exc_info(exc_info):
Guido van Rossum13257902007-06-07 23:15:56 +0000421 assert_(exc_info is None or isinstance(exc_info, tuple),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000422 "exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
423 # More exc_info checks?
424
425def check_iterator(iterator):
426 # Technically a string is legal, which is why it's a really bad
427 # idea, because it may cause the response to be returned
428 # character-by-character
429 assert_(not isinstance(iterator, str),
430 "You should not return a string as your application iterator, "
431 "instead return a single-item list containing that string.")