tests.py 31 KB

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