blob: 2df3f9f7fe99680fb465220760e554355ee2d17d [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
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000130def check_string_type(value, title):
131 if isinstance(value, str):
132 return value
133 assert isinstance(value, bytes), \
134 "{0} must be a string or bytes object (not {1})".format(title, value)
135 return str(value, "iso-8859-1")
136
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000137def validator(application):
138
139 """
140 When applied between a WSGI server and a WSGI application, this
141 middleware will check for WSGI compliancy on a number of levels.
142 This middleware does not modify the request or response in any
143 way, but will throw an AssertionError if anything seems off
144 (except for a failure to close the application iterator, which
145 will be printed to stderr -- there's no way to throw an exception
146 at that point).
147 """
148
149 def lint_app(*args, **kw):
150 assert_(len(args) == 2, "Two arguments required")
151 assert_(not kw, "No keyword arguments allowed")
152 environ, start_response = args
153
154 check_environ(environ)
155
156 # We use this to check if the application returns without
157 # calling start_response:
158 start_response_started = []
159
160 def start_response_wrapper(*args, **kw):
161 assert_(len(args) == 2 or len(args) == 3, (
162 "Invalid number of arguments: %s" % (args,)))
163 assert_(not kw, "No keyword arguments allowed")
164 status = args[0]
165 headers = args[1]
166 if len(args) == 3:
167 exc_info = args[2]
168 else:
169 exc_info = None
170
171 check_status(status)
172 check_headers(headers)
173 check_content_type(status, headers)
174 check_exc_info(exc_info)
175
176 start_response_started.append(None)
177 return WriteWrapper(start_response(*args))
178
179 environ['wsgi.input'] = InputWrapper(environ['wsgi.input'])
180 environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors'])
181
182 iterator = application(environ, start_response_wrapper)
183 assert_(iterator is not None and iterator != False,
184 "The application must return an iterator, if only an empty list")
185
186 check_iterator(iterator)
187
188 return IteratorWrapper(iterator, start_response_started)
189
190 return lint_app
191
192class InputWrapper:
193
194 def __init__(self, wsgi_input):
195 self.input = wsgi_input
196
197 def read(self, *args):
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000198 assert_(len(args) == 1)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000199 v = self.input.read(*args)
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000200 assert_(isinstance(v, bytes))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000201 return v
202
203 def readline(self):
204 v = self.input.readline()
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000205 assert_(isinstance(v, bytes))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000206 return v
207
208 def readlines(self, *args):
209 assert_(len(args) <= 1)
210 lines = self.input.readlines(*args)
Guido van Rossum13257902007-06-07 23:15:56 +0000211 assert_(isinstance(lines, list))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000212 for line in lines:
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000213 assert_(isinstance(line, bytes))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000214 return lines
215
216 def __iter__(self):
217 while 1:
218 line = self.readline()
219 if not line:
220 return
221 yield line
222
223 def close(self):
224 assert_(0, "input.close() must not be called")
225
226class ErrorWrapper:
227
228 def __init__(self, wsgi_errors):
229 self.errors = wsgi_errors
230
231 def write(self, s):
Guido van Rossum13257902007-06-07 23:15:56 +0000232 assert_(isinstance(s, str))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000233 self.errors.write(s)
234
235 def flush(self):
236 self.errors.flush()
237
238 def writelines(self, seq):
239 for line in seq:
240 self.write(line)
241
242 def close(self):
243 assert_(0, "errors.close() must not be called")
244
245class WriteWrapper:
246
247 def __init__(self, wsgi_writer):
248 self.writer = wsgi_writer
249
250 def __call__(self, s):
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000251 assert_(isinstance(s, (str, bytes)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000252 self.writer(s)
253
254class PartialIteratorWrapper:
255
256 def __init__(self, wsgi_iterator):
257 self.iterator = wsgi_iterator
258
259 def __iter__(self):
260 # We want to make sure __iter__ is called
261 return IteratorWrapper(self.iterator, None)
262
263class IteratorWrapper:
264
265 def __init__(self, wsgi_iterator, check_start_response):
266 self.original_iterator = wsgi_iterator
267 self.iterator = iter(wsgi_iterator)
268 self.closed = False
269 self.check_start_response = check_start_response
270
271 def __iter__(self):
272 return self
273
Georg Brandla18af4e2007-04-21 15:47:16 +0000274 def __next__(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000275 assert_(not self.closed,
276 "Iterator read after closed")
Georg Brandla18af4e2007-04-21 15:47:16 +0000277 v = next(self.iterator)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000278 if self.check_start_response is not None:
279 assert_(self.check_start_response,
280 "The application returns and we started iterating over its body, but start_response has not yet been called")
281 self.check_start_response = None
282 return v
283
284 def close(self):
285 self.closed = True
286 if hasattr(self.original_iterator, 'close'):
287 self.original_iterator.close()
288
289 def __del__(self):
290 if not self.closed:
291 sys.stderr.write(
292 "Iterator garbage collected without being closed")
293 assert_(self.closed,
294 "Iterator garbage collected without being closed")
295
296def check_environ(environ):
Guido van Rossum13257902007-06-07 23:15:56 +0000297 assert_(isinstance(environ, dict),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000298 "Environment is not of the right type: %r (environment: %r)"
299 % (type(environ), environ))
300
301 for key in ['REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT',
302 'wsgi.version', 'wsgi.input', 'wsgi.errors',
303 'wsgi.multithread', 'wsgi.multiprocess',
304 'wsgi.run_once']:
305 assert_(key in environ,
306 "Environment missing required key: %r" % (key,))
307
308 for key in ['HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH']:
309 assert_(key not in environ,
310 "Environment should not have the key: %s "
311 "(use %s instead)" % (key, key[5:]))
312
313 if 'QUERY_STRING' not in environ:
314 warnings.warn(
315 'QUERY_STRING is not in the WSGI environment; the cgi '
316 'module will use sys.argv when this variable is missing, '
317 'so application errors are more likely',
318 WSGIWarning)
319
320 for key in environ.keys():
321 if '.' in key:
322 # Extension, we don't care about its type
323 continue
Guido van Rossum13257902007-06-07 23:15:56 +0000324 assert_(isinstance(environ[key], str),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000325 "Environmental variable %s is not a string: %r (value: %r)"
326 % (key, type(environ[key]), environ[key]))
327
Guido van Rossum13257902007-06-07 23:15:56 +0000328 assert_(isinstance(environ['wsgi.version'], tuple),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000329 "wsgi.version should be a tuple (%r)" % (environ['wsgi.version'],))
330 assert_(environ['wsgi.url_scheme'] in ('http', 'https'),
331 "wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
332
333 check_input(environ['wsgi.input'])
334 check_errors(environ['wsgi.errors'])
335
336 # @@: these need filling out:
337 if environ['REQUEST_METHOD'] not in (
338 'GET', 'HEAD', 'POST', 'OPTIONS','PUT','DELETE','TRACE'):
339 warnings.warn(
340 "Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
341 WSGIWarning)
342
343 assert_(not environ.get('SCRIPT_NAME')
344 or environ['SCRIPT_NAME'].startswith('/'),
345 "SCRIPT_NAME doesn't start with /: %r" % environ['SCRIPT_NAME'])
346 assert_(not environ.get('PATH_INFO')
347 or environ['PATH_INFO'].startswith('/'),
348 "PATH_INFO doesn't start with /: %r" % environ['PATH_INFO'])
349 if environ.get('CONTENT_LENGTH'):
350 assert_(int(environ['CONTENT_LENGTH']) >= 0,
351 "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
352
353 if not environ.get('SCRIPT_NAME'):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000354 assert_('PATH_INFO' in environ,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000355 "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
356 "should at least be '/' if SCRIPT_NAME is empty)")
357 assert_(environ.get('SCRIPT_NAME') != '/',
358 "SCRIPT_NAME cannot be '/'; it should instead be '', and "
359 "PATH_INFO should be '/'")
360
361def check_input(wsgi_input):
362 for attr in ['read', 'readline', 'readlines', '__iter__']:
363 assert_(hasattr(wsgi_input, attr),
364 "wsgi.input (%r) doesn't have the attribute %s"
365 % (wsgi_input, attr))
366
367def check_errors(wsgi_errors):
368 for attr in ['flush', 'write', 'writelines']:
369 assert_(hasattr(wsgi_errors, attr),
370 "wsgi.errors (%r) doesn't have the attribute %s"
371 % (wsgi_errors, attr))
372
373def check_status(status):
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000374 status = check_string_type(status, "Status")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000375 # Implicitly check that we can turn it into an integer:
376 status_code = status.split(None, 1)[0]
377 assert_(len(status_code) == 3,
378 "Status codes must be three characters: %r" % status_code)
379 status_int = int(status_code)
380 assert_(status_int >= 100, "Status code is invalid: %r" % status_int)
381 if len(status) < 4 or status[3] != ' ':
382 warnings.warn(
383 "The status string (%r) should be a three-digit integer "
384 "followed by a single space and a status explanation"
385 % status, WSGIWarning)
386
387def check_headers(headers):
Guido van Rossum13257902007-06-07 23:15:56 +0000388 assert_(isinstance(headers, list),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000389 "Headers (%r) must be of type list: %r"
390 % (headers, type(headers)))
391 header_names = {}
392 for item in headers:
Guido van Rossum13257902007-06-07 23:15:56 +0000393 assert_(isinstance(item, tuple),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000394 "Individual headers (%r) must be of type tuple: %r"
395 % (item, type(item)))
396 assert_(len(item) == 2)
397 name, value = item
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000398 name = check_string_type(name, "Header name")
399 value = check_string_type(value, "Header value")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000400 assert_(name.lower() != 'status',
401 "The Status header cannot be used; it conflicts with CGI "
402 "script, and HTTP status is not given through headers "
403 "(value: %r)." % value)
404 header_names[name.lower()] = None
405 assert_('\n' not in name and ':' not in name,
406 "Header names may not contain ':' or '\\n': %r" % name)
407 assert_(header_re.search(name), "Bad header name: %r" % name)
408 assert_(not name.endswith('-') and not name.endswith('_'),
409 "Names may not end in '-' or '_': %r" % name)
410 if bad_header_value_re.search(value):
411 assert_(0, "Bad header value: %r (bad char: %r)"
412 % (value, bad_header_value_re.search(value).group(0)))
413
414def check_content_type(status, headers):
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000415 status = check_string_type(status, "Status")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000416 code = int(status.split(None, 1)[0])
417 # @@: need one more person to verify this interpretation of RFC 2616
418 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
419 NO_MESSAGE_BODY = (204, 304)
420 for name, value in headers:
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000421 name = check_string_type(name, "Header name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000422 if name.lower() == 'content-type':
423 if code not in NO_MESSAGE_BODY:
424 return
425 assert_(0, ("Content-Type header found in a %s response, "
426 "which must not return content.") % code)
427 if code not in NO_MESSAGE_BODY:
428 assert_(0, "No Content-Type header found in headers (%s)" % headers)
429
430def check_exc_info(exc_info):
Guido van Rossum13257902007-06-07 23:15:56 +0000431 assert_(exc_info is None or isinstance(exc_info, tuple),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000432 "exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
433 # More exc_info checks?
434
435def check_iterator(iterator):
436 # Technically a string is legal, which is why it's a really bad
437 # idea, because it may cause the response to be returned
438 # character-by-character
Antoine Pitrou38a66ad2009-01-03 18:41:49 +0000439 assert_(not isinstance(iterator, (str, bytes)),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000440 "You should not return a string as your application iterator, "
441 "instead return a single-item list containing that string.")