blob: e72c507024ce21769471cdb311f1127d1793ba65 [file] [log] [blame]
Phillip J. Eby5cf565d2006-06-09 16:40:18 +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
101 - That .next() returns a string
102
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
116from types import DictType, StringType, TupleType, ListType
117import warnings
118
119header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
120bad_header_value_re = re.compile(r'[\000-\037]')
121
122class WSGIWarning(Warning):
123 """
124 Raised in response to WSGI-spec-related warnings
125 """
126
127def validator(application):
128
129 """
130 When applied between a WSGI server and a WSGI application, this
131 middleware will check for WSGI compliancy on a number of levels.
132 This middleware does not modify the request or response in any
133 way, but will throw an AssertionError if anything seems off
134 (except for a failure to close the application iterator, which
135 will be printed to stderr -- there's no way to throw an exception
136 at that point).
137 """
138
139 def lint_app(*args, **kw):
140 assert len(args) == 2, "Two arguments required"
141 assert not kw, "No keyword arguments allowed"
142 environ, start_response = args
143
144 check_environ(environ)
145
146 # We use this to check if the application returns without
147 # calling start_response:
148 start_response_started = []
149
150 def start_response_wrapper(*args, **kw):
151 assert len(args) == 2 or len(args) == 3, (
152 "Invalid number of arguments: %s" % args)
153 assert not kw, "No keyword arguments allowed"
154 status = args[0]
155 headers = args[1]
156 if len(args) == 3:
157 exc_info = args[2]
158 else:
159 exc_info = None
160
161 check_status(status)
162 check_headers(headers)
163 check_content_type(status, headers)
164 check_exc_info(exc_info)
165
166 start_response_started.append(None)
167 return WriteWrapper(start_response(*args))
168
169 environ['wsgi.input'] = InputWrapper(environ['wsgi.input'])
170 environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors'])
171
172 iterator = application(environ, start_response_wrapper)
173 assert iterator is not None and iterator != False, (
174 "The application must return an iterator, if only an empty list")
175
176 check_iterator(iterator)
177
178 return IteratorWrapper(iterator, start_response_started)
179
180 return lint_app
181
182class InputWrapper:
183
184 def __init__(self, wsgi_input):
185 self.input = wsgi_input
186
187 def read(self, *args):
188 assert len(args) <= 1
189 v = self.input.read(*args)
190 assert type(v) is type("")
191 return v
192
193 def readline(self):
194 v = self.input.readline()
195 assert type(v) is type("")
196 return v
197
198 def readlines(self, *args):
199 assert len(args) <= 1
200 lines = self.input.readlines(*args)
201 assert type(lines) is type([])
202 for line in lines:
203 assert type(line) is type("")
204 return lines
205
206 def __iter__(self):
207 while 1:
208 line = self.readline()
209 if not line:
210 return
211 yield line
212
213 def close(self):
214 assert 0, "input.close() must not be called"
215
216class ErrorWrapper:
217
218 def __init__(self, wsgi_errors):
219 self.errors = wsgi_errors
220
221 def write(self, s):
222 assert type(s) is type("")
223 self.errors.write(s)
224
225 def flush(self):
226 self.errors.flush()
227
228 def writelines(self, seq):
229 for line in seq:
230 self.write(line)
231
232 def close(self):
233 assert 0, "errors.close() must not be called"
234
235class WriteWrapper:
236
237 def __init__(self, wsgi_writer):
238 self.writer = wsgi_writer
239
240 def __call__(self, s):
241 assert type(s) is type("")
242 self.writer(s)
243
244class PartialIteratorWrapper:
245
246 def __init__(self, wsgi_iterator):
247 self.iterator = wsgi_iterator
248
249 def __iter__(self):
250 # We want to make sure __iter__ is called
251 return IteratorWrapper(self.iterator)
252
253class IteratorWrapper:
254
255 def __init__(self, wsgi_iterator, check_start_response):
256 self.original_iterator = wsgi_iterator
257 self.iterator = iter(wsgi_iterator)
258 self.closed = False
259 self.check_start_response = check_start_response
260
261 def __iter__(self):
262 return self
263
264 def next(self):
265 assert not self.closed, (
266 "Iterator read after closed")
267 v = self.iterator.next()
268 if self.check_start_response is not None:
269 assert self.check_start_response, (
270 "The application returns and we started iterating over its body, but start_response has not yet been called")
271 self.check_start_response = None
272 return v
273
274 def close(self):
275 self.closed = True
276 if hasattr(self.original_iterator, 'close'):
277 self.original_iterator.close()
278
279 def __del__(self):
280 if not self.closed:
281 sys.stderr.write(
282 "Iterator garbage collected without being closed")
283 assert self.closed, (
284 "Iterator garbage collected without being closed")
285
286def check_environ(environ):
287 assert type(environ) is DictType, (
288 "Environment is not of the right type: %r (environment: %r)"
289 % (type(environ), environ))
290
291 for key in ['REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT',
292 'wsgi.version', 'wsgi.input', 'wsgi.errors',
293 'wsgi.multithread', 'wsgi.multiprocess',
294 'wsgi.run_once']:
295 assert key in environ, (
296 "Environment missing required key: %r" % key)
297
298 for key in ['HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH']:
299 assert key not in environ, (
300 "Environment should not have the key: %s "
301 "(use %s instead)" % (key, key[5:]))
302
303 if 'QUERY_STRING' not in environ:
304 warnings.warn(
305 'QUERY_STRING is not in the WSGI environment; the cgi '
306 'module will use sys.argv when this variable is missing, '
307 'so application errors are more likely',
308 WSGIWarning)
309
310 for key in environ.keys():
311 if '.' in key:
312 # Extension, we don't care about its type
313 continue
314 assert type(environ[key]) is StringType, (
315 "Environmental variable %s is not a string: %r (value: %r)"
316 % (type(environ[key]), environ[key]))
317
318 assert type(environ['wsgi.version']) is TupleType, (
319 "wsgi.version should be a tuple (%r)" % environ['wsgi.version'])
320 assert environ['wsgi.url_scheme'] in ('http', 'https'), (
321 "wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
322
323 check_input(environ['wsgi.input'])
324 check_errors(environ['wsgi.errors'])
325
326 # @@: these need filling out:
327 if environ['REQUEST_METHOD'] not in (
328 'GET', 'HEAD', 'POST', 'OPTIONS','PUT','DELETE','TRACE'):
329 warnings.warn(
330 "Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
331 WSGIWarning)
332
333 assert (not environ.get('SCRIPT_NAME')
334 or environ['SCRIPT_NAME'].startswith('/')), (
335 "SCRIPT_NAME doesn't start with /: %r" % environ['SCRIPT_NAME'])
336 assert (not environ.get('PATH_INFO')
337 or environ['PATH_INFO'].startswith('/')), (
338 "PATH_INFO doesn't start with /: %r" % environ['PATH_INFO'])
339 if environ.get('CONTENT_LENGTH'):
340 assert int(environ['CONTENT_LENGTH']) >= 0, (
341 "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
342
343 if not environ.get('SCRIPT_NAME'):
344 assert environ.has_key('PATH_INFO'), (
345 "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
346 "should at least be '/' if SCRIPT_NAME is empty)")
347 assert environ.get('SCRIPT_NAME') != '/', (
348 "SCRIPT_NAME cannot be '/'; it should instead be '', and "
349 "PATH_INFO should be '/'")
350
351def check_input(wsgi_input):
352 for attr in ['read', 'readline', 'readlines', '__iter__']:
353 assert hasattr(wsgi_input, attr), (
354 "wsgi.input (%r) doesn't have the attribute %s"
355 % (wsgi_input, attr))
356
357def check_errors(wsgi_errors):
358 for attr in ['flush', 'write', 'writelines']:
359 assert hasattr(wsgi_errors, attr), (
360 "wsgi.errors (%r) doesn't have the attribute %s"
361 % (wsgi_errors, attr))
362
363def check_status(status):
364 assert type(status) is StringType, (
365 "Status must be a string (not %r)" % status)
366 # Implicitly check that we can turn it into an integer:
367 status_code = status.split(None, 1)[0]
368 assert len(status_code) == 3, (
369 "Status codes must be three characters: %r" % status_code)
370 status_int = int(status_code)
371 assert status_int >= 100, "Status code is invalid: %r" % status_int
372 if len(status) < 4 or status[3] != ' ':
373 warnings.warn(
374 "The status string (%r) should be a three-digit integer "
375 "followed by a single space and a status explanation"
376 % status, WSGIWarning)
377
378def check_headers(headers):
379 assert type(headers) is ListType, (
380 "Headers (%r) must be of type list: %r"
381 % (headers, type(headers)))
382 header_names = {}
383 for item in headers:
384 assert type(item) is TupleType, (
385 "Individual headers (%r) must be of type tuple: %r"
386 % (item, type(item)))
387 assert len(item) == 2
388 name, value = item
389 assert name.lower() != 'status', (
390 "The Status header cannot be used; it conflicts with CGI "
391 "script, and HTTP status is not given through headers "
392 "(value: %r)." % value)
393 header_names[name.lower()] = None
394 assert '\n' not in name and ':' not in name, (
395 "Header names may not contain ':' or '\\n': %r" % name)
396 assert header_re.search(name), "Bad header name: %r" % name
397 assert not name.endswith('-') and not name.endswith('_'), (
398 "Names may not end in '-' or '_': %r" % name)
399 assert not bad_header_value_re.search(value), (
400 "Bad header value: %r (bad char: %r)"
401 % (value, bad_header_value_re.search(value).group(0)))
402
403def check_content_type(status, headers):
404 code = int(status.split(None, 1)[0])
405 # @@: need one more person to verify this interpretation of RFC 2616
406 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
407 NO_MESSAGE_BODY = (204, 304)
408 for name, value in headers:
409 if name.lower() == 'content-type':
410 if code not in NO_MESSAGE_BODY:
411 return
412 assert 0, (("Content-Type header found in a %s response, "
413 "which must not return content.") % code)
414 if code not in NO_MESSAGE_BODY:
415 assert 0, "No Content-Type header found in headers (%s)" % headers
416
417def check_exc_info(exc_info):
418 assert exc_info is None or type(exc_info) is type(()), (
419 "exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
420 # More exc_info checks?
421
422def check_iterator(iterator):
423 # Technically a string is legal, which is why it's a really bad
424 # idea, because it may cause the response to be returned
425 # character-by-character
426 assert not isinstance(iterator, str), (
427 "You should not return a string as your application iterator, "
428 "instead return a single-item list containing that string.")
429