PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/wsgiref/validate.py

https://bitbucket.org/varialus/jyjy
Python | 432 lines | 374 code | 25 blank | 33 comment | 24 complexity | ef0a6ea241aa72bf9e44d9192393a1cc MD5 | raw file
  1. # (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. """
  6. Middleware to check for obedience to the WSGI specification.
  7. Some of the things this checks:
  8. * Signature of the application and start_response (including that
  9. keyword arguments are not used).
  10. * Environment checks:
  11. - Environment is a dictionary (and not a subclass).
  12. - That all the required keys are in the environment: REQUEST_METHOD,
  13. SERVER_NAME, SERVER_PORT, wsgi.version, wsgi.input, wsgi.errors,
  14. wsgi.multithread, wsgi.multiprocess, wsgi.run_once
  15. - That HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH are not in the
  16. environment (these headers should appear as CONTENT_LENGTH and
  17. CONTENT_TYPE).
  18. - Warns if QUERY_STRING is missing, as the cgi module acts
  19. unpredictably in that case.
  20. - That CGI-style variables (that don't contain a .) have
  21. (non-unicode) string values
  22. - That wsgi.version is a tuple
  23. - That wsgi.url_scheme is 'http' or 'https' (@@: is this too
  24. restrictive?)
  25. - Warns if the REQUEST_METHOD is not known (@@: probably too
  26. restrictive).
  27. - That SCRIPT_NAME and PATH_INFO are empty or start with /
  28. - That at least one of SCRIPT_NAME or PATH_INFO are set.
  29. - That CONTENT_LENGTH is a positive integer.
  30. - That SCRIPT_NAME is not '/' (it should be '', and PATH_INFO should
  31. be '/').
  32. - That wsgi.input has the methods read, readline, readlines, and
  33. __iter__
  34. - That wsgi.errors has the methods flush, write, writelines
  35. * The status is a string, contains a space, starts with an integer,
  36. and that integer is in range (> 100).
  37. * That the headers is a list (not a subclass, not another kind of
  38. sequence).
  39. * That the items of the headers are tuples of strings.
  40. * That there is no 'status' header (that is used in CGI, but not in
  41. WSGI).
  42. * That the headers don't contain newlines or colons, end in _ or -, or
  43. contain characters codes below 037.
  44. * That Content-Type is given if there is content (CGI often has a
  45. default content type, but WSGI does not).
  46. * That no Content-Type is given when there is no content (@@: is this
  47. too restrictive?)
  48. * That the exc_info argument to start_response is a tuple or None.
  49. * That all calls to the writer are with strings, and no other methods
  50. on the writer are accessed.
  51. * That wsgi.input is used properly:
  52. - .read() is called with zero or one argument
  53. - That it returns a string
  54. - That readline, readlines, and __iter__ return strings
  55. - That .close() is not called
  56. - No other methods are provided
  57. * That wsgi.errors is used properly:
  58. - .write() and .writelines() is called with a string
  59. - That .close() is not called, and no other methods are provided.
  60. * The response iterator:
  61. - That it is not a string (it should be a list of a single string; a
  62. string will work, but perform horribly).
  63. - That .next() returns a string
  64. - That the iterator is not iterated over until start_response has
  65. been called (that can signal either a server or application
  66. error).
  67. - That .close() is called (doesn't raise exception, only prints to
  68. sys.stderr, because we only know it isn't called when the object
  69. is garbage collected).
  70. """
  71. __all__ = ['validator']
  72. import re
  73. import sys
  74. from types import DictType, StringType, TupleType, ListType
  75. import warnings
  76. header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
  77. bad_header_value_re = re.compile(r'[\000-\037]')
  78. class WSGIWarning(Warning):
  79. """
  80. Raised in response to WSGI-spec-related warnings
  81. """
  82. def assert_(cond, *args):
  83. if not cond:
  84. raise AssertionError(*args)
  85. def validator(application):
  86. """
  87. When applied between a WSGI server and a WSGI application, this
  88. middleware will check for WSGI compliancy on a number of levels.
  89. This middleware does not modify the request or response in any
  90. way, but will throw an AssertionError if anything seems off
  91. (except for a failure to close the application iterator, which
  92. will be printed to stderr -- there's no way to throw an exception
  93. at that point).
  94. """
  95. def lint_app(*args, **kw):
  96. assert_(len(args) == 2, "Two arguments required")
  97. assert_(not kw, "No keyword arguments allowed")
  98. environ, start_response = args
  99. check_environ(environ)
  100. # We use this to check if the application returns without
  101. # calling start_response:
  102. start_response_started = []
  103. def start_response_wrapper(*args, **kw):
  104. assert_(len(args) == 2 or len(args) == 3, (
  105. "Invalid number of arguments: %s" % (args,)))
  106. assert_(not kw, "No keyword arguments allowed")
  107. status = args[0]
  108. headers = args[1]
  109. if len(args) == 3:
  110. exc_info = args[2]
  111. else:
  112. exc_info = None
  113. check_status(status)
  114. check_headers(headers)
  115. check_content_type(status, headers)
  116. check_exc_info(exc_info)
  117. start_response_started.append(None)
  118. return WriteWrapper(start_response(*args))
  119. environ['wsgi.input'] = InputWrapper(environ['wsgi.input'])
  120. environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors'])
  121. iterator = application(environ, start_response_wrapper)
  122. assert_(iterator is not None and iterator != False,
  123. "The application must return an iterator, if only an empty list")
  124. check_iterator(iterator)
  125. return IteratorWrapper(iterator, start_response_started)
  126. return lint_app
  127. class InputWrapper:
  128. def __init__(self, wsgi_input):
  129. self.input = wsgi_input
  130. def read(self, *args):
  131. assert_(len(args) <= 1)
  132. v = self.input.read(*args)
  133. assert_(type(v) is type(""))
  134. return v
  135. def readline(self):
  136. v = self.input.readline()
  137. assert_(type(v) is type(""))
  138. return v
  139. def readlines(self, *args):
  140. assert_(len(args) <= 1)
  141. lines = self.input.readlines(*args)
  142. assert_(type(lines) is type([]))
  143. for line in lines:
  144. assert_(type(line) is type(""))
  145. return lines
  146. def __iter__(self):
  147. while 1:
  148. line = self.readline()
  149. if not line:
  150. return
  151. yield line
  152. def close(self):
  153. assert_(0, "input.close() must not be called")
  154. class ErrorWrapper:
  155. def __init__(self, wsgi_errors):
  156. self.errors = wsgi_errors
  157. def write(self, s):
  158. assert_(type(s) is type(""))
  159. self.errors.write(s)
  160. def flush(self):
  161. self.errors.flush()
  162. def writelines(self, seq):
  163. for line in seq:
  164. self.write(line)
  165. def close(self):
  166. assert_(0, "errors.close() must not be called")
  167. class WriteWrapper:
  168. def __init__(self, wsgi_writer):
  169. self.writer = wsgi_writer
  170. def __call__(self, s):
  171. assert_(type(s) is type(""))
  172. self.writer(s)
  173. class PartialIteratorWrapper:
  174. def __init__(self, wsgi_iterator):
  175. self.iterator = wsgi_iterator
  176. def __iter__(self):
  177. # We want to make sure __iter__ is called
  178. return IteratorWrapper(self.iterator, None)
  179. class IteratorWrapper:
  180. def __init__(self, wsgi_iterator, check_start_response):
  181. self.original_iterator = wsgi_iterator
  182. self.iterator = iter(wsgi_iterator)
  183. self.closed = False
  184. self.check_start_response = check_start_response
  185. def __iter__(self):
  186. return self
  187. def next(self):
  188. assert_(not self.closed,
  189. "Iterator read after closed")
  190. v = self.iterator.next()
  191. if self.check_start_response is not None:
  192. assert_(self.check_start_response,
  193. "The application returns and we started iterating over its body, but start_response has not yet been called")
  194. self.check_start_response = None
  195. return v
  196. def close(self):
  197. self.closed = True
  198. if hasattr(self.original_iterator, 'close'):
  199. self.original_iterator.close()
  200. def __del__(self):
  201. if not self.closed:
  202. sys.stderr.write(
  203. "Iterator garbage collected without being closed")
  204. assert_(self.closed,
  205. "Iterator garbage collected without being closed")
  206. def check_environ(environ):
  207. assert_(type(environ) is DictType,
  208. "Environment is not of the right type: %r (environment: %r)"
  209. % (type(environ), environ))
  210. for key in ['REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT',
  211. 'wsgi.version', 'wsgi.input', 'wsgi.errors',
  212. 'wsgi.multithread', 'wsgi.multiprocess',
  213. 'wsgi.run_once']:
  214. assert_(key in environ,
  215. "Environment missing required key: %r" % (key,))
  216. for key in ['HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH']:
  217. assert_(key not in environ,
  218. "Environment should not have the key: %s "
  219. "(use %s instead)" % (key, key[5:]))
  220. if 'QUERY_STRING' not in environ:
  221. warnings.warn(
  222. 'QUERY_STRING is not in the WSGI environment; the cgi '
  223. 'module will use sys.argv when this variable is missing, '
  224. 'so application errors are more likely',
  225. WSGIWarning)
  226. for key in environ.keys():
  227. if '.' in key:
  228. # Extension, we don't care about its type
  229. continue
  230. assert_(type(environ[key]) is StringType,
  231. "Environmental variable %s is not a string: %r (value: %r)"
  232. % (key, type(environ[key]), environ[key]))
  233. assert_(type(environ['wsgi.version']) is TupleType,
  234. "wsgi.version should be a tuple (%r)" % (environ['wsgi.version'],))
  235. assert_(environ['wsgi.url_scheme'] in ('http', 'https'),
  236. "wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
  237. check_input(environ['wsgi.input'])
  238. check_errors(environ['wsgi.errors'])
  239. # @@: these need filling out:
  240. if environ['REQUEST_METHOD'] not in (
  241. 'GET', 'HEAD', 'POST', 'OPTIONS','PUT','DELETE','TRACE'):
  242. warnings.warn(
  243. "Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
  244. WSGIWarning)
  245. assert_(not environ.get('SCRIPT_NAME')
  246. or environ['SCRIPT_NAME'].startswith('/'),
  247. "SCRIPT_NAME doesn't start with /: %r" % environ['SCRIPT_NAME'])
  248. assert_(not environ.get('PATH_INFO')
  249. or environ['PATH_INFO'].startswith('/'),
  250. "PATH_INFO doesn't start with /: %r" % environ['PATH_INFO'])
  251. if environ.get('CONTENT_LENGTH'):
  252. assert_(int(environ['CONTENT_LENGTH']) >= 0,
  253. "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
  254. if not environ.get('SCRIPT_NAME'):
  255. assert_('PATH_INFO' in environ,
  256. "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
  257. "should at least be '/' if SCRIPT_NAME is empty)")
  258. assert_(environ.get('SCRIPT_NAME') != '/',
  259. "SCRIPT_NAME cannot be '/'; it should instead be '', and "
  260. "PATH_INFO should be '/'")
  261. def check_input(wsgi_input):
  262. for attr in ['read', 'readline', 'readlines', '__iter__']:
  263. assert_(hasattr(wsgi_input, attr),
  264. "wsgi.input (%r) doesn't have the attribute %s"
  265. % (wsgi_input, attr))
  266. def check_errors(wsgi_errors):
  267. for attr in ['flush', 'write', 'writelines']:
  268. assert_(hasattr(wsgi_errors, attr),
  269. "wsgi.errors (%r) doesn't have the attribute %s"
  270. % (wsgi_errors, attr))
  271. def check_status(status):
  272. assert_(type(status) is StringType,
  273. "Status must be a string (not %r)" % status)
  274. # Implicitly check that we can turn it into an integer:
  275. status_code = status.split(None, 1)[0]
  276. assert_(len(status_code) == 3,
  277. "Status codes must be three characters: %r" % status_code)
  278. status_int = int(status_code)
  279. assert_(status_int >= 100, "Status code is invalid: %r" % status_int)
  280. if len(status) < 4 or status[3] != ' ':
  281. warnings.warn(
  282. "The status string (%r) should be a three-digit integer "
  283. "followed by a single space and a status explanation"
  284. % status, WSGIWarning)
  285. def check_headers(headers):
  286. assert_(type(headers) is ListType,
  287. "Headers (%r) must be of type list: %r"
  288. % (headers, type(headers)))
  289. header_names = {}
  290. for item in headers:
  291. assert_(type(item) is TupleType,
  292. "Individual headers (%r) must be of type tuple: %r"
  293. % (item, type(item)))
  294. assert_(len(item) == 2)
  295. name, value = item
  296. assert_(name.lower() != 'status',
  297. "The Status header cannot be used; it conflicts with CGI "
  298. "script, and HTTP status is not given through headers "
  299. "(value: %r)." % value)
  300. header_names[name.lower()] = None
  301. assert_('\n' not in name and ':' not in name,
  302. "Header names may not contain ':' or '\\n': %r" % name)
  303. assert_(header_re.search(name), "Bad header name: %r" % name)
  304. assert_(not name.endswith('-') and not name.endswith('_'),
  305. "Names may not end in '-' or '_': %r" % name)
  306. if bad_header_value_re.search(value):
  307. assert_(0, "Bad header value: %r (bad char: %r)"
  308. % (value, bad_header_value_re.search(value).group(0)))
  309. def check_content_type(status, headers):
  310. code = int(status.split(None, 1)[0])
  311. # @@: need one more person to verify this interpretation of RFC 2616
  312. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  313. NO_MESSAGE_BODY = (204, 304)
  314. for name, value in headers:
  315. if name.lower() == 'content-type':
  316. if code not in NO_MESSAGE_BODY:
  317. return
  318. assert_(0, ("Content-Type header found in a %s response, "
  319. "which must not return content.") % code)
  320. if code not in NO_MESSAGE_BODY:
  321. assert_(0, "No Content-Type header found in headers (%s)" % headers)
  322. def check_exc_info(exc_info):
  323. assert_(exc_info is None or type(exc_info) is type(()),
  324. "exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
  325. # More exc_info checks?
  326. def check_iterator(iterator):
  327. # Technically a string is legal, which is why it's a really bad
  328. # idea, because it may cause the response to be returned
  329. # character-by-character
  330. assert_(not isinstance(iterator, str),
  331. "You should not return a string as your application iterator, "
  332. "instead return a single-item list containing that string.")