tests.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. # -*- encoding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from datetime import datetime, timedelta
  4. from io import BytesIO
  5. from itertools import chain
  6. import time
  7. from unittest import skipIf
  8. from django.db import connection, connections
  9. from django.core import signals
  10. from django.core.exceptions import SuspiciousOperation
  11. from django.core.handlers.wsgi import WSGIRequest, LimitedStream
  12. from django.http import (HttpRequest, HttpResponse, parse_cookie,
  13. build_request_repr, UnreadablePostError, RawPostDataException)
  14. from django.test import SimpleTestCase, TransactionTestCase, override_settings
  15. from django.test.client import FakePayload
  16. from django.test.utils import str_prefix
  17. from django.utils import six
  18. from django.utils.http import cookie_date, urlencode
  19. from django.utils.six.moves.urllib.parse import urlencode as original_urlencode
  20. from django.utils.timezone import utc
  21. class RequestsTests(SimpleTestCase):
  22. def test_httprequest(self):
  23. request = HttpRequest()
  24. self.assertEqual(list(request.GET.keys()), [])
  25. self.assertEqual(list(request.POST.keys()), [])
  26. self.assertEqual(list(request.COOKIES.keys()), [])
  27. self.assertEqual(list(request.META.keys()), [])
  28. def test_httprequest_repr(self):
  29. request = HttpRequest()
  30. request.path = '/somepath/'
  31. request.GET = {'get-key': 'get-value'}
  32. request.POST = {'post-key': 'post-value'}
  33. request.COOKIES = {'post-key': 'post-value'}
  34. request.META = {'post-key': 'post-value'}
  35. self.assertEqual(repr(request), str_prefix("<HttpRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"))
  36. self.assertEqual(build_request_repr(request), repr(request))
  37. self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={'a': 'b'}, POST_override={'c': 'd'}, COOKIES_override={'e': 'f'}, META_override={'g': 'h'}),
  38. str_prefix("<HttpRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"))
  39. def test_bad_httprequest_repr(self):
  40. """
  41. If an exception occurs when parsing GET, POST, COOKIES, or META, the
  42. repr of the request should show it.
  43. """
  44. class Bomb(object):
  45. """An object that raises an exception when printed out."""
  46. def __repr__(self):
  47. raise Exception('boom!')
  48. bomb = Bomb()
  49. for attr in ['GET', 'POST', 'COOKIES', 'META']:
  50. request = HttpRequest()
  51. setattr(request, attr, {'bomb': bomb})
  52. self.assertIn('%s:<could not parse>' % attr, repr(request))
  53. def test_wsgirequest(self):
  54. request = WSGIRequest({'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'wsgi.input': BytesIO(b'')})
  55. self.assertEqual(list(request.GET.keys()), [])
  56. self.assertEqual(list(request.POST.keys()), [])
  57. self.assertEqual(list(request.COOKIES.keys()), [])
  58. self.assertEqual(set(request.META.keys()), set(['PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'wsgi.input']))
  59. self.assertEqual(request.META['PATH_INFO'], 'bogus')
  60. self.assertEqual(request.META['REQUEST_METHOD'], 'bogus')
  61. self.assertEqual(request.META['SCRIPT_NAME'], '')
  62. def test_wsgirequest_with_script_name(self):
  63. """
  64. Ensure that the request's path is correctly assembled, regardless of
  65. whether or not the SCRIPT_NAME has a trailing slash.
  66. Refs #20169.
  67. """
  68. # With trailing slash
  69. request = WSGIRequest({'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  70. self.assertEqual(request.path, '/PREFIX/somepath/')
  71. # Without trailing slash
  72. request = WSGIRequest({'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  73. self.assertEqual(request.path, '/PREFIX/somepath/')
  74. def test_wsgirequest_with_force_script_name(self):
  75. """
  76. Ensure that the FORCE_SCRIPT_NAME setting takes precedence over the
  77. request's SCRIPT_NAME environment parameter.
  78. Refs #20169.
  79. """
  80. with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
  81. request = WSGIRequest({'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  82. self.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
  83. def test_wsgirequest_path_with_force_script_name_trailing_slash(self):
  84. """
  85. Ensure that the request's path is correctly assembled, regardless of
  86. whether or not the FORCE_SCRIPT_NAME setting has a trailing slash.
  87. Refs #20169.
  88. """
  89. # With trailing slash
  90. with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
  91. request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  92. self.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
  93. # Without trailing slash
  94. with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX'):
  95. request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  96. self.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
  97. def test_wsgirequest_repr(self):
  98. request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  99. request.GET = {'get-key': 'get-value'}
  100. request.POST = {'post-key': 'post-value'}
  101. request.COOKIES = {'post-key': 'post-value'}
  102. request.META = {'post-key': 'post-value'}
  103. self.assertEqual(repr(request), str_prefix("<WSGIRequest\npath:/somepath/,\nGET:{%(_)s'get-key': %(_)s'get-value'},\nPOST:{%(_)s'post-key': %(_)s'post-value'},\nCOOKIES:{%(_)s'post-key': %(_)s'post-value'},\nMETA:{%(_)s'post-key': %(_)s'post-value'}>"))
  104. self.assertEqual(build_request_repr(request), repr(request))
  105. self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={'a': 'b'}, POST_override={'c': 'd'}, COOKIES_override={'e': 'f'}, META_override={'g': 'h'}),
  106. str_prefix("<WSGIRequest\npath:/otherpath/,\nGET:{%(_)s'a': %(_)s'b'},\nPOST:{%(_)s'c': %(_)s'd'},\nCOOKIES:{%(_)s'e': %(_)s'f'},\nMETA:{%(_)s'g': %(_)s'h'}>"))
  107. def test_wsgirequest_path_info(self):
  108. def wsgi_str(path_info):
  109. path_info = path_info.encode('utf-8') # Actual URL sent by the browser (bytestring)
  110. if six.PY3:
  111. path_info = path_info.decode('iso-8859-1') # Value in the WSGI environ dict (native string)
  112. return path_info
  113. # Regression for #19468
  114. request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  115. self.assertEqual(request.path, "/سلام/")
  116. def test_parse_cookie(self):
  117. self.assertEqual(parse_cookie('invalid@key=true'), {})
  118. def test_httprequest_location(self):
  119. request = HttpRequest()
  120. self.assertEqual(request.build_absolute_uri(location="https://www.example.com/asdf"),
  121. 'https://www.example.com/asdf')
  122. request.get_host = lambda: 'www.example.com'
  123. request.path = ''
  124. self.assertEqual(request.build_absolute_uri(location="/path/with:colons"),
  125. 'http://www.example.com/path/with:colons')
  126. def test_near_expiration(self):
  127. "Cookie will expire when an near expiration time is provided"
  128. response = HttpResponse()
  129. # There is a timing weakness in this test; The
  130. # expected result for max-age requires that there be
  131. # a very slight difference between the evaluated expiration
  132. # time, and the time evaluated in set_cookie(). If this
  133. # difference doesn't exist, the cookie time will be
  134. # 1 second larger. To avoid the problem, put in a quick sleep,
  135. # which guarantees that there will be a time difference.
  136. expires = datetime.utcnow() + timedelta(seconds=10)
  137. time.sleep(0.001)
  138. response.set_cookie('datetime', expires=expires)
  139. datetime_cookie = response.cookies['datetime']
  140. self.assertEqual(datetime_cookie['max-age'], 10)
  141. def test_aware_expiration(self):
  142. "Cookie accepts an aware datetime as expiration time"
  143. response = HttpResponse()
  144. expires = (datetime.utcnow() + timedelta(seconds=10)).replace(tzinfo=utc)
  145. time.sleep(0.001)
  146. response.set_cookie('datetime', expires=expires)
  147. datetime_cookie = response.cookies['datetime']
  148. self.assertEqual(datetime_cookie['max-age'], 10)
  149. def test_far_expiration(self):
  150. "Cookie will expire when an distant expiration time is provided"
  151. response = HttpResponse()
  152. response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6))
  153. datetime_cookie = response.cookies['datetime']
  154. self.assertEqual(datetime_cookie['expires'], 'Sat, 01-Jan-2028 04:05:06 GMT')
  155. def test_max_age_expiration(self):
  156. "Cookie will expire if max_age is provided"
  157. response = HttpResponse()
  158. response.set_cookie('max_age', max_age=10)
  159. max_age_cookie = response.cookies['max_age']
  160. self.assertEqual(max_age_cookie['max-age'], 10)
  161. self.assertEqual(max_age_cookie['expires'], cookie_date(time.time() + 10))
  162. def test_httponly_cookie(self):
  163. response = HttpResponse()
  164. response.set_cookie('example', httponly=True)
  165. example_cookie = response.cookies['example']
  166. # A compat cookie may be in use -- check that it has worked
  167. # both as an output string, and using the cookie attributes
  168. self.assertTrue('; httponly' in str(example_cookie))
  169. self.assertTrue(example_cookie['httponly'])
  170. def test_limited_stream(self):
  171. # Read all of a limited stream
  172. stream = LimitedStream(BytesIO(b'test'), 2)
  173. self.assertEqual(stream.read(), b'te')
  174. # Reading again returns nothing.
  175. self.assertEqual(stream.read(), b'')
  176. # Read a number of characters greater than the stream has to offer
  177. stream = LimitedStream(BytesIO(b'test'), 2)
  178. self.assertEqual(stream.read(5), b'te')
  179. # Reading again returns nothing.
  180. self.assertEqual(stream.readline(5), b'')
  181. # Read sequentially from a stream
  182. stream = LimitedStream(BytesIO(b'12345678'), 8)
  183. self.assertEqual(stream.read(5), b'12345')
  184. self.assertEqual(stream.read(5), b'678')
  185. # Reading again returns nothing.
  186. self.assertEqual(stream.readline(5), b'')
  187. # Read lines from a stream
  188. stream = LimitedStream(BytesIO(b'1234\n5678\nabcd\nefgh\nijkl'), 24)
  189. # Read a full line, unconditionally
  190. self.assertEqual(stream.readline(), b'1234\n')
  191. # Read a number of characters less than a line
  192. self.assertEqual(stream.readline(2), b'56')
  193. # Read the rest of the partial line
  194. self.assertEqual(stream.readline(), b'78\n')
  195. # Read a full line, with a character limit greater than the line length
  196. self.assertEqual(stream.readline(6), b'abcd\n')
  197. # Read the next line, deliberately terminated at the line end
  198. self.assertEqual(stream.readline(4), b'efgh')
  199. # Read the next line... just the line end
  200. self.assertEqual(stream.readline(), b'\n')
  201. # Read everything else.
  202. self.assertEqual(stream.readline(), b'ijkl')
  203. # Regression for #15018
  204. # If a stream contains a newline, but the provided length
  205. # is less than the number of provided characters, the newline
  206. # doesn't reset the available character count
  207. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
  208. self.assertEqual(stream.readline(10), b'1234\n')
  209. self.assertEqual(stream.readline(3), b'abc')
  210. # Now expire the available characters
  211. self.assertEqual(stream.readline(3), b'd')
  212. # Reading again returns nothing.
  213. self.assertEqual(stream.readline(2), b'')
  214. # Same test, but with read, not readline.
  215. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
  216. self.assertEqual(stream.read(6), b'1234\na')
  217. self.assertEqual(stream.read(2), b'bc')
  218. self.assertEqual(stream.read(2), b'd')
  219. self.assertEqual(stream.read(2), b'')
  220. self.assertEqual(stream.read(), b'')
  221. def test_stream(self):
  222. payload = FakePayload('name=value')
  223. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  224. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  225. 'CONTENT_LENGTH': len(payload),
  226. 'wsgi.input': payload})
  227. self.assertEqual(request.read(), b'name=value')
  228. def test_read_after_value(self):
  229. """
  230. Reading from request is allowed after accessing request contents as
  231. POST or body.
  232. """
  233. payload = FakePayload('name=value')
  234. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  235. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  236. 'CONTENT_LENGTH': len(payload),
  237. 'wsgi.input': payload})
  238. self.assertEqual(request.POST, {'name': ['value']})
  239. self.assertEqual(request.body, b'name=value')
  240. self.assertEqual(request.read(), b'name=value')
  241. def test_value_after_read(self):
  242. """
  243. Construction of POST or body is not allowed after reading
  244. from request.
  245. """
  246. payload = FakePayload('name=value')
  247. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  248. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  249. 'CONTENT_LENGTH': len(payload),
  250. 'wsgi.input': payload})
  251. self.assertEqual(request.read(2), b'na')
  252. self.assertRaises(RawPostDataException, lambda: request.body)
  253. self.assertEqual(request.POST, {})
  254. def test_non_ascii_POST(self):
  255. payload = FakePayload(urlencode({'key': 'España'}))
  256. request = WSGIRequest({
  257. 'REQUEST_METHOD': 'POST',
  258. 'CONTENT_LENGTH': len(payload),
  259. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  260. 'wsgi.input': payload,
  261. })
  262. self.assertEqual(request.POST, {'key': ['España']})
  263. def test_alternate_charset_POST(self):
  264. """
  265. Test a POST with non-utf-8 payload encoding.
  266. """
  267. payload = FakePayload(original_urlencode({'key': 'España'.encode('latin-1')}))
  268. request = WSGIRequest({
  269. 'REQUEST_METHOD': 'POST',
  270. 'CONTENT_LENGTH': len(payload),
  271. 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=iso-8859-1',
  272. 'wsgi.input': payload,
  273. })
  274. self.assertEqual(request.POST, {'key': ['España']})
  275. def test_body_after_POST_multipart_form_data(self):
  276. """
  277. Reading body after parsing multipart/form-data is not allowed
  278. """
  279. # Because multipart is used for large amounts fo data i.e. file uploads,
  280. # we don't want the data held in memory twice, and we don't want to
  281. # silence the error by setting body = '' either.
  282. payload = FakePayload("\r\n".join([
  283. '--boundary',
  284. 'Content-Disposition: form-data; name="name"',
  285. '',
  286. 'value',
  287. '--boundary--'
  288. '']))
  289. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  290. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  291. 'CONTENT_LENGTH': len(payload),
  292. 'wsgi.input': payload})
  293. self.assertEqual(request.POST, {'name': ['value']})
  294. self.assertRaises(RawPostDataException, lambda: request.body)
  295. def test_body_after_POST_multipart_related(self):
  296. """
  297. Reading body after parsing multipart that isn't form-data is allowed
  298. """
  299. # Ticket #9054
  300. # There are cases in which the multipart data is related instead of
  301. # being a binary upload, in which case it should still be accessible
  302. # via body.
  303. payload_data = b"\r\n".join([
  304. b'--boundary',
  305. b'Content-ID: id; name="name"',
  306. b'',
  307. b'value',
  308. b'--boundary--'
  309. b''])
  310. payload = FakePayload(payload_data)
  311. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  312. 'CONTENT_TYPE': 'multipart/related; boundary=boundary',
  313. 'CONTENT_LENGTH': len(payload),
  314. 'wsgi.input': payload})
  315. self.assertEqual(request.POST, {})
  316. self.assertEqual(request.body, payload_data)
  317. def test_POST_multipart_with_content_length_zero(self):
  318. """
  319. Multipart POST requests with Content-Length >= 0 are valid and need to be handled.
  320. """
  321. # According to:
  322. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
  323. # Every request.POST with Content-Length >= 0 is a valid request,
  324. # this test ensures that we handle Content-Length == 0.
  325. payload = FakePayload("\r\n".join([
  326. '--boundary',
  327. 'Content-Disposition: form-data; name="name"',
  328. '',
  329. 'value',
  330. '--boundary--'
  331. '']))
  332. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  333. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  334. 'CONTENT_LENGTH': 0,
  335. 'wsgi.input': payload})
  336. self.assertEqual(request.POST, {})
  337. def test_POST_binary_only(self):
  338. payload = b'\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@'
  339. environ = {'REQUEST_METHOD': 'POST',
  340. 'CONTENT_TYPE': 'application/octet-stream',
  341. 'CONTENT_LENGTH': len(payload),
  342. 'wsgi.input': BytesIO(payload)}
  343. request = WSGIRequest(environ)
  344. self.assertEqual(request.POST, {})
  345. self.assertEqual(request.FILES, {})
  346. self.assertEqual(request.body, payload)
  347. # Same test without specifying content-type
  348. environ.update({'CONTENT_TYPE': '', 'wsgi.input': BytesIO(payload)})
  349. request = WSGIRequest(environ)
  350. self.assertEqual(request.POST, {})
  351. self.assertEqual(request.FILES, {})
  352. self.assertEqual(request.body, payload)
  353. def test_read_by_lines(self):
  354. payload = FakePayload('name=value')
  355. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  356. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  357. 'CONTENT_LENGTH': len(payload),
  358. 'wsgi.input': payload})
  359. self.assertEqual(list(request), [b'name=value'])
  360. def test_POST_after_body_read(self):
  361. """
  362. POST should be populated even if body is read first
  363. """
  364. payload = FakePayload('name=value')
  365. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  366. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  367. 'CONTENT_LENGTH': len(payload),
  368. 'wsgi.input': payload})
  369. request.body # evaluate
  370. self.assertEqual(request.POST, {'name': ['value']})
  371. def test_POST_after_body_read_and_stream_read(self):
  372. """
  373. POST should be populated even if body is read first, and then
  374. the stream is read second.
  375. """
  376. payload = FakePayload('name=value')
  377. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  378. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  379. 'CONTENT_LENGTH': len(payload),
  380. 'wsgi.input': payload})
  381. request.body # evaluate
  382. self.assertEqual(request.read(1), b'n')
  383. self.assertEqual(request.POST, {'name': ['value']})
  384. def test_POST_after_body_read_and_stream_read_multipart(self):
  385. """
  386. POST should be populated even if body is read first, and then
  387. the stream is read second. Using multipart/form-data instead of urlencoded.
  388. """
  389. payload = FakePayload("\r\n".join([
  390. '--boundary',
  391. 'Content-Disposition: form-data; name="name"',
  392. '',
  393. 'value',
  394. '--boundary--'
  395. '']))
  396. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  397. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  398. 'CONTENT_LENGTH': len(payload),
  399. 'wsgi.input': payload})
  400. request.body # evaluate
  401. # Consume enough data to mess up the parsing:
  402. self.assertEqual(request.read(13), b'--boundary\r\nC')
  403. self.assertEqual(request.POST, {'name': ['value']})
  404. def test_POST_connection_error(self):
  405. """
  406. If wsgi.input.read() raises an exception while trying to read() the
  407. POST, the exception should be identifiable (not a generic IOError).
  408. """
  409. class ExplodingBytesIO(BytesIO):
  410. def read(self, len=0):
  411. raise IOError("kaboom!")
  412. payload = b'name=value'
  413. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  414. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  415. 'CONTENT_LENGTH': len(payload),
  416. 'wsgi.input': ExplodingBytesIO(payload)})
  417. with self.assertRaises(UnreadablePostError):
  418. request.body
  419. def test_FILES_connection_error(self):
  420. """
  421. If wsgi.input.read() raises an exception while trying to read() the
  422. FILES, the exception should be identifiable (not a generic IOError).
  423. """
  424. class ExplodingBytesIO(BytesIO):
  425. def read(self, len=0):
  426. raise IOError("kaboom!")
  427. payload = b'x'
  428. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  429. 'CONTENT_TYPE': 'multipart/form-data; boundary=foo_',
  430. 'CONTENT_LENGTH': len(payload),
  431. 'wsgi.input': ExplodingBytesIO(payload)})
  432. with self.assertRaises(UnreadablePostError):
  433. request.FILES
  434. class HostValidationTests(SimpleTestCase):
  435. poisoned_hosts = [
  436. 'example.com@evil.tld',
  437. 'example.com:dr.frankenstein@evil.tld',
  438. 'example.com:dr.frankenstein@evil.tld:80',
  439. 'example.com:80/badpath',
  440. 'example.com: recovermypassword.com',
  441. ]
  442. @override_settings(
  443. USE_X_FORWARDED_HOST=False,
  444. ALLOWED_HOSTS=[
  445. 'forward.com', 'example.com', 'internal.com', '12.34.56.78',
  446. '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com',
  447. '.multitenant.com', 'INSENSITIVE.com',
  448. ])
  449. def test_http_get_host(self):
  450. # Check if X_FORWARDED_HOST is provided.
  451. request = HttpRequest()
  452. request.META = {
  453. 'HTTP_X_FORWARDED_HOST': 'forward.com',
  454. 'HTTP_HOST': 'example.com',
  455. 'SERVER_NAME': 'internal.com',
  456. 'SERVER_PORT': 80,
  457. }
  458. # X_FORWARDED_HOST is ignored.
  459. self.assertEqual(request.get_host(), 'example.com')
  460. # Check if X_FORWARDED_HOST isn't provided.
  461. request = HttpRequest()
  462. request.META = {
  463. 'HTTP_HOST': 'example.com',
  464. 'SERVER_NAME': 'internal.com',
  465. 'SERVER_PORT': 80,
  466. }
  467. self.assertEqual(request.get_host(), 'example.com')
  468. # Check if HTTP_HOST isn't provided.
  469. request = HttpRequest()
  470. request.META = {
  471. 'SERVER_NAME': 'internal.com',
  472. 'SERVER_PORT': 80,
  473. }
  474. self.assertEqual(request.get_host(), 'internal.com')
  475. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  476. request = HttpRequest()
  477. request.META = {
  478. 'SERVER_NAME': 'internal.com',
  479. 'SERVER_PORT': 8042,
  480. }
  481. self.assertEqual(request.get_host(), 'internal.com:8042')
  482. legit_hosts = [
  483. 'example.com',
  484. 'example.com:80',
  485. '12.34.56.78',
  486. '12.34.56.78:443',
  487. '[2001:19f0:feee::dead:beef:cafe]',
  488. '[2001:19f0:feee::dead:beef:cafe]:8080',
  489. 'xn--4ca9at.com', # Punnycode for öäü.com
  490. 'anything.multitenant.com',
  491. 'multitenant.com',
  492. 'insensitive.com',
  493. 'example.com.',
  494. 'example.com.:80',
  495. ]
  496. for host in legit_hosts:
  497. request = HttpRequest()
  498. request.META = {
  499. 'HTTP_HOST': host,
  500. }
  501. request.get_host()
  502. # Poisoned host headers are rejected as suspicious
  503. for host in chain(self.poisoned_hosts, ['other.com', 'example.com..']):
  504. with self.assertRaises(SuspiciousOperation):
  505. request = HttpRequest()
  506. request.META = {
  507. 'HTTP_HOST': host,
  508. }
  509. request.get_host()
  510. @override_settings(USE_X_FORWARDED_HOST=True, ALLOWED_HOSTS=['*'])
  511. def test_http_get_host_with_x_forwarded_host(self):
  512. # Check if X_FORWARDED_HOST is provided.
  513. request = HttpRequest()
  514. request.META = {
  515. 'HTTP_X_FORWARDED_HOST': 'forward.com',
  516. 'HTTP_HOST': 'example.com',
  517. 'SERVER_NAME': 'internal.com',
  518. 'SERVER_PORT': 80,
  519. }
  520. # X_FORWARDED_HOST is obeyed.
  521. self.assertEqual(request.get_host(), 'forward.com')
  522. # Check if X_FORWARDED_HOST isn't provided.
  523. request = HttpRequest()
  524. request.META = {
  525. 'HTTP_HOST': 'example.com',
  526. 'SERVER_NAME': 'internal.com',
  527. 'SERVER_PORT': 80,
  528. }
  529. self.assertEqual(request.get_host(), 'example.com')
  530. # Check if HTTP_HOST isn't provided.
  531. request = HttpRequest()
  532. request.META = {
  533. 'SERVER_NAME': 'internal.com',
  534. 'SERVER_PORT': 80,
  535. }
  536. self.assertEqual(request.get_host(), 'internal.com')
  537. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  538. request = HttpRequest()
  539. request.META = {
  540. 'SERVER_NAME': 'internal.com',
  541. 'SERVER_PORT': 8042,
  542. }
  543. self.assertEqual(request.get_host(), 'internal.com:8042')
  544. # Poisoned host headers are rejected as suspicious
  545. legit_hosts = [
  546. 'example.com',
  547. 'example.com:80',
  548. '12.34.56.78',
  549. '12.34.56.78:443',
  550. '[2001:19f0:feee::dead:beef:cafe]',
  551. '[2001:19f0:feee::dead:beef:cafe]:8080',
  552. 'xn--4ca9at.com', # Punnycode for öäü.com
  553. ]
  554. for host in legit_hosts:
  555. request = HttpRequest()
  556. request.META = {
  557. 'HTTP_HOST': host,
  558. }
  559. request.get_host()
  560. for host in self.poisoned_hosts:
  561. with self.assertRaises(SuspiciousOperation):
  562. request = HttpRequest()
  563. request.META = {
  564. 'HTTP_HOST': host,
  565. }
  566. request.get_host()
  567. @override_settings(DEBUG=True, ALLOWED_HOSTS=[])
  568. def test_host_validation_disabled_in_debug_mode(self):
  569. """If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass."""
  570. request = HttpRequest()
  571. request.META = {
  572. 'HTTP_HOST': 'example.com',
  573. }
  574. self.assertEqual(request.get_host(), 'example.com')
  575. # Invalid hostnames would normally raise a SuspiciousOperation,
  576. # but we have DEBUG=True, so this check is disabled.
  577. request = HttpRequest()
  578. request.META = {
  579. 'HTTP_HOST': "invalid_hostname.com",
  580. }
  581. self.assertEqual(request.get_host(), "invalid_hostname.com")
  582. @override_settings(ALLOWED_HOSTS=[])
  583. def test_get_host_suggestion_of_allowed_host(self):
  584. """get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS."""
  585. msg_invalid_host = "Invalid HTTP_HOST header: %r."
  586. msg_suggestion = msg_invalid_host + "You may need to add %r to ALLOWED_HOSTS."
  587. msg_suggestion2 = msg_invalid_host + "The domain name provided is not valid according to RFC 1034/1035"
  588. for host in [ # Valid-looking hosts
  589. 'example.com',
  590. '12.34.56.78',
  591. '[2001:19f0:feee::dead:beef:cafe]',
  592. 'xn--4ca9at.com', # Punnycode for öäü.com
  593. ]:
  594. request = HttpRequest()
  595. request.META = {'HTTP_HOST': host}
  596. self.assertRaisesMessage(
  597. SuspiciousOperation,
  598. msg_suggestion % (host, host),
  599. request.get_host
  600. )
  601. for domain, port in [ # Valid-looking hosts with a port number
  602. ('example.com', 80),
  603. ('12.34.56.78', 443),
  604. ('[2001:19f0:feee::dead:beef:cafe]', 8080),
  605. ]:
  606. host = '%s:%s' % (domain, port)
  607. request = HttpRequest()
  608. request.META = {'HTTP_HOST': host}
  609. self.assertRaisesMessage(
  610. SuspiciousOperation,
  611. msg_suggestion % (host, domain),
  612. request.get_host
  613. )
  614. for host in self.poisoned_hosts:
  615. request = HttpRequest()
  616. request.META = {'HTTP_HOST': host}
  617. self.assertRaisesMessage(
  618. SuspiciousOperation,
  619. msg_invalid_host % host,
  620. request.get_host
  621. )
  622. request = HttpRequest()
  623. request.META = {'HTTP_HOST': "invalid_hostname.com"}
  624. self.assertRaisesMessage(
  625. SuspiciousOperation,
  626. msg_suggestion2 % "invalid_hostname.com",
  627. request.get_host
  628. )
  629. @skipIf(connection.vendor == 'sqlite'
  630. and connection.settings_dict['TEST']['NAME'] in (None, '', ':memory:'),
  631. "Cannot establish two connections to an in-memory SQLite database.")
  632. class DatabaseConnectionHandlingTests(TransactionTestCase):
  633. available_apps = []
  634. def setUp(self):
  635. # Use a temporary connection to avoid messing with the main one.
  636. self._old_default_connection = connections['default']
  637. del connections['default']
  638. def tearDown(self):
  639. try:
  640. connections['default'].close()
  641. finally:
  642. connections['default'] = self._old_default_connection
  643. def test_request_finished_db_state(self):
  644. # Force closing connection on request end
  645. connection.settings_dict['CONN_MAX_AGE'] = 0
  646. # The GET below will not succeed, but it will give a response with
  647. # defined ._handler_class. That is needed for sending the
  648. # request_finished signal.
  649. response = self.client.get('/')
  650. # Make sure there is an open connection
  651. connection.ensure_connection()
  652. connection.enter_transaction_management()
  653. signals.request_finished.send(sender=response._handler_class)
  654. self.assertEqual(len(connection.transaction_state), 0)
  655. def test_request_finished_failed_connection(self):
  656. # Force closing connection on request end
  657. connection.settings_dict['CONN_MAX_AGE'] = 0
  658. connection.enter_transaction_management()
  659. connection.set_dirty()
  660. # Test that the rollback doesn't succeed (for example network failure
  661. # could cause this).
  662. def fail_horribly():
  663. raise Exception("Horrible failure!")
  664. connection._rollback = fail_horribly
  665. try:
  666. with self.assertRaises(Exception):
  667. signals.request_finished.send(sender=self.__class__)
  668. # The connection's state wasn't cleaned up
  669. self.assertEqual(len(connection.transaction_state), 1)
  670. finally:
  671. del connection._rollback
  672. # The connection will be cleaned on next request where the conn
  673. # works again.
  674. signals.request_finished.send(sender=self.__class__)
  675. self.assertEqual(len(connection.transaction_state), 0)