summaryrefslogtreecommitdiff
path: root/waitress/tests/test_adjustments.py
blob: 00b035399e74413cd2f9b0ab6b7ab3b02a7311d0 (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
import sys
import socket
import warnings

from waitress.compat import (
    PY2,
    WIN,
    )

if sys.version_info[:2] == (2, 6): # pragma: no cover
    import unittest2 as unittest
else: # pragma: no cover
    import unittest

class Test_asbool(unittest.TestCase):

    def _callFUT(self, s):
        from waitress.adjustments import asbool
        return asbool(s)

    def test_s_is_None(self):
        result = self._callFUT(None)
        self.assertEqual(result, False)

    def test_s_is_True(self):
        result = self._callFUT(True)
        self.assertEqual(result, True)

    def test_s_is_False(self):
        result = self._callFUT(False)
        self.assertEqual(result, False)

    def test_s_is_true(self):
        result = self._callFUT('True')
        self.assertEqual(result, True)

    def test_s_is_false(self):
        result = self._callFUT('False')
        self.assertEqual(result, False)

    def test_s_is_yes(self):
        result = self._callFUT('yes')
        self.assertEqual(result, True)

    def test_s_is_on(self):
        result = self._callFUT('on')
        self.assertEqual(result, True)

    def test_s_is_1(self):
        result = self._callFUT(1)
        self.assertEqual(result, True)

class Test_as_socket_list(unittest.TestCase):

    def test_only_sockets_in_list(self):
        from waitress.adjustments import as_socket_list
        sockets = [
            socket.socket(socket.AF_INET, socket.SOCK_STREAM),
            socket.socket(socket.AF_INET6, socket.SOCK_STREAM)]
        if hasattr(socket, 'AF_UNIX'):
            sockets.append(socket.socket(socket.AF_UNIX, socket.SOCK_STREAM))
        new_sockets = as_socket_list(sockets)
        self.assertEqual(sockets, new_sockets)
        for sock in sockets:
            sock.close()

    def test_not_only_sockets_in_list(self):
        from waitress.adjustments import as_socket_list
        sockets = [
            socket.socket(socket.AF_INET, socket.SOCK_STREAM),
            socket.socket(socket.AF_INET6, socket.SOCK_STREAM),
            {'something': 'else'}]
        new_sockets = as_socket_list(sockets)
        self.assertEqual(new_sockets, [sockets[0], sockets[1]])
        for sock in [sock for sock in sockets if isinstance(sock, socket.socket)]:
            sock.close()

class TestAdjustments(unittest.TestCase):

    def _hasIPv6(self): # pragma: nocover
        if not socket.has_ipv6:
            return False

        try:
            socket.getaddrinfo(
                '::1',
                0,
                socket.AF_UNSPEC,
                socket.SOCK_STREAM,
                socket.IPPROTO_TCP,
                socket.AI_PASSIVE | socket.AI_ADDRCONFIG
            )

            return True
        except socket.gaierror as e:
            # Check to see what the error is
            if e.errno == socket.EAI_ADDRFAMILY:
                return False
            else:
                raise e

    def _makeOne(self, **kw):
        from waitress.adjustments import Adjustments
        return Adjustments(**kw)

    def test_goodvars(self):
        inst = self._makeOne(
            host='localhost',
            port='8080',
            threads='5',
            trusted_proxy='192.168.1.1',
            trusted_proxy_headers={'forwarded'},
            trusted_proxy_count=2,
            log_untrusted_proxy_headers=True,
            url_scheme='https',
            backlog='20',
            recv_bytes='200',
            send_bytes='300',
            outbuf_overflow='400',
            inbuf_overflow='500',
            connection_limit='1000',
            cleanup_interval='1100',
            channel_timeout='1200',
            log_socket_errors='true',
            max_request_header_size='1300',
            max_request_body_size='1400',
            expose_tracebacks='true',
            ident='abc',
            asyncore_loop_timeout='5',
            asyncore_use_poll=True,
            unix_socket_perms='777',
            url_prefix='///foo/',
            ipv4=True,
            ipv6=False,
        )

        self.assertEqual(inst.host, 'localhost')
        self.assertEqual(inst.port, 8080)
        self.assertEqual(inst.threads, 5)
        self.assertEqual(inst.trusted_proxy, '192.168.1.1')
        self.assertEqual(inst.trusted_proxy_headers, {'forwarded'})
        self.assertEqual(inst.trusted_proxy_count, 2)
        self.assertEqual(inst.log_untrusted_proxy_headers, True)
        self.assertEqual(inst.url_scheme, 'https')
        self.assertEqual(inst.backlog, 20)
        self.assertEqual(inst.recv_bytes, 200)
        self.assertEqual(inst.send_bytes, 300)
        self.assertEqual(inst.outbuf_overflow, 400)
        self.assertEqual(inst.inbuf_overflow, 500)
        self.assertEqual(inst.connection_limit, 1000)
        self.assertEqual(inst.cleanup_interval, 1100)
        self.assertEqual(inst.channel_timeout, 1200)
        self.assertEqual(inst.log_socket_errors, True)
        self.assertEqual(inst.max_request_header_size, 1300)
        self.assertEqual(inst.max_request_body_size, 1400)
        self.assertEqual(inst.expose_tracebacks, True)
        self.assertEqual(inst.asyncore_loop_timeout, 5)
        self.assertEqual(inst.asyncore_use_poll, True)
        self.assertEqual(inst.ident, 'abc')
        self.assertEqual(inst.unix_socket_perms, 0o777)
        self.assertEqual(inst.url_prefix, '/foo')
        self.assertEqual(inst.ipv4, True)
        self.assertEqual(inst.ipv6, False)

        bind_pairs = [
            sockaddr[:2]
            for (family, _, _, sockaddr) in inst.listen
            if family == socket.AF_INET
        ]

        # On Travis, somehow we start listening to two sockets when resolving
        # localhost...
        self.assertEqual(('127.0.0.1', 8080), bind_pairs[0])

    def test_goodvar_listen(self):
        inst = self._makeOne(listen='127.0.0.1')

        bind_pairs = [(host, port) for (_, _, _, (host, port)) in inst.listen]

        self.assertEqual(bind_pairs, [('127.0.0.1', 8080)])

    def test_default_listen(self):
        inst = self._makeOne()

        bind_pairs = [(host, port) for (_, _, _, (host, port)) in inst.listen]

        self.assertEqual(bind_pairs, [('0.0.0.0', 8080)])

    def test_multiple_listen(self):
        inst = self._makeOne(listen='127.0.0.1:9090 127.0.0.1:8080')

        bind_pairs = [sockaddr[:2] for (_, _, _, sockaddr) in inst.listen]

        self.assertEqual(bind_pairs,
                         [('127.0.0.1', 9090),
                          ('127.0.0.1', 8080)])

    def test_wildcard_listen(self):
        inst = self._makeOne(listen='*:8080')

        bind_pairs = [sockaddr[:2] for (_, _, _, sockaddr) in inst.listen]

        self.assertTrue(len(bind_pairs) >= 1)

    def test_ipv6_no_port(self): # pragma: nocover
        if not self._hasIPv6():
            return

        inst = self._makeOne(listen='[::1]')

        bind_pairs = [sockaddr[:2] for (_, _, _, sockaddr) in inst.listen]

        self.assertEqual(bind_pairs, [('::1', 8080)])

    def test_bad_port(self):
        self.assertRaises(ValueError, self._makeOne, listen='127.0.0.1:test')

    def test_service_port(self):
        if WIN and PY2: # pragma: no cover
            # On Windows and Python 2 this is broken, so we raise a ValueError
            self.assertRaises(
                ValueError,
                self._makeOne,
                listen='127.0.0.1:http',
            )
            return

        inst = self._makeOne(listen='127.0.0.1:http 0.0.0.0:https')

        bind_pairs = [sockaddr[:2] for (_, _, _, sockaddr) in inst.listen]

        self.assertEqual(bind_pairs, [('127.0.0.1', 80), ('0.0.0.0', 443)])

    def test_dont_mix_host_port_listen(self):
        self.assertRaises(
            ValueError,
            self._makeOne,
            host='localhost',
            port='8080',
            listen='127.0.0.1:8080',
        )

    def test_good_sockets(self):
        sockets = [
            socket.socket(socket.AF_INET6, socket.SOCK_STREAM),
            socket.socket(socket.AF_INET, socket.SOCK_STREAM)]
        inst = self._makeOne(sockets=sockets)
        self.assertEqual(inst.sockets, sockets)
        sockets[0].close()
        sockets[1].close()

    def test_dont_mix_sockets_and_listen(self):
        sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM)]
        self.assertRaises(
            ValueError,
            self._makeOne,
            listen='127.0.0.1:8080',
            sockets=sockets)
        sockets[0].close()

    def test_dont_mix_sockets_and_host_port(self):
        sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM)]
        self.assertRaises(
            ValueError,
            self._makeOne,
            host='localhost',
            port='8080',
            sockets=sockets)
        sockets[0].close()

    def test_dont_mix_sockets_and_unix_socket(self):
        sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM)]
        self.assertRaises(
            ValueError,
            self._makeOne,
            unix_socket='./tmp/test',
            sockets=sockets)
        sockets[0].close()

    def test_dont_mix_unix_socket_and_host_port(self):
        self.assertRaises(
            ValueError,
            self._makeOne,
            unix_socket='./tmp/test',
            host='localhost',
            port='8080')

    def test_dont_mix_unix_socket_and_listen(self):
        self.assertRaises(
            ValueError,
            self._makeOne,
            unix_socket='./tmp/test',
            listen='127.0.0.1:8080')

    def test_dont_use_unsupported_socket_types(self):
        sockets = [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]
        self.assertRaises(
            ValueError,
            self._makeOne,
            sockets=sockets)
        sockets[0].close()

    def test_dont_mix_forwarded_with_x_forwarded(self):
        with self.assertRaises(ValueError) as cm:
            self._makeOne(trusted_proxy='localhost', trusted_proxy_headers={'forwarded', 'x-forwarded-for'})

        self.assertIn('The Forwarded proxy header', str(cm.exception))

    def test_unknown_trusted_proxy_header(self):
        with self.assertRaises(ValueError) as cm:
            self._makeOne(trusted_proxy='localhost', trusted_proxy_headers={'forwarded', 'x-forwarded-unknown'})

        self.assertIn(
            'unknown trusted_proxy_headers value (x-forwarded-unknown)',
            str(cm.exception)
        )

    def test_trusted_proxy_count_no_trusted_proxy(self):
        with self.assertRaises(ValueError) as cm:
            self._makeOne(trusted_proxy_count=1)

        self.assertIn(
            'trusted_proxy_count has no meaning',
            str(cm.exception)
        )

    def test_trusted_proxy_headers_no_trusted_proxy(self):
        with self.assertRaises(ValueError) as cm:
            self._makeOne(trusted_proxy_headers={'forwarded'})

        self.assertIn(
            'trusted_proxy_headers has no meaning',
            str(cm.exception)
        )

    def test_trusted_proxy_headers_string_list(self):
        inst = self._makeOne(trusted_proxy='localhost', trusted_proxy_headers='x-forwarded-for x-forwarded-by')
        self.assertEqual(inst.trusted_proxy_headers, {'x-forwarded-for', 'x-forwarded-by'})

    def test_trusted_proxy_headers_string_list_newlines(self):
        inst = self._makeOne(trusted_proxy='localhost', trusted_proxy_headers='x-forwarded-for\nx-forwarded-by\nx-forwarded-host')
        self.assertEqual(inst.trusted_proxy_headers, {'x-forwarded-for', 'x-forwarded-by', 'x-forwarded-host'})

    def test_no_trusted_proxy_headers_trusted_proxy(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.resetwarnings()
            warnings.simplefilter("always")
            self._makeOne(trusted_proxy='localhost')

            self.assertGreaterEqual(len(w), 1)
            self.assertTrue(issubclass(w[0].category, DeprecationWarning))
            self.assertIn("Implicitly trusting X-Forwarded-Proto", str(w[0]))

    def test_clear_untrusted_proxy_headers(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.resetwarnings()
            warnings.simplefilter("always")
            self._makeOne(trusted_proxy='localhost', trusted_proxy_headers={'x-forwarded-for'})

            self.assertGreaterEqual(len(w), 1)
            self.assertTrue(issubclass(w[0].category, DeprecationWarning))
            self.assertIn("clear_untrusted_proxy_headers will be set to True", str(w[0]))

    def test_deprecated_send_bytes(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.resetwarnings()
            warnings.simplefilter("always")
            self._makeOne(send_bytes=1)

            self.assertGreaterEqual(len(w), 1)
            self.assertTrue(issubclass(w[0].category, DeprecationWarning))
            self.assertIn("send_bytes", str(w[0]))

    def test_badvar(self):
        self.assertRaises(ValueError, self._makeOne, nope=True)

    def test_ipv4_disabled(self):
        self.assertRaises(ValueError, self._makeOne, ipv4=False, listen="127.0.0.1:8080")

    def test_ipv6_disabled(self):
        self.assertRaises(ValueError, self._makeOne, ipv6=False, listen="[::]:8080")

    def test_server_header_removable(self):
        inst = self._makeOne(ident=None)
        self.assertEqual(inst.ident, None)

        inst = self._makeOne(ident='')
        self.assertEqual(inst.ident, None)

        inst = self._makeOne(ident='specific_header')
        self.assertEqual(inst.ident, 'specific_header')


class TestCLI(unittest.TestCase):

    def parse(self, argv):
        from waitress.adjustments import Adjustments
        return Adjustments.parse_args(argv)

    def test_noargs(self):
        opts, args = self.parse([])
        self.assertDictEqual(opts, {'call': False, 'help': False})
        self.assertSequenceEqual(args, [])

    def test_help(self):
        opts, args = self.parse(['--help'])
        self.assertDictEqual(opts, {'call': False, 'help': True})
        self.assertSequenceEqual(args, [])

    def test_call(self):
        opts, args = self.parse(['--call'])
        self.assertDictEqual(opts, {'call': True, 'help': False})
        self.assertSequenceEqual(args, [])

    def test_both(self):
        opts, args = self.parse(['--call', '--help'])
        self.assertDictEqual(opts, {'call': True, 'help': True})
        self.assertSequenceEqual(args, [])

    def test_positive_boolean(self):
        opts, args = self.parse(['--expose-tracebacks'])
        self.assertDictContainsSubset({'expose_tracebacks': 'true'}, opts)
        self.assertSequenceEqual(args, [])

    def test_negative_boolean(self):
        opts, args = self.parse(['--no-expose-tracebacks'])
        self.assertDictContainsSubset({'expose_tracebacks': 'false'}, opts)
        self.assertSequenceEqual(args, [])

    def test_cast_params(self):
        opts, args = self.parse([
            '--host=localhost',
            '--port=80',
            '--unix-socket-perms=777'
        ])
        self.assertDictContainsSubset({
            'host': 'localhost',
            'port': '80',
            'unix_socket_perms': '777',
        }, opts)
        self.assertSequenceEqual(args, [])

    def test_listen_params(self):
        opts, args = self.parse([
            '--listen=test:80',
            ])

        self.assertDictContainsSubset({
            'listen': ' test:80'
            }, opts)
        self.assertSequenceEqual(args, [])

    def test_multiple_listen_params(self):
        opts, args = self.parse([
            '--listen=test:80',
            '--listen=test:8080',
            ])

        self.assertDictContainsSubset({
            'listen': ' test:80 test:8080'
            }, opts)
        self.assertSequenceEqual(args, [])

    def test_bad_param(self):
        import getopt
        self.assertRaises(getopt.GetoptError, self.parse, ['--no-host'])


if hasattr(socket, 'AF_UNIX'):
    class TestUnixSocket(unittest.TestCase):
        def _makeOne(self, **kw):
            from waitress.adjustments import Adjustments
            return Adjustments(**kw)

        def test_dont_mix_internet_and_unix_sockets(self):
            sockets = [
                socket.socket(socket.AF_INET, socket.SOCK_STREAM),
                socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)]
            self.assertRaises(
                ValueError,
                self._makeOne,
                sockets=sockets)
            sockets[0].close()
            sockets[1].close()