tests.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. from io import BytesIO
  2. from itertools import chain
  3. from urllib.parse import urlencode
  4. from django.core.exceptions import DisallowedHost
  5. from django.core.handlers.wsgi import LimitedStream, WSGIRequest
  6. from django.http import HttpRequest, RawPostDataException, UnreadablePostError
  7. from django.http.request import HttpHeaders, split_domain_port
  8. from django.test import RequestFactory, SimpleTestCase, override_settings
  9. from django.test.client import FakePayload
  10. class RequestsTests(SimpleTestCase):
  11. def test_httprequest(self):
  12. request = HttpRequest()
  13. self.assertEqual(list(request.GET), [])
  14. self.assertEqual(list(request.POST), [])
  15. self.assertEqual(list(request.COOKIES), [])
  16. self.assertEqual(list(request.META), [])
  17. # .GET and .POST should be QueryDicts
  18. self.assertEqual(request.GET.urlencode(), '')
  19. self.assertEqual(request.POST.urlencode(), '')
  20. # and FILES should be MultiValueDict
  21. self.assertEqual(request.FILES.getlist('foo'), [])
  22. self.assertIsNone(request.content_type)
  23. self.assertIsNone(request.content_params)
  24. def test_httprequest_full_path(self):
  25. request = HttpRequest()
  26. request.path = '/;some/?awful/=path/foo:bar/'
  27. request.path_info = '/prefix' + request.path
  28. request.META['QUERY_STRING'] = ';some=query&+query=string'
  29. expected = '/%3Bsome/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string'
  30. self.assertEqual(request.get_full_path(), expected)
  31. self.assertEqual(request.get_full_path_info(), '/prefix' + expected)
  32. def test_httprequest_full_path_with_query_string_and_fragment(self):
  33. request = HttpRequest()
  34. request.path = '/foo#bar'
  35. request.path_info = '/prefix' + request.path
  36. request.META['QUERY_STRING'] = 'baz#quux'
  37. self.assertEqual(request.get_full_path(), '/foo%23bar?baz#quux')
  38. self.assertEqual(request.get_full_path_info(), '/prefix/foo%23bar?baz#quux')
  39. def test_httprequest_repr(self):
  40. request = HttpRequest()
  41. request.path = '/somepath/'
  42. request.method = 'GET'
  43. request.GET = {'get-key': 'get-value'}
  44. request.POST = {'post-key': 'post-value'}
  45. request.COOKIES = {'post-key': 'post-value'}
  46. request.META = {'post-key': 'post-value'}
  47. self.assertEqual(repr(request), "<HttpRequest: GET '/somepath/'>")
  48. def test_httprequest_repr_invalid_method_and_path(self):
  49. request = HttpRequest()
  50. self.assertEqual(repr(request), "<HttpRequest>")
  51. request = HttpRequest()
  52. request.method = "GET"
  53. self.assertEqual(repr(request), "<HttpRequest>")
  54. request = HttpRequest()
  55. request.path = ""
  56. self.assertEqual(repr(request), "<HttpRequest>")
  57. def test_wsgirequest(self):
  58. request = WSGIRequest({
  59. 'PATH_INFO': 'bogus',
  60. 'REQUEST_METHOD': 'bogus',
  61. 'CONTENT_TYPE': 'text/html; charset=utf8',
  62. 'wsgi.input': BytesIO(b''),
  63. })
  64. self.assertEqual(list(request.GET), [])
  65. self.assertEqual(list(request.POST), [])
  66. self.assertEqual(list(request.COOKIES), [])
  67. self.assertEqual(
  68. set(request.META),
  69. {'PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'CONTENT_TYPE', 'wsgi.input'}
  70. )
  71. self.assertEqual(request.META['PATH_INFO'], 'bogus')
  72. self.assertEqual(request.META['REQUEST_METHOD'], 'bogus')
  73. self.assertEqual(request.META['SCRIPT_NAME'], '')
  74. self.assertEqual(request.content_type, 'text/html')
  75. self.assertEqual(request.content_params, {'charset': 'utf8'})
  76. def test_wsgirequest_with_script_name(self):
  77. """
  78. The request's path is correctly assembled, regardless of whether or
  79. not the SCRIPT_NAME has a trailing slash (#20169).
  80. """
  81. # With trailing slash
  82. request = WSGIRequest({
  83. 'PATH_INFO': '/somepath/',
  84. 'SCRIPT_NAME': '/PREFIX/',
  85. 'REQUEST_METHOD': 'get',
  86. 'wsgi.input': BytesIO(b''),
  87. })
  88. self.assertEqual(request.path, '/PREFIX/somepath/')
  89. # Without trailing slash
  90. request = WSGIRequest({
  91. 'PATH_INFO': '/somepath/',
  92. 'SCRIPT_NAME': '/PREFIX',
  93. 'REQUEST_METHOD': 'get',
  94. 'wsgi.input': BytesIO(b''),
  95. })
  96. self.assertEqual(request.path, '/PREFIX/somepath/')
  97. def test_wsgirequest_script_url_double_slashes(self):
  98. """
  99. WSGI squashes multiple successive slashes in PATH_INFO, WSGIRequest
  100. should take that into account when populating request.path and
  101. request.META['SCRIPT_NAME'] (#17133).
  102. """
  103. request = WSGIRequest({
  104. 'SCRIPT_URL': '/mst/milestones//accounts/login//help',
  105. 'PATH_INFO': '/milestones/accounts/login/help',
  106. 'REQUEST_METHOD': 'get',
  107. 'wsgi.input': BytesIO(b''),
  108. })
  109. self.assertEqual(request.path, '/mst/milestones/accounts/login/help')
  110. self.assertEqual(request.META['SCRIPT_NAME'], '/mst')
  111. def test_wsgirequest_with_force_script_name(self):
  112. """
  113. The FORCE_SCRIPT_NAME setting takes precedence over the request's
  114. SCRIPT_NAME environment parameter (#20169).
  115. """
  116. with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
  117. request = WSGIRequest({
  118. 'PATH_INFO': '/somepath/',
  119. 'SCRIPT_NAME': '/PREFIX/',
  120. 'REQUEST_METHOD': 'get',
  121. 'wsgi.input': BytesIO(b''),
  122. })
  123. self.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
  124. def test_wsgirequest_path_with_force_script_name_trailing_slash(self):
  125. """
  126. The request's path is correctly assembled, regardless of whether or not
  127. the FORCE_SCRIPT_NAME setting has a trailing slash (#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), "<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), "<WSGIRequest: GET '/somepath/'>")
  146. def test_wsgirequest_path_info(self):
  147. def wsgi_str(path_info, encoding='utf-8'):
  148. path_info = path_info.encode(encoding) # Actual URL sent by the browser (bytestring)
  149. path_info = path_info.decode('iso-8859-1') # Value in the WSGI environ dict (native string)
  150. return path_info
  151. # Regression for #19468
  152. request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
  153. self.assertEqual(request.path, "/سلام/")
  154. # The URL may be incorrectly encoded in a non-UTF-8 encoding (#26971)
  155. request = WSGIRequest({
  156. 'PATH_INFO': wsgi_str("/café/", encoding='iso-8859-1'),
  157. 'REQUEST_METHOD': 'get',
  158. 'wsgi.input': BytesIO(b''),
  159. })
  160. # Since it's impossible to decide the (wrong) encoding of the URL, it's
  161. # left percent-encoded in the path.
  162. self.assertEqual(request.path, "/caf%E9/")
  163. def test_limited_stream(self):
  164. # Read all of a limited stream
  165. stream = LimitedStream(BytesIO(b'test'), 2)
  166. self.assertEqual(stream.read(), b'te')
  167. # Reading again returns nothing.
  168. self.assertEqual(stream.read(), b'')
  169. # Read a number of characters greater than the stream has to offer
  170. stream = LimitedStream(BytesIO(b'test'), 2)
  171. self.assertEqual(stream.read(5), b'te')
  172. # Reading again returns nothing.
  173. self.assertEqual(stream.readline(5), b'')
  174. # Read sequentially from a stream
  175. stream = LimitedStream(BytesIO(b'12345678'), 8)
  176. self.assertEqual(stream.read(5), b'12345')
  177. self.assertEqual(stream.read(5), b'678')
  178. # Reading again returns nothing.
  179. self.assertEqual(stream.readline(5), b'')
  180. # Read lines from a stream
  181. stream = LimitedStream(BytesIO(b'1234\n5678\nabcd\nefgh\nijkl'), 24)
  182. # Read a full line, unconditionally
  183. self.assertEqual(stream.readline(), b'1234\n')
  184. # Read a number of characters less than a line
  185. self.assertEqual(stream.readline(2), b'56')
  186. # Read the rest of the partial line
  187. self.assertEqual(stream.readline(), b'78\n')
  188. # Read a full line, with a character limit greater than the line length
  189. self.assertEqual(stream.readline(6), b'abcd\n')
  190. # Read the next line, deliberately terminated at the line end
  191. self.assertEqual(stream.readline(4), b'efgh')
  192. # Read the next line... just the line end
  193. self.assertEqual(stream.readline(), b'\n')
  194. # Read everything else.
  195. self.assertEqual(stream.readline(), b'ijkl')
  196. # Regression for #15018
  197. # If a stream contains a newline, but the provided length
  198. # is less than the number of provided characters, the newline
  199. # doesn't reset the available character count
  200. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
  201. self.assertEqual(stream.readline(10), b'1234\n')
  202. self.assertEqual(stream.readline(3), b'abc')
  203. # Now expire the available characters
  204. self.assertEqual(stream.readline(3), b'd')
  205. # Reading again returns nothing.
  206. self.assertEqual(stream.readline(2), b'')
  207. # Same test, but with read, not readline.
  208. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9)
  209. self.assertEqual(stream.read(6), b'1234\na')
  210. self.assertEqual(stream.read(2), b'bc')
  211. self.assertEqual(stream.read(2), b'd')
  212. self.assertEqual(stream.read(2), b'')
  213. self.assertEqual(stream.read(), b'')
  214. def test_stream(self):
  215. payload = FakePayload('name=value')
  216. request = WSGIRequest({
  217. 'REQUEST_METHOD': 'POST',
  218. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  219. 'CONTENT_LENGTH': len(payload),
  220. 'wsgi.input': payload},
  221. )
  222. self.assertEqual(request.read(), b'name=value')
  223. def test_read_after_value(self):
  224. """
  225. Reading from request is allowed after accessing request contents as
  226. POST or body.
  227. """
  228. payload = FakePayload('name=value')
  229. request = WSGIRequest({
  230. 'REQUEST_METHOD': 'POST',
  231. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  232. 'CONTENT_LENGTH': len(payload),
  233. 'wsgi.input': payload,
  234. })
  235. self.assertEqual(request.POST, {'name': ['value']})
  236. self.assertEqual(request.body, b'name=value')
  237. self.assertEqual(request.read(), b'name=value')
  238. def test_value_after_read(self):
  239. """
  240. Construction of POST or body is not allowed after reading
  241. from request.
  242. """
  243. payload = FakePayload('name=value')
  244. request = WSGIRequest({
  245. 'REQUEST_METHOD': 'POST',
  246. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  247. 'CONTENT_LENGTH': len(payload),
  248. 'wsgi.input': payload,
  249. })
  250. self.assertEqual(request.read(2), b'na')
  251. with self.assertRaises(RawPostDataException):
  252. 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(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 of 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({
  290. 'REQUEST_METHOD': 'POST',
  291. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  292. 'CONTENT_LENGTH': len(payload),
  293. 'wsgi.input': payload,
  294. })
  295. self.assertEqual(request.POST, {'name': ['value']})
  296. with self.assertRaises(RawPostDataException):
  297. request.body
  298. def test_body_after_POST_multipart_related(self):
  299. """
  300. Reading body after parsing multipart that isn't form-data is allowed
  301. """
  302. # Ticket #9054
  303. # There are cases in which the multipart data is related instead of
  304. # being a binary upload, in which case it should still be accessible
  305. # via body.
  306. payload_data = b"\r\n".join([
  307. b'--boundary',
  308. b'Content-ID: id; name="name"',
  309. b'',
  310. b'value',
  311. b'--boundary--'
  312. b''])
  313. payload = FakePayload(payload_data)
  314. request = WSGIRequest({
  315. 'REQUEST_METHOD': 'POST',
  316. 'CONTENT_TYPE': 'multipart/related; boundary=boundary',
  317. 'CONTENT_LENGTH': len(payload),
  318. 'wsgi.input': payload,
  319. })
  320. self.assertEqual(request.POST, {})
  321. self.assertEqual(request.body, payload_data)
  322. def test_POST_multipart_with_content_length_zero(self):
  323. """
  324. Multipart POST requests with Content-Length >= 0 are valid and need to be handled.
  325. """
  326. # According to:
  327. # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
  328. # Every request.POST with Content-Length >= 0 is a valid request,
  329. # this test ensures that we handle Content-Length == 0.
  330. payload = FakePayload("\r\n".join([
  331. '--boundary',
  332. 'Content-Disposition: form-data; name="name"',
  333. '',
  334. 'value',
  335. '--boundary--'
  336. '']))
  337. request = WSGIRequest({
  338. 'REQUEST_METHOD': 'POST',
  339. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  340. 'CONTENT_LENGTH': 0,
  341. 'wsgi.input': payload,
  342. })
  343. self.assertEqual(request.POST, {})
  344. def test_POST_binary_only(self):
  345. payload = b'\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@'
  346. environ = {
  347. 'REQUEST_METHOD': 'POST',
  348. 'CONTENT_TYPE': 'application/octet-stream',
  349. 'CONTENT_LENGTH': len(payload),
  350. 'wsgi.input': BytesIO(payload),
  351. }
  352. request = WSGIRequest(environ)
  353. self.assertEqual(request.POST, {})
  354. self.assertEqual(request.FILES, {})
  355. self.assertEqual(request.body, payload)
  356. # Same test without specifying content-type
  357. environ.update({'CONTENT_TYPE': '', 'wsgi.input': BytesIO(payload)})
  358. request = WSGIRequest(environ)
  359. self.assertEqual(request.POST, {})
  360. self.assertEqual(request.FILES, {})
  361. self.assertEqual(request.body, payload)
  362. def test_read_by_lines(self):
  363. payload = FakePayload('name=value')
  364. request = WSGIRequest({
  365. 'REQUEST_METHOD': 'POST',
  366. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  367. 'CONTENT_LENGTH': len(payload),
  368. 'wsgi.input': payload,
  369. })
  370. self.assertEqual(list(request), [b'name=value'])
  371. def test_POST_after_body_read(self):
  372. """
  373. POST should be populated even if body is read first
  374. """
  375. payload = FakePayload('name=value')
  376. request = WSGIRequest({
  377. 'REQUEST_METHOD': 'POST',
  378. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  379. 'CONTENT_LENGTH': len(payload),
  380. 'wsgi.input': payload,
  381. })
  382. request.body # evaluate
  383. self.assertEqual(request.POST, {'name': ['value']})
  384. def test_POST_after_body_read_and_stream_read(self):
  385. """
  386. POST should be populated even if body is read first, and then
  387. the stream is read second.
  388. """
  389. payload = FakePayload('name=value')
  390. request = WSGIRequest({
  391. 'REQUEST_METHOD': 'POST',
  392. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  393. 'CONTENT_LENGTH': len(payload),
  394. 'wsgi.input': payload,
  395. })
  396. request.body # evaluate
  397. self.assertEqual(request.read(1), b'n')
  398. self.assertEqual(request.POST, {'name': ['value']})
  399. def test_POST_after_body_read_and_stream_read_multipart(self):
  400. """
  401. POST should be populated even if body is read first, and then
  402. the stream is read second. Using multipart/form-data instead of urlencoded.
  403. """
  404. payload = FakePayload("\r\n".join([
  405. '--boundary',
  406. 'Content-Disposition: form-data; name="name"',
  407. '',
  408. 'value',
  409. '--boundary--'
  410. '']))
  411. request = WSGIRequest({
  412. 'REQUEST_METHOD': 'POST',
  413. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  414. 'CONTENT_LENGTH': len(payload),
  415. 'wsgi.input': payload,
  416. })
  417. request.body # evaluate
  418. # Consume enough data to mess up the parsing:
  419. self.assertEqual(request.read(13), b'--boundary\r\nC')
  420. self.assertEqual(request.POST, {'name': ['value']})
  421. def test_POST_immutable_for_mutipart(self):
  422. """
  423. MultiPartParser.parse() leaves request.POST immutable.
  424. """
  425. payload = FakePayload("\r\n".join([
  426. '--boundary',
  427. 'Content-Disposition: form-data; name="name"',
  428. '',
  429. 'value',
  430. '--boundary--',
  431. ]))
  432. request = WSGIRequest({
  433. 'REQUEST_METHOD': 'POST',
  434. 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
  435. 'CONTENT_LENGTH': len(payload),
  436. 'wsgi.input': payload,
  437. })
  438. self.assertFalse(request.POST._mutable)
  439. def test_POST_connection_error(self):
  440. """
  441. If wsgi.input.read() raises an exception while trying to read() the
  442. POST, the exception should be identifiable (not a generic IOError).
  443. """
  444. class ExplodingBytesIO(BytesIO):
  445. def read(self, len=0):
  446. raise IOError("kaboom!")
  447. payload = b'name=value'
  448. request = WSGIRequest({
  449. 'REQUEST_METHOD': 'POST',
  450. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  451. 'CONTENT_LENGTH': len(payload),
  452. 'wsgi.input': ExplodingBytesIO(payload),
  453. })
  454. with self.assertRaises(UnreadablePostError):
  455. request.body
  456. def test_set_encoding_clears_POST(self):
  457. payload = FakePayload('name=Hello Günter')
  458. request = WSGIRequest({
  459. 'REQUEST_METHOD': 'POST',
  460. 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
  461. 'CONTENT_LENGTH': len(payload),
  462. 'wsgi.input': payload,
  463. })
  464. self.assertEqual(request.POST, {'name': ['Hello Günter']})
  465. request.encoding = 'iso-8859-16'
  466. self.assertEqual(request.POST, {'name': ['Hello GĂŒnter']})
  467. def test_set_encoding_clears_GET(self):
  468. request = WSGIRequest({
  469. 'REQUEST_METHOD': 'GET',
  470. 'wsgi.input': '',
  471. 'QUERY_STRING': 'name=Hello%20G%C3%BCnter',
  472. })
  473. self.assertEqual(request.GET, {'name': ['Hello Günter']})
  474. request.encoding = 'iso-8859-16'
  475. self.assertEqual(request.GET, {'name': ['Hello G\u0102\u0152nter']})
  476. def test_FILES_connection_error(self):
  477. """
  478. If wsgi.input.read() raises an exception while trying to read() the
  479. FILES, the exception should be identifiable (not a generic IOError).
  480. """
  481. class ExplodingBytesIO(BytesIO):
  482. def read(self, len=0):
  483. raise IOError("kaboom!")
  484. payload = b'x'
  485. request = WSGIRequest({
  486. 'REQUEST_METHOD': 'POST',
  487. 'CONTENT_TYPE': 'multipart/form-data; boundary=foo_',
  488. 'CONTENT_LENGTH': len(payload),
  489. 'wsgi.input': ExplodingBytesIO(payload),
  490. })
  491. with self.assertRaises(UnreadablePostError):
  492. request.FILES
  493. @override_settings(ALLOWED_HOSTS=['example.com'])
  494. def test_get_raw_uri(self):
  495. factory = RequestFactory(HTTP_HOST='evil.com')
  496. request = factory.get('////absolute-uri')
  497. self.assertEqual(request.get_raw_uri(), 'http://evil.com//absolute-uri')
  498. request = factory.get('/?foo=bar')
  499. self.assertEqual(request.get_raw_uri(), 'http://evil.com/?foo=bar')
  500. request = factory.get('/path/with:colons')
  501. self.assertEqual(request.get_raw_uri(), 'http://evil.com/path/with:colons')
  502. class HostValidationTests(SimpleTestCase):
  503. poisoned_hosts = [
  504. 'example.com@evil.tld',
  505. 'example.com:dr.frankenstein@evil.tld',
  506. 'example.com:dr.frankenstein@evil.tld:80',
  507. 'example.com:80/badpath',
  508. 'example.com: recovermypassword.com',
  509. ]
  510. @override_settings(
  511. USE_X_FORWARDED_HOST=False,
  512. ALLOWED_HOSTS=[
  513. 'forward.com', 'example.com', 'internal.com', '12.34.56.78',
  514. '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com',
  515. '.multitenant.com', 'INSENSITIVE.com', '[::ffff:169.254.169.254]',
  516. ])
  517. def test_http_get_host(self):
  518. # Check if X_FORWARDED_HOST is provided.
  519. request = HttpRequest()
  520. request.META = {
  521. 'HTTP_X_FORWARDED_HOST': 'forward.com',
  522. 'HTTP_HOST': 'example.com',
  523. 'SERVER_NAME': 'internal.com',
  524. 'SERVER_PORT': 80,
  525. }
  526. # X_FORWARDED_HOST is ignored.
  527. self.assertEqual(request.get_host(), 'example.com')
  528. # Check if X_FORWARDED_HOST isn't provided.
  529. request = HttpRequest()
  530. request.META = {
  531. 'HTTP_HOST': 'example.com',
  532. 'SERVER_NAME': 'internal.com',
  533. 'SERVER_PORT': 80,
  534. }
  535. self.assertEqual(request.get_host(), 'example.com')
  536. # Check if HTTP_HOST isn't provided.
  537. request = HttpRequest()
  538. request.META = {
  539. 'SERVER_NAME': 'internal.com',
  540. 'SERVER_PORT': 80,
  541. }
  542. self.assertEqual(request.get_host(), 'internal.com')
  543. # Check if HTTP_HOST isn't provided, and we're on a nonstandard port
  544. request = HttpRequest()
  545. request.META = {
  546. 'SERVER_NAME': 'internal.com',
  547. 'SERVER_PORT': 8042,
  548. }
  549. self.assertEqual(request.get_host(), 'internal.com:8042')
  550. legit_hosts = [
  551. 'example.com',
  552. 'example.com:80',
  553. '12.34.56.78',
  554. '12.34.56.78:443',
  555. '[2001:19f0:feee::dead:beef:cafe]',
  556. '[2001:19f0:feee::dead:beef:cafe]:8080',
  557. 'xn--4ca9at.com', # Punycode for öäü.com
  558. 'anything.multitenant.com',
  559. 'multitenant.com',
  560. 'insensitive.com',
  561. 'example.com.',
  562. 'example.com.:80',
  563. '[::ffff:169.254.169.254]',
  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(DisallowedHost):
  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(DisallowedHost):
  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_in_debug_mode(self):
  666. """
  667. If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are
  668. allowed.
  669. """
  670. valid_hosts = ['localhost', '127.0.0.1', '[::1]']
  671. for host in valid_hosts:
  672. request = HttpRequest()
  673. request.META = {'HTTP_HOST': host}
  674. self.assertEqual(request.get_host(), host)
  675. # Other hostnames raise a DisallowedHost.
  676. with self.assertRaises(DisallowedHost):
  677. request = HttpRequest()
  678. request.META = {'HTTP_HOST': 'example.com'}
  679. request.get_host()
  680. @override_settings(ALLOWED_HOSTS=[])
  681. def test_get_host_suggestion_of_allowed_host(self):
  682. """get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS."""
  683. msg_invalid_host = "Invalid HTTP_HOST header: %r."
  684. msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS."
  685. msg_suggestion2 = msg_invalid_host + " The domain name provided is not valid according to RFC 1034/1035"
  686. for host in [ # Valid-looking hosts
  687. 'example.com',
  688. '12.34.56.78',
  689. '[2001:19f0:feee::dead:beef:cafe]',
  690. 'xn--4ca9at.com', # Punycode for öäü.com
  691. ]:
  692. request = HttpRequest()
  693. request.META = {'HTTP_HOST': host}
  694. with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, host)):
  695. request.get_host()
  696. for domain, port in [ # Valid-looking hosts with a port number
  697. ('example.com', 80),
  698. ('12.34.56.78', 443),
  699. ('[2001:19f0:feee::dead:beef:cafe]', 8080),
  700. ]:
  701. host = '%s:%s' % (domain, port)
  702. request = HttpRequest()
  703. request.META = {'HTTP_HOST': host}
  704. with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, domain)):
  705. request.get_host()
  706. for host in self.poisoned_hosts:
  707. request = HttpRequest()
  708. request.META = {'HTTP_HOST': host}
  709. with self.assertRaisesMessage(DisallowedHost, msg_invalid_host % host):
  710. request.get_host()
  711. request = HttpRequest()
  712. request.META = {'HTTP_HOST': "invalid_hostname.com"}
  713. with self.assertRaisesMessage(DisallowedHost, msg_suggestion2 % "invalid_hostname.com"):
  714. request.get_host()
  715. def test_split_domain_port_removes_trailing_dot(self):
  716. domain, port = split_domain_port('example.com.:8080')
  717. self.assertEqual(domain, 'example.com')
  718. self.assertEqual(port, '8080')
  719. class BuildAbsoluteURITests(SimpleTestCase):
  720. factory = RequestFactory()
  721. def test_absolute_url(self):
  722. request = HttpRequest()
  723. url = 'https://www.example.com/asdf'
  724. self.assertEqual(request.build_absolute_uri(location=url), url)
  725. def test_host_retrieval(self):
  726. request = HttpRequest()
  727. request.get_host = lambda: 'www.example.com'
  728. request.path = ''
  729. self.assertEqual(
  730. request.build_absolute_uri(location='/path/with:colons'),
  731. 'http://www.example.com/path/with:colons'
  732. )
  733. def test_request_path_begins_with_two_slashes(self):
  734. # //// creates a request with a path beginning with //
  735. request = self.factory.get('////absolute-uri')
  736. tests = (
  737. # location isn't provided
  738. (None, 'http://testserver//absolute-uri'),
  739. # An absolute URL
  740. ('http://example.com/?foo=bar', 'http://example.com/?foo=bar'),
  741. # A schema-relative URL
  742. ('//example.com/?foo=bar', 'http://example.com/?foo=bar'),
  743. # Relative URLs
  744. ('/foo/bar/', 'http://testserver/foo/bar/'),
  745. ('/foo/./bar/', 'http://testserver/foo/bar/'),
  746. ('/foo/../bar/', 'http://testserver/bar/'),
  747. ('///foo/bar/', 'http://testserver/foo/bar/'),
  748. )
  749. for location, expected_url in tests:
  750. with self.subTest(location=location):
  751. self.assertEqual(request.build_absolute_uri(location=location), expected_url)
  752. class RequestHeadersTests(SimpleTestCase):
  753. ENVIRON = {
  754. # Non-headers are ignored.
  755. 'PATH_INFO': '/somepath/',
  756. 'REQUEST_METHOD': 'get',
  757. 'wsgi.input': BytesIO(b''),
  758. 'SERVER_NAME': 'internal.com',
  759. 'SERVER_PORT': 80,
  760. # These non-HTTP prefixed headers are included.
  761. 'CONTENT_TYPE': 'text/html',
  762. 'CONTENT_LENGTH': '100',
  763. # All HTTP-prefixed headers are included.
  764. 'HTTP_ACCEPT': '*',
  765. 'HTTP_HOST': 'example.com',
  766. 'HTTP_USER_AGENT': 'python-requests/1.2.0',
  767. }
  768. def test_base_request_headers(self):
  769. request = HttpRequest()
  770. request.META = self.ENVIRON
  771. self.assertEqual(dict(request.headers), {
  772. 'Content-Type': 'text/html',
  773. 'Content-Length': '100',
  774. 'Accept': '*',
  775. 'Host': 'example.com',
  776. 'User-Agent': 'python-requests/1.2.0',
  777. })
  778. def test_wsgi_request_headers(self):
  779. request = WSGIRequest(self.ENVIRON)
  780. self.assertEqual(dict(request.headers), {
  781. 'Content-Type': 'text/html',
  782. 'Content-Length': '100',
  783. 'Accept': '*',
  784. 'Host': 'example.com',
  785. 'User-Agent': 'python-requests/1.2.0',
  786. })
  787. def test_wsgi_request_headers_getitem(self):
  788. request = WSGIRequest(self.ENVIRON)
  789. self.assertEqual(request.headers['User-Agent'], 'python-requests/1.2.0')
  790. self.assertEqual(request.headers['user-agent'], 'python-requests/1.2.0')
  791. self.assertEqual(request.headers['Content-Type'], 'text/html')
  792. self.assertEqual(request.headers['Content-Length'], '100')
  793. def test_wsgi_request_headers_get(self):
  794. request = WSGIRequest(self.ENVIRON)
  795. self.assertEqual(request.headers.get('User-Agent'), 'python-requests/1.2.0')
  796. self.assertEqual(request.headers.get('user-agent'), 'python-requests/1.2.0')
  797. self.assertEqual(request.headers.get('Content-Type'), 'text/html')
  798. self.assertEqual(request.headers.get('Content-Length'), '100')
  799. class HttpHeadersTests(SimpleTestCase):
  800. def test_basic(self):
  801. environ = {
  802. 'CONTENT_TYPE': 'text/html',
  803. 'CONTENT_LENGTH': '100',
  804. 'HTTP_HOST': 'example.com',
  805. }
  806. headers = HttpHeaders(environ)
  807. self.assertEqual(sorted(headers), ['Content-Length', 'Content-Type', 'Host'])
  808. self.assertEqual(headers, {
  809. 'Content-Type': 'text/html',
  810. 'Content-Length': '100',
  811. 'Host': 'example.com',
  812. })
  813. def test_parse_header_name(self):
  814. tests = (
  815. ('PATH_INFO', None),
  816. ('HTTP_ACCEPT', 'Accept'),
  817. ('HTTP_USER_AGENT', 'User-Agent'),
  818. ('HTTP_X_FORWARDED_PROTO', 'X-Forwarded-Proto'),
  819. ('CONTENT_TYPE', 'Content-Type'),
  820. ('CONTENT_LENGTH', 'Content-Length'),
  821. )
  822. for header, expected in tests:
  823. with self.subTest(header=header):
  824. self.assertEqual(HttpHeaders.parse_header_name(header), expected)