summaryrefslogtreecommitdiff
path: root/webtest/lint.py
blob: a06fe6a5a36c512022506658e15ce0473230820e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# (c) 2005 Ian Bicking and contributors; written for Paste
# (http://pythonpaste.org)
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php Also licenced under the
# Apache License, 2.0: http://opensource.org/licenses/apache2.0.php Licensed to
# PSF under a Contributor Agreement

"""
Middleware to check for obedience to the WSGI specification.

Some of the things this checks:

* Signature of the application and start_response (including that
  keyword arguments are not used).

* Environment checks:

  - Environment is a dictionary (and not a subclass).

  - That all the required keys are in the environment: REQUEST_METHOD,
    SERVER_NAME, SERVER_PORT, wsgi.version, wsgi.input, wsgi.errors,
    wsgi.multithread, wsgi.multiprocess, wsgi.run_once

  - That HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH are not in the
    environment (these headers should appear as CONTENT_LENGTH and
    CONTENT_TYPE).

  - Warns if QUERY_STRING is missing, as the cgi module acts
    unpredictably in that case.

  - That CGI-style variables (that don't contain a .) have
    (non-unicode) string values

  - That wsgi.version is a tuple

  - That wsgi.url_scheme is 'http' or 'https' (@@: is this too
    restrictive?)

  - Warns if the REQUEST_METHOD is not known (@@: probably too
    restrictive).

  - That SCRIPT_NAME and PATH_INFO are empty or start with /

  - That at least one of SCRIPT_NAME or PATH_INFO are set.

  - That CONTENT_LENGTH is a positive integer.

  - That SCRIPT_NAME is not '/' (it should be '', and PATH_INFO should
    be '/').

  - That wsgi.input has the methods read, readline, readlines, and
    __iter__

  - That wsgi.errors has the methods flush, write, writelines

* The status is a string, contains a space, starts with an integer,
  and that integer is in range (> 100).

* That the headers is a list (not a subclass, not another kind of
  sequence).

* That the items of the headers are tuples of 'native' strings (i.e.
  bytestrings in Python2, and unicode strings in Python3).

* That there is no 'status' header (that is used in CGI, but not in
  WSGI).

* That the headers don't contain newlines or colons, end in _ or -, or
  contain characters codes below 037.

* That Content-Type is given if there is content (CGI often has a
  default content type, but WSGI does not).

* That no Content-Type is given when there is no content (@@: is this
  too restrictive?)

* That the exc_info argument to start_response is a tuple or None.

* That all calls to the writer are with strings, and no other methods
  on the writer are accessed.

* That wsgi.input is used properly:

  - .read() is called with zero or one argument

  - That it returns a string

  - That readline, readlines, and __iter__ return strings

  - That .close() is not called

  - No other methods are provided

* That wsgi.errors is used properly:

  - .write() and .writelines() is called with a string, except
    with python3

  - That .close() is not called, and no other methods are provided.

* The response iterator:

  - That it is not a string (it should be a list of a single string; a
    string will work, but perform horribly).

  - That .next() returns a string

  - That the iterator is not iterated over until start_response has
    been called (that can signal either a server or application
    error).

  - That .close() is called (doesn't raise exception, only prints to
    sys.stderr, because we only know it isn't called when the object
    is garbage collected).

"""

import re
import warnings

from webtest.compat import Iterable

header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
bad_header_value_re = re.compile(r'[\000-\037]')

valid_methods = (
    'GET', 'HEAD', 'POST', 'OPTIONS', 'PUT', 'DELETE',
    'TRACE', 'PATCH',
)

METADATA_TYPE = (str, bytes)

# PEP-3333 says that environment variables must be "native strings",
# i.e. str(), which however is something *different* in py2 and py3.
SLASH = '/'


def to_string(value):
    if not isinstance(value, str):
        return value.decode('latin1')
    else:
        return value


class WSGIWarning(Warning):
    """
    Raised in response to WSGI-spec-related warnings
    """


def middleware(application, global_conf=None):

    """
    When applied between a WSGI server and a WSGI application, this
    middleware will check for WSGI compliancy on a number of levels.
    This middleware does not modify the request or response in any
    way, but will throw an AssertionError if anything seems off
    (except for a failure to close the application iterator, which
    will be printed to stderr -- there's no way to throw an exception
    at that point).
    """

    def lint_app(*args, **kw):
        assert len(args) == 2, "Two arguments required"
        assert not kw, "No keyword arguments allowed"
        environ, start_response = args

        check_environ(environ)

        # We use this to check if the application returns without
        # calling start_response:
        start_response_started = []

        def start_response_wrapper(*args, **kw):
            assert len(args) == 2 or len(args) == 3, (
                "Invalid number of arguments: %s" % args)
            assert not kw, "No keyword arguments allowed"
            status = args[0]
            headers = args[1]
            if len(args) == 3:
                exc_info = args[2]
            else:
                exc_info = None

            check_status(status)
            check_headers(headers)
            check_content_type(status, headers)
            check_exc_info(exc_info)

            start_response_started.append(None)
            return WriteWrapper(start_response(*args))

        environ['wsgi.input'] = InputWrapper(environ['wsgi.input'])
        environ['wsgi.errors'] = ErrorWrapper(environ['wsgi.errors'])

        iterator = application(environ, start_response_wrapper)
        if not isinstance(iterator, Iterable):
            raise AssertionError(
                "The application must return an iterator, if only an empty list"
            )

        check_iterator(iterator)

        return IteratorWrapper(iterator, start_response_started)

    return lint_app


class InputWrapper:

    def __init__(self, wsgi_input):
        self.input = wsgi_input

    def read(self, *args):
        assert len(args) <= 1
        v = self.input.read(*args)
        assert type(v) is bytes
        return v

    def readline(self, *args):
        v = self.input.readline(*args)
        assert type(v) is bytes
        return v

    def readlines(self, *args):
        assert len(args) <= 1
        lines = self.input.readlines(*args)
        assert isinstance(lines, list)
        for line in lines:
            assert type(line) is bytes
        return lines

    def __iter__(self):
        while 1:
            line = self.readline()
            if not line:
                return
            yield line

    def close(self):
        raise AssertionError("input.close() must not be called")

    def seek(self, *a, **kw):
        return self.input.seek(*a, **kw)


class ErrorWrapper:

    def __init__(self, wsgi_errors):
        self.errors = wsgi_errors

    def write(self, s):
        self.errors.write(s)

    def flush(self):
        self.errors.flush()

    def writelines(self, seq):
        for line in seq:
            self.write(line)

    def close(self):
        raise AssertionError("errors.close() must not be called")


class WriteWrapper:

    def __init__(self, wsgi_writer):
        self.writer = wsgi_writer

    def __call__(self, s):
        assert type(s) is bytes
        self.writer(s)


class IteratorWrapper:

    def __init__(self, wsgi_iterator, check_start_response):
        self.original_iterator = wsgi_iterator
        self.iterator = iter(wsgi_iterator)
        self.closed = False
        self.check_start_response = check_start_response

    def __iter__(self):
        return self

    def next(self):
        assert not self.closed, (
            "Iterator read after closed")
        v = next(self.iterator)
        if self.check_start_response is not None:
            assert self.check_start_response, (
                "The application returns and we started iterating over its"
                " body, but start_response has not yet been called")
            self.check_start_response = None
        assert isinstance(v, bytes), (
            "Iterator %r returned a non-%r object: %r"
            % (self.iterator, bytes, v))
        return v

    __next__ = next

    def close(self):
        self.closed = True
        if hasattr(self.original_iterator, 'close'):
            self.original_iterator.close()

    def __del__(self):
        assert self.closed, (
            "Iterator garbage collected without being closed")


def check_environ(environ):
    if type(environ) is not dict:
        raise AssertionError(
            "Environment is not of the right type: %r (environment: %r)"
            % (type(environ), environ)
        )

    for key in ['REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT',
                'wsgi.version', 'wsgi.input', 'wsgi.errors',
                'wsgi.multithread', 'wsgi.multiprocess',
                'wsgi.run_once']:
        if key not in environ:
            raise AssertionError("Environment missing required key: %r" % key)

    for key in ['HTTP_CONTENT_TYPE', 'HTTP_CONTENT_LENGTH']:
        if key in environ:
            raise AssertionError(
                "Environment should not have the key: %s "
                "(use %s instead)" % (key, key[5:])
            )

    if 'QUERY_STRING' not in environ:
        warnings.warn(
            'QUERY_STRING is not in the WSGI environment; the cgi '
            'module will use sys.argv when this variable is missing, '
            'so application errors are more likely',
            WSGIWarning)

    for key in environ:
        if '.' in key:
            # Extension, we don't care about its type
            continue
        if type(environ[key]) not in METADATA_TYPE:
            raise AssertionError(
                "Environmental variable %s is not a string: %r (value: %r)"
                % (key, type(environ[key]), environ[key])
            )

    if type(environ['wsgi.version']) is not tuple:
        raise AssertionError(
            "wsgi.version should be a tuple (%r)" % environ['wsgi.version']
        )

    if environ['wsgi.url_scheme'] not in ('http', 'https'):
        raise AssertionError(
            "wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme']
        )

    check_input(environ['wsgi.input'])
    check_errors(environ['wsgi.errors'])

    # @@: these need filling out:
    if environ['REQUEST_METHOD'] not in valid_methods:
        warnings.warn(
            "Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
            WSGIWarning)

    if environ.get('SCRIPT_NAME') and not environ['SCRIPT_NAME'].startswith(SLASH):
        raise AssertionError(
            "SCRIPT_NAME doesn't start with /: %r" % environ['SCRIPT_NAME']
        )

    if environ.get('PATH_INFO') and not environ['PATH_INFO'].startswith(SLASH):
        raise AssertionError(
            "PATH_INFO doesn't start with /: %r" % environ['PATH_INFO']
        )

    if environ.get('CONTENT_LENGTH'):
        if int(environ['CONTENT_LENGTH']) < 0:
            raise AssertionError(
                "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH']
            )

    if not environ.get('SCRIPT_NAME'):
        if 'PATH_INFO' not in environ:
            raise AssertionError(
                "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO "
                "should at least be '/' if SCRIPT_NAME is empty)"
            )

    if environ.get('SCRIPT_NAME') == SLASH:
        raise AssertionError(
            "SCRIPT_NAME cannot be '/'; it should instead be '', and "
            "PATH_INFO should be '/'"
        )


def check_input(wsgi_input):
    for attr in ['read', 'readline', 'readlines', '__iter__']:
        if not hasattr(wsgi_input, attr):
            raise AssertionError(
                "wsgi.input (%r) doesn't have the attribute %s"
                % (wsgi_input, attr)
            )


def check_errors(wsgi_errors):
    for attr in ['flush', 'write', 'writelines']:
        if not hasattr(wsgi_errors, attr):
            raise AssertionError(
                "wsgi.errors (%r) doesn't have the attribute %s"
                % (wsgi_errors, attr)
            )


def check_status(status):
    if type(status) not in METADATA_TYPE:
        raise AssertionError(f"Status must be a {METADATA_TYPE} (not {status!r})")

    status = to_string(status)

    if len(status) <= 5:
        raise AssertionError(
            "The status string (%r) should be a three-digit "
            "integer followed by a single space and a status explanation" % status
        )

    if not status[:3].isdigit():
        raise AssertionError(
            "The status string (%r) should start with three digits" % status
        )

    status_int = int(status[:3])

    if status_int < 100:
        raise AssertionError(
            "The status code must be greater or equal than 100 (got %d)" % status_int
        )

    if status[3] != ' ':
        raise AssertionError(
            "The status string (%r) should start with three"
            "digits and a space (4th characters is not a space here)" % status
        )


def _assert_latin1_str(string, message):
    if type(string) is not str:
        raise AssertionError(message)

    if type(string) is str:
        try:
            string.encode('latin1')
        except UnicodeEncodeError:
            raise AssertionError(message)
    return string


def check_headers(headers):
    if type(headers) is not list:
        raise AssertionError(
            f"Headers ({headers!r}) must be of type list: {type(headers)!r}"
        )

    for item in headers:
        if type(item) is not tuple:
            raise AssertionError(
                "Individual headers (%r) must be of type tuple: %r"
                % (item, type(item))
            )

        assert len(item) == 2
        name, value = item
        _assert_latin1_str(
            name,
            "Header names must be latin1 string "
            "(not Py2 unicode or Py3 bytes type). "
            "%r is not a valid latin1 string" % (name,)
        )

        if name.lower() == 'status':
            raise AssertionError(
                "The Status header cannot be used; it conflicts with CGI "
                "script, and HTTP status is not given through headers "
                "(value: %r)." % value
            )

        if '\n' in name or ':' in name:
            raise AssertionError(
                "Header names may not contain ':' or '\\n': %r" % name
            )

        if not header_re.search(name):
            raise AssertionError("Bad header name: %r" % name)

        if name.endswith('-') or name.endswith('_'):
            raise AssertionError("Names may not end in '-' or '_': %r" % name)

        _assert_latin1_str(
            value,
            "Header values must be latin1 string "
            "(not Py2 unicode or Py3 bytes type)."
            "%r is not a valid latin1 string" % (value,)
        )

        if bad_header_value_re.search(value):
            raise AssertionError(
                "Bad header value: %r (bad char: %r)"
                % (value, bad_header_value_re.search(value).group(0))
            )


def check_content_type(status, headers):
    code = int(status.split(None, 1)[0])
    # @@: need one more person to verify this interpretation of RFC 2616
    #     http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
    NO_MESSAGE_BODY = (201, 204, 304)
    NO_MESSAGE_TYPE = (204, 304)
    length = None
    for name, value in headers:
        if name.lower() == 'content-length' and value.isdigit():
            length = int(value)
            break
    for name, value in headers:
        if name.lower() == 'content-type':
            if code not in NO_MESSAGE_TYPE:
                return
            elif not length:
                warnings.warn(("Content-Type header found in a %s response, "
                               "which should not return content.") % code,
                              WSGIWarning)
                return
            else:
                raise AssertionError(
                    "Content-Type header found in a %s response, "
                    "which must not return content." % code
                )

    if code not in NO_MESSAGE_BODY and length is not None and length > 0:
        raise AssertionError(
            "No Content-Type header found in headers (%s)" % headers
        )


def check_exc_info(exc_info):
    if exc_info is not None and type(exc_info) is not tuple:
        raise AssertionError(
            f"exc_info ({exc_info!r}) is not a tuple: {type(exc_info)!r}"
        )
    # More exc_info checks?


def check_iterator(iterator):
    valid_type = bytes
    # Technically a bytes (str for py2.x) is legal, which is why it's a
    # really bad idea, because it may cause the response to be returned
    # character-by-character

    if isinstance(iterator, valid_type):
        raise AssertionError(
            "You should not return a bytes as your application iterator, "
            "instead return a single-item list containing that string."
        )

__all__ = ['middleware']