lint.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. import re
  72. import six
  73. import sys
  74. import warnings
  75. header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
  76. bad_header_value_re = re.compile(r'[\000-\037]')
  77. class WSGIWarning(Warning):
  78. """
  79. Raised in response to WSGI-spec-related warnings
  80. """
  81. def middleware(application, global_conf=None):
  82. """
  83. When applied between a WSGI server and a WSGI application, this
  84. middleware will check for WSGI compliancy on a number of levels.
  85. This middleware does not modify the request or response in any
  86. way, but will throw an AssertionError if anything seems off
  87. (except for a failure to close the application iterator, which
  88. will be printed to stderr -- there's no way to throw an exception
  89. at that point).
  90. """
  91. def lint_app(*args, **kw):
  92. assert len(args) == 2, "Two arguments required"
  93. assert not kw, "No keyword arguments allowed"
  94. environ, start_response = args
  95. check_environ(environ)
  96. # We use this to check if the application returns without
  97. # calling start_response:
  98. start_response_started = []
  99. def start_response_wrapper(*args, **kw):
  100. assert len(args) == 2 or len(args) == 3, (
  101. "Invalid number of arguments: %s" % args)
  102. assert not kw, "No keyword arguments allowed"
  103. status = args[0]
  104. headers = args[1]
  105. if len(args) == 3:
  106. exc_info = args[2]
  107. else:
  108. exc_info = None
  109. check_status(status)
  110. check_headers(headers)
  111. check_content_type(status, headers)
  112. check_exc_info(exc_info)
  113. start_response_started.append(None)
  114. return WriteWrapper(start_response(*args))
  115. environ['wsgi.input'] = InputWrapper(environ['wsgi.input'])
  116. environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors'])
  117. iterator = application(environ, start_response_wrapper)
  118. assert iterator is not None and iterator != False, (
  119. "The application must return an iterator, if only an empty list")
  120. check_iterator(iterator)
  121. return IteratorWrapper(iterator, start_response_started)
  122. return lint_app
  123. class InputWrapper(object):
  124. def __init__(self, wsgi_input):
  125. self.input = wsgi_input
  126. def read(self, *args):
  127. assert len(args) <= 1
  128. v = self.input.read(*args)
  129. assert isinstance(v, six.binary_type)
  130. return v
  131. def readline(self, *args):
  132. v = self.input.readline(*args)
  133. assert isinstance(v, six.binary_type)
  134. return v
  135. def readlines(self, *args):
  136. assert len(args) <= 1
  137. lines = self.input.readlines(*args)
  138. assert isinstance(lines, list)
  139. for line in lines:
  140. assert isinstance(line, six.binary_type)
  141. return lines
  142. def __iter__(self):
  143. while 1:
  144. line = self.readline()
  145. if not line:
  146. return
  147. yield line
  148. def close(self):
  149. assert 0, "input.close() must not be called"
  150. class ErrorWrapper(object):
  151. def __init__(self, wsgi_errors):
  152. self.errors = wsgi_errors
  153. def write(self, s):
  154. assert isinstance(s, bytes)
  155. self.errors.write(s)
  156. def flush(self):
  157. self.errors.flush()
  158. def writelines(self, seq):
  159. for line in seq:
  160. self.write(line)
  161. def close(self):
  162. assert 0, "errors.close() must not be called"
  163. class WriteWrapper(object):
  164. def __init__(self, wsgi_writer):
  165. self.writer = wsgi_writer
  166. def __call__(self, s):
  167. assert isinstance(s, six.binary_type)
  168. self.writer(s)
  169. class PartialIteratorWrapper(object):
  170. def __init__(self, wsgi_iterator):
  171. self.iterator = wsgi_iterator
  172. def __iter__(self):
  173. # We want to make sure __iter__ is called
  174. return IteratorWrapper(self.iterator)
  175. class IteratorWrapper(object):
  176. def __init__(self, wsgi_iterator, check_start_response):
  177. self.original_iterator = wsgi_iterator
  178. self.iterator = iter(wsgi_iterator)
  179. self.closed = False
  180. self.check_start_response = check_start_response
  181. def __iter__(self):
  182. return self
  183. def next(self):
  184. assert not self.closed, (
  185. "Iterator read after closed")
  186. v = six.next(self.iterator)
  187. if self.check_start_response is not None:
  188. assert self.check_start_response, (
  189. "The application returns and we started iterating over its body, but start_response has not yet been called")
  190. self.check_start_response = None
  191. return v
  192. __next__ = next
  193. def close(self):
  194. self.closed = True
  195. if hasattr(self.original_iterator, 'close'):
  196. self.original_iterator.close()
  197. def __del__(self):
  198. if not self.closed:
  199. sys.stderr.write(
  200. "Iterator garbage collected without being closed")
  201. assert self.closed, (
  202. "Iterator garbage collected without being closed")
  203. def check_environ(environ):
  204. assert isinstance(environ,dict), (
  205. "Environment is not of the right type: %r (environment: %r)"
  206. % (type(environ), environ))
  207. for key in ['REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT',
  208. 'wsgi.version', 'wsgi.input', 'wsgi.errors',
  209. 'wsgi.multithread', 'wsgi.multiprocess',
  210. 'wsgi.run_once']:
  211. assert key in environ, (
  212. "Environment missing required key: %r" % key)
  213. for key in ['HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH']:
  214. assert key not in environ, (
  215. "Environment should not have the key: %s "
  216. "(use %s instead)" % (key, key[5:]))
  217. if 'QUERY_STRING' not in environ:
  218. warnings.warn(
  219. 'QUERY_STRING is not in the WSGI environment; the cgi '
  220. 'module will use sys.argv when this variable is missing, '
  221. 'so application errors are more likely',
  222. WSGIWarning)
  223. for key in environ.keys():
  224. if '.' in key:
  225. # Extension, we don't care about its type
  226. continue
  227. assert isinstance(environ[key], str), (
  228. "Environmental variable %s is not a string: %r (value: %r)"
  229. % (key, type(environ[key]), environ[key]))
  230. assert isinstance(environ['wsgi.version'], tuple), (
  231. "wsgi.version should be a tuple (%r)" % environ['wsgi.version'])
  232. assert environ['wsgi.url_scheme'] in ('http', 'https'), (
  233. "wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
  234. check_input(environ['wsgi.input'])
  235. check_errors(environ['wsgi.errors'])
  236. # @@: these need filling out:
  237. if environ['REQUEST_METHOD'] not in (
  238. 'GET', 'HEAD', 'POST', 'OPTIONS','PUT','DELETE','TRACE'):
  239. warnings.warn(
  240. "Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
  241. WSGIWarning)
  242. assert (not environ.get('SCRIPT_NAME')
  243. or environ['SCRIPT_NAME'].startswith('/')), (
  244. "SCRIPT_NAME doesn't start with /: %r" % environ['SCRIPT_NAME'])
  245. assert (not environ.get('PATH_INFO')
  246. or environ['PATH_INFO'].startswith('/')), (
  247. "PATH_INFO doesn't start with /: %r" % environ['PATH_INFO'])
  248. if environ.get('CONTENT_LENGTH'):
  249. assert int(environ['CONTENT_LENGTH']) >= 0, (
  250. "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH'])
  251. if not environ.get('SCRIPT_NAME'):
  252. assert 'PATH_INFO' in environ, (
  253. "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
  254. "should at least be '/' if SCRIPT_NAME is empty)")
  255. assert environ.get('SCRIPT_NAME') != '/', (
  256. "SCRIPT_NAME cannot be '/'; it should instead be '', and "
  257. "PATH_INFO should be '/'")
  258. def check_input(wsgi_input):
  259. for attr in ['read', 'readline', 'readlines', '__iter__']:
  260. assert hasattr(wsgi_input, attr), (
  261. "wsgi.input (%r) doesn't have the attribute %s"
  262. % (wsgi_input, attr))
  263. def check_errors(wsgi_errors):
  264. for attr in ['flush', 'write', 'writelines']:
  265. assert hasattr(wsgi_errors, attr), (
  266. "wsgi.errors (%r) doesn't have the attribute %s"
  267. % (wsgi_errors, attr))
  268. def check_status(status):
  269. assert isinstance(status, str), (
  270. "Status must be a string (not %r)" % status)
  271. # Implicitly check that we can turn it into an integer:
  272. status_code = status.split(None, 1)[0]
  273. assert len(status_code) == 3, (
  274. "Status codes must be three characters: %r" % status_code)
  275. status_int = int(status_code)
  276. assert status_int >= 100, "Status code is invalid: %r" % status_int
  277. if len(status) < 4 or status[3] != ' ':
  278. warnings.warn(
  279. "The status string (%r) should be a three-digit integer "
  280. "followed by a single space and a status explanation"
  281. % status, WSGIWarning)
  282. def check_headers(headers):
  283. assert isinstance(headers,list), (
  284. "Headers (%r) must be of type list: %r"
  285. % (headers, type(headers)))
  286. header_names = {}
  287. for item in headers:
  288. assert isinstance(item, tuple), (
  289. "Individual headers (%r) must be of type tuple: %r"
  290. % (item, type(item)))
  291. assert len(item) == 2
  292. name, value = item
  293. assert name.lower() != 'status', (
  294. "The Status header cannot be used; it conflicts with CGI "
  295. "script, and HTTP status is not given through headers "
  296. "(value: %r)." % value)
  297. header_names[name.lower()] = None
  298. assert '\n' not in name and ':' not in name, (
  299. "Header names may not contain ':' or '\\n': %r" % name)
  300. assert header_re.search(name), "Bad header name: %r" % name
  301. assert not name.endswith('-') and not name.endswith('_'), (
  302. "Names may not end in '-' or '_': %r" % name)
  303. assert not bad_header_value_re.search(value), (
  304. "Bad header value: %r (bad char: %r)"
  305. % (value, bad_header_value_re.search(value).group(0)))
  306. def check_content_type(status, headers):
  307. code = int(status.split(None, 1)[0])
  308. # @@: need one more person to verify this interpretation of RFC 2616
  309. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  310. NO_MESSAGE_BODY = (204, 304)
  311. NO_MESSAGE_TYPE = (204, 304)
  312. for name, value in headers:
  313. if name.lower() == 'content-type':
  314. if code not in NO_MESSAGE_TYPE:
  315. return
  316. assert 0, (("Content-Type header found in a %s response, "
  317. "which must not return content.") % code)
  318. if code not in NO_MESSAGE_BODY:
  319. assert 0, "No Content-Type header found in headers (%s)" % headers
  320. def check_exc_info(exc_info):
  321. assert exc_info is None or type(exc_info) is type(()), (
  322. "exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
  323. # More exc_info checks?
  324. def check_iterator(iterator):
  325. # Technically a string is legal, which is why it's a really bad
  326. # idea, because it may cause the response to be returned
  327. # character-by-character
  328. assert not isinstance(iterator, str), (
  329. "You should not return a string as your application iterator, "
  330. "instead return a single-item list containing that string.")
  331. def make_middleware(application, global_conf):
  332. # @@: global_conf should be taken out of the middleware function,
  333. # and isolated here
  334. return middleware(application)
  335. make_middleware.__doc__ = __doc__
  336. __all__ = ['middleware', 'make_middleware']