Repository navigation
Expand file tree
/
Copy pathtest_httpbin.py
More file actions
executable file
·1678 lines (1474 loc) · 73.7 KB
/
Copy pathtest_httpbin.py
File metadata and controls
executable file
·1678 lines (1474 loc) · 73.7 KB
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import base64
import unittest
import contextlib
import wsgiref.validate
import json
from urllib.parse import urlencode, urlparse
from werkzeug.datastructures import Headers
from werkzeug.http import parse_dict_header
from werkzeug.test import Client
from hashlib import md5, sha256, sha512
from io import BytesIO
import httpbin
from httpbin.helpers import parse_multi_value_header
# Set HTTPBIN_TEST_TARGET_URL to run the tests against any running httpbin,
# for example http://localhost:8080, instead of the in-process Flask app.
TARGET_URL = os.environ.get('HTTPBIN_TEST_TARGET_URL')
def local_only(reason):
"""Skip a test that needs the in-process app when TARGET_URL is set."""
return unittest.skipIf(TARGET_URL, reason)
class TargetResponse(object):
"""The parts of Werkzeug's test response that these tests read."""
def __init__(self, response):
self.status_code = response.status_code
# urllib3 keeps repeated headers apart; requests would join them.
self.headers = Headers(list(response.raw.headers.items()))
# The raw bytes, as the test client returns them: no gzip decoding.
self.data = response.raw.read(decode_content=False)
response.close()
def get_data(self):
return self.data
@property
def json(self):
return json.loads(self.data.decode('utf-8'))
@property
def content_length(self):
value = self.headers.get('Content-Length')
return None if value is None else int(value)
def close(self):
pass
class TargetClient(object):
"""Stands in for Flask's test client, sending each request over HTTP to
TARGET_URL. Like the test client, it keeps cookies, never follows
redirects and sends Host: localhost unless a test sets its own."""
def __init__(self, base_url):
import requests
self.base_url = base_url.rstrip('/')
self.session = requests.Session()
self.session.headers.clear()
def open(self, path='/', method='GET', headers=None, data=None,
content_type=None, environ_base=None):
# A real connection supplies REMOTE_ADDR; nothing else can be faked.
unsupported = set(environ_base or {}) - {'REMOTE_ADDR'}
if unsupported:
raise unittest.SkipTest(
'needs WSGI environ keys %s' % ', '.join(sorted(unsupported)))
request_headers = {'Host': 'localhost'}
request_headers.update(headers or {})
# The test client ignores a header with no name; requests refuses it.
request_headers.pop('', None)
if content_type:
request_headers['Content-Type'] = content_type
if isinstance(data, str):
data = data.encode('utf-8')
response = self.session.request(
method, self.base_url + path, headers=request_headers, data=data,
allow_redirects=False, stream=True)
return TargetResponse(response)
def get(self, path='/', **kwargs):
return self.open(path, method='GET', **kwargs)
def post(self, path='/', **kwargs):
return self.open(path, method='POST', **kwargs)
def put(self, path='/', **kwargs):
return self.open(path, method='PUT', **kwargs)
def patch(self, path='/', **kwargs):
return self.open(path, method='PATCH', **kwargs)
def delete(self, path='/', **kwargs):
return self.open(path, method='DELETE', **kwargs)
def head(self, path='/', **kwargs):
return self.open(path, method='HEAD', **kwargs)
def options(self, path='/', **kwargs):
return self.open(path, method='OPTIONS', **kwargs)
@contextlib.contextmanager
def _setenv(key, value):
"""Context manager to set an environment variable temporarily."""
old_value = os.environ.get(key, None)
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
yield
if old_value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def _string_to_base64(string):
"""Encodes string to utf-8 and then base64"""
utf8_encoded = string.encode('utf-8')
return base64.urlsafe_b64encode(utf8_encoded)
def _hash(data, algorithm):
"""Encode binary data according to specified algorithm, use MD5 by default"""
if algorithm == 'SHA-256':
return sha256(data).hexdigest()
elif algorithm == 'SHA-512':
return sha512(data).hexdigest()
else:
return md5(data).hexdigest()
def _make_digest_auth_header(username, password, method, uri, nonce,
realm=None, opaque=None, algorithm=None,
qop=None, cnonce=None, nc=None, body=None):
"""Compile a digest authentication header string.
Arguments:
- `nonce`: nonce string, received within "WWW-Authenticate" header
- `realm`: realm string, received within "WWW-Authenticate" header
- `opaque`: opaque string, received within "WWW-Authenticate" header
- `algorithm`: type of hashing algorithm, used by the client
- `qop`: type of quality-of-protection, used by the client
- `cnonce`: client nonce, required if qop is "auth" or "auth-int"
- `nc`: client nonce count, required if qop is "auth" or "auth-int"
- `body`: body of the outgoing request (bytes), used if qop is "auth-int"
"""
assert username
assert password
assert nonce
assert method
assert uri
assert algorithm in ('MD5', 'SHA-256', 'SHA-512', None)
a1 = ':'.join([username, realm or '', password])
ha1 = _hash(a1.encode('utf-8'), algorithm)
a2 = ':'.join([method, uri])
if qop == 'auth-int':
a2 = ':'.join([a2, _hash(body or b'', algorithm)])
ha2 = _hash(a2.encode('utf-8'), algorithm)
a3 = ':'.join([ha1, nonce])
if qop in ('auth', 'auth-int'):
assert cnonce
assert nc
a3 = ':'.join([a3, nc, cnonce, qop])
a3 = ':'.join([a3, ha2])
auth_response = _hash(a3.encode('utf-8'), algorithm)
auth_header = \
'Digest username="{0}", response="{1}", uri="{2}", nonce="{3}"'\
.format(username, auth_response, uri, nonce)
# 'realm' and 'opaque' should be returned unchanged, even if empty
if realm != None:
auth_header += ', realm="{0}"'.format(realm)
if opaque != None:
auth_header += ', opaque="{0}"'.format(opaque)
if algorithm:
auth_header += ', algorithm="{0}"'.format(algorithm)
if cnonce:
auth_header += ', cnonce="{0}"'.format(cnonce)
if nc:
auth_header += ', nc={0}'.format(nc)
if qop:
auth_header += ', qop={0}'.format(qop)
return auth_header
class HttpbinTestCase(unittest.TestCase):
"""Httpbin tests"""
def setUp(self):
if TARGET_URL:
self.app = TargetClient(TARGET_URL)
else:
httpbin.app.debug = True
self.app = httpbin.app.test_client()
def test_index(self):
response = self.app.get('/', headers={'User-Agent': 'test'})
self.assertEqual(response.status_code, 200)
def get_data(self, response):
if 'get_data' in dir(response):
return response.get_data()
else:
return response.data
def test_response_headers_simple(self):
supported_verbs = ['get', 'post']
for verb in supported_verbs:
method = getattr(self.app, verb)
response = method('/response-headers?animal=dog')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers.get_all('animal'), ['dog'])
assert json.loads(response.data.decode('utf-8'))['animal'] == 'dog'
def test_response_headers_refuses_renderable_content_types(self):
for query in (
'Content-Type=text/html',
'content-type=Text/HTML;%20charset=utf-8',
'Content-Type=image/svg%2Bxml',
'Content-Type=application/atom%2Bxml',
'Content-Type=text/javascript',
):
response = self.app.get('/response-headers?' + query)
self.assertEqual(response.status_code, 400, query)
self.assertEqual(
response.headers.get('Content-Type'), 'text/plain; charset=utf-8')
self.assertEqual(response.data, b'this Content-Type is not allowed\n')
def test_response_headers_allows_inert_content_types(self):
response = self.app.get('/response-headers?Content-Type=text/plain')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers.get_all('Content-Type'), ['text/plain'])
def test_response_headers_drops_reserved_headers(self):
reserved = (
'Content-Length', 'Transfer-Encoding', 'Connection', 'Keep-Alive',
'Proxy-Connection', 'TE', 'Trailer', 'Upgrade', 'Refresh',
'X-Content-Type-Options', 'Proxy-Authenticate',
)
query = '&'.join(name + '=1' for name in reserved)
response = self.app.get('/response-headers?animal=dog&' + query)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers.get_all('Content-Length'),
[str(len(response.data))])
for name in ('Refresh', 'Upgrade', 'Trailer', 'TE', 'Keep-Alive',
'Proxy-Connection', 'Proxy-Authenticate'):
self.assertNotIn(name, response.headers, name)
self.assertNotIn('1', response.headers.get_all('X-Content-Type-Options'))
echoed = json.loads(response.data.decode('utf-8'))
self.assertEqual(echoed['animal'], 'dog')
for name in reserved:
if name != 'Content-Length':
self.assertNotIn(name, echoed, name)
def test_response_headers_refuses_content_type_lists(self):
# A comma-separated list is not a single valid media type.
for value in ('text/plain,text/html', 'text/plain, text/html',
'text/html,text/plain', 'application/json,text/html'):
response = self.app.get(
'/response-headers?' + urlencode({'Content-Type': value, 'x': '<b>'}))
self.assertEqual(response.status_code, 400, value)
self.assertEqual(
response.data, b'the Content-Type is not a valid media type\n')
self.assertEqual(response.headers.get_all('Content-Type'),
['text/plain; charset=utf-8'])
def test_response_headers_content_type_validation_cases(self):
for query, message in (
('Content-Type=text/plain,text/html&x=%3Cb%3E1%3C/b%3E',
b'the Content-Type is not a valid media type\n'),
('Content-Type=text/plain&Content-Type=text/html',
b'only one Content-Type is allowed\n'),
('content-type=TEXT/HTML', b'this Content-Type is not allowed\n'),
('Content-Type=text/plain;x=,text/html',
b'the Content-Type is not a valid media type\n'),
):
response = self.app.get('/response-headers?' + query)
self.assertEqual(response.status_code, 400, query)
self.assertEqual(response.headers.get_all('Content-Type'),
['text/plain; charset=utf-8'], query)
self.assertEqual(response.data, message, query)
def test_response_headers_refuses_repeated_content_types(self):
for pairs in (
[('Content-Type', 'text/plain'), ('Content-Type', 'text/plain')],
[('Content-Type', 'text/plain'), ('content-type', 'text/html')],
[('content-type', 'text/plain'), ('CONTENT-TYPE', 'text/csv')],
):
response = self.app.get('/response-headers?' + urlencode(pairs))
self.assertEqual(response.status_code, 400, pairs)
self.assertEqual(response.data, b'only one Content-Type is allowed\n')
def test_response_headers_content_type_replaces_json(self):
for key in ('Content-Type', 'content-type', 'CONTENT-TYPE'):
response = self.app.get(
'/response-headers?' + urlencode({key: 'text/csv; header=present'}))
self.assertEqual(response.status_code, 200, key)
self.assertEqual(response.headers.get_all('Content-Type'),
['text/csv; header=present'])
echoed = json.loads(response.data.decode('utf-8'))
self.assertEqual(echoed['Content-Type'], 'text/csv; header=present')
def test_response_headers_refuses_invalid_content_types(self):
for value in ('textplain', 'text/', '/plain', 'a/b/c', 'text /plain',
'text/plain extra', 'text/plain; =x', 'text/plain; a=',
'text/plain; a=1; A=2', 'text/plain; ;',
'text/plain\x01', u't\xebxt/plain'):
response = self.app.get(
'/response-headers?' + urlencode({'Content-Type': value}))
self.assertEqual(response.status_code, 400, value)
self.assertEqual(
response.data, b'the Content-Type is not a valid media type\n')
def test_response_headers_escapes_echo_for_other_types(self):
response = self.app.get(
'/response-headers?Content-Type=text/csv&x=%3Cb%3E%22%27%26')
self.assertEqual(response.status_code, 200)
echoed = json.loads(response.data.decode('utf-8'))
self.assertEqual(echoed['x'], '<b>"'&')
self.assertEqual(response.headers.get('x'), '<b>"\'&')
def test_response_headers_does_not_escape_inert_types(self):
for content_type in ('text/plain', 'application/json'):
response = self.app.get(
'/response-headers?Content-Type=%s&x=%%3Cb%%3E' % content_type)
echoed = json.loads(response.data.decode('utf-8'))
self.assertEqual(echoed['x'], '<b>', content_type)
response = self.app.get('/response-headers?x=%3Cb%3E')
self.assertEqual(json.loads(response.data.decode('utf-8'))['x'], '<b>')
def test_response_headers_set_cookie_domain(self):
allowed = (
('Set-Cookie', ['x=1; Path=/; HttpOnly']),
('Set-Cookie', ['x=1; Domain=localhost']),
('Set-Cookie', ['x=1; Domain=.localhost']),
('Set-Cookie', ['x=1; DOMAIN=LOCALHOST']),
('set-cookie', ['x=1; Domain=localhost']),
('Set-Cookie', ['x="q"', 'y=1; Path=/x']),
)
refused = (
('Set-Cookie', ['x=1; Domain=.example.com']),
('set-cookie', ['x=1; Domain=.example.com']),
('SET-COOKIE', ['x=1; Domain=.example.com']),
('Set-Cookie', ['x=1; dOmAiN=.example.com']),
('Set-Cookie', ['x=1; Domain = .example.com']),
('Set-Cookie', [u'x=1; Doma\u0130n=.example.com']),
('Set-Cookie', ['x=1; Domain=sub.localhost']),
('Set-Cookie', ['x=1; Domain=..localhost']),
('Set-Cookie', ['x=1; Domain=localhost:8080']),
('Set-Cookie', ['x=1; Domain=']),
('Set-Cookie', ['x=1; Domain']),
('Set-Cookie', ['x=1; Domain=localhost; Domain=.example.com']),
('Set-Cookie', ['x=1; Domain=.example.com; Domain=localhost']),
('Set-Cookie', ['a=1', 'b=2; Domain=localhost', 'c=3; Domain=.example.com']),
('Set-Cookie', ['no-equals-sign']),
('Set-Cookie', ['; Domain=localhost']),
('Set-Cookie', ['x y=1']),
('Set-Cookie', ['x=a\\b']),
)
for method in ('GET', 'POST'):
for key, values in allowed + refused:
query = urlencode([(key, v) for v in values] + [('Foo', 'bar')])
response = self.app.open(
'/response-headers?' + query, method=method,
headers={'X-Forwarded-Host': 'other.example'})
if (key, values) in allowed:
self.assertEqual(response.status_code, 200, values)
self.assertEqual(response.headers.get_all(key), values)
else:
self.assertEqual(response.status_code, 400, values)
self.assertEqual(response.headers.get_all('Set-Cookie'), [])
self.assertIsNone(response.headers.get('Foo'))
error = json.loads(response.data.decode('utf-8'))
self.assertEqual(error['status_code'], 400)
self.assertEqual(error['error'], 'Bad Request')
def test_response_headers_set_cookie_domain_ignores_port(self):
response = self.app.get(
'/response-headers?Set-Cookie=x%3D1%3B%20Domain%3Dlocalhost',
headers={'Host': 'localhost:8080'})
self.assertEqual(response.status_code, 200)
def test_response_headers_multi(self):
supported_verbs = ['get', 'post']
for verb in supported_verbs:
method = getattr(self.app, verb)
response = method('/response-headers?animal=dog&animal=cat')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers.get_all('animal'), ['dog', 'cat'])
assert json.loads(response.data.decode('utf-8'))['animal'] == ['dog', 'cat']
def test_get(self):
response = self.app.get('/get', headers={'User-Agent': 'test'})
self.assertEqual(response.status_code, 200)
data = json.loads(response.data.decode('utf-8'))
self.assertEqual(data['args'], {})
self.assertEqual(data['headers']['Host'], 'localhost')
self.assertEqual(data['headers']['User-Agent'], 'test')
# self.assertEqual(data['origin'], None)
self.assertEqual(data['url'], 'http://localhost/get')
self.assertTrue(response.data.endswith(b'\n'))
def test_anything(self):
response = self.app.get('/anything')
self.assertEqual(response.status_code, 200)
response = self.app.get('/anything/foo/bar')
self.assertEqual(response.status_code, 200)
data = json.loads(response.data.decode('utf-8'))
self.assertEqual(data['args'], {})
self.assertEqual(data['headers']['Host'], 'localhost')
self.assertEqual(data['url'], 'http://localhost/anything/foo/bar')
self.assertEqual(data['method'], 'GET')
self.assertTrue(response.data.endswith(b'\n'))
def test_base64(self):
greeting = u'Здравствуй, мир!'
b64_encoded = _string_to_base64(greeting)
response = self.app.get('/base64/' + b64_encoded.decode('ascii'))
content = response.data.decode('utf-8')
self.assertEqual(greeting, content)
self.assertEqual(
response.headers.get('Content-Type'), 'text/plain; charset=utf-8')
def test_base64_text_decodes_as_declared(self):
# A client decodes with the declared charset, as requests does
greeting = u'\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439'
response = self.app.get(
'/base64/' + _string_to_base64(greeting).decode('ascii'))
charset = response.headers.get('Content-Type').partition('charset=')[2]
self.assertEqual(response.data.decode(charset), greeting)
def test_base64_markup_is_plain_text(self):
markup = _string_to_base64(u'<b>bold</b>')
response = self.app.get('/base64/' + markup.decode('ascii'))
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.headers.get('Content-Type'), 'text/plain; charset=utf-8')
self.assertEqual(
response.data, b'<b>bold</b>')
def test_post_binary(self):
response = self.app.post('/post',
data=b'\x01\x02\x03\x81\x82\x83',
content_type='application/octet-stream')
self.assertEqual(response.status_code, 200)
def test_post_body_text(self):
with open('httpbin/core.py') as f:
response = self.app.post('/post', data={"file": f.read()})
self.assertEqual(response.status_code, 200)
def test_post_body_binary(self):
response = self.app.post(
'/post',
data={"file": b'\x01\x02\x03\x81\x82\x83'})
self.assertEqual(response.status_code, 200)
def test_post_body_unicode(self):
response = self.app.post('/post', data=u'оживлённым'.encode('utf-8'))
self.assertEqual(json.loads(response.data.decode('utf-8'))['data'], u'оживлённым')
def test_dump_request(self):
response = self.app.get('/dump/request?a=1&b=%20x',
headers={'x-custom-thing': 'v1'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers.get('Content-Type'),
'text/plain; charset=utf-8')
self.assertTrue(response.data.startswith(
b'GET /dump/request?a=1&b=%20x HTTP/1.1\r\nHost: localhost\r\n'),
response.data)
self.assertIn(b'\r\nX-Custom-Thing: v1\r\n', response.data)
self.assertTrue(response.data.endswith(b'\r\n\r\n'))
def test_dump_request_takes_any_method(self):
for method in ('ARBITRARY-METHOD', 'PROPFIND', 'QUERY'):
response = self.app.open('/dump/request', method=method)
self.assertEqual(response.status_code, 200, method)
self.assertTrue(response.data.startswith(
method.encode() + b' /dump/request HTTP/1.1\r\n'), method)
def test_dump_request_shows_each_part_type(self):
data = (
'--bound\r\n'
'Content-Disposition: form-data; name="f"; filename="a.txt"\r\n'
'Content-Type: text/x-foo\r\n\r\nhello\r\n'
'--bound--\r\n'
)
response = self.app.post(
'/dump/request', data=data,
content_type='multipart/form-data; boundary=bound')
self.assertIn(b'\r\nContent-Type: multipart/form-data; boundary=bound\r\n',
response.data)
self.assertTrue(response.data.endswith(data.encode()))
self.assertIn(b'Content-Type: text/x-foo\r\n\r\nhello', response.data)
def test_query_method_echoes_like_post(self):
for path in ('/anything', '/anything/x', '/delay/0'):
response = self.app.open(
path + '?a=1', method='QUERY', data='{"k": "v"}',
content_type='application/json')
self.assertEqual(response.status_code, 200, path)
echoed = json.loads(response.data.decode('utf-8'))
self.assertEqual(echoed['data'], '{"k": "v"}', path)
self.assertEqual(echoed['args'], {'a': '1'}, path)
echoed = json.loads(self.app.open('/anything', method='QUERY').data.decode('utf-8'))
self.assertEqual(echoed['method'], 'QUERY')
response = self.app.open('/get', method='QUERY')
self.assertEqual(response.status_code, 405)
def test_post_repeated_file_field_echoes_every_file(self):
data = (
'--bound\r\n'
'Content-Disposition: form-data; name="f"; filename="a.txt"\r\n'
'Content-Type: text/plain\r\n\r\nfirst\r\n'
'--bound\r\n'
'Content-Disposition: form-data; name="f"; filename="b.bin"\r\n'
'Content-Type: application/x-thing\r\n\r\n\xff\xfe\r\n'
'--bound--\r\n'
).encode('latin-1')
response = self.app.post(
'/post', data=data, content_type='multipart/form-data; boundary=bound')
files = json.loads(response.data.decode('utf-8'))['files']
self.assertEqual(files['f'], ['first', 'data:application/x-thing;base64,//4='])
def test_post_file_with_missing_content_type_header(self):
# I built up the form data manually here because I couldn't find a way
# to convince the werkzeug test client to send files without the
# content-type of the file set.
data = '--bound\r\nContent-Disposition: form-data; name="media"; '
data += 'filename="test.bin"\r\n\r\n\xa5\xc6\n--bound--\r\n'
response = self.app.post(
'/post',
content_type='multipart/form-data; boundary=bound',
data=data,
)
self.assertEqual(response.status_code, 200)
"""
This is currently a sort of negative-test.
We validate that when running Flask-only server that
Transfer-Encoding: chunked requests are unsupported and
we return 501 Not Implemented
"""
@local_only('checks that the Flask development server refuses chunked bodies')
def test_post_chunked(self):
data = '{"animal":"dog"}'
response = self.app.post(
'/post',
content_type='application/json',
headers=[('Transfer-Encoding', 'chunked')],
data=data,
)
self.assertEqual(response.status_code, 501)
#self.assertEqual(response.status_code, 200)
#self.assertEqual(json.loads(response.data.decode('utf-8'))['data'], '{"animal":"dog"}')
#self.assertEqual(json.loads(response.data.decode('utf-8'))['json'], {"animal": "dog"})
def test_nosniff_on_every_response(self):
for path in ('/get', '/html', '/base64/SFRUUEJJTiBpcyBhd2Vzb21l',
'/status/404', '/nope'):
response = self.app.get(path)
self.assertEqual(
response.headers.get_all('X-Content-Type-Options'), ['nosniff'],
path)
def test_cookies_are_secure_behind_a_tls_proxy(self):
https_requests = (
{'X-Forwarded-Proto': 'https'},
{'X-Forwarded-Protocol': 'https'},
{'X-Forwarded-Ssl': 'on'},
)
for headers in https_requests:
for path in ('/cookies/set?k=v', '/cookies/set/k/v',
'/cookies/delete?k', '/digest-auth/auth/user/passwd'):
response = self.app.get(path, headers=headers)
cookies = response.headers.get_all('Set-Cookie')
self.assertTrue(cookies, path)
for cookie in cookies:
self.assertIn('; Secure', cookie, (path, headers))
for path in ('/cookies/set?k=v', '/cookies/delete?k',
'/digest-auth/auth/user/passwd'):
response = self.app.get(path, headers={'X-Forwarded-Proto': 'http'})
for cookie in response.headers.get_all('Set-Cookie'):
self.assertNotIn('Secure', cookie, path)
def test_set_cors_headers_after_request(self):
response = self.app.get('/get')
self.assertEqual(
response.headers.get('Access-Control-Allow-Origin'), '*'
)
def test_set_cors_credentials_headers_after_auth_request(self):
response = self.app.get('/basic-auth/foo/bar')
self.assertEqual(
response.headers.get('Access-Control-Allow-Credentials'), 'true'
)
def test_set_cors_headers_after_request_with_request_origin(self):
response = self.app.get('/get', headers={'Origin': 'origin'})
self.assertEqual(
response.headers.get('Access-Control-Allow-Origin'), 'origin'
)
def test_set_cors_headers_with_options_verb(self):
response = self.app.open('/get', method='OPTIONS')
self.assertEqual(
response.headers.get('Access-Control-Allow-Origin'), '*'
)
self.assertEqual(
response.headers.get('Access-Control-Allow-Credentials'), 'true'
)
self.assertEqual(
response.headers.get('Access-Control-Allow-Methods'),
'GET, POST, PUT, DELETE, PATCH, OPTIONS'
)
self.assertEqual(
response.headers.get('Access-Control-Max-Age'), '3600'
)
# FIXME should we add any extra headers?
self.assertNotIn(
'Access-Control-Allow-Headers', response.headers
)
def test_set_cors_allow_headers(self):
response = self.app.open('/get', method='OPTIONS', headers={'Access-Control-Request-Headers': 'X-Test-Header'})
self.assertEqual(
response.headers.get('Access-Control-Allow-Headers'), 'X-Test-Header'
)
def test_headers(self):
headers = {
"Accept": "*/*",
"Host": "localhost:1234",
"User-Agent": "curl/7.54.0",
"Via": "bar"
}
response = self.app.get('/headers', headers=headers)
self.assertEqual(response.status_code, 200)
self.assertTrue({'Accept', 'Host', 'User-Agent'}.issubset(set(response.json['headers'].keys())))
self.assertNotIn('Via', response.json)
def test_show_env_is_documented(self):
home = self.app.get('/').data.decode('utf-8')
self.assertIn('<h2>Proxy headers</h2>', home)
self.assertIn('/headers?show_env=1', home)
spec = json.loads(self.app.get('/spec.json').data.decode('utf-8'))
for path in ('/get', '/headers'):
names = [p['name'] for p in spec['paths'][path]['get'].get('parameters', [])]
self.assertIn('show_env', names, path)
FIXED_CONTENT_PATHS = (
'/json', '/xml', '/html', '/robots.txt', '/deny', '/encoding/utf8',
'/image', '/image/png', '/image/jpeg', '/image/webp', '/image/svg',
)
def test_fixed_content_takes_a_status(self):
for path in self.FIXED_CONTENT_PATHS:
normal = self.app.get(path)
self.assertEqual(normal.status_code, 200, path)
for status in (200, 201, 404, 500, 503, 599):
response = self.app.get('%s?status=%d' % (path, status))
self.assertEqual(response.status_code, status, path)
self.assertEqual(response.data, normal.data, path)
self.assertEqual(response.headers['Content-Type'],
normal.headers['Content-Type'], path)
head = self.app.head(path + '?status=500')
self.assertEqual(head.status_code, 500, path)
self.assertEqual(head.data, b'', path)
def test_fixed_content_refuses_other_statuses(self):
for path in self.FIXED_CONTENT_PATHS:
normal = self.app.get(path).data
refusal = None
for value in ('100', '101', '199', '204', '205', '300', '301',
'302', '304', '307', '399', '0', '600', '-200',
'+500', '0500', '500%20', '5e2', 'abc', '',
'%ZZ', '500%', '99999999999999999999'):
response = self.app.get('%s?status=%s' % (path, value))
self.assertEqual(response.status_code, 400, (path, value))
self.assertEqual(response.headers['Content-Type'],
'text/plain; charset=utf-8')
# one fixed answer for every refusal: the value is not repeated
refusal = refusal or response.data
self.assertEqual(response.data, refusal, (path, value))
self.assertNotEqual(response.data, normal)
def test_fixed_content_status_leaves_a_406_alone(self):
response = self.app.get('/image?status=500',
headers={'Accept': 'text/plain'})
self.assertEqual(response.status_code, 406)
def test_response_headers_takes_a_status(self):
response = self.app.get('/response-headers?status=503&Retry-After=5')
self.assertEqual(response.status_code, 503)
self.assertEqual(response.headers['Retry-After'], '5')
self.assertNotIn('Status', response.headers)
self.assertNotIn('status', json.loads(response.data.decode('utf-8')))
self.assertEqual(
self.app.get('/response-headers?status=401&WWW-Authenticate=x'
).status_code, 401)
# another spelling is an ordinary header
other = self.app.get('/response-headers?Status=503')
self.assertEqual(other.status_code, 200)
self.assertEqual(other.headers['Status'], '503')
# no status: nothing changes
self.assertEqual(self.app.get('/response-headers?a=b').status_code, 200)
def test_response_headers_refuses_a_bad_status(self):
for query in ('status=204', 'status=205', 'status=301', 'status=100',
'status=abc', 'status=', 'status=%ZZ', 'status=0500',
'status=500&status=503', 'status=600'):
response = self.app.get('/response-headers?' + query)
self.assertEqual(response.status_code, 400, query)
self.assertEqual(response.headers['Content-Type'],
'text/plain; charset=utf-8')
self.assertNotIn(b'500', response.data, query)
self.assertNotIn(b'abc', response.data, query)
# never a redirect: Location and Refresh are refused with a status
for query in ('status=302&Location=/x', 'status=200&location=/x',
'status=200&Refresh=0;url=/x', 'status=200&REFRESH=1'):
response = self.app.get('/response-headers?' + query)
self.assertEqual(response.status_code, 400, query)
self.assertNotIn('Location', response.headers)
# without a status Location is still allowed
self.assertEqual(
self.app.get('/response-headers?Location=/x').headers['Location'],
'/x')
# the Content-Type rules still apply
self.assertEqual(
self.app.get('/response-headers?status=503&Content-Type=text/html'
).status_code, 400)
def test_headers_show_env(self):
headers = {
"Accept": "*/*",
"Host": "localhost:1234",
"User-Agent": "curl/7.54.0",
"Via": "bar"
}
response = self.app.get('/headers?show_env=true', headers=headers)
self.assertEqual(response.status_code, 200)
self.assertTrue({'Accept', 'Host', 'User-Agent', 'Via'}.issubset(set(response.json['headers'].keys())))
def test_user_agent(self):
response = self.app.get(
'/user-agent', headers={'User-Agent': 'test'}
)
self.assertIn('test', response.data.decode('utf-8'))
self.assertEqual(response.status_code, 200)
def test_gzip(self):
response = self.app.get('/gzip')
self.assertEqual(response.status_code, 200)
def test_brotli(self):
response = self.app.get('/brotli')
self.assertEqual(response.status_code, 200)
def test_zstd(self):
from httpbin import filters
if filters._zstd is None:
self.skipTest('no zstd support in this Python')
response = self.app.get('/zstd', headers={'User-Agent': 'test'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers['Content-Encoding'], 'zstd')
self.assertEqual(response.headers['Content-Length'], str(len(response.data)))
body = json.loads(filters._zstd.decompress(response.data))
self.assertTrue(body['zstd'])
self.assertEqual(body['headers']['User-Agent'], 'test')
self.assertEqual(body['method'], 'GET')
@local_only('simulates a Python without zstd in the in-process app')
def test_zstd_without_support_says_so(self):
from httpbin import filters
saved, filters._zstd = filters._zstd, None
try:
response = self.app.get('/zstd')
finally:
filters._zstd = saved
self.assertEqual(response.status_code, 501)
def test_bearer_auth(self):
token = 'abcd1234'
response = self.app.get(
'/bearer',
headers={'Authorization': 'Bearer ' + token}
)
self.assertEqual(response.status_code, 200)
assert json.loads(response.data.decode('utf-8'))['token'] == token
def test_bearer_auth_with_wrong_authorization_type(self):
"""Sending an non-Bearer Authorization header to /bearer should return a 401"""
auth_headers = (
('Authorization', 'Basic 1234abcd'),
('Authorization', ''),
('', '')
)
for header in auth_headers:
response = self.app.get(
'/bearer',
headers={header[0]: header[1]}
)
self.assertEqual(response.status_code, 401)
def test_bearer_auth_with_missing_token(self):
"""Sending an 'Authorization: Bearer' header with no token to /bearer should return a 401"""
response = self.app.get(
'/bearer',
headers={'Authorization': 'Bearer'}
)
self.assertEqual(response.status_code, 401)
def test_digest_auth_with_wrong_password(self):
auth_header = 'Digest username="user",realm="wrong",nonce="wrong",uri="/digest-auth/user/passwd/MD5",response="wrong",opaque="wrong"'
response = self.app.get(
'/digest-auth/auth/user/passwd/MD5',
environ_base={
# httpbin's digest auth implementation uses the remote addr to
# build the nonce
'REMOTE_ADDR': '127.0.0.1',
},
headers={
'Authorization': auth_header,
}
)
self.assertTrue('Digest' in response.headers.get('WWW-Authenticate'))
self.assertEqual(response.status_code, 401)
def test_digest_auth(self):
"""Test different combinations of digest auth parameters"""
username = 'user'
password = 'passwd'
for qop in None, 'auth', 'auth-int',:
for algorithm in None, 'MD5', 'SHA-256', 'SHA-512':
for body in None, b'', b'request payload':
for stale_after in (None, 1, 4) if algorithm else (None,) :
self._test_digest_auth(username, password, qop, algorithm, body, stale_after)
def test_digest_auth_with_wrong_authorization_type(self):
"""Sending an non-digest Authorization header to /digest-auth should return a 401"""
auth_headers = (
('Authorization', 'Basic 1234abcd'),
('Authorization', ''),
('', '')
)
for header in auth_headers:
response = self.app.get(
'/digest-auth/auth/myname/mysecret',
headers={header[0]: header[1]}
)
self.assertEqual(response.status_code, 401)
def test_digest_auth_with_incomplete_credentials(self):
"""A Digest header missing required parameters should return a 401"""
response = self.app.get(
'/digest-auth/auth/myname/mysecret',
headers={'Authorization': 'Digest username="myname"'}
)
self.assertEqual(response.status_code, 401)
def test_digest_auth_challenge_header(self):
response = self.app.get('/digest-auth/auth/myname/mysecret/SHA-256')
header = response.headers.get('WWW-Authenticate')
self.assertRegex(
header,
r'^Digest realm="me@kennethreitz.com", nonce="[0-9a-f]{64}", '
r'qop="auth", opaque="[0-9a-f]{64}", algorithm=SHA-256, stale=FALSE$'
)
def _test_digest_auth(self, username, password, qop, algorithm=None, body=None, stale_after=None):
uri = self._digest_auth_create_uri(username, password, qop, algorithm, stale_after)
unauthorized_response = self._test_digest_auth_first_challenge(uri)
header = unauthorized_response.headers.get('WWW-Authenticate')
authorized_response, nonce = self._test_digest_response_for_auth_request(header, username, password, qop, uri, body)
self.assertEqual(authorized_response.status_code, 200)
if None == stale_after :
return
# test stale after scenerio
self._digest_auth_stale_after_check(header, username, password, uri, body, qop, stale_after)
def _test_digest_auth_first_challenge(self, uri):
unauthorized_response = self.app.get(
uri,
environ_base={
# digest auth uses the remote addr to build the nonce
'REMOTE_ADDR': '127.0.0.1',
}
)
# make sure it returns a 401
self.assertEqual(unauthorized_response.status_code, 401)
return unauthorized_response
def _digest_auth_create_uri(self, username, password, qop, algorithm, stale_after):
uri = '/digest-auth/{0}/{1}/{2}'.format(qop or 'wrong-qop', username, password)
if algorithm:
uri += '/' + algorithm
if stale_after:
uri += '/{0}'.format(stale_after)
return uri
def _digest_auth_stale_after_check(self, header, username, password, uri, body, qop, stale_after):
for nc in range(2, stale_after + 1):
authorized_response, nonce = self._test_digest_response_for_auth_request(header, username, password, qop, uri, \
body, nc)
self.assertEqual(authorized_response.status_code, 200)
stale_response, nonce = self._test_digest_response_for_auth_request(header, username, password, qop, uri, \
body, stale_after + 1)
self.assertEqual(stale_response.status_code, 401)
header = stale_response.headers.get('WWW-Authenticate')
self.assertIn('stale=TRUE', header)
def _test_digest_response_for_auth_request(self, header, username, password, qop, uri, body, nc=1, nonce=None):
auth_type, auth_info = header.split(None, 1)
self.assertEqual(auth_type, 'Digest')
d = parse_dict_header(auth_info)
nonce = nonce or d['nonce']
realm = d['realm']
opaque = d['opaque']
if qop :
self.assertIn(qop, [x.strip() for x in d['qop'].split(',')], 'Challenge should contains expected qop')
algorithm = d['algorithm']
cnonce, nc = (_hash(os.urandom(10), "MD5"), '{:08}'.format(nc)) if qop in ('auth', 'auth-int') else (None, None)
auth_header = _make_digest_auth_header(
username, password, 'GET', uri, nonce, realm, opaque, algorithm, qop, cnonce, nc, body)
# make second request
return self.app.get(
uri,
environ_base={
# httpbin's digest auth implementation uses the remote addr to
# build the nonce
'REMOTE_ADDR': '127.0.0.1',
},
headers={
'Authorization': auth_header,
},
data=body
), nonce
def test_digest_auth_wrong_user(self):
"""The right password under another username must not authenticate."""
for qop in None, 'auth', 'auth-int':
uri = self._digest_auth_create_uri('user', 'passwd', qop, 'MD5', None)
header = self._test_digest_auth_first_challenge(uri).headers.get(
'WWW-Authenticate')
response, _ = self._test_digest_response_for_auth_request(
header, 'someone-else', 'passwd', qop, uri, None)
self.assertEqual(response.status_code, 401, qop)
def test_auth_routes_take_every_method(self):
"""Basic, hidden basic, bearer and digest auth answer GET, POST, PUT,
DELETE, PATCH and TRACE alike; other methods are refused."""
basic = 'Basic ' + base64.b64encode(b'user:passwd').decode()
wrong = 'Basic ' + base64.b64encode(b'user:wrong').decode()
for method in ('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'TRACE'):
def call(path, auth=None, body=None):
headers = {'Authorization': auth} if auth else {}
return self.app.open(
path, method=method, headers=headers, data=body,
environ_base={'REMOTE_ADDR': '127.0.0.1'})
self.assertEqual(call('/basic-auth/user/passwd', basic).status_code, 200, method)
self.assertEqual(call('/basic-auth/user/passwd', wrong).status_code, 401, method)
self.assertEqual(call('/hidden-basic-auth/user/passwd', basic).status_code, 200, method)
self.assertEqual(call('/hidden-basic-auth/user/passwd', wrong).status_code, 404, method)
self.assertEqual(call('/bearer', 'Bearer token').status_code, 200, method)
self.assertEqual(call('/bearer').status_code, 401, method)
for qop, body in (('auth', None), ('auth-int', b'payload'), ('none', None)):
uri = '/digest-auth/%s/user/passwd' % qop
challenge = call(uri)
self.assertEqual(challenge.status_code, 401, (method, qop))
header = challenge.headers['WWW-Authenticate']
d = parse_dict_header(header.split(None, 1)[1])
real_qop = None if qop == 'none' else qop