annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/wsgiref/validate.py @ 69:33d812a61356

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