tests.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. # -*- encoding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import time
  4. from datetime import datetime, timedelta
  5. from io import BytesIO
  6. from itertools import chain
  7. from django.core.exceptions import SuspiciousOperation
  8. from django.core.handlers.wsgi import LimitedStream, WSGIRequest
  9. from django.http import (
  10. HttpRequest, HttpResponse, RawPostDataException, UnreadablePostError,
  11. parse_cookie,
  12. )
  13. from django.test import RequestFactory, SimpleTestCase, override_settings
  14. from django.test.client import FakePayload
  15. from django.test.utils import str_prefix
  16. from django.utils import six
  17. from django.utils.encoding import force_str
  18. from django.utils.http import cookie_date, urlencode
  19. from django.utils.six.moves import http_cookies
  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. # .GET and .POST should be QueryDicts
  30. self.assertEqual(request.GET.urlencode(), '')
  31. self.assertEqual(request.POST.urlencode(), '')
  32. # and FILES should be MultiValueDict
  33. self.assertEqual(request.FILES.getlist('foo'), [])
  34. def test_httprequest_full_path(self):
  35. request = HttpRequest()
  36. request.path = request.path_info = '/;some/?awful/=path/foo:bar/'
  37. request.META['QUERY_STRING'] = ';some=query&+query=string'
  38. expected = '/%3Bsome/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string'
  39. self.assertEqual(request.get_full_path(), expected)
  40. def test_httprequest_full_path_with_query_string_and_fragment(self):
  41. request = HttpRequest()
  42. request.path = request.path_info = '/foo#bar'
  43. request.META['QUERY_STRING'] = 'baz#quux'
  44. self.assertEqual(request.get_full_path(), '/foo%23bar?baz#quux')
  45. def test_httprequest_repr(self):
  46. request = HttpRequest()
  47. request.path = '/somepath/'
  48. request.method = 'GET'
  49. request.GET = {'get-key': 'get-value'}
  50. request.POST = {'post-key': 'post-value'}
  51. request.COOKIES = {'post-key': 'post-value'}
  52. request.META = {'post-key': 'post-value'}
  53. self.assertEqual(repr(request), str_prefix("<HttpRequest: GET '/somepath/'>"))
  54. def test_httprequest_repr_invalid_method_and_path(self):
  55. request = HttpRequest()
  56. self.assertEqual(repr(request), str_prefix("<HttpRequest>"))
  57. request = HttpRequest()
  58. request.method = "GET"
  59. self.assertEqual(repr(request), str_prefix("<HttpRequest>"))
  60. request = HttpRequest()
  61. request.path = ""
  62. self.assertEqual(repr(request), str_prefix("<HttpRequest>"))
  63. def test_wsgirequest(self):
  64. request = WSGIRequest({'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'wsgi.input': BytesIO(b'')})
  65. self.assertEqual(list(request.GET.keys()), [])
  66. self.assertEqual(list(request.POST.keys()), [])
  67. self.assertEqual(list(request.COOKIES.keys()), [])
  68. self.assertEqual(set(request.META.keys()), {'PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'wsgi.input'})
  69. self.assertEqual(request.META['PATH_INFO'], 'bogus')
  70. self.assertEqual(request.META['REQUEST_METHOD'], 'bogus')
  71. self.assertEqual(request.META['SCRIPT_NAME'], '')
  72. def test_wsgirequest_with_script_name(self):
  73. """
  74. Ensure that the request's path is correctly assembled, regardless of
  75. whether or not the SCRIPT_NAME has a trailing slash.
  76. Refs #20169.
  77. """
  78. # With trailing slash
  79. request = WSGIRequest({
  80. 'PATH_INFO': '/somepath/',
  81. 'SCRIPT_NAME': '/PREFIX/',
  82. 'REQUEST_METHOD': 'get',
  83. 'wsgi.input': BytesIO(b''),
  84. })
  85. self.assertEqual(request.path, '/PREFIX/somepath/')
  86. # Without trailing slash
  87. request = WSGIRequest({
  88. 'PATH_INFO': '/somepath/',
  89. 'SCRIPT_NAME': '/PREFIX',
  90. 'REQUEST_METHOD': 'get',
  91. 'wsgi.input': BytesIO(b''),
  92. })
  93. self.assertEqual(request.path, '/PREFIX/somepath/')
  94. def test_wsgirequest_script_url_double_slashes(self):
  95. """
  96. WSGI squashes multiple successive slashes in PATH_INFO, WSGIRequest
  97. should take that into account when populating request.path and
  98. request.META['SCRIPT_NAME'].
  99. Refs #17133.
  100. """
  101. request = WSGIRequest({
  102. 'SCRIPT_URL': '/mst/milestones//accounts/login//help',
  103. 'PATH_INFO': '/milestones/accounts/login/help',
  104. 'REQUEST_METHOD': 'get',
  105. 'wsgi.input': BytesIO(b''),
  106. })
  107. self.assertEqual(request.path, '/mst/milestones/accounts/login/help')
  108. self.assertEqual(request.META['SCRIPT_NAME'], '/mst')
  109. def test_wsgirequest_with_force_script_name(self):
  110. """
  111. Ensure that the FORCE_SCRIPT_NAME setting takes precedence over the
  112. request's SCRIPT_NAME environment parameter.
  113. Refs #20169.
  114. """
  115. with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
  116. request = WSGIRequest({
  117. 'PATH_INFO': '/somepath/',
  118. 'SCRIPT_NAME': '/PREFIX/',
  119. 'REQUEST_METHOD': 'get',
  120. 'wsgi.input': BytesIO(b''),
  121. })
  122. self.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
  123. def test_wsgirequest_path_with_force_script_name_trailing_slash(self):
  124. """
  125. Ensure that the request's path is correctly assembled, regardless of
  126. whether or not the FORCE_SCRIPT_NAME setting has a trailing slash.
  127. Refs #20169.
  128. """
  129. # With trailing slash
  130. with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
  131. request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  132. self.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
  133. # Without trailing slash
  134. with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX'):
  135. request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  136. self.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
  137. def test_wsgirequest_repr(self):
  138. request = WSGIRequest({'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  139. self.assertEqual(repr(request), str_prefix("<WSGIRequest: GET '/'>"))
  140. request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  141. request.GET = {'get-key': 'get-value'}
  142. request.POST = {'post-key': 'post-value'}
  143. request.COOKIES = {'post-key': 'post-value'}
  144. request.META = {'post-key': 'post-value'}
  145. self.assertEqual(repr(request), str_prefix("<WSGIRequest: GET '/somepath/'>"))
  146. def test_wsgirequest_path_info(self):
  147. def wsgi_str(path_info):
  148. path_info = path_info.encode('utf-8') # Actual URL sent by the browser (bytestring)
  149. if six.PY3:
  150. path_info = path_info.decode('iso-8859-1') # Value in the WSGI environ dict (native string)
  151. return path_info
  152. # Regression for #19468
  153. request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  154. self.assertEqual(request.path, "/سلام/")
  155. def test_parse_cookie(self):
  156. self.assertEqual(parse_cookie('invalid@key=true'), {})
  157. def test_httprequest_location(self):
  158. request = HttpRequest()
  159. self.assertEqual(request.build_absolute_uri(location="https://www.example.com/asdf"),
  160. 'https://www.example.com/asdf')
  161. request.get_host = lambda: 'www.example.com'
  162. request.path = ''
  163. self.assertEqual(request.build_absolute_uri(location="/path/with:colons"),
  164. 'http://www.example.com/path/with:colons')
  165. def test_near_expiration(self):
  166. "Cookie will expire when an near expiration time is provided"
  167. response = HttpResponse()
  168. # There is a timing weakness in this test; The
  169. # expected result for max-age requires that there be
  170. # a very slight difference between the evaluated expiration
  171. # time, and the time evaluated in set_cookie(). If this
  172. # difference doesn't exist, the cookie time will be
  173. # 1 second larger. To avoid the problem, put in a quick sleep,
  174. # which guarantees that there will be a time difference.
  175. expires = datetime.utcnow() + timedelta(seconds=10)
  176. time.sleep(0.001)
  177. response.set_cookie('datetime', expires=expires)
  178. datetime_cookie = response.cookies['datetime']
  179. self.assertEqual(datetime_cookie['max-age'], 10)
  180. def test_aware_expiration(self):
  181. "Cookie accepts an aware datetime as expiration time"
  182. response = HttpResponse()
  183. expires = (datetime.utcnow() + timedelta(seconds=10)).replace(tzinfo=utc)
  184. time.sleep(0.001)
  185. response.set_cookie('datetime', expires=expires)
  186. datetime_cookie = response.cookies['datetime']
  187. self.assertEqual(datetime_cookie['max-age'], 10)
  188. def test_create_cookie_after_deleting_cookie(self):
  189. """
  190. Setting a cookie after deletion should clear the expiry date.
  191. """
  192. response = HttpResponse()
  193. response.set_cookie('c', 'old-value')
  194. self.assertEqual(response.cookies['c']['expires'], '')
  195. response.delete_cookie('c')
  196. self.assertEqual(response.cookies['c']['expires'], 'Thu, 01-Jan-1970 00:00:00 GMT')
  197. response.set_cookie('c', 'new-value')
  198. self.assertEqual(response.cookies['c']['expires'], '')
  199. def test_far_expiration(self):
  200. "Cookie will expire when an distant expiration time is provided"
  201. response = HttpResponse()
  202. response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6))
  203. datetime_cookie = response.cookies['datetime']
  204. self.assertIn(
  205. datetime_cookie['expires'],
  206. # Slight time dependency; refs #23450
  207. ('Sat, 01-Jan-2028 04:05:06 GMT', 'Sat, 01-Jan-2028 04:05:07 GMT')
  208. )
  209. def test_max_age_expiration(self):
  210. "Cookie will expire if max_age is provided"
  211. response = HttpResponse()
  212. response.set_cookie('max_age', max_age=10)
  213. max_age_cookie = response.cookies['max_age']
  214. self.assertEqual(max_age_cookie['max-age'], 10)
  215. self.assertEqual(max_age_cookie['expires'], cookie_date(time.time() + 10))
  216. def test_httponly_cookie(self):
  217. response = HttpResponse()
  218. response.set_cookie('example', httponly=True)
  219. example_cookie = response.cookies['example']
  220. # A compat cookie may be in use -- check that it has worked
  221. # both as an output string, and using the cookie attributes
  222. self.assertIn('; %s' % http_cookies.Morsel._reserved['httponly'], str(example_cookie))
  223. self.assertTrue(example_cookie['httponly'])
  224. def test_unicode_cookie(self):
  225. "Verify HttpResponse.set_cookie() works with unicode data."
  226. response = HttpResponse()
  227. cookie_value = '清風'
  228. response.set_cookie('test', cookie_value)
  229. self.assertEqual(force_str(cookie_value), response.cookies['test'].value)
  230. def test_limited_stream(self):
  231. # Read all of a limited stream
  232. stream = LimitedStream(BytesIO(b'test'), 2)
  233. self.assertEqual(stream.read(), b'te')
  234. # Reading again returns nothing.
  235. self.assertEqual(stream.read(), b'')
  236. # Read a number of characters greater than the stream has to offer
  237. stream = LimitedStream(BytesIO(b'test'), 2)
  238. self.assertEqual(stream.read(5), b'te')
  239. # Reading again returns nothing.
  240. self.assertEqual(stream.readline(5), b'')
  241. # Read sequentially from a stream
  242. stream = LimitedStream(BytesIO(b'12345678'), 8)
  243. self.assertEqual(stream.read(5), b'12345')
  244. self.assertEqual(stream.read(5), b'678')
  245. # Reading again returns nothing.
  246. self.assertEqual(stream.readline(5), b'')
  247. # Read lines from a stream
  248. stream = LimitedStream(BytesIO(b'1234\n5678\nabcd\nefgh\nijkl'), 24)
  249. # Read a full line, unconditionally
  250. self.assertEqual(stream.readline(), b'1234\n')
  251. # Read a number of characters less than a line
  252. self.assertEqual(stream.readline(2), b'56')
  253. # Read the rest of the partial line
  254. self.assertEqual(stream.readline(), b'78\n')
  255. # Read a full line, with a character limit greater than the line length
  256. self.assertEqual(stream.readline(6), b'abcd\n')
  257. # Read the next line, deliberately terminated at the line end
  258. self.assertEqual(stream.readline(4), b'efgh')
  259. # Read the next line... just the line end
  260. self.assertEqual(stream.readline(), b'\n')
  261. # Read everything else.
  262. self.assertEqual(stream.readline(), b'ijkl')
  263. # Regression for #15018
  264. # If a stream contains a newline, but the provided length
  265. # is less than the number of provided characters, the newline
  266. # doesn't reset the available character count
  267. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
  268. self.assertEqual(stream.readline(10), b'1234\n')
  269. self.assertEqual(stream.readline(3), b'abc')
  270. # Now expire the available characters
  271. self.assertEqual(stream.readline(3), b'd')
  272. # Reading again returns nothing.
  273. self.assertEqual(stream.readline(2), b'')
  274. # Same test, but with read, not readline.
  275. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
  276. self.assertEqual(stream.read(6), b'1234\na')
  277. self.assertEqual(stream.read(2), b'bc')
  278. self.assertEqual(stream.read(2), b'd')
  279. self.assertEqual(stream.read(2), b'')
  280. self.assertEqual(stream.read(), b'')
  281. def test_stream(self):
  282. payload = FakePayload('name=value')
  283. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  284. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  285. 'CONTENT_LENGTH': len(payload),
  286. 'wsgi.input': payload})
  287. self.assertEqual(request.read(), b'name=value')
  288. def test_read_after_value(self):
  289. """
  290. Reading from request is allowed after accessing request contents as
  291. POST or body.
  292. """
  293. payload = FakePayload('name=value')
  294. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  295. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  296. 'CONTENT_LENGTH': len(payload),
  297. 'wsgi.input': payload})
  298. self.assertEqual(request.POST, {'name': ['value']})
  299. self.assertEqual(request.body, b'name=value')
  300. self.assertEqual(request.read(), b'name=value')
  301. def test_value_after_read(self):
  302. """
  303. Construction of POST or body is not allowed after reading
  304. from request.
  305. """
  306. payload = FakePayload('name=value')
  307. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  308. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  309. 'CONTENT_LENGTH': len(payload),
  310. 'wsgi.input': payload})
  311. self.assertEqual(request.read(2), b'na')
  312. self.assertRaises(RawPostDataException, lambda: request.body)
  313. self.assertEqual(request.POST, {})
  314. def test_non_ascii_POST(self):
  315. payload = FakePayload(urlencode({'key': 'España'}))
  316. request = WSGIRequest({
  317. 'REQUEST_METHOD': 'POST',
  318. 'CONTENT_LENGTH': len(payload),
  319. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  320. 'wsgi.input': payload,
  321. })
  322. self.assertEqual(request.POST, {'key': ['España']})
  323. def test_alternate_charset_POST(self):
  324. """
  325. Test a POST with non-utf-8 payload encoding.
  326. """
  327. payload = FakePayload(original_urlencode({'key': 'España'.encode('latin-1')}))
  328. request = WSGIRequest({
  329. 'REQUEST_METHOD': 'POST',
  330. 'CONTENT_LENGTH': len(payload),
  331. 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=iso-8859-1',
  332. 'wsgi.input': payload,
  333. })
  334. self.assertEqual(request.POST, {'key': ['España']})
  335. def test_body_after_POST_multipart_form_data(self):
  336. """
  337. Reading body after parsing multipart/form-data is not allowed
  338. """
  339. # Because multipart is used for large amounts of data i.e. file uploads,
  340. # we don't want the data held in memory twice, and we don't want to
  341. # silence the error by setting body = '' either.
  342. payload = FakePayload("\r\n".join([
  343. '--boundary',
  344. 'Content-Disposition: form-data; name="name"',
  345. '',
  346. 'value',
  347. '--boundary--'
  348. '']))
  349. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  350. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  351. 'CONTENT_LENGTH': len(payload),
  352. 'wsgi.input': payload})
  353. self.assertEqual(request.POST, {'name': ['value']})
  354. self.assertRaises(RawPostDataException, lambda: request.body)
  355. def test_body_after_POST_multipart_related(self):
  356. """
  357. Reading body after parsing multipart that isn't form-data is allowed
  358. """
  359. # Ticket #9054
  360. # There are cases in which the multipart data is related instead of
  361. # being a binary upload, in which case it should still be accessible
  362. # via body.
  363. payload_data = b"\r\n".join([
  364. b'--boundary',
  365. b'Content-ID: id; name="name"',
  366. b'',
  367. b'value',
  368. b'--boundary--'
  369. b''])
  370. payload = FakePayload(payload_data)
  371. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  372. 'CONTENT_TYPE': 'multipart/related; boundary=boundary',
  373. 'CONTENT_LENGTH': len(payload),
  374. 'wsgi.input': payload})
  375. self.assertEqual(request.POST, {})
  376. self.assertEqual(request.body, payload_data)
  377. def test_POST_multipart_with_content_length_zero(self):
  378. """
  379. Multipart POST requests with Content-Length >= 0 are valid and need to be handled.
  380. """
  381. # According to:
  382. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
  383. # Every request.POST with Content-Length >= 0 is a valid request,
  384. # this test ensures that we handle Content-Length == 0.
  385. payload = FakePayload("\r\n".join([
  386. '--boundary',
  387. 'Content-Disposition: form-data; name="name"',
  388. '',
  389. 'value',
  390. '--boundary--'
  391. '']))
  392. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  393. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  394. 'CONTENT_LENGTH': 0,
  395. 'wsgi.input': payload})
  396. self.assertEqual(request.POST, {})
  397. def test_POST_binary_only(self):
  398. payload = b'\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@'
  399. environ = {'REQUEST_METHOD': 'POST',
  400. 'CONTENT_TYPE': 'application/octet-stream',
  401. 'CONTENT_LENGTH': len(payload),
  402. 'wsgi.input': BytesIO(payload)}
  403. request = WSGIRequest(environ)
  404. self.assertEqual(request.POST, {})
  405. self.assertEqual(request.FILES, {})
  406. self.assertEqual(request.body, payload)
  407. # Same test without specifying content-type
  408. environ.update({'CONTENT_TYPE': '', 'wsgi.input': BytesIO(payload)})
  409. request = WSGIRequest(environ)
  410. self.assertEqual(request.POST, {})
  411. self.assertEqual(request.FILES, {})
  412. self.assertEqual(request.body, payload)
  413. def test_read_by_lines(self):
  414. payload = FakePayload('name=value')
  415. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  416. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  417. 'CONTENT_LENGTH': len(payload),
  418. 'wsgi.input': payload})
  419. self.assertEqual(list(request), [b'name=value'])
  420. def test_POST_after_body_read(self):
  421. """
  422. POST should be populated even if body is read first
  423. """
  424. payload = FakePayload('name=value')
  425. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  426. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  427. 'CONTENT_LENGTH': len(payload),
  428. 'wsgi.input': payload})
  429. request.body # evaluate
  430. self.assertEqual(request.POST, {'name': ['value']})
  431. def test_POST_after_body_read_and_stream_read(self):
  432. """
  433. POST should be populated even if body is read first, and then
  434. the stream is read second.
  435. """
  436. payload = FakePayload('name=value')
  437. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  438. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  439. 'CONTENT_LENGTH': len(payload),
  440. 'wsgi.input': payload})
  441. request.body # evaluate
  442. self.assertEqual(request.read(1), b'n')
  443. self.assertEqual(request.POST, {'name': ['value']})
  444. def test_POST_after_body_read_and_stream_read_multipart(self):
  445. """
  446. POST should be populated even if body is read first, and then
  447. the stream is read second. Using multipart/form-data instead of urlencoded.
  448. """
  449. payload = FakePayload("\r\n".join([
  450. '--boundary',
  451. 'Content-Disposition: form-data; name="name"',
  452. '',
  453. 'value',
  454. '--boundary--'
  455. '']))
  456. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  457. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  458. 'CONTENT_LENGTH': len(payload),
  459. 'wsgi.input': payload})
  460. request.body # evaluate
  461. # Consume enough data to mess up the parsing:
  462. self.assertEqual(request.read(13), b'--boundary\r\nC')
  463. self.assertEqual(request.POST, {'name': ['value']})
  464. def test_POST_connection_error(self):
  465. """
  466. If wsgi.input.read() raises an exception while trying to read() the
  467. POST, the exception should be identifiable (not a generic IOError).
  468. """
  469. class ExplodingBytesIO(BytesIO):
  470. def read(self, len=0):
  471. raise IOError("kaboom!")
  472. payload = b'name=value'
  473. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  474. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  475. 'CONTENT_LENGTH': len(payload),
  476. 'wsgi.input': ExplodingBytesIO(payload)})
  477. with self.assertRaises(UnreadablePostError):
  478. request.body
  479. def test_FILES_connection_error(self):
  480. """
  481. If wsgi.input.read() raises an exception while trying to read() the
  482. FILES, the exception should be identifiable (not a generic IOError).
  483. """
  484. class ExplodingBytesIO(BytesIO):
  485. def read(self, len=0):
  486. raise IOError("kaboom!")
  487. payload = b'x'
  488. request = WSGIRequest({'REQUEST_METHOD': 'POST',
  489. 'CONTENT_TYPE': 'multipart/form-data; boundary=foo_',
  490. 'CONTENT_LENGTH': len(payload),
  491. 'wsgi.input': ExplodingBytesIO(payload)})
  492. with self.assertRaises(UnreadablePostError):
  493. request.FILES
  494. @override_settings(ALLOWED_HOSTS=['example.com'])
  495. def test_get_raw_uri(self):
  496. factory = RequestFactory(HTTP_HOST='evil.com')
  497. request = factory.get('////absolute-uri')
  498. self.assertEqual(request.get_raw_uri(), 'http://evil.com//absolute-uri')
  499. request = factory.get('/?foo=bar')
  500. self.assertEqual(request.get_raw_uri(), 'http://evil.com/?foo=bar')
  501. request = factory.get('/path/with:colons')
  502. self.assertEqual(request.get_raw_uri(), 'http://evil.com/path/with:colons')
  503. class HostValidationTests(SimpleTestCase):
  504. poisoned_hosts = [
  505. 'example.com@evil.tld',
  506. 'example.com:dr.frankenstein@evil.tld',
  507. 'example.com:dr.frankenstein@evil.tld:80',
  508. 'example.com:80/badpath',
  509. 'example.com: recovermypassword.com',
  510. ]
  511. @override_settings(
  512. USE_X_FORWARDED_HOST=False,
  513. ALLOWED_HOSTS=[
  514. 'forward.com', 'example.com', 'internal.com', '12.34.56.78',
  515. '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com',
  516. '.multitenant.com', 'INSENSITIVE.com',
  517. ])
  518. def test_http_get_host(self):
  519. # Check if X_FORWARDED_HOST is provided.
  520. request = HttpRequest()
  521. request.META = {
  522. 'HTTP_X_FORWARDED_HOST': 'forward.com',
  523. 'HTTP_HOST': 'example.com',
  524. 'SERVER_NAME': 'internal.com',
  525. 'SERVER_PORT': 80,
  526. }
  527. # X_FORWARDED_HOST is ignored.
  528. self.assertEqual(request.get_host(), 'example.com')
  529. # Check if X_FORWARDED_HOST isn't provided.
  530. request = HttpRequest()
  531. request.META = {
  532. 'HTTP_HOST': 'example.com',
  533. 'SERVER_NAME': 'internal.com',
  534. 'SERVER_PORT': 80,
  535. }
  536. self.assertEqual(request.get_host(), 'example.com')
  537. # Check if HTTP_HOST isn't provided.
  538. request = HttpRequest()
  539. request.META = {
  540. 'SERVER_NAME': 'internal.com',
  541. 'SERVER_PORT': 80,
  542. }
  543. self.assertEqual(request.get_host(), 'internal.com')
  544. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  545. request = HttpRequest()
  546. request.META = {
  547. 'SERVER_NAME': 'internal.com',
  548. 'SERVER_PORT': 8042,
  549. }
  550. self.assertEqual(request.get_host(), 'internal.com:8042')
  551. legit_hosts = [
  552. 'example.com',
  553. 'example.com:80',
  554. '12.34.56.78',
  555. '12.34.56.78:443',
  556. '[2001:19f0:feee::dead:beef:cafe]',
  557. '[2001:19f0:feee::dead:beef:cafe]:8080',
  558. 'xn--4ca9at.com', # Punycode for öäü.com
  559. 'anything.multitenant.com',
  560. 'multitenant.com',
  561. 'insensitive.com',
  562. 'example.com.',
  563. 'example.com.:80',
  564. ]
  565. for host in legit_hosts:
  566. request = HttpRequest()
  567. request.META = {
  568. 'HTTP_HOST': host,
  569. }
  570. request.get_host()
  571. # Poisoned host headers are rejected as suspicious
  572. for host in chain(self.poisoned_hosts, ['other.com', 'example.com..']):
  573. with self.assertRaises(SuspiciousOperation):
  574. request = HttpRequest()
  575. request.META = {
  576. 'HTTP_HOST': host,
  577. }
  578. request.get_host()
  579. @override_settings(USE_X_FORWARDED_HOST=True, ALLOWED_HOSTS=['*'])
  580. def test_http_get_host_with_x_forwarded_host(self):
  581. # Check if X_FORWARDED_HOST is provided.
  582. request = HttpRequest()
  583. request.META = {
  584. 'HTTP_X_FORWARDED_HOST': 'forward.com',
  585. 'HTTP_HOST': 'example.com',
  586. 'SERVER_NAME': 'internal.com',
  587. 'SERVER_PORT': 80,
  588. }
  589. # X_FORWARDED_HOST is obeyed.
  590. self.assertEqual(request.get_host(), 'forward.com')
  591. # Check if X_FORWARDED_HOST isn't provided.
  592. request = HttpRequest()
  593. request.META = {
  594. 'HTTP_HOST': 'example.com',
  595. 'SERVER_NAME': 'internal.com',
  596. 'SERVER_PORT': 80,
  597. }
  598. self.assertEqual(request.get_host(), 'example.com')
  599. # Check if HTTP_HOST isn't provided.
  600. request = HttpRequest()
  601. request.META = {
  602. 'SERVER_NAME': 'internal.com',
  603. 'SERVER_PORT': 80,
  604. }
  605. self.assertEqual(request.get_host(), 'internal.com')
  606. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  607. request = HttpRequest()
  608. request.META = {
  609. 'SERVER_NAME': 'internal.com',
  610. 'SERVER_PORT': 8042,
  611. }
  612. self.assertEqual(request.get_host(), 'internal.com:8042')
  613. # Poisoned host headers are rejected as suspicious
  614. legit_hosts = [
  615. 'example.com',
  616. 'example.com:80',
  617. '12.34.56.78',
  618. '12.34.56.78:443',
  619. '[2001:19f0:feee::dead:beef:cafe]',
  620. '[2001:19f0:feee::dead:beef:cafe]:8080',
  621. 'xn--4ca9at.com', # Punycode for öäü.com
  622. ]
  623. for host in legit_hosts:
  624. request = HttpRequest()
  625. request.META = {
  626. 'HTTP_HOST': host,
  627. }
  628. request.get_host()
  629. for host in self.poisoned_hosts:
  630. with self.assertRaises(SuspiciousOperation):
  631. request = HttpRequest()
  632. request.META = {
  633. 'HTTP_HOST': host,
  634. }
  635. request.get_host()
  636. @override_settings(USE_X_FORWARDED_PORT=False)
  637. def test_get_port(self):
  638. request = HttpRequest()
  639. request.META = {
  640. 'SERVER_PORT': '8080',
  641. 'HTTP_X_FORWARDED_PORT': '80',
  642. }
  643. # Shouldn't use the X-Forwarded-Port header
  644. self.assertEqual(request.get_port(), '8080')
  645. request = HttpRequest()
  646. request.META = {
  647. 'SERVER_PORT': '8080',
  648. }
  649. self.assertEqual(request.get_port(), '8080')
  650. @override_settings(USE_X_FORWARDED_PORT=True)
  651. def test_get_port_with_x_forwarded_port(self):
  652. request = HttpRequest()
  653. request.META = {
  654. 'SERVER_PORT': '8080',
  655. 'HTTP_X_FORWARDED_PORT': '80',
  656. }
  657. # Should use the X-Forwarded-Port header
  658. self.assertEqual(request.get_port(), '80')
  659. request = HttpRequest()
  660. request.META = {
  661. 'SERVER_PORT': '8080',
  662. }
  663. self.assertEqual(request.get_port(), '8080')
  664. @override_settings(DEBUG=True, ALLOWED_HOSTS=[])
  665. def test_host_validation_disabled_in_debug_mode(self):
  666. """If ALLOWED_HOSTS is empty and DEBUG is True, all hosts pass."""
  667. request = HttpRequest()
  668. request.META = {
  669. 'HTTP_HOST': 'example.com',
  670. }
  671. self.assertEqual(request.get_host(), 'example.com')
  672. # Invalid hostnames would normally raise a SuspiciousOperation,
  673. # but we have DEBUG=True, so this check is disabled.
  674. request = HttpRequest()
  675. request.META = {
  676. 'HTTP_HOST': "invalid_hostname.com",
  677. }
  678. self.assertEqual(request.get_host(), "invalid_hostname.com")
  679. @override_settings(ALLOWED_HOSTS=[])
  680. def test_get_host_suggestion_of_allowed_host(self):
  681. """get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS."""
  682. msg_invalid_host = "Invalid HTTP_HOST header: %r."
  683. msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS."
  684. msg_suggestion2 = msg_invalid_host + " The domain name provided is not valid according to RFC 1034/1035"
  685. for host in [ # Valid-looking hosts
  686. 'example.com',
  687. '12.34.56.78',
  688. '[2001:19f0:feee::dead:beef:cafe]',
  689. 'xn--4ca9at.com', # Punycode for öäü.com
  690. ]:
  691. request = HttpRequest()
  692. request.META = {'HTTP_HOST': host}
  693. self.assertRaisesMessage(
  694. SuspiciousOperation,
  695. msg_suggestion % (host, host),
  696. request.get_host
  697. )
  698. for domain, port in [ # Valid-looking hosts with a port number
  699. ('example.com', 80),
  700. ('12.34.56.78', 443),
  701. ('[2001:19f0:feee::dead:beef:cafe]', 8080),
  702. ]:
  703. host = '%s:%s' % (domain, port)
  704. request = HttpRequest()
  705. request.META = {'HTTP_HOST': host}
  706. self.assertRaisesMessage(
  707. SuspiciousOperation,
  708. msg_suggestion % (host, domain),
  709. request.get_host
  710. )
  711. for host in self.poisoned_hosts:
  712. request = HttpRequest()
  713. request.META = {'HTTP_HOST': host}
  714. self.assertRaisesMessage(
  715. SuspiciousOperation,
  716. msg_invalid_host % host,
  717. request.get_host
  718. )
  719. request = HttpRequest()
  720. request.META = {'HTTP_HOST': "invalid_hostname.com"}
  721. self.assertRaisesMessage(
  722. SuspiciousOperation,
  723. msg_suggestion2 % "invalid_hostname.com",
  724. request.get_host
  725. )
  726. class BuildAbsoluteURITestCase(SimpleTestCase):
  727. """
  728. Regression tests for ticket #18314.
  729. """
  730. def setUp(self):
  731. self.factory = RequestFactory()
  732. def test_build_absolute_uri_no_location(self):
  733. """
  734. Ensures that ``request.build_absolute_uri()`` returns the proper value
  735. when the ``location`` argument is not provided, and ``request.path``
  736. begins with //.
  737. """
  738. # //// is needed to create a request with a path beginning with //
  739. request = self.factory.get('////absolute-uri')
  740. self.assertEqual(
  741. request.build_absolute_uri(),
  742. 'http://testserver//absolute-uri'
  743. )
  744. def test_build_absolute_uri_absolute_location(self):
  745. """
  746. Ensures that ``request.build_absolute_uri()`` returns the proper value
  747. when an absolute URL ``location`` argument is provided, and
  748. ``request.path`` begins with //.
  749. """
  750. # //// is needed to create a request with a path beginning with //
  751. request = self.factory.get('////absolute-uri')
  752. self.assertEqual(
  753. request.build_absolute_uri(location='http://example.com/?foo=bar'),
  754. 'http://example.com/?foo=bar'
  755. )
  756. def test_build_absolute_uri_schema_relative_location(self):
  757. """
  758. Ensures that ``request.build_absolute_uri()`` returns the proper value
  759. when a schema-relative URL ``location`` argument is provided, and
  760. ``request.path`` begins with //.
  761. """
  762. # //// is needed to create a request with a path beginning with //
  763. request = self.factory.get('////absolute-uri')
  764. self.assertEqual(
  765. request.build_absolute_uri(location='//example.com/?foo=bar'),
  766. 'http://example.com/?foo=bar'
  767. )
  768. def test_build_absolute_uri_relative_location(self):
  769. """
  770. Ensures that ``request.build_absolute_uri()`` returns the proper value
  771. when a relative URL ``location`` argument is provided, and
  772. ``request.path`` begins with //.
  773. """
  774. # //// is needed to create a request with a path beginning with //
  775. request = self.factory.get('////absolute-uri')
  776. self.assertEqual(
  777. request.build_absolute_uri(location='/foo/bar/'),
  778. 'http://testserver/foo/bar/'
  779. )