httpserver_test.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. from __future__ import absolute_import, division, print_function
  2. from tornado import gen, netutil
  3. from tornado.concurrent import Future
  4. from tornado.escape import json_decode, json_encode, utf8, _unicode, recursive_unicode, native_str
  5. from tornado.http1connection import HTTP1Connection
  6. from tornado.httpclient import HTTPError
  7. from tornado.httpserver import HTTPServer
  8. from tornado.httputil import HTTPHeaders, HTTPMessageDelegate, HTTPServerConnectionDelegate, ResponseStartLine # noqa: E501
  9. from tornado.iostream import IOStream
  10. from tornado.locks import Event
  11. from tornado.log import gen_log
  12. from tornado.netutil import ssl_options_to_context
  13. from tornado.simple_httpclient import SimpleAsyncHTTPClient
  14. from tornado.testing import AsyncHTTPTestCase, AsyncHTTPSTestCase, AsyncTestCase, ExpectLog, gen_test # noqa: E501
  15. from tornado.test.util import unittest, skipOnTravis
  16. from tornado.web import Application, RequestHandler, stream_request_body
  17. from contextlib import closing
  18. import datetime
  19. import gzip
  20. import os
  21. import shutil
  22. import socket
  23. import ssl
  24. import sys
  25. import tempfile
  26. from io import BytesIO
  27. def read_stream_body(stream, callback):
  28. """Reads an HTTP response from `stream` and runs callback with its
  29. start_line, headers and body."""
  30. chunks = []
  31. class Delegate(HTTPMessageDelegate):
  32. def headers_received(self, start_line, headers):
  33. self.headers = headers
  34. self.start_line = start_line
  35. def data_received(self, chunk):
  36. chunks.append(chunk)
  37. def finish(self):
  38. conn.detach()
  39. callback((self.start_line, self.headers, b''.join(chunks)))
  40. conn = HTTP1Connection(stream, True)
  41. conn.read_response(Delegate())
  42. class HandlerBaseTestCase(AsyncHTTPTestCase):
  43. def get_app(self):
  44. return Application([('/', self.__class__.Handler)])
  45. def fetch_json(self, *args, **kwargs):
  46. response = self.fetch(*args, **kwargs)
  47. response.rethrow()
  48. return json_decode(response.body)
  49. class HelloWorldRequestHandler(RequestHandler):
  50. def initialize(self, protocol="http"):
  51. self.expected_protocol = protocol
  52. def get(self):
  53. if self.request.protocol != self.expected_protocol:
  54. raise Exception("unexpected protocol")
  55. self.finish("Hello world")
  56. def post(self):
  57. self.finish("Got %d bytes in POST" % len(self.request.body))
  58. # In pre-1.0 versions of openssl, SSLv23 clients always send SSLv2
  59. # ClientHello messages, which are rejected by SSLv3 and TLSv1
  60. # servers. Note that while the OPENSSL_VERSION_INFO was formally
  61. # introduced in python3.2, it was present but undocumented in
  62. # python 2.7
  63. skipIfOldSSL = unittest.skipIf(
  64. getattr(ssl, 'OPENSSL_VERSION_INFO', (0, 0)) < (1, 0),
  65. "old version of ssl module and/or openssl")
  66. class BaseSSLTest(AsyncHTTPSTestCase):
  67. def get_app(self):
  68. return Application([('/', HelloWorldRequestHandler,
  69. dict(protocol="https"))])
  70. class SSLTestMixin(object):
  71. def get_ssl_options(self):
  72. return dict(ssl_version=self.get_ssl_version(), # type: ignore
  73. **AsyncHTTPSTestCase.get_ssl_options())
  74. def get_ssl_version(self):
  75. raise NotImplementedError()
  76. def test_ssl(self):
  77. response = self.fetch('/')
  78. self.assertEqual(response.body, b"Hello world")
  79. def test_large_post(self):
  80. response = self.fetch('/',
  81. method='POST',
  82. body='A' * 5000)
  83. self.assertEqual(response.body, b"Got 5000 bytes in POST")
  84. def test_non_ssl_request(self):
  85. # Make sure the server closes the connection when it gets a non-ssl
  86. # connection, rather than waiting for a timeout or otherwise
  87. # misbehaving.
  88. with ExpectLog(gen_log, '(SSL Error|uncaught exception)'):
  89. with ExpectLog(gen_log, 'Uncaught exception', required=False):
  90. with self.assertRaises((IOError, HTTPError)):
  91. self.fetch(
  92. self.get_url("/").replace('https:', 'http:'),
  93. request_timeout=3600,
  94. connect_timeout=3600,
  95. raise_error=True)
  96. def test_error_logging(self):
  97. # No stack traces are logged for SSL errors.
  98. with ExpectLog(gen_log, 'SSL Error') as expect_log:
  99. with self.assertRaises((IOError, HTTPError)):
  100. self.fetch(self.get_url("/").replace("https:", "http:"),
  101. raise_error=True)
  102. self.assertFalse(expect_log.logged_stack)
  103. # Python's SSL implementation differs significantly between versions.
  104. # For example, SSLv3 and TLSv1 throw an exception if you try to read
  105. # from the socket before the handshake is complete, but the default
  106. # of SSLv23 allows it.
  107. class SSLv23Test(BaseSSLTest, SSLTestMixin):
  108. def get_ssl_version(self):
  109. return ssl.PROTOCOL_SSLv23
  110. @skipIfOldSSL
  111. class SSLv3Test(BaseSSLTest, SSLTestMixin):
  112. def get_ssl_version(self):
  113. return ssl.PROTOCOL_SSLv3
  114. @skipIfOldSSL
  115. class TLSv1Test(BaseSSLTest, SSLTestMixin):
  116. def get_ssl_version(self):
  117. return ssl.PROTOCOL_TLSv1
  118. class SSLContextTest(BaseSSLTest, SSLTestMixin):
  119. def get_ssl_options(self):
  120. context = ssl_options_to_context(
  121. AsyncHTTPSTestCase.get_ssl_options(self))
  122. assert isinstance(context, ssl.SSLContext)
  123. return context
  124. class BadSSLOptionsTest(unittest.TestCase):
  125. def test_missing_arguments(self):
  126. application = Application()
  127. self.assertRaises(KeyError, HTTPServer, application, ssl_options={
  128. "keyfile": "/__missing__.crt",
  129. })
  130. def test_missing_key(self):
  131. """A missing SSL key should cause an immediate exception."""
  132. application = Application()
  133. module_dir = os.path.dirname(__file__)
  134. existing_certificate = os.path.join(module_dir, 'test.crt')
  135. existing_key = os.path.join(module_dir, 'test.key')
  136. self.assertRaises((ValueError, IOError),
  137. HTTPServer, application, ssl_options={
  138. "certfile": "/__mising__.crt",
  139. })
  140. self.assertRaises((ValueError, IOError),
  141. HTTPServer, application, ssl_options={
  142. "certfile": existing_certificate,
  143. "keyfile": "/__missing__.key"
  144. })
  145. # This actually works because both files exist
  146. HTTPServer(application, ssl_options={
  147. "certfile": existing_certificate,
  148. "keyfile": existing_key,
  149. })
  150. class MultipartTestHandler(RequestHandler):
  151. def post(self):
  152. self.finish({"header": self.request.headers["X-Header-Encoding-Test"],
  153. "argument": self.get_argument("argument"),
  154. "filename": self.request.files["files"][0].filename,
  155. "filebody": _unicode(self.request.files["files"][0]["body"]),
  156. })
  157. # This test is also called from wsgi_test
  158. class HTTPConnectionTest(AsyncHTTPTestCase):
  159. def get_handlers(self):
  160. return [("/multipart", MultipartTestHandler),
  161. ("/hello", HelloWorldRequestHandler)]
  162. def get_app(self):
  163. return Application(self.get_handlers())
  164. def raw_fetch(self, headers, body, newline=b"\r\n"):
  165. with closing(IOStream(socket.socket())) as stream:
  166. self.io_loop.run_sync(lambda: stream.connect(('127.0.0.1', self.get_http_port())))
  167. stream.write(
  168. newline.join(headers +
  169. [utf8("Content-Length: %d" % len(body))]) +
  170. newline + newline + body)
  171. read_stream_body(stream, self.stop)
  172. start_line, headers, body = self.wait()
  173. return body
  174. def test_multipart_form(self):
  175. # Encodings here are tricky: Headers are latin1, bodies can be
  176. # anything (we use utf8 by default).
  177. response = self.raw_fetch([
  178. b"POST /multipart HTTP/1.0",
  179. b"Content-Type: multipart/form-data; boundary=1234567890",
  180. b"X-Header-encoding-test: \xe9",
  181. ],
  182. b"\r\n".join([
  183. b"Content-Disposition: form-data; name=argument",
  184. b"",
  185. u"\u00e1".encode("utf-8"),
  186. b"--1234567890",
  187. u'Content-Disposition: form-data; name="files"; filename="\u00f3"'.encode("utf8"),
  188. b"",
  189. u"\u00fa".encode("utf-8"),
  190. b"--1234567890--",
  191. b"",
  192. ]))
  193. data = json_decode(response)
  194. self.assertEqual(u"\u00e9", data["header"])
  195. self.assertEqual(u"\u00e1", data["argument"])
  196. self.assertEqual(u"\u00f3", data["filename"])
  197. self.assertEqual(u"\u00fa", data["filebody"])
  198. def test_newlines(self):
  199. # We support both CRLF and bare LF as line separators.
  200. for newline in (b"\r\n", b"\n"):
  201. response = self.raw_fetch([b"GET /hello HTTP/1.0"], b"",
  202. newline=newline)
  203. self.assertEqual(response, b'Hello world')
  204. @gen_test
  205. def test_100_continue(self):
  206. # Run through a 100-continue interaction by hand:
  207. # When given Expect: 100-continue, we get a 100 response after the
  208. # headers, and then the real response after the body.
  209. stream = IOStream(socket.socket())
  210. yield stream.connect(("127.0.0.1", self.get_http_port()))
  211. yield stream.write(b"\r\n".join([
  212. b"POST /hello HTTP/1.1",
  213. b"Content-Length: 1024",
  214. b"Expect: 100-continue",
  215. b"Connection: close",
  216. b"\r\n"]))
  217. data = yield stream.read_until(b"\r\n\r\n")
  218. self.assertTrue(data.startswith(b"HTTP/1.1 100 "), data)
  219. stream.write(b"a" * 1024)
  220. first_line = yield stream.read_until(b"\r\n")
  221. self.assertTrue(first_line.startswith(b"HTTP/1.1 200"), first_line)
  222. header_data = yield stream.read_until(b"\r\n\r\n")
  223. headers = HTTPHeaders.parse(native_str(header_data.decode('latin1')))
  224. body = yield stream.read_bytes(int(headers["Content-Length"]))
  225. self.assertEqual(body, b"Got 1024 bytes in POST")
  226. stream.close()
  227. class EchoHandler(RequestHandler):
  228. def get(self):
  229. self.write(recursive_unicode(self.request.arguments))
  230. def post(self):
  231. self.write(recursive_unicode(self.request.arguments))
  232. class TypeCheckHandler(RequestHandler):
  233. def prepare(self):
  234. self.errors = {}
  235. fields = [
  236. ('method', str),
  237. ('uri', str),
  238. ('version', str),
  239. ('remote_ip', str),
  240. ('protocol', str),
  241. ('host', str),
  242. ('path', str),
  243. ('query', str),
  244. ]
  245. for field, expected_type in fields:
  246. self.check_type(field, getattr(self.request, field), expected_type)
  247. self.check_type('header_key', list(self.request.headers.keys())[0], str)
  248. self.check_type('header_value', list(self.request.headers.values())[0], str)
  249. self.check_type('cookie_key', list(self.request.cookies.keys())[0], str)
  250. self.check_type('cookie_value', list(self.request.cookies.values())[0].value, str)
  251. # secure cookies
  252. self.check_type('arg_key', list(self.request.arguments.keys())[0], str)
  253. self.check_type('arg_value', list(self.request.arguments.values())[0][0], bytes)
  254. def post(self):
  255. self.check_type('body', self.request.body, bytes)
  256. self.write(self.errors)
  257. def get(self):
  258. self.write(self.errors)
  259. def check_type(self, name, obj, expected_type):
  260. actual_type = type(obj)
  261. if expected_type != actual_type:
  262. self.errors[name] = "expected %s, got %s" % (expected_type,
  263. actual_type)
  264. class HTTPServerTest(AsyncHTTPTestCase):
  265. def get_app(self):
  266. return Application([("/echo", EchoHandler),
  267. ("/typecheck", TypeCheckHandler),
  268. ("//doubleslash", EchoHandler),
  269. ])
  270. def test_query_string_encoding(self):
  271. response = self.fetch("/echo?foo=%C3%A9")
  272. data = json_decode(response.body)
  273. self.assertEqual(data, {u"foo": [u"\u00e9"]})
  274. def test_empty_query_string(self):
  275. response = self.fetch("/echo?foo=&foo=")
  276. data = json_decode(response.body)
  277. self.assertEqual(data, {u"foo": [u"", u""]})
  278. def test_empty_post_parameters(self):
  279. response = self.fetch("/echo", method="POST", body="foo=&bar=")
  280. data = json_decode(response.body)
  281. self.assertEqual(data, {u"foo": [u""], u"bar": [u""]})
  282. def test_types(self):
  283. headers = {"Cookie": "foo=bar"}
  284. response = self.fetch("/typecheck?foo=bar", headers=headers)
  285. data = json_decode(response.body)
  286. self.assertEqual(data, {})
  287. response = self.fetch("/typecheck", method="POST", body="foo=bar", headers=headers)
  288. data = json_decode(response.body)
  289. self.assertEqual(data, {})
  290. def test_double_slash(self):
  291. # urlparse.urlsplit (which tornado.httpserver used to use
  292. # incorrectly) would parse paths beginning with "//" as
  293. # protocol-relative urls.
  294. response = self.fetch("//doubleslash")
  295. self.assertEqual(200, response.code)
  296. self.assertEqual(json_decode(response.body), {})
  297. def test_malformed_body(self):
  298. # parse_qs is pretty forgiving, but it will fail on python 3
  299. # if the data is not utf8. On python 2 parse_qs will work,
  300. # but then the recursive_unicode call in EchoHandler will
  301. # fail.
  302. if str is bytes:
  303. return
  304. with ExpectLog(gen_log, 'Invalid x-www-form-urlencoded body'):
  305. response = self.fetch(
  306. '/echo', method="POST",
  307. headers={'Content-Type': 'application/x-www-form-urlencoded'},
  308. body=b'\xe9')
  309. self.assertEqual(200, response.code)
  310. self.assertEqual(b'{}', response.body)
  311. class HTTPServerRawTest(AsyncHTTPTestCase):
  312. def get_app(self):
  313. return Application([
  314. ('/echo', EchoHandler),
  315. ])
  316. def setUp(self):
  317. super(HTTPServerRawTest, self).setUp()
  318. self.stream = IOStream(socket.socket())
  319. self.io_loop.run_sync(lambda: self.stream.connect(('127.0.0.1', self.get_http_port())))
  320. def tearDown(self):
  321. self.stream.close()
  322. super(HTTPServerRawTest, self).tearDown()
  323. def test_empty_request(self):
  324. self.stream.close()
  325. self.io_loop.add_timeout(datetime.timedelta(seconds=0.001), self.stop)
  326. self.wait()
  327. def test_malformed_first_line_response(self):
  328. with ExpectLog(gen_log, '.*Malformed HTTP request line'):
  329. self.stream.write(b'asdf\r\n\r\n')
  330. read_stream_body(self.stream, self.stop)
  331. start_line, headers, response = self.wait()
  332. self.assertEqual('HTTP/1.1', start_line.version)
  333. self.assertEqual(400, start_line.code)
  334. self.assertEqual('Bad Request', start_line.reason)
  335. def test_malformed_first_line_log(self):
  336. with ExpectLog(gen_log, '.*Malformed HTTP request line'):
  337. self.stream.write(b'asdf\r\n\r\n')
  338. # TODO: need an async version of ExpectLog so we don't need
  339. # hard-coded timeouts here.
  340. self.io_loop.add_timeout(datetime.timedelta(seconds=0.05),
  341. self.stop)
  342. self.wait()
  343. def test_malformed_headers(self):
  344. with ExpectLog(gen_log, '.*Malformed HTTP message.*no colon in header line'):
  345. self.stream.write(b'GET / HTTP/1.0\r\nasdf\r\n\r\n')
  346. self.io_loop.add_timeout(datetime.timedelta(seconds=0.05),
  347. self.stop)
  348. self.wait()
  349. def test_chunked_request_body(self):
  350. # Chunked requests are not widely supported and we don't have a way
  351. # to generate them in AsyncHTTPClient, but HTTPServer will read them.
  352. self.stream.write(b"""\
  353. POST /echo HTTP/1.1
  354. Transfer-Encoding: chunked
  355. Content-Type: application/x-www-form-urlencoded
  356. 4
  357. foo=
  358. 3
  359. bar
  360. 0
  361. """.replace(b"\n", b"\r\n"))
  362. read_stream_body(self.stream, self.stop)
  363. start_line, headers, response = self.wait()
  364. self.assertEqual(json_decode(response), {u'foo': [u'bar']})
  365. def test_chunked_request_uppercase(self):
  366. # As per RFC 2616 section 3.6, "Transfer-Encoding" header's value is
  367. # case-insensitive.
  368. self.stream.write(b"""\
  369. POST /echo HTTP/1.1
  370. Transfer-Encoding: Chunked
  371. Content-Type: application/x-www-form-urlencoded
  372. 4
  373. foo=
  374. 3
  375. bar
  376. 0
  377. """.replace(b"\n", b"\r\n"))
  378. read_stream_body(self.stream, self.stop)
  379. start_line, headers, response = self.wait()
  380. self.assertEqual(json_decode(response), {u'foo': [u'bar']})
  381. @gen_test
  382. def test_invalid_content_length(self):
  383. with ExpectLog(gen_log, '.*Only integer Content-Length is allowed'):
  384. self.stream.write(b"""\
  385. POST /echo HTTP/1.1
  386. Content-Length: foo
  387. bar
  388. """.replace(b"\n", b"\r\n"))
  389. yield self.stream.read_until_close()
  390. class XHeaderTest(HandlerBaseTestCase):
  391. class Handler(RequestHandler):
  392. def get(self):
  393. self.set_header('request-version', self.request.version)
  394. self.write(dict(remote_ip=self.request.remote_ip,
  395. remote_protocol=self.request.protocol))
  396. def get_httpserver_options(self):
  397. return dict(xheaders=True, trusted_downstream=['5.5.5.5'])
  398. def test_ip_headers(self):
  399. self.assertEqual(self.fetch_json("/")["remote_ip"], "127.0.0.1")
  400. valid_ipv4 = {"X-Real-IP": "4.4.4.4"}
  401. self.assertEqual(
  402. self.fetch_json("/", headers=valid_ipv4)["remote_ip"],
  403. "4.4.4.4")
  404. valid_ipv4_list = {"X-Forwarded-For": "127.0.0.1, 4.4.4.4"}
  405. self.assertEqual(
  406. self.fetch_json("/", headers=valid_ipv4_list)["remote_ip"],
  407. "4.4.4.4")
  408. valid_ipv6 = {"X-Real-IP": "2620:0:1cfe:face:b00c::3"}
  409. self.assertEqual(
  410. self.fetch_json("/", headers=valid_ipv6)["remote_ip"],
  411. "2620:0:1cfe:face:b00c::3")
  412. valid_ipv6_list = {"X-Forwarded-For": "::1, 2620:0:1cfe:face:b00c::3"}
  413. self.assertEqual(
  414. self.fetch_json("/", headers=valid_ipv6_list)["remote_ip"],
  415. "2620:0:1cfe:face:b00c::3")
  416. invalid_chars = {"X-Real-IP": "4.4.4.4<script>"}
  417. self.assertEqual(
  418. self.fetch_json("/", headers=invalid_chars)["remote_ip"],
  419. "127.0.0.1")
  420. invalid_chars_list = {"X-Forwarded-For": "4.4.4.4, 5.5.5.5<script>"}
  421. self.assertEqual(
  422. self.fetch_json("/", headers=invalid_chars_list)["remote_ip"],
  423. "127.0.0.1")
  424. invalid_host = {"X-Real-IP": "www.google.com"}
  425. self.assertEqual(
  426. self.fetch_json("/", headers=invalid_host)["remote_ip"],
  427. "127.0.0.1")
  428. def test_trusted_downstream(self):
  429. valid_ipv4_list = {"X-Forwarded-For": "127.0.0.1, 4.4.4.4, 5.5.5.5"}
  430. resp = self.fetch("/", headers=valid_ipv4_list)
  431. if resp.headers['request-version'].startswith('HTTP/2'):
  432. # This is a hack - there's nothing that fundamentally requires http/1
  433. # here but tornado_http2 doesn't support it yet.
  434. self.skipTest('requires HTTP/1.x')
  435. result = json_decode(resp.body)
  436. self.assertEqual(result['remote_ip'], "4.4.4.4")
  437. def test_scheme_headers(self):
  438. self.assertEqual(self.fetch_json("/")["remote_protocol"], "http")
  439. https_scheme = {"X-Scheme": "https"}
  440. self.assertEqual(
  441. self.fetch_json("/", headers=https_scheme)["remote_protocol"],
  442. "https")
  443. https_forwarded = {"X-Forwarded-Proto": "https"}
  444. self.assertEqual(
  445. self.fetch_json("/", headers=https_forwarded)["remote_protocol"],
  446. "https")
  447. https_multi_forwarded = {"X-Forwarded-Proto": "https , http"}
  448. self.assertEqual(
  449. self.fetch_json("/", headers=https_multi_forwarded)["remote_protocol"],
  450. "http")
  451. http_multi_forwarded = {"X-Forwarded-Proto": "http,https"}
  452. self.assertEqual(
  453. self.fetch_json("/", headers=http_multi_forwarded)["remote_protocol"],
  454. "https")
  455. bad_forwarded = {"X-Forwarded-Proto": "unknown"}
  456. self.assertEqual(
  457. self.fetch_json("/", headers=bad_forwarded)["remote_protocol"],
  458. "http")
  459. class SSLXHeaderTest(AsyncHTTPSTestCase, HandlerBaseTestCase):
  460. def get_app(self):
  461. return Application([('/', XHeaderTest.Handler)])
  462. def get_httpserver_options(self):
  463. output = super(SSLXHeaderTest, self).get_httpserver_options()
  464. output['xheaders'] = True
  465. return output
  466. def test_request_without_xprotocol(self):
  467. self.assertEqual(self.fetch_json("/")["remote_protocol"], "https")
  468. http_scheme = {"X-Scheme": "http"}
  469. self.assertEqual(
  470. self.fetch_json("/", headers=http_scheme)["remote_protocol"], "http")
  471. bad_scheme = {"X-Scheme": "unknown"}
  472. self.assertEqual(
  473. self.fetch_json("/", headers=bad_scheme)["remote_protocol"], "https")
  474. class ManualProtocolTest(HandlerBaseTestCase):
  475. class Handler(RequestHandler):
  476. def get(self):
  477. self.write(dict(protocol=self.request.protocol))
  478. def get_httpserver_options(self):
  479. return dict(protocol='https')
  480. def test_manual_protocol(self):
  481. self.assertEqual(self.fetch_json('/')['protocol'], 'https')
  482. @unittest.skipIf(not hasattr(socket, 'AF_UNIX') or sys.platform == 'cygwin',
  483. "unix sockets not supported on this platform")
  484. class UnixSocketTest(AsyncTestCase):
  485. """HTTPServers can listen on Unix sockets too.
  486. Why would you want to do this? Nginx can proxy to backends listening
  487. on unix sockets, for one thing (and managing a namespace for unix
  488. sockets can be easier than managing a bunch of TCP port numbers).
  489. Unfortunately, there's no way to specify a unix socket in a url for
  490. an HTTP client, so we have to test this by hand.
  491. """
  492. def setUp(self):
  493. super(UnixSocketTest, self).setUp()
  494. self.tmpdir = tempfile.mkdtemp()
  495. self.sockfile = os.path.join(self.tmpdir, "test.sock")
  496. sock = netutil.bind_unix_socket(self.sockfile)
  497. app = Application([("/hello", HelloWorldRequestHandler)])
  498. self.server = HTTPServer(app)
  499. self.server.add_socket(sock)
  500. self.stream = IOStream(socket.socket(socket.AF_UNIX))
  501. self.io_loop.run_sync(lambda: self.stream.connect(self.sockfile))
  502. def tearDown(self):
  503. self.stream.close()
  504. self.io_loop.run_sync(self.server.close_all_connections)
  505. self.server.stop()
  506. shutil.rmtree(self.tmpdir)
  507. super(UnixSocketTest, self).tearDown()
  508. @gen_test
  509. def test_unix_socket(self):
  510. self.stream.write(b"GET /hello HTTP/1.0\r\n\r\n")
  511. response = yield self.stream.read_until(b"\r\n")
  512. self.assertEqual(response, b"HTTP/1.1 200 OK\r\n")
  513. header_data = yield self.stream.read_until(b"\r\n\r\n")
  514. headers = HTTPHeaders.parse(header_data.decode('latin1'))
  515. body = yield self.stream.read_bytes(int(headers["Content-Length"]))
  516. self.assertEqual(body, b"Hello world")
  517. @gen_test
  518. def test_unix_socket_bad_request(self):
  519. # Unix sockets don't have remote addresses so they just return an
  520. # empty string.
  521. with ExpectLog(gen_log, "Malformed HTTP message from"):
  522. self.stream.write(b"garbage\r\n\r\n")
  523. response = yield self.stream.read_until_close()
  524. self.assertEqual(response, b"HTTP/1.1 400 Bad Request\r\n\r\n")
  525. class KeepAliveTest(AsyncHTTPTestCase):
  526. """Tests various scenarios for HTTP 1.1 keep-alive support.
  527. These tests don't use AsyncHTTPClient because we want to control
  528. connection reuse and closing.
  529. """
  530. def get_app(self):
  531. class HelloHandler(RequestHandler):
  532. def get(self):
  533. self.finish('Hello world')
  534. def post(self):
  535. self.finish('Hello world')
  536. class LargeHandler(RequestHandler):
  537. def get(self):
  538. # 512KB should be bigger than the socket buffers so it will
  539. # be written out in chunks.
  540. self.write(''.join(chr(i % 256) * 1024 for i in range(512)))
  541. class FinishOnCloseHandler(RequestHandler):
  542. @gen.coroutine
  543. def get(self):
  544. self.flush()
  545. never_finish = Event()
  546. yield never_finish.wait()
  547. def on_connection_close(self):
  548. # This is not very realistic, but finishing the request
  549. # from the close callback has the right timing to mimic
  550. # some errors seen in the wild.
  551. self.finish('closed')
  552. return Application([('/', HelloHandler),
  553. ('/large', LargeHandler),
  554. ('/finish_on_close', FinishOnCloseHandler)])
  555. def setUp(self):
  556. super(KeepAliveTest, self).setUp()
  557. self.http_version = b'HTTP/1.1'
  558. def tearDown(self):
  559. # We just closed the client side of the socket; let the IOLoop run
  560. # once to make sure the server side got the message.
  561. self.io_loop.add_timeout(datetime.timedelta(seconds=0.001), self.stop)
  562. self.wait()
  563. if hasattr(self, 'stream'):
  564. self.stream.close()
  565. super(KeepAliveTest, self).tearDown()
  566. # The next few methods are a crude manual http client
  567. @gen.coroutine
  568. def connect(self):
  569. self.stream = IOStream(socket.socket())
  570. yield self.stream.connect(('127.0.0.1', self.get_http_port()))
  571. @gen.coroutine
  572. def read_headers(self):
  573. first_line = yield self.stream.read_until(b'\r\n')
  574. self.assertTrue(first_line.startswith(b'HTTP/1.1 200'), first_line)
  575. header_bytes = yield self.stream.read_until(b'\r\n\r\n')
  576. headers = HTTPHeaders.parse(header_bytes.decode('latin1'))
  577. raise gen.Return(headers)
  578. @gen.coroutine
  579. def read_response(self):
  580. self.headers = yield self.read_headers()
  581. body = yield self.stream.read_bytes(int(self.headers['Content-Length']))
  582. self.assertEqual(b'Hello world', body)
  583. def close(self):
  584. self.stream.close()
  585. del self.stream
  586. @gen_test
  587. def test_two_requests(self):
  588. yield self.connect()
  589. self.stream.write(b'GET / HTTP/1.1\r\n\r\n')
  590. yield self.read_response()
  591. self.stream.write(b'GET / HTTP/1.1\r\n\r\n')
  592. yield self.read_response()
  593. self.close()
  594. @gen_test
  595. def test_request_close(self):
  596. yield self.connect()
  597. self.stream.write(b'GET / HTTP/1.1\r\nConnection: close\r\n\r\n')
  598. yield self.read_response()
  599. data = yield self.stream.read_until_close()
  600. self.assertTrue(not data)
  601. self.assertEqual(self.headers['Connection'], 'close')
  602. self.close()
  603. # keepalive is supported for http 1.0 too, but it's opt-in
  604. @gen_test
  605. def test_http10(self):
  606. self.http_version = b'HTTP/1.0'
  607. yield self.connect()
  608. self.stream.write(b'GET / HTTP/1.0\r\n\r\n')
  609. yield self.read_response()
  610. data = yield self.stream.read_until_close()
  611. self.assertTrue(not data)
  612. self.assertTrue('Connection' not in self.headers)
  613. self.close()
  614. @gen_test
  615. def test_http10_keepalive(self):
  616. self.http_version = b'HTTP/1.0'
  617. yield self.connect()
  618. self.stream.write(b'GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n')
  619. yield self.read_response()
  620. self.assertEqual(self.headers['Connection'], 'Keep-Alive')
  621. self.stream.write(b'GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n')
  622. yield self.read_response()
  623. self.assertEqual(self.headers['Connection'], 'Keep-Alive')
  624. self.close()
  625. @gen_test
  626. def test_http10_keepalive_extra_crlf(self):
  627. self.http_version = b'HTTP/1.0'
  628. yield self.connect()
  629. self.stream.write(b'GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n\r\n')
  630. yield self.read_response()
  631. self.assertEqual(self.headers['Connection'], 'Keep-Alive')
  632. self.stream.write(b'GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n')
  633. yield self.read_response()
  634. self.assertEqual(self.headers['Connection'], 'Keep-Alive')
  635. self.close()
  636. @gen_test
  637. def test_pipelined_requests(self):
  638. yield self.connect()
  639. self.stream.write(b'GET / HTTP/1.1\r\n\r\nGET / HTTP/1.1\r\n\r\n')
  640. yield self.read_response()
  641. yield self.read_response()
  642. self.close()
  643. @gen_test
  644. def test_pipelined_cancel(self):
  645. yield self.connect()
  646. self.stream.write(b'GET / HTTP/1.1\r\n\r\nGET / HTTP/1.1\r\n\r\n')
  647. # only read once
  648. yield self.read_response()
  649. self.close()
  650. @gen_test
  651. def test_cancel_during_download(self):
  652. yield self.connect()
  653. self.stream.write(b'GET /large HTTP/1.1\r\n\r\n')
  654. yield self.read_headers()
  655. yield self.stream.read_bytes(1024)
  656. self.close()
  657. @gen_test
  658. def test_finish_while_closed(self):
  659. yield self.connect()
  660. self.stream.write(b'GET /finish_on_close HTTP/1.1\r\n\r\n')
  661. yield self.read_headers()
  662. self.close()
  663. @gen_test
  664. def test_keepalive_chunked(self):
  665. self.http_version = b'HTTP/1.0'
  666. yield self.connect()
  667. self.stream.write(b'POST / HTTP/1.0\r\n'
  668. b'Connection: keep-alive\r\n'
  669. b'Transfer-Encoding: chunked\r\n'
  670. b'\r\n'
  671. b'0\r\n'
  672. b'\r\n')
  673. yield self.read_response()
  674. self.assertEqual(self.headers['Connection'], 'Keep-Alive')
  675. self.stream.write(b'GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n')
  676. yield self.read_response()
  677. self.assertEqual(self.headers['Connection'], 'Keep-Alive')
  678. self.close()
  679. class GzipBaseTest(object):
  680. def get_app(self):
  681. return Application([('/', EchoHandler)])
  682. def post_gzip(self, body):
  683. bytesio = BytesIO()
  684. gzip_file = gzip.GzipFile(mode='w', fileobj=bytesio)
  685. gzip_file.write(utf8(body))
  686. gzip_file.close()
  687. compressed_body = bytesio.getvalue()
  688. return self.fetch('/', method='POST', body=compressed_body,
  689. headers={'Content-Encoding': 'gzip'})
  690. def test_uncompressed(self):
  691. response = self.fetch('/', method='POST', body='foo=bar')
  692. self.assertEquals(json_decode(response.body), {u'foo': [u'bar']})
  693. class GzipTest(GzipBaseTest, AsyncHTTPTestCase):
  694. def get_httpserver_options(self):
  695. return dict(decompress_request=True)
  696. def test_gzip(self):
  697. response = self.post_gzip('foo=bar')
  698. self.assertEquals(json_decode(response.body), {u'foo': [u'bar']})
  699. class GzipUnsupportedTest(GzipBaseTest, AsyncHTTPTestCase):
  700. def test_gzip_unsupported(self):
  701. # Gzip support is opt-in; without it the server fails to parse
  702. # the body (but parsing form bodies is currently just a log message,
  703. # not a fatal error).
  704. with ExpectLog(gen_log, "Unsupported Content-Encoding"):
  705. response = self.post_gzip('foo=bar')
  706. self.assertEquals(json_decode(response.body), {})
  707. class StreamingChunkSizeTest(AsyncHTTPTestCase):
  708. # 50 characters long, and repetitive so it can be compressed.
  709. BODY = b'01234567890123456789012345678901234567890123456789'
  710. CHUNK_SIZE = 16
  711. def get_http_client(self):
  712. # body_producer doesn't work on curl_httpclient, so override the
  713. # configured AsyncHTTPClient implementation.
  714. return SimpleAsyncHTTPClient()
  715. def get_httpserver_options(self):
  716. return dict(chunk_size=self.CHUNK_SIZE, decompress_request=True)
  717. class MessageDelegate(HTTPMessageDelegate):
  718. def __init__(self, connection):
  719. self.connection = connection
  720. def headers_received(self, start_line, headers):
  721. self.chunk_lengths = []
  722. def data_received(self, chunk):
  723. self.chunk_lengths.append(len(chunk))
  724. def finish(self):
  725. response_body = utf8(json_encode(self.chunk_lengths))
  726. self.connection.write_headers(
  727. ResponseStartLine('HTTP/1.1', 200, 'OK'),
  728. HTTPHeaders({'Content-Length': str(len(response_body))}))
  729. self.connection.write(response_body)
  730. self.connection.finish()
  731. def get_app(self):
  732. class App(HTTPServerConnectionDelegate):
  733. def start_request(self, server_conn, request_conn):
  734. return StreamingChunkSizeTest.MessageDelegate(request_conn)
  735. return App()
  736. def fetch_chunk_sizes(self, **kwargs):
  737. response = self.fetch('/', method='POST', **kwargs)
  738. response.rethrow()
  739. chunks = json_decode(response.body)
  740. self.assertEqual(len(self.BODY), sum(chunks))
  741. for chunk_size in chunks:
  742. self.assertLessEqual(chunk_size, self.CHUNK_SIZE,
  743. 'oversized chunk: ' + str(chunks))
  744. self.assertGreater(chunk_size, 0,
  745. 'empty chunk: ' + str(chunks))
  746. return chunks
  747. def compress(self, body):
  748. bytesio = BytesIO()
  749. gzfile = gzip.GzipFile(mode='w', fileobj=bytesio)
  750. gzfile.write(body)
  751. gzfile.close()
  752. compressed = bytesio.getvalue()
  753. if len(compressed) >= len(body):
  754. raise Exception("body did not shrink when compressed")
  755. return compressed
  756. def test_regular_body(self):
  757. chunks = self.fetch_chunk_sizes(body=self.BODY)
  758. # Without compression we know exactly what to expect.
  759. self.assertEqual([16, 16, 16, 2], chunks)
  760. def test_compressed_body(self):
  761. self.fetch_chunk_sizes(body=self.compress(self.BODY),
  762. headers={'Content-Encoding': 'gzip'})
  763. # Compression creates irregular boundaries so the assertions
  764. # in fetch_chunk_sizes are as specific as we can get.
  765. def test_chunked_body(self):
  766. def body_producer(write):
  767. write(self.BODY[:20])
  768. write(self.BODY[20:])
  769. chunks = self.fetch_chunk_sizes(body_producer=body_producer)
  770. # HTTP chunk boundaries translate to application-visible breaks
  771. self.assertEqual([16, 4, 16, 14], chunks)
  772. def test_chunked_compressed(self):
  773. compressed = self.compress(self.BODY)
  774. self.assertGreater(len(compressed), 20)
  775. def body_producer(write):
  776. write(compressed[:20])
  777. write(compressed[20:])
  778. self.fetch_chunk_sizes(body_producer=body_producer,
  779. headers={'Content-Encoding': 'gzip'})
  780. class MaxHeaderSizeTest(AsyncHTTPTestCase):
  781. def get_app(self):
  782. return Application([('/', HelloWorldRequestHandler)])
  783. def get_httpserver_options(self):
  784. return dict(max_header_size=1024)
  785. def test_small_headers(self):
  786. response = self.fetch("/", headers={'X-Filler': 'a' * 100})
  787. response.rethrow()
  788. self.assertEqual(response.body, b"Hello world")
  789. def test_large_headers(self):
  790. with ExpectLog(gen_log, "Unsatisfiable read", required=False):
  791. try:
  792. self.fetch("/", headers={'X-Filler': 'a' * 1000}, raise_error=True)
  793. self.fail("did not raise expected exception")
  794. except HTTPError as e:
  795. # 431 is "Request Header Fields Too Large", defined in RFC
  796. # 6585. However, many implementations just close the
  797. # connection in this case, resulting in a 599.
  798. self.assertIn(e.response.code, (431, 599))
  799. @skipOnTravis
  800. class IdleTimeoutTest(AsyncHTTPTestCase):
  801. def get_app(self):
  802. return Application([('/', HelloWorldRequestHandler)])
  803. def get_httpserver_options(self):
  804. return dict(idle_connection_timeout=0.1)
  805. def setUp(self):
  806. super(IdleTimeoutTest, self).setUp()
  807. self.streams = []
  808. def tearDown(self):
  809. super(IdleTimeoutTest, self).tearDown()
  810. for stream in self.streams:
  811. stream.close()
  812. @gen.coroutine
  813. def connect(self):
  814. stream = IOStream(socket.socket())
  815. yield stream.connect(('127.0.0.1', self.get_http_port()))
  816. self.streams.append(stream)
  817. raise gen.Return(stream)
  818. @gen_test
  819. def test_unused_connection(self):
  820. stream = yield self.connect()
  821. event = Event()
  822. stream.set_close_callback(event.set)
  823. yield event.wait()
  824. @gen_test
  825. def test_idle_after_use(self):
  826. stream = yield self.connect()
  827. event = Event()
  828. stream.set_close_callback(event.set)
  829. # Use the connection twice to make sure keep-alives are working
  830. for i in range(2):
  831. stream.write(b"GET / HTTP/1.1\r\n\r\n")
  832. yield stream.read_until(b"\r\n\r\n")
  833. data = yield stream.read_bytes(11)
  834. self.assertEqual(data, b"Hello world")
  835. # Now let the timeout trigger and close the connection.
  836. yield event.wait()
  837. class BodyLimitsTest(AsyncHTTPTestCase):
  838. def get_app(self):
  839. class BufferedHandler(RequestHandler):
  840. def put(self):
  841. self.write(str(len(self.request.body)))
  842. @stream_request_body
  843. class StreamingHandler(RequestHandler):
  844. def initialize(self):
  845. self.bytes_read = 0
  846. def prepare(self):
  847. if 'expected_size' in self.request.arguments:
  848. self.request.connection.set_max_body_size(
  849. int(self.get_argument('expected_size')))
  850. if 'body_timeout' in self.request.arguments:
  851. self.request.connection.set_body_timeout(
  852. float(self.get_argument('body_timeout')))
  853. def data_received(self, data):
  854. self.bytes_read += len(data)
  855. def put(self):
  856. self.write(str(self.bytes_read))
  857. return Application([('/buffered', BufferedHandler),
  858. ('/streaming', StreamingHandler)])
  859. def get_httpserver_options(self):
  860. return dict(body_timeout=3600, max_body_size=4096)
  861. def get_http_client(self):
  862. # body_producer doesn't work on curl_httpclient, so override the
  863. # configured AsyncHTTPClient implementation.
  864. return SimpleAsyncHTTPClient()
  865. def test_small_body(self):
  866. response = self.fetch('/buffered', method='PUT', body=b'a' * 4096)
  867. self.assertEqual(response.body, b'4096')
  868. response = self.fetch('/streaming', method='PUT', body=b'a' * 4096)
  869. self.assertEqual(response.body, b'4096')
  870. def test_large_body_buffered(self):
  871. with ExpectLog(gen_log, '.*Content-Length too long'):
  872. response = self.fetch('/buffered', method='PUT', body=b'a' * 10240)
  873. self.assertEqual(response.code, 400)
  874. @unittest.skipIf(os.name == 'nt', 'flaky on windows')
  875. def test_large_body_buffered_chunked(self):
  876. # This test is flaky on windows for unknown reasons.
  877. with ExpectLog(gen_log, '.*chunked body too large'):
  878. response = self.fetch('/buffered', method='PUT',
  879. body_producer=lambda write: write(b'a' * 10240))
  880. self.assertEqual(response.code, 400)
  881. def test_large_body_streaming(self):
  882. with ExpectLog(gen_log, '.*Content-Length too long'):
  883. response = self.fetch('/streaming', method='PUT', body=b'a' * 10240)
  884. self.assertEqual(response.code, 400)
  885. @unittest.skipIf(os.name == 'nt', 'flaky on windows')
  886. def test_large_body_streaming_chunked(self):
  887. with ExpectLog(gen_log, '.*chunked body too large'):
  888. response = self.fetch('/streaming', method='PUT',
  889. body_producer=lambda write: write(b'a' * 10240))
  890. self.assertEqual(response.code, 400)
  891. def test_large_body_streaming_override(self):
  892. response = self.fetch('/streaming?expected_size=10240', method='PUT',
  893. body=b'a' * 10240)
  894. self.assertEqual(response.body, b'10240')
  895. def test_large_body_streaming_chunked_override(self):
  896. response = self.fetch('/streaming?expected_size=10240', method='PUT',
  897. body_producer=lambda write: write(b'a' * 10240))
  898. self.assertEqual(response.body, b'10240')
  899. @gen_test
  900. def test_timeout(self):
  901. stream = IOStream(socket.socket())
  902. try:
  903. yield stream.connect(('127.0.0.1', self.get_http_port()))
  904. # Use a raw stream because AsyncHTTPClient won't let us read a
  905. # response without finishing a body.
  906. stream.write(b'PUT /streaming?body_timeout=0.1 HTTP/1.0\r\n'
  907. b'Content-Length: 42\r\n\r\n')
  908. with ExpectLog(gen_log, 'Timeout reading body'):
  909. response = yield stream.read_until_close()
  910. self.assertEqual(response, b'')
  911. finally:
  912. stream.close()
  913. @gen_test
  914. def test_body_size_override_reset(self):
  915. # The max_body_size override is reset between requests.
  916. stream = IOStream(socket.socket())
  917. try:
  918. yield stream.connect(('127.0.0.1', self.get_http_port()))
  919. # Use a raw stream so we can make sure it's all on one connection.
  920. stream.write(b'PUT /streaming?expected_size=10240 HTTP/1.1\r\n'
  921. b'Content-Length: 10240\r\n\r\n')
  922. stream.write(b'a' * 10240)
  923. fut = Future()
  924. read_stream_body(stream, callback=fut.set_result)
  925. start_line, headers, response = yield fut
  926. self.assertEqual(response, b'10240')
  927. # Without the ?expected_size parameter, we get the old default value
  928. stream.write(b'PUT /streaming HTTP/1.1\r\n'
  929. b'Content-Length: 10240\r\n\r\n')
  930. with ExpectLog(gen_log, '.*Content-Length too long'):
  931. data = yield stream.read_until_close()
  932. self.assertEqual(data, b'HTTP/1.1 400 Bad Request\r\n\r\n')
  933. finally:
  934. stream.close()
  935. class LegacyInterfaceTest(AsyncHTTPTestCase):
  936. def get_app(self):
  937. # The old request_callback interface does not implement the
  938. # delegate interface, and writes its response via request.write
  939. # instead of request.connection.write_headers.
  940. def handle_request(request):
  941. self.http1 = request.version.startswith("HTTP/1.")
  942. if not self.http1:
  943. # This test will be skipped if we're using HTTP/2,
  944. # so just close it out cleanly using the modern interface.
  945. request.connection.write_headers(
  946. ResponseStartLine('', 200, 'OK'),
  947. HTTPHeaders())
  948. request.connection.finish()
  949. return
  950. message = b"Hello world"
  951. request.connection.write(utf8("HTTP/1.1 200 OK\r\n"
  952. "Content-Length: %d\r\n\r\n" % len(message)))
  953. request.connection.write(message)
  954. request.connection.finish()
  955. return handle_request
  956. def test_legacy_interface(self):
  957. response = self.fetch('/')
  958. if not self.http1:
  959. self.skipTest("requires HTTP/1.x")
  960. self.assertEqual(response.body, b"Hello world")